@protobase/ui 0.121.12 → 0.122.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/messages.d.ts +2 -2
- package/dist/activity-chart/messages.d.ts +2 -2
- package/dist/app/change-confirm/messages.d.ts +2 -2
- package/dist/app/charts/messages.d.ts +2 -2
- package/dist/app/confirm-sign-in-messages.d.ts +2 -2
- package/dist/app/conversation/messages.d.ts +2 -2
- package/dist/app/conversation/thread-state.d.ts +1 -1
- package/dist/app/conversation-page/messages.d.ts +2 -2
- package/dist/app/create/messages.d.ts +2 -2
- package/dist/app/delete/messages.d.ts +2 -2
- package/dist/app/displays/messages.d.ts +2 -2
- package/dist/app/embedded-list/messages.d.ts +2 -2
- package/dist/app/export/messages.d.ts +2 -2
- package/dist/app/field-messages.d.ts +2 -2
- package/dist/app/field-types/json/messages.d.ts +2 -2
- package/dist/app/field-types/runner-install/messages.d.ts +2 -2
- package/dist/app/field-types/workflow/definition.d.ts +1 -1
- package/dist/app/field-types/workflow/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-page/messages.d.ts +2 -2
- package/dist/app/field-types/workflow-run/messages.d.ts +2 -2
- package/dist/app/file-viewers/messages.d.ts +2 -2
- package/dist/app/focus/messages.d.ts +2 -2
- package/dist/app/gallery/messages.d.ts +2 -2
- package/dist/app/hand-order/messages.d.ts +2 -2
- package/dist/app/history/messages.d.ts +2 -2
- package/dist/app/import/messages.d.ts +2 -2
- package/dist/app/list-messages.d.ts +2 -2
- package/dist/app/messages.d.ts +2 -2
- package/dist/app/pages/messages.d.ts +2 -2
- package/dist/app/record-chart/messages.d.ts +2 -2
- package/dist/app/record-messages.d.ts +2 -2
- package/dist/app/record-mode/shown-layout.d.ts +1 -1
- package/dist/app/record-row/messages.d.ts +2 -2
- package/dist/app/related-cards/messages.d.ts +2 -2
- package/dist/app/runtime/messages.d.ts +2 -2
- package/dist/app/saved/messages.d.ts +2 -2
- package/dist/app/saved/use-favorite.d.ts +1 -1
- package/dist/app/searches/messages.d.ts +2 -2
- package/dist/app/searches/use-save-search.d.ts +1 -1
- package/dist/app-shell/messages.d.ts +2 -2
- package/dist/assistant-dock/messages.d.ts +2 -2
- package/dist/auth/messages.d.ts +2 -2
- package/dist/calls/messages.d.ts +2 -2
- package/dist/chat/messages.d.ts +2 -2
- package/dist/compact-table/messages.d.ts +2 -2
- package/dist/data-grid/messages.d.ts +2 -2
- package/dist/filter-panel/messages.d.ts +2 -2
- package/dist/invitations/messages.d.ts +2 -2
- package/dist/mailbox/messages.d.ts +2 -2
- package/dist/mentions/messages.d.ts +2 -2
- package/dist/mocks/customers.d.ts +1 -1
- package/dist/mocks/invoices.d.ts +1 -1
- package/dist/mocks/orders.d.ts +2 -2
- package/dist/notifications/bell/messages.d.ts +2 -2
- package/dist/organizations/messages.d.ts +2 -2
- package/dist/package.js +1 -1
- package/dist/plugins/messages.d.ts +2 -2
- package/dist/record-view/messages.d.ts +2 -2
- package/dist/shell/assets/{account-page-BsAc4o17.js → account-page-Dw3W4H6l.js} +2 -2
- package/dist/shell/assets/{app-Bb88M0VJ.js → app-B4Vl9AEn.js} +5 -5
- package/dist/shell/assets/{assistant-shell-CdVAnpMe.js → assistant-shell-DyBHCHuy.js} +2 -2
- package/dist/shell/assets/{board-display-DKT7398I.js → board-display-BlJwyapl.js} +2 -2
- package/dist/shell/assets/{calendar-display-0c2dGTmG.js → calendar-display-C2vvdk6I.js} +2 -2
- package/dist/shell/assets/{call-rings-BV5na0xp.js → call-rings-DKHVIKwh.js} +2 -2
- package/dist/shell/assets/{calls-n9IoOXzL.js → calls-CDleoS9h.js} +2 -2
- package/dist/shell/assets/{circle-alert-kISSXwIV.js → circle-alert-DYA4c4B7.js} +2 -2
- package/dist/shell/assets/{composed-page-hn7I0Ulk.js → composed-page-BtPlNGV4.js} +2 -2
- package/dist/shell/assets/{composer-section-Cb1kOpwt.js → composer-section-zJurnYKu.js} +2 -2
- package/dist/shell/assets/{connect-route-l21XyxhS.js → connect-route-oTxVxU6f.js} +2 -2
- package/dist/shell/assets/{copy-field-D22CFeg3.js → copy-field-D_iD-sgT.js} +2 -2
- package/dist/shell/assets/{create-route-CSe9DhbY.js → create-route-z6BVZwk3.js} +2 -2
- package/dist/shell/assets/{custom-step-container-field-C5l4j0FI.js → custom-step-container-field-vl09jwo_.js} +2 -2
- package/dist/shell/assets/{embedded-list-DjvOszEj.js → embedded-list-B0wJoqm3.js} +3 -3
- package/dist/shell/assets/{export-dialog-Bh3TSYyL.js → export-dialog-DN8mwLKi.js} +2 -2
- package/dist/shell/assets/{first-organization-page-BtfoRENE.js → first-organization-page-CN5x-0QP.js} +2 -2
- package/dist/shell/assets/{graph-view-C4fwqz7Q.js → graph-view-w7lrzAmt.js} +2 -2
- package/dist/shell/assets/{group-donut-Bcnc0EaM.js → group-donut-g3nDENBg.js} +2 -2
- package/dist/shell/assets/{guest-call-page-D09z7u-V.js → guest-call-page-_-o8LpKg.js} +3 -3
- package/dist/shell/assets/{html-viewer-BtwOBvDg.js → html-viewer-Bfjrowsp.js} +2 -2
- package/dist/shell/assets/{import-dialog-Dwx_yEfS.js → import-dialog-DeGzN4TA.js} +2 -2
- package/dist/shell/assets/{import-table-dialog-T3V3RoDY.js → import-table-dialog-BcSfnTNF.js} +2 -2
- package/dist/shell/assets/{index-DvNpfiwE.js → index-Bu8r1CM4.js} +1 -1
- package/dist/shell/assets/{invitations-page-X90SMPsK.js → invitations-page-CVkFsOgL.js} +2 -2
- package/dist/shell/assets/{layout-grid-Bp_eP5eU.js → layout-grid-Cmzqqy11.js} +2 -2
- package/dist/shell/assets/{legend-item-CEZ-8FXv.js → legend-item-dXfws39r.js} +2 -2
- package/dist/shell/assets/{list-page-BUtWO_Zd.js → list-page-C7H5G772.js} +4 -4
- package/dist/shell/assets/{maplibre-Cv3xuTP_.js → maplibre-C1Y1UO5-.js} +2 -2
- package/dist/shell/assets/{markdown-content-jO-R6jpp.js → markdown-content-Be_Vsipv.js} +2 -2
- package/dist/shell/assets/{members-page-BZyldmfB.js → members-page-vnYWXsnN.js} +2 -2
- package/dist/shell/assets/{message-content-DJEa6jyY.js → message-content-BgtfnCSo.js} +2 -2
- package/dist/shell/assets/{messages-BIP4feL2.js → messages-BJNycdpS.js} +2 -2
- package/dist/shell/assets/{organization-page-CjQ7oJk4.js → organization-page-Cbb97Ebt.js} +2 -2
- package/dist/shell/assets/{organizations-page-2cKqhNJh.js → organizations-page-Cq7fzpZa.js} +2 -2
- package/dist/shell/assets/{pending-invitation-row-Cef2WdTI.js → pending-invitation-row-xX2VAQLM.js} +2 -2
- package/dist/shell/assets/{period-chart-BPq3Knz8.js → period-chart-CgHgMZ2l.js} +2 -2
- package/dist/shell/assets/{person-row-BLVor9QR.js → person-row-CjXGB6eY.js} +2 -2
- package/dist/shell/assets/{public-form-page-CMaHcrdf.js → public-form-page-DROsvcsL.js} +2 -2
- package/dist/shell/assets/{record-lines-jznjVtIQ.js → record-lines-D-pcqwS2.js} +2 -2
- package/dist/shell/assets/{record-map-9KEjeN_F.js → record-map-COL77PxJ.js} +2 -2
- package/dist/shell/assets/{record-opens-CQLXpqJS.js → record-opens-AboxTqcw.js} +2 -2
- package/dist/shell/assets/{record-page-JFlxtSyg.js → record-page-Ctj-uKq1.js} +3 -3
- package/dist/shell/assets/{record-preview-CUs7j-lh.js → record-preview--cdSUcRq.js} +2 -2
- package/dist/shell/assets/{records-map-CLF98-H0.js → records-map-C5es9EjJ.js} +2 -2
- package/dist/shell/assets/{render-node-DoB1k2WS.js → render-node-BbfwkxfK.js} +3 -3
- package/dist/shell/assets/{reorder-button-Cg-WKutS.js → reorder-button-ClD-Ptqm.js} +2 -2
- package/dist/shell/assets/{run-trace-view-CmujelWd.js → run-trace-view-BlfDwdyz.js} +2 -2
- package/dist/shell/assets/{runner-install-field-wpoIgnks.js → runner-install-field-E1dq6epi.js} +2 -2
- package/dist/shell/assets/{runtime-update-BaNRaM6l.js → runtime-update-Dwwvn6ea.js} +2 -2
- package/dist/shell/assets/{shared-protobase-ui-630Rm7Jd.js → shared-protobase-ui-9v4EmiO7.js} +1 -1
- package/dist/shell/assets/{sheet-source-7m5PMllh.js → sheet-source-C2r0xsKl.js} +2 -2
- package/dist/shell/assets/{sign-in-policy-page-GgyC3l_6.js → sign-in-policy-page-D9_X1fyz.js} +2 -2
- package/dist/shell/assets/{start-block-queries-B8K1ZsVK.js → start-block-queries-CSHzGGu1.js} +2 -2
- package/dist/shell/assets/{step-catalog-Dktva0VF.js → step-catalog-DFsFCluU.js} +2 -2
- package/dist/shell/assets/{step-panel-CjUWMleA.js → step-panel-DmMSxA8x.js} +2 -2
- package/dist/shell/assets/{timeline-display-CCPZ8VKv.js → timeline-display-Br58uLQ8.js} +2 -2
- package/dist/shell/assets/{trash-BfIEK322.js → trash-DzKZquG9.js} +2 -2
- package/dist/shell/assets/{update-set-Drag3hOc.js → update-set-DwG0XGif.js} +2 -2
- package/dist/shell/assets/{use-calendar-move-fM4kqYZF.js → use-calendar-move-DusjGuvd.js} +2 -2
- package/dist/shell/assets/{use-display-rows-CEB1AStC.js → use-display-rows-llOhHJvA.js} +2 -2
- package/dist/shell/assets/{use-my-invitations-DxoZihem.js → use-my-invitations-tnMnjktl.js} +2 -2
- package/dist/shell/assets/{use-paged-search-tHTP8FRX.js → use-paged-search-BWcRlArY.js} +2 -2
- package/dist/shell/assets/{use-run-trace-b8SpFDRU.js → use-run-trace-B2K4dLw0.js} +2 -2
- package/dist/shell/assets/{use-workflow-page-oeKIRs_g.js → use-workflow-page-ted3LYxk.js} +2 -2
- package/dist/shell/assets/{use-workflow-types-D1TLbN3E.js → use-workflow-types-f_gVwLT2.js} +2 -2
- package/dist/shell/assets/{workflow-canvas-CJQ0Ll0M.js → workflow-canvas-T1QChoXq.js} +2 -2
- package/dist/shell/assets/{workflow-field-CpGs8ZXh.js → workflow-field-D0Yp-t1X.js} +3 -3
- package/dist/shell/assets/{workflow-graph-editor-CLlL2jNQ.js → workflow-graph-editor-CJmYosOs.js} +2 -2
- package/dist/shell/assets/{workflow-run-field-R43RqM3Z.js → workflow-run-field-CaJfI9Xi.js} +3 -3
- package/dist/shell/assets/{workflow-status-field-BaytFzWg.js → workflow-status-field-DlZvZQNx.js} +2 -2
- package/dist/shell/assets/{workflow-workbench-DYClQZZ1.js → workflow-workbench-BcZEcj70.js} +2 -2
- package/dist/shell/index.html +3 -3
- package/dist/shell/protobase.shell.json +2 -2
- package/dist/shell/protobase.sw.js +2 -2
- package/dist/shell-source-maps/assets/{account-page-BsAc4o17.js.map → account-page-Dw3W4H6l.js.map} +1 -1
- package/dist/shell-source-maps/assets/{app-Bb88M0VJ.js.map → app-B4Vl9AEn.js.map} +1 -1
- package/dist/shell-source-maps/assets/{assistant-shell-CdVAnpMe.js.map → assistant-shell-DyBHCHuy.js.map} +1 -1
- package/dist/shell-source-maps/assets/{board-display-DKT7398I.js.map → board-display-BlJwyapl.js.map} +1 -1
- package/dist/shell-source-maps/assets/{calendar-display-0c2dGTmG.js.map → calendar-display-C2vvdk6I.js.map} +1 -1
- package/dist/shell-source-maps/assets/{call-rings-BV5na0xp.js.map → call-rings-DKHVIKwh.js.map} +1 -1
- package/dist/shell-source-maps/assets/{calls-n9IoOXzL.js.map → calls-CDleoS9h.js.map} +1 -1
- package/dist/shell-source-maps/assets/{circle-alert-kISSXwIV.js.map → circle-alert-DYA4c4B7.js.map} +1 -1
- package/dist/shell-source-maps/assets/{composed-page-hn7I0Ulk.js.map → composed-page-BtPlNGV4.js.map} +1 -1
- package/dist/shell-source-maps/assets/{composer-section-Cb1kOpwt.js.map → composer-section-zJurnYKu.js.map} +1 -1
- package/dist/shell-source-maps/assets/{connect-route-l21XyxhS.js.map → connect-route-oTxVxU6f.js.map} +1 -1
- package/dist/shell-source-maps/assets/{copy-field-D22CFeg3.js.map → copy-field-D_iD-sgT.js.map} +1 -1
- package/dist/shell-source-maps/assets/{create-route-CSe9DhbY.js.map → create-route-z6BVZwk3.js.map} +1 -1
- package/dist/shell-source-maps/assets/{custom-step-container-field-C5l4j0FI.js.map → custom-step-container-field-vl09jwo_.js.map} +1 -1
- package/dist/shell-source-maps/assets/{embedded-list-DjvOszEj.js.map → embedded-list-B0wJoqm3.js.map} +1 -1
- package/dist/shell-source-maps/assets/{export-dialog-Bh3TSYyL.js.map → export-dialog-DN8mwLKi.js.map} +1 -1
- package/dist/shell-source-maps/assets/{first-organization-page-BtfoRENE.js.map → first-organization-page-CN5x-0QP.js.map} +1 -1
- package/dist/shell-source-maps/assets/{graph-view-C4fwqz7Q.js.map → graph-view-w7lrzAmt.js.map} +1 -1
- package/dist/shell-source-maps/assets/{group-donut-Bcnc0EaM.js.map → group-donut-g3nDENBg.js.map} +1 -1
- package/dist/shell-source-maps/assets/{guest-call-page-D09z7u-V.js.map → guest-call-page-_-o8LpKg.js.map} +1 -1
- package/dist/shell-source-maps/assets/{html-viewer-BtwOBvDg.js.map → html-viewer-Bfjrowsp.js.map} +1 -1
- package/dist/shell-source-maps/assets/{import-dialog-Dwx_yEfS.js.map → import-dialog-DeGzN4TA.js.map} +1 -1
- package/dist/shell-source-maps/assets/{import-table-dialog-T3V3RoDY.js.map → import-table-dialog-BcSfnTNF.js.map} +1 -1
- package/dist/shell-source-maps/assets/{invitations-page-X90SMPsK.js.map → invitations-page-CVkFsOgL.js.map} +1 -1
- package/dist/shell-source-maps/assets/{layout-grid-Bp_eP5eU.js.map → layout-grid-Cmzqqy11.js.map} +1 -1
- package/dist/shell-source-maps/assets/{legend-item-CEZ-8FXv.js.map → legend-item-dXfws39r.js.map} +1 -1
- package/dist/shell-source-maps/assets/{list-page-BUtWO_Zd.js.map → list-page-C7H5G772.js.map} +1 -1
- package/dist/shell-source-maps/assets/{maplibre-Cv3xuTP_.js.map → maplibre-C1Y1UO5-.js.map} +1 -1
- package/dist/shell-source-maps/assets/{markdown-content-jO-R6jpp.js.map → markdown-content-Be_Vsipv.js.map} +1 -1
- package/dist/shell-source-maps/assets/{members-page-BZyldmfB.js.map → members-page-vnYWXsnN.js.map} +1 -1
- package/dist/shell-source-maps/assets/{message-content-DJEa6jyY.js.map → message-content-BgtfnCSo.js.map} +1 -1
- package/dist/shell-source-maps/assets/{messages-BIP4feL2.js.map → messages-BJNycdpS.js.map} +1 -1
- package/dist/shell-source-maps/assets/{organization-page-CjQ7oJk4.js.map → organization-page-Cbb97Ebt.js.map} +1 -1
- package/dist/shell-source-maps/assets/{organizations-page-2cKqhNJh.js.map → organizations-page-Cq7fzpZa.js.map} +1 -1
- package/dist/shell-source-maps/assets/{pending-invitation-row-Cef2WdTI.js.map → pending-invitation-row-xX2VAQLM.js.map} +1 -1
- package/dist/shell-source-maps/assets/{period-chart-BPq3Knz8.js.map → period-chart-CgHgMZ2l.js.map} +1 -1
- package/dist/shell-source-maps/assets/{person-row-BLVor9QR.js.map → person-row-CjXGB6eY.js.map} +1 -1
- package/dist/shell-source-maps/assets/{public-form-page-CMaHcrdf.js.map → public-form-page-DROsvcsL.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-lines-jznjVtIQ.js.map → record-lines-D-pcqwS2.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-map-9KEjeN_F.js.map → record-map-COL77PxJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-opens-CQLXpqJS.js.map → record-opens-AboxTqcw.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-page-JFlxtSyg.js.map → record-page-Ctj-uKq1.js.map} +1 -1
- package/dist/shell-source-maps/assets/{record-preview-CUs7j-lh.js.map → record-preview--cdSUcRq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{records-map-CLF98-H0.js.map → records-map-C5es9EjJ.js.map} +1 -1
- package/dist/shell-source-maps/assets/{render-node-DoB1k2WS.js.map → render-node-BbfwkxfK.js.map} +1 -1
- package/dist/shell-source-maps/assets/{reorder-button-Cg-WKutS.js.map → reorder-button-ClD-Ptqm.js.map} +1 -1
- package/dist/shell-source-maps/assets/{run-trace-view-CmujelWd.js.map → run-trace-view-BlfDwdyz.js.map} +1 -1
- package/dist/shell-source-maps/assets/{runner-install-field-wpoIgnks.js.map → runner-install-field-E1dq6epi.js.map} +1 -1
- package/dist/shell-source-maps/assets/{runtime-update-BaNRaM6l.js.map → runtime-update-Dwwvn6ea.js.map} +1 -1
- package/dist/shell-source-maps/assets/{sheet-source-7m5PMllh.js.map → sheet-source-C2r0xsKl.js.map} +1 -1
- package/dist/shell-source-maps/assets/{sign-in-policy-page-GgyC3l_6.js.map → sign-in-policy-page-D9_X1fyz.js.map} +1 -1
- package/dist/shell-source-maps/assets/{start-block-queries-B8K1ZsVK.js.map → start-block-queries-CSHzGGu1.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-catalog-Dktva0VF.js.map → step-catalog-DFsFCluU.js.map} +1 -1
- package/dist/shell-source-maps/assets/{step-panel-CjUWMleA.js.map → step-panel-DmMSxA8x.js.map} +1 -1
- package/dist/shell-source-maps/assets/{timeline-display-CCPZ8VKv.js.map → timeline-display-Br58uLQ8.js.map} +1 -1
- package/dist/shell-source-maps/assets/{trash-BfIEK322.js.map → trash-DzKZquG9.js.map} +1 -1
- package/dist/shell-source-maps/assets/{update-set-Drag3hOc.js.map → update-set-DwG0XGif.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-calendar-move-fM4kqYZF.js.map → use-calendar-move-DusjGuvd.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-display-rows-CEB1AStC.js.map → use-display-rows-llOhHJvA.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-my-invitations-DxoZihem.js.map → use-my-invitations-tnMnjktl.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-paged-search-tHTP8FRX.js.map → use-paged-search-BWcRlArY.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-run-trace-b8SpFDRU.js.map → use-run-trace-B2K4dLw0.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-workflow-page-oeKIRs_g.js.map → use-workflow-page-ted3LYxk.js.map} +1 -1
- package/dist/shell-source-maps/assets/{use-workflow-types-D1TLbN3E.js.map → use-workflow-types-f_gVwLT2.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-canvas-CJQ0Ll0M.js.map → workflow-canvas-T1QChoXq.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-field-CpGs8ZXh.js.map → workflow-field-D0Yp-t1X.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-graph-editor-CLlL2jNQ.js.map → workflow-graph-editor-CJmYosOs.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-run-field-R43RqM3Z.js.map → workflow-run-field-CaJfI9Xi.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-status-field-BaytFzWg.js.map → workflow-status-field-DlZvZQNx.js.map} +1 -1
- package/dist/shell-source-maps/assets/{workflow-workbench-DYClQZZ1.js.map → workflow-workbench-BcZEcj70.js.map} +1 -1
- package/dist/status/messages.d.ts +2 -2
- package/dist/users/messages.d.ts +2 -2
- package/package.json +5 -5
package/dist/shell-source-maps/assets/{record-page-JFlxtSyg.js.map → record-page-Ctj-uKq1.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"mappings":";6xFASA,IAAMA,GAAa,CACjB,KAAM,SACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,iDAAkD,IAAK,QAAS,CAAC,EAC/E,CAAC,OAAQ,CAAE,EAAG,uDAAwD,IAAK,QAAS,CAAC,EACrF,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,IAAK,EAAG,IAAK,KAAM,eAAgB,IAAK,QAAS,CAAC,EAC7E,CAAC,OAAQ,CAAE,EAAG,IAAK,EAAG,IAAK,MAAO,KAAM,OAAQ,KAAM,GAAI,IAAK,IAAK,QAAS,CAAC,CAChF,CACF,EACAA,GAAW,KACX,IAAMC,GAASC,GAAiBF,EAAU,ECXpCA,GAAa,CACjB,KAAM,OACN,KAAM,GACN,KAAM,CACJ,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,KAAM,E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GAAS,CAChE,IAAM3pB,EAAQ5J,EAAOsB,EAAM,OAAOtB,GAAQ,OAE1C,MADI,CAACA,GAAQ,CAAC4J,GAAS,CAACmmB,EAAQ/vB,CAAI,GAAK8vB,EAAc,SAAS9vB,CAAI,EAAU,CAAC,EACxE,CAAC,CAAE,MAAOwzB,EAAKxzB,CAAI,CAAC,EAAE,OAASmc,EAASnc,CAAI,EAAG,MAAOyzB,EAAMzzB,CAAI,GAAI,EAAAtC,EAAA,KAAC,OAAD,CAAM,MAAOw3B,GAAWtrB,EAAOzD,EAAO,OAAOnG,GAAO,OAAWwzB,EAAKxzB,CAAI,CAAC,EAAI,SAAA8Z,GAAalQ,EAAOzD,EAAO,OAAOnG,GAAOwzB,EAAKxzB,CAAI,CAAC,CAAQ,IAAI,EAAAtC,EAAA,KAACkiB,EAAD,CAAU,UAAU,UAAY,EAAE,CAAC,CAC5P,CAAC,CACF,GACA,CAACna,IAAW,EAAA/H,EAAA,KAACquB,GAAD,CAAqB,QAAkB,YAAmB,SAAS,EAC3E,CACJ,KACF,GACF,GAEJuJ,KACC,EAAA53B,EAAA,KAAC,MAAD,CAAK,UAAU,yHAA0H,SAAA43B,EAAkB,EAE1J,GAET","names":["__iconData","Images","createLucideIcon","Info","ListTree","Undo2","Zap","RecordHeader","import_jsx_runtime","collection","title","badge","lastEditedBy","_Fragment","text","presence","AvatarStack","actions","headingClass","GroupSection","id","useId","cn","open","toggle","AppLink","ChevronRight","count","help","HeadingLevel","RecordTabs","segmentedClass","tabs","tab","SpecTable","rows","row","KeyFacts","facts","Icon","label","value","itemClass","ActionRail","children","tone","name","description","render","onRun","blocked","running","linesLimit","useLines","list","useList","lines","link","parentKey","position","items","useMemo","a","b","more","import_react","auditField","kind","model","frame","item","SidebarCard","body","Section","CustomSection","useProjectUi","Component","components","RecordScope","scope","unmarkFieldRefs","fallback","CustomOrFallback","FullAreaRecord","component","CustomBoundary","standard","FullArea","usePageScroll","ConversationCall","useRecordCallAddress","client","useClient","members","useMembers","page","joining","RecordCall","user","MembersTitle","auth","useOptionalAuth","me","usePresence","others","otherMembers","member","StatusMark","presenceOf","index","ConversationHeader","subtitle","CallMark","buttonClass","DeleteMessageDialog","ResponsiveDialog","Button","onClose","onDelete","MessageActionsBar","controls","reacted","groups","group","offered","onReact","emoji","entry","thread","onEdit","symbol","MessageActionsSheet","mine","choose","onChoose","preview","onCopy","reaction","press","onUnreact","pixels","attachmentOf","file","fileShown","attachments","stored","recordKey","attachmentsByMessage","byMessage","attachment","message","isPreviewed","isPreviewable","FileLabel","FileText","formatSize","FileDownload","className","MessageAttachments","MessageEditor","draft","setDraft","useState","saving","setSaving","mounted","useRef","trimmed","save","onCancel","saved","onSave","mentionedIds","MentionBox","event","ReactionChips","people","userIds","lastReplyLabel","viewerZone","chatDayLabel","time","now","zone","formatTime","ThreadSummary","last","formatDateTime","deleteAllowed","option","condition","parseCondition","evaluateCondition","messageAccess","can","permissions","rowAllows","reactionAccess","emojiSet","values","reactions","reactionsByMessage","field","reactionGroups","set","these","useMessageControls","toast","useToast","setup","access","reacts","key","copy","writes","nextPress","textBoxes","swallowReleaseClick","swallow","stop","useMessagePress","timer","pressing","step","next","onControl","typing","onOpen","lowersKeyboard","idsOf","ConversationMessage","editing","setEditing","deleting","setDeleting","acting","setActing","author","files","messageKey","mentionIds","edited","replies","chips","footer","showLabel","ChatMessage","changed","mentions","MentionedText","where","createWhere","messagesRequest","printFilter","threadSort","repliesRequest","first","ofMessagesFilter","of","messages","readOfMessages","filter","pageToken","ownPositionFilter","timeOf","conversationRows","oldestFirst","previous","sent","before","newDay","sameChatDay","isNew","newLineAbove","soon","authorOf","sender","continued","keysOf","firstUnreadKey","hasEarlier","lastRead","found","highestKey","useMessageAttachments","useAdminMeta","results","useQueries","pages","keys","resources","result","useMessageReactions","useMessageWrites","refresh","useRefreshResource","run","write","resource","failed","refusalReason","error","deleteOps","keyValue","keyOf","useMessageSetup","messagePermissions","usePermissions","reactionPermissions","useNewLine","line","setLine","decidable","decided","decide","ConversationMessages","recordKey$3","senders","listLabels","views","withLabels","read","state","threadState","loaded","ErrorBanner","retryOf","Quiet","readEnd","own","readTo","showsErrorAbove","reactionsError","attachmentsError","ChatThread","ChatDivider","matchingMembers","wanted","query","person","inConversation","useThreadHead","head","useRecord","named","ids","labels","usePickedLabels","elsewhere","ThreadPanel","recordKey$2","headRow","SidePanel","MessageComposer","owner","store","raise","at","moveReadPosition","status","isApiError","useReadPosition","recordKey$1","kept","openedAt","setOpenedAt","setError","writing","find","useCallback","made","useThreadAddress","useAppAddress","here","address","call","go","ConversationPage","useRecordTitle","searchPeople","threaded","channel","relay","useRelay","useViewChannel","useTypingSender","typed","TypingLine","draftStorageKey","userId","readDraft","guarded","raw","storage","parsed","etag","writeDraft","actionIcon","namedIcon","useRecordActions","app","runner","useActionRunner","action","asking","setAsking","actionLink","isDanger","asksFirst","RouteLink","deletes","edit","Pencil","Trash2","ActionPrompt","RecordActions","slot","useTopBarSlot","props","createPortal","ActionMenu","prompt","op","describeBatchFailure","ops","appText","nameFailingOperation","without","source","useRecordEditor","queryClient","useQueryClient","update","useUpdateRecord","feedback","useLiveSave","mode","subject","restored","draftKey","showRestored","setShowRestored","linesConflict","setLinesConflict","conflicts","setConflicts","errors","setErrors","rejections","setRejections","differs","fieldsDirty","dirty","keep","toDraft","change","current","adoptLatest","latest","theirs","displayValue","patchOf","toPatchValue","reject","fieldErrors","saveRecordOnly","isConflict","saveBatch","recordOps","linesPlan","lineOp","ConflictChoices","fields","onKeepMine","onUseTheirs","SaveButton","record","taken","useFocusZoneFilled","compact","useFocusPage","button","FocusSlot","SaveState","size","shown","readOnly","Check","RecordFocus","view","useAuth","editor","useNavigationGuard","usePauseFocusRefresh","askDiscard","setAskDiscard","noun","humanize","restore","useRestore","pastVersion","surfaceReadable","fieldAccess","mayUpdate","canDelete","remove","useDeleteFlow","details","danger","barActions","surfaceField","discardNotice","FocusNotice","conflict","refusedField","surfaceProblem","fieldMessage","FocusRecordContext","FocusActions","FieldSurface","ComponentSurface","hints","FieldEditor","RecordFocusPage","FocusPage","RecordMap","lazy","module","defaultZoom","MapSection","maps","style","recordPosition","map","Suspense","rangeBuckets","chartPoints","points","series","point","measure","empty","ranges","rangeLabels","RecordChartSection","range","setRange","setMeasure","granularity","requests","useAggregates","measures","part","Segmented","Skeleton","PeriodChart","trendSummary","total","RecordTrendSection","useAggregate","sum","periodPoints","toggledOpen","groupOpen","needsAttention","splitTabs","layout","shownTab","tabFields","layoutItems","attentionTab","emptyLinesState","shownIds","storedIds","changedData","edits","filledData","planLinesOps","plan","push","byId","recordId","final","etagOf","written","data","added","etags","wildcard","encodeKey","reorder","start","tags","create","place","ref","placeOf","moved","each","above","refOf","useLinesDraft","setState","rejection","setRejection","nextId","target","order","toFieldDraft","forget","findLinesResource","lineColumnNames","listColumnNames","useRecordLines","parent","columns","galleryTiles","swipeStep","dx","dy","keyStep","steppedPhoto","by","togglesDetails","detailsOpenStorageKey","readDetailsOpen","writeDetailsOpen","control","Lightbox","panel","sidebarId","desktop","useIsDesktop","detailsOpen","setDetailsOpen","trapped","setTrapped","useFocusTrap","photos","onIndex","image","shownImage","shownDetails","hasDetails","toggleDetails","detailsTitle","X","FileImage","ChevronLeft","Sheet","detailFields","sections","whenShown","omit","PhotoDetails","photoKey","singular","FieldValue","isPicture","parts","holder","galleryItems","isStoredFile","cover","same","useGalleryPhotos","sort","useQuery","spans","Tile","photo","large","GallerySection","photoPermissions","setOpen","holderView","readable","changedBy","describeChange","verb","afterSave","useRecordHistory","useInfiniteQuery","pageSize","pageParam","refetch","Loading","Change","who","formatRelativeTime","HistorySection","history","CommentBody","comment","usePostComment","useMutation","input","CommentComposer","emptyDraft","post","submit","useRecordComments","Comment","Avatar","initialsOf","hueOf","CommentsSection","comments","canWrite","innerItems","whenOf","conditionalItems","isRecordCondition","fallbackEntries","shownLayout","when","held","itself","fallbackAt","inner","useShownLayout","conditions","useConditions","w","elsewhereRequest","otherOrganization","tenant","useRecordElsewhere","request","organizations","setFound","session","other","useRelatedRecords","titleOf","relations","relationTitleQuery","addresses","relationTitle","incomingRelations","listed","drawnItems","registered","plural","several","incomingAddress","relation","useIncomingCounts","counts","IncomingCard","formatInt","HeadingCount","Badge","formatTag","names","relatedAdd","createOffered","Empty","singularOf","RelatedRecord","xs","useIsXs","orderBy","defaultOrderBy","useListPage","adding","add","Plus","scopeOf","labelled","RelatedField","path","RowButtonLink","viewAllAddress","embeddedDisplay","listText","ArrowRight","and","given","relatedMatch","through","links","parseFilter","countTotal","useRelatedCount","counted","queries","countQuery","match","enabled","RelatedSection","display","pick","useEmbeddedDisplay","sorting","setSorting","heading","opens","relatedOpens","RelatedCards","handOrder","relatedHandOrder","displaySwitch","EmbeddedDisplaySwitch","ReorderButton","HandSortedList","EmbeddedList","relatedValue","relationTarget","GroupCount","only","titleBadgeField","sidebarFields","visible","recordMessagesFilter","ThreadSection","working","callsModel","calls","ThreadBox","MessageThread","RecordBlocks","tree","RootRecordScope","PlanReadsProvider","StartBlockQueries","RenderNode","RecordLines","lazyComponent","__vitePreload","ComposerSection","hidden","layoutFor","editable","RecordPage","ui","useOpenedRecord","Notice","RecordSkeleton","RecordNotFound","LoadedRecord","opened","viewedField","back","FileViewerPage","standardAsked","to","openedAddress","RecordOpens","meta","fieldsRef","useFocusFirstInvalid","canUpdate","recordShown","openGroups","atEdit","addressedTab","recordAt","readAddress","editAddress","leavesForm","related","pickTarget","picked","drafted","fromDraft","chosen","isChosen","fieldTypes","updatedAt","hint","known","badgeField","ValueBadge","fieldView","problem","locked","Field","isRequiredOnEdit","fieldHelp","isWideField","showsValue","linkTextOf","readRow","firstSidebar","summary","MetadataCard","markdown","isMarkdown","json","markdownExcerpt","jsonSummary","contact","contactFormat","builtIn","ContactLink","valueTitle","shownWidget","WidgetPart","startDelete","formControls","inApp","mainItem","visibleFields","filledFields","helpShown","sidebarCard","offersEdit","after","Fragment"],"ignoreList":[0,1,2,3,4],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/images.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/info.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/list-tree.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/undo-2.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/zap.mjs","../../../src/record-view/record-header.tsx","../../../src/record-view/group-section.tsx","../../../src/record-view/record-tabs.tsx","../../../src/record-view/spec-table.tsx","../../../src/record-view/key-facts.tsx","../../../src/record-view/action-rail.tsx","../../../src/app/use-lines.ts","../../../src/live/audit-fields.ts","../../../src/app/custom-section.tsx","../../../src/app/full-area-record.tsx","../../../src/app/conversation-page/conversation-call.tsx","../../../src/app/conversation-page/members-title.tsx","../../../src/app/conversation-page/conversation-header.tsx","../../../src/app/conversation-page/delete-message-dialog.tsx","../../../src/app/conversation-page/message-actions-bar.tsx","../../../src/app/conversation-page/message-actions-sheet.tsx","../../../src/app/conversation-page/attachments.ts","../../../src/app/conversation-page/message-attachments.tsx","../../../src/app/conversation-page/message-editor.tsx","../../../src/app/conversation-page/reaction-chips.tsx","../../../src/app/conversation-page/reply-labels.ts","../../../src/app/conversation-page/thread-summary.tsx","../../../src/app/conversation-page/message-access.ts","../../../src/app/conversation-page/reactions.ts","../../../src/app/conversation-page/use-message-controls.ts","../../../src/app/conversation-page/message-press.ts","../../../src/app/conversation-page/use-message-press.ts","../../../src/app/conversation-page/conversation-message.tsx","../../../src/app/conversation-page/conversation-reads.ts","../../../src/app/conversation-page/conversation-rows.ts","../../../src/app/conversation-page/use-message-attachments.ts","../../../src/app/conversation-page/use-message-reactions.ts","../../../src/app/conversation-page/use-message-writes.ts","../../../src/app/conversation-page/use-message-setup.ts","../../../src/app/conversation-page/use-new-line.ts","../../../src/app/conversation-page/conversation-messages.tsx","../../../src/app/conversation-page/member-search.ts","../../../src/app/conversation-page/thread-head.ts","../../../src/app/conversation-page/use-thread-head.ts","../../../src/app/conversation-page/thread-panel.tsx","../../../src/app/conversation-page/read-position-write.ts","../../../src/app/conversation-page/use-read-position.ts","../../../src/app/conversation-page/use-thread-address.ts","../../../src/app/conversation-page/conversation-page.tsx","../../../src/app/draft-storage.ts","../../../src/app/action-icon.ts","../../../src/app/pages/record-actions.tsx","../../../src/app/batch-failure.ts","../../../src/app/use-record-editor.ts","../../../src/app/focus/messages.ts","../../../src/app/focus/conflict-choices.tsx","../../../src/app/focus/record-focus-page.tsx","../../../src/app/map/map-section.tsx","../../../src/app/record-chart/chart-points.ts","../../../src/app/record-chart/messages.ts","../../../src/app/record-chart/record-chart-section.tsx","../../../src/app/record-trend/messages.ts","../../../src/app/record-trend/trend-summary.ts","../../../src/app/record-trend/record-trend-section.tsx","../../../src/app/group-open.ts","../../../src/app/record-tabs.ts","../../../src/app/lines-plan.ts","../../../src/app/use-lines-draft.ts","../../../src/app/use-record-lines.ts","../../../src/app/gallery/gallery-layout.ts","../../../src/app/gallery/details-open-storage.ts","../../../src/app/gallery/messages.ts","../../../src/app/gallery/lightbox.tsx","../../../src/app/gallery/detail-fields.ts","../../../src/app/gallery/photo-details.tsx","../../../src/app/gallery/gallery-items.ts","../../../src/app/gallery/use-gallery-photos.ts","../../../src/app/gallery/gallery-section.tsx","../../../src/app/history/messages.ts","../../../src/app/history/describe-change.ts","../../../src/app/history/use-record-history.ts","../../../src/app/history/history-section.tsx","../../../src/app/comments/comment-body.tsx","../../../src/app/comments/use-post-comment.ts","../../../src/app/comments/messages.ts","../../../src/app/comments/comment-composer.tsx","../../../src/app/comments/use-record-comments.ts","../../../src/app/comments/comments-section.tsx","../../../src/app/record-mode/shown-layout.ts","../../../src/app/record-mode/use-shown-layout.ts","../../../src/app/record-elsewhere.ts","../../../src/app/use-record-elsewhere.ts","../../../src/app/use-related-records.ts","../../../src/app/incoming-relations.ts","../../../src/app/use-incoming-counts.ts","../../../src/app/incoming-card.tsx","../../../src/record-view/heading-count.tsx","../../../src/app/related-cards/related-add.ts","../../../src/app/related-cards/related-record.tsx","../../../src/app/related-match.ts","../../../src/app/related-count.ts","../../../src/app/related-section.tsx","../../../src/app/related-value.ts","../../../src/app/group-count.tsx","../../../src/app/read-values/title-badge.ts","../../../src/app/conversation/record-filter.ts","../../../src/app/conversation/thread-section.tsx","../../../src/app/pages/record-blocks.tsx","../../../src/app/record-sections.tsx","../../../src/app/record-page.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: \"images\",\n size: 24,\n node: [\n [\"path\", { d: \"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16\", key: \"9kzy35\" }],\n [\"path\", { d: \"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2\", key: \"1t0f0t\" }],\n [\"circle\", { cx: \"13\", cy: \"7\", r: \"1\", fill: \"currentColor\", key: \"1obus6\" }],\n [\"rect\", { x: \"8\", y: \"2\", width: \"14\", height: \"14\", rx: \"2\", key: \"1gvhby\" }]\n ]\n};\n__iconData.node;\nconst Images = createLucideIcon(__iconData);\n\nexport { __iconData, Images as default };\n//# sourceMappingURL=images.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: \"info\",\n size: 24,\n node: [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"M12 16v-4\", key: \"1dtifu\" }],\n [\"path\", { d: \"M12 8h.01\", key: \"e9boi3\" }]\n ]\n};\n__iconData.node;\nconst Info = createLucideIcon(__iconData);\n\nexport { __iconData, Info as default };\n//# sourceMappingURL=info.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"list-tree\",\n size: 24,\n node: [\n [\"path\", { d: \"M8 5h13\", key: \"1pao27\" }],\n [\"path\", { d: \"M13 12h8\", key: \"h98zly\" }],\n [\"path\", { d: \"M13 19h8\", key: \"c3s6r1\" }],\n [\"path\", { d: \"M3 10a2 2 0 0 0 2 2h3\", key: \"1npucw\" }],\n [\"path\", { d: \"M3 5v12a2 2 0 0 0 2 2h3\", key: \"x1gjn2\" }]\n ]\n};\n__iconData.node;\nconst ListTree = createLucideIcon(__iconData);\n\nexport { __iconData, ListTree as default };\n//# sourceMappingURL=list-tree.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: \"undo-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M9 14 4 9l5-5\", key: \"102s5s\" }],\n [\"path\", { d: \"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11\", key: \"f3b9sd\" }]\n ]\n};\n__iconData.node;\nconst Undo2 = createLucideIcon(__iconData);\n\nexport { __iconData, Undo2 as default };\n//# sourceMappingURL=undo-2.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: \"zap\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z\",\n key: \"1v7up4\"\n }\n ]\n ]\n};\n__iconData.node;\nconst Zap = createLucideIcon(__iconData);\n\nexport { __iconData, Zap as default };\n//# sourceMappingURL=zap.mjs.map\n","import type { ReactNode } from 'react'\nimport { AvatarStack } from '../primitives/avatar'\nimport { text } from './messages'\n\nexport type RecordHeaderProps = {\n /** A line above the title naming the collection; the record page leaves it to the breadcrumb. */\n collection?: string\n title: string\n /** The badge beside the title, such as a status; without it there is none. */\n badge?: ReactNode\n /** A line under the title; without a name it reads \"Last updated ...\". The record page leaves it to its sidebar. */\n lastEditedBy?: { name?: string; ago: string }\n presence?: Array<{ initials: string; hue: number }>\n actions?: ReactNode\n}\n\nexport const RecordHeader = ({ collection, title, badge, lastEditedBy, presence = [], actions }: RecordHeaderProps) => {\n return (\n <header className=\"flex flex-col gap-4 border-b border-border pb-6 md:flex-row md:items-end md:justify-between md:gap-6\">\n <div>\n {collection && <p className=\"mb-1 text-xs text-muted-foreground\">{collection}</p>}\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <h1 className=\"text-xl font-semibold tracking-tight text-foreground md:text-2xl\">{title}</h1>\n {badge}\n </div>\n {lastEditedBy && (\n <p className=\"mt-1.5 text-xs text-muted-foreground\">\n {lastEditedBy.name ? (\n <>\n {text('lastEditedBy')} <span className=\"font-medium text-foreground\">{lastEditedBy.name}</span> {lastEditedBy.ago}\n </>\n ) : (\n <>{text('lastUpdated', { ago: lastEditedBy.ago })}</>\n )}\n </p>\n )}\n </div>\n <div className=\"flex items-center gap-4\">\n {presence.length > 0 && (\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <AvatarStack people={presence} size=\"md\" />\n {text('viewing', { count: presence.length })}\n </span>\n )}\n {actions}\n </div>\n </header>\n )\n}\n","import { ChevronRight } from 'lucide-react'\nimport { useId, type ReactNode } from 'react'\nimport type { AppAddress } from '@protobase/schema'\nimport { cn } from '../lib/cn'\nimport { AppLink } from '../app/use-app-address'\nimport { HeadingLevel } from '../lib/heading-level'\n\nconst headingClass = 'text-base font-semibold text-foreground'\n\ntype GroupSectionProps = { title: string; help?: string; count?: ReactNode; open: boolean; toggle?: AppAddress; children: ReactNode }\n\n/**\n * A heading over sections of the record page, `count` after its title and `help` under it. With `toggle`, the address\n * that opens or closes it, the heading is a link, so a copied link opens the page with the group open; the items show\n * only while `open`. Without it the group is always open. Its heading is an h2 and the sections in it head with h3.\n */\nexport const GroupSection = ({ title, help, count, open, toggle, children }: GroupSectionProps) => {\n const id = useId()\n return (\n <div>\n <div className={cn('py-8', open && 'pb-0')}>\n <h2 className=\"flex items-center gap-2\">\n {toggle ? (\n <AppLink to={toggle} replace aria-expanded={open} aria-controls={id} className={cn('inline-flex items-center gap-1.5', headingClass)}>\n <ChevronRight className={cn('size-4 transition-transform', open && 'rotate-90')} />\n {title}\n </AppLink>\n ) : (\n <span className={headingClass}>{title}</span>\n )}\n {count}\n </h2>\n {help && <p className={cn('mt-1 max-w-xl leading-6 text-muted-foreground', toggle && 'pl-5.5')}>{help}</p>}\n </div>\n {open && (\n <div id={id} className=\"divide-y divide-border\">\n <HeadingLevel.Provider value={2}>{children}</HeadingLevel.Provider>\n </div>\n )}\n </div>\n )\n}\n","import type { AppAddress } from '@protobase/schema'\nimport { cn } from '../lib/cn'\nimport { AppLink } from '../app/use-app-address'\nimport { segmentedClass } from '../primitives/segmented'\nimport { text } from './messages'\n\n/** The record page's tabs, links whose addresses show each; the shown one is the current page. */\nexport const RecordTabs = ({ tabs }: { tabs: Array<{ title: string; to: AppAddress; current: boolean }> }) => (\n // One line of tabs scrolls sideways on a narrow screen, which the page cannot do for it\n <nav aria-label={text('tabs')} className=\"overflow-x-auto py-6\">\n <span className={segmentedClass.group('md')}>\n {tabs.map((tab) => (\n <AppLink key={tab.title} to={tab.to} replace aria-current={tab.current ? 'page' : undefined} className={cn(segmentedClass.option(tab.current, 'md'), 'whitespace-nowrap')}>\n {tab.title}\n </AppLink>\n ))}\n </span>\n </nav>\n)\n","import type { ReactNode } from 'react'\nimport { cn } from '../lib/cn'\n\nexport type SpecRow = {\n label: string\n value: ReactNode\n /** A line under the label. */\n help?: string\n /** The value runs under its label across the row, as a text of several lines does. */\n wide?: boolean\n}\n\n/**\n * Label/value rows, the label on the left and the value on the right, as a property's features table on a real estate\n * site: what a record page's section shows on its read view. A wide row puts its value under the label.\n */\nexport const SpecTable = ({ rows }: { rows: SpecRow[] }) => (\n <dl className=\"border-t border-border\">\n {rows.map((row) => (\n <div key={row.label} className={cn('grid gap-x-4 border-b border-border py-2.5', row.wide ? 'grid-cols-1 gap-y-1.5' : 'grid-cols-[minmax(0,2fr)_minmax(0,3fr)]')}>\n <dt className=\"min-w-0 text-muted-foreground\">\n {row.label}\n {row.help && <span className=\"mt-0.5 block text-xs text-faint-foreground\">{row.help}</span>}\n </dt>\n <dd className=\"min-w-0 break-words text-foreground\">{row.value}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { LucideIcon } from 'lucide-react'\nimport type { ReactNode } from 'react'\n\nexport type KeyFact = {\n label: string\n value: ReactNode\n /** Drawn above the value in place of the label, which screen readers and the tooltip still give. */\n icon?: LucideIcon\n}\n\n/**\n * A record's key facts side by side, as the bedrooms, area and energy label of a listing on a real estate site: each\n * value under its icon, or under its label without one, wrapping onto more rows as needed, two to a row on a mobile\n * screen.\n */\nexport const KeyFacts = ({ facts }: { facts: KeyFact[] }) => (\n <dl className=\"grid grid-cols-2 gap-x-4 gap-y-5 sm:flex sm:flex-wrap sm:gap-x-10\">\n {facts.map(({ label, value, icon: Icon }) => (\n <div key={label} title={label} className=\"flex min-w-0 flex-col gap-1.5\">\n <dt className=\"text-muted-foreground\">\n {Icon ? (\n <>\n <Icon className=\"size-5\" aria-hidden />\n <span className=\"sr-only\">{label}</span>\n </>\n ) : (\n label\n )}\n </dt>\n <dd className=\"min-w-0 break-words text-base font-semibold text-foreground\">{value}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { LucideIcon } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport { cn } from '../lib/cn'\nimport { text } from './messages'\n\nexport type RailAction = {\n name: string\n description?: string\n icon: LucideIcon\n onRun?: () => void\n /** Why the action cannot run now; the button is disabled with this as its tooltip. */\n blocked?: string\n running?: boolean\n /** `danger` draws an action that destroys something, such as Delete, in red. */\n tone?: 'danger'\n /**\n * Draws the action as the caller's own element, such as a link, given the rail's classes and content, instead of a\n * button; in a menu, with the `menuitem` role too.\n */\n render?: (item: { className: string; children: ReactNode; role?: 'menuitem' }) => ReactNode\n}\n\nconst itemClass =\n 'flex min-h-11 items-center gap-2 rounded-md border border-border-strong px-3 text-left hover:bg-surface disabled:cursor-default disabled:opacity-60 md:min-h-0 md:w-full md:items-start md:gap-3 md:rounded-none md:border-0 md:px-4 md:py-3'\n\n/** Named actions with one-line descriptions; on phones a row of buttons, from `md` a list. */\nexport const ActionRail = ({ actions }: { actions: RailAction[] }) => (\n <div className=\"overflow-hidden rounded-lg border border-border bg-background\">\n <h2 className=\"hidden border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:block\">{text('actions')}</h2>\n <ul className=\"flex flex-wrap gap-2 p-2 md:block md:divide-y md:divide-border md:p-0\">\n {actions.map(({ name, description, icon: Icon, onRun, blocked, running, tone, render }) => {\n const children = (\n <>\n <Icon className={cn('size-4 shrink-0 md:mt-0.5', tone === 'danger' ? 'text-danger-text' : 'text-muted-foreground')} aria-hidden />\n <span>\n <span className={cn('block font-medium', tone === 'danger' ? 'text-danger-text' : 'text-foreground')}>{name}</span>\n {description && <span className=\"mt-0.5 hidden text-xs leading-snug text-muted-foreground md:block\">{description}</span>}\n </span>\n </>\n )\n return (\n <li key={name}>\n {render ? (\n render({ className: itemClass, children })\n ) : (\n <button type=\"button\" onClick={onRun} disabled={Boolean(blocked) || running} title={blocked} className={itemClass}>\n {children}\n </button>\n )}\n </li>\n )\n })}\n </ul>\n </div>\n)\n","import { useEffect, useMemo } from 'react'\nimport type { FieldModel, ResourceModel } from '@protobase/schema'\nimport { useList } from '../data/use-list'\n\n/** The most lines a record's line editor loads; a record with more shows them read-only, as it cannot save them as a whole. */\nexport const linesLimit = 1000\n\n/**\n * The numbered lines of a record, in the order of their `position` field, as the server has them: every page, up to\n * `linesLimit`, each as large as the API gives. `labels` names the records their relations point at. Nothing is\n * fetched without a lines resource.\n */\nexport const useLines = (lines: ResourceModel | undefined, link: FieldModel | undefined, position: string | undefined, parentKey: string, labels?: Record<string, string>) => {\n const list = useList(lines?.name ?? '', {\n enabled: Boolean(lines && link),\n filter: link ? `${link.name} = \"${parentKey}\"` : undefined,\n pageSize: 500,\n labels,\n ...(position && lines?.fields[position]?.sortable && { orderBy: `${position} asc` }),\n })\n // The same array while no page changes, so what depends on the lines is worked out again only when they do\n const items = useMemo(() => (position ? [...list.items].sort((a, b) => Number(a[position]) - Number(b[position])) : list.items), [list.data, position])\n const more = list.hasNextPage && list.items.length < linesLimit\n useEffect(() => {\n if (more && !list.isFetchingNextPage) void list.fetchNextPage()\n }, [more, list.isFetchingNextPage])\n return {\n items,\n labels: list.labels,\n loading: (list.isPending || more) && Boolean(lines),\n /** Every line is loaded, so the lines can be saved as a whole. */\n complete: !list.hasNextPage,\n }\n}\n","import type { ResourceModel } from '@protobase/schema'\n\n/** The field that holds when a record was created or last updated: `created_at` or `createdAt`, as the model names it. */\nexport const auditField = (model: ResourceModel, kind: 'created' | 'updated') => [`${kind}_at`, `${kind}At`].find((name) => model.fields[name])\n","import type { ReactNode } from 'react'\nimport type { CustomSectionModel } from '@protobase/schema'\nimport { unmarkFieldRefs } from '@protobase/schema/internal'\nimport { Section, SidebarCard } from '../record-view'\nimport { CustomOrFallback } from './pages/custom-or-fallback'\nimport { useProjectUi } from './pages/project-ui'\nimport { RecordScope, type LayoutRecord } from './pages/record-scope'\n\n// A section or a sidebar card under the item's title when it has one\nconst frame = (item: CustomSectionModel, body: ReactNode) => {\n if (item.sidebar) return item.title ? <SidebarCard title={item.title}>{body}</SidebarCard> : body\n return item.title ? <Section title={item.title}>{body}</Section> : <section className=\"py-8\">{body}</section>\n}\n\n/**\n * A component of the record layout (`l.custom`), drawn with the record around it, so `useLayoutRecord()` gives it, in a\n * section or a sidebar card under its title when it has one. The record page around it stays the framework's. When the\n * component is missing or throws, `fallback`, the item's fallback as the page draws it, takes its place, title included.\n */\nexport const CustomSection = ({ item, scope, fallback }: { item: CustomSectionModel; scope: LayoutRecord; fallback: ReactNode | undefined }) => {\n const { components } = useProjectUi()\n const Component = components?.[item.component]\n const body = Component && (\n <RecordScope value={scope}>\n <Component {...unmarkFieldRefs(item.props ?? {})} />\n </RecordScope>\n )\n // Without a fallback the warning stands in the frame, where the component would\n if (fallback === undefined) {\n return frame(\n item,\n <CustomOrFallback name={item.component} registered={Boolean(Component)} fallback={undefined}>\n {body}\n </CustomOrFallback>,\n )\n }\n return (\n <CustomOrFallback name={item.component} registered={Boolean(Component)} fallback={fallback}>\n {frame(item, body)}\n </CustomOrFallback>\n )\n}\n","import type { ReactElement, ReactNode } from 'react'\nimport { usePageScroll } from '../app-shell'\nimport { CustomBoundary } from './pages/custom-boundary'\nimport { useProjectUi } from './pages/project-ui'\nimport { RecordScope, type LayoutRecord } from './pages/record-scope'\n\n/**\n * A record page that is a component of the app's own (`.record({ component })`), with the record around it as\n * `useLayoutRecord()` gives it. It fills the content area, which does not scroll while it shows; `standard`, the\n * record's standard page, shows instead while the component is missing or when it throws.\n */\nexport const FullAreaRecord = ({ component, scope, standard }: { component: string; scope: LayoutRecord; standard: ReactElement }) => {\n const { components } = useProjectUi()\n const Component = components?.[component]\n if (!Component) return standard\n return (\n <CustomBoundary name={component} fallback={standard}>\n <FullArea>\n <RecordScope value={scope}>\n <Component />\n </RecordScope>\n </FullArea>\n </CustomBoundary>\n )\n}\n\n/**\n * The content area of a record page that fills it, where the page does not scroll. Inside a boundary, a component that\n * throws takes the page's scrolling back with it. The one grid cell stretches its child to the area's width and height.\n */\nexport const FullArea = ({ children }: { children: ReactNode }) => {\n usePageScroll(false)\n return <div className=\"grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]\">{children}</div>\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { RecordCall } from '../../calls/record-call'\nimport { useRecordCallAddress } from '../../calls/use-record-call-address'\nimport { useClient } from '../../data/api-provider'\nimport { useMembers } from '../../people/use-members'\nimport type { LayoutRecord } from '../pages/record-scope'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord }\n\n/**\n * The record's call while the page joins it (`?call=join`), on a conversation with `call`: beside the messages, or\n * above them at mobile width, half the space either way, so the box under the messages stays in view. It opens the\n * `call` function's socket with the record's key, and names the people in it after the organization's members.\n */\nexport const ConversationCall = ({ page, scope }: Props) => {\n const { joining } = useRecordCallAddress(scope.model.name, scope.key)\n const client = useClient()\n const members = useMembers()\n if (page.call === undefined || !joining) return null\n return (\n <div className=\"grid min-h-0 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)] border-border max-md:h-1/2 max-md:border-b md:w-1/2 md:border-r\">\n <RecordCall resource={scope.model.name} recordKey={scope.key} url={client.functionSocketUrl(page.call, { key: scope.key })} nameOf={(user) => members.member(user)?.name ?? user} />\n </div>\n )\n}\n","import { useOptionalAuth } from '../../auth/auth-provider'\nimport { useMembers } from '../../people/use-members'\nimport { presenceOf, usePresence } from '../../presence/presence'\nimport { StatusMark } from '../../status/status-mark'\nimport { otherMembers } from '../titles/member-names'\n\n/**\n * The people of a members field other than the reader, by name, each with their presence and status as `StatusMark`\n * draws it: its text in full beside one person, on hover beside several. `fallback`, the record's title, shows until\n * every name is known.\n */\nexport const MembersTitle = ({ value, fallback }: { value: unknown; fallback: string }) => {\n const auth = useOptionalAuth()\n const me = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const { member } = useMembers()\n const presence = usePresence()\n const others = otherMembers(value, me)\n if (others.length === 0 || !others.every((id) => member(id))) return fallback\n return others.map((id, index) => (\n <span key={id} className=\"inline-flex min-w-0 items-center gap-1.5\">\n {member(id)!.name}\n <StatusMark status={member(id)!.status} presence={presenceOf(presence, id)} textShown={others.length === 1 ? 'full' : 'hover'} />\n {index < others.length - 1 && ','}\n </span>\n ))\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { CallMark } from '../../calls/call-mark'\nimport { cn } from '../../lib/cn'\nimport { buttonClass } from '../../primitives/button'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { AppLink } from '../use-app-address'\nimport { MembersTitle } from './members-title'\nimport { text } from './messages'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord; title: string }\n\n/**\n * The slim row over a conversation: the record's title, which the top bar repeats at mobile width and so shows only on\n * a wider screen, or with `members` the other people in it with their status, shown at every width; its `subtitle`\n * beside it; with `call`, the record's call, Start call or the call going on with Join; and a link to the record's\n * standard page, where its details, Edit and Delete are.\n */\nexport const ConversationHeader = ({ page, scope, title }: Props) => {\n const subtitle = page.subtitle === undefined ? undefined : scope.record[page.subtitle]\n const members = page.members !== undefined\n return (\n <div className=\"flex h-12 shrink-0 items-center gap-3 border-b border-border bg-background px-4\">\n <h1 className={cn(members ? 'flex' : 'hidden md:flex', 'min-w-0 items-center gap-2 truncate font-medium')}>{members ? <MembersTitle value={scope.record[page.members!]} fallback={title} /> : title}</h1>\n {typeof subtitle === 'string' && subtitle !== '' && <p className=\"min-w-0 flex-1 truncate text-sm text-muted-foreground\">{subtitle}</p>}\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n {page.call !== undefined && <CallMark resource={scope.model.name} recordKey={scope.key} />}\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: scope.key, standard: true }} className={buttonClass({ variant: 'ghost', size: 'sm' })}>\n {text('details')}\n </AppLink>\n </div>\n </div>\n )\n}\n","import { Button } from '../../primitives/button'\nimport { ResponsiveDialog } from '../../primitives/responsive-dialog'\nimport { text } from './messages'\n\n/** Asks before a message is deleted, since it goes for everyone in the conversation. */\nexport const DeleteMessageDialog = ({ onDelete, onClose }: { onDelete: () => void; onClose: () => void }) => (\n <ResponsiveDialog\n open\n title={text('deleteTitle')}\n description={text('deleteDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"danger\" onClick={onDelete}>\n {text('delete')}\n </Button>\n </>\n }\n />\n)\n","import { Button, buttonClass } from '../../primitives/button'\nimport { AppLink } from '../use-app-address'\nimport type { MessageControls } from './message-controls'\nimport { text } from './messages'\n\n/**\n * What the reader can do to a message, a bar over its top right corner shown while they point at it or move into it with\n * the keyboard, so it takes no room of its own: react with an emoji they have not reacted with yet, reply in its\n * thread, edit and delete. Only a screen that can point shows it; on a touch screen a tap or long-press opens\n * `MessageActionsSheet` instead.\n */\nexport const MessageActionsBar = ({ controls }: { controls: MessageControls }) => {\n const { emoji, groups, onReact, thread, onEdit, onDelete } = controls\n const reacted = new Set(groups.filter((group) => group.mine).map((group) => group.emoji))\n const offered = onReact ? emoji.filter((entry) => !reacted.has(entry.emoji)) : []\n if (offered.length === 0 && !thread && !onEdit && !onDelete) return null\n return (\n <div\n role=\"toolbar\"\n aria-label={text('messageActions')}\n className=\"pointer-events-none absolute -top-3 right-0 z-10 hidden items-center gap-0.5 rounded-md border border-border bg-background p-0.5 opacity-0 shadow-sm transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100 [@media(hover:hover)]:flex\"\n >\n {offered.map(({ emoji: value, symbol, name }) => (\n <Button key={value} size=\"icon\" variant=\"ghost\" aria-label={text('reactWith', { name })} title={name} onClick={() => onReact!(value)}>\n <span aria-hidden>{symbol}</span>\n </Button>\n ))}\n {thread && (\n <AppLink to={thread} className={buttonClass({ variant: 'ghost', size: 'sm' })}>\n {text('replyInThread')}\n </AppLink>\n )}\n {onEdit && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onEdit}>\n {text('edit')}\n </Button>\n )}\n {onDelete && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onDelete}>\n {text('delete')}\n </Button>\n )}\n </div>\n )\n}\n","import { Button, buttonClass } from '../../primitives/button'\nimport { ResponsiveDialog } from '../../primitives/responsive-dialog'\nimport { AppLink } from '../use-app-address'\nimport type { MessageControls } from './message-controls'\nimport { text } from './messages'\n\ntype Props = {\n controls: MessageControls\n /** Names the message it acts on, such as \"Message from Lena Fischer\". */\n title: string\n /** The message's text, shown under the title. */\n preview: string\n onClose: () => void\n}\n\n/**\n * What the reader can do to a message, opened by a finger's tap or long-press on it, under a line of the message: a row\n * of every emoji, those they reacted with pressed, taking their reaction back as its chip does, then reply in its\n * thread, copy its text, edit and delete. A sheet from the bottom at mobile width, a dialog on a wider touch screen.\n * Each choice closes it.\n */\nexport const MessageActionsSheet = ({ controls, title, preview, onClose }: Props) => {\n const { emoji, groups, onReact, onUnreact, thread, onCopy, onEdit, onDelete } = controls\n const mine = new Map(groups.flatMap((group) => (group.mine ? [[group.emoji, group.mine] as const] : [])))\n const choose = (onChoose: () => void) => () => {\n onClose()\n onChoose()\n }\n // The sheet stacks its buttons from the last up, and the dialog lines them up from the left: Delete leftmost there,\n // Reply in thread on top here\n return (\n <ResponsiveDialog\n open\n title={title}\n description={preview && <span className=\"line-clamp-2\">{preview}</span>}\n onClose={onClose}\n actions={\n <>\n {onDelete && (\n <Button variant=\"danger\" onClick={choose(onDelete)}>\n {text('delete')}\n </Button>\n )}\n {onEdit && <Button onClick={choose(onEdit)}>{text('edit')}</Button>}\n {onCopy && <Button onClick={choose(onCopy)}>{text('copyText')}</Button>}\n {thread && (\n <AppLink to={thread} className={buttonClass()} onClick={onClose}>\n {text('replyInThread')}\n </AppLink>\n )}\n </>\n }\n >\n {emoji.length > 0 && (\n <div role=\"group\" aria-label={text('react')} className=\"flex flex-wrap gap-1\">\n {emoji.map(({ emoji: value, symbol, name }) => {\n const reaction = mine.get(value)\n const press = reaction ? onUnreact && (() => onUnreact(reaction)) : onReact && (() => onReact(value))\n return (\n <Button key={value} size=\"icon\" variant={reaction ? 'secondary' : 'ghost'} aria-pressed={reaction !== undefined} aria-label={text('reactWith', { name })} disabled={!press} onClick={press && choose(press)}>\n <span aria-hidden>{symbol}</span>\n </Button>\n )\n })}\n </div>\n )}\n </ResponsiveDialog>\n )\n}\n","import type { AttachmentsModel, ResourceModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { fileShown, isPreviewable } from '../../live/file-values'\n\ntype Row = Record<string, unknown>\n\n/**\n * A file under a message, as its attachment record gives it: the record's key, which deletes it, the file's name, type\n * and size from the file field's value, the signed link the API answers with it, `undefined` while the file is missing\n * from storage, and an image's size in pixels where the record holds it.\n */\nexport type Attachment = { key: ReturnType<typeof recordKey>; name: string; type: string; size: number | undefined; url: string | undefined; width: number | undefined; height: number | undefined }\n\nconst pixels = (value: unknown) => (typeof value === 'number' ? value : undefined)\n\n/** The attachment record `row` as an `Attachment`; `undefined` for one with no file. */\nexport const attachmentOf = (row: Row, model: ResourceModel, attachments: AttachmentsModel): Attachment | undefined => {\n const file = fileShown(row[attachments.file])\n if (!file) return\n const stored = 'missing' in file ? undefined : file\n return {\n key: recordKey(model, row),\n name: file.name,\n type: file.type,\n size: stored?.size,\n url: stored?.url,\n width: attachments.width === undefined ? undefined : pixels(row[attachments.width]),\n height: attachments.height === undefined ? undefined : pixels(row[attachments.height]),\n }\n}\n\n/** Attachment rows by the key of the message they are in, as text, each message's in the order the rows came. */\nexport const attachmentsByMessage = (rows: readonly Row[], model: ResourceModel, attachments: AttachmentsModel) => {\n const byMessage = new Map<string, Attachment[]>()\n for (const row of rows) {\n const attachment = attachmentOf(row, model, attachments)\n if (!attachment) continue\n const message = String(row[attachments.field])\n byMessage.set(message, [...(byMessage.get(message) ?? []), attachment])\n }\n return byMessage\n}\n\n/** Whether a file shows as an image under its message, rather than as a link that downloads it: a raster image with a link. */\nexport const isPreviewed = (attachment: Pick<Attachment, 'type' | 'url'>) => attachment.url !== undefined && isPreviewable(attachment.type)\n","import { FileText } from 'lucide-react'\nimport { formatSize } from '../../live/file-values'\nimport { buttonClass } from '../../primitives/button'\nimport { isPreviewed, type Attachment } from './attachments'\nimport { text } from './messages'\n\n/** The tallest an image preview is drawn, in CSS pixels; a wider one is scaled down to the message's width. */\nexport const previewHeight = 240\n\nconst FileLabel = ({ attachment }: { attachment: Attachment }) => (\n <>\n <FileText className=\"size-4\" />\n <span className=\"max-w-64 truncate\">{attachment.name}</span>\n {attachment.size !== undefined && <span className=\"text-muted-foreground\">{formatSize(attachment.size)}</span>}\n </>\n)\n\nconst FileDownload = ({ attachment }: { attachment: Attachment }) => {\n const className = buttonClass({ variant: 'secondary', size: 'sm' })\n if (attachment.url === undefined) {\n return (\n <span className={className} aria-disabled title={text('fileMissing')}>\n <FileLabel attachment={attachment} />\n </span>\n )\n }\n return (\n <a href={attachment.url} download={attachment.name} className={className}>\n <FileLabel attachment={attachment} />\n </a>\n )\n}\n\n/**\n * A message's files under its text: an image as a preview at most `previewHeight` high, a link that opens it in a new\n * tab, any other file as a link with its name and size that downloads it. The links are those the API signs for the\n * reader.\n */\nexport const MessageAttachments = ({ attachments }: { attachments: readonly Attachment[] }) => (\n <div className=\"flex flex-wrap items-start gap-2\">\n {attachments.map((attachment) =>\n isPreviewed(attachment) ? (\n <a key={String(attachment.key)} href={attachment.url} target=\"_blank\" rel=\"noreferrer\" title={attachment.name} className=\"max-w-full\">\n <img\n src={attachment.url}\n alt={attachment.name}\n width={attachment.width}\n height={attachment.height}\n style={{ maxHeight: previewHeight }}\n className=\"h-auto w-auto max-w-full rounded-md border border-border object-contain\"\n />\n </a>\n ) : (\n <FileDownload key={String(attachment.key)} attachment={attachment} />\n ),\n )}\n </div>\n)\n","import { useEffect, useRef, useState, type KeyboardEvent } from 'react'\nimport { MentionBox, mentionedIds, type MentionDraft, type PeopleSearch, type PickedUser } from '../../mentions'\nimport { Button } from '../../primitives/button'\nimport { text } from './messages'\n\ntype Props = {\n /** The message's text as it is. */\n body: string\n /** The people it mentions, by id and name, kept while their `@name` stays in the text. */\n picked: PickedUser[]\n /** Finds the people `@` lists; without it, `@` is plain text. */\n searchPeople?: PeopleSearch\n /** Resolves true once saved; false leaves the box open, as the server refused it. */\n onSave: (body: string, mentions: string[]) => Promise<boolean>\n onCancel: () => void\n}\n\n/**\n * A message's text in a box to change it, its mentions kept while their `@name` stays: Enter or Save keeps the trimmed\n * text, Shift+Enter starts a new line, Escape or Cancel leaves it as it was. An empty text is no edit: deleting is.\n * The box is read-only while it saves, so nothing typed then is lost, and a save that ends after the box closed\n * closes nothing, such as the box opened again on the same message.\n */\nexport const MessageEditor = ({ body, picked, searchPeople, onSave, onCancel }: Props) => {\n const [draft, setDraft] = useState<MentionDraft>({ text: body, picked })\n const [saving, setSaving] = useState(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const trimmed = draft.text.trim()\n const save = async () => {\n if (trimmed === '' || saving) return\n if (trimmed === body) return onCancel()\n setSaving(true)\n const saved = await onSave(trimmed, mentionedIds(trimmed, draft.picked))\n if (!mounted.current) return\n setSaving(false)\n if (saved) onCancel()\n }\n const keys = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.nativeEvent.isComposing) return\n if (event.key === 'Escape') return onCancel()\n if (event.key !== 'Enter' || event.shiftKey) return\n event.preventDefault()\n void save()\n }\n return (\n <div className=\"flex flex-col gap-2 whitespace-normal\">\n <MentionBox value={draft} onChange={setDraft} searchPeople={searchPeople} onKeyDown={keys} readOnly={saving} aria-label={text('editMessage')} autoFocus />\n <div className=\"flex gap-2\">\n <Button size=\"sm\" variant=\"primary\" disabled={trimmed === ''} loading={saving} onClick={() => void save()}>\n {text('save')}\n </Button>\n <Button size=\"sm\" onClick={onCancel}>\n {text('cancel')}\n </Button>\n </div>\n </div>\n )\n}\n","import { Button } from '../../primitives/button'\nimport type { ReactionGroup } from './reactions'\nimport { text } from './messages'\n\ntype Props = {\n groups: readonly ReactionGroup[]\n member: (id: string) => { name: string } | undefined\n /** Given when the reader may react. */\n onReact?: (emoji: string) => void\n /** Given when the reader may take back their own reaction. */\n onUnreact?: (reaction: Record<string, unknown>) => void\n}\n\n/**\n * A message's reactions, one button per emoji with its count, naming who reacted on hover: the reader's own filled,\n * taking it back when pressed, and another's adding the reader's with the same emoji.\n */\nexport const ReactionChips = ({ groups, member, onReact, onUnreact }: Props) =>\n groups.map(({ emoji, symbol, name, count, userIds, mine }) => {\n const people = userIds.map((id) => member(id)?.name ?? text('someone')).join(', ')\n const press = mine ? onUnreact && (() => onUnreact(mine)) : onReact && (() => onReact(emoji))\n return (\n <Button key={emoji} size=\"sm\" variant={mine ? 'primary' : 'secondary'} aria-pressed={mine !== undefined} aria-label={text('reactedBy', { name, people })} title={people} disabled={!press} onClick={press}>\n <span aria-hidden>{symbol}</span>\n <span>{count}</span>\n </Button>\n )\n })\n","import { chatDayLabel } from '../../chat/chat-day'\nimport { formatTime } from '../../format/date'\nimport { viewerZone } from '../../format/zone'\nimport { text } from './messages'\n\n/** When a thread's last reply came, sent at `time`: \"Last reply Today, 10:42\", in the viewer's zone unless given. */\nexport const lastReplyLabel = (time: string, now = Date.now(), zone = viewerZone()) => text('lastReply', { time: `${chatDayLabel(time, now, zone)}, ${formatTime(Date.parse(time), zone)}` })\n","import type { AppAddress } from '@protobase/schema'\nimport { formatDateTime } from '../../format/date'\nimport { buttonClass } from '../../primitives/button'\nimport { AppLink } from '../use-app-address'\nimport { lastReplyLabel } from './reply-labels'\nimport { text } from './messages'\n\ntype Props = { count: number; last: string | undefined; to: AppAddress }\n\n/** Under a thread's first message in the conversation: its number of replies, a link that opens the thread, and when the last one came. */\nexport const ThreadSummary = ({ count, last, to }: Props) => (\n <div className=\"flex items-center gap-2 whitespace-normal\">\n <AppLink to={to} className={`${buttonClass({ variant: 'ghost', size: 'sm' })} -ml-2.5`}>\n {text('replies', { count })}\n </AppLink>\n {last !== undefined && (\n <time dateTime={last} title={formatDateTime(Date.parse(last))} className=\"text-xs text-muted-foreground\">\n {lastReplyLabel(last)}\n </time>\n )}\n </div>\n)\n","import type { ResourcePermissions } from '@protobase/client'\nimport { evaluateCondition, parseCondition } from '@protobase/layout'\nimport type { ConversationPageModel } from '@protobase/schema'\nimport { can, rowAllows } from '../permissions'\n\ntype Row = Record<string, unknown>\n\n// Delete is offered unless its condition holds for the message; one that does not parse keeps every message\nconst deleteAllowed = (option: ConversationPageModel['delete'], row: Row) => {\n if (option === undefined || option === false) return false\n if (option === true) return true\n const condition = parseCondition(option.unless)\n return condition.ok && !evaluateCondition(condition, row)\n}\n\n/**\n * What the reader may do to a message, as far as the page can tell: edit their own (`mine`) when the conversation lets\n * authors edit, and delete one when it lets anyone and its condition does not keep the message, each only where the\n * resource's access and the row's own permissions allow it. The server checks every write again.\n */\nexport const messageAccess = (page: Pick<ConversationPageModel, 'edit' | 'delete'>, row: Row, mine: boolean, permissions: ResourcePermissions) => ({\n edit: page.edit === true && mine && can(permissions, 'update') && rowAllows(row, 'update'),\n delete: deleteAllowed(page.delete, row) && can(permissions, 'delete') && rowAllows(row, 'delete'),\n})\n\n/** Whether the reader may react, and take back their own reactions, by the reaction resource's access. */\nexport const reactionAccess = (permissions: ResourcePermissions) => ({ react: can(permissions, 'create'), unreact: can(permissions, 'delete') })\n","import type { ReactionsModel } from '@protobase/schema'\n\ntype Row = Record<string, unknown>\n\n/**\n * One emoji under a message: its label, how many reacted with it and who, by user id, and the reader's own reaction\n * with it, if any, as the row the reactions API gave.\n */\nexport type ReactionGroup = { emoji: string; symbol: string; name: string; count: number; userIds: string[]; mine?: Row }\n\n/** An emoji a conversation offers, as it stores it, draws it and names it. */\nexport type EmojiEntry = { emoji: string; symbol: string; name: string }\n\n/** The emoji a conversation offers, in the order of the emoji field's values, each with its label. */\nexport const emojiSet = (reactions: Pick<ReactionsModel, 'labels'>, values: readonly string[]): EmojiEntry[] =>\n values.flatMap((emoji) => (Object.hasOwn(reactions.labels, emoji) ? [{ emoji, ...reactions.labels[emoji]! }] : []))\n\n/** Reaction rows by the key of the message they answer, as text. */\nexport const reactionsByMessage = (rows: readonly Row[], field: string) => {\n const byMessage = new Map<string, Row[]>()\n for (const row of rows) {\n const message = String(row[field])\n byMessage.set(message, [...(byMessage.get(message) ?? []), row])\n }\n return byMessage\n}\n\n/** A message's reactions per emoji of `set`, in its order, each emoji someone reacted with once; `me` finds the reader's own. */\nexport const reactionGroups = (rows: readonly Row[], { user, emoji: field }: Pick<ReactionsModel, 'user' | 'emoji'>, set: readonly EmojiEntry[], me: string | undefined): ReactionGroup[] =>\n set.flatMap(({ emoji, symbol, name }) => {\n const these = rows.filter((row) => row[field] === emoji)\n if (these.length === 0) return []\n const userIds = these.map((row) => String(row[user]))\n return [{ emoji, symbol, name, count: these.length, userIds, mine: me === undefined ? undefined : these.find((row) => row[user] === me) }]\n })\n","import { useToast } from '../../toasts/toast-provider'\nimport { messageAccess, reactionAccess } from './message-access'\nimport type { MessageControls } from './message-controls'\nimport type { MessageSetup } from './message-setup'\nimport { reactionGroups } from './reactions'\nimport { text } from './messages'\n\ntype Message = { row: Record<string, unknown>; key: string; mine: boolean; body: string; onEdit: () => void; onDelete: () => void }\n\n/** What the reader can do to one message, as `MessageControls`, by the conversation's options and their access. */\nexport const useMessageControls = (setup: MessageSetup, { row, key, mine, body, onEdit, onDelete }: Message): MessageControls => {\n const toast = useToast()\n const { page, me, writes } = setup\n const access = messageAccess(page, row, mine, setup.messagePermissions)\n const reacts = reactionAccess(setup.reactionPermissions)\n const groups = page.reactions ? reactionGroups(setup.reactionsOf(key), page.reactions, setup.emoji, me) : []\n const copy = () =>\n navigator.clipboard.writeText(body).then(\n () => void toast.show({ state: 'success', title: text('copied') }),\n () => void toast.show({ state: 'error', title: text('notCopied') }),\n )\n return {\n emoji: reacts.react ? setup.emoji : [],\n groups,\n onReact: writes.react && reacts.react ? (emoji) => void writes.react!(key, emoji) : undefined,\n onUnreact: writes.unreact && reacts.unreact ? (reaction) => void writes.unreact!(reaction) : undefined,\n thread: setup.threadTo?.(key),\n onCopy: body === '' ? undefined : () => void copy(),\n onEdit: access.edit ? onEdit : undefined,\n onDelete: access.delete ? onDelete : undefined,\n }\n}\n","/** How long a finger rests on a message before its actions open without letting go. */\nexport const longPressMs = 500\n\n/** How far, in CSS pixels, a finger may drift before its press counts as a scroll rather than a tap or long-press. */\nexport const pressSlop = 10\n\n/**\n * Where a finger came down on a message, while it may still become a tap or long-press. `tapOpens`: a tap opens the\n * actions too, unless it came while the reader was typing, when it only lowers the keyboard. `lifted`: the finger is\n * up, so only the tap's click may still come, however late the browser sends it.\n */\nexport type Press = { x: number; y: number; tapOpens: boolean; lifted?: true } | undefined\n\nexport type PressEvent =\n /**\n * `touch`: a finger rather than a mouse or pen. `onControl`: on a link or button of the message, which keeps its own\n * press. `typing`: a text box had the focus, so the on-screen keyboard is up.\n */\n | { type: 'down'; x: number; y: number; touch: boolean; onControl: boolean; typing: boolean }\n | { type: 'move'; x: number; y: number }\n /** The finger lifted. */\n | { type: 'up' }\n /** The browser took the touch over, such as to scroll. */\n | { type: 'cancel' }\n /** The finger stayed down for `longPressMs`. */\n | { type: 'held' }\n /** The browser's click after the finger lifted. */\n | { type: 'tap' }\n\n/**\n * The next state of a press on a message, and whether it opens the message's actions: a finger that comes down on the\n * message, off its links and buttons, and lifts or rests there without drifting away; a tap while the reader types\n * only lowers the keyboard. A mouse keeps the hover bar.\n */\nexport const nextPress = (press: Press, event: PressEvent): { press: Press; open: boolean } => {\n if (event.type === 'down') {\n return { press: event.touch && !event.onControl ? { x: event.x, y: event.y, tapOpens: !event.typing } : undefined, open: false }\n }\n if (event.type === 'cancel') return { press: undefined, open: false }\n if (event.type === 'up') return { press: press && { ...press, lifted: true }, open: false }\n if (event.type === 'move') {\n if (!press) return { press, open: false }\n const drifted = Math.hypot(event.x - press.x, event.y - press.y) > pressSlop\n return { press: drifted ? undefined : press, open: false }\n }\n if (event.type === 'tap') return { press: undefined, open: press?.tapOpens === true }\n if (press?.lifted) return { press, open: false }\n return { press: undefined, open: press !== undefined }\n}\n","import { useEffect, useRef, type MouseEvent, type PointerEvent } from 'react'\nimport { longPressMs, nextPress, type Press, type PressEvent } from './message-press'\n\n/** A message's own links and buttons, such as a mention, a file, a reaction or its thread's replies. */\nconst controls = 'a[href], button, input, textarea, select, [role=\"button\"]'\n\n/** A box the reader types in, which has the on-screen keyboard up while it has the focus. */\nconst textBoxes = 'input, textarea, [contenteditable]:not([contenteditable=\"false\"])'\n\n/**\n * Swallows the click a browser may send when the finger of a long-press lifts, which would land on what the long-press\n * opened, such as the backdrop of its sheet, and close it again. A new press or key comes before any later click, so\n * it stops there.\n */\nconst swallowReleaseClick = () => {\n const swallow = (event: Event) => {\n event.preventDefault()\n event.stopPropagation()\n stop()\n }\n const stop = () => {\n window.removeEventListener('click', swallow, true)\n window.removeEventListener('pointerdown', stop, true)\n window.removeEventListener('keydown', stop, true)\n }\n window.addEventListener('click', swallow, true)\n window.addEventListener('pointerdown', stop, true)\n window.addEventListener('keydown', stop, true)\n}\n\n/**\n * The handlers that open a message's actions with a finger: a tap, or a long-press, which opens them while the finger\n * still rests, as `nextPress` decides; a tap while the reader types lowers the keyboard instead. The browser's own\n * long-press menu stays shut on a message pressed this way.\n */\nexport const useMessagePress = (onOpen: () => void) => {\n const press = useRef<Press>(undefined)\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n /** Whether the latest press was a finger's that may open the actions, which the browser's long-press menu leaves alone. */\n const pressing = useRef(false)\n const step = (event: PressEvent) => {\n const next = nextPress(press.current, event)\n press.current = next.press\n if (!next.press) clearTimeout(timer.current)\n return next.open\n }\n useEffect(() => () => clearTimeout(timer.current), [])\n\n return {\n onPointerDown: (event: PointerEvent) => {\n clearTimeout(timer.current)\n const onControl = event.target instanceof Element && event.target.closest(controls) !== null\n const typing = document.activeElement instanceof Element && document.activeElement.matches(textBoxes)\n step({ type: 'down', x: event.clientX, y: event.clientY, touch: event.pointerType === 'touch', onControl, typing })\n pressing.current = press.current !== undefined\n if (!press.current) return\n timer.current = setTimeout(() => {\n if (!step({ type: 'held' })) return\n // A short tick where the device can, as a native long-press gives.\n navigator.vibrate?.(10)\n swallowReleaseClick()\n onOpen()\n }, longPressMs)\n },\n onPointerMove: (event: PointerEvent) => step({ type: 'move', x: event.clientX, y: event.clientY }),\n // A lifted finger is no long-press, even when the browser sends the tap's click later than `longPressMs`\n onPointerUp: () => {\n clearTimeout(timer.current)\n step({ type: 'up' })\n },\n onPointerCancel: () => step({ type: 'cancel' }),\n onClick: () => {\n const lowersKeyboard = press.current?.tapOpens === false\n if (step({ type: 'tap' })) onOpen()\n if (lowersKeyboard && document.activeElement instanceof HTMLElement) document.activeElement.blur()\n },\n onContextMenu: (event: MouseEvent) => {\n if (pressing.current) event.preventDefault()\n },\n }\n}\n","import { useState } from 'react'\nimport { ChatMessage, type ChatAuthor } from '../../chat'\nimport { formatDateTime } from '../../format/date'\nimport { cn } from '../../lib/cn'\nimport { MentionedText } from '../../mentions'\nimport { buttonClass } from '../../primitives/button'\nimport { DeleteMessageDialog } from './delete-message-dialog'\nimport { MessageActionsBar } from './message-actions-bar'\nimport { MessageActionsSheet } from './message-actions-sheet'\nimport { MessageAttachments } from './message-attachments'\nimport { MessageEditor } from './message-editor'\nimport type { MessageSetup } from './message-setup'\nimport { ReactionChips } from './reaction-chips'\nimport { ThreadSummary } from './thread-summary'\nimport { useMessageControls } from './use-message-controls'\nimport { useMessagePress } from './use-message-press'\nimport { text } from './messages'\n\ntype Props = {\n setup: MessageSetup\n row: Record<string, unknown>\n /** The message's key, as text. */\n messageKey: string\n author: ChatAuthor\n time: string | undefined\n continued: boolean\n}\n\nconst idsOf = (value: unknown) => (Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [])\n\n/**\n * One message under its author, named after the organization's member with their id when there is one: its text with\n * the people it mentions picked out as `MentionedText` does, or a box to change it while its author edits it; its files;\n * in the conversation itself its thread's replies; and a footer of \"(edited)\" once changed and its reactions. What the reader\n * can do to it shows in a bar while they point at it, or, by touch, in a sheet a tap or long-press opens, which also\n * copies its text; a button only a keyboard or screen reader reaches opens that sheet on a touch screen too.\n */\nexport const ConversationMessage = ({ setup, row, messageKey, author, time, continued }: Props) => {\n const { page, me, member } = setup\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n const [acting, setActing] = useState(false)\n const press = useMessagePress(() => setActing(true))\n const body = row[page.text] == null ? '' : String(row[page.text])\n const mine = me !== undefined && author.id === me\n const name = member(author.id)?.name ?? author.name\n const files = setup.attachmentsOf(messageKey)\n const mentionIds = page.mentions === undefined ? [] : idsOf(row[page.mentions])\n const controls = useMessageControls(setup, { row, key: messageKey, mine, body, onEdit: () => setEditing(true), onDelete: () => setDeleting(true) })\n const edited = page.edited === undefined ? undefined : row[page.edited]\n const replies = page.thread && setup.threadTo ? Number(row[page.thread.count] ?? 0) : 0\n const last = page.thread && typeof row[page.thread.last] === 'string' ? (row[page.thread.last] as string) : undefined\n const chips = controls.groups.length > 0 && <ReactionChips groups={controls.groups} member={member} onReact={controls.onReact} onUnreact={controls.onUnreact} />\n const footer = (typeof edited === 'string' || chips) && (\n <span className=\"flex flex-wrap items-center gap-1\">\n {typeof edited === 'string' && <span title={text('editedAt', { time: formatDateTime(Date.parse(edited)) })}>{text('edited')}</span>}\n {chips}\n </span>\n )\n const title = mine ? text('yourMessage') : name ? text('messageFrom', { name }) : text('message')\n const showLabel = mine ? text('showYourActions') : name ? text('showActionsFrom', { name }) : text('showActions')\n return (\n <>\n <div\n data-message={messageKey}\n className={cn('group relative rounded-md [@media(hover:none)]:select-none [@media(hover:none)]:[-webkit-touch-callout:none] [&_a]:[-webkit-touch-callout:default]', acting && 'bg-muted')}\n {...(!editing && press)}\n >\n {!editing && <MessageActionsBar controls={controls} />}\n {!editing && (\n // On a touch screen, the way in for a screen reader or a keyboard, out of sight until it has the focus\n <button\n type=\"button\"\n className={cn(buttonClass({ variant: 'secondary', size: 'sm' }), 'sr-only focus-visible:not-sr-only focus-visible:absolute focus-visible:right-0 focus-visible:top-0 focus-visible:z-10 [@media(hover:hover)]:hidden')}\n onClick={() => setActing(true)}\n >\n {showLabel}\n </button>\n )}\n <ChatMessage author={{ id: author.id, name }} time={time} continued={continued} footer={footer}>\n {editing ? (\n <MessageEditor\n body={body}\n picked={mentionIds.flatMap((id) => (member(id) ? [{ id, name: member(id)!.name }] : []))}\n searchPeople={setup.searchPeople}\n onSave={(changed, mentions) => setup.writes.edit(messageKey, changed, mentions)}\n onCancel={() => setEditing(false)}\n />\n ) : (\n body !== '' && <MentionedText text={body} mentions={mentionIds.map((id) => ({ name: member(id)?.name }))} />\n )}\n {files.length > 0 && <MessageAttachments attachments={files} />}\n {replies > 0 && controls.thread && <ThreadSummary count={replies} last={last} to={controls.thread} />}\n </ChatMessage>\n </div>\n {deleting && (\n <DeleteMessageDialog\n onClose={() => setDeleting(false)}\n onDelete={() => {\n setDeleting(false)\n void setup.writes.remove(messageKey, files)\n }}\n />\n )}\n {acting && !editing && <MessageActionsSheet controls={controls} title={title} preview={body} onClose={() => setActing(false)} />}\n </>\n )\n}\n","import { threadSort } from '@protobase/layout'\nimport type { Client } from '@protobase/client'\nimport { createWhere, printFilter, type ConversationPageModel, type ReadPositionModel } from '@protobase/schema'\n\nconst where = createWhere()\n\n/** How many messages a page of the conversation brings: the latest on opening, and each \"Load earlier\". */\nexport const conversationPageSize = 50\n\n/** How many records one read of a page of messages' reactions or files brings; a page with more reads on until it has them all. */\nexport const recordsPageSize = 500\n\n/**\n * The read of a conversation's messages through the list API, with the reader's own access, so a message they may not\n * read never shows: those whose relation holds the record's key, newest first, a page at a time. With threads, only\n * the messages of the conversation itself, not the replies in a thread.\n */\nexport const messagesRequest = (page: Pick<ConversationPageModel, 'field' | 'time' | 'thread'>, recordKey: string) => ({\n filter: printFilter(page.thread ? where.and(where.eq(page.field, recordKey), where.isNull(page.thread.field)) : where.eq(page.field, recordKey)),\n orderBy: threadSort(page.time),\n pageSize: conversationPageSize,\n})\n\n/** The read of the replies in the thread of the message keyed `first`, newest first, a page at a time. */\nexport const repliesRequest = (page: Pick<ConversationPageModel, 'time'>, thread: NonNullable<ConversationPageModel['thread']>, first: string) => ({\n filter: printFilter(where.eq(thread.field, first)),\n orderBy: threadSort(page.time),\n pageSize: conversationPageSize,\n})\n\n/** The records of a resource of the messages' own, such as their reactions or files, by its relation `field` to them. */\ntype OfMessages = { resource: string; field: string }\n\n/** The filter of the records, such as reactions, of the messages keyed `messages`. */\nexport const ofMessagesFilter = (of: Pick<OfMessages, 'field'>, messages: readonly string[]) => printFilter(where.in(of.field, [...messages]))\n\n/** Every record, such as a reaction, of the messages keyed `messages`, in one read, or one per `recordsPageSize` of them. */\nexport const readOfMessages = async (client: Pick<Client, 'list'>, of: OfMessages, messages: readonly string[]) => {\n const filter = ofMessagesFilter(of, messages)\n const rows: Record<string, unknown>[] = []\n let pageToken = ''\n do {\n const page = await client.list(of.resource, { filter, pageSize: recordsPageSize, pageToken })\n rows.push(...page.items)\n pageToken = page.nextPageToken\n } while (pageToken)\n return rows\n}\n\n/**\n * The read of the reader's own read position in a record, through the list API: the one whose relation holds the\n * record's key and whose author, `author`, is `me`, even where the resource lets them read other people's.\n */\nexport const ownPositionFilter = (position: Pick<ReadPositionModel, 'field'>, recordKey: string, author: string, me: string) =>\n printFilter(where.and(where.eq(position.field, recordKey), where.eq(author, me)))\n","import type { ChatAuthor } from '../../chat'\nimport { chatDayLabel, sameChatDay } from '../../chat/chat-day'\nimport { authorOf } from '../conversation/thread-items'\n\ntype Row = Record<string, unknown>\n\n/** How long after a message the same author's next one still joins it, so a quick run of messages reads as one. */\nexport const groupWindowMs = 5 * 60_000\n\nexport type MessageFields = { key: (row: Row) => string; sender: string; time: string }\n\n/**\n * One line of a conversation: a day's divider, the \"New messages\" line, or a message under its author, `continued`\n * when it follows the same author's message of a moment ago, so it leaves out their avatar, name and time.\n */\nexport type ConversationRow =\n | { kind: 'day'; key: string; label: string }\n | { kind: 'new'; key: string }\n | { kind: 'message'; key: string; row: Row; author: ChatAuthor; time: string | undefined; continued: boolean }\n\nconst timeOf = (row: Row, time: string) => (typeof row[time] === 'string' ? (row[time] as string) : undefined)\n\n/**\n * The messages, oldest first, as the conversation's lines: a day divider above each day's first message, the \"New\n * messages\" line above the message keyed `newLineAbove`, and each message grouped with the one before it when the same\n * author sent both within `groupWindowMs` on the same day, with no line between.\n */\nexport const conversationRows = (oldestFirst: Row[], { key, sender, time }: MessageFields, newLineAbove?: string, now = Date.now()): ConversationRow[] =>\n oldestFirst.flatMap((row, index): ConversationRow[] => {\n const previous = oldestFirst[index - 1]\n const sent = timeOf(row, time)\n const before = previous && timeOf(previous, time)\n const newDay = sent !== undefined && (before === undefined || !sameChatDay(before, sent))\n const isNew = key(row) === newLineAbove\n const soon = sent !== undefined && before !== undefined && Date.parse(sent) - Date.parse(before) < groupWindowMs\n const author = authorOf(row[sender])\n const continued = !newDay && !isNew && soon && authorOf(previous![sender]).id === author.id\n return [\n ...(newDay ? [{ kind: 'day' as const, key: `day:${key(row)}`, label: chatDayLabel(sent, now) }] : []),\n ...(isNew ? [{ kind: 'new' as const, key: `new:${key(row)}` }] : []),\n { kind: 'message', key: key(row), row, author, time: sent, continued },\n ]\n })\n\nconst keysOf = (rows: Row[], key: (row: Row) => string) => rows.map((row) => Number(key(row)))\n\n/**\n * The key of the message the \"New messages\" line goes above: the first after `lastRead`, the key of the newest message\n * the reader read, by someone other than `me`; none when none is unread. When earlier messages are not loaded and the\n * lowest loaded key is past `lastRead`, the first unread one may be among those, so there is no line rather than one in\n * the wrong place.\n */\nexport const firstUnreadKey = (oldestFirst: Row[], { key, sender }: Omit<MessageFields, 'time'>, lastRead: number, me: string, hasEarlier: boolean) => {\n if (hasEarlier && Math.min(...keysOf(oldestFirst, key)) > lastRead) return\n const found = oldestFirst.find((row) => Number(key(row)) > lastRead && authorOf(row[sender]).id !== me)\n return found && key(found)\n}\n\n/** The highest key among the messages, the one reading them all reads to, whatever order their times put them in. */\nexport const highestKey = (rows: Row[], key: (row: Row) => string) => (rows.length === 0 ? undefined : Math.max(...keysOf(rows, key)))\n","import { useQueries } from '@tanstack/react-query'\nimport type { AttachmentsModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { attachmentsByMessage, type Attachment } from './attachments'\nimport { ofMessagesFilter, readOfMessages } from './conversation-reads'\n\n/**\n * The files of the messages shown, read with the reader's own access in one batch per page of messages, never one read\n * per message, and read again when the files' resource changes, as a sent or deleted message's do: `byMessage` holds\n * each message's files by its key. Without attachments, nothing is read.\n */\nexport const useMessageAttachments = (attachments: AttachmentsModel | undefined, pages: readonly (readonly string[])[]) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const results = useQueries({\n queries: (attachments ? pages.filter((page) => page.length > 0) : []).map((page) => ({\n queryKey: keys.attachmentsOf(attachments!.resource, ofMessagesFilter(attachments!, page)),\n queryFn: () => readOfMessages(client, attachments!, page),\n })),\n })\n const model = attachments && resources[attachments.resource]\n const rows = results.flatMap((result) => result.data ?? [])\n return { byMessage: attachments && model ? attachmentsByMessage(rows, model, attachments) : new Map<string, Attachment[]>(), error: results.find((result) => result.error)?.error ?? undefined }\n}\n","import { useQueries } from '@tanstack/react-query'\nimport type { ReactionsModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { ofMessagesFilter, readOfMessages } from './conversation-reads'\nimport { reactionsByMessage } from './reactions'\n\n/**\n * The reactions to the messages shown, read in one batch per page of messages, never one read per message, and read\n * again as they change: `byMessage` holds each message's reaction rows by its key. Without reactions, nothing is read.\n */\nexport const useMessageReactions = (reactions: ReactionsModel | undefined, pages: readonly (readonly string[])[]) => {\n const client = useClient()\n const results = useQueries({\n queries: (reactions ? pages.filter((page) => page.length > 0) : []).map((page) => ({\n queryKey: keys.reactionsOf(reactions!.resource, ofMessagesFilter(reactions!, page)),\n queryFn: () => readOfMessages(client, reactions!, page),\n })),\n })\n const rows = results.flatMap((result) => result.data ?? [])\n return { byMessage: reactionsByMessage(rows, reactions?.field ?? ''), error: results.find((result) => result.error)?.error ?? undefined }\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport type { Attachment } from './attachments'\nimport { deleteOps } from './message-ops'\nimport { useClient } from '../../data/api-provider'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { useToast } from '../../toasts/toast-provider'\nimport { keyValue } from '../create/create-values'\nimport { refusalReason } from '../displays/board-columns'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { text } from './messages'\n\n/**\n * The writes a reader makes to a conversation's messages, each resolving whether the server took it: edit a message's\n * text and mentions, delete one after its files, and react to one or take a reaction back. A refused write changes nothing on screen\n * and shows the server's reason in a toast; a taken one reads the resource again.\n */\nexport const useMessageWrites = (page: ConversationPageModel) => {\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const { resources } = useAdminMeta()\n const model = resources[page.resource]!\n const reactions = page.reactions\n\n const run = (resource: string, failed: string, write: () => Promise<unknown>) =>\n write().then(\n () => {\n void refresh(resource)\n return true\n },\n (error: unknown) => {\n toast.show({ state: 'error', title: failed, description: refusalReason(error) })\n return false\n },\n )\n\n const edit = (key: string, body: string, mentions: string[]) =>\n run(page.resource, text('notSaved'), () => client.update(page.resource, key, { [page.text]: body, ...(page.mentions !== undefined && { [page.mentions]: mentions }) }, '*'))\n // Its files first, in the same batch: a message's files never outlive it\n const remove = (key: string, files: readonly Attachment[]) =>\n run(page.resource, text('notDeleted'), () => (page.attachments && files.length > 0 ? client.batchWrite(deleteOps(page, model, key, files)) : client.remove(page.resource, key)))\n const react = reactions && ((key: string, emoji: string) => run(reactions.resource, text('reactionNotSaved'), () => client.create(reactions.resource, { [reactions.field]: keyValue(model, key), [reactions.emoji]: emoji })))\n const unreact = reactions && ((row: Record<string, unknown>) => run(reactions.resource, text('reactionNotSaved'), () => client.remove(reactions.resource, keyOf(resources[reactions.resource]!, row))))\n return { edit, remove, react, unreact }\n}\n","import type { AppAddress, ConversationPageModel } from '@protobase/schema'\nimport type { PeopleSearch } from '../../mentions'\nimport { useMembers } from '../../people/use-members'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport type { MessageSetup } from './message-setup'\nimport { emojiSet } from './reactions'\nimport { useMessageAttachments } from './use-message-attachments'\nimport { useMessageReactions } from './use-message-reactions'\nimport { useMessageWrites } from './use-message-writes'\n\ntype Input = {\n page: ConversationPageModel\n me: string | undefined\n /** The keys of the messages shown, a list per page they were read in, whose reactions and files are read a page at a time. */\n pages: readonly (readonly string[])[]\n threadTo?: (key: string) => AppAddress\n searchPeople?: PeopleSearch\n}\n\n/** The `MessageSetup` of the messages shown, with their reactions and files read, and the errors of those reads, if any. */\nexport const useMessageSetup = ({ page, me, pages, threadTo, searchPeople }: Input) => {\n const { resources } = useAdminMeta()\n const { member } = useMembers()\n const writes = useMessageWrites(page)\n const messagePermissions = usePermissions(page.resource)\n const reactionPermissions = usePermissions(page.reactions?.resource ?? page.resource)\n const reactions = useMessageReactions(page.reactions, pages)\n const files = useMessageAttachments(page.attachments, pages)\n const values = page.reactions ? (resources[page.reactions.resource]?.fields[page.reactions.emoji]?.enumValues ?? []) : []\n const setup: MessageSetup = {\n page,\n me,\n member,\n writes,\n emoji: page.reactions ? emojiSet(page.reactions, values) : [],\n messagePermissions,\n reactionPermissions,\n reactionsOf: (key) => reactions.byMessage.get(key) ?? [],\n attachmentsOf: (key) => files.byMessage.get(key) ?? [],\n threadTo,\n searchPeople,\n }\n return { setup, reactionsError: reactions.error, attachmentsError: files.error }\n}\n","import { useState } from 'react'\n\n/**\n * The key of the message the \"New messages\" line goes above, or undefined for none: decided once by `decide`, when the\n * first messages and the read position at opening are both there, and kept while the page is open, so the line neither\n * moves nor appears under a reader following new messages as they come.\n */\nexport const useNewLine = (decidable: boolean, decide: () => string | undefined) => {\n const [line, setLine] = useState<{ above: string | undefined }>()\n if (!line && decidable) {\n const decided = { above: decide() }\n setLine(decided)\n return decided.above\n }\n return line?.above\n}\n","import type { AppAddress, ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { ChatDivider, ChatThread } from '../../chat'\nimport { useList } from '../../data/use-list'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport type { PeopleSearch } from '../../mentions'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { retryOf, showsErrorAbove, threadState } from '../conversation/thread-state'\nimport { ConversationMessage } from './conversation-message'\nimport { messagesRequest } from './conversation-reads'\nimport { conversationRows, firstUnreadKey, highestKey } from './conversation-rows'\nimport { useMessageSetup } from './use-message-setup'\nimport { useNewLine } from './use-new-line'\nimport { text } from './messages'\n\ntype Props = {\n page: ConversationPageModel\n model: ResourceModel\n recordKey: string\n me: string | undefined\n /** The reader's read position, as `useReadPosition` gives it. */\n position: { ready: boolean; openedAt: number | undefined; readTo: ((key: number) => void) | undefined }\n /** The address that opens a message's thread, for a conversation with threads. */\n threadTo?: (key: string) => AppAddress\n /** Finds the people `@` lists while editing a message. */\n searchPeople?: PeopleSearch\n}\n\n/**\n * The record's messages, the latest page with earlier ones on request, read with the reader's own access and their\n * senders' names in the same read, kept current as the live updates tell of new, changed and deleted ones. They show\n * once the read position is there too, so they open on the \"New messages\" line, and reading to the end moves it. They\n * scroll in a box of their own, so the box that sends one stays in view. Their reactions and files are read a page at a\n * time.\n */\nexport const ConversationMessages = ({ page, model, recordKey, me, position, threadTo, searchPeople }: Props) => {\n const { resources, views } = useAdminMeta()\n const senders = [page.sender]\n const list = useList(model.name, { ...messagesRequest(page, recordKey), labels: listLabels(resources, views, model, senders) })\n const oldestFirst = withLabels(resources, model, senders, list.items, list.labels).reverse()\n const key = (row: Record<string, unknown>) => String(keyOf(model, row))\n const { setup, reactionsError, attachmentsError } = useMessageSetup({ page, me, pages: (list.data?.pages ?? []).map((read) => read.items.map(key)), threadTo, searchPeople })\n const state = threadState(list)\n const loaded = state === 'messages' && !list.isLoading && position.ready\n const newLineAbove = useNewLine(loaded && oldestFirst.length > 0 && position.openedAt !== undefined && me !== undefined, () =>\n firstUnreadKey(oldestFirst, { key, sender: page.sender }, position.openedAt!, me!, list.hasNextPage),\n )\n if (state === 'error') return <div className=\"flex-1 p-4\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>\n // The live region mounts with the messages it opens on, so a screen reader announces only those that arrive later\n if (!loaded) return <div className=\"flex-1 p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n const rows = conversationRows(oldestFirst, { key, sender: page.sender, time: page.time }, newLineAbove)\n const readEnd = highestKey(oldestFirst, key)\n // The reader's own newest message: when one arrives, the thread goes to the end wherever they were\n const own = rows.findLast((line) => line.kind === 'message' && me !== undefined && line.author.id === me)\n const readTo = position.readTo\n return (\n <>\n {showsErrorAbove(list) && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>}\n {reactionsError !== undefined && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadReactions')} error={reactionsError} /></div>}\n {attachmentsError !== undefined && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadFiles')} error={attachmentsError} /></div>}\n <ChatThread\n length={oldestFirst.length}\n followKey={own?.key}\n empty={page.empty ?? text('noMessages')}\n onLoadEarlier={list.hasNextPage ? () => void list.fetchNextPage() : undefined}\n loadingEarlier={list.isFetchingNextPage}\n onReadToEnd={readTo && readEnd !== undefined ? () => readTo(readEnd) : undefined}\n >\n {rows.map((line) =>\n line.kind === 'day' ? (\n <ChatDivider key={line.key} label={line.label} />\n ) : line.kind === 'new' ? (\n <ChatDivider key={line.key} tone=\"new\" />\n ) : (\n <ConversationMessage key={line.key} setup={setup} row={line.row} messageKey={line.key} author={line.author} time={line.time} continued={line.continued} />\n ),\n )}\n </ChatThread>\n </>\n )\n}\n","import type { PickedUser } from '../../mentions'\n\n/** The most people `@` lists at once; typing more of a name narrows them. */\nexport const mentionListSize = 8\n\n/**\n * The organization's members whose name holds `query`, ignoring case, other than `me`, in the members' order, at most\n * `mentionListSize`: the people the composer's `@` lists.\n */\nexport const matchingMembers = (members: readonly PickedUser[], query: string, me: string | undefined): PickedUser[] => {\n const wanted = query.toLocaleLowerCase()\n return members\n .filter((person) => person.id !== me && person.name.toLocaleLowerCase().includes(wanted))\n .slice(0, mentionListSize)\n .map(({ id, name }) => ({ id, name }))\n}\n","/** Whether the thread's first message, `row`, is one of the conversation of the record keyed `recordKey`. */\nexport const inConversation = (row: Record<string, unknown>, field: string, recordKey: string) => row[field] != null && String(row[field]) === recordKey\n","import type { ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { useRecord } from '../../data/use-record'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { keyValue } from '../create/create-values'\nimport { useAdminMeta } from '../meta-gate'\nimport { usePickedLabels } from '../use-picked-labels'\nimport { inConversation } from './thread-head'\n\n/**\n * A thread's first message, keyed `first`, with its sender named as the replies' are: `row` once read and in the\n * conversation of the record keyed `recordKey`, and `elsewhere` when it is another conversation's, such as from an\n * address of another one.\n */\nexport const useThreadHead = (page: ConversationPageModel, model: ResourceModel, recordKey: string, first: string) => {\n const { resources, views } = useAdminMeta()\n const head = useRecord(page.resource, keyValue(model, first))\n const read = head.data?.record\n const senders = [page.sender]\n const sender = model.fields[page.sender]\n const named = page.sender in listLabels(resources, views, model, senders) && sender?.relation ? resources[sender.relation.resource] : undefined\n const ids = named && read?.[page.sender] != null ? [String(read[page.sender])] : []\n const labels = usePickedLabels(named ?? model, named && views[named.name], ids)\n const elsewhere = read !== undefined && !inConversation(read, page.field, recordKey)\n const [row] = read && !elsewhere ? withLabels(resources, model, senders, [read], { [page.sender]: Object.fromEntries(labels) }) : []\n return { row, elsewhere, error: head.error }\n}\n","import type { ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { ChatDivider, ChatThread } from '../../chat'\nimport { useList } from '../../data/use-list'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport type { PeopleSearch } from '../../mentions'\nimport { SidePanel } from '../../side-panel'\nimport { authorOf } from '../conversation/thread-items'\nimport { MessageComposer } from '../conversation/message-composer'\nimport { keyValue } from '../create/create-values'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { ConversationMessage } from './conversation-message'\nimport { repliesRequest } from './conversation-reads'\nimport { conversationRows } from './conversation-rows'\nimport { useMessageSetup } from './use-message-setup'\nimport { useThreadHead } from './use-thread-head'\nimport { text } from './messages'\n\ntype Props = {\n page: ConversationPageModel & { thread: NonNullable<ConversationPageModel['thread']> }\n /** The record the conversation is of, and its key. */\n owner: ResourceModel\n recordKey: string\n /** The key of the thread's first message. */\n first: string\n me: string | undefined\n searchPeople?: PeopleSearch\n onClose: () => void\n}\n\n/**\n * A thread beside its conversation, covering the screen at mobile width: its first message, its replies kept current\n * as the live updates tell of changes, and a box of its own that replies in it. The reader reacts to, edits and deletes\n * its messages as in the conversation. A first message of another conversation shows as not found, with no box, so no\n * reply joins a thread of another conversation from here. Key it by the first message, so another thread starts afresh.\n */\nexport const ThreadPanel = ({ page, owner, recordKey, first, me, searchPeople, onClose }: Props) => {\n const { resources, views } = useAdminMeta()\n const model = resources[page.resource]!\n const senders = [page.sender]\n const head = useThreadHead(page, model, recordKey, first)\n const list = useList(page.resource, { ...repliesRequest(page, page.thread, first), labels: listLabels(resources, views, model, senders) })\n const oldestFirst = withLabels(resources, model, senders, list.items, list.labels).reverse()\n const key = (row: Record<string, unknown>) => String(keyOf(model, row))\n const { setup, reactionsError, attachmentsError } = useMessageSetup({ page, me, pages: [[first], ...(list.data?.pages ?? []).map((read) => read.items.map(key))], searchPeople })\n const headRow = head.row\n const error = head.error ?? list.error ?? reactionsError ?? attachmentsError\n const rows = conversationRows(oldestFirst, { key, sender: page.sender, time: page.time })\n const own = rows.findLast((line) => line.kind === 'message' && me !== undefined && line.author.id === me)\n const replies = headRow ? Number(headRow[page.thread.count] ?? 0) : 0\n return (\n <SidePanel\n title={text('thread')}\n onClose={onClose}\n footer={\n !head.elsewhere && <MessageComposer\n resource={page.resource}\n field={page.text}\n values={{ [page.field]: keyValue(owner, recordKey), [page.thread.field]: keyValue(model, first) }}\n placeholder={text('replyPlaceholder')}\n searchPeople={searchPeople}\n mentions={page.mentions}\n attachments={page.attachments}\n />\n }\n >\n {error && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadThread')} error={error} /></div>}\n {head.elsewhere ? (\n <div className=\"flex-1 p-4\"><Quiet>{text('threadElsewhere')}</Quiet></div>\n ) : !headRow || list.isLoading ? (\n <div className=\"flex-1 p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n ) : (\n <ChatThread length={oldestFirst.length + 1} followKey={own?.key} onLoadEarlier={list.hasNextPage ? () => void list.fetchNextPage() : undefined} loadingEarlier={list.isFetchingNextPage}>\n <ConversationMessage setup={setup} row={headRow} messageKey={first} author={authorOf(headRow[page.sender])} time={typeof headRow[page.time] === 'string' ? (headRow[page.time] as string) : undefined} continued={false} />\n {replies > 0 && <ChatDivider label={text('replies', { count: replies })} />}\n {rows.map((line) =>\n line.kind === 'day' ? (\n <ChatDivider key={line.key} label={line.label} />\n ) : line.kind === 'new' ? null : (\n <ConversationMessage key={line.key} setup={setup} row={line.row} messageKey={line.key} author={line.author} time={line.time} continued={line.continued} />\n ),\n )}\n </ChatThread>\n )}\n </SidePanel>\n )\n}\n","import { isApiError } from '@protobase/client'\n\n/** The reader's stored position: its record's key, the key of the message they read to, and the version it was read at. */\nexport type SavedPosition = { key: string; lastRead: number; etag: string }\n\n/** How the position is read and written: `update` writes only over the version `at` holds, else rejects with a 412. */\nexport type PositionStore = {\n find: () => Promise<SavedPosition | undefined>\n create: (lastRead: number) => Promise<SavedPosition>\n update: (at: SavedPosition, lastRead: number) => Promise<SavedPosition>\n}\n\n// After another tab's write, the position it stored, which this one compares against once\nconst stored = async (store: PositionStore, failed: unknown) => {\n const found = await store.find()\n if (!found) throw failed\n return found\n}\n\nconst raise = (store: PositionStore, at: SavedPosition, lastRead: number) => (at.lastRead >= lastRead ? at : store.update(at, lastRead))\n\n/**\n * Moves the reader's position up to `lastRead` from `saved`, what this tab last stored, and answers what is stored\n * after. It never moves down: each write goes over the version it compared against, so when another tab wrote since,\n * the write is refused, and the position that tab stored is compared again and kept when it is as far or further. A\n * create another tab beat to it, refused as taken, goes the same way.\n */\nexport const moveReadPosition = async (store: PositionStore, saved: SavedPosition | undefined, lastRead: number): Promise<SavedPosition> => {\n if (saved && saved.lastRead >= lastRead) return saved\n const write = saved ? store.update(saved, lastRead) : store.create(lastRead)\n const status = saved ? 412 : 409\n return write.catch(async (failed: unknown) => {\n if (!isApiError(failed) || failed.status !== status) throw failed\n return raise(store, await stored(store, failed), lastRead)\n })\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReadPositionModel, ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { keyValue } from '../create/create-values'\nimport { ownPositionFilter } from './conversation-reads'\nimport { moveReadPosition, type PositionStore, type SavedPosition } from './read-position-write'\n\ntype Props = {\n /** The page's read position, none for a conversation that keeps none. */\n position: ReadPositionModel | undefined\n /** The read position resource, as the reader's `/meta` describes it. */\n model: ResourceModel | undefined\n /** The record the conversation is of. */\n owner: ResourceModel\n recordKey: string\n me: string | undefined\n}\n\n/**\n * The reader's read position in a record's conversation. `openedAt` is the key of the newest message they had read when\n * they opened it, 0 for none, and undefined while it loads or without a read position: it stays put while the page is\n * open, so the \"New messages\" line does not move as they read. `readTo` moves the position to a message they read; it\n * never moves back, not even over a further move another tab stored, a move to where it is writes nothing, and moves go\n * one after another. Without a read position, `ready` holds at once and there is no `readTo`, so nothing is read or\n * written; one that could not be read is ready too.\n */\nexport const useReadPosition = ({ position, model, owner, recordKey, me }: Props) => {\n const client = useClient()\n const author = model?.author\n const kept = position !== undefined && author !== undefined && me !== undefined\n const [openedAt, setOpenedAt] = useState<number>()\n const [error, setError] = useState<unknown>()\n const saved = useRef<SavedPosition>(undefined)\n const writing = useRef<Promise<void>>(Promise.resolve())\n\n const find = useCallback(async (): Promise<SavedPosition | undefined> => {\n if (!kept) return\n const { items } = await client.list(position.resource, { filter: ownPositionFilter(position, recordKey, author, me), pageSize: 1 })\n const [found] = items\n if (!found) return\n return { key: String(keyOf(model!, found)), lastRead: Number(found[position.message] ?? 0), etag: String(found.etag) }\n }, [client, kept, position, model, recordKey, author, me])\n\n useEffect(() => {\n if (!kept) return\n find().then((found) => {\n saved.current = found\n setOpenedAt(found?.lastRead ?? 0)\n }, setError)\n }, [kept, find])\n\n // Each write goes over the version of the position it was read at, so it never lands over another tab's further move\n const store = useMemo((): PositionStore => ({\n find,\n create: async (lastRead) => {\n const made = await client.create(position!.resource, { [position!.field]: keyValue(owner, recordKey), [position!.message]: lastRead })\n return { key: String(keyOf(model!, made.record)), lastRead, etag: made.etag }\n },\n update: async (at, lastRead) => {\n const { etag } = await client.update(position!.resource, at.key, { [position!.message]: lastRead }, at.etag)\n return { key: at.key, lastRead, etag }\n },\n }), [client, position, owner, recordKey, model, find])\n\n const readTo = useCallback(\n (lastRead: number) => {\n writing.current = writing.current\n .then(async () => {\n saved.current = await moveReadPosition(store, saved.current, lastRead)\n })\n .catch(setError)\n },\n [store],\n )\n\n // A position that could not be read leaves the line out rather than the messages\n return { ready: !kept || openedAt !== undefined || error !== undefined, openedAt: kept ? openedAt : undefined, readTo: kept && openedAt !== undefined ? readTo : undefined, error }\n}\n","import type { AppAddress } from '@protobase/schema'\nimport { useAppAddress } from '../use-app-address'\n\n/**\n * The thread a conversation page shows beside it, as its address holds it (`?thread=`): `open`, the key of the\n * thread's first message, none while no thread is open; `to`, the address that opens a message's thread, for a link;\n * and `close`, which goes back to the conversation alone. Both keep the record's call the page joins (`?call=join`).\n */\nexport const useThreadAddress = (resource: string, key: string) => {\n const { address, go } = useAppAddress()\n const here = address?.kind === 'record' && address.resource === resource && address.key === key ? address : undefined\n const call = here?.call && { call: here.call }\n const to = (message: string): AppAddress => ({ kind: 'record', resource, key, ...call, thread: message })\n const close = () => go({ kind: 'record', resource, key, ...call })\n return { open: here?.thread, to, close }\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { useOptionalAuth } from '../../auth/auth-provider'\nimport { useMembers } from '../../people/use-members'\nimport { keyValue } from '../create/create-values'\nimport { MessageComposer } from '../conversation/message-composer'\nimport { FullArea } from '../full-area-record'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRecordTitle } from '../titles/record-titles'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { ConversationCall } from './conversation-call'\nimport { ConversationHeader } from './conversation-header'\nimport { ConversationMessages } from './conversation-messages'\nimport { matchingMembers } from './member-search'\nimport { ThreadPanel } from './thread-panel'\nimport { useReadPosition } from './use-read-position'\nimport { useThreadAddress } from './use-thread-address'\nimport { text } from './messages'\nimport { useRelay } from '../../relay/relay-context'\nimport { TypingLine } from '../../relay/typing-line'\nimport { useTypingSender } from '../../relay/use-typing-sender'\nimport { useViewChannel } from '../../relay/use-view-channel'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord }\n\n/**\n * A record page that is the record's conversation (`.record({ conversation })`), filling the content area: its header,\n * its messages and the box that sends one, where `@` lists the organization's members. The page does not scroll; the\n * messages scroll in a box of their own, so the box stays in view. With `typing`, a line above the box says who else\n * types, over the app's realtime relay. With threads, the thread its address names (`?thread=`) opens in a panel beside\n * it. With `call`, the record's call shows while the page joins it (`?call=join`), between the header and the messages:\n * beside them, or above them at mobile width, with a thread's panel after both, covering the screen at mobile width. Key\n * it by the record, so another one starts afresh.\n */\nexport const ConversationPage = ({ page, scope }: Props) => {\n const { resources, views } = useAdminMeta()\n const title = useRecordTitle()(scope.model, views[scope.model.name], scope.record, scope.key)\n const auth = useOptionalAuth()\n const me = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const members = useMembers()\n const model = resources[page.resource]!\n const position = useReadPosition({ position: page.readPosition, model: page.readPosition && resources[page.readPosition.resource], owner: scope.model, recordKey: scope.key, me })\n const searchPeople = page.mentions === undefined ? undefined : async (query: string) => matchingMembers(members.data ?? [], query, me)\n const thread = useThreadAddress(scope.model.name, scope.key)\n const threaded = page.thread && { ...page, thread: page.thread }\n const channel = `${scope.model.name}/${scope.key}`\n const relay = useRelay()\n useViewChannel(channel)\n const typing = useTypingSender(channel)\n const typed = page.typing && relay ? typing : undefined\n return (\n <FullArea>\n <div className=\"flex min-h-0 min-w-0\">\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <ConversationHeader page={page} scope={scope} title={title} />\n <div className=\"flex min-h-0 min-w-0 flex-1 max-md:flex-col\">\n <ConversationCall page={page} scope={scope} />\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <ConversationMessages page={page} model={model} recordKey={scope.key} me={me} position={position} threadTo={threaded && thread.to} searchPeople={searchPeople} />\n {position.error !== undefined && <p className=\"shrink-0 px-4 text-sm text-danger-text\">{text('positionNotSaved')}</p>}\n {typed && <TypingLine channel={channel} />}\n <div className=\"shrink-0 px-3 pb-3\">\n <MessageComposer\n resource={page.resource}\n field={page.text}\n values={{ [page.field]: keyValue(scope.model, scope.key) }}\n placeholder={page.placeholder}\n searchPeople={searchPeople}\n mentions={page.mentions}\n attachments={page.attachments}\n onDraft={typed?.onText}\n onSent={(key) => {\n typed?.onSent()\n relay?.store.sent(key)\n }}\n />\n </div>\n </div>\n </div>\n </div>\n {threaded && thread.open !== undefined && <ThreadPanel key={thread.open} page={threaded} owner={scope.model} recordKey={scope.key} first={thread.open} me={me} searchPeople={searchPeople} onClose={thread.close} />}\n </div>\n </FullArea>\n )\n}\n","import { guarded } from '../lib/guarded'\n\n/** What a person had changed on a record but not saved: the field edits and the new order of its lines. */\nexport type RecordDraft = { etag: string; fields: Record<string, unknown>; order?: string[] }\n\nexport const draftStorageKey = (userId: string, resource: string, recordKey: string) => `protobase:draft:${userId}:${resource}:${recordKey}`\n\n/** The saved draft, only if it was made against the version of the record that is on screen now. */\nexport const readDraft = (storage: Pick<Storage, 'getItem'>, key: string, etag: string): RecordDraft | undefined =>\n guarded(() => {\n const raw = storage.getItem(key)\n if (raw === null) return undefined\n const parsed = JSON.parse(raw) as Partial<RecordDraft> | null\n if (!parsed || parsed.etag !== etag || typeof parsed.fields !== 'object' || parsed.fields === null) return undefined\n return { etag, fields: parsed.fields, ...(Array.isArray(parsed.order) && { order: parsed.order.map(String) }) }\n }, undefined)\n\nexport const writeDraft = (storage: Pick<Storage, 'setItem' | 'removeItem'>, key: string, draft: RecordDraft | undefined) =>\n guarded(() => (draft ? storage.setItem(key, JSON.stringify(draft)) : storage.removeItem(key)), undefined)\n","import { Zap, type LucideIcon } from 'lucide-react'\nimport { namedIcon } from './named-icon'\n\nexport const actionIcon = (name: string | undefined): LucideIcon => namedIcon(name) ?? Zap\n","import { Pencil, Trash2 } from 'lucide-react'\nimport { useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport { topBarButton, useTopBarSlot } from '../../app-shell'\nimport type { LiveRecord } from '../../data/use-record'\nimport type { ActionModel, AppAddress, ResourceModel } from '@protobase/schema'\nimport { ActionMenu, ActionRail, type RailAction } from '../../record-view'\nimport { RouteLink } from '../../primitives/route-link'\nimport { actionIcon } from '../action-icon'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { text } from '../record-messages'\nimport { actionLink } from './action-link'\nimport { ActionPrompt, asksFirst, isDanger } from './action-prompt'\nimport { useActionRunner } from './use-run-action'\n\ntype RecordActionsProps = { model: ResourceModel; stored: LiveRecord; recordKey: string; edit?: AppAddress; onDelete?: () => void }\n\n/**\n * The record page's actions, for a rail or a focus page's bar: Edit, a link to the form at `edit`, when the page offers\n * it; the view's named actions, run like the Action block runs them, a delete among them returning to the list, a\n * delete and a danger one in red; and the record's own Delete, `onDelete`, unless a named action deletes already.\n * `prompt` is what asks before an action runs, drawn wherever the actions are.\n */\nexport const useRecordActions = ({ model, stored, recordKey, edit, onDelete }: RecordActionsProps) => {\n const app = useAppAddress()\n const { go } = app\n const scope = { model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }\n const runner = useActionRunner(model.name, scope, (action) => action.run?.kind === 'delete' && go({ kind: 'list', resource: model.name }, { replace: true }))\n const [asking, setAsking] = useState<ActionModel>()\n const named = runner.actions.map((action): RailAction => {\n const blocked = runner.blocked(action)\n // A link that can be followed is a link, looking as the rail's buttons do; a disabled one stays a disabled button\n const link = action.run?.kind === 'link' && !blocked ? actionLink(action.run, stored.record, app) : undefined\n return {\n name: action.label,\n icon: actionIcon(action.icon),\n blocked,\n running: runner.running === action.name,\n ...(isDanger(action) && { tone: 'danger' as const }),\n onRun: () => (asksFirst(action) ? setAsking(action) : void runner.run(action)),\n ...(link && { render: ({ className, children, role }) => <RouteLink to={link} role={role} className={className}>{children}</RouteLink> }),\n }\n })\n const deletes = runner.actions.some((action) => action.run?.kind === 'delete')\n const actions: RailAction[] = [\n ...(edit ? [{ name: text('edit'), icon: Pencil, render: ({ className, children, role }) => <AppLink to={edit} role={role} className={className}>{children}</AppLink> } satisfies RailAction] : []),\n ...named,\n ...(onDelete && !deletes ? [{ name: text('delete'), icon: Trash2, tone: 'danger' as const, onRun: onDelete }] : []),\n ]\n const prompt = asking && (\n <ActionPrompt\n action={asking}\n label={asking.label}\n danger={isDanger(asking)}\n records={[stored.record]}\n onCancel={() => setAsking(undefined)}\n onConfirm={() => {\n setAsking(undefined)\n void runner.run(asking)\n }}\n onSubmit={async (values) => {\n await runner.submit(asking, values)\n setAsking(undefined)\n }}\n />\n )\n return { actions, prompt }\n}\n\n/**\n * The record page's actions in one rail. On a mobile screen they sit in the top bar's menu instead, at hand however\n * long the record is, when the shell has a top bar.\n */\nexport const RecordActions = (props: RecordActionsProps) => {\n const slot = useTopBarSlot()\n const { actions, prompt } = useRecordActions(props)\n if (actions.length === 0) return null\n return (\n <>\n <div className={slot ? 'max-md:hidden' : undefined}>\n <ActionRail actions={actions} />\n </div>\n {slot && createPortal(<ActionMenu actions={actions} label={text('recordActions')} className={topBarButton} />, slot)}\n {prompt}\n </>\n )\n}\n","import { ApiError, type BatchOp } from '@protobase/client'\nimport { text as appText } from './messages'\n\nconst label = (op: BatchOp) => {\n const resource = typeof op.resource === 'string' ? op.resource : op.resource.toModel().name\n return op.op === 'reorder' ? `reorder ${resource} by ${op.field}` : `${op.op} ${resource}`\n}\n\n/** \"Operation 2 (reorder invoice_lines by position) failed: ...\" so the person knows which part was refused. */\nexport const describeBatchFailure = (error: ApiError, ops: BatchOp[]) => {\n const index = error.operation\n const op = index === undefined ? undefined : ops[index]\n return op ? appText('operationFailed', { index: index! + 1, label: label(op), message: error.message }) : appText('nothingSaved', { message: error.message })\n}\n\n/** The same error with the failing operation named in its message, keeping its class so a 412 stays a 412. */\nexport const nameFailingOperation = (error: ApiError, ops: BatchOp[]) => {\n const named = new (error.constructor as typeof ApiError)({ ...error.problem, detail: describeBatchFailure(error, ops) })\n return named\n}\n","import { useQueryClient } from '@tanstack/react-query'\nimport { useEffect, useState } from 'react'\nimport { isApiError, type BatchOp, type ProblemError } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { keys } from '../data/query-keys'\nimport type { LiveRecord } from '../data/use-record'\nimport { isConflict, useUpdateRecord } from '../data/use-update-record'\nimport { displayValue } from '../live/display-value'\nimport { differs, toDraft, toPatchValue } from '../live/field-values'\nimport { nameFailingOperation } from './batch-failure'\nimport { fieldErrors } from './field-errors'\nimport { readDraft, writeDraft } from './draft-storage'\nimport type { LinesPlan } from './lines-plan'\nimport type { LinesDraft } from './use-lines-draft'\nimport { useLiveSave, type SaveMode } from './use-live-save'\n\nexport type RecordEditorParams = {\n model: ResourceModel\n stored: LiveRecord\n recordKey: string\n mode: SaveMode\n subject: string\n /** Where unsaved changes are kept in local storage, so a reload or a stray click does not lose them. */\n draftKey?: string\n /** The changes to the record's lines, written together with the record on Save. */\n lines?: LinesDraft\n}\n\nconst without = <V>(source: Record<string, V>, name: string): Record<string, V> => Object.fromEntries(Object.entries(source).filter(([key]) => key !== name))\n\n/**\n * Draft state for one record. Saving sends only the changed fields with the ETag that was read;\n * a 412 refetches the record and marks the fields both sides changed so the user can pick a side.\n * When the lines changed too, Save sends the record and the lines' writes as one batch: all or nothing.\n */\nexport const useRecordEditor = ({ model, stored, recordKey, mode, subject, draftKey, lines }: RecordEditorParams) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const update = useUpdateRecord(model.name, recordKey)\n const feedback = useLiveSave(mode, subject)\n const [restored] = useState(() => (draftKey ? readDraft(localStorage, draftKey, stored.etag) : undefined))\n const [draft, setDraft] = useState<Record<string, unknown>>(restored?.fields ?? {})\n const [showRestored, setShowRestored] = useState(Boolean(restored))\n const [linesConflict, setLinesConflict] = useState(false)\n const [conflicts, setConflicts] = useState<Record<string, string>>({})\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\n // A draft is kept as typed, so a line break or space at its end stays while the rest is still to come; it is a change\n // only when it stands for another value than the stored one.\n const changed = Object.entries(draft).filter(([name, entry]) => differs(model.fields[name]!, entry, stored.record[name]))\n const fieldsDirty = changed.length > 0\n const dirty = fieldsDirty || Boolean(lines?.dirty)\n\n // The restored order is applied once, when the record opens.\n useEffect(() => {\n if (restored?.order) lines?.setOrder(restored.order)\n }, [])\n\n // A sensitive value, and so a write-only one, is never kept in local storage\n useEffect(() => {\n if (!draftKey) return\n const kept = Object.fromEntries(Object.entries(draft).filter(([name]) => !model.fields[name]?.sensitive))\n const keep = Object.keys(kept).length > 0 || Boolean(lines?.order)\n writeDraft(localStorage, draftKey, keep ? { etag: stored.etag, fields: kept, ...(lines?.order && { order: lines.order }) } : undefined)\n }, [draftKey, model, draft, lines?.order, stored.etag])\n\n // Booleans and files are edited as they are stored; everything else as text\n const value = (name: string) => (name in draft ? draft[name] : ['boolean', 'file'].includes(model.fields[name]!.type) ? stored.record[name] : toDraft(stored.record[name]))\n\n const change = (name: string, next: unknown) => {\n setErrors((current) => without(current, name))\n const typed = typeof next === 'string' ? next !== toDraft(stored.record[name]) : differs(model.fields[name]!, next, stored.record[name])\n setDraft((current) => (typed ? { ...current, [name]: next } : without(current, name)))\n }\n\n const adoptLatest = async () => {\n const latest = await client.get(model.name, recordKey)\n queryClient.setQueryData(keys.record(model.name, recordKey), latest)\n const theirs: Record<string, string> = {}\n const keep: Record<string, unknown> = {}\n for (const [name, mine] of Object.entries(draft)) {\n const field = model.fields[name]!\n if (!differs(field, mine, latest.record[name])) continue\n keep[name] = mine\n if (toDraft(latest.record[name]) !== toDraft(stored.record[name])) theirs[name] = field.type === 'file' ? displayValue(field, latest.record[name]) : toDraft(latest.record[name])\n }\n setDraft(keep)\n setConflicts(theirs)\n }\n\n const patchOf = () => Object.fromEntries(changed.map(([name, entry]) => [name, toPatchValue(model.fields[name]!, entry)]))\n\n const reject = (error: unknown) => {\n const found = fieldErrors(error)\n setErrors(found)\n if (Object.keys(found).length > 0) setRejections((count) => count + 1)\n }\n\n const saveRecordOnly = async () => {\n try {\n await update.mutateAsync({ patch: patchOf(), etag: stored.etag })\n } catch (error) {\n if (isConflict(error)) await adoptLatest()\n else if (isApiError(error)) reject(error)\n throw error\n }\n }\n\n const saveBatch = async (linesPlan: LinesPlan) => {\n const recordOps: BatchOp[] = fieldsDirty ? [{ op: 'update', resource: model.name, key: recordKey, data: patchOf(), etag: stored.etag }] : []\n const ops = [...recordOps, ...linesPlan.ops]\n try {\n await client.batchWrite(ops)\n } catch (error) {\n if (isConflict(error)) {\n await adoptLatest()\n await queryClient.invalidateQueries({ queryKey: ['list'] })\n setLinesConflict(true)\n } else if (isApiError(error)) {\n // A refused operation on a line shows on that line, not on the record's fields\n const lineOp = error.operation === undefined ? -1 : error.operation - recordOps.length\n const row = linesPlan.rows[lineOp]\n if (lineOp < 0) reject(error)\n else if (row) lines?.reject(row, error)\n }\n throw isApiError(error) ? nameFailingOperation(error, ops) : error\n }\n await Promise.all([queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }), queryClient.invalidateQueries({ queryKey: ['list'] }), queryClient.invalidateQueries({ queryKey: ['page'] }), queryClient.invalidateQueries({ queryKey: ['map'] }), queryClient.invalidateQueries({ queryKey: ['aggregate'] })])\n lines?.reset()\n }\n\n const save = () =>\n feedback.run(async () => {\n const linesPlan = lines?.plan()\n if (linesPlan && linesPlan.ops.length > 0) await saveBatch(linesPlan)\n else await saveRecordOnly()\n setDraft({})\n setConflicts({})\n setErrors({})\n setLinesConflict(false)\n setShowRestored(false)\n })\n\n const discard = () => {\n setDraft({})\n setConflicts({})\n setErrors({})\n setLinesConflict(false)\n setShowRestored(false)\n lines?.reset()\n }\n\n return {\n value,\n change,\n save,\n dirty,\n discard,\n /** The changes on screen were brought back from this browser. */\n restored: showRestored && dirty,\n dismissRestored: () => setShowRestored(false),\n /** Someone changed the lines while they were being edited here. */\n linesConflict,\n saving: feedback.phase === 'saving',\n phase: feedback.phase,\n message: feedback.message,\n conflicts,\n /** The server's problem with each field, from the last save. */\n errors,\n rejections,\n keepMine: (name: string) => setConflicts((current) => without(current, name)),\n useTheirs: (name: string) => {\n setConflicts((current) => without(current, name))\n setDraft((current) => without(current, name))\n },\n }\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('focus-record')\n","import { Button } from '../../primitives/button'\nimport { text } from './messages'\n\n/** A save conflict's choices: each settles one field, so each names the field it settles. */\nexport const ConflictChoices = ({ fields, onKeepMine, onUseTheirs }: { fields: { name: string; label: string }[]; onKeepMine: (name: string) => void; onUseTheirs: (name: string) => void }) => (\n <>\n {fields.map(({ name, label }) => [\n <Button key={`mine:${name}`} size=\"sm\" onClick={() => onKeepMine(name)}>{text('keepMine', { field: label })}</Button>,\n <Button key={`theirs:${name}`} size=\"sm\" onClick={() => onUseTheirs(name)}>{text('useTheirs', { field: label })}</Button>,\n ])}\n </>\n)\n","import { Check, ListTree, Undo2 } from 'lucide-react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { useMemo, useState, type ReactElement } from 'react'\nimport type { RecordPageModel, ResourceModel } from '@protobase/schema'\nimport { useAuth } from '../../auth'\nimport { usePauseFocusRefresh } from '../../data/focus-refresh'\nimport { keys } from '../../data/query-keys'\nimport type { LiveRecord } from '../../data/use-record'\nimport { FocusActions, FocusNotice, FocusPage, FocusSlot, useFocusPage, useFocusZoneFilled } from '../../focus-page'\nimport { humanize } from '../../live/naming'\nimport { Button } from '../../primitives/button'\nimport { useDeleteFlow } from '../delete/use-delete-flow'\nimport { useRestore } from '../delete/use-restore'\nimport { draftStorageKey } from '../draft-storage'\nimport { fieldMessage } from '../field-errors'\nimport { FieldEditor } from '../field-editor'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { useProjectUi } from '../pages/project-ui'\nimport { RecordScope } from '../pages/record-scope'\nimport { useRecordActions } from '../pages/record-actions'\nimport { can, fieldAccess } from '../permissions'\nimport { useNavigationGuard } from '../router'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { useRecordEditor } from '../use-record-editor'\nimport { ConflictChoices } from './conflict-choices'\nimport { FocusRecordContext, type FocusRecord } from './focus-record'\nimport { text } from './messages'\n\ntype RecordFocusPageProps = {\n model: ResourceModel\n recordKey: string\n stored: LiveRecord\n page: Exclude<RecordPageModel, { conversation: unknown }>\n /** The record's standard page, which shows when the surface throws or its component is missing. */\n standard: ReactElement\n}\n\n// The zone Save stands in: secondary beside a primary of the surface's own, else it is the page's primary\nconst SaveButton = ({ record, label }: { record: FocusRecord; label: string }) => {\n const { dirty, saving, save } = record\n const taken = useFocusZoneFilled('primary')\n const compact = useFocusPage()?.size === 'compact'\n // Stays pressable to the keyboard while there is nothing to save, so focus survives a press of it\n const button = (\n <Button variant={!taken || dirty ? 'primary' : 'secondary'} loading={saving} aria-disabled={!dirty} className=\"max-md:min-h-11\" onClick={() => void (dirty && !saving && save())}>\n {label}\n </Button>\n )\n // A bar with no room drops Save while there is nothing to save\n if (compact && !dirty) return null\n return taken ? <FocusSlot zone=\"secondary\">{button}</FocusSlot> : <FocusSlot zone=\"primary\" fallback>{button}</FocusSlot>\n}\n\n// How the work stands, in the bar, unless the surface says so in words of its own\nconst SaveState = ({ record, saved, readOnly }: { record: FocusRecord; saved: boolean; readOnly: boolean }) => {\n const size = useFocusPage()?.size\n const words = () => {\n if (readOnly) return text('readOnly')\n if (record.saving) return text('saving')\n if (record.dirty) return size === 'wide' ? text('unsaved') : text('unsavedShort')\n return saved ? text('saved') : undefined\n }\n const shown = words()\n if (!shown) return null\n return (\n <FocusSlot zone=\"state\" fallback>\n <span role=\"status\" title={readOnly ? text('readOnlyWhy') : undefined} className=\"flex items-center gap-1 truncate\">\n {!readOnly && !record.dirty && !record.saving && <Check className=\"size-3.5 text-success-text\" aria-hidden />}\n {shown}\n </span>\n </FocusSlot>\n )\n}\n\nconst RecordFocus = ({ model, recordKey, stored, page }: Omit<RecordFocusPageProps, 'standard'>) => {\n const meta = useAdminMeta()\n const view = meta.views[model.name]\n const { address, go } = useAppAddress()\n const title = useRecordTitle()(model, view, stored.record, recordKey)\n const { state: auth } = useAuth()\n const editor = useRecordEditor({\n model,\n stored,\n recordKey,\n mode: 'button',\n subject: title,\n // A draft of its own: the form keeps its fields and line order in another, which this page never touches\n draftKey: auth.kind === 'signed-in' ? `${draftStorageKey(auth.user.id, model.name, recordKey)}:focus` : undefined,\n })\n useNavigationGuard(editor.dirty || editor.saving)\n usePauseFocusRefresh(editor.dirty)\n const queryClient = useQueryClient()\n const [askDiscard, setAskDiscard] = useState(false)\n const noun = view?.names?.singular ?? humanize(model.name)\n const permissions = usePermissions(model.name)\n const restore = useRestore(model)\n // An earlier version of the record, as a field type that keeps versions draws it, is only read\n const pastVersion = address?.kind === 'record' && address.version !== undefined && address.version !== Number(stored.record.version)\n // The surface's own field counts: one this reader may only read is not theirs to change here\n const surfaceReadable = 'surface' in page && (fieldAccess(stored.permissions, page.surface) === 'read' || model.fields[page.surface]?.readOnly === true)\n const mayUpdate = can(permissions, 'update') && stored.permissions?.update !== false && !surfaceReadable\n const readOnly = !mayUpdate || pastVersion\n const canDelete = can(permissions, 'delete') && stored.permissions?.delete !== false\n const remove = useDeleteFlow({\n model,\n view,\n restore,\n onDeleted: () => go({ kind: 'list', resource: model.name }, { replace: true }),\n onReview: () => void queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }),\n })\n const startDelete = canDelete ? () => void remove.start({ key: recordKey, title, etag: stored.etag, snapshot: stored.record }) : undefined\n const { actions, prompt } = useRecordActions({ model, stored, recordKey, onDelete: startDelete })\n const details = useMemo(() => ({ kind: 'record' as const, resource: model.name, key: recordKey, standard: true }), [model.name, recordKey])\n // Open details stands before Delete, which stays last\n const danger = actions.filter((action) => action.tone === 'danger')\n const barActions = [\n ...actions.filter((action) => action.tone !== 'danger'),\n ...(editor.dirty ? [{ name: text('discardChanges'), icon: Undo2, onRun: () => setAskDiscard(true) }] : []),\n { name: text('detailsOf', { noun }), icon: ListTree, render: ({ className, children, role }: { className: string; children: React.ReactNode; role?: 'menuitem' }) => <AppLink to={details} role={role} className={className}>{children}</AppLink> },\n ...danger,\n ]\n const record: FocusRecord = {\n model,\n record: stored.record,\n key: recordKey,\n ...(stored.etag !== undefined && { etag: stored.etag }),\n ...(stored.permissions && { permissions: stored.permissions }),\n readOnly,\n mayUpdate,\n value: editor.value,\n // A read-only page changes and saves nothing, whatever its surface asks\n change: (name, next) => (readOnly ? undefined : editor.change(name, next)),\n dirty: editor.dirty,\n saving: editor.saving,\n refused: editor.message !== undefined,\n save: async () => !readOnly && Boolean(await editor.save()),\n discard: editor.discard,\n details,\n }\n const surfaceField = 'surface' in page ? page.surface : undefined\n const discardNotice = askDiscard && editor.dirty && (\n <FocusNotice\n level=\"draft\"\n actions={\n <>\n <Button size=\"sm\" variant=\"danger\" onClick={() => { editor.discard(); setAskDiscard(false) }}>{text('discardChanges')}</Button>\n <Button size=\"sm\" onClick={() => setAskDiscard(false)}>{text('keep')}</Button>\n </>\n }\n >\n {text('discardAsk')}\n </FocusNotice>\n )\n const conflict = Object.keys(editor.conflicts).length > 0\n // The surface's own field has no form around it to mark, so what is wrong with it is said here\n const refusedField = surfaceField ? editor.errors[surfaceField] : undefined\n const surfaceProblem = refusedField && surfaceField ? fieldMessage(model.fields[surfaceField]!, view?.fields[surfaceField]?.label ?? humanize(surfaceField), refusedField) : undefined\n return (\n <FocusRecordContext.Provider value={record}>\n {!readOnly && <SaveButton record={record} label={text('save')} />}\n <SaveState record={record} saved={editor.phase === 'saved'} readOnly={readOnly} />\n <FocusActions actions={barActions} />\n {editor.message && !askDiscard && (\n <FocusNotice level=\"refused\" actions={<AppLink to={details} className=\"text-body font-medium text-primary-text hover:underline\">{text('detailsOf', { noun })}</AppLink>}>\n <strong className=\"font-medium\">{text('notSaved')}</strong> {surfaceProblem ?? editor.message}\n </FocusNotice>\n )}\n {conflict && (\n <FocusNotice\n level=\"conflict\"\n actions={\n <ConflictChoices\n fields={Object.keys(editor.conflicts).map((name) => ({ name, label: view?.fields[name]?.label ?? humanize(name) }))}\n onKeepMine={editor.keepMine}\n onUseTheirs={editor.useTheirs}\n />\n }\n >\n {text('conflict')}\n </FocusNotice>\n )}\n {discardNotice}\n {editor.restored && !askDiscard && (\n <FocusNotice\n level=\"draft\"\n actions={\n <>\n <Button size=\"sm\" onClick={editor.dismissRestored}>{text('keep')}</Button>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </>\n }\n >\n {text('restored')}\n </FocusNotice>\n )}\n {surfaceField ? <FieldSurface model={model} name={surfaceField} stored={stored} editor={editor} readOnly={readOnly} /> : <ComponentSurface name={(page as { component: string }).component} model={model} stored={stored} recordKey={recordKey} />}\n {remove.dialogs}\n {prompt}\n </FocusRecordContext.Provider>\n )\n}\n\ntype Editor = ReturnType<typeof useRecordEditor>\n\n// One field fills the surface, drawn by its field type\nconst FieldSurface = ({ model, name, stored, editor, readOnly }: { model: ResourceModel; name: string; stored: LiveRecord; editor: Editor; readOnly: boolean }) => {\n const hints = useAdminMeta().views[model.name]?.fields[name]\n // Hidden from this reader, the field is not drawn: the page's boundary shows the form, which leaves it out too\n if (fieldAccess(stored.permissions, name) === 'hidden') throw new Error(`The surface's field ${name} is hidden from this reader`)\n return (\n <div className=\"absolute inset-0\">\n <FieldEditor field={model.fields[name]!} hints={hints} value={editor.value(name)} stored={stored.record[name]} locked={readOnly} invalid={Boolean(editor.errors[name])} resource={model.name} onChange={(next) => editor.change(name, next)} />\n </div>\n )\n}\n\nconst ComponentSurface = ({ name, model, stored, recordKey }: { name: string; model: ResourceModel; stored: LiveRecord; recordKey: string }) => {\n const Component = useProjectUi().components?.[name]\n if (!Component) throw new Error(`No component is registered as ${name}`)\n return (\n <div className=\"absolute inset-0\">\n <RecordScope value={{ model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }}>\n <Component />\n </RecordScope>\n </div>\n )\n}\n\n/**\n * A record's page as a focus page, as `.record(...)` asks: the bar's state, Save and actions, the notices of a save, and\n * the surface, one field or the app's component, with the record's standard form a link away. The form shows instead\n * when the surface throws.\n */\nexport const RecordFocusPage = ({ model, recordKey, stored, page, standard }: RecordFocusPageProps) => {\n const title = useRecordTitle()(model, useAdminMeta().views[model.name], stored.record, recordKey)\n return (\n <CustomBoundary name={'surface' in page ? page.surface : page.component} fallback={standard} resetKey={model}>\n <FocusPage label={title}>\n <RecordFocus model={model} recordKey={recordKey} stored={stored} page={page} />\n </FocusPage>\n </CustomBoundary>\n )\n}\n","import { lazy, Suspense } from 'react'\nimport type { MapSectionModel } from '@protobase/schema'\nimport { Section, SidebarCard } from '../../record-view'\nimport { useAdminMeta } from '../meta-gate'\nimport { recordPosition } from './record-position'\n\n// MapLibre and the tiles' protocol load with the first map drawn, so a page without one never loads them.\nconst RecordMap = lazy(() => import('./record-map').then((module) => ({ default: module.RecordMap })))\n\nconst defaultZoom = 15\n\n/**\n * A map of the record's position (`l.map`), in a section or a sidebar card under its title, drawn with the map style\n * `/meta` names. Without a style, or for a record without a position, there is nothing to draw and no section.\n */\nexport const MapSection = ({ item, record }: { item: MapSectionModel; record: Record<string, unknown> }) => {\n const maps = useAdminMeta().maps\n const style = maps?.style\n const position = recordPosition(record, item)\n if (!style || !position) return null\n const map = (\n <div className={`overflow-hidden rounded-lg border border-border bg-muted ${item.sidebar ? 'h-48' : 'h-64 md:h-80'}`}>\n <Suspense fallback={null}>\n {/* A new position is a new map, centred on it */}\n <RecordMap key={`${position.latitude},${position.longitude}`} style={style} layers={maps?.layers} position={position} zoom={item.zoom ?? defaultZoom} />\n </Suspense>\n </div>\n )\n return item.sidebar ? <SidebarCard title={item.title}>{map}</SidebarCard> : <Section title={item.title}>{map}</Section>\n}\n","import type { AggregateGroup } from '@protobase/client'\nimport type { RecordChartRange } from '@protobase/schema'\nimport type { PeriodBucket } from '../charts/period-types'\n\n/** What each bucket of a record's chart reads of its samples. */\nexport type SampleMeasure = 'average' | 'maximum'\n\n/** How long a bucket is over each range: a minute over the hour, 5 minutes over the day, an hour over the week. */\nexport const rangeBuckets = { '1h': 'minute', '24h': '5_minutes', '7d': 'hour' } as const satisfies Record<RecordChartRange, PeriodBucket>\n\n/** A bucket's start, read as UTC as the chart draws it, with each series' number under its key, `null` where it has none. */\nexport type SamplePoint = { at: number; value: number | null; count: number } & Record<string, number | null>\n\n/**\n * The buckets of several series as one line of points, each series' number under `keys[i]`. The series come from\n * requests sent one by one, so their ranges may end a bucket apart: a bucket one of them lacks holds `null` for it, as\n * one without a sample does, which the chart draws as a gap rather than as 0.\n */\nexport const chartPoints = (series: AggregateGroup[][], keys: string[], measure: SampleMeasure): SamplePoint[] => {\n const points = new Map<number, SamplePoint>()\n series.forEach((groups, index) => {\n for (const group of groups) {\n const at = Date.parse(`${String(group.value)}Z`)\n const point = points.get(at) ?? ({ at, value: null, count: 0 } as SamplePoint)\n point[keys[index]!] = group[measure] ?? null\n point.count = Math.max(point.count, group.count)\n points.set(at, point)\n }\n })\n const empty = Object.fromEntries(keys.map((key) => [key, null]))\n return [...points.values()].sort((a, b) => a.at - b.at).map((point) => ({ ...empty, ...point }))\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-chart')\n","import { useState } from 'react'\nimport { createWhere, printFilter, type RecordChartModel, type RecordChartRange } from '@protobase/schema'\nimport { useAggregates } from '../../data/use-aggregates'\nimport { viewerZone } from '../../format/zone'\nimport { humanize } from '../../live/naming'\nimport { Segmented } from '../../primitives/segmented'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport type { ChartMeasure } from '../charts/chart-groups'\nimport { PeriodChart } from '../charts/lazy-charts'\nimport type { ChartSeries } from '../charts/split-points'\nimport { useAdminMeta } from '../meta-gate'\nimport { chartPoints, rangeBuckets, type SampleMeasure } from './chart-points'\nimport { text } from './messages'\n\nconst where = createWhere()\nconst ranges: RecordChartRange[] = ['1h', '24h', '7d']\nconst rangeLabels = { '1h': 'hour', '24h': 'day', '7d': 'week' } as const\n\n/**\n * Line graphs of the samples of `item.resource` that point at the record (`l.chart`), each series' average or maximum\n * per bucket over the last hour, day or week, which the person switches between. Each series is one `:aggregate`\n * read with their access; a bucket without a sample is a gap in its line.\n */\nexport const RecordChartSection = ({ item, recordKey }: { item: RecordChartModel; recordKey: string }) => {\n const { resources, views } = useAdminMeta()\n const [range, setRange] = useState<RecordChartRange>(item.range ?? '1h')\n const [measure, setMeasure] = useState<SampleMeasure>('average')\n const model = resources[item.resource]\n const view = views[item.resource]\n const granularity = rangeBuckets[range]\n const filter = printFilter(where.eq(item.field, recordKey))\n const requests = item.series.map((name) => ({ groupBy: item.at, filter, ...(measure === 'average' ? { average: name } : { maximum: name }), range, granularity, timeZone: viewerZone() }))\n const results = useAggregates(item.resource, requests, Boolean(model))\n if (!model) return null\n\n const measures = item.series.map((name): ChartMeasure => ({ kind: measure, field: model.fields[name]!, ...(view?.fields[name] && { hints: view.fields[name] }) }))\n const series: ChartSeries[] = item.series.map((name, index) => ({ key: `s${index}`, label: view?.fields[name]?.label ?? humanize(name), color: `var(--chart-${index + 1})`, measure: measures[index]! }))\n const points = results.every((result) => result.data) ? chartPoints(results.map((result) => result.data!.groups), series.map((part) => part.key), measure) : []\n const actions = (\n <div className=\"flex flex-wrap gap-2\">\n <Segmented label={text('measure')} value={measure} onChange={setMeasure} options={[{ value: 'average', label: text('average') }, { value: 'maximum', label: text('maximum') }]} />\n <Segmented label={text('range')} value={range} onChange={setRange} options={ranges.map((value) => ({ value, label: text(rangeLabels[value]) }))} />\n </div>\n )\n const body = () => {\n if (results.some((result) => result.error)) return <p className=\"text-danger-text\">{text('couldNotLoad')}</p>\n if (results.some((result) => result.isPending)) return <Skeleton className=\"h-40 w-full\" />\n if (points.every((point) => point.count === 0)) return <p className=\"text-muted-foreground\">{text('noSamples')}</p>\n // One series needs no legend: the section's title names it\n return <PeriodChart points={points} measure={measures[0]!} bucket={granularity} type=\"line\" series={series} {...(series.length > 1 && { resource: item.resource, view })} />\n }\n return (\n <Section title={item.title} help={item.help} actions={actions}>\n {body()}\n </Section>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-trend')\n","import type { ChartRange } from '@protobase/schema'\nimport { text } from './messages'\n\n/** The line over a trend: how many records its bars hold together, over its range, such as \"4 in the last 90 days\". */\nexport const trendSummary = (total: number, range: ChartRange) => text(`total_${range}`, { count: total })\n","import { createWhere, printFilter, type RecordTrendModel } from '@protobase/schema'\nimport { useAggregate } from '../../data/use-aggregates'\nimport { viewerZone } from '../../format/zone'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { periodPoints } from '../charts/chart-groups'\nimport { PeriodChart } from '../charts/lazy-charts'\nimport { ErrorBanner } from '../error-banner'\nimport { trendSummary } from './trend-summary'\nimport { text } from './messages'\n\nconst where = createWhere()\nconst count = { kind: 'count' } as const\n\n/**\n * Bars of how many records of `item.resource` point at the record (`l.trend`), per bucket of their date over the\n * item's range, under a line with their total over that range: one `:aggregate` read with the reader's access, read\n * again when the records change. With none in the range the bars stay, flat, so the page below does not move.\n */\nexport const RecordTrendSection = ({ item, recordKey }: { item: RecordTrendModel; recordKey: string }) => {\n const filter = printFilter(where.eq(item.field, recordKey))\n const result = useAggregate(item.resource, { groupBy: item.at, filter, granularity: item.granularity, range: item.range, timeZone: viewerZone() })\n const body = () => {\n if (result.isPending) return <Skeleton className=\"h-[calc(10rem+2rem)] w-full\" />\n if (result.error) return <ErrorBanner title={text('couldNotLoad')} error={result.error} onRetry={() => void result.refetch()} />\n const total = result.data.groups.reduce((sum, group) => sum + group.count, 0)\n return (\n <>\n <p className=\"mb-3 leading-5 text-foreground\">{trendSummary(total, item.range)}</p>\n <PeriodChart points={periodPoints(result.data.groups, count)} measure={count} bucket={item.granularity} type=\"bar\" />\n </>\n )\n }\n return (\n <Section title={item.title} help={item.help}>\n <div aria-busy={result.isPending}>{body()}</div>\n </Section>\n )\n}\n","import type { GroupModel } from '@protobase/schema'\n\n/** The open groups after the person opens or closes `title`. */\nexport const toggledOpen = (open: readonly string[] = [], title: string) => (open.includes(title) ? open.filter((name) => name !== title) : [...open, title])\n\n/** Whether a group shows its items: always unless `collapsed`, else when the address names it or one of its sections holds a field that needs the person's attention. */\nexport const groupOpen = (group: GroupModel, open: readonly string[] = [], needsAttention: (field: string) => boolean) =>\n !group.collapsed || open.includes(group.title) || group.items.some((item) => item.kind === 'section' && item.fields.some(needsAttention))\n","import type { LayoutItemModel, TabModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\n\n/** The shown layout around its tabs: the items before them, the tabs, and the items after. A view's tabs stand together. */\nexport const splitTabs = (layout: LayoutItemModel[]) => {\n const first = layout.findIndex((item) => item.kind === 'tab')\n if (first === -1) return { before: layout, tabs: [] as TabModel[], after: [] as LayoutItemModel[] }\n const tabs: TabModel[] = []\n for (const item of layout.slice(first)) {\n if (item.kind !== 'tab') break\n tabs.push(item)\n }\n return { before: layout.slice(0, first), tabs, after: layout.slice(first + tabs.length) }\n}\n\n/** The tab shown: the one the address names, else the first. */\nexport const shownTab = (tabs: TabModel[], named: string | undefined) => tabs.find((tab) => tab.title === named) ?? tabs[0]\n\nconst tabFields = (tab: TabModel) => layoutItems(tab.items).flatMap((item) => (item.kind === 'section' ? item.fields : []))\n\n/** The tab to show after a turned-down save: the first that holds a field needing attention, unless the shown one does. */\nexport const attentionTab = (tabs: TabModel[], shown: TabModel | undefined, needsAttention: (field: string) => boolean) => {\n if (!shown || tabFields(shown).some(needsAttention)) return undefined\n return tabs.find((tab) => tabFields(tab).some(needsAttention))\n}\n","import type { BatchOp, BatchRef } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { differs, toPatchValue } from '../live/field-values'\nimport { recordId, recordKey } from '../live/model-helpers'\n\ntype Line = Record<string, unknown>\n\n/** What the person changed in a record's lines and has not saved: their order, new lines, edited fields and removed lines. */\nexport type LinesState = {\n /** The ids in the order on screen, once a line was moved; new lines have ids of their own until saved. */\n order?: string[]\n /** The new lines' ids, in the order they were added. */\n added: string[]\n /** Per line id, the fields as typed, the way a form holds them. */\n edits: Record<string, Record<string, unknown>>\n removed: string[]\n}\n\nexport const emptyLinesState: LinesState = { added: [], edits: {}, removed: [] }\n\n/** The batch that saves the lines, and per operation the id of the line it writes, none for a reorder. */\nexport type LinesPlan = { ops: BatchOp[]; rows: Array<string | undefined> }\n\nexport type LinesPlanInput = {\n model: ResourceModel\n /** The integer field that holds the lines' order. */\n position: string\n /** The relation to the record the lines belong to, and that record's key, which a new line gets. */\n link: { field: string; value: unknown }\n /** The lines as the server has them, in their order. */\n stored: Line[]\n state: LinesState\n}\n\n/** The ids on screen, in order: the stored lines that are kept, then the new ones, as far as `order` does not say otherwise. */\nexport const shownIds = (storedIds: string[], state: LinesState) => {\n const kept = [...storedIds.filter((id) => !state.removed.includes(id)), ...state.added]\n if (!state.order) return kept\n return [...state.order.filter((id) => kept.includes(id)), ...kept.filter((id) => !state.order!.includes(id))]\n}\n\n/** The edited fields that differ from the stored line, as the API takes them. */\nconst changedData = (model: ResourceModel, edits: Record<string, unknown>, line: Line) =>\n Object.fromEntries(\n Object.entries(edits).flatMap(([name, draft]) => {\n const field = model.fields[name]\n return field && differs(field, draft, line[name]) ? [[name, toPatchValue(field, draft)]] : []\n }),\n )\n\n/** The fields filled in on a new line; the database's defaults fill the rest. */\nconst filledData = (model: ResourceModel, edits: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(edits).flatMap(([name, draft]) => {\n const field = model.fields[name]\n if (!field || (field.type !== 'boolean' && String(draft ?? '').trim() === '')) return []\n return [[name, toPatchValue(field, draft)]]\n }),\n )\n\n/**\n * The batch that writes the lines as they are on screen: removed lines are deleted, edited ones updated with the ETag\n * they were read with, and new ones created with the parent's key and their place. New lines after the kept ones are\n * numbered on from them; new lines between kept ones need the kept ones out of the way first, so those are moved above\n * every position in use, the new lines created at their places, and the kept ones moved to theirs. A kept line the batch\n * wrote before is moved with `*`, as its ETag was checked by that earlier operation of the same transaction.\n */\nexport const planLinesOps = ({ model, position, link, stored, state }: LinesPlanInput): LinesPlan => {\n const plan: LinesPlan = { ops: [], rows: [] }\n const push = (op: BatchOp, row?: string) => {\n plan.ops.push(op)\n plan.rows.push(row)\n }\n const byId = new Map(stored.map((line) => [recordId(model, line), line]))\n const storedIds = [...byId.keys()]\n const final = shownIds(storedIds, state)\n const keyOf = (id: string) => recordKey(model, byId.get(id)!)\n const etagOf = (id: string) => {\n const etag = byId.get(id)!.etag\n return typeof etag === 'string' ? etag : undefined\n }\n\n for (const id of state.removed) {\n if (!byId.has(id)) continue\n const etag = etagOf(id)\n push({ op: 'delete', resource: model.name, key: keyOf(id), ...(etag && { etag }) }, id)\n }\n\n const written = new Set<string>()\n for (const [id, edits] of Object.entries(state.edits)) {\n if (!byId.has(id) || state.removed.includes(id)) continue\n const data = changedData(model, edits, byId.get(id)!)\n if (Object.keys(data).length === 0) continue\n const etag = etagOf(id)\n push({ op: 'update', resource: model.name, key: keyOf(id), data, ...(etag && { etag }) }, id)\n written.add(id)\n }\n\n const kept = final.filter((id) => byId.has(id))\n const added = final.filter((id) => !byId.has(id))\n const etags = (ids: string[], wildcard: boolean) =>\n Object.fromEntries(\n ids.flatMap((id) => {\n const etag = wildcard || written.has(id) ? '*' : etagOf(id)\n return etag ? [[encodeKey(keyOf(id)), etag]] : []\n }),\n )\n const reorder = (keys: Array<ReturnType<typeof keyOf> | BatchRef>, start: number, tags: Record<string, string>): BatchOp => ({\n op: 'reorder',\n resource: model.name,\n field: position,\n keys,\n ...(start !== 1 && { start }),\n etags: tags,\n })\n const create = (id: string, place: number, ref?: string): BatchOp => ({\n op: 'create',\n resource: model.name,\n data: { ...filledData(model, state.edits[id] ?? {}), [link.field]: link.value, [position]: place },\n ...(ref && { ref }),\n })\n const placeOf = (line: Line) => Number(line[position]) || 0\n\n const moved = kept.some((id, index) => id !== storedIds.filter((each) => kept.includes(each))[index])\n const atEnd = added.every((id) => final.indexOf(id) >= kept.length)\n if (atEnd) {\n if (moved) push(reorder(kept.map(keyOf), 1, etags(kept, false)))\n const last = moved ? kept.length : Math.max(0, ...kept.map((id) => placeOf(byId.get(id)!)))\n added.forEach((id, index) => push(create(id, last + 1 + index), id))\n return plan\n }\n\n const above = Math.max(final.length, ...stored.map(placeOf)) + 1\n if (kept.length > 0) push(reorder(kept.map(keyOf), above, etags(kept, false)))\n const refOf = (id: string) => `line${added.indexOf(id) + 1}`\n for (const id of added) push(create(id, final.indexOf(id) + 1, refOf(id)), id)\n push(reorder(final.map((id) => (byId.has(id) ? keyOf(id) : { $ref: refOf(id) })), 1, etags(kept, true)))\n return plan\n}\n","import { useMemo, useRef, useState } from 'react'\nimport type { ApiError, ProblemError } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { toFieldDraft } from '../live/field-values'\nimport { recordId } from '../live/model-helpers'\nimport { fieldErrors } from './field-errors'\nimport { emptyLinesState, planLinesOps, shownIds, type LinesPlan, type LinesState } from './lines-plan'\n\ntype Line = Record<string, unknown>\n\n/** Where the lines are written: their resource, the field that orders them, and the relation to the record with its key. */\nexport type LinesTarget = { model: ResourceModel; position: string; link: { field: string; value: unknown } }\n\n/** A line on screen: a stored one, with what was typed over it, or a new one, which has no `stored`. */\nexport type ShownLine = { id: string; stored?: Line }\n\n/** What the server said about a line on the last save: per field, and its message for the line as a whole. */\nexport type LineRejection = { id: string; fields: Record<string, ProblemError>; message: string }\n\nconst without = <V>(source: Record<string, V>, name: string): Record<string, V> => Object.fromEntries(Object.entries(source).filter(([key]) => key !== name))\n\n/**\n * The changes the person made to a record's lines, kept in the form until Save writes them, together with the record,\n * in one batch: the order, new lines, typed fields and removed lines. `shown` is the lines as they are on screen;\n * `plan()` is the batch that makes them permanent.\n */\nexport const useLinesDraft = (target: LinesTarget | undefined, stored: Line[]) => {\n const [state, setState] = useState<LinesState>(emptyLinesState)\n const [rejection, setRejection] = useState<LineRejection>()\n const nextId = useRef(1)\n const byId = useMemo(() => new Map(target ? stored.map((line) => [recordId(target.model, line), line]) : []), [target, stored])\n const shown: ShownLine[] = shownIds([...byId.keys()], state).map((id) => ({ id, stored: byId.get(id) }))\n\n const plan = (): LinesPlan => (target ? planLinesOps({ ...target, stored, state }) : { ops: [], rows: [] })\n const dirty = plan().ops.length > 0\n // The same array while the order stays, so a draft is kept only when it changes\n const order = useMemo(() => {\n const kept = shownIds([...byId.keys()], state).filter((id) => byId.has(id))\n const before = [...byId.keys()].filter((id) => kept.includes(id))\n return state.order !== undefined && kept.some((id, index) => id !== before[index]) ? kept : undefined\n }, [byId, state])\n\n /** The value a line's field editor holds: what was typed, else the stored value as the editor takes it. */\n const value = (id: string, name: string) => {\n const typed = state.edits[id]\n if (typed && name in typed) return typed[name]\n const field = target?.model.fields[name]\n const current = byId.get(id)?.[name]\n if (!field) return current\n return ['boolean', 'file'].includes(field.type) ? current : toFieldDraft(field, current)\n }\n\n const forget = (id: string) => setRejection((current) => (current?.id === id ? undefined : current))\n\n return {\n shown,\n dirty,\n /** The stored lines' ids in the order on screen, once moved, for keeping a draft. */\n order,\n value,\n change: (id: string, name: string, next: unknown) => {\n forget(id)\n setState((current) => ({ ...current, edits: { ...current.edits, [id]: { ...current.edits[id], [name]: next } } }))\n },\n /** Adds an empty line at the end; the database's defaults fill what is left empty when it is saved. */\n add: () => {\n const id = `new:${nextId.current++}`\n setState((current) => ({ ...current, added: [...current.added, id] }))\n return id\n },\n remove: (id: string) => {\n forget(id)\n setState((current) =>\n current.added.includes(id) ? { ...current, added: current.added.filter((each) => each !== id), edits: without(current.edits, id) } : { ...current, removed: [...current.removed, id] },\n )\n },\n setOrder: (next: string[]) => setState((current) => ({ ...current, order: next })),\n reset: () => {\n setState(emptyLinesState)\n setRejection(undefined)\n },\n /** The server turned down the write of line `id`: its fields and message show on that line until it changes. */\n reject: (id: string, error: ApiError) => setRejection({ id, fields: fieldErrors(error), message: error.message }),\n rejection,\n plan,\n }\n}\n\nexport type LinesDraft = ReturnType<typeof useLinesDraft>\n","import { useMemo } from 'react'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\nimport { listColumnNames } from '../live/columns-from-model'\nimport { listLabels } from '../live/relation-labels'\nimport { keyValue } from './create/create-values'\nimport { useAdminMeta } from './meta-gate'\nimport { useLines } from './use-lines'\nimport { useLinesDraft } from './use-lines-draft'\n\n/**\n * The record's lines, as its view declares them with `l.related(..., { lines: true })`: the section, the lines'\n * resource, the relation that points at the record and the field that orders them.\n */\nexport const findLinesResource = (resources: Record<string, ResourceModel>, view: ViewModel | undefined) => {\n const item = layoutItems(view?.layout ?? []).find((each) => each.kind === 'related' && each.lines === true)\n if (item?.kind !== 'related') return\n const model = resources[item.resource]\n const link = model?.fields[item.field]\n const position = model?.position?.field\n if (!model || !link || !position || model.position?.within !== item.field) return\n return { item, model, link, position }\n}\n\n/**\n * The lines' columns: the list columns of their view, or its first fields, without what the editor fills in itself:\n * the key, the tenant, the relation to the record and the position, which is the order of the rows.\n */\nexport const lineColumnNames = (lines: ResourceModel, view: ViewModel | undefined, link: string, position: string) =>\n listColumnNames(lines, view).filter((name) => {\n const field = lines.fields[name]\n return field && !field.writeOnly && name !== link && name !== position && name !== lines.tenant && !lines.primaryKey.includes(name)\n })\n\n/** The record's lines when its view declares them: the section, the resource, its columns, the lines as stored and the changes made to them. */\nexport const useRecordLines = (parent: ResourceModel, parentKey: string) => {\n const { resources, views } = useAdminMeta()\n const found = useMemo(() => findLinesResource(resources, views[parent.name]), [resources, views, parent])\n const model = found?.model\n const columns = found ? lineColumnNames(found.model, views[found.model.name], found.link.name, found.position) : []\n const data = useLines(model, found?.link, found?.position, parentKey, model ? listLabels(resources, views, model, columns) : undefined)\n const target = useMemo(() => (found ? { model: found.model, position: found.position, link: { field: found.link.name, value: keyValue(parent, parentKey) } } : undefined), [found, parent, parentKey])\n const draft = useLinesDraft(target, data.items)\n return { item: found?.item, model, columns, data, draft }\n}\n\nexport type RecordLinesData = ReturnType<typeof useRecordLines>\n","/** The most tiles a gallery draws: one large and four smaller. */\nexport const maxTiles = 5\n\n/**\n * How many of `count` photos a gallery draws as tiles, and how many more its last tile counts (\"+N\"): five at most,\n * three of four so the large tile keeps its two rows beside two wide ones, every photo when there are fewer.\n */\nexport const galleryTiles = (count: number) => {\n const shown = count >= maxTiles ? maxTiles : count === 4 ? 3 : count\n return { shown, more: count - shown }\n}\n\n/** A swipe's step: a mostly sideways drag of 40 pixels or more moves to the next photo leftwards, the previous rightwards. */\nexport const swipeStep = (dx: number, dy: number) => (Math.abs(dx) < 40 || Math.abs(dx) <= Math.abs(dy) ? 0 : dx < 0 ? 1 : -1)\n\n/** A key's step: the right arrow moves to the next photo, the left arrow to the previous one. */\nexport const keyStep = (key: string) => (key === 'ArrowRight' ? 1 : key === 'ArrowLeft' ? -1 : 0)\n\n/** The photo a step from `index` lands on among `count`: it stops at the first and the last rather than wrapping around. */\nexport const steppedPhoto = (index: number, by: number, count: number) => Math.min(Math.max(index + by, 0), Math.max(count - 1, 0))\n\n/** Whether a key press toggles a photo's details: `i` alone, without Ctrl, Cmd or Alt, which belong to the browser. */\nexport const togglesDetails = (event: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }) => event.key === 'i' && !event.ctrlKey && !event.metaKey && !event.altKey\n","import { guarded } from '../../lib/guarded'\n\n/** Where this browser remembers whether the lightbox opens with a photo's details shown. */\nexport const detailsOpenStorageKey = 'protobase:lightbox-details'\n\n/** Whether the lightbox's details were left open in this browser; closed until someone opens them. */\nexport const readDetailsOpen = (storage: Pick<Storage, 'getItem'>) => guarded(() => storage.getItem(detailsOpenStorageKey) === 'true', false)\n\n/** Remembers only open details, so the default (closed) costs no storage. */\nexport const writeDetailsOpen = (storage: Pick<Storage, 'setItem' | 'removeItem'>, open: boolean) =>\n guarded(() => (open ? storage.setItem(detailsOpenStorageKey, 'true') : storage.removeItem(detailsOpenStorageKey)), undefined)\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/gallery')\n","import { ChevronLeft, ChevronRight, Info, X } from 'lucide-react'\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '../../lib/cn'\nimport { useFocusTrap } from '../../lib/use-focus-trap'\nimport { useIsDesktop } from '../../lib/use-media-query'\nimport { FileImage } from '../../live/file-image'\nimport { shownImage } from '../../live/file-values'\nimport { Sheet } from '../../primitives/sheet'\nimport { readDetailsOpen, writeDetailsOpen } from './details-open-storage'\nimport { keyStep, steppedPhoto, swipeStep, togglesDetails } from './gallery-layout'\nimport { text } from './messages'\n\nexport type LightboxProps = {\n /** The dialog's accessible name, such as the gallery's title. */\n title: string\n /** The photos' files, in order. */\n photos: readonly unknown[]\n /** The photo shown. */\n index: number\n onIndex: (index: number) => void\n onClose: () => void\n /**\n * The details of the photo at a position, which the info button shows in a sidebar beside it, or in a sheet over the\n * lower part of a mobile screen; `undefined` where the photo has none the user may read, which leaves out the button.\n */\n details?: (index: number) => ReactNode | undefined\n /** The details' heading and the info button's name, such as \"Photo details\". */\n detailsTitle?: string\n}\n\nconst control =\n 'flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40'\n\n/**\n * Photos one at a time at full size over the page: a modal dialog with a counter, arrows and keys (left, right, Escape)\n * that step through them, stopping at the first and the last, and a sideways swipe on a touch screen. For a photo with\n * details the user may read, an info button, or the `i` key, shows them in a sidebar beside it, or in a sheet over the\n * lower part of a mobile screen; this browser remembers whether they were left shown. The page does not scroll behind\n * it, and focus returns to what opened it.\n */\nexport const Lightbox = ({ title, photos, index, onIndex, onClose, details, detailsTitle = text('details') }: LightboxProps) => {\n const panel = useRef<HTMLDivElement>(null)\n const start = useRef<{ x: number; y: number }>(undefined)\n const sidebarId = useId()\n const desktop = useIsDesktop()\n const [detailsOpen, setDetailsOpen] = useState(() => readDetailsOpen(localStorage))\n // The sheet waits for the dialog's own focus trap, so the sheet's is the one on top, which Escape closes first\n const [trapped, setTrapped] = useState(false)\n useFocusTrap(panel, true, onClose)\n useEffect(() => setTrapped(true), [])\n const count = photos.length\n // At an end the arrow stays focusable, so the keys keep working, and does nothing\n const step = (by: number) => {\n const next = steppedPhoto(index, by, count)\n if (next !== index) onIndex(next)\n }\n const image = shownImage(photos[index], { width: 1600, height: 1200 })\n const shownDetails = details?.(index)\n const hasDetails = shownDetails !== undefined\n const toggleDetails = (open: boolean) => {\n setDetailsOpen(open)\n writeDetailsOpen(localStorage, open)\n }\n\n const key = (event: KeyboardEvent) => {\n if (hasDetails && togglesDetails(event)) {\n event.preventDefault()\n return toggleDetails(!detailsOpen)\n }\n const by = keyStep(event.key)\n if (by === 0) return\n event.preventDefault()\n step(by)\n }\n const down = (event: PointerEvent) => {\n if (event.pointerType === 'touch') start.current = { x: event.clientX, y: event.clientY }\n }\n const up = (event: PointerEvent) => {\n if (!start.current) return\n step(swipeStep(event.clientX - start.current.x, event.clientY - start.current.y))\n start.current = undefined\n }\n\n // The dialog is the page while it is open: it scrolls to details taller than the screen, with the photo kept in view\n return (\n <div ref={panel} tabIndex={-1} role=\"dialog\" aria-modal=\"true\" aria-label={title} onKeyDown={key} className=\"fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop pl-[var(--pb-safe-left)] pr-[var(--pb-safe-right)] outline-none md:flex-row\">\n <div className=\"flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1\">\n <div className=\"flex shrink-0 items-center justify-between gap-2 p-3 pt-[calc(0.75rem+var(--pb-safe-top))]\">\n <span className=\"rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground\" aria-live=\"polite\">\n {`${index + 1} / ${count}`}\n </span>\n <div className=\"flex items-center gap-2\">\n {hasDetails && (\n <button\n type=\"button\"\n className={cn(control, 'aria-expanded:bg-foreground aria-expanded:text-background')}\n aria-label={detailsTitle}\n aria-expanded={detailsOpen}\n aria-controls={desktop ? sidebarId : undefined}\n aria-keyshortcuts=\"i\"\n onClick={() => toggleDetails(!detailsOpen)}\n >\n <Info className=\"size-4\" aria-hidden />\n </button>\n )}\n <button type=\"button\" className={control} aria-label={text('close')} onClick={onClose}>\n <X className=\"size-4\" aria-hidden />\n </button>\n </div>\n </div>\n <div className=\"relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-[calc(0.75rem+var(--pb-safe-bottom))] md:px-16\" onPointerDown={down} onPointerUp={up} onPointerCancel={() => (start.current = undefined)}>\n {image && <FileImage key={image.url} image={image} className=\"max-h-full max-w-full select-none object-contain\" />}\n {count > 1 && (\n <>\n <button type=\"button\" className={cn(control, 'absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40')} aria-label={text('previousPhoto')} aria-disabled={index === 0} onClick={() => step(-1)}>\n <ChevronLeft className=\"size-5\" aria-hidden />\n </button>\n <button type=\"button\" className={cn(control, 'absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40')} aria-label={text('nextPhoto')} aria-disabled={index === count - 1} onClick={() => step(1)}>\n <ChevronRight className=\"size-5\" aria-hidden />\n </button>\n </>\n )}\n </div>\n </div>\n {hasDetails && detailsOpen && desktop && (\n <aside id={sidebarId} aria-label={detailsTitle} className=\"min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 pt-[calc(1.25rem+var(--pb-safe-top))] text-foreground\">\n <h2 className=\"mb-3 text-base font-semibold\">{detailsTitle}</h2>\n {shownDetails}\n </aside>\n )}\n <Sheet title={detailsTitle} open={hasDetails && detailsOpen && !desktop && trapped} onClose={() => toggleDetails(false)}>\n <div className=\"pt-3\">{shownDetails}</div>\n </Sheet>\n </div>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\nimport { whenShown } from '../record-mode/record-mode'\n\n/**\n * The fields of a photo's details: those its record page shows in its sections, or without a layout every field but its\n * key and tenant, less sensitive ones, those meant only for its form and those the gallery already shows: `omit`, such as the photo's file and the\n * field pointing at the gallery's record.\n */\nexport const detailFields = (model: ResourceModel, view: ViewModel | undefined, omit: readonly string[]) => {\n const sections = layoutItems(view?.layout ?? []).flatMap((item) => (item.kind === 'section' && whenShown(item.when, false) ? item.fields : []))\n const names = sections.length > 0 ? [...new Set(sections)] : Object.keys(model.fields).filter((name) => name !== model.tenant && !model.primaryKey.includes(name))\n return names.filter((name) => model.fields[name] && !model.fields[name].sensitive && !omit.includes(name) && whenShown(view?.fields[name]?.when, false))\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useRecord } from '../../data/use-record'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SpecTable } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { FieldValue } from '../pages/field-value'\nimport { fieldAccess } from '../permissions'\nimport { AppLink } from '../use-app-address'\nimport { text } from './messages'\n\n/**\n * A photo's record, as the record API answers the user, so the server decides what they may read: its `fields` (see\n * `detailFields`), as label/value rows, and a link to its page.\n */\nexport const PhotoDetails = ({ model, view, photoKey, fields }: { model: ResourceModel; view: ViewModel | undefined; photoKey: string; fields: readonly string[] }) => {\n const record = useRecord(model.name, photoKey)\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n if (record.isPending) return <Skeleton className=\"h-4 w-48\" />\n if (record.error) return <ErrorBanner title={text('couldNotLoadOne', { singular })} error={record.error} />\n const shown = fields.filter((name) => fieldAccess(record.data.permissions, name) !== 'hidden')\n return (\n <>\n <SpecTable rows={shown.map((name) => ({ label: view?.fields[name]?.label ?? humanize(name), value: <FieldValue model={model} field={model.fields[name]!} value={record.data.record[name]} /> }))} />\n <AppLink to={{ kind: 'record', resource: model.name, key: photoKey }} className=\"mt-3 inline-block font-medium text-primary-text hover:underline\">\n {text('open', { singular })}\n </AppLink>\n </>\n )\n}\n","import type { KeyValue, ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { isStoredFile, shownImage } from '../../live/file-values'\n\n/** A photo of a gallery: its file, and the record holding it by its key in the record API's text form, when one does. */\nexport type GalleryItem = { file: unknown; key?: string }\n\n/** The most photo records a gallery reads: the list API's largest page. */\nexport const galleryPhotoLimit = 500\n\n// A file the gallery can draw: an image with a link, not a missing file or a document.\nconst isPicture = (value: unknown) => shownImage(value, { width: 0, height: 0 }) !== undefined\n\n// A row's key in the record API's text form, or none when the caller cannot read every part of it.\nconst keyOf = (holder: ResourceModel, row: Record<string, unknown>) => {\n const parts = holder.primaryKey.map((name) => row[name])\n if (parts.some((part) => part === null || part === undefined)) return undefined\n return encodeKey(parts as KeyValue[])\n}\n\n/**\n * The photos a gallery steps through: the record's own `cover` first, then the `image` of each of the photo records\n * `rows`, less the one the cover already shows, whose record the cover takes; empty values, missing files and files\n * that are no image are left out.\n */\nexport const galleryItems = (cover: unknown, rows: ReadonlyArray<Record<string, unknown>>, image: string | undefined, holder: ResourceModel | undefined): GalleryItem[] => {\n const photos = image === undefined ? [] : rows.flatMap((row): GalleryItem[] => {\n const file = row[image]\n if (!isStoredFile(file) || !isPicture(file)) return []\n const key = holder && keyOf(holder, row)\n return [{ file, ...(key !== undefined && { key }) }]\n })\n if (!isStoredFile(cover) || !isPicture(cover)) return photos\n const same = (item: GalleryItem) => isStoredFile(item.file) && item.file.uri === cover.uri\n const key = photos.find(same)?.key\n return [{ file: cover, ...(key !== undefined && { key }) }, ...photos.filter((item) => !same(item))]\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { createWhere, printFilter, type GalleryModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { galleryItems, galleryPhotoLimit } from './gallery-items'\n\nconst where = createWhere()\n\n/**\n * A gallery's photos: the record's own image, then the photo records that point at it, read with the list API under\n * the user's own access, so its row filters and readable fields apply. Without the photos' resource in `/meta`, the\n * user cannot list them, and the record's image is all there is.\n */\nexport const useGalleryPhotos = (item: GalleryModel, record: Record<string, unknown>, recordKey: string) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const holder = item.photos ? resources[item.photos.resource] : undefined\n const filter = item.photos ? printFilter(where.eq(item.photos.field, recordKey)) : ''\n const sort = item.photos?.sort ?? ''\n const rows = useQuery({\n queryKey: keys.list(holder?.name ?? '', filter, sort, galleryPhotoLimit, 'gallery'),\n enabled: holder !== undefined,\n queryFn: async () => (await client.list(holder!.name, { filter, ...(sort && { orderBy: sort }), pageSize: galleryPhotoLimit })).items,\n })\n const cover = item.image === undefined ? undefined : record[item.image]\n return {\n holder,\n items: galleryItems(cover, rows.data ?? [], item.photos?.image, holder),\n isPending: holder !== undefined && rows.isPending,\n error: rows.error,\n }\n}\n","import { Images } from 'lucide-react'\nimport { useState } from 'react'\nimport type { GalleryModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { FileImage } from '../../live/file-image'\nimport { humanize } from '../../live/naming'\nimport { shownImage } from '../../live/file-values'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { galleryTiles } from './gallery-layout'\nimport { Lightbox } from './lightbox'\nimport { detailFields } from './detail-fields'\nimport { PhotoDetails } from './photo-details'\nimport { useGalleryPhotos } from './use-gallery-photos'\nimport { text } from './messages'\n\n// Where each tile sits from md up, by how many are drawn: the first large over two rows, the rest beside it. On a mobile\n// screen only the first is drawn, across the whole gallery.\nconst spans: Record<number, string[]> = {\n 1: ['md:col-span-4 md:row-span-2'],\n 2: ['md:col-span-2 md:row-span-2', 'md:col-span-2 md:row-span-2'],\n 3: ['md:col-span-2 md:row-span-2', 'md:col-span-2', 'md:col-span-2'],\n 5: ['md:col-span-2 md:row-span-2', '', '', '', ''],\n}\n\nconst Tile = ({ photo, large }: { photo: unknown; large: boolean }) => {\n const image = shownImage(photo, large ? { width: 960, height: 720 } : { width: 480, height: 360 })\n return image ? <FileImage image={image} loading=\"lazy\" className=\"size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]\" /> : null\n}\n\n/**\n * A record's photos as tiles, one large and the next ones smaller, the last counting those not drawn (\"+N\"); a mobile\n * screen draws the large one with the number of photos. Each tile opens the lightbox at its photo. A photo held by a\n * record of a resource the user may read has its details beside it there, as the record API answers them. A record\n * without photos has no gallery.\n */\nexport const GallerySection = ({ item, record, recordKey }: { item: GalleryModel; record: Record<string, unknown>; recordKey: string }) => {\n const { views } = useAdminMeta()\n const photos = useGalleryPhotos(item, record, recordKey)\n const photoPermissions = usePermissions(photos.holder?.name ?? '')\n const [open, setOpen] = useState<number>()\n if (photos.isPending) return <Section title={item.title}><Skeleton className=\"aspect-[4/3] w-full rounded-lg md:aspect-[2/1]\" /></Section>\n if (photos.error) return <Section title={item.title}><ErrorBanner title={text('couldNotLoad')} error={photos.error} /></Section>\n const count = photos.items.length\n if (count === 0) return null\n const { shown, more } = galleryTiles(count)\n const holder = photos.holder\n const holderView = holder && views[holder.name]\n // Reading a photo's record is the user's to do: its resource is in their `/meta`, readable, and they can read its key.\n // Its file and the field pointing here are what the lightbox and this page show already.\n const fields = holder ? detailFields(holder, holderView, [item.photos?.image, item.photos?.field].filter((name) => name !== undefined)) : []\n const readable = holder !== undefined && photoPermissions.read !== false && fields.length > 0\n const details = (index: number) => {\n const key = photos.items[index]?.key\n return readable && key !== undefined ? <PhotoDetails key={key} model={holder} view={holderView} photoKey={key} fields={fields} /> : undefined\n }\n\n return (\n <Section title={item.title}>\n <div className=\"grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]\">\n {photos.items.slice(0, shown).map((photo, index) => {\n const last = index === shown - 1 && more > 0\n return (\n <button\n key={index}\n type=\"button\"\n aria-label={last ? text('showAll', { count }) : text('showPhoto', { index: index + 1, count })}\n onClick={() => setOpen(index)}\n className={cn(\n 'group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',\n index === 0 ? 'col-span-4 row-span-2' : 'max-md:hidden',\n spans[shown]![index],\n )}\n >\n <Tile photo={photo.file} large={index === 0} />\n {last && <span className=\"absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white\" aria-hidden>{`+${more}`}</span>}\n {index === 0 && count > 1 && (\n <span className=\"absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden\" aria-hidden>\n <Images className=\"size-3.5\" />\n {count}\n </span>\n )}\n </button>\n )\n })}\n </div>\n {open !== undefined && (\n <Lightbox\n title={item.title}\n photos={photos.items.map((photo) => photo.file)}\n index={open}\n onIndex={setOpen}\n onClose={() => setOpen(undefined)}\n details={details}\n detailsTitle={holder && text('holderDetails', { singular: holderView?.names?.singular ?? humanize(holder.name) })}\n />\n )}\n </Section>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/history')\n","import type { HistoryChange } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { humanize } from '../../live/naming'\nimport { text } from './messages'\n\n/** A field an update changed: its values as the list shows them, none for a sensitive field, whose values are never kept. */\nexport type ChangedField = { name: string; label: string; before?: string; after?: string }\n\nexport type DescribedChange = { who: string; verb: string; fields: ChangedField[] }\n\n/** Who made a change: their name, else their id; a write from outside the app names the database role. */\nexport const changedBy = (change: HistoryChange) => {\n if (change.actor) return change.actor.name ?? change.actor.id\n return change.databaseRole ? text('databaseRole', { role: change.databaseRole }) : text('database')\n}\n\n/**\n * A change as the record page tells it: who, what they did, and for an update each changed field the model still has,\n * before and after, as the view labels and formats it.\n */\nexport const describeChange = (change: HistoryChange, model: ResourceModel, view?: ViewModel): DescribedChange => {\n const fields = (change.operation === 'create' ? [] : change.changed).flatMap((name): ChangedField[] => {\n const field = model.fields[name]\n if (!field || name === model.softDelete) return []\n const hints = view?.fields[name]\n const label = hints?.label ?? humanize(name)\n if (field.sensitive || !change.before || !change.after) return [{ name, label }]\n return [{ name, label, before: displayValue(field, change.before[name], hints), after: displayValue(field, change.after[name], hints) }]\n })\n // An update of only fields the record page does not show, such as one gone from the model, is still a change\n const verb = change.operation === 'update' && fields.length === 0 ? text('changedThis') : text(change.operation)\n return { who: changedBy(change), verb, fields }\n}\n","import { useEffect } from 'react'\nimport { useInfiniteQuery } from '@tanstack/react-query'\nimport type { HistoryPage } from '@protobase/client'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\n/** How long after a save the history looks again: the server keeps a change just after its write commits. */\nconst afterSave = 1500\n\n/**\n * A record's changes, newest first, `pageSize` at a time. Its key starts with the record's, so refreshing the record\n * refreshes it too; it looks again shortly after `etag` changes, once the server has kept the save.\n */\nexport const useRecordHistory = (resource: string, recordKey: string, pageSize: number, etag: string) => {\n const client = useClient()\n const query = useInfiniteQuery({\n queryKey: keys.history(resource, recordKey, pageSize),\n initialPageParam: '',\n queryFn: ({ pageParam }): Promise<HistoryPage> => client.history(resource, recordKey, { pageSize, pageToken: pageParam }),\n getNextPageParam: (last) => last.nextPageToken || undefined,\n })\n const { refetch } = query\n useEffect(() => {\n const timer = setTimeout(() => void refetch(), afterSave)\n return () => clearTimeout(timer)\n }, [etag, refetch])\n return { ...query, items: query.data?.pages.flatMap((page) => page.items) ?? [] }\n}\n","import type { HistoryChange } from '@protobase/client'\nimport type { HistorySectionModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { formatDateTime, formatRelativeTime } from '../../format/date'\nimport { Button } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { describeChange } from './describe-change'\nimport { useRecordHistory } from './use-record-history'\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\nconst Change = ({ change, model, view }: { change: HistoryChange; model: ResourceModel; view?: ViewModel }) => {\n const { who, verb, fields } = describeChange(change, model, view)\n const at = Date.parse(change.at)\n return (\n <li className=\"flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0\">\n <p>\n <span className=\"font-medium text-foreground\">{who}</span> <span className=\"text-muted-foreground\">{verb}</span>{' '}\n <time dateTime={change.at} title={formatDateTime(at)} className=\"text-muted-foreground\">\n · {formatRelativeTime(Math.max(0, Math.round((Date.now() - at) / 1000)))}\n </time>\n </p>\n {fields.length > 0 && (\n <dl className=\"grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1\">\n {fields.map((field) => (\n <div key={field.name} className=\"contents\">\n <dt className=\"text-muted-foreground\">{field.label}</dt>\n <dd className=\"min-w-0 break-words\">\n {field.before === undefined ? (\n <span className=\"text-muted-foreground\">changed</span>\n ) : (\n <>\n <del className=\"text-muted-foreground\">{field.before}</del> → <ins className=\"no-underline\">{field.after}</ins>\n </>\n )}\n </dd>\n </div>\n ))}\n </dl>\n )}\n </li>\n )\n}\n\n/** The record's changes, newest first, with who made each and the fields before and after; Show more pages further back. */\nexport const HistorySection = ({ item, model, view, recordKey, etag }: { item: HistorySectionModel; model: ResourceModel; view?: ViewModel; recordKey: string; etag: string }) => {\n const history = useRecordHistory(model.name, recordKey, item.limit ?? 10, etag)\n return (\n <Section title={item.title}>\n {history.isPending ? (\n <Loading />\n ) : history.error ? (\n <ErrorBanner title=\"Could not load the history\" error={history.error} />\n ) : history.items.length === 0 ? (\n <p className=\"text-muted-foreground\">No changes kept yet.</p>\n ) : (\n <>\n <ol className=\"divide-y divide-border\">\n {history.items.map((change) => <Change key={change.id} change={change} model={model} view={view} />)}\n </ol>\n {history.hasNextPage && (\n <Button size=\"sm\" className=\"mt-4\" disabled={history.isFetchingNextPage} onClick={() => void history.fetchNextPage()}>\n Show more\n </Button>\n )}\n </>\n )}\n </Section>\n )\n}\n","import type { RecordComment } from '@protobase/client'\nimport { MentionedText } from '../../mentions'\n\n/** A comment's text as written, line breaks kept, each `@{name}` of someone it mentions picked out. */\nexport const CommentBody = ({ comment }: { comment: RecordComment }) => <MentionedText text={comment.body} mentions={comment.mentions} />\n","import { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\n/** Posts a comment on the record, then loads its comments again so the new one shows. */\nexport const usePostComment = (resource: string, recordKey: string) => {\n const client = useClient()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (input: { body: string; mentions: string[] }) => client.comment(resource, recordKey, input),\n onSuccess: () => queryClient.invalidateQueries({ queryKey: keys.comments(resource, recordKey) }),\n })\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/comments')\n","import { useCallback, useState, type KeyboardEvent } from 'react'\nimport { useClient } from '../../data/api-provider'\nimport { emptyDraft, MentionBox, mentionedIds, type MentionDraft } from '../../mentions'\nimport { Button } from '../../primitives/button'\nimport { useToast } from '../../toasts/toast-provider'\nimport { useNavigationGuard } from '../router'\nimport { refusalReason } from '../displays/board-columns'\nimport { usePostComment } from './use-post-comment'\nimport { text } from './messages'\n\n/**\n * The box a comment is written in. Typing `@` lists the people who may read the record by the name typed after it\n * (see `MentionBox`). ⌘/Ctrl+Enter or the button posts.\n */\nexport const CommentComposer = ({ resource, recordKey }: { resource: string; recordKey: string }) => {\n const [draft, setDraft] = useState<MentionDraft>(emptyDraft)\n const client = useClient()\n const toast = useToast()\n const post = usePostComment(resource, recordKey)\n const searchPeople = useCallback((query: string) => client.mentionable(resource, recordKey, query), [client, resource, recordKey])\n // A comment being written, or posted, is gone when the page is left\n useNavigationGuard(draft.text.trim() !== '' || post.isPending, 'input-lost')\n\n const submit = () => {\n if (draft.text.trim() === '' || post.isPending) return\n post.mutate(\n { body: draft.text, mentions: mentionedIds(draft.text, draft.picked) },\n {\n onSuccess: () => setDraft(emptyDraft),\n onError: (error) => toast.show({ state: 'error', title: text('couldNotPost'), description: refusalReason(error) }),\n },\n )\n }\n\n const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey)) return\n event.preventDefault()\n submit()\n }\n\n return (\n <div className=\"flex flex-col gap-2\">\n <MentionBox aria-label={text('comment')} placeholder={text('placeholder')} value={draft} onChange={setDraft} searchPeople={searchPeople} onKeyDown={onKeyDown} />\n <div>\n <Button variant=\"primary\" size=\"sm\" disabled={draft.text.trim() === ''} loading={post.isPending} onClick={submit}>\n {text('comment')}\n </Button>\n </div>\n </div>\n )\n}\n","import { useInfiniteQuery } from '@tanstack/react-query'\nimport type { CommentPage } from '@protobase/client'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\nconst pageSize = 20\n\n/** A record's comments, oldest first: the newest page, then each earlier one `fetchNextPage` loads, at the top. */\nexport const useRecordComments = (resource: string, recordKey: string) => {\n const client = useClient()\n const query = useInfiniteQuery({\n queryKey: keys.comments(resource, recordKey),\n initialPageParam: '',\n queryFn: ({ pageParam }): Promise<CommentPage> => client.comments(resource, recordKey, { pageSize, pageToken: pageParam }),\n getNextPageParam: (last) => last.nextPageToken || undefined,\n })\n return { ...query, items: query.data?.pages.flatMap((page) => page.items).reverse() ?? [] }\n}\n","import type { RecordComment } from '@protobase/client'\nimport type { CommentsSectionModel } from '@protobase/schema'\nimport { hueOf, initialsOf } from '../../auth/user-to-shell'\nimport { formatDateTime, formatRelativeTime } from '../../format/date'\nimport { Avatar } from '../../primitives/avatar'\nimport { Button } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { CommentBody } from './comment-body'\nimport { CommentComposer } from './comment-composer'\nimport { useRecordComments } from './use-record-comments'\nimport { text } from './messages'\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\nconst Comment = ({ comment }: { comment: RecordComment }) => {\n const author = comment.author.name ?? comment.author.id\n const at = Date.parse(comment.createdAt)\n return (\n <li className=\"flex gap-3 py-3 first:pt-0 last:pb-0\">\n <Avatar initials={initialsOf(author) || '?'} hue={hueOf(comment.author.id)} size=\"md\" className=\"ring-0\" />\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <p>\n <span className=\"font-medium text-foreground\">{author}</span>{' '}\n <time dateTime={comment.createdAt} title={formatDateTime(at)} className=\"text-muted-foreground\">\n · {formatRelativeTime(Math.max(0, Math.round((Date.now() - at) / 1000)))}\n </time>\n </p>\n <CommentBody comment={comment} />\n </div>\n </li>\n )\n}\n\n/**\n * The record's comments, oldest first with the newest just above the box, and Show earlier comments for those before;\n * `canWrite` false, for a visitor who is not signed in, leaves out the box.\n */\nexport const CommentsSection = ({ item, resource, recordKey, canWrite }: { item: CommentsSectionModel; resource: string; recordKey: string; canWrite: boolean }) => {\n const comments = useRecordComments(resource, recordKey)\n return (\n <Section title={item.title}>\n {comments.isPending ? (\n <Loading />\n ) : comments.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={comments.error} />\n ) : (\n <>\n {comments.hasNextPage && (\n <Button size=\"sm\" className=\"mb-4\" disabled={comments.isFetchingNextPage} onClick={() => void comments.fetchNextPage()}>\n {text('showEarlier')}\n </Button>\n )}\n {comments.items.length === 0 ? (\n <p className=\"text-muted-foreground\">{text('noComments')}</p>\n ) : (\n <ol className=\"divide-y divide-border\">\n {comments.items.map((comment) => <Comment key={comment.id} comment={comment} />)}\n </ol>\n )}\n </>\n )}\n {canWrite && (\n <div className=\"mt-4\">\n <CommentComposer resource={resource} recordKey={recordKey} />\n </div>\n )}\n </Section>\n )\n}\n","import { isRecordCondition, type CustomSectionModel, type LayoutItemModel } from '@protobase/schema'\nimport { whenShown } from './record-mode'\n\n// A custom section's fallback holds items with conditions of their own, as a tab or group does\nconst innerItems = (item: LayoutItemModel): LayoutItemModel[] => {\n if (item.kind === 'group' || item.kind === 'tab') return item.items\n if (item.kind === 'custom') return item.fallback ?? []\n return []\n}\n\n// A tab has no condition: it shows while any of its items does.\nexport const whenOf = (item: LayoutItemModel) => (item.kind === 'tab' ? undefined : item.when)\n\n/** The items with a record condition in `when`, those inside tabs, groups and fallbacks too, whose conditions the page evaluates: a group before its items. */\nexport const conditionalItems = (items: LayoutItemModel[]): LayoutItemModel[] =>\n items.flatMap((item) => [item, ...conditionalItems(innerItems(item))]).filter((item) => isRecordCondition(whenOf(item)))\n\n/** A shown custom section: `fallbackAt` holds each shown fallback item's place in the whole fallback. */\ntype ShownCustom = CustomSectionModel & { fallbackAt?: number[] }\n\n/** A shown custom section's fallback items, each with its place in the whole fallback, which stays as siblings hide and show. */\nexport const fallbackEntries = (item: ShownCustom) => (item.fallback ?? []).map((entry, index) => [entry, item.fallbackAt?.[index] ?? index] as const)\n\n/**\n * The items that show: those with a record condition only when it holds (`held`, one answer per conditional item in\n * the order `conditionalItems` lists them, `undefined` while loading) and the page is no preview; the others by the\n * form or read view. A tab or group keeps the items inside it that show, and goes when it or all of them do not; a\n * custom section keeps the fallback items that show, `[]` when none does, so it then falls back to nothing, and their\n * places in the whole fallback for `fallbackEntries`.\n */\nexport const shownLayout = (items: LayoutItemModel[], held: Array<boolean | undefined>, editing: boolean, preview: boolean) => {\n let next = 0\n const shown = (item: LayoutItemModel) => {\n const when = whenOf(item)\n return isRecordCondition(when) ? !preview && held[next++] === true : whenShown(when, editing)\n }\n const keep = (list: LayoutItemModel[]): LayoutItemModel[] =>\n list.flatMap((item) => {\n const itself = shown(item)\n if (item.kind === 'custom' && item.fallback) {\n const kept = item.fallback.map((entry) => keep([entry]))\n const fallbackAt = kept.flatMap((entry, index) => (entry.length > 0 ? [index] : []))\n return itself ? [{ ...item, fallback: kept.flat(), fallbackAt } as LayoutItemModel] : []\n }\n if (item.kind !== 'group' && item.kind !== 'tab') return itself ? [item] : []\n const inner = keep(item.items)\n return itself && inner.length > 0 ? [{ ...item, items: inner } as LayoutItemModel] : []\n })\n return keep(items)\n}\n","import type { LayoutItemModel } from '@protobase/schema'\nimport { useConditions } from '../pages/use-conditions'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { conditionalItems, shownLayout, whenOf } from './shown-layout'\n\n/**\n * The layout items to draw: those meant for the form or the read view as the page is, and those with a record\n * condition while it holds for the saved record. Conditional items stay out while their values load and on a preview.\n */\nexport const useShownLayout = (items: LayoutItemModel[], scope: LayoutRecord, editing: boolean, preview: boolean) => {\n const conditions = preview ? [] : conditionalItems(items).map((item) => whenOf(item) as string)\n const held = useConditions(conditions, scope)\n return shownLayout(items, held, editing, preview)\n}\n","import { createWhere, printFilter, type ResourceModel } from '@protobase/schema'\n\nconst w = createWhere()\n\n/**\n * The list request that finds a record the session's organization does not have, and the organization it is in: for a\n * resource whose lists read across the person's organizations (`tenantAcross`), with a key of one field they can\n * filter on. `undefined` for any other resource, whose record is simply not found.\n */\nexport const elsewhereRequest = (model: ResourceModel, recordKey: string) => {\n const [key, ...more] = model.primaryKey\n if (!model.tenantAcross || model.tenant === undefined || key === undefined || more.length > 0 || !model.fields[key]?.filterable) return undefined\n return { filter: printFilter(w.eq(key, recordKey)), pageSize: 1, fields: [key, model.tenant] }\n}\n\n/** The organization a found row is in, when it is another than `current`; `undefined` when it is not found or is there. */\nexport const otherOrganization = (model: ResourceModel, row: Record<string, unknown> | undefined, current: string | undefined) => {\n const tenant = row?.[model.tenant!]\n if (tenant === undefined || tenant === null || String(tenant) === current) return undefined\n return String(tenant)\n}\n","import { useEffect, useMemo, useState } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useAuth } from '../auth'\nimport { useClient } from '../data/api-provider'\nimport { elsewhereRequest, otherOrganization } from './record-elsewhere'\n\nexport type RecordElsewhere = { state: 'looking' } | { state: 'switching' } | { state: 'missing' } | { state: 'failed'; error: unknown }\n\n/**\n * For a record not found in the session's organization: looks for it across the person's organizations, and when it is\n * in another one, switches the session there and opens the page again, so the record and everything on its page are\n * read in its own organization. `missing` when it is nowhere else, or the resource does not list across organizations.\n */\nexport const useRecordElsewhere = (model: ResourceModel, recordKey: string): RecordElsewhere => {\n const client = useClient()\n const { session, organizations } = useAuth()\n const request = useMemo(() => (organizations ? elsewhereRequest(model, recordKey) : undefined), [organizations, model, recordKey])\n const [found, setFound] = useState<RecordElsewhere>(request ? { state: 'looking' } : { state: 'missing' })\n useEffect(() => {\n if (!request) return\n const look = async () => {\n const [page, current] = await Promise.all([client.list(model.name, request), session.organizations.current()])\n const other = otherOrganization(model, page.items[0], current.organization?.id)\n if (other === undefined) return setFound({ state: 'missing' })\n setFound({ state: 'switching' })\n await session.organizations.switchTo(other)\n window.location.reload()\n }\n look().catch((error: unknown) => setFound({ state: 'failed', error }))\n }, [client, session, model, request])\n return found\n}\n","import { useQueries, useQueryClient } from '@tanstack/react-query'\nimport type { AppAddress, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { relationTitle, relationTitleQuery } from './titles/relation-title'\nimport { useRecordTitle } from './titles/record-titles'\n\n/** Per relation the record holds, the address and name of the record it points at, derived for the reader where its view does. The tenant is left out. */\nexport const useRelatedRecords = (model: ResourceModel, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, record: Record<string, unknown>) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const titleOf = useRecordTitle()\n const relations = Object.values(model.fields).filter(\n (field) => field.type === 'relation' && field.relation && field.name !== model.tenant && record[field.name] != null && resources[field.relation.resource]?.primaryKey.length === 1,\n )\n const labels = useQueries({\n queries: relations.map((field) => {\n const target = resources[field.relation!.resource]!\n return relationTitleQuery(queryClient, client, target, views[target.name], String(record[field.name]))\n }),\n })\n const addresses = relations.map((field): AppAddress => ({ kind: 'record', resource: field.relation!.resource, key: String(record[field.name]) }))\n return {\n addresses: Object.fromEntries(relations.map((field, index) => [field.name, addresses[index]!])),\n labels: Object.fromEntries(\n relations.map((field, index) => {\n const target = resources[field.relation!.resource]!\n return [field.name, relationTitle(labels[index]?.data, titleOf, target, views[target.name], String(record[field.name]))]\n }),\n ),\n }\n}\n","import { createWhere, printFilter, type AppAddress, type LayoutItemModel, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { humanize } from '../live/naming'\n\nconst where = createWhere()\n\n/** A resource whose records point at a record through one of its fields, as the record page's rail counts them. */\nexport type IncomingRelation = { resource: string; field: string; label: string }\n\n/**\n * The relations that point at records of `model`, as the rail lists them by default: each filterable relation of\n * another resource the user can see (a hidden resource or field is not in the meta), to a record of one key column.\n * Left out are a resource's tenant, which every record holds, and what an `l.related` section or an `l.thread` of the\n * page already lists, the record's lines included. A custom component's fallback counts only when `registered` says the\n * app has no component of that name, since the page then draws the fallback in its place. Two fields of one resource are\n * told apart by their labels.\n */\nexport const incomingRelations = (\n model: ResourceModel,\n resources: Record<string, ResourceModel>,\n views: Record<string, ViewModel>,\n layout: LayoutItemModel[],\n registered: (component: string) => boolean,\n): IncomingRelation[] => {\n if (model.primaryKey.length !== 1) return []\n const listed = new Set(\n drawnItems(layout, registered).flatMap((item) => {\n if (item.kind === 'thread') return [`${item.resource}.${item.field}`, ...(item.calls ? [`${item.calls.resource}.${item.calls.field}`] : [])]\n return item.kind === 'related' && !item.through && !item.from ? [`${item.resource}.${item.field}`] : []\n }),\n )\n const found = Object.values(resources).flatMap((source) =>\n Object.values(source.fields)\n .filter((field) => field.type === 'relation' && field.relation?.resource === model.name && field.relation.columns.length === 1 && field.filterable)\n .filter((field) => field.name !== source.tenant && !listed.has(`${source.name}.${field.name}`))\n .map((field) => ({ source, field: field.name })),\n )\n return found.map(({ source, field }) => {\n const view = views[source.name]\n const plural = view?.names?.plural ?? humanize(source.name)\n const several = found.filter((other) => other.source.name === source.name).length > 1\n return { resource: source.name, field, label: several ? `${plural} (${view?.fields[field]?.label ?? humanize(field)})` : plural }\n })\n}\n\n// The layout's items the page draws, wherever they sit: a custom item's fallback only when its component is missing\nconst drawnItems = (layout: readonly LayoutItemModel[], registered: (component: string) => boolean): LayoutItemModel[] =>\n layout.flatMap((item) => {\n if (item.kind === 'group' || item.kind === 'tab') return drawnItems(item.items, registered)\n if (item.kind === 'custom' && !registered(item.component)) return [item, ...drawnItems(item.fallback ?? [], registered)]\n return [item]\n })\n\n/** The list of the records that point at `key` through `relation`, filtered as its list's address reads. */\nexport const incomingAddress = (relation: IncomingRelation, key: string): AppAddress => ({ kind: 'list', resource: relation.resource, filter: printFilter(where.eq(relation.field, key)) })\n","import { useQueries } from '@tanstack/react-query'\nimport { printFilter, createWhere, type ResourceModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { keys } from '../data/query-keys'\nimport type { IncomingRelation } from './incoming-relations'\n\nconst where = createWhere()\n\n/** How many records point at `key` through each relation: `undefined` while loading, left out when the list is refused. */\nexport const useIncomingCounts = (relations: IncomingRelation[], resources: Record<string, ResourceModel>, key: string) => {\n const client = useClient()\n const counts = useQueries({\n queries: relations.map((relation) => {\n const filter = printFilter(where.eq(relation.field, key))\n return {\n queryKey: keys.list(relation.resource, filter, '', 1, 'incoming'),\n queryFn: async () => {\n const page = await client.list(relation.resource, { filter, pageSize: 1, count: 'exact', fields: resources[relation.resource]!.primaryKey })\n return { count: page.totalSize ?? page.totalSizeEstimate, exact: page.totalSize !== undefined }\n },\n }\n }),\n })\n return relations.flatMap((relation, index) => {\n const result = counts[index]!\n if (result.error) return []\n return [{ relation, count: result.data }]\n })\n}\n","import { ChevronRight } from 'lucide-react'\nimport type { LayoutItemModel, ResourceModel } from '@protobase/schema'\nimport { formatInt } from '../format/number'\nimport { Skeleton } from '../primitives/skeleton'\nimport { SidebarCard } from '../record-view'\nimport { incomingAddress, incomingRelations } from './incoming-relations'\nimport { useAdminMeta } from './meta-gate'\nimport { useProjectUi } from './pages/project-ui'\nimport { AppLink } from './use-app-address'\nimport { useIncomingCounts } from './use-incoming-counts'\nimport { text } from './record-messages'\n\ntype IncomingCardProps = { model: ResourceModel; recordKey: string; layout: LayoutItemModel[] }\n\n/** The rail's card of the records pointing at this one: per resource and field, how many, linking to them in their list. */\nexport const IncomingCard = ({ model, recordKey, layout }: IncomingCardProps) => {\n const { resources, views } = useAdminMeta()\n const { components } = useProjectUi()\n const relations = incomingRelations(model, resources, views, layout, (component) => Boolean(components?.[component]))\n const counts = useIncomingCounts(relations, resources, recordKey)\n if (counts.length === 0) return null\n return (\n <SidebarCard title={text('relatedRecords')}>\n <ul className=\"-mx-2\">\n {counts.map(({ relation, count }) => (\n <li key={`${relation.resource}.${relation.field}`}>\n <AppLink to={incomingAddress(relation, recordKey)} className=\"group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted\">\n <span className=\"min-w-0 truncate font-medium text-primary-text\">{relation.label}</span>\n <span className=\"flex shrink-0 items-center gap-1 tabular-nums text-muted-foreground\">\n {count === undefined ? <Skeleton className=\"h-4 w-6\" /> : `${formatInt(count.count)}${count.exact ? '' : '+'}`}\n <ChevronRight className=\"size-4 text-faint-foreground group-hover:text-foreground\" />\n </span>\n </AppLink>\n </li>\n ))}\n </ul>\n </SidebarCard>\n )\n}\n","import { formatTag } from '../locale/active-locale'\nimport { cn } from '../lib/cn'\nimport { Badge } from '../primitives/badge'\nimport { Skeleton } from '../primitives/skeleton'\nimport { text } from './messages'\n\n/** What a heading's records are called, to say the count aloud, such as \"2 tasks\"; \"records\" without. */\nexport type CountNames = { singular: string; plural: string }\n\ntype HeadingCountProps = {\n /** `undefined` while it loads, `null` when it could not be counted. */\n count: number | null | undefined\n names?: CountNames\n}\n\n/**\n * How many records a heading stands over, as a quiet pill after its title, 0 as an outline, and to a screen reader a\n * phrase such as \"(2 tasks)\"; a placeholder of its size while unknown, and nothing when it could not be counted.\n */\nexport const HeadingCount = ({ count, names }: HeadingCountProps) => {\n if (count === null) return null\n if (count === undefined) return <Skeleton className=\"inline-block h-5 w-7 rounded-full\" />\n return (\n <>\n <Badge dot={false} className={cn('tabular-nums', count === 0 && 'bg-transparent ring-1 ring-border ring-inset')}>\n <span aria-hidden>{count.toLocaleString(formatTag())}</span>\n </Badge>\n <span className=\"sr-only\">{names ? text('headingCount', { count, ...names }) : text('headingCountRecords', { count })}</span>\n </>\n )\n}\n","import type { ResourcePermissions } from '@protobase/client'\nimport type { RelatedModel, ViewModel } from '@protobase/schema'\nimport { createOffered } from '../create/create-offered'\nimport type { CurrentAddress } from '../current-address'\n\n/**\n * Where a related section starts a record of its resource with `field` filled in with this record's key, to whoever\n * the list would offer New; none through a join resource, whose `field` holds another resource's key, or without a key.\n */\nexport const relatedAdd = (item: RelatedModel, value: string | number | boolean | null, view: ViewModel | undefined, pages: Readonly<Record<string, unknown>>, permissions: ResourcePermissions): CurrentAddress | undefined => {\n if (item.through || value === null) return\n if (!createOffered(view, pages, permissions)) return\n return { kind: 'create', resource: item.resource, values: { [item.field]: String(value) } }\n}\n","import { ArrowRight, Plus } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { buttonClass } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\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 { scopeOf, useListPage } from '../pages/use-layout-data'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport type { CurrentAddress } from '../current-address'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { text } from './messages'\n\ntype RelatedRecordProps = {\n title: string\n help?: string\n /** What shows after the title, such as how many records match. */\n count?: ReactNode\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order that picks the record, the list's own when empty. */\n sort: string\n /** The fields it shows, in full. */\n fields: string[]\n /** A button to an address the record's fields name. */\n button?: RowButtonModel\n empty?: string\n /** Where a record is started while none matches, when the user may create one. */\n add?: CurrentAddress\n}\n\nconst Empty = ({ empty }: { empty: string | undefined }) => <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n\nconst singularOf = (model: ResourceModel, view: ViewModel | undefined) => (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n\n/**\n * A record page section showing the first record a filter finds as part of the page rather than a card: its `fields`\n * in full, under their labels when there are several and alone when there is one, with a link to its own page and\n * `button` on the heading's line, or, while none matches, a link to `add` one. A second record is read only to tell there are more, when \"View all\" opens them.\n */\nexport const RelatedRecord = ({ title, help, count, model, view, filter, sort, fields, button, empty, add }: RelatedRecordProps) => {\n const xs = useIsXs()\n const { resources } = useAdminMeta()\n const orderBy = sort || defaultOrderBy(model, view)\n const page = useListPage(model, { filter, sort: orderBy, pageSize: 2 })\n if (page.isPending) return <Section title={title} help={help} count={count}><Skeleton className=\"h-24 w-full\" /></Section>\n if (page.error) return <Section title={title} help={help} count={count}><ErrorBanner title={text('couldNotLoad')} error={page.error} /></Section>\n const [row, next] = page.data.items\n if (!row) {\n const adding = add && (\n <AppLink to={add} className={buttonClass({ size: 'sm' })}>\n <Plus className=\"size-3.5\" />\n {text('add', { singular: singularOf(model, view) })}\n </AppLink>\n )\n return <Section title={title} help={help} count={count} actions={adding}><Empty empty={empty} /></Section>\n }\n const scope = scopeOf(model, row)\n const singular = singularOf(model, view)\n const plural = view?.names?.plural ?? humanize(model.name)\n const labelled = fields.length > 1\n const shown = fields.map((path) => <RelatedField key={path} scope={scope} path={path} labelled={labelled} />)\n const actions = (\n <div className=\"flex flex-wrap items-center gap-2\">\n {button && <RowButtonLink button={button} model={model} view={view} record={row} models={resources} />}\n <AppLink to={{ kind: 'record', resource: model.name, key: recordKey(model, row) }} className={buttonClass({ size: 'sm' })}>\n {text('open', { singular })}\n </AppLink>\n </div>\n )\n return (\n <Section title={title} help={help} count={count} actions={actions}>\n <div className=\"flex min-w-0 flex-col gap-4\">\n {labelled ? <dl className=\"flex flex-col gap-4\">{shown}</dl> : shown}\n {next && (\n <AppLink to={viewAllAddress(model, view, xs, { filter, orderBy, display: embeddedDisplay(view, xs, {}) })} className=\"flex items-center gap-1 self-start 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 )}\n </div>\n </Section>\n )\n}\n","import { createWhere, parseFilter, printFilter, type RelatedModel, type ResourceModel } from '@protobase/schema'\n\nconst where = createWhere()\n\n// A single condition stays as it is, so the list that \"View all\" opens reads it as its own filter\nconst and = (...parts: Array<string | undefined>) => {\n const given = parts.filter((part): part is string => Boolean(part))\n return given.length === 1 ? given[0]! : given.map((part) => `(${part})`).join(' AND ')\n}\n\n/**\n * The filter on a related section's resource: its `field` is this record's key, or, through a join resource, one of\n * the keys the join records that point at this record hold. `null` without a key, so nothing can match.\n */\nexport const relatedMatch = (item: RelatedModel, value: string | number | boolean | null, resources: Record<string, ResourceModel>) => {\n const { through } = item\n if (value === null) return null\n if (!through) return and(printFilter(where.eq(item.field, value)), item.filter)\n const key = through.key ?? resources[through.resource]?.primaryKey[0]\n const links = parseFilter(and(printFilter(where.eq(through.field, value)), through.filter))\n if (!links.ok || !key) return null\n return and(printFilter(where.related(item.field, through.resource, key, links.ast)), item.filter)\n}\n","import { useQueries } from '@tanstack/react-query'\nimport type { RelatedModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { useAdminMeta } from './meta-gate'\nimport { countQuery } from './pages/use-layout-data'\nimport { relatedMatch } from './related-match'\n\n/** A related section and the value of this record its `field` is matched against. */\nexport type CountedRelated = { item: RelatedModel; value: string | number | boolean | null }\n\n/** What some counts add up to: `null` when one could not be counted, `undefined` while one is still loading. */\nexport const countTotal = (counts: Array<number | null | undefined>) => {\n if (counts.some((count) => count === null)) return null\n if (counts.some((count) => count === undefined)) return\n return counts.reduce<number>((total, count) => total + count!, 0)\n}\n\n/**\n * How many records the reader may see in these related sections together, one count query each, shared with every\n * other count of the same records, so a live change reads them again; `undefined` while one is loading. A section\n * that can match nothing counts 0, and one of a resource the reader cannot list counts nothing; `null` when one fails, so a failure never reads as 0.\n */\nexport const useRelatedCount = (sections: CountedRelated[], enabled = true) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const counted = sections.flatMap(({ item, value }) => {\n const model = resources[item.resource]\n return model ? [{ model, match: relatedMatch(item, value, resources) }] : []\n })\n const queries = useQueries({\n queries: counted.map(({ model, match }) => ({ ...countQuery(client, model, match ?? ''), enabled: enabled && match !== null })),\n })\n return countTotal(\n counted.map(({ match }, index) => {\n if (match === null) return 0\n const query = queries[index]!\n if (query.isError) return null\n // A server that gives neither an exact nor an estimated total has no count to show\n return query.isSuccess ? (query.data ?? null) : undefined\n }),\n )\n}\n","import { useState, type ReactNode } from 'react'\nimport { createWhere, printFilter, type RelatedModel } from '@protobase/schema'\nimport { listColumnNames } from '../live/columns-from-model'\nimport { Section } from '../record-view'\nimport { HeadingCount } from '../record-view/heading-count'\nimport { EmbeddedDisplaySwitch, EmbeddedList } from './embedded-list/embedded-list'\nimport { useEmbeddedDisplay } from './embedded-list/use-embedded-display'\nimport { relatedAdd } from './related-cards/related-add'\nimport { RelatedCards } from './related-cards/related-cards'\nimport { RelatedRecord } from './related-cards/related-record'\nimport { relatedOpens } from './related-opens'\nimport { relatedMatch } from './related-match'\nimport { useRelatedCount } from './related-count'\nimport { relatedHandOrder } from './hand-order/hand-order'\nimport { HandSortedList } from './hand-order/hand-sorted-list'\nimport { ReorderButton } from './hand-order/reorder-button'\nimport { useAdminMeta, usePermissions } from './meta-gate'\nimport { text } from './record-messages'\n\nconst where = createWhere()\n\nconst Empty = ({ empty }: { empty: string | undefined }) => <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n\n/**\n * A record page section listing the first records of another resource that point at this record, directly or through\n * a join resource, in the list page's table or display, or as cards with their actions, with a link to them all in the list,\n * or the first one's fields in full. When they are ordered by\n * hand within this record, **Reorder** shows them all in their order, to be moved by their drag handles.\n */\nexport const RelatedSection = ({ item, value, owner }: { item: RelatedModel; value: string | number | boolean | null; owner: string }) => {\n const { resources, views, pages } = useAdminMeta()\n const model = resources[item.resource]\n const view = model && views[model.name]\n const match = relatedMatch(item, value, resources)\n const [display, pick] = useEmbeddedDisplay(view, `related:${owner}:${item.title}`, item.display)\n const permissions = usePermissions(item.resource)\n const [sorting, setSorting] = useState(false)\n // Only a section that hides while empty or shows its count counts its records\n const count = useRelatedCount([{ item, value }], Boolean(item.hideEmpty || item.count))\n if (!model) return null\n if (item.hideEmpty && (count === undefined || count === 0)) return null\n const heading = { title: item.title, help: item.help, count: item.count ? <HeadingCount count={count} names={view?.names} /> : undefined }\n const opens = relatedOpens(item, model, resources)\n // The relation names this record on every row, so it is left out of the default columns\n const columns = item.columns ?? listColumnNames(model, view).filter((name) => name !== item.field)\n // What it lists, when it can match any record\n const listed = (list: (filter: string) => ReactNode) => (match === null ? <Empty empty={item.empty} /> : list(match))\n if (item.presentation === 'cards' || item.presentation === 'compact') {\n const compact = item.presentation === 'compact' ? { time: item.time } : undefined\n // The time beside a compact card's title is not shown again among its values; the tone's value shows first, so its\n // colour is never all that says it\n const shown = compact ? columns.filter((name) => name !== item.time) : columns\n const values = item.tone === undefined || shown.includes(item.tone) ? shown : [item.tone, ...shown]\n return (\n <Section {...heading}>\n {listed((filter) => <RelatedCards model={model} view={view} filter={filter} sort={item.sort ?? ''} fields={values} actions={item.actions ?? []} button={item.button} limit={item.limit ?? 10} display={item.display} empty={item.empty} compact={compact} tone={item.tone} />)}\n </Section>\n )\n }\n if (item.presentation === 'record') {\n if (match === null) return <Section {...heading}><Empty empty={item.empty} /></Section>\n // A new match starts afresh, so the previous record never shows while its query loads\n return <RelatedRecord key={match} {...heading} model={model} view={view} filter={match} sort={item.sort ?? ''} fields={columns} button={item.button} empty={item.empty} add={relatedAdd(item, value, view, pages, permissions)} />\n }\n const handOrder = relatedHandOrder(item, model, permissions)\n const displaySwitch = <EmbeddedDisplaySwitch view={view} value={display} onChange={pick} />\n const actions = handOrder ? (\n <div className=\"flex items-center gap-2\">\n {!sorting && displaySwitch}\n <ReorderButton size=\"sm\" sorting={sorting} onChange={setSorting} />\n </div>\n ) : (\n displaySwitch\n )\n if (sorting && handOrder) {\n return (\n <Section {...heading} actions={actions}>\n <HandSortedList model={model} view={view} field={handOrder} filter={printFilter(where.eq(item.field, value!))} columns={columns} />\n </Section>\n )\n }\n return (\n <Section {...heading} actions={actions}>\n {listed((filter) => <EmbeddedList key={filter} model={model} view={view} filter={filter} sort={item.sort ?? ''} columns={columns} limit={item.limit ?? 10} display={display} empty={item.empty} opens={opens} button={item.button} />)}\n </Section>\n )\n}\n","import type { RelatedModel } from '@protobase/schema'\nimport { relationTarget } from './related-opens'\n\n/**\n * The value a related section's `field` is matched against: the record's key, or with `from` that field's value as it\n * is (a relation by its key). Null when the record holds none, so the section lists nothing.\n */\nexport const relatedValue = (item: RelatedModel, record: Record<string, unknown>, recordKey: string): string | number | boolean | null => {\n if (item.from === undefined) return recordKey\n const value = record[item.from]\n if (typeof value === 'boolean') return value\n return relationTarget(record, item.from) ?? null\n}\n","import { HeadingCount } from '../record-view/heading-count'\nimport { useAdminMeta } from './meta-gate'\nimport { useRelatedCount, type CountedRelated } from './related-count'\n\n/** How many records a group's related tables hold together, after its heading, named as their records when they are of one resource. */\nexport const GroupCount = ({ sections }: { sections: CountedRelated[] }) => {\n const count = useRelatedCount(sections)\n const { views } = useAdminMeta()\n const resources = new Set(sections.map(({ item }) => item.resource))\n const [only] = resources\n const names = resources.size === 1 ? views[only!]?.names : undefined\n return <HeadingCount count={count} names={names} />\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\n\n/**\n * The field whose value shows as a badge beside a record page's title: the view's `titleBadge`, else an enum `status`\n * the sidebar does not show already. None when the field is not `visible` to the reader or holds no value.\n */\nexport const titleBadgeField = (model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, sidebarFields: readonly string[], visible: (name: string) => boolean) => {\n const status = model.fields.status?.type === 'enum' && !sidebarFields.includes('status') ? 'status' : undefined\n const name = view?.titleBadge ?? status\n if (name === undefined || !model.fields[name] || !visible(name)) return\n const value = record[name]\n if (value === null || value === undefined || value === '') return\n return name\n}\n","import { createWhere, printFilter } from '@protobase/schema'\n\nconst where = createWhere()\n\n/** The filter that finds a record's messages: those whose relation `field` holds its key. */\nexport const recordMessagesFilter = (field: string, recordKey: string) => printFilter(where.eq(field, recordKey))\n","import type { ThreadSectionModel } from '@protobase/schema'\nimport { Section } from '../../record-view'\nimport { useAdminMeta } from '../meta-gate'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { useConditions } from '../pages/use-conditions'\nimport { MessageThread } from './message-thread'\nimport { recordMessagesFilter } from './record-filter'\nimport { ThreadBox } from './thread-box'\n\n/** The record's conversation (`l.thread`): the latest messages whose relation `item.field` holds its key, ending in a working indicator while `item.working` holds for the record, with its `item.calls` between them. */\nexport const ThreadSection = ({ item, scope }: { item: ThreadSectionModel; scope: LayoutRecord }) => {\n const { resources } = useAdminMeta()\n const [working] = useConditions(item.working === undefined ? [] : [item.working], scope)\n const model = resources[item.resource]\n if (!model) return null\n const callsModel = item.calls && resources[item.calls.resource]\n const calls = item.calls && callsModel && { model: callsModel, filter: recordMessagesFilter(item.calls.field, scope.key), fields: item.calls }\n return (\n <Section title={item.title} help={item.help}>\n <ThreadBox>\n <MessageThread model={model} filter={recordMessagesFilter(item.field, scope.key)} sender={item.sender} time={item.time} text={item.text} status={item.status} calls={calls} limit={item.limit} empty={item.empty} working={item.working === undefined ? undefined : working === true} />\n </ThreadBox>\n </Section>\n )\n}\n","import type { LayoutNode, ReadPlan } from '@protobase/layout'\nimport type { BlocksSectionModel } from '@protobase/schema'\nimport { PlanReadsProvider } from './plan-reads'\nimport { RootRecordScope, type LayoutRecord } from './record-scope'\nimport { RenderNode } from './render-node'\nimport { StartBlockQueries } from './start-block-queries'\n\n/**\n * A block tree on the record page (`l.blocks`), drawn as a composed page's inside the page's own record: its planned\n * reads all start as it draws, their `{{@root.…}}` slots filled from the record, and its blocks read the record as `@root`.\n */\nexport const RecordBlocks = ({ item, scope }: { item: BlocksSectionModel; scope: LayoutRecord }) => {\n // The server sent the tree and its plan as `@protobase/layout` makes them\n const tree = item.tree as LayoutNode\n const plan = item.reads as ReadPlan | undefined\n return (\n <RootRecordScope value={scope}>\n <PlanReadsProvider tree={tree} plan={plan}>\n <StartBlockQueries tree={tree} plan={plan} />\n <RenderNode node={tree} at=\"\" />\n </PlanReadsProvider>\n </RootRecordScope>\n )\n}\n","import { Skeleton } from '../primitives/skeleton'\nimport { lazyComponent } from './lazy-component'\n\n// The record page's sections that draw with code of their own, such as the lines' dragging and the conversation's\n// composer, load with the first record that shows one.\n\nexport const RecordLines = lazyComponent(() => import('./record-lines').then((module) => module.RecordLines), () => <Skeleton className=\"h-32 w-full rounded-lg\" />)\nexport const ComposerSection = lazyComponent(() => import('./conversation/composer-section').then((module) => module.ComposerSection), () => <Skeleton className=\"h-24 w-full rounded-lg\" />)\n","import { Check } from 'lucide-react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { Fragment, useEffect, type ReactElement } from 'react'\nimport { isApiError } from '@protobase/client'\nimport { type LayoutItemModel, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { usePauseFocusRefresh } from '../data/focus-refresh'\nimport { keys } from '../data/query-keys'\nimport { useOpenedRecord, type LiveRecord } from '../data/use-record'\nimport { displayValue, valueTitle } from '../live/display-value'\nimport { fromDraft, isRequiredOnEdit, toDraft } from '../live/field-values'\nimport { auditField } from '../live/audit-fields'\nimport { humanize } from '../live/naming'\nimport { useRecordTitle } from './titles/record-titles'\nimport { Button, buttonClass } from '../primitives/button'\nimport { Skeleton } from '../primitives/skeleton'\nimport { cn } from '../lib/cn'\nimport { Field, GroupSection, KeyFacts, MetadataCard, RecordHeader, RecordTabs, Section, SpecTable } from '../record-view'\nimport { ErrorBanner } from './error-banner'\nimport { CustomSection } from './custom-section'\nimport { ConversationPage } from './conversation-page/conversation-page'\nimport { FullAreaRecord } from './full-area-record'\nimport { RecordFocusPage } from './focus/record-focus-page'\nimport { openedAddress } from './opened-address'\nimport { RecordOpens } from './record-opens'\nimport { MapSection } from './map/map-section'\nimport { RecordChartSection } from './record-chart/record-chart-section'\nimport { RecordTrendSection } from './record-trend/record-trend-section'\nimport { RecordActions } from './pages/record-actions'\nimport type { LayoutRecord } from './pages/record-scope'\nimport { FieldEditor, showsValue } from './field-editor'\nimport { groupOpen, toggledOpen } from './group-open'\nimport { attentionTab, shownTab, splitTabs } from './record-tabs'\nimport { isWideField, shownWidget } from './field-types/shown-widget'\nimport { WidgetPart } from './field-types/widget-part'\nimport { useProjectUi } from './pages/project-ui'\nimport { Notice, useAdminMeta, usePermissions } from './meta-gate'\nimport { can, fieldAccess } from './permissions'\nimport { useRestore } from './delete/use-restore'\nimport { useAuth } from '../auth'\nimport { inApp } from '../app-shell/breadcrumb'\nimport { draftStorageKey } from './draft-storage'\nimport { useRecordLines } from './use-record-lines'\nimport { useDeleteFlow } from './delete/use-delete-flow'\nimport { useNavigationGuard } from './router'\nimport { AppLink, useAppAddress } from './use-app-address'\nimport { FieldValue } from './pages/field-value'\nimport { GallerySection } from './gallery/gallery-section'\nimport { HistorySection } from './history/history-section'\nimport { CommentsSection } from './comments/comments-section'\nimport { filledFields } from './filled-fields'\nimport { namedIcon } from './named-icon'\nimport { fieldHelp, helpShown, recordShown, whenShown } from './record-mode/record-mode'\nimport { fallbackEntries } from './record-mode/shown-layout'\nimport { useShownLayout } from './record-mode/use-shown-layout'\nimport { useRecordEditor } from './use-record-editor'\nimport { useRecordElsewhere } from './use-record-elsewhere'\nimport { fieldMessage } from './field-errors'\nimport { useFocusFirstInvalid } from './use-focus-first-invalid'\nimport { useRelatedRecords } from './use-related-records'\nimport { IncomingCard } from './incoming-card'\nimport { isChosen, keyValue } from './create/create-values'\nimport { RelatedSection } from './related-section'\nimport { relatedValue } from './related-value'\nimport { GroupCount } from './group-count'\nimport { ValueBadge } from './value-badge'\nimport { titleBadgeField } from './read-values/title-badge'\nimport { useClient } from '../data/api-provider'\nimport { markdownExcerpt } from '../markdown/markdown-excerpt'\nimport { ThreadSection } from './conversation/thread-section'\nimport { RecordBlocks } from './pages/record-blocks'\nimport { isMarkdown } from '../markdown/markdown-hint'\nimport { ContactLink } from '../live/contact-link'\nimport { linkTextOf } from '../live/link-text'\nimport { jsonSummary } from '../live/json-summary'\nimport { contactFormat } from '../live/contact-links'\nimport { text as appText } from './messages'\nimport { text } from './record-messages'\nimport { RecordSkeleton } from './record-skeleton'\nimport { ComposerSection, RecordLines } from './record-sections'\nimport { FileViewerPage, viewedField } from './file-viewers/file-viewer-page'\n\nconst hidden = (model: ResourceModel, name: string) => name === model.tenant || model.primaryKey.includes(name)\n\n/**\n * The view's layout, or one section with the editable fields when the view has none, then History when the resource\n * keeps it and Comments when it takes them. The read view, which is all a user who may only read the resource gets,\n * shows every field: the record rather than what can be changed.\n */\nconst layoutFor = (model: ResourceModel, view: ViewModel | undefined, read: boolean): LayoutItemModel[] => {\n if (view && view.layout.length > 0) return view.layout\n // A write-only field is edited only where the view's layout names it\n const shown = Object.values(model.fields).filter((field) => !hidden(model, field.name) && !field.writeOnly)\n const editable = shown.filter((field) => !field.readOnly)\n const fields = (editable.length > 0 && !read ? editable : shown).map((field) => field.name)\n return [{ kind: 'section', title: text('details'), fields }, ...(model.history ? [{ kind: 'history' as const, title: text('history') }] : []), ...(model.comments ? [{ kind: 'comments' as const, title: text('comments') }] : [])]\n}\n\nexport const RecordPage = ({ resource, recordKey }: { resource: string; recordKey: string }) => {\n const { resources, views } = useAdminMeta()\n const { address } = useAppAddress()\n const ui = useProjectUi()\n const model = resources[resource]\n const record = useOpenedRecord(resource, recordKey)\n if (!model) return <Notice title={appText('notFound')}>{appText('noResource', { name: resource })}</Notice>\n if (record.isPending) return <RecordSkeleton />\n if (record.error) return <div className=\"p-8\">{isApiError(record.error) && record.error.status === 404 ? <RecordNotFound model={model} recordKey={recordKey} /> : <ErrorBanner title={text('couldNotLoad')} error={record.error} />}</div>\n // A record opened from a list shows that row's fields until it has loaded; the loaded record draws the page anew, so\n // its form starts from the whole record\n const standard = <LoadedRecord key={record.isPlaceholderData ? 'preview' : 'loaded'} model={model} recordKey={recordKey} stored={record.data} preview={record.isPlaceholderData} />\n // A file the address opens shows in the viewer for its type, once the whole record has its link\n const opened = address?.kind === 'record' && address.file !== undefined && !record.isPlaceholderData ? viewedField(ui, model, record.data.record, address.file) : undefined\n // Back leads to the page whose file links open viewers: the standard page, also on a view whose record page is another\n const ownPage = views[resource]?.recordOpens !== undefined || views[resource]?.record !== undefined\n const back = { kind: 'record' as const, resource, key: recordKey, ...(ownPage && { standard: true as const }) }\n if (opened) return <FileViewerPage key={opened.file.uri} model={model} record={record.data.record} viewed={opened} back={back} />\n const standardAsked = address?.kind === 'record' && address.standard === true\n const opens = views[resource]?.recordOpens\n if (opens && !standardAsked) {\n if (record.isPlaceholderData) return <RecordSkeleton />\n const to = openedAddress(opens, record.data.record)\n if (to) return <RecordOpens to={to} />\n }\n const page = views[resource]?.record\n if (!page || standardAsked) return standard\n // The app's component reads fields a list row may not have, so it waits for the whole record\n if (record.isPlaceholderData) return <RecordSkeleton />\n const { record: fields, etag, permissions } = record.data\n if ('conversation' in page) return <ConversationPage key={recordKey} page={page.conversation} scope={{ model, record: fields, key: recordKey, etag, permissions }} />\n if ('surface' in page || page.focus) return <RecordFocusPage model={model} recordKey={recordKey} stored={record.data} page={page} standard={standard} />\n return <FullAreaRecord component={page.component} scope={{ model, record: fields, key: recordKey, etag, permissions }} standard={standard} />\n}\n\n// A record the session's organization does not have may be in another of the person's organizations, which opens it\nconst RecordNotFound = ({ model, recordKey }: { model: ResourceModel; recordKey: string }) => {\n const elsewhere = useRecordElsewhere(model, recordKey)\n if (elsewhere.state === 'looking') return <RecordSkeleton />\n if (elsewhere.state === 'switching') return <Notice title={text('loading')}>{text('openingElsewhere')}</Notice>\n if (elsewhere.state === 'failed') return <ErrorBanner title={text('couldNotLoad')} error={elsewhere.error} />\n return <Notice title={appText('notFound')}>{text('noRecord')}</Notice>\n}\n\ntype LoadedRecordProps = {\n model: ResourceModel\n recordKey: string\n stored: LiveRecord\n /** `stored` is what a list row knows of the record: its fields show as they will, the others as placeholders, and none takes input. */\n preview: boolean\n}\n\nconst LoadedRecord = ({ model, recordKey, stored, preview }: LoadedRecordProps) => {\n const meta = useAdminMeta()\n const { address, go } = useAppAddress()\n const view = meta.views[model.name]\n const title = useRecordTitle()(model, view, stored.record, recordKey)\n const { state: auth } = useAuth()\n const lines = useRecordLines(model, recordKey)\n const editor = useRecordEditor({\n model,\n stored,\n recordKey,\n mode: view?.saveFeedback ?? 'toast',\n subject: title,\n // A draft kept from before waits for the whole record, which it was made to\n draftKey: !preview && auth.kind === 'signed-in' ? draftStorageKey(auth.user.id, model.name, recordKey) : undefined,\n lines: lines.draft,\n })\n const queryClient = useQueryClient()\n const client = useClient()\n const fieldsRef = useFocusFirstInvalid<HTMLDivElement>(editor.rejections)\n const permissions = usePermissions(model.name)\n const restore = useRestore(model)\n // An earlier version of the record, as a field type that keeps versions draws it, is only read\n const pastVersion = address?.kind === 'record' && address.version !== undefined\n const canUpdate = can(permissions, 'update') && stored.permissions?.update !== false && !pastVersion\n const { shown, offersEdit, editing } = recordShown(view?.recordMode, canUpdate, address?.kind === 'record' && address.edit === true)\n // Only the form leaves changes behind; on the read view a draft kept from before waits for Edit. A save under way\n // counts too, so leaving never cuts off a write and then restores the draft of a record that was saved.\n useNavigationGuard((editor.dirty && shown === 'form') || editor.saving)\n // Unsaved changes keep the version of the record they were made to, wherever the draft shows\n usePauseFocusRefresh(editor.dirty)\n const openGroups = address?.kind === 'record' ? address.open : undefined\n const atEdit = address?.kind === 'record' && address.edit === true\n const addressedTab = address?.kind === 'record' ? address.tab : undefined\n // The standard page of a view whose record page is the app's own component stays the standard page as it changes\n const standard = address?.kind === 'record' && address.standard === true\n const recordAt = (open: readonly string[] = [], edit = false, tab?: string) =>\n ({ kind: 'record' as const, resource: model.name, key: recordKey, ...(edit && { edit }), ...(open.length > 0 && { open }), ...(tab && { tab }), ...(standard && { standard }) })\n // Edit, Cancel and the save keep the groups the person opened and the tab they are on\n const readAddress = recordAt(openGroups, false, addressedTab)\n const editAddress = recordAt(openGroups, true, addressedTab)\n // A form that Edit opened goes back to the record once saved, or when its changes are dropped\n const leavesForm = shown === 'form' && view?.recordMode !== undefined && view.recordMode !== 'edit'\n const canDelete = can(permissions, 'delete') && stored.permissions?.delete !== false\n const remove = useDeleteFlow({\n model,\n view,\n restore,\n onDeleted: () => go({ kind: 'list', resource: model.name }, { replace: true }),\n onReview: () => void queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }),\n })\n const related = useRelatedRecords(model, meta.resources, meta.views, stored.record)\n // A relation to a record of one key column is chosen on the form; the record's own key and its tenant are not\n const pickTarget = (name: string) => {\n const field = model.fields[name]\n const target = field?.relation ? meta.resources[field.relation.resource] : undefined\n if (!target || target.primaryKey.length !== 1 || name === model.tenant || model.primaryKey.includes(name)) return undefined\n return target\n }\n const picked = Object.values(model.fields).filter((field) => pickTarget(field.name))\n // The form names and links the record each relation points at now, chosen or stored\n const drafted = { ...stored.record, ...Object.fromEntries(picked.map((field) => [field.name, fromDraft(field, editor.value(field.name))])) }\n const chosen = useRelatedRecords(model, meta.resources, meta.views, drafted)\n const pick = (name: string, next: unknown) => {\n const target = pickTarget(name)\n if (!target || !isChosen(next)) return editor.change(name, next)\n // The picker knows the chosen record's name, so the form shows it without asking the server\n queryClient.setQueryData(keys.relatedLabel(target.name, next.key), { label: next.label })\n editor.change(name, keyValue(target, next.key))\n }\n const { fields: fieldTypes } = useProjectUi()\n // The items and fields meant only for the form, or only for reading the record, show only there\n const scope: LayoutRecord = { model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }\n const layout = useShownLayout(layoutFor(model, view, shown === 'read'), scope, editing, preview)\n const { before, tabs, after } = splitTabs(layout)\n const tab = shownTab(tabs, addressedTab)\n const needsAttention = (name: string) => editing && (editor.errors[name] !== undefined || editor.conflicts[name] !== undefined)\n // A turned-down save moves to the first tab that holds a field to put right, where the form then focuses it\n useEffect(() => {\n if (editor.rejections === 0) return\n const target = attentionTab(tabs, tab, needsAttention)\n if (target) go(recordAt(openGroups, atEdit, target === tabs[0] ? undefined : target.title), { replace: true })\n }, [editor.rejections])\n const sidebarFields = layout.flatMap((item) => (item.kind === 'sidebar' ? item.fields : []))\n const updatedAt = auditField(model, 'updated')\n const hint = (name: string) => view?.fields[name]\n // A write-only field has no value to show, so it is on the form only\n const visible = (name: string) => fieldAccess(stored.permissions, name) !== 'hidden' && whenShown(hint(name)?.when, editing) && (shown === 'form' || !model.fields[name]?.writeOnly)\n const known = (name: string) => !preview || Object.hasOwn(stored.record, name)\n const badgeField = titleBadgeField(model, view, stored.record, sidebarFields, visible)\n const badge = badgeField && (\n <ValueBadge value={stored.record[badgeField]} hints={hint(badgeField)}>\n <span className=\"sr-only\">{hint(badgeField)?.label ?? humanize(badgeField)}: </span>\n {displayValue(model.fields[badgeField]!, stored.record[badgeField], hint(badgeField))}\n </ValueBadge>\n )\n\n const fieldView = (name: string) => {\n const field = model.fields[name]\n const access = fieldAccess(stored.permissions, name)\n if (!field || access === 'hidden') return null\n const conflict = editor.conflicts[name]\n const target = pickTarget(name)\n const label = hint(name)?.label ?? humanize(name)\n const problem = editor.errors[name]\n const locked = shown !== 'form' || access === 'read'\n return (\n <Field\n // A revealed sensitive value is forgotten when the record changes\n key={field.sensitive ? `${name}:${stored.etag}` : name}\n name={name}\n label={label}\n required={shown === 'form' && access !== 'read' && isRequiredOnEdit(field)}\n help={fieldHelp(hint(name), view, editing)}\n error={problem && fieldMessage(field, label, problem)}\n wide={isWideField(fieldTypes, field, hint(name))}\n readOnly={showsValue(field, hint(name), locked, Boolean(target))}\n conflict={\n conflict === undefined\n ? undefined\n : { user: { name: text('someoneElse'), initials: '?', hue: 40 }, ago: text('justNow'), theirValue: conflict || '—', onKeepMine: () => editor.keepMine(name), onUseTheirs: () => editor.useTheirs(name) }\n }\n >\n {known(name) ? (\n <FieldEditor\n field={field}\n hints={hint(name)}\n value={editor.value(name)}\n stored={stored.record[name]}\n relationLabel={chosen.labels[name]}\n relationTo={chosen.addresses[name]}\n relationPicker={target && { target, view: meta.views[target.name] }}\n locked={locked}\n invalid={Boolean(editor.errors[name])}\n reveal={field.sensitive && !field.writeOnly ? () => client.reveal(model.name, recordKey, name) : undefined}\n resource={model.name}\n record={stored.record}\n linkText={hint(name)?.format === 'url' ? linkTextOf(model, view, name, stored.record, related.labels) : undefined}\n onChange={(next) => pick(name, next)}\n />\n ) : (\n <Skeleton className=\"h-9\" />\n )}\n </Field>\n )\n }\n\n // The read view's row of a field: its value as the record page shows values, a sensitive one masked with its eye\n const readRow = (name: string) => {\n const field = model.fields[name]!\n const value = !known(name) ? (\n <Skeleton className=\"h-4 w-32\" />\n ) : field.sensitive ? (\n <FieldEditor field={field} hints={hint(name)} value=\"\" stored={stored.record[name]} locked reveal={() => client.reveal(model.name, recordKey, name)} resource={model.name} onChange={(next) => editor.change(name, next)} />\n ) : (\n <FieldValue model={model} field={field} value={stored.record[name]} relationLabel={related.labels[name]} record={stored.record} relationLabels={related.labels} />\n )\n return { label: hint(name)?.label ?? humanize(name), help: fieldHelp(hint(name), view, editing), wide: isWideField(fieldTypes, field, hint(name)), value }\n }\n\n // The sidebar's fields are one Summary card, where the first sidebar stands among the sidebar's custom components and maps\n const firstSidebar = layout.findIndex((item) => item.kind === 'sidebar')\n const summary = (\n <MetadataCard\n title={text('summary')}\n rows={sidebarFields.flatMap((name) => {\n const field = model.fields[name]\n if (!field || !visible(name)) return []\n if (!known(name)) return [{ label: hint(name)?.label ?? humanize(name), value: <Skeleton className=\"h-4 w-24\" /> }]\n const value = stored.record[name]\n const markdown = isMarkdown(field, hint(name)) && typeof value === 'string' && value !== ''\n // A sidebar value stays on one line, so markdown shows as its plain-text excerpt and JSON as its summary, like a list cell\n const json = field.type === 'json' && value !== null && value !== undefined\n const text = markdown ? markdownExcerpt(value) : json ? jsonSummary(value) : displayValue(field, value, hint(name))\n const contact = field.type === 'text' && typeof value === 'string' && value !== '' ? contactFormat(hint(name)) : undefined\n const builtIn = field.type === 'enum' ? <ValueBadge value={value} hints={hint(name)}>{text}</ValueBadge> : contact ? <ContactLink format={contact} value={text} label={linkTextOf(model, view, name, stored.record, related.labels)} /> : <span title={valueTitle(field, value, undefined, hint(name))}>{text}</span>\n const shown = shownWidget(fieldTypes, field, hint(name))\n return [{ label: hint(name)?.label ?? humanize(name), title: text, value: shown ? <WidgetPart shown={shown} part=\"display\" field={field} value={stored.record[name]} fallback={builtIn} /> : builtIn }]\n })}\n />\n )\n\n const save = async () => {\n if ((await editor.save()) && leavesForm) go(readAddress, { replace: true })\n }\n\n // Edit and Delete are actions like the view's own, in the rail; Save leads the sidebar, above them\n const startDelete = canDelete ? () => void remove.start({ key: recordKey, title, etag: stored.etag, snapshot: stored.record }) : undefined\n const formControls = shown === 'form' && (\n <>\n <Button variant=\"primary\" className=\"max-md:min-h-11 max-md:flex-1 md:w-full\" loading={editor.saving} disabled={!editor.dirty && editor.phase !== 'saved'} onClick={() => void save()}>\n {editor.phase === 'saved' && <Check className=\"size-4\" />}\n {editor.phase === 'saved' ? text('saved') : text('save')}\n </Button>\n {leavesForm && (\n // Cancel drops the changes when it leaves the form here, not when it opens the record in another tab\n <AppLink to={readAddress} className={cn(buttonClass(), 'max-md:min-h-11 md:w-full')} onClick={(event) => inApp(event) && editor.discard()}>\n {text('cancel')}\n </AppLink>\n )}\n {editor.dirty && <span className=\"text-xs text-muted-foreground max-md:order-first\">{text('unsavedChanges')}</span>}\n </>\n )\n\n // The main column's items; a group renders its sections and related tables through the same code\n const mainItem = (item: LayoutItemModel, index: number): ReactElement[] => {\n if (item.kind === 'group') {\n const children = item.items.flatMap(mainItem)\n if (children.length === 0) return []\n const open = groupOpen(item, openGroups, needsAttention)\n const toggle = item.collapsed ? recordAt(toggledOpen(openGroups, item.title), atEdit, addressedTab) : undefined\n // The count covers the related tables the page draws, closed or open\n const counted = item.items.flatMap((inner) => (inner.kind === 'related' && (inner.from === undefined || known(inner.from)) ? [{ item: inner, value: relatedValue(inner, stored.record, recordKey) }] : []))\n const count = item.count ? <GroupCount sections={counted} /> : undefined\n return [<GroupSection key={`group:${item.title}`} title={item.title} help={item.help} count={count} open={open} toggle={toggle}>{children}</GroupSection>]\n }\n if (item.kind === 'related' && item.lines) {\n // The lines load on their own, and only once the record has\n if (!lines.model || !lines.item || preview) return []\n return [<RecordLines key={`lines:${item.title}`} lines={{ ...lines, model: lines.model, item: lines.item }} editable={shown === 'form'} saving={editor.saving} />]\n }\n if (item.kind === 'related') {\n if (item.from !== undefined && !known(item.from)) return []\n return [<RelatedSection key={`related:${item.title}`} item={item} value={relatedValue(item, stored.record, recordKey)} owner={model.name} />]\n }\n if (item.kind === 'chart') return [<RecordChartSection key={`chart:${index}`} item={item} recordKey={recordKey} />]\n if (item.kind === 'trend') return [<RecordTrendSection key={`trend:${index}`} item={item} recordKey={recordKey} />]\n // Project components, maps, photos and block trees read fields a list row may not have, so they wait for the record\n if (preview && (item.kind === 'custom' || item.kind === 'map' || item.kind === 'gallery' || item.kind === 'blocks')) return []\n if (item.kind === 'custom') return item.sidebar ? [] : [<CustomSection key={`custom:${index}`} item={item} scope={scope} fallback={item.fallback && <>{fallbackEntries(item).flatMap(([entry, at]) => mainItem(entry, at))}</>} />]\n if (item.kind === 'map') return item.sidebar ? [] : [<MapSection key={`map:${index}`} item={item} record={stored.record} />]\n if (item.kind === 'gallery') return [<GallerySection key={`gallery:${index}`} item={item} record={stored.record} recordKey={recordKey} />]\n if (item.kind === 'history') return [<HistorySection key={`history:${index}`} item={item} model={model} view={view} recordKey={recordKey} etag={stored.etag} />]\n if (item.kind === 'thread') return [<ThreadSection key={`thread:${index}`} item={item} scope={scope} />]\n if (item.kind === 'blocks') return [<RecordBlocks key={`blocks:${index}`} item={item} scope={scope} />]\n // Writing waits for the record, so a message never goes out from the preview\n if (item.kind === 'composer') return preview ? [] : [<ComposerSection key={`composer:${index}`} item={item} owner={model} recordKey={recordKey} />]\n if (item.kind === 'comments') return [<CommentsSection key={`comments:${index}`} item={item} resource={model.name} recordKey={recordKey} canWrite={auth.kind !== 'visitor'} />]\n if (item.kind !== 'section') return []\n // A section whose fields are all hidden from this user would be a lone heading, as would key facts all empty\n const visibleFields = item.fields.filter((name) => model.fields[name] && visible(name))\n const facts = shown === 'read' && item.presentation === 'facts'\n const fields = facts ? filledFields(stored.record, visibleFields) : visibleFields\n if (fields.length === 0) return []\n return [\n <Section key={item.title} title={item.title} help={helpShown(item.helpWhen, view, editing) ? item.help : undefined}>\n {facts ? (\n <KeyFacts facts={fields.map((name) => ({ label: readRow(name).label, value: readRow(name).value, icon: namedIcon(hint(name)?.icon) }))} />\n ) : shown === 'read' ? (\n <SpecTable rows={fields.map(readRow)} />\n ) : (\n <div className=\"grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2\">{fields.map(fieldView)}</div>\n )}\n </Section>,\n ]\n }\n\n // A sidebar map, or a sidebar custom section with its fallback of sidebar maps and custom sections in its place\n const sidebarCard = (item: LayoutItemModel, index: number): ReactElement | null => {\n if (item.kind === 'map') return <MapSection key={`map:${index}`} item={item} record={stored.record} />\n if (item.kind !== 'custom') return null\n return <CustomSection key={`custom:${index}`} item={item} scope={scope} fallback={item.fallback && <>{fallbackEntries(item).map(([entry, at]) => sidebarCard(entry, at))}</>} />\n }\n\n return (\n // The preview looks as the loaded form will, but takes no input: typing there would be lost when the record loads\n <div ref={fieldsRef} className=\"flex flex-1 flex-col\" inert={preview}>\n {remove.dialogs}\n <div className=\"flex-1\">\n <div className={cn(view?.recordWidth !== 'full' && 'mx-auto max-w-[1100px]', 'px-4 pb-8 pt-6 md:px-10 md:py-8')}>\n <RecordHeader title={title} badge={badge} />\n {editor.message && <div className=\"mt-4\"><ErrorBanner title={text('notSaved')} error={new Error(editor.message)} /></div>}\n {editor.linesConflict && (\n <div className=\"mt-4\">\n <ErrorBanner title={text('linesChanged')} error={new Error(text('linesReloaded'))} />\n </div>\n )}\n {shown !== 'form' && offersEdit && editor.dirty && (\n <div className=\"mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2\" role=\"status\">\n <span>{text('unsavedKept')}</span>\n <span className=\"flex gap-2\">\n <AppLink to={editAddress} className={buttonClass({ size: 'sm' })}>{text('continueEditing')}</AppLink>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </span>\n </div>\n )}\n {shown === 'form' && editor.restored && (\n <div className=\"mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2\" role=\"status\">\n <span>{text('unsavedRestored')}</span>\n <span className=\"flex gap-2\">\n <Button size=\"sm\" onClick={editor.dismissRestored}>{text('keep')}</Button>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </span>\n </div>\n )}\n <div className=\"grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12\">\n <div className=\"divide-y divide-border\">\n {before.flatMap(mainItem)}\n {tab && (\n <RecordTabs tabs={tabs.map((each, index) => ({ title: each.title, to: recordAt(openGroups, atEdit, index === 0 ? undefined : each.title), current: each === tab }))} />\n )}\n {tab && (\n <div key={`tab:${tab.title}`} className=\"divide-y divide-border\">\n {tab.items.flatMap(mainItem)}\n </div>\n )}\n {after.flatMap(mainItem)}\n </div>\n {/* Beside the main column the sidebar stays in view below the top bar, and scrolls on its own when taller than the window */}\n <aside className=\"space-y-4 md:sticky md:top-[var(--pb-sticky-top,0px)] md:max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px))] md:self-start md:overflow-y-auto md:pb-4 md:pt-8\">\n {formControls && <div className=\"hidden flex-col items-center gap-2 md:flex\">{formControls}</div>}\n {!preview && <RecordActions model={model} stored={stored} recordKey={recordKey} edit={offersEdit ? editAddress : undefined} onDelete={startDelete} />}\n {firstSidebar === -1 && summary}\n {layout.map((item, index) => {\n if ((item.kind === 'custom' || item.kind === 'map') && item.sidebar && !preview) return sidebarCard(item, index)\n return index === firstSidebar ? <Fragment key=\"summary\">{summary}</Fragment> : null\n })}\n {/* The record's timestamps, but for those the Summary shows already */}\n <MetadataCard\n title={text('details')}\n rows={[auditField(model, 'created'), updatedAt].flatMap((name) => {\n const field = name ? model.fields[name] : undefined\n if (!name || !field || !visible(name) || sidebarFields.includes(name)) return []\n return [{ label: hint(name)?.label ?? humanize(name), value: known(name) ? <span title={valueTitle(field, stored.record[name], undefined, hint(name))}>{displayValue(field, stored.record[name], hint(name))}</span> : <Skeleton className=\"h-4 w-24\" /> }]\n })}\n />\n {!preview && <IncomingCard model={model} recordKey={recordKey} layout={layout} />}\n </aside>\n </div>\n </div>\n </div>\n {/* On a mobile screen the form's controls stay in view below the record, above the shell's bottom bar */}\n {formControls && (\n <div className=\"sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden\">{formControls}</div>\n )}\n </div>\n )\n}\n"],"file":"record-page-JFlxtSyg.js","debugId":"09165c6d-4b28-4e35-a1ec-ce9b7078a0db"}
|
|
1
|
+
{"version":3,"mappings":";6xFASA,IAAMA,GAAa,CACjB,KAAM,SACN,KAAM,GACN,KAAM,CACJ,CAAC,OAAQ,CAAE,EAAG,iDAAkD,IAAK,QAAS,CAAC,EAC/E,CAAC,OAAQ,CAAE,EAAG,uDAAwD,IAAK,QAAS,CAAC,EACrF,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,IAAK,EAAG,IAAK,KAAM,eAAgB,IAAK,QAAS,CAAC,EAC7E,CAAC,OAAQ,CAAE,EAAG,IAAK,EAAG,IAAK,MAAO,KAAM,OAAQ,KAAM,GAAI,IAAK,IAAK,QAAS,CAAC,CAChF,CACF,EACAA,GAAW,KACX,IAAMC,GAASC,GAAiBF,EAAU,ECXpCA,GAAa,CACjB,KAAM,OACN,KAAM,GACN,KAAM,CACJ,CAAC,SAAU,CAAE,GAAI,KAAM,GAAI,KAAM,EAAG,KAAM,IAAK,QAAS,CAAC,EACzD,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,EAC1C,CAAC,OAAQ,CAAE,EAAG,YAAa,IAAK,QAAS,CAAC,CAC5C,CACF,EACAA,GAAW,KACX,IAAMG,GAAOD,GAAiBF,EAAU,ECVlCA,GAAa,CACjB,KAAM,YACN,KAAM,GACN,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AAI,EAAG,MAAOyzB,EAAMzzB,CAAI,GAAI,EAAAtC,EAAA,KAAC,OAAD,CAAM,MAAOw3B,GAAWtrB,EAAOzD,EAAO,OAAOnG,GAAO,OAAWwzB,EAAKxzB,CAAI,CAAC,EAAI,SAAA8Z,GAAalQ,EAAOzD,EAAO,OAAOnG,GAAOwzB,EAAKxzB,CAAI,CAAC,CAAQ,IAAI,EAAAtC,EAAA,KAACkiB,EAAD,CAAU,UAAU,UAAY,EAAE,CAAC,CAC5P,CAAC,CACF,GACA,CAACna,IAAW,EAAA/H,EAAA,KAACquB,GAAD,CAAqB,QAAkB,YAAmB,SAAS,EAC3E,CACJ,KACF,GACF,GAEJuJ,KACC,EAAA53B,EAAA,KAAC,MAAD,CAAK,UAAU,yHAA0H,SAAA43B,EAAkB,EAE1J,GAET","names":["__iconData","Images","createLucideIcon","Info","ListTree","Undo2","Zap","RecordHeader","import_jsx_runtime","collection","title","badge","lastEditedBy","_Fragment","text","presence","AvatarStack","actions","headingClass","GroupSection","id","useId","cn","open","toggle","AppLink","ChevronRight","count","help","HeadingLevel","RecordTabs","segmentedClass","tabs","tab","SpecTable","rows","row","KeyFacts","facts","Icon","label","value","itemClass","ActionRail","children","tone","name","description","render","onRun","blocked","running","linesLimit","useLines","list","useList","lines","link","parentKey","position","items","useMemo","a","b","more","import_react","auditField","kind","model","frame","item","SidebarCard","body","Section","CustomSection","useProjectUi","Component","components","RecordScope","scope","unmarkFieldRefs","fallback","CustomOrFallback","FullAreaRecord","component","CustomBoundary","standard","FullArea","usePageScroll","ConversationCall","useRecordCallAddress","client","useClient","members","useMembers","page","joining","RecordCall","user","MembersTitle","auth","useOptionalAuth","me","usePresence","others","otherMembers","member","StatusMark","presenceOf","index","ConversationHeader","subtitle","CallMark","buttonClass","DeleteMessageDialog","ResponsiveDialog","Button","onClose","onDelete","MessageActionsBar","controls","reacted","groups","group","offered","onReact","emoji","entry","thread","onEdit","symbol","MessageActionsSheet","mine","choose","onChoose","preview","onCopy","reaction","press","onUnreact","pixels","attachmentOf","file","fileShown","attachments","stored","recordKey","attachmentsByMessage","byMessage","attachment","message","isPreviewed","isPreviewable","FileLabel","FileText","formatSize","FileDownload","className","MessageAttachments","MessageEditor","draft","setDraft","useState","saving","setSaving","mounted","useRef","trimmed","save","onCancel","saved","onSave","mentionedIds","MentionBox","event","ReactionChips","people","userIds","lastReplyLabel","viewerZone","chatDayLabel","time","now","zone","formatTime","ThreadSummary","last","formatDateTime","deleteAllowed","option","condition","parseCondition","evaluateCondition","messageAccess","can","permissions","rowAllows","reactionAccess","emojiSet","values","reactions","reactionsByMessage","field","reactionGroups","set","these","useMessageControls","toast","useToast","setup","access","reacts","key","copy","writes","nextPress","textBoxes","swallowReleaseClick","swallow","stop","useMessagePress","timer","pressing","step","next","onControl","typing","onOpen","lowersKeyboard","idsOf","ConversationMessage","editing","setEditing","deleting","setDeleting","acting","setActing","author","files","messageKey","mentionIds","edited","replies","chips","footer","showLabel","ChatMessage","changed","mentions","MentionedText","where","createWhere","messagesRequest","printFilter","threadSort","repliesRequest","first","ofMessagesFilter","of","messages","readOfMessages","filter","pageToken","ownPositionFilter","timeOf","conversationRows","oldestFirst","previous","sent","before","newDay","sameChatDay","isNew","newLineAbove","soon","authorOf","sender","continued","keysOf","firstUnreadKey","hasEarlier","lastRead","found","highestKey","useMessageAttachments","useAdminMeta","results","useQueries","pages","keys","resources","result","useMessageReactions","useMessageWrites","refresh","useRefreshResource","run","write","resource","failed","refusalReason","error","deleteOps","keyValue","keyOf","useMessageSetup","messagePermissions","usePermissions","reactionPermissions","useNewLine","line","setLine","decidable","decided","decide","ConversationMessages","recordKey$3","senders","listLabels","views","withLabels","read","state","threadState","loaded","ErrorBanner","retryOf","Quiet","readEnd","own","readTo","showsErrorAbove","reactionsError","attachmentsError","ChatThread","ChatDivider","matchingMembers","wanted","query","person","inConversation","useThreadHead","head","useRecord","named","ids","labels","usePickedLabels","elsewhere","ThreadPanel","recordKey$2","headRow","SidePanel","MessageComposer","owner","store","raise","at","moveReadPosition","status","isApiError","useReadPosition","recordKey$1","kept","openedAt","setOpenedAt","setError","writing","find","useCallback","made","useThreadAddress","useAppAddress","here","address","call","go","ConversationPage","useRecordTitle","searchPeople","threaded","channel","relay","useRelay","useViewChannel","useTypingSender","typed","TypingLine","draftStorageKey","userId","readDraft","guarded","raw","storage","parsed","etag","writeDraft","actionIcon","namedIcon","useRecordActions","app","runner","useActionRunner","action","asking","setAsking","actionLink","isDanger","asksFirst","RouteLink","deletes","edit","Pencil","Trash2","ActionPrompt","RecordActions","slot","useTopBarSlot","props","createPortal","ActionMenu","prompt","op","describeBatchFailure","ops","appText","nameFailingOperation","without","source","useRecordEditor","queryClient","useQueryClient","update","useUpdateRecord","feedback","useLiveSave","mode","subject","restored","draftKey","showRestored","setShowRestored","linesConflict","setLinesConflict","conflicts","setConflicts","errors","setErrors","rejections","setRejections","differs","fieldsDirty","dirty","keep","toDraft","change","current","adoptLatest","latest","theirs","displayValue","patchOf","toPatchValue","reject","fieldErrors","saveRecordOnly","isConflict","saveBatch","recordOps","linesPlan","lineOp","ConflictChoices","fields","onKeepMine","onUseTheirs","SaveButton","record","taken","useFocusZoneFilled","compact","useFocusPage","button","FocusSlot","SaveState","size","shown","readOnly","Check","RecordFocus","view","useAuth","editor","useNavigationGuard","usePauseFocusRefresh","askDiscard","setAskDiscard","noun","humanize","restore","useRestore","pastVersion","surfaceReadable","fieldAccess","mayUpdate","canDelete","remove","useDeleteFlow","details","danger","barActions","surfaceField","discardNotice","FocusNotice","conflict","refusedField","surfaceProblem","fieldMessage","FocusRecordContext","FocusActions","FieldSurface","ComponentSurface","hints","FieldEditor","RecordFocusPage","FocusPage","RecordMap","lazy","module","defaultZoom","MapSection","maps","style","recordPosition","map","Suspense","rangeBuckets","chartPoints","points","series","point","measure","empty","ranges","rangeLabels","RecordChartSection","range","setRange","setMeasure","granularity","requests","useAggregates","measures","part","Segmented","Skeleton","PeriodChart","trendSummary","total","RecordTrendSection","useAggregate","sum","periodPoints","toggledOpen","groupOpen","needsAttention","splitTabs","layout","shownTab","tabFields","layoutItems","attentionTab","emptyLinesState","shownIds","storedIds","changedData","edits","filledData","planLinesOps","plan","push","byId","recordId","final","etagOf","written","data","added","etags","wildcard","encodeKey","reorder","start","tags","create","place","ref","placeOf","moved","each","above","refOf","useLinesDraft","setState","rejection","setRejection","nextId","target","order","toFieldDraft","forget","findLinesResource","lineColumnNames","listColumnNames","useRecordLines","parent","columns","galleryTiles","swipeStep","dx","dy","keyStep","steppedPhoto","by","togglesDetails","detailsOpenStorageKey","readDetailsOpen","writeDetailsOpen","control","Lightbox","panel","sidebarId","desktop","useIsDesktop","detailsOpen","setDetailsOpen","trapped","setTrapped","useFocusTrap","photos","onIndex","image","shownImage","shownDetails","hasDetails","toggleDetails","detailsTitle","X","FileImage","ChevronLeft","Sheet","detailFields","sections","whenShown","omit","PhotoDetails","photoKey","singular","FieldValue","isPicture","parts","holder","galleryItems","isStoredFile","cover","same","useGalleryPhotos","sort","useQuery","spans","Tile","photo","large","GallerySection","photoPermissions","setOpen","holderView","readable","changedBy","describeChange","verb","afterSave","useRecordHistory","useInfiniteQuery","pageSize","pageParam","refetch","Loading","Change","who","formatRelativeTime","HistorySection","history","CommentBody","comment","usePostComment","useMutation","input","CommentComposer","emptyDraft","post","submit","useRecordComments","Comment","Avatar","initialsOf","hueOf","CommentsSection","comments","canWrite","innerItems","whenOf","conditionalItems","isRecordCondition","fallbackEntries","shownLayout","when","held","itself","fallbackAt","inner","useShownLayout","conditions","useConditions","w","elsewhereRequest","otherOrganization","tenant","useRecordElsewhere","request","organizations","setFound","session","other","useRelatedRecords","titleOf","relations","relationTitleQuery","addresses","relationTitle","incomingRelations","listed","drawnItems","registered","plural","several","incomingAddress","relation","useIncomingCounts","counts","IncomingCard","formatInt","HeadingCount","Badge","formatTag","names","relatedAdd","createOffered","Empty","singularOf","RelatedRecord","xs","useIsXs","orderBy","defaultOrderBy","useListPage","adding","add","Plus","scopeOf","labelled","RelatedField","path","RowButtonLink","viewAllAddress","embeddedDisplay","listText","ArrowRight","and","given","relatedMatch","through","links","parseFilter","countTotal","useRelatedCount","counted","queries","countQuery","match","enabled","RelatedSection","display","pick","useEmbeddedDisplay","sorting","setSorting","heading","opens","relatedOpens","RelatedCards","handOrder","relatedHandOrder","displaySwitch","EmbeddedDisplaySwitch","ReorderButton","HandSortedList","EmbeddedList","relatedValue","relationTarget","GroupCount","only","titleBadgeField","sidebarFields","visible","recordMessagesFilter","ThreadSection","working","callsModel","calls","ThreadBox","MessageThread","RecordBlocks","tree","RootRecordScope","PlanReadsProvider","StartBlockQueries","RenderNode","RecordLines","lazyComponent","__vitePreload","ComposerSection","hidden","layoutFor","editable","RecordPage","ui","useOpenedRecord","Notice","RecordSkeleton","RecordNotFound","LoadedRecord","opened","viewedField","back","FileViewerPage","standardAsked","to","openedAddress","RecordOpens","meta","fieldsRef","useFocusFirstInvalid","canUpdate","recordShown","openGroups","atEdit","addressedTab","recordAt","readAddress","editAddress","leavesForm","related","pickTarget","picked","drafted","fromDraft","chosen","isChosen","fieldTypes","updatedAt","hint","known","badgeField","ValueBadge","fieldView","problem","locked","Field","isRequiredOnEdit","fieldHelp","isWideField","showsValue","linkTextOf","readRow","firstSidebar","summary","MetadataCard","markdown","isMarkdown","json","markdownExcerpt","jsonSummary","contact","contactFormat","builtIn","ContactLink","valueTitle","shownWidget","WidgetPart","startDelete","formControls","inApp","mainItem","visibleFields","filledFields","helpShown","sidebarCard","offersEdit","after","Fragment"],"ignoreList":[0,1,2,3,4],"sources":["../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/images.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/info.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/list-tree.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/undo-2.mjs","../../../../../node_modules/.bun/lucide-react@1.52.0+0ac650c021fb1b59/node_modules/lucide-react/dist/esm/icons/zap.mjs","../../../src/record-view/record-header.tsx","../../../src/record-view/group-section.tsx","../../../src/record-view/record-tabs.tsx","../../../src/record-view/spec-table.tsx","../../../src/record-view/key-facts.tsx","../../../src/record-view/action-rail.tsx","../../../src/app/use-lines.ts","../../../src/live/audit-fields.ts","../../../src/app/custom-section.tsx","../../../src/app/full-area-record.tsx","../../../src/app/conversation-page/conversation-call.tsx","../../../src/app/conversation-page/members-title.tsx","../../../src/app/conversation-page/conversation-header.tsx","../../../src/app/conversation-page/delete-message-dialog.tsx","../../../src/app/conversation-page/message-actions-bar.tsx","../../../src/app/conversation-page/message-actions-sheet.tsx","../../../src/app/conversation-page/attachments.ts","../../../src/app/conversation-page/message-attachments.tsx","../../../src/app/conversation-page/message-editor.tsx","../../../src/app/conversation-page/reaction-chips.tsx","../../../src/app/conversation-page/reply-labels.ts","../../../src/app/conversation-page/thread-summary.tsx","../../../src/app/conversation-page/message-access.ts","../../../src/app/conversation-page/reactions.ts","../../../src/app/conversation-page/use-message-controls.ts","../../../src/app/conversation-page/message-press.ts","../../../src/app/conversation-page/use-message-press.ts","../../../src/app/conversation-page/conversation-message.tsx","../../../src/app/conversation-page/conversation-reads.ts","../../../src/app/conversation-page/conversation-rows.ts","../../../src/app/conversation-page/use-message-attachments.ts","../../../src/app/conversation-page/use-message-reactions.ts","../../../src/app/conversation-page/use-message-writes.ts","../../../src/app/conversation-page/use-message-setup.ts","../../../src/app/conversation-page/use-new-line.ts","../../../src/app/conversation-page/conversation-messages.tsx","../../../src/app/conversation-page/member-search.ts","../../../src/app/conversation-page/thread-head.ts","../../../src/app/conversation-page/use-thread-head.ts","../../../src/app/conversation-page/thread-panel.tsx","../../../src/app/conversation-page/read-position-write.ts","../../../src/app/conversation-page/use-read-position.ts","../../../src/app/conversation-page/use-thread-address.ts","../../../src/app/conversation-page/conversation-page.tsx","../../../src/app/draft-storage.ts","../../../src/app/action-icon.ts","../../../src/app/pages/record-actions.tsx","../../../src/app/batch-failure.ts","../../../src/app/use-record-editor.ts","../../../src/app/focus/messages.ts","../../../src/app/focus/conflict-choices.tsx","../../../src/app/focus/record-focus-page.tsx","../../../src/app/map/map-section.tsx","../../../src/app/record-chart/chart-points.ts","../../../src/app/record-chart/messages.ts","../../../src/app/record-chart/record-chart-section.tsx","../../../src/app/record-trend/messages.ts","../../../src/app/record-trend/trend-summary.ts","../../../src/app/record-trend/record-trend-section.tsx","../../../src/app/group-open.ts","../../../src/app/record-tabs.ts","../../../src/app/lines-plan.ts","../../../src/app/use-lines-draft.ts","../../../src/app/use-record-lines.ts","../../../src/app/gallery/gallery-layout.ts","../../../src/app/gallery/details-open-storage.ts","../../../src/app/gallery/messages.ts","../../../src/app/gallery/lightbox.tsx","../../../src/app/gallery/detail-fields.ts","../../../src/app/gallery/photo-details.tsx","../../../src/app/gallery/gallery-items.ts","../../../src/app/gallery/use-gallery-photos.ts","../../../src/app/gallery/gallery-section.tsx","../../../src/app/history/messages.ts","../../../src/app/history/describe-change.ts","../../../src/app/history/use-record-history.ts","../../../src/app/history/history-section.tsx","../../../src/app/comments/comment-body.tsx","../../../src/app/comments/use-post-comment.ts","../../../src/app/comments/messages.ts","../../../src/app/comments/comment-composer.tsx","../../../src/app/comments/use-record-comments.ts","../../../src/app/comments/comments-section.tsx","../../../src/app/record-mode/shown-layout.ts","../../../src/app/record-mode/use-shown-layout.ts","../../../src/app/record-elsewhere.ts","../../../src/app/use-record-elsewhere.ts","../../../src/app/use-related-records.ts","../../../src/app/incoming-relations.ts","../../../src/app/use-incoming-counts.ts","../../../src/app/incoming-card.tsx","../../../src/record-view/heading-count.tsx","../../../src/app/related-cards/related-add.ts","../../../src/app/related-cards/related-record.tsx","../../../src/app/related-match.ts","../../../src/app/related-count.ts","../../../src/app/related-section.tsx","../../../src/app/related-value.ts","../../../src/app/group-count.tsx","../../../src/app/read-values/title-badge.ts","../../../src/app/conversation/record-filter.ts","../../../src/app/conversation/thread-section.tsx","../../../src/app/pages/record-blocks.tsx","../../../src/app/record-sections.tsx","../../../src/app/record-page.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: \"images\",\n size: 24,\n node: [\n [\"path\", { d: \"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16\", key: \"9kzy35\" }],\n [\"path\", { d: \"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2\", key: \"1t0f0t\" }],\n [\"circle\", { cx: \"13\", cy: \"7\", r: \"1\", fill: \"currentColor\", key: \"1obus6\" }],\n [\"rect\", { x: \"8\", y: \"2\", width: \"14\", height: \"14\", rx: \"2\", key: \"1gvhby\" }]\n ]\n};\n__iconData.node;\nconst Images = createLucideIcon(__iconData);\n\nexport { __iconData, Images as default };\n//# sourceMappingURL=images.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: \"info\",\n size: 24,\n node: [\n [\"circle\", { cx: \"12\", cy: \"12\", r: \"10\", key: \"1mglay\" }],\n [\"path\", { d: \"M12 16v-4\", key: \"1dtifu\" }],\n [\"path\", { d: \"M12 8h.01\", key: \"e9boi3\" }]\n ]\n};\n__iconData.node;\nconst Info = createLucideIcon(__iconData);\n\nexport { __iconData, Info as default };\n//# sourceMappingURL=info.mjs.map\n","/**\n * @license lucide-react v1.52.0 - ISC\n *\n * This source code is licensed under the ISC license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createLucideIcon from '../createLucideIcon.mjs';\n\nconst __iconData = {\n name: \"list-tree\",\n size: 24,\n node: [\n [\"path\", { d: \"M8 5h13\", key: \"1pao27\" }],\n [\"path\", { d: \"M13 12h8\", key: \"h98zly\" }],\n [\"path\", { d: \"M13 19h8\", key: \"c3s6r1\" }],\n [\"path\", { d: \"M3 10a2 2 0 0 0 2 2h3\", key: \"1npucw\" }],\n [\"path\", { d: \"M3 5v12a2 2 0 0 0 2 2h3\", key: \"x1gjn2\" }]\n ]\n};\n__iconData.node;\nconst ListTree = createLucideIcon(__iconData);\n\nexport { __iconData, ListTree as default };\n//# sourceMappingURL=list-tree.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: \"undo-2\",\n size: 24,\n node: [\n [\"path\", { d: \"M9 14 4 9l5-5\", key: \"102s5s\" }],\n [\"path\", { d: \"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11\", key: \"f3b9sd\" }]\n ]\n};\n__iconData.node;\nconst Undo2 = createLucideIcon(__iconData);\n\nexport { __iconData, Undo2 as default };\n//# sourceMappingURL=undo-2.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: \"zap\",\n size: 24,\n node: [\n [\n \"path\",\n {\n d: \"M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z\",\n key: \"1v7up4\"\n }\n ]\n ]\n};\n__iconData.node;\nconst Zap = createLucideIcon(__iconData);\n\nexport { __iconData, Zap as default };\n//# sourceMappingURL=zap.mjs.map\n","import type { ReactNode } from 'react'\nimport { AvatarStack } from '../primitives/avatar'\nimport { text } from './messages'\n\nexport type RecordHeaderProps = {\n /** A line above the title naming the collection; the record page leaves it to the breadcrumb. */\n collection?: string\n title: string\n /** The badge beside the title, such as a status; without it there is none. */\n badge?: ReactNode\n /** A line under the title; without a name it reads \"Last updated ...\". The record page leaves it to its sidebar. */\n lastEditedBy?: { name?: string; ago: string }\n presence?: Array<{ initials: string; hue: number }>\n actions?: ReactNode\n}\n\nexport const RecordHeader = ({ collection, title, badge, lastEditedBy, presence = [], actions }: RecordHeaderProps) => {\n return (\n <header className=\"flex flex-col gap-4 border-b border-border pb-6 md:flex-row md:items-end md:justify-between md:gap-6\">\n <div>\n {collection && <p className=\"mb-1 text-xs text-muted-foreground\">{collection}</p>}\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-1\">\n <h1 className=\"text-xl font-semibold tracking-tight text-foreground md:text-2xl\">{title}</h1>\n {badge}\n </div>\n {lastEditedBy && (\n <p className=\"mt-1.5 text-xs text-muted-foreground\">\n {lastEditedBy.name ? (\n <>\n {text('lastEditedBy')} <span className=\"font-medium text-foreground\">{lastEditedBy.name}</span> {lastEditedBy.ago}\n </>\n ) : (\n <>{text('lastUpdated', { ago: lastEditedBy.ago })}</>\n )}\n </p>\n )}\n </div>\n <div className=\"flex items-center gap-4\">\n {presence.length > 0 && (\n <span className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <AvatarStack people={presence} size=\"md\" />\n {text('viewing', { count: presence.length })}\n </span>\n )}\n {actions}\n </div>\n </header>\n )\n}\n","import { ChevronRight } from 'lucide-react'\nimport { useId, type ReactNode } from 'react'\nimport type { AppAddress } from '@protobase/schema'\nimport { cn } from '../lib/cn'\nimport { AppLink } from '../app/use-app-address'\nimport { HeadingLevel } from '../lib/heading-level'\n\nconst headingClass = 'text-base font-semibold text-foreground'\n\ntype GroupSectionProps = { title: string; help?: string; count?: ReactNode; open: boolean; toggle?: AppAddress; children: ReactNode }\n\n/**\n * A heading over sections of the record page, `count` after its title and `help` under it. With `toggle`, the address\n * that opens or closes it, the heading is a link, so a copied link opens the page with the group open; the items show\n * only while `open`. Without it the group is always open. Its heading is an h2 and the sections in it head with h3.\n */\nexport const GroupSection = ({ title, help, count, open, toggle, children }: GroupSectionProps) => {\n const id = useId()\n return (\n <div>\n <div className={cn('py-8', open && 'pb-0')}>\n <h2 className=\"flex items-center gap-2\">\n {toggle ? (\n <AppLink to={toggle} replace aria-expanded={open} aria-controls={id} className={cn('inline-flex items-center gap-1.5', headingClass)}>\n <ChevronRight className={cn('size-4 transition-transform', open && 'rotate-90')} />\n {title}\n </AppLink>\n ) : (\n <span className={headingClass}>{title}</span>\n )}\n {count}\n </h2>\n {help && <p className={cn('mt-1 max-w-xl leading-6 text-muted-foreground', toggle && 'pl-5.5')}>{help}</p>}\n </div>\n {open && (\n <div id={id} className=\"divide-y divide-border\">\n <HeadingLevel.Provider value={2}>{children}</HeadingLevel.Provider>\n </div>\n )}\n </div>\n )\n}\n","import type { AppAddress } from '@protobase/schema'\nimport { cn } from '../lib/cn'\nimport { AppLink } from '../app/use-app-address'\nimport { segmentedClass } from '../primitives/segmented'\nimport { text } from './messages'\n\n/** The record page's tabs, links whose addresses show each; the shown one is the current page. */\nexport const RecordTabs = ({ tabs }: { tabs: Array<{ title: string; to: AppAddress; current: boolean }> }) => (\n // One line of tabs scrolls sideways on a narrow screen, which the page cannot do for it\n <nav aria-label={text('tabs')} className=\"overflow-x-auto py-6\">\n <span className={segmentedClass.group('md')}>\n {tabs.map((tab) => (\n <AppLink key={tab.title} to={tab.to} replace aria-current={tab.current ? 'page' : undefined} className={cn(segmentedClass.option(tab.current, 'md'), 'whitespace-nowrap')}>\n {tab.title}\n </AppLink>\n ))}\n </span>\n </nav>\n)\n","import type { ReactNode } from 'react'\nimport { cn } from '../lib/cn'\n\nexport type SpecRow = {\n label: string\n value: ReactNode\n /** A line under the label. */\n help?: string\n /** The value runs under its label across the row, as a text of several lines does. */\n wide?: boolean\n}\n\n/**\n * Label/value rows, the label on the left and the value on the right, as a property's features table on a real estate\n * site: what a record page's section shows on its read view. A wide row puts its value under the label.\n */\nexport const SpecTable = ({ rows }: { rows: SpecRow[] }) => (\n <dl className=\"border-t border-border\">\n {rows.map((row) => (\n <div key={row.label} className={cn('grid gap-x-4 border-b border-border py-2.5', row.wide ? 'grid-cols-1 gap-y-1.5' : 'grid-cols-[minmax(0,2fr)_minmax(0,3fr)]')}>\n <dt className=\"min-w-0 text-muted-foreground\">\n {row.label}\n {row.help && <span className=\"mt-0.5 block text-xs text-faint-foreground\">{row.help}</span>}\n </dt>\n <dd className=\"min-w-0 break-words text-foreground\">{row.value}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { LucideIcon } from 'lucide-react'\nimport type { ReactNode } from 'react'\n\nexport type KeyFact = {\n label: string\n value: ReactNode\n /** Drawn above the value in place of the label, which screen readers and the tooltip still give. */\n icon?: LucideIcon\n}\n\n/**\n * A record's key facts side by side, as the bedrooms, area and energy label of a listing on a real estate site: each\n * value under its icon, or under its label without one, wrapping onto more rows as needed, two to a row on a mobile\n * screen.\n */\nexport const KeyFacts = ({ facts }: { facts: KeyFact[] }) => (\n <dl className=\"grid grid-cols-2 gap-x-4 gap-y-5 sm:flex sm:flex-wrap sm:gap-x-10\">\n {facts.map(({ label, value, icon: Icon }) => (\n <div key={label} title={label} className=\"flex min-w-0 flex-col gap-1.5\">\n <dt className=\"text-muted-foreground\">\n {Icon ? (\n <>\n <Icon className=\"size-5\" aria-hidden />\n <span className=\"sr-only\">{label}</span>\n </>\n ) : (\n label\n )}\n </dt>\n <dd className=\"min-w-0 break-words text-base font-semibold text-foreground\">{value}</dd>\n </div>\n ))}\n </dl>\n)\n","import type { LucideIcon } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport { cn } from '../lib/cn'\nimport { text } from './messages'\n\nexport type RailAction = {\n name: string\n description?: string\n icon: LucideIcon\n onRun?: () => void\n /** Why the action cannot run now; the button is disabled with this as its tooltip. */\n blocked?: string\n running?: boolean\n /** `danger` draws an action that destroys something, such as Delete, in red. */\n tone?: 'danger'\n /**\n * Draws the action as the caller's own element, such as a link, given the rail's classes and content, instead of a\n * button; in a menu, with the `menuitem` role too.\n */\n render?: (item: { className: string; children: ReactNode; role?: 'menuitem' }) => ReactNode\n}\n\nconst itemClass =\n 'flex min-h-11 items-center gap-2 rounded-md border border-border-strong px-3 text-left hover:bg-surface disabled:cursor-default disabled:opacity-60 md:min-h-0 md:w-full md:items-start md:gap-3 md:rounded-none md:border-0 md:px-4 md:py-3'\n\n/** Named actions with one-line descriptions; on phones a row of buttons, from `md` a list. */\nexport const ActionRail = ({ actions }: { actions: RailAction[] }) => (\n <div className=\"overflow-hidden rounded-lg border border-border bg-background\">\n <h2 className=\"hidden border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:block\">{text('actions')}</h2>\n <ul className=\"flex flex-wrap gap-2 p-2 md:block md:divide-y md:divide-border md:p-0\">\n {actions.map(({ name, description, icon: Icon, onRun, blocked, running, tone, render }) => {\n const children = (\n <>\n <Icon className={cn('size-4 shrink-0 md:mt-0.5', tone === 'danger' ? 'text-danger-text' : 'text-muted-foreground')} aria-hidden />\n <span>\n <span className={cn('block font-medium', tone === 'danger' ? 'text-danger-text' : 'text-foreground')}>{name}</span>\n {description && <span className=\"mt-0.5 hidden text-xs leading-snug text-muted-foreground md:block\">{description}</span>}\n </span>\n </>\n )\n return (\n <li key={name}>\n {render ? (\n render({ className: itemClass, children })\n ) : (\n <button type=\"button\" onClick={onRun} disabled={Boolean(blocked) || running} title={blocked} className={itemClass}>\n {children}\n </button>\n )}\n </li>\n )\n })}\n </ul>\n </div>\n)\n","import { useEffect, useMemo } from 'react'\nimport type { FieldModel, ResourceModel } from '@protobase/schema'\nimport { useList } from '../data/use-list'\n\n/** The most lines a record's line editor loads; a record with more shows them read-only, as it cannot save them as a whole. */\nexport const linesLimit = 1000\n\n/**\n * The numbered lines of a record, in the order of their `position` field, as the server has them: every page, up to\n * `linesLimit`, each as large as the API gives. `labels` names the records their relations point at. Nothing is\n * fetched without a lines resource.\n */\nexport const useLines = (lines: ResourceModel | undefined, link: FieldModel | undefined, position: string | undefined, parentKey: string, labels?: Record<string, string>) => {\n const list = useList(lines?.name ?? '', {\n enabled: Boolean(lines && link),\n filter: link ? `${link.name} = \"${parentKey}\"` : undefined,\n pageSize: 500,\n labels,\n ...(position && lines?.fields[position]?.sortable && { orderBy: `${position} asc` }),\n })\n // The same array while no page changes, so what depends on the lines is worked out again only when they do\n const items = useMemo(() => (position ? [...list.items].sort((a, b) => Number(a[position]) - Number(b[position])) : list.items), [list.data, position])\n const more = list.hasNextPage && list.items.length < linesLimit\n useEffect(() => {\n if (more && !list.isFetchingNextPage) void list.fetchNextPage()\n }, [more, list.isFetchingNextPage])\n return {\n items,\n labels: list.labels,\n loading: (list.isPending || more) && Boolean(lines),\n /** Every line is loaded, so the lines can be saved as a whole. */\n complete: !list.hasNextPage,\n }\n}\n","import type { ResourceModel } from '@protobase/schema'\n\n/** The field that holds when a record was created or last updated: `created_at` or `createdAt`, as the model names it. */\nexport const auditField = (model: ResourceModel, kind: 'created' | 'updated') => [`${kind}_at`, `${kind}At`].find((name) => model.fields[name])\n","import type { ReactNode } from 'react'\nimport type { CustomSectionModel } from '@protobase/schema'\nimport { unmarkFieldRefs } from '@protobase/schema/internal'\nimport { Section, SidebarCard } from '../record-view'\nimport { CustomOrFallback } from './pages/custom-or-fallback'\nimport { useProjectUi } from './pages/project-ui'\nimport { RecordScope, type LayoutRecord } from './pages/record-scope'\n\n// A section or a sidebar card under the item's title when it has one\nconst frame = (item: CustomSectionModel, body: ReactNode) => {\n if (item.sidebar) return item.title ? <SidebarCard title={item.title}>{body}</SidebarCard> : body\n return item.title ? <Section title={item.title}>{body}</Section> : <section className=\"py-8\">{body}</section>\n}\n\n/**\n * A component of the record layout (`l.custom`), drawn with the record around it, so `useLayoutRecord()` gives it, in a\n * section or a sidebar card under its title when it has one. The record page around it stays the framework's. When the\n * component is missing or throws, `fallback`, the item's fallback as the page draws it, takes its place, title included.\n */\nexport const CustomSection = ({ item, scope, fallback }: { item: CustomSectionModel; scope: LayoutRecord; fallback: ReactNode | undefined }) => {\n const { components } = useProjectUi()\n const Component = components?.[item.component]\n const body = Component && (\n <RecordScope value={scope}>\n <Component {...unmarkFieldRefs(item.props ?? {})} />\n </RecordScope>\n )\n // Without a fallback the warning stands in the frame, where the component would\n if (fallback === undefined) {\n return frame(\n item,\n <CustomOrFallback name={item.component} registered={Boolean(Component)} fallback={undefined}>\n {body}\n </CustomOrFallback>,\n )\n }\n return (\n <CustomOrFallback name={item.component} registered={Boolean(Component)} fallback={fallback}>\n {frame(item, body)}\n </CustomOrFallback>\n )\n}\n","import type { ReactElement, ReactNode } from 'react'\nimport { usePageScroll } from '../app-shell'\nimport { CustomBoundary } from './pages/custom-boundary'\nimport { useProjectUi } from './pages/project-ui'\nimport { RecordScope, type LayoutRecord } from './pages/record-scope'\n\n/**\n * A record page that is a component of the app's own (`.record({ component })`), with the record around it as\n * `useLayoutRecord()` gives it. It fills the content area, which does not scroll while it shows; `standard`, the\n * record's standard page, shows instead while the component is missing or when it throws.\n */\nexport const FullAreaRecord = ({ component, scope, standard }: { component: string; scope: LayoutRecord; standard: ReactElement }) => {\n const { components } = useProjectUi()\n const Component = components?.[component]\n if (!Component) return standard\n return (\n <CustomBoundary name={component} fallback={standard}>\n <FullArea>\n <RecordScope value={scope}>\n <Component />\n </RecordScope>\n </FullArea>\n </CustomBoundary>\n )\n}\n\n/**\n * The content area of a record page that fills it, where the page does not scroll. Inside a boundary, a component that\n * throws takes the page's scrolling back with it. The one grid cell stretches its child to the area's width and height.\n */\nexport const FullArea = ({ children }: { children: ReactNode }) => {\n usePageScroll(false)\n return <div className=\"grid min-h-0 flex-1 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)]\">{children}</div>\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { RecordCall } from '../../calls/record-call'\nimport { useRecordCallAddress } from '../../calls/use-record-call-address'\nimport { useClient } from '../../data/api-provider'\nimport { useMembers } from '../../people/use-members'\nimport type { LayoutRecord } from '../pages/record-scope'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord }\n\n/**\n * The record's call while the page joins it (`?call=join`), on a conversation with `call`: beside the messages, or\n * above them at mobile width, half the space either way, so the box under the messages stays in view. It opens the\n * `call` function's socket with the record's key, and names the people in it after the organization's members.\n */\nexport const ConversationCall = ({ page, scope }: Props) => {\n const { joining } = useRecordCallAddress(scope.model.name, scope.key)\n const client = useClient()\n const members = useMembers()\n if (page.call === undefined || !joining) return null\n return (\n <div className=\"grid min-h-0 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)] border-border max-md:h-1/2 max-md:border-b md:w-1/2 md:border-r\">\n <RecordCall resource={scope.model.name} recordKey={scope.key} url={client.functionSocketUrl(page.call, { key: scope.key })} nameOf={(user) => members.member(user)?.name ?? user} />\n </div>\n )\n}\n","import { useOptionalAuth } from '../../auth/auth-provider'\nimport { useMembers } from '../../people/use-members'\nimport { presenceOf, usePresence } from '../../presence/presence'\nimport { StatusMark } from '../../status/status-mark'\nimport { otherMembers } from '../titles/member-names'\n\n/**\n * The people of a members field other than the reader, by name, each with their presence and status as `StatusMark`\n * draws it: its text in full beside one person, on hover beside several. `fallback`, the record's title, shows until\n * every name is known.\n */\nexport const MembersTitle = ({ value, fallback }: { value: unknown; fallback: string }) => {\n const auth = useOptionalAuth()\n const me = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const { member } = useMembers()\n const presence = usePresence()\n const others = otherMembers(value, me)\n if (others.length === 0 || !others.every((id) => member(id))) return fallback\n return others.map((id, index) => (\n <span key={id} className=\"inline-flex min-w-0 items-center gap-1.5\">\n {member(id)!.name}\n <StatusMark status={member(id)!.status} presence={presenceOf(presence, id)} textShown={others.length === 1 ? 'full' : 'hover'} />\n {index < others.length - 1 && ','}\n </span>\n ))\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { CallMark } from '../../calls/call-mark'\nimport { cn } from '../../lib/cn'\nimport { buttonClass } from '../../primitives/button'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { AppLink } from '../use-app-address'\nimport { MembersTitle } from './members-title'\nimport { text } from './messages'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord; title: string }\n\n/**\n * The slim row over a conversation: the record's title, which the top bar repeats at mobile width and so shows only on\n * a wider screen, or with `members` the other people in it with their status, shown at every width; its `subtitle`\n * beside it; with `call`, the record's call, Start call or the call going on with Join; and a link to the record's\n * standard page, where its details, Edit and Delete are.\n */\nexport const ConversationHeader = ({ page, scope, title }: Props) => {\n const subtitle = page.subtitle === undefined ? undefined : scope.record[page.subtitle]\n const members = page.members !== undefined\n return (\n <div className=\"flex h-12 shrink-0 items-center gap-3 border-b border-border bg-background px-4\">\n <h1 className={cn(members ? 'flex' : 'hidden md:flex', 'min-w-0 items-center gap-2 truncate font-medium')}>{members ? <MembersTitle value={scope.record[page.members!]} fallback={title} /> : title}</h1>\n {typeof subtitle === 'string' && subtitle !== '' && <p className=\"min-w-0 flex-1 truncate text-sm text-muted-foreground\">{subtitle}</p>}\n <div className=\"ml-auto flex shrink-0 items-center gap-2\">\n {page.call !== undefined && <CallMark resource={scope.model.name} recordKey={scope.key} />}\n <AppLink to={{ kind: 'record', resource: scope.model.name, key: scope.key, standard: true }} className={buttonClass({ variant: 'ghost', size: 'sm' })}>\n {text('details')}\n </AppLink>\n </div>\n </div>\n )\n}\n","import { Button } from '../../primitives/button'\nimport { ResponsiveDialog } from '../../primitives/responsive-dialog'\nimport { text } from './messages'\n\n/** Asks before a message is deleted, since it goes for everyone in the conversation. */\nexport const DeleteMessageDialog = ({ onDelete, onClose }: { onDelete: () => void; onClose: () => void }) => (\n <ResponsiveDialog\n open\n title={text('deleteTitle')}\n description={text('deleteDescription')}\n onClose={onClose}\n actions={\n <>\n <Button onClick={onClose}>{text('cancel')}</Button>\n <Button variant=\"danger\" onClick={onDelete}>\n {text('delete')}\n </Button>\n </>\n }\n />\n)\n","import { Button, buttonClass } from '../../primitives/button'\nimport { AppLink } from '../use-app-address'\nimport type { MessageControls } from './message-controls'\nimport { text } from './messages'\n\n/**\n * What the reader can do to a message, a bar over its top right corner shown while they point at it or move into it with\n * the keyboard, so it takes no room of its own: react with an emoji they have not reacted with yet, reply in its\n * thread, edit and delete. Only a screen that can point shows it; on a touch screen a tap or long-press opens\n * `MessageActionsSheet` instead.\n */\nexport const MessageActionsBar = ({ controls }: { controls: MessageControls }) => {\n const { emoji, groups, onReact, thread, onEdit, onDelete } = controls\n const reacted = new Set(groups.filter((group) => group.mine).map((group) => group.emoji))\n const offered = onReact ? emoji.filter((entry) => !reacted.has(entry.emoji)) : []\n if (offered.length === 0 && !thread && !onEdit && !onDelete) return null\n return (\n <div\n role=\"toolbar\"\n aria-label={text('messageActions')}\n className=\"pointer-events-none absolute -top-3 right-0 z-10 hidden items-center gap-0.5 rounded-md border border-border bg-background p-0.5 opacity-0 shadow-sm transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100 [@media(hover:hover)]:flex\"\n >\n {offered.map(({ emoji: value, symbol, name }) => (\n <Button key={value} size=\"icon\" variant=\"ghost\" aria-label={text('reactWith', { name })} title={name} onClick={() => onReact!(value)}>\n <span aria-hidden>{symbol}</span>\n </Button>\n ))}\n {thread && (\n <AppLink to={thread} className={buttonClass({ variant: 'ghost', size: 'sm' })}>\n {text('replyInThread')}\n </AppLink>\n )}\n {onEdit && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onEdit}>\n {text('edit')}\n </Button>\n )}\n {onDelete && (\n <Button size=\"sm\" variant=\"ghost\" onClick={onDelete}>\n {text('delete')}\n </Button>\n )}\n </div>\n )\n}\n","import { Button, buttonClass } from '../../primitives/button'\nimport { ResponsiveDialog } from '../../primitives/responsive-dialog'\nimport { AppLink } from '../use-app-address'\nimport type { MessageControls } from './message-controls'\nimport { text } from './messages'\n\ntype Props = {\n controls: MessageControls\n /** Names the message it acts on, such as \"Message from Lena Fischer\". */\n title: string\n /** The message's text, shown under the title. */\n preview: string\n onClose: () => void\n}\n\n/**\n * What the reader can do to a message, opened by a finger's tap or long-press on it, under a line of the message: a row\n * of every emoji, those they reacted with pressed, taking their reaction back as its chip does, then reply in its\n * thread, copy its text, edit and delete. A sheet from the bottom at mobile width, a dialog on a wider touch screen.\n * Each choice closes it.\n */\nexport const MessageActionsSheet = ({ controls, title, preview, onClose }: Props) => {\n const { emoji, groups, onReact, onUnreact, thread, onCopy, onEdit, onDelete } = controls\n const mine = new Map(groups.flatMap((group) => (group.mine ? [[group.emoji, group.mine] as const] : [])))\n const choose = (onChoose: () => void) => () => {\n onClose()\n onChoose()\n }\n // The sheet stacks its buttons from the last up, and the dialog lines them up from the left: Delete leftmost there,\n // Reply in thread on top here\n return (\n <ResponsiveDialog\n open\n title={title}\n description={preview && <span className=\"line-clamp-2\">{preview}</span>}\n onClose={onClose}\n actions={\n <>\n {onDelete && (\n <Button variant=\"danger\" onClick={choose(onDelete)}>\n {text('delete')}\n </Button>\n )}\n {onEdit && <Button onClick={choose(onEdit)}>{text('edit')}</Button>}\n {onCopy && <Button onClick={choose(onCopy)}>{text('copyText')}</Button>}\n {thread && (\n <AppLink to={thread} className={buttonClass()} onClick={onClose}>\n {text('replyInThread')}\n </AppLink>\n )}\n </>\n }\n >\n {emoji.length > 0 && (\n <div role=\"group\" aria-label={text('react')} className=\"flex flex-wrap gap-1\">\n {emoji.map(({ emoji: value, symbol, name }) => {\n const reaction = mine.get(value)\n const press = reaction ? onUnreact && (() => onUnreact(reaction)) : onReact && (() => onReact(value))\n return (\n <Button key={value} size=\"icon\" variant={reaction ? 'secondary' : 'ghost'} aria-pressed={reaction !== undefined} aria-label={text('reactWith', { name })} disabled={!press} onClick={press && choose(press)}>\n <span aria-hidden>{symbol}</span>\n </Button>\n )\n })}\n </div>\n )}\n </ResponsiveDialog>\n )\n}\n","import type { AttachmentsModel, ResourceModel } from '@protobase/schema'\nimport { recordKey } from '../../live/model-helpers'\nimport { fileShown, isPreviewable } from '../../live/file-values'\n\ntype Row = Record<string, unknown>\n\n/**\n * A file under a message, as its attachment record gives it: the record's key, which deletes it, the file's name, type\n * and size from the file field's value, the signed link the API answers with it, `undefined` while the file is missing\n * from storage, and an image's size in pixels where the record holds it.\n */\nexport type Attachment = { key: ReturnType<typeof recordKey>; name: string; type: string; size: number | undefined; url: string | undefined; width: number | undefined; height: number | undefined }\n\nconst pixels = (value: unknown) => (typeof value === 'number' ? value : undefined)\n\n/** The attachment record `row` as an `Attachment`; `undefined` for one with no file. */\nexport const attachmentOf = (row: Row, model: ResourceModel, attachments: AttachmentsModel): Attachment | undefined => {\n const file = fileShown(row[attachments.file])\n if (!file) return\n const stored = 'missing' in file ? undefined : file\n return {\n key: recordKey(model, row),\n name: file.name,\n type: file.type,\n size: stored?.size,\n url: stored?.url,\n width: attachments.width === undefined ? undefined : pixels(row[attachments.width]),\n height: attachments.height === undefined ? undefined : pixels(row[attachments.height]),\n }\n}\n\n/** Attachment rows by the key of the message they are in, as text, each message's in the order the rows came. */\nexport const attachmentsByMessage = (rows: readonly Row[], model: ResourceModel, attachments: AttachmentsModel) => {\n const byMessage = new Map<string, Attachment[]>()\n for (const row of rows) {\n const attachment = attachmentOf(row, model, attachments)\n if (!attachment) continue\n const message = String(row[attachments.field])\n byMessage.set(message, [...(byMessage.get(message) ?? []), attachment])\n }\n return byMessage\n}\n\n/** Whether a file shows as an image under its message, rather than as a link that downloads it: a raster image with a link. */\nexport const isPreviewed = (attachment: Pick<Attachment, 'type' | 'url'>) => attachment.url !== undefined && isPreviewable(attachment.type)\n","import { FileText } from 'lucide-react'\nimport { formatSize } from '../../live/file-values'\nimport { buttonClass } from '../../primitives/button'\nimport { isPreviewed, type Attachment } from './attachments'\nimport { text } from './messages'\n\n/** The tallest an image preview is drawn, in CSS pixels; a wider one is scaled down to the message's width. */\nexport const previewHeight = 240\n\nconst FileLabel = ({ attachment }: { attachment: Attachment }) => (\n <>\n <FileText className=\"size-4\" />\n <span className=\"max-w-64 truncate\">{attachment.name}</span>\n {attachment.size !== undefined && <span className=\"text-muted-foreground\">{formatSize(attachment.size)}</span>}\n </>\n)\n\nconst FileDownload = ({ attachment }: { attachment: Attachment }) => {\n const className = buttonClass({ variant: 'secondary', size: 'sm' })\n if (attachment.url === undefined) {\n return (\n <span className={className} aria-disabled title={text('fileMissing')}>\n <FileLabel attachment={attachment} />\n </span>\n )\n }\n return (\n <a href={attachment.url} download={attachment.name} className={className}>\n <FileLabel attachment={attachment} />\n </a>\n )\n}\n\n/**\n * A message's files under its text: an image as a preview at most `previewHeight` high, a link that opens it in a new\n * tab, any other file as a link with its name and size that downloads it. The links are those the API signs for the\n * reader.\n */\nexport const MessageAttachments = ({ attachments }: { attachments: readonly Attachment[] }) => (\n <div className=\"flex flex-wrap items-start gap-2\">\n {attachments.map((attachment) =>\n isPreviewed(attachment) ? (\n <a key={String(attachment.key)} href={attachment.url} target=\"_blank\" rel=\"noreferrer\" title={attachment.name} className=\"max-w-full\">\n <img\n src={attachment.url}\n alt={attachment.name}\n width={attachment.width}\n height={attachment.height}\n style={{ maxHeight: previewHeight }}\n className=\"h-auto w-auto max-w-full rounded-md border border-border object-contain\"\n />\n </a>\n ) : (\n <FileDownload key={String(attachment.key)} attachment={attachment} />\n ),\n )}\n </div>\n)\n","import { useEffect, useRef, useState, type KeyboardEvent } from 'react'\nimport { MentionBox, mentionedIds, type MentionDraft, type PeopleSearch, type PickedUser } from '../../mentions'\nimport { Button } from '../../primitives/button'\nimport { text } from './messages'\n\ntype Props = {\n /** The message's text as it is. */\n body: string\n /** The people it mentions, by id and name, kept while their `@name` stays in the text. */\n picked: PickedUser[]\n /** Finds the people `@` lists; without it, `@` is plain text. */\n searchPeople?: PeopleSearch\n /** Resolves true once saved; false leaves the box open, as the server refused it. */\n onSave: (body: string, mentions: string[]) => Promise<boolean>\n onCancel: () => void\n}\n\n/**\n * A message's text in a box to change it, its mentions kept while their `@name` stays: Enter or Save keeps the trimmed\n * text, Shift+Enter starts a new line, Escape or Cancel leaves it as it was. An empty text is no edit: deleting is.\n * The box is read-only while it saves, so nothing typed then is lost, and a save that ends after the box closed\n * closes nothing, such as the box opened again on the same message.\n */\nexport const MessageEditor = ({ body, picked, searchPeople, onSave, onCancel }: Props) => {\n const [draft, setDraft] = useState<MentionDraft>({ text: body, picked })\n const [saving, setSaving] = useState(false)\n const mounted = useRef(true)\n useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n }\n }, [])\n const trimmed = draft.text.trim()\n const save = async () => {\n if (trimmed === '' || saving) return\n if (trimmed === body) return onCancel()\n setSaving(true)\n const saved = await onSave(trimmed, mentionedIds(trimmed, draft.picked))\n if (!mounted.current) return\n setSaving(false)\n if (saved) onCancel()\n }\n const keys = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.nativeEvent.isComposing) return\n if (event.key === 'Escape') return onCancel()\n if (event.key !== 'Enter' || event.shiftKey) return\n event.preventDefault()\n void save()\n }\n return (\n <div className=\"flex flex-col gap-2 whitespace-normal\">\n <MentionBox value={draft} onChange={setDraft} searchPeople={searchPeople} onKeyDown={keys} readOnly={saving} aria-label={text('editMessage')} autoFocus />\n <div className=\"flex gap-2\">\n <Button size=\"sm\" variant=\"primary\" disabled={trimmed === ''} loading={saving} onClick={() => void save()}>\n {text('save')}\n </Button>\n <Button size=\"sm\" onClick={onCancel}>\n {text('cancel')}\n </Button>\n </div>\n </div>\n )\n}\n","import { Button } from '../../primitives/button'\nimport type { ReactionGroup } from './reactions'\nimport { text } from './messages'\n\ntype Props = {\n groups: readonly ReactionGroup[]\n member: (id: string) => { name: string } | undefined\n /** Given when the reader may react. */\n onReact?: (emoji: string) => void\n /** Given when the reader may take back their own reaction. */\n onUnreact?: (reaction: Record<string, unknown>) => void\n}\n\n/**\n * A message's reactions, one button per emoji with its count, naming who reacted on hover: the reader's own filled,\n * taking it back when pressed, and another's adding the reader's with the same emoji.\n */\nexport const ReactionChips = ({ groups, member, onReact, onUnreact }: Props) =>\n groups.map(({ emoji, symbol, name, count, userIds, mine }) => {\n const people = userIds.map((id) => member(id)?.name ?? text('someone')).join(', ')\n const press = mine ? onUnreact && (() => onUnreact(mine)) : onReact && (() => onReact(emoji))\n return (\n <Button key={emoji} size=\"sm\" variant={mine ? 'primary' : 'secondary'} aria-pressed={mine !== undefined} aria-label={text('reactedBy', { name, people })} title={people} disabled={!press} onClick={press}>\n <span aria-hidden>{symbol}</span>\n <span>{count}</span>\n </Button>\n )\n })\n","import { chatDayLabel } from '../../chat/chat-day'\nimport { formatTime } from '../../format/date'\nimport { viewerZone } from '../../format/zone'\nimport { text } from './messages'\n\n/** When a thread's last reply came, sent at `time`: \"Last reply Today, 10:42\", in the viewer's zone unless given. */\nexport const lastReplyLabel = (time: string, now = Date.now(), zone = viewerZone()) => text('lastReply', { time: `${chatDayLabel(time, now, zone)}, ${formatTime(Date.parse(time), zone)}` })\n","import type { AppAddress } from '@protobase/schema'\nimport { formatDateTime } from '../../format/date'\nimport { buttonClass } from '../../primitives/button'\nimport { AppLink } from '../use-app-address'\nimport { lastReplyLabel } from './reply-labels'\nimport { text } from './messages'\n\ntype Props = { count: number; last: string | undefined; to: AppAddress }\n\n/** Under a thread's first message in the conversation: its number of replies, a link that opens the thread, and when the last one came. */\nexport const ThreadSummary = ({ count, last, to }: Props) => (\n <div className=\"flex items-center gap-2 whitespace-normal\">\n <AppLink to={to} className={`${buttonClass({ variant: 'ghost', size: 'sm' })} -ml-2.5`}>\n {text('replies', { count })}\n </AppLink>\n {last !== undefined && (\n <time dateTime={last} title={formatDateTime(Date.parse(last))} className=\"text-xs text-muted-foreground\">\n {lastReplyLabel(last)}\n </time>\n )}\n </div>\n)\n","import type { ResourcePermissions } from '@protobase/client'\nimport { evaluateCondition, parseCondition } from '@protobase/layout'\nimport type { ConversationPageModel } from '@protobase/schema'\nimport { can, rowAllows } from '../permissions'\n\ntype Row = Record<string, unknown>\n\n// Delete is offered unless its condition holds for the message; one that does not parse keeps every message\nconst deleteAllowed = (option: ConversationPageModel['delete'], row: Row) => {\n if (option === undefined || option === false) return false\n if (option === true) return true\n const condition = parseCondition(option.unless)\n return condition.ok && !evaluateCondition(condition, row)\n}\n\n/**\n * What the reader may do to a message, as far as the page can tell: edit their own (`mine`) when the conversation lets\n * authors edit, and delete one when it lets anyone and its condition does not keep the message, each only where the\n * resource's access and the row's own permissions allow it. The server checks every write again.\n */\nexport const messageAccess = (page: Pick<ConversationPageModel, 'edit' | 'delete'>, row: Row, mine: boolean, permissions: ResourcePermissions) => ({\n edit: page.edit === true && mine && can(permissions, 'update') && rowAllows(row, 'update'),\n delete: deleteAllowed(page.delete, row) && can(permissions, 'delete') && rowAllows(row, 'delete'),\n})\n\n/** Whether the reader may react, and take back their own reactions, by the reaction resource's access. */\nexport const reactionAccess = (permissions: ResourcePermissions) => ({ react: can(permissions, 'create'), unreact: can(permissions, 'delete') })\n","import type { ReactionsModel } from '@protobase/schema'\n\ntype Row = Record<string, unknown>\n\n/**\n * One emoji under a message: its label, how many reacted with it and who, by user id, and the reader's own reaction\n * with it, if any, as the row the reactions API gave.\n */\nexport type ReactionGroup = { emoji: string; symbol: string; name: string; count: number; userIds: string[]; mine?: Row }\n\n/** An emoji a conversation offers, as it stores it, draws it and names it. */\nexport type EmojiEntry = { emoji: string; symbol: string; name: string }\n\n/** The emoji a conversation offers, in the order of the emoji field's values, each with its label. */\nexport const emojiSet = (reactions: Pick<ReactionsModel, 'labels'>, values: readonly string[]): EmojiEntry[] =>\n values.flatMap((emoji) => (Object.hasOwn(reactions.labels, emoji) ? [{ emoji, ...reactions.labels[emoji]! }] : []))\n\n/** Reaction rows by the key of the message they answer, as text. */\nexport const reactionsByMessage = (rows: readonly Row[], field: string) => {\n const byMessage = new Map<string, Row[]>()\n for (const row of rows) {\n const message = String(row[field])\n byMessage.set(message, [...(byMessage.get(message) ?? []), row])\n }\n return byMessage\n}\n\n/** A message's reactions per emoji of `set`, in its order, each emoji someone reacted with once; `me` finds the reader's own. */\nexport const reactionGroups = (rows: readonly Row[], { user, emoji: field }: Pick<ReactionsModel, 'user' | 'emoji'>, set: readonly EmojiEntry[], me: string | undefined): ReactionGroup[] =>\n set.flatMap(({ emoji, symbol, name }) => {\n const these = rows.filter((row) => row[field] === emoji)\n if (these.length === 0) return []\n const userIds = these.map((row) => String(row[user]))\n return [{ emoji, symbol, name, count: these.length, userIds, mine: me === undefined ? undefined : these.find((row) => row[user] === me) }]\n })\n","import { useToast } from '../../toasts/toast-provider'\nimport { messageAccess, reactionAccess } from './message-access'\nimport type { MessageControls } from './message-controls'\nimport type { MessageSetup } from './message-setup'\nimport { reactionGroups } from './reactions'\nimport { text } from './messages'\n\ntype Message = { row: Record<string, unknown>; key: string; mine: boolean; body: string; onEdit: () => void; onDelete: () => void }\n\n/** What the reader can do to one message, as `MessageControls`, by the conversation's options and their access. */\nexport const useMessageControls = (setup: MessageSetup, { row, key, mine, body, onEdit, onDelete }: Message): MessageControls => {\n const toast = useToast()\n const { page, me, writes } = setup\n const access = messageAccess(page, row, mine, setup.messagePermissions)\n const reacts = reactionAccess(setup.reactionPermissions)\n const groups = page.reactions ? reactionGroups(setup.reactionsOf(key), page.reactions, setup.emoji, me) : []\n const copy = () =>\n navigator.clipboard.writeText(body).then(\n () => void toast.show({ state: 'success', title: text('copied') }),\n () => void toast.show({ state: 'error', title: text('notCopied') }),\n )\n return {\n emoji: reacts.react ? setup.emoji : [],\n groups,\n onReact: writes.react && reacts.react ? (emoji) => void writes.react!(key, emoji) : undefined,\n onUnreact: writes.unreact && reacts.unreact ? (reaction) => void writes.unreact!(reaction) : undefined,\n thread: setup.threadTo?.(key),\n onCopy: body === '' ? undefined : () => void copy(),\n onEdit: access.edit ? onEdit : undefined,\n onDelete: access.delete ? onDelete : undefined,\n }\n}\n","/** How long a finger rests on a message before its actions open without letting go. */\nexport const longPressMs = 500\n\n/** How far, in CSS pixels, a finger may drift before its press counts as a scroll rather than a tap or long-press. */\nexport const pressSlop = 10\n\n/**\n * Where a finger came down on a message, while it may still become a tap or long-press. `tapOpens`: a tap opens the\n * actions too, unless it came while the reader was typing, when it only lowers the keyboard. `lifted`: the finger is\n * up, so only the tap's click may still come, however late the browser sends it.\n */\nexport type Press = { x: number; y: number; tapOpens: boolean; lifted?: true } | undefined\n\nexport type PressEvent =\n /**\n * `touch`: a finger rather than a mouse or pen. `onControl`: on a link or button of the message, which keeps its own\n * press. `typing`: a text box had the focus, so the on-screen keyboard is up.\n */\n | { type: 'down'; x: number; y: number; touch: boolean; onControl: boolean; typing: boolean }\n | { type: 'move'; x: number; y: number }\n /** The finger lifted. */\n | { type: 'up' }\n /** The browser took the touch over, such as to scroll. */\n | { type: 'cancel' }\n /** The finger stayed down for `longPressMs`. */\n | { type: 'held' }\n /** The browser's click after the finger lifted. */\n | { type: 'tap' }\n\n/**\n * The next state of a press on a message, and whether it opens the message's actions: a finger that comes down on the\n * message, off its links and buttons, and lifts or rests there without drifting away; a tap while the reader types\n * only lowers the keyboard. A mouse keeps the hover bar.\n */\nexport const nextPress = (press: Press, event: PressEvent): { press: Press; open: boolean } => {\n if (event.type === 'down') {\n return { press: event.touch && !event.onControl ? { x: event.x, y: event.y, tapOpens: !event.typing } : undefined, open: false }\n }\n if (event.type === 'cancel') return { press: undefined, open: false }\n if (event.type === 'up') return { press: press && { ...press, lifted: true }, open: false }\n if (event.type === 'move') {\n if (!press) return { press, open: false }\n const drifted = Math.hypot(event.x - press.x, event.y - press.y) > pressSlop\n return { press: drifted ? undefined : press, open: false }\n }\n if (event.type === 'tap') return { press: undefined, open: press?.tapOpens === true }\n if (press?.lifted) return { press, open: false }\n return { press: undefined, open: press !== undefined }\n}\n","import { useEffect, useRef, type MouseEvent, type PointerEvent } from 'react'\nimport { longPressMs, nextPress, type Press, type PressEvent } from './message-press'\n\n/** A message's own links and buttons, such as a mention, a file, a reaction or its thread's replies. */\nconst controls = 'a[href], button, input, textarea, select, [role=\"button\"]'\n\n/** A box the reader types in, which has the on-screen keyboard up while it has the focus. */\nconst textBoxes = 'input, textarea, [contenteditable]:not([contenteditable=\"false\"])'\n\n/**\n * Swallows the click a browser may send when the finger of a long-press lifts, which would land on what the long-press\n * opened, such as the backdrop of its sheet, and close it again. A new press or key comes before any later click, so\n * it stops there.\n */\nconst swallowReleaseClick = () => {\n const swallow = (event: Event) => {\n event.preventDefault()\n event.stopPropagation()\n stop()\n }\n const stop = () => {\n window.removeEventListener('click', swallow, true)\n window.removeEventListener('pointerdown', stop, true)\n window.removeEventListener('keydown', stop, true)\n }\n window.addEventListener('click', swallow, true)\n window.addEventListener('pointerdown', stop, true)\n window.addEventListener('keydown', stop, true)\n}\n\n/**\n * The handlers that open a message's actions with a finger: a tap, or a long-press, which opens them while the finger\n * still rests, as `nextPress` decides; a tap while the reader types lowers the keyboard instead. The browser's own\n * long-press menu stays shut on a message pressed this way.\n */\nexport const useMessagePress = (onOpen: () => void) => {\n const press = useRef<Press>(undefined)\n const timer = useRef<ReturnType<typeof setTimeout>>(undefined)\n /** Whether the latest press was a finger's that may open the actions, which the browser's long-press menu leaves alone. */\n const pressing = useRef(false)\n const step = (event: PressEvent) => {\n const next = nextPress(press.current, event)\n press.current = next.press\n if (!next.press) clearTimeout(timer.current)\n return next.open\n }\n useEffect(() => () => clearTimeout(timer.current), [])\n\n return {\n onPointerDown: (event: PointerEvent) => {\n clearTimeout(timer.current)\n const onControl = event.target instanceof Element && event.target.closest(controls) !== null\n const typing = document.activeElement instanceof Element && document.activeElement.matches(textBoxes)\n step({ type: 'down', x: event.clientX, y: event.clientY, touch: event.pointerType === 'touch', onControl, typing })\n pressing.current = press.current !== undefined\n if (!press.current) return\n timer.current = setTimeout(() => {\n if (!step({ type: 'held' })) return\n // A short tick where the device can, as a native long-press gives.\n navigator.vibrate?.(10)\n swallowReleaseClick()\n onOpen()\n }, longPressMs)\n },\n onPointerMove: (event: PointerEvent) => step({ type: 'move', x: event.clientX, y: event.clientY }),\n // A lifted finger is no long-press, even when the browser sends the tap's click later than `longPressMs`\n onPointerUp: () => {\n clearTimeout(timer.current)\n step({ type: 'up' })\n },\n onPointerCancel: () => step({ type: 'cancel' }),\n onClick: () => {\n const lowersKeyboard = press.current?.tapOpens === false\n if (step({ type: 'tap' })) onOpen()\n if (lowersKeyboard && document.activeElement instanceof HTMLElement) document.activeElement.blur()\n },\n onContextMenu: (event: MouseEvent) => {\n if (pressing.current) event.preventDefault()\n },\n }\n}\n","import { useState } from 'react'\nimport { ChatMessage, type ChatAuthor } from '../../chat'\nimport { formatDateTime } from '../../format/date'\nimport { cn } from '../../lib/cn'\nimport { MentionedText } from '../../mentions'\nimport { buttonClass } from '../../primitives/button'\nimport { DeleteMessageDialog } from './delete-message-dialog'\nimport { MessageActionsBar } from './message-actions-bar'\nimport { MessageActionsSheet } from './message-actions-sheet'\nimport { MessageAttachments } from './message-attachments'\nimport { MessageEditor } from './message-editor'\nimport type { MessageSetup } from './message-setup'\nimport { ReactionChips } from './reaction-chips'\nimport { ThreadSummary } from './thread-summary'\nimport { useMessageControls } from './use-message-controls'\nimport { useMessagePress } from './use-message-press'\nimport { text } from './messages'\n\ntype Props = {\n setup: MessageSetup\n row: Record<string, unknown>\n /** The message's key, as text. */\n messageKey: string\n author: ChatAuthor\n time: string | undefined\n continued: boolean\n}\n\nconst idsOf = (value: unknown) => (Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : [])\n\n/**\n * One message under its author, named after the organization's member with their id when there is one: its text with\n * the people it mentions picked out as `MentionedText` does, or a box to change it while its author edits it; its files;\n * in the conversation itself its thread's replies; and a footer of \"(edited)\" once changed and its reactions. What the reader\n * can do to it shows in a bar while they point at it, or, by touch, in a sheet a tap or long-press opens, which also\n * copies its text; a button only a keyboard or screen reader reaches opens that sheet on a touch screen too.\n */\nexport const ConversationMessage = ({ setup, row, messageKey, author, time, continued }: Props) => {\n const { page, me, member } = setup\n const [editing, setEditing] = useState(false)\n const [deleting, setDeleting] = useState(false)\n const [acting, setActing] = useState(false)\n const press = useMessagePress(() => setActing(true))\n const body = row[page.text] == null ? '' : String(row[page.text])\n const mine = me !== undefined && author.id === me\n const name = member(author.id)?.name ?? author.name\n const files = setup.attachmentsOf(messageKey)\n const mentionIds = page.mentions === undefined ? [] : idsOf(row[page.mentions])\n const controls = useMessageControls(setup, { row, key: messageKey, mine, body, onEdit: () => setEditing(true), onDelete: () => setDeleting(true) })\n const edited = page.edited === undefined ? undefined : row[page.edited]\n const replies = page.thread && setup.threadTo ? Number(row[page.thread.count] ?? 0) : 0\n const last = page.thread && typeof row[page.thread.last] === 'string' ? (row[page.thread.last] as string) : undefined\n const chips = controls.groups.length > 0 && <ReactionChips groups={controls.groups} member={member} onReact={controls.onReact} onUnreact={controls.onUnreact} />\n const footer = (typeof edited === 'string' || chips) && (\n <span className=\"flex flex-wrap items-center gap-1\">\n {typeof edited === 'string' && <span title={text('editedAt', { time: formatDateTime(Date.parse(edited)) })}>{text('edited')}</span>}\n {chips}\n </span>\n )\n const title = mine ? text('yourMessage') : name ? text('messageFrom', { name }) : text('message')\n const showLabel = mine ? text('showYourActions') : name ? text('showActionsFrom', { name }) : text('showActions')\n return (\n <>\n <div\n data-message={messageKey}\n className={cn('group relative rounded-md [@media(hover:none)]:select-none [@media(hover:none)]:[-webkit-touch-callout:none] [&_a]:[-webkit-touch-callout:default]', acting && 'bg-muted')}\n {...(!editing && press)}\n >\n {!editing && <MessageActionsBar controls={controls} />}\n {!editing && (\n // On a touch screen, the way in for a screen reader or a keyboard, out of sight until it has the focus\n <button\n type=\"button\"\n className={cn(buttonClass({ variant: 'secondary', size: 'sm' }), 'sr-only focus-visible:not-sr-only focus-visible:absolute focus-visible:right-0 focus-visible:top-0 focus-visible:z-10 [@media(hover:hover)]:hidden')}\n onClick={() => setActing(true)}\n >\n {showLabel}\n </button>\n )}\n <ChatMessage author={{ id: author.id, name }} time={time} continued={continued} footer={footer}>\n {editing ? (\n <MessageEditor\n body={body}\n picked={mentionIds.flatMap((id) => (member(id) ? [{ id, name: member(id)!.name }] : []))}\n searchPeople={setup.searchPeople}\n onSave={(changed, mentions) => setup.writes.edit(messageKey, changed, mentions)}\n onCancel={() => setEditing(false)}\n />\n ) : (\n body !== '' && <MentionedText text={body} mentions={mentionIds.map((id) => ({ name: member(id)?.name }))} />\n )}\n {files.length > 0 && <MessageAttachments attachments={files} />}\n {replies > 0 && controls.thread && <ThreadSummary count={replies} last={last} to={controls.thread} />}\n </ChatMessage>\n </div>\n {deleting && (\n <DeleteMessageDialog\n onClose={() => setDeleting(false)}\n onDelete={() => {\n setDeleting(false)\n void setup.writes.remove(messageKey, files)\n }}\n />\n )}\n {acting && !editing && <MessageActionsSheet controls={controls} title={title} preview={body} onClose={() => setActing(false)} />}\n </>\n )\n}\n","import { threadSort } from '@protobase/layout'\nimport type { Client } from '@protobase/client'\nimport { createWhere, printFilter, type ConversationPageModel, type ReadPositionModel } from '@protobase/schema'\n\nconst where = createWhere()\n\n/** How many messages a page of the conversation brings: the latest on opening, and each \"Load earlier\". */\nexport const conversationPageSize = 50\n\n/** How many records one read of a page of messages' reactions or files brings; a page with more reads on until it has them all. */\nexport const recordsPageSize = 500\n\n/**\n * The read of a conversation's messages through the list API, with the reader's own access, so a message they may not\n * read never shows: those whose relation holds the record's key, newest first, a page at a time. With threads, only\n * the messages of the conversation itself, not the replies in a thread.\n */\nexport const messagesRequest = (page: Pick<ConversationPageModel, 'field' | 'time' | 'thread'>, recordKey: string) => ({\n filter: printFilter(page.thread ? where.and(where.eq(page.field, recordKey), where.isNull(page.thread.field)) : where.eq(page.field, recordKey)),\n orderBy: threadSort(page.time),\n pageSize: conversationPageSize,\n})\n\n/** The read of the replies in the thread of the message keyed `first`, newest first, a page at a time. */\nexport const repliesRequest = (page: Pick<ConversationPageModel, 'time'>, thread: NonNullable<ConversationPageModel['thread']>, first: string) => ({\n filter: printFilter(where.eq(thread.field, first)),\n orderBy: threadSort(page.time),\n pageSize: conversationPageSize,\n})\n\n/** The records of a resource of the messages' own, such as their reactions or files, by its relation `field` to them. */\ntype OfMessages = { resource: string; field: string }\n\n/** The filter of the records, such as reactions, of the messages keyed `messages`. */\nexport const ofMessagesFilter = (of: Pick<OfMessages, 'field'>, messages: readonly string[]) => printFilter(where.in(of.field, [...messages]))\n\n/** Every record, such as a reaction, of the messages keyed `messages`, in one read, or one per `recordsPageSize` of them. */\nexport const readOfMessages = async (client: Pick<Client, 'list'>, of: OfMessages, messages: readonly string[]) => {\n const filter = ofMessagesFilter(of, messages)\n const rows: Record<string, unknown>[] = []\n let pageToken = ''\n do {\n const page = await client.list(of.resource, { filter, pageSize: recordsPageSize, pageToken })\n rows.push(...page.items)\n pageToken = page.nextPageToken\n } while (pageToken)\n return rows\n}\n\n/**\n * The read of the reader's own read position in a record, through the list API: the one whose relation holds the\n * record's key and whose author, `author`, is `me`, even where the resource lets them read other people's.\n */\nexport const ownPositionFilter = (position: Pick<ReadPositionModel, 'field'>, recordKey: string, author: string, me: string) =>\n printFilter(where.and(where.eq(position.field, recordKey), where.eq(author, me)))\n","import type { ChatAuthor } from '../../chat'\nimport { chatDayLabel, sameChatDay } from '../../chat/chat-day'\nimport { authorOf } from '../conversation/thread-items'\n\ntype Row = Record<string, unknown>\n\n/** How long after a message the same author's next one still joins it, so a quick run of messages reads as one. */\nexport const groupWindowMs = 5 * 60_000\n\nexport type MessageFields = { key: (row: Row) => string; sender: string; time: string }\n\n/**\n * One line of a conversation: a day's divider, the \"New messages\" line, or a message under its author, `continued`\n * when it follows the same author's message of a moment ago, so it leaves out their avatar, name and time.\n */\nexport type ConversationRow =\n | { kind: 'day'; key: string; label: string }\n | { kind: 'new'; key: string }\n | { kind: 'message'; key: string; row: Row; author: ChatAuthor; time: string | undefined; continued: boolean }\n\nconst timeOf = (row: Row, time: string) => (typeof row[time] === 'string' ? (row[time] as string) : undefined)\n\n/**\n * The messages, oldest first, as the conversation's lines: a day divider above each day's first message, the \"New\n * messages\" line above the message keyed `newLineAbove`, and each message grouped with the one before it when the same\n * author sent both within `groupWindowMs` on the same day, with no line between.\n */\nexport const conversationRows = (oldestFirst: Row[], { key, sender, time }: MessageFields, newLineAbove?: string, now = Date.now()): ConversationRow[] =>\n oldestFirst.flatMap((row, index): ConversationRow[] => {\n const previous = oldestFirst[index - 1]\n const sent = timeOf(row, time)\n const before = previous && timeOf(previous, time)\n const newDay = sent !== undefined && (before === undefined || !sameChatDay(before, sent))\n const isNew = key(row) === newLineAbove\n const soon = sent !== undefined && before !== undefined && Date.parse(sent) - Date.parse(before) < groupWindowMs\n const author = authorOf(row[sender])\n const continued = !newDay && !isNew && soon && authorOf(previous![sender]).id === author.id\n return [\n ...(newDay ? [{ kind: 'day' as const, key: `day:${key(row)}`, label: chatDayLabel(sent, now) }] : []),\n ...(isNew ? [{ kind: 'new' as const, key: `new:${key(row)}` }] : []),\n { kind: 'message', key: key(row), row, author, time: sent, continued },\n ]\n })\n\nconst keysOf = (rows: Row[], key: (row: Row) => string) => rows.map((row) => Number(key(row)))\n\n/**\n * The key of the message the \"New messages\" line goes above: the first after `lastRead`, the key of the newest message\n * the reader read, by someone other than `me`; none when none is unread. When earlier messages are not loaded and the\n * lowest loaded key is past `lastRead`, the first unread one may be among those, so there is no line rather than one in\n * the wrong place.\n */\nexport const firstUnreadKey = (oldestFirst: Row[], { key, sender }: Omit<MessageFields, 'time'>, lastRead: number, me: string, hasEarlier: boolean) => {\n if (hasEarlier && Math.min(...keysOf(oldestFirst, key)) > lastRead) return\n const found = oldestFirst.find((row) => Number(key(row)) > lastRead && authorOf(row[sender]).id !== me)\n return found && key(found)\n}\n\n/** The highest key among the messages, the one reading them all reads to, whatever order their times put them in. */\nexport const highestKey = (rows: Row[], key: (row: Row) => string) => (rows.length === 0 ? undefined : Math.max(...keysOf(rows, key)))\n","import { useQueries } from '@tanstack/react-query'\nimport type { AttachmentsModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { attachmentsByMessage, type Attachment } from './attachments'\nimport { ofMessagesFilter, readOfMessages } from './conversation-reads'\n\n/**\n * The files of the messages shown, read with the reader's own access in one batch per page of messages, never one read\n * per message, and read again when the files' resource changes, as a sent or deleted message's do: `byMessage` holds\n * each message's files by its key. Without attachments, nothing is read.\n */\nexport const useMessageAttachments = (attachments: AttachmentsModel | undefined, pages: readonly (readonly string[])[]) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const results = useQueries({\n queries: (attachments ? pages.filter((page) => page.length > 0) : []).map((page) => ({\n queryKey: keys.attachmentsOf(attachments!.resource, ofMessagesFilter(attachments!, page)),\n queryFn: () => readOfMessages(client, attachments!, page),\n })),\n })\n const model = attachments && resources[attachments.resource]\n const rows = results.flatMap((result) => result.data ?? [])\n return { byMessage: attachments && model ? attachmentsByMessage(rows, model, attachments) : new Map<string, Attachment[]>(), error: results.find((result) => result.error)?.error ?? undefined }\n}\n","import { useQueries } from '@tanstack/react-query'\nimport type { ReactionsModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { ofMessagesFilter, readOfMessages } from './conversation-reads'\nimport { reactionsByMessage } from './reactions'\n\n/**\n * The reactions to the messages shown, read in one batch per page of messages, never one read per message, and read\n * again as they change: `byMessage` holds each message's reaction rows by its key. Without reactions, nothing is read.\n */\nexport const useMessageReactions = (reactions: ReactionsModel | undefined, pages: readonly (readonly string[])[]) => {\n const client = useClient()\n const results = useQueries({\n queries: (reactions ? pages.filter((page) => page.length > 0) : []).map((page) => ({\n queryKey: keys.reactionsOf(reactions!.resource, ofMessagesFilter(reactions!, page)),\n queryFn: () => readOfMessages(client, reactions!, page),\n })),\n })\n const rows = results.flatMap((result) => result.data ?? [])\n return { byMessage: reactionsByMessage(rows, reactions?.field ?? ''), error: results.find((result) => result.error)?.error ?? undefined }\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport type { Attachment } from './attachments'\nimport { deleteOps } from './message-ops'\nimport { useClient } from '../../data/api-provider'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { useToast } from '../../toasts/toast-provider'\nimport { keyValue } from '../create/create-values'\nimport { refusalReason } from '../displays/board-columns'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRefreshResource } from '../pages/use-layout-data'\nimport { text } from './messages'\n\n/**\n * The writes a reader makes to a conversation's messages, each resolving whether the server took it: edit a message's\n * text and mentions, delete one after its files, and react to one or take a reaction back. A refused write changes nothing on screen\n * and shows the server's reason in a toast; a taken one reads the resource again.\n */\nexport const useMessageWrites = (page: ConversationPageModel) => {\n const client = useClient()\n const toast = useToast()\n const refresh = useRefreshResource()\n const { resources } = useAdminMeta()\n const model = resources[page.resource]!\n const reactions = page.reactions\n\n const run = (resource: string, failed: string, write: () => Promise<unknown>) =>\n write().then(\n () => {\n void refresh(resource)\n return true\n },\n (error: unknown) => {\n toast.show({ state: 'error', title: failed, description: refusalReason(error) })\n return false\n },\n )\n\n const edit = (key: string, body: string, mentions: string[]) =>\n run(page.resource, text('notSaved'), () => client.update(page.resource, key, { [page.text]: body, ...(page.mentions !== undefined && { [page.mentions]: mentions }) }, '*'))\n // Its files first, in the same batch: a message's files never outlive it\n const remove = (key: string, files: readonly Attachment[]) =>\n run(page.resource, text('notDeleted'), () => (page.attachments && files.length > 0 ? client.batchWrite(deleteOps(page, model, key, files)) : client.remove(page.resource, key)))\n const react = reactions && ((key: string, emoji: string) => run(reactions.resource, text('reactionNotSaved'), () => client.create(reactions.resource, { [reactions.field]: keyValue(model, key), [reactions.emoji]: emoji })))\n const unreact = reactions && ((row: Record<string, unknown>) => run(reactions.resource, text('reactionNotSaved'), () => client.remove(reactions.resource, keyOf(resources[reactions.resource]!, row))))\n return { edit, remove, react, unreact }\n}\n","import type { AppAddress, ConversationPageModel } from '@protobase/schema'\nimport type { PeopleSearch } from '../../mentions'\nimport { useMembers } from '../../people/use-members'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport type { MessageSetup } from './message-setup'\nimport { emojiSet } from './reactions'\nimport { useMessageAttachments } from './use-message-attachments'\nimport { useMessageReactions } from './use-message-reactions'\nimport { useMessageWrites } from './use-message-writes'\n\ntype Input = {\n page: ConversationPageModel\n me: string | undefined\n /** The keys of the messages shown, a list per page they were read in, whose reactions and files are read a page at a time. */\n pages: readonly (readonly string[])[]\n threadTo?: (key: string) => AppAddress\n searchPeople?: PeopleSearch\n}\n\n/** The `MessageSetup` of the messages shown, with their reactions and files read, and the errors of those reads, if any. */\nexport const useMessageSetup = ({ page, me, pages, threadTo, searchPeople }: Input) => {\n const { resources } = useAdminMeta()\n const { member } = useMembers()\n const writes = useMessageWrites(page)\n const messagePermissions = usePermissions(page.resource)\n const reactionPermissions = usePermissions(page.reactions?.resource ?? page.resource)\n const reactions = useMessageReactions(page.reactions, pages)\n const files = useMessageAttachments(page.attachments, pages)\n const values = page.reactions ? (resources[page.reactions.resource]?.fields[page.reactions.emoji]?.enumValues ?? []) : []\n const setup: MessageSetup = {\n page,\n me,\n member,\n writes,\n emoji: page.reactions ? emojiSet(page.reactions, values) : [],\n messagePermissions,\n reactionPermissions,\n reactionsOf: (key) => reactions.byMessage.get(key) ?? [],\n attachmentsOf: (key) => files.byMessage.get(key) ?? [],\n threadTo,\n searchPeople,\n }\n return { setup, reactionsError: reactions.error, attachmentsError: files.error }\n}\n","import { useState } from 'react'\n\n/**\n * The key of the message the \"New messages\" line goes above, or undefined for none: decided once by `decide`, when the\n * first messages and the read position at opening are both there, and kept while the page is open, so the line neither\n * moves nor appears under a reader following new messages as they come.\n */\nexport const useNewLine = (decidable: boolean, decide: () => string | undefined) => {\n const [line, setLine] = useState<{ above: string | undefined }>()\n if (!line && decidable) {\n const decided = { above: decide() }\n setLine(decided)\n return decided.above\n }\n return line?.above\n}\n","import type { AppAddress, ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { ChatDivider, ChatThread } from '../../chat'\nimport { useList } from '../../data/use-list'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport type { PeopleSearch } from '../../mentions'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { retryOf, showsErrorAbove, threadState } from '../conversation/thread-state'\nimport { ConversationMessage } from './conversation-message'\nimport { messagesRequest } from './conversation-reads'\nimport { conversationRows, firstUnreadKey, highestKey } from './conversation-rows'\nimport { useMessageSetup } from './use-message-setup'\nimport { useNewLine } from './use-new-line'\nimport { text } from './messages'\n\ntype Props = {\n page: ConversationPageModel\n model: ResourceModel\n recordKey: string\n me: string | undefined\n /** The reader's read position, as `useReadPosition` gives it. */\n position: { ready: boolean; openedAt: number | undefined; readTo: ((key: number) => void) | undefined }\n /** The address that opens a message's thread, for a conversation with threads. */\n threadTo?: (key: string) => AppAddress\n /** Finds the people `@` lists while editing a message. */\n searchPeople?: PeopleSearch\n}\n\n/**\n * The record's messages, the latest page with earlier ones on request, read with the reader's own access and their\n * senders' names in the same read, kept current as the live updates tell of new, changed and deleted ones. They show\n * once the read position is there too, so they open on the \"New messages\" line, and reading to the end moves it. They\n * scroll in a box of their own, so the box that sends one stays in view. Their reactions and files are read a page at a\n * time.\n */\nexport const ConversationMessages = ({ page, model, recordKey, me, position, threadTo, searchPeople }: Props) => {\n const { resources, views } = useAdminMeta()\n const senders = [page.sender]\n const list = useList(model.name, { ...messagesRequest(page, recordKey), labels: listLabels(resources, views, model, senders) })\n const oldestFirst = withLabels(resources, model, senders, list.items, list.labels).reverse()\n const key = (row: Record<string, unknown>) => String(keyOf(model, row))\n const { setup, reactionsError, attachmentsError } = useMessageSetup({ page, me, pages: (list.data?.pages ?? []).map((read) => read.items.map(key)), threadTo, searchPeople })\n const state = threadState(list)\n const loaded = state === 'messages' && !list.isLoading && position.ready\n const newLineAbove = useNewLine(loaded && oldestFirst.length > 0 && position.openedAt !== undefined && me !== undefined, () =>\n firstUnreadKey(oldestFirst, { key, sender: page.sender }, position.openedAt!, me!, list.hasNextPage),\n )\n if (state === 'error') return <div className=\"flex-1 p-4\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>\n // The live region mounts with the messages it opens on, so a screen reader announces only those that arrive later\n if (!loaded) return <div className=\"flex-1 p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n const rows = conversationRows(oldestFirst, { key, sender: page.sender, time: page.time }, newLineAbove)\n const readEnd = highestKey(oldestFirst, key)\n // The reader's own newest message: when one arrives, the thread goes to the end wherever they were\n const own = rows.findLast((line) => line.kind === 'message' && me !== undefined && line.author.id === me)\n const readTo = position.readTo\n return (\n <>\n {showsErrorAbove(list) && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoad')} error={list.error} onRetry={retryOf(list)} /></div>}\n {reactionsError !== undefined && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadReactions')} error={reactionsError} /></div>}\n {attachmentsError !== undefined && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadFiles')} error={attachmentsError} /></div>}\n <ChatThread\n length={oldestFirst.length}\n followKey={own?.key}\n empty={page.empty ?? text('noMessages')}\n onLoadEarlier={list.hasNextPage ? () => void list.fetchNextPage() : undefined}\n loadingEarlier={list.isFetchingNextPage}\n onReadToEnd={readTo && readEnd !== undefined ? () => readTo(readEnd) : undefined}\n >\n {rows.map((line) =>\n line.kind === 'day' ? (\n <ChatDivider key={line.key} label={line.label} />\n ) : line.kind === 'new' ? (\n <ChatDivider key={line.key} tone=\"new\" />\n ) : (\n <ConversationMessage key={line.key} setup={setup} row={line.row} messageKey={line.key} author={line.author} time={line.time} continued={line.continued} />\n ),\n )}\n </ChatThread>\n </>\n )\n}\n","import type { PickedUser } from '../../mentions'\n\n/** The most people `@` lists at once; typing more of a name narrows them. */\nexport const mentionListSize = 8\n\n/**\n * The organization's members whose name holds `query`, ignoring case, other than `me`, in the members' order, at most\n * `mentionListSize`: the people the composer's `@` lists.\n */\nexport const matchingMembers = (members: readonly PickedUser[], query: string, me: string | undefined): PickedUser[] => {\n const wanted = query.toLocaleLowerCase()\n return members\n .filter((person) => person.id !== me && person.name.toLocaleLowerCase().includes(wanted))\n .slice(0, mentionListSize)\n .map(({ id, name }) => ({ id, name }))\n}\n","/** Whether the thread's first message, `row`, is one of the conversation of the record keyed `recordKey`. */\nexport const inConversation = (row: Record<string, unknown>, field: string, recordKey: string) => row[field] != null && String(row[field]) === recordKey\n","import type { ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { useRecord } from '../../data/use-record'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport { keyValue } from '../create/create-values'\nimport { useAdminMeta } from '../meta-gate'\nimport { usePickedLabels } from '../use-picked-labels'\nimport { inConversation } from './thread-head'\n\n/**\n * A thread's first message, keyed `first`, with its sender named as the replies' are: `row` once read and in the\n * conversation of the record keyed `recordKey`, and `elsewhere` when it is another conversation's, such as from an\n * address of another one.\n */\nexport const useThreadHead = (page: ConversationPageModel, model: ResourceModel, recordKey: string, first: string) => {\n const { resources, views } = useAdminMeta()\n const head = useRecord(page.resource, keyValue(model, first))\n const read = head.data?.record\n const senders = [page.sender]\n const sender = model.fields[page.sender]\n const named = page.sender in listLabels(resources, views, model, senders) && sender?.relation ? resources[sender.relation.resource] : undefined\n const ids = named && read?.[page.sender] != null ? [String(read[page.sender])] : []\n const labels = usePickedLabels(named ?? model, named && views[named.name], ids)\n const elsewhere = read !== undefined && !inConversation(read, page.field, recordKey)\n const [row] = read && !elsewhere ? withLabels(resources, model, senders, [read], { [page.sender]: Object.fromEntries(labels) }) : []\n return { row, elsewhere, error: head.error }\n}\n","import type { ConversationPageModel, ResourceModel } from '@protobase/schema'\nimport { ChatDivider, ChatThread } from '../../chat'\nimport { useList } from '../../data/use-list'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { listLabels, withLabels } from '../../live/relation-labels'\nimport type { PeopleSearch } from '../../mentions'\nimport { SidePanel } from '../../side-panel'\nimport { authorOf } from '../conversation/thread-items'\nimport { MessageComposer } from '../conversation/message-composer'\nimport { keyValue } from '../create/create-values'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta } from '../meta-gate'\nimport { Quiet } from '../pages/blocks/card-frame'\nimport { ConversationMessage } from './conversation-message'\nimport { repliesRequest } from './conversation-reads'\nimport { conversationRows } from './conversation-rows'\nimport { useMessageSetup } from './use-message-setup'\nimport { useThreadHead } from './use-thread-head'\nimport { text } from './messages'\n\ntype Props = {\n page: ConversationPageModel & { thread: NonNullable<ConversationPageModel['thread']> }\n /** The record the conversation is of, and its key. */\n owner: ResourceModel\n recordKey: string\n /** The key of the thread's first message. */\n first: string\n me: string | undefined\n searchPeople?: PeopleSearch\n onClose: () => void\n}\n\n/**\n * A thread beside its conversation, covering the screen at mobile width: its first message, its replies kept current\n * as the live updates tell of changes, and a box of its own that replies in it. The reader reacts to, edits and deletes\n * its messages as in the conversation. A first message of another conversation shows as not found, with no box, so no\n * reply joins a thread of another conversation from here. Key it by the first message, so another thread starts afresh.\n */\nexport const ThreadPanel = ({ page, owner, recordKey, first, me, searchPeople, onClose }: Props) => {\n const { resources, views } = useAdminMeta()\n const model = resources[page.resource]!\n const senders = [page.sender]\n const head = useThreadHead(page, model, recordKey, first)\n const list = useList(page.resource, { ...repliesRequest(page, page.thread, first), labels: listLabels(resources, views, model, senders) })\n const oldestFirst = withLabels(resources, model, senders, list.items, list.labels).reverse()\n const key = (row: Record<string, unknown>) => String(keyOf(model, row))\n const { setup, reactionsError, attachmentsError } = useMessageSetup({ page, me, pages: [[first], ...(list.data?.pages ?? []).map((read) => read.items.map(key))], searchPeople })\n const headRow = head.row\n const error = head.error ?? list.error ?? reactionsError ?? attachmentsError\n const rows = conversationRows(oldestFirst, { key, sender: page.sender, time: page.time })\n const own = rows.findLast((line) => line.kind === 'message' && me !== undefined && line.author.id === me)\n const replies = headRow ? Number(headRow[page.thread.count] ?? 0) : 0\n return (\n <SidePanel\n title={text('thread')}\n onClose={onClose}\n footer={\n !head.elsewhere && <MessageComposer\n resource={page.resource}\n field={page.text}\n values={{ [page.field]: keyValue(owner, recordKey), [page.thread.field]: keyValue(model, first) }}\n placeholder={text('replyPlaceholder')}\n searchPeople={searchPeople}\n mentions={page.mentions}\n attachments={page.attachments}\n />\n }\n >\n {error && <div className=\"shrink-0 p-2\"><ErrorBanner title={text('couldNotLoadThread')} error={error} /></div>}\n {head.elsewhere ? (\n <div className=\"flex-1 p-4\"><Quiet>{text('threadElsewhere')}</Quiet></div>\n ) : !headRow || list.isLoading ? (\n <div className=\"flex-1 p-4\"><Quiet>{text('loadingMessages')}</Quiet></div>\n ) : (\n <ChatThread length={oldestFirst.length + 1} followKey={own?.key} onLoadEarlier={list.hasNextPage ? () => void list.fetchNextPage() : undefined} loadingEarlier={list.isFetchingNextPage}>\n <ConversationMessage setup={setup} row={headRow} messageKey={first} author={authorOf(headRow[page.sender])} time={typeof headRow[page.time] === 'string' ? (headRow[page.time] as string) : undefined} continued={false} />\n {replies > 0 && <ChatDivider label={text('replies', { count: replies })} />}\n {rows.map((line) =>\n line.kind === 'day' ? (\n <ChatDivider key={line.key} label={line.label} />\n ) : line.kind === 'new' ? null : (\n <ConversationMessage key={line.key} setup={setup} row={line.row} messageKey={line.key} author={line.author} time={line.time} continued={line.continued} />\n ),\n )}\n </ChatThread>\n )}\n </SidePanel>\n )\n}\n","import { isApiError } from '@protobase/client'\n\n/** The reader's stored position: its record's key, the key of the message they read to, and the version it was read at. */\nexport type SavedPosition = { key: string; lastRead: number; etag: string }\n\n/** How the position is read and written: `update` writes only over the version `at` holds, else rejects with a 412. */\nexport type PositionStore = {\n find: () => Promise<SavedPosition | undefined>\n create: (lastRead: number) => Promise<SavedPosition>\n update: (at: SavedPosition, lastRead: number) => Promise<SavedPosition>\n}\n\n// After another tab's write, the position it stored, which this one compares against once\nconst stored = async (store: PositionStore, failed: unknown) => {\n const found = await store.find()\n if (!found) throw failed\n return found\n}\n\nconst raise = (store: PositionStore, at: SavedPosition, lastRead: number) => (at.lastRead >= lastRead ? at : store.update(at, lastRead))\n\n/**\n * Moves the reader's position up to `lastRead` from `saved`, what this tab last stored, and answers what is stored\n * after. It never moves down: each write goes over the version it compared against, so when another tab wrote since,\n * the write is refused, and the position that tab stored is compared again and kept when it is as far or further. A\n * create another tab beat to it, refused as taken, goes the same way.\n */\nexport const moveReadPosition = async (store: PositionStore, saved: SavedPosition | undefined, lastRead: number): Promise<SavedPosition> => {\n if (saved && saved.lastRead >= lastRead) return saved\n const write = saved ? store.update(saved, lastRead) : store.create(lastRead)\n const status = saved ? 412 : 409\n return write.catch(async (failed: unknown) => {\n if (!isApiError(failed) || failed.status !== status) throw failed\n return raise(store, await stored(store, failed), lastRead)\n })\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport type { ReadPositionModel, ResourceModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { recordKey as keyOf } from '../../live/model-helpers'\nimport { keyValue } from '../create/create-values'\nimport { ownPositionFilter } from './conversation-reads'\nimport { moveReadPosition, type PositionStore, type SavedPosition } from './read-position-write'\n\ntype Props = {\n /** The page's read position, none for a conversation that keeps none. */\n position: ReadPositionModel | undefined\n /** The read position resource, as the reader's `/meta` describes it. */\n model: ResourceModel | undefined\n /** The record the conversation is of. */\n owner: ResourceModel\n recordKey: string\n me: string | undefined\n}\n\n/**\n * The reader's read position in a record's conversation. `openedAt` is the key of the newest message they had read when\n * they opened it, 0 for none, and undefined while it loads or without a read position: it stays put while the page is\n * open, so the \"New messages\" line does not move as they read. `readTo` moves the position to a message they read; it\n * never moves back, not even over a further move another tab stored, a move to where it is writes nothing, and moves go\n * one after another. Without a read position, `ready` holds at once and there is no `readTo`, so nothing is read or\n * written; one that could not be read is ready too.\n */\nexport const useReadPosition = ({ position, model, owner, recordKey, me }: Props) => {\n const client = useClient()\n const author = model?.author\n const kept = position !== undefined && author !== undefined && me !== undefined\n const [openedAt, setOpenedAt] = useState<number>()\n const [error, setError] = useState<unknown>()\n const saved = useRef<SavedPosition>(undefined)\n const writing = useRef<Promise<void>>(Promise.resolve())\n\n const find = useCallback(async (): Promise<SavedPosition | undefined> => {\n if (!kept) return\n const { items } = await client.list(position.resource, { filter: ownPositionFilter(position, recordKey, author, me), pageSize: 1 })\n const [found] = items\n if (!found) return\n return { key: String(keyOf(model!, found)), lastRead: Number(found[position.message] ?? 0), etag: String(found.etag) }\n }, [client, kept, position, model, recordKey, author, me])\n\n useEffect(() => {\n if (!kept) return\n find().then((found) => {\n saved.current = found\n setOpenedAt(found?.lastRead ?? 0)\n }, setError)\n }, [kept, find])\n\n // Each write goes over the version of the position it was read at, so it never lands over another tab's further move\n const store = useMemo((): PositionStore => ({\n find,\n create: async (lastRead) => {\n const made = await client.create(position!.resource, { [position!.field]: keyValue(owner, recordKey), [position!.message]: lastRead })\n return { key: String(keyOf(model!, made.record)), lastRead, etag: made.etag }\n },\n update: async (at, lastRead) => {\n const { etag } = await client.update(position!.resource, at.key, { [position!.message]: lastRead }, at.etag)\n return { key: at.key, lastRead, etag }\n },\n }), [client, position, owner, recordKey, model, find])\n\n const readTo = useCallback(\n (lastRead: number) => {\n writing.current = writing.current\n .then(async () => {\n saved.current = await moveReadPosition(store, saved.current, lastRead)\n })\n .catch(setError)\n },\n [store],\n )\n\n // A position that could not be read leaves the line out rather than the messages\n return { ready: !kept || openedAt !== undefined || error !== undefined, openedAt: kept ? openedAt : undefined, readTo: kept && openedAt !== undefined ? readTo : undefined, error }\n}\n","import type { AppAddress } from '@protobase/schema'\nimport { useAppAddress } from '../use-app-address'\n\n/**\n * The thread a conversation page shows beside it, as its address holds it (`?thread=`): `open`, the key of the\n * thread's first message, none while no thread is open; `to`, the address that opens a message's thread, for a link;\n * and `close`, which goes back to the conversation alone. Both keep the record's call the page joins (`?call=join`).\n */\nexport const useThreadAddress = (resource: string, key: string) => {\n const { address, go } = useAppAddress()\n const here = address?.kind === 'record' && address.resource === resource && address.key === key ? address : undefined\n const call = here?.call && { call: here.call }\n const to = (message: string): AppAddress => ({ kind: 'record', resource, key, ...call, thread: message })\n const close = () => go({ kind: 'record', resource, key, ...call })\n return { open: here?.thread, to, close }\n}\n","import type { ConversationPageModel } from '@protobase/schema'\nimport { useOptionalAuth } from '../../auth/auth-provider'\nimport { useMembers } from '../../people/use-members'\nimport { keyValue } from '../create/create-values'\nimport { MessageComposer } from '../conversation/message-composer'\nimport { FullArea } from '../full-area-record'\nimport { useAdminMeta } from '../meta-gate'\nimport { useRecordTitle } from '../titles/record-titles'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { ConversationCall } from './conversation-call'\nimport { ConversationHeader } from './conversation-header'\nimport { ConversationMessages } from './conversation-messages'\nimport { matchingMembers } from './member-search'\nimport { ThreadPanel } from './thread-panel'\nimport { useReadPosition } from './use-read-position'\nimport { useThreadAddress } from './use-thread-address'\nimport { text } from './messages'\nimport { useRelay } from '../../relay/relay-context'\nimport { TypingLine } from '../../relay/typing-line'\nimport { useTypingSender } from '../../relay/use-typing-sender'\nimport { useViewChannel } from '../../relay/use-view-channel'\n\ntype Props = { page: ConversationPageModel; scope: LayoutRecord }\n\n/**\n * A record page that is the record's conversation (`.record({ conversation })`), filling the content area: its header,\n * its messages and the box that sends one, where `@` lists the organization's members. The page does not scroll; the\n * messages scroll in a box of their own, so the box stays in view. With `typing`, a line above the box says who else\n * types, over the app's realtime relay. With threads, the thread its address names (`?thread=`) opens in a panel beside\n * it. With `call`, the record's call shows while the page joins it (`?call=join`), between the header and the messages:\n * beside them, or above them at mobile width, with a thread's panel after both, covering the screen at mobile width. Key\n * it by the record, so another one starts afresh.\n */\nexport const ConversationPage = ({ page, scope }: Props) => {\n const { resources, views } = useAdminMeta()\n const title = useRecordTitle()(scope.model, views[scope.model.name], scope.record, scope.key)\n const auth = useOptionalAuth()\n const me = auth?.state.kind === 'signed-in' ? auth.state.user.id : undefined\n const members = useMembers()\n const model = resources[page.resource]!\n const position = useReadPosition({ position: page.readPosition, model: page.readPosition && resources[page.readPosition.resource], owner: scope.model, recordKey: scope.key, me })\n const searchPeople = page.mentions === undefined ? undefined : async (query: string) => matchingMembers(members.data ?? [], query, me)\n const thread = useThreadAddress(scope.model.name, scope.key)\n const threaded = page.thread && { ...page, thread: page.thread }\n const channel = `${scope.model.name}/${scope.key}`\n const relay = useRelay()\n useViewChannel(channel)\n const typing = useTypingSender(channel)\n const typed = page.typing && relay ? typing : undefined\n return (\n <FullArea>\n <div className=\"flex min-h-0 min-w-0\">\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <ConversationHeader page={page} scope={scope} title={title} />\n <div className=\"flex min-h-0 min-w-0 flex-1 max-md:flex-col\">\n <ConversationCall page={page} scope={scope} />\n <div className=\"flex min-h-0 min-w-0 flex-1 flex-col\">\n <ConversationMessages page={page} model={model} recordKey={scope.key} me={me} position={position} threadTo={threaded && thread.to} searchPeople={searchPeople} />\n {position.error !== undefined && <p className=\"shrink-0 px-4 text-sm text-danger-text\">{text('positionNotSaved')}</p>}\n {typed && <TypingLine channel={channel} />}\n <div className=\"shrink-0 px-3 pb-3\">\n <MessageComposer\n resource={page.resource}\n field={page.text}\n values={{ [page.field]: keyValue(scope.model, scope.key) }}\n placeholder={page.placeholder}\n searchPeople={searchPeople}\n mentions={page.mentions}\n attachments={page.attachments}\n onDraft={typed?.onText}\n onSent={(key) => {\n typed?.onSent()\n relay?.store.sent(key)\n }}\n />\n </div>\n </div>\n </div>\n </div>\n {threaded && thread.open !== undefined && <ThreadPanel key={thread.open} page={threaded} owner={scope.model} recordKey={scope.key} first={thread.open} me={me} searchPeople={searchPeople} onClose={thread.close} />}\n </div>\n </FullArea>\n )\n}\n","import { guarded } from '../lib/guarded'\n\n/** What a person had changed on a record but not saved: the field edits and the new order of its lines. */\nexport type RecordDraft = { etag: string; fields: Record<string, unknown>; order?: string[] }\n\nexport const draftStorageKey = (userId: string, resource: string, recordKey: string) => `protobase:draft:${userId}:${resource}:${recordKey}`\n\n/** The saved draft, only if it was made against the version of the record that is on screen now. */\nexport const readDraft = (storage: Pick<Storage, 'getItem'>, key: string, etag: string): RecordDraft | undefined =>\n guarded(() => {\n const raw = storage.getItem(key)\n if (raw === null) return undefined\n const parsed = JSON.parse(raw) as Partial<RecordDraft> | null\n if (!parsed || parsed.etag !== etag || typeof parsed.fields !== 'object' || parsed.fields === null) return undefined\n return { etag, fields: parsed.fields, ...(Array.isArray(parsed.order) && { order: parsed.order.map(String) }) }\n }, undefined)\n\nexport const writeDraft = (storage: Pick<Storage, 'setItem' | 'removeItem'>, key: string, draft: RecordDraft | undefined) =>\n guarded(() => (draft ? storage.setItem(key, JSON.stringify(draft)) : storage.removeItem(key)), undefined)\n","import { Zap, type LucideIcon } from 'lucide-react'\nimport { namedIcon } from './named-icon'\n\nexport const actionIcon = (name: string | undefined): LucideIcon => namedIcon(name) ?? Zap\n","import { Pencil, Trash2 } from 'lucide-react'\nimport { useState } from 'react'\nimport { createPortal } from 'react-dom'\nimport { topBarButton, useTopBarSlot } from '../../app-shell'\nimport type { LiveRecord } from '../../data/use-record'\nimport type { ActionModel, AppAddress, ResourceModel } from '@protobase/schema'\nimport { ActionMenu, ActionRail, type RailAction } from '../../record-view'\nimport { RouteLink } from '../../primitives/route-link'\nimport { actionIcon } from '../action-icon'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { text } from '../record-messages'\nimport { actionLink } from './action-link'\nimport { ActionPrompt, asksFirst, isDanger } from './action-prompt'\nimport { useActionRunner } from './use-run-action'\n\ntype RecordActionsProps = { model: ResourceModel; stored: LiveRecord; recordKey: string; edit?: AppAddress; onDelete?: () => void }\n\n/**\n * The record page's actions, for a rail or a focus page's bar: Edit, a link to the form at `edit`, when the page offers\n * it; the view's named actions, run like the Action block runs them, a delete among them returning to the list, a\n * delete and a danger one in red; and the record's own Delete, `onDelete`, unless a named action deletes already.\n * `prompt` is what asks before an action runs, drawn wherever the actions are.\n */\nexport const useRecordActions = ({ model, stored, recordKey, edit, onDelete }: RecordActionsProps) => {\n const app = useAppAddress()\n const { go } = app\n const scope = { model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }\n const runner = useActionRunner(model.name, scope, (action) => action.run?.kind === 'delete' && go({ kind: 'list', resource: model.name }, { replace: true }))\n const [asking, setAsking] = useState<ActionModel>()\n const named = runner.actions.map((action): RailAction => {\n const blocked = runner.blocked(action)\n // A link that can be followed is a link, looking as the rail's buttons do; a disabled one stays a disabled button\n const link = action.run?.kind === 'link' && !blocked ? actionLink(action.run, stored.record, app) : undefined\n return {\n name: action.label,\n icon: actionIcon(action.icon),\n blocked,\n running: runner.running === action.name,\n ...(isDanger(action) && { tone: 'danger' as const }),\n onRun: () => (asksFirst(action) ? setAsking(action) : void runner.run(action)),\n ...(link && { render: ({ className, children, role }) => <RouteLink to={link} role={role} className={className}>{children}</RouteLink> }),\n }\n })\n const deletes = runner.actions.some((action) => action.run?.kind === 'delete')\n const actions: RailAction[] = [\n ...(edit ? [{ name: text('edit'), icon: Pencil, render: ({ className, children, role }) => <AppLink to={edit} role={role} className={className}>{children}</AppLink> } satisfies RailAction] : []),\n ...named,\n ...(onDelete && !deletes ? [{ name: text('delete'), icon: Trash2, tone: 'danger' as const, onRun: onDelete }] : []),\n ]\n const prompt = asking && (\n <ActionPrompt\n action={asking}\n label={asking.label}\n danger={isDanger(asking)}\n records={[stored.record]}\n onCancel={() => setAsking(undefined)}\n onConfirm={() => {\n setAsking(undefined)\n void runner.run(asking)\n }}\n onSubmit={async (values) => {\n await runner.submit(asking, values)\n setAsking(undefined)\n }}\n />\n )\n return { actions, prompt }\n}\n\n/**\n * The record page's actions in one rail. On a mobile screen they sit in the top bar's menu instead, at hand however\n * long the record is, when the shell has a top bar.\n */\nexport const RecordActions = (props: RecordActionsProps) => {\n const slot = useTopBarSlot()\n const { actions, prompt } = useRecordActions(props)\n if (actions.length === 0) return null\n return (\n <>\n <div className={slot ? 'max-md:hidden' : undefined}>\n <ActionRail actions={actions} />\n </div>\n {slot && createPortal(<ActionMenu actions={actions} label={text('recordActions')} className={topBarButton} />, slot)}\n {prompt}\n </>\n )\n}\n","import { ApiError, type BatchOp } from '@protobase/client'\nimport { text as appText } from './messages'\n\nconst label = (op: BatchOp) => {\n const resource = typeof op.resource === 'string' ? op.resource : op.resource.toModel().name\n return op.op === 'reorder' ? `reorder ${resource} by ${op.field}` : `${op.op} ${resource}`\n}\n\n/** \"Operation 2 (reorder invoice_lines by position) failed: ...\" so the person knows which part was refused. */\nexport const describeBatchFailure = (error: ApiError, ops: BatchOp[]) => {\n const index = error.operation\n const op = index === undefined ? undefined : ops[index]\n return op ? appText('operationFailed', { index: index! + 1, label: label(op), message: error.message }) : appText('nothingSaved', { message: error.message })\n}\n\n/** The same error with the failing operation named in its message, keeping its class so a 412 stays a 412. */\nexport const nameFailingOperation = (error: ApiError, ops: BatchOp[]) => {\n const named = new (error.constructor as typeof ApiError)({ ...error.problem, detail: describeBatchFailure(error, ops) })\n return named\n}\n","import { useQueryClient } from '@tanstack/react-query'\nimport { useEffect, useState } from 'react'\nimport { isApiError, type BatchOp, type ProblemError } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { keys } from '../data/query-keys'\nimport type { LiveRecord } from '../data/use-record'\nimport { isConflict, useUpdateRecord } from '../data/use-update-record'\nimport { displayValue } from '../live/display-value'\nimport { differs, toDraft, toPatchValue } from '../live/field-values'\nimport { nameFailingOperation } from './batch-failure'\nimport { fieldErrors } from './field-errors'\nimport { readDraft, writeDraft } from './draft-storage'\nimport type { LinesPlan } from './lines-plan'\nimport type { LinesDraft } from './use-lines-draft'\nimport { useLiveSave, type SaveMode } from './use-live-save'\n\nexport type RecordEditorParams = {\n model: ResourceModel\n stored: LiveRecord\n recordKey: string\n mode: SaveMode\n subject: string\n /** Where unsaved changes are kept in local storage, so a reload or a stray click does not lose them. */\n draftKey?: string\n /** The changes to the record's lines, written together with the record on Save. */\n lines?: LinesDraft\n}\n\nconst without = <V>(source: Record<string, V>, name: string): Record<string, V> => Object.fromEntries(Object.entries(source).filter(([key]) => key !== name))\n\n/**\n * Draft state for one record. Saving sends only the changed fields with the ETag that was read;\n * a 412 refetches the record and marks the fields both sides changed so the user can pick a side.\n * When the lines changed too, Save sends the record and the lines' writes as one batch: all or nothing.\n */\nexport const useRecordEditor = ({ model, stored, recordKey, mode, subject, draftKey, lines }: RecordEditorParams) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const update = useUpdateRecord(model.name, recordKey)\n const feedback = useLiveSave(mode, subject)\n const [restored] = useState(() => (draftKey ? readDraft(localStorage, draftKey, stored.etag) : undefined))\n const [draft, setDraft] = useState<Record<string, unknown>>(restored?.fields ?? {})\n const [showRestored, setShowRestored] = useState(Boolean(restored))\n const [linesConflict, setLinesConflict] = useState(false)\n const [conflicts, setConflicts] = useState<Record<string, string>>({})\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\n // A draft is kept as typed, so a line break or space at its end stays while the rest is still to come; it is a change\n // only when it stands for another value than the stored one.\n const changed = Object.entries(draft).filter(([name, entry]) => differs(model.fields[name]!, entry, stored.record[name]))\n const fieldsDirty = changed.length > 0\n const dirty = fieldsDirty || Boolean(lines?.dirty)\n\n // The restored order is applied once, when the record opens.\n useEffect(() => {\n if (restored?.order) lines?.setOrder(restored.order)\n }, [])\n\n // A sensitive value, and so a write-only one, is never kept in local storage\n useEffect(() => {\n if (!draftKey) return\n const kept = Object.fromEntries(Object.entries(draft).filter(([name]) => !model.fields[name]?.sensitive))\n const keep = Object.keys(kept).length > 0 || Boolean(lines?.order)\n writeDraft(localStorage, draftKey, keep ? { etag: stored.etag, fields: kept, ...(lines?.order && { order: lines.order }) } : undefined)\n }, [draftKey, model, draft, lines?.order, stored.etag])\n\n // Booleans and files are edited as they are stored; everything else as text\n const value = (name: string) => (name in draft ? draft[name] : ['boolean', 'file'].includes(model.fields[name]!.type) ? stored.record[name] : toDraft(stored.record[name]))\n\n const change = (name: string, next: unknown) => {\n setErrors((current) => without(current, name))\n const typed = typeof next === 'string' ? next !== toDraft(stored.record[name]) : differs(model.fields[name]!, next, stored.record[name])\n setDraft((current) => (typed ? { ...current, [name]: next } : without(current, name)))\n }\n\n const adoptLatest = async () => {\n const latest = await client.get(model.name, recordKey)\n queryClient.setQueryData(keys.record(model.name, recordKey), latest)\n const theirs: Record<string, string> = {}\n const keep: Record<string, unknown> = {}\n for (const [name, mine] of Object.entries(draft)) {\n const field = model.fields[name]!\n if (!differs(field, mine, latest.record[name])) continue\n keep[name] = mine\n if (toDraft(latest.record[name]) !== toDraft(stored.record[name])) theirs[name] = field.type === 'file' ? displayValue(field, latest.record[name]) : toDraft(latest.record[name])\n }\n setDraft(keep)\n setConflicts(theirs)\n }\n\n const patchOf = () => Object.fromEntries(changed.map(([name, entry]) => [name, toPatchValue(model.fields[name]!, entry)]))\n\n const reject = (error: unknown) => {\n const found = fieldErrors(error)\n setErrors(found)\n if (Object.keys(found).length > 0) setRejections((count) => count + 1)\n }\n\n const saveRecordOnly = async () => {\n try {\n await update.mutateAsync({ patch: patchOf(), etag: stored.etag })\n } catch (error) {\n if (isConflict(error)) await adoptLatest()\n else if (isApiError(error)) reject(error)\n throw error\n }\n }\n\n const saveBatch = async (linesPlan: LinesPlan) => {\n const recordOps: BatchOp[] = fieldsDirty ? [{ op: 'update', resource: model.name, key: recordKey, data: patchOf(), etag: stored.etag }] : []\n const ops = [...recordOps, ...linesPlan.ops]\n try {\n await client.batchWrite(ops)\n } catch (error) {\n if (isConflict(error)) {\n await adoptLatest()\n await queryClient.invalidateQueries({ queryKey: ['list'] })\n setLinesConflict(true)\n } else if (isApiError(error)) {\n // A refused operation on a line shows on that line, not on the record's fields\n const lineOp = error.operation === undefined ? -1 : error.operation - recordOps.length\n const row = linesPlan.rows[lineOp]\n if (lineOp < 0) reject(error)\n else if (row) lines?.reject(row, error)\n }\n throw isApiError(error) ? nameFailingOperation(error, ops) : error\n }\n await Promise.all([queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }), queryClient.invalidateQueries({ queryKey: ['list'] }), queryClient.invalidateQueries({ queryKey: ['page'] }), queryClient.invalidateQueries({ queryKey: ['map'] }), queryClient.invalidateQueries({ queryKey: ['aggregate'] })])\n lines?.reset()\n }\n\n const save = () =>\n feedback.run(async () => {\n const linesPlan = lines?.plan()\n if (linesPlan && linesPlan.ops.length > 0) await saveBatch(linesPlan)\n else await saveRecordOnly()\n setDraft({})\n setConflicts({})\n setErrors({})\n setLinesConflict(false)\n setShowRestored(false)\n })\n\n const discard = () => {\n setDraft({})\n setConflicts({})\n setErrors({})\n setLinesConflict(false)\n setShowRestored(false)\n lines?.reset()\n }\n\n return {\n value,\n change,\n save,\n dirty,\n discard,\n /** The changes on screen were brought back from this browser. */\n restored: showRestored && dirty,\n dismissRestored: () => setShowRestored(false),\n /** Someone changed the lines while they were being edited here. */\n linesConflict,\n saving: feedback.phase === 'saving',\n phase: feedback.phase,\n message: feedback.message,\n conflicts,\n /** The server's problem with each field, from the last save. */\n errors,\n rejections,\n keepMine: (name: string) => setConflicts((current) => without(current, name)),\n useTheirs: (name: string) => {\n setConflicts((current) => without(current, name))\n setDraft((current) => without(current, name))\n },\n }\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('focus-record')\n","import { Button } from '../../primitives/button'\nimport { text } from './messages'\n\n/** A save conflict's choices: each settles one field, so each names the field it settles. */\nexport const ConflictChoices = ({ fields, onKeepMine, onUseTheirs }: { fields: { name: string; label: string }[]; onKeepMine: (name: string) => void; onUseTheirs: (name: string) => void }) => (\n <>\n {fields.map(({ name, label }) => [\n <Button key={`mine:${name}`} size=\"sm\" onClick={() => onKeepMine(name)}>{text('keepMine', { field: label })}</Button>,\n <Button key={`theirs:${name}`} size=\"sm\" onClick={() => onUseTheirs(name)}>{text('useTheirs', { field: label })}</Button>,\n ])}\n </>\n)\n","import { Check, ListTree, Undo2 } from 'lucide-react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { useMemo, useState, type ReactElement } from 'react'\nimport type { RecordPageModel, ResourceModel } from '@protobase/schema'\nimport { useAuth } from '../../auth'\nimport { usePauseFocusRefresh } from '../../data/focus-refresh'\nimport { keys } from '../../data/query-keys'\nimport type { LiveRecord } from '../../data/use-record'\nimport { FocusActions, FocusNotice, FocusPage, FocusSlot, useFocusPage, useFocusZoneFilled } from '../../focus-page'\nimport { humanize } from '../../live/naming'\nimport { Button } from '../../primitives/button'\nimport { useDeleteFlow } from '../delete/use-delete-flow'\nimport { useRestore } from '../delete/use-restore'\nimport { draftStorageKey } from '../draft-storage'\nimport { fieldMessage } from '../field-errors'\nimport { FieldEditor } from '../field-editor'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { CustomBoundary } from '../pages/custom-boundary'\nimport { useProjectUi } from '../pages/project-ui'\nimport { RecordScope } from '../pages/record-scope'\nimport { useRecordActions } from '../pages/record-actions'\nimport { can, fieldAccess } from '../permissions'\nimport { useNavigationGuard } from '../router'\nimport { useRecordTitle } from '../titles/record-titles'\nimport { AppLink, useAppAddress } from '../use-app-address'\nimport { useRecordEditor } from '../use-record-editor'\nimport { ConflictChoices } from './conflict-choices'\nimport { FocusRecordContext, type FocusRecord } from './focus-record'\nimport { text } from './messages'\n\ntype RecordFocusPageProps = {\n model: ResourceModel\n recordKey: string\n stored: LiveRecord\n page: Exclude<RecordPageModel, { conversation: unknown }>\n /** The record's standard page, which shows when the surface throws or its component is missing. */\n standard: ReactElement\n}\n\n// The zone Save stands in: secondary beside a primary of the surface's own, else it is the page's primary\nconst SaveButton = ({ record, label }: { record: FocusRecord; label: string }) => {\n const { dirty, saving, save } = record\n const taken = useFocusZoneFilled('primary')\n const compact = useFocusPage()?.size === 'compact'\n // Stays pressable to the keyboard while there is nothing to save, so focus survives a press of it\n const button = (\n <Button variant={!taken || dirty ? 'primary' : 'secondary'} loading={saving} aria-disabled={!dirty} className=\"max-md:min-h-11\" onClick={() => void (dirty && !saving && save())}>\n {label}\n </Button>\n )\n // A bar with no room drops Save while there is nothing to save\n if (compact && !dirty) return null\n return taken ? <FocusSlot zone=\"secondary\">{button}</FocusSlot> : <FocusSlot zone=\"primary\" fallback>{button}</FocusSlot>\n}\n\n// How the work stands, in the bar, unless the surface says so in words of its own\nconst SaveState = ({ record, saved, readOnly }: { record: FocusRecord; saved: boolean; readOnly: boolean }) => {\n const size = useFocusPage()?.size\n const words = () => {\n if (readOnly) return text('readOnly')\n if (record.saving) return text('saving')\n if (record.dirty) return size === 'wide' ? text('unsaved') : text('unsavedShort')\n return saved ? text('saved') : undefined\n }\n const shown = words()\n if (!shown) return null\n return (\n <FocusSlot zone=\"state\" fallback>\n <span role=\"status\" title={readOnly ? text('readOnlyWhy') : undefined} className=\"flex items-center gap-1 truncate\">\n {!readOnly && !record.dirty && !record.saving && <Check className=\"size-3.5 text-success-text\" aria-hidden />}\n {shown}\n </span>\n </FocusSlot>\n )\n}\n\nconst RecordFocus = ({ model, recordKey, stored, page }: Omit<RecordFocusPageProps, 'standard'>) => {\n const meta = useAdminMeta()\n const view = meta.views[model.name]\n const { address, go } = useAppAddress()\n const title = useRecordTitle()(model, view, stored.record, recordKey)\n const { state: auth } = useAuth()\n const editor = useRecordEditor({\n model,\n stored,\n recordKey,\n mode: 'button',\n subject: title,\n // A draft of its own: the form keeps its fields and line order in another, which this page never touches\n draftKey: auth.kind === 'signed-in' ? `${draftStorageKey(auth.user.id, model.name, recordKey)}:focus` : undefined,\n })\n useNavigationGuard(editor.dirty || editor.saving)\n usePauseFocusRefresh(editor.dirty)\n const queryClient = useQueryClient()\n const [askDiscard, setAskDiscard] = useState(false)\n const noun = view?.names?.singular ?? humanize(model.name)\n const permissions = usePermissions(model.name)\n const restore = useRestore(model)\n // An earlier version of the record, as a field type that keeps versions draws it, is only read\n const pastVersion = address?.kind === 'record' && address.version !== undefined && address.version !== Number(stored.record.version)\n // The surface's own field counts: one this reader may only read is not theirs to change here\n const surfaceReadable = 'surface' in page && (fieldAccess(stored.permissions, page.surface) === 'read' || model.fields[page.surface]?.readOnly === true)\n const mayUpdate = can(permissions, 'update') && stored.permissions?.update !== false && !surfaceReadable\n const readOnly = !mayUpdate || pastVersion\n const canDelete = can(permissions, 'delete') && stored.permissions?.delete !== false\n const remove = useDeleteFlow({\n model,\n view,\n restore,\n onDeleted: () => go({ kind: 'list', resource: model.name }, { replace: true }),\n onReview: () => void queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }),\n })\n const startDelete = canDelete ? () => void remove.start({ key: recordKey, title, etag: stored.etag, snapshot: stored.record }) : undefined\n const { actions, prompt } = useRecordActions({ model, stored, recordKey, onDelete: startDelete })\n const details = useMemo(() => ({ kind: 'record' as const, resource: model.name, key: recordKey, standard: true }), [model.name, recordKey])\n // Open details stands before Delete, which stays last\n const danger = actions.filter((action) => action.tone === 'danger')\n const barActions = [\n ...actions.filter((action) => action.tone !== 'danger'),\n ...(editor.dirty ? [{ name: text('discardChanges'), icon: Undo2, onRun: () => setAskDiscard(true) }] : []),\n { name: text('detailsOf', { noun }), icon: ListTree, render: ({ className, children, role }: { className: string; children: React.ReactNode; role?: 'menuitem' }) => <AppLink to={details} role={role} className={className}>{children}</AppLink> },\n ...danger,\n ]\n const record: FocusRecord = {\n model,\n record: stored.record,\n key: recordKey,\n ...(stored.etag !== undefined && { etag: stored.etag }),\n ...(stored.permissions && { permissions: stored.permissions }),\n readOnly,\n mayUpdate,\n value: editor.value,\n // A read-only page changes and saves nothing, whatever its surface asks\n change: (name, next) => (readOnly ? undefined : editor.change(name, next)),\n dirty: editor.dirty,\n saving: editor.saving,\n refused: editor.message !== undefined,\n save: async () => !readOnly && Boolean(await editor.save()),\n discard: editor.discard,\n details,\n }\n const surfaceField = 'surface' in page ? page.surface : undefined\n const discardNotice = askDiscard && editor.dirty && (\n <FocusNotice\n level=\"draft\"\n actions={\n <>\n <Button size=\"sm\" variant=\"danger\" onClick={() => { editor.discard(); setAskDiscard(false) }}>{text('discardChanges')}</Button>\n <Button size=\"sm\" onClick={() => setAskDiscard(false)}>{text('keep')}</Button>\n </>\n }\n >\n {text('discardAsk')}\n </FocusNotice>\n )\n const conflict = Object.keys(editor.conflicts).length > 0\n // The surface's own field has no form around it to mark, so what is wrong with it is said here\n const refusedField = surfaceField ? editor.errors[surfaceField] : undefined\n const surfaceProblem = refusedField && surfaceField ? fieldMessage(model.fields[surfaceField]!, view?.fields[surfaceField]?.label ?? humanize(surfaceField), refusedField) : undefined\n return (\n <FocusRecordContext.Provider value={record}>\n {!readOnly && <SaveButton record={record} label={text('save')} />}\n <SaveState record={record} saved={editor.phase === 'saved'} readOnly={readOnly} />\n <FocusActions actions={barActions} />\n {editor.message && !askDiscard && (\n <FocusNotice level=\"refused\" actions={<AppLink to={details} className=\"text-body font-medium text-primary-text hover:underline\">{text('detailsOf', { noun })}</AppLink>}>\n <strong className=\"font-medium\">{text('notSaved')}</strong> {surfaceProblem ?? editor.message}\n </FocusNotice>\n )}\n {conflict && (\n <FocusNotice\n level=\"conflict\"\n actions={\n <ConflictChoices\n fields={Object.keys(editor.conflicts).map((name) => ({ name, label: view?.fields[name]?.label ?? humanize(name) }))}\n onKeepMine={editor.keepMine}\n onUseTheirs={editor.useTheirs}\n />\n }\n >\n {text('conflict')}\n </FocusNotice>\n )}\n {discardNotice}\n {editor.restored && !askDiscard && (\n <FocusNotice\n level=\"draft\"\n actions={\n <>\n <Button size=\"sm\" onClick={editor.dismissRestored}>{text('keep')}</Button>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </>\n }\n >\n {text('restored')}\n </FocusNotice>\n )}\n {surfaceField ? <FieldSurface model={model} name={surfaceField} stored={stored} editor={editor} readOnly={readOnly} /> : <ComponentSurface name={(page as { component: string }).component} model={model} stored={stored} recordKey={recordKey} />}\n {remove.dialogs}\n {prompt}\n </FocusRecordContext.Provider>\n )\n}\n\ntype Editor = ReturnType<typeof useRecordEditor>\n\n// One field fills the surface, drawn by its field type\nconst FieldSurface = ({ model, name, stored, editor, readOnly }: { model: ResourceModel; name: string; stored: LiveRecord; editor: Editor; readOnly: boolean }) => {\n const hints = useAdminMeta().views[model.name]?.fields[name]\n // Hidden from this reader, the field is not drawn: the page's boundary shows the form, which leaves it out too\n if (fieldAccess(stored.permissions, name) === 'hidden') throw new Error(`The surface's field ${name} is hidden from this reader`)\n return (\n <div className=\"absolute inset-0\">\n <FieldEditor field={model.fields[name]!} hints={hints} value={editor.value(name)} stored={stored.record[name]} locked={readOnly} invalid={Boolean(editor.errors[name])} resource={model.name} onChange={(next) => editor.change(name, next)} />\n </div>\n )\n}\n\nconst ComponentSurface = ({ name, model, stored, recordKey }: { name: string; model: ResourceModel; stored: LiveRecord; recordKey: string }) => {\n const Component = useProjectUi().components?.[name]\n if (!Component) throw new Error(`No component is registered as ${name}`)\n return (\n <div className=\"absolute inset-0\">\n <RecordScope value={{ model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }}>\n <Component />\n </RecordScope>\n </div>\n )\n}\n\n/**\n * A record's page as a focus page, as `.record(...)` asks: the bar's state, Save and actions, the notices of a save, and\n * the surface, one field or the app's component, with the record's standard form a link away. The form shows instead\n * when the surface throws.\n */\nexport const RecordFocusPage = ({ model, recordKey, stored, page, standard }: RecordFocusPageProps) => {\n const title = useRecordTitle()(model, useAdminMeta().views[model.name], stored.record, recordKey)\n return (\n <CustomBoundary name={'surface' in page ? page.surface : page.component} fallback={standard} resetKey={model}>\n <FocusPage label={title}>\n <RecordFocus model={model} recordKey={recordKey} stored={stored} page={page} />\n </FocusPage>\n </CustomBoundary>\n )\n}\n","import { lazy, Suspense } from 'react'\nimport type { MapSectionModel } from '@protobase/schema'\nimport { Section, SidebarCard } from '../../record-view'\nimport { useAdminMeta } from '../meta-gate'\nimport { recordPosition } from './record-position'\n\n// MapLibre and the tiles' protocol load with the first map drawn, so a page without one never loads them.\nconst RecordMap = lazy(() => import('./record-map').then((module) => ({ default: module.RecordMap })))\n\nconst defaultZoom = 15\n\n/**\n * A map of the record's position (`l.map`), in a section or a sidebar card under its title, drawn with the map style\n * `/meta` names. Without a style, or for a record without a position, there is nothing to draw and no section.\n */\nexport const MapSection = ({ item, record }: { item: MapSectionModel; record: Record<string, unknown> }) => {\n const maps = useAdminMeta().maps\n const style = maps?.style\n const position = recordPosition(record, item)\n if (!style || !position) return null\n const map = (\n <div className={`overflow-hidden rounded-lg border border-border bg-muted ${item.sidebar ? 'h-48' : 'h-64 md:h-80'}`}>\n <Suspense fallback={null}>\n {/* A new position is a new map, centred on it */}\n <RecordMap key={`${position.latitude},${position.longitude}`} style={style} layers={maps?.layers} position={position} zoom={item.zoom ?? defaultZoom} />\n </Suspense>\n </div>\n )\n return item.sidebar ? <SidebarCard title={item.title}>{map}</SidebarCard> : <Section title={item.title}>{map}</Section>\n}\n","import type { AggregateGroup } from '@protobase/client'\nimport type { RecordChartRange } from '@protobase/schema'\nimport type { PeriodBucket } from '../charts/period-types'\n\n/** What each bucket of a record's chart reads of its samples. */\nexport type SampleMeasure = 'average' | 'maximum'\n\n/** How long a bucket is over each range: a minute over the hour, 5 minutes over the day, an hour over the week. */\nexport const rangeBuckets = { '1h': 'minute', '24h': '5_minutes', '7d': 'hour' } as const satisfies Record<RecordChartRange, PeriodBucket>\n\n/** A bucket's start, read as UTC as the chart draws it, with each series' number under its key, `null` where it has none. */\nexport type SamplePoint = { at: number; value: number | null; count: number } & Record<string, number | null>\n\n/**\n * The buckets of several series as one line of points, each series' number under `keys[i]`. The series come from\n * requests sent one by one, so their ranges may end a bucket apart: a bucket one of them lacks holds `null` for it, as\n * one without a sample does, which the chart draws as a gap rather than as 0.\n */\nexport const chartPoints = (series: AggregateGroup[][], keys: string[], measure: SampleMeasure): SamplePoint[] => {\n const points = new Map<number, SamplePoint>()\n series.forEach((groups, index) => {\n for (const group of groups) {\n const at = Date.parse(`${String(group.value)}Z`)\n const point = points.get(at) ?? ({ at, value: null, count: 0 } as SamplePoint)\n point[keys[index]!] = group[measure] ?? null\n point.count = Math.max(point.count, group.count)\n points.set(at, point)\n }\n })\n const empty = Object.fromEntries(keys.map((key) => [key, null]))\n return [...points.values()].sort((a, b) => a.at - b.at).map((point) => ({ ...empty, ...point }))\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-chart')\n","import { useState } from 'react'\nimport { createWhere, printFilter, type RecordChartModel, type RecordChartRange } from '@protobase/schema'\nimport { useAggregates } from '../../data/use-aggregates'\nimport { viewerZone } from '../../format/zone'\nimport { humanize } from '../../live/naming'\nimport { Segmented } from '../../primitives/segmented'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport type { ChartMeasure } from '../charts/chart-groups'\nimport { PeriodChart } from '../charts/lazy-charts'\nimport type { ChartSeries } from '../charts/split-points'\nimport { useAdminMeta } from '../meta-gate'\nimport { chartPoints, rangeBuckets, type SampleMeasure } from './chart-points'\nimport { text } from './messages'\n\nconst where = createWhere()\nconst ranges: RecordChartRange[] = ['1h', '24h', '7d']\nconst rangeLabels = { '1h': 'hour', '24h': 'day', '7d': 'week' } as const\n\n/**\n * Line graphs of the samples of `item.resource` that point at the record (`l.chart`), each series' average or maximum\n * per bucket over the last hour, day or week, which the person switches between. Each series is one `:aggregate`\n * read with their access; a bucket without a sample is a gap in its line.\n */\nexport const RecordChartSection = ({ item, recordKey }: { item: RecordChartModel; recordKey: string }) => {\n const { resources, views } = useAdminMeta()\n const [range, setRange] = useState<RecordChartRange>(item.range ?? '1h')\n const [measure, setMeasure] = useState<SampleMeasure>('average')\n const model = resources[item.resource]\n const view = views[item.resource]\n const granularity = rangeBuckets[range]\n const filter = printFilter(where.eq(item.field, recordKey))\n const requests = item.series.map((name) => ({ groupBy: item.at, filter, ...(measure === 'average' ? { average: name } : { maximum: name }), range, granularity, timeZone: viewerZone() }))\n const results = useAggregates(item.resource, requests, Boolean(model))\n if (!model) return null\n\n const measures = item.series.map((name): ChartMeasure => ({ kind: measure, field: model.fields[name]!, ...(view?.fields[name] && { hints: view.fields[name] }) }))\n const series: ChartSeries[] = item.series.map((name, index) => ({ key: `s${index}`, label: view?.fields[name]?.label ?? humanize(name), color: `var(--chart-${index + 1})`, measure: measures[index]! }))\n const points = results.every((result) => result.data) ? chartPoints(results.map((result) => result.data!.groups), series.map((part) => part.key), measure) : []\n const actions = (\n <div className=\"flex flex-wrap gap-2\">\n <Segmented label={text('measure')} value={measure} onChange={setMeasure} options={[{ value: 'average', label: text('average') }, { value: 'maximum', label: text('maximum') }]} />\n <Segmented label={text('range')} value={range} onChange={setRange} options={ranges.map((value) => ({ value, label: text(rangeLabels[value]) }))} />\n </div>\n )\n const body = () => {\n if (results.some((result) => result.error)) return <p className=\"text-danger-text\">{text('couldNotLoad')}</p>\n if (results.some((result) => result.isPending)) return <Skeleton className=\"h-40 w-full\" />\n if (points.every((point) => point.count === 0)) return <p className=\"text-muted-foreground\">{text('noSamples')}</p>\n // One series needs no legend: the section's title names it\n return <PeriodChart points={points} measure={measures[0]!} bucket={granularity} type=\"line\" series={series} {...(series.length > 1 && { resource: item.resource, view })} />\n }\n return (\n <Section title={item.title} help={item.help} actions={actions}>\n {body()}\n </Section>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/record-trend')\n","import type { ChartRange } from '@protobase/schema'\nimport { text } from './messages'\n\n/** The line over a trend: how many records its bars hold together, over its range, such as \"4 in the last 90 days\". */\nexport const trendSummary = (total: number, range: ChartRange) => text(`total_${range}`, { count: total })\n","import { createWhere, printFilter, type RecordTrendModel } from '@protobase/schema'\nimport { useAggregate } from '../../data/use-aggregates'\nimport { viewerZone } from '../../format/zone'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { periodPoints } from '../charts/chart-groups'\nimport { PeriodChart } from '../charts/lazy-charts'\nimport { ErrorBanner } from '../error-banner'\nimport { trendSummary } from './trend-summary'\nimport { text } from './messages'\n\nconst where = createWhere()\nconst count = { kind: 'count' } as const\n\n/**\n * Bars of how many records of `item.resource` point at the record (`l.trend`), per bucket of their date over the\n * item's range, under a line with their total over that range: one `:aggregate` read with the reader's access, read\n * again when the records change. With none in the range the bars stay, flat, so the page below does not move.\n */\nexport const RecordTrendSection = ({ item, recordKey }: { item: RecordTrendModel; recordKey: string }) => {\n const filter = printFilter(where.eq(item.field, recordKey))\n const result = useAggregate(item.resource, { groupBy: item.at, filter, granularity: item.granularity, range: item.range, timeZone: viewerZone() })\n const body = () => {\n if (result.isPending) return <Skeleton className=\"h-[calc(10rem+2rem)] w-full\" />\n if (result.error) return <ErrorBanner title={text('couldNotLoad')} error={result.error} onRetry={() => void result.refetch()} />\n const total = result.data.groups.reduce((sum, group) => sum + group.count, 0)\n return (\n <>\n <p className=\"mb-3 leading-5 text-foreground\">{trendSummary(total, item.range)}</p>\n <PeriodChart points={periodPoints(result.data.groups, count)} measure={count} bucket={item.granularity} type=\"bar\" />\n </>\n )\n }\n return (\n <Section title={item.title} help={item.help}>\n <div aria-busy={result.isPending}>{body()}</div>\n </Section>\n )\n}\n","import type { GroupModel } from '@protobase/schema'\n\n/** The open groups after the person opens or closes `title`. */\nexport const toggledOpen = (open: readonly string[] = [], title: string) => (open.includes(title) ? open.filter((name) => name !== title) : [...open, title])\n\n/** Whether a group shows its items: always unless `collapsed`, else when the address names it or one of its sections holds a field that needs the person's attention. */\nexport const groupOpen = (group: GroupModel, open: readonly string[] = [], needsAttention: (field: string) => boolean) =>\n !group.collapsed || open.includes(group.title) || group.items.some((item) => item.kind === 'section' && item.fields.some(needsAttention))\n","import type { LayoutItemModel, TabModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\n\n/** The shown layout around its tabs: the items before them, the tabs, and the items after. A view's tabs stand together. */\nexport const splitTabs = (layout: LayoutItemModel[]) => {\n const first = layout.findIndex((item) => item.kind === 'tab')\n if (first === -1) return { before: layout, tabs: [] as TabModel[], after: [] as LayoutItemModel[] }\n const tabs: TabModel[] = []\n for (const item of layout.slice(first)) {\n if (item.kind !== 'tab') break\n tabs.push(item)\n }\n return { before: layout.slice(0, first), tabs, after: layout.slice(first + tabs.length) }\n}\n\n/** The tab shown: the one the address names, else the first. */\nexport const shownTab = (tabs: TabModel[], named: string | undefined) => tabs.find((tab) => tab.title === named) ?? tabs[0]\n\nconst tabFields = (tab: TabModel) => layoutItems(tab.items).flatMap((item) => (item.kind === 'section' ? item.fields : []))\n\n/** The tab to show after a turned-down save: the first that holds a field needing attention, unless the shown one does. */\nexport const attentionTab = (tabs: TabModel[], shown: TabModel | undefined, needsAttention: (field: string) => boolean) => {\n if (!shown || tabFields(shown).some(needsAttention)) return undefined\n return tabs.find((tab) => tabFields(tab).some(needsAttention))\n}\n","import type { BatchOp, BatchRef } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { differs, toPatchValue } from '../live/field-values'\nimport { recordId, recordKey } from '../live/model-helpers'\n\ntype Line = Record<string, unknown>\n\n/** What the person changed in a record's lines and has not saved: their order, new lines, edited fields and removed lines. */\nexport type LinesState = {\n /** The ids in the order on screen, once a line was moved; new lines have ids of their own until saved. */\n order?: string[]\n /** The new lines' ids, in the order they were added. */\n added: string[]\n /** Per line id, the fields as typed, the way a form holds them. */\n edits: Record<string, Record<string, unknown>>\n removed: string[]\n}\n\nexport const emptyLinesState: LinesState = { added: [], edits: {}, removed: [] }\n\n/** The batch that saves the lines, and per operation the id of the line it writes, none for a reorder. */\nexport type LinesPlan = { ops: BatchOp[]; rows: Array<string | undefined> }\n\nexport type LinesPlanInput = {\n model: ResourceModel\n /** The integer field that holds the lines' order. */\n position: string\n /** The relation to the record the lines belong to, and that record's key, which a new line gets. */\n link: { field: string; value: unknown }\n /** The lines as the server has them, in their order. */\n stored: Line[]\n state: LinesState\n}\n\n/** The ids on screen, in order: the stored lines that are kept, then the new ones, as far as `order` does not say otherwise. */\nexport const shownIds = (storedIds: string[], state: LinesState) => {\n const kept = [...storedIds.filter((id) => !state.removed.includes(id)), ...state.added]\n if (!state.order) return kept\n return [...state.order.filter((id) => kept.includes(id)), ...kept.filter((id) => !state.order!.includes(id))]\n}\n\n/** The edited fields that differ from the stored line, as the API takes them. */\nconst changedData = (model: ResourceModel, edits: Record<string, unknown>, line: Line) =>\n Object.fromEntries(\n Object.entries(edits).flatMap(([name, draft]) => {\n const field = model.fields[name]\n return field && differs(field, draft, line[name]) ? [[name, toPatchValue(field, draft)]] : []\n }),\n )\n\n/** The fields filled in on a new line; the database's defaults fill the rest. */\nconst filledData = (model: ResourceModel, edits: Record<string, unknown>) =>\n Object.fromEntries(\n Object.entries(edits).flatMap(([name, draft]) => {\n const field = model.fields[name]\n if (!field || (field.type !== 'boolean' && String(draft ?? '').trim() === '')) return []\n return [[name, toPatchValue(field, draft)]]\n }),\n )\n\n/**\n * The batch that writes the lines as they are on screen: removed lines are deleted, edited ones updated with the ETag\n * they were read with, and new ones created with the parent's key and their place. New lines after the kept ones are\n * numbered on from them; new lines between kept ones need the kept ones out of the way first, so those are moved above\n * every position in use, the new lines created at their places, and the kept ones moved to theirs. A kept line the batch\n * wrote before is moved with `*`, as its ETag was checked by that earlier operation of the same transaction.\n */\nexport const planLinesOps = ({ model, position, link, stored, state }: LinesPlanInput): LinesPlan => {\n const plan: LinesPlan = { ops: [], rows: [] }\n const push = (op: BatchOp, row?: string) => {\n plan.ops.push(op)\n plan.rows.push(row)\n }\n const byId = new Map(stored.map((line) => [recordId(model, line), line]))\n const storedIds = [...byId.keys()]\n const final = shownIds(storedIds, state)\n const keyOf = (id: string) => recordKey(model, byId.get(id)!)\n const etagOf = (id: string) => {\n const etag = byId.get(id)!.etag\n return typeof etag === 'string' ? etag : undefined\n }\n\n for (const id of state.removed) {\n if (!byId.has(id)) continue\n const etag = etagOf(id)\n push({ op: 'delete', resource: model.name, key: keyOf(id), ...(etag && { etag }) }, id)\n }\n\n const written = new Set<string>()\n for (const [id, edits] of Object.entries(state.edits)) {\n if (!byId.has(id) || state.removed.includes(id)) continue\n const data = changedData(model, edits, byId.get(id)!)\n if (Object.keys(data).length === 0) continue\n const etag = etagOf(id)\n push({ op: 'update', resource: model.name, key: keyOf(id), data, ...(etag && { etag }) }, id)\n written.add(id)\n }\n\n const kept = final.filter((id) => byId.has(id))\n const added = final.filter((id) => !byId.has(id))\n const etags = (ids: string[], wildcard: boolean) =>\n Object.fromEntries(\n ids.flatMap((id) => {\n const etag = wildcard || written.has(id) ? '*' : etagOf(id)\n return etag ? [[encodeKey(keyOf(id)), etag]] : []\n }),\n )\n const reorder = (keys: Array<ReturnType<typeof keyOf> | BatchRef>, start: number, tags: Record<string, string>): BatchOp => ({\n op: 'reorder',\n resource: model.name,\n field: position,\n keys,\n ...(start !== 1 && { start }),\n etags: tags,\n })\n const create = (id: string, place: number, ref?: string): BatchOp => ({\n op: 'create',\n resource: model.name,\n data: { ...filledData(model, state.edits[id] ?? {}), [link.field]: link.value, [position]: place },\n ...(ref && { ref }),\n })\n const placeOf = (line: Line) => Number(line[position]) || 0\n\n const moved = kept.some((id, index) => id !== storedIds.filter((each) => kept.includes(each))[index])\n const atEnd = added.every((id) => final.indexOf(id) >= kept.length)\n if (atEnd) {\n if (moved) push(reorder(kept.map(keyOf), 1, etags(kept, false)))\n const last = moved ? kept.length : Math.max(0, ...kept.map((id) => placeOf(byId.get(id)!)))\n added.forEach((id, index) => push(create(id, last + 1 + index), id))\n return plan\n }\n\n const above = Math.max(final.length, ...stored.map(placeOf)) + 1\n if (kept.length > 0) push(reorder(kept.map(keyOf), above, etags(kept, false)))\n const refOf = (id: string) => `line${added.indexOf(id) + 1}`\n for (const id of added) push(create(id, final.indexOf(id) + 1, refOf(id)), id)\n push(reorder(final.map((id) => (byId.has(id) ? keyOf(id) : { $ref: refOf(id) })), 1, etags(kept, true)))\n return plan\n}\n","import { useMemo, useRef, useState } from 'react'\nimport type { ApiError, ProblemError } from '@protobase/client'\nimport type { ResourceModel } from '@protobase/schema'\nimport { toFieldDraft } from '../live/field-values'\nimport { recordId } from '../live/model-helpers'\nimport { fieldErrors } from './field-errors'\nimport { emptyLinesState, planLinesOps, shownIds, type LinesPlan, type LinesState } from './lines-plan'\n\ntype Line = Record<string, unknown>\n\n/** Where the lines are written: their resource, the field that orders them, and the relation to the record with its key. */\nexport type LinesTarget = { model: ResourceModel; position: string; link: { field: string; value: unknown } }\n\n/** A line on screen: a stored one, with what was typed over it, or a new one, which has no `stored`. */\nexport type ShownLine = { id: string; stored?: Line }\n\n/** What the server said about a line on the last save: per field, and its message for the line as a whole. */\nexport type LineRejection = { id: string; fields: Record<string, ProblemError>; message: string }\n\nconst without = <V>(source: Record<string, V>, name: string): Record<string, V> => Object.fromEntries(Object.entries(source).filter(([key]) => key !== name))\n\n/**\n * The changes the person made to a record's lines, kept in the form until Save writes them, together with the record,\n * in one batch: the order, new lines, typed fields and removed lines. `shown` is the lines as they are on screen;\n * `plan()` is the batch that makes them permanent.\n */\nexport const useLinesDraft = (target: LinesTarget | undefined, stored: Line[]) => {\n const [state, setState] = useState<LinesState>(emptyLinesState)\n const [rejection, setRejection] = useState<LineRejection>()\n const nextId = useRef(1)\n const byId = useMemo(() => new Map(target ? stored.map((line) => [recordId(target.model, line), line]) : []), [target, stored])\n const shown: ShownLine[] = shownIds([...byId.keys()], state).map((id) => ({ id, stored: byId.get(id) }))\n\n const plan = (): LinesPlan => (target ? planLinesOps({ ...target, stored, state }) : { ops: [], rows: [] })\n const dirty = plan().ops.length > 0\n // The same array while the order stays, so a draft is kept only when it changes\n const order = useMemo(() => {\n const kept = shownIds([...byId.keys()], state).filter((id) => byId.has(id))\n const before = [...byId.keys()].filter((id) => kept.includes(id))\n return state.order !== undefined && kept.some((id, index) => id !== before[index]) ? kept : undefined\n }, [byId, state])\n\n /** The value a line's field editor holds: what was typed, else the stored value as the editor takes it. */\n const value = (id: string, name: string) => {\n const typed = state.edits[id]\n if (typed && name in typed) return typed[name]\n const field = target?.model.fields[name]\n const current = byId.get(id)?.[name]\n if (!field) return current\n return ['boolean', 'file'].includes(field.type) ? current : toFieldDraft(field, current)\n }\n\n const forget = (id: string) => setRejection((current) => (current?.id === id ? undefined : current))\n\n return {\n shown,\n dirty,\n /** The stored lines' ids in the order on screen, once moved, for keeping a draft. */\n order,\n value,\n change: (id: string, name: string, next: unknown) => {\n forget(id)\n setState((current) => ({ ...current, edits: { ...current.edits, [id]: { ...current.edits[id], [name]: next } } }))\n },\n /** Adds an empty line at the end; the database's defaults fill what is left empty when it is saved. */\n add: () => {\n const id = `new:${nextId.current++}`\n setState((current) => ({ ...current, added: [...current.added, id] }))\n return id\n },\n remove: (id: string) => {\n forget(id)\n setState((current) =>\n current.added.includes(id) ? { ...current, added: current.added.filter((each) => each !== id), edits: without(current.edits, id) } : { ...current, removed: [...current.removed, id] },\n )\n },\n setOrder: (next: string[]) => setState((current) => ({ ...current, order: next })),\n reset: () => {\n setState(emptyLinesState)\n setRejection(undefined)\n },\n /** The server turned down the write of line `id`: its fields and message show on that line until it changes. */\n reject: (id: string, error: ApiError) => setRejection({ id, fields: fieldErrors(error), message: error.message }),\n rejection,\n plan,\n }\n}\n\nexport type LinesDraft = ReturnType<typeof useLinesDraft>\n","import { useMemo } from 'react'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\nimport { listColumnNames } from '../live/columns-from-model'\nimport { listLabels } from '../live/relation-labels'\nimport { keyValue } from './create/create-values'\nimport { useAdminMeta } from './meta-gate'\nimport { useLines } from './use-lines'\nimport { useLinesDraft } from './use-lines-draft'\n\n/**\n * The record's lines, as its view declares them with `l.related(..., { lines: true })`: the section, the lines'\n * resource, the relation that points at the record and the field that orders them.\n */\nexport const findLinesResource = (resources: Record<string, ResourceModel>, view: ViewModel | undefined) => {\n const item = layoutItems(view?.layout ?? []).find((each) => each.kind === 'related' && each.lines === true)\n if (item?.kind !== 'related') return\n const model = resources[item.resource]\n const link = model?.fields[item.field]\n const position = model?.position?.field\n if (!model || !link || !position || model.position?.within !== item.field) return\n return { item, model, link, position }\n}\n\n/**\n * The lines' columns: the list columns of their view, or its first fields, without what the editor fills in itself:\n * the key, the tenant, the relation to the record and the position, which is the order of the rows.\n */\nexport const lineColumnNames = (lines: ResourceModel, view: ViewModel | undefined, link: string, position: string) =>\n listColumnNames(lines, view).filter((name) => {\n const field = lines.fields[name]\n return field && !field.writeOnly && name !== link && name !== position && name !== lines.tenant && !lines.primaryKey.includes(name)\n })\n\n/** The record's lines when its view declares them: the section, the resource, its columns, the lines as stored and the changes made to them. */\nexport const useRecordLines = (parent: ResourceModel, parentKey: string) => {\n const { resources, views } = useAdminMeta()\n const found = useMemo(() => findLinesResource(resources, views[parent.name]), [resources, views, parent])\n const model = found?.model\n const columns = found ? lineColumnNames(found.model, views[found.model.name], found.link.name, found.position) : []\n const data = useLines(model, found?.link, found?.position, parentKey, model ? listLabels(resources, views, model, columns) : undefined)\n const target = useMemo(() => (found ? { model: found.model, position: found.position, link: { field: found.link.name, value: keyValue(parent, parentKey) } } : undefined), [found, parent, parentKey])\n const draft = useLinesDraft(target, data.items)\n return { item: found?.item, model, columns, data, draft }\n}\n\nexport type RecordLinesData = ReturnType<typeof useRecordLines>\n","/** The most tiles a gallery draws: one large and four smaller. */\nexport const maxTiles = 5\n\n/**\n * How many of `count` photos a gallery draws as tiles, and how many more its last tile counts (\"+N\"): five at most,\n * three of four so the large tile keeps its two rows beside two wide ones, every photo when there are fewer.\n */\nexport const galleryTiles = (count: number) => {\n const shown = count >= maxTiles ? maxTiles : count === 4 ? 3 : count\n return { shown, more: count - shown }\n}\n\n/** A swipe's step: a mostly sideways drag of 40 pixels or more moves to the next photo leftwards, the previous rightwards. */\nexport const swipeStep = (dx: number, dy: number) => (Math.abs(dx) < 40 || Math.abs(dx) <= Math.abs(dy) ? 0 : dx < 0 ? 1 : -1)\n\n/** A key's step: the right arrow moves to the next photo, the left arrow to the previous one. */\nexport const keyStep = (key: string) => (key === 'ArrowRight' ? 1 : key === 'ArrowLeft' ? -1 : 0)\n\n/** The photo a step from `index` lands on among `count`: it stops at the first and the last rather than wrapping around. */\nexport const steppedPhoto = (index: number, by: number, count: number) => Math.min(Math.max(index + by, 0), Math.max(count - 1, 0))\n\n/** Whether a key press toggles a photo's details: `i` alone, without Ctrl, Cmd or Alt, which belong to the browser. */\nexport const togglesDetails = (event: { key: string; ctrlKey: boolean; metaKey: boolean; altKey: boolean }) => event.key === 'i' && !event.ctrlKey && !event.metaKey && !event.altKey\n","import { guarded } from '../../lib/guarded'\n\n/** Where this browser remembers whether the lightbox opens with a photo's details shown. */\nexport const detailsOpenStorageKey = 'protobase:lightbox-details'\n\n/** Whether the lightbox's details were left open in this browser; closed until someone opens them. */\nexport const readDetailsOpen = (storage: Pick<Storage, 'getItem'>) => guarded(() => storage.getItem(detailsOpenStorageKey) === 'true', false)\n\n/** Remembers only open details, so the default (closed) costs no storage. */\nexport const writeDetailsOpen = (storage: Pick<Storage, 'setItem' | 'removeItem'>, open: boolean) =>\n guarded(() => (open ? storage.setItem(detailsOpenStorageKey, 'true') : storage.removeItem(detailsOpenStorageKey)), undefined)\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/gallery')\n","import { ChevronLeft, ChevronRight, Info, X } from 'lucide-react'\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from 'react'\nimport { cn } from '../../lib/cn'\nimport { useFocusTrap } from '../../lib/use-focus-trap'\nimport { useIsDesktop } from '../../lib/use-media-query'\nimport { FileImage } from '../../live/file-image'\nimport { shownImage } from '../../live/file-values'\nimport { Sheet } from '../../primitives/sheet'\nimport { readDetailsOpen, writeDetailsOpen } from './details-open-storage'\nimport { keyStep, steppedPhoto, swipeStep, togglesDetails } from './gallery-layout'\nimport { text } from './messages'\n\nexport type LightboxProps = {\n /** The dialog's accessible name, such as the gallery's title. */\n title: string\n /** The photos' files, in order. */\n photos: readonly unknown[]\n /** The photo shown. */\n index: number\n onIndex: (index: number) => void\n onClose: () => void\n /**\n * The details of the photo at a position, which the info button shows in a sidebar beside it, or in a sheet over the\n * lower part of a mobile screen; `undefined` where the photo has none the user may read, which leaves out the button.\n */\n details?: (index: number) => ReactNode | undefined\n /** The details' heading and the info button's name, such as \"Photo details\". */\n detailsTitle?: string\n}\n\nconst control =\n 'flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40'\n\n/**\n * Photos one at a time at full size over the page: a modal dialog with a counter, arrows and keys (left, right, Escape)\n * that step through them, stopping at the first and the last, and a sideways swipe on a touch screen. For a photo with\n * details the user may read, an info button, or the `i` key, shows them in a sidebar beside it, or in a sheet over the\n * lower part of a mobile screen; this browser remembers whether they were left shown. The page does not scroll behind\n * it, and focus returns to what opened it.\n */\nexport const Lightbox = ({ title, photos, index, onIndex, onClose, details, detailsTitle = text('details') }: LightboxProps) => {\n const panel = useRef<HTMLDivElement>(null)\n const start = useRef<{ x: number; y: number }>(undefined)\n const sidebarId = useId()\n const desktop = useIsDesktop()\n const [detailsOpen, setDetailsOpen] = useState(() => readDetailsOpen(localStorage))\n // The sheet waits for the dialog's own focus trap, so the sheet's is the one on top, which Escape closes first\n const [trapped, setTrapped] = useState(false)\n useFocusTrap(panel, true, onClose)\n useEffect(() => setTrapped(true), [])\n const count = photos.length\n // At an end the arrow stays focusable, so the keys keep working, and does nothing\n const step = (by: number) => {\n const next = steppedPhoto(index, by, count)\n if (next !== index) onIndex(next)\n }\n const image = shownImage(photos[index], { width: 1600, height: 1200 })\n const shownDetails = details?.(index)\n const hasDetails = shownDetails !== undefined\n const toggleDetails = (open: boolean) => {\n setDetailsOpen(open)\n writeDetailsOpen(localStorage, open)\n }\n\n const key = (event: KeyboardEvent) => {\n if (hasDetails && togglesDetails(event)) {\n event.preventDefault()\n return toggleDetails(!detailsOpen)\n }\n const by = keyStep(event.key)\n if (by === 0) return\n event.preventDefault()\n step(by)\n }\n const down = (event: PointerEvent) => {\n if (event.pointerType === 'touch') start.current = { x: event.clientX, y: event.clientY }\n }\n const up = (event: PointerEvent) => {\n if (!start.current) return\n step(swipeStep(event.clientX - start.current.x, event.clientY - start.current.y))\n start.current = undefined\n }\n\n // The dialog is the page while it is open: it scrolls to details taller than the screen, with the photo kept in view\n return (\n <div ref={panel} tabIndex={-1} role=\"dialog\" aria-modal=\"true\" aria-label={title} onKeyDown={key} className=\"fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop pl-[var(--pb-safe-left)] pr-[var(--pb-safe-right)] outline-none md:flex-row\">\n <div className=\"flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1\">\n <div className=\"flex shrink-0 items-center justify-between gap-2 p-3 pt-[calc(0.75rem+var(--pb-safe-top))]\">\n <span className=\"rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground\" aria-live=\"polite\">\n {`${index + 1} / ${count}`}\n </span>\n <div className=\"flex items-center gap-2\">\n {hasDetails && (\n <button\n type=\"button\"\n className={cn(control, 'aria-expanded:bg-foreground aria-expanded:text-background')}\n aria-label={detailsTitle}\n aria-expanded={detailsOpen}\n aria-controls={desktop ? sidebarId : undefined}\n aria-keyshortcuts=\"i\"\n onClick={() => toggleDetails(!detailsOpen)}\n >\n <Info className=\"size-4\" aria-hidden />\n </button>\n )}\n <button type=\"button\" className={control} aria-label={text('close')} onClick={onClose}>\n <X className=\"size-4\" aria-hidden />\n </button>\n </div>\n </div>\n <div className=\"relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-[calc(0.75rem+var(--pb-safe-bottom))] md:px-16\" onPointerDown={down} onPointerUp={up} onPointerCancel={() => (start.current = undefined)}>\n {image && <FileImage key={image.url} image={image} className=\"max-h-full max-w-full select-none object-contain\" />}\n {count > 1 && (\n <>\n <button type=\"button\" className={cn(control, 'absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40')} aria-label={text('previousPhoto')} aria-disabled={index === 0} onClick={() => step(-1)}>\n <ChevronLeft className=\"size-5\" aria-hidden />\n </button>\n <button type=\"button\" className={cn(control, 'absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40')} aria-label={text('nextPhoto')} aria-disabled={index === count - 1} onClick={() => step(1)}>\n <ChevronRight className=\"size-5\" aria-hidden />\n </button>\n </>\n )}\n </div>\n </div>\n {hasDetails && detailsOpen && desktop && (\n <aside id={sidebarId} aria-label={detailsTitle} className=\"min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 pt-[calc(1.25rem+var(--pb-safe-top))] text-foreground\">\n <h2 className=\"mb-3 text-base font-semibold\">{detailsTitle}</h2>\n {shownDetails}\n </aside>\n )}\n <Sheet title={detailsTitle} open={hasDetails && detailsOpen && !desktop && trapped} onClose={() => toggleDetails(false)}>\n <div className=\"pt-3\">{shownDetails}</div>\n </Sheet>\n </div>\n )\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { layoutItems } from '@protobase/schema/internal'\nimport { whenShown } from '../record-mode/record-mode'\n\n/**\n * The fields of a photo's details: those its record page shows in its sections, or without a layout every field but its\n * key and tenant, less sensitive ones, those meant only for its form and those the gallery already shows: `omit`, such as the photo's file and the\n * field pointing at the gallery's record.\n */\nexport const detailFields = (model: ResourceModel, view: ViewModel | undefined, omit: readonly string[]) => {\n const sections = layoutItems(view?.layout ?? []).flatMap((item) => (item.kind === 'section' && whenShown(item.when, false) ? item.fields : []))\n const names = sections.length > 0 ? [...new Set(sections)] : Object.keys(model.fields).filter((name) => name !== model.tenant && !model.primaryKey.includes(name))\n return names.filter((name) => model.fields[name] && !model.fields[name].sensitive && !omit.includes(name) && whenShown(view?.fields[name]?.when, false))\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { useRecord } from '../../data/use-record'\nimport { humanize } from '../../live/naming'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { SpecTable } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { FieldValue } from '../pages/field-value'\nimport { fieldAccess } from '../permissions'\nimport { AppLink } from '../use-app-address'\nimport { text } from './messages'\n\n/**\n * A photo's record, as the record API answers the user, so the server decides what they may read: its `fields` (see\n * `detailFields`), as label/value rows, and a link to its page.\n */\nexport const PhotoDetails = ({ model, view, photoKey, fields }: { model: ResourceModel; view: ViewModel | undefined; photoKey: string; fields: readonly string[] }) => {\n const record = useRecord(model.name, photoKey)\n const singular = (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n if (record.isPending) return <Skeleton className=\"h-4 w-48\" />\n if (record.error) return <ErrorBanner title={text('couldNotLoadOne', { singular })} error={record.error} />\n const shown = fields.filter((name) => fieldAccess(record.data.permissions, name) !== 'hidden')\n return (\n <>\n <SpecTable rows={shown.map((name) => ({ label: view?.fields[name]?.label ?? humanize(name), value: <FieldValue model={model} field={model.fields[name]!} value={record.data.record[name]} /> }))} />\n <AppLink to={{ kind: 'record', resource: model.name, key: photoKey }} className=\"mt-3 inline-block font-medium text-primary-text hover:underline\">\n {text('open', { singular })}\n </AppLink>\n </>\n )\n}\n","import type { KeyValue, ResourceModel } from '@protobase/schema'\nimport { encodeKey } from '@protobase/schema/internal'\nimport { isStoredFile, shownImage } from '../../live/file-values'\n\n/** A photo of a gallery: its file, and the record holding it by its key in the record API's text form, when one does. */\nexport type GalleryItem = { file: unknown; key?: string }\n\n/** The most photo records a gallery reads: the list API's largest page. */\nexport const galleryPhotoLimit = 500\n\n// A file the gallery can draw: an image with a link, not a missing file or a document.\nconst isPicture = (value: unknown) => shownImage(value, { width: 0, height: 0 }) !== undefined\n\n// A row's key in the record API's text form, or none when the caller cannot read every part of it.\nconst keyOf = (holder: ResourceModel, row: Record<string, unknown>) => {\n const parts = holder.primaryKey.map((name) => row[name])\n if (parts.some((part) => part === null || part === undefined)) return undefined\n return encodeKey(parts as KeyValue[])\n}\n\n/**\n * The photos a gallery steps through: the record's own `cover` first, then the `image` of each of the photo records\n * `rows`, less the one the cover already shows, whose record the cover takes; empty values, missing files and files\n * that are no image are left out.\n */\nexport const galleryItems = (cover: unknown, rows: ReadonlyArray<Record<string, unknown>>, image: string | undefined, holder: ResourceModel | undefined): GalleryItem[] => {\n const photos = image === undefined ? [] : rows.flatMap((row): GalleryItem[] => {\n const file = row[image]\n if (!isStoredFile(file) || !isPicture(file)) return []\n const key = holder && keyOf(holder, row)\n return [{ file, ...(key !== undefined && { key }) }]\n })\n if (!isStoredFile(cover) || !isPicture(cover)) return photos\n const same = (item: GalleryItem) => isStoredFile(item.file) && item.file.uri === cover.uri\n const key = photos.find(same)?.key\n return [{ file: cover, ...(key !== undefined && { key }) }, ...photos.filter((item) => !same(item))]\n}\n","import { useQuery } from '@tanstack/react-query'\nimport { createWhere, printFilter, type GalleryModel } from '@protobase/schema'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\nimport { useAdminMeta } from '../meta-gate'\nimport { galleryItems, galleryPhotoLimit } from './gallery-items'\n\nconst where = createWhere()\n\n/**\n * A gallery's photos: the record's own image, then the photo records that point at it, read with the list API under\n * the user's own access, so its row filters and readable fields apply. Without the photos' resource in `/meta`, the\n * user cannot list them, and the record's image is all there is.\n */\nexport const useGalleryPhotos = (item: GalleryModel, record: Record<string, unknown>, recordKey: string) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const holder = item.photos ? resources[item.photos.resource] : undefined\n const filter = item.photos ? printFilter(where.eq(item.photos.field, recordKey)) : ''\n const sort = item.photos?.sort ?? ''\n const rows = useQuery({\n queryKey: keys.list(holder?.name ?? '', filter, sort, galleryPhotoLimit, 'gallery'),\n enabled: holder !== undefined,\n queryFn: async () => (await client.list(holder!.name, { filter, ...(sort && { orderBy: sort }), pageSize: galleryPhotoLimit })).items,\n })\n const cover = item.image === undefined ? undefined : record[item.image]\n return {\n holder,\n items: galleryItems(cover, rows.data ?? [], item.photos?.image, holder),\n isPending: holder !== undefined && rows.isPending,\n error: rows.error,\n }\n}\n","import { Images } from 'lucide-react'\nimport { useState } from 'react'\nimport type { GalleryModel } from '@protobase/schema'\nimport { cn } from '../../lib/cn'\nimport { FileImage } from '../../live/file-image'\nimport { humanize } from '../../live/naming'\nimport { shownImage } from '../../live/file-values'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { useAdminMeta, usePermissions } from '../meta-gate'\nimport { galleryTiles } from './gallery-layout'\nimport { Lightbox } from './lightbox'\nimport { detailFields } from './detail-fields'\nimport { PhotoDetails } from './photo-details'\nimport { useGalleryPhotos } from './use-gallery-photos'\nimport { text } from './messages'\n\n// Where each tile sits from md up, by how many are drawn: the first large over two rows, the rest beside it. On a mobile\n// screen only the first is drawn, across the whole gallery.\nconst spans: Record<number, string[]> = {\n 1: ['md:col-span-4 md:row-span-2'],\n 2: ['md:col-span-2 md:row-span-2', 'md:col-span-2 md:row-span-2'],\n 3: ['md:col-span-2 md:row-span-2', 'md:col-span-2', 'md:col-span-2'],\n 5: ['md:col-span-2 md:row-span-2', '', '', '', ''],\n}\n\nconst Tile = ({ photo, large }: { photo: unknown; large: boolean }) => {\n const image = shownImage(photo, large ? { width: 960, height: 720 } : { width: 480, height: 360 })\n return image ? <FileImage image={image} loading=\"lazy\" className=\"size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]\" /> : null\n}\n\n/**\n * A record's photos as tiles, one large and the next ones smaller, the last counting those not drawn (\"+N\"); a mobile\n * screen draws the large one with the number of photos. Each tile opens the lightbox at its photo. A photo held by a\n * record of a resource the user may read has its details beside it there, as the record API answers them. A record\n * without photos has no gallery.\n */\nexport const GallerySection = ({ item, record, recordKey }: { item: GalleryModel; record: Record<string, unknown>; recordKey: string }) => {\n const { views } = useAdminMeta()\n const photos = useGalleryPhotos(item, record, recordKey)\n const photoPermissions = usePermissions(photos.holder?.name ?? '')\n const [open, setOpen] = useState<number>()\n if (photos.isPending) return <Section title={item.title}><Skeleton className=\"aspect-[4/3] w-full rounded-lg md:aspect-[2/1]\" /></Section>\n if (photos.error) return <Section title={item.title}><ErrorBanner title={text('couldNotLoad')} error={photos.error} /></Section>\n const count = photos.items.length\n if (count === 0) return null\n const { shown, more } = galleryTiles(count)\n const holder = photos.holder\n const holderView = holder && views[holder.name]\n // Reading a photo's record is the user's to do: its resource is in their `/meta`, readable, and they can read its key.\n // Its file and the field pointing here are what the lightbox and this page show already.\n const fields = holder ? detailFields(holder, holderView, [item.photos?.image, item.photos?.field].filter((name) => name !== undefined)) : []\n const readable = holder !== undefined && photoPermissions.read !== false && fields.length > 0\n const details = (index: number) => {\n const key = photos.items[index]?.key\n return readable && key !== undefined ? <PhotoDetails key={key} model={holder} view={holderView} photoKey={key} fields={fields} /> : undefined\n }\n\n return (\n <Section title={item.title}>\n <div className=\"grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]\">\n {photos.items.slice(0, shown).map((photo, index) => {\n const last = index === shown - 1 && more > 0\n return (\n <button\n key={index}\n type=\"button\"\n aria-label={last ? text('showAll', { count }) : text('showPhoto', { index: index + 1, count })}\n onClick={() => setOpen(index)}\n className={cn(\n 'group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary',\n index === 0 ? 'col-span-4 row-span-2' : 'max-md:hidden',\n spans[shown]![index],\n )}\n >\n <Tile photo={photo.file} large={index === 0} />\n {last && <span className=\"absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white\" aria-hidden>{`+${more}`}</span>}\n {index === 0 && count > 1 && (\n <span className=\"absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden\" aria-hidden>\n <Images className=\"size-3.5\" />\n {count}\n </span>\n )}\n </button>\n )\n })}\n </div>\n {open !== undefined && (\n <Lightbox\n title={item.title}\n photos={photos.items.map((photo) => photo.file)}\n index={open}\n onIndex={setOpen}\n onClose={() => setOpen(undefined)}\n details={details}\n detailsTitle={holder && text('holderDetails', { singular: holderView?.names?.singular ?? humanize(holder.name) })}\n />\n )}\n </Section>\n )\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/history')\n","import type { HistoryChange } from '@protobase/client'\nimport type { ResourceModel, ViewModel } from '@protobase/schema'\nimport { displayValue } from '../../live/display-value'\nimport { humanize } from '../../live/naming'\nimport { text } from './messages'\n\n/** A field an update changed: its values as the list shows them, none for a sensitive field, whose values are never kept. */\nexport type ChangedField = { name: string; label: string; before?: string; after?: string }\n\nexport type DescribedChange = { who: string; verb: string; fields: ChangedField[] }\n\n/** Who made a change: their name, else their id; a write from outside the app names the database role. */\nexport const changedBy = (change: HistoryChange) => {\n if (change.actor) return change.actor.name ?? change.actor.id\n return change.databaseRole ? text('databaseRole', { role: change.databaseRole }) : text('database')\n}\n\n/**\n * A change as the record page tells it: who, what they did, and for an update each changed field the model still has,\n * before and after, as the view labels and formats it.\n */\nexport const describeChange = (change: HistoryChange, model: ResourceModel, view?: ViewModel): DescribedChange => {\n const fields = (change.operation === 'create' ? [] : change.changed).flatMap((name): ChangedField[] => {\n const field = model.fields[name]\n if (!field || name === model.softDelete) return []\n const hints = view?.fields[name]\n const label = hints?.label ?? humanize(name)\n if (field.sensitive || !change.before || !change.after) return [{ name, label }]\n return [{ name, label, before: displayValue(field, change.before[name], hints), after: displayValue(field, change.after[name], hints) }]\n })\n // An update of only fields the record page does not show, such as one gone from the model, is still a change\n const verb = change.operation === 'update' && fields.length === 0 ? text('changedThis') : text(change.operation)\n return { who: changedBy(change), verb, fields }\n}\n","import { useEffect } from 'react'\nimport { useInfiniteQuery } from '@tanstack/react-query'\nimport type { HistoryPage } from '@protobase/client'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\n/** How long after a save the history looks again: the server keeps a change just after its write commits. */\nconst afterSave = 1500\n\n/**\n * A record's changes, newest first, `pageSize` at a time. Its key starts with the record's, so refreshing the record\n * refreshes it too; it looks again shortly after `etag` changes, once the server has kept the save.\n */\nexport const useRecordHistory = (resource: string, recordKey: string, pageSize: number, etag: string) => {\n const client = useClient()\n const query = useInfiniteQuery({\n queryKey: keys.history(resource, recordKey, pageSize),\n initialPageParam: '',\n queryFn: ({ pageParam }): Promise<HistoryPage> => client.history(resource, recordKey, { pageSize, pageToken: pageParam }),\n getNextPageParam: (last) => last.nextPageToken || undefined,\n })\n const { refetch } = query\n useEffect(() => {\n const timer = setTimeout(() => void refetch(), afterSave)\n return () => clearTimeout(timer)\n }, [etag, refetch])\n return { ...query, items: query.data?.pages.flatMap((page) => page.items) ?? [] }\n}\n","import type { HistoryChange } from '@protobase/client'\nimport type { HistorySectionModel, ResourceModel, ViewModel } from '@protobase/schema'\nimport { formatDateTime, formatRelativeTime } from '../../format/date'\nimport { Button } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { describeChange } from './describe-change'\nimport { useRecordHistory } from './use-record-history'\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\nconst Change = ({ change, model, view }: { change: HistoryChange; model: ResourceModel; view?: ViewModel }) => {\n const { who, verb, fields } = describeChange(change, model, view)\n const at = Date.parse(change.at)\n return (\n <li className=\"flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0\">\n <p>\n <span className=\"font-medium text-foreground\">{who}</span> <span className=\"text-muted-foreground\">{verb}</span>{' '}\n <time dateTime={change.at} title={formatDateTime(at)} className=\"text-muted-foreground\">\n · {formatRelativeTime(Math.max(0, Math.round((Date.now() - at) / 1000)))}\n </time>\n </p>\n {fields.length > 0 && (\n <dl className=\"grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1\">\n {fields.map((field) => (\n <div key={field.name} className=\"contents\">\n <dt className=\"text-muted-foreground\">{field.label}</dt>\n <dd className=\"min-w-0 break-words\">\n {field.before === undefined ? (\n <span className=\"text-muted-foreground\">changed</span>\n ) : (\n <>\n <del className=\"text-muted-foreground\">{field.before}</del> → <ins className=\"no-underline\">{field.after}</ins>\n </>\n )}\n </dd>\n </div>\n ))}\n </dl>\n )}\n </li>\n )\n}\n\n/** The record's changes, newest first, with who made each and the fields before and after; Show more pages further back. */\nexport const HistorySection = ({ item, model, view, recordKey, etag }: { item: HistorySectionModel; model: ResourceModel; view?: ViewModel; recordKey: string; etag: string }) => {\n const history = useRecordHistory(model.name, recordKey, item.limit ?? 10, etag)\n return (\n <Section title={item.title}>\n {history.isPending ? (\n <Loading />\n ) : history.error ? (\n <ErrorBanner title=\"Could not load the history\" error={history.error} />\n ) : history.items.length === 0 ? (\n <p className=\"text-muted-foreground\">No changes kept yet.</p>\n ) : (\n <>\n <ol className=\"divide-y divide-border\">\n {history.items.map((change) => <Change key={change.id} change={change} model={model} view={view} />)}\n </ol>\n {history.hasNextPage && (\n <Button size=\"sm\" className=\"mt-4\" disabled={history.isFetchingNextPage} onClick={() => void history.fetchNextPage()}>\n Show more\n </Button>\n )}\n </>\n )}\n </Section>\n )\n}\n","import type { RecordComment } from '@protobase/client'\nimport { MentionedText } from '../../mentions'\n\n/** A comment's text as written, line breaks kept, each `@{name}` of someone it mentions picked out. */\nexport const CommentBody = ({ comment }: { comment: RecordComment }) => <MentionedText text={comment.body} mentions={comment.mentions} />\n","import { useMutation, useQueryClient } from '@tanstack/react-query'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\n/** Posts a comment on the record, then loads its comments again so the new one shows. */\nexport const usePostComment = (resource: string, recordKey: string) => {\n const client = useClient()\n const queryClient = useQueryClient()\n return useMutation({\n mutationFn: (input: { body: string; mentions: string[] }) => client.comment(resource, recordKey, input),\n onSuccess: () => queryClient.invalidateQueries({ queryKey: keys.comments(resource, recordKey) }),\n })\n}\n","import { messages } from '../../locale/messages'\n\nexport const text = messages('app/comments')\n","import { useCallback, useState, type KeyboardEvent } from 'react'\nimport { useClient } from '../../data/api-provider'\nimport { emptyDraft, MentionBox, mentionedIds, type MentionDraft } from '../../mentions'\nimport { Button } from '../../primitives/button'\nimport { useToast } from '../../toasts/toast-provider'\nimport { useNavigationGuard } from '../router'\nimport { refusalReason } from '../displays/board-columns'\nimport { usePostComment } from './use-post-comment'\nimport { text } from './messages'\n\n/**\n * The box a comment is written in. Typing `@` lists the people who may read the record by the name typed after it\n * (see `MentionBox`). ⌘/Ctrl+Enter or the button posts.\n */\nexport const CommentComposer = ({ resource, recordKey }: { resource: string; recordKey: string }) => {\n const [draft, setDraft] = useState<MentionDraft>(emptyDraft)\n const client = useClient()\n const toast = useToast()\n const post = usePostComment(resource, recordKey)\n const searchPeople = useCallback((query: string) => client.mentionable(resource, recordKey, query), [client, resource, recordKey])\n // A comment being written, or posted, is gone when the page is left\n useNavigationGuard(draft.text.trim() !== '' || post.isPending, 'input-lost')\n\n const submit = () => {\n if (draft.text.trim() === '' || post.isPending) return\n post.mutate(\n { body: draft.text, mentions: mentionedIds(draft.text, draft.picked) },\n {\n onSuccess: () => setDraft(emptyDraft),\n onError: (error) => toast.show({ state: 'error', title: text('couldNotPost'), description: refusalReason(error) }),\n },\n )\n }\n\n const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey)) return\n event.preventDefault()\n submit()\n }\n\n return (\n <div className=\"flex flex-col gap-2\">\n <MentionBox aria-label={text('comment')} placeholder={text('placeholder')} value={draft} onChange={setDraft} searchPeople={searchPeople} onKeyDown={onKeyDown} />\n <div>\n <Button variant=\"primary\" size=\"sm\" disabled={draft.text.trim() === ''} loading={post.isPending} onClick={submit}>\n {text('comment')}\n </Button>\n </div>\n </div>\n )\n}\n","import { useInfiniteQuery } from '@tanstack/react-query'\nimport type { CommentPage } from '@protobase/client'\nimport { useClient } from '../../data/api-provider'\nimport { keys } from '../../data/query-keys'\n\nconst pageSize = 20\n\n/** A record's comments, oldest first: the newest page, then each earlier one `fetchNextPage` loads, at the top. */\nexport const useRecordComments = (resource: string, recordKey: string) => {\n const client = useClient()\n const query = useInfiniteQuery({\n queryKey: keys.comments(resource, recordKey),\n initialPageParam: '',\n queryFn: ({ pageParam }): Promise<CommentPage> => client.comments(resource, recordKey, { pageSize, pageToken: pageParam }),\n getNextPageParam: (last) => last.nextPageToken || undefined,\n })\n return { ...query, items: query.data?.pages.flatMap((page) => page.items).reverse() ?? [] }\n}\n","import type { RecordComment } from '@protobase/client'\nimport type { CommentsSectionModel } from '@protobase/schema'\nimport { hueOf, initialsOf } from '../../auth/user-to-shell'\nimport { formatDateTime, formatRelativeTime } from '../../format/date'\nimport { Avatar } from '../../primitives/avatar'\nimport { Button } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\nimport { ErrorBanner } from '../error-banner'\nimport { CommentBody } from './comment-body'\nimport { CommentComposer } from './comment-composer'\nimport { useRecordComments } from './use-record-comments'\nimport { text } from './messages'\n\nconst Loading = () => <div className=\"flex flex-col gap-2\">{Array.from({ length: 3 }, (_, index) => <Skeleton key={index} className=\"h-4 w-full\" />)}</div>\n\nconst Comment = ({ comment }: { comment: RecordComment }) => {\n const author = comment.author.name ?? comment.author.id\n const at = Date.parse(comment.createdAt)\n return (\n <li className=\"flex gap-3 py-3 first:pt-0 last:pb-0\">\n <Avatar initials={initialsOf(author) || '?'} hue={hueOf(comment.author.id)} size=\"md\" className=\"ring-0\" />\n <div className=\"flex min-w-0 flex-1 flex-col gap-0.5\">\n <p>\n <span className=\"font-medium text-foreground\">{author}</span>{' '}\n <time dateTime={comment.createdAt} title={formatDateTime(at)} className=\"text-muted-foreground\">\n · {formatRelativeTime(Math.max(0, Math.round((Date.now() - at) / 1000)))}\n </time>\n </p>\n <CommentBody comment={comment} />\n </div>\n </li>\n )\n}\n\n/**\n * The record's comments, oldest first with the newest just above the box, and Show earlier comments for those before;\n * `canWrite` false, for a visitor who is not signed in, leaves out the box.\n */\nexport const CommentsSection = ({ item, resource, recordKey, canWrite }: { item: CommentsSectionModel; resource: string; recordKey: string; canWrite: boolean }) => {\n const comments = useRecordComments(resource, recordKey)\n return (\n <Section title={item.title}>\n {comments.isPending ? (\n <Loading />\n ) : comments.error ? (\n <ErrorBanner title={text('couldNotLoad')} error={comments.error} />\n ) : (\n <>\n {comments.hasNextPage && (\n <Button size=\"sm\" className=\"mb-4\" disabled={comments.isFetchingNextPage} onClick={() => void comments.fetchNextPage()}>\n {text('showEarlier')}\n </Button>\n )}\n {comments.items.length === 0 ? (\n <p className=\"text-muted-foreground\">{text('noComments')}</p>\n ) : (\n <ol className=\"divide-y divide-border\">\n {comments.items.map((comment) => <Comment key={comment.id} comment={comment} />)}\n </ol>\n )}\n </>\n )}\n {canWrite && (\n <div className=\"mt-4\">\n <CommentComposer resource={resource} recordKey={recordKey} />\n </div>\n )}\n </Section>\n )\n}\n","import { isRecordCondition, type CustomSectionModel, type LayoutItemModel } from '@protobase/schema'\nimport { whenShown } from './record-mode'\n\n// A custom section's fallback holds items with conditions of their own, as a tab or group does\nconst innerItems = (item: LayoutItemModel): LayoutItemModel[] => {\n if (item.kind === 'group' || item.kind === 'tab') return item.items\n if (item.kind === 'custom') return item.fallback ?? []\n return []\n}\n\n// A tab has no condition: it shows while any of its items does.\nexport const whenOf = (item: LayoutItemModel) => (item.kind === 'tab' ? undefined : item.when)\n\n/** The items with a record condition in `when`, those inside tabs, groups and fallbacks too, whose conditions the page evaluates: a group before its items. */\nexport const conditionalItems = (items: LayoutItemModel[]): LayoutItemModel[] =>\n items.flatMap((item) => [item, ...conditionalItems(innerItems(item))]).filter((item) => isRecordCondition(whenOf(item)))\n\n/** A shown custom section: `fallbackAt` holds each shown fallback item's place in the whole fallback. */\ntype ShownCustom = CustomSectionModel & { fallbackAt?: number[] }\n\n/** A shown custom section's fallback items, each with its place in the whole fallback, which stays as siblings hide and show. */\nexport const fallbackEntries = (item: ShownCustom) => (item.fallback ?? []).map((entry, index) => [entry, item.fallbackAt?.[index] ?? index] as const)\n\n/**\n * The items that show: those with a record condition only when it holds (`held`, one answer per conditional item in\n * the order `conditionalItems` lists them, `undefined` while loading) and the page is no preview; the others by the\n * form or read view. A tab or group keeps the items inside it that show, and goes when it or all of them do not; a\n * custom section keeps the fallback items that show, `[]` when none does, so it then falls back to nothing, and their\n * places in the whole fallback for `fallbackEntries`.\n */\nexport const shownLayout = (items: LayoutItemModel[], held: Array<boolean | undefined>, editing: boolean, preview: boolean) => {\n let next = 0\n const shown = (item: LayoutItemModel) => {\n const when = whenOf(item)\n return isRecordCondition(when) ? !preview && held[next++] === true : whenShown(when, editing)\n }\n const keep = (list: LayoutItemModel[]): LayoutItemModel[] =>\n list.flatMap((item) => {\n const itself = shown(item)\n if (item.kind === 'custom' && item.fallback) {\n const kept = item.fallback.map((entry) => keep([entry]))\n const fallbackAt = kept.flatMap((entry, index) => (entry.length > 0 ? [index] : []))\n return itself ? [{ ...item, fallback: kept.flat(), fallbackAt } as LayoutItemModel] : []\n }\n if (item.kind !== 'group' && item.kind !== 'tab') return itself ? [item] : []\n const inner = keep(item.items)\n return itself && inner.length > 0 ? [{ ...item, items: inner } as LayoutItemModel] : []\n })\n return keep(items)\n}\n","import type { LayoutItemModel } from '@protobase/schema'\nimport { useConditions } from '../pages/use-conditions'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { conditionalItems, shownLayout, whenOf } from './shown-layout'\n\n/**\n * The layout items to draw: those meant for the form or the read view as the page is, and those with a record\n * condition while it holds for the saved record. Conditional items stay out while their values load and on a preview.\n */\nexport const useShownLayout = (items: LayoutItemModel[], scope: LayoutRecord, editing: boolean, preview: boolean) => {\n const conditions = preview ? [] : conditionalItems(items).map((item) => whenOf(item) as string)\n const held = useConditions(conditions, scope)\n return shownLayout(items, held, editing, preview)\n}\n","import { createWhere, printFilter, type ResourceModel } from '@protobase/schema'\n\nconst w = createWhere()\n\n/**\n * The list request that finds a record the session's organization does not have, and the organization it is in: for a\n * resource whose lists read across the person's organizations (`tenantAcross`), with a key of one field they can\n * filter on. `undefined` for any other resource, whose record is simply not found.\n */\nexport const elsewhereRequest = (model: ResourceModel, recordKey: string) => {\n const [key, ...more] = model.primaryKey\n if (!model.tenantAcross || model.tenant === undefined || key === undefined || more.length > 0 || !model.fields[key]?.filterable) return undefined\n return { filter: printFilter(w.eq(key, recordKey)), pageSize: 1, fields: [key, model.tenant] }\n}\n\n/** The organization a found row is in, when it is another than `current`; `undefined` when it is not found or is there. */\nexport const otherOrganization = (model: ResourceModel, row: Record<string, unknown> | undefined, current: string | undefined) => {\n const tenant = row?.[model.tenant!]\n if (tenant === undefined || tenant === null || String(tenant) === current) return undefined\n return String(tenant)\n}\n","import { useEffect, useMemo, useState } from 'react'\nimport type { ResourceModel } from '@protobase/schema'\nimport { useAuth } from '../auth'\nimport { useClient } from '../data/api-provider'\nimport { elsewhereRequest, otherOrganization } from './record-elsewhere'\n\nexport type RecordElsewhere = { state: 'looking' } | { state: 'switching' } | { state: 'missing' } | { state: 'failed'; error: unknown }\n\n/**\n * For a record not found in the session's organization: looks for it across the person's organizations, and when it is\n * in another one, switches the session there and opens the page again, so the record and everything on its page are\n * read in its own organization. `missing` when it is nowhere else, or the resource does not list across organizations.\n */\nexport const useRecordElsewhere = (model: ResourceModel, recordKey: string): RecordElsewhere => {\n const client = useClient()\n const { session, organizations } = useAuth()\n const request = useMemo(() => (organizations ? elsewhereRequest(model, recordKey) : undefined), [organizations, model, recordKey])\n const [found, setFound] = useState<RecordElsewhere>(request ? { state: 'looking' } : { state: 'missing' })\n useEffect(() => {\n if (!request) return\n const look = async () => {\n const [page, current] = await Promise.all([client.list(model.name, request), session.organizations.current()])\n const other = otherOrganization(model, page.items[0], current.organization?.id)\n if (other === undefined) return setFound({ state: 'missing' })\n setFound({ state: 'switching' })\n await session.organizations.switchTo(other)\n window.location.reload()\n }\n look().catch((error: unknown) => setFound({ state: 'failed', error }))\n }, [client, session, model, request])\n return found\n}\n","import { useQueries, useQueryClient } from '@tanstack/react-query'\nimport type { AppAddress, ResourceModel, ViewModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { relationTitle, relationTitleQuery } from './titles/relation-title'\nimport { useRecordTitle } from './titles/record-titles'\n\n/** Per relation the record holds, the address and name of the record it points at, derived for the reader where its view does. The tenant is left out. */\nexport const useRelatedRecords = (model: ResourceModel, resources: Record<string, ResourceModel>, views: Record<string, ViewModel>, record: Record<string, unknown>) => {\n const client = useClient()\n const queryClient = useQueryClient()\n const titleOf = useRecordTitle()\n const relations = Object.values(model.fields).filter(\n (field) => field.type === 'relation' && field.relation && field.name !== model.tenant && record[field.name] != null && resources[field.relation.resource]?.primaryKey.length === 1,\n )\n const labels = useQueries({\n queries: relations.map((field) => {\n const target = resources[field.relation!.resource]!\n return relationTitleQuery(queryClient, client, target, views[target.name], String(record[field.name]))\n }),\n })\n const addresses = relations.map((field): AppAddress => ({ kind: 'record', resource: field.relation!.resource, key: String(record[field.name]) }))\n return {\n addresses: Object.fromEntries(relations.map((field, index) => [field.name, addresses[index]!])),\n labels: Object.fromEntries(\n relations.map((field, index) => {\n const target = resources[field.relation!.resource]!\n return [field.name, relationTitle(labels[index]?.data, titleOf, target, views[target.name], String(record[field.name]))]\n }),\n ),\n }\n}\n","import { createWhere, printFilter, type AppAddress, type LayoutItemModel, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { humanize } from '../live/naming'\n\nconst where = createWhere()\n\n/** A resource whose records point at a record through one of its fields, as the record page's rail counts them. */\nexport type IncomingRelation = { resource: string; field: string; label: string }\n\n/**\n * The relations that point at records of `model`, as the rail lists them by default: each filterable relation of\n * another resource the user can see (a hidden resource or field is not in the meta), to a record of one key column.\n * Left out are a resource's tenant, which every record holds, and what an `l.related` section or an `l.thread` of the\n * page already lists, the record's lines included. A custom component's fallback counts only when `registered` says the\n * app has no component of that name, since the page then draws the fallback in its place. Two fields of one resource are\n * told apart by their labels.\n */\nexport const incomingRelations = (\n model: ResourceModel,\n resources: Record<string, ResourceModel>,\n views: Record<string, ViewModel>,\n layout: LayoutItemModel[],\n registered: (component: string) => boolean,\n): IncomingRelation[] => {\n if (model.primaryKey.length !== 1) return []\n const listed = new Set(\n drawnItems(layout, registered).flatMap((item) => {\n if (item.kind === 'thread') return [`${item.resource}.${item.field}`, ...(item.calls ? [`${item.calls.resource}.${item.calls.field}`] : [])]\n return item.kind === 'related' && !item.through && !item.from ? [`${item.resource}.${item.field}`] : []\n }),\n )\n const found = Object.values(resources).flatMap((source) =>\n Object.values(source.fields)\n .filter((field) => field.type === 'relation' && field.relation?.resource === model.name && field.relation.columns.length === 1 && field.filterable)\n .filter((field) => field.name !== source.tenant && !listed.has(`${source.name}.${field.name}`))\n .map((field) => ({ source, field: field.name })),\n )\n return found.map(({ source, field }) => {\n const view = views[source.name]\n const plural = view?.names?.plural ?? humanize(source.name)\n const several = found.filter((other) => other.source.name === source.name).length > 1\n return { resource: source.name, field, label: several ? `${plural} (${view?.fields[field]?.label ?? humanize(field)})` : plural }\n })\n}\n\n// The layout's items the page draws, wherever they sit: a custom item's fallback only when its component is missing\nconst drawnItems = (layout: readonly LayoutItemModel[], registered: (component: string) => boolean): LayoutItemModel[] =>\n layout.flatMap((item) => {\n if (item.kind === 'group' || item.kind === 'tab') return drawnItems(item.items, registered)\n if (item.kind === 'custom' && !registered(item.component)) return [item, ...drawnItems(item.fallback ?? [], registered)]\n return [item]\n })\n\n/** The list of the records that point at `key` through `relation`, filtered as its list's address reads. */\nexport const incomingAddress = (relation: IncomingRelation, key: string): AppAddress => ({ kind: 'list', resource: relation.resource, filter: printFilter(where.eq(relation.field, key)) })\n","import { useQueries } from '@tanstack/react-query'\nimport { printFilter, createWhere, type ResourceModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { keys } from '../data/query-keys'\nimport type { IncomingRelation } from './incoming-relations'\n\nconst where = createWhere()\n\n/** How many records point at `key` through each relation: `undefined` while loading, left out when the list is refused. */\nexport const useIncomingCounts = (relations: IncomingRelation[], resources: Record<string, ResourceModel>, key: string) => {\n const client = useClient()\n const counts = useQueries({\n queries: relations.map((relation) => {\n const filter = printFilter(where.eq(relation.field, key))\n return {\n queryKey: keys.list(relation.resource, filter, '', 1, 'incoming'),\n queryFn: async () => {\n const page = await client.list(relation.resource, { filter, pageSize: 1, count: 'exact', fields: resources[relation.resource]!.primaryKey })\n return { count: page.totalSize ?? page.totalSizeEstimate, exact: page.totalSize !== undefined }\n },\n }\n }),\n })\n return relations.flatMap((relation, index) => {\n const result = counts[index]!\n if (result.error) return []\n return [{ relation, count: result.data }]\n })\n}\n","import { ChevronRight } from 'lucide-react'\nimport type { LayoutItemModel, ResourceModel } from '@protobase/schema'\nimport { formatInt } from '../format/number'\nimport { Skeleton } from '../primitives/skeleton'\nimport { SidebarCard } from '../record-view'\nimport { incomingAddress, incomingRelations } from './incoming-relations'\nimport { useAdminMeta } from './meta-gate'\nimport { useProjectUi } from './pages/project-ui'\nimport { AppLink } from './use-app-address'\nimport { useIncomingCounts } from './use-incoming-counts'\nimport { text } from './record-messages'\n\ntype IncomingCardProps = { model: ResourceModel; recordKey: string; layout: LayoutItemModel[] }\n\n/** The rail's card of the records pointing at this one: per resource and field, how many, linking to them in their list. */\nexport const IncomingCard = ({ model, recordKey, layout }: IncomingCardProps) => {\n const { resources, views } = useAdminMeta()\n const { components } = useProjectUi()\n const relations = incomingRelations(model, resources, views, layout, (component) => Boolean(components?.[component]))\n const counts = useIncomingCounts(relations, resources, recordKey)\n if (counts.length === 0) return null\n return (\n <SidebarCard title={text('relatedRecords')}>\n <ul className=\"-mx-2\">\n {counts.map(({ relation, count }) => (\n <li key={`${relation.resource}.${relation.field}`}>\n <AppLink to={incomingAddress(relation, recordKey)} className=\"group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted\">\n <span className=\"min-w-0 truncate font-medium text-primary-text\">{relation.label}</span>\n <span className=\"flex shrink-0 items-center gap-1 tabular-nums text-muted-foreground\">\n {count === undefined ? <Skeleton className=\"h-4 w-6\" /> : `${formatInt(count.count)}${count.exact ? '' : '+'}`}\n <ChevronRight className=\"size-4 text-faint-foreground group-hover:text-foreground\" />\n </span>\n </AppLink>\n </li>\n ))}\n </ul>\n </SidebarCard>\n )\n}\n","import { formatTag } from '../locale/active-locale'\nimport { cn } from '../lib/cn'\nimport { Badge } from '../primitives/badge'\nimport { Skeleton } from '../primitives/skeleton'\nimport { text } from './messages'\n\n/** What a heading's records are called, to say the count aloud, such as \"2 tasks\"; \"records\" without. */\nexport type CountNames = { singular: string; plural: string }\n\ntype HeadingCountProps = {\n /** `undefined` while it loads, `null` when it could not be counted. */\n count: number | null | undefined\n names?: CountNames\n}\n\n/**\n * How many records a heading stands over, as a quiet pill after its title, 0 as an outline, and to a screen reader a\n * phrase such as \"(2 tasks)\"; a placeholder of its size while unknown, and nothing when it could not be counted.\n */\nexport const HeadingCount = ({ count, names }: HeadingCountProps) => {\n if (count === null) return null\n if (count === undefined) return <Skeleton className=\"inline-block h-5 w-7 rounded-full\" />\n return (\n <>\n <Badge dot={false} className={cn('tabular-nums', count === 0 && 'bg-transparent ring-1 ring-border ring-inset')}>\n <span aria-hidden>{count.toLocaleString(formatTag())}</span>\n </Badge>\n <span className=\"sr-only\">{names ? text('headingCount', { count, ...names }) : text('headingCountRecords', { count })}</span>\n </>\n )\n}\n","import type { ResourcePermissions } from '@protobase/client'\nimport type { RelatedModel, ViewModel } from '@protobase/schema'\nimport { createOffered } from '../create/create-offered'\nimport type { CurrentAddress } from '../current-address'\n\n/**\n * Where a related section starts a record of its resource with `field` filled in with this record's key, to whoever\n * the list would offer New; none through a join resource, whose `field` holds another resource's key, or without a key.\n */\nexport const relatedAdd = (item: RelatedModel, value: string | number | boolean | null, view: ViewModel | undefined, pages: Readonly<Record<string, unknown>>, permissions: ResourcePermissions): CurrentAddress | undefined => {\n if (item.through || value === null) return\n if (!createOffered(view, pages, permissions)) return\n return { kind: 'create', resource: item.resource, values: { [item.field]: String(value) } }\n}\n","import { ArrowRight, Plus } from 'lucide-react'\nimport type { ReactNode } from 'react'\nimport type { ResourceModel, RowButtonModel, ViewModel } from '@protobase/schema'\nimport { useIsXs } from '../../lib/use-media-query'\nimport { recordKey } from '../../live/model-helpers'\nimport { humanize } from '../../live/naming'\nimport { buttonClass } from '../../primitives/button'\nimport { Skeleton } from '../../primitives/skeleton'\nimport { Section } from '../../record-view'\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 { scopeOf, useListPage } from '../pages/use-layout-data'\nimport { useAdminMeta } from '../meta-gate'\nimport { RowButtonLink } from '../row-button/row-button-link'\nimport type { CurrentAddress } from '../current-address'\nimport { AppLink } from '../use-app-address'\nimport { RelatedField } from './related-field'\nimport { text } from './messages'\n\ntype RelatedRecordProps = {\n title: string\n help?: string\n /** What shows after the title, such as how many records match. */\n count?: ReactNode\n model: ResourceModel\n view: ViewModel | undefined\n filter: string\n /** The order that picks the record, the list's own when empty. */\n sort: string\n /** The fields it shows, in full. */\n fields: string[]\n /** A button to an address the record's fields name. */\n button?: RowButtonModel\n empty?: string\n /** Where a record is started while none matches, when the user may create one. */\n add?: CurrentAddress\n}\n\nconst Empty = ({ empty }: { empty: string | undefined }) => <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n\nconst singularOf = (model: ResourceModel, view: ViewModel | undefined) => (view?.names?.singular ?? humanize(model.name)).toLowerCase()\n\n/**\n * A record page section showing the first record a filter finds as part of the page rather than a card: its `fields`\n * in full, under their labels when there are several and alone when there is one, with a link to its own page and\n * `button` on the heading's line, or, while none matches, a link to `add` one. A second record is read only to tell there are more, when \"View all\" opens them.\n */\nexport const RelatedRecord = ({ title, help, count, model, view, filter, sort, fields, button, empty, add }: RelatedRecordProps) => {\n const xs = useIsXs()\n const { resources } = useAdminMeta()\n const orderBy = sort || defaultOrderBy(model, view)\n const page = useListPage(model, { filter, sort: orderBy, pageSize: 2 })\n if (page.isPending) return <Section title={title} help={help} count={count}><Skeleton className=\"h-24 w-full\" /></Section>\n if (page.error) return <Section title={title} help={help} count={count}><ErrorBanner title={text('couldNotLoad')} error={page.error} /></Section>\n const [row, next] = page.data.items\n if (!row) {\n const adding = add && (\n <AppLink to={add} className={buttonClass({ size: 'sm' })}>\n <Plus className=\"size-3.5\" />\n {text('add', { singular: singularOf(model, view) })}\n </AppLink>\n )\n return <Section title={title} help={help} count={count} actions={adding}><Empty empty={empty} /></Section>\n }\n const scope = scopeOf(model, row)\n const singular = singularOf(model, view)\n const plural = view?.names?.plural ?? humanize(model.name)\n const labelled = fields.length > 1\n const shown = fields.map((path) => <RelatedField key={path} scope={scope} path={path} labelled={labelled} />)\n const actions = (\n <div className=\"flex flex-wrap items-center gap-2\">\n {button && <RowButtonLink button={button} model={model} view={view} record={row} models={resources} />}\n <AppLink to={{ kind: 'record', resource: model.name, key: recordKey(model, row) }} className={buttonClass({ size: 'sm' })}>\n {text('open', { singular })}\n </AppLink>\n </div>\n )\n return (\n <Section title={title} help={help} count={count} actions={actions}>\n <div className=\"flex min-w-0 flex-col gap-4\">\n {labelled ? <dl className=\"flex flex-col gap-4\">{shown}</dl> : shown}\n {next && (\n <AppLink to={viewAllAddress(model, view, xs, { filter, orderBy, display: embeddedDisplay(view, xs, {}) })} className=\"flex items-center gap-1 self-start 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 )}\n </div>\n </Section>\n )\n}\n","import { createWhere, parseFilter, printFilter, type RelatedModel, type ResourceModel } from '@protobase/schema'\n\nconst where = createWhere()\n\n// A single condition stays as it is, so the list that \"View all\" opens reads it as its own filter\nconst and = (...parts: Array<string | undefined>) => {\n const given = parts.filter((part): part is string => Boolean(part))\n return given.length === 1 ? given[0]! : given.map((part) => `(${part})`).join(' AND ')\n}\n\n/**\n * The filter on a related section's resource: its `field` is this record's key, or, through a join resource, one of\n * the keys the join records that point at this record hold. `null` without a key, so nothing can match.\n */\nexport const relatedMatch = (item: RelatedModel, value: string | number | boolean | null, resources: Record<string, ResourceModel>) => {\n const { through } = item\n if (value === null) return null\n if (!through) return and(printFilter(where.eq(item.field, value)), item.filter)\n const key = through.key ?? resources[through.resource]?.primaryKey[0]\n const links = parseFilter(and(printFilter(where.eq(through.field, value)), through.filter))\n if (!links.ok || !key) return null\n return and(printFilter(where.related(item.field, through.resource, key, links.ast)), item.filter)\n}\n","import { useQueries } from '@tanstack/react-query'\nimport type { RelatedModel } from '@protobase/schema'\nimport { useClient } from '../data/api-provider'\nimport { useAdminMeta } from './meta-gate'\nimport { countQuery } from './pages/use-layout-data'\nimport { relatedMatch } from './related-match'\n\n/** A related section and the value of this record its `field` is matched against. */\nexport type CountedRelated = { item: RelatedModel; value: string | number | boolean | null }\n\n/** What some counts add up to: `null` when one could not be counted, `undefined` while one is still loading. */\nexport const countTotal = (counts: Array<number | null | undefined>) => {\n if (counts.some((count) => count === null)) return null\n if (counts.some((count) => count === undefined)) return\n return counts.reduce<number>((total, count) => total + count!, 0)\n}\n\n/**\n * How many records the reader may see in these related sections together, one count query each, shared with every\n * other count of the same records, so a live change reads them again; `undefined` while one is loading. A section\n * that can match nothing counts 0, and one of a resource the reader cannot list counts nothing; `null` when one fails, so a failure never reads as 0.\n */\nexport const useRelatedCount = (sections: CountedRelated[], enabled = true) => {\n const client = useClient()\n const { resources } = useAdminMeta()\n const counted = sections.flatMap(({ item, value }) => {\n const model = resources[item.resource]\n return model ? [{ model, match: relatedMatch(item, value, resources) }] : []\n })\n const queries = useQueries({\n queries: counted.map(({ model, match }) => ({ ...countQuery(client, model, match ?? ''), enabled: enabled && match !== null })),\n })\n return countTotal(\n counted.map(({ match }, index) => {\n if (match === null) return 0\n const query = queries[index]!\n if (query.isError) return null\n // A server that gives neither an exact nor an estimated total has no count to show\n return query.isSuccess ? (query.data ?? null) : undefined\n }),\n )\n}\n","import { useState, type ReactNode } from 'react'\nimport { createWhere, printFilter, type RelatedModel } from '@protobase/schema'\nimport { listColumnNames } from '../live/columns-from-model'\nimport { Section } from '../record-view'\nimport { HeadingCount } from '../record-view/heading-count'\nimport { EmbeddedDisplaySwitch, EmbeddedList } from './embedded-list/embedded-list'\nimport { useEmbeddedDisplay } from './embedded-list/use-embedded-display'\nimport { relatedAdd } from './related-cards/related-add'\nimport { RelatedCards } from './related-cards/related-cards'\nimport { RelatedRecord } from './related-cards/related-record'\nimport { relatedOpens } from './related-opens'\nimport { relatedMatch } from './related-match'\nimport { useRelatedCount } from './related-count'\nimport { relatedHandOrder } from './hand-order/hand-order'\nimport { HandSortedList } from './hand-order/hand-sorted-list'\nimport { ReorderButton } from './hand-order/reorder-button'\nimport { useAdminMeta, usePermissions } from './meta-gate'\nimport { text } from './record-messages'\n\nconst where = createWhere()\n\nconst Empty = ({ empty }: { empty: string | undefined }) => <p className=\"text-muted-foreground\">{empty ?? text('nothingYet')}</p>\n\n/**\n * A record page section listing the first records of another resource that point at this record, directly or through\n * a join resource, in the list page's table or display, or as cards with their actions, with a link to them all in the list,\n * or the first one's fields in full. When they are ordered by\n * hand within this record, **Reorder** shows them all in their order, to be moved by their drag handles.\n */\nexport const RelatedSection = ({ item, value, owner }: { item: RelatedModel; value: string | number | boolean | null; owner: string }) => {\n const { resources, views, pages } = useAdminMeta()\n const model = resources[item.resource]\n const view = model && views[model.name]\n const match = relatedMatch(item, value, resources)\n const [display, pick] = useEmbeddedDisplay(view, `related:${owner}:${item.title}`, item.display)\n const permissions = usePermissions(item.resource)\n const [sorting, setSorting] = useState(false)\n // Only a section that hides while empty or shows its count counts its records\n const count = useRelatedCount([{ item, value }], Boolean(item.hideEmpty || item.count))\n if (!model) return null\n if (item.hideEmpty && (count === undefined || count === 0)) return null\n const heading = { title: item.title, help: item.help, count: item.count ? <HeadingCount count={count} names={view?.names} /> : undefined }\n const opens = relatedOpens(item, model, resources)\n // The relation names this record on every row, so it is left out of the default columns\n const columns = item.columns ?? listColumnNames(model, view).filter((name) => name !== item.field)\n // What it lists, when it can match any record\n const listed = (list: (filter: string) => ReactNode) => (match === null ? <Empty empty={item.empty} /> : list(match))\n if (item.presentation === 'cards' || item.presentation === 'compact') {\n const compact = item.presentation === 'compact' ? { time: item.time } : undefined\n // The time beside a compact card's title is not shown again among its values; the tone's value shows first, so its\n // colour is never all that says it\n const shown = compact ? columns.filter((name) => name !== item.time) : columns\n const values = item.tone === undefined || shown.includes(item.tone) ? shown : [item.tone, ...shown]\n return (\n <Section {...heading}>\n {listed((filter) => <RelatedCards model={model} view={view} filter={filter} sort={item.sort ?? ''} fields={values} actions={item.actions ?? []} button={item.button} limit={item.limit ?? 10} display={item.display} empty={item.empty} compact={compact} tone={item.tone} />)}\n </Section>\n )\n }\n if (item.presentation === 'record') {\n if (match === null) return <Section {...heading}><Empty empty={item.empty} /></Section>\n // A new match starts afresh, so the previous record never shows while its query loads\n return <RelatedRecord key={match} {...heading} model={model} view={view} filter={match} sort={item.sort ?? ''} fields={columns} button={item.button} empty={item.empty} add={relatedAdd(item, value, view, pages, permissions)} />\n }\n const handOrder = relatedHandOrder(item, model, permissions)\n const displaySwitch = <EmbeddedDisplaySwitch view={view} value={display} onChange={pick} />\n const actions = handOrder ? (\n <div className=\"flex items-center gap-2\">\n {!sorting && displaySwitch}\n <ReorderButton size=\"sm\" sorting={sorting} onChange={setSorting} />\n </div>\n ) : (\n displaySwitch\n )\n if (sorting && handOrder) {\n return (\n <Section {...heading} actions={actions}>\n <HandSortedList model={model} view={view} field={handOrder} filter={printFilter(where.eq(item.field, value!))} columns={columns} />\n </Section>\n )\n }\n return (\n <Section {...heading} actions={actions}>\n {listed((filter) => <EmbeddedList key={filter} model={model} view={view} filter={filter} sort={item.sort ?? ''} columns={columns} limit={item.limit ?? 10} display={display} empty={item.empty} opens={opens} button={item.button} />)}\n </Section>\n )\n}\n","import type { RelatedModel } from '@protobase/schema'\nimport { relationTarget } from './related-opens'\n\n/**\n * The value a related section's `field` is matched against: the record's key, or with `from` that field's value as it\n * is (a relation by its key). Null when the record holds none, so the section lists nothing.\n */\nexport const relatedValue = (item: RelatedModel, record: Record<string, unknown>, recordKey: string): string | number | boolean | null => {\n if (item.from === undefined) return recordKey\n const value = record[item.from]\n if (typeof value === 'boolean') return value\n return relationTarget(record, item.from) ?? null\n}\n","import { HeadingCount } from '../record-view/heading-count'\nimport { useAdminMeta } from './meta-gate'\nimport { useRelatedCount, type CountedRelated } from './related-count'\n\n/** How many records a group's related tables hold together, after its heading, named as their records when they are of one resource. */\nexport const GroupCount = ({ sections }: { sections: CountedRelated[] }) => {\n const count = useRelatedCount(sections)\n const { views } = useAdminMeta()\n const resources = new Set(sections.map(({ item }) => item.resource))\n const [only] = resources\n const names = resources.size === 1 ? views[only!]?.names : undefined\n return <HeadingCount count={count} names={names} />\n}\n","import type { ResourceModel, ViewModel } from '@protobase/schema'\n\n/**\n * The field whose value shows as a badge beside a record page's title: the view's `titleBadge`, else an enum `status`\n * the sidebar does not show already. None when the field is not `visible` to the reader or holds no value.\n */\nexport const titleBadgeField = (model: ResourceModel, view: ViewModel | undefined, record: Record<string, unknown>, sidebarFields: readonly string[], visible: (name: string) => boolean) => {\n const status = model.fields.status?.type === 'enum' && !sidebarFields.includes('status') ? 'status' : undefined\n const name = view?.titleBadge ?? status\n if (name === undefined || !model.fields[name] || !visible(name)) return\n const value = record[name]\n if (value === null || value === undefined || value === '') return\n return name\n}\n","import { createWhere, printFilter } from '@protobase/schema'\n\nconst where = createWhere()\n\n/** The filter that finds a record's messages: those whose relation `field` holds its key. */\nexport const recordMessagesFilter = (field: string, recordKey: string) => printFilter(where.eq(field, recordKey))\n","import type { ThreadSectionModel } from '@protobase/schema'\nimport { Section } from '../../record-view'\nimport { useAdminMeta } from '../meta-gate'\nimport type { LayoutRecord } from '../pages/record-scope'\nimport { useConditions } from '../pages/use-conditions'\nimport { MessageThread } from './message-thread'\nimport { recordMessagesFilter } from './record-filter'\nimport { ThreadBox } from './thread-box'\n\n/** The record's conversation (`l.thread`): the latest messages whose relation `item.field` holds its key, ending in a working indicator while `item.working` holds for the record, with its `item.calls` between them. */\nexport const ThreadSection = ({ item, scope }: { item: ThreadSectionModel; scope: LayoutRecord }) => {\n const { resources } = useAdminMeta()\n const [working] = useConditions(item.working === undefined ? [] : [item.working], scope)\n const model = resources[item.resource]\n if (!model) return null\n const callsModel = item.calls && resources[item.calls.resource]\n const calls = item.calls && callsModel && { model: callsModel, filter: recordMessagesFilter(item.calls.field, scope.key), fields: item.calls }\n return (\n <Section title={item.title} help={item.help}>\n <ThreadBox>\n <MessageThread model={model} filter={recordMessagesFilter(item.field, scope.key)} sender={item.sender} time={item.time} text={item.text} status={item.status} calls={calls} limit={item.limit} empty={item.empty} working={item.working === undefined ? undefined : working === true} />\n </ThreadBox>\n </Section>\n )\n}\n","import type { LayoutNode, ReadPlan } from '@protobase/layout'\nimport type { BlocksSectionModel } from '@protobase/schema'\nimport { PlanReadsProvider } from './plan-reads'\nimport { RootRecordScope, type LayoutRecord } from './record-scope'\nimport { RenderNode } from './render-node'\nimport { StartBlockQueries } from './start-block-queries'\n\n/**\n * A block tree on the record page (`l.blocks`), drawn as a composed page's inside the page's own record: its planned\n * reads all start as it draws, their `{{@root.…}}` slots filled from the record, and its blocks read the record as `@root`.\n */\nexport const RecordBlocks = ({ item, scope }: { item: BlocksSectionModel; scope: LayoutRecord }) => {\n // The server sent the tree and its plan as `@protobase/layout` makes them\n const tree = item.tree as LayoutNode\n const plan = item.reads as ReadPlan | undefined\n return (\n <RootRecordScope value={scope}>\n <PlanReadsProvider tree={tree} plan={plan}>\n <StartBlockQueries tree={tree} plan={plan} />\n <RenderNode node={tree} at=\"\" />\n </PlanReadsProvider>\n </RootRecordScope>\n )\n}\n","import { Skeleton } from '../primitives/skeleton'\nimport { lazyComponent } from './lazy-component'\n\n// The record page's sections that draw with code of their own, such as the lines' dragging and the conversation's\n// composer, load with the first record that shows one.\n\nexport const RecordLines = lazyComponent(() => import('./record-lines').then((module) => module.RecordLines), () => <Skeleton className=\"h-32 w-full rounded-lg\" />)\nexport const ComposerSection = lazyComponent(() => import('./conversation/composer-section').then((module) => module.ComposerSection), () => <Skeleton className=\"h-24 w-full rounded-lg\" />)\n","import { Check } from 'lucide-react'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { Fragment, useEffect, type ReactElement } from 'react'\nimport { isApiError } from '@protobase/client'\nimport { type LayoutItemModel, type ResourceModel, type ViewModel } from '@protobase/schema'\nimport { usePauseFocusRefresh } from '../data/focus-refresh'\nimport { keys } from '../data/query-keys'\nimport { useOpenedRecord, type LiveRecord } from '../data/use-record'\nimport { displayValue, valueTitle } from '../live/display-value'\nimport { fromDraft, isRequiredOnEdit, toDraft } from '../live/field-values'\nimport { auditField } from '../live/audit-fields'\nimport { humanize } from '../live/naming'\nimport { useRecordTitle } from './titles/record-titles'\nimport { Button, buttonClass } from '../primitives/button'\nimport { Skeleton } from '../primitives/skeleton'\nimport { cn } from '../lib/cn'\nimport { Field, GroupSection, KeyFacts, MetadataCard, RecordHeader, RecordTabs, Section, SpecTable } from '../record-view'\nimport { ErrorBanner } from './error-banner'\nimport { CustomSection } from './custom-section'\nimport { ConversationPage } from './conversation-page/conversation-page'\nimport { FullAreaRecord } from './full-area-record'\nimport { RecordFocusPage } from './focus/record-focus-page'\nimport { openedAddress } from './opened-address'\nimport { RecordOpens } from './record-opens'\nimport { MapSection } from './map/map-section'\nimport { RecordChartSection } from './record-chart/record-chart-section'\nimport { RecordTrendSection } from './record-trend/record-trend-section'\nimport { RecordActions } from './pages/record-actions'\nimport type { LayoutRecord } from './pages/record-scope'\nimport { FieldEditor, showsValue } from './field-editor'\nimport { groupOpen, toggledOpen } from './group-open'\nimport { attentionTab, shownTab, splitTabs } from './record-tabs'\nimport { isWideField, shownWidget } from './field-types/shown-widget'\nimport { WidgetPart } from './field-types/widget-part'\nimport { useProjectUi } from './pages/project-ui'\nimport { Notice, useAdminMeta, usePermissions } from './meta-gate'\nimport { can, fieldAccess } from './permissions'\nimport { useRestore } from './delete/use-restore'\nimport { useAuth } from '../auth'\nimport { inApp } from '../app-shell/breadcrumb'\nimport { draftStorageKey } from './draft-storage'\nimport { useRecordLines } from './use-record-lines'\nimport { useDeleteFlow } from './delete/use-delete-flow'\nimport { useNavigationGuard } from './router'\nimport { AppLink, useAppAddress } from './use-app-address'\nimport { FieldValue } from './pages/field-value'\nimport { GallerySection } from './gallery/gallery-section'\nimport { HistorySection } from './history/history-section'\nimport { CommentsSection } from './comments/comments-section'\nimport { filledFields } from './filled-fields'\nimport { namedIcon } from './named-icon'\nimport { fieldHelp, helpShown, recordShown, whenShown } from './record-mode/record-mode'\nimport { fallbackEntries } from './record-mode/shown-layout'\nimport { useShownLayout } from './record-mode/use-shown-layout'\nimport { useRecordEditor } from './use-record-editor'\nimport { useRecordElsewhere } from './use-record-elsewhere'\nimport { fieldMessage } from './field-errors'\nimport { useFocusFirstInvalid } from './use-focus-first-invalid'\nimport { useRelatedRecords } from './use-related-records'\nimport { IncomingCard } from './incoming-card'\nimport { isChosen, keyValue } from './create/create-values'\nimport { RelatedSection } from './related-section'\nimport { relatedValue } from './related-value'\nimport { GroupCount } from './group-count'\nimport { ValueBadge } from './value-badge'\nimport { titleBadgeField } from './read-values/title-badge'\nimport { useClient } from '../data/api-provider'\nimport { markdownExcerpt } from '../markdown/markdown-excerpt'\nimport { ThreadSection } from './conversation/thread-section'\nimport { RecordBlocks } from './pages/record-blocks'\nimport { isMarkdown } from '../markdown/markdown-hint'\nimport { ContactLink } from '../live/contact-link'\nimport { linkTextOf } from '../live/link-text'\nimport { jsonSummary } from '../live/json-summary'\nimport { contactFormat } from '../live/contact-links'\nimport { text as appText } from './messages'\nimport { text } from './record-messages'\nimport { RecordSkeleton } from './record-skeleton'\nimport { ComposerSection, RecordLines } from './record-sections'\nimport { FileViewerPage, viewedField } from './file-viewers/file-viewer-page'\n\nconst hidden = (model: ResourceModel, name: string) => name === model.tenant || model.primaryKey.includes(name)\n\n/**\n * The view's layout, or one section with the editable fields when the view has none, then History when the resource\n * keeps it and Comments when it takes them. The read view, which is all a user who may only read the resource gets,\n * shows every field: the record rather than what can be changed.\n */\nconst layoutFor = (model: ResourceModel, view: ViewModel | undefined, read: boolean): LayoutItemModel[] => {\n if (view && view.layout.length > 0) return view.layout\n // A write-only field is edited only where the view's layout names it\n const shown = Object.values(model.fields).filter((field) => !hidden(model, field.name) && !field.writeOnly)\n const editable = shown.filter((field) => !field.readOnly)\n const fields = (editable.length > 0 && !read ? editable : shown).map((field) => field.name)\n return [{ kind: 'section', title: text('details'), fields }, ...(model.history ? [{ kind: 'history' as const, title: text('history') }] : []), ...(model.comments ? [{ kind: 'comments' as const, title: text('comments') }] : [])]\n}\n\nexport const RecordPage = ({ resource, recordKey }: { resource: string; recordKey: string }) => {\n const { resources, views } = useAdminMeta()\n const { address } = useAppAddress()\n const ui = useProjectUi()\n const model = resources[resource]\n const record = useOpenedRecord(resource, recordKey)\n if (!model) return <Notice title={appText('notFound')}>{appText('noResource', { name: resource })}</Notice>\n if (record.isPending) return <RecordSkeleton />\n if (record.error) return <div className=\"p-8\">{isApiError(record.error) && record.error.status === 404 ? <RecordNotFound model={model} recordKey={recordKey} /> : <ErrorBanner title={text('couldNotLoad')} error={record.error} />}</div>\n // A record opened from a list shows that row's fields until it has loaded; the loaded record draws the page anew, so\n // its form starts from the whole record\n const standard = <LoadedRecord key={record.isPlaceholderData ? 'preview' : 'loaded'} model={model} recordKey={recordKey} stored={record.data} preview={record.isPlaceholderData} />\n // A file the address opens shows in the viewer for its type, once the whole record has its link\n const opened = address?.kind === 'record' && address.file !== undefined && !record.isPlaceholderData ? viewedField(ui, model, record.data.record, address.file) : undefined\n // Back leads to the page whose file links open viewers: the standard page, also on a view whose record page is another\n const ownPage = views[resource]?.recordOpens !== undefined || views[resource]?.record !== undefined\n const back = { kind: 'record' as const, resource, key: recordKey, ...(ownPage && { standard: true as const }) }\n if (opened) return <FileViewerPage key={opened.file.uri} model={model} record={record.data.record} viewed={opened} back={back} />\n const standardAsked = address?.kind === 'record' && address.standard === true\n const opens = views[resource]?.recordOpens\n if (opens && !standardAsked) {\n if (record.isPlaceholderData) return <RecordSkeleton />\n const to = openedAddress(opens, record.data.record)\n if (to) return <RecordOpens to={to} />\n }\n const page = views[resource]?.record\n if (!page || standardAsked) return standard\n // The app's component reads fields a list row may not have, so it waits for the whole record\n if (record.isPlaceholderData) return <RecordSkeleton />\n const { record: fields, etag, permissions } = record.data\n if ('conversation' in page) return <ConversationPage key={recordKey} page={page.conversation} scope={{ model, record: fields, key: recordKey, etag, permissions }} />\n if ('surface' in page || page.focus) return <RecordFocusPage model={model} recordKey={recordKey} stored={record.data} page={page} standard={standard} />\n return <FullAreaRecord component={page.component} scope={{ model, record: fields, key: recordKey, etag, permissions }} standard={standard} />\n}\n\n// A record the session's organization does not have may be in another of the person's organizations, which opens it\nconst RecordNotFound = ({ model, recordKey }: { model: ResourceModel; recordKey: string }) => {\n const elsewhere = useRecordElsewhere(model, recordKey)\n if (elsewhere.state === 'looking') return <RecordSkeleton />\n if (elsewhere.state === 'switching') return <Notice title={text('loading')}>{text('openingElsewhere')}</Notice>\n if (elsewhere.state === 'failed') return <ErrorBanner title={text('couldNotLoad')} error={elsewhere.error} />\n return <Notice title={appText('notFound')}>{text('noRecord')}</Notice>\n}\n\ntype LoadedRecordProps = {\n model: ResourceModel\n recordKey: string\n stored: LiveRecord\n /** `stored` is what a list row knows of the record: its fields show as they will, the others as placeholders, and none takes input. */\n preview: boolean\n}\n\nconst LoadedRecord = ({ model, recordKey, stored, preview }: LoadedRecordProps) => {\n const meta = useAdminMeta()\n const { address, go } = useAppAddress()\n const view = meta.views[model.name]\n const title = useRecordTitle()(model, view, stored.record, recordKey)\n const { state: auth } = useAuth()\n const lines = useRecordLines(model, recordKey)\n const editor = useRecordEditor({\n model,\n stored,\n recordKey,\n mode: view?.saveFeedback ?? 'toast',\n subject: title,\n // A draft kept from before waits for the whole record, which it was made to\n draftKey: !preview && auth.kind === 'signed-in' ? draftStorageKey(auth.user.id, model.name, recordKey) : undefined,\n lines: lines.draft,\n })\n const queryClient = useQueryClient()\n const client = useClient()\n const fieldsRef = useFocusFirstInvalid<HTMLDivElement>(editor.rejections)\n const permissions = usePermissions(model.name)\n const restore = useRestore(model)\n // An earlier version of the record, as a field type that keeps versions draws it, is only read\n const pastVersion = address?.kind === 'record' && address.version !== undefined\n const canUpdate = can(permissions, 'update') && stored.permissions?.update !== false && !pastVersion\n const { shown, offersEdit, editing } = recordShown(view?.recordMode, canUpdate, address?.kind === 'record' && address.edit === true)\n // Only the form leaves changes behind; on the read view a draft kept from before waits for Edit. A save under way\n // counts too, so leaving never cuts off a write and then restores the draft of a record that was saved.\n useNavigationGuard((editor.dirty && shown === 'form') || editor.saving)\n // Unsaved changes keep the version of the record they were made to, wherever the draft shows\n usePauseFocusRefresh(editor.dirty)\n const openGroups = address?.kind === 'record' ? address.open : undefined\n const atEdit = address?.kind === 'record' && address.edit === true\n const addressedTab = address?.kind === 'record' ? address.tab : undefined\n // The standard page of a view whose record page is the app's own component stays the standard page as it changes\n const standard = address?.kind === 'record' && address.standard === true\n const recordAt = (open: readonly string[] = [], edit = false, tab?: string) =>\n ({ kind: 'record' as const, resource: model.name, key: recordKey, ...(edit && { edit }), ...(open.length > 0 && { open }), ...(tab && { tab }), ...(standard && { standard }) })\n // Edit, Cancel and the save keep the groups the person opened and the tab they are on\n const readAddress = recordAt(openGroups, false, addressedTab)\n const editAddress = recordAt(openGroups, true, addressedTab)\n // A form that Edit opened goes back to the record once saved, or when its changes are dropped\n const leavesForm = shown === 'form' && view?.recordMode !== undefined && view.recordMode !== 'edit'\n const canDelete = can(permissions, 'delete') && stored.permissions?.delete !== false\n const remove = useDeleteFlow({\n model,\n view,\n restore,\n onDeleted: () => go({ kind: 'list', resource: model.name }, { replace: true }),\n onReview: () => void queryClient.invalidateQueries({ queryKey: keys.record(model.name, recordKey) }),\n })\n const related = useRelatedRecords(model, meta.resources, meta.views, stored.record)\n // A relation to a record of one key column is chosen on the form; the record's own key and its tenant are not\n const pickTarget = (name: string) => {\n const field = model.fields[name]\n const target = field?.relation ? meta.resources[field.relation.resource] : undefined\n if (!target || target.primaryKey.length !== 1 || name === model.tenant || model.primaryKey.includes(name)) return undefined\n return target\n }\n const picked = Object.values(model.fields).filter((field) => pickTarget(field.name))\n // The form names and links the record each relation points at now, chosen or stored\n const drafted = { ...stored.record, ...Object.fromEntries(picked.map((field) => [field.name, fromDraft(field, editor.value(field.name))])) }\n const chosen = useRelatedRecords(model, meta.resources, meta.views, drafted)\n const pick = (name: string, next: unknown) => {\n const target = pickTarget(name)\n if (!target || !isChosen(next)) return editor.change(name, next)\n // The picker knows the chosen record's name, so the form shows it without asking the server\n queryClient.setQueryData(keys.relatedLabel(target.name, next.key), { label: next.label })\n editor.change(name, keyValue(target, next.key))\n }\n const { fields: fieldTypes } = useProjectUi()\n // The items and fields meant only for the form, or only for reading the record, show only there\n const scope: LayoutRecord = { model, record: stored.record, key: recordKey, etag: stored.etag, permissions: stored.permissions }\n const layout = useShownLayout(layoutFor(model, view, shown === 'read'), scope, editing, preview)\n const { before, tabs, after } = splitTabs(layout)\n const tab = shownTab(tabs, addressedTab)\n const needsAttention = (name: string) => editing && (editor.errors[name] !== undefined || editor.conflicts[name] !== undefined)\n // A turned-down save moves to the first tab that holds a field to put right, where the form then focuses it\n useEffect(() => {\n if (editor.rejections === 0) return\n const target = attentionTab(tabs, tab, needsAttention)\n if (target) go(recordAt(openGroups, atEdit, target === tabs[0] ? undefined : target.title), { replace: true })\n }, [editor.rejections])\n const sidebarFields = layout.flatMap((item) => (item.kind === 'sidebar' ? item.fields : []))\n const updatedAt = auditField(model, 'updated')\n const hint = (name: string) => view?.fields[name]\n // A write-only field has no value to show, so it is on the form only\n const visible = (name: string) => fieldAccess(stored.permissions, name) !== 'hidden' && whenShown(hint(name)?.when, editing) && (shown === 'form' || !model.fields[name]?.writeOnly)\n const known = (name: string) => !preview || Object.hasOwn(stored.record, name)\n const badgeField = titleBadgeField(model, view, stored.record, sidebarFields, visible)\n const badge = badgeField && (\n <ValueBadge value={stored.record[badgeField]} hints={hint(badgeField)}>\n <span className=\"sr-only\">{hint(badgeField)?.label ?? humanize(badgeField)}: </span>\n {displayValue(model.fields[badgeField]!, stored.record[badgeField], hint(badgeField))}\n </ValueBadge>\n )\n\n const fieldView = (name: string) => {\n const field = model.fields[name]\n const access = fieldAccess(stored.permissions, name)\n if (!field || access === 'hidden') return null\n const conflict = editor.conflicts[name]\n const target = pickTarget(name)\n const label = hint(name)?.label ?? humanize(name)\n const problem = editor.errors[name]\n const locked = shown !== 'form' || access === 'read'\n return (\n <Field\n // A revealed sensitive value is forgotten when the record changes\n key={field.sensitive ? `${name}:${stored.etag}` : name}\n name={name}\n label={label}\n required={shown === 'form' && access !== 'read' && isRequiredOnEdit(field)}\n help={fieldHelp(hint(name), view, editing)}\n error={problem && fieldMessage(field, label, problem)}\n wide={isWideField(fieldTypes, field, hint(name))}\n readOnly={showsValue(field, hint(name), locked, Boolean(target))}\n conflict={\n conflict === undefined\n ? undefined\n : { user: { name: text('someoneElse'), initials: '?', hue: 40 }, ago: text('justNow'), theirValue: conflict || '—', onKeepMine: () => editor.keepMine(name), onUseTheirs: () => editor.useTheirs(name) }\n }\n >\n {known(name) ? (\n <FieldEditor\n field={field}\n hints={hint(name)}\n value={editor.value(name)}\n stored={stored.record[name]}\n relationLabel={chosen.labels[name]}\n relationTo={chosen.addresses[name]}\n relationPicker={target && { target, view: meta.views[target.name] }}\n locked={locked}\n invalid={Boolean(editor.errors[name])}\n reveal={field.sensitive && !field.writeOnly ? () => client.reveal(model.name, recordKey, name) : undefined}\n resource={model.name}\n record={stored.record}\n linkText={hint(name)?.format === 'url' ? linkTextOf(model, view, name, stored.record, related.labels) : undefined}\n onChange={(next) => pick(name, next)}\n />\n ) : (\n <Skeleton className=\"h-9\" />\n )}\n </Field>\n )\n }\n\n // The read view's row of a field: its value as the record page shows values, a sensitive one masked with its eye\n const readRow = (name: string) => {\n const field = model.fields[name]!\n const value = !known(name) ? (\n <Skeleton className=\"h-4 w-32\" />\n ) : field.sensitive ? (\n <FieldEditor field={field} hints={hint(name)} value=\"\" stored={stored.record[name]} locked reveal={() => client.reveal(model.name, recordKey, name)} resource={model.name} onChange={(next) => editor.change(name, next)} />\n ) : (\n <FieldValue model={model} field={field} value={stored.record[name]} relationLabel={related.labels[name]} record={stored.record} relationLabels={related.labels} />\n )\n return { label: hint(name)?.label ?? humanize(name), help: fieldHelp(hint(name), view, editing), wide: isWideField(fieldTypes, field, hint(name)), value }\n }\n\n // The sidebar's fields are one Summary card, where the first sidebar stands among the sidebar's custom components and maps\n const firstSidebar = layout.findIndex((item) => item.kind === 'sidebar')\n const summary = (\n <MetadataCard\n title={text('summary')}\n rows={sidebarFields.flatMap((name) => {\n const field = model.fields[name]\n if (!field || !visible(name)) return []\n if (!known(name)) return [{ label: hint(name)?.label ?? humanize(name), value: <Skeleton className=\"h-4 w-24\" /> }]\n const value = stored.record[name]\n const markdown = isMarkdown(field, hint(name)) && typeof value === 'string' && value !== ''\n // A sidebar value stays on one line, so markdown shows as its plain-text excerpt and JSON as its summary, like a list cell\n const json = field.type === 'json' && value !== null && value !== undefined\n const text = markdown ? markdownExcerpt(value) : json ? jsonSummary(value) : displayValue(field, value, hint(name))\n const contact = field.type === 'text' && typeof value === 'string' && value !== '' ? contactFormat(hint(name)) : undefined\n const builtIn = field.type === 'enum' ? <ValueBadge value={value} hints={hint(name)}>{text}</ValueBadge> : contact ? <ContactLink format={contact} value={text} label={linkTextOf(model, view, name, stored.record, related.labels)} /> : <span title={valueTitle(field, value, undefined, hint(name))}>{text}</span>\n const shown = shownWidget(fieldTypes, field, hint(name))\n return [{ label: hint(name)?.label ?? humanize(name), title: text, value: shown ? <WidgetPart shown={shown} part=\"display\" field={field} value={stored.record[name]} fallback={builtIn} /> : builtIn }]\n })}\n />\n )\n\n const save = async () => {\n if ((await editor.save()) && leavesForm) go(readAddress, { replace: true })\n }\n\n // Edit and Delete are actions like the view's own, in the rail; Save leads the sidebar, above them\n const startDelete = canDelete ? () => void remove.start({ key: recordKey, title, etag: stored.etag, snapshot: stored.record }) : undefined\n const formControls = shown === 'form' && (\n <>\n <Button variant=\"primary\" className=\"max-md:min-h-11 max-md:flex-1 md:w-full\" loading={editor.saving} disabled={!editor.dirty && editor.phase !== 'saved'} onClick={() => void save()}>\n {editor.phase === 'saved' && <Check className=\"size-4\" />}\n {editor.phase === 'saved' ? text('saved') : text('save')}\n </Button>\n {leavesForm && (\n // Cancel drops the changes when it leaves the form here, not when it opens the record in another tab\n <AppLink to={readAddress} className={cn(buttonClass(), 'max-md:min-h-11 md:w-full')} onClick={(event) => inApp(event) && editor.discard()}>\n {text('cancel')}\n </AppLink>\n )}\n {editor.dirty && <span className=\"text-xs text-muted-foreground max-md:order-first\">{text('unsavedChanges')}</span>}\n </>\n )\n\n // The main column's items; a group renders its sections and related tables through the same code\n const mainItem = (item: LayoutItemModel, index: number): ReactElement[] => {\n if (item.kind === 'group') {\n const children = item.items.flatMap(mainItem)\n if (children.length === 0) return []\n const open = groupOpen(item, openGroups, needsAttention)\n const toggle = item.collapsed ? recordAt(toggledOpen(openGroups, item.title), atEdit, addressedTab) : undefined\n // The count covers the related tables the page draws, closed or open\n const counted = item.items.flatMap((inner) => (inner.kind === 'related' && (inner.from === undefined || known(inner.from)) ? [{ item: inner, value: relatedValue(inner, stored.record, recordKey) }] : []))\n const count = item.count ? <GroupCount sections={counted} /> : undefined\n return [<GroupSection key={`group:${item.title}`} title={item.title} help={item.help} count={count} open={open} toggle={toggle}>{children}</GroupSection>]\n }\n if (item.kind === 'related' && item.lines) {\n // The lines load on their own, and only once the record has\n if (!lines.model || !lines.item || preview) return []\n return [<RecordLines key={`lines:${item.title}`} lines={{ ...lines, model: lines.model, item: lines.item }} editable={shown === 'form'} saving={editor.saving} />]\n }\n if (item.kind === 'related') {\n if (item.from !== undefined && !known(item.from)) return []\n return [<RelatedSection key={`related:${item.title}`} item={item} value={relatedValue(item, stored.record, recordKey)} owner={model.name} />]\n }\n if (item.kind === 'chart') return [<RecordChartSection key={`chart:${index}`} item={item} recordKey={recordKey} />]\n if (item.kind === 'trend') return [<RecordTrendSection key={`trend:${index}`} item={item} recordKey={recordKey} />]\n // Project components, maps, photos and block trees read fields a list row may not have, so they wait for the record\n if (preview && (item.kind === 'custom' || item.kind === 'map' || item.kind === 'gallery' || item.kind === 'blocks')) return []\n if (item.kind === 'custom') return item.sidebar ? [] : [<CustomSection key={`custom:${index}`} item={item} scope={scope} fallback={item.fallback && <>{fallbackEntries(item).flatMap(([entry, at]) => mainItem(entry, at))}</>} />]\n if (item.kind === 'map') return item.sidebar ? [] : [<MapSection key={`map:${index}`} item={item} record={stored.record} />]\n if (item.kind === 'gallery') return [<GallerySection key={`gallery:${index}`} item={item} record={stored.record} recordKey={recordKey} />]\n if (item.kind === 'history') return [<HistorySection key={`history:${index}`} item={item} model={model} view={view} recordKey={recordKey} etag={stored.etag} />]\n if (item.kind === 'thread') return [<ThreadSection key={`thread:${index}`} item={item} scope={scope} />]\n if (item.kind === 'blocks') return [<RecordBlocks key={`blocks:${index}`} item={item} scope={scope} />]\n // Writing waits for the record, so a message never goes out from the preview\n if (item.kind === 'composer') return preview ? [] : [<ComposerSection key={`composer:${index}`} item={item} owner={model} recordKey={recordKey} />]\n if (item.kind === 'comments') return [<CommentsSection key={`comments:${index}`} item={item} resource={model.name} recordKey={recordKey} canWrite={auth.kind !== 'visitor'} />]\n if (item.kind !== 'section') return []\n // A section whose fields are all hidden from this user would be a lone heading, as would key facts all empty\n const visibleFields = item.fields.filter((name) => model.fields[name] && visible(name))\n const facts = shown === 'read' && item.presentation === 'facts'\n const fields = facts ? filledFields(stored.record, visibleFields) : visibleFields\n if (fields.length === 0) return []\n return [\n <Section key={item.title} title={item.title} help={helpShown(item.helpWhen, view, editing) ? item.help : undefined}>\n {facts ? (\n <KeyFacts facts={fields.map((name) => ({ label: readRow(name).label, value: readRow(name).value, icon: namedIcon(hint(name)?.icon) }))} />\n ) : shown === 'read' ? (\n <SpecTable rows={fields.map(readRow)} />\n ) : (\n <div className=\"grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2\">{fields.map(fieldView)}</div>\n )}\n </Section>,\n ]\n }\n\n // A sidebar map, or a sidebar custom section with its fallback of sidebar maps and custom sections in its place\n const sidebarCard = (item: LayoutItemModel, index: number): ReactElement | null => {\n if (item.kind === 'map') return <MapSection key={`map:${index}`} item={item} record={stored.record} />\n if (item.kind !== 'custom') return null\n return <CustomSection key={`custom:${index}`} item={item} scope={scope} fallback={item.fallback && <>{fallbackEntries(item).map(([entry, at]) => sidebarCard(entry, at))}</>} />\n }\n\n return (\n // The preview looks as the loaded form will, but takes no input: typing there would be lost when the record loads\n <div ref={fieldsRef} className=\"flex flex-1 flex-col\" inert={preview}>\n {remove.dialogs}\n <div className=\"flex-1\">\n <div className={cn(view?.recordWidth !== 'full' && 'mx-auto max-w-[1100px]', 'px-4 pb-8 pt-6 md:px-10 md:py-8')}>\n <RecordHeader title={title} badge={badge} />\n {editor.message && <div className=\"mt-4\"><ErrorBanner title={text('notSaved')} error={new Error(editor.message)} /></div>}\n {editor.linesConflict && (\n <div className=\"mt-4\">\n <ErrorBanner title={text('linesChanged')} error={new Error(text('linesReloaded'))} />\n </div>\n )}\n {shown !== 'form' && offersEdit && editor.dirty && (\n <div className=\"mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2\" role=\"status\">\n <span>{text('unsavedKept')}</span>\n <span className=\"flex gap-2\">\n <AppLink to={editAddress} className={buttonClass({ size: 'sm' })}>{text('continueEditing')}</AppLink>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </span>\n </div>\n )}\n {shown === 'form' && editor.restored && (\n <div className=\"mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2\" role=\"status\">\n <span>{text('unsavedRestored')}</span>\n <span className=\"flex gap-2\">\n <Button size=\"sm\" onClick={editor.dismissRestored}>{text('keep')}</Button>\n <Button size=\"sm\" onClick={editor.discard}>{text('discard')}</Button>\n </span>\n </div>\n )}\n <div className=\"grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12\">\n <div className=\"divide-y divide-border\">\n {before.flatMap(mainItem)}\n {tab && (\n <RecordTabs tabs={tabs.map((each, index) => ({ title: each.title, to: recordAt(openGroups, atEdit, index === 0 ? undefined : each.title), current: each === tab }))} />\n )}\n {tab && (\n <div key={`tab:${tab.title}`} className=\"divide-y divide-border\">\n {tab.items.flatMap(mainItem)}\n </div>\n )}\n {after.flatMap(mainItem)}\n </div>\n {/* Beside the main column the sidebar stays in view below the top bar, and scrolls on its own when taller than the window */}\n <aside className=\"space-y-4 md:sticky md:top-[var(--pb-sticky-top,0px)] md:max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px))] md:self-start md:overflow-y-auto md:pb-4 md:pt-8\">\n {formControls && <div className=\"hidden flex-col items-center gap-2 md:flex\">{formControls}</div>}\n {!preview && <RecordActions model={model} stored={stored} recordKey={recordKey} edit={offersEdit ? editAddress : undefined} onDelete={startDelete} />}\n {firstSidebar === -1 && summary}\n {layout.map((item, index) => {\n if ((item.kind === 'custom' || item.kind === 'map') && item.sidebar && !preview) return sidebarCard(item, index)\n return index === firstSidebar ? <Fragment key=\"summary\">{summary}</Fragment> : null\n })}\n {/* The record's timestamps, but for those the Summary shows already */}\n <MetadataCard\n title={text('details')}\n rows={[auditField(model, 'created'), updatedAt].flatMap((name) => {\n const field = name ? model.fields[name] : undefined\n if (!name || !field || !visible(name) || sidebarFields.includes(name)) return []\n return [{ label: hint(name)?.label ?? humanize(name), value: known(name) ? <span title={valueTitle(field, stored.record[name], undefined, hint(name))}>{displayValue(field, stored.record[name], hint(name))}</span> : <Skeleton className=\"h-4 w-24\" /> }]\n })}\n />\n {!preview && <IncomingCard model={model} recordKey={recordKey} layout={layout} />}\n </aside>\n </div>\n </div>\n </div>\n {/* On a mobile screen the form's controls stay in view below the record, above the shell's bottom bar */}\n {formControls && (\n <div className=\"sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden\">{formControls}</div>\n )}\n </div>\n )\n}\n"],"file":"record-page-Ctj-uKq1.js","debugId":"ad8feb8a-ab5c-4c3e-8d64-451416124b39"}
|