@everfur/sdk 0.15.0 → 0.16.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/CHANGELOG.md +160 -0
- package/LICENSE.md +1 -0
- package/README.md +12 -5
- package/SDK-LICENSE.txt +130 -0
- package/THIRD_PARTY_NOTICES +9 -0
- package/dist/CameraPort.d-Cv31Pz7g.d.cts +1 -0
- package/dist/CameraPort.d-Cv31Pz7g.d.ts +1 -0
- package/dist/{DepthViews.d-dXWL6ToG.d.cts → DepthViews.d-A7S-XYiI.d.ts} +2 -1
- package/dist/{DepthViews.d-DbJejGm3.d.ts → DepthViews.d-C4TIZDfz.d.cts} +2 -1
- package/dist/{DepthViews.d-CuBElgEc.d.ts → DepthViews.d-CNjaHLAS.d.ts} +2 -1
- package/dist/{DepthViews.d-BqMnWSMu.d.cts → DepthViews.d-DapfRz1S.d.cts} +2 -1
- package/dist/ErrorPolicyPort.d-68yrE3BE.d.ts +1 -0
- package/dist/ErrorPolicyPort.d-DirW9hgO.d.cts +1 -0
- package/dist/EverfurError.d-8NHtlgzA.d.cts +1 -0
- package/dist/EverfurError.d-8NHtlgzA.d.ts +1 -0
- package/dist/EverfurResult.d-BFH-3s6E.d.cts +1 -0
- package/dist/EverfurResult.d-D_-254ZY.d.ts +1 -0
- package/dist/IntakeMedia.d-4a89XrP7.d.ts +1 -0
- package/dist/IntakeMedia.d-DGxrhgIW.d.ts +1 -0
- package/dist/IntakeMedia.d-DUPR4lVM.d.cts +1 -0
- package/dist/IntakeMedia.d-JJCUvQu7.d.cts +1 -0
- package/dist/LICENSE.md +1 -0
- package/dist/LifecyclePort.d-Cr1p33a7.d.cts +1 -0
- package/dist/LifecyclePort.d-Cr1p33a7.d.ts +1 -0
- package/dist/PhotoController.d-BzCJOE7e.d.cts +1 -0
- package/dist/PhotoController.d-D0XiUUOl.d.ts +1 -0
- package/dist/{RecordsPage.d-DKrZ9rHX.d.ts → RecordsPage.d-6WMbieaV.d.ts} +2 -1
- package/dist/{RecordsPage.d-DRPdUAo4.d.cts → RecordsPage.d-B2gLf8RH.d.cts} +2 -1
- package/dist/SDK-LICENSE.txt +130 -0
- package/dist/THIRD_PARTY_NOTICES +9 -0
- package/dist/TelemetryPort.d-BDNr00hu.d.cts +1 -0
- package/dist/TelemetryPort.d-BDNr00hu.d.ts +1 -0
- package/dist/animations/index.cjs +2 -1
- package/dist/animations/index.d.cts +24 -23
- package/dist/animations/index.d.ts +24 -23
- package/dist/animations/index.js +2 -1
- package/dist/{Chat.d-a7Ksz7NZ.d.ts → appStateLifecycle.d-B7L427MF.d.ts} +73 -141
- package/dist/{Chat.d-CtfANk3A.d.cts → appStateLifecycle.d-CWedOJq4.d.cts} +73 -141
- package/dist/{attachments.d-CpaOfi2g.d.cts → attachments.d-BARh-PrJ.d.cts} +26 -7
- package/dist/{attachments.d-BGn2_knv.d.ts → attachments.d-CB0R1_vK.d.ts} +26 -7
- package/dist/{attachments.d-CoQhXrP9.d.ts → attachments.d-CPgp4_W-.d.ts} +3 -2
- package/dist/{attachments.d-CqHMGoER.d.cts → attachments.d-DeoaCEMD.d.cts} +3 -2
- package/dist/{bookingCopy.d-BwCOCZUj.d.ts → bookingCopy.d-BakTjvWw.d.ts} +3 -2
- package/dist/{bookingCopy.d-Bnq2zk0F.d.cts → bookingCopy.d-CVmpuk9C.d.cts} +3 -2
- package/dist/branding.d-Bbc6p1XY.d.cts +1 -0
- package/dist/branding.d-y6c0UwhE.d.ts +1 -0
- package/dist/cacheEpoch.d-DknKn3S0.d.cts +1 -0
- package/dist/cacheEpoch.d-DknKn3S0.d.ts +1 -0
- package/dist/callCopy.d-Bw6oZT54.d.cts +1 -0
- package/dist/callCopy.d-Bw6oZT54.d.ts +1 -0
- package/dist/callRoom.d-B1DoYdJe.d.cts +1 -0
- package/dist/callRoom.d-Dqm1rUqT.d.ts +1 -0
- package/dist/{casesRepository.d-DG83Ggbq.d.ts → casesRepository.d-CuokarTU.d.ts} +2 -1
- package/dist/{casesRepository.d-CsUJ2Oyb.d.cts → casesRepository.d-DKRLtYb8.d.cts} +2 -1
- package/dist/chat/index.cjs +229 -214
- package/dist/chat/index.d.cts +12 -9
- package/dist/chat/index.d.ts +12 -9
- package/dist/chat/index.js +230 -215
- package/dist/client/index.cjs +2 -1
- package/dist/client/index.d.cts +7 -6
- package/dist/client/index.d.ts +7 -6
- package/dist/client/index.js +2 -1
- package/dist/{clinicBatch.d-Byjx4y_W.d.ts → clinicBatch.d-BP_Rpvcy.d.ts} +3 -2
- package/dist/{clinicBatch.d-BLpbpS51.d.cts → clinicBatch.d-BTDdhMQ2.d.cts} +3 -2
- package/dist/clinicModels.d-BXgKZqDb.d.cts +1 -0
- package/dist/clinicModels.d-CaS64-P-.d.ts +1 -0
- package/dist/clinicRequestProps.d-1dCtouGA.d.cts +1 -0
- package/dist/clinicRequestProps.d-CjsMg_OD.d.ts +1 -0
- package/dist/{config.d-C0WgjutL.d.cts → config.d-84fNJFv9.d.cts} +2 -1
- package/dist/{config.d-zd2eTb2L.d.ts → config.d-B4-Mrwq2.d.ts} +2 -1
- package/dist/consent/index.cjs +1 -0
- package/dist/consent/index.d.cts +6 -5
- package/dist/consent/index.d.ts +6 -5
- package/dist/consent/index.js +1 -0
- package/dist/{context.d-Du_UPxa1.d.cts → context.d-87MMrNm6.d.cts} +6 -5
- package/dist/{context.d-BBjmV0rz.d.ts → context.d-rNGMZH8T.d.ts} +6 -5
- package/dist/{copy.d-Da_PP2K3.d.cts → copy.d-CJOLhJac.d.cts} +3 -2
- package/dist/{copy.d-D_VVj01o.d.ts → copy.d-DbwWriBp.d.ts} +3 -2
- package/dist/core/index.cjs +2 -1
- package/dist/core/index.d.cts +14 -13
- package/dist/core/index.d.ts +14 -13
- package/dist/core/index.js +2 -1
- package/dist/{depth.d-RTV61QNf.d.cts → depth.d-CXpPxNSK.d.cts} +3 -2
- package/dist/{depth.d-BEedifOR.d.ts → depth.d-Dca1T_RH.d.ts} +3 -2
- package/dist/{entitlementRepository.d-BwThmh3V.d.ts → entitlementRepository.d-BBRYTUlp.d.ts} +3 -2
- package/dist/{entitlementRepository.d-C-stdRyA.d.cts → entitlementRepository.d-DBhzBQjZ.d.cts} +3 -2
- package/dist/features.d-DrQxTw3-.d.cts +1 -0
- package/dist/features.d-DrQxTw3-.d.ts +1 -0
- package/dist/{focus.d-Dsm39DjO.d.cts → focus.d-BQnOVAql.d.cts} +4 -3
- package/dist/{focus.d-CtotIyEt.d.ts → focus.d-BZ2sEpbU.d.ts} +4 -3
- package/dist/health-plan/index.cjs +135 -131
- package/dist/health-plan/index.d.cts +78 -24
- package/dist/health-plan/index.d.ts +78 -24
- package/dist/health-plan/index.js +135 -131
- package/dist/{idempotency.d-Cv-B7SfC.d.ts → idempotency.d-9wNNohIA.d.cts} +2 -1
- package/dist/{idempotency.d-Bfm7oIxS.d.cts → idempotency.d-BdB17veP.d.ts} +2 -1
- package/dist/{identity.d-BksOEa6m.d.ts → identity.d-DxNvhj3a.d.ts} +2 -1
- package/dist/{identity.d-CioQhZrq.d.cts → identity.d-nRZBzkG2.d.cts} +2 -1
- package/dist/ids.d-B2GAAifq.d.cts +1 -0
- package/dist/ids.d-B2GAAifq.d.ts +1 -0
- package/dist/index.cjs +234 -219
- package/dist/index.d.cts +15 -12
- package/dist/index.d.ts +15 -12
- package/dist/index.js +235 -220
- package/dist/{introEvents.d-fAZitxMA.d.cts → introEvents.d-CQeiUeLn.d.cts} +2 -1
- package/dist/{introEvents.d-tOi4o3F4.d.ts → introEvents.d-bkIxpIKr.d.ts} +2 -1
- package/dist/introEvents.d-dS3fJCH1.d.cts +1 -0
- package/dist/introEvents.d-dS3fJCH1.d.ts +1 -0
- package/dist/models.d-BSqvbTE1.d.cts +1 -0
- package/dist/models.d-DOwnr8fi.d.ts +1 -0
- package/dist/notifications/index.cjs +1 -0
- package/dist/notifications/index.d.cts +5 -4
- package/dist/notifications/index.d.ts +5 -4
- package/dist/notifications/index.js +1 -0
- package/dist/{optInView.d-BkNSv4Gk.d.cts → optInView.d-BbVUUeoG.d.cts} +15 -2
- package/dist/{optInView.d-B8zTORO2.d.ts → optInView.d-DVJcB4Gp.d.ts} +15 -2
- package/dist/optionalModule.d-DbJmsq5f.d.cts +1 -0
- package/dist/optionalModule.d-DbJmsq5f.d.ts +1 -0
- package/dist/{parse.d-B5JHS6Pr.d.ts → parse.d-CGeJrcAC.d.ts} +2 -1
- package/dist/{parse.d-BgjO82mY.d.cts → parse.d-Dk0BasyK.d.cts} +2 -1
- package/dist/{pets.d-OWxskXCP.d.ts → pets.d-DBopbeRe.d.ts} +2 -1
- package/dist/{pets.d-B_LoizOv.d.cts → pets.d-DVptPgi0.d.cts} +2 -1
- package/dist/{petsRepository.d-Ba3xhJcj.d.ts → petsRepository.d-BtuooSOW.d.ts} +2 -1
- package/dist/{petsRepository.d-B5DWzU7C.d.cts → petsRepository.d-Daef7u0o.d.cts} +2 -1
- package/dist/photo/index.cjs +1 -0
- package/dist/photo/index.d.cts +1 -0
- package/dist/photo/index.d.ts +1 -0
- package/dist/photo/index.js +1 -0
- package/dist/ports.d-BX4f4UsB.d.cts +1 -0
- package/dist/ports.d-BX4f4UsB.d.ts +1 -0
- package/dist/{ports.d-BDtwHxmW.d.ts → ports.d-BxCVSbSi.d.ts} +5 -4
- package/dist/{ports.d-gZNTn8Qf.d.cts → ports.d-CAT70bVD.d.cts} +5 -4
- package/dist/presentation.d-vy8kTGfR.d.cts +1 -0
- package/dist/presentation.d-vy8kTGfR.d.ts +1 -0
- package/dist/profile.d-CSs1wlXT.d.cts +1 -0
- package/dist/profile.d-CSs1wlXT.d.ts +1 -0
- package/dist/projection.d-CeIUsbSk.d.cts +1 -0
- package/dist/projection.d-CeIUsbSk.d.ts +1 -0
- package/dist/quickPrompts.d-NM_81Jc1.d.cts +1 -0
- package/dist/quickPrompts.d-NM_81Jc1.d.ts +1 -0
- package/dist/records/depth/index.cjs +2 -1
- package/dist/records/depth/index.d.cts +10 -9
- package/dist/records/depth/index.d.ts +10 -9
- package/dist/records/depth/index.js +2 -1
- package/dist/records/index.cjs +243 -200
- package/dist/records/index.d.cts +170 -73
- package/dist/records/index.d.ts +170 -73
- package/dist/records/index.js +244 -201
- package/dist/recordsAsk.d-C5CGSi3j.d.cts +1 -0
- package/dist/recordsAsk.d-C5CGSi3j.d.ts +1 -0
- package/dist/{requestFunnel.d-DFf9C__p.d.ts → requestFunnel.d-Cxt0JqYx.d.ts} +3 -2
- package/dist/{requestFunnel.d-CR4akGCY.d.cts → requestFunnel.d-mEu6B-n8.d.cts} +3 -2
- package/dist/resolve.d-CoQWUy1Y.d.cts +1 -0
- package/dist/resolve.d-CoQWUy1Y.d.ts +1 -0
- package/dist/{runtimeTypes.d-BqBOrZxa.d.ts → runtimeTypes.d-Bkcj_XQy.d.ts} +5 -4
- package/dist/{runtimeTypes.d-CHdH-y2c.d.cts → runtimeTypes.d-D_qHJROH.d.cts} +5 -4
- package/dist/{screenProps.d-B1dIANI0.d.cts → screenProps.d-CR1lrpzR.d.cts} +3 -2
- package/dist/{screenProps.d-CVqFJw-J.d.ts → screenProps.d-D9n-ancr.d.ts} +3 -2
- package/dist/server/events/index.cjs +2 -1
- package/dist/server/events/index.d.cts +3 -2
- package/dist/server/events/index.d.ts +3 -2
- package/dist/server/events/index.js +2 -1
- package/dist/server/index.cjs +2 -1
- package/dist/server/index.d.cts +4 -3
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +2 -1
- package/dist/sheetCopy.d-CAhLOxjc.d.cts +1 -0
- package/dist/sheetCopy.d-CAhLOxjc.d.ts +1 -0
- package/dist/sheetSeam.d-B09jf4YC.d.ts +1 -0
- package/dist/sheetSeam.d-BBuEIVsa.d.cts +1 -0
- package/dist/shop/index.cjs +17 -16
- package/dist/shop/index.d.cts +13 -3
- package/dist/shop/index.d.ts +13 -3
- package/dist/shop/index.js +17 -16
- package/dist/species.d-BXAIMh7I.d.cts +1 -0
- package/dist/species.d-BXAIMh7I.d.ts +1 -0
- package/dist/tabs/index.cjs +5 -4
- package/dist/tabs/index.d.cts +35 -15
- package/dist/tabs/index.d.ts +35 -15
- package/dist/tabs/index.js +6 -5
- package/dist/tabsModel.d-B7QMug1u.d.cts +16 -0
- package/dist/tabsModel.d-B7QMug1u.d.ts +16 -0
- package/dist/televet/booking/index.cjs +1 -0
- package/dist/televet/booking/index.d.cts +7 -6
- package/dist/televet/booking/index.d.ts +7 -6
- package/dist/televet/booking/index.js +1 -0
- package/dist/televet/call/index.cjs +1 -0
- package/dist/televet/call/index.d.cts +1 -0
- package/dist/televet/call/index.d.ts +1 -0
- package/dist/televet/call/index.js +1 -0
- package/dist/televet/index.cjs +1 -0
- package/dist/televet/index.d.cts +1 -0
- package/dist/televet/index.d.ts +1 -0
- package/dist/televet/index.js +1 -0
- package/dist/televetGlobal.d-CC-DrqkQ.d.ts +1 -0
- package/dist/televetGlobal.d-CKwDCbmN.d.cts +1 -0
- package/dist/testing/index.cjs +1 -0
- package/dist/testing/index.d.cts +2 -1
- package/dist/testing/index.d.ts +2 -1
- package/dist/testing/index.js +1 -0
- package/dist/testing/rn/index.cjs +2 -2
- package/dist/testing/rn/index.d.cts +11 -9
- package/dist/testing/rn/index.d.ts +11 -9
- package/dist/testing/rn/index.js +2 -2
- package/dist/testing/web/index.cjs +1 -0
- package/dist/testing/web/index.d.cts +8 -7
- package/dist/testing/web/index.d.ts +8 -7
- package/dist/testing/web/index.js +1 -0
- package/dist/texting/index.cjs +23 -17
- package/dist/texting/index.d.cts +9 -6
- package/dist/texting/index.d.ts +9 -6
- package/dist/texting/index.js +24 -18
- package/dist/threadOptions.d-6hfQS1x7.d.cts +55 -0
- package/dist/threadOptions.d-6hfQS1x7.d.ts +55 -0
- package/dist/threadOptions.d-BEG-LZrC.d.cts +147 -0
- package/dist/threadOptions.d-BerQM1Ql.d.ts +147 -0
- package/dist/{threadOptions.d-DZ0AoQGk.d.ts → threadOptions.d-BgBvSIw8.d.ts} +7 -40
- package/dist/{threadOptions.d-CnSfFVMr.d.cts → threadOptions.d-P9v7I7va.d.cts} +7 -40
- package/dist/{timelineRows.d-CF1KvLcQ.d.cts → timelineRows.d-C04lp_Vj.d.cts} +2 -1
- package/dist/{timelineRows.d-CtL0y7y1.d.ts → timelineRows.d-_7JemrY-.d.ts} +2 -1
- package/dist/tokens.d-BUVqme2D.d.cts +1 -0
- package/dist/tokens.d-BUVqme2D.d.ts +1 -0
- package/dist/typeStyle.d-B3Kdtjie.d.ts +1 -0
- package/dist/typeStyle.d-DmlwyJq-.d.cts +1 -0
- package/dist/uploadTransport.d-CWL7CdWP.d.cts +1 -0
- package/dist/uploadTransport.d-EGoUl7gX.d.ts +1 -0
- package/dist/{planSignals.d-DtxZoWGM.d.ts → useHealthPlanSubscription.d-CUbHE6eK.d.ts} +82 -3
- package/dist/{planSignals.d-Cl6n5QpS.d.cts → useHealthPlanSubscription.d-OhLZpn-n.d.cts} +82 -3
- package/dist/useIntroSeen.d-CTWFUthO.d.cts +1 -0
- package/dist/useIntroSeen.d-CTWFUthO.d.ts +1 -0
- package/dist/{usePresentation.d-BsR08Wxt.d.ts → usePresentation.d-CBtBx38t.d.ts} +41 -40
- package/dist/{usePresentation.d-CZS0qlLI.d.cts → usePresentation.d-YkJeq9mf.d.cts} +41 -40
- package/dist/useRecords.d-BYNX01El.d.cts +1 -0
- package/dist/useRecords.d-DWk61a4c.d.ts +1 -0
- package/dist/{useRecordsDepth.d-k-zYIHTe.d.cts → useRecordsDepth.d-FTImzp6T.d.cts} +2 -1
- package/dist/{useRecordsDepth.d-DTAxFf5s.d.ts → useRecordsDepth.d-_rqDIvoq.d.ts} +2 -1
- package/dist/useVetVisit.d-BtdwhmgD.d.cts +1 -0
- package/dist/useVetVisit.d-DoYQimyt.d.ts +1 -0
- package/dist/video/index.cjs +1 -0
- package/dist/video/index.d.cts +1 -0
- package/dist/video/index.d.ts +1 -0
- package/dist/video/index.js +1 -0
- package/dist/{view.d-CAWQjcY_.d.cts → view.d-Dd6AfMvG.d.cts} +4 -3
- package/dist/{view.d-BE7VOlsB.d.ts → view.d-gmYinlac.d.ts} +4 -3
- package/dist/visitIntent.d-D7_yVp1I.d.cts +1 -0
- package/dist/visitIntent.d-D7_yVp1I.d.ts +1 -0
- package/dist/web/consent/index.cjs +1 -0
- package/dist/web/consent/index.d.cts +6 -5
- package/dist/web/consent/index.d.ts +6 -5
- package/dist/web/consent/index.js +1 -0
- package/dist/web/health-plan/index.cjs +3 -2
- package/dist/web/health-plan/index.d.cts +16 -69
- package/dist/web/health-plan/index.d.ts +16 -69
- package/dist/web/health-plan/index.js +3 -2
- package/dist/web/index.cjs +20 -17
- package/dist/web/index.d.cts +35 -43
- package/dist/web/index.d.ts +35 -43
- package/dist/web/index.js +20 -17
- package/dist/web/intro/index.cjs +1 -0
- package/dist/web/intro/index.d.cts +7 -6
- package/dist/web/intro/index.d.ts +7 -6
- package/dist/web/intro/index.js +1 -0
- package/dist/web/notifications/index.cjs +1 -0
- package/dist/web/notifications/index.d.cts +4 -3
- package/dist/web/notifications/index.d.ts +4 -3
- package/dist/web/notifications/index.js +1 -0
- package/dist/web/records/depth/index.cjs +1 -0
- package/dist/web/records/depth/index.d.cts +10 -9
- package/dist/web/records/depth/index.d.ts +10 -9
- package/dist/web/records/depth/index.js +1 -0
- package/dist/web/records/index.cjs +1 -0
- package/dist/web/records/index.d.cts +12 -11
- package/dist/web/records/index.d.ts +12 -11
- package/dist/web/records/index.js +1 -0
- package/dist/web/records/upload/index.cjs +1 -0
- package/dist/web/records/upload/index.d.cts +1 -0
- package/dist/web/records/upload/index.d.ts +1 -0
- package/dist/web/records/upload/index.js +1 -0
- package/dist/web/records-sheet/index.cjs +12 -11
- package/dist/web/records-sheet/index.d.cts +1 -0
- package/dist/web/records-sheet/index.d.ts +1 -0
- package/dist/web/records-sheet/index.js +12 -11
- package/dist/web/shop/index.cjs +12 -11
- package/dist/web/shop/index.d.cts +4 -3
- package/dist/web/shop/index.d.ts +4 -3
- package/dist/web/shop/index.js +12 -11
- package/dist/web/televet/booking/index.cjs +1 -0
- package/dist/web/televet/booking/index.d.cts +7 -6
- package/dist/web/televet/booking/index.d.ts +7 -6
- package/dist/web/televet/booking/index.js +1 -0
- package/dist/web/televet/call/index.cjs +1 -0
- package/dist/web/televet/call/index.d.cts +1 -0
- package/dist/web/televet/call/index.d.ts +1 -0
- package/dist/web/televet/call/index.js +1 -0
- package/dist/web/televet/index.cjs +1 -0
- package/dist/web/televet/index.d.cts +1 -0
- package/dist/web/televet/index.d.ts +1 -0
- package/dist/web/televet/index.js +1 -0
- package/dist/web/texting/index.cjs +2 -1
- package/dist/web/texting/index.d.cts +9 -6
- package/dist/web/texting/index.d.ts +9 -6
- package/dist/web/texting/index.js +2 -1
- package/package.json +15 -6
- package/LICENSE +0 -21
- package/dist/tabsModel.d-BfIQg6yS.d.cts +0 -31
- package/dist/tabsModel.d-BfIQg6yS.d.ts +0 -31
package/dist/records/index.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
1
2
|
"use strict";var react=require("react"),zod=require("zod"),reactNative=require("react-native"),jsxRuntime=require("react/jsx-runtime"),reactNativeSafeAreaContext=require("react-native-safe-area-context");var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
2
3
|
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
3
4
|
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
@@ -102,13 +103,13 @@ return Object.freeze({docId:d.doc_id,title:d.title??null,documentClass:d.documen
|
|
|
102
103
|
return Object.freeze({petRef:pet,schemaVersion:schemaVersion,isEmpty:isEmpty,withheld:false,generatedAt:strOrNull(w.generated_at),identity:/* @__PURE__ */Object.freeze(identity),entities:/* @__PURE__ */Object.freeze(entities),entitySeries:/* @__PURE__ */Object.freeze(entitySeries),forwardLooking:/* @__PURE__ */Object.freeze(forwardLooking),documents:/* @__PURE__ */Object.freeze(documents),disclaimer:disclaimer})}function withheldView(petRef,schemaVersion,disclaimer){/* @__PURE__ */
|
|
103
104
|
return Object.freeze({petRef:petRef,schemaVersion:schemaVersion,isEmpty:false,withheld:true,generatedAt:null,identity:/* @__PURE__ */Object.freeze([]),entities:/* @__PURE__ */Object.freeze([]),entitySeries:/* @__PURE__ */Object.freeze([]),forwardLooking:/* @__PURE__ */Object.freeze([]),documents:/* @__PURE__ */Object.freeze({}),disclaimer:disclaimer})}var consentSchema=/* @__PURE__ */zod.z.object({pet_ref:/* @__PURE__ */zod.z.string().optional(),granted:/* @__PURE__ */zod.z.boolean().optional(),version:/* @__PURE__ */zod.z.string().nullish(),granted_at:/* @__PURE__ */zod.z.string().nullish()});function mapConsent(petRef,wire){let parsed=consentSchema.safeParse(wire),data=parsed.success?parsed.data:{};/* @__PURE__ */
|
|
104
105
|
return Object.freeze({petRef:typeof data.pet_ref=="string"&&data.pet_ref.length>0?data.pet_ref:petRef,granted:data.granted===true,version:data.version??null,grantedAt:data.granted_at??null})}function isObject(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function numberOr(v,fallback){return typeof v=="number"&&Number.isFinite(v)?v:fallback}function strOr(v,fallback){return typeof v=="string"&&v.length>0?v:fallback}function strOrNull(v){return typeof v=="string"&&v.length>0?v:null}var RECORDS_TERMINAL=/* @__PURE__ */Object.freeze(["published","failed","revoked"]);function isTerminalStatus(status){return RECORDS_TERMINAL.includes(status)}function recordsDenialReasonOf(error){if(error===null)return null;let reason=error.recordsReason;return reason==="consent_required"||reason==="session_required"||reason==="entitlement"||reason==="pet_not_found"?reason:null}var RECORDS_CONSENT_REQUIRED_WIRE_CODE="records_consent_required";function recordsWireCodeOf(error){let raw=error.raw;if(raw===null||typeof raw!="object")return null;let body=raw,code=typeof body.error=="object"&&body.error!==null?body.error.code:body.code;return typeof code=="string"&&code.length>0?code:null}function isRecordsConsentRequired(error){return error===null||error.httpStatus!==409?false:recordsWireCodeOf(error)===RECORDS_CONSENT_REQUIRED_WIRE_CODE}var unavailableUploadTransport=/* @__PURE__ */Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function isUploadTransportAvailable(transport){return transport!==unavailableUploadTransport}var noopRecordsTelemetry=/* @__PURE__ */Object.freeze({record(){}}),MAX_UPLOAD_BYTES=25*1024*1024,CONSENT_VERSION_MAX=64,IDEMPOTENCY_KEY_MAX=128,PET_REF_MAX=128;var UPLOAD_DEADLINE_MS=9e4;function createRecordsController(deps){return new RecordsControllerImpl(deps)}var RecordsControllerImpl=class{constructor(deps){this.recordCache=/* @__PURE__ */new Map;this.consentEpoch=/* @__PURE__ */new Map;this.reportedGaps=/* @__PURE__ */new Set;this.features=RECORDS_FEATURES_PDF_ONLY;this.repository=deps.repository,this.uploads=deps.uploads,this.telemetry=deps.telemetry??noopRecordsTelemetry,this.newIdempotencyKey=deps.newIdempotencyKey??defaultIdempotencyFactory(),this.timers=deps.timers??defaultTimers,this.uploadDeadlineMs=deps.uploadDeadlineMs??UPLOAD_DEADLINE_MS}async createUploadRequest(input){let res=await this.repository.createRequest({pet_ref:input.petRef,idempotency_key:input.idempotencyKey});if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async getRequest(id){let res=await this.repository.getRequest(id);if(!res.ok)return this.onRequestError(res.error);let view=mapRequestView(res.value);return view===null?err(internal()):(this.observeRequest(view),ok(view))}async listRequests(){let res=await this.repository.listRequests();if(!res.ok)return this.onRequestError(res.error);let views=mapRequestList(res.value);for(let view of views)this.observeRequest(view);return ok(views)}async readFeatures(){let read=this.repository.getFeatures;if(read===void 0)return this.features=RECORDS_FEATURES_PDF_ONLY;let features=RECORDS_FEATURES_PDF_ONLY;try{let res=await read.call(this.repository);res.ok&&(features=mapRecordsFeatures(res.value))}catch{}return this.features=features,features}async uploadDocument(input){let{requestId:requestId2,file:file}=input,rejection=validateFile(file,this.features.uploadContentTypes);if(rejection!==null)return this.telemetry.record("records.upload.rejected",{reason:rejection}),err(uploadFailed(`upload rejected: ${rejection}`));let initiated=await this.repository.initiateUpload(requestId2,{content_type:file.mimeType,file_size:file.sizeBytes});if(!initiated.ok)return this.onRequestError(initiated.error);let s3=await this.postToS3(initiated.value,file,input);if(!s3.ok)return this.telemetry.record("records.upload.failed",{reason:s3.reason}),err(uploadFailed(s3.reason));let completed=await this.repository.completeUpload(requestId2,{upload_id:initiated.value.upload_id});if(!completed.ok)return completed.error.code==="mediaUploadFailed"&&this.telemetry.record("records.upload.rejected",{reason:reasonFromWire(completed.error)??"corrupt"}),this.onRequestError(completed.error);let doc=mapUploadedDocument(completed.value);return doc===null?err(internal()):ok(doc)}async postToS3(policy,file,input){let deadline=new AbortController,signal=mergeSignals(deadline.signal,input.signal),handle=this.timers.setTimeout(()=>deadline.abort(),this.uploadDeadlineMs);try{let opts={signal:signal};return input.onProgress&&(opts.onProgress=input.onProgress),await this.uploads.postMultipart(policy,file,opts),{ok:!0}}catch{return{ok:false,reason:deadline.signal.aborted&&input.signal?.aborted!==true?"timeout":"upload_error"}}finally{this.timers.clearTimeout(handle)}}async getRecord(pet){let epoch=this.consentEpoch.get(pet)??0,res=await this.repository.getRecord(pet);if(epoch!==(this.consentEpoch.get(pet)??0))return err(/* @__PURE__ */Object.freeze({...makeEverfurError("accessDenied",{retryable:false}),recordsReason:"consent_required"}));if(!res.ok){let reason=recordsDenialReasonOf(res.error);return reason==="consent_required"?(this.recordCache.delete(pet),this.telemetry.record("records.consent.denied",{pet_ref:pet})):reason==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:pet}),err(res.error)}let view=mapRecordView(pet,res.value);return view.petRef!==pet?err(internal()):view.withheld?(this.telemetry.record("records.redaction.withheld",{pet_ref:pet}),this.recordCache.delete(pet),ok(view)):(this.recordCache.set(pet,view),ok(view))}peekCachedRecord(pet){return this.recordCache.get(pet)??null}async getConsent(pet){let res=await this.repository.getConsent(pet);return res.ok?ok(mapConsent(pet,res.value)):err(res.error)}async grantConsent(input){let res=await this.repository.putConsent(input.petRef,{consent_version:input.consentVersion,idempotency_key:input.idempotencyKey});return res.ok?ok(mapConsent(input.petRef,res.value)):(recordsDenialReasonOf(res.error)==="entitlement"&&this.telemetry.record("records.capability.denied",{pet_ref:input.petRef}),err(res.error))}async revokeConsent(pet){let res=await this.repository.deleteConsent(pet);return res.ok?(this.consentEpoch.set(pet,(this.consentEpoch.get(pet)??0)+1),this.recordCache.delete(pet),ok(mapConsent(pet,res.value))):err(res.error)}reportCapabilityDenied(pet){this.telemetry.record("records.capability.denied",pet?{pet_ref:pet}:{})}observeRequest(view){view.reviewStartedAt!==null&&!this.reportedGaps.has(view.id)&&(this.reportedGaps.add(view.id),this.telemetry.record("records.parse.gap",{request_id:view.id}))}onRequestError(error){return recordsDenialReasonOf(error)==="entitlement"&&this.telemetry.record("records.capability.denied",{}),err(error)}};function validateFile(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported_format";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"oversize":null}function reasonFromWire(error){let raw=error.wireMessage;return raw==="unsupported_format"||raw==="oversize"||raw==="corrupt"?raw:null}function uploadFailed(wireMessage){return makeEverfurError("mediaUploadFailed",{retryable:false,wireMessage:wireMessage})}function internal(){return makeEverfurError("internalError",{retryable:true})}var defaultTimers={setTimeout:(handler,ms2)=>setTimeout(handler,ms2),clearTimeout:handle=>clearTimeout(handle)};function mergeSignals(a,b){if(!b)return a;let ctrl=new AbortController;if(a.aborted||b.aborted)return ctrl.abort(),ctrl.signal;let onAbort=()=>ctrl.abort();return a.addEventListener("abort",onAbort,{once:true}),b.addEventListener("abort",onAbort,{once:true}),ctrl.signal}function defaultIdempotencyFactory(){let counter=0;return()=>`records-${Date.now().toString(36)}-${(counter++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function assertNever(x){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(x)}`)}function errorFrame(fields){/* @__PURE__ */
|
|
105
|
-
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var SDK_VERSION="0.
|
|
106
|
+
return Object.freeze({kind:"error",terminal:true,code:fields.code,retryable:fields.retryable,wireMessage:fields.wireMessage,synthesized:fields.synthesized,lastEventId:fields.lastEventId,serverRequestId:null})}function mintFailedError(cause,refusal){let message=cause instanceof Error?cause.message:typeof cause=="string"?cause:null;return makeEverfurError("authRejected",{retryable:false,...refusal?.wireCode?{wireCode:refusal.wireCode}:{},...refusal?.requestId?{requestId:refusal.requestId}:{},...message?{wireMessage:message}:{},...cause!=null?{raw:cause}:{}})}function authHeaders(auth){let headers={};return auth.mode==="personalized"?headers.authorization=`Bearer ${auth.token}`:headers["x-everfur-partner-key"]=auth.publishableKey,auth.userRef&&(headers["x-everfur-user-ref"]=auth.userRef),auth.sessionId&&(headers["x-everfur-session-id"]=auth.sessionId),headers}function withAuthHeaders(req,auth){return{...req,headers:{...stripAuthHeaders(req.headers),...authHeaders(auth)}}}function stripAuthHeaders(headers){if(!headers)return{};let out={};for(let[key,value]of Object.entries(headers)){let lower=key.toLowerCase();lower==="authorization"||lower==="x-everfur-partner-key"||(out[key]=value)}return out}async function authedSend(req,ctx){if(ctx.mode==="anonymous")return ctx.transport.request(withAuthHeaders(req,{mode:"anonymous",publishableKey:ctx.publishableKey,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));let token;try{token=await ctx.identity.currentToken()}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause))}let first=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:token,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));if(first.ok||first.error.httpStatus!==401)return first;let refreshed;try{refreshed=await ctx.identity.currentToken({forceRefresh:!0})}catch(cause){return ctx.identity.reportRejected?.(),err(mintFailedError(cause,{wireCode:wireCodeOf(first.error.raw),requestId:first.error.requestId}))}let retry=await ctx.transport.request(withAuthHeaders(req,{mode:"personalized",token:refreshed,userRef:ctx.userRef,...ctx.sessionId?{sessionId:ctx.sessionId}:{}}));return!retry.ok&&retry.error.httpStatus===401?(ctx.identity.reportRejected?.(),err(refusedAfterRemintError(retry.error))):retry}function refusedAfterRemintError(refusal){let raw=refusal.raw,wireCode=wireCodeOf(raw);return makeEverfurError("authRejected",{retryable:false,...refusal.httpStatus!==void 0?{httpStatus:refusal.httpStatus}:{},...refusal.requestId?{requestId:refusal.requestId}:{},...wireCode?{wireCode:wireCode}:{},...refusal.reasonCode?{reasonCode:refusal.reasonCode}:{},...refusal.wireMessage?{wireMessage:refusal.wireMessage}:{},...raw!=null?{raw:raw}:{}})}function wireCodeOf(body){if(typeof body!="object"||body===null)return null;let b=body,code=(typeof b.error=="object"&&b.error!==null?b.error.code:void 0)??b.code;return typeof code=="string"&&code.length>0?code:null}var SDK_VERSION="0.16.0";function networkError(cause){return makeEverfurError("internalError",{retryable:true,wireMessage:describeCause(cause)})}function describeCause(cause){return cause instanceof Error?cause.message:typeof cause=="string"?cause:"network request failed"}var FUNNEL_UNARY_TIMEOUT_MS=3e4,RETRY_OVERRIDE_MAX_MS=BACKOFF_CAP_MS*2,IDEMPOTENCY_HEADER="idempotency-key",MUTATING_METHODS=/* @__PURE__ */new Set(["POST","PUT","PATCH","DELETE"]),NOOP_OBSERVER=/* @__PURE__ */Object.freeze({onEvent(){}}),defaultFunnelTimers=/* @__PURE__ */Object.freeze({setTimeout:(handler,ms2)=>setTimeout(handler,ms2),clearTimeout:handle=>clearTimeout(handle),now:()=>Date.now()});function seededIdempotencyKey(seed){let safe=seed.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return safe.length===0?null:`efs_${safe}`.slice(0,128)}function createRequestFunnel(deps){let observer=deps.observer??NOOP_OBSERVER,timers=deps.timers??defaultFunnelTimers,rng=deps.rng??Math.random,sleep=deps.sleep??((ms2,signal)=>delayAbortable(ms2,timers,signal)),ceiling=deps.maxAttempts??MAX_RETRY_ATTEMPTS,timeoutMs=deps.unaryTimeoutMs??FUNNEL_UNARY_TIMEOUT_MS,mintKey=deps.newIdempotencyKey??defaultIdempotencyKeyFactory(),emit=event=>{try{observer.onEvent(event)}catch{}};async function send(call,req,opts){let perCallMaxAttempts=opts?.maxAttempts,maxAttempts=Math.max(1,perCallMaxAttempts??ceiling),idempotent=opts?.idempotent??MUTATING_METHODS.has(req.method),seeded=opts?.idempotencyKey===void 0?null:seededIdempotencyKey(opts.idempotencyKey),idempotencyKey=idempotent?seeded??mintKey():null,base2=assembleHeaders(req,idempotencyKey),attempt=0;for(;;){let stamp2=extra=>/* @__PURE__ */Object.freeze({call:call,method:req.method,path:req.path,attempt:attempt,...idempotencyKey?{idempotencyKey:idempotencyKey}:{},...extra});emit(stamp2({phase:"attempt"}));let deadline=boundedSignal(timeoutMs,timers),merged=mergeSignals2(deadline.signal,req.signal),settled;try{settled=await authedSend({...base2,signal:merged.signal},deps.auth)}catch(cause){settled=err(networkError(cause))}finally{merged.dispose(),deadline.cancel()}if(settled.ok)return emit(stamp2({phase:"settled",ok:true,reason:"ok"})),settled;let error=settled.error,decision=decideRetry(error,attempt,{maxAttempts:maxAttempts,rng:rng,now:timers.now(),aborted:req.signal?.aborted===true,...perCallMaxAttempts!==void 0?{perCallMaxAttempts:perCallMaxAttempts}:{},...deps.errorPolicy!==void 0?{policy:deps.errorPolicy}:{}}),settledEvent={ok:false,code:error.code,reason:decision.reason,...error.httpStatus!==void 0?{httpStatus:error.httpStatus}:{},...error.requestId!==void 0?{requestId:error.requestId}:{}};if(!decision.retry)return emit(stamp2({phase:"settled",...settledEvent})),err(error);if(emit(stamp2({phase:"retry",...settledEvent,delayMs:decision.delayMs})),await sleep(decision.delayMs,req.signal),req.signal?.aborted===true)return emit(stamp2({phase:"settled",...settledEvent,reason:"aborted"})),err(error);attempt+=1}}async function authorize(req){return withAuthHeaders(req,await resolveDeviceAuth(deps.auth))}async function*stream(call,req,signal){emit(
|
|
106
107
|
/* @__PURE__ */Object.freeze({call:call,phase:"stream.open",method:req.method,path:req.path,attempt:0}));try{yield*deps.auth.transport.stream(req,signal)}catch{yield errorFrame({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}}/* @__PURE__ */
|
|
107
108
|
return Object.freeze({send:send,authorize:authorize,stream:stream})}function assembleHeaders(req,idempotencyKey){let headers={};for(let[key,value]of Object.entries(req.headers??{}))key.toLowerCase()!==IDEMPOTENCY_HEADER&&(headers[key]=value);return idempotencyKey!==null&&(headers["Idempotency-Key"]=idempotencyKey),{...req,headers:headers}}function defaultIdempotencyKeyFactory(){let counter=0;return()=>`efk_${Date.now().toString(36)}_${(counter++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}var POLICY_MAX_ATTEMPTS_CAP=10;function decideRetry(error,attempt,ctx){if(ctx.aborted)return{retry:false,reason:"aborted"};let throttle=throttleKind(error);if(throttle==="quota")return{retry:false,reason:"daily-quota-exhausted"};if(throttle!=="burst"&&!isAutoRetryable(error.code))return{retry:false,reason:"terminal-code"};let reason=throttle==="burst"?"burst-throttle":"retryable-code";if((()=>{if(ctx.policy===void 0)return false;try{return!ctx.policy.shouldRetry(error.code,attempt)}catch{return false}})())return{retry:false,reason:"terminal-code"};let policyCeiling=()=>{if(ctx.policy===void 0)return null;let raw;try{raw=ctx.policy.maxAttempts(error.code)}catch{return null}return typeof raw!="number"||!Number.isFinite(raw)?null:Math.max(1,Math.min(POLICY_MAX_ATTEMPTS_CAP,Math.floor(raw)))},ceiling=ctx.perCallMaxAttempts??policyCeiling()??ctx.maxAttempts;if(attempt+1>=ceiling)return{retry:false,reason:"attempts-exhausted"};let override=retryOverrideMs(error,ctx.now);return override!==null?override>RETRY_OVERRIDE_MAX_MS?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:reason,delayMs:override}:{retry:true,reason:reason,delayMs:backoffDelayMs(attempt,ctx.rng)}}function throttleKind(error){let code=error.code==="unknown"?fromWire(rawWireCode(error.raw)):error.code;return code==="quotaExceeded"?"quota":code==="rateLimited"||error.httpStatus===429?"burst":null}function retryOverrideMs(error,now){let at=findResetsAt(error.raw);if(at!==null){let delta=at-now;return delta>0?delta:0}let wait=findRetryAfterSeconds(error.raw);return wait===null?null:Math.round(wait*1e3)}function findRetryAfterSeconds(raw){for(let scope of candidateScopes(raw)){let value=scope.retry_after_seconds;if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return value}return null}function findResetsAt(raw){for(let scope of candidateScopes(raw)){let value=scope.resets_at,parsed=parseInstantMs(value);if(parsed!==null)return parsed}return null}function candidateScopes(raw){if(!isRecord(raw))return[];let out=[raw];for(let nested of["error","detail"]){let value=raw[nested];isRecord(value)&&out.push(value)}return out}function parseInstantMs(value){if(typeof value=="number"&&Number.isFinite(value))return value<1e11?Math.round(value*1e3):Math.round(value);if(typeof value=="string"&&value.trim().length>0){let parsed=Date.parse(value);return Number.isFinite(parsed)?parsed:null}return null}function rawWireCode(raw){for(let scope of candidateScopes(raw)){let code=scope.code;if(typeof code=="string"&&code.length>0)return code}return null}function isRecord(value){return typeof value=="object"&&value!==null}async function resolveDeviceAuth(auth){return auth.mode==="anonymous"?{mode:"anonymous",publishableKey:auth.publishableKey,userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}:{mode:"personalized",token:await auth.identity.currentToken(),userRef:auth.userRef,...auth.sessionId?{sessionId:auth.sessionId}:{}}}function boundedSignal(ms2,timers){let ctrl=new AbortController,handle=timers.setTimeout(()=>ctrl.abort(),ms2);return{signal:ctrl.signal,cancel:()=>timers.clearTimeout(handle)}}function mergeSignals2(deadline,caller){let noop=()=>{};if(!caller)return{signal:deadline,dispose:noop};let ctrl=new AbortController;if(deadline.aborted||caller.aborted)return ctrl.abort(),{signal:ctrl.signal,dispose:noop};let onAbort=()=>ctrl.abort();return deadline.addEventListener("abort",onAbort,{once:true}),caller.addEventListener("abort",onAbort,{once:true}),{signal:ctrl.signal,dispose:()=>{deadline.removeEventListener("abort",onAbort),caller.removeEventListener("abort",onAbort)}}}function delayAbortable(ms2,timers,signal){return ms2<=0||signal?.aborted===true?Promise.resolve():new Promise(resolve=>{let handle=timers.setTimeout(()=>{signal?.removeEventListener("abort",onAbort),resolve()},ms2),onAbort=()=>{timers.clearTimeout(handle),resolve()};signal?.addEventListener("abort",onAbort,{once:true})})}function hasLoneSurrogate(value){for(let i=0;i<value.length;i+=1){let code=value.charCodeAt(i);if(code>=55296&&code<=56319){let low=value.charCodeAt(i+1);if(!(low>=56320&&low<=57343))return true;i+=1}else if(code>=56320&&code<=57343)return true}return false}function serverLength(value){return[...value].length}function isNotFoundError(error){return error!=null&&(error.httpStatus===404||error.category==="notFound")}function plainNotFound(error){return error.code!=="conversationNotFound"?error:makeEverfurError("resourceNotFound",{retryable:false,...error.httpStatus===void 0?{}:{httpStatus:error.httpStatus},...error.requestId===void 0?{}:{requestId:error.requestId},...error.reasonCode===void 0?{}:{reasonCode:error.reasonCode},...error.wireMessage===void 0?{}:{wireMessage:error.wireMessage},...error.raw===void 0?{}:{raw:error.raw}})}function plainResult(res){return res.ok?res:err(plainNotFound(res.error))}function withPlainNotFound(funnel){return{send:async(...args)=>plainResult(await funnel.send(...args)),authorize:req=>funnel.authorize(req),stream:(call,req,signal)=>funnel.stream(call,req,signal)}}var BASE="/widget/v1/records";function createHttpRecordsRepository(deps){let{auth:auth}=deps,mode=auth.mode,funnel=deps.funnel??createRequestFunnel({auth:auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=async(call,req,kind)=>{let res=await funnel.send(call,req);return res.ok?res:err(tagReason(plainNotFound(res.error),mode,kind))},segmentError=(field,value)=>typeof value!="string"||value.length===0?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is required and must be a non-empty string`}):hasLoneSurrogate(value)?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} contains an unpaired surrogate and cannot be encoded`}):null,boundsError=(field,value,max)=>{let unusable=segmentError(field,value);if(unusable!==null)return unusable;let length=[...value].length;return length>max?makeEverfurError("validationFailed",{retryable:false,wireMessage:`${field} is ${length} characters; the server accepts at most ${max}`}):null},firstError=(...checks)=>checks.find(c=>c!==null)??null;return{createRequest:body=>{let invalid5=firstError(boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",body.pet_ref,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.createRequest",post(`${BASE}/requests`,body),"request")},initiateUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.initiateUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/initiate`,body),"request")},completeUpload:(requestId2,body)=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.completeUpload",post(`${BASE}/requests/${encodeURIComponent(requestId2)}/uploads/complete`,body),"request")},getRequest:requestId2=>{let invalid5=segmentError("request_id",requestId2);return invalid5?Promise.resolve(err(invalid5)):send("records.getRequest",get(`${BASE}/requests/${encodeURIComponent(requestId2)}`),"request")},listRequests:async()=>{let res=await send("records.listRequests",get(`${BASE}/requests`),"request");if(!res.ok)return res;let value=res.value;return{ok:true,value:Array.isArray(value)?value:value.items??[]}},getRecord:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getRecord",get(`${BASE}/pets/${encodeURIComponent(petRef)}/record`),"content")},getConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.getConsent",get(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")},putConsent:(petRef,body)=>{let invalid5=firstError(boundsError("consent_version",body.consent_version,CONSENT_VERSION_MAX),boundsError("idempotency_key",body.idempotency_key,IDEMPOTENCY_KEY_MAX),boundsError("pet_ref",petRef,PET_REF_MAX));return invalid5?Promise.resolve(err(invalid5)):send("records.putConsent",put(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`,body),"consent")},getFeatures:()=>send("records.getFeatures",get(`${BASE}/features`),"request"),deleteConsent:petRef=>{let invalid5=boundsError("pet_ref",petRef,PET_REF_MAX);return invalid5?Promise.resolve(err(invalid5)):send("records.deleteConsent",del(`${BASE}/pets/${encodeURIComponent(petRef)}/consent`),"consent")}}}function withReason(error,reason){let tagged={...error,recordsReason:reason};for(let key of["wireMessage","raw"]){let descriptor=Object.getOwnPropertyDescriptor(error,key);descriptor!==void 0&&Object.defineProperty(tagged,key,descriptor)}/* @__PURE__ */
|
|
108
|
-
return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=react.useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return react.useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=react.useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=react.useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=react.useRef(scope),[binding,setBinding]=react.useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=react.useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=react.useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=react.useRef(0);react.useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),react.useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=react.useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;react.useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=react.useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=react.useRef(0),polledIdRef=react.useRef(null),[pollEpoch,rearmPolls]=react.useReducer(n2=>n2+1,0);react.useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=react.useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=react.useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=react.useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=react.useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=react.useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&¬ifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=react.useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return react.useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
|
|
109
|
+
return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";function recordsErrorReasonFor(error){return error.httpStatus!==404?null:error.reasonCode===PET_NOT_REGISTERED?"pet_not_found":"entitlement"}function tagReason(error,mode,kind){let notFound=recordsErrorReasonFor(error);return notFound!==null?withReason(error,notFound):error.code!=="accessDenied"?error:withReason(error,mode==="anonymous"?"session_required":kind==="content"?"consent_required":"entitlement")}function get(path){return{method:"GET",path:path}}function post(path,body){return{method:"POST",path:path,body:body}}function put(path,body){return{method:"PUT",path:path,body:body}}function del(path){return{method:"DELETE",path:path}}var EVERFUR_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurContext@v1"),globalContextHost=globalThis,EverfurContext=globalContextHost[EVERFUR_CONTEXT_SYMBOL]??(globalContextHost[EVERFUR_CONTEXT_SYMBOL]=react.createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=react.useContext(EverfurContext);if(ctx===null)throw new EverfurConfigError("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return ctx}var epochs=/* @__PURE__ */new Map,listeners=/* @__PURE__ */new Set;function notifyRecordsConsentWithdrawn(petRef){epochs.set(petRef,(epochs.get(petRef)??0)+1);for(let listener of[...listeners])listener()}function recordsConsentEpochOf(petRef){return epochs.get(petRef)??0}function subscribe(onStoreChange){return listeners.add(onStoreChange),()=>{listeners.delete(onStoreChange)}}function useRecordsConsentEpoch(petRef){let snapshot=react.useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return react.useSyncExternalStore(subscribe,snapshot,snapshot)}var INITIAL={record:null,requests:[],consent:null,error:null,denialReason:null,withheld:false,loading:true,isUploading:false,uploadProgress:null,uploadQueue:[],uploadContentTypes:RECORDS_FEATURES_PDF_ONLY.uploadContentTypes},POLL_INTERVAL_MS=4e3,MAX_POLLS=30;function useEverfurRecords(opts){let{petRef:petRef}=opts,ownTransport=react.useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=react.useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=react.useRef(scope),[binding,setBinding]=react.useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=react.useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=react.useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=react.useRef(0);react.useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),react.useEffect(()=>{if(opts.controller)return;let{services:services}=runtime.registry,telemetry={record:(event,props)=>services.telemetry.track(event,props)},acquired=runtime.registry.acquire("records",`${userRef??""}|${petRef}${hasOwnTransport?"|own-upload":""}`,()=>createRecordsController({repository:createHttpRecordsRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}),uploads:hasOwnTransport?{postMultipart:(policy,file,o)=>(ownTransport.current??services.uploadTransport).postMultipart(policy,file,o)}:services.uploadTransport,telemetry:telemetry}),()=>{});return setBinding({scope:scope,controller:acquired}),()=>{runtime.registry.release(acquired)}},[runtime,userRef,petRef,opts.controller,scopeEpoch,scope,hasOwnTransport]);let patch=react.useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return;let gen=generation.current+=1;pollsRef.current=0,rearmPolls(),patch({loading:true,error:null,denialReason:null,withheld:false});let[consentRes,listRes]=await Promise.all([controller.getConsent(petRef),controller.listRequests()]);if(gen!==generation.current)return;let consent=consentRes.ok?consentRes.value:null,requests=listRes.ok?listRes.value.filter(request=>request.petRef===petRef):[],listError=listRes.ok?null:listRes.error;if(consent&&consent.granted){let recordRes=await controller.getRecord(petRef);if(gen!==generation.current)return;if(recordRes.ok){patch({consent:consent,requests:requests,record:recordRes.value,withheld:recordRes.value.withheld,error:recordRes.value.withheld?withheldSentinel():listError,denialReason:null,loading:false});return}patch({consent:consent,requests:requests,record:null,error:recordRes.error,denialReason:recordsDenialReasonOf(recordRes.error),withheld:false,loading:false});return}patch({consent:consent,requests:requests,record:null,error:consentRes.ok?listError:consentRes.error,denialReason:consent?"consent_required":consentDenial(consentRes),withheld:false,loading:false})},[controller,petRef,patch,scope]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;react.useEffect(()=>{if(!readUploadFeatures||!controller?.readFeatures)return;let live=true;return controller.readFeatures().then(features=>{live&&activeScope.current===scope&&patch({uploadContentTypes:features.uploadContentTypes})}),()=>{live=false}},[controller,readUploadFeatures,patch,scope]);let activeRequest=react.useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=react.useRef(0),polledIdRef=react.useRef(null),[pollEpoch,rearmPolls]=react.useReducer(n2=>n2+1,0);react.useEffect(()=>{if(!controller||activeId===null||activeStatus===null||isTerminalStatus(activeStatus)||activeStatus==="in_review")return;polledIdRef.current!==String(activeId)&&(polledIdRef.current=String(activeId),pollsRef.current=0);let cancelled=false,tick=async()=>{if(cancelled||pollsRef.current>=MAX_POLLS)return;pollsRef.current+=1;let res=await controller.getRequest(activeId);if(!cancelled){if(res.ok&&res.value.petRef===petRef){if(setSnap(current=>({...current,requests:replaceRequest(current.requests,res.value)})),isTerminalStatus(res.value.status)){res.value.status==="published"&&load();return}if(res.value.status==="in_review")return}handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS)}},handle=setTimeout(()=>{tick()},POLL_INTERVAL_MS);return()=>{cancelled=true,clearTimeout(handle)}},[controller,activeId,activeStatus,load,pollEpoch,petRef,setSnap]);let createRequest=react.useCallback(async idempotencyKey=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.createUploadRequest({petRef:petRef,idempotencyKey:idempotencyKey});return activeScope.current===scope&&res.ok&&res.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,res.value)})),res},[controller,petRef,scope,setSnap]),patchItem=react.useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=react.useCallback(async(requestId2,files)=>{let batch=Date.now().toString(36),queue=files.map((file,index)=>{let skipReason=skipReasonFor(file,snap.uploadContentTypes);return{key:`${batch}-${index}`,name:file.name??null,status:skipReason===null?"queued":"skipped",progress:0,skipReason:skipReason,error:null}}),settled=[...queue];if(!controller||activeScope.current!==scope)/* @__PURE__ */return Object.freeze(settled);setSnap(c=>({...c,uploadQueue:queue,isUploading:true,uploadProgress:0}));for(let[index,file]of files.entries()){let item=queue[index];if(item.status==="skipped")continue;if(activeScope.current!==scope)break;patchItem(item.key,current=>({...current,status:"uploading",progress:0})),patch({uploadProgress:0});let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{if(activeScope.current!==scope)return;let bounded=Math.min(1,Math.max(0,fraction));patchItem(item.key,current=>({...current,progress:Math.max(current.progress,bounded)})),patch({uploadProgress:bounded})}});if(activeScope.current!==scope)break;let next=res.ok?{...item,status:"done",progress:1}:{...item,status:"failed",error:res.error};if(settled[index]=next,patchItem(item.key,()=>next),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}}return activeScope.current===scope&&patch({isUploading:false,uploadProgress:null}),/* @__PURE__ */Object.freeze(settled)},[controller,patch,patchItem,petRef,scope,setSnap,snap.uploadContentTypes]),uploadDocument=react.useCallback(async(requestId2,file)=>{if(!controller||activeScope.current!==scope)return notReady();let key=`${Date.now().toString(36)}-0`;setSnap(c=>({...c,isUploading:true,uploadProgress:0,uploadQueue:[{key:key,name:file.name??null,status:"uploading",progress:0,skipReason:null,error:null}]}));let res=await controller.uploadDocument({requestId:requestId2,file:file,onProgress:fraction=>{activeScope.current===scope&&(patch({uploadProgress:fraction}),patchItem(key,current=>({...current,progress:Math.max(current.progress,Math.min(1,fraction))})))}});if(activeScope.current!==scope)return res;if(patch({isUploading:false,uploadProgress:null}),patchItem(key,current=>res.ok?{...current,status:"done",progress:1}:{...current,status:"failed",error:res.error}),res.ok){let refreshed=await controller.getRequest(requestId2);activeScope.current===scope&&refreshed.ok&&refreshed.value.petRef===petRef&&setSnap(c=>({...c,requests:replaceRequest(c.requests,refreshed.value)}))}return res},[controller,patch,patchItem,petRef,scope,setSnap]),grantConsent=react.useCallback(async(consentVersion,idempotencyKey)=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.grantConsent({petRef:petRef,consentVersion:consentVersion,idempotencyKey:idempotencyKey});return res.ok&&activeScope.current===scope&&load(),res},[controller,petRef,load,scope]),revokeConsent=react.useCallback(async()=>{if(!controller||activeScope.current!==scope)return notReady();let res=await controller.revokeConsent(petRef);return res.ok&¬ifyRecordsConsentWithdrawn(petRef),res.ok&&activeScope.current===scope&&(generation.current+=1,patch({record:null,withheld:false,loading:false,denialReason:"consent_required",consent:res.value})),res},[controller,petRef,patch,scope]),refresh=react.useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return react.useMemo(()=>({status:status,record:snap.record,requests:snap.requests,activeRequest:activeRequest,consent:snap.consent,error:snap.error,denialReason:snap.denialReason,withheld:snap.withheld,isUploading:snap.isUploading,uploadProgress:snap.uploadProgress,uploadQueue:snap.uploadQueue,uploadContentTypes:snap.uploadContentTypes,createRequest:createRequest,uploadDocument:uploadDocument,uploadDocuments:uploadDocuments,grantConsent:grantConsent,revokeConsent:revokeConsent,refresh:refresh}),[status,snap,activeRequest,createRequest,uploadDocument,uploadDocuments,grantConsent,revokeConsent,refresh])}function skipReasonFor(file,types){if(!isAcceptedUploadType(file.mimeType,types))return"unsupported";let size=file.sizeBytes;return typeof size!="number"||!Number.isFinite(size)||size<=0||size>MAX_UPLOAD_BYTES?"too_large":null}function classifyPick(files,types){let uploadable=[],skipped=[];for(let file of files){let reason=skipReasonFor(file,types);reason===null?uploadable.push(file):skipped.push({name:file.name??null,reason:reason})}return{uploadable:uploadable,skipped:skipped}}function selectStatus(snap,hasController){return snap.loading||!hasController?"loading":snap.withheld||snap.denialReason!==null||snap.error!==null?"error":snap.record!==null&&!snap.record.isEmpty||snap.requests.length>0?"populated":"empty"}function newestRequest(requests){if(requests.length===0)return null;let newest=requests[0];for(let r of requests)r.updatedAt>newest.updatedAt&&(newest=r);return newest}function replaceRequest(requests,next){let filtered=requests.filter(r=>r.id!==next.id);return[next,...filtered]}function consentDenial(res){return res.ok?"consent_required":recordsDenialReasonOf(res.error)??"consent_required"}function withheldSentinel(){return makeEverfurError("internalError",{retryable:false})}function notReady(){return{ok:false,error:makeEverfurError("internalError",{retryable:true})}}function definedProps(props){let out={};if(props==null)return out;for(let key of Object.keys(props))props[key]!==void 0&&(out[key]=props[key]);return out}function reportHostFailure(error){let globalConsole=globalThis.console;try{globalConsole?.error?.("[everfur] A host callback threw; the SDK ignored it.",error)}catch{}}function isThenable(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function callHost(fn,...args){if(typeof fn=="function")try{let result=fn(...args);return isThenable(result)&&Promise.resolve(result).then(void 0,reportHostFailure),result}catch(error){reportHostFailure(error);return}}var GUARDED=/* @__PURE__ */new WeakMap;function guardHost(fn){if(typeof fn!="function")return;let cached=GUARDED.get(fn);if(cached!==void 0)return cached;let guarded=(...args)=>{callHost(fn,...args)};return GUARDED.set(fn,guarded),guarded}function guardHostProps(props,names){let guarded=null;for(let name of names){let fn=props[name];typeof fn=="function"&&(guarded??={...props},guarded[name]=guardHost(fn))}return guarded??props}function callHostAsync(fn,...args){let started;try{started=fn(...args)}catch(error){return reportHostFailure(error),Promise.resolve({ok:false,error:error})}return Promise.resolve(started).then(value=>({ok:true,value:value}),error=>({ok:false,error:error}))}var RECORDS_DASHBOARD=/* @__PURE__ */Object.freeze({name:"dashboard"});function initialRecordsNav(initial=RECORDS_DASHBOARD){/* @__PURE__ */
|
|
109
110
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([initial])})}function currentRecordsScreen(state){return state.stack[state.stack.length-1]??RECORDS_DASHBOARD}function pushRecordsNav(state,screen){/* @__PURE__ */
|
|
110
111
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
111
|
-
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange2,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange2} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label=>`Status: ${label}`,latestA11y:(reading,status,date2)=>`Latest reading ${reading}, ${status}, collected ${date2}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n2=>n2+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
|
|
112
|
+
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack.slice(0,-1),screen])})}function resetRecordsNav(screen){return initialRecordsNav(screen)}function popRecordsNav(state){return state.stack.length<=1?{state:state,handled:false}:{state:/* @__PURE__ */Object.freeze({stack:/* @__PURE__ */Object.freeze(state.stack.slice(0,-1))}),handled:true}}function transitionRecordsNav(state,to){return to.name==="dashboard"?resetRecordsNav(to):currentRecordsScreen(state).name==="upload"&&to.name==="request"?replaceRecordsNav(state,to):pushRecordsNav(state,to)}function recordsNavReducer(state,action){switch(action.type){case"push":return pushRecordsNav(state,action.screen);case"pop":return popRecordsNav(state).state;case"replace":return replaceRecordsNav(state,action.screen);case"reset":return resetRecordsNav(action.screen);case"navigate":return transitionRecordsNav(state,action.screen);default:return state}}var freezeInPlace=Object.freeze;function deepFreeze(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){freezeInPlace(value);for(let key of Object.keys(value))deepFreeze(value[key])}return value}var TEXT_SCALE_TIER_CAPS=/* @__PURE__ */Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),SPACE={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},RADIUS={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},TYPE_SIZE={nano:8,small:9,micro:10,tiny:11,caption:13,bodyTight:15,body:17,subtitle:20,heading:22,verdict:24},LINE_HEIGHT={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},WEIGHT={regular:"400",medium:"500",bold:"700"},LETTER_SPACING={eyebrow:1,monoWide:.9,headerBrand:-.42,tight:-.35},DEFAULT_MAX_FONT_SCALE=0,SYSTEM_FONT_FAMILY="System",SYSTEM_MONO_FAMILY="monospace",TIERS=["content","heading","control","compact","badge"];function authoredTierSizes(size){let out={};for(let tier of TIERS)out[tier]=size;return out}var NO_FONT_SOURCES=[];function baseType(){return{family:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,fontUrl:null,families:{regular:SYSTEM_FONT_FAMILY,medium:SYSTEM_FONT_FAMILY,bold:SYSTEM_FONT_FAMILY,mono:SYSTEM_MONO_FAMILY,monoMedium:SYSTEM_MONO_FAMILY,monoBold:SYSTEM_MONO_FAMILY},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:TYPE_SIZE,tierSizes:authoredTierSizes(TYPE_SIZE),lineHeight:LINE_HEIGHT,weight:WEIGHT,letterSpacing:LETTER_SPACING,scale:1,maxScale:DEFAULT_MAX_FONT_SCALE,scaleCaps:TEXT_SCALE_TIER_CAPS,headingFamily:null,headingWeight:null,fontSources:NO_FONT_SOURCES}}var NO_SLOTS={},EASING_CURVES=/* @__PURE__ */Object.freeze({standard:/* @__PURE__ */Object.freeze([.2,0,0,1]),emphasized:/* @__PURE__ */Object.freeze([.2,.8,.2,1]),exit:/* @__PURE__ */Object.freeze([.4,0,1,1])});function cssCubicBezier(curve){return`cubic-bezier(${curve.join(", ")})`}var MOTION={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:cssCubicBezier(EASING_CURVES.standard),emphasized:cssCubicBezier(EASING_CURVES.emphasized),exit:cssCubicBezier(EASING_CURVES.exit)},reducedMotion:false},LIGHT_COLOR={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FFFFFF",surfaceSubtle:"#F1F5F2",background:"#FFFFFF",borderRingCream:"#E4E4E4",chatGround:"#FFFFFF",composerFill:"#FFFFFF",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#000000",secondary:"#0E462E",muted:"#6B6B6B",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#C03410",onDanger:"#FFFFFF",errorRed:"#C03410",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(192,52,16,0.06)",badgeBgNeutral:"rgba(107,107,107,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#E9F1E9",scanButtonPink:"#FFC3BC",highlight:"#FFC3BC",onHighlight:"#000000",mark:"#07C168",controlEdge:"rgba(16,70,46,0.18)",structureEdge:"rgba(16,70,46,0.25)",primaryEdge:"#10462E",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)",info:"#10462E",badgeBgInfo:"rgba(16,70,46,0.10)",infoEdge:"rgba(16,70,46,0.25)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:LIGHT_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS}),DARK_COLOR={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A9A9A",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",onDanger:"#0E1F17",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",bubbleVet:"#FFC3BC",onBubbleVet:"#000000",skeleton:"#23272C",scanButtonPink:"#FFC3BC",highlight:"#605051",onHighlight:"#F5F3F0",mark:"#07C168",controlEdge:"rgba(107,211,154,0.22)",structureEdge:"rgba(107,211,154,0.28)",primaryEdge:"#6BD39A",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)",info:"#6BD39A",badgeBgInfo:"rgba(107,211,154,0.12)",infoEdge:"rgba(107,211,154,0.28)"},EVERFUR_DARK=deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false,assistantAvatarUrl:null},color:DARK_COLOR,space:SPACE,radius:RADIUS,type:baseType(),motion:MOTION,slots:NO_SLOTS});var EVERFUR_THEME_CONTEXT_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),globalThemeHost=globalThis,EverfurThemeContext=globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]??(globalThemeHost[EVERFUR_THEME_CONTEXT_SYMBOL]=react.createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return react.useContext(EverfurThemeContext)}function tierMultiplier(type,tier){let cap=type.scaleCaps[tier];return cap>0?cap:void 0}function Text({tier:tier="content",...props}){let{type:type}=useEverfurTheme(),cap=tierMultiplier(type,tier);return react.createElement(reactNative.Text,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=react.forwardRef(function(props,ref){return react.createElement(reactNative.TextInput,{...props,...ref===null?{}:{ref:ref}})});function slotBox(slot,borderWidth){if(slot===void 0)return{};let out={};return slot.backgroundColor!==void 0&&(out.backgroundColor=slot.backgroundColor),slot.borderColor!==void 0&&(out.borderColor=slot.borderColor,out.borderWidth=borderWidth??1),slot.borderRadius!==void 0&&(out.borderRadius=slot.borderRadius),out}function slotText(slot){return slot?.textColor===void 0?{}:{color:slot.textColor}}function recordCardSlot(slots){return slots.recordCard??slots.card}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function face(theme,weight){let type=theme.type,fontFamily=type.families[weight];return weight==="mono"||type.namedFaces[weight]?{fontFamily:fontFamily}:{fontFamily:fontFamily,fontWeight:type.weight[FACE_WEIGHT[weight]]}}function headingFace(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type;if(headingFamily===null&&headingWeight===null)return face(theme,fallback);if(headingFamily!==null)return{fontFamily:headingFamily,fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]};let base2=face(theme,fallback);return base2.fontWeight===void 0||headingWeight===null?base2:{fontFamily:base2.fontFamily,fontWeight:headingWeight}}var CLINIC_REQUEST_COPY=/* @__PURE__ */Object.freeze({title:"Request records",clinic:"Clinic",search:"Search clinics by name or location",placeholder:"Clinic name, city, or ZIP",email:"Clinic email",emailPlaceholder:"records@clinic.com",ownerName:"Your full name",scopeHeading:"What you’re authorizing",send:"Send request",sending:"Sending…",cancel:"Cancel",sign:"Signature",draw:"Draw your signature",type:"Type your name to sign",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",clear:"Clear",drawHint:"Draw your signature in the box above.",clearA11y:"Clear signature",typedSignatureA11y:name=>`Typed signature: ${name}`,missingSignature:"Please add your signature before submitting.",recentlyUsed:"Recently used",moreClinics:"Load more"});var CLINIC_PICKER_COPY=/* @__PURE__ */Object.freeze({title:CLINIC_REQUEST_COPY.title,titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Request ${name}’s records`:CLINIC_REQUEST_COPY.title},leadWeb:"Find the clinic that has them. We send a secure request and read every page they send back.",leadNative:"Find the clinic that has them.",searchLabelWeb:"Find the clinic",howItWorks:"How it works",howSteps:petName=>[{title:"We send a secure request",body:"With your permission, straight to the clinic’s records team."},{title:"The clinic sends the file",body:"Most clinics respond within 3 to 5 business days. We follow up for you."},{title:"Everfur reads every page",body:`Visits, vaccines, labs and prescriptions land in ${petName}’s records.`}],placeholder:CLINIC_REQUEST_COPY.placeholder,searchA11y:CLINIC_REQUEST_COPY.search,clearSearch:"Clear search",loading:"Loading clinics",uploadOwn:"I already have the records",uploadOwnStarting:"Setting up your upload…",noPet:"Add a pet first, then come back to request their records.",recentlyUsed:CLINIC_REQUEST_COPY.recentlyUsed,noMatch:query=>`No clinics match “${query}”. You can still request records using the option above.`,loadingMore:"Loading more…",loadMoreFailed:"Couldn’t load more. Tap to retry.",selectA11y:summary=>`Request records from ${summary}`,resultsCount:count=>count===1?"Showing 1 clinic":`Showing ${String(count)} clinics`,fallback:/* @__PURE__ */Object.freeze({title:"Can’t find your clinic?",subtitle:"Add it by email and we’ll request your records.",nameLabel:"Clinic name",namePlaceholder:"Your clinic’s name",emailLabel:"Clinic email",emailPlaceholder:"records@clinic.com",reviewNote:"We review every request by hand before reaching out to the clinic.",submit:"Continue"})});function clinicEmailStatusBadge(status){switch(status){case"verified":return{label:"Email on file",a11y:"verified email on file, we can request records directly",tone:"positive"};case"unverified":return{label:"Email unconfirmed",a11y:"email on file but unconfirmed, we will try and let you know",tone:"caution"};default:return{label:"We may need your help",a11y:"no email on file, we may ask you to confirm how to reach this clinic",tone:"neutral"}}}var KM_PER_MILE=1.609344;function milesLabel(km){return km===null||!Number.isFinite(km)?null:(km/KM_PER_MILE).toFixed(1)}function formatClinicDistanceLabel(km){let miles=milesLabel(km);return miles===null?"":`${miles} mi`}function formatClinicDistanceForA11y(km){let miles=milesLabel(km);return miles===null?"":`${miles} ${miles==="1.0"?"mile":"miles"} away`}var CLINIC_SEARCH_DEBOUNCE_MS=300,CLINIC_SEARCH_MIN_CHARS=2;var RECORDS_COPY=/* @__PURE__ */Object.freeze({loading:"Loading",empty:"No records yet",upload:"Upload records",consentRequired:"Consent required",allow:"Allow",sessionRequired:"Sign in required",recordUnavailable:"Record unavailable",retry:"Try again",records:"Records",beingReviewed:"being reviewed"}),RECORDS_FOOTNOTE="Everfur summarizes what your vet recorded. It is informational, not diagnostic.";var NAMELESS_PET="your pet";function petNameOr(petName){let trimmed=petName?.trim()??"";return trimmed.length>0?trimmed:NAMELESS_PET}var DASHBOARD_COPY=/* @__PURE__ */Object.freeze({title:"Health records",titleWeb:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s Records`:"Health records"},titleNative:petName=>{let name=petName?.trim()??"";return name.length>0?name:"Health records"},openTimeline:"Open timeline",loading:"Loading health records",lead:petName=>`${petNameOr(petName)}’s lab trends`,retryMarkers:"Retry loading lab trends",viewFullRecord:"View full medical record",viewTimeline:"View full timeline",important:disclaimer=>`Important: ${disclaimer}`}),MARKER_SUMMARY_COPY=/* @__PURE__ */Object.freeze({title:"At a glance",marker:"Marker",markers:"Markers",outOfRange:"out of range",inRange:"in range",noRange:"NO RANGE",subtitle:"Summary of your pet’s biomarkers",ask:"Ask about these markers",a11y:(total,inRange,outOfRange2,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange2} out of range${unknown>0?`, ${unknown} without a range`:""}.`}),MARKER_CAROUSEL_COPY=/* @__PURE__ */Object.freeze({counter:(index,total)=>`${index+1} of ${total}`,a11y:(name,index,total)=>name!==null?`${name}, marker ${index+1} of ${total}. Swipe left or right to see more markers.`:`Marker ${index+1} of ${total}`}),MARKER_CARD_COPY=/* @__PURE__ */Object.freeze({tapHint:"Tap a point to see where it came from.",singleHint:"One reading so far: we’ll plot a trend as more come in.",empty:"No readings for this marker yet.",ask:"Ask about this marker",askNamed:name=>{let trimmed=name?.trim()??"";return trimmed.length>0?`Ask about ${trimmed}`:"Ask about this marker"},status:label2=>`Status: ${label2}`,latestA11y:(reading,status,date2)=>`Latest reading ${reading}, ${status}, collected ${date2}`,readingsA11y:name=>`${name} readings, oldest to newest`}),PROVENANCE_COPY=/* @__PURE__ */Object.freeze({title:"Where this comes from",close:"Close reading details",collected:"Collected",clinic:"Clinic",referenceRange:"Reference range",noRange:"Not on file for this reading",sourceDocument:"Source document",unverified:"Our team hasn’t verified this reading against the original document yet.",reviewed:"Reviewed by our team",ask:"Ask about this reading"}),IN_PROGRESS_COPY=/* @__PURE__ */Object.freeze({title:petName=>`${petNameOr(petName)}’s records are on the way`,anotherClinic:"Another clinic",anotherClinicSub:"Seen more than one vet? We ask each one.",uploadDocumentPhotoSub:"A PDF, or a photo of a paper record.",body:petName=>`We’re requesting ${petNameOr(petName)}’s records from your vet. This usually takes a few days; we’ll show lab trends here as soon as they arrive.`,a11y:petName=>`Records request in progress for ${petNameOr(petName)}.`,ask:"Ask about this request"}),REQUEST_PROMPT_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Add ${petNameOr(petName)}’s records`,firstRecordTitle:petName=>`Add ${petNameOr(petName)}’s first record`,body:"Records can come from more than one clinic over a lifetime.",requestFromClinic:"Request from a clinic",requestFromClinicSub:"We send a secure request and read every page they send back.",uploadDocument:"Upload a document"});function isRecordsInProgress(request){return!isTerminalStatus(request.status)}function pickPetRecordsRequest(requests,petRef){if(petRef===null)return null;let forPet=requests.filter(r=>r.petRef===petRef);if(forPet.length===0)return null;let published=forPet.find(r=>r.status==="published");return published!==void 0?published:forPet.filter(isRecordsInProgress).sort((a,b)=>b.updatedAt.localeCompare(a.updatedAt))[0]??null}function deriveRecordsDashboardState(args){if(args.hasMarkers)return"published";let request=pickPetRecordsRequest(args.requests,args.petRef);return request===null?"none":request.status==="published"||isRecordsInProgress(request)?"in_progress":"none"}function selectDashboardLoading(input){return input.recordLoading?true:input.hasFullRecord?false:input.markersLoading||!input.hasMarkers&&input.requestsLoading}function selectDashboardView(input){return selectDashboardLoading(input)?"loading":input.hasFullRecord?"record":input.markersError||input.recordError&&!input.hasMarkers?"error":input.dashboardState==="in_progress"&&input.drivingRequest!==null?"in_progress":input.dashboardState==="none"?"none":"labs_only"}function recordsEmptyVariantForError(error){return error?.httpStatus===429?"rate_limited":error?.httpStatus===502?"service_unavailable":"error"}var REQUEST_SCREEN_COPY=/* @__PURE__ */Object.freeze({loading:"Loading record request",sentTitle:"Request sent",sentLeadWeb:(clinicName,petName)=>`${clinicName} has the request. We’ll let you know when ${petName}’s file arrives.`,sentLeadNative:petName=>`We’ll let you know when ${petName}’s file arrives.`,whereItStands:"Where it stands",details:"Request details",detailsClinic:"Clinic",detailsSent:"Sent",timelineA11y:"Request timeline",awaitingNote:"Clinics usually reply within a week. We follow up automatically and will let you know if there’s no reply by day 14.",waitingBanner:elapsedDays=>`It’s been ${elapsedDays} ${elapsedDays===1?"day":"days"}. Some clinics take a little longer; we’ve been following up automatically and are still on it. If there’s no reply by day 14, we’ll let you know.`,viewRecords:"View health records",nextStep:"You can try a different clinic or upload records you already have.",tryAnotherClinic:"Request from a different clinic",convert:"Upload my own records instead",converting:"Switching…",convertHint:"We’ll stop waiting on the clinic so you can add the records you already have. If the clinic does reply, we’ll still add their records too.",freshUpload:"Upload your own records",freshUploadStarting:"Starting…",cancel:"Cancel request",cancelling:"Cancelling…",resend:"Resend email",resending:"Resending…",errors:/* @__PURE__ */Object.freeze({cancel:"We couldn’t cancel this request. Please try again.",retry:"We couldn’t retry this request. Please try again.",email:"We couldn’t update the clinic email. Please try again.",convert:"We couldn’t switch this to an upload. Please try again.",start:"We couldn’t start that. Please try again.",invalidEmail:"Enter a valid clinic email."})});function fallbackFailureTitle(request){if(request.wireStatus==="clinic_declined")return"The clinic declined to release the records.";if(request.wireStatus==="clinic_responded_no_records")return"The clinic replied but didn’t include your records.";switch(request.failureCode){case"no_response":return"The clinic didn’t reply after several reminders over 14 days.";case"parse_timeout":case"parse_error":return"We received the records but couldn’t read them. Uploading a clean copy usually fixes this.";case"hard_bounce":case"dispatch_failed":return"We couldn’t deliver the email to the clinic.";default:return"This request didn’t go through."}}function failureTitle(request){let reason=request.failureReason?.trim()??"";return reason.length>0?reason:fallbackFailureTitle(request)}var MS_PER_DAY=1440*60*1e3;function requestElapsedDays(request,nowMs){if(!request.createdAt)return 0;let created=Date.parse(request.createdAt);if(Number.isNaN(created))return 0;let diff=nowMs-created;return diff<=0?0:Math.floor(diff/MS_PER_DAY)}var RECORDS_WAITING_LONG_DAYS=7;function requestWaitingTooLong(request,nowMs){return request.wireStatus!=="awaiting_response"?false:requestElapsedDays(request,nowMs)>=RECORDS_WAITING_LONG_DAYS}function isTerminalFailure(request){return request.status==="failed"}function shouldOfferRecovery(request){return isTerminalFailure(request)||request.canUpdateClinicEmail===true||request.canRetrySend===true}function useClinicPicker(controller,location){let[query,setQueryValue]=react.useState(""),[debouncedQuery,setDebounced]=react.useState(""),[clinics,setClinics]=react.useState([]),[cursor,setCursor]=react.useState(null),[recent,setRecent]=react.useState([]),[recentLoading,setRecentLoading]=react.useState(true),[initialLoading,setInitialLoading]=react.useState(false),[loadingMore,setLoadingMore]=react.useState(false),[error,setError]=react.useState(null),[pageError,setPageError]=react.useState(null),[attempt,setAttempt]=react.useState(0),generation=react.useRef(0),live=react.useRef(true),lat=location?.latitude,lng=location?.longitude,bias=react.useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);react.useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),react.useEffect(()=>{let alive=true;return setRecentLoading(true),controller.recentClinics({limit:5}).then(result=>{alive&&(result.ok&&setRecent(result.value.clinics),setRecentLoading(false))}).catch(()=>{alive&&setRecentLoading(false)}),()=>{alive=false}},[controller]),react.useEffect(()=>{let trimmed=query.trim();if(trimmed.length<CLINIC_SEARCH_MIN_CHARS){setDebounced("");return}let handle=setTimeout(()=>setDebounced(trimmed),CLINIC_SEARCH_DEBOUNCE_MS);return()=>clearTimeout(handle)},[query]);let isSearchActive=debouncedQuery.length>=CLINIC_SEARCH_MIN_CHARS;react.useEffect(()=>{let revision=generation.current+=1;if(setClinics([]),setCursor(null),setError(null),setPageError(null),!isSearchActive){setInitialLoading(false);return}setInitialLoading(true),controller.searchClinics({query:debouncedQuery,limit:25,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(result.value.clinics),setCursor(result.value.nextCursor)):setError(result.error),setInitialLoading(false))}).catch(()=>{live.current&&revision===generation.current&&setInitialLoading(false)})},[controller,debouncedQuery,isSearchActive,bias,attempt]);let loadMore=react.useCallback(()=>{if(!isSearchActive||cursor===null||loadingMore)return;let revision=generation.current;setLoadingMore(true),setPageError(null),controller.searchClinics({query:debouncedQuery,limit:25,cursor:cursor,...bias?{location:bias}:{}}).then(result=>{!live.current||revision!==generation.current||(result.ok?(setClinics(current=>[...current,...result.value.clinics]),setCursor(result.value.nextCursor)):setPageError(result.error),setLoadingMore(false))}).catch(()=>{live.current&&revision===generation.current&&setLoadingMore(false)})},[controller,cursor,debouncedQuery,isSearchActive,loadingMore,bias]),setQuery=react.useCallback(value=>setQueryValue(value),[]),retry=react.useCallback(()=>setAttempt(n2=>n2+1),[]);return react.useMemo(()=>({query:query,debouncedQuery:debouncedQuery,isSearchActive:isSearchActive,clinics:clinics,recent:recent,recentLoading:recentLoading,initialLoading:initialLoading,loadingMore:loadingMore,hasNextPage:cursor!==null,error:error,pageError:pageError,setQuery:setQuery,loadMore:loadMore,retry:retry}),[query,debouncedQuery,isSearchActive,clinics,recent,recentLoading,initialLoading,loadingMore,cursor,error,pageError,setQuery,loadMore,retry])}function clinicDraftFor(clinic,freeText,email2,idempotencyKey){/* @__PURE__ */
|
|
112
113
|
return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),clinicSchema=/* @__PURE__ */zod.z.object({clinicId:/* @__PURE__ */uuid.optional(),clinicFreeText:text(200).refine(value=>value.trim().length>0).optional(),clinicEmail:text(320,3).refine(value=>!hasControl(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())).optional(),signatureId:/* @__PURE__ */uuid.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0)),inputSchema=/* @__PURE__ */zod.z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */zod.z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */zod.z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */zod.z.string(),created_count:/* @__PURE__ */zod.z.number().int().nonnegative(),failed_count:/* @__PURE__ */zod.z.number().int().nonnegative(),results:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({idempotency_key:/* @__PURE__ */zod.z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */zod.z.string().nullable().optional(),created:/* @__PURE__ */zod.z.boolean(),request:/* @__PURE__ */zod.z.unknown().optional(),failure_code:/* @__PURE__ */zod.z.string().nullable().optional(),failure_reason:/* @__PURE__ */zod.z.string().nullable().optional()}))});function createRecordsClinicBatchClient(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}});return{async createClinicRequestBatch(input){if(!inputSchema.safeParse(input).success)return err(makeEverfurError("validationFailed",{retryable:false}));let result=await funnel.send("records.clinic.createBatch",{method:"POST",path:"/widget/v1/records/clinic-requests/batch",body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,clinics:input.clinics.map(clinic=>({...clinic.clinicId!==void 0?{clinic_id:clinic.clinicId}:{clinic_free_text:clinic.clinicFreeText},...clinic.clinicEmail!==void 0?{clinic_email:clinic.clinicEmail}:{},...clinic.signatureId!==void 0?{signature_id:clinic.signatureId}:{signature_png_base64:clinic.signaturePngBase64},idempotency_key:clinic.idempotencyKey}))}});if(!result.ok)return result;let parsed=responseSchema.safeParse(result.value);if(!parsed.success||parsed.data.pet_ref!==input.petRef)return malformed();let results=[];for(let row of parsed.data.results){let request=row.request===void 0||row.request===null?null:mapRequestView(row.request);if(row.created!==(request!==null))return malformed();results.push(/* @__PURE__ */Object.freeze({idempotencyKey:row.idempotency_key,clinicId:row.clinic_id??null,clinicFreeText:row.clinic_free_text??null,created:row.created,request:request,failureCode:row.failure_code??null,failureReason:row.failure_reason??null}))}return ok(/* @__PURE__ */Object.freeze({requestGroupId:parsed.data.request_group_id,petRef:parsed.data.pet_ref,results:/* @__PURE__ */Object.freeze(results),createdCount:parsed.data.created_count,failedCount:parsed.data.failed_count}))}}}function malformed(){return err(makeEverfurError("internalError",{retryable:false}))}var uuid2=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),clinicPageSchema=/* @__PURE__ */zod.z.object({clinics:/* @__PURE__ */zod.z.array(/* @__PURE__ */zod.z.object({clinic_id:uuid2,name:/* @__PURE__ */zod.z.string().min(1),address:/* @__PURE__ */zod.z.string().nullable(),phone:/* @__PURE__ */zod.z.string().nullable(),email_status:/* @__PURE__ */zod.z.string(),distance_km:/* @__PURE__ */zod.z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */zod.z.string().nullable().optional()}),copySchema=/* @__PURE__ */zod.z.object({authorization_version:/* @__PURE__ */zod.z.string().min(1),scope_template:/* @__PURE__ */zod.z.string().min(1),authorization_template:/* @__PURE__ */zod.z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */zod.z.object({upload_id:/* @__PURE__ */zod.z.string().min(1),upload_url:/* @__PURE__ */zod.z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */zod.z.record(/* @__PURE__ */zod.z.string())});function createRecordsClinicController(deps){let{repository:repository}=deps,request=async pending=>{let result=await pending;if(!result.ok)return result;let mapped=mapRequestView(result.value);return mapped===null?malformed2():ok(mapped)},page=async pending=>{let result=await pending;if(!result.ok)return result;let parsed=clinicPageSchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({clinics:/* @__PURE__ */Object.freeze(parsed.data.clinics.map(clinic=>/* @__PURE__ */Object.freeze({id:clinic.clinic_id,name:clinic.name,address:clinic.address,phone:clinic.phone,emailStatus:clinic.email_status,distanceKm:clinic.distance_km}))),nextCursor:parsed.data.next_cursor??null})):malformed2()};return{searchClinics:(input={})=>page(repository.searchClinics(input)),recentClinics:(input={})=>page(repository.recentClinics(input)),async getRequestGroup(requestGroupId){let result=await repository.getRequestGroup(requestGroupId);if(!result.ok)return result;let group=mapRequestGroup(result.value);return group===null?malformed2():ok(group)},async getAuthorizationCopy(){let result=await repository.getAuthorizationCopy();if(!result.ok)return result;let parsed=copySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({authorizationVersion:parsed.data.authorization_version,scopeTemplate:parsed.data.scope_template,authorizationTemplate:parsed.data.authorization_template})):malformed2()},async createClinicRequest(input){let result=await request(repository.createClinicRequest(input));return result.ok&&result.value.petRef!==input.petRef?malformed2():result},retryRequest:id=>request(repository.retryRequest(id)),revokeRequest:id=>request(repository.revokeRequest(id)),updateClinicEmail:(id,clinicEmail)=>request(repository.updateClinicEmail(id,clinicEmail)),convertToUpload:id=>request(repository.convertToUpload(id)),async initiateSignatureUpload(fileSize){let result=await repository.initiateSignatureUpload(fileSize);if(!result.ok)return result;let parsed=signaturePolicySchema.safeParse(result.value);return parsed.success?ok(/* @__PURE__ */Object.freeze({uploadId:parsed.data.upload_id,uploadUrl:parsed.data.upload_url,uploadFields:/* @__PURE__ */Object.freeze(parsed.data.upload_fields)})):malformed2()},async completeSignatureUpload(uploadId){let result=await repository.completeSignatureUpload(uploadId);if(!result.ok)return result;let parsed=zod.z.object({signature_id:uuid2}).safeParse(result.value);return parsed.success?ok(parsed.data.signature_id):malformed2()}}}function malformed2(){return err(makeEverfurError("internalError",{retryable:false}))}var BASE2="/widget/v1/records",uuid3=/* @__PURE__ */zod.z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),text2=(max,min=1)=>zod.z.string().refine(value=>!hasLoneSurrogate(value)&&[...value].length>=min&&[...value].length<=max),hasControl2=value=>[...value].some(character=>character.charCodeAt(0)<32||character.charCodeAt(0)===127),email=text2(320,3).refine(value=>!hasControl2(value)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim())),requestId=text2(64),recentSchema=/* @__PURE__ */zod.z.object({limit:/* @__PURE__ */zod.z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */zod.z.object({query:text2(200,0).optional(),location:/* @__PURE__ */zod.z.object({latitude:/* @__PURE__ */zod.z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */zod.z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */zod.z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */zod.z.object({petRef:text2(128),ownerName:text2(200).refine(value=>value.trim().length>0&&!hasControl2(value)),authorizationVersion:text2(64),clinicId:/* @__PURE__ */uuid3.optional(),clinicFreeText:text2(200).refine(value=>value.trim().length>0).optional(),clinicEmail:email.optional(),signatureId:/* @__PURE__ */uuid3.optional(),signaturePngBase64:/* @__PURE__ */zod.z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */zod.z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)}).strict().refine(value=>value.clinicId===void 0!=(value.clinicFreeText===void 0)).refine(value=>value.signatureId===void 0!=(value.signaturePngBase64===void 0));function createHttpRecordsClinicRepository(deps){let funnel=deps.funnel??createRequestFunnel({auth:deps.auth,...deps.errorPolicy?{errorPolicy:deps.errorPolicy}:{}}),send=(call,request,deduplicated=false)=>funnel.send(`records.clinic.${call}`,request,request.method==="GET"||deduplicated?void 0:{idempotent:false,maxAttempts:1}),recover=(id,action,body)=>requestId.safeParse(id).success?send(action,{method:"POST",path:`${BASE2}/requests/${encodeURIComponent(id)}/${action}`,...body?{body:body}:{}}):invalid();return{searchClinics(input){return searchSchema.safeParse(input).success?send("search",{method:"GET",path:`${BASE2}/clinics/search`,query:{q:input.query??"",lat:input.location?.latitude,lng:input.location?.longitude,limit:input.limit,cursor:input.cursor}}):invalid()},recentClinics(input){return recentSchema.safeParse(input).success?send("recent",{method:"GET",path:`${BASE2}/clinics/recent`,query:{limit:input.limit}}):invalid()},getRequestGroup(requestGroupId){return requestId.safeParse(requestGroupId).success?send("requestGroup",{method:"GET",path:`${BASE2}/request-groups/${encodeURIComponent(requestGroupId)}`}):invalid()},getAuthorizationCopy:()=>send("authorizationCopy",{method:"GET",path:`${BASE2}/authorization-copy`}),createClinicRequest(input){return createSchema.safeParse(input).success?send("create",{method:"POST",path:`${BASE2}/clinic-requests`,body:{pet_ref:input.petRef,owner_name:input.ownerName,authorization_version:input.authorizationVersion,idempotency_key:input.idempotencyKey,...input.clinicId!==void 0?{clinic_id:input.clinicId}:{clinic_free_text:input.clinicFreeText},...input.clinicEmail!==void 0?{clinic_email:input.clinicEmail}:{},...input.signatureId!==void 0?{signature_id:input.signatureId}:{signature_png_base64:input.signaturePngBase64}}},true):invalid()},retryRequest:id=>recover(id,"retry"),revokeRequest:id=>recover(id,"revoke"),convertToUpload:id=>recover(id,"convert-to-upload"),updateClinicEmail(id,clinicEmail){return email.safeParse(clinicEmail).success?recover(id,"clinic-email",{clinic_email:clinicEmail}):invalid()},initiateSignatureUpload(fileSize){return!Number.isInteger(fileSize)||fileSize<=0||fileSize>2*1024*1024?invalid():send("signatureInitiate",{method:"POST",path:`${BASE2}/signatures/initiate`,body:{content_type:"image/png",file_size:fileSize}})},completeSignatureUpload(uploadId){return/^sig-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(uploadId)?send("signatureComplete",{method:"POST",path:`${BASE2}/signatures/complete`,body:{upload_id:uploadId}}):invalid()}}}function invalid(){return Promise.resolve(err(makeEverfurError("validationFailed",{retryable:false})))}function useEverfurRecordsClinic(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),controller=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=react.useRef(controller);return react.useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),react.useMemo(()=>{let run=async operation=>{if(userRef===null||active.current!==controller)return err(makeEverfurError("accessDenied"));let result=await operation();return active.current===controller?result:err(makeEverfurError("accessDenied"))};return{searchClinics:input=>run(()=>controller.searchClinics(input)),recentClinics:input=>run(()=>controller.recentClinics(input)),getRequestGroup:id=>run(()=>controller.getRequestGroup(id)),getAuthorizationCopy:()=>run(()=>controller.getAuthorizationCopy()),createClinicRequest:input=>run(()=>controller.createClinicRequest(input)),retryRequest:id=>run(()=>controller.retryRequest(id)),revokeRequest:id=>run(()=>controller.revokeRequest(id)),updateClinicEmail:(id,email2)=>run(()=>controller.updateClinicEmail(id,email2)),convertToUpload:id=>run(()=>controller.convertToUpload(id)),initiateSignatureUpload:size=>run(()=>controller.initiateSignatureUpload(size)),completeSignatureUpload:id=>run(()=>controller.completeSignatureUpload(id))}},[controller,userRef])}function useEverfurRecordsClinicBatch(){let{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),client=react.useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=react.useRef(client);return react.useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),react.useMemo(()=>({async createClinicRequestBatch(input){if(userRef===null||active.current!==client)return err(makeEverfurError("accessDenied"));let result=await client.createClinicRequestBatch(input);return active.current===client?result:err(makeEverfurError("accessDenied"))}}),[client,userRef])}var HostRenderBoundary=class extends react.Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey}}static getDerivedStateFromError(){return{failed:true}}static getDerivedStateFromProps(props,state){return Object.is(props.resetKey,state.key)?null:{failed:false,key:props.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};function RenderHost({render:render}){return render()}function HostRender({render:render,fallback:fallback,resetKey:resetKey}){return react.createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children:react.createElement(RenderHost,{render:render})})}var REQUIRES=/* @__PURE__ */Object.freeze({chat:/* @__PURE__ */Object.freeze(["chat.message.create"]),records:/* @__PURE__ */Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:/* @__PURE__ */Object.freeze(["records.clinic.create"]),video:/* @__PURE__ */Object.freeze(["video.gait.execute"]),photo:/* @__PURE__ */Object.freeze(["photo.checkup.execute"]),animations:/* @__PURE__ */Object.freeze(["animations.state.read"]),televet:/* @__PURE__ */Object.freeze(["televet.visit.create"]),texting:/* @__PURE__ */Object.freeze(["sms.identity.read","sms.identity.update"]),healthPlan:/* @__PURE__ */Object.freeze(["shop.plan.read","shop.plan.update"])});function requires(name){return REQUIRES[name]}function decideCapability(name,decisions,opts){let keys=requires(name),byResource=/* @__PURE__ */new Map;for(let decision of decisions)byResource.set(decision.resource,decision);if(opts?.isPending===true&&keys.some(key=>!byResource.has(key)))return freezeDecision({name:name,enabled:false,isPending:true,limits:{}});let limits=mergeLimits(keys,byResource);return keys.filter(key=>byResource.get(key)?.granted!==true).length===0?freezeDecision({name:name,enabled:true,isPending:false,limits:limits}):freezeDecision({name:name,enabled:false,isPending:false,limits:limits,disabled:disabledFor(keys,byResource)})}function mergeLimits(keys,byResource){let out={};for(let key of keys){let decisionLimits=byResource.get(key)?.limits;if(decisionLimits)for(let[limitKey,limitValue]of Object.entries(decisionLimits)){let existing=out[limitKey];out[limitKey]=existing===void 0?limitValue:Math.min(existing,limitValue)}}return out}function disabledFor(keys,byResource){for(let key of keys){let explicit=byResource.get(key)?.disabled;if(explicit)/* @__PURE__ */
|
|
113
114
|
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
114
115
|
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base2={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base2.disabled=d.disabled),/* @__PURE__ */Object.freeze(base2)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=react.useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return react.useMemo(()=>decideCapability(name,snapshot.decisions,{isPending:snapshot.isPending}),[name,snapshot])}var MIN_OFFSTATE_HEIGHT=48;function selectView(decision){return decision.isPending?"pending":decision.enabled?"enabled":"disabled"}function CapabilityGate(props){let{capability:capability,children:children,renderDisabled:renderDisabled,renderPending:renderPending,style:style}=props,decision=useCapability(capability),view=react.useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsxRuntime.jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsxRuntime.jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=react.useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
@@ -166,16 +167,16 @@ return jsxRuntime.jsx(InboxGlyph,{size:size,color:color});case"no_records":/* @_
|
|
|
166
167
|
return jsxRuntime.jsx(ActivityGlyph,{size:size,color:color});case"rate_limited":/* @__PURE__ */
|
|
167
168
|
return jsxRuntime.jsx(ClockGlyph,{size:size,color:color});case"service_unavailable":/* @__PURE__ */
|
|
168
169
|
return jsxRuntime.jsx(ToolGlyph,{size:size,color:color});case"error":/* @__PURE__ */
|
|
169
|
-
return jsxRuntime.jsx(WifiOffGlyph,{size:size,color:color});default:return null}}function RecordsEmptyState({variant:variant,onAction:onAction,message:message,testID:testID}){let styles=useStyles(),theme=useEverfurTheme(),copy=RECORDS_EMPTY_COPY[variant],[cooldown,setCooldown]=react.useState(variant==="rate_limited"?RATE_LIMIT_COOLDOWN_S:0);react.useEffect(()=>{variant==="rate_limited"&&setCooldown(RATE_LIMIT_COOLDOWN_S)},[variant]),react.useEffect(()=>{if(cooldown<=0)return;let handle=setTimeout(()=>setCooldown(s=>Math.max(0,s-1)),1e3);return()=>clearTimeout(handle)},[cooldown]);let cooling=variant==="rate_limited"&&cooldown>0,
|
|
170
|
+
return jsxRuntime.jsx(WifiOffGlyph,{size:size,color:color});default:return null}}function RecordsEmptyState({variant:variant,onAction:onAction,message:message,testID:testID}){let styles=useStyles(),theme=useEverfurTheme(),copy=RECORDS_EMPTY_COPY[variant],[cooldown,setCooldown]=react.useState(variant==="rate_limited"?RATE_LIMIT_COOLDOWN_S:0);react.useEffect(()=>{variant==="rate_limited"&&setCooldown(RATE_LIMIT_COOLDOWN_S)},[variant]),react.useEffect(()=>{if(cooldown<=0)return;let handle=setTimeout(()=>setCooldown(s=>Math.max(0,s-1)),1e3);return()=>clearTimeout(handle)},[cooldown]);let cooling=variant==="rate_limited"&&cooldown>0,label2=cooling?coolingActionLabel(cooldown):copy.action;/* @__PURE__ */
|
|
170
171
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
|
|
171
172
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
172
173
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:copy.title}),
|
|
173
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),
|
|
174
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.body,children:message??copy.body}),label2!==null&&onAction?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label2,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.actionLabel,children:label2})}):null]})}function useStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles3(theme),[theme])}var GLYPH_SIZE=22,GLYPH_BOX=48;function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme;return reactNative.StyleSheet.create({container:{paddingVertical:space.xxl,paddingHorizontal:space.xl,alignItems:"center",gap:space.sm+space.xs/2},glyph:{width:GLYPH_BOX,height:GLYPH_BOX,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug)-1,color:color.brandInk,textAlign:"center"},body:{...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.normal),color:color.text.muted,textAlign:"center",maxWidth:320},action:{marginTop:space.sm,minHeight:space.xxl+space.sm,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,backgroundColor:color.brand,alignItems:"center",justifyContent:"center",...slotBox(slots.primaryButton)},actionDisabled:{opacity:.5},actionLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug)-1,...slotText(slots.primaryButton)}})}var RECORDS_SANDBOX_COPY=/* @__PURE__ */Object.freeze({note:"Test account: clinics are never contacted. Use records test mode to move a request forward.",clinicNotContacted:"Clinic not contacted",notEmailed:email2=>`This is a test account, so no email went to ${email2}.`,newClinicDirectSendNote:"This is a test account, so this clinic will not be emailed."});var NO_SUBSCRIPTION=()=>()=>{};function isSandboxSnapshot(snapshot){return snapshot?.livemode===false}function useEntitlementSource(){try{return useEverfurContext().runtime.entitlements??null}catch{return null}}function useRecordsSandboxTenant(){let source=useEntitlementSource(),subscribe2=react.useCallback(listener=>source===null?NO_SUBSCRIPTION():source.subscribe(listener),[source]),read=react.useCallback(()=>source===null?false:isSandboxSnapshot(source.getSnapshot()),[source]);return react.useSyncExternalStore(subscribe2,read,read)}function useBrandImage(uri){let[failed,setFailed]=react.useState(null);return{shown:uri!==null&&failed!==uri,onError:()=>setFailed(uri)}}function BrandLogo({logoUrl:logoUrl,name:name,barStyle:barStyle,logoStyle:logoStyle,testID:testID}){let image=useBrandImage(logoUrl);return logoUrl===null||!image.shown?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text4=>text4.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text4=normalize(disclaimer);return text4.length===0||text4===FOOTNOTE}function parseColor(value){let rgba=toRgba(value);return rgba===null?null:normalizeRgba(rgba)}function toRgba(value){if(typeof value=="number")return argbIntToRgba(value);if(typeof value!="string")return null;let s=value.trim();if(s.length===0)return null;if(s.startsWith("#"))return fromHex(s.slice(1));if(s.toLowerCase().startsWith("0x"))return fromHex(s.slice(2));if(s.toLowerCase().startsWith("rgb"))return fromRgbFunc(s);if(/^[0-9a-fA-F]+$/.test(s)){let hex=fromHex(s);if(hex!==null)return hex}return/^\d+$/.test(s)?argbIntToRgba(Number.parseInt(s,10)):null}function fromHex(hex){let h=hex.trim();if(!/^[0-9a-fA-F]+$/.test(h))return null;if(h.length===3)return{r:dup(h[0]),g:dup(h[1]),b:dup(h[2]),a:1};if(h.length===6)return{r:byte(h,0),g:byte(h,2),b:byte(h,4),a:1};if(h.length===8){let a=byte(h,0);return{r:byte(h,2),g:byte(h,4),b:byte(h,6),a:a/255}}return null}function fromRgbFunc(input){let open=input.indexOf("("),close=input.indexOf(")");if(open<0||close<0||close<open)return null;let parts=input.slice(open+1,close).split(",").map(p=>p.trim());if(parts.length<3)return null;let r=clampByte(Number(parts[0])),g=clampByte(Number(parts[1])),b=clampByte(Number(parts[2]));if(r===null||g===null||b===null)return null;let a=1;if(parts.length>=4){let alpha=Number(parts[3]);if(!Number.isFinite(alpha))return null;a=Math.min(1,Math.max(0,alpha))}return{r:r,g:g,b:b,a:a}}function argbIntToRgba(n2){if(!Number.isFinite(n2))return null;let int=Math.trunc(n2)>>>0,a=int>>>24&255;return{r:int>>>16&255,g:int>>>8&255,b:int&255,a:a===0?1:a/255}}function byte(hex,at){return Number.parseInt(hex.slice(at,at+2),16)}function dup(nibble){return Number.parseInt(`${nibble??"0"}${nibble??"0"}`,16)}function clampByte(n2){return Number.isFinite(n2)?Math.min(255,Math.max(0,Math.round(n2))):null}function normalizeRgba(rgba){if(rgba.a>=1)return rgbToHex(rgba.r,rgba.g,rgba.b);let a=Math.round(rgba.a*1e3)/1e3;return`rgba(${rgba.r},${rgba.g},${rgba.b},${a})`}function rgbToHex(r,g,b){return`#${hex2(r)}${hex2(g)}${hex2(b)}`.toUpperCase()}function hex2(n2){return n2.toString(16).padStart(2,"0")}var NEAR_BLACK="#111111",WHITE="#FFFFFF",BLACK="#000000";function readableOn(background){let rgba=toRgba(background);if(rgba===null)return WHITE;let bg=relativeLuminance(rgba),black=relativeLuminance({r:17,g:17,b:17}),white=relativeLuminance({r:255,g:255,b:255});return luminanceContrast(bg,white)>=luminanceContrast(bg,black)?WHITE:NEAR_BLACK}function legibleOn(background,target){let first=readableOn(background);return contrastRatio(first,background)>=target?first:contrastRatio(WHITE,background)>=contrastRatio(BLACK,background)?WHITE:BLACK}function poleForGrounds(grounds){let worst=ink=>grounds.reduce((low,ground)=>Math.min(low,contrastRatio(ink,ground)),Number.POSITIVE_INFINITY);return worst(WHITE)>=worst(BLACK)?WHITE:BLACK}function relativeLuminance(rgba){let r=linearize(rgba.r/255),g=linearize(rgba.g/255),b=linearize(rgba.b/255);return.2126*r+.7152*g+.0722*b}function linearize(channel){return channel<=.03928?channel/12.92:Math.pow((channel+.055)/1.055,2.4)}function luminanceContrast(l1,l2){let lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+.05)/(darker+.05)}function contrastRatio(a,b){let fg=toRgba(a),bg=toRgba(b);if(fg===null||bg===null)return 1;let ground=bg.a>=1?bg:{...bg},fore=fg.a>=1?fg:composite(fg,ground);return luminanceContrast(relativeLuminance(fore),relativeLuminance(ground))}function composite(fg,bg){let a=fg.a,mix2=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix2(fg.r,bg.r),g:mix2(fg.g,bg.g),b:mix2(fg.b,bg.b),a:1}}function flattenOnto(color,background){let fg=toRgba(color),bg=toRgba(background);if(fg===null||bg===null)return null;let out=fg.a>=1?fg:composite(fg,{...bg});return rgbToHex(out.r,out.g,out.b)}function withAlpha(color,alpha){let rgba=toRgba(color);if(rgba===null)return null;let a=Math.min(1,Math.max(0,alpha));return`rgba(${rgba.r}, ${rgba.g}, ${rgba.b}, ${a})`}var PUSH_STEP=.05;function pushToContrast(color,grounds,pole,target){let first=grounds[0];if(first===void 0)return pole;let reads=candidate=>grounds.every(ground=>contrastRatio(candidate,ground)>=target);if(toRgba(color)===null)return pole;if(reads(color))return color;let flat=flattenOnto(color,first),from=flat===null?null:toRgba(flat),to=toRgba(pole);if(from===null||to===null)return pole;for(let step=1;step<1/PUSH_STEP;step+=1){let t=step*PUSH_STEP,mix2=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix2(from.r,to.r),mix2(from.g,to.g),mix2(from.b,to.b));if(reads(candidate))return candidate}return pole}function brandedStatus(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color,c=theme.color,same2=(a,b)=>parseColor(a)===parseColor(b);return{success:!same2(c.success,compiled.success),warning:!same2(c.warningStrong,compiled.warningStrong)||!same2(c.cautionAccent,compiled.cautionAccent),info:!(same2(c.info,c.brandInk)&&same2(c.badgeBgInfo,c.brandSoft)&&same2(c.infoEdge,c.structureEdge))}}var SLOT_MIN_CONTRAST=4.5;function brandedSuccessInk(theme){if(!brandedStatus(theme).success)return null;let grounds=[theme.color.surface];return pushToContrast(theme.color.success,grounds,poleForGrounds(grounds),SLOT_MIN_CONTRAST)}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
|
|
174
175
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
|
|
175
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:
|
|
176
|
-
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??
|
|
177
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:
|
|
178
|
-
return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence2?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence2?styles.chipSentenceText:null,fg],children:
|
|
176
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label2,onPress:onPress,kind:kind="primary",disabled:disabled=false,busy:busy=false,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID,style:style}){let styles=useScreenStyles(),theme=useEverfurTheme(),still=theme.motion.reducedMotion,box3=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink,text4=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
|
|
177
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label2,accessibilityHint:accessibilityHint,accessibilityState:{disabled:disabled||busy,busy:busy},style:({pressed:pressed})=>[styles.pill,box3,disabled?styles.pillDisabled:null,pressed&&!still?styles.pressed:null,style],testID:testID,children:[busy?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
|
|
178
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:label2})]})}function Chip({label:label2,tone:tone="neutral",testID:testID}){let styles=useScreenStyles(),{bg:bg,fg:fg}=styles.chipTones[tone],sentence2=label2.length>CHIP_WORD_MAX;/* @__PURE__ */
|
|
179
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.chip,sentence2?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.chipText,sentence2?styles.chipSentenceText:null,fg],children:label2})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
|
|
179
180
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.sectionHeader,children:[
|
|
180
181
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionCount,children:count}):null]})}function Chevron({direction:direction="right"}){let styles=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
|
|
181
182
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.chevron,{transform:[{rotate:rotate}]}],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),bannerText=slotText(slots.banner),bannerInk=slots.banner?.textColor,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({bg:{backgroundColor:bg,borderColor:"transparent"},fg:{color:fg}}),edge=(line2,fg)=>({bg:{backgroundColor:color.surface,borderColor:line2},fg:{color:fg}});return{chipTones:{neutral:edge(color.brandBorderStrong,color.text.primary),info:tone(color.brandSoft,color.brandInk),warning:edge(color.cautionAccent,color.text.primary),critical:edge(color.danger,color.danger),positive:edge(color.success,brandedSuccessInk(theme)??color.brandInk)},...reactNative.StyleSheet.create({root:{flex:1,backgroundColor:color.background},body:{flex:1},content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg},contentTight:{paddingHorizontal:space.sm,paddingBottom:space.xxl,gap:space.lg},inset:{paddingHorizontal:space.sm},section:{gap:space.sm+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.xs},sectionTitle:{...text4(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text4(size.bodyTight,lineHeight.snug,color.text.muted,"medium")},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.xs,...slotBox(recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(recordCard,hairline)},row:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.md,paddingVertical:space.md},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowMain:{flex:1},rowRight:{alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text4(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text4(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text4(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text4(size.caption,lineHeight.normal,color.text.muted),...cardText},chip:{minHeight:24,justifyContent:"center",borderRadius:radius.pill,borderWidth:1.5,paddingHorizontal:space.sm+space.xs/2,alignSelf:"flex-start"},chipText:{...text4(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text4(size.caption,lineHeight.normal,color.text.primary,"medium"),letterSpacing:0,textTransform:"none"},pill:{minHeight:BUTTON_HEIGHT,borderRadius:radius.pill,paddingHorizontal:space.lg+space.xs/2,flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm},pillPrimary:{backgroundColor:color.brand,...slotBox(slots.primaryButton)},pillPrimaryLabel:{...text4(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text4(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text4(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text4(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text4(size.body,lineHeight.snug,color.linkInk,"bold")},pillDisabled:{opacity:.5},pressed:{transform:[{scale:RECORDS_MOTION.pressScale}]},infoNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(slots.banner)},infoNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.text.primary),...bannerText},cautionNote:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2},cautionNoteText:{flex:1,...text4(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text4(size.bodyTight,lineHeight.relaxed,color.text.primary),errorBanner:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md},errorText:{flex:1,...text4(size.bodyTight,lineHeight.normal,errorColor)},band:{flexDirection:"row",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,...slotBox(slots.banner)},bandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:bannerInk??color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text4(size.small,lineHeight.tight,color.text.secondary,"bold"),...bannerText},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text4(size.body+1,lineHeight.snug,color.text.primary,"bold")},field:{minHeight:touch,paddingHorizontal:space.md,paddingVertical:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:size.body,...slotBox(slots.input,1),...slotText(slots.input)},fieldLabel:{...text4(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text4(size.caption,lineHeight.normal,color.text.muted),bodyText:text4(size.body,lineHeight.normal,color.text.primary)})}}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,BACK_LABEL="Back";function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let styles=useStyles2(),theme=useEverfurTheme(),logoUrl=theme.meta.logoUrl,row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
|
|
@@ -192,16 +193,14 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.shareGlyph,accessibilityEl
|
|
|
192
193
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareDot,styles.shareDotLeft]}),
|
|
193
194
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareDot,styles.shareDotBottom]}),
|
|
194
195
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareStroke,styles.shareStrokeUp]}),
|
|
195
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareStroke,styles.shareStrokeDown]})]})}function SendGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
196
|
-
return jsxRuntime.
|
|
197
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.sendBody}),
|
|
198
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.sendFold})]})}function DownloadGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
196
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.shareStroke,styles.shareStrokeDown]})]})}function SendGlyph(){let styles=useStyles2(),theme=useEverfurTheme(),ink=theme.slots.header?.textColor??theme.color.brandInk,size=theme.space.lg+theme.space.xs/2,strokes=react.useMemo(()=>SEND_SEGMENTS.map(seg=>sendStroke(seg,size,2*size/24,ink)),[size,ink]);/* @__PURE__ */
|
|
197
|
+
return jsxRuntime.jsx(reactNative.View,{style:styles.sendGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:"everfur-record-send-glyph",children:strokes.map((stroke3,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:stroke3},i))})}var SEND_SEGMENTS=[[22,2,11,13],[22,2,15,22],[15,22,11,13],[11,13,2,9],[2,9,22,2]];function sendStroke([x1,y1,x2,y2],size,w,ink){let u=size/24,len=Math.hypot(x2-x1,y2-y1)*u+w;return{position:"absolute",left:(x1+x2)/2*u-len/2,top:(y1+y2)/2*u-w/2,width:len,height:w,borderRadius:w/2,backgroundColor:ink,transform:[{rotate:`${Math.atan2(y2-y1,x2-x1)}rad`}]}}function DownloadGlyph(){let styles=useStyles2();/* @__PURE__ */
|
|
199
198
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
200
199
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadStem}),
|
|
201
200
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadHead}),
|
|
202
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},sandboxNote:{marginHorizontal:space.lg,marginBottom:space.md},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},
|
|
201
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,header=theme.slots.header,ink=header?.textColor??color.brandInk,rowBase={flexDirection:"row",alignItems:"center",justifyContent:"space-between",paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,gap:space.sm},touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return reactNative.StyleSheet.create({row:{...rowBase,...slotBox(header)},rowUnderLogo:rowBase,bar:{...slotBox(header)},logoBar:{alignItems:"center",paddingTop:space.sm,paddingHorizontal:space.lg},logo:{height:LOGO_HEIGHT,width:LOGO_MAX_WIDTH},back:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},chevron:{width:chevron,height:chevron,borderLeftWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginLeft:space.xs},title:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.heading,lineHeight:Math.round(type.size.heading*type.lineHeight.tight)+1,color:ink},spacer:{flex:1},sandboxNote:{marginHorizontal:space.lg,marginBottom:space.md},documentTitle:{flex:1,textAlign:"center",...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.text.primary,...slotText(header)},right:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2},listGlyph:{width:glyph,height:glyph,justifyContent:"space-evenly"},listBar:{height:stroke3,borderRadius:stroke3,backgroundColor:ink},shareGlyph:{width:glyph-space.xs,height:glyph-space.xs},shareDot:{position:"absolute",width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs,borderWidth:stroke3,borderColor:ink},shareDotTop:{right:0,top:0},shareDotLeft:{left:0,top:space.xs+space.xs/2},shareDotBottom:{right:0,bottom:0},shareStroke:{position:"absolute",left:space.xs,top:space.sm,width:space.sm+space.xs/2,height:stroke3,backgroundColor:ink},shareStrokeUp:{transform:[{rotate:"-30deg"}]},shareStrokeDown:{transform:[{rotate:"30deg"}]},sendGlyph:{width:glyph-space.xs,height:glyph-space.xs},downloadGlyph:{width:glyph-space.xs,height:glyph-space.xs,alignItems:"center"},downloadStem:{width:stroke3,height:space.sm+space.xs/2,backgroundColor:ink},downloadHead:{width:space.sm,height:space.sm,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],marginTop:-space.sm},downloadTray:{position:"absolute",bottom:0,left:0,right:0,height:space.xs+space.xs/2,borderLeftWidth:stroke3,borderRightWidth:stroke3,borderBottomWidth:stroke3,borderColor:ink}})}var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
|
|
203
202
|
return jsxRuntime.jsxs(reactNative.View,{testID:"records-gate-off",style:[{minHeight:MIN_HEIGHT,justifyContent:"center",gap:space.md,padding:space.lg,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surfaceCream},style],children:[reason.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
204
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms2=Date.parse(at);if(Number.isNaN(ms2))return"-";let date2=new Date(ms2);return dayLabel(date2.getUTCFullYear(),date2.getUTCMonth(),date2.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms2=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms2))return formatRecordsDate(at);let date2=new Date(ms2);return dayLabel(date2.getFullYear(),date2.getMonth(),date2.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}function documentsNewestFirst(documents){let at=doc=>{let ms2=doc.receivedAt===null?Number.NaN:Date.parse(doc.receivedAt);return Number.isNaN(ms2)?Number.NEGATIVE_INFINITY:ms2};return Object.values(documents).map((doc,index)=>({doc:doc,index:index,ms:at(doc)})).sort((a,b)=>b.ms===a.ms?a.index-b.index:b.ms>a.ms?1:-1).map(entry=>entry.doc)}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date2=>`Measured ${date2}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date2=>`Expires ${date2}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num5=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num5} ${unit}`:num5}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var DOCUMENT_CLASS_LABELS=/* @__PURE__ */Object.freeze({lab_report:"Lab report",pims_export:"Practice export",vaccination_certificate:"Vaccination certificate",imaging_report:"Imaging report",discharge_summary:"Discharge summary",referral_letter:"Referral letter",clinician_note:"Clinician note",consent_form:"Consent form",invoice_estimate:"Invoice",prescription:"Prescription",genetic_report:"Genetic report"});function documentTitle(doc){let title=doc.title?.trim()??"";if(title.length>0)return title;let cls=doc.documentClass;return(cls&&Object.prototype.hasOwnProperty.call(DOCUMENT_CLASS_LABELS,cls)?DOCUMENT_CLASS_LABELS[cls]:void 0)??DEPTH_COPY.uploadedDocument}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date2=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date2].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date2=>`Last done ${date2}`,overdue:"Overdue",due:date2=>`Due ${date2}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date2=>`Generated ${formatRecordsDate(date2)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms2=Date.parse(expiresAt);return Number.isNaN(ms2)?false:ms2<=nowMs}function formatShareExpiry(expiresAt,expired){let date2=formatRecordsDate(expiresAt);return date2==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date2}`:`Expires ${date2}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
|
|
203
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onExit,accessibilityRole:"button",accessibilityLabel:exitLabel,testID:"records-gate-off-exit",style:{minHeight:MIN_TARGET,alignSelf:"flex-start",justifyContent:"center",paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:1.5,borderColor:color.brandInk},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsxRuntime.jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}function formatShortDate(at){if(at===null||at.length===0)return"";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let year=iso[1]??"",month=iso[2]??"",day=iso[3]??"";return`${Number(month)}/${Number(day)}/${year.slice(2)}`}let ms2=Date.parse(at);if(Number.isNaN(ms2))return at;let date2=new Date(ms2);return`${date2.getUTCMonth()+1}/${date2.getUTCDate()}/${String(date2.getUTCFullYear()).slice(2)}`}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null)return dayLabel(Number(iso[1]),Number(iso[2])-1,Number(iso[3]));let ms2=Date.parse(at);if(Number.isNaN(ms2))return"-";let date2=new Date(ms2);return dayLabel(date2.getUTCFullYear(),date2.getUTCMonth(),date2.getUTCDate())}function dayLabel(year,month,day){let name=MONTHS[month];return name===void 0?"-":`${name} ${day}, ${year}`}function formatRecordsInstant(at){let parts=at?/^([\d-]{10}T[\d:]+)(\.\d+)?(.*)$/.exec(at):null,ms2=parts?Date.parse(`${parts[1]}${(parts[2]??"").slice(0,4)}${parts[3]||"Z"}`):Number.NaN;if(Number.isNaN(ms2))return formatRecordsDate(at);let date2=new Date(ms2);return dayLabel(date2.getFullYear(),date2.getMonth(),date2.getDate())}function formatIdentityValue(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return value;let formatted=formatRecordsDate(value),day=Number(value.slice(8,10));return formatted==="-"||day<1||day>31?value:formatted}function documentsNewestFirst(documents){let at=doc=>{let ms2=doc.receivedAt===null?Number.NaN:Date.parse(doc.receivedAt);return Number.isNaN(ms2)?Number.NEGATIVE_INFINITY:ms2};return Object.values(documents).map((doc,index)=>({doc:doc,index:index,ms:at(doc)})).sort((a,b)=>b.ms===a.ms?a.index-b.index:b.ms>a.ms?1:-1).map(entry=>entry.doc)}var DEPTH_COPY=/* @__PURE__ */Object.freeze({timeline:"Timeline",loadingTimeline:"Loading timeline",labResults:"Blood & lab work",visits:"Visits",physicalExams:"Physical exams",visitNotes:"Visit notes",visit:"Visit",exam:"Exam",visitNote:"Visit note",notRecorded:"Not recorded",abnormal:"Abnormal",notExamined:"Not examined",normal:"Normal",measured:date2=>`Measured ${date2}`,uploadedDocument:"Uploaded document",kind:/* @__PURE__ */Object.freeze({visit:"Visit",vaccine:"Vaccine",weight:"Weight",medication:"Medication"}),clinicVisit:"Clinic visit",doctor:name=>`Dr. ${name}`,lot:lot=>`Lot ${lot}`,expires:date2=>`Expires ${date2}`});function markerStatusLabel(status){switch(status){case"above":return{label:"Above range",outOfRange:true};case"below":return{label:"Below range",outOfRange:true};case"in_range":return{label:"In range",outOfRange:false};default:return{label:"No range on file",outOfRange:false}}}function trajectoryLabel(trajectory,visitCount){return visitCount<2?null:`${trajectory==="flat"?"Holding steady":`Trending ${trajectory==="down"?"down":trajectory==="up"?"up":"steady"}`} over ${visitCount} visits`}function humanize(key){let spaced=key.replace(/_/g," ").trim();return spaced.length===0?key:spaced.charAt(0).toUpperCase()+spaced.slice(1)}var BODY_SYSTEM_LABEL=/* @__PURE__ */Object.freeze({general:"General / attitude",eent:"Eyes, ears, nose & throat",oral_dental:"Oral & dental",cardiovascular:"Cardiovascular",respiratory:"Respiratory",gastrointestinal:"GI / abdomen",urogenital:"Urogenital",musculoskeletal:"Musculoskeletal",neurologic:"Neurologic",integument:"Skin & coat",lymphatic:"Lymph nodes"});function bodySystemLabel(system){return Object.prototype.hasOwnProperty.call(BODY_SYSTEM_LABEL,system)?BODY_SYSTEM_LABEL[system]:humanize(system)}var SOAP_SECTION_LABEL=/* @__PURE__ */Object.freeze({reason_for_visit:"Reason for visit",subjective:"Subjective",objective:"Objective",assessment:"Assessment",plan:"Plan",discharge_instructions:"Discharge instructions",follow_up:"Follow-up",remarks:"Notes"});function soapSectionLabel(section){return Object.prototype.hasOwnProperty.call(SOAP_SECTION_LABEL,section)?SOAP_SECTION_LABEL[section]:humanize(section)}function formatWeightKg(weightKg){return weightKg===null||!Number.isFinite(weightKg)?"-":`${weightKg.toFixed(3).replace(/\.?0+$/,"")} kg`}function formatMarkerReading(value,unit,qualitative){if((value===null||!Number.isFinite(value))&&qualitative)return qualitative;if(value===null||!Number.isFinite(value))return"-";let num5=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num5} ${unit}`:num5}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}var DOCUMENT_CLASS_LABELS=/* @__PURE__ */Object.freeze({lab_report:"Lab report",pims_export:"Practice export",vaccination_certificate:"Vaccination certificate",imaging_report:"Imaging report",discharge_summary:"Discharge summary",referral_letter:"Referral letter",clinician_note:"Clinician note",consent_form:"Consent form",invoice_estimate:"Invoice",prescription:"Prescription",genetic_report:"Genetic report"});function documentTitle(doc){let title=doc.title?.trim()??"";if(title.length>0)return title;let cls=doc.documentClass;return(cls&&Object.prototype.hasOwnProperty.call(DOCUMENT_CLASS_LABELS,cls)?DOCUMENT_CLASS_LABELS[cls]:void 0)??DEPTH_COPY.uploadedDocument}var RECORD_SCREEN_COPY=/* @__PURE__ */Object.freeze({title:"Visits & records",shareA11y:"Share medical record",requestClinicsA11y:"Request records from clinics",inReview:count=>`${count} ${count===1?"document":"documents"} from your vet ${count===1?"is":"are"} being reviewed. Your full record will appear here once review is complete.`,needsAttention:"Needs attention",conflictSub:"Two documents list different values. Your vet can confirm which is correct.",askConflict:"Ask Everfur about this",whatsOnFile:"What's on file",coverage:/* @__PURE__ */Object.freeze({labs:"Labs",vaccines:"Vaccines",weight:"Weight",vitals:"Vitals",exams:"Exams",procedures:"Procedures",genetics:"Genetics",parasite:"Parasite prevention",reproductive:"Reproductive"}),onFile:"on file",noneOnFile:"none on file",documentsOnFile:count=>`${count} ${count===1?"document":"documents"} on file`,inReviewChip:count=>`${count} in review`,beingVerified:count=>`${count} being verified`,beingVerifiedA11y:count=>`${count} ${count===1?"fact is":"facts are"} being verified`,pendingReview:"Pending review: ",dateRange:(from,to)=>`${formatRecordsDate(from)} to ${formatRecordsDate(to)}`,documents:"Sources on file",uploadedDocument:DEPTH_COPY.uploadedDocument,documentRowA11y:title=>`View what ${title} contributed to this record`,documentMeta:(pageCount,receivedAt)=>{let date2=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date2].filter(part=>part!==null);return parts.length>0?parts.join(" · "):null},identity:"Identity",needsReview:"Needs review",upcomingCare:"Upcoming care",careTimeline:"Care timeline",careTimelineSub:"Related records grouped over time, newest first.",lastDone:date2=>`Last done ${date2}`,overdue:"Overdue",due:date2=>`Due ${date2}`,askUpcomingCare:"Ask Everfur about upcoming care",askEverfur:"Ask Everfur",askExam:"Ask Everfur about this exam",askVisit:"Ask Everfur about this visit",labResults:DEPTH_COPY.labResults,visits:DEPTH_COPY.visits,physicalExams:DEPTH_COPY.physicalExams,visitNotes:DEPTH_COPY.visitNotes,document:/* @__PURE__ */Object.freeze({title:"Health Record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s health record`:"Health Record"},download:"Download PDF",empty:"This record is empty for now.",docTitle:"Medical Record",namelessPet:"Your pet",generated:date2=>`Generated ${formatRecordsDate(date2)}`,identity:"Identity",labs:"Blood & Lab Work",ref:band=>`Ref ${band}`,noRange:"No reference range",upcomingCare:"Upcoming Care",physicalExams:"Physical Exams",clinicianNotes:"Clinician Notes"})}),ENTITY_SECTION_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccinations",medication:"Medications",problem:"Problems & diagnoses",procedure:"Procedures & surgery",allergy:"Allergies",parasite_prevention:"Parasite prevention",reproductive:"Reproductive history",vital:"Vitals",body_weight:"Weight",lab_result:"Lab results",imaging:"Imaging & radiology",genetic_result:"Genetic testing",document_note:"Other notes"});function entityTypeLabel(entityType){return Object.prototype.hasOwnProperty.call(ENTITY_SECTION_TITLE,entityType)?ENTITY_SECTION_TITLE[entityType]:humanize(entityType)}var ENTITY_SECTION_ORDER=/* @__PURE__ */Object.freeze(["vaccination","medication","problem","procedure","allergy","parasite_prevention","reproductive","vital","body_weight"]);function orderEntityTypes(types){let known=ENTITY_SECTION_ORDER.filter(type=>types.includes(type)),rest=types.filter(type=>!ENTITY_SECTION_ORDER.includes(type));return[...known,...rest]}function conflictSeverityMeta(severity){switch(severity){case"identity_risk":return{label:"Identity mismatch",rank:0,tone:"critical"};case"benign":return{label:"Minor difference",rank:2,tone:"neutral"};default:return{label:"Needs review",rank:1,tone:"warning"}}}function dueBadge(dueAt,nowMs){if(!dueAt)return null;let due=Date.parse(dueAt);if(Number.isNaN(due))return null;let overdue=due<nowMs-1440*60*1e3;return{label:overdue?RECORD_SCREEN_COPY.overdue:RECORD_SCREEN_COPY.due(formatRecordsDate(dueAt)),overdue:overdue}}function formatReferenceBand(point){return point===null?null:point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}`:point.refLow!==null?`≥ ${point.refLow}`:point.refHigh!==null?`≤ ${point.refHigh}`:null}var SHARE_COPY=/* @__PURE__ */Object.freeze({openA11y:"Share medical record",openA11yFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share ${name}’s record`:"Share medical record"},title:"Share medical record",titleFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Send ${name}’s record`:"Share medical record"},helper:"Anyone with an active link can view this record until it expires. You can turn a link off anytime.",leadNative:"Pick who it’s for; we include the right pages.",leadWebFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Share a snapshot of what ${name}’s vets recorded. Pick who it’s for and we include the right pages.`:"Pick who it’s for; we include the right pages."},audienceLabel:"Who it’s for",audiences:/* @__PURE__ */Object.freeze({vet:"Vet",groomer:"Groomer",boarding:"Boarding"}),included:"What’s included",sendTo:"Send to",sendToPlaceholder:"vet@example.com…",send:"Send",sending:"Sending…",addEmailFor:petName=>{let name=petName?.trim()??"";return name.length>0?`Add an email to send ${name}’s record.`:"Add an email to send the record."},emailInvalid:"That email doesn’t look right. Check it and try again.",emailFailed:"Could not send the email. Please try again.",close:"Close",closeSheetA11y:"Close share sheet",viewDocument:"View document",previewNative:"Preview what they get",createLink:"Create link and share",shareLinkNative:"Share link",linkTerms:"Sent as a secure link that works for 7 days. You can stop sharing it any time.",creatingLink:"Creating link...",downloadPdf:"Download PDF",preparingPdf:"Preparing PDF...",activeLinks:"Active links",loadingLinks:"Loading your share links",errorTitle:"Couldn’t load your links",errorBody:"Check your connection and try again. You can still create a new link above.",retry:"Try again",retrying:"Retrying...",emptyTitle:"No active links yet",emptyBody:"Create a link above to let your vet or a sitter view this record. It expires on its own, and you can turn it off anytime.",copyLink:"Copy link",turnOff:"Turn off",turnOffA11y:context=>`Turn off share link, ${context}`,turningOff:"Turning off...",keep:"Keep",confirmTurnOff:"Turn off this link? Anyone who has it will lose access.",shareMessage:url=>`View this medical record: ${url}`,consentOffTitle:"Records access is off",consentOffBody:"Allow records for this pet again to create a link or download the PDF. Any links that were live have been turned off. You can still turn off a link from this list.",toasts:/* @__PURE__ */Object.freeze({noAddress:"Link created, but no address came back. It is listed under Active links.",shareSheet:"Could not open the share sheet. The link is saved below.",pdfShareSheet:"Could not open the share sheet for this PDF.",copied:"Link copied.",copyFailed:"Could not copy the link.",copiedNative:"Link copied. It works for 7 days.",copyFailedNative:url=>`Couldn’t copy. The link is ${url}`,turnedOff:"Link turned off.",sentTo:email2=>`Sent to ${email2}. The link works for 7 days.`})}),FULL_RECORD_LINES=/* @__PURE__ */Object.freeze(["Vaccines, medications and allergies","Conditions and procedures, with dates"]),DEPTH_SECTIONS=/* @__PURE__ */Object.freeze([["encounters","encounters",DEPTH_COPY.visits],["lab_results","markers",DEPTH_COPY.labResults],["physical_exams","physical_exams",DEPTH_COPY.physicalExams]]);function shareIncludedLines(scope,features){let lines=[];scope.sections.includes("entities")&&(scope.entityTypes===null?lines.push(...FULL_RECORD_LINES):lines.push(...orderEntityTypes(scope.entityTypes).map(entityTypeLabel)));for(let[section,feature,label2]of DEPTH_SECTIONS)scope.sections.includes(section)&&features[feature]===true&&lines.push(label2);return scope.sections.includes("forward_looking")&&lines.push(RECORD_SCREEN_COPY.upcomingCare),/* @__PURE__ */Object.freeze(lines)}function isShareExpired(expiresAt,nowMs){if(!expiresAt)return false;let ms2=Date.parse(expiresAt);return Number.isNaN(ms2)?false:ms2<=nowMs}function formatShareExpiry(expiresAt,expired){let date2=formatRecordsDate(expiresAt);return date2==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date2}`:`Expires ${date2}`}function buildShareRows(shares,urls,nowMs){let rows=shares.map(share=>{let expired=isShareExpired(share.expiresAt,nowMs),expiryLabel=formatShareExpiry(share.expiresAt,expired),createdDate=formatRecordsDate(share.createdAt),statusLabel=expired?"Expired":"Active",actionContext=expiryLabel.replace(/^Expires /,"expiring ").replace(/^Expired /,"expired ").replace(/^Expired$/,"expired").replace(/^No expiry date$/,"with no expiry date");return{shareId:share.shareId,shareUrl:urls[share.shareId]??null,active:!expired,statusLabel:statusLabel,expiryLabel:expiryLabel,createdLabel:createdDate==="-"?null:`Created ${createdDate}`,a11yLabel:`Share link. ${statusLabel}. ${expiryLabel}.`,actionContext:actionContext}});/* @__PURE__ */
|
|
205
204
|
return Object.freeze([...rows.filter(r=>r.active),...rows.filter(r=>!r.active)])}function shareErrorMessage(error,action){let status=error?.httpStatus;if(isRecordsConsentRequired(error)){if(action==="create"||action==="email")return"Records access for this pet is off, so a new link cannot be created.";if(action==="download")return"Records access for this pet is off, so the PDF cannot be downloaded."}if(status===429)return"You are creating links a little too fast. Wait a moment, then try again.";if(action==="revoke"&&(status===404||status===409||status===410))return"That link was already turned off.";if(status===401||status===403)return"You need to be signed in as this pet's owner to do that.";if(action==="email"&&(status===400||status===422||error?.code==="validationFailed"))return SHARE_COPY.emailInvalid;switch(action){case"create":return"Could not create a share link. Please try again.";case"revoke":return"Could not turn off that link. Please try again.";case"email":return SHARE_COPY.emailFailed;default:return"Could not download the record PDF. Please try again."}}function SkeletonBlock({width:width,height:height,radius:radius,style:style}){let{color:color,radius:radii}=useEverfurTheme();/* @__PURE__ */
|
|
206
205
|
return jsxRuntime.jsx(reactNative.View,{style:[{width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton},style],accessibilityElementsHidden:true,importantForAccessibility:"no"})}var DONUT=180,BADGE_W=70,BADGE_H=22,CAROUSEL_H=300,DISCLAIMER_H=44,RAIL_DOT=24,TIMELINE_BUBBLE=34,TIMELINE_ROWS=6,CLINIC_ROWS=5;function DashboardSkeleton({testID:testID}){let styles=useStyles3(),action=key=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionRow,children:[
|
|
207
206
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actionLeft,children:[
|
|
@@ -249,14 +248,14 @@ return jsxRuntime.jsx(reactNative.View,{style:styles.clinics,accessible:true,acc
|
|
|
249
248
|
return jsxRuntime.jsx(reactNative.View,{style:styles.shares,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:SHARE_COPY.loadingLinks,testID:testID,children:[0,1].map(index=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.shareRow,children:[
|
|
250
249
|
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"55%",height:13}),
|
|
251
250
|
/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"40%",height:11})]},index))})}var TIMELINE_SEPARATOR_INSET=62;function useStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles5(theme),[theme])}function makeStyles5(theme){let{color:color,space:space,radius:radius}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({dashboard:{flex:1,paddingHorizontal:space.sm,paddingTop:space.xs,gap:space.lg,backgroundColor:color.background},inset:{paddingHorizontal:space.sm},summaryCard:{alignItems:"center",borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg+space.xs,gap:space.md+space.xs/2},badges:{flexDirection:"row",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.lg},dots:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{alignSelf:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},request:{paddingHorizontal:space.lg,paddingTop:space.xs,gap:space.lg+space.xs/2,backgroundColor:color.background},railRow:{flexDirection:"row",alignItems:"flex-start",gap:space.md},railColumn:{alignItems:"center",width:RAIL_DOT},connector:{marginVertical:space.xs/2},railBody:{flex:1,paddingBottom:space.lg+space.xs/2,gap:space.xs+space.xs/2},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2,gap:space.sm},timeline:{flex:1,backgroundColor:color.background},timelineDisclaimer:{paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBody:{flex:1,gap:space.xs-1},timelineTop:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{gap:space.md},clinicRow:{borderRadius:radius.lg-space.xs/2,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md+space.xs/2,gap:space.sm},shares:{gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder},shareRow:{gap:space.xs+space.xs/2}})}var EMAIL=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function EverfurClinicPicker(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
252
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=react.useState(false),[startError,setStartError]=react.useState(null),[fallbackOpen,setFallbackOpen]=react.useState(false),[fallbackName,setFallbackName]=react.useState(""),[fallbackNameDirty,setFallbackNameDirty]=react.useState(false),[fallbackEmail,setFallbackEmail]=react.useState(""),[fallbackTouched,setFallbackTouched]=react.useState(false),select=react.useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,onEndReached=event=>{let{layoutMeasurement:layoutMeasurement,contentOffset:contentOffset,contentSize:contentSize}=event.nativeEvent;layoutMeasurement.height+contentOffset.y>=contentSize.height-layoutMeasurement.height*.6&&picker.loadMore()},listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle"
|
|
253
|
-
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
251
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles(),theme=useEverfurTheme(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=react.useState(false),[startError,setStartError]=react.useState(null),[fallbackOpen,setFallbackOpen]=react.useState(false),[fallbackName,setFallbackName]=react.useState(""),[fallbackNameDirty,setFallbackNameDirty]=react.useState(false),[fallbackEmail,setFallbackEmail]=react.useState(""),[fallbackTouched,setFallbackTouched]=react.useState(false),select=react.useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,onEndReached=event=>{let{layoutMeasurement:layoutMeasurement,contentOffset:contentOffset,contentSize:contentSize}=event.nativeEvent;layoutMeasurement.height+contentOffset.y>=contentSize.height-layoutMeasurement.height*.6&&picker.loadMore()},listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle",resultsAnnouncement=picker.isSearchActive&&!picker.initialLoading&&!picker.error&&picker.clinics.length>0?CLINIC_PICKER_COPY.resultsCount(picker.clinics.length):"";return react.useEffect(()=>{resultsAnnouncement.length>0&&reactNative.AccessibilityInfo.announceForAccessibility?.(resultsAnnouncement)},[resultsAnnouncement]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
254
252
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:CLINIC_PICKER_COPY.titleFor(petName),onBack:onBack,testID:"records-clinic-header"}),
|
|
255
253
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,testID:"records-clinic-lead",children:CLINIC_PICKER_COPY.leadNative}),
|
|
256
254
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.searchBar,children:[
|
|
257
255
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{testID:"records-clinic-search-glyph",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:/* @__PURE__ */jsxRuntime.jsx(SearchGlyph,{size:theme.space.md,color:theme.color.text.muted,strokeWidth:2})}),
|
|
258
256
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{value:picker.query,onChangeText:picker.setQuery,placeholder:CLINIC_PICKER_COPY.placeholder,placeholderTextColor:theme.color.text.muted,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",maxLength:200,accessibilityLabel:CLINIC_PICKER_COPY.searchA11y,style:local.searchInput,testID:"records-clinic-search-input"}),picker.query.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>picker.setQuery(""),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.clearSearch,hitSlop:8,testID:"records-clinic-search-clear",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.clearGlyph,children:"×"})}):null]}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.uploadWrap,children:[startError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:startError})}):null,
|
|
259
257
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:starting?CLINIC_PICKER_COPY.uploadOwnStarting:CLINIC_PICKER_COPY.uploadOwn,kind:"outline",busy:starting,onPress:startUpload,testID:"records-clinic-upload-own"})]}):null,
|
|
258
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:local.srOnly,testID:"records-clinic-results-status",children:resultsAnnouncement}),
|
|
260
259
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.list,keyboardShouldPersistTaps:"handled",keyboardDismissMode:reactNative.Platform.OS==="ios"?"interactive":"on-drag",onScroll:picker.isSearchActive?onEndReached:void 0,scrollEventThrottle:200,testID:"records-clinic-results",children:[picker.isSearchActive?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fallbackCard,testID:"records-clinic-fallback-card",children:[
|
|
261
260
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>setFallbackOpen(open=>!open),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.fallback.title,accessibilityHint:CLINIC_PICKER_COPY.fallback.subtitle,accessibilityState:{expanded:fallbackOpen},style:local.fallbackHeader,testID:"records-clinic-fallback",children:[
|
|
262
261
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.fallbackCopy,children:[
|
|
@@ -282,14 +281,12 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
282
281
|
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>onSelect(clinic),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.selectA11y(summary),hitSlop:8,style:styles.item,testID:`records-clinic-${clinic.id}`,children:[
|
|
283
282
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.itemHeader,children:[
|
|
284
283
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemName,numberOfLines:1,children:clinic.name}),distance?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:distance}):null]}),clinic.address?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemAddress,numberOfLines:2,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:clinic.phone}):null,
|
|
285
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({lead:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text4(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text4(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text4(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n2=>`Send ${n2} ${n2===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=react.useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=react.useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text4=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text4)?null:text4}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinic,setClinic]=react.useState(null),[email2,setEmail]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[created,setCreated]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null),captureAbort=react.useRef(null),lifetime=react.useRef(0);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),react.useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[drafts,setDrafts]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[outcome,setOutcome]=react.useState(null),[group,setGroup]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),lifetime=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),signature=react.useRef(null),captureAbort=react.useRef(null);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),react.useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),pet=petNameOr(props.petName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),pet,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:pet,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&®isterSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame2=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame2.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame2.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text4=name.trim();if(text4.length===0)return bitmap;let chars=[...text4],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n2=0;n2<256;n2+=1){let c=n2;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n2]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false}){let styles=useStyles4(),[mode,setMode]=react.useState("draw"),[typed,setTyped]=react.useState(""),[strokes,setStrokes]=react.useState([]),[width,setWidth]=react.useState(0),current=react.useRef([]),drawing=react.useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=react.useRef(scale);scaleRef.current=scale;let disabledRef=react.useRef(disabled);disabledRef.current=disabled,react.useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n2,stroke3)=>n2+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=react.useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=react.useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
286
|
-
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,testID:"records-signature-pad",children:[
|
|
287
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.type,style:styles.input,value:typed,maxLength:100,editable:!disabled,autoComplete:"off",autoCorrect:false,onChangeText:value=>{disabledRef.current||setTyped(value)}}):null,
|
|
284
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeLabel,badge.tone==="positive"?styles.badgePositiveText:badge.tone==="caution"?styles.badgeCautionText:styles.badgeNeutralText],children:badge.label})})]})}function useLocalStyles(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({srOnly:{position:"absolute",width:1,height:1,overflow:"hidden"},lead:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),paddingHorizontal:space.lg,paddingBottom:space.md},howCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.md,marginTop:space.sm,...slotBox(card)},howTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...cardText},howRow:{flexDirection:"row",gap:space.md},howNumber:{...face(theme,"monoBold"),fontSize:type.size.caption,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.brandInk,minWidth:space.xl},howText:{flex:1,gap:space.xs/2},howStepTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary),...cardText},searchBar:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingHorizontal:space.md+space.xs/2,height:space.xxl+space.md,marginHorizontal:space.lg,marginBottom:space.sm,borderRadius:radius.lg+space.xs/2,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.borderHairlineGreen,...slotBox(theme.slots.input,hairline)},searchInput:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text4(type.size.heading,type.lineHeight.tight,color.text.muted),uploadWrap:{paddingHorizontal:space.lg,paddingBottom:space.md,gap:space.sm},list:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.md},sectionLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},fallbackCard:{borderRadius:radius.lg-space.xs/2,borderWidth:1,borderStyle:"dashed",borderColor:color.brandBorder,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.md,...slotBox(card,1)},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},fallbackForm:{gap:space.sm},item:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(card,1)},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text4(type.size.body,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...cardText},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:{...text4(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},badge:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+1,paddingVertical:space.xs},badgePositive:{backgroundColor:color.badgeBgPositive},badgeCaution:{backgroundColor:color.badgeBgCaution},badgeNeutral:{backgroundColor:color.badgeBgNeutral},badgeLabel:{...text4(type.size.micro,type.lineHeight.snug,color.text.muted,"bold")},badgePositiveText:{color:color.success},badgeCautionText:{color:color.cautionAccent},badgeNeutralText:{color:color.text.muted},footer:{gap:space.sm,paddingTop:space.sm},footerLoading:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.md},footerRetry:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},footerRetryLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.brandInk,"bold")}})}var CLINIC_BATCH_COPY=/* @__PURE__ */Object.freeze({title:"Request records",resultTitle:"Request status",addClinic:"Add a clinic",atCap:`Up to ${RECORDS_CLINIC_BATCH_MAX} clinics`,send:n2=>`Send ${n2} ${n2===1?"request":"requests"}`,sending:"Sending…",addToContinue:"Add a clinic to continue",tryAgain:"Try again",remove:name=>`Remove ${name}`,emailToAdd:"Email to add",perClinic:"Per-clinic result",sent:"Sent",notSent:"Not sent",allFailed:"We couldn’t send any of these requests. See the details below and try again.",partial:(created,total,failed)=>`${created} of ${total} requests sent. ${failed} couldn’t be sent.`,allSent:created=>`${created} ${created===1?"request":"requests"} sent.`,responded:(responded,total)=>`${responded} of ${total} ${total===1?"clinic":"clinics"} responded`});var CLINIC_FORM_SEARCH_LIMIT=25,CLINIC_FORM_RESULTS_STEP=5;function useVisibleClinics(clinics){let[state,setState]=react.useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=react.useCallback(()=>{setState(previous=>({list:clinics,shown:(previous.list===clinics?previous.shown:CLINIC_FORM_RESULTS_STEP)+CLINIC_FORM_RESULTS_STEP}))},[clinics]);return{visible:clinics.slice(0,shown),hasMore:clinics.length>shown,showMore:showMore}}var SignatureUploadLegError=class extends Error{constructor(){super("Signature upload failed"),this.name="SignatureUploadLegError"}};function isSignatureUploadLegFailure(error){return error instanceof SignatureUploadLegError}function renderClinicScope(copy,owner,pet,clinic){let fields={owner_name:owner,pet_name:pet,clinic_name:clinic},unknown=false,text4=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text4)?null:text4}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinic,setClinic]=react.useState(null),[email2,setEmail]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[created,setCreated]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),attempt=react.useRef(null),captureAbort=react.useRef(null),lifetime=react.useRef(0);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,attempt.current=null,captureAbort.current?.abort()}),[controller]),react.useEffect(()=>{let live=true;return setCopy(null),attempt.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let invalidate=()=>{attempt.current=null,setError(null)},clinicName=clinic?.name??query.trim(),scope=copy?renderClinicScope(copy,ownerName.trim(),props.petName,clinicName):null,needsEmail=clinicNeedsEmail(clinic),results=useVisibleClinics(clinics),ready=!!(copy&&scope&&ownerName.trim()&&props.petName.trim()&&clinicName&&(!needsEmail||/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email2.trim()))&&capture),search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},submit=async()=>{if(locked.current||created||!ready||!copy||!scope||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(!attempt.current){captureAbort.current=new AbortController;let signature=await capture({petRef:props.petRef,petName:props.petName,ownerName:ownerName.trim(),clinicName:clinicName,authorizationVersion:copy.authorizationVersion,scopeText:scope,signal:captureAbort.current.signal});if(!current()||signature===null)return;let target=clinic&&(!needsEmail||clinic.emailStatus==="none")?{clinicId:clinic.id}:{clinicFreeText:clinicName};attempt.current={petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,...target,...needsEmail?{clinicEmail:email2.trim().toLowerCase()}:{},...signature.signatureId!==void 0?{signatureId:signature.signatureId}:{signaturePngBase64:signature.signaturePngBase64},idempotencyKey:keyFactory.current()}}if(!current())return;let result=await controller.createClinicRequest(attempt.current);if(!current())return;if(!result.ok){setError(result.error);return}if(result.value.petRef!==props.petRef){setError(makeEverfurError("internalError"));return}setCreated(result.value),attempt.current=null,props.onCreated?.(result.value)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}};return{ownerName:ownerName,query:query,clinic:clinic,email:email2,clinics:clinics,copy:copy,scope:scope,error:error,busy:busy,searching:searching,created:created,ready:ready,needsEmail:needsEmail,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0&&clinic===null?recent:[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(null),setEmail(""),setQueryValue(value))},setEmail(value){locked.current||(invalidate(),setEmail(value))},selectClinic(value){locked.current||(invalidate(),generation.current+=1,setSearching(false),setClinics([]),setClinic(value),setQueryValue(value.name),setEmail(""))},invalidate:invalidate,search:search,submit:submit,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var EMAIL2=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function draftName(draft){return draft.clinic?.name??draft.freeText??""}function draftNeedsEmail(draft){return clinicNeedsEmail(draft.clinic)}function useClinicBatchForm(props,controller,batchClient,capture,registerSignature){let[ownerName,setOwner]=react.useState(props.ownerName),[query,setQueryValue]=react.useState(""),[clinics,setClinics]=react.useState([]),[recent,setRecent]=react.useState([]),[drafts,setDrafts]=react.useState([]),[copy,setCopy]=react.useState(null),[error,setError]=react.useState(null),[busy,setBusy]=react.useState(false),[searching,setSearching]=react.useState(false),[outcome,setOutcome]=react.useState(null),[group,setGroup]=react.useState(null),[copyAttempt,setCopyAttempt]=react.useState(0),active=react.useRef(false),locked=react.useRef(false),generation=react.useRef(0),lifetime=react.useRef(0),keyFactory=react.useRef(defaultIdempotencyKeyFactory()),signature=react.useRef(null),captureAbort=react.useRef(null);react.useEffect(()=>(active.current=true,locked.current=false,setBusy(false),()=>{active.current=false,lifetime.current+=1,generation.current+=1,signature.current=null,captureAbort.current?.abort()}),[controller,batchClient]),react.useEffect(()=>{let live=true;return setCopy(null),signature.current=null,controller.getAuthorizationCopy().then(result=>{live&&(result.ok?(setCopy(result.value),setError(null)):setError(result.error))}).catch(()=>{live&&setError(makeEverfurError("internalError"))}),()=>{live=false}},[controller,copyAttempt]),react.useEffect(()=>{let live=true;return setRecent([]),controller.recentClinics({limit:5}).then(result=>{live&&result.ok&&setRecent(result.value.clinics)}).catch(()=>{}),()=>{live=false}},[controller]);let results=useVisibleClinics(clinics),invalidate=()=>{signature.current=null,setError(null)},names=drafts.map(draftName),pet=petNameOr(props.petName),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),pet,name)):[],scopeText=scopes.every(s=>s!==null)?scopes.join(`\n\n`):null,draftsReady=drafts.length>0&&drafts.every(draft=>!draftNeedsEmail(draft)||EMAIL2.test(draft.email.trim())),atCap=drafts.length>=RECORDS_CLINIC_BATCH_MAX,ready=!!(copy&&scopeText&&ownerName.trim()&&draftsReady&&capture)&&outcome===null,search=async()=>{if(locked.current)return;let revision=++generation.current;setSearching(true);try{let result=await controller.searchClinics({query:query.trim(),limit:CLINIC_FORM_SEARCH_LIMIT});if(!active.current||revision!==generation.current)return;result.ok?(setClinics(result.value.clinics),setError(null)):setError(result.error)}catch{active.current&&revision===generation.current&&setError(makeEverfurError("internalError"))}finally{active.current&&revision===generation.current&&setSearching(false)}},add=draft=>{locked.current||atCap||outcome!==null||draft.clinic!==null&&drafts.some(d=>d.clinic?.id===draft.clinic?.id)||(invalidate(),setDrafts(current=>[...current,{...draft,key:keyFactory.current(),idempotencyKey:keyFactory.current()}]),setClinics([]),setQueryValue(""))},submit=async()=>{if(locked.current||outcome!==null||!ready||!copy||!scopeText||!capture)return;locked.current=true;let run=lifetime.current,current=()=>active.current&&lifetime.current===run;setBusy(true),setError(null);try{if(signature.current===null){captureAbort.current=new AbortController;let captured=await capture({petRef:props.petRef,petName:pet,ownerName:ownerName.trim(),clinicName:names.join(", "),authorizationVersion:copy.authorizationVersion,scopeText:scopeText,signal:captureAbort.current.signal});if(!current()||captured===null)return;if(signature.current=captured,captured.signaturePngBase64!==void 0&®isterSignature!==void 0){let abort=captureAbort.current;try{let registered=await registerSignature(captured.signaturePngBase64,abort.signal);if(!current())return;signature.current={signatureId:registered.signatureId}}catch(registrationError){if(!isSignatureUploadLegFailure(registrationError)||abort.signal.aborted)throw registrationError;if(!current())return}}}let signed=signature.current,items=drafts.map(draft=>({...draft.clinic!==null&&(!draftNeedsEmail(draft)||draft.clinic.emailStatus==="none")?{clinicId:draft.clinic.id}:{clinicFreeText:draftName(draft)},...draftNeedsEmail(draft)?{clinicEmail:draft.email.trim().toLowerCase()}:{},...signed.signatureId!==void 0?{signatureId:signed.signatureId}:{signaturePngBase64:signed.signaturePngBase64},idempotencyKey:draft.idempotencyKey})),result=await batchClient.createClinicRequestBatch({petRef:props.petRef,ownerName:ownerName.trim(),authorizationVersion:copy.authorizationVersion,clinics:items});if(!current())return;if(!result.ok){setError(result.error);return}setOutcome(result.value),props.onCreated?.(result.value),loadGroup(result.value.requestGroupId,run)}catch{current()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,current()&&setBusy(false)}},loadGroup=async(requestGroupId,run)=>{try{let result=await controller.getRequestGroup(requestGroupId);if(!active.current||lifetime.current!==run)return;result.ok&&result.value.petRef===props.petRef&&setGroup(result.value)}catch{}},refreshGroup=async()=>{outcome===null||locked.current||await loadGroup(outcome.requestGroupId,lifetime.current)};return{ownerName:ownerName,query:query,clinics:clinics,copy:copy,scopeText:scopeText,error:error,busy:busy,searching:searching,drafts:drafts,outcome:outcome,group:group,ready:ready,atCap:atCap,visibleClinics:results.visible,hasMoreClinics:results.hasMore,showMoreClinics:results.showMore,recent:clinics.length===0?recent.filter(clinic=>!drafts.some(d=>d.clinic?.id===clinic.id)):[],setOwnerName(value){locked.current||(invalidate(),setOwner(value))},setQuery(value){locked.current||(generation.current+=1,setSearching(false),setClinics([]),setQueryValue(value))},search:search,addClinic(clinic){add({clinic:clinic,freeText:null,email:""})},addFreeText(){let name=query.trim();name.length!==0&&add({clinic:null,freeText:name,email:""})},setDraftEmail(key,email2){locked.current||(invalidate(),setDrafts(current=>current.map(draft=>draft.key===key?{...draft,email:email2}:draft)))},removeDraft(key){locked.current||outcome!==null||(invalidate(),setDrafts(current=>current.filter(draft=>draft.key!==key)))},submit:submit,refreshGroup:refreshGroup,retryCopy(){setError(null),setCopyAttempt(value=>value+1)}}}var NO_PROPS=/* @__PURE__ */Object.freeze({}),REMEASURE_INTERVAL_MS=100,REMEASURE_ATTEMPTS=20;function readWindowTops(chatTopInWindow,chatTopInParent,chatHeight,windowHeight){return![chatTopInWindow,chatTopInParent,chatHeight,windowHeight].every(Number.isFinite)||chatTopInWindow+chatHeight>windowHeight+1?null:{chatTop:Math.max(0,chatTopInWindow),parentTop:Math.max(0,chatTopInWindow-chatTopInParent)}}function useChatKeyboardOffset(hostOffset,lifts){let hostGiven=typeof hostOffset=="number",probeRef=react.useRef(null),[reading,setReading]=react.useState(null),frame2=react.useRef(null),retry=react.useRef(null),mounted=react.useRef(true),stopRetry=react.useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=react.useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame2.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,reactNative.Dimensions.get("window").height);if(next!==null){setReading(last=>last!==null&&last.chatTop===next.chatTop&&last.parentTop===next.parentTop?last:next);return}attempt>=REMEASURE_ATTEMPTS||(retry.current=setTimeout(()=>{retry.current=null,measureAt(attempt+1)},REMEASURE_INTERVAL_MS))})},[]),onLayout=react.useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame2.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return react.useMemo(()=>{if(!lifts)return{avoidingProps:NO_PROPS,probeRef:null,topInWindow:null};let measured=reading?.parentTop??0;return{avoidingProps:measured>0?{keyboardVerticalOffset:measured,onLayout:onLayout}:{onLayout:onLayout},probeRef:probeRef,topInWindow:reading?.chatTop??null}},[lifts,hostGiven,hostOffset,reading,onLayout])}function KeyboardOffsetProbe({probeRef:probeRef}){return probeRef===null?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{ref:probeRef,collapsable:false,pointerEvents:"none",style:PROBE_STYLE})}var PROBE_STYLE=/* @__PURE__ */Object.freeze({position:"absolute",top:0,left:0,width:0,height:0});function trustedSignatureUploadUrl(value){try{let url=new URL(value);if(url.protocol!=="https:"||url.username||url.password||url.port&&url.port!=="443")return!1;let host=url.hostname.toLowerCase();return host==="s3.amazonaws.com"||host.endsWith(".s3.amazonaws.com")||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3[.-][a-z0-9-]+\.amazonaws\.com$/.test(host)||/^(?:[a-z0-9][a-z0-9.-]*\.)?s3\.dualstack\.[a-z0-9-]+\.amazonaws\.com$/.test(host)||host==="s3-accelerate.amazonaws.com"||host.endsWith(".s3-accelerate.amazonaws.com")||host==="s3-accelerate.dualstack.amazonaws.com"||host.endsWith(".s3-accelerate.dualstack.amazonaws.com")}catch{return false}}var FAILED="Signature upload failed",UPLOAD_TIMEOUT_MS=3e4;function base64ByteLength(base64){let padding=base64.endsWith("==")?2:base64.endsWith("=")?1:0;return Math.floor(base64.length*3/4)-padding}async function registerRnSignature(signaturePngBase64,controller,signal,fetchImpl){let fail=()=>new Error(FAILED),size=base64ByteLength(signaturePngBase64);if(size<=0||signal.aborted)throw fail();let initiated=await controller.initiateSignatureUpload(size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw fail();let form=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))form.append(key,value);form.append("file",{uri:`data:image/png;base64,${signaturePngBase64}`,name:"signature.png",type:"image/png"});let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,UPLOAD_TIMEOUT_MS);try{if(!(await(fetchImpl??fetch)(initiated.value.uploadUrl,{method:"POST",body:form,credentials:"omit",signal:uploadAbort.signal})).ok||signal.aborted)throw fail()}catch{throw signal.aborted?fail():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw fail();return{signatureId:completed.value}}var SIGNATURE_CANVAS=/* @__PURE__ */Object.freeze({width:360,height:120});function blank(width,height){return{width:width,height:height,pixels:new Uint8Array(width*height)}}function stamp(bitmap,cx,cy,radius){for(let dy=-radius;dy<=radius;dy+=1)for(let dx=-radius;dx<=radius;dx+=1){if(dx*dx+dy*dy>radius*radius+radius)continue;let x=cx+dx,y=cy+dy;x<0||y<0||x>=bitmap.width||y>=bitmap.height||(bitmap.pixels[y*bitmap.width+x]=1)}}var MAX_STEPS_PER_STROKE=16384;function padPoint(point,bitmap){let[x,y]=point;if(!Number.isFinite(x)||!Number.isFinite(y))return null;let cx=Math.min(2*bitmap.width,Math.max(-bitmap.width,Math.round(x))),cy=Math.min(2*bitmap.height,Math.max(-bitmap.height,Math.round(y)));return[cx,cy]}function line(bitmap,from,to,radius,budget){let[x0,y0]=from,[x1,y1]=to,dx=Math.abs(x1-x0),dy=-Math.abs(y1-y0),sx=x0<x1?1:-1,sy=y0<y1?1:-1,error=dx+dy,steps=0;for(;steps<budget&&(stamp(bitmap,x0,y0,radius),steps+=1,!(x0===x1&&y0===y1));){let twice=2*error;twice>=dy&&(error+=dy,x0+=sx),twice<=dx&&(error+=dx,y0+=sy)}return steps}function rasterizeStrokes(strokes,penRadius=1){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height);for(let stroke3 of strokes){let points=[];for(let point of stroke3){let clamped=padPoint(point,bitmap);clamped!==null&&points.push(clamped)}if(points.length===0)continue;if(points.length===1){let[x,y]=points[0];stamp(bitmap,x,y,penRadius);continue}let budget=MAX_STEPS_PER_STROKE;for(let i=1;i<points.length&&budget>0;i+=1)budget-=line(bitmap,points[i-1],points[i],penRadius,budget)}return bitmap}var FONT_ORDER="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,'-",FONT_ROWS="ehhvhhhuhhuhhufgggggfuhhhhhuvgguggvvggugggfggnhhfhhhvhhhv44444v72222ichikokihggggggvhrllhhhhpljhhhehhhhheuhhugggehhhliduhhukihfgge11uv444444hhhhhhehhhhha4hhhllrhhha4ahhhha4444v1248gv00e1fhfgguhhhu00fgggf11fhhhf00ehvgf698s8880fhhf1egguhhhh40c444e20622icggikokic44444e00qllhh00uhhhh00ehhhe0uhhugg0fhhf1100mpggg00fge1u88s889600hhhjd00hhha400hhlla00ha4ah00hhf1e00v248vehjlphe4c4444eeh1248vv2421he26aiv22vgu11he68guhhev124888ehhehheehhf12c00000cc0000c48c480000000v000",FONT_DIGITS="0123456789abcdefghijklmnopqrstuv",GLYPH_W=5,GLYPH_H=7,ADVANCE=GLYPH_W+1;function glyphRow(char,row){let index=FONT_ORDER.indexOf(char);return index<0?0:FONT_DIGITS.indexOf(FONT_ROWS.charAt(index*GLYPH_H+row))}function rasterizeTypedName(name){let bitmap=blank(SIGNATURE_CANVAS.width,SIGNATURE_CANVAS.height),text4=name.trim();if(text4.length===0)return bitmap;let chars=[...text4],scale=4;for(;scale>1&&(chars.length*ADVANCE-1)*scale>bitmap.width-8;)scale-=1;let textWidth=(chars.length*ADVANCE-1)*scale,x0=Math.max(0,Math.floor((bitmap.width-textWidth)/2)),y0=Math.floor((bitmap.height-GLYPH_H*scale)/2);return chars.forEach((char,i)=>{let gx=x0+i*ADVANCE*scale;for(let row=0;row<GLYPH_H;row+=1){let bits=glyphRow(char,row);for(let col=0;col<GLYPH_W;col+=1)if((bits>>GLYPH_W-1-col&1)!==0)for(let sy=0;sy<scale;sy+=1)for(let sx=0;sx<scale;sx+=1){let x=gx+col*scale+sx,y=y0+row*scale+sy;x<bitmap.width&&y<bitmap.height&&(bitmap.pixels[y*bitmap.width+x]=1)}}}),bitmap}var BitWriter=class{constructor(){this.bytes=[];this.acc=0;this.count=0}writeBits(value,count){for(this.acc|=value<<this.count,this.count+=count;this.count>=8;)this.bytes.push(this.acc&255),this.acc>>>=8,this.count-=8}writeCode(code,length){let reversed=0;for(let i=0;i<length;i+=1)reversed=reversed<<1|code>>i&1;this.writeBits(reversed,length)}finish(){return this.count>0&&this.bytes.push(this.acc&255),Uint8Array.from(this.bytes)}};function writeLiteral(out,symbol){symbol<144?out.writeCode(48+symbol,8):symbol<256?out.writeCode(400+(symbol-144),9):symbol<280?out.writeCode(symbol-256,7):out.writeCode(192+(symbol-280),8)}var LENGTH_BASE=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258],LENGTH_EXTRA=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],DIST_BASE=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],DIST_EXTRA=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function writeMatch(out,length,distance){let li=LENGTH_BASE.length-1;for(;LENGTH_BASE[li]>length;)li-=1;writeLiteral(out,257+li),LENGTH_EXTRA[li]>0&&out.writeBits(length-LENGTH_BASE[li],LENGTH_EXTRA[li]);let di=DIST_BASE.length-1;for(;DIST_BASE[di]>distance;)di-=1;out.writeCode(di,5),DIST_EXTRA[di]>0&&out.writeBits(distance-DIST_BASE[di],DIST_EXTRA[di])}var WINDOW=32768,MIN_MATCH=3,MAX_MATCH=258,HASH_BITS=15,CHAIN_LIMIT=64;function deflate(input){let out=new BitWriter;out.writeBits(1,1),out.writeBits(1,2);let head=new Int32Array(1<<HASH_BITS).fill(-1),prev=new Int32Array(input.length).fill(-1),hashAt=i2=>(input[i2]<<10^input[i2+1]<<5^input[i2+2])&(1<<HASH_BITS)-1,insert=i2=>{if(i2+MIN_MATCH>input.length)return;let h=hashAt(i2);prev[i2]=head[h],head[h]=i2},i=0;for(;i<input.length;){let bestLength=0,bestDistance=0;if(i+MIN_MATCH<=input.length){let candidate=head[hashAt(i)],chain=0,limit=Math.min(MAX_MATCH,input.length-i);for(;candidate>=0&&chain<CHAIN_LIMIT&&i-candidate<=WINDOW;){let length=0;for(;length<limit&&input[candidate+length]===input[i+length];)length+=1;if(length>bestLength&&(bestLength=length,bestDistance=i-candidate,length===limit))break;candidate=prev[candidate],chain+=1}}if(bestLength>=MIN_MATCH){writeMatch(out,bestLength,bestDistance);for(let k=0;k<bestLength;k+=1)insert(i+k);i+=bestLength}else writeLiteral(out,input[i]),insert(i),i+=1}return writeLiteral(out,256),out.finish()}function adler32(bytes){let a=1,b=0;for(let byte2 of bytes)a=(a+byte2)%65521,b=(b+a)%65521;return(b<<16|a)>>>0}var crcTable=null;function crc32(bytes){if(crcTable===null){crcTable=new Uint32Array(256);for(let n2=0;n2<256;n2+=1){let c=n2;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n2]=c>>>0}}let crc=4294967295;for(let byte2 of bytes)crc=crcTable[(crc^byte2)&255]^crc>>>8;return(crc^4294967295)>>>0}function u32(value){return[value>>>24&255,value>>>16&255,value>>>8&255,value&255]}function chunk(type,data){let typed=Uint8Array.from([...type].map(c=>c.charCodeAt(0))),body=new Uint8Array(typed.length+data.length);return body.set(typed,0),body.set(data,typed.length),[...u32(data.length),...body,...u32(crc32(body))]}var BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function toBase64(bytes){let out="";for(let i=0;i<bytes.length;i+=3){let a=bytes[i],b=i+1<bytes.length?bytes[i+1]:0,c=i+2<bytes.length?bytes[i+2]:0,triple=a<<16|b<<8|c;out+=BASE64.charAt(triple>>18&63)+BASE64.charAt(triple>>12&63),out+=i+1<bytes.length?BASE64.charAt(triple>>6&63):"=",out+=i+2<bytes.length?BASE64.charAt(triple&63):"="}return out}function encodeSignaturePng(bitmap){let{width:width,height:height,pixels:pixels}=bitmap,stride=Math.ceil(width/8)+1,raw=new Uint8Array(stride*height);for(let y=0;y<height;y+=1){let rowStart=y*stride;raw[rowStart]=0,raw.fill(255,rowStart+1,rowStart+stride);for(let x=0;x<width;x+=1)if(pixels[y*width+x]===1){let index=rowStart+1+(x>>3);raw[index]=raw[index]&~(128>>(x&7))}}let compressed=deflate(raw),idat=new Uint8Array(2+compressed.length+4);idat[0]=120,idat[1]=1,idat.set(compressed,2),idat.set(u32(adler32(raw)),2+compressed.length);let ihdr=Uint8Array.from([...u32(width),...u32(height),1,0,0,0,0]),png=Uint8Array.from([137,80,78,71,13,10,26,10,...chunk("IHDR",ihdr),...chunk("IDAT",idat),...chunk("IEND",new Uint8Array(0))]);return toBase64(png)}var SIGNATURE_STROKE_WIDTH=2.6,INK="#111111";function strokeSegments(strokes,scale){let segments=[];return strokes.forEach((stroke3,s)=>{let at=i=>{let p=stroke3[i];return[p[0]/scale,p[1]/scale]};if(stroke3.length===1){let[x,y]=at(0);segments.push({key:`${s}-0`,cx:x,cy:y,length:0,angle:0});return}for(let i=1;i<stroke3.length;i+=1){let[x0,y0]=at(i-1),[x1,y1]=at(i);segments.push({key:`${s}-${i}`,cx:(x0+x1)/2,cy:(y0+y1)/2,length:Math.hypot(x1-x0,y1-y0),angle:Math.atan2(y1-y0,x1-x0)})}}),segments}var MIN_DRAWN_POINTS=8,MIN_MOVE=2;function SignaturePad({onChange:onChange,disabled:disabled=false,mode:controlledMode}){let styles=useStyles4(),[ownMode,setMode]=react.useState("draw"),controlled=controlledMode!==void 0,mode=controlledMode??ownMode,[typed,setTyped]=react.useState(""),[strokes,setStrokes]=react.useState([]),[width,setWidth]=react.useState(0),current=react.useRef([]),drawing=react.useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=react.useRef(scale);scaleRef.current=scale;let disabledRef=react.useRef(disabled);disabledRef.current=disabled,react.useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n2,stroke3)=>n2+stroke3.length,0);callHost(onChange,points>=MIN_DRAWN_POINTS?encodeSignaturePng(rasterizeStrokes(strokes)):null)},[mode,typed,strokes,onChange]);let point=event=>{let{locationX:locationX,locationY:locationY}=event.nativeEvent;return[locationX*scaleRef.current,locationY*scaleRef.current]},commitStroke=()=>{let finished=current.current,inProgress=drawing.current;current.current=[],drawing.current=null,setStrokes(committed=>[...committed.filter(s=>s!==inProgress),finished])},responder=react.useMemo(()=>reactNative.PanResponder.create({onStartShouldSetPanResponder:()=>!disabledRef.current,onMoveShouldSetPanResponder:()=>!disabledRef.current,onPanResponderTerminationRequest:()=>false,onPanResponderGrant:event=>{current.current=[point(event)]},onPanResponderMove:event=>{let next=point(event),last=current.current[current.current.length-1];if(last!==void 0&&Math.abs(last[0]-next[0])<MIN_MOVE&&Math.abs(last[1]-next[1])<MIN_MOVE)return;current.current=[...current.current,next];let previous=drawing.current,trail=current.current;drawing.current=trail,setStrokes(committed=>[...committed.filter(s=>s!==previous),trail])},onPanResponderRelease:()=>commitStroke(),onPanResponderTerminate:()=>commitStroke()}),[]),clear=react.useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=react.useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),shownMode=react.useRef(mode);react.useEffect(()=>{shownMode.current!==mode&&(shownMode.current=mode,current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[mode]);let onLayout=event=>setWidth(event.nativeEvent.layout.width),markPoints=strokes.reduce((n2,stroke3)=>n2+stroke3.length,0);/* @__PURE__ */
|
|
285
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.container,testID:"records-signature-pad",children:[controlled?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.type,style:styles.input,value:typed,maxLength:100,editable:!disabled,autoComplete:"off",autoCorrect:false,onChangeText:value=>{disabledRef.current||setTyped(value)}}):null,
|
|
288
286
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{onLayout:onLayout,style:[styles.canvas,{height:width>0?width/3:120}],accessible:true,accessibilityLabel:CLINIC_REQUEST_COPY.sign,accessibilityRole:"image",testID:"records-signature-canvas",...mode==="draw"?responder.panHandlers:{},children:mode==="type"?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.typedPreview,numberOfLines:1,adjustsFontSizeToFit:true,children:typed.trim()}):strokeSegments(strokes,scale).map(segment=>{let box3=segment.length+SIGNATURE_STROKE_WIDTH;/* @__PURE__ */
|
|
289
287
|
return jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:[styles.segment,{width:box3,left:segment.cx-box3/2,top:segment.cy-SIGNATURE_STROKE_WIDTH/2,transform:[{rotate:`${segment.angle}rad`}]}]},segment.key)})}),
|
|
290
|
-
/* @__PURE__ */jsxRuntime.
|
|
291
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CLINIC_REQUEST_COPY.
|
|
292
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw,accessibilityState:{disabled:disabled},disabled:disabled,onPress:toggle,style:styles.button,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.buttonLabel,children:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw})})]})]})}function useStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles6(theme),[theme])}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({container:{gap:space.sm},label:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary},input:{minHeight:44,padding:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:type.size.body,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:SIGNATURE_STROKE_WIDTH,borderRadius:SIGNATURE_STROKE_WIDTH/2,backgroundColor:INK},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:INK,paddingHorizontal:space.md},actions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},button:{minHeight:44,paddingHorizontal:space.md,justifyContent:"center",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,backgroundColor:color.surface},buttonLabel:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary}})}function EverfurClinicRequestBatch(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
288
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.hint,testID:"records-signature-hint",children:markPoints>=MIN_DRAWN_POINTS||mode==="type"?" ":CLINIC_REQUEST_COPY.drawHint}),
|
|
289
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[mode==="type"?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:CLINIC_REQUEST_COPY.clearA11y,accessibilityState:{disabled:disabled},disabled:disabled,onPress:clear,style:styles.button,testID:"records-signature-clear",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.buttonLabel,children:CLINIC_REQUEST_COPY.clear})}),controlled?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw,accessibilityState:{disabled:disabled},disabled:disabled,onPress:toggle,style:styles.button,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.buttonLabel,children:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw})})]})]})}function useStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles6(theme),[theme])}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme;return reactNative.StyleSheet.create({container:{gap:space.sm},label:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary},input:{minHeight:44,padding:space.sm,borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...face(theme,"regular"),fontSize:type.size.body,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},canvas:{width:"100%",backgroundColor:"#ffffff",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,overflow:"hidden",justifyContent:"center"},segment:{position:"absolute",height:SIGNATURE_STROKE_WIDTH,borderRadius:SIGNATURE_STROKE_WIDTH/2,backgroundColor:INK},typedPreview:{textAlign:"center",fontSize:32,fontStyle:"italic",fontWeight:"700",color:INK,paddingHorizontal:space.md},hint:{...face(theme,"regular"),fontSize:type.size.tiny,color:color.text.muted},actions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},button:{minHeight:44,paddingHorizontal:space.md,justifyContent:"center",borderWidth:1,borderColor:color.borderHairlineGreen,borderRadius:radius.sm,backgroundColor:color.surface},buttonLabel:{...face(theme,"regular"),fontSize:type.size.body,color:color.text.primary}})}function EverfurClinicRequestBatch(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
293
290
|
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}var IOS=reactNative.Platform.OS==="ios";function clinicDetail(clinic){return[clinic.address,clinic.phone].filter(Boolean).join(", ")}function BatchBody(props){let runtimeController=useEverfurRecordsClinic(),runtimeBatch=useEverfurRecordsClinicBatch(),controller=props.controller??runtimeController,[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),register=react.useCallback((image,signal)=>registerRnSignature(image,controller,signal),[controller]),form=useClinicBatchForm(props,controller,props.batchClient??runtimeBatch,props.onCaptureSignature??padCapture,props.onCaptureSignature?void 0:register),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),styles=useScreenStyles(),local=useLocalStyles2(),insets=reactNativeSafeAreaContext.useSafeAreaInsets(),keyboard=useChatKeyboardOffset(void 0,IOS),sendLabel=form.busy?CLINIC_BATCH_COPY.sending:form.drafts.length===0?CLINIC_BATCH_COPY.addToContinue:form.error?CLINIC_BATCH_COPY.tryAgain:CLINIC_BATCH_COPY.send(form.drafts.length),title=form.outcome?CLINIC_BATCH_COPY.resultTitle:CLINIC_BATCH_COPY.title,canSearch=!form.busy&&!form.searching&&form.query.trim().length>=2,search=()=>{canSearch&&(reactNative.Keyboard.dismiss(),form.search())},option=(key,clinic)=>{let detail=clinicDetail(clinic);/* @__PURE__ */
|
|
294
291
|
return jsxRuntime.jsxs(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:[clinic.name,detail].filter(Boolean).join(", "),accessibilityState:{disabled:form.busy},disabled:form.busy,onPress:()=>form.addClinic(clinic),style:[local.option,form.busy?styles.pillDisabled:null],children:[
|
|
295
292
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.optionName,children:clinic.name}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:detail}):null]},key)};/* @__PURE__ */
|
|
@@ -314,7 +311,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:local.option,accessible:true,acce
|
|
|
314
311
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.block,children:[
|
|
315
312
|
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:form.atCap?CLINIC_BATCH_COPY.atCap:CLINIC_BATCH_COPY.addClinic}),!form.atCap&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
316
313
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:styles.field,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,autoCorrect:false,autoCapitalize:"words",returnKeyType:"search",onSubmitEditing:search,onChangeText:form.setQuery,testID:"records-batch-search-input"}),
|
|
317
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.search,kind:"outline",disabled:!canSearch,onPress:search,testID:"records-batch-search"}),form.query.trim().length>0&&form.clinics.length===0&&!form.searching?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_BATCH_COPY.addClinic,kind:"link",disabled:form.busy,onPress:form.addFreeText,testID:"records-batch-add-typed"}):null,form.searching?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading}):null,form.recent.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:styles.fieldLabel,children:CLINIC_REQUEST_COPY.recentlyUsed}):null,form.recent.map(clinic=>option(`recent-${clinic.id}`,clinic)),form.visibleClinics.map(clinic=>option(clinic.id,clinic)),form.hasMoreClinics?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.moreClinics,kind:"link",disabled:form.busy,onPress:form.showMoreClinics}):null]})]}),
|
|
314
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.search,kind:"outline",disabled:!canSearch,onPress:search,testID:"records-batch-search"}),form.query.trim().length>0&&form.clinics.length===0&&!form.searching?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_BATCH_COPY.addClinic,kind:"link",disabled:form.busy,onPress:form.addFreeText,testID:"records-batch-add-typed"}):null,form.searching?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading}):null,form.recent.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:styles.fieldLabel,children:CLINIC_REQUEST_COPY.recentlyUsed}):null,form.recent.map(clinic=>option(`recent-${clinic.id}`,clinic)),form.visibleClinics.map(clinic=>option(clinic.id,clinic)),form.hasMoreClinics?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:CLINIC_REQUEST_COPY.moreClinics,kind:"link",disabled:form.busy,onPress:form.showMoreClinics,testID:"records-clinic-results-more"}):null]})]}),
|
|
318
315
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.scopeCard,accessibilityRole:"summary",testID:"records-batch-scope",children:[
|
|
319
316
|
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?form.drafts.length>0&&form.ownerName.trim()?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeText,testID:"records-batch-scope-text",children:form.scopeText??makeEverfurError("internalError").displayMessage}):null:!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading})]}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:styles.bodyText,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error.displayMessage})}),!form.copy&&form.error&&/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:form.retryCopy})]}),
|
|
320
317
|
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({header:{flexDirection:"row",alignItems:"center",gap:space.md,paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md,...slotBox(theme.slots.header)},title:{flex:1,...text4(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.header)},close:{minHeight:touch,minWidth:touch,alignItems:"center",justifyContent:"center"},closeLabel:text4(type.size.body,type.lineHeight.snug,color.linkInk,"bold"),content:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.lg},lead:text4(type.size.body,type.lineHeight.normal,color.text.muted),block:{gap:space.sm},sectionTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},option:{minHeight:touch,justifyContent:"center",gap:space.xs/2,borderRadius:radius.md,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.md,paddingVertical:space.sm+space.xs/2,...slotBox(theme.slots.card,1)},optionName:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...slotText(theme.slots.card)},draft:{gap:space.sm,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.md,...slotBox(theme.slots.card,1)},remove:{alignSelf:"flex-start",minHeight:touch,paddingHorizontal:0},scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.sm,...slotBox(theme.slots.card,1)},scopeText:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),...slotText(theme.slots.card)},footer:{paddingHorizontal:space.lg,paddingTop:space.md,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background}})}var RECORDS_CONSENT_COPY=/* @__PURE__ */Object.freeze({scopeHeading:"What we ask for",scopeBody:"You’re asking your pet’s clinic to release their medical records to Everfur, on your behalf, so we can organize them for you.",whatWeDo:/* @__PURE__ */Object.freeze(["We email the clinic a signed copy of this authorization.","When records arrive, our team reviews them before they appear in your app.","You can revoke this request at any time."]),retentionNote:"We keep the records you receive so you always have them. See our Privacy Policy for how records are stored and used.",authorizeLabel:petName=>`I’m ${petNameOr(petName)}’s owner. I authorize Everfur to request these records on my behalf.`,missingSignatureError:"Please add your signature before submitting.",missingDraftError:"Something went wrong with your selection. Please go back and pick the clinic again.",newClinicDirectSendNote:"We’ll email this clinic directly to request your pet’s medical records. Clinics usually reply within a week.",titleFreeText:"Check and send",titleDirectory:"Check and send",leadWeb:petName=>`The clinic gets a secure request, with your permission to release ${petNameOr(petName)}’s records to Everfur.`,leadNative:"The clinic gets a secure request, with your permission.",whatHappensNext:"What happens next",whatHappensNextBody:"Most clinics respond within 3 to 5 business days. We follow up automatically, and you can cancel any time before the records arrive.",noEmailNote:(petName,clinicName)=>`We don’t have an email on file for ${clinicName}. Add it so we can request ${petNameOr(petName)}’s records.`,emailLabel:"Clinic email for records",emailPlaceholder:"records@clinic.com",emailRequired:"Add the clinic’s records email to send the request.",emailInvalid:"That email doesn’t look right. Check it and try again.",reuseSignature:"Reuse a previous signature",reuseHint:"…or sign again below",reuseTileA11y:"Use this earlier signature",reuseTileSelectedA11y:"Earlier signature, selected",signType:"Type your name to sign",signDraw:"Sign with your finger",clear:"Clear",clearA11y:"Clear signature",fullName:"Your full name",fullNamePlaceholder:"Jane Doe",toType:"Can’t draw? Type your name instead",toDraw:"Draw your signature instead",signatureHint:clinicName=>`Your signature is added to the authorization sent to ${clinicName}.`,submit:"Send request",submitting:"Sending…"});var FACT_VALUE_FIELD="value_text",FACT_ENTITY_TYPE_MAX=64,FACT_CANONICAL_KEY_MAX=512;function isFactReviewerLocked(error){return error!==null&&error.httpStatus===409&&!isRecordsConsentRequired(error)}var FACT_FIELD_BY_KIND=/* @__PURE__ */Object.freeze({num:"value_num",date:"value_date",bool:"value_bool",text:FACT_VALUE_FIELD}),NUMERIC=/^[+-]?(?:\d+\.?\d*|\.\d+)$/,ISO_DATE=/^\d{4}-\d{2}-\d{2}$/;function inferFactValueKind(value){if(value==null)return"text";let trimmed=value.trim();return NUMERIC.test(trimmed)?"num":ISO_DATE.test(trimmed)&&!Number.isNaN(Date.parse(trimmed))?"date":trimmed==="true"||trimmed==="false"?"bool":"text"}function factCorrectionFor(original,corrected){let next=corrected.trim(),kind=inferFactValueKind(original);if(kind==="num"&&NUMERIC.test(next)){let parsed=Number(next);if(Number.isFinite(parsed))/* @__PURE__ */return Object.freeze({[FACT_FIELD_BY_KIND.num]:parsed})}return kind==="date"&&ISO_DATE.test(next)&&!Number.isNaN(Date.parse(next))?/* @__PURE__ */Object.freeze({[FACT_FIELD_BY_KIND.date]:next}):/* @__PURE__ */Object.freeze(kind==="bool"&&(next==="true"||next==="false")?{[FACT_FIELD_BY_KIND.bool]:next==="true"}:{[FACT_FIELD_BY_KIND.text]:next})}var str2=/* @__PURE__ */zod.z.string().nullish(),num=/* @__PURE__ */zod.z.number().nullish(),pointSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,ref_low:num,ref_high:num,status:str2,source_clinic:str2,source_doc_id:str2,doc_id:str2,reviewed:/* @__PURE__ */zod.z.boolean().nullish()}),latestSchema=/* @__PURE__ */zod.z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,status:str2}),markerSchema=/* @__PURE__ */zod.z.object({marker_id:/* @__PURE__ */zod.z.string().min(1),canonical_name:str2,name:str2,loinc_code:str2,canonical_unit:str2,unit:str2,panel_name:str2,panel:str2,meaning_text:str2,meaning:str2,latest:/* @__PURE__ */latestSchema.nullish(),trajectory:str2,points:/* @__PURE__ */zod.z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */zod.z.object({total_markers:/* @__PURE__ */zod.z.number().int().nonnegative(),in_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */zod.z.number().int().nonnegative(),unknown_count:/* @__PURE__ */zod.z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */zod.z.object({markers:/* @__PURE__ */zod.z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */zod.z.string().optional(),featured_marker_id:str2});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
@@ -333,7 +330,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
333
330
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:IOS2?"padding":void 0,style:styles.body,...keyboard.avoidingProps,children:[
|
|
334
331
|
/* @__PURE__ */jsxRuntime.jsx(KeyboardOffsetProbe,{probeRef:keyboard.probeRef}),
|
|
335
332
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,keyboardShouldPersistTaps:"handled",keyboardDismissMode:IOS2?"interactive":"on-drag",testID:"records-consent",children:[
|
|
336
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,testID:"records-consent-lead",children:RECORDS_CONSENT_COPY.
|
|
333
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.lead,testID:"records-consent-lead",children:RECORDS_CONSENT_COPY.leadWeb(petName)}),
|
|
337
334
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.scopeCard,accessibilityRole:"summary",children:[
|
|
338
335
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.scopeHeading}),
|
|
339
336
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.scopeBody}),
|
|
@@ -356,18 +353,19 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
356
353
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,contentContainerStyle:local.gallery,children:form.signatures.map(sig=>{let selected=form.reuseSignatureId===sig.signatureId;/* @__PURE__ */
|
|
357
354
|
return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>form.pickReuseSignature(selected?null:sig.signatureId),accessibilityRole:"button",accessibilityLabel:selected?RECORDS_CONSENT_COPY.reuseTileSelectedA11y:RECORDS_CONSENT_COPY.reuseTileA11y,style:[local.tile,selected?local.tileSelected:null],testID:`records-consent-reuse-${sig.signatureId}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:{uri:sig.previewUrl},style:local.tileImage,resizeMode:"contain",accessibilityIgnoresInvertColors:true})},sig.signatureId)})}),
|
|
358
355
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:RECORDS_CONSENT_COPY.reuseHint})]}):null,
|
|
359
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.signatureHeader,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:mode==="type"?
|
|
360
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
361
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
362
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:RECORDS_CONSENT_COPY.signatureHint(form.clinicName)})]}),
|
|
356
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.signatureHeader,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:mode==="type"?CLINIC_REQUEST_COPY.type:CLINIC_REQUEST_COPY.draw})}),
|
|
357
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setMode(m=>m==="draw"?"type":"draw"),disabled:busy,accessibilityRole:"button",accessibilityLabel:mode==="draw"?RECORDS_CONSENT_COPY.toType:RECORDS_CONSENT_COPY.toDraw,accessibilityState:{disabled:busy},style:local.modeToggle,testID:"records-consent-sign-mode-toggle",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.modeToggleText,children:mode==="draw"?RECORDS_CONSENT_COPY.toType:RECORDS_CONSENT_COPY.toDraw})}),
|
|
358
|
+
/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:onPadChange,disabled:busy,mode:mode}),
|
|
359
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:RECORDS_CONSENT_COPY.signatureHint(form.clinicName)}),form.signatureLastMissing?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,testID:"records-consent-signature-required",children:RECORDS_CONSENT_COPY.missingSignatureError}):null]}),
|
|
363
360
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.nextCard,accessibilityRole:"summary",testID:"records-consent-next",children:[
|
|
364
361
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
365
362
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:form.error})}):null,form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
366
|
-
/* @__PURE__ */jsxRuntime.
|
|
367
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
363
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footer,testID:"records-consent-footer",children:[onBack?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:BACK_LABEL,kind:"link",disabled:busy,onPress:onBack,style:local.cancel,testID:"records-consent-cancel"}):null,
|
|
364
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onPress:()=>{reactNative.Keyboard.dismiss(),form.submit()},style:local.submit,testID:"records-consent-submit"})]})]}),
|
|
365
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xl+space.xs,gap:space.lg+space.xs/2},lead:text4(type.size.body,type.lineHeight.normal,color.text.muted),scopeCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(theme.slots.card,1)},nextCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.sm,...slotBox(theme.slots.card)},scopeHeading:{...text4(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(theme.slots.card)},scopeBody:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),...slotText(theme.slots.card)},bullets:{gap:space.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},check:{...text4(type.size.body,type.lineHeight.normal,color.brandInk,"bold")},bulletText:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},retentionRow:{paddingTop:space.xs,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},retentionText:text4(type.size.tiny,type.lineHeight.normal,color.text.muted),serverScope:{...text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),paddingTop:space.xs},toggle:{flexDirection:"row",alignItems:"flex-start",gap:space.md,borderRadius:radius.lg-space.xs,borderWidth:hairline,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md+space.xs/2},toggleChecked:{borderColor:color.brandInk,backgroundColor:color.brandSoft},box:{width:space.xl,height:space.xl,borderRadius:radius.xs+1,borderWidth:1.6,borderColor:color.brandInk,alignItems:"center",justifyContent:"center",backgroundColor:color.surface},boxChecked:{backgroundColor:color.brandInk},boxCheck:{...text4(type.size.body,type.lineHeight.tight,color.surface,"bold")},toggleLabel:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"bold")},block:{gap:space.sm},signatureBlock:{gap:space.sm},gallery:{gap:space.sm,paddingVertical:space.xs},tile:{width:space.xxl*3+space.lg,height:space.xxl+space.lg+space.sm,borderRadius:radius.sm,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,overflow:"hidden"},tileSelected:{borderColor:color.brandInk,borderWidth:2},tileImage:{width:"100%",height:"100%"},signatureHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},modeToggle:{minHeight:space.xxl+space.md,alignItems:"center",justifyContent:"center"},modeToggleText:{...text4(type.size.bodyTight,type.lineHeight.snug,color.linkInk,"bold"),textDecorationLine:"underline"},footer:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.sm,paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.xxl,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background},cancel:{flexGrow:0,flexShrink:0},submit:{flexGrow:1,flexShrink:1,flexBasis:space.xxl*4,minWidth:0,minHeight:space.xxl+space.lg+space.xs+space.xs/2}})}function fileHandleFromMedia(source){let handle={uri:source.uri,mimeType:source.mimeType},size=mediaByteSize(source);return size!==null&&(handle.sizeBytes=size),/* @__PURE__ */Object.freeze(handle)}function mediaByteSize(source){let candidate=source.byteSize??source.sizeBytes;return typeof candidate=="number"&&Number.isFinite(candidate)&&candidate>=0?candidate:null}function captureOptionsFor(mode,maxDurationSeconds){/* @__PURE__ */
|
|
368
366
|
return Object.freeze({mode:mode})}function isCaptureAvailable(camera){return camera!=null&&camera.isAvailable===true}function markerStatusTone(status){return status==="above"||status==="below"?"critical":status==="in_range"?"positive":"neutral"}function markerStatusSpoken(status){switch(status){case"above":return"above the reference range";case"below":return"below the reference range";case"in_range":return"within range";default:return"no reference range on file"}}function rangePhrase(point){return point.refLow!==null&&point.refHigh!==null?`, reference range ${point.refLow} to ${point.refHigh}`:point.refLow!==null?`, reference range at least ${point.refLow}`:point.refHigh!==null?`, reference range up to ${point.refHigh}`:""}function formatReferenceRange(point,unit){let u=unit?` ${unit}`:"";return point.refLow!==null&&point.refHigh!==null?`${point.refLow}-${point.refHigh}${u}`:point.refLow!==null?`≥ ${point.refLow}${u}`:point.refHigh!==null?`≤ ${point.refHigh}${u}`:"-"}function markerPointSpoken(marker,point){let reviewed=point.reviewed?", reviewed by our team":"",clinic=point.sourceClinic?`, from ${point.sourceClinic}`:"";return`${formatRecordsDate(point.at)}: ${formatMarkerReading(point.value,marker.unit,point.qualitativeResult)}, ${markerStatusSpoken(point.status)}${rangePhrase(point)}${clinic}${reviewed}`}function markersFeaturedFirst(markers,featuredMarkerId){if(!featuredMarkerId)return markers;let at=markers.findIndex(marker=>marker.markerId===featuredMarkerId);return at<=0?markers:[markers[at],...markers.slice(0,at),...markers.slice(at+1)]}var MARKER_CAROUSEL_MAX_DOTS=7;function markerDotWindow(activeIndex,total,max=MARKER_CAROUSEL_MAX_DOTS){let count=Math.max(0,Math.min(total,max)),start=total<=max?0:Math.max(0,Math.min(activeIndex-Math.floor(max/2),total-max));return Array.from({length:count},(_,i)=>start+i)}function lead(petName){return petName?.trim()||"my pet"}function clause(text4){let t=text4.trim();return/[.!?]$/.test(t)?t:`${t}.`}function buildMarkerAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",parts=[`I'm looking at ${lead(petName)}'s ${name}`],stats=[input.latestValueText?.trim(),input.statusText?.trim(),input.trajectoryText?.trim()].filter(Boolean).join(", ");return parts[0]+=stats?`: ${stats}.`:".",input.meaningText?.trim()&&parts.push(clause(input.meaningText)),parts.push(`What does this trend tell me, and should I do anything differently for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"marker",id:input.markerId,payload:{marker:name,...input.statusText?.trim()?{status:input.statusText.trim()}:{}}}}}function buildMarkerSummaryAskPrompt(petName,summary,petId){let{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary;if(totalMarkers===0)return{prompt:`I'm looking at ${lead(petName)}'s lab markers, but there aren't any on file yet. What lab work is worth running for ${lead(petName)}?`,entityRef:{type:"marker_summary",id:petId,payload:{total:0}}};let tail=unknownCount>0?`, ${unknownCount} without a reference range`:"";return{prompt:`I'm looking at ${lead(petName)}'s lab markers: ${totalMarkers} total, ${inRangeCount} in range, ${outOfRangeCount} out of range${tail}. What should I focus on?`,entityRef:{type:"marker_summary",id:petId,payload:{total:totalMarkers,inRange:inRangeCount,outOfRange:outOfRangeCount,unknown:unknownCount}}}}function buildMarkerReadingAskPrompt(petName,input){let name=input.canonicalName.trim()||"a lab marker",bits=[`${name}: ${input.valueText.trim()}`];input.collectedAt?.trim()&&bits.push(`collected ${input.collectedAt.trim()}`),input.sourceClinic?.trim()&&bits.push(`from ${input.sourceClinic.trim()}`),input.referenceText?.trim()&&bits.push(`reference range ${input.referenceText.trim()}`),input.flagged&&bits.push(`flagged ${input.flagged}`);let payload={marker:name};return input.flagged&&(payload.status=input.flagged),input.reviewed!==void 0&&(payload.reviewed=input.reviewed),{prompt:`I'm looking at ${lead(petName)}'s ${bits.join(", ")}. What does this mean, and should I be concerned?`,entityRef:{type:"lab_reading",id:input.entityId,payload:payload}}}function buildRecordsRequestAskPrompt(petName,input,requestId2){let clinic=input.clinicName?.trim(),held=input.heldItemCount??0,heldPhrase=held>0?`, ${held} fact${held===1?"":"s"} being verified`:"";return{prompt:`I'm looking at ${lead(petName)}'s records request${clinic?` to ${clinic}`:""}, status: ${input.statusLabel.trim()}${heldPhrase}. What does this status mean, and what happens next?`,entityRef:{type:"records_request",id:requestId2,payload:{status:input.status,held:held,...clinic?{clinic:clinic}:{}}}}}var ENTITY_TYPE_MAP=/* @__PURE__ */Object.freeze({vaccination:"vaccine",medication:"medication",body_weight:"weight",vital:"weight"});function buildEntityRowAskPrompt(petName,input,entityType,entityId){let kind=input.entityTypeLabel.trim()||"record",title=input.title.trim()||kind,detail=input.detail?.trim();return{prompt:`I'm looking at ${lead(petName)}'s ${kind.toLowerCase()}: ${title}${detail?`, ${detail}`:""}. What does this mean, and what should I keep on top of for ${lead(petName)}?`,entityRef:{type:ENTITY_TYPE_MAP[entityType]??entityType,id:entityId,payload:{kind:kind,title:title,...detail?{detail:detail}:{}}}}}function buildUpcomingCareAskPrompt(petName,items,petId){let list=items.filter(i=>i.label.trim()),entityRef={type:"upcoming_care",id:petId};if(list.length===0)return{prompt:`I'm looking at ${lead(petName)}'s upcoming care, but nothing is scheduled yet. What preventive care and checkups should ${lead(petName)} be on?`,entityRef:entityRef};let named=[...list].sort((a,b)=>(a.tone==="overdue"?0:1)-(b.tone==="overdue"?0:1)).slice(0,4).map(i=>i.relativeText.trim()?`${i.label.trim()} (${i.relativeText.trim().toLowerCase()})`:i.label.trim());return{prompt:`I'm looking at ${lead(petName)}'s upcoming care: ${named.join(", ")}. What should I prioritize for ${lead(petName)}, and how do I stay on top of these?`,entityRef:entityRef}}function buildPhysicalExamAskPrompt(petName,input,examId){let parts=[`I'm looking at ${lead(petName)}'s physical exam${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`],abnormal=input.abnormal.filter(a=>a.system.trim());return abnormal.length>0?(parts.push(`Abnormal: ${abnormal.slice(0,6).map(a=>`${a.system.trim()}: ${a.finding.trim()}`).join("; ")}.`),parts.push(`What do these findings mean, and what should I follow up on for ${lead(petName)}?`)):parts.push(`Everything examined came back normal. What does this tell me about ${lead(petName)}'s health?`),{prompt:parts.join(" "),entityRef:{type:"physical_exam",id:examId}}}function buildVisitNoteAskPrompt(petName,input,noteId){let parts=[`I'm looking at ${lead(petName)}'s visit notes${input.observedOn?.trim()?` from ${input.observedOn.trim()}`:""}.`];for(let s of input.sections.filter(section=>section.text.trim()).slice(0,3))parts.push(`${s.label.trim()||"Note"}: ${clause(s.text)}`);return parts.push(`Can you summarize what happened and what I should follow up on for ${lead(petName)}?`),{prompt:parts.join(" "),entityRef:{type:"visit",id:noteId}}}function buildConflictAskPrompt(petName,input,conflictId){let scope=input.scopeLabel.trim()||"a detail",cands=input.candidates.filter(c=>c.value.trim()),rendered=cands.slice(0,3).map(c=>`"${c.value.trim()}"${c.clinicName?.trim()?` (${c.clinicName.trim()})`:""}`).join(" vs ");return{prompt:`Two of ${lead(petName)}'s documents disagree on ${scope}: ${rendered}. Which is likely correct, and what should I ask my vet?`,entityRef:{type:"conflict",id:conflictId,payload:{field:scope,severity:input.severity,values:cands.map(c=>c.value.trim()).join(" | ")}}}}var REQUEST_LIST_COPY=/* @__PURE__ */Object.freeze({title:"Medical records",subtitle:petName=>{let name=petName?.trim()??"";return name.length>0?`${name}’s uploads and clinic requests`:"Every upload and clinic request"},requestRecords:"Request records",requestRecordsA11y:"Request records from a clinic",uploadOwn:"I already have the records",ownerUpload:"Records you uploaded",clinicRequest:"Clinic request",meta:(ownerUpload,createdAt)=>`${ownerUpload?"Uploaded":"Requested"} ${formatRecordsInstant(createdAt)}`,rowA11y:(source,meta,status)=>`${source}, ${meta}, status ${status}`,allRequests:"Your record requests"}),STEP_LABELS=/* @__PURE__ */Object.freeze({preparing:"Preparing",sent:"Sent",processing:"Processing",done:"Ready"});function stepLabel(status){switch(status){case"awaiting_clinic":return STEP_LABELS.sent;case"received":case"parsing":case"in_review":return STEP_LABELS.processing;case"published":return STEP_LABELS.done;default:return STEP_LABELS.preparing}}function requestRowView(request){let ownerUpload=request.source==="owner_provided",source=request.clinicName?.trim()||(ownerUpload?REQUEST_LIST_COPY.ownerUpload:REQUEST_LIST_COPY.clinicRequest),status=request.statusLabel.trim()||stepLabel(request.status),meta=REQUEST_LIST_COPY.meta(ownerUpload,request.createdAt);/* @__PURE__ */
|
|
369
367
|
return Object.freeze({source:source,meta:meta,status:status,ownerUpload:ownerUpload,a11yLabel:REQUEST_LIST_COPY.rowA11y(source,meta,status)})}var PROCESSING_WIRE=/* @__PURE__ */new Set(["records_received","parsing","parsing_failed","in_review","review_email_failed"]),PROCESSING_FOLDED=/* @__PURE__ */new Set(["received","parsing","in_review"]);function isProcessing(request){return request.wireStatus!==void 0?PROCESSING_WIRE.has(request.wireStatus):PROCESSING_FOLDED.has(request.status)}function requestsStatusCardView(requests,petName,opts={}){let active=requests.filter(r=>!isTerminalStatus(r.status));if(requests.length===0||opts.activeOnly===true&&active.length===0)return null;let processing=requests.filter(isProcessing).length,title=processing>0?`${processing} document${processing===1?"":"s"} being read`:active.length>0?`${active.length} active record request${active.length===1?"":"s"}`:REQUEST_LIST_COPY.allRequests,subtitle=processing>0?`We’ll add ${processing===1?"it":"them"} to ${petName}’s records once ready.`:active.length>0?"See each clinic’s status and what happens next.":"See the status of every upload and clinic request.";/* @__PURE__ */
|
|
370
|
-
return Object.freeze({title:title,subtitle:subtitle,processing:processing>0,a11yLabel:`${title}. ${subtitle}`})}function canUploadRecords(onPickDocument){return onPickDocument!==void 0}function resolveConsentVersion(consentVersion,consent){return consentVersion??consent?.version??""}function canGrantConsent(consentVersion,consent){return resolveConsentVersion(consentVersion,consent).length>0}function selectErrorView(state,canGrant){return state.denialReason==="consent_required"?canGrant?{kind:"consent_required"}:{kind:"consent_unavailable"}:state.denialReason==="pet_not_found"?{kind:"pet_not_found",error:makeEverfurError("petNotFound",{retryable:false})}:state.denialReason==="entitlement"?{kind:"error",error:makeEverfurError("accessDenied")}:state.denialReason==="session_required"?{kind:"session_required"}:state.withheld?{kind:"withheld"}:state.error===null?{kind:"withheld"}:{kind:"error",error:state.error}}function isConsentGate(view){return view.kind==="consent_required"||view.kind==="consent_unavailable"}function selectRequestTitle(request){let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:request.source==="owner_provided"?REQUEST_TITLE_COPY.ownerUpload:REQUEST_TITLE_COPY.clinicRequest}var REQUEST_TITLE_COPY=/* @__PURE__ */Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function selectResumableUploadRequest(_record,activeRequest){return activeRequest===null||activeRequest.status!=="awaiting_upload"?null:activeRequest}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
368
|
+
return Object.freeze({title:title,subtitle:subtitle,processing:processing>0,a11yLabel:`${title}. ${subtitle}`})}function canUploadRecords(onPickDocument){return onPickDocument!==void 0}function resolveConsentVersion(consentVersion,consent){return consentVersion??consent?.version??""}function canGrantConsent(consentVersion,consent){return resolveConsentVersion(consentVersion,consent).length>0}function selectErrorView(state,canGrant){return state.denialReason==="consent_required"?canGrant?{kind:"consent_required"}:{kind:"consent_unavailable"}:state.denialReason==="pet_not_found"?{kind:"pet_not_found",error:makeEverfurError("petNotFound",{retryable:false})}:state.denialReason==="entitlement"?{kind:"error",error:makeEverfurError("accessDenied")}:state.denialReason==="session_required"?{kind:"session_required"}:state.withheld?{kind:"withheld"}:state.error===null?{kind:"withheld"}:{kind:"error",error:state.error}}function isConsentGate(view){return view.kind==="consent_required"||view.kind==="consent_unavailable"}function selectRequestTitle(request){let clinic=request.clinicName?.trim()??"";return clinic.length>0?clinic:request.source==="owner_provided"?REQUEST_TITLE_COPY.ownerUpload:REQUEST_TITLE_COPY.clinicRequest}var REQUEST_TITLE_COPY=/* @__PURE__ */Object.freeze({ownerUpload:"Records you uploaded",clinicRequest:"Record request"});function selectResumableUploadRequest(_record,activeRequest){return activeRequest===null||activeRequest.status!=="awaiting_upload"?null:activeRequest}function heldItemsLabel(count){return`${count} ${RECORDS_COPY.beingReviewed}`}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
371
369
|
return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=request.actionNeededLabel?.trim()??"";return action.length>0?action:request.statusLabel}function selectClinicCall(request){if(request.showClinicPhone!==true)return null;let phone=request.clinicPhone?.trim()??"";return phone.length===0?null:{phone:phone,dial:`tel:${phone.replace(/[^+\d]/g,"")}`,clinicName:request.clinicName?.trim()||null}}function selectRequestStatusTone(request){switch(request.wireStatus??request.status){case"published":return"positive";case"failed":case"clinic_declined":return"critical";case"revoked":return"neutral";case"clinic_responded_no_records":case"awaiting_upload":case"records_received":case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return"warning";default:return"info"}}var RING_SIZE=200,RING_STROKE=16;function buildRingSegments(summary,colors){let denominator=summary.inRangeCount+summary.outOfRangeCount+summary.unknownCount;if(!Number.isFinite(denominator)||denominator<=0)return[];let buckets=[{key:"in_range",color:colors.inRange,count:summary.inRangeCount},{key:"out_of_range",color:colors.outOfRange,count:summary.outOfRangeCount},{key:"unknown",color:colors.unknown,count:summary.unknownCount}],cumulative=0,out=[];for(let bucket of buckets){if(!(bucket.count>0))continue;let sweepDeg=bucket.count/denominator*360;if(!Number.isFinite(sweepDeg))return null;out.push({key:bucket.key,color:bucket.color,startDeg:cumulative,sweepDeg:sweepDeg}),cumulative+=sweepDeg}return out}function MarkerSummaryCard({summary:summary,onAsk:onAsk,testID:testID}){let styles=useStyles5(),theme=useEverfurTheme(),{totalMarkers:totalMarkers,inRangeCount:inRangeCount,outOfRangeCount:outOfRangeCount,unknownCount:unknownCount}=summary,segments=react.useMemo(()=>buildRingSegments(summary,{inRange:theme.color.success,outOfRange:theme.color.danger,unknown:theme.color.text.muted}),[summary,theme]),hasArcs=segments!==null&&segments.length>0;/* @__PURE__ */
|
|
372
370
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.card,accessibilityRole:"summary",testID:testID,children:[
|
|
373
371
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.title,children:MARKER_SUMMARY_COPY.title}),
|
|
@@ -378,8 +376,8 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.card,accessibilityRole:"su
|
|
|
378
376
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.centerLabel,children:totalMarkers===1?MARKER_SUMMARY_COPY.marker:MARKER_SUMMARY_COPY.markers})]})]})}),hasArcs||segments===null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.badges,children:[
|
|
379
377
|
/* @__PURE__ */jsxRuntime.jsx(Badge,{count:outOfRangeCount,label:MARKER_SUMMARY_COPY.outOfRange,color:theme.color.danger,styles:styles}),
|
|
380
378
|
/* @__PURE__ */jsxRuntime.jsx(Badge,{count:inRangeCount,label:MARKER_SUMMARY_COPY.inRange,color:theme.color.success,styles:styles}),unknownCount>0?/* @__PURE__ */jsxRuntime.jsx(Badge,{count:unknownCount,label:MARKER_SUMMARY_COPY.noRange,color:theme.color.text.muted,styles:styles}):null]}):null,
|
|
381
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:MARKER_SUMMARY_COPY.ask,style:styles.ask,testID:"marker-summary-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askLabel,children:MARKER_SUMMARY_COPY.ask})}):null]})}function Arc({segment:segment,styles:styles}){return(segment.sweepDeg<=180?[{start:segment.startDeg,sweep:segment.sweepDeg}]:[{start:segment.startDeg,sweep:180},{start:segment.startDeg+180,sweep:segment.sweepDeg-180}]).map((piece,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.piece,{transform:[{rotate:`${piece.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${segment.key}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.window,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.halfRing,{borderTopColor:segment.color,borderRightColor:segment.color,transform:[{rotate:`${piece.sweep-135}deg`}]}]})})},index))}function Badge({count:count,label:
|
|
382
|
-
return jsxRuntime.jsx(reactNative.View,{style:[styles.badge,{borderColor:color}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeText,{color:color}],children:`${count} ${
|
|
379
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:MARKER_SUMMARY_COPY.ask,style:styles.ask,testID:"marker-summary-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askLabel,children:MARKER_SUMMARY_COPY.ask})}):null]})}function Arc({segment:segment,styles:styles}){return(segment.sweepDeg<=180?[{start:segment.startDeg,sweep:segment.sweepDeg}]:[{start:segment.startDeg,sweep:180},{start:segment.startDeg+180,sweep:segment.sweepDeg-180}]).map((piece,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.piece,{transform:[{rotate:`${piece.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${segment.key}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.window,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.halfRing,{borderTopColor:segment.color,borderRightColor:segment.color,transform:[{rotate:`${piece.sweep-135}deg`}]}]})})},index))}function Badge({count:count,label:label2,color:color,styles:styles}){/* @__PURE__ */
|
|
380
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.badge,{borderColor:color}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.badgeText,{color:color}],children:`${count} ${label2}`})})}function useStyles5(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,cardText=slotText(recordCardSlot(slots));return reactNative.StyleSheet.create({card:{borderRadius:radius.lg,backgroundColor:color.surfaceCream,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.sm+space.xs/2,...slotBox(recordCardSlot(slots),1)},title:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),color:color.brandInk,letterSpacing:-.4,...cardText},ringRow:{alignItems:"center"},ringWrap:{width:RING_SIZE,height:RING_SIZE,alignItems:"center",justifyContent:"center"},track:{position:"absolute",width:RING_SIZE,height:RING_SIZE,borderRadius:RING_SIZE/2,borderWidth:RING_STROKE,borderColor:color.surfaceSubtle},piece:{position:"absolute",width:RING_SIZE,height:RING_SIZE},window:{position:"absolute",left:RING_SIZE/2,top:0,width:RING_SIZE/2,height:RING_SIZE,overflow:"hidden"},halfRing:{position:"absolute",left:-RING_SIZE/2,top:0,width:RING_SIZE,height:RING_SIZE,borderRadius:RING_SIZE/2,borderWidth:RING_STROKE,borderBottomColor:"transparent",borderLeftColor:"transparent"},center:{position:"absolute",alignItems:"center",justifyContent:"center"},centerCount:{...face(theme,"medium"),fontSize:type.size.verdict*2,lineHeight:type.size.verdict*2+space.xs,color:color.text.primary,textAlign:"center",...cardText},centerLabel:{...face(theme,"medium"),fontSize:type.size.heading-1,lineHeight:type.size.heading+space.xs/2,color:color.text.primary,textAlign:"center",...cardText},badges:{flexDirection:"row",flexWrap:"wrap",justifyContent:"center",gap:space.sm},badge:{borderWidth:1,borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs},badgeText:{...face(theme,"mono"),fontSize:type.size.nano,lineHeight:type.size.tiny,letterSpacing:type.letterSpacing.headerBrand/2,textTransform:"uppercase"},subtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.relaxed),color:color.text.primary,...cardText},ask:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:space.sm,minHeight:space.xxl+space.sm,marginTop:space.xs/2,paddingHorizontal:space.lg,borderRadius:radius.pill,borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},askLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.primary,letterSpacing:type.letterSpacing.tight}})}function numeric(point){return point.value!==null&&Number.isFinite(point.value)}function buildMarkerChart(marker){let readings=marker.points.filter(numeric);if(readings.length===0)return null;let latest=marker.points[marker.points.length-1]??null,refLow=latest?.refLow??null,refHigh=latest?.refHigh??null,values=readings.map(p=>p.value),lo=Math.min(...values,...refLow!==null?[refLow]:[],...refHigh!==null?[refHigh]:[]),hi=Math.max(...values,...refLow!==null?[refLow]:[],...refHigh!==null?[refHigh]:[]);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,y=value=>(yMax-value)/span*100,xInset=6,count=readings.length,points=readings.map((point,index)=>({index:index,xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:y(point.value),status:point.status,point:point})),band=refLow!==null||refHigh!==null?{topPct:refHigh!==null?y(refHigh):0,bottomPct:refLow!==null?y(refLow):100}:null;return{points:points,band:band,firstDate:readings[0]?.at??null,lastDate:readings[readings.length-1]?.at??null}}function sheetSlotBox(slot,borderWidth){let{borderRadius:borderRadius,...box3}=slotBox(slot,borderWidth);return borderRadius===void 0?box3:{...box3,borderTopLeftRadius:borderRadius,borderTopRightRadius:borderRadius}}var CAROUSEL_HEIGHT=416,PLOT_HEIGHT=140;function pct(value){return`${value}%`}function MarkerTrendCard({marker:marker,width:width,onPointPress:onPointPress,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles(),status=markerStatusLabel(marker.latest?.status??null),tone=markerStatusTone(marker.latest?.status??null),traj=trajectoryLabel(marker.trajectory,marker.points.length),chart=react.useMemo(()=>buildMarkerChart(marker),[marker]),latestReading=marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null;/* @__PURE__ */
|
|
383
381
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.page,width!==void 0?{width:width}:null],testID:`marker-card-${marker.markerId}`,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
384
382
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.headerRow,children:[
|
|
385
383
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.nameColumn,children:[
|
|
@@ -394,9 +392,9 @@ return jsxRuntime.jsxs(reactNative.View,{style:styles.carousel,onLayout:onLayout
|
|
|
394
392
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,pagingEnabled:true,showsHorizontalScrollIndicator:false,onMomentumScrollEnd:onMomentumEnd,snapToAlignment:"start",children:markers.map(marker=>/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCard,{marker:marker,width:width>0?width:void 0,onPointPress:onPointPress,onAsk:onAsk},marker.markerId))}),
|
|
395
393
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.footer,accessible:true,accessibilityRole:"adjustable",accessibilityLabel:MARKER_CAROUSEL_COPY.a11y(active?.name??null,activeIndex,markers.length),children:[
|
|
396
394
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dots,testID:"marker-carousel-dots",children:markerDotWindow(activeIndex,markers.length).map(index=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,index===activeIndex?styles.dotActive:null]},markers[index]?.markerId??index))}),
|
|
397
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.counter,children:MARKER_CAROUSEL_COPY.counter(activeIndex,markers.length)})]})]})}function MarkerProvenanceSheet({marker:marker,point:point,onClose:onClose,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles();if(marker===null||point===null)return null;let row=(
|
|
398
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailLabel,children:
|
|
399
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailValue,children:value})]},
|
|
395
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.counter,children:MARKER_CAROUSEL_COPY.counter(activeIndex,markers.length)})]})]})}function MarkerProvenanceSheet({marker:marker,point:point,onClose:onClose,onAsk:onAsk}){let styles=useStyles6(),screen=useScreenStyles();if(marker===null||point===null)return null;let row=(label2,value)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.detailRow,accessible:true,accessibilityRole:"text",accessibilityLabel:`${label2}: ${value}`,children:[
|
|
396
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailLabel,children:label2}),
|
|
397
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.detailValue,children:value})]},label2);/* @__PURE__ */
|
|
400
398
|
return jsxRuntime.jsxs(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:[
|
|
401
399
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:styles.backdrop,onPress:onClose,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.close}),
|
|
402
400
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"marker-provenance-sheet",children:[
|
|
@@ -407,13 +405,13 @@ return jsxRuntime.jsxs(reactNative.Modal,{transparent:true,visible:true,animatio
|
|
|
407
405
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheetBody,children:[
|
|
408
406
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.valueRow,children:[
|
|
409
407
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetName,children:marker.name}),
|
|
410
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null,point.reviewed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,dot=space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(recordCardSlot(slots)),dialogText=slotText(slots.dialog),nameText={...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},valueText=text4(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:space.sm},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(slots),1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,gap:space.xs/2},markerName:{...nameText,...cardText},sheetName:{...nameText,...dialogText},unit:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted,...cardText},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...valueText,...cardText},sheetValue:{...valueText,...dialogText},latestValueDanger:{color:color.danger},latestDate:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...cardText},chartWrap:{gap:space.sm},plot:{height:PLOT_HEIGHT,borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:color.badgeBgPositive},point:{position:"absolute",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,borderWidth:2,borderColor:color.surface},pointDanger:{backgroundColor:color.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...text4(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},emptyBody:{alignItems:"center",justifyContent:"center",gap:space.sm,paddingVertical:space.xxl+space.xs},emptyText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},carousel:{height:CAROUSEL_HEIGHT},footer:{alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{flexDirection:"row",gap:space.xs+space.xs/2},dot:{width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs-1,backgroundColor:color.borderHairlineGreen},dotActive:{width:space.lg+space.xs/2,backgroundColor:color.brand},counter:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},backdrop:{flex:1,backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surfaceCream,borderTopLeftRadius:radius.xl-space.xs,borderTopRightRadius:radius.xl-space.xs,paddingHorizontal:space.lg+space.xs,paddingTop:space.sm,paddingBottom:space.xxl+space.xs,maxHeight:"80%",gap:space.md,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},sheetTitle:{flex:1,...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},closeButton:{width:space.xxl+space.md,height:space.xxl+space.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},sheetBody:{gap:space.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs,backgroundColor:color.badgeBgPositive},reviewedText:{...text4(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{gap:space.xs/2},detailLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted,"medium"),...dialogText},detailValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),...dialogText},unverified:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...dialogText}})}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:
|
|
408
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.reviewedText,children:PROVENANCE_COPY.reviewed})}):null,row(PROVENANCE_COPY.collected,formatRecordsDate(point.at)),point.sourceClinic?row(PROVENANCE_COPY.clinic,point.sourceClinic):null,row(PROVENANCE_COPY.referenceRange,point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):PROVENANCE_COPY.noRange),point.docId?row(PROVENANCE_COPY.sourceDocument,point.docId):null,point.reviewed?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=reactNative.StyleSheet.hairlineWidth,dot=space.md,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(recordCardSlot(slots)),dialogText=slotText(slots.dialog),nameText={...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},valueText=text4(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return reactNative.StyleSheet.create({page:{paddingHorizontal:space.sm},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(slots),1)},headerRow:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,gap:space.xs/2},markerName:{...nameText,...cardText},sheetName:{...nameText,...dialogText},unit:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted,...cardText},latestRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...valueText,...cardText},sheetValue:{...valueText,...dialogText},latestValueDanger:{color:color.danger},latestDate:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...cardText},chartWrap:{gap:space.sm},plot:{height:PLOT_HEIGHT,borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderHairlineGreen,overflow:"hidden"},band:{position:"absolute",left:0,right:0,backgroundColor:color.badgeBgPositive},point:{position:"absolute",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,borderWidth:2,borderColor:color.surface},pointDanger:{backgroundColor:color.danger},a11yTable:{width:1,height:1,overflow:"hidden",position:"absolute"},tapHint:{...text4(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},emptyBody:{alignItems:"center",justifyContent:"center",gap:space.sm,paddingVertical:space.xxl+space.xs},emptyText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",...cardText},carousel:{height:CAROUSEL_HEIGHT},footer:{alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{flexDirection:"row",gap:space.xs+space.xs/2},dot:{width:space.xs+space.xs/2,height:space.xs+space.xs/2,borderRadius:space.xs-1,backgroundColor:color.borderHairlineGreen},dotActive:{width:space.lg+space.xs/2,backgroundColor:color.brand},counter:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},backdrop:{flex:1,backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surfaceCream,borderTopLeftRadius:radius.xl-space.xs,borderTopRightRadius:radius.xl-space.xs,paddingHorizontal:space.lg+space.xs,paddingTop:space.sm,paddingBottom:space.xxl+space.xs,maxHeight:"80%",gap:space.md,...sheetSlotBox(slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},sheetHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},sheetTitle:{flex:1,...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},closeButton:{width:space.xxl+space.md,height:space.xxl+space.md,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},sheetBody:{gap:space.md},valueRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs,backgroundColor:color.badgeBgPositive},reviewedText:{...text4(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{gap:space.xs/2},detailLabel:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted,"medium"),...dialogText},detailValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),...dialogText},unverified:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),...dialogText}})}var FALLBACK_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),GIVEN_PREFIX="Given",ISO_DATE_PREFIX=/^\d{4}-\d{2}-\d{2}/,DETAIL_SEPARATOR=" · ";function joinDetail(parts){let kept=parts.filter(part=>part!==null&&part.trim().length>0);return kept.length>0?kept.join(DETAIL_SEPARATOR):null}function rowTitle(facts,humanizeCategory){let label2=facts.label.trim();if(label2.length>0)return label2;let fallback=FALLBACK_TITLE[facts.category];return fallback!==void 0?fallback:humanizeCategory(facts.category)}function entityRowSummary(facts,fmt){let title=rowTitle(facts,fmt.humanize),value=fmt.formatEntityValue(facts.value,facts.unit),shownValue=value.trim().length>0?value:null,rawDate=facts.observedAt!==null&&facts.observedAt.trim().length>0?fmt.formatRecordsDate(facts.observedAt):null,observed=rawDate!==null&&rawDate!=="-"?rawDate:null;switch(facts.category){case"vaccination":{let valueIsDate=facts.value!==null&&ISO_DATE_PREFIX.test(facts.value.trim()),givenOn=valueIsDate?fmt.formatRecordsDate(facts.value):observed;return givenOn!==null&&givenOn!=="-"?{title:title,detail:joinDetail([`${GIVEN_PREFIX} ${givenOn}`,valueIsDate?null:shownValue])}:{title:title,detail:joinDetail([shownValue])}}case"medication":return{title:title,detail:joinDetail([observed])};case"problem":return{title:title,detail:joinDetail([observed])};case"body_weight":return{title:title,detail:joinDetail([observed])};case"allergy":return{title:title,detail:joinDetail([observed])};case"vital":return{title:title,detail:joinDetail([shownValue,observed])};case"lab_result":return{title:title,detail:joinDetail([shownValue,observed])};default:return{title:title,detail:joinDetail([shownValue,observed])}}}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:label2=>`Edit ${label2}. Correct or remove this record detail.`,title:label2=>`Edit ${label2}`,helper:"Corrects your record. Your vet can still review it.",close:"Close",closeEditorA11y:"Close editor",save:"Save changes",saving:"Saving...",remove:"Remove this detail",confirmRemove:"Remove this detail from your record? This can't be undone.",removeConfirm:"Remove",removing:"Removing...",keep:"Keep",noChange:"Change a value before saving.",saved:"Saved.",removed:"Removed.",detail:"record detail"});function factEditErrorMessage(error,mode){return isRecordsConsentRequired(error)?mode==="remove"?"Records access for this pet is off, so this detail cannot be removed.":"Records access for this pet is off, so this detail cannot be changed.":isFactReviewerLocked(error)?mode==="remove"?"A clinician already reviewed this detail, so it can't be removed here.":"A clinician already reviewed this detail, so it can't be changed here.":mode==="remove"?"Couldn't remove that. Please check your connection and try again.":"Couldn't save that. Please check your connection and try again."}var EMPTY_FACT_OVERLAY=/* @__PURE__ */Object.freeze({edits:/* @__PURE__ */Object.freeze({}),removed:/* @__PURE__ */Object.freeze([])});function applyFactOverlay(entities,overlay){if(Object.keys(overlay.edits).length===0&&overlay.removed.length===0)return entities;let out=[];for(let entity of entities){let key=entity.canonicalKey??null;if(key!==null&&overlay.removed.includes(key))continue;let edited=key!==null?overlay.edits[key]:void 0;out.push(edited===void 0?entity:/* @__PURE__ */Object.freeze({...entity,value:edited}))}/* @__PURE__ */
|
|
411
409
|
return Object.freeze(out)}function isFactEditable(entity){return typeof entity.canonicalKey=="string"&&entity.canonicalKey.length>0}function defaultFactKey(){return`records-fact-${Date.now().toString(36)}`}function useRecordFactEdit(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[overlay,setOverlay]=react.useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=react.useState(null),markDark=react.useCallback(()=>setDarkScope(scope),[scope]),[refused,setRefused]=react.useState(null);react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&value.features.fact_edit===false&&setRefused(scope)},()=>{}),()=>{current=false}},[client,userRef,scope]);let available=userRef!==null&&darkScope!==scope&&refused!==scope,locked=react.useRef(false),mintRef=react.useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=react.useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=react.useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=react.useCallback(async(entity,value)=>{let key=entity.canonicalKey??"",next=value.trim();if(locked.current||key.length===0||next.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,edits:{...current.edits,[key]:next}}));let result=await client.editFact(petRef,{entityType:entity.category,canonicalKey:key,correctedFields:factCorrectionFor(entity.value,next),idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"edit"),result},[client,petRef,overlay,settle,mint]),remove=react.useCallback(async entity=>{let key=entity.canonicalKey??"";if(locked.current||key.length===0)return err(makeEverfurError("validationFailed",{retryable:false}));locked.current=true,setBusy(true),setError(null);let snapshot=overlay;setOverlay(current=>({...current,removed:[...current.removed,key]}));let result=await client.removeFact(petRef,{entityType:entity.category,canonicalKey:key,idempotencyKey:mint()});return locked.current=false,settle(result,()=>setOverlay(snapshot),"remove"),result},[client,petRef,overlay,settle,mint]),clearError=react.useCallback(()=>setError(null),[]);return react.useMemo(()=>({overlay:overlay,busy:busy,error:error,available:available,edit:edit,remove:remove,clearError:clearError}),[overlay,busy,error,available,edit,remove,clearError])}var VACCINE_CATEGORIES=/* @__PURE__ */Object.freeze(["vaccination","parasite_prevention"]),VACCINE_UNDATED_GROUP="Undated",VACCINE_STATUS_LABEL=/* @__PURE__ */Object.freeze({given:"Given",prevention:"Prevention",overdue:"Overdue",noDate:"No date"}),VACCINE_CHIP_TONE=/* @__PURE__ */Object.freeze({given:"positive",prevention:"neutral",overdue:"critical",noDate:"neutral"});function toMillis(value){if(!value)return null;let ms2=Date.parse(value);return Number.isNaN(ms2)?null:ms2}function isLapsed(entity){let status=entity.status?.toLowerCase()??"";return/overdue|lapsed|expired/.test(status)}function vaccineTone(entity){return entity.category==="parasite_prevention"?"prevention":toMillis(entity.observedAt)===null?"noDate":isLapsed(entity)?"overdue":"given"}function yearOf(at){let ms2=toMillis(at);return ms2===null?VACCINE_UNDATED_GROUP:String(new Date(ms2).getUTCFullYear())}function buildRow(entity){let tone=vaccineTone(entity),parts=[entity.value!==null&&entity.value.length>0?entity.value:null,entity.observedAt!==null?formatRecordsDate(entity.observedAt):null].filter(part=>part!==null&&part.length>0);return{key:entity.key,name:entity.label,detail:parts.length>0?parts.join(" · "):null,statusLabel:VACCINE_STATUS_LABEL[tone],tone:tone,entity:entity}}function selectVaccineGroups(entities){let byYear=/* @__PURE__ */new Map;for(let entity of entities){if(!VACCINE_CATEGORIES.includes(entity.category))continue;let year=yearOf(entity.observedAt),bucket=byYear.get(year),item={row:buildRow(entity),at:entity.observedAt};bucket===void 0?byYear.set(year,[item]):bucket.push(item)}let years=[...byYear.keys()].sort((a,b)=>a===VACCINE_UNDATED_GROUP?1:b===VACCINE_UNDATED_GROUP?-1:Number(b)-Number(a));/* @__PURE__ */
|
|
412
410
|
return Object.freeze(years.map(year=>{let items=byYear.get(year)??[],ordered=year===VACCINE_UNDATED_GROUP?items:[...items].sort((a,b)=>(toMillis(b.at)??0)-(toMillis(a.at)??0));/* @__PURE__ */
|
|
413
|
-
return Object.freeze({year:year,items:/* @__PURE__ */Object.freeze(ordered.map(i=>i.row))})}))}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let styles=useStyles7(),[open,setOpen]=react.useState(false),
|
|
411
|
+
return Object.freeze({year:year,items:/* @__PURE__ */Object.freeze(ordered.map(i=>i.row))})}))}var ABSOLUTE_FILL=/* @__PURE__ */Object.freeze({position:"absolute",top:0,right:0,bottom:0,left:0});function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let styles=useStyles7(),[open,setOpen]=react.useState(false),label2=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
414
412
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,children:[
|
|
415
413
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.main,children:children}),
|
|
416
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setOpen(true),accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.editA11y(
|
|
414
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setOpen(true),accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.editA11y(label2),hitSlop:6,style:styles.editButton,testID:`fact-edit-open-${entity.canonicalKey??entity.key}`,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.pencil,accessibilityElementsHidden:true,importantForAccessibility:"no"})}),open?/* @__PURE__ */jsxRuntime.jsx(FactEditSheet,{entity:entity,title:label2,factEdit:factEdit,onClose:()=>setOpen(false)}):null]})}function FactEditSheet({entity:entity,title:title,factEdit:factEdit,onClose:onClose}){let styles=useStyles7(),screen=useScreenStyles(),theme=useEverfurTheme(),[draft,setDraft]=react.useState(entity.value??""),[localError,setLocalError]=react.useState(null),[confirmingRemove,setConfirmingRemove]=react.useState(false);react.useEffect(()=>{factEdit.clearError()},[factEdit]);let changed=draft.trim().length>0&&draft.trim()!==(entity.value??"").trim(),error=localError??factEdit.error,busy=factEdit.busy,submitEdit=()=>{if(!changed){setLocalError(FACT_EDIT_COPY.noChange);return}setLocalError(null),factEdit.edit(entity,draft).then(result=>{result.ok&&onClose()})},submitRemove=()=>{setLocalError(null),factEdit.remove(entity).then(result=>{result.ok?onClose():setConfirmingRemove(false)})};/* @__PURE__ */
|
|
417
415
|
return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.KeyboardAvoidingView,{behavior:"padding",style:styles.backdrop,children:[
|
|
418
416
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.closeEditorA11y,onPress:onClose}),
|
|
419
417
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"fact-edit-sheet",children:[
|
|
@@ -430,7 +428,21 @@ return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animation
|
|
|
430
428
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.removing:FACT_EDIT_COPY.removeConfirm,kind:"danger",busy:busy,onPress:submitRemove,style:styles.confirmButton,testID:"fact-edit-remove-confirm"}),
|
|
431
429
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:FACT_EDIT_COPY.keep,kind:"outline",disabled:busy,onPress:()=>setConfirmingRemove(false),style:styles.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.actions,children:[
|
|
432
430
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:busy?FACT_EDIT_COPY.saving:FACT_EDIT_COPY.save,busy:busy,disabled:!changed,onPress:submitEdit,testID:"fact-edit-save"}),
|
|
433
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.remove,disabled:busy,onPress:()=>{setLocalError(null),setConfirmingRemove(true)},style:[styles.removeButton,busy?styles.removeDisabled:null],testID:"fact-edit-remove",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles9(theme),[theme])}function makeStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:space.sm},main:{flex:1},editButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},pencil:{width:space.md+space.xs/2,height:space.xs/2,backgroundColor:color.brandInk,borderRadius:radius.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md,...sheetSlotBox(theme.slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text4(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.dialog)},helper:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.dialog)},helperError:{color:errorColor},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...slotText(theme.slots.dialog)},actions:{gap:space.sm},removeButton:{minHeight:touch,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...text4(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}function
|
|
431
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:FACT_EDIT_COPY.remove,disabled:busy,onPress:()=>{setLocalError(null),setConfirmingRemove(true)},style:[styles.removeButton,busy?styles.removeDisabled:null],testID:"fact-edit-remove",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles9(theme),[theme])}function makeStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({row:{flexDirection:"row",alignItems:"center",gap:space.sm},main:{flex:1},editButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},pencil:{width:space.md+space.xs/2,height:space.xs/2,backgroundColor:color.brandInk,borderRadius:radius.pill,transform:[{rotate:"-45deg"}]},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:SHEET_SCRIM},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md,...sheetSlotBox(theme.slots.dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text4(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.dialog)},helper:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.dialog)},helperError:{color:errorColor},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...slotText(theme.slots.dialog)},actions:{gap:space.sm},removeButton:{minHeight:touch,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...text4(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}function isFinitePoint(point){return point.value!==null&&Number.isFinite(point.value)}function pointDisplay(point){return point.display!==null&&point.display.length>0?point.display:point.value!==null?String(point.value):""}function buildTrendModel(series){let primary=series.find(s=>s.points.some(isFinitePoint));if(primary===void 0)return null;let numeric2=primary.points.filter(isFinitePoint),first=numeric2[0];if(first===void 0)return null;let values=numeric2.map(p=>p.value),lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,xInset=6,count=numeric2.length,points=numeric2.map((p,index)=>({xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:(yMax-p.value)/span*100})),bandTopPct=(yMax-hi)/span*100,bandBottomPct=(yMax-lo)/span*100,minPoint=numeric2.reduce((acc,p)=>p.value<acc.value?p:acc,first),maxPoint=numeric2.reduce((acc,p)=>p.value>acc.value?p:acc,first),lastNumeric=numeric2[numeric2.length-1]??first,latest=primary.points[primary.points.length-1]??lastNumeric,latestDisplay=pointDisplay(latest),heroDisplay=latestDisplay.length>0?latestDisplay:pointDisplay(lastNumeric);return{label:primary.label,heroDisplay:heroDisplay,minDisplay:pointDisplay(minPoint),maxDisplay:pointDisplay(maxPoint),firstDate:formatShortDate(primary.points[0]?.at??null),lastDate:formatShortDate(latest.at),points:points,bandTopPct:bandTopPct,bandBottomPct:bandBottomPct}}function entityTypeOf(key){let separator=key.indexOf(":");return separator<=0?null:key.slice(0,separator)}function groupSeriesByEntityType(series,order,labelFor){let byType=/* @__PURE__ */new Map,firstSeen=[];for(let one of series){let type=entityTypeOf(one.key)??"",bucket=byType.get(type);bucket===void 0?(byType.set(type,[one]),firstSeen.push(type)):bucket.push(one)}let listed=order.filter(type=>byType.has(type)),rest=firstSeen.filter(type=>!listed.includes(type));/* @__PURE__ */
|
|
432
|
+
return Object.freeze([...listed,...rest].map(type=>/* @__PURE__ */Object.freeze({entityType:type.length>0?type:null,label:type.length>0?labelFor(type):null,series:/* @__PURE__ */Object.freeze([...byType.get(type)??[]])})))}function pct2(value){return`${value}%`}function CareTimeline({series:series,testID:testID}){let styles=useStyles8(),groups=react.useMemo(()=>groupSeriesByEntityType(series,ENTITY_SECTION_ORDER,entityTypeLabel),[series]);return groups.length===0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:testID,children:[
|
|
433
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[
|
|
434
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:RECORD_SCREEN_COPY.careTimeline}),
|
|
435
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.sectionSub,children:RECORD_SCREEN_COPY.careTimelineSub})]}),groups.map(group=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.group,children:[group.label===null?null:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.groupLabel,numberOfLines:1,children:group.label}),group.series.map(one=>/* @__PURE__ */jsxRuntime.jsx(SeriesCard,{series:one,styles:styles},one.key))]},group.entityType??"_"))]})}function SeriesCard({series:series,styles:styles}){let model=react.useMemo(()=>buildTrendModel([series]),[series]);if(model!==null)/* @__PURE__ */return jsxRuntime.jsx(TrendChart,{model:model,styles:styles});let display=series.points[series.points.length-1]?.display??null,summary=display!==null&&display.length>0?`${series.label}, ${display}`:series.label;/* @__PURE__ */
|
|
436
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.card,accessible:true,accessibilityRole:"text",accessibilityLabel:summary,children:[
|
|
437
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.eyebrow,numberOfLines:1,children:series.label}),display!==null&&display.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.hero,numberOfLines:1,children:display}):null]})}function TrendChart({model:model,styles:styles,testID:testID}){let summary=model.heroDisplay.length>0?`${model.label}, ${model.heroDisplay}`:model.label,bandHeightPct=Math.max(0,model.bandBottomPct-model.bandTopPct);/* @__PURE__ */
|
|
438
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.card,testID:testID,children:[
|
|
439
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:summary,children:[
|
|
440
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.eyebrow,numberOfLines:1,children:model.label}),model.heroDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.hero,numberOfLines:1,children:model.heroDisplay}):null]}),
|
|
441
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.plot,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[model.points.map((p,index)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.guide,{left:pct2(p.xPct)}]},`g-${index}`)),
|
|
442
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.band,{top:pct2(model.bandTopPct),height:pct2(bandHeightPct)}]}),model.points.map((p,index)=>{let latest=index===model.points.length-1;/* @__PURE__ */
|
|
443
|
+
return jsxRuntime.jsx(reactNative.View,{style:[styles.point,latest?styles.pointLatest:null,{left:pct2(p.xPct),top:pct2(p.yPct)}]},`pt-${index}`)}),model.maxDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.edgeLabel,{top:pct2(model.bandTopPct)}],numberOfLines:1,children:model.maxDisplay}):null,model.minDisplay.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.edgeLabel,{top:pct2(model.bandBottomPct)}],numberOfLines:1,children:model.minDisplay}):null]}),model.firstDate.length>0||model.lastDate.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.dates,children:[
|
|
444
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.dateLabel,children:model.firstDate}),
|
|
445
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.dateLabel,children:model.lastDate})]}):null]})}function useStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles10(theme),[theme])}function makeStyles10(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,cardText=slotText(recordCardSlot(slots)),plotHeight=space.xxl*3,dotSize=space.sm,dotOffset=-(dotSize/2),bandInset=space.xs,softShadow={shadowColor:color.brand,shadowOffset:{width:0,height:space.xs},shadowRadius:space.sm,shadowOpacity:.08,elevation:space.xs};return reactNative.StyleSheet.create({section:{gap:space.lg},sectionTitle:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),letterSpacing:-.4,color:color.text.primary},sectionSub:{...face(theme,"regular"),marginTop:space.xs,fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted},group:{gap:space.sm},groupLabel:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,letterSpacing:letterSpacing.eyebrow,textTransform:"uppercase"},card:{gap:space.sm,padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,...softShadow,...slotBox(recordCardSlot(slots),hairline)},eyebrow:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,letterSpacing:letterSpacing.eyebrow,textTransform:"uppercase",...cardText},hero:{...face(theme,"bold"),fontSize:size.verdict,lineHeight:lh(size.verdict,lineHeight.tight),color:color.text.primary,letterSpacing:letterSpacing.tight,...cardText},plot:{position:"relative",height:plotHeight,marginTop:space.xs},guide:{position:"absolute",top:0,bottom:0,width:hairline,backgroundColor:color.borderHairlineGreen},band:{position:"absolute",left:bandInset,right:space.xs,borderRadius:radius.sm,backgroundColor:color.brandSoft},point:{position:"absolute",width:dotSize,height:dotSize,marginLeft:dotOffset,marginTop:dotOffset,borderRadius:radius.pill,backgroundColor:color.brand,borderWidth:hairline,borderColor:color.surfaceCream},pointLatest:{backgroundColor:color.accent,borderColor:color.onAccent},edgeLabel:{position:"absolute",right:0,marginTop:-space.sm,...face(theme,"medium"),fontSize:size.tiny,lineHeight:lh(size.tiny,lineHeight.tight),color:color.text.muted,...cardText},dates:{flexDirection:"row",justifyContent:"space-between"},dateLabel:{...face(theme,"regular"),fontSize:size.tiny,lineHeight:lh(size.tiny,lineHeight.normal),color:color.text.muted,...cardText}})}function RecordSections({record:record,depth:depth,petName:petName,showLabs:showLabs=true,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit,nowMs:nowMs}){let styles=useScreenStyles(),local=useLocalStyles4(),now=nowMs??Date.now(),entities=react.useMemo(()=>factEdit?applyFactOverlay(record.entities,factEdit.overlay):record.entities,[record.entities,factEdit]),byType=react.useMemo(()=>{let order=[],groups=/* @__PURE__ */new Map;for(let entity of entities){let category=entity.category.trim();if(category.length===0||VACCINE_CATEGORIES.includes(category))continue;let bucket=groups.get(category);bucket===void 0?(order.push(category),groups.set(category,[entity])):bucket.push(entity)}return{order:orderEntityTypes(order),groups:groups}},[entities]),vaccineGroups=react.useMemo(()=>selectVaccineGroups(entities),[entities]),documents=react.useMemo(()=>documentsNewestFirst(record.documents),[record.documents]),ask=(build,label2,testID)=>onAsk?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{let built=build();onAsk(built.prompt,built.entityRef)},accessibilityRole:"button",accessibilityLabel:label2,style:[styles.pill,styles.pillAsk,local.ask],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.pillAskLabel,children:label2})}):null,editable=factEdit!==void 0&&factEdit.available;/* @__PURE__ */
|
|
434
446
|
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
435
447
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sections,children:[depth&&depth.conflicts.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-conflicts",children:[
|
|
436
448
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.needsAttention,count:depth.conflicts.length}),[...depth.conflicts].sort((a,b)=>conflictSeverityMeta(a.severity).rank-conflictSeverityMeta(b.severity).rank).map(conflict=>{let meta=conflictSeverityMeta(conflict.severity),scope=humanize(conflict.field??conflict.entityType);/* @__PURE__ */
|
|
@@ -443,7 +455,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.conflictCard,{borderColor:
|
|
|
443
455
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowMuted,children:[candidate.docId?documentTitle(record.documents[candidate.docId]??{title:null}):RECORD_SCREEN_COPY.uploadedDocument,candidate.collectedAt?formatRecordsDate(candidate.collectedAt):null].filter(Boolean).join(" · ")})]},index)),ask(()=>buildConflictAskPrompt(petName,{scopeLabel:scope,severity:conflict.severity,candidates:conflict.candidates.map(c=>({value:c.value,clinicName:c.docId?record.documents[c.docId]?.title??null:null}))},conflict.conflictId),RECORD_SCREEN_COPY.askConflict,`records-ask-conflict-${conflict.conflictId}`)]},conflict.conflictId)})]}):null,depth?.completeness?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-completeness",children:[
|
|
444
456
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
|
|
445
457
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
446
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([
|
|
458
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.coverageRow,children:[[RECORD_SCREEN_COPY.coverage.labs,depth.completeness.hasLabHistory],[RECORD_SCREEN_COPY.coverage.vaccines,depth.completeness.hasVaccinationHistory],[RECORD_SCREEN_COPY.coverage.weight,depth.completeness.hasWeightHistory],[RECORD_SCREEN_COPY.coverage.vitals,depth.completeness.hasVitalsHistory],[RECORD_SCREEN_COPY.coverage.exams,depth.completeness.hasPhysicalExamHistory],[RECORD_SCREEN_COPY.coverage.procedures,depth.completeness.hasProcedureHistory],[RECORD_SCREEN_COPY.coverage.genetics,depth.completeness.hasGeneticHistory],[RECORD_SCREEN_COPY.coverage.parasite,depth.completeness.hasParasitePreventionHistory],[RECORD_SCREEN_COPY.coverage.reproductive,depth.completeness.hasReproductiveHistory]].map(([label2,present])=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.coveragePill,present?[styles.chipTones.positive.bg,local.coverageOnFile]:[styles.chipTones.neutral.bg,local.coverageRest]],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label2}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:[{color:styles.rowMuted.color},local.coverageRestText]],children:label2})},label2))}),
|
|
447
459
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.metaRow,children:[
|
|
448
460
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.metaRow,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.dateRange(depth.completeness.earliestRecordAt,depth.completeness.latestRecordAt)})}):null,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).length>0?/* @__PURE__ */jsxRuntime.jsxs(Text,{style:local.pendingText,children:[RECORD_SCREEN_COPY.pendingReview,Object.entries(depth.completeness.entitiesPendingReview).filter(([,count])=>count>0).map(([type,count])=>`${entityTypeLabel(type)} (${count})`).join(", ")]}):null]})]}):null,documents.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-documents",children:[
|
|
449
461
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
|
|
@@ -453,7 +465,8 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.conflictCard,{borderColor:
|
|
|
453
465
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.identity}),
|
|
454
466
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:record.identity.map((field,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
455
467
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.identityLabel,children:field.label}),
|
|
456
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.identityValue,children:formatIdentityValue(field.value)})]},`${index}:${field.label}`))})]}):null,
|
|
468
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.identityValue,children:formatIdentityValue(field.value)})]},`${index}:${field.label}`))})]}):null,
|
|
469
|
+
/* @__PURE__ */jsxRuntime.jsx(CareTimeline,{series:record.entitySeries,testID:"record-section-care-timeline"}),record.forwardLooking.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-upcoming",children:[
|
|
457
470
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.upcomingCare,count:record.forwardLooking.length}),
|
|
458
471
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:record.forwardLooking.map((item,index)=>{let badge=dueBadge(item.dueAt,now);/* @__PURE__ */
|
|
459
472
|
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
@@ -464,18 +477,18 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDiv
|
|
|
464
477
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:group.items.map((row,index)=>{let body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
465
478
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
466
479
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:row.name}),row.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:row.detail}):null,ask(()=>buildEntityRowAskPrompt(petName,{entityTypeLabel:entityTypeLabel(row.entity.category),title:row.name,detail:row.detail},row.entity.category,row.key),RECORD_SCREEN_COPY.askEverfur,`records-ask-entity-${row.key}`)]}),
|
|
467
|
-
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:row.statusLabel,tone:VACCINE_CHIP_TONE[row.tone]})]});return editable&&isFactEditable(row.entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:row.entity,factEdit:factEdit,children:body},row.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:body},row.key)})})]},group.year))]}):null,byType.order.map(category=>{let rows=byType.groups.get(category)??[];if(rows.length===0)return null;let
|
|
480
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:row.statusLabel,tone:VACCINE_CHIP_TONE[row.tone]})]});return editable&&isFactEditable(row.entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:row.entity,factEdit:factEdit,children:body},row.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:body},row.key)})})]},group.year))]}):null,byType.order.map(category=>{let rows=byType.groups.get(category)??[];if(rows.length===0)return null;let label2=entityTypeLabel(category);/* @__PURE__ */
|
|
468
481
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:`record-section-${category}`,children:[
|
|
469
|
-
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:
|
|
470
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:rows.map((entity,index)=>{let
|
|
482
|
+
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:label2,count:rows.length}),
|
|
483
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:rows.map((entity,index)=>{let summary=entityRowSummary(entity,{formatEntityValue:formatEntityValue,formatRecordsDate:formatRecordsDate,humanize:humanize}),detail=summary.detail,row=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
471
484
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
472
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:
|
|
485
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:summary.title}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null,ask(()=>buildEntityRowAskPrompt(petName,{entityTypeLabel:label2,title:summary.title,detail:detail},category,entity.key),RECORD_SCREEN_COPY.askEverfur,`records-ask-entity-${entity.key}`)]}),entity.status?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:humanize(entity.status)}):null]});return editable&&isFactEditable(entity)&&factEdit?/* @__PURE__ */jsxRuntime.jsx(FactEditAffordance,{entity:entity,factEdit:factEdit,children:row},entity.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:row},entity.key)})})]},category)}),depth&&depth.physicalExams.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-exams",children:[
|
|
473
486
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.physicalExams,count:depth.physicalExams.length}),depth.physicalExams.map(exam=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
474
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.rowTitle,local.cardTitle],accessibilityRole:"header",children:exam.observedOn?formatRecordsDate(exam.observedOn):DEPTH_COPY.exam}),exam.systems.map((system,index)=>{let abnormal=system.findingStatus==="abnormal",
|
|
475
|
-
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[bodySystemLabel(system.system),
|
|
487
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.rowTitle,local.cardTitle],accessibilityRole:"header",children:exam.observedOn?formatRecordsDate(exam.observedOn):DEPTH_COPY.exam}),exam.systems.map((system,index)=>{let abnormal=system.findingStatus==="abnormal",label2=abnormal?DEPTH_COPY.abnormal:system.findingStatus==="not_examined"?DEPTH_COPY.notExamined:DEPTH_COPY.normal;/* @__PURE__ */
|
|
488
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],accessible:true,accessibilityRole:"text",accessibilityLabel:[bodySystemLabel(system.system),label2,abnormal?system.finding:null].filter(Boolean).join(", "),children:[
|
|
476
489
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
477
490
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:bodySystemLabel(system.system)}),abnormal&&system.finding?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:system.finding}):null]}),
|
|
478
|
-
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:
|
|
491
|
+
/* @__PURE__ */jsxRuntime.jsx(Chip,{label:label2,tone:abnormal?"warning":system.findingStatus==="not_examined"?"neutral":"positive"})]},system.system)}),ask(()=>buildPhysicalExamAskPrompt(petName,{observedOn:exam.observedOn?formatRecordsDate(exam.observedOn):null,abnormal:exam.systems.filter(s=>s.findingStatus==="abnormal").map(s=>({system:bodySystemLabel(s.system),finding:s.finding??""}))},exam.examId),RECORD_SCREEN_COPY.askExam,`records-ask-exam-${exam.examId}`)]},exam.examId))]}):null,depth&&depth.clinicianNotes.length>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.section,testID:"record-section-notes",children:[
|
|
479
492
|
/* @__PURE__ */jsxRuntime.jsx(SectionHeader,{title:RECORD_SCREEN_COPY.visitNotes,count:depth.clinicianNotes.length}),depth.clinicianNotes.map(note=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.card,children:[
|
|
480
493
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.rowTitle,local.cardTitle],accessibilityRole:"header",children:note.observedOn?formatRecordsDate(note.observedOn):DEPTH_COPY.visitNote}),note.sections.map((section,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.noteSection,index>0?styles.rowDivider:null],children:[
|
|
481
494
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteLabel,children:soapSectionLabel(section.section)}),
|
|
@@ -491,64 +504,76 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.row,index>0?styles.rowDiv
|
|
|
491
504
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:depth.encounters.map((encounter,index)=>{let detail=[encounter.date?formatRecordsDate(encounter.date):null,encounter.clinicName,encounter.veterinarian].filter(p=>p&&p!=="-").join(" · ");/* @__PURE__ */
|
|
492
505
|
return jsxRuntime.jsx(reactNative.View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowMain,children:[
|
|
493
506
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
|
|
494
|
-
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},coverageRestText:{},coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){react.useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label,meta){return`${label} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct2=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct2}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&¤t.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&¤t.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function buildRequestRail(request){return buildRailEvents(request)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles8(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
|
|
507
|
+
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record.disclaimer})]})}function heldCount(heldTotal,pending){return heldTotal>0?heldTotal:Object.values(pending).reduce((sum,count)=>sum+count,0)}function useLocalStyles4(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth;return reactNative.StyleSheet.create({sections:{gap:space.lg+space.xs},vaccineGroup:{gap:space.xs+1,marginBottom:space.sm},vaccineYear:{...face(theme,"monoMedium"),fontSize:type.size.micro,lineHeight:type.size.micro+space.xs,color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",paddingTop:space.xs+2},ask:{marginTop:space.lg},conflictCard:{borderRadius:radius.md,borderWidth:1,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm,...slotBox(recordCardSlot(theme.slots),1)},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...slotText(recordCardSlot(theme.slots))},candidate:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,paddingTop:space.sm},coverageRow:{flexDirection:"row",flexWrap:"wrap",gap:space.sm,paddingVertical:space.md},coveragePill:{borderRadius:radius.pill,paddingHorizontal:space.sm+space.xs/2,paddingVertical:space.xs+1},coverageText:{...face(theme,"medium"),fontSize:type.size.caption,lineHeight:type.size.caption+space.xs-1},coverageRest:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},coverageRestText:{},coverageOnFile:theme.slots.chip?.borderRadius===void 0?{}:{borderRadius:theme.slots.chip.borderRadius},metaRow:{flexDirection:"row",alignItems:"center",gap:space.sm,paddingBottom:space.md},metaText:{flex:1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},pendingText:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,paddingBottom:space.md},identityLabel:{...face(theme,"medium"),fontSize:type.size.bodyTight,lineHeight:Math.round(type.size.bodyTight*type.lineHeight.snug),color:color.text.secondary},identityValue:{flexShrink:1,textAlign:"right",...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},cardTitle:{paddingTop:space.sm},noteSection:{paddingVertical:space.md,gap:space.xs},noteLabel:{...face(theme,"bold"),fontSize:type.size.bodyTight,color:color.text.secondary,textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},noteBody:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.primary},noteBodyMuted:{...face(theme,"regular"),fontSize:type.size.body+1,lineHeight:Math.round((type.size.body+1)*type.lineHeight.relaxed),color:color.text.muted,fontStyle:"italic"}})}var CALL_CLINIC_COPY=/* @__PURE__ */Object.freeze({heading:"A quick call can help",fallbackPrompt:"Reaching out to the clinic directly often speeds up a slow records request.",call:"Call the clinic",callAt:phone=>`Call the clinic at ${phone}`});function presentConsentText(consentText){return typeof consentText=="string"&&consentText.trim().length>0?consentText:null}function isConsentTextMissing(consentVersion,consentText){return typeof consentVersion=="string"&&consentVersion.length>0&&presentConsentText(consentText)===null}var CONSENT_TEXT_MISSING_WARNING="[everfur] consentVersion was passed without consentText, so the records consent gate shows no consent text above Allow. Pass the consent text your member agrees to as consentText, next to its consentVersion.",warned=false;function warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment3()===!0}catch{development=false}if(!development)return;warned=true;let globalConsole=globalThis.console;try{globalConsole?.warn?.(CONSENT_TEXT_MISSING_WARNING)}catch{}}function useConsentTextWarning(consentVersion,consentText,isDevelopment3){react.useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=reactNative.useColorScheme();return colorScheme==="dark"?"dark":colorScheme==="light"?"light":null}function isThenable2(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&typeof value.then=="function"}function useRnReducedMotion(){let[reduced,setReduced]=react.useState(false);return react.useEffect(()=>{let mounted=true,query=reactNative.AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(reactNative.AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=reactNative.AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=reactNative.PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(reactNative.PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=reactNative.Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(reactNative.Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return react.useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=reactNative.Platform?.OS;return typeof os=="string"?os:null}catch{return null}}function contrastSignal(){return platformOS()==="android"?{query:"isHighTextContrastEnabled",event:"highTextContrastChanged"}:{query:"isDarkerSystemColorsEnabled",event:"darkerSystemColorsChanged"}}function useRnHighContrast(){let[on,setOn]=react.useState(false);return react.useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=reactNative.AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(reactNative.AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=reactNative.AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(reactNative.AccessibilityInfo,event,value=>setOn(value===true)):void 0;return()=>{mounted=false,subscription?.remove?.()}},[]),on}function rnPlatformMonoFamily(){return platformOS()==="ios"?"Menlo":SYSTEM_MONO_FAMILY}function isDevelopment(){return globalThis.__DEV__!==false}var warnedFaces=/* @__PURE__ */new Set;function warnUnregisteredFace(family){if(!isDevelopment()||warnedFaces.has(family))return;warnedFaces.add(family);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme names the font face "${family}", which this app has not registered; the SDK renders the platform font at that weight instead. Register the font file (expo-font or your native font assets) or name a registered face.`)}catch{}}function rnIsFontRegistered(family){let loader=globalThis.expo?.modules?.ExpoFontLoader,getLoadedFonts=loader?.getLoadedFonts;if(typeof getLoadedFonts!="function")return null;let loaded;try{loaded=getLoadedFonts.call(loader)}catch{return null}if(!Array.isArray(loaded)||loaded.length===0)return null;let registered=loaded.includes(family);return registered||warnUnregisteredFace(family),registered}var warnedRemoteFonts=/* @__PURE__ */new Set;function remoteFontFields(theme){let fields=[];return theme.type.fontSources.length>0&&fields.push("fontSources"),Object.values(theme.type.fontUrls).some(url=>typeof url=="string"&&url.length>0)&&fields.push("fontUrls"),fields}var REMOTE_FONT_LABEL=/* @__PURE__ */Object.freeze({fontSources:"appearance.fonts (font_sources)",fontUrls:"font_urls"});function warnRemoteFonts(theme){if(!isDevelopment())return;let fresh=remoteFontFields(theme).filter(field=>!warnedRemoteFonts.has(field));if(fresh.length===0)return;for(let field of fresh)warnedRemoteFonts.add(field);let globalConsole=globalThis.console;try{globalConsole?.warn?.(`[everfur] The theme sets ${fresh.map(field=>REMOTE_FONT_LABEL[field]).join(" and ")}, which only the web SDK loads. React Native does not download fonts: register the font file with expo-font (or your native font assets) and name the family. Until then the SDK renders the family as named, or the platform font when the app reports that family missing.`)}catch{}}function useRnResolvedTheme(theme){react.useEffect(()=>{try{warnRemoteFonts(theme)}catch{}},[theme])}var rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,useResolvedTheme:useRnResolvedTheme,isDevelopment:isDevelopment});var isDevelopment2=()=>rnThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment2)}var MAX_MB=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_COPY=/* @__PURE__ */Object.freeze({title:petName=>`Upload ${petNameOr(petName)}’s records`,screenTitle:"Upload a document",subtitle:petName=>`Already have lab results, a vet summary, or test reports? Add them here and we’ll read them and pull out ${petNameOr(petName)}’s health markers.`,noPet:"Select a pet first, then upload their records.",cardTitle:"Add records",cardSubtitle:`Upload PDF records you already have, up to ${MAX_MB} MB each. You can pick several at once. We’ll read them and add the results to your records.`,chooseFiles:"Choose a file",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total}…`,cancel:"Cancel",cancelA11y:"Cancel these uploads",received:done=>`${done===1?"Record received.":`${done} records received.`} We’ll read and review ${done===1?"it":"them"}, then add the results to your records, usually within 1-2 business days.`,retryFailed:failed=>`Retry ${failed} that didn’t upload`,haveMore:"Have more?",addMore:"Upload another document",addMoreA11y:"Upload another document",done:"Done",doneA11y:"Done, view records",errors:/* @__PURE__ */Object.freeze({start:"We couldn’t start that upload. Check your connection and try again.",startPlain:"We couldn’t start that upload. Please try again.",upload:"We couldn’t upload that record. Check your connection and try again."})}),UPLOAD_PHOTO_COPY=/* @__PURE__ */Object.freeze({note:"A PDF, or a photo of a paper record. Add them all; we sort them by date.",takePhoto:"Take a photo",takePhotoMeta:"of a paper record",choosePhotos:"Choose from photos",chooseFileMeta:"PDF",haveMoreLead:"PDFs and photos of paper records both work. Add them all; we sort them by date.",unreadable:"We can’t read this kind of file. Upload a PDF or a photo of the record."});function uploadActionA11y(label2,meta){return`${label2} ${meta}`}var MAX_MB2=Math.round(MAX_UPLOAD_BYTES/(1024*1024)),UPLOAD_QUEUE_COPY=/* @__PURE__ */Object.freeze({queued:"Queued",verifying:"Verifying…",done:"Done",failed:"Failed",uploading:(done,total)=>`Uploading ${Math.min(done+1,total)} of ${total} records`,uploaded:(done,total)=>`${done} of ${total} records uploaded`});function uploadItemStatusLabel(item){let pct3=Math.round(item.progress*100);switch(item.status){case"done":return UPLOAD_QUEUE_COPY.done;case"failed":return UPLOAD_QUEUE_COPY.failed;case"uploading":return item.progress>=1?UPLOAD_QUEUE_COPY.verifying:`${pct3}%`;case"queued":return UPLOAD_QUEUE_COPY.queued;default:return null}}function skippedFilesMessage(skipped,photosLive=false){if(skipped.length===0)return null;let nameList=entries=>{let names=entries.map(e=>e.name??"");return names.length<=3?names.join(", "):`${names.slice(0,3).join(", ")} and ${names.length-3} more`},tooLarge=skipped.filter(s=>s.reason==="too_large"),unsupported=skipped.filter(s=>s.reason==="unsupported");if(photosLive){let lines=[];return unsupported.length>0&&lines.push(UPLOAD_PHOTO_COPY.unreadable),tooLarge.length>0&&lines.push(`Didn’t upload: ${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB.`),lines.join(" ")}let parts=[];return unsupported.length>0&&parts.push(`${nameList(unsupported)} ${unsupported.length>1?"are not PDFs":"is not a PDF"}`),tooLarge.length>0&&parts.push(`${nameList(tooLarge)} ${tooLarge.length>1?"are":"is"} over ${MAX_MB2} MB`),`Didn’t upload: ${parts.join("; ")}. We can only read PDFs up to ${MAX_MB2} MB right now.`}function skippedOf(queue){let out=[];for(let item of queue)item.status==="skipped"&&item.skipReason!==null&&out.push({name:item.name,reason:item.skipReason});return out}var RECORDS_RECOVERY_COPY=/* @__PURE__ */Object.freeze({email:"Clinic email",emailPlaceholder:"records@clinic.com",emailError:"Enter a valid clinic email.",updateEmail:"Update email & resend",retry:"Retry sending",retryA11y:"Retry sending records request",retryHint:"Save the updated email first, then retry.",cancelRequest:"Cancel request",keepRequest:"Keep it",uploadInstead:"Upload instead",cancelQuestion:"Cancel this request?",cancelConsequence:"We’ll stop sending reminders to the clinic. If the clinic has already sent records, they may still arrive. You can start a new request or upload your own records anytime."});function useRecordsRecovery({request:request,onRecovered:onRecovered,canUpload:canUpload=false},controller){let[email2,setEmailValue]=react.useState(""),[busy,setBusy]=react.useState(false),[error,setError]=react.useState(null),[confirmingRevoke,setConfirmingRevoke]=react.useState(false),[settled,setSettled]=react.useState(null),locked=react.useRef(false),active=react.useRef(false),generation=react.useRef(0);react.useEffect(()=>(active.current=true,()=>{active.current=false,generation.current+=1}),[controller]);let current=settled!==null&&settled.before===request.updatedAt?{...settled.value,canRetrySend:request.canRetrySend===true&&settled.value.canRetrySend===true,canUpdateClinicEmail:request.canUpdateClinicEmail===true&&settled.value.canUpdateClinicEmail===true,canRevoke:request.canRevoke===true&&settled.value.canRevoke===true,canConvertToUpload:request.canConvertToUpload===true&&settled.value.canConvertToUpload===true}:request,trimmed=email2.trim(),validEmail=trimmed.length<=320&&!Array.from(trimmed).some(c=>c.charCodeAt(0)<=32||c.charCodeAt(0)===127)&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed),hasEmailEdit=current.canUpdateClinicEmail===true&&trimmed.length>0,canRetry=current.canRetrySend===true&&!busy&&!hasEmailEdit,canUpdateEmail=current.canUpdateClinicEmail===true&&!busy&&validEmail,canConvert=current.canConvertToUpload===true&&canUpload,run=async kind=>{let allowed={retry:canRetry,email:canUpdateEmail,revoke:current.canRevoke===true&&confirmingRevoke,convert:canConvert};if(locked.current||!active.current||!allowed[kind])return;locked.current=true,setBusy(true),setError(null);let revision=generation.current,live=()=>active.current&&revision===generation.current;try{let result=kind==="retry"?await controller.retryRequest(request.id):kind==="email"?await controller.updateClinicEmail(request.id,trimmed):kind==="revoke"?await controller.revokeRequest(request.id):await controller.convertToUpload(request.id);if(!live())return;if(!result.ok){setError(result.error);return}if(result.value.id!==request.id||result.value.petRef!==request.petRef){setError(makeEverfurError("internalError"));return}setSettled({before:request.updatedAt,value:result.value}),setEmailValue(""),setConfirmingRevoke(!1),onRecovered()}catch{live()&&setError(makeEverfurError("internalError"))}finally{locked.current=false,live()&&setBusy(false)}};return{request:current,email:email2,busy:busy,error:error,canRetry:canRetry,canUpdateEmail:canUpdateEmail,canConvert:canConvert,hasEmailEdit:hasEmailEdit,confirmingRevoke:confirmingRevoke&¤t.canRevoke===true,emailInvalid:trimmed.length>0&&!validEmail,setEmail(value){locked.current||(setEmailValue(value),setError(null))},retry:()=>run("retry"),updateEmail:()=>run("email"),revoke:()=>run("revoke"),convert:()=>run("convert"),askRevoke(){!locked.current&¤t.canRevoke===true&&setConfirmingRevoke(true)},keepRequest(){locked.current||setConfirmingRevoke(false)}}}var RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","records_received","processing","ready"],OWNER_RAIL_STAGES=["requested","awaiting_upload","records_received","processing","ready"],CONVERTED_RAIL_STAGES=["requested","sent_to_clinic","awaiting_clinic","awaiting_upload","records_received","processing","ready"],REQUEST_TIMELINE_TITLES=/* @__PURE__ */Object.freeze({requested:"Request created",sent_to_clinic:"Sent to the clinic",awaiting_clinic:"Waiting on the clinic",awaiting_upload:"Add your records",records_received:"Records received",processing:"Preparing your records",parsing_failed:"Needs a closer look",manual_review:"Our team is reviewing it",ready:"Ready to view",delivery_failed:"Email could not be delivered",processing_failed:"Could not process the records",clinic_declined:"Clinic declined the request",clinic_no_records:"Clinic replied without your records",no_response:"No response from the clinic",revoked:"You cancelled this request"}),CLINIC_RAIL_TITLES=/* @__PURE__ */Object.freeze({requested:"Request sent",sent_to_clinic:"Clinic notified",awaiting_clinic:"Waiting for records…"}),CLINIC_RAIL_DETAILS=/* @__PURE__ */Object.freeze({notified:email2=>`A secure request went to ${email2}.`,received:"Everfur reads every page: dates, vaccines, labs and prescriptions.",added:petName=>`Added to ${petName}’s records`}),DETAILS=/* @__PURE__ */Object.freeze({delivered:"Email delivered to the clinic",emailing:"Emailing the clinic",bounced:"The clinic email did not go through",waiting:"Waiting for the clinic to send the records",upload:"Upload the records you already have",ownerAdded:"You added these records",clinicSent:"The clinic sent the records",preparing:"Getting your records ready to view",ready:"Your records are ready to view",parsingFailed:"We couldn’t read this one automatically",manualReview:"Checking these by hand so nothing’s missed",switchedTitle:"Stopped waiting on the clinic",switched:"You switched to uploading your own records"}),TERMINAL_DETAILS=/* @__PURE__ */Object.freeze({delivery_failed:"The clinic email could not be delivered",processing_failed:"We could not read these records",clinic_declined:"The clinic declined to release records",clinic_no_records:"The clinic replied without records",no_response:"No reply after repeated reminders",revoked:"You cancelled this request"}),WIRE_FROM_STATUS=/* @__PURE__ */Object.freeze({requested:"sent",awaiting_clinic:"awaiting_response",awaiting_upload:"awaiting_upload",received:"records_received",parsing:"parsing",in_review:"in_review",published:"published",failed:"failed",revoked:"revoked"});function wireStatusOf(request){return request.wireStatus??WIRE_FROM_STATUS[request.status]??"sent"}function reminderProgressLabel(status,reminderCount){return status!=="awaiting_response"||reminderCount<=0?null:`${reminderCount} ${reminderCount===1?"reminder":"reminders"} sent`}function reachedRailIndex(status){switch(status){case"submitted":case"sent":return 1;case"awaiting_response":return 2;case"records_received":return 3;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 4;case"published":return 5;default:return-1}}function deliveryDetail(request){switch(request.dispatchStatus){case"sent":return DETAILS.delivered;case"preparing":case"queued":case"sending":return DETAILS.emailing;case"failed":return DETAILS.bounced;default:return null}}function awaitingDetail(request,status){return reminderProgressLabel(status,request.reminderCount??0)??DETAILS.waiting}function isOwnerSourcedRequest(request){return request.source==="owner_provided"||!!request.convertedToUploadAt}function railDetail(key,request,status){let isOwnerSourced=isOwnerSourcedRequest(request);switch(key){case"sent_to_clinic":return deliveryDetail(request);case"awaiting_clinic":return awaitingDetail(request,status);case"awaiting_upload":return DETAILS.upload;case"records_received":return isOwnerSourced?DETAILS.ownerAdded:DETAILS.clinicSent;case"processing":return DETAILS.preparing;case"ready":return DETAILS.ready;default:return null}}function tookReviewBranch(request,status){return!!request.reviewStartedAt||status==="parsing_failed"||status==="review_email_failed"}function expandProcessingPhase(event,request,status){if(event.key!=="processing"||!tookReviewBranch(request,status))return[event];let atParsingFailed=status==="parsing_failed",published=status==="published",parsingFailedState=published?"done":atParsingFailed?"current":"done",reviewState=published?"done":atParsingFailed?"upcoming":"current";return[{key:"parsing_failed",title:REQUEST_TIMELINE_TITLES.parsing_failed,detail:DETAILS.parsingFailed,at:null,state:parsingFailedState},{key:"manual_review",title:REQUEST_TIMELINE_TITLES.manual_review,detail:DETAILS.manualReview,at:request.reviewStartedAt??null,state:reviewState}]}function convertedReachedIndex(status){switch(status){case"awaiting_upload":return 3;case"records_received":return 4;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 5;case"published":return 6;default:return 3}}function convertedClinicSwitchEvent(request){return{key:"awaiting_clinic",title:DETAILS.switchedTitle,detail:DETAILS.switched,at:request.convertedToUploadAt??null,state:"done"}}function ownerReachedIndex(status){switch(status){case"submitted":case"sent":return 0;case"awaiting_upload":return 1;case"records_received":return 2;case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return 3;case"published":return 4;default:return-1}}function railTimestamp(key,request,status){switch(key){case"requested":return request.createdAt||null;case"awaiting_clinic":return request.lastReminderAt??null;case"processing":return request.parsingStartedAt??request.reviewStartedAt??null;case"ready":return status==="published"&&request.updatedAt||null;default:return null}}function railEvent(key,request,status,state){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:railDetail(key,request,status),at:railTimestamp(key,request,status),state:state}}function terminalEvent(key,request){return{key:key,title:REQUEST_TIMELINE_TITLES[key],detail:TERMINAL_DETAILS[key]??null,at:request.updatedAt||null,state:"failed"}}function walkRail(stages,reached,request,status,replace){return stages.map((key,idx)=>{let replaced=replace?.(key)??null;if(replaced!==null)return replaced;let state=status==="published"||idx<reached?"done":idx===reached?"current":"upcoming";return railEvent(key,request,status,state)}).flatMap(event=>expandProcessingPhase(event,request,status))}function buildRequestTimeline(request,options={}){return inArtifactWords(buildRailEvents(request),request,options.petName??null,options.sandbox===true)}function buildRequestRail(request){return buildRailEvents(request)}function inArtifactWords(events,request,petName,sandbox){let clinicRail=request.source!=="owner_provided"&&!events.some(event=>event.key==="delivery_failed"),email2=request.clinicEmail?.trim()??"";return events.map(event=>{if(event.title!==REQUEST_TIMELINE_TITLES[event.key])return event;if(event.key==="ready")return{...event,title:CLINIC_RAIL_DETAILS.added(petNameOr(petName))};if(!clinicRail)return event;if(sandbox&&event.key==="sent_to_clinic")return{...event,title:RECORDS_SANDBOX_COPY.clinicNotContacted,detail:email2.length>0?RECORDS_SANDBOX_COPY.notEmailed(email2):null};let title=CLINIC_RAIL_TITLES[event.key]??event.title;return event.key==="sent_to_clinic"&&request.dispatchStatus==="sent"&&email2.length>0?{...event,title:title,detail:CLINIC_RAIL_DETAILS.notified(email2)}:event.key==="records_received"&&!isOwnerSourcedRequest(request)?{...event,title:title,detail:CLINIC_RAIL_DETAILS.received}:{...event,title:title}})}function buildRailEvents(request){let status=wireStatusOf(request),done=key=>railEvent(key,request,status,"done");if(status==="revoked")return[done("requested"),terminalEvent("revoked",request)];if(request.convertedToUploadAt)return status==="failed"?[done("requested"),done("sent_to_clinic"),convertedClinicSwitchEvent(request),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)]:walkRail(CONVERTED_RAIL_STAGES,convertedReachedIndex(status),request,status,key=>key==="awaiting_clinic"?convertedClinicSwitchEvent(request):null);if(request.source==="owner_provided"){if(status==="failed"||status==="clinic_declined")return[done("requested"),done("awaiting_upload"),done("records_received"),terminalEvent("processing_failed",request)];let reached2=ownerReachedIndex(status);return walkRail(OWNER_RAIL_STAGES,reached2<0?1:reached2,request,status)}if(status==="clinic_declined")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_declined",request)];if(status==="clinic_responded_no_records")return[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("clinic_no_records",request)];if(status==="failed"){let code=request.failureCode??null;return code==="no_response"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),terminalEvent("no_response",request)]:code==="hard_bounce"||code==="dispatch_failed"?[done("requested"),terminalEvent("delivery_failed",request)]:code==="parse_timeout"||code==="parse_error"||request.dispatchStatus==="sent"?[done("requested"),done("sent_to_clinic"),done("awaiting_clinic"),done("records_received"),terminalEvent("processing_failed",request)]:[done("requested"),terminalEvent("delivery_failed",request)]}let reached=reachedRailIndex(status);return walkRail(RAIL_STAGES,reached<0?1:reached,request,status)}var A11Y_STATE=/* @__PURE__ */Object.freeze({done:"completed",current:"in progress",failed:"needs attention",upcoming:"not started"}),DOT_SIZE=28,NOW="Now",DOT_CORE_SIZE=10;function RequestTimeline({request:request,petName:petName}){let styles=useStyles9(),sandbox=useRecordsSandboxTenant(),events=buildRequestTimeline(request,{petName:petName??null,sandbox:sandbox});/* @__PURE__ */
|
|
495
508
|
return jsxRuntime.jsx(reactNative.View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsxRuntime.jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date2=event.at?formatRecordsInstant(event.at):null,a11yParts=[event.title,event.detail,date2,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
|
|
496
509
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
|
|
497
510
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.railColumn,children:[
|
|
498
511
|
/* @__PURE__ */jsxRuntime.jsx(TimelineDot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.connector,event.state==="done"&&styles.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),
|
|
499
512
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.body,children:[
|
|
500
513
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.titleRow,children:[
|
|
501
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.title,event.state==="current"&&(event.key==="ready"?styles.titleReadyCurrent:styles.titleCurrent),event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.now,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date2?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:date2}):null]}),event.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function
|
|
514
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.title,event.state==="current"&&(event.key==="ready"?styles.titleReadyCurrent:styles.titleCurrent),event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.now,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date2?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:date2}):null]}),event.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function useStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,type:type}=theme,{size:size}=type;return reactNative.StyleSheet.create({container:{gap:0},row:{flexDirection:"row",alignItems:"flex-start",gap:12},railColumn:{alignItems:"center",width:DOT_SIZE},body:{flex:1,paddingBottom:18,gap:2},titleRow:{flexDirection:"row",alignItems:"center",gap:8},dot:{width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,alignItems:"center",justifyContent:"center"},dotDone:{backgroundColor:color.brand,borderWidth:2,borderColor:color.primaryEdge},dotFailed:{backgroundColor:color.danger},dotCurrent:{borderWidth:2,borderColor:color.brandInk,backgroundColor:color.surface},dotCurrentCore:{width:DOT_CORE_SIZE,height:DOT_CORE_SIZE,borderRadius:DOT_CORE_SIZE/2,backgroundColor:color.mark},now:{borderRadius:theme.radius.pill,backgroundColor:color.highlight,paddingHorizontal:theme.space.sm,paddingVertical:theme.space.xs/2},nowText:{...face(theme,"monoBold"),fontSize:size.tiny,lineHeight:size.tiny+4,letterSpacing:.6,color:color.onHighlight,textTransform:"uppercase"},dotUpcoming:{borderWidth:2,borderColor:color.structureEdge,backgroundColor:color.surface},glyph:{...face(theme,"bold"),fontSize:size.caption,lineHeight:size.caption+2,color:color.surface},glyphOnBrand:{color:color.onPrimary},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,marginVertical:2},connectorDone:{backgroundColor:color.primaryEdge},title:{flexShrink:1,...face(theme,"bold"),fontSize:size.bodyTight,lineHeight:size.bodyTight+4,color:color.text.primary},titleCurrent:{color:color.brandInk},titleReadyCurrent:{color:brandedSuccessInk(theme)??color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...face(theme,"regular")},date:{marginLeft:"auto",...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+4,color:color.text.muted},detail:{...face(theme,"regular"),fontSize:size.caption,lineHeight:size.caption+5,color:color.text.muted},detailUpcoming:{color:color.text.muted,opacity:.7}})}function failureOf(result){if(typeof result!="object"||result===null||result.ok!==false)return null;let error=result.error;return typeof error=="object"&&error!==null&&typeof error.displayMessage=="string"?error:makeEverfurError("internalError")}function useConsentGrant(onGrant){let[pending,setPending]=react.useState(false),[error,setError]=react.useState(null),inFlight=react.useRef(false),mounted=react.useRef(true);react.useEffect(()=>(mounted.current=true,()=>{mounted.current=false}),[]);let latest=react.useRef(onGrant);latest.current=onGrant;let grant=react.useCallback(()=>{if(inFlight.current)return;let out;try{out=latest.current()}catch{setError(makeEverfurError("internalError"));return}if(out==null||typeof out.then!="function")return;inFlight.current=true,setPending(true),setError(null);let settle=failure=>{inFlight.current=false,mounted.current&&(setPending(false),setError(failure))};out.then(result=>settle(failureOf(result)),()=>settle(makeEverfurError("internalError")))},[]);return{pending:pending,error:error,grant:grant}}function renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
502
515
|
return jsxRuntime.jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
503
516
|
return jsxRuntime.jsx(ConsentUnavailableState,{});case"session_required":/* @__PURE__ */
|
|
504
517
|
return jsxRuntime.jsx(SessionRequiredState,{});case"withheld":/* @__PURE__ */
|
|
505
518
|
return jsxRuntime.jsx(WithheldState,{});case"pet_not_found":case"error":/* @__PURE__ */
|
|
506
|
-
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function makeGrantHandler(records,consentVersion){return()=>{let version=resolveConsentVersion(consentVersion,records.consent);if(version.length===0)return;let key=`records-consent-${Date.now().toString(36)}`;return records.grantConsent(version,key)}}function UploadQueue({records:records}){let styles=
|
|
507
|
-
return jsxRuntime.jsxs(reactNative.View,{style:styles.timeline,testID:"records-upload-queue",children:[skipped!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:styles.errorText,children:skipped}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:records.isUploading?UPLOAD_QUEUE_COPY.uploading(done,rows.length):UPLOAD_QUEUE_COPY.uploaded(done,rows.length),children:rows.map(item=>{let
|
|
519
|
+
return jsxRuntime.jsx(ErrorState,{error:errorView.error,onRetry:records.refresh});default:return assertNever(errorView)}}function makeGrantHandler(records,consentVersion){return()=>{let version=resolveConsentVersion(consentVersion,records.consent);if(version.length===0)return;let key=`records-consent-${Date.now().toString(36)}`;return records.grantConsent(version,key)}}function UploadQueue({records:records}){let styles=useStyles10(),queue=records.uploadQueue;if(queue.length===0)return null;let rows=queue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,skipped=skippedFilesMessage(skippedOf(queue));/* @__PURE__ */
|
|
520
|
+
return jsxRuntime.jsxs(reactNative.View,{style:styles.timeline,testID:"records-upload-queue",children:[skipped!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"polite",style:styles.errorText,children:skipped}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",accessibilityLabel:records.isUploading?UPLOAD_QUEUE_COPY.uploading(done,rows.length):UPLOAD_QUEUE_COPY.uploaded(done,rows.length),children:rows.map(item=>{let pct3=Math.round(item.progress*100);
|
|
508
521
|
/* @__PURE__ */
|
|
509
522
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRow,testID:`records-upload-file-${item.status}`,children:[
|
|
510
523
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.uploadRowHead,children:[
|
|
511
524
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowLabel,children:item.name??""}),
|
|
512
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:
|
|
525
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct3},children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.progressFill,{width:`${pct3}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles10(),text4=presentConsentText(consentText),{pending:pending,error:error,grant:grant}=useConsentGrant(onGrant);return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(RECORDS_COPY.consentRequired)},[]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,testID:"records-consent-gate",children:[
|
|
513
526
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.askText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text4!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text4}):null,
|
|
514
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:grant,disabled:pending,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,accessibilityState:{disabled:pending,busy:pending},style:pending?styles.disabledButton:styles.primaryButton,testID:"records-consent-allow",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:pending?styles.disabledLabel:styles.primaryLabel,children:RECORDS_COPY.allow})}),error!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",testID:"records-consent-grant-error",children:error.displayMessage}):null]})}function AlertState({label:
|
|
527
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:grant,disabled:pending,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,accessibilityState:{disabled:pending,busy:pending},style:pending?styles.disabledButton:styles.primaryButton,testID:"records-consent-allow",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:pending?styles.disabledLabel:styles.primaryLabel,children:RECORDS_COPY.allow})}),error!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",testID:"records-consent-grant-error",children:error.displayMessage}):null]})}function AlertState({label:label2,glyph:glyph}){let styles=useStyles10();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(label2)},[label2]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:label2,children:[
|
|
515
528
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
|
|
516
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:
|
|
529
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:label2})]})}function ConsentUnavailableState(){/* @__PURE__ */
|
|
517
530
|
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.consentRequired,glyph:"empty"})}function SessionRequiredState(){/* @__PURE__ */
|
|
518
|
-
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}function
|
|
519
|
-
return jsxRuntime.
|
|
520
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
531
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}function SessionRequiredScreen({style:style,testID:testID}){let styles=useScreenStyles();/* @__PURE__ */
|
|
532
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],testID:testID,children:[
|
|
533
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:/* @__PURE__ */jsxRuntime.jsx(SessionRequiredState,{})}),
|
|
534
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function WithheldState(){/* @__PURE__ */
|
|
535
|
+
return jsxRuntime.jsx(AlertState,{label:RECORDS_COPY.recordUnavailable,glyph:"withheld"})}function ErrorState({error:error,onRetry:onRetry}){let styles=useStyles10();return react.useEffect(()=>{reactNative.AccessibilityInfo.announceForAccessibility?.(error.displayMessage)},[error.displayMessage]),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:[
|
|
536
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:error.displayMessage}),error.retryable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onRetry,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.retry,style:styles.primaryButton,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.primaryLabel,children:RECORDS_COPY.retry})}):null]})}function ClinicCallCard({call:call,prompt:prompt}){let styles=useStyles10(),intro=prompt.trim().length>0?prompt:CALL_CLINIC_COPY.fallbackPrompt;/* @__PURE__ */
|
|
521
537
|
return jsxRuntime.jsxs(reactNative.View,{style:styles.callCard,accessibilityRole:"summary",children:[
|
|
522
538
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
|
|
523
539
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineMeta,children:intro}),
|
|
524
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function
|
|
525
|
-
return
|
|
540
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>{reactNative.Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles12(theme),[theme])}function makeStyles12(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(recordCardSlot(slots),reactNative.StyleSheet.hairlineWidth),cardText=slotText(recordCardSlot(slots)),lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,glyphSize=space.xxl+space.sm,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,softShadow={shadowColor:color.brand,shadowOffset:{width:0,height:space.xs},shadowRadius:space.sm,shadowOpacity:.08,elevation:space.xs};return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},withheldGlyph:{width:glyphSize,height:glyphSize,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,borderWidth:hairline,borderColor:color.cautionAccent},errorText:{...face(theme,"regular"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:errorColor,textAlign:"center",marginBottom:space.md},askText:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.primary,textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},linkButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...softShadow,...slotBox(slots.primaryButton)},linkLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,letterSpacing:letterSpacing.tight,...slotText(slots.primaryButton)},disabledButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.surfaceSubtle,borderWidth:hairline,borderColor:color.brandBorder},disabledLabel:{...face(theme,"bold"),color:color.text.muted,fontSize:size.body,letterSpacing:letterSpacing.tight},list:{flex:1},listContent:{padding:space.lg,gap:space.md},timeline:{paddingVertical:space.md,paddingHorizontal:space.lg,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,gap:space.xs,...softShadow,...card},timelineTitle:{...headingFace(theme,"bold"),fontSize:size.heading,lineHeight:lh(size.heading,lineHeight.snug),color:color.text.primary,letterSpacing:letterSpacing.tight,...cardText},timelineLabel:{...headingFace(theme,"bold"),fontSize:size.subtitle,lineHeight:lh(size.subtitle,lineHeight.snug),color:color.text.secondary,letterSpacing:letterSpacing.tight,...cardText},callCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...card},timelineMeta:{...face(theme,"regular"),fontSize:size.bodyTight,lineHeight:lh(size.bodyTight,lineHeight.normal),color:color.text.muted,...cardText},recordBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...softShadow,...card},row:{flexDirection:"row",justifyContent:"space-between",gap:space.md,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},rowLabel:{...face(theme,"regular"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.muted,flexShrink:1,...cardText},rowValue:{...face(theme,"medium"),fontSize:size.body,lineHeight:lh(size.body,lineHeight.normal),color:color.text.primary,textAlign:"right",flexShrink:1,...cardText},disclaimer:{...face(theme,"regular"),fontSize:size.caption,lineHeight:lh(size.caption,lineHeight.normal),color:color.text.muted,marginTop:space.md},uploadRow:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},uploadRowHead:{flexDirection:"row",justifyContent:"space-between",gap:space.md},progressTrack:{height:space.xs,borderRadius:radius.pill,backgroundColor:color.brandSofter,overflow:"hidden",width:"100%"},progressFill:{height:"100%",backgroundColor:color.brand}})}var REQUEST_DOCUMENTS_COPY=/* @__PURE__ */Object.freeze({download:"Download",downloadA11y:title=>`Download, ${title}`,listA11y:"You added these records"});function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}function formatLabel(docFormat){let trimmed=docFormat?.trim();return trimmed?trimmed.toUpperCase():null}function requestDocumentRows(items){/* @__PURE__ */
|
|
541
|
+
return Object.freeze(items.map(item=>{let format=formatLabel(item.docFormat),date2=item.receivedAt?formatRecordsInstant(item.receivedAt):null,title=item.fileName??format??date2??item.sourceDocId,meta=[item.fileName!==null&&format!==null&&item.fileName.toUpperCase().endsWith(`.${format}`)||title===format?null:format,item.byteSize!==null?formatBytes(item.byteSize):null,title===date2?null:date2].filter(part=>!!part).join(" · ");/* @__PURE__ */
|
|
542
|
+
return Object.freeze({key:item.sourceDocId,title:title,meta:meta||null,downloadUrl:item.downloadUrl})}))}function useRequestDocuments(requestId2,opts={}){let enabled=opts.enabled??true,client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[documents,setDocuments]=react.useState(null),[loading,setLoading]=react.useState(enabled),[error,setError]=react.useState(null),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(!enabled||userRef===null){setDocuments(null),setError(null),setLoading(false);return}setLoading(true),setError(null);let result=await client.listRequestDocuments(requestId2);gen!==generation.current||!live.current||(result.ok?setDocuments(result.value):(setDocuments(null),setError(result.error)),setLoading(false))},[client,enabled,requestId2,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]);let rows=react.useMemo(()=>documents===null?[]:requestDocumentRows(documents),[documents]),refresh=react.useCallback(()=>{load()},[load]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated";return react.useMemo(()=>({status:status,rows:rows,error:error,refresh:refresh}),[status,rows,error,refresh])}function announceLine(line2){if(!(reactNative.Platform.OS!=="ios"||line2===""))try{let announce=reactNative.AccessibilityInfo?.announceForAccessibility;typeof announce=="function"&&announce.call(reactNative.AccessibilityInfo,line2)}catch{}}function AnnounceLine({line:line2}){return react.useEffect(()=>{announceLine(line2)},[line2]),null}async function shareLinkViaOs(url){await reactNative.Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:url}:{message:url})}function RequestDocumentsList({requestId:requestId2,open:open=true,onOpenUrl:onOpenUrl,testID:testID="records-request-documents"}){let styles=useScreenStyles(),local=useLocalStyles5(),theme=useEverfurTheme(),documents=useRequestDocuments(requestId2,{enabled:open}),client=useEverfurRecordsDepthClient(),[savingKey,setSavingKey]=react.useState(null),[failedKey,setFailedKey]=react.useState(null),live=react.useRef(true),saving=react.useRef(null);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let save=async row=>{if(saving.current!==null)return;saving.current=row.key,setSavingKey(row.key),setFailedKey(null);let failed=true;try{let fresh=await client.listRequestDocuments(requestId2),doc=fresh.ok?fresh.value.find(item=>item.sourceDocId===row.key)??null:null;failed=doc===null,doc!==null&&live.current&&(onOpenUrl?await callHostAsync(onOpenUrl,doc.downloadUrl,"request_document"):failed=!await shareFileLinkViaOs(doc.downloadUrl).then(()=>!0,()=>!1))}catch{failed=true}finally{saving.current=null,live.current&&(setSavingKey(null),failed&&setFailedKey(row.key))}};return open?documents.status==="loading"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.loading,accessibilityState:{busy:true},testID:`${testID}-loading`,children:/* @__PURE__ */jsxRuntime.jsx(SkeletonBlock,{width:"100%",height:theme.space.lg+theme.space.md})}):documents.status==="error"&&isRecordsConsentRequired(documents.error)?null:documents.status==="error"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.errorRow,testID:`${testID}-error`,children:[
|
|
543
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,accessibilityRole:"alert",accessibilityLiveRegion:"polite",children:documents.error?.displayMessage??""}),
|
|
544
|
+
/* @__PURE__ */jsxRuntime.jsx(AnnounceLine,{line:documents.error?.displayMessage??""}),documents.error?.retryable===true?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:documents.refresh,testID:`${testID}-retry`}):null]}):documents.status==="empty"?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityRole:"list",accessibilityLabel:REQUEST_DOCUMENTS_COPY.listA11y,style:local.list,testID:testID,children:documents.rows.map((row,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.row,index===0?null:local.rowRule],children:[
|
|
545
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.rowText,children:[
|
|
546
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,numberOfLines:1,children:row.title}),row.meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.muted,local.tabular],children:row.meta}):null]}),
|
|
547
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_DOCUMENTS_COPY.download,kind:"outline",accessibilityLabel:REQUEST_DOCUMENTS_COPY.downloadA11y(row.title),busy:savingKey===row.key,onPress:()=>{save(row)},testID:`${testID}-download-${row.key}`}),failedKey===row.key?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
548
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.full],accessibilityRole:"alert",accessibilityLiveRegion:"polite",testID:`${testID}-save-failed-${row.key}`,children:RECORDS_EMPTY_COPY.error.title}),
|
|
549
|
+
/* @__PURE__ */jsxRuntime.jsx(AnnounceLine,{line:RECORDS_EMPTY_COPY.error.title})]}):null]},row.key))}):null}function useLocalStyles5(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles5(theme),[theme])}function makeLocalStyles5(theme){let{color:color,space:space}=theme;return reactNative.StyleSheet.create({loading:{paddingTop:space.sm},errorRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.sm,paddingTop:space.sm},list:{paddingTop:space.sm},row:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm,paddingVertical:space.sm},rowRule:{borderTopWidth:1,borderTopColor:color.brandBorder},rowText:{flex:1,minWidth:0},tabular:{fontVariant:["tabular-nums"]},full:{flexBasis:"100%"}})}function EverfurRecordsRequests(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
550
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(SessionRequiredScreen,{style:style,testID:"records-requests-session-required"}):/* @__PURE__ */jsxRuntime.jsx(RequestsBody,{...rest,style:style})})}function RequestsBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,style:style}){let styles=useScreenStyles(),local=useLocalStyles6(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),requests=react.useMemo(()=>selectRequestList(records.requests.filter(r=>r.petRef===petRef)),[records.requests,petRef]),ask=onAsk?request=>{let built=buildRecordsRequestAskPrompt(petName,{clinicName:request.clinicName??null,statusLabel:selectPrimaryLabel(request),status:request.status,heldItemCount:request.heldItemCount},request.id);onAsk(built.prompt,built.entityRef)}:void 0,body;return records.status==="loading"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-list-loading"}):records.status==="error"&&requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error?.displayMessage,onAction:records.error?.retryable?records.refresh:void 0,testID:"records-list-error"}):requests.length===0?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-list-empty"}):body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.list,testID:"records-list-results",children:requests.map(request=>/* @__PURE__ */jsxRuntime.jsx(RequestRow,{request:request,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:request.id}):void 0,onAsk:ask?()=>ask(request):void 0,onOpenUrl:onOpenUrl},request.id))}),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
526
551
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:REQUEST_LIST_COPY.title,onBack:onBack,testID:"records-list-header"}),requests.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,testID:"records-list-subtitle",children:REQUEST_LIST_COPY.subtitle(petName)}):null,
|
|
527
552
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.footer,children:[
|
|
528
553
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_LIST_COPY.requestRecords,accessibilityLabel:REQUEST_LIST_COPY.requestRecordsA11y,onPress:()=>onNavigate({name:"clinicPicker"}),testID:"records-list-new"}),
|
|
529
554
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_LIST_COPY.uploadOwn,kind:"outline",onPress:()=>onNavigate({name:"upload"}),testID:"records-list-upload-own"})]}):null,
|
|
530
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestRow({request:request,onOpen:onOpen,onAsk:onAsk}){let styles=useScreenStyles(),local=
|
|
555
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestRow({request:request,onOpen:onOpen,onAsk:onAsk,onOpenUrl:onOpenUrl}){let styles=useScreenStyles(),local=useLocalStyles6(),row=requestRowView(request),tone=selectRequestStatusTone(request),content=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
531
556
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.bubble,styles.chipTones[tone].bg],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
532
557
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.copy,children:[
|
|
533
558
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.source,numberOfLines:1,children:row.source}),
|
|
534
559
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.meta,numberOfLines:1,children:row.meta}),
|
|
535
560
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsxRuntime.jsx(Chip,{label:row.status,tone:tone})})]}),onOpen?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]});/* @__PURE__ */
|
|
536
|
-
return jsxRuntime.jsxs(reactNative.View,{style:local.row,testID:`records-request-row-${request.id}`,children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:row.a11yLabel,style:local.rowInner,testID:`records-request-open-${request.id}`,children:content}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.rowInner,accessible:true,accessibilityLabel:row.a11yLabel,children:content}),onOpen&&selectResumableUploadRequest(null,request)!==null?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.cardTitle,onPress:onOpen,testID:`records-request-resume-upload-${request.id}`}):null,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",accessibilityHint:row.source,onPress:onAsk,testID:`records-request-ask-${request.id}`}):null]})}function RecordsRequestsStatusCard({requests:requests,petName:petName,activeOnly:activeOnly=false,onOpen:onOpen}){let local=
|
|
561
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.row,testID:`records-request-row-${request.id}`,children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:row.a11yLabel,style:local.rowInner,testID:`records-request-open-${request.id}`,children:content}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.rowInner,accessible:true,accessibilityLabel:row.a11yLabel,children:content}),onOpen&&selectResumableUploadRequest(null,request)!==null?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.cardTitle,onPress:onOpen,testID:`records-request-resume-upload-${request.id}`}):null,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",accessibilityHint:row.source,onPress:onAsk,testID:`records-request-ask-${request.id}`}):null,isOwnerSourcedRequest(request)?/* @__PURE__ */jsxRuntime.jsx(RequestDocumentsList,{requestId:request.id,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},testID:`records-request-documents-${request.id}`}):null]})}function RecordsRequestsStatusCard({requests:requests,petName:petName,activeOnly:activeOnly=false,onOpen:onOpen}){let local=useLocalStyles6(),view=requestsStatusCardView(requests,petNameOr(petName),{activeOnly:activeOnly});return view===null||onOpen===void 0?null:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:view.a11yLabel,style:local.card,testID:"records-requests-status",children:[
|
|
537
562
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[local.cardBubble,view.processing?local.cardBubbleProcessing:null],accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
538
563
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.cardText,children:[
|
|
539
564
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,children:view.title}),
|
|
540
565
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:view.subtitle})]}),
|
|
541
|
-
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function
|
|
542
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DashboardBody,{...rest,style:style})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=
|
|
566
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,m)=>Math.round(size*m),bubble=space.xxl+space.xs/2;return reactNative.StyleSheet.create({subtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,paddingHorizontal:space.lg,paddingBottom:space.md},list:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.md},row:{borderRadius:radius.lg,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,paddingHorizontal:space.md+space.xs/2,paddingVertical:space.md,gap:space.sm},rowInner:{flexDirection:"row",alignItems:"center",gap:space.md},bubble:{width:bubble,height:bubble,borderRadius:bubble/2},copy:{flex:1,gap:space.xs+1},source:{...face(theme,"bold"),fontSize:type.size.body,lineHeight:lh(type.size.body,type.lineHeight.snug),color:color.text.primary},meta:{...face(theme,"regular"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.normal),color:color.text.muted},footer:{paddingHorizontal:space.lg,paddingTop:space.sm+space.xs/2,paddingBottom:space.lg,gap:space.sm+space.xs/2,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},card:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,paddingHorizontal:space.md+space.xs,paddingVertical:space.md,...slotBox(recordCardSlot(theme.slots),1)},cardBubble:{width:space.xl+space.xs/2,height:space.xl+space.xs/2,borderRadius:radius.pill,borderWidth:2,borderColor:color.brandInk},cardBubbleProcessing:{borderColor:color.warningStrong,backgroundColor:color.badgeBgCaution},cardText:{flex:1,gap:2},cardTitle:{...headingFace(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight,type.lineHeight.snug),color:color.brandInk,...slotText(recordCardSlot(theme.slots))},cardSubtitle:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,...slotText(recordCardSlot(theme.slots))}})}var readDepth=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,renderPending:renderPending,...guarded}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{alwaysShowWays:alwaysShowWays,...rest}=guarded,{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
567
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(SessionRequiredScreen,{style:style,testID:"dashboard-session-required"}):/* @__PURE__ */jsxRuntime.jsx(DashboardBody,{...rest,style:style})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles7(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),{runtime:runtime}=useEverfurContext(),photoWay=acceptsPhotos(records.uploadContentTypes)&&isCaptureAvailable(runtime.registry.services.camera),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth,depthEmpty),[provenance,setProvenance]=react.useState(null),onPointPress=react.useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequestFromClinic=clinicDecision.enabled||clinicDecision.isPending,markerList=markers.markers?.markers??[],hasMarkers=markerList.length>0,hasFullRecord=records.record!==null&&!records.record.isEmpty&&!records.record.withheld,drivingRequest=pickPetRecordsRequest(records.requests,petRef),petRequests=records.requests.filter(r=>r.petRef===petRef),openRequests=onNavigate?()=>onNavigate({name:"requests"}):void 0,errorView=records.status==="error"?selectErrorView(records,canGrant):null,consentGate=errorView!==null&&isConsentGate(errorView),dashboardState=deriveRecordsDashboardState({hasMarkers:hasMarkers&&!consentGate,requests:records.requests,petRef:petRef}),view=consentGate?selectDashboardView({recordLoading:false,hasFullRecord:false,recordError:false,markersLoading:false,markersError:false,hasMarkers:false,requestsLoading:false,dashboardState:dashboardState,drivingRequest:drivingRequest}):selectDashboardView({recordLoading:records.status==="loading",hasFullRecord:hasFullRecord,recordError:records.status==="error",markersLoading:markers.status==="loading",markersError:markers.status==="error",hasMarkers:hasMarkers,requestsLoading:records.status==="loading",dashboardState:dashboardState,drivingRequest:drivingRequest}),consentControl=errorView?.kind==="consent_required"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{testID:"dashboard-consent",children:renderErrorFamily(records,onGrant,canGrant,consentText)}):null,disclaimer=markers.markers?.disclaimer??records.record?.disclaimer??"",retryAll=()=>{records.refresh(),markers.refresh(),depth.refresh()},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,name=petNameOr(petName),askSummary=onAsk&&markers.markers?.summary?()=>{let built=buildMarkerSummaryAskPrompt(petName,markers.markers?.summary??{totalMarkers:0,inRangeCount:0,outOfRangeCount:0,unknownCount:0},petRef);onAsk(built.prompt,built.entityRef)}:void 0,askMarker=onAsk?marker=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null,statusText:marker.latest?markerStatusLabel(marker.latest.status).label:null,trajectoryText:trajectoryLabel(marker.trajectory,marker.points.length),meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,askReading=onAsk&&provenance?()=>{let{marker:marker,point:point}=provenance,built=buildMarkerReadingAskPrompt(petName,{canonicalName:marker.name,valueText:formatMarkerReading(point.value,marker.unit,point.qualitativeResult),collectedAt:formatRecordsDate(point.at),sourceClinic:point.sourceClinic,referenceText:point.refLow!==null||point.refHigh!==null?formatReferenceRange(point,marker.unit):null,flagged:point.status==="above"?"above":point.status==="below"?"below":null,reviewed:point.reviewed,entityId:point.docId??marker.markerId});setProvenance(null),onAsk(built.prompt,built.entityRef)}:void 0,labs=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[markers.markers?.summary?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(MarkerSummaryCard,{summary:markers.markers.summary,onAsk:askSummary,testID:"dashboard-marker-summary"})}):null,
|
|
543
568
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.lead,children:DASHBOARD_COPY.lead(petName)}),
|
|
544
569
|
/* @__PURE__ */jsxRuntime.jsx(MarkerTrendCarousel,{markers:markerList,featuredMarkerId:markers.markers?.featuredMarkerId??null,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.actions],children:[withRecord?/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"record",label:DASHBOARD_COPY.viewFullRecord,onPress:()=>onNavigate({name:"record"}),testID:"dashboard-full-record-action"}):null,
|
|
545
570
|
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"timeline",label:DASHBOARD_COPY.viewTimeline,onPress:()=>onNavigate({name:"timeline"}),testID:"dashboard-timeline-action"}),
|
|
546
571
|
/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"requests",label:REQUEST_LIST_COPY.allRequests,onPress:()=>onNavigate({name:"requests"}),testID:"dashboard-requests-action"})]}):null,addActions=inset=>onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.inset,local.addActions],testID:"dashboard-actions",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onPress:()=>onNavigate({name:"clinicPicker"}),style:local.addCta,testID:"dashboard-actions-clinic"}):null,
|
|
547
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.addCta,testID:"dashboard-actions-upload"})]}):null,body;if(
|
|
572
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.addCta,testID:"dashboard-actions-upload"})]}):null,body;if(errorView!==null&&!consentGate)body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retryAll:void 0,testID:"dashboard-error"}):renderErrorFamily(records,onGrant,canGrant,consentText);else switch(view){case"loading":body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"dashboard-loading"});break;case"record":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.contentTight,testID:"dashboard-record",children:[hasMarkers?labs:markers.status==="error"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[styles.inset,local.actions],children:/* @__PURE__ */jsxRuntime.jsx(ActionRow,{glyph:"retry",label:DASHBOARD_COPY.retryMarkers,onPress:retryAll,testID:"dashboard-markers-retry"})}):null,
|
|
548
573
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:records.record?/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:records.record,depth:depthView,petName:petName,showLabs:!hasMarkers,onNavigate:onNavigate,onAsk:onAsk}):null}),
|
|
549
574
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,activeOnly:true,onOpen:openRequests})}),addActions(),actions(true)]});break;case"error":body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(markers.error??records.error),message:(markers.error??records.error)?.displayMessage,onAction:(markers.error??records.error)?.retryable?retryAll:void 0,testID:"dashboard-error"});break;case"in_progress":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"dashboard-in-progress",children:[drivingRequest?/* @__PURE__ */jsxRuntime.jsx(InProgressCard,{request:drivingRequest,petName:name,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:drivingRequest.id}):void 0,onAsk:onAsk?()=>{let built=buildRecordsRequestAskPrompt(petName,{clinicName:drivingRequest.clinicName??null,statusLabel:selectPrimaryLabel(drivingRequest),status:drivingRequest.status,heldItemCount:drivingRequest.heldItemCount},drivingRequest.id);onAsk(built.prompt,built.entityRef)}:void 0}):null,
|
|
550
575
|
/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,onOpen:openRequests}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.ways,testID:"dashboard-ways",children:[canRequestFromClinic?/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:IN_PROGRESS_COPY.anotherClinic,sub:IN_PROGRESS_COPY.anotherClinicSub,onPress:()=>onNavigate({name:"clinicPicker"}),testID:"dashboard-way-clinic"}):null,
|
|
551
|
-
/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:REQUEST_PROMPT_COPY.uploadDocument,...photoWay?{sub:IN_PROGRESS_COPY.uploadDocumentPhotoSub}:{},dashed:true,onPress:()=>onNavigate({name:"upload"}),testID:"dashboard-way-upload"})]}):null,
|
|
576
|
+
/* @__PURE__ */jsxRuntime.jsx(WayCard,{title:REQUEST_PROMPT_COPY.uploadDocument,...photoWay?{sub:IN_PROGRESS_COPY.uploadDocumentPhotoSub}:{},dashed:true,onPress:()=>onNavigate({name:"upload"}),testID:"dashboard-way-upload"})]}):null,consentControl,
|
|
552
577
|
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"none":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"dashboard-request-prompt",children:[
|
|
553
578
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.promptCard,children:[
|
|
554
579
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.promptHeader,children:[
|
|
@@ -557,7 +582,7 @@ return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...render
|
|
|
557
582
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.promptBody,children:REQUEST_PROMPT_COPY.body}),onNavigate?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
558
583
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onPress:()=>onNavigate({name:"clinicPicker"}),style:local.promptCta,testID:"dashboard-request-prompt-clinic"}),
|
|
559
584
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_PROMPT_COPY.uploadDocument,kind:"outline",onPress:()=>onNavigate({name:"upload"}),style:local.promptCtaSecondary,testID:"dashboard-request-prompt-upload"})]}):null]}),
|
|
560
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,onOpen:openRequests}),
|
|
585
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,onOpen:openRequests}),consentControl,
|
|
561
586
|
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"labs_only":body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.contentTight,testID:"dashboard-labs-only",children:[labs,
|
|
562
587
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(RecordsRequestsStatusCard,{requests:petRequests,petName:petName,activeOnly:true,onOpen:openRequests})}),addActions(),
|
|
563
588
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.inset,children:/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:disclaimer})}),actions(false)]});break;default:body=assertNever(view)}/* @__PURE__ */
|
|
@@ -565,27 +590,27 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
565
590
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"dashboard-header",right:onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"timeline"}),accessibilityRole:"button",accessibilityLabel:DASHBOARD_COPY.openTimeline,hitSlop:12,style:local.headerButton,testID:"dashboard-timeline-link",children:/* @__PURE__ */jsxRuntime.jsx(ListGlyph2,{})}):void 0}),
|
|
566
591
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),
|
|
567
592
|
/* @__PURE__ */jsxRuntime.jsx(MarkerProvenanceSheet,{marker:provenance?.marker??null,point:provenance?.point??null,onClose:()=>setProvenance(null),onAsk:askReading}),
|
|
568
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var ACTION_GLYPH_SIZE=18;function ActionRow({glyph:glyph,label:
|
|
569
|
-
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:
|
|
593
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var ACTION_GLYPH_SIZE=18;function ActionRow({glyph:glyph,label:label2,onPress:onPress,testID:testID}){let local=useLocalStyles7(),ink=useEverfurTheme().color.brandInk,icon=glyph==="record"?/* @__PURE__ */jsxRuntime.jsx(FileTextGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):glyph==="timeline"?/* @__PURE__ */jsxRuntime.jsx(ListGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):glyph==="requests"?/* @__PURE__ */jsxRuntime.jsx(InboxGlyph,{size:ACTION_GLYPH_SIZE,color:ink}):/* @__PURE__ */jsxRuntime.jsx(RefreshGlyph,{size:ACTION_GLYPH_SIZE,color:ink});/* @__PURE__ */
|
|
594
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label2,style:local.actionRow,testID:testID,children:[
|
|
570
595
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.actionLeft,children:[
|
|
571
596
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.actionIcon,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:testID?`${testID}-glyph`:void 0,children:icon}),
|
|
572
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionLabel,children:
|
|
573
|
-
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function InProgressCard({request:request,petName:petName,onOpen:onOpen,onAsk:onAsk}){let styles=useScreenStyles(),local=
|
|
597
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionLabel,children:label2})]}),
|
|
598
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function InProgressCard({request:request,petName:petName,onOpen:onOpen,onAsk:onAsk}){let styles=useScreenStyles(),local=useLocalStyles7(),title=IN_PROGRESS_COPY.title(petName),clinic=request.clinicName?.trim()??"",status=selectPrimaryLabel(request),content=/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressInner,children:[
|
|
574
599
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressHead,children:[
|
|
575
600
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.inProgressHeadText,children:[
|
|
576
601
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.inProgressTitle,children:title}),clinic.length>0?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:clinic}):null]}),onOpen?/* @__PURE__ */jsxRuntime.jsx(Chevron,{}):null]}),
|
|
577
602
|
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:request,petName:petName}),status.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.statusCard,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.statusText,children:status})}):null]});/* @__PURE__ */
|
|
578
|
-
return jsxRuntime.jsxs(reactNative.View,{style:local.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:onOpen?false:void 0,accessibilityLabel:onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:[title,clinic,status].filter(part=>part.length>0).join(". "),testID:"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onPress:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,accessibilityLabel:accessibilityLabel,dashed:dashed=false,onPress:onPress,testID:testID}){let local=
|
|
603
|
+
return jsxRuntime.jsxs(reactNative.View,{style:local.inProgressCard,testID:"dashboard-in-progress-card",accessibilityRole:"summary",accessible:onOpen?false:void 0,accessibilityLabel:onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),children:[onOpen?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:[title,clinic,status].filter(part=>part.length>0).join(". "),testID:"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onPress:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,accessibilityLabel:accessibilityLabel,dashed:dashed=false,onPress:onPress,testID:testID}){let local=useLocalStyles7(),still=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
579
604
|
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??(sub?`${title}. ${sub}`:title),style:({pressed:pressed})=>[local.way,dashed?local.wayDashed:null,pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],testID:testID,children:[
|
|
580
605
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.wayText,children:[
|
|
581
606
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.wayTitle,children:title}),sub?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.waySub,children:sub}):null]}),
|
|
582
|
-
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function
|
|
607
|
+
/* @__PURE__ */jsxRuntime.jsx(Chevron,{})]})}function useLocalStyles7(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles7(theme),[theme])}function makeLocalStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,touch=space.xxl+space.md,card=theme.slots.card,cardText=slotText(card);return reactNative.StyleSheet.create({headerButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},actions:{gap:space.sm+space.xs/2},actionRow:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,paddingHorizontal:space.lg,paddingVertical:space.lg,...slotBox(card,1)},actionLeft:{flex:1,flexDirection:"row",alignItems:"center",gap:space.md},actionIcon:{width:ACTION_GLYPH_SIZE,height:ACTION_GLYPH_SIZE,alignItems:"center",justifyContent:"center"},actionLabel:{flex:1,...face(theme,"medium"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg,...slotBox(card,1)},inProgressHeadText:{flex:1,gap:space.xs/2},ways:{gap:space.sm},way:{flexDirection:"row",alignItems:"center",gap:space.md,borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,...slotBox(card,1)},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...headingFace(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary,...cardText},waySub:{...face(theme,"regular"),fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,...cardText},inProgressInner:{gap:space.lg},inProgressHead:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},inProgressTitle:{...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:-.4,color:color.brandInk,...cardText},promptCard:{borderRadius:radius.sm,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.borderRingCream,paddingHorizontal:space.lg+space.xs,paddingVertical:space.lg+space.xs/2,...slotBox(card,hairline)},promptHeader:{flexDirection:"row",alignItems:"center",gap:space.xs+1},promptGlyph:{width:space.xl+1,height:space.xl+1,borderRadius:radius.xs,borderWidth:2,borderColor:color.warningStrong},promptTitle:{flex:1,...headingFace(theme,"bold"),fontSize:type.size.subtitle,lineHeight:Math.round(type.size.subtitle*type.lineHeight.snug),letterSpacing:type.letterSpacing.headerBrand,color:color.brandInk,...cardText},promptBody:{marginTop:space.sm-1,...face(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:space.lg+space.xs,color:color.text.primary,...cardText},promptCta:{marginTop:space.sm-1,minHeight:space.xxl+space.sm},promptCtaSecondary:{marginTop:space.sm,minHeight:space.xxl+space.sm},addActions:{gap:space.sm},addCta:{minHeight:space.xxl+space.sm}})}var KIND_ORDER=/* @__PURE__ */Object.freeze({visit:0,vaccine:1,weight:2,medication:3});function toMillis2(iso){if(!iso)return null;let ms2=Date.parse(iso);return Number.isNaN(ms2)?null:ms2}function buildTimelineRows(timeline){let rows=[...timeline.visits.map((visit,index)=>({key:`visit-${index}-${visit.visitId}`,kind:"visit",kindLabel:DEPTH_COPY.kind.visit,at:visit.visitDate,date:formatRecordsDate(visit.visitDate),title:visit.summary??DEPTH_COPY.clinicVisit,detail:visit.veterinarian?DEPTH_COPY.doctor(visit.veterinarian):null,docId:visit.docId})),...timeline.vaccines.map((vaccine,index)=>{let parts=[];return vaccine.lot&&parts.push(DEPTH_COPY.lot(vaccine.lot)),vaccine.expiresOn&&parts.push(DEPTH_COPY.expires(formatRecordsDate(vaccine.expiresOn))),{key:`vaccine-${index}-${vaccine.vaccineId}`,kind:"vaccine",kindLabel:DEPTH_COPY.kind.vaccine,at:vaccine.administeredOn,date:formatRecordsDate(vaccine.administeredOn),title:vaccine.product||DEPTH_COPY.kind.vaccine,detail:parts.length?parts.join(" · "):null,docId:vaccine.docId}}),...timeline.weights.map((weight,index)=>({key:`weight-${index}-${weight.weightId}`,kind:"weight",kindLabel:DEPTH_COPY.kind.weight,at:weight.observedOn,date:formatRecordsDate(weight.observedOn),title:formatWeightKg(weight.weightKg),detail:null,docId:weight.docId})),...timeline.medications.map((medication,index)=>{let parts=[medication.dose,medication.route,medication.frequency].filter(p=>!!p);return{key:`medication-${index}-${medication.medicationId}`,kind:"medication",kindLabel:DEPTH_COPY.kind.medication,at:medication.startedOn,date:formatRecordsDate(medication.startedOn),title:medication.drugName||DEPTH_COPY.kind.medication,detail:parts.length?parts.join(" · "):null,docId:medication.docId}})];/* @__PURE__ */
|
|
583
608
|
return Object.freeze(rows.sort((a,b)=>{let am=toMillis2(a.at),bm=toMillis2(b.at);return am===null&&bm===null?KIND_ORDER[a.kind]-KIND_ORDER[b.kind]:am===null?1:bm===null?-1:bm!==am?bm-am:KIND_ORDER[a.kind]-KIND_ORDER[b.kind]}))}var SPINNER_DELAY_MS=300,readTimeline=(client,petRef)=>client.getTimeline(petRef),timelineEmpty=value=>value.isEmpty;var contributionsEmpty=value=>value.contributions.length===0;function EverfurRecordsTimeline({petRef:petRef,style:style,onBack:onBack}){let state=useRecordsDepthRead(petRef,readTimeline,timelineEmpty);/* @__PURE__ */
|
|
584
609
|
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsxRuntime.jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsxRuntime.jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,onBack:onBack}){let read=react.useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),shown=state.value?.document??null,title=shown!==null?documentTitle(shown):DEPTH_COPY.uploadedDocument;/* @__PURE__ */
|
|
585
|
-
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsxRuntime.jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=
|
|
610
|
+
return jsxRuntime.jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsxRuntime.jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=useStyles11();/* @__PURE__ */
|
|
586
611
|
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...recordsGateExit(guardHost(onBack),BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.container,style],children:[header??null,
|
|
587
612
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:renderState(state,render,styles,loading,empty)}),
|
|
588
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function renderState(state,render,styles,loading,empty){switch(state.status){case"loading":return loading??/* @__PURE__ */jsxRuntime.jsx(LoadingState,{styles:styles});case"empty":return empty??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:RECORDS_COPY.empty,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.emptyGlyph})});case"error":return state.error?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(state.error),message:state.error.displayMessage,onAction:state.error.retryable?state.refresh:void 0,testID:"depth-error"}):null;case"populated":return state.value===null||state.value.withheld?null:render(state.value);default:return null}}function LoadingState({styles:styles}){let[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:RECORDS_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{}):null})}function TimelineBody({timeline:timeline}){let styles=
|
|
613
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})})}function renderState(state,render,styles,loading,empty){switch(state.status){case"loading":return loading??/* @__PURE__ */jsxRuntime.jsx(LoadingState,{styles:styles});case"empty":return empty??/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.centered,accessible:true,accessibilityRole:"summary",accessibilityLabel:RECORDS_COPY.empty,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.emptyGlyph})});case"error":return state.error?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(state.error),message:state.error.displayMessage,onAction:state.error.retryable?state.refresh:void 0,testID:"depth-error"}):null;case"populated":return state.value===null||state.value.withheld?null:render(state.value);default:return null}}function LoadingState({styles:styles}){let[visible,setVisible]=react.useState(false);return react.useEffect(()=>{let id=setTimeout(()=>setVisible(true),SPINNER_DELAY_MS);return()=>clearTimeout(id)},[]),/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.centered,accessible:true,accessibilityState:{busy:true},accessibilityLabel:RECORDS_COPY.loading,children:visible?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{}):null})}function TimelineBody({timeline:timeline}){let styles=useStyles11(),rows=buildTimelineRows(timeline);/* @__PURE__ */
|
|
589
614
|
return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContainerStyle:styles.timelineContent,accessibilityLabel:DEPTH_COPY.timeline,children:[timeline.disclaimer.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineBand,accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(timeline.disclaimer),children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineBandText,children:timeline.disclaimer})}):null,rows.map((row,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[index>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineSeparator}):null,
|
|
590
615
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.timelineRow,accessible:true,accessibilityRole:"text",accessibilityLabel:[row.kindLabel,row.date,row.title,row.detail].filter(Boolean).join(", "),testID:`records-timeline-row-${row.kind}`,children:[
|
|
591
616
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.timelineBubble,accessibilityElementsHidden:true,importantForAccessibility:"no"}),
|
|
@@ -593,15 +618,15 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContaine
|
|
|
593
618
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.topLine,children:[
|
|
594
619
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineKind,children:row.kindLabel}),
|
|
595
620
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.date,children:row.date})]}),
|
|
596
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineTitle,children:row.title}),row.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:row.detail}):null]})]})]},row.key))]})}function ContributionsBody({view:view}){let styles=
|
|
621
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.timelineTitle,children:row.title}),row.detail?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:row.detail}):null]})]})]},row.key))]})}function ContributionsBody({view:view}){let styles=useStyles11();/* @__PURE__ */
|
|
597
622
|
return jsxRuntime.jsxs(reactNative.ScrollView,{style:styles.list,contentContainerStyle:styles.listContent,accessibilityLabel:RECORDS_COPY.records,children:[view.document?.receivedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsInstant(view.document.receivedAt)}):null,
|
|
598
623
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.row,accessible:true,accessibilityRole:"text",children:[
|
|
599
624
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowTitle,children:entity.label}),
|
|
600
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles12(theme),[theme])}function makeStyles12(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(recordCardSlot(slots)),text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text4(fontSize,multiplier,fg,weight),...cardText});return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},errorText:{...text4(size.subtitle,lineHeight.snug,errorColor),textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,...slotText(slots.primaryButton)},list:{flex:1},listContent:{padding:space.lg,gap:space.md},section:{gap:space.sm},heading:{...text4(size.heading,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(recordCardSlot(slots),hairline)},row:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(size.caption,lineHeight.normal,color.text.muted,"medium")},date:inCard(size.caption,lineHeight.normal,color.text.muted),rowTitle:{...inCard(size.body,lineHeight.normal,color.text.primary,"bold"),...headingFace(theme,"bold")},rowValue:{...inCard(size.body,lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(size.bodyTight,lineHeight.normal,color.text.muted),rowMuted:{...inCard(size.bodyTight,lineHeight.normal,color.text.muted),opacity:.7},chip:{...text4(size.caption,lineHeight.normal,color.text.primary),alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:{...text4(size.caption,lineHeight.normal,color.text.muted),marginTop:space.md},timelineContent:{paddingBottom:space.xxl},timelineBand:{flexDirection:"row",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,marginHorizontal:space.lg,marginTop:space.xs,marginBottom:space.md},timelineBandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary)},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBubble:{width:space.xxl+space.xs/2,height:space.xxl+space.xs/2,borderRadius:radius.pill,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},timelineBody:{flex:1,gap:space.xs-1},timelineKind:{...face(theme,"mono"),fontSize:size.micro,lineHeight:size.bodyTight,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text4(size.body,lineHeight.normal,color.text.primary,"medium")}})}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=react.useState(null),[loading,setLoading]=react.useState(true),[error,setError]=react.useState(null),[lit,setLit]=react.useState(null),available=lit===true,[urls,setUrls]=react.useState({}),[creating,setCreating]=react.useState(false),[revokingId,setRevokingId]=react.useState(null),[preparingPdf,setPreparingPdf]=react.useState(false),[consentRequired,setConsentRequired]=react.useState(false),[sending,setSending]=react.useState(false),[featuresState,setFeaturesState]=react.useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setLoading(true),setError(null),userRef===null){setShares(null),setLoading(false);return}let result=await client.listShares(petRef);gen!==generation.current||!live.current||(result.ok?(setShares(result.value),setLit(true)):isDarkRouteError(result.error)?(setShares(null),setLit(false)):(setShares(null),setError(result.error),answeredBehindGate(result)&&setLit(true)),setLoading(false))},[client,petRef,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&setFeaturesState({client:client,value:value})},()=>{}),()=>{current=false}},[client,userRef]);let seenEpoch=react.useRef(consentEpoch);react.useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=react.useCallback(async audience=>{setCreating(true);let result=await(audience!==void 0&&shareAudiences.some(scope=>scope.audience===audience)?client.createShare(petRef,{audience:audience}):client.createShare(petRef));return live.current&&(setCreating(false),result.ok?(setUrls(current=>({...current,[result.value.shareId]:result.value.shareUrl})),load()):isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef,load,shareAudiences]),sendEmail=react.useCallback(async input=>{setSending(true);let result=await client.emailShare(petRef,input);return live.current&&(setSending(false),result.ok?load():isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)?setConsentRequired(true):result.error.httpStatus===502&&load()),result},[client,petRef,load]),revoke=react.useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=react.useCallback(async()=>{setPreparingPdf(true);let result=await client.getPdfLink(petRef);return live.current&&(setPreparingPdf(false),!result.ok&&isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef]),refresh=react.useCallback(()=>{setConsentRequired(false),load()},[load]),rows=react.useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return react.useMemo(()=>({status:status,rows:rows,available:available,consentRequired:consentRequired,error:error,creating:creating,revokingId:revokingId,preparingPdf:preparingPdf,shareAudiences:shareAudiences,features:features,sending:sending,createLink:createLink,sendEmail:sendEmail,revoke:revoke,pdfLink:pdfLink,refresh:refresh}),[status,rows,available,consentRequired,error,creating,revokingId,preparingPdf,shareAudiences,features,sending,createLink,sendEmail,revoke,pdfLink,refresh])}function answeredBehindGate(result){return result.ok||result.error.httpStatus!==void 0&&result.error.httpStatus!==404}function sharesListShown(shares){return shares.available||shares.status!=="empty"}function useRecordsDepthProbe(petRef){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=react.useState({scope:scope,lit:null});react.useEffect(()=>{if(userRef===null)return;let live=true;return client.listShares(petRef).then(result=>{live&&(!result.ok&&isDarkRouteError(result.error)?setState({scope:scope,lit:false}):answeredBehindGate(result)&&setState({scope:scope,lit:true}))},()=>{}),()=>{live=false}},[client,petRef,userRef,scope]);let lit=state.scope===scope?state.lit:null;return react.useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=react.useState(false),[error,setError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=react.useCallback(async()=>{setPreparing(true),setError(null);let result=await client.getPdfLink(petRef);return live.current&&(setPreparing(false),result.ok||setError(result.error)),result},[client,petRef]);return react.useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}async function shareLinkViaOs(url){await reactNative.Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await reactNative.Share.share(reactNative.Platform.OS==="ios"?{url:url}:{message:url})}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDocument(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]);/* @__PURE__ */
|
|
601
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(DocumentBody,{...rest,style:style})})}function documentIsEmpty(record,depth){return record.identity.length===0&&record.entities.length===0&&record.forwardLooking.length===0&&(depth===null||depth.labResults.length===0&&depth.physicalExams.length===0&&depth.clinicianNotes.length===0)}function DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl,style:style}){let styles=useScreenStyles(),local=
|
|
625
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles11(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles13(theme),[theme])}function makeStyles13(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight}=type,lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=reactNative.StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(recordCardSlot(slots)),text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text4(fontSize,multiplier,fg,weight),...cardText});return reactNative.StyleSheet.create({container:{flex:1,minHeight:minSurface,backgroundColor:color.background},body:{flex:1},centered:{minHeight:minSurface,flexGrow:1,alignItems:"center",justifyContent:"center",padding:space.xl,gap:space.lg},emptyGlyph:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.lg,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},errorText:{...text4(size.subtitle,lineHeight.snug,errorColor),textAlign:"center",marginBottom:space.md},primaryButton:{minHeight:touchTarget,minWidth:touchTarget,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xl,paddingVertical:space.md,borderRadius:radius.pill,backgroundColor:color.primary,...slotBox(slots.primaryButton)},primaryLabel:{...face(theme,"bold"),color:color.onPrimary,fontSize:size.body,...slotText(slots.primaryButton)},list:{flex:1},listContent:{padding:space.lg,gap:space.md},section:{gap:space.sm},heading:{...text4(size.heading,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(recordCardSlot(slots),hairline)},row:{gap:space.xs,paddingVertical:space.xs,borderBottomWidth:hairline,borderBottomColor:color.borderHairlineGreen},topLine:{flexDirection:"row",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(size.caption,lineHeight.normal,color.text.muted,"medium")},date:inCard(size.caption,lineHeight.normal,color.text.muted),rowTitle:{...inCard(size.body,lineHeight.normal,color.text.primary,"bold"),...headingFace(theme,"bold")},rowValue:{...inCard(size.body,lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(size.bodyTight,lineHeight.normal,color.text.muted),rowMuted:{...inCard(size.bodyTight,lineHeight.normal,color.text.muted),opacity:.7},chip:{...text4(size.caption,lineHeight.normal,color.text.primary),alignSelf:"flex-start",paddingHorizontal:space.sm,paddingVertical:space.xs,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:{...text4(size.caption,lineHeight.normal,color.text.muted),marginTop:space.md},timelineContent:{paddingBottom:space.xxl},timelineBand:{flexDirection:"row",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,marginHorizontal:space.lg,marginTop:space.xs,marginBottom:space.md},timelineBandText:{flex:1,...text4(size.caption,lineHeight.normal,color.text.secondary)},timelineSeparator:{height:hairline,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},timelineRow:{flexDirection:"row",gap:space.md,paddingHorizontal:space.lg,paddingVertical:space.md+space.xs/2},timelineBubble:{width:space.xxl+space.xs/2,height:space.xxl+space.xs/2,borderRadius:radius.pill,backgroundColor:color.brandSoft,borderWidth:hairline,borderColor:color.brandBorder},timelineBody:{flex:1,gap:space.xs-1},timelineKind:{...face(theme,"mono"),fontSize:size.micro,lineHeight:size.bodyTight,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text4(size.body,lineHeight.normal,color.text.primary,"medium")}})}function useRecordShares(petRef,opts={}){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),now=opts.now??Date.now,[shares,setShares]=react.useState(null),[loading,setLoading]=react.useState(true),[error,setError]=react.useState(null),[lit,setLit]=react.useState(null),available=lit===true,[urls,setUrls]=react.useState({}),[creating,setCreating]=react.useState(false),[revokingId,setRevokingId]=react.useState(null),[preparingPdf,setPreparingPdf]=react.useState(false),[consentRequired,setConsentRequired]=react.useState(false),[sending,setSending]=react.useState(false),[featuresState,setFeaturesState]=react.useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=react.useRef(0),live=react.useRef(true),load=react.useCallback(async()=>{let gen=generation.current+=1;if(setLoading(true),setError(null),userRef===null){setShares(null),setLoading(false);return}let result=await client.listShares(petRef);gen!==generation.current||!live.current||(result.ok?(setShares(result.value),setLit(true)):isDarkRouteError(result.error)?(setShares(null),setLit(false)):(setShares(null),setError(result.error),answeredBehindGate(result)&&setLit(true)),setLoading(false))},[client,petRef,userRef]);react.useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),react.useEffect(()=>{if(userRef===null||client.readFeatures===void 0)return;let current=true;return client.readFeatures().then(value=>{current&&setFeaturesState({client:client,value:value})},()=>{}),()=>{current=false}},[client,userRef]);let seenEpoch=react.useRef(consentEpoch);react.useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=react.useCallback(async audience=>{setCreating(true);let result=await(audience!==void 0&&shareAudiences.some(scope=>scope.audience===audience)?client.createShare(petRef,{audience:audience}):client.createShare(petRef));return live.current&&(setCreating(false),result.ok?(setUrls(current=>({...current,[result.value.shareId]:result.value.shareUrl})),load()):isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef,load,shareAudiences]),sendEmail=react.useCallback(async input=>{setSending(true);let result=await client.emailShare(petRef,input);return live.current&&(setSending(false),result.ok?load():isDarkRouteError(result.error)?setLit(false):isRecordsConsentRequired(result.error)?setConsentRequired(true):result.error.httpStatus===502&&load()),result},[client,petRef,load]),revoke=react.useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=react.useCallback(async()=>{setPreparingPdf(true);let result=await client.getPdfLink(petRef);return live.current&&(setPreparingPdf(false),!result.ok&&isRecordsConsentRequired(result.error)&&setConsentRequired(true)),result},[client,petRef]),refresh=react.useCallback(()=>{setConsentRequired(false),load()},[load]),rows=react.useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return react.useMemo(()=>({status:status,rows:rows,available:available,consentRequired:consentRequired,error:error,creating:creating,revokingId:revokingId,preparingPdf:preparingPdf,shareAudiences:shareAudiences,features:features,sending:sending,createLink:createLink,sendEmail:sendEmail,revoke:revoke,pdfLink:pdfLink,refresh:refresh}),[status,rows,available,consentRequired,error,creating,revokingId,preparingPdf,shareAudiences,features,sending,createLink,sendEmail,revoke,pdfLink,refresh])}function answeredBehindGate(result){return result.ok||result.error.httpStatus!==void 0&&result.error.httpStatus!==404}function sharesListShown(shares){return shares.available||shares.status!=="empty"}function useRecordsDepthProbe(petRef){let client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),scope=react.useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=react.useState({scope:scope,lit:null});react.useEffect(()=>{if(userRef===null)return;let live=true;return client.listShares(petRef).then(result=>{live&&(!result.ok&&isDarkRouteError(result.error)?setState({scope:scope,lit:false}):answeredBehindGate(result)&&setState({scope:scope,lit:true}))},()=>{}),()=>{live=false}},[client,petRef,userRef,scope]);let lit=state.scope===scope?state.lit:null;return react.useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=react.useState(false),[error,setError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=react.useCallback(async()=>{setPreparing(true),setError(null);let result=await client.getPdfLink(petRef);return live.current&&(setPreparing(false),result.ok||setError(result.error)),result},[client,petRef]);return react.useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth2=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty2=value=>!value.available;function EverfurRecordDocument(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]),{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
626
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(SessionRequiredScreen,{style:style,testID:"records-document-session-required"}):/* @__PURE__ */jsxRuntime.jsx(DocumentBody,{...rest,style:style})})}function documentIsEmpty(record,depth){return record.identity.length===0&&record.entities.length===0&&record.forwardLooking.length===0&&(depth===null||depth.labResults.length===0&&depth.physicalExams.length===0&&depth.clinicianNotes.length===0)}function DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl,style:style}){let styles=useScreenStyles(),local=useLocalStyles8(),theme=useEverfurTheme(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth2,depthEmpty2),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[shareFailed,setShareFailed]=react.useState(false),download=()=>{setShareFailed(false),pdf.pdfLink().then(result=>{if(!result.ok)return;callHostAsync(onOpenUrl??(target=>shareFileLinkViaOs(target)),result.value.downloadUrl,"record_pdf").then(outcome=>{!outcome.ok&&!onOpenUrl&&setShareFailed(true)})})},body,documentShown=false;if(records.status==="loading"||depth.status==="loading"&&record!==null)body=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DASHBOARD_COPY.loading,testID:"record-document-loading",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{color:theme.color.brandInk})});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?()=>{records.refresh(),depth.refresh()}:void 0,testID:"record-document-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else record===null||documentIsEmpty(record,depthView)?body=/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.centered,testID:"record-document-empty",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.emptyText,children:COPY.empty})}):(documentShown=true,body=/* @__PURE__ */jsxRuntime.jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,local.root,style],children:[
|
|
602
627
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:download,disabled:pdf.preparing,accessibilityRole:"button",accessibilityLabel:COPY.download,accessibilityState:{disabled:pdf.preparing,busy:pdf.preparing},hitSlop:8,style:local.download,testID:"record-document-download",children:pdf.preparing?/* @__PURE__ */jsxRuntime.jsx(reactNative.ActivityIndicator,{size:"small",color:theme.slots.header?.textColor??theme.color.brandInk}):/* @__PURE__ */jsxRuntime.jsx(DownloadGlyph,{})}):void 0}),pdf.error?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",children:pdf.error.displayMessage}):shareFailed?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:SHARE_COPY.toasts.pdfShareSheet}):null,
|
|
603
628
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),
|
|
604
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let local=
|
|
629
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let local=useLocalStyles8(),groups=react.useMemo(()=>{let order=[],byType=/* @__PURE__ */new Map;for(let entity of record.entities){let category=entity.category.trim();if(category.length===0)continue;let bucket=byType.get(category);bucket===void 0?(order.push(category),byType.set(category,[entity])):bucket.push(entity)}let known=DOCUMENT_ENTITY_ORDER.filter(type=>order.includes(type)),rest=order.filter(type=>!DOCUMENT_ENTITY_ORDER.includes(type));return[...known,...rest].map(type=>({type:type,rows:byType.get(type)??[]}))},[record.entities]),now=Date.now(),section=(title,children,testID)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.section,testID:testID,children:[
|
|
605
630
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sectionHeader,children:[
|
|
606
631
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.sectionTitle,accessibilityRole:"header",children:title}),
|
|
607
632
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.rule})]}),
|
|
@@ -628,7 +653,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[local.row,index>0?local.rowDivid
|
|
|
628
653
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fieldLabel,children:bodySystemLabel(system.system)}),
|
|
629
654
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.fieldValue,children:system.finding})]},system.system))]},exam.examId)),"record-document-exams"):null,depth&&depth.clinicianNotes.length>0?section(COPY.clinicianNotes,depth.clinicianNotes.map((note,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.block,index>0?local.rowDivider:null],children:[note.observedOn?/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.blockDate,children:formatRecordsDate(note.observedOn)}):null,note.sections.filter(s=>s.text).map((s,i)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.noteSection,children:[
|
|
630
655
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteLabel,children:soapSectionLabel(s.section)}),
|
|
631
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteBody,children:s.text})]},`${s.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.disclaimer,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.disclaimerText,children:record.disclaimer})})]})}function
|
|
656
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.noteBody,children:s.text})]},`${s.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.disclaimer,children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.disclaimerText,children:record.disclaimer})})]})}function useLocalStyles8(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles8(theme),[theme])}function makeLocalStyles8(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),mono=(fontSize,fg)=>({...face(theme,"mono"),fontSize:fontSize,lineHeight:fontSize+space.xs-1,color:fg,letterSpacing:type.letterSpacing.eyebrow/2,textTransform:"uppercase"});return reactNative.StyleSheet.create({root:{backgroundColor:color.surface},inset:{paddingHorizontal:space.lg},download:{width:space.xxl+space.xs+space.xs/2,height:space.xxl+space.xs+space.xs/2,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"},centered:{flex:1,alignItems:"center",justifyContent:"center",paddingHorizontal:space.xxl,minHeight:space.xxl*3+space.xl},emptyText:{...text4(type.size.body,type.lineHeight.normal,color.text.muted,"medium"),textAlign:"center"},page:{paddingHorizontal:space.lg+space.xs,paddingBottom:space.xxl+space.lg},letterhead:{alignItems:"center",paddingTop:space.md,paddingBottom:space.lg+space.xs+space.xs/2,borderBottomWidth:2,borderBottomColor:color.brandInk,gap:space.xs+space.xs/2,marginBottom:space.sm},wordmark:{...text4(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:type.letterSpacing.headerBrand},docTitle:{...mono(type.size.caption,color.brandInk),marginTop:space.sm+space.xs/2,letterSpacing:type.letterSpacing.eyebrow+.4},petName:text4(type.size.verdict+space.xs/2,type.lineHeight.tight,color.text.primary),generated:{...mono(type.size.tiny,color.text.muted),textTransform:"none"},section:{marginTop:space.lg+space.xs+space.xs/2},sectionHeader:{flexDirection:"row",alignItems:"center",gap:space.sm+space.xs/2,marginBottom:space.sm},sectionTitle:mono(type.size.tiny,color.brandInk),rule:{flex:1,height:hairline,backgroundColor:color.borderHairlineGreen},row:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.md+space.xs/2,paddingVertical:space.sm+1},rowDivider:{borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},rowFlag:{backgroundColor:color.badgeBgCritical,marginHorizontal:-space.sm,paddingHorizontal:space.sm,borderRadius:radius.xs},rowMain:{flexShrink:1},rowRight:{alignItems:"flex-end",gap:space.xs/2},rowLabel:{flexShrink:1,...text4(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowValue:{...text4(type.size.body,type.lineHeight.normal,color.text.primary,"bold"),textAlign:"right"},rowValueAlert:{color:color.danger},rowMeta:{marginTop:space.xs/2,...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},markerStatus:mono(type.size.micro,color.text.muted),block:{paddingVertical:space.sm+space.xs/2},blockDate:{...mono(type.size.tiny,color.text.muted),marginBottom:space.xs+space.xs/2},fieldRow:{flexDirection:"row",alignItems:"flex-start",gap:space.md+space.xs/2,paddingVertical:space.xs-1},fieldLabel:{width:120,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted,"medium")},fieldValue:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")},noteSection:{marginTop:space.sm},noteLabel:{...mono(type.size.tiny,color.brandInk),marginBottom:space.xs/2},noteBody:text4(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),disclaimer:{marginTop:radius.xl,paddingTop:space.md+space.xs/2,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen},disclaimerText:text4(type.size.tiny,type.lineHeight.relaxed,color.text.muted)})}function ShareSheet({petRef:petRef,petName:petName,onClose:onClose,onNavigate:onNavigate,onOpenUrl:onOpenUrl,onCopy:onCopy}){let styles=useStyles12(),screen=useScreenStyles(),shares=useRecordShares(petRef),[notice,setNotice]=react.useState(null),[pendingRevokeId,setPendingRevokeId]=react.useState(null),[audience,setAudience]=react.useState("vet"),[email2,setEmail]=react.useState(""),exportable=shares.available&&!shares.consentRequired,linkWritable=shares.features.sharing!==false,mintable=exportable&&linkWritable,armed=shares.shareAudiences.length>0,scope=shares.shareAudiences.find(served=>served.audience===audience)??null,included=scope!==null?shareIncludedLines(scope,shares.features):[],open=(url,kind)=>{let opener=onOpenUrl??((target,what)=>what==="share_link"?shareLinkViaOs(target):shareFileLinkViaOs(target)),failure=kind==="share_link"?SHARE_COPY.toasts.shareSheet:SHARE_COPY.toasts.pdfShareSheet;callHostAsync(opener,url,kind).then(outcome=>{outcome.ok||setNotice(failure)})},onCreateLink=()=>{setNotice(null),shares.createLink(armed?audience:void 0).then(result=>{result.ok?open(result.value.shareUrl,"share_link"):setNotice(shareErrorMessage(result.error,"create"))})},onSend=()=>{if(shares.sending)return;setNotice(null);let address=email2.trim();if(address.length===0){setNotice(SHARE_COPY.addEmailFor(petName));return}if(!isShareRecipientEmail(address)){setNotice(SHARE_COPY.emailInvalid);return}shares.sendEmail({recipientEmail:address,recipientKind:audience}).then(result=>{result.ok?(setEmail(""),setNotice(SHARE_COPY.toasts.sentTo(address))):setNotice(shareErrorMessage(result.error,"email"))})},onDownload=()=>{setNotice(null),shares.pdfLink().then(result=>{result.ok?open(result.value.downloadUrl,"record_pdf"):setNotice(shareErrorMessage(result.error,"download"))})},onCopyRow=row=>{if(!onCopy||row.shareUrl===null)return;let url=row.shareUrl;callHostAsync(onCopy,url).then(outcome=>setNotice(outcome.ok?SHARE_COPY.toasts.copiedNative:SHARE_COPY.toasts.copyFailedNative(url)))},onConfirmRevoke=shareId=>{shares.revoke(shareId).then(result=>{setPendingRevokeId(null),setNotice(result.ok?SHARE_COPY.toasts.turnedOff:shareErrorMessage(result.error,"revoke"))})};/* @__PURE__ */
|
|
632
657
|
return jsxRuntime.jsx(reactNative.Modal,{transparent:true,visible:true,animationType:"slide",onRequestClose:onClose,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.backdrop,children:[
|
|
633
658
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{style:ABSOLUTE_FILL,accessibilityRole:"button",accessibilityLabel:SHARE_COPY.closeSheetA11y,onPress:onClose}),
|
|
634
659
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.sheet,accessibilityViewIsModal:true,testID:"share-record-sheet",children:[
|
|
@@ -667,16 +692,16 @@ return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setAudience(option),acc
|
|
|
667
692
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[
|
|
668
693
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:shares.revokingId===row.shareId?SHARE_COPY.turningOff:SHARE_COPY.turnOff,kind:"danger",busy:shares.revokingId===row.shareId,onPress:()=>onConfirmRevoke(row.shareId),testID:`share-revoke-do-${row.shareId}`}),
|
|
669
694
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onPress:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:styles.rowActions,children:[onCopy?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,accessibilityHint:row.a11yLabel,onPress:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}):null,linkWritable?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:SHARE_COPY.turnOff,kind:"danger",accessibilityLabel:SHARE_COPY.turnOffA11y(row.actionContext),onPress:()=>setPendingRevokeId(row.shareId),testID:`share-ask-revoke-${row.shareId}`}):null]})]},row.shareId))})]}):null]}),
|
|
670
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:screen.inset})]})]})})}function
|
|
671
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest,style:style})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy,style:style}){let styles=useScreenStyles(),local=
|
|
695
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:screen.inset})]})]})})}function useStyles12(){let theme=useEverfurTheme();return react.useMemo(()=>makeStyles14(theme),[theme])}function makeStyles14(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,hairline=reactNative.StyleSheet.hairlineWidth,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),{dialog:dialog,tab:tab,input:input,card:card}=theme.slots,dialogText=slotText(dialog);return reactNative.StyleSheet.create({active:{color:color.success},inactive:{color:color.text.muted},backdrop:{flex:1,justifyContent:"flex-end",backgroundColor:"rgba(0,0,0,0.4)"},sheet:{backgroundColor:color.surface,borderTopLeftRadius:radius.xl-1,borderTopRightRadius:radius.xl-1,paddingHorizontal:space.lg+space.xs+space.xs/2,paddingTop:space.md,paddingBottom:radius.xl,maxHeight:"88%",gap:space.md,...sheetSlotBox(dialog)},handle:{alignSelf:"center",width:space.xxl+space.xs,height:space.xs,borderRadius:radius.pill,backgroundColor:color.borderRingCream},header:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},headerText:{flex:1,gap:space.xs},title:{...text4(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},helper:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...dialogText},terms:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text4(type.size.verdict,type.lineHeight.tight,color.text.primary),...dialogText},scroll:{flexGrow:0},body:{gap:space.lg,paddingBottom:space.sm},actions:{gap:space.sm},form:{gap:space.sm,paddingBottom:space.sm},fieldLabel:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium")},choices:{flexDirection:"row",gap:space.sm},choice:{flex:1,minHeight:touch,alignItems:"center",justifyContent:"center",paddingHorizontal:space.sm,borderRadius:radius.md,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface,...slotBox(tab,hairline)},choiceOn:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:color.brandSoft},choiceTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...slotText(tab)},choiceTitleOn:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},included:{gap:space.xs},includedRow:{flexDirection:"row",gap:space.sm},includedLine:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),includedText:{flex:1},field:{...text4(type.size.body,type.lineHeight.normal,color.text.primary),minHeight:touch,paddingHorizontal:space.md,borderRadius:radius.sm,borderWidth:hairline,borderColor:color.borderHairlineGreen,backgroundColor:color.surface,...slotBox(input,hairline),...slotText(input)},placeholder:{color:color.text.placeholder},notice:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary),padding:space.md,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft},section:{gap:space.sm},sectionLabel:{...text4(type.size.bodyTight,type.lineHeight.snug,color.text.secondary,"bold"),textTransform:"uppercase",letterSpacing:type.letterSpacing.eyebrow/2},stateCard:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(card,hairline)},stateTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},stateBody:text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),list:{gap:space.md},row:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(card,hairline)},statusLine:{flexDirection:"row",alignItems:"center",gap:space.sm},statusDot:{width:space.sm,height:space.sm,borderRadius:space.xs},status:{...text4(type.size.bodyTight,type.lineHeight.snug,color.text.primary,"bold")},expiry:{...text4(type.size.caption,type.lineHeight.normal,color.text.muted)},created:text4(type.size.tiny,type.lineHeight.normal,color.text.muted),url:{...text4(type.size.caption,type.lineHeight.normal,color.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},confirm:{gap:space.sm},confirmText:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")}})}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordDetail(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
696
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RecordBody,{...rest,style:style})})}function RecordBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,onOpenUrl:onOpenUrl,onCopy:onCopy,style:style}){let styles=useScreenStyles(),local=useLocalStyles9(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=react.useState(false);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,retry=()=>{records.refresh(),depth.refresh()},shareable=onNavigate!==void 0||shareProbe.lit===true,clinicDecision=useCapability("recordsClinic"),canRequestFromClinics=onNavigate!==void 0&&(clinicDecision.enabled||clinicDecision.isPending),body;if(records.status==="loading"||depth.status==="loading"&&record!==null&&!record.isEmpty)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-record-loading"});else if(records.status==="error"){let errorView=selectErrorView(records,canGrant);body=errorView.kind==="error"||errorView.kind==="pet_not_found"?/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(errorView.error),message:errorView.error.displayMessage,onAction:errorView.error.retryable?retry:void 0,testID:"everfur-record-error"}):renderErrorFamily(records,onGrant,canGrant,consentText)}else if(record===null||record.isEmpty){let inReview=depthView?.completeness?.documentsInReview??0;body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:styles.content,testID:"everfur-record-empty",children:[
|
|
672
697
|
/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
673
698
|
/* @__PURE__ */jsxRuntime.jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:local.content,testID:"everfur-record",children:/* @__PURE__ */jsxRuntime.jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
674
699
|
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
675
700
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||canRequestFromClinics?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[canRequestFromClinics&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onNavigate({name:"clinicBatch"}),accessibilityRole:"button",accessibilityLabel:RECORD_SCREEN_COPY.requestClinicsA11y,hitSlop:8,style:local.share,testID:"everfur-record-request-clinics",children:/* @__PURE__ */jsxRuntime.jsx(SendGlyph,{})}):null,shareable?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setSharing(true),accessibilityRole:"button",accessibilityLabel:SHARE_COPY.openA11yFor(petName),hitSlop:8,style:local.share,testID:"everfur-record-share",children:/* @__PURE__ */jsxRuntime.jsx(ShareGlyph,{})}):null]}):void 0}),
|
|
676
701
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.body,children:body}),sharing?/* @__PURE__ */jsxRuntime.jsx(ShareSheet,{petRef:petRef,petName:petName,onClose:()=>setSharing(false),onNavigate:onNavigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{}}):null,
|
|
677
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function
|
|
702
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function useLocalStyles9(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles9(theme),[theme])}function makeLocalStyles9(theme){let{space:space,radius:radius}=theme;return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl+space.sm,gap:space.lg+space.xs},share:{width:space.xxl+space.sm,height:space.xxl+space.sm,borderRadius:radius.pill,alignItems:"center",justifyContent:"center"}})}function useRecordsPullToRefresh(refresh,testID){let theme=useEverfurTheme(),[refreshing,setRefreshing]=react.useState(false),onRefresh=react.useCallback(()=>{setRefreshing(true),refresh().finally(()=>setRefreshing(false))},[refresh]);/* @__PURE__ */
|
|
678
703
|
return jsxRuntime.jsx(reactNative.RefreshControl,{refreshing:refreshing,onRefresh:onRefresh,tintColor:theme.color.brandInk,colors:[theme.color.brandInk],testID:testID})}function EverfurRecordsUpload(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
679
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(UploadBody,{...rest,style:style})})}function UploadBody({petRef:petRef,petName:petName,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=
|
|
704
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(UploadBody,{...rest,style:style})})}function UploadBody({petRef:petRef,petName:petName,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style}){let styles=useScreenStyles(),local=useLocalStyles10(),theme=useEverfurTheme(),{runtime:runtime}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport));/* @__PURE__ */
|
|
680
705
|
return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
681
706
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:"",onBack:onBack,testID:"upload-header"}),
|
|
682
707
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,testID:"upload-screen",children:[
|
|
@@ -685,7 +710,7 @@ return jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
|
685
710
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.title,accessibilityRole:"header",children:UPLOAD_COPY.screenTitle}),
|
|
686
711
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.subtitle,children:UPLOAD_COPY.subtitle(petName)})]}),
|
|
687
712
|
/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:null,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]}),
|
|
688
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=
|
|
713
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function UploadRecordCard({records:records,requestId:requestId2,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload,onDone:onDone}){let styles=useScreenStyles(),local=useLocalStyles10(),{runtime:runtime}=useEverfurContext(),camera=runtime.registry.services.camera,types=records.uploadContentTypes,photosLive=acceptsPhotos(types),canTakePhoto=photosLive&&isCaptureAvailable(camera),canChoosePhotos=photosLive&&onPickPhotos!==void 0,photoCopy=canTakePhoto||canChoosePhotos,[pickError,setPickError]=react.useState(null),[batchCount,setBatchCount]=react.useState(0),resolvedId=react.useRef(requestId2),failedFiles=react.useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&batchCount>0,run=react.useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photoCopy);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal);let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n2=>n2+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])},[records,types,photoCopy]),pickFrom=react.useCallback(picker=>{!picker||!canUpload||callHostAsync(picker).then(outcome=>{if(!outcome.ok){setPickError(UPLOAD_COPY.errors.startPlain);return}let picked=outcome.value;picked!==null&&run(Array.isArray(picked)?picked:[picked])})},[canUpload,run]),pick2=react.useCallback(()=>{pickFrom(onPickDocument)},[pickFrom,onPickDocument]),pickPhotos=react.useCallback(()=>{pickFrom(onPickPhotos)},[pickFrom,onPickPhotos]),takePhoto=react.useCallback(()=>{!canTakePhoto||!canUpload||callHostAsync(()=>camera.capture(captureOptionsFor("photo"))).then(outcome=>{if(!outcome.ok)return;let handle=fileHandleFromMedia(outcome.value);if(handle.sizeBytes===void 0){setPickError(UPLOAD_COPY.errors.startPlain);return}run([handle])})},[camera,canTakePhoto,canUpload,run]),retryFailed=react.useCallback(()=>{run(failedFiles.current)},[run]);/* @__PURE__ */
|
|
689
714
|
return jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-upload-card",children:[
|
|
690
715
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:UPLOAD_COPY.cardTitle}),
|
|
691
716
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardSubtitle,children:photoCopy?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),pickError?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.errorBanner,accessibilityRole:"alert",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,children:pickError})}):null,
|
|
@@ -697,23 +722,23 @@ return jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-upload
|
|
|
697
722
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.takePhotoMeta})]}):null,canChoosePhotos?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:local.action,children:/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_PHOTO_COPY.choosePhotos,kind:"outline",disabled:!canUpload,onPress:pickPhotos,testID:"records-upload-choose-photos"})}):null,
|
|
698
723
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.action,children:[
|
|
699
724
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick2,testID:"records-upload-choose"}),
|
|
700
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick2,testID:"records-upload-choose"})]})}function
|
|
701
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(RequestBody,{...rest,style:style})})}function RequestBody({petRef:petRef,petName:petName,requestId:requestId2,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,style:style,nowMs:nowMs}){let styles=useScreenStyles(),{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),request=records.requests.find(r=>r.id===requestId2)??null,canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport)),title=request?selectRequestTitle(request):"",refreshControl=useRecordsPullToRefresh(records.refresh,"records-request-refresh"),body;return records.status==="loading"&&request===null?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-request-loading"}):records.status==="error"&&records.error?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error.displayMessage,onAction:records.error.retryable?records.refresh:void 0,testID:"records-request-error"}):request===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-request-missing"}):
|
|
725
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick2,testID:"records-upload-choose"})]})}function useLocalStyles10(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles10(theme),[theme])}var UPLOAD_GLYPH=24;function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{padding:space.lg+space.xs,gap:space.lg+space.xs},header:{gap:space.sm,alignItems:"center"},iconBubble:{width:space.xxl+space.lg+space.xs,height:space.xxl+space.lg+space.xs,borderRadius:radius.pill,alignItems:"center",justifyContent:"center",marginBottom:space.xs},title:{...text4(type.size.heading+space.xs/2,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),textAlign:"center"},subtitle:{...text4(type.size.body,type.lineHeight.normal,color.text.muted),textAlign:"center",maxWidth:340},card:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.md,...slotBox(theme.slots.card,1)},cardTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.card)},cardSubtitle:{...text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.card)},uploadingRow:{flexDirection:"row",alignItems:"center",gap:space.sm},progressText:{flex:1,...text4(type.size.bodyTight,type.lineHeight.normal,color.text.secondary)},settled:{gap:space.sm},success:text4(type.size.bodyTight,type.lineHeight.normal,color.text.primary),settledActions:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:space.sm},actions:{gap:space.md},action:{gap:space.xs},actionMeta:text4(type.size.bodyTight,type.lineHeight.normal,color.text.muted)})}function EverfurRecordsRequest(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]),{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
726
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(SessionRequiredScreen,{style:style,testID:"records-request-session-required"}):/* @__PURE__ */jsxRuntime.jsx(RequestBody,{...rest,style:style})})}function RequestBody({petRef:petRef,petName:petName,requestId:requestId2,controller:controller,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,onNavigate:onNavigate,onBack:onBack,onOpenUrl:onOpenUrl,style:style,nowMs:nowMs}){let styles=useScreenStyles(),{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:uploadTransport?{petRef:petRef,uploadTransport:uploadTransport,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),request=records.requests.find(r=>r.id===requestId2)??null,canUpload=canUploadRecords(onPickDocument)&&(controller!==void 0||uploadTransport!==void 0||isUploadTransportAvailable(runtime.registry.services.uploadTransport)),title=request?selectRequestTitle(request):"",refreshControl=useRecordsPullToRefresh(records.refresh,"records-request-refresh"),body;return records.status==="loading"&&request===null?body=/* @__PURE__ */jsxRuntime.jsx(RequestSkeleton,{testID:"records-request-loading"}):records.status==="error"&&records.error?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(records.error),message:records.error.displayMessage,onAction:records.error.retryable?records.refresh:void 0,testID:"records-request-error"}):request===null?body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-request-missing"}):body=/* @__PURE__ */jsxRuntime.jsx(RequestDetail,{petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,onOpenUrl:onOpenUrl,nowMs:nowMs,refreshControl:refreshControl},JSON.stringify([userRef,scopeEpoch,request.id])),/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[styles.root,style],children:[
|
|
702
727
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:title,onBack:onBack,testID:"records-request-header"}),
|
|
703
728
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.KeyboardAvoidingView,{behavior:"padding",style:styles.body,children:body}),
|
|
704
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestDetail({petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,nowMs:nowMs,refreshControl:refreshControl}){let styles=useScreenStyles(),local=
|
|
729
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function RequestDetail({petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,onOpenUrl:onOpenUrl,nowMs:nowMs,refreshControl:refreshControl}){let styles=useScreenStyles(),local=useLocalStyles11(),theme=useEverfurTheme(),form=useRecordsRecovery({request:request,onRecovered:records.refresh,canUpload:canUpload},useEverfurRecordsClinic()),[lastAction,setLastAction]=react.useState(null),[starting,setStarting]=react.useState(false),[startError,setStartError]=react.useState(null),live=react.useRef(true);react.useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let current=form.request,now=nowMs??Date.now(),published=current.status==="published",terminal=current.status==="published"||current.status==="failed"||current.status==="revoked",failed=isTerminalFailure(current),clinicNoRecords=current.wireStatus==="clinic_responded_no_records",waitingTooLong=requestWaitingTooLong(current,now),elapsedDays=requestElapsedDays(current,now),expectation=terminal?null:current.waitingExpectation?.trim()||null,call=selectClinicCall(current),showRecovery=shouldOfferRecovery(current),canConvert=form.canConvert,canStartFresh=terminal&&!published,actionError=form.error!==null&&lastAction!==null&&lastAction!=="start"?lastAction==="revoke"?REQUEST_SCREEN_COPY.errors.cancel:REQUEST_SCREEN_COPY.errors[lastAction]:null,run=(action,fn)=>{setLastAction(action),fn()},startFresh=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(live.current){if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}}))},clinicName=current.clinicName?.trim()??"",clinicRequest=!isOwnerSourcedRequest(current)&&clinicName.length>0,awaitingClinic=clinicRequest&&(current.status==="requested"||current.status==="awaiting_clinic"),sentDate=formatRecordsInstant(current.createdAt);/* @__PURE__ */
|
|
705
730
|
return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.content,keyboardShouldPersistTaps:"handled",refreshControl:refreshControl,testID:`records-request-${current.id}`,children:[awaitingClinic?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.sent,testID:"records-request-sent",children:[
|
|
706
731
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.sentTitle}),
|
|
707
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:REQUEST_SCREEN_COPY.
|
|
732
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:REQUEST_SCREEN_COPY.sentLeadWeb(clinicName,petNameOr(petName))})]}):null,
|
|
708
733
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-request-where",children:[
|
|
709
734
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.whereItStands}),
|
|
710
|
-
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:current,petName:petName})]}),clinicRequest?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-request-details",children:[
|
|
735
|
+
/* @__PURE__ */jsxRuntime.jsx(RequestTimeline,{request:current,petName:petName}),isOwnerSourcedRequest(current)?/* @__PURE__ */jsxRuntime.jsx(RequestDocumentsList,{requestId:current.id,...onOpenUrl?{onOpenUrl:onOpenUrl}:{}}):null]}),clinicRequest?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.card,testID:"records-request-details",children:[
|
|
711
736
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.cardTitle,accessibilityRole:"header",children:REQUEST_SCREEN_COPY.details}),
|
|
712
737
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.detailRow,children:[
|
|
713
738
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsClinic}),
|
|
714
739
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.detailValue,children:clinicName})]}),sentDate!=="-"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.detailRow,children:[
|
|
715
740
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsSent}),
|
|
716
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.detailValue,children:sentDate})]}):null]}):null,current.status==="awaiting_upload"?/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:current.id,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload}):null,current.statusLabel.length>0?/* @__PURE__ */jsxRuntime.
|
|
741
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.detailValue,children:sentDate})]}):null]}):null,current.status==="awaiting_upload"?/* @__PURE__ */jsxRuntime.jsx(UploadRecordCard,{records:records,requestId:current.id,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,canUpload:canUpload}):null,current.statusLabel.length>0||current.heldItemCount>0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.statusRow,accessibilityRole:"summary",testID:"records-request-status-row",children:[current.statusLabel.length>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:current.statusLabel,tone:selectRequestStatusTone(current),testID:"records-request-status-chip"}):null,current.heldItemCount>0?/* @__PURE__ */jsxRuntime.jsx(Chip,{label:heldItemsLabel(current.heldItemCount),tone:"neutral",testID:"records-request-held-count"}):null]}):null,expectation&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoNote,accessibilityRole:"summary",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoNoteText,children:expectation})}):current.wireStatus==="awaiting_response"&&!waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.infoNote,accessibilityRole:"summary",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.infoNoteText,children:REQUEST_SCREEN_COPY.awaitingNote})}):null,waitingTooLong?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:styles.cautionNote,accessibilityRole:"summary",testID:"records-request-waiting-banner",children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.cautionNoteText,children:REQUEST_SCREEN_COPY.waitingBanner(elapsedDays)})}):null,published&&onNavigate?/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.viewRecords,onPress:()=>onNavigate({name:"dashboard"}),style:local.readyCta,testID:"records-request-view-dashboard"}):null,showRecovery?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[local.failureCard,failed?local.failureCritical:local.failureCaution],accessibilityRole:"summary",testID:"records-failure-card",children:[
|
|
717
742
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[local.failureTitle,failed?local.failureTitleCritical:local.failureTitleCaution],children:failureTitle(current)}),current.canUpdateClinicEmail!==true&¤t.canRetrySend!==true?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.rowDetail,children:REQUEST_SCREEN_COPY.nextStep}):null,current.canUpdateClinicEmail===true?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:local.emailBlock,children:[
|
|
718
743
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.fieldLabel,children:RECORDS_RECOVERY_COPY.email}),
|
|
719
744
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{style:styles.field,accessibilityLabel:RECORDS_RECOVERY_COPY.email,placeholder:RECORDS_RECOVERY_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,maxLength:320,value:form.email,editable:!form.busy,onChangeText:form.setEmail,testID:"records-failure-clinic-email"}),form.emailInvalid?/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.errorText,accessibilityRole:"alert",children:REQUEST_SCREEN_COPY.errors.invalidEmail}):null,
|
|
@@ -725,13 +750,13 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:local.conte
|
|
|
725
750
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:local.confirmTitle,accessibilityRole:"header",children:RECORDS_RECOVERY_COPY.cancelQuestion}),
|
|
726
751
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
727
752
|
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onPress:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
|
|
728
|
-
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function
|
|
729
|
-
return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let
|
|
753
|
+
/* @__PURE__ */jsxRuntime.jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsxRuntime.jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles11(){let theme=useEverfurTheme();return react.useMemo(()=>makeLocalStyles11(theme),[theme])}function makeLocalStyles11(theme){let{color:color,space:space,radius:radius,type:type}=theme,text4=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return reactNative.StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xxl,gap:space.lg+space.xs/2},readyCta:{minHeight:space.xxl+space.lg+space.xs/2},sent:{gap:space.xs},card:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surface,padding:space.lg,gap:space.md,...slotBox(recordCardSlot(theme.slots),1)},cardTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(recordCardSlot(theme.slots))},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.lg},detailValue:{flexShrink:1,textAlign:"right",...text4(type.size.body,type.lineHeight.normal,color.text.primary)},failureCard:{borderRadius:radius.lg-space.xs,borderWidth:1,padding:space.md+space.xs/2,gap:space.md},failureCritical:{borderColor:color.badgeBgCritical,backgroundColor:color.badgeBgCritical},failureCaution:{borderColor:color.badgeBgCaution,backgroundColor:color.badgeBgCaution},failureTitle:{...text4(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},failureTitleCritical:{color:color.danger},failureTitleCaution:{color:color.warningStrong},emailBlock:{gap:space.sm},callBlock:{gap:space.sm},block:{gap:space.sm},statusRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:space.sm},confirmTitle:{...text4(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")}})}var REF_MAX=128;var ICONS=/* @__PURE__ */new Set(["shield","arrow","check","star","truck","refresh","card","alert","x","chat","repeat","calendar","flame","box","cart","minus","plus","chev","pulse","file","kit","dna","heart","bottle","harness","ramp"]),TONES=/* @__PURE__ */new Set(["y","c","g","r"]),TRACK_STATES=/* @__PURE__ */new Set(["done","now","next"]),obj=value=>value!==null&&typeof value=="object"&&!Array.isArray(value)?value:null,str4=(value,max=1e3)=>typeof value=="string"&&value.trim().length>0&&value.length<=max?value.trim():null,kindOf=value=>typeof value=="string"&&/^[A-Za-z0-9_-]{1,40}$/.test(value)?value:null,iconOf=value=>typeof value=="string"&&ICONS.has(value)?value:null;function imageOf(value){let s=str4(value,2048);return s===null||/\s/.test(s)?null:/^https:\/\/[^/]/i.test(s)||/^\/(?![/\\])/.test(s)?s:null}var idOf=value=>typeof value=="number"&&Number.isInteger(value)?String(value):str4(value,REF_MAX);function weightOf(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:null}function clean(fields){/* @__PURE__ */
|
|
754
|
+
return Object.freeze(Object.fromEntries(Object.entries(fields).filter(([,v])=>v!=null)))}function listOf(value,each,max=20){if(!Array.isArray(value))return null;let out=[];for(let row of value){if(out.length>=max)break;let mapped=each(row);mapped!==null&&out.push(mapped)}return out.length===0?null:/* @__PURE__ */Object.freeze(out)}var words=(value,max=12,len=300)=>listOf(value,v=>str4(v,len),max);function focusOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,300);if(o===null||kicker===null||title===null)return null;let risk=obj(o.risk),odds=obj(o.odds),quote=obj(o.quote),jump=obj(o.jump);return clean({kicker:kicker,title:title,sources:listOf(o.sources,r=>{let label2=str4(obj(r)?.label,60);return label2===null?null:clean({label:label2,kind:kindOf(obj(r)?.kind)})},6),risk:str4(risk?.lead,300)===null?null:clean({lead:str4(risk?.lead,300),body:str4(risk?.body),kind:kindOf(risk?.kind)}),odds:str4(odds?.label,120)===null||str4(odds?.from,20)===null||str4(odds?.to,20)===null?null:clean({label:str4(odds?.label,120),tag:str4(odds?.tag,40),from:str4(odds?.from,20),to:str4(odds?.to,20),toLabel:str4(odds?.toLabel,120)}),quote:str4(quote?.text)===null?null:clean({kicker:str4(quote?.kicker,120),tag:str4(quote?.tag,40),text:str4(quote?.text)}),jump:str4(jump?.title,300)===null||str4(jump?.go,60)===null?null:clean({title:str4(jump?.title,300),go:str4(jump?.go,60)})})}function routineOf(value){let o=obj(value),title=str4(o?.title,300),steps=listOf(o?.steps,r=>{let s=obj(r),t=str4(s?.title,300),tone=s?.tone;return t===null?null:clean({title:t,body:str4(s?.body),source:str4(s?.source,200),tone:typeof tone=="string"&&TONES.has(tone)?tone:null,icon:iconOf(s?.icon),fromVet:s?.fromVet===true?true:null})});return title===null||steps===null?null:clean({title:title,label:str4(o?.label,60),steps:steps})}function pickOf(value){let o=obj(value),title=str4(o?.title,300);if(o===null||title===null)return null;let rating=obj(o.rating),reviews=obj(o.reviews),why=obj(o.why),score=obj(why?.score),dose=obj(o.dose),ingredients=obj(o.ingredients),reviewItems=listOf(reviews?.items,r=>{let v=obj(r),stars=v?.stars,text4=str4(v?.text),by=str4(v?.by,80);return typeof stars!="number"||!Number.isFinite(stars)||stars<1||stars>5||text4===null||by===null?null:clean({stars:Math.round(stars),text:text4,by:by})},5),whyRows=listOf(why?.rows,r=>{let v=obj(r),chip=str4(v?.chip,40),t=str4(v?.title,300);return chip===null||t===null?null:clean({chip:chip,kind:kindOf(v?.kind),title:t,body:str4(v?.body)})}),stats=listOf(dose?.stats,r=>{let v=obj(r),val=str4(v?.value,40),label2=str4(v?.label,120),kind=v?.kind;return val===null||label2===null?null:clean({value:val,label:label2,kind:kind==="weight"||kind==="dose"||kind==="days"?kind:null})},6),ingredientItems=words(ingredients?.items,12,80);return clean({title:title,none:o.none===true?true:null,hidden:o.none===true&&o.hidden===true?true:null,productId:idOf(o.productId),partnerSku:str4(o.partnerSku,200),rating:str4(rating?.value,20)===null?null:clean({value:str4(rating?.value,20),label:str4(rating?.label,120)}),line:str4(o.line),reviews:str4(reviews?.label,200)===null||reviewItems===null?null:clean({label:str4(reviews?.label,200),items:reviewItems}),checkoutLine:str4(o.checkoutLine,300),why:str4(why?.title,200)===null||whyRows===null?null:clean({title:str4(why?.title,200),rows:whyRows,score:str4(score?.text,200)===null||str4(score?.value,20)===null?null:clean({text:str4(score?.text,200),value:str4(score?.value,20)})}),dose:str4(dose?.title,200)===null||stats===null?null:clean({title:str4(dose?.title,200),stats:stats,note:str4(dose?.note)}),doseLabel:str4(o.doseLabel,120),ingredients:ingredientItems===null?null:clean({label:str4(ingredients?.label,200),items:ingredientItems}),proof:str4(o.proof,300),trust:listOf(o.trust,r=>{let v=obj(r),icon=iconOf(v?.icon),label2=str4(v?.label,120);return icon===null||label2===null?null:clean({icon:icon,label:label2})},6),more:str4(o.more,120),fine:str4(o.fine),checkin:str4(o.checkin,200)})}function signsOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),t=str4(v?.title,300),body=str4(v?.body);return t===null||body===null?null:clean({title:t,body:body,urgent:v?.urgent===true?true:null,callVet:v?.callVet===true?true:null})});return title===null||items===null?null:clean({title:title,items:items})}function checkupOf(value){let o=obj(value),title=str4(o?.title,200),questions=words(o?.questions,12,300),add=str4(o?.add,80),added=str4(o?.added,80);return title===null||questions===null||add===null||added===null?null:clean({title:title,questions:questions,add:add,added:added})}function extrasOf(value){let o=obj(value),title=str4(o?.title,200),items=listOf(o?.items,r=>{let v=obj(r),key=str4(v?.key,REF_MAX),t=str4(v?.title,300),action=str4(v?.action,80),productId=idOf(v?.productId),added=str4(v?.added,80)??(productId!==null?action:null);return key===null||t===null||action===null||added===null?null:clean({key:key,productId:productId,title:t,body:str4(v?.body),price:str4(v?.price,40),was:str4(v?.was,40),tag:str4(v?.tag,40),imageUrl:imageOf(v?.imageUrl),icon:iconOf(v?.icon),kind:kindOf(v?.kind),action:action,added:added,owned:v?.owned===true?true:null})},6);return title===null||items===null?null:clean({title:title,items:items})}function waitOf(value){let o=obj(value),kicker=str4(o?.kicker,120),title=str4(o?.title,120);return o===null||kicker===null||title===null?null:clean({kicker:kicker,title:title,icon:iconOf(o.icon),track:listOf(o.track,r=>{let v=obj(r),t=str4(v?.title,120),state=v?.state;return t===null?null:clean({title:t,detail:str4(v?.detail,120),state:typeof state=="string"&&TRACK_STATES.has(state)?state:null,tag:str4(v?.tag,40)})},6),heading:str4(o.heading,200),rows:listOf(o.rows,r=>{let v=obj(r),icon=iconOf(v?.icon),label2=str4(v?.label,120);if(icon===null||label2===null)return null;if(v?.fromVet===true)return clean({icon:icon,label:label2,text:"",fromVet:true});let text4=str4(v?.text,300);return text4===null?null:clean({icon:icon,label:label2,text:text4})},6),note:str4(o.note,300),action:str4(o.action,80)})}function healthPlanFocusDesignFromWire(raw){let o=obj(raw),title=str4(o?.title,300),pick2=pickOf(o?.pick);if(o===null||title===null||pick2===null)return null;let byline=obj(o.byline);return clean({eyebrow:str4(o.eyebrow,120),title:title,subtitle:str4(o.subtitle,300),subtitleNoRecords:str4(o.subtitleNoRecords,300),headImageUrl:imageOf(o.headImageUrl),byline:str4(byline?.name,120)===null?null:clean({name:str4(byline?.name,120),role:str4(byline?.role,120),imageUrl:imageOf(byline?.imageUrl),shortName:str4(byline?.shortName,60)}),focus:focusOf(o.focus),routine:routineOf(o.routine),pick:pick2,signs:signsOf(o.signs),checkup:checkupOf(o.checkup),extras:extrasOf(o.extras),wait:waitOf(o.wait),fine:str4(o.fine),checkoutRows:listOf(o.checkoutRows,r=>{let v=obj(r),icon=iconOf(v?.icon),label2=str4(v?.label,60),val=str4(v?.value,200);return icon===null||label2===null||val===null?null:clean({icon:icon,label:label2,value:val})},6)})}function healthPlanPageFromWire(raw,petRef){let o=obj(raw);if(o===null||!("page"in o))return null;let pet=obj(o.pet),sex=pet?.sex;/* @__PURE__ */
|
|
730
755
|
return Object.freeze({petRef:str4(o.pet_ref,REF_MAX)??petRef,pet:/* @__PURE__ */Object.freeze({name:str4(pet?.name,120),species:str4(pet?.species,60),sex:sex==="female"||sex==="male"?sex:null,breed:str4(pet?.breed,120),weightKg:weightOf(pet?.weight_kg),weightLb:weightOf(pet?.weight_lb)}),checkout:o.checkout==="everfur_stripe"?"everfur_stripe":"partner",page:healthPlanFocusDesignFromWire(o.page),vetReviewed:o.vet_reviewed===true,trackingTextsEnabled:o.tracking_texts_enabled===true})}function invalid3(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function malformed3(call){return makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:`${call}: the response was not the expected shape`})}function disposed(verb){return makeEverfurError("runtimeDisposed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${verb} was called after unmount`})}var validRef=value=>typeof value=="string"&&value.length>0&&value.length<=REF_MAX;function base(petRef){return`/widget/v1/pets/${encodeURIComponent(petRef)}/plan`}async function readPage(funnel,petRef,opts){if(!validRef(petRef))return err(invalid3("petRef must be 1..128 characters"));let res=await funnel.send("healthPlan.page.read",{method:"GET",path:`${base(petRef)}/page`,...opts?.signal?{signal:opts.signal}:{}});if(!res.ok)return err(res.error);let page=healthPlanPageFromWire(res.value,petRef);return page===null?err(malformed3("healthPlan.page.read")):ok(page)}var readers=/* @__PURE__ */new WeakMap;function createHealthPlanPageReader(runtime){let known=readers.get(runtime);if(known!==void 0)return known;let reader=makeHealthPlanPageReader(runtime);return readers.set(runtime,reader),reader}function makeHealthPlanPageReader(runtime){return{getPage:(petRef,opts)=>{if(runtime.isDisposed)return Promise.resolve(err(disposed("getPage")));let{services:services}=runtime.registry,funnel=withPlainNotFound(createRequestFunnel({auth:services.authFor(null),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}}));return readPage(funnel,petRef,opts)}}}var HEALTH_PLAN_STALE_MS=6e4;function useHealthPlanRevalidation({lifecycle:lifecycle,refreshKey:refreshKey,readyAt:readyAt,revalidate:revalidate,refresh:refresh,now:now=Date.now}){let latest=react.useRef({readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now});latest.current={readyAt:readyAt,revalidate:revalidate,refresh:refresh??revalidate,now:now},react.useEffect(()=>{if(lifecycle==null)return;let stop=callHost(()=>lifecycle.onForeground(()=>{let{readyAt:at,revalidate:run,now:clock}=latest.current;at!==null&&clock()-at>=HEALTH_PLAN_STALE_MS&&run()}));return()=>{typeof stop=="function"&&callHost(stop)}},[lifecycle]);let seenKey=react.useRef(refreshKey);react.useEffect(()=>{Object.is(seenKey.current,refreshKey)||(seenKey.current=refreshKey,latest.current.refresh())},[refreshKey])}var HEALTH_PLAN_PAGE_SHARE_MS=HEALTH_PLAN_STALE_MS,SHARED_READS_SYMBOL=/* @__PURE__ */Symbol.for("@everfur/sdk#HealthPlanPageReads@v1");function sharedReads(){let host=globalThis,stored=host[SHARED_READS_SYMBOL];if(stored instanceof WeakMap)return stored;let made=/* @__PURE__ */new WeakMap;return host[SHARED_READS_SYMBOL]=made,made}function readShared(reader,runtime,userRef,petRef,fresh){let all=sharedReads(),reads=all.get(runtime);reads===void 0&&(reads=/* @__PURE__ */new Map,all.set(runtime,reads));let map=reads,key=`${userRef}\0${petRef}`,hit=map.get(key);if(!fresh&&hit!==void 0&&(hit.at===null||Date.now()-hit.at<HEALTH_PLAN_PAGE_SHARE_MS))return hit.promise;let entry={at:null,promise:reader.getPage(petRef).then(res=>(map.get(key)===entry&&(res.ok||isNotFoundError(res.error)?entry.at=Date.now():map.delete(key)),res))};return map.set(key,entry),entry.promise}function useHealthPlanPage(options){let{userRef:userRef,runtime:runtime}=useEverfurContext(),own=react.useMemo(()=>createHealthPlanPageReader(runtime),[runtime]),hostRepository=options.repository,repository=hostRepository??own,getPage=react.useCallback((pet,fresh)=>hostRepository!==void 0||userRef==null?repository.getPage(pet):readShared(own,runtime,userRef,pet,fresh),[hostRepository,repository,own,runtime,userRef]),{petRef:petRef}=options,enabled=options.enabled!==false&&userRef!=null&&petRef!==null,[state,setState]=react.useState({phase:"idle",petRef:null,page:null,error:null}),epoch=react.useRef(0),quiet=react.useRef(0),read=react.useCallback(async fresh=>{let mine=++epoch.current;if(!enabled||petRef===null){setState(prev=>prev.phase==="idle"&&prev.petRef===null?prev:{phase:"idle",petRef:null,page:null,error:null});return}setState(prev=>({phase:"loading",petRef:petRef,page:prev.petRef===petRef?prev.page:null,error:null}));let res=await getPage(petRef,fresh);mine===epoch.current&&(res.ok?setState({phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}):isNotFoundError(res.error)?setState({phase:"ready",petRef:petRef,page:null,error:null,missing:true,readyAt:Date.now()}):setState({phase:"failed",petRef:petRef,page:null,error:res.error}))},[enabled,petRef,getPage]),load=react.useCallback(()=>read(true),[read]),ready=state.phase==="ready"&&state.petRef===petRef,revalidate=react.useCallback(async()=>{if(!enabled||petRef===null||!ready)return;let mine=epoch.current,seq=++quiet.current,res=await getPage(petRef,true);mine!==epoch.current||seq!==quiet.current||!res.ok||setState(prev=>prev.phase==="ready"&&prev.petRef===petRef?{phase:"ready",petRef:petRef,page:res.value,error:null,readyAt:Date.now()}:prev)},[enabled,petRef,ready,getPage]);useHealthPlanRevalidation({lifecycle:options.lifecycle,refreshKey:options.refreshKey,readyAt:ready?state.readyAt??null:null,revalidate:()=>{revalidate()},refresh:()=>{ready?revalidate():load()}}),react.useEffect(()=>(read(false),()=>{epoch.current+=1}),[read]);let stale=enabled&&state.petRef!==petRef;return react.useMemo(()=>({phase:stale?"loading":state.phase,page:stale?null:state.page,error:stale?null:state.error,missing:!stale&&state.missing===true,refresh:load}),[stale,state,load])}var SPECIES_ALIASES=/* @__PURE__ */Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function canonicalPetSpecies(raw){if(typeof raw!="string")return null;let key=raw.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(SPECIES_ALIASES,key)?SPECIES_ALIASES[key]:null}var LIST_MAX=50,REF_MAX2=128,NAME_MAX=120,SHORT_MAX=120,NOTES_MAX=2e3,FOOD_MAX=120,MICROCHIP_MAX=80,SEXES=/* @__PURE__ */new Set(["male","female","unknown"]),PRECISIONS=/* @__PURE__ */new Set(["day","month","year"]),ACTIVITY=/* @__PURE__ */new Set(["low","medium","high","athletic"]),INDOOR_OUTDOOR=/* @__PURE__ */new Set(["indoor","outdoor","both"]),SEVERITIES=/* @__PURE__ */new Set(["mild","moderate","severe"]),ISO_DATE2=/^(\d{4})-(\d{2})-(\d{2})$/,SCALAR_WIRE=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],LIST_WIRE=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];/* @__PURE__ */Object.freeze([...SCALAR_WIRE,...LIST_WIRE].map(([key])=>key));function isRealDate(value){let match=ISO_DATE2.exec(value);if(match===null)return false;let[year,month,day]=[Number(match[1]),Number(match[2]),Number(match[3])],date2=new Date(Date.UTC(year,month-1,day));return date2.getUTCFullYear()===year&&date2.getUTCMonth()===month-1&&date2.getUTCDate()===day}var oneOf=allowed=>(field,value)=>typeof value=="string"&&allowed.has(value)?null:`${field} must be one of ${[...allowed].join(", ")}`,boolean=(field,value)=>typeof value=="boolean"?null:`${field} must be true or false`,date=(field,value)=>typeof value=="string"&&isRealDate(value)?null:`${field} must be a real date written YYYY-MM-DD`,text3=(max,opts={})=>(field,value)=>{if(typeof value!="string")return`${field} must be a string`;if(hasLoneSurrogate(value))return`${field} contains an unpaired surrogate and cannot be encoded`;let measured=opts.trimmed?value.trim():value;if(opts.required&&measured.length===0)return`${field} is required and must not be blank`;let length=serverLength(measured);return length<=max?null:`${field} is ${length} characters; the server accepts at most ${max}`},SCALAR_CHECKS={sex:oneOf(SEXES),spayedNeutered:boolean,birthDate:date,birthDatePrecision:oneOf(PRECISIONS),activityLevel:oneOf(ACTIVITY),indoorOutdoor:oneOf(INDOOR_OUTDOOR),foodBrand:text3(FOOD_MAX),foodType:text3(FOOD_MAX),microchipId:text3(MICROCHIP_MAX)},REF_FIELD=["ref","ref",false,text3(REF_MAX2,{required:true,trimmed:true})],NOTES_FIELD=["notes","notes",false,text3(NOTES_MAX,{trimmed:true})],MEDICATION_FIELDS=[REF_FIELD,["name","name",true,text3(NAME_MAX,{required:true,trimmed:true})],["dose","dose",false,text3(SHORT_MAX,{trimmed:true})],["frequency","frequency",false,text3(SHORT_MAX,{trimmed:true})],["startDate","start_date",false,date],["endDate","end_date",false,date],NOTES_FIELD],ITEM_FIELDS={allergies:[REF_FIELD,["allergen","allergen",true,text3(NAME_MAX,{required:true,trimmed:true})],["severity","severity",false,oneOf(SEVERITIES)],NOTES_FIELD],medications:MEDICATION_FIELDS,supplements:MEDICATION_FIELDS,conditions:[REF_FIELD,["conditionName","condition_name",true,text3(NAME_MAX,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,date],NOTES_FIELD]};function itemToWire(list,index,raw){let at=`${list}[${index}]`;if(typeof raw!="object"||raw===null||Array.isArray(raw))return{error:`${at} must be an object`};let source=raw,item={};for(let[key,wire,isRequired,check]of ITEM_FIELDS[list]){let value=source[key];if(value==null){if(isRequired)return{error:`${at}.${key} is required`};value===null&&(item[wire]=null);continue}let bad=check(`${at}.${key}`,value);if(bad!==null)return{error:bad};item[wire]=value}let start=item.start_date,end=item.end_date;return typeof start=="string"&&typeof end=="string"&&end<start?{error:`${at}.endDate must not be before startDate`}:{item:item}}function listToWire(list,raw){if(!Array.isArray(raw))return{error:`${list} must be an array (send [] to clear it)`};if(raw.length>LIST_MAX)return{error:`${list} has ${raw.length} items; the server accepts at most ${LIST_MAX}`};let items=[],refs=/* @__PURE__ */new Set;for(let index=0;index<raw.length;index+=1){let mapped=itemToWire(list,index,raw[index]);if("error"in mapped)return mapped;let ref=mapped.item.ref;if(typeof ref=="string"){let key=ref.trim();if(refs.has(key))return{error:`${list}: ref ${JSON.stringify(key)} is used twice; a ref names one item`};refs.add(key)}items.push(mapped.item)}return{items:items}}function petHealthToWire(input,species){let source=input,body={};for(let[key,wire]of SCALAR_WIRE){let value=source[key];if(value!==void 0){if(value!==null){let bad=SCALAR_CHECKS[key](key,value);if(bad!==null)return{error:bad}}body[wire]=value}}let dateSent=source.birthDate!==void 0,precisionSent=source.birthDatePrecision!==void 0;if(dateSent!==precisionSent||dateSent&&source.birthDate===null!=(source.birthDatePrecision===null))return{error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[key,wire]of LIST_WIRE){let value=source[key];if(value===void 0)continue;let mapped=listToWire(key,value);if("error"in mapped)return mapped;body[wire]=mapped.items}return Object.keys(body).length>0&&species!==void 0&&canonicalPetSpecies(species)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:body}}var str5=value=>typeof value=="string"?value:null,pick=(allowed,value)=>typeof value=="string"&&allowed.has(value)?value:null,bool=value=>typeof value=="boolean"?value:null;function itemsFromWire(raw,map){return Array.isArray(raw)?/* @__PURE__ */Object.freeze(raw.flatMap(row=>{if(typeof row!="object"||row===null||Array.isArray(row))return[];let item=map(row);return item===null?[]:[item]})):/* @__PURE__ */Object.freeze([])}function medicationFromWire(o){let name=str5(o.name);return name===null||name.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(o.ref),name:name,dose:str5(o.dose),frequency:str5(o.frequency),startDate:str5(o.start_date),endDate:str5(o.end_date),notes:str5(o.notes)})}function petHealthFromWire(o){let version=o.profile_version;/* @__PURE__ */
|
|
731
756
|
return Object.freeze({profileVersion:typeof version=="number"&&Number.isInteger(version)&&version>=0?version:0,sex:pick(SEXES,o.sex),spayedNeutered:bool(o.spayed_neutered),birthDate:str5(o.birth_date),birthDatePrecision:pick(PRECISIONS,o.birth_date_precision),activityLevel:pick(ACTIVITY,o.activity_level),indoorOutdoor:pick(INDOOR_OUTDOOR,o.indoor_outdoor),foodBrand:str5(o.food_brand),foodType:str5(o.food_type),microchipId:str5(o.microchip_id),allergies:itemsFromWire(o.allergies,row=>{let allergen=str5(row.allergen);return allergen===null||allergen.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),allergen:allergen,severity:pick(SEVERITIES,row.severity),notes:str5(row.notes)})}),medications:itemsFromWire(o.medications,medicationFromWire),supplements:itemsFromWire(o.supplements,medicationFromWire),conditions:itemsFromWire(o.conditions,row=>{let conditionName=str5(row.condition_name);return conditionName===null||conditionName.length===0?null:/* @__PURE__ */Object.freeze({ref:str5(row.ref),conditionName:conditionName,diagnosedDate:str5(row.diagnosed_date),notes:str5(row.notes)})})})}var PET_NAME_MAX=100,PET_SPECIES_MAX=50,PET_BREED_MAX=100,PET_AGE_YEARS_MAX=50,PET_WEIGHT_KG_MAX=500,PET_REF_MAX2=128,ERASE_USER_DATA_TIMEOUT_MS=6e4;function invalid4(wireMessage){return makeEverfurError("validationFailed",{retryable:false,wireMessage:wireMessage})}function checkString(field,value,max){if(typeof value!="string")return invalid4(`${field} must be a string`);let length=serverLength(value);return length<=max?null:invalid4(`${field} is ${length} characters; the server accepts at most ${max}`)}function outOfRange(field,value,max){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=max?null:invalid4(`${field} must be a finite number between 0 and ${max}`)}function validate(petRef,profile){if(typeof petRef!="string")return invalid4("pet_ref must be a string");if(petRef.trim().length===0)return invalid4("pet_ref must not be blank");if(hasLoneSurrogate(petRef))return invalid4("pet_ref contains an unpaired surrogate and cannot be encoded");if(profile!=null&&typeof profile!="object")return invalid4("profile must be an object");let checks=[checkString("pet_ref",petRef,PET_REF_MAX2)];return profile?.name!==void 0&&checks.push(checkString("name",profile.name,PET_NAME_MAX)),profile?.species!==void 0&&checks.push(checkString("species",profile.species,PET_SPECIES_MAX)),profile?.breed!==void 0&&checks.push(checkString("breed",profile.breed,PET_BREED_MAX)),profile?.ageYears!==void 0&&checks.push(outOfRange("age_years",profile.ageYears,PET_AGE_YEARS_MAX)),profile?.weightKg!==void 0&&checks.push(outOfRange("weight_kg",profile.weightKg,PET_WEIGHT_KG_MAX)),checks.find(c=>c!==null)??null}function healthToWire(source,species){let health=petHealthToWire(source,species);return"error"in health?{error:invalid4(health.error)}:health}function patchToWire(patch){if(typeof patch!="object"||patch===null)return{error:invalid4("patch must be an object")};let p=patch,fields=[["name","name",v=>checkString("name",v,PET_NAME_MAX)],["species","species",v=>checkString("species",v,PET_SPECIES_MAX)],["breed","breed",v=>checkString("breed",v,PET_BREED_MAX)],["ageYears","age_years",v=>outOfRange("age_years",v,PET_AGE_YEARS_MAX)],["weightKg","weight_kg",v=>outOfRange("weight_kg",v,PET_WEIGHT_KG_MAX)]],body={};for(let[key,wire,check]of fields){let value=p[key];if(value!==void 0){if(value!==null){let bad=check(value);if(bad!==null)return{error:bad}}body[wire]=value}}let health=healthToWire(p,p.species);return"error"in health?health:(Object.assign(body,health.body),Object.keys(body).length===0?{error:invalid4("patch must change at least one field")}:{body:body})}function toWire(profile){if(profile==null)return{body:{}};let health=healthToWire(profile,profile.species);return"error"in health?health:{body:{...profile.name!==void 0?{name:profile.name}:{},...profile.species!==void 0?{species:profile.species}:{},...profile.breed!==void 0?{breed:profile.breed}:{},...profile.ageYears!==void 0?{age_years:profile.ageYears}:{},...profile.weightKg!==void 0?{weight_kg:profile.weightKg}:{},...health.body}}}var str6=v=>typeof v=="string"?v:null,num3=v=>typeof v=="number"&&Number.isFinite(v)?v:null;function fromWire2(raw,petRef){let o=typeof raw=="object"&&raw!==null?raw:{};/* @__PURE__ */
|
|
732
757
|
return Object.freeze({petRef:str6(o.pet_ref)??petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg)})}function widgetPetFromWire(raw){if(typeof raw!="object"||raw===null)return null;let o=raw,petRef=str6(o.pet_ref);return petRef===null||petRef.length===0?null:/* @__PURE__ */Object.freeze({petId:str6(o.pet_id),petRef:petRef,name:str6(o.name),species:str6(o.species),breed:str6(o.breed),ageYears:num3(o.age_years),weightKg:num3(o.weight_kg),updatedAt:str6(o.updated_at)})}function widgetPetProfileFromWire(raw){let pet=widgetPetFromWire(raw);return pet===null?null:/* @__PURE__ */Object.freeze({...pet,...petHealthFromWire(raw)})}function petListFromWire(raw){let rows=Array.isArray(raw)?raw:typeof raw=="object"&&raw!==null&&Array.isArray(raw.pets)?raw.pets:[];/* @__PURE__ */
|
|
733
758
|
return Object.freeze(rows.flatMap(row=>{let pet=widgetPetFromWire(row);return pet===null?[]:[pet]}))}function createPetsRepository(auth){return createPetsRepositoryOver(createRequestFunnel({auth:auth}),createRequestFunnel({auth:auth,unaryTimeoutMs:ERASE_USER_DATA_TIMEOUT_MS}))}function createPetsRepositoryOver(funnel,eraseFunnel=funnel){let withSignal=(req,signal)=>signal?{...req,signal:signal}:req,petPath=petRef=>validate(petRef,void 0)??`/widget/v1/pets/${encodeURIComponent(petRef)}`;return{async list(opts){let res=await funnel.send("pets.list",withSignal({method:"GET",path:"/widget/v1/pets"},opts?.signal));return res.ok?ok(petListFromWire(res.value)):err(res.error)},async registerPet(petRef,profile,opts){let invalid5=validate(petRef,profile);if(invalid5!==null)return err(invalid5);let wire=toWire(profile);if("error"in wire)return err(wire.error);let base2={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(petRef)}`,body:wire.body},res=await funnel.send("pets.registerPet",opts?.signal?{...base2,signal:opts.signal}:base2);return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async updatePet(petRef,patch,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let wire=patchToWire(patch);if("error"in wire)return err(wire.error);let res=await funnel.send("pets.updatePet",withSignal({method:"PATCH",path:path,body:wire.body},opts?.signal));return res.ok?ok(fromWire2(res.value,petRef)):err(res.error)},async getPetProfile(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.getPetProfile",withSignal({method:"GET",path:`${path}/profile`},opts?.signal));if(!res.ok)return err(res.error);let profile=widgetPetProfileFromWire(res.value);return profile===null?err(makeEverfurError("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):ok(profile)},async deletePet(petRef,opts){let path=petPath(petRef);if(typeof path!="string")return err(path);let res=await funnel.send("pets.deletePet",withSignal({method:"DELETE",path:path},opts?.signal));return res.ok?ok(void 0):err(res.error)},async eraseUserData(opts){let res=await eraseFunnel.send("pets.eraseUserData",withSignal({method:"DELETE",path:"/widget/v1/me"},opts?.signal),{maxAttempts:1});return res.ok?ok(void 0):err(res.error)}}}var listeners2=/* @__PURE__ */new WeakMap;function subscribePetsChanged(runtime,listener){let set=listeners2.get(runtime);return set===void 0&&(set=/* @__PURE__ */new Set,listeners2.set(runtime,set)),set.add(listener),()=>{set?.delete(listener)}}function useEverfurPets(){let{runtime:runtime,userRef:userRef,activePet:activePetRef,scopeEpoch:scopeEpoch}=useEverfurContext(),repository=react.useMemo(()=>createPetsRepository(runtime.registry.services.authFor(userRef)),[runtime,userRef,scopeEpoch]),[state,setState]=react.useState({repository:repository,pets:[],loading:true,error:null}),current=state.repository===repository?state:{pets:[],loading:true,error:null},generation=react.useRef(0),load=react.useCallback(async()=>{let request=++generation.current;setState(previous=>({...previous,repository:repository,loading:true,error:null,pets:previous.repository===repository?previous.pets:[]}));let result=await repository.list();request===generation.current&&setState(result.ok?{repository:repository,pets:result.value,loading:false,error:null}:previous=>({repository:repository,pets:previous.repository===repository?previous.pets:[],loading:false,error:result.error}))},[repository]);react.useEffect(()=>(load(),()=>{generation.current+=1}),[load]),react.useEffect(()=>subscribePetsChanged(runtime,()=>{load()}),[runtime,load]);let activePet=react.useMemo(()=>activePetRef===null?null:current.pets.find(pet=>pet.petRef===activePetRef)??null,[activePetRef,current.pets]);return react.useMemo(()=>({pets:current.pets,activePet:activePet,loading:current.loading,error:current.error,refresh:load}),[current.pets,current.loading,current.error,activePet,load])}var DEFAULT_PRESENTATION=/* @__PURE__ */Object.freeze({chatAnswerStyle:"cards",chatHistoryStyle:"sheet",chatTopCard:"focus",chatFollowUpCount:3,chatFollowUpsExcludeTelevet:false,chatComposerMic:true,chatComposerUpload:true,safetyDisclaimerPlacement:"composer",healthPlanLayout:"focus_plan",recordsTopRiskLine:true,recordsClearResultsFilter:true,chatComposerStyle:"compact",chatComposerPlaceholder:"pet_name",chatHistoryBar:"scroll",chatGeneralBanner:true,chatSendButton:"always_dark",chatTextingAsk:true}),PRESENTATION_WIRE_NAMES=/* @__PURE__ */Object.freeze({chatAnswerStyle:"chat_answer_style",chatHistoryStyle:"chat_history_style",chatTopCard:"chat_top_card",chatFollowUpCount:"chat_follow_up_count",chatFollowUpsExcludeTelevet:"chat_follow_ups_exclude_televet",chatComposerMic:"chat_composer_mic",chatComposerUpload:"chat_composer_upload",safetyDisclaimerPlacement:"safety_disclaimer_placement",healthPlanLayout:"health_plan_layout",recordsTopRiskLine:"records_top_risk_line",recordsClearResultsFilter:"records_clear_results_filter",chatComposerStyle:"chat_composer_style",chatComposerPlaceholder:"chat_composer_placeholder",chatHistoryBar:"chat_history_bar",chatGeneralBanner:"chat_general_banner",chatSendButton:"chat_send_button",chatTextingAsk:"chat_texting_ask"}),FIELDS=Object.keys(PRESENTATION_WIRE_NAMES),PRESENTATION_LOCK="presentation",PRESENTATION_LOCK_PREFIX="presentation.";var ENUMS={chatAnswerStyle:["bubbles","cards"],chatHistoryStyle:["drawer","sheet"],chatTopCard:["none","focus"],safetyDisclaimerPlacement:["composer","answer_footer"],healthPlanLayout:["standard","focus_plan"],chatComposerStyle:["standard","compact"],chatComposerPlaceholder:["generic","pet_name"],chatHistoryBar:["pinned","scroll"],chatSendButton:["always_dark","dim_when_empty"]},BOOLS=/* @__PURE__ */new Set(["chatFollowUpsExcludeTelevet","chatComposerMic","chatComposerUpload","recordsTopRiskLine","recordsClearResultsFilter","chatGeneralBanner","chatTextingAsk"]);function parseField(field,value){if(value==null)return;let allowed=ENUMS[field];return allowed!==void 0?typeof value=="string"&&allowed.includes(value)?value:void 0:BOOLS.has(field)?typeof value=="boolean"?value:void 0:typeof value=="number"&&Number.isInteger(value)&&value>=0&&value<=3?value:void 0}function parsePresentation(raw){if(raw===null||typeof raw!="object"||Array.isArray(raw))return null;let source=raw,out={};for(let field of FIELDS){let wire=PRESENTATION_WIRE_NAMES[field],value=Object.prototype.hasOwnProperty.call(source,wire)?source[wire]:source[field],parsed=parseField(field,value);parsed!==void 0&&(out[field]=parsed)}return Object.keys(out).length===0?null:/* @__PURE__ */Object.freeze(out)}function isPresentationFieldLocked(field,locked){if(locked==null)return false;let one=`${PRESENTATION_LOCK_PREFIX}${PRESENTATION_WIRE_NAMES[field]}`;for(let name of locked)if(name===PRESENTATION_LOCK||name===one)return true;return false}function resolvePresentation(input){let server=parsePresentation(input?.server??null)??{},client=parsePresentation(input?.client??null)??{},locked=input?.locked?[...input.locked]:null,out={};for(let field of FIELDS){let fromServer=server[field],fromClient=isPresentationFieldLocked(field,locked)?void 0:client[field];out[field]=fromClient??fromServer??DEFAULT_PRESENTATION[field]}/* @__PURE__ */
|
|
734
|
-
return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=react.useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=react.useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return react.useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var COARSE_NOW_TICK_MS=3600*1e3;function useCoarseNow(fixed,shown=true){let[now,setNow]=react.useState(()=>fixed??Date.now()),first=react.useRef(true);return react.useEffect(()=>{if(first.current){first.current=false;return}fixed===void 0&&shown&&setNow(Date.now())},[fixed,shown]),react.useEffect(()=>{if(fixed!==void 0||!shown)return;let tick=setInterval(()=>setNow(Date.now()),COARSE_NOW_TICK_MS),onVisible=()=>{document.visibilityState==="visible"&&setNow(Date.now())},doc=typeof document<"u"&&typeof document.addEventListener=="function"?document:null;return doc?.addEventListener("visibilitychange",onVisible),()=>{clearInterval(tick),doc?.removeEventListener("visibilitychange",onVisible)}},[fixed,shown]),fixed??now}var capital=text4=>text4.charAt(0).toUpperCase()+text4.slice(1);function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,vitalsSource:w=>`Where ${w.name}'s vitals come from`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",noDate:"No date",dueIn:(date2,days)=>`Due ${date2} · in ${days} ${days===1?"day":"days"}`,dueToday:date2=>`Due ${date2} · today`,overdueByDays:(date2,days)=>`Overdue by ${days} ${days===1?"day":"days"} · due ${date2}`,recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",screeningsClear:"All clear",screeningsToReview:n2=>`${n2} to review`,noScreenings:"No screenings yet",visits:"Visits & records",timeline:"Timeline",events:n2=>`${n2} ${n2===1?"event":"events"}`,weight:"Weight",vetVisits:n2=>`${n2} vet ${n2===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n2=>`${n2} ${n2===1?"visit":"visits"}`,panelsCount:n2=>`${n2} blood ${n2===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",findClinic:w=>`Find ${w.name}'s clinic`,chooseFile:"Choose a file",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",noVetTitle:w=>`When ${w.name} has a vet, start here.`,requestedFrom:clinic=>`Requested from ${clinic}. Clinics usually take 2 to 5 days.`,onTheWayFrom:(w,clinic)=>`${w.Name}'s records from ${clinic} are on the way.`,readingUpload:"We're reading the document you uploaded.",seeWhereItStands:"See where it stands",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct2)=>` since ${date2}, about ${pct2}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"});var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms2=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms2)?null:ms2}function shortDate(ms2){let d=new Date(ms2);return`${MONTHS2[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms2){return`${shortDate(ms2)}, ${new Date(ms2).getUTCFullYear()}`}function monthTick(ms2){let d=new Date(ms2);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms2=>new Date(ms2).toISOString().slice(0,10);function num4(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text4){let t=text4.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text4){return/temp/i.test(text4)?"temp":/heart|pulse/i.test(text4)?"heart":/resp|breath/i.test(text4)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms2=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms2>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms2})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms2=>ms2>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms2){let key=dayKey(ms2);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num4(lb(kg))} lb`,kilos=`${num4(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms2=dayMs(w.observedOn);return ms2===null||w.weightKg===null?[]:[{ms:ms2,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text4=weightText(last.kg,unit);return{latest:text4.main,sub:`${text4.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms2=dayMs(point.at);if(ms2===null)continue;let key=dayKey(ms2),day=days.get(key)??{ms:ms2,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms2,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num4(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms2=dayMs(e.date);if(ms2===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms2))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms2,date:summary!==null&&type!==null?`${shortDate(ms2)} · ${type}`:shortDate(ms2),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms2=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms2===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms2,date:shortDate(ms2),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n2 of names)panels.set(n2,(panels.get(n2)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label=>({label:label,detail:[(visits.get(label)??0)>0?SHEET_COPY.visitsCount(visits.get(label)??0):null,(panels.get(label)??0)>0?SHEET_COPY.panelsCount(panels.get(label)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}var newestFirst=requests=>[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0)),sentence=label=>/[.!?]$/.test(label)?label:`${label}.`;function sheetOnTheWay(words2,requests){let active=newestFirst(requests).filter(r=>!isTerminalStatus(r.status)),waiting=active.filter(r=>r.status==="awaiting_upload"),moving=active.filter(r=>r.status!=="awaiting_upload"),lines=[],clinics=/* @__PURE__ */new Map;for(let r of moving){let clinic=r.clinicName?.trim()??"";r.source!=="clinic_request"||clinic===""||clinics.has(clinic)||clinics.set(clinic,r)}for(let[clinic,newest]of clinics)lines.push({key:`clinic-${clinic}`,text:SHEET_COPY.onTheWayFrom(words2,clinic),requestId:newest.id});let upload=moving.find(r=>r.source==="owner_provided");upload!==void 0&&lines.push({key:"upload",text:SHEET_COPY.readingUpload,requestId:upload.id});let wait=waiting[0],label=wait?.statusLabel.trim()??"";return wait!==void 0&&label!==""&&lines.push({key:"awaiting-upload",text:sentence(label),requestId:wait.id}),lines}function sheetRequestedClinic(requests){return newestFirst(requests).find(r=>!isTerminalStatus(r.status)&&r.status!=="awaiting_upload"&&r.source==="clinic_request"&&(r.clinicName?.trim()??"")!=="")?.clinicName?.trim()??null}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function sheetAge(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<=0)return null;let totalMonths=Math.floor(ageYears*12+1e-9),years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}M`:months>0?`${years}Y ${months}M`:`${years}Y`}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,sheetAge(inputs.petAgeYears),weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms2=>ms2!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null,inFlight:sheetOnTheWay(inputs.words,inputs.requests),requestedClinic:sheetRequestedClinic(inputs.requests)}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num4(value),unit:unit,range:range===null?null:`${num4(range.low)} to ${num4(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num4(range.low),num4(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric2=marker.points.flatMap(p=>{let ms2=dayMs(p.at);return p.value===null||ms2===null?[]:[{p:p,ms:ms2,v:p.value}]}),chart=[];if(numeric2.length>0){let values=numeric2.map(n2=>n2.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric2.map((n2,i)=>({x:numeric2.length===1?50:Math.round((18+64*i/(numeric2.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n2.v-lo)/(hi-lo))*10)/10)):50,label:num4(n2.v),out:pointFlag(n2.p.status)==="above"||pointFlag(n2.p.status)==="below",tick:shortDate(n2.ms)}))}let first=numeric2[0],final=numeric2[numeric2.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric2.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct2=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num4(delta),row.unit):SHEET_COPY.changeDown(num4(delta),row.unit);change=pct2===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct2)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms2=dayMs(pt.at);return ms2!==null&&dayKey(ms2)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}function mapTier(wire){let tier={url:wire.url,kind:wire.kind,expiresAt:wire.expires_at};return typeof wire.loop_duration_ms=="number"&&(tier.loopDurationMs=wire.loop_duration_ms),typeof wire.cache_key=="string"&&wire.cache_key.length>0&&(tier.cacheKey=wire.cache_key),/* @__PURE__ */Object.freeze(tier)}function mapPetStateResponse(wire){let tiers={};wire.tiers.animation&&(tiers.animation=mapTier(wire.tiers.animation)),wire.tiers.image&&(tiers.image=mapTier(wire.tiers.image));let overlays={};wire.overlays.weather_alert&&(overlays.weatherAlert=mapTier(wire.overlays.weather_alert));let response={category:wire.category,tiers:/* @__PURE__ */Object.freeze(tiers),overlays:/* @__PURE__ */Object.freeze(overlays),idle:"bundled",ttlSeconds:wire.ttl_seconds,degraded:wire.degraded};return typeof wire.cache_epoch=="number"&&(response.cacheEpoch=wire.cache_epoch),/* @__PURE__ */Object.freeze(response)}var mediaKindWireSchema=/* @__PURE__ */zod.z.enum(["webp","video"]),categoryWireSchema=/* @__PURE__ */zod.z.enum(["health","attention","moment","activity","mood","idle"]),petStateTierWireSchema=/* @__PURE__ */zod.z.object({url:/* @__PURE__ */zod.z.string(),kind:/* @__PURE__ */mediaKindWireSchema.default("webp"),loop_duration_ms:/* @__PURE__ */zod.z.number().nullish(),expires_at:/* @__PURE__ */zod.z.string(),cache_key:/* @__PURE__ */zod.z.string().nullish()}),petStateResponseWireSchema=/* @__PURE__ */zod.z.object({category:categoryWireSchema,tiers:/* @__PURE__ */zod.z.object({animation:/* @__PURE__ */petStateTierWireSchema.optional(),image:/* @__PURE__ */petStateTierWireSchema.optional()}).default({}),overlays:/* @__PURE__ */zod.z.object({weather_alert:/* @__PURE__ */petStateTierWireSchema.optional()}).default({}),idle:/* @__PURE__ */zod.z.literal("bundled").default("bundled"),ttl_seconds:/* @__PURE__ */zod.z.number(),degraded:/* @__PURE__ */zod.z.boolean().default(false),cache_epoch:/* @__PURE__ */zod.z.number().default(0)});function parsePetStateWire(raw){let parsed=petStateResponseWireSchema.safeParse(raw);return parsed.success?parsed.data:null}function createPetStateRepository(auth){return createPetStateRepositoryOver(createRequestFunnel({auth:auth}))}function createPetStateRepositoryOver(funnel){return{async getState(petRef,opts){if(hasLoneSurrogate(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let path=`/widget/v1/pets/${encodeURIComponent(petRef)}/state`,res=await funnel.send("animations.getState",opts?.signal?{method:"GET",path:path,signal:opts.signal}:{method:"GET",path:path},opts?.maxAttempts!==void 0?{maxAttempts:opts.maxAttempts}:void 0);if(res.ok){let wire=parsePetStateWire(res.value);return wire===null?err(makeEverfurError("internalError",{retryable:true})):ok(mapPetStateResponse(wire))}return res.error.httpStatus===404?ok(null):err(res.error)}}}var LOADING=/* @__PURE__ */Object.freeze({status:"loading"}),NONE=/* @__PURE__ */Object.freeze({status:"none"}),RETRY_MS=3e4,RECORDS_PET_ART_RETRIES_MS=/* @__PURE__ */Object.freeze([2e3,6e3]),NO_FAILURES=/* @__PURE__ */Object.freeze({animation:false,image:false});function recordsPetArtOf(read,failed,reducedMotion){if(read.kind==="pending")return LOADING;if(read.kind==="failed"||read.value===null)return NONE;let{animation:animation,image:image}=read.value.tiers;return animation!==void 0&&animation.kind==="webp"&&!reducedMotion&&!failed.animation?{status:"art",url:animation.url,key:animation.cacheKey??animation.url,animated:true}:image!==void 0&&image.kind==="webp"&&!failed.image?{status:"art",url:image.url,key:image.cacheKey??image.url,animated:false}:NONE}function useRecordsPetArt(petRef,opts){let context=react.useContext(EverfurContext),runtime=context?.runtime??null,userRef=context?.userRef??null,scope=runtime!==null&&userRef!==null&&petRef!==null?`${userRef}|${petRef}`:null,[read,setRead]=react.useState({scope:scope,read:{kind:"pending"}}),[failed,setFailed]=react.useState({scope:scope,failed:NO_FAILURES}),[due,setDue]=react.useState({scope:scope,at:0}),current=read.scope===scope?read.read:{kind:"pending"},done=current.kind==="answer"&¤t.value===null,attempts=react.useRef({scope:scope,n:0});react.useEffect(()=>{if(scope===null||runtime===null||userRef===null||petRef===null||!opts.isFocused||done)return;let at=due.scope===scope?due.at:0,live=true,controller=typeof AbortController=="function"?new AbortController:null,run=()=>{createPetStateRepository(runtime.registry.services.authFor(userRef)).getState(petRef,controller?{signal:controller.signal,maxAttempts:1}:{maxAttempts:1}).then(result=>{if(!live)return;if(result.ok){attempts.current={scope:scope,n:0};let value=result.value;setRead(prev=>value!==null&&value.degraded&&prev.scope===scope&&prev.read.kind==="answer"&&prev.read.value!==null?prev:{scope:scope,read:{kind:"answer",value:value}}),value!==null&&(value.degraded||setFailed({scope:scope,failed:NO_FAILURES}),setDue({scope:scope,at:Date.now()+Math.max(30,value.ttlSeconds)*1e3}));return}if(result.error.httpStatus===403){setRead({scope:scope,read:{kind:"answer",value:null}});return}let n2=attempts.current.scope===scope?attempts.current.n:0,quick=RECORDS_PET_ART_RETRIES_MS[n2];attempts.current={scope:scope,n:n2+1},setRead(prev=>prev.scope===scope&&prev.read.kind==="answer"?prev:quick!==void 0?{scope:scope,read:{kind:"pending"}}:{scope:scope,read:{kind:"failed"}}),setDue({scope:scope,at:Date.now()+(quick??RETRY_MS)})})},wait=Math.max(0,at-Date.now()),timer=wait===0?null:setTimeout(run,wait);return timer===null&&run(),()=>{live=false,timer!==null&&clearTimeout(timer),controller?.abort()}},[scope,runtime,userRef,petRef,opts.isFocused,done,due]);let failedNow=failed.scope===scope?failed.failed:NO_FAILURES,art=react.useMemo(()=>scope===null?NONE:recordsPetArtOf(current,failedNow,opts.reducedMotion),[scope,current,failedNow,opts.reducedMotion]),onError=react.useCallback(()=>{art.status==="art"&&setFailed(prev=>{let base2=prev.scope===scope?prev.failed:NO_FAILURES;return{scope:scope,failed:art.animated?{...base2,animation:true}:{...base2,image:true}}})},[art,scope]);return react.useMemo(()=>({art:art,onError:onError}),[art,onError])}var HUB_COPY=/* @__PURE__ */Object.freeze({temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",vitalsLabel:pet=>`Vitals at ${pet}’s last exam`,vitalLabel:(name,value,unit)=>`${name}, ${value} ${unit}. More about it`,sayLine:"I wonder what I may be hiding",sayPhrases:["Hmmm","I wonder","what I may be","hiding"],upcomingCare:"Upcoming Care",viewAll:"View all →",dueSoon:"Due soon",later:"Later",nothingDue:pet=>`Nothing due for ${pet} right now.`,overdueBy:n2=>`Overdue by ${n2} ${n2===1?"day":"days"}`,dueToday:"Due today",dueIn:n2=>`Due in ${n2} ${n2===1?"day":"days"}`,noDueDate:"No due date on file",withDue:(relative,date2)=>`${relative} · due ${date2}`,dueOn:date2=>`Due ${date2}`,thisDay:(dated,weekday)=>`${dated} · this ${weekday}`,inWeeks:(dated,weeks)=>`${dated} · in ${weeks} ${weeks===1?"week":"weeks"}`,recordsHistory:"Records & History",labs:"Labs & bloodwork",labsA11y:(n2,noun)=>`Labs and bloodwork, ${n2} ${noun}`,labsA11yUnknown:"Labs and bloodwork",labsCountUnknown:"--",markers:n2=>n2===1?"marker":"markers",results:n2=>n2===1?"result":"results",screenings:"Screenings",screeningsA11y:pill=>`Screenings${pill!==null?`, ${pill}`:""}`,toReview:n2=>`${n2} to review`,allClear:"All clear",visits:"Visits & records",visitsA11y:date2=>`Visits and records${date2!==null?`, latest ${date2}`:""}`,timeline:"Timeline",events:n2=>`${n2} events`,timelineA11y:n2=>`Timeline${n2>0?`, ${n2} events`:""}`,weight:"Weight",estimatedRange:"Estimated Optimal Adult Range",noWeights:pet=>`No weights on file yet. They show up here from ${pet}’s vet visits.`,legendOver:["OVER","WEIGHT"],legendStable:["STABLE"],legendUnder:["UNDER","WEIGHT"],trendSummary:(n2,latest,trend,low,high)=>`${n2===1?"1 reading":`${n2} readings`}, latest ${latest}${n2===1?"":`, trend ${trend}`}.${low!==null&&high!==null?` Healthy range ${low} to ${high}.`:""}`,pointLabel:(when,value,unit)=>when!==null?`${when}, ${value} ${unit}`:`${value} ${unit}`,addRecords:pet=>`Add ${pet}’s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",onFileNow:"On file now",videoVisit:"Everfur video visit",pages:n2=>`${n2} ${n2===1?"page":"pages"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onTheWay:pet=>`${pet}’s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",requestSentTo:clinic=>clinic!==null?`Request sent to ${clinic}`:"Request sent",signedRelease:when=>`${when} · you signed the release`,waitingFor:whose=>`Waiting for ${whose} records`,inHealthTab:whose=>`In ${whose} Health tab`,everyPageRead:"Every page read: vaccines, labs, visits, meds",today:"Today",anotherClinic:"Another clinic",anotherClinicText:"Seen more than one vet? We ask each one.",uploadText:"A PDF, or a photo of a paper record.",requestTitle:pet=>`${pet}’s records request`,requestA11y:(pet,status)=>`Records request for ${pet}. ${status}`,sample:"Sample",peekLead:pet=>`A sneak peek at how ${pet}’s records will read. Every number links back to the page it came from.`,previousGroup:"Previous group",nextGroup:"Next group",markerGroups:"Marker groups",sampleNotTheirs:pet=>`This is a sample, not ${pet}’s result.`,sampleNote:" Add her records to see her own numbers. Anything outside the range gets flagged like this, with what it measures and what to ask her vet.",columns:["Test","Result","Unit","Range"],slideOf:(chip,n2,of)=>`${chip}, ${n2} of ${of}`,high:"High",legal:RECORDS_FOOTNOTE,noVetTitle:w=>`When ${w.name} has a vet, start here.`});function hubAge(totalMonths){let years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}m`:months>0?`${years}y ${months}m`:`${years}y`}var CHEM_P2={cap:"Read from the lab report, page 2",who:"Chemistry panel",page:"p. 2 of 12"},HUB_SAMPLE_GROUPS=/* @__PURE__ */Object.freeze([{key:"liver",chip:"Liver",lead:"What the liver makes and clears.",markers:[{name:"ALT",flag:"High",what:"An enzyme found mostly in liver cells.",at:92,value:"118",unit:"U/L"},{name:"ALP",what:"An enzyme from the liver and bones.",at:33,value:"64",unit:"U/L"},{name:"GGT",what:"An enzyme tied to the liver’s bile ducts.",at:36,value:"3",unit:"U/L"},{name:"Total bilirubin",what:"A yellow pigment the liver clears.",at:33,value:"0.2",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALB",result:"3.2",unit:"g/dL",range:"2.3-4.0"},{test:"ALP",result:"64",unit:"U/L",range:"23-212",lit:true},{test:"ALT",result:"118 H",unit:"U/L",range:"10-100",lit:true},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27"},{test:"GGT",result:"3",unit:"U/L",range:"0-11",lit:true},{test:"T. BILI",result:"0.2",unit:"mg/dL",range:"0.0-0.9",lit:true}]}},{key:"kidney",chip:"Kidney",lead:"What the kidneys filter out and keep in balance.",markers:[{name:"BUN",what:"Protein waste the kidneys filter out.",at:53,value:"18",unit:"mg/dL"},{name:"Creatinine",what:"Muscle waste the kidneys filter out.",at:48,value:"1.1",unit:"mg/dL"},{name:"SDMA",what:"Another measure of kidney filtering.",at:59,value:"9",unit:"µg/dL"},{name:"Phosphorus",what:"A mineral the kidneys keep in balance.",at:42,value:"4.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALT",result:"45",unit:"U/L",range:"10-100"},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27",lit:true},{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0"},{test:"CREA",result:"1.1",unit:"mg/dL",range:"0.5-1.8",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8",lit:true},{test:"SDMA",result:"9",unit:"µg/dL",range:"0-14",lit:true}]}},{key:"blood",chip:"Blood cells",lead:"The cells that carry oxygen, fight infection and help blood clot.",markers:[{name:"Red blood cells",what:"Cells that carry oxygen around the body.",at:43,value:"6.9",unit:"M/µL"},{name:"Hemoglobin",what:"The part of red cells that holds oxygen.",at:42,value:"15.8",unit:"g/dL"},{name:"White blood cells",what:"Cells that fight infection.",at:44,value:"9.8",unit:"K/µL"},{name:"Platelets",what:"Cell fragments that help blood clot.",at:41,value:"265",unit:"K/µL"}],from:{cap:"Read from the lab report, page 3",who:"Complete blood count",page:"p. 3 of 12",rows:[{test:"HCT",result:"46",unit:"%",range:"37.3-61.7"},{test:"HGB",result:"15.8",unit:"g/dL",range:"13.1-20.5",lit:true},{test:"NEUT",result:"6.1",unit:"K/µL",range:"2.95-11.64"},{test:"PLT",result:"265",unit:"K/µL",range:"148-484",lit:true},{test:"RBC",result:"6.9",unit:"M/µL",range:"5.65-8.87",lit:true},{test:"WBC",result:"9.8",unit:"K/µL",range:"5.05-16.76",lit:true}]}},{key:"sugar",chip:"Sugar and salts",lead:"Fuel, and the salts that keep fluids, nerves and muscles steady.",markers:[{name:"Glucose",what:"Blood sugar, the body’s main fuel.",at:41,value:"96",unit:"mg/dL"},{name:"Sodium",what:"A salt that keeps fluids in balance.",at:31,value:"147",unit:"mmol/L"},{name:"Potassium",what:"A salt that helps nerves and muscles work.",at:49,value:"4.6",unit:"mmol/L"},{name:"Calcium",what:"A mineral for bones, muscles and nerves.",at:52,value:"10.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0",lit:true},{test:"CL",result:"112",unit:"mmol/L",range:"109-122"},{test:"GLU",result:"96",unit:"mg/dL",range:"70-143",lit:true},{test:"K",result:"4.6",unit:"mmol/L",range:"3.5-5.8",lit:true},{test:"NA",result:"147",unit:"mmol/L",range:"144-160",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8"}]}}]),HUB_SAMPLE_MORE=/* @__PURE__ */Object.freeze([{key:"screenings",title:"Screenings",tint:"pink",lead:"Tests that look for common problems early, and what came back.",rows:[{title:"Heartworm test",pill:"Negative",tone:"clear"},{title:"Tick panel (4Dx)",pill:"Negative",tone:"clear"}]},{key:"visits",title:"Visits & records",tint:"blue",lead:"Every visit, with the vet’s notes and the pages they came from.",rows:[{title:"Wellness exam",text:"38 pages"},{title:"Everfur video visit",text:"3 pages"}]},{key:"timeline",title:"Timeline",tint:"yellow",lead:"Her whole history in order, with what’s due next.",rows:[{title:"Rabies vaccine",pill:"Due soon",tone:"soon"},{title:"Heartworm test",text:"Apr 18"}]}]);var APP_HUB_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",text:"#000000",bg:"#FFFFFF",white:"#FFFFFF",mist:"#F1F5F2",charcoal:"#3D3D3D",alert:"#C03410",alertDeep:"#6D1D14",pink:"#FFC3BC",yellow:"#F2C763",skyBlue:"#4E98C9",tintSage:"#E6ECE8",tintPink:"#FFEAE8",tintPinkSoft:"#FFF6F5",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintYellowEdge:"#F6D892",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoGrey:"#6B6B6B",icoSage:"#819E90",icoBlue:"#4E98C9",barTrack:"#ECECEC",pillPlainEdge:"rgba(16, 70, 46, 0.2)"}),APP_HUB_TYPE=/* @__PURE__ */Object.freeze({screenTitle:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"medium",color:"ink",letterSpacing:-.33}),cardTitle:/* @__PURE__ */Object.freeze({size:18,lineHeight:22.5,face:"bold",color:"ink",letterSpacing:-.36}),body:/* @__PURE__ */Object.freeze({size:17,lineHeight:26.35,face:"regular",color:"text",letterSpacing:0}),bodySm:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"regular",color:"text",letterSpacing:0}),bodySmBold:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"bold",color:"ink",letterSpacing:0}),fine:/* @__PURE__ */Object.freeze({size:13,lineHeight:18.2,face:"regular",color:"muted",letterSpacing:0}),labelMono:/* @__PURE__ */Object.freeze({size:12,lineHeight:16.8,face:"monoBold",color:"muted",letterSpacing:.72,upper:true}),pill:/* @__PURE__ */Object.freeze({size:12,lineHeight:14.4,face:"monoBold",color:"ink",letterSpacing:.72,upper:true}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:18,face:"bold",color:"ink",letterSpacing:0}),buttonRow:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"bold",color:"ink",letterSpacing:0}),chip:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"medium",color:"ink",letterSpacing:0}),hand:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"hand",color:"ink",letterSpacing:0})}),APP_HUB_LEGACY=/* @__PURE__ */Object.freeze({surface:"#FFFFFF",textPrimary:"#111111",textMuted:"#6E6660",border:"#C8BEB4",brand:"#10462E",brandSoft:"rgba(16, 70, 46, 0.1)",danger:"#B91C1C"}),APP_HUB_TIMELINE=/* @__PURE__ */Object.freeze({dot:24,check:12,core:10,ring:2,rowGap:12,bodyBottom:18,bodyGap:2,titleGap:8,rail:2,railMin:22,railGap:2,titleSize:14,titleLineHeight:18,dateSize:12,dateLineHeight:16,detailSize:13,detailLineHeight:17,upcomingOpacity:.7});var APP_HUB=/* @__PURE__ */Object.freeze({screen:{gap:12,padX:16,padBottom:24,legalTop:20},hero:{nameSize:22,nameLineHeight:26,nameTracking:-.44,metaTop:2,metaLineHeight:18,metaTracking:.26,stageHeight:280,stageTop:4,grassFraction:.46,petBottom:40,petBoxHeight:224,petTop:16,sayWidth:230,sayHeight:61,sayFontSize:22,sayArcPath:"M 12 60 Q 120 -4 228 60",sayViewBox:[240,64],vitalsTop:8,vitalsLeft:8,vitalMinHeight:40,vitalPadX:8,vitalGap:6,vitalIcon:22,vitalValueSize:17,vitalUnitSize:13,lawnOverlap:26,lawnRadius:28},card:{pad:16,radius:20,border:1,headGap:8,headBottom:12},button:{md:52,sm:46,row:36,padMd:24,padSm:16,padRow:14,iconMd:22,iconSm:20,iconRow:17,edge:1.5,gap:8,mdLabel:17,textGap:6,textMinHeight:24},pill:{minHeight:24,padX:10,edgeThin:1.25,edgeThick:1.5},upcoming:{listGap:4,bleed:8,rowPadY:10,rowPadX:8,rowGap:12,rowRadius:10,icon:20,maxRows:4},tiles:{top:8,titleBottom:12,gap:12,pad:16,radius:20,innerGap:8,icon:22,chevron:20,titleLineHeight:19,footMinHeight:28,numSize:20,numLineHeight:22,numTracking:-.4,countGap:8},weight:{headGap:4,headBottom:16,numSize:32,numLineHeight:34,numTracking:-.64,numGap:8},chart:{height:176,plotTop:24,axisBand:20,rightInset:14,indicatorWidth:8,plotLeft:62,dataLeft:76,dot:6,dotRing:1.5,lineWidth:2,labelGap:7,labelMax:12,labelMin:9,labelCharWidth:.62,edgePad:4,legendX:14,legendLine:14.4,legendSize:12,legendTracking:.24,monthY:172,monthSize:12,maxTicks:5,maxValues:8,bandFrom:.3,bandTo:.7,reach:.88,bandPct:.1,lineColor:"#111111",gridColor:"#EAEAEA",bandColor:"#D8F3E3"},add:{gap:12,headGap:8,icon:26,sourcesGap:6,sourcesTop:4,sourcePadY:10,sourcePadX:14,sourceRadius:10,sourceColumnGap:12,actsGap:12,actsTop:4},peek:{top:12,headGap:12,leadTop:8,labsTop:16,chipsTop:10,chipsGap:8,slideTop:16,slideGap:4,slideLeadTop:2,slideLeadBottom:8,markerPad:12,markerGap:8,markerRadius:10,markerTopGap:12,barHeight:8,barDot:12,barDotRing:2,valueGap:4,fromMinHeight:40,fromGap:6,fromIcon:16,fromChevron:18,moreGap:12,moreTop:16,morePad:16,moreInnerGap:12,moreRadius:20,moreIcon:22,moreHeadGap:8,rowsGap:6,rowMinHeight:44,rowPadY:8,rowPadX:14,rowRadius:10,roundButton:36,chipHeight:36,chipPadX:14},onTheWay:{dot:28,titleSize:22,titleLineHeight:25,titleTracking:-.44,wayIcon:26,wayPad:16,wayRadius:20},inProgress:{radius:18,pad:18,gap:16,titleSize:16,titleLineHeight:20,statusRadius:14,statusPad:14,statusSize:13,statusLineHeight:19}});var HIDDEN3={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},frame=size=>({width:size,height:size});function bar2(x1,y1,x2,y2,w,color){let len=Math.hypot(x2-x1,y2-y1)+w;return{position:"absolute",left:(x1+x2)/2-len/2,top:(y1+y2)/2-w/2,width:len,height:w,borderRadius:w/2,backgroundColor:color,transform:[{rotate:`${Math.atan2(y2-y1,x2-x1)}rad`}]}}function DownloadGlyph2({size:size,color:color}){let u=size/24.7029,w=2.05857*u;/* @__PURE__ */
|
|
759
|
+
return Object.freeze(out)}var NO_SNAPSHOT=/* @__PURE__ */Object.freeze({branding:null}),NO_STORE=/* @__PURE__ */Object.freeze({subscribe:()=>()=>{},getSnapshot:()=>NO_SNAPSHOT});function keyOf(input){return input?Object.keys(input).sort().map(k=>`${k}=${String(input[k])}`).join("&"):""}function useEverfurPresentation(client){return useEverfurPresentationState(client).presentation}function useEverfurPresentationState(client){let{runtime:runtime}=useEverfurContext(),store=runtime?.entitlements??NO_STORE,readBranding=react.useCallback(()=>store.getSnapshot()?.branding??null,[store]),branding=react.useSyncExternalStore(store.subscribe,readBranding,readBranding),clientKey=keyOf(client);return react.useMemo(()=>{let locked=branding?.lockedFields??null;return{presentation:resolvePresentation({server:branding?.presentation??null,locked:locked,client:client??null}),isLocked:field=>isPresentationFieldLocked(field,locked)}},[branding,clientKey])}var COARSE_NOW_TICK_MS=3600*1e3;function useCoarseNow(fixed,shown=true){let[now,setNow]=react.useState(()=>fixed??Date.now()),first=react.useRef(true);return react.useEffect(()=>{if(first.current){first.current=false;return}fixed===void 0&&shown&&setNow(Date.now())},[fixed,shown]),react.useEffect(()=>{if(fixed!==void 0||!shown)return;let tick=setInterval(()=>setNow(Date.now()),COARSE_NOW_TICK_MS),onVisible=()=>{document.visibilityState==="visible"&&setNow(Date.now())},doc=typeof document<"u"&&typeof document.addEventListener=="function"?document:null;return doc?.addEventListener("visibilitychange",onVisible),()=>{clearInterval(tick),doc?.removeEventListener("visibilitychange",onVisible)}},[fixed,shown]),fixed??now}var capital=text4=>text4.charAt(0).toUpperCase()+text4.slice(1);function sheetPetWords(name,pronoun){let trimmed=name.trim(),shown=trimmed.length>0?trimmed:NAMELESS_PET,Name=capital(shown);return pronoun==="her"?{name:shown,Name:Name,poss:"her",Poss:"Her",subj:"she"}:pronoun==="his"?{name:shown,Name:Name,poss:"his",Poss:"His",subj:"he"}:{name:shown,Name:Name,poss:`${shown}'s`,Poss:`${Name}'s`,subj:shown}}var SHEET_COPY=/* @__PURE__ */Object.freeze({vitalsFrom:(w,visit,date2)=>`Vitals from ${w.poss} ${visit}, ${date2}`,vitalsSource:w=>`Where ${w.name}'s vitals come from`,temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",upcomingCare:"Upcoming care",overdueBy:date2=>`Overdue · due by ${date2}`,dueSoon:"Due soon",later:"Later",noDate:"No date",dueIn:(date2,days)=>`Due ${date2} · in ${days} ${days===1?"day":"days"}`,dueToday:date2=>`Due ${date2} · today`,overdueByDays:(date2,days)=>`Overdue by ${days} ${days===1?"day":"days"} · due ${date2}`,recordsHistory:"Records & history",labs:"Labs & bloodwork",results:"results",screenings:"Screenings",screeningsClear:"All clear",screeningsToReview:n2=>`${n2} to review`,noScreenings:"No screenings yet",visits:"Visits & records",timeline:"Timeline",events:n2=>`${n2} ${n2===1?"event":"events"}`,weight:"Weight",vetVisits:n2=>`${n2} vet ${n2===1?"visit":"visits"}`,history:"History",theirClinic:w=>`${w.Poss} clinic`,bloodPanel:"Blood panel",aboveRange:"above range",belowRange:"below range",othersInRange:"Other values in range.",addRecords:w=>`Add ${w.name}'s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",visitsCount:n2=>`${n2} ${n2===1?"visit":"visits"}`,panelsCount:n2=>`${n2} blood ${n2===1?"panel":"panels"}`,requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onFileNow:"On file now",firstRecord:w=>`Add ${w.name}'s first record`,firstLead:w=>`Records can come from more than one clinic over a lifetime. Start with the one ${w.subj} sees most, and this page fills in from there.`,requestFromTheirClinic:w=>`Request from ${w.poss} clinic`,requestDetail:"We send a secure request and read every page they send back.",uploadDetail:"A PDF, or a photo of a paper record.",findClinic:w=>`Find ${w.name}'s clinic`,chooseFile:"Choose a file",sayBeats:/* @__PURE__ */Object.freeze(["Hmmm","I wonder","what I may be","hiding"]),sayStill:"I wonder what I may be hiding",sample:"Sample",peekLead:w=>`A sneak peek at how ${w.name}'s records will read. Every number links back to the page it came from.`,sampleNote:w=>`Sample data until ${w.poss} records arrive.`,onTheWay:w=>`${w.Name}'s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",anotherClinic:"Another clinic",anotherClinicDetail:"Seen more than one vet? We ask each one.",noDueDate:"No due date on file",noLabs:w=>`No lab results on file for ${w.name} yet. They show up here when a record includes a blood or urine panel.`,noVisits:w=>`No visits in ${w.name}'s records yet. They show up here when a record includes one.`,oneReading:"One reading so far: we'll plot a trend as more come in.",takingNow:"Taking now",noCurrentMeds:"No current medications on file.",noVetTitle:w=>`When ${w.name} has a vet, start here.`,requestedFrom:clinic=>`Requested from ${clinic}. Clinics usually take 2 to 5 days.`,onTheWayFrom:(w,clinic)=>`${w.Name}'s records from ${clinic} are on the way.`,readingUpload:"We're reading the document you uploaded.",seeWhereItStands:"See where it stands",topRisk:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,panelOn:date2=>`${date2} blood panel`,latestReading:"Latest reading",rangeLine:(low,high,unit)=>`range ${low} to ${high}${unit?` ${unit}`:""}`,noRange:"No range on the report",above:"Above",inRange:"In range",below:"Below",high:"High",belowRangePill:"Below range",changeUp:(delta,unit)=>`Up ${delta}${unit?` ${unit}`:""}`,changeDown:(delta,unit)=>`Down ${delta}${unit?` ${unit}`:""}`,changeSince:(date2,pct3)=>` since ${date2}, about ${pct3}%.`,whatIs:name=>`What ${name} is`,otherValues:panel=>`Other ${panel} values`,panelTitle:(panel,date2)=>`${panel} · ${date2}`,askAboutThis:"Ask about this"});var DAY_MS=864e5,DUE_SOON_DAYS=30,LB_PER_KG=2.20462,MONTHS2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function dayMs(value){if(value==null||value.length===0)return null;let ms2=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(value)?`${value}T00:00:00Z`:value);return Number.isNaN(ms2)?null:ms2}function shortDate(ms2){let d=new Date(ms2);return`${MONTHS2[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function longDate(ms2){return`${shortDate(ms2)}, ${new Date(ms2).getUTCFullYear()}`}function monthTick(ms2){let d=new Date(ms2);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}var dayKey=ms2=>new Date(ms2).toISOString().slice(0,10);function num4(value){return String(Math.round(value*100)/100)}var lb=kg=>Math.round(kg*LB_PER_KG*10)/10;function midSentence(text4){let t=text4.trim();return t.length<2||t[1]===t[1]?.toUpperCase()?t:t.charAt(0).toLowerCase()+t.slice(1)}function vitalKind(text4){return/temp/i.test(text4)?"temp":/heart|pulse/i.test(text4)?"heart":/resp|breath/i.test(text4)?"breath":null}var VITAL_ORDER=["temp","heart","breath"],VITAL_LABEL={temp:SHEET_COPY.temperature,heart:SHEET_COPY.heartRate,breath:SHEET_COPY.breathing};function sheetVitals(record){if(record===null||record.withheld)return{vitals:[],observedMs:null};let best=/* @__PURE__ */new Map;for(let e of record.entities){if(e.category!=="vital"||e.value===null||e.value.trim().length===0)continue;let kind=vitalKind(`${e.canonicalKey??""} ${e.key} ${e.label}`);if(kind===null)continue;let ms2=dayMs(e.observedAt)??0,prev=best.get(kind);(prev===void 0||ms2>prev.ms)&&best.set(kind,{value:e.value.trim(),unit:e.unit,ms:ms2})}let vitals=VITAL_ORDER.flatMap(kind=>{let v=best.get(kind);return v===void 0?[]:[{kind:kind,value:v.value,unit:v.unit,label:VITAL_LABEL[kind]}]}),observed=[...best.values()].map(v=>v.ms).filter(ms2=>ms2>0);return{vitals:vitals,observedMs:observed.length>0?Math.max(...observed):null}}function encounterOn(encounters,ms2){let key=dayKey(ms2);return encounters.find(e=>{let at=dayMs(e.date);return at!==null&&dayKey(at)===key})??null}function dueIcon(title){return/vaccin|rabies|dhpp|booster|bordetella|lepto|lyme|parvo|distemper/i.test(title)?"efi-shield":/\b(alt|alp|lab|labs|blood|panel|bloodwork|urinalysis|chemistry|cbc)\b/i.test(title)?"efi-flask-sm":"efi-calendar"}function sheetDue(items,nowMs){return items.map(item=>{let due=dayMs(item.dueAt),icon=dueIcon(item.title);if(due!==null&&due<nowMs-DAY_MS+1)return{item:item,title:item.title,when:SHEET_COPY.overdueBy(shortDate(due)),tone:"alert",pill:null,icon:icon};let when=item.detail??(due===null?SHEET_COPY.noDueDate:longDate(due));if(due===null)return{item:item,title:item.title,when:when,tone:"none",pill:null,icon:icon};let soon=due-nowMs<=DUE_SOON_DAYS*DAY_MS;return{item:item,title:item.title,when:when,tone:soon?"watch":"later",pill:soon?SHEET_COPY.dueSoon:SHEET_COPY.later,icon:icon}})}function pointFlag(status){return status==null?null:/above|high/i.test(status)?"above":/below|low/i.test(status)?"below":/in_range|normal|in range/i.test(status)?"in":null}var kgShown=kg=>Math.round(kg*10)/10;function weightText(kg,unit){let pounds=`${num4(lb(kg))} lb`,kilos=`${num4(kgShown(kg))} kg`;return unit==="kg"?{main:kilos,other:pounds}:{main:pounds,other:kilos}}function weightModel(timeline,unit){if(timeline===null||timeline.withheld)return null;let readings=timeline.weights.flatMap(w=>{let ms2=dayMs(w.observedOn);return ms2===null||w.weightKg===null?[]:[{ms:ms2,kg:w.weightKg}]}).sort((a,b)=>a.ms-b.ms),last=readings[readings.length-1];if(last===void 0)return null;let lbs=readings.map(r=>lb(r.kg)),lo=Math.min(...lbs),hi=Math.max(...lbs),t0=readings[0]?.ms??last.ms,span=last.ms-t0,points=readings.map((r,i)=>({x:span>0?Math.round((3.55+93.45*(r.ms-t0)/span)*100)/100:50,y:hi>lo?Math.round((75-50*((lbs[i]??lo)-lo)/(hi-lo))*10)/10:50,lb:lbs[i]??0,value:unit==="kg"?kgShown(r.kg):lbs[i]??0,ms:r.ms})),tickPoints=points.length<=4?points:[points[0],points[points.length-1]].filter(p=>p!==void 0),text4=weightText(last.kg,unit);return{latest:text4.main,sub:`${text4.other} · ${shortDate(last.ms)}`,single:points.length===1,points:points,ticks:tickPoints.map(p=>({x:p.x,label:monthTick(p.ms)})),vetCount:points.length}}function labDays(markers){let days=/* @__PURE__ */new Map;if(markers===null||markers.withheld)return days;for(let marker of markers.markers)for(let point of marker.points){let ms2=dayMs(point.at);if(ms2===null)continue;let key=dayKey(ms2),day=days.get(key)??{ms:ms2,flagged:[],total:0,inRange:0,clinics:/* @__PURE__ */new Set};day.total+=1;let flag=pointFlag(point.status);flag==="in"&&(day.inRange+=1),(flag==="above"||flag==="below")&&day.flagged.push({marker:marker,point:point,ms:ms2,flag:flag}),point.sourceClinic&&day.clinics.add(point.sourceClinic),days.set(key,day)}return days}function historyModel(inputs,days){let items=[];for(let[key,day]of days)day.flagged.forEach((f,i)=>{let value=f.point.value===null?f.point.qualitativeResult??"":num4(f.point.value),unit=f.point.unit??f.marker.unit,others=day.flagged.length===1&&day.inRange===day.total-1&&day.total>1;items.push({key:`lab-${key}-${f.marker.markerId}-${i}`,ms:day.ms,date:`${shortDate(day.ms)} · ${SHEET_COPY.bloodPanel}`,title:`${f.marker.name} ${value}${unit?` ${unit}`:""}, ${f.flag==="above"?SHEET_COPY.aboveRange:SHEET_COPY.belowRange}`,text:others?SHEET_COPY.othersInRange:null,alert:true,markerId:f.marker.markerId,order:0})});let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],visits=inputs.timeline?.withheld===false?inputs.timeline.visits:[],usedVisits=/* @__PURE__ */new Set;encounters.forEach((e,i)=>{let ms2=dayMs(e.date);if(ms2===null)return;let visit=visits.find(v=>e.docId!==null&&v.docId===e.docId||dayMs(v.visitDate)!==null&&dayKey(dayMs(v.visitDate)??0)===dayKey(ms2))??null;visit!==null&&usedVisits.add(visit.visitId);let summary=visit?.summary?.trim()||null,type=e.type?.trim()||null,title=summary??type;title!==null&&items.push({key:`enc-${e.encounterId}-${i}`,ms:ms2,date:summary!==null&&type!==null?`${shortDate(ms2)} · ${type}`:shortDate(ms2),title:title,text:null,alert:false,markerId:null,order:1})});for(let v of visits){let ms2=dayMs(v.visitDate),summary=v.summary?.trim()||null;usedVisits.has(v.visitId)||ms2===null||summary===null||items.push({key:`visit-${v.visitId}`,ms:ms2,date:shortDate(ms2),title:summary,text:null,alert:false,markerId:null,order:1})}items.sort((a,b)=>b.ms-a.ms||a.order-b.order);let years=[];for(let entry of items){let item={key:entry.key,ms:entry.ms,date:entry.date,title:entry.title,text:entry.text,alert:entry.alert,markerId:entry.markerId},year=String(new Date(item.ms).getUTCFullYear()),last=years[years.length-1];last!==void 0&&last.year===year?last.items.push(item):years.push({year:year,items:[item]})}return{years:years,count:items.length}}function sourcesModel(inputs,days){let encounters=inputs.depth?.withheld===false?inputs.depth.encounters:[],clinicLabel=name=>name?.trim()||SHEET_COPY.theirClinic(inputs.words),visits=/* @__PURE__ */new Map;for(let e of encounters)visits.set(clinicLabel(e.clinicName),(visits.get(clinicLabel(e.clinicName))??0)+1);let panels=/* @__PURE__ */new Map,onlyClinic=visits.size===1?[...visits.keys()][0]:void 0;for(let day of days.values()){let names=day.clinics.size>0?[...day.clinics].map(clinicLabel):[onlyClinic??SHEET_COPY.theirClinic(inputs.words)];for(let n2 of names)panels.set(n2,(panels.get(n2)??0)+1)}return[.../* @__PURE__ */new Set([...visits.keys(),...panels.keys()])].map(label2=>({label:label2,detail:[(visits.get(label2)??0)>0?SHEET_COPY.visitsCount(visits.get(label2)??0):null,(panels.get(label2)??0)>0?SHEET_COPY.panelsCount(panels.get(label2)??0):null].filter(p=>p!==null).join(" · ")}))}var PULL_PCT={requested:15,awaiting_clinic:35,awaiting_upload:35,received:60,parsing:75,in_review:90};function sheetPull(requests){let open=requests.filter(r=>!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(open===void 0)return null;let step=(open.waitingExpectation?.trim()||open.statusLabel).trim();return step.length===0?null:{step:step,pct:PULL_PCT[open.status]??15}}var newestFirst=requests=>[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0)),sentence=label2=>/[.!?]$/.test(label2)?label2:`${label2}.`;function sheetOnTheWay(words2,requests){let active=newestFirst(requests).filter(r=>!isTerminalStatus(r.status)),waiting=active.filter(r=>r.status==="awaiting_upload"),moving=active.filter(r=>r.status!=="awaiting_upload"),lines=[],clinics=/* @__PURE__ */new Map;for(let r of moving){let clinic=r.clinicName?.trim()??"";r.source!=="clinic_request"||clinic===""||clinics.has(clinic)||clinics.set(clinic,r)}for(let[clinic,newest]of clinics)lines.push({key:`clinic-${clinic}`,text:SHEET_COPY.onTheWayFrom(words2,clinic),requestId:newest.id});let upload=moving.find(r=>r.source==="owner_provided");upload!==void 0&&lines.push({key:"upload",text:SHEET_COPY.readingUpload,requestId:upload.id});let wait=waiting[0],label2=wait?.statusLabel.trim()??"";return wait!==void 0&&label2!==""&&lines.push({key:"awaiting-upload",text:sentence(label2),requestId:wait.id}),lines}function sheetRequestedClinic(requests){return newestFirst(requests).find(r=>!isTerminalStatus(r.status)&&r.status!=="awaiting_upload"&&r.source==="clinic_request"&&(r.clinicName?.trim()??"")!=="")?.clinicName?.trim()??null}function sheetMedications(timeline){if(timeline===null||timeline.withheld)return null;let named=timeline.medications.filter(m=>(m.drugName?.trim()??"")!=="");return named.length===0?null:{current:named.filter(m=>(m.stoppedOn?.trim()??"")==="").map(m=>{let parts=[m.dose,m.frequency,m.route].map(p=>p?.trim()??"").filter(p=>p!==""),detail=m.sig?.trim()||(parts.length>0?parts.join(" · "):null);return{key:m.medicationId,name:(m.drugName??"").trim(),detail:detail}})}}function sheetFailedRequest(requests){if(requests.some(r=>!isTerminalStatus(r.status)))return null;let newest=[...requests].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(newest===void 0||newest.status!=="failed")return null;let words2=newest.statusLabel.trim();return words2.length>0?words2:null}function sheetHasRecord(record,markers,depth){return record!==null&&!record.withheld&&!record.isEmpty||markers!==null&&!markers.withheld&&markers.markers.length>0?true:depth!==null&&!depth.withheld&&depth.encounters.length>0}function sheetAge(ageYears){if(typeof ageYears!="number"||!Number.isFinite(ageYears)||ageYears<=0)return null;let totalMonths=Math.floor(ageYears*12+1e-9),years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}M`:months>0?`${years}Y ${months}M`:`${years}Y`}function buildRecordsSheetModel(inputs){let{record:record,depth:depth,markers:markers,nowMs:nowMs}=inputs,has=sheetHasRecord(record,markers,depth),pull=sheetPull(inputs.requests),days=labDays(markers),{vitals:vitals,observedMs:observedMs}=sheetVitals(record),encounters=depth?.withheld===false?depth.encounters:[],visitAt=observedMs===null?null:encounterOn(encounters,observedMs),vitalsFrom=observedMs!==null&&visitAt?.type?SHEET_COPY.vitalsFrom(inputs.words,midSentence(visitAt.type),shortDate(observedMs)):null,unit=inputs.weightUnit??"lb",weight=weightModel(inputs.timeline,unit),latestKg=weight!==null?null:inputs.petWeightKg,meta=[inputs.breed?.trim()||null,sheetAge(inputs.petAgeYears),weight?.latest??(latestKg!==null?weightText(latestKg,unit).main:null)].filter(p=>p!==null),timelineVisits=inputs.timeline?.withheld===false?inputs.timeline.visits.length:0,history=historyModel(inputs,days),encounterDays=encounters.map(e=>dayMs(e.date)).filter(ms2=>ms2!==null),markerList=markers?.withheld===false?markers.markers:[],featured=markers?.featuredMarkerId??markerList.find(m=>pointFlag(m.latest?.status)==="above"||pointFlag(m.latest?.status)==="below")?.markerId??markerList[0]?.markerId??null;return{state:has?"full":pull!==null?"onTheWay":"none",meta:meta.length>0?meta.join(" · "):null,vitals:vitals,vitalsFrom:vitalsFrom,due:record!==null&&!record.withheld?sheetDue(record.forwardLooking,nowMs):[],labsCount:markers?.withheld===false?markers.summary?.totalMarkers??markers.markers.length:0,featuredMarkerId:featured,latestVisit:encounterDays.length>0?longDate(Math.max(...encounterDays)):null,weight:weight,history:history.years,historyCount:history.count,sources:sourcesModel(inputs,days),pull:pull,hasVisits:encounters.length>0||timelineVisits>0,medications:sheetMedications(inputs.timeline),failedRequest:pull===null?sheetFailedRequest(inputs.requests):null,inFlight:sheetOnTheWay(inputs.words,inputs.requests),requestedClinic:sheetRequestedClinic(inputs.requests)}}function lastPoint(marker){let dated=marker.points.filter(p=>p.value!==null);return dated[dated.length-1]??marker.points[marker.points.length-1]??null}function rangeOf(point){return point===null||point.refLow===null||point.refHigh===null||!Number.isFinite(point.refLow)||!Number.isFinite(point.refHigh)||point.refHigh<=point.refLow?null:{low:point.refLow,high:point.refHigh}}function markerRow(marker,point=lastPoint(marker)){let range=rangeOf(point),unit=point?.unit??marker.unit,value=point?.value??null;return{markerId:marker.markerId,name:marker.name,value:value===null?point?.qualitativeResult??"":num4(value),unit:unit,range:range===null?null:`${num4(range.low)} to ${num4(range.high)}${unit?` ${unit}`:""}`,at:range===null||value===null?null:Math.round(Math.min(100,Math.max(0,20+60*(value-range.low)/(range.high-range.low)))),flag:pointFlag(point?.status??marker.latest?.status??null)}}function flagPill(flag){return flag==="above"?SHEET_COPY.high:flag==="below"?SHEET_COPY.belowRangePill:flag==="in"?SHEET_COPY.inRange:null}var panelWord=panel=>{let name=panel.replace(/\s+panel$/i,"").trim()||panel;return name.length>1&&name[1]===name[1]?.toUpperCase()?name:name.charAt(0).toLowerCase()+name.slice(1)};function buildSheetLabModel(markers,markerId){let marker=markers.markers.find(m=>m.markerId===markerId);if(marker===void 0)return null;let last=lastPoint(marker),row=markerRow(marker,last),lastMs=dayMs(last?.at??marker.latest?.at??null),range=rangeOf(last),latestSub=[lastMs===null?null:shortDate(lastMs),range===null?SHEET_COPY.noRange:SHEET_COPY.rangeLine(num4(range.low),num4(range.high),row.unit)].filter(p=>p!==null).join(" · "),numeric2=marker.points.flatMap(p=>{let ms2=dayMs(p.at);return p.value===null||ms2===null?[]:[{p:p,ms:ms2,v:p.value}]}),chart=[];if(numeric2.length>0){let values=numeric2.map(n2=>n2.v),lo=range?.low??Math.min(...values),hi=range?.high??Math.max(...values);chart=numeric2.map((n2,i)=>({x:numeric2.length===1?50:Math.round((18+64*i/(numeric2.length-1))*100)/100,y:hi>lo?Math.min(98,Math.max(2,Math.round((75-50*(n2.v-lo)/(hi-lo))*10)/10)):50,label:num4(n2.v),out:pointFlag(n2.p.status)==="above"||pointFlag(n2.p.status)==="below",tick:shortDate(n2.ms)}))}let first=numeric2[0],final=numeric2[numeric2.length-1],change=null;if(first!==void 0&&final!==void 0&&numeric2.length>=2&&final.v!==first.v){let delta=Math.abs(final.v-first.v),pct3=first.v!==0?Math.round(delta/Math.abs(first.v)*100):null,lead2=final.v>first.v?SHEET_COPY.changeUp(num4(delta),row.unit):SHEET_COPY.changeDown(num4(delta),row.unit);change=pct3===null?null:{lead:lead2,rest:SHEET_COPY.changeSince(shortDate(first.ms),pct3)}}let groups=[],lastKey=lastMs===null?null:dayKey(lastMs),others=markers.markers.filter(m=>m.markerId!==marker.markerId),samePanel=others.filter(m=>m.panel!==null&&m.panel===marker.panel);if(samePanel.length>0&&marker.panel!==null){let rows=samePanel.map(m=>markerRow(m));groups.push({title:SHEET_COPY.otherValues(panelWord(marker.panel)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}if(lastKey!==null&&lastMs!==null){let byPanel=/* @__PURE__ */new Map;for(let m of others){if(m.panel===null||m.panel===marker.panel)continue;let p=[...m.points].reverse().find(pt=>{let ms2=dayMs(pt.at);return ms2!==null&&dayKey(ms2)===lastKey});p!==void 0&&byPanel.set(m.panel,[...byPanel.get(m.panel)??[],markerRow(m,p)])}for(let[panel,rows]of byPanel)groups.push({title:SHEET_COPY.panelTitle(panel,shortDate(lastMs)),allInRange:rows.every(r=>r.flag==="in"),rows:rows})}return{markerId:marker.markerId,name:marker.name,meta:lastMs===null?null:SHEET_COPY.panelOn(longDate(lastMs)),pill:flagPill(row.flag),flagged:row.flag==="above"||row.flag==="below",latest:`${row.value}${row.unit?` ${row.unit}`:""}`,latestSub:latestSub,hasRange:range!==null,chart:chart,change:change,meaning:(marker.meaning??"").split(/\n\s*\n/).map(p=>p.trim()).filter(p=>p.length>0),groups:groups}}var HEALTH_TAB_SHARED_COPY=/* @__PURE__ */Object.freeze({vitalsFromLabel:pet=>`Where ${pet}’s vitals come from`,vitalsFrom:(vet,date2)=>`From ${vet}’s exam, ${date2}. `,examNotes:"Exam notes",onTheWayFrom:(pet,clinic)=>`${pet}’s records from ${clinic} are on the way.`,readingUpload:"We’re reading the document you uploaded.",uploadFormatHint:"Upload PDF records you already have, up to 25 MB each. You can pick several at once. We'll read them and add the results to your records.",uploadLimitHint:"PDFs up to 25 MB each. You can pick several at once.",results:n2=>n2===1?"result":"results",noScreenings:"No screenings yet",screeningsToReview:n2=>`${n2} to review`,screeningsClear:"All clear",noVisits:"No visits yet",oneReading:"One reading so far: we’ll plot a trend as more come in.",uploadedDocument:"Uploaded document"}),MONTHS_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function healthTabDate(ms2){let d=new Date(ms2);return`${MONTHS_SHORT[d.getUTCMonth()]??""} ${d.getUTCDate()}, ${d.getUTCFullYear()}`}function healthTabScreenings(markers){let W=HEALTH_TAB_SHARED_COPY,screenings=markers.filter(m=>(m.latest?.qualitativeResult??"").trim().length>0);if(screenings.length===0)return null;let flagged=screenings.filter(m=>screeningIsFlagged(m.latest?.status??null,m.latest?.qualitativeResult??"")),first=flagged[0]??screenings[0];return flagged.length>0?{label:W.screeningsToReview(flagged.length),flagged:true,markerId:first.markerId}:{label:W.screeningsClear,flagged:false,markerId:first.markerId}}function screeningIsFlagged(status,resultText){return status==="in_range"?false:status==="above"||status==="below"?true:/negative|not detected|clear|none/i.test(resultText)?false:/positive|detected|present|reactive/i.test(resultText)}function documentClassLabel(value){let spaced=value.replace(/_/g," ").trim();return spaced.length>0?spaced.charAt(0).toUpperCase()+spaced.slice(1):value}function healthTabSources(record,depth){if(record===null||record.withheld)return[];let clinics=/* @__PURE__ */new Map;if(depth!==null&&!depth.withheld)for(let e of depth.encounters){let name=e.clinicName?.trim();e.docId!==null&&name&&clinics.set(e.docId,name)}return Object.values(record.documents).sort((a,b)=>(dayMs(b.receivedAt)??0)-(dayMs(a.receivedAt)??0)).slice(0,4).reverse().map(doc=>{let received=dayMs(doc.receivedAt);return{key:doc.docId,name:clinics.get(doc.docId)??HEALTH_TAB_SHARED_COPY.uploadedDocument,meta:[doc.documentClass?documentClassLabel(doc.documentClass):null,received!==null?healthTabDate(received):null].filter(p=>p!==null).join(" · ")}})}var MONTHS_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"];function examDate(ms2){let d=new Date(ms2);return`${MONTHS_LONG[d.getUTCMonth()]??""} ${d.getUTCDate()}`}function vitalsExam(depth,observedMs){if(observedMs===null||depth===null||depth.withheld)return null;let day=new Date(observedMs).toISOString().slice(0,10),encounter=depth.encounters.find(e=>{let ms3=dayMs(e.date);return ms3!==null&&new Date(ms3).toISOString().slice(0,10)===day}),vet=encounter?.veterinarian?.trim(),ms2=dayMs(encounter?.date);return vet&&ms2!==null?{vet:vet,date:examDate(ms2)}:null}function healthTabOnTheWay(petName,requests){let W=HEALTH_TAB_SHARED_COPY;return sheetOnTheWay(sheetPetWords(petName,null),requests).map(line2=>line2.key==="upload"?{...line2,text:W.readingUpload}:line2.key.startsWith("clinic-")?{...line2,text:W.onTheWayFrom(petName,line2.key.slice(7))}:line2)}function mapTier(wire){let tier={url:wire.url,kind:wire.kind,expiresAt:wire.expires_at};return typeof wire.loop_duration_ms=="number"&&(tier.loopDurationMs=wire.loop_duration_ms),typeof wire.cache_key=="string"&&wire.cache_key.length>0&&(tier.cacheKey=wire.cache_key),/* @__PURE__ */Object.freeze(tier)}function mapPetStateResponse(wire){let tiers={};wire.tiers.animation&&(tiers.animation=mapTier(wire.tiers.animation)),wire.tiers.image&&(tiers.image=mapTier(wire.tiers.image));let overlays={};wire.overlays.weather_alert&&(overlays.weatherAlert=mapTier(wire.overlays.weather_alert));let response={category:wire.category,tiers:/* @__PURE__ */Object.freeze(tiers),overlays:/* @__PURE__ */Object.freeze(overlays),idle:"bundled",ttlSeconds:wire.ttl_seconds,degraded:wire.degraded};return typeof wire.cache_epoch=="number"&&(response.cacheEpoch=wire.cache_epoch),/* @__PURE__ */Object.freeze(response)}var mediaKindWireSchema=/* @__PURE__ */zod.z.enum(["webp","video"]),categoryWireSchema=/* @__PURE__ */zod.z.enum(["health","attention","moment","activity","mood","idle"]),petStateTierWireSchema=/* @__PURE__ */zod.z.object({url:/* @__PURE__ */zod.z.string(),kind:/* @__PURE__ */mediaKindWireSchema.default("webp"),loop_duration_ms:/* @__PURE__ */zod.z.number().nullish(),expires_at:/* @__PURE__ */zod.z.string(),cache_key:/* @__PURE__ */zod.z.string().nullish()}),petStateResponseWireSchema=/* @__PURE__ */zod.z.object({category:categoryWireSchema,tiers:/* @__PURE__ */zod.z.object({animation:/* @__PURE__ */petStateTierWireSchema.nullish(),image:/* @__PURE__ */petStateTierWireSchema.nullish()}).default({}),overlays:/* @__PURE__ */zod.z.object({weather_alert:/* @__PURE__ */petStateTierWireSchema.nullish()}).default({}),idle:/* @__PURE__ */zod.z.literal("bundled").default("bundled"),ttl_seconds:/* @__PURE__ */zod.z.number(),degraded:/* @__PURE__ */zod.z.boolean().default(false),cache_epoch:/* @__PURE__ */zod.z.number().default(0)});function parsePetStateWire(raw){let parsed=petStateResponseWireSchema.safeParse(raw);return parsed.success?parsed.data:null}function createPetStateRepository(auth){return createPetStateRepositoryOver(createRequestFunnel({auth:auth}))}function createPetStateRepositoryOver(funnel){return{async getState(petRef,opts){if(hasLoneSurrogate(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let path=`/widget/v1/pets/${encodeURIComponent(petRef)}/state`,res=await funnel.send("animations.getState",opts?.signal?{method:"GET",path:path,signal:opts.signal}:{method:"GET",path:path},opts?.maxAttempts!==void 0?{maxAttempts:opts.maxAttempts}:void 0);if(res.ok){let wire=parsePetStateWire(res.value);return wire===null?err(makeEverfurError("internalError",{retryable:true})):ok(mapPetStateResponse(wire))}return res.error.httpStatus===404?ok(null):err(res.error)}}}var LOADING=/* @__PURE__ */Object.freeze({status:"loading"}),NONE=/* @__PURE__ */Object.freeze({status:"none"}),RETRY_MS=3e4,RECORDS_PET_ART_RETRIES_MS=/* @__PURE__ */Object.freeze([2e3,6e3]),NO_FAILURES=/* @__PURE__ */Object.freeze({animation:false,image:false});function recordsPetArtOf(read,failed,reducedMotion){if(read.kind==="pending")return LOADING;if(read.kind==="failed"||read.value===null)return NONE;let{animation:animation,image:image}=read.value.tiers;return animation!==void 0&&animation.kind==="webp"&&!reducedMotion&&!failed.animation?{status:"art",url:animation.url,key:animation.cacheKey??animation.url,animated:true}:image!==void 0&&image.kind==="webp"&&!failed.image?{status:"art",url:image.url,key:image.cacheKey??image.url,animated:false}:NONE}function useRecordsPetArt(petRef,opts){let context=react.useContext(EverfurContext),runtime=context?.runtime??null,userRef=context?.userRef??null,scope=runtime!==null&&userRef!==null&&petRef!==null?`${userRef}|${petRef}`:null,[read,setRead]=react.useState({scope:scope,read:{kind:"pending"}}),[failed,setFailed]=react.useState({scope:scope,failed:NO_FAILURES}),[due,setDue]=react.useState({scope:scope,at:0}),current=read.scope===scope?read.read:{kind:"pending"},done=current.kind==="answer"&¤t.value===null,attempts=react.useRef({scope:scope,n:0});react.useEffect(()=>{if(scope===null||runtime===null||userRef===null||petRef===null||!opts.isFocused||done)return;let at=due.scope===scope?due.at:0,live=true,controller=typeof AbortController=="function"?new AbortController:null,run=()=>{createPetStateRepository(runtime.registry.services.authFor(userRef)).getState(petRef,controller?{signal:controller.signal,maxAttempts:1}:{maxAttempts:1}).then(result=>{if(!live)return;if(result.ok){attempts.current={scope:scope,n:0};let value=result.value;setRead(prev=>value!==null&&value.degraded&&prev.scope===scope&&prev.read.kind==="answer"&&prev.read.value!==null?prev:{scope:scope,read:{kind:"answer",value:value}}),value!==null&&(value.degraded||setFailed({scope:scope,failed:NO_FAILURES}),setDue({scope:scope,at:Date.now()+Math.max(30,value.ttlSeconds)*1e3}));return}if(result.error.httpStatus===403){setRead({scope:scope,read:{kind:"answer",value:null}});return}let n2=attempts.current.scope===scope?attempts.current.n:0,quick=RECORDS_PET_ART_RETRIES_MS[n2];attempts.current={scope:scope,n:n2+1},setRead(prev=>prev.scope===scope&&prev.read.kind==="answer"?prev:quick!==void 0?{scope:scope,read:{kind:"pending"}}:{scope:scope,read:{kind:"failed"}}),setDue({scope:scope,at:Date.now()+(quick??RETRY_MS)})})},wait=Math.max(0,at-Date.now()),timer=wait===0?null:setTimeout(run,wait);return timer===null&&run(),()=>{live=false,timer!==null&&clearTimeout(timer),controller?.abort()}},[scope,runtime,userRef,petRef,opts.isFocused,done,due]);let failedNow=failed.scope===scope?failed.failed:NO_FAILURES,art=react.useMemo(()=>scope===null?NONE:recordsPetArtOf(current,failedNow,opts.reducedMotion),[scope,current,failedNow,opts.reducedMotion]),onError=react.useCallback(()=>{art.status==="art"&&setFailed(prev=>{let base2=prev.scope===scope?prev.failed:NO_FAILURES;return{scope:scope,failed:art.animated?{...base2,animation:true}:{...base2,image:true}}})},[art,scope]);return react.useMemo(()=>({art:art,onError:onError}),[art,onError])}var HUB_COPY=/* @__PURE__ */Object.freeze({temperature:"Temperature",heartRate:"Heart rate",breathing:"Breathing",vitalsLabel:pet=>`Vitals at ${pet}’s last exam`,vitalLabel:(name,value,unit,more=true)=>`${name}, ${value} ${unit}.${more?" More about it":""}`,sayLine:"I wonder what I may be hiding",sayPhrases:["Hmmm","I wonder","what I may be","hiding"],upcomingCare:"Upcoming Care",viewAll:"View all →",dueSoon:"Due soon",later:"Later",nothingDue:pet=>`Nothing due for ${pet} right now.`,overdueBy:n2=>`Overdue by ${n2} ${n2===1?"day":"days"}`,dueToday:"Due today",dueIn:n2=>`Due in ${n2} ${n2===1?"day":"days"}`,noDueDate:"No due date on file",withDue:(relative,date2)=>`${relative} · due ${date2}`,dueOn:date2=>`Due ${date2}`,thisDay:(dated,weekday)=>`${dated} · this ${weekday}`,inWeeks:(dated,weeks)=>`${dated} · in ${weeks} ${weeks===1?"week":"weeks"}`,recordsHistory:"Records & History",labs:"Labs & bloodwork",labsA11y:(n2,noun)=>`Labs and bloodwork, ${n2} ${noun}`,labsA11yUnknown:"Labs and bloodwork",labsCountUnknown:"--",screenings:"Screenings",screeningsA11y:pill=>`Screenings${pill!==null?`, ${pill}`:""}`,toReview:n2=>`${n2} to review`,allClear:"All clear",visits:"Visits & records",visitsA11y:date2=>`Visits and records${date2!==null?`, latest ${date2}`:""}`,timeline:"Timeline",events:n2=>`${n2} events`,timelineA11y:n2=>`Timeline${n2>0?`, ${n2} events`:""}`,weight:"Weight",estimatedRange:"Estimated Optimal Adult Range",noWeights:pet=>`No weights on file yet. They show up here from ${pet}’s vet visits.`,legendOver:["OVER","WEIGHT"],legendStable:["STABLE"],legendUnder:["UNDER","WEIGHT"],trendSummary:(n2,latest,trend,low,high)=>`${n2===1?"1 reading":`${n2} readings`}, latest ${latest}${n2===1?"":`, trend ${trend}`}.${low!==null&&high!==null?` Healthy range ${low} to ${high}.`:""}`,pointLabel:(when,value,unit)=>when!==null?`${when}, ${value} ${unit}`:`${value} ${unit}`,addRecords:pet=>`Add ${pet}’s records`,moreThanOneClinic:"Records can come from more than one clinic over a lifetime.",onFileNow:"On file now",videoVisit:"Everfur video visit",requestFromClinic:"Request from a clinic",uploadDocument:"Upload a document",onTheWay:pet=>`${pet}’s records are on the way`,clinicsTake:"Clinics usually take 2 to 5 days.",requestSentTo:clinic=>clinic!==null?`Request sent to ${clinic}`:"Request sent",signedRelease:when=>`${when} · you signed the release`,waitingFor:whose=>`Waiting for ${whose} records`,inHealthTab:whose=>`In ${whose} Health tab`,everyPageRead:"Every page read: vaccines, labs, visits, meds",today:"Today",anotherClinic:"Another clinic",anotherClinicText:"Seen more than one vet? We ask each one.",uploadText:"A PDF, or a photo of a paper record.",requestTitle:pet=>`${pet}’s records request`,requestA11y:(pet,status)=>`Records request for ${pet}. ${status}`,sample:"Sample",peekLead:pet=>`A sneak peek at how ${pet}’s records will read. Every number links back to the page it came from.`,previousGroup:"Previous group",nextGroup:"Next group",markerGroups:"Marker groups",sampleNotTheirs:pet=>`This is a sample, not ${pet}’s result.`,sampleNote:poss=>` Add ${poss} records to see ${poss} own numbers. Anything outside the range gets flagged like this, with what it measures and what to ask ${poss} vet.`,columns:["Test","Result","Unit","Range"],slideOf:(chip,n2,of)=>`${chip}, ${n2} of ${of}`,high:"High",legal:RECORDS_FOOTNOTE,noVetTitle:w=>`When ${w.name} has a vet, start here.`});function hubAge(totalMonths){let years=Math.floor(totalMonths/12),months=totalMonths%12;return years<=0?`${months}m`:months>0?`${years}y ${months}m`:`${years}y`}var CHEM_P2={cap:"Read from the lab report, page 2",who:"Chemistry panel",page:"p. 2 of 12"},HUB_SAMPLE_GROUPS=/* @__PURE__ */Object.freeze([{key:"liver",chip:"Liver",lead:"What the liver makes and clears.",markers:[{name:"ALT",flag:"High",what:"An enzyme found mostly in liver cells.",at:92,value:"118",unit:"U/L"},{name:"ALP",what:"An enzyme from the liver and bones.",at:33,value:"64",unit:"U/L"},{name:"GGT",what:"An enzyme tied to the liver’s bile ducts.",at:36,value:"3",unit:"U/L"},{name:"Total bilirubin",what:"A yellow pigment the liver clears.",at:33,value:"0.2",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALB",result:"3.2",unit:"g/dL",range:"2.3-4.0"},{test:"ALP",result:"64",unit:"U/L",range:"23-212",lit:true},{test:"ALT",result:"118 H",unit:"U/L",range:"10-100",lit:true},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27"},{test:"GGT",result:"3",unit:"U/L",range:"0-11",lit:true},{test:"T. BILI",result:"0.2",unit:"mg/dL",range:"0.0-0.9",lit:true}]}},{key:"kidney",chip:"Kidney",lead:"What the kidneys filter out and keep in balance.",markers:[{name:"BUN",what:"Protein waste the kidneys filter out.",at:53,value:"18",unit:"mg/dL"},{name:"Creatinine",what:"Muscle waste the kidneys filter out.",at:48,value:"1.1",unit:"mg/dL"},{name:"SDMA",what:"Another measure of kidney filtering.",at:59,value:"9",unit:"µg/dL"},{name:"Phosphorus",what:"A mineral the kidneys keep in balance.",at:42,value:"4.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"ALT",result:"45",unit:"U/L",range:"10-100"},{test:"BUN",result:"18",unit:"mg/dL",range:"7-27",lit:true},{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0"},{test:"CREA",result:"1.1",unit:"mg/dL",range:"0.5-1.8",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8",lit:true},{test:"SDMA",result:"9",unit:"µg/dL",range:"0-14",lit:true}]}},{key:"blood",chip:"Blood cells",lead:"The cells that carry oxygen, fight infection and help blood clot.",markers:[{name:"Red blood cells",what:"Cells that carry oxygen around the body.",at:43,value:"6.9",unit:"M/µL"},{name:"Hemoglobin",what:"The part of red cells that holds oxygen.",at:42,value:"15.8",unit:"g/dL"},{name:"White blood cells",what:"Cells that fight infection.",at:44,value:"9.8",unit:"K/µL"},{name:"Platelets",what:"Cell fragments that help blood clot.",at:41,value:"265",unit:"K/µL"}],from:{cap:"Read from the lab report, page 3",who:"Complete blood count",page:"p. 3 of 12",rows:[{test:"HCT",result:"46",unit:"%",range:"37.3-61.7"},{test:"HGB",result:"15.8",unit:"g/dL",range:"13.1-20.5",lit:true},{test:"NEUT",result:"6.1",unit:"K/µL",range:"2.95-11.64"},{test:"PLT",result:"265",unit:"K/µL",range:"148-484",lit:true},{test:"RBC",result:"6.9",unit:"M/µL",range:"5.65-8.87",lit:true},{test:"WBC",result:"9.8",unit:"K/µL",range:"5.05-16.76",lit:true}]}},{key:"sugar",chip:"Sugar and salts",lead:"Fuel, and the salts that keep fluids, nerves and muscles steady.",markers:[{name:"Glucose",what:"Blood sugar, the body’s main fuel.",at:41,value:"96",unit:"mg/dL"},{name:"Sodium",what:"A salt that keeps fluids in balance.",at:31,value:"147",unit:"mmol/L"},{name:"Potassium",what:"A salt that helps nerves and muscles work.",at:49,value:"4.6",unit:"mmol/L"},{name:"Calcium",what:"A mineral for bones, muscles and nerves.",at:52,value:"10.1",unit:"mg/dL"}],from:{...CHEM_P2,rows:[{test:"CA",result:"10.1",unit:"mg/dL",range:"7.9-12.0",lit:true},{test:"CL",result:"112",unit:"mmol/L",range:"109-122"},{test:"GLU",result:"96",unit:"mg/dL",range:"70-143",lit:true},{test:"K",result:"4.6",unit:"mmol/L",range:"3.5-5.8",lit:true},{test:"NA",result:"147",unit:"mmol/L",range:"144-160",lit:true},{test:"PHOS",result:"4.1",unit:"mg/dL",range:"2.5-6.8"}]}}]),HUB_SAMPLE_MORE=/* @__PURE__ */Object.freeze([{key:"screenings",title:"Screenings",tint:"pink",lead:"Tests that look for common problems early, and what came back.",rows:[{title:"Heartworm test",pill:"Negative",tone:"clear"},{title:"Tick panel (4Dx)",pill:"Negative",tone:"clear"}]},{key:"visits",title:"Visits & records",tint:"blue",lead:"Every visit, with the vet’s notes and the pages they came from.",rows:[{title:"Wellness exam",text:"38 pages"},{title:"Everfur video visit",text:"3 pages"}]},{key:"timeline",title:"Timeline",tint:"yellow",lead:"Her whole history in order, with what’s due next.",rows:[{title:"Rabies vaccine",pill:"Due soon",tone:"soon"},{title:"Heartworm test",text:"Apr 18"}]}]);var APP_HUB_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",text:"#000000",bg:"#FFFFFF",white:"#FFFFFF",mist:"#F1F5F2",charcoal:"#3D3D3D",alert:"#C03410",alertDeep:"#6D1D14",pink:"#FFC3BC",yellow:"#F2C763",skyBlue:"#4E98C9",tintSage:"#E6ECE8",tintPink:"#FFEAE8",tintPinkSoft:"#FFF6F5",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintYellowEdge:"#F6D892",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoGrey:"#6B6B6B",icoSage:"#819E90",icoBlue:"#4E98C9",barTrack:"#ECECEC",pillPlainEdge:"rgba(16, 70, 46, 0.2)"}),APP_HUB_TYPE=/* @__PURE__ */Object.freeze({screenTitle:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"medium",color:"ink",letterSpacing:-.33}),cardTitle:/* @__PURE__ */Object.freeze({size:18,lineHeight:22.5,face:"bold",color:"ink",letterSpacing:-.36}),body:/* @__PURE__ */Object.freeze({size:17,lineHeight:26.35,face:"regular",color:"text",letterSpacing:0}),bodySm:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"regular",color:"text",letterSpacing:0}),bodySmBold:/* @__PURE__ */Object.freeze({size:15,lineHeight:21.75,face:"bold",color:"ink",letterSpacing:0}),fine:/* @__PURE__ */Object.freeze({size:13,lineHeight:18.2,face:"regular",color:"muted",letterSpacing:0}),labelMono:/* @__PURE__ */Object.freeze({size:12,lineHeight:16.8,face:"monoBold",color:"muted",letterSpacing:.72,upper:true}),pill:/* @__PURE__ */Object.freeze({size:12,lineHeight:14.4,face:"monoBold",color:"ink",letterSpacing:.72,upper:true}),button:/* @__PURE__ */Object.freeze({size:15,lineHeight:18,face:"bold",color:"ink",letterSpacing:0}),buttonRow:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"bold",color:"ink",letterSpacing:0}),chip:/* @__PURE__ */Object.freeze({size:14,lineHeight:16.8,face:"medium",color:"ink",letterSpacing:0}),hand:/* @__PURE__ */Object.freeze({size:22,lineHeight:26.4,face:"hand",color:"ink",letterSpacing:0})}),APP_HUB_LEGACY=/* @__PURE__ */Object.freeze({surface:"#FFFFFF",textPrimary:"#111111",textMuted:"#6E6660",border:"#C8BEB4",brand:"#10462E",brandSoft:"rgba(16, 70, 46, 0.1)",danger:"#B91C1C"}),APP_HUB_TIMELINE=/* @__PURE__ */Object.freeze({dot:24,check:12,core:10,ring:2,rowGap:12,bodyBottom:18,bodyGap:2,titleGap:8,rail:2,railMin:22,railGap:2,titleSize:14,titleLineHeight:18,dateSize:12,dateLineHeight:16,detailSize:13,detailLineHeight:17,upcomingOpacity:.7});var APP_HUB=/* @__PURE__ */Object.freeze({screen:{gap:12,padX:16,padBottom:24,legalTop:20},hero:{nameSize:22,nameLineHeight:26,nameTracking:-.44,metaTop:2,metaLineHeight:18,metaTracking:.26,stageHeight:280,stageTop:4,grassFraction:.46,petBottom:40,petBoxHeight:224,petTop:16,sayWidth:230,sayHeight:61,sayFontSize:22,sayArcPath:"M 12 60 Q 120 -4 228 60",sayViewBox:[240,64],vitalsTop:8,vitalsLeft:8,vitalMinHeight:40,vitalPadX:8,vitalGap:6,vitalIcon:22,vitalValueSize:17,vitalUnitSize:13,lawnOverlap:26,lawnRadius:28},card:{pad:16,radius:20,border:1,headGap:8,headBottom:12},button:{md:52,sm:46,row:36,padMd:24,padSm:16,padRow:14,iconMd:22,iconSm:20,iconRow:17,edge:1.5,gap:8,mdLabel:17,textGap:6,textMinHeight:24},pill:{minHeight:24,padX:10,edgeThin:1.25,edgeThick:1.5},upcoming:{listGap:4,bleed:8,rowPadY:10,rowPadX:8,rowGap:12,rowRadius:10,icon:20,maxRows:4},tiles:{top:8,titleBottom:12,gap:12,pad:16,radius:20,innerGap:8,icon:22,chevron:20,titleLineHeight:19,footMinHeight:28,numSize:20,numLineHeight:22,numTracking:-.4,countGap:8},weight:{headGap:4,headBottom:16,numSize:32,numLineHeight:34,numTracking:-.64,numGap:8},chart:{height:176,plotTop:24,axisBand:20,rightInset:14,indicatorWidth:8,plotLeft:62,dataLeft:76,dot:6,dotRing:1.5,lineWidth:2,labelGap:7,labelMax:12,labelMin:9,labelCharWidth:.62,edgePad:4,legendX:14,legendLine:14.4,legendSize:12,legendTracking:.24,monthY:172,monthSize:12,maxTicks:5,maxValues:8,bandFrom:.3,bandTo:.7,reach:.88,bandPct:.1,lineColor:"#111111",gridColor:"#EAEAEA",bandColor:"#D8F3E3"},add:{gap:12,headGap:8,icon:26,sourcesGap:6,sourcesTop:4,sourcePadY:10,sourcePadX:14,sourceRadius:10,sourceColumnGap:12,actsGap:12,actsTop:4},peek:{top:12,headGap:12,leadTop:8,labsTop:16,chipsTop:10,chipsGap:8,slideTop:16,slideGap:4,slideLeadTop:2,slideLeadBottom:8,markerPad:12,markerGap:8,markerRadius:10,markerTopGap:12,barHeight:8,barDot:12,barDotRing:2,valueGap:4,fromMinHeight:40,fromGap:6,fromIcon:16,fromChevron:18,moreGap:12,moreTop:16,morePad:16,moreInnerGap:12,moreRadius:20,moreIcon:22,moreHeadGap:8,rowsGap:6,rowMinHeight:44,rowPadY:8,rowPadX:14,rowRadius:10,roundButton:36,chipHeight:36,chipPadX:14},onTheWay:{dot:28,titleSize:22,titleLineHeight:25,titleTracking:-.44,wayIcon:26,wayPad:16,wayRadius:20},inProgress:{radius:18,pad:18,gap:16,titleSize:16,titleLineHeight:20,statusRadius:14,statusPad:14,statusSize:13,statusLineHeight:19}});var HIDDEN3={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},frame=size=>({width:size,height:size});function bar2(x1,y1,x2,y2,w,color){let len=Math.hypot(x2-x1,y2-y1)+w;return{position:"absolute",left:(x1+x2)/2-len/2,top:(y1+y2)/2-w/2,width:len,height:w,borderRadius:w/2,backgroundColor:color,transform:[{rotate:`${Math.atan2(y2-y1,x2-x1)}rad`}]}}function DownloadGlyph2({size:size,color:color}){let u=size/24.7029,w=2.05857*u;/* @__PURE__ */
|
|
735
760
|
return jsxRuntime.jsxs(reactNative.View,{style:frame(size),...HIDDEN3,children:[
|
|
736
761
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(12.35*u,3.09*u,12.35*u,15.44*u,w,color)}),
|
|
737
762
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(7.2*u,10.29*u,12.35*u,15.44*u,w,color)}),
|
|
@@ -789,135 +814,146 @@ return jsxRuntime.jsxs(reactNative.View,{style:frame(size),...HIDDEN3,children:[
|
|
|
789
814
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(2.14*u,17.14*u,15*u,17.14*u,w,color)}),
|
|
790
815
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:arc(15*u,19.29*u,2.14*u,w,color,["right","bottom"],-45)})]})}function SyringeGlyph({size:size,color:color}){let u=size/19.5956,w=1.63296*u,seg=[[14.53,1.63,17.8,4.9],[13.72,5.72,16.17,3.27],[15.35,7.35,6.94,15.76],[12.08,4.08,3.67,12.49],[6.94,15.76,5.55,16.37],[5.55,16.37,4.16,15.76],[4.16,15.76,3.67,15.27],[3.67,15.27,3.06,13.88],[3.06,13.88,3.67,12.49],[7.18,8.98,10.45,12.25],[3.92,15.51,1.47,17.96],[11.27,3.27,16.17,8.17]];/* @__PURE__ */
|
|
791
816
|
return jsxRuntime.jsx(reactNative.View,{style:frame(size),...HIDDEN3,children:seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i))})}var CORNERS=[[6,4,"left"],[18,20,"right"],[6,20,"bottom"],[16,6,"bottom"]];function FileGlyph({size:size,color:color}){let u=size/24,w=2*u,seg=[[6,2,15,2],[4,4,4,20],[6,22,18,22],[20,7,20,20],[15,2,20,7],[14,2,14,6],[16,8,20,8],[8,9,10,9],[8,13,16,13],[8,17,16,17]];/* @__PURE__ */
|
|
792
|
-
return jsxRuntime.jsxs(reactNative.View,{style:frame(size),...HIDDEN3,children:[seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i)),CORNERS.map(([cx,cy,side],i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:arc(cx*u,cy*u,2*u,w,color,[side],45)},`c${i}`))]})}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}var RAPH_RN_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",alert:"#C03410",alertDeep:"#6D1D14",tintSage:"#E6ECE8",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoSage:"#819E90",efWhite:"#FFFFFF",efBlack:"#000000",efCharcoal:"#3D3D3D",efSkyBlue:"#4E98C9",embCyan1:"#E0FDFF",bgMist:"#F1F5F2",paper:"#F8F7F4",watch:"#F9E6B9",barTrack:"#ECECEC",topCard:"#FFCE34",topKicker:"#4A4845",topInk:"#262523",plainEdge:"rgba(16, 70, 46, 0.2)"}),RAPH_RN_RULES=/* @__PURE__ */Object.freeze({".rec-note":/* @__PURE__ */Object.freeze({fontSize:12.5}),".efh":/* @__PURE__ */Object.freeze({gap:12,fontSize:15}),".efh-sheet":/* @__PURE__ */Object.freeze({marginTop:20,paddingTop:20,paddingBottom:28,paddingLeft:16,borderTopLeftRadius:28}),".efh-ico":/* @__PURE__ */Object.freeze({width:22}),".efh-label":/* @__PURE__ */Object.freeze({fontSize:12}),".efh-pill":/* @__PURE__ */Object.freeze({minHeight:24}),".efh-card":/* @__PURE__ */Object.freeze({paddingTop:16,borderRadius:20}),".efh-card__title":/* @__PURE__ */Object.freeze({fontSize:18}),".efh-btn":/* @__PURE__ */Object.freeze({minHeight:48}),".efh-btn--row":/* @__PURE__ */Object.freeze({minHeight:40}),".efh-head":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-name":/* @__PURE__ */Object.freeze({fontSize:22}),".efh-meta":/* @__PURE__ */Object.freeze({fontSize:13}),".efh-stage":/* @__PURE__ */Object.freeze({height:236,marginTop:4,marginLeft:-16}),".efh-stage__grass":/* @__PURE__ */Object.freeze({height:"44%"}),".efh-stage__pet":/* @__PURE__ */Object.freeze({left:"58%",bottom:22,height:"86%"}),".efh-stage .efh-vitals":/* @__PURE__ */Object.freeze({top:14,left:16,gap:12}),".efh-head__from":/* @__PURE__ */Object.freeze({marginTop:12}),".efh-due li":/* @__PURE__ */Object.freeze({borderRadius:10}),".efh-tiles":/* @__PURE__ */Object.freeze({gap:10}),".efh-tile__num":/* @__PURE__ */Object.freeze({fontSize:20}),".efh-wt b":/* @__PURE__ */Object.freeze({fontSize:32}),".efh-wchart__plot":/* @__PURE__ */Object.freeze({height:148}),".efh-sheet .rec-note":/* @__PURE__ */Object.freeze({marginTop:4}),".efh-mk__name":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-mk__line":/* @__PURE__ */Object.freeze({rowGap:0,columnGap:6,marginTop:1,fontSize:13,lineHeight:18.2}),".efh-mk__line b":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-none":/* @__PURE__ */Object.freeze({paddingTop:0}),".efh-none__scene":/* @__PURE__ */Object.freeze({marginBottom:16,marginLeft:-16}),".efh-none__t":/* @__PURE__ */Object.freeze({fontSize:22,lineHeight:25.3,letterSpacing:-.44}),".efh-none__lead":/* @__PURE__ */Object.freeze({marginTop:8,fontSize:15,lineHeight:22.5}),".efh-ways":/* @__PURE__ */Object.freeze({gap:12,marginTop:16}),".efh-way":/* @__PURE__ */Object.freeze({columnGap:12,paddingTop:16,borderRadius:20}),".efh-way__w":/* @__PURE__ */Object.freeze({gap:2}),".efh-way__t":/* @__PURE__ */Object.freeze({fontSize:16,lineHeight:20.8}),".efh-way__x":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75}),".efh-peek__labs .efh-card__title":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-peek__g":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75,marginBottom:6}),".efh-peek__g b":/* @__PURE__ */Object.freeze({fontSize:16})}),RAPH_RN_SAY=/* @__PURE__ */Object.freeze({viewBox:[0,0,240,64],path:{x0:12,y0:60,cx:120,cy:-4,x1:228,y1:60},width:210,headX:.34,headTop:0,gap:2,fontSize:22,fontWeight:"500",beats:4,keyframes:[{offset:0,opacity:0},{offset:.025,opacity:1},{offset:.052,opacity:1},{offset:.077,opacity:0},{offset:1,opacity:0}],durationMs:44e3,easing:"ease-in-out",delayMs:1200,staggerMs:3600}),RAPH_RN_SCENE=/* @__PURE__ */Object.freeze({height:212,grassHeight:64,petHeight:150,petBottom:16,petAspect:.731,grassSize:[1520,479],petSize:[307,420]});var R=RAPH_RN_RULES;function raphPx(selector,prop){let v=R[selector]?.[prop];return typeof v=="number"?v:Number.NaN}var n=raphPx;function raphPct(selector,prop){let v=R[selector]?.[prop];return typeof v=="string"&&v.endsWith("%")?Number(v.slice(0,-1))/100:Number.NaN}var RAPH_RN_METRICS=/* @__PURE__ */Object.freeze({gap:n(".efh","gap"),sheetPadTop:n(".efh-sheet","paddingTop"),sheetPadX:n(".efh-sheet","paddingLeft"),sheetPadBottom:n(".efh-sheet","paddingBottom"),sheetRadius:n(".efh-sheet","borderTopLeftRadius"),sheetGap:n(".efh-sheet","marginTop"),cardPad:n(".efh-card","paddingTop"),cardRadius:n(".efh-card","borderRadius"),name:n(".efh-name","fontSize"),cardTitle:n(".efh-card__title","fontSize"),rowTitle:n(".efh-mk__name","fontSize"),body:n(".efh","fontSize"),small:n(".efh-meta","fontSize"),mono:n(".efh-label","fontSize"),tileNum:n(".efh-tile__num","fontSize"),big:n(".efh-wt b","fontSize"),button:n(".efh-btn","minHeight"),rowButton:n(".efh-btn--row","minHeight"),pill:n(".efh-pill","minHeight"),plot:n(".efh-wchart__plot","height"),rowRadius:n(".efh-due li","borderRadius"),tileGap:n(".efh-tiles","gap"),icon:n(".efh-ico","width")});function sameColour(a,b){return a.trim().toLowerCase()===b.trim().toLowerCase()}function mix(a,b,t){let over=withAlpha(a,t);return(over!==null?flattenOnto(over,b):null)??b}var same=(a,b)=>parseColor(a)===parseColor(b);function raphIdentity(theme){if(theme.brightness!=="light")return false;let c=theme.color,k=EVERFUR_LIGHT.color;return same(c.primary,k.primary)&&same(c.brandInk,k.brandInk)&&same(c.onPrimary,k.onPrimary)&&same(c.accent,k.accent)&&same(c.accentEdge,k.accentEdge)}function brandTints(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),dark=theme.brightness==="dark",identity=raphIdentity(theme),compiled=(dark?EVERFUR_DARK:EVERFUR_LIGHT).color,accentSet=!same(c.accent,compiled.accent),ground=dark?c.surface:P.efWhite,tint=(hue,lightT)=>mix(hue,ground,dark?.18:lightT),tintSage=identity?P.tintSage:tint(v.primary,.105),topFill=accentSet?v.accent:tintSage;return{tintSage:tintSage,chevron:identity?P.icoSage:mix(c.brandInk,ground,.527),rowGround:identity?P.bgMist:tint(v.primary,.059),tintPartner:accentSet?tint(v.accent,.14):P.embCyan1,topFill:topFill,plainEdge:identity?P.plainEdge:withAlpha(c.brandInk,.2)??c.structureEdge,topKicker:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink3:P.topKicker,P.topInk]),topInk:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink:P.topInk,P.topInk])}}function recordsSheetLook(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),tints=brandTints(theme),accentOnFill=raphIdentity(theme)?P.go:sameColour(c.accent,c.primary)?c.onPrimary:c.accent;return theme.brightness==="dark"?/* @__PURE__ */Object.freeze({dark:true,paper:v.paper,ground:c.background,card:v.card,text:v.ink,muted:v.ink3,line:c.structureEdge,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:c.success,goTint:c.badgeBgPositive,alert:v.riskInk,alertDeep:v.riskInk,alertTint:c.badgeBgCritical,watch:c.badgeBgCaution,wind:P.efSkyBlue,tintBlue:c.surfaceSubtle,tintYellow:c.surfaceSubtle,barTrack:c.structureEdge,...tints}):/* @__PURE__ */Object.freeze({dark:false,paper:v.paper,ground:P.efWhite,card:P.efWhite,text:P.efBlack,muted:P.muted,line:P.line,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:P.go,goTint:P.tintGo,alert:P.alert,alertDeep:P.alertDeep,alertTint:P.tintRed,watch:P.watch,wind:P.efSkyBlue,tintBlue:P.tintBlue,tintYellow:P.tintYellow,barTrack:P.barTrack,...tints})}function isRecordsSheetIdentity(theme){return raphIdentity(theme)}function partnerAccentSet(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color;return!same(theme.color.accent,compiled.accent)}function hubLook(theme){let look=recordsSheetLook(theme);if(look.dark)/* @__PURE__ */
|
|
793
|
-
return Object.freeze({dark:true,bg:
|
|
794
|
-
return Object.freeze({dark:false,bg:APP_HUB_PALETTE.bg,white:APP_HUB_PALETTE.white,text:APP_HUB_PALETTE.text,muted:APP_HUB_PALETTE.muted,line:APP_HUB_PALETTE.line,charcoal:APP_HUB_PALETTE.charcoal,ink:brand,fill:identity?APP_HUB_PALETTE.ink:
|
|
817
|
+
return jsxRuntime.jsxs(reactNative.View,{style:frame(size),...HIDDEN3,children:[seg.map(([x1,y1,x2,y2],i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:bar2(x1*u,y1*u,x2*u,y2*u,w,color)},i)),CORNERS.map(([cx,cy,side],i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:arc(cx*u,cy*u,2*u,w,color,[side],45)},`c${i}`))]})}var RAPH_V3_LIGHT=/* @__PURE__ */Object.freeze({ink:"#262523",ink2:"#4A4845",ink3:"#6B6863",paper:"#F8F7F4",card:"#FFFFFF",line:"#E7E6E2",tile:"#F2F1EE",shadow:"rgba(38, 37, 35, .07)",riskBg:"#FFE3E1",riskInk:"#B0231B",riskDot:"#E5372B",clearBg:"#E6F4D3",clearInk:"#2F6A12",clearDot:"#5FA82B",watchDot:"#E5A000"}),cache=/* @__PURE__ */new WeakMap;function v3Palette(theme){let hit=cache.get(theme);if(hit!==void 0)return hit;let c=theme.color,dark=theme.brightness==="dark",neutrals=dark?{dark:dark,ink:c.text.primary,ink2:c.text.secondary,ink3:c.text.muted,paper:c.background,card:c.surface,line:c.borderRingCream,tile:c.surfaceSubtle,shadow:c.shadow,riskBg:c.badgeBgCritical,riskInk:c.danger,riskDot:c.danger,clearBg:c.badgeBgPositive,clearInk:c.success,clearDot:c.success,watchDot:c.warningStrong}:{dark:dark,...RAPH_V3_LIGHT},textOn=(ink,grounds)=>pushToContrast(ink,grounds,poleForGrounds(grounds),V3_TEXT_CONTRAST),labelOn=(ink,fill)=>contrastRatio(ink,fill)>=V3_TEXT_CONTRAST?ink:legibleOn(fill,V3_TEXT_CONTRAST),badgeGrounds=[neutrals.card,neutrals.paper].map(under=>flattenOnto(c.brandSoft,under)??under),brand={primary:c.primary,onPrimary:labelOn(c.onPrimary,c.primary),accent:c.accent,onAccent:labelOn(c.onAccent,c.accent),link:textOn(c.linkInk,[neutrals.card,neutrals.paper,neutrals.tile]),badge:c.brandSoft,onBadge:textOn(c.brandInk,badgeGrounds)},palette=/* @__PURE__ */Object.freeze({...neutrals,...brand});return cache.set(theme,palette),palette}var V3_TEXT_CONTRAST=4.5;function v3InkOn(fill,inks){for(let ink of inks)if(contrastRatio(ink,fill)>=V3_TEXT_CONTRAST)return ink;return legibleOn(fill,V3_TEXT_CONTRAST)}var RAPH_RN_PALETTE=/* @__PURE__ */Object.freeze({ink:"#10462E",go:"#07C168",muted:"#6B6B6B",line:"#E4E4E4",alert:"#C03410",alertDeep:"#6D1D14",tintSage:"#E6ECE8",tintBlue:"#EAEEF6",tintYellow:"#FCF0D6",tintRed:"#FBF1EE",tintGo:"#DCF6EA",icoSage:"#819E90",efWhite:"#FFFFFF",efBlack:"#000000",efCharcoal:"#3D3D3D",efSkyBlue:"#4E98C9",embCyan1:"#E0FDFF",bgMist:"#F1F5F2",paper:"#F8F7F4",watch:"#F9E6B9",barTrack:"#ECECEC",topCard:"#FFCE34",topKicker:"#4A4845",topInk:"#262523",plainEdge:"rgba(16, 70, 46, 0.2)"}),RAPH_RN_RULES=/* @__PURE__ */Object.freeze({".rec-note":/* @__PURE__ */Object.freeze({fontSize:12.5}),".efh":/* @__PURE__ */Object.freeze({gap:12,fontSize:15}),".efh-sheet":/* @__PURE__ */Object.freeze({marginTop:20,paddingTop:20,paddingBottom:28,paddingLeft:16,borderTopLeftRadius:28}),".efh-ico":/* @__PURE__ */Object.freeze({width:22}),".efh-label":/* @__PURE__ */Object.freeze({fontSize:12}),".efh-pill":/* @__PURE__ */Object.freeze({minHeight:24}),".efh-card":/* @__PURE__ */Object.freeze({paddingTop:16,borderRadius:20}),".efh-card__title":/* @__PURE__ */Object.freeze({fontSize:18}),".efh-btn":/* @__PURE__ */Object.freeze({minHeight:48}),".efh-btn--row":/* @__PURE__ */Object.freeze({minHeight:40}),".efh-head":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-name":/* @__PURE__ */Object.freeze({fontSize:22}),".efh-meta":/* @__PURE__ */Object.freeze({fontSize:13}),".efh-stage":/* @__PURE__ */Object.freeze({height:236,marginTop:4,marginLeft:-16}),".efh-stage__grass":/* @__PURE__ */Object.freeze({height:"44%"}),".efh-stage__pet":/* @__PURE__ */Object.freeze({left:"58%",bottom:22,height:"86%"}),".efh-stage .efh-vitals":/* @__PURE__ */Object.freeze({top:14,left:16,gap:12}),".efh-head__from":/* @__PURE__ */Object.freeze({marginTop:12}),".efh-due li":/* @__PURE__ */Object.freeze({borderRadius:10}),".efh-tiles":/* @__PURE__ */Object.freeze({gap:10}),".efh-tile__num":/* @__PURE__ */Object.freeze({fontSize:20}),".efh-wt b":/* @__PURE__ */Object.freeze({fontSize:32}),".efh-wchart__plot":/* @__PURE__ */Object.freeze({height:148}),".efh-sheet .rec-note":/* @__PURE__ */Object.freeze({marginTop:4}),".efh-mk__name":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-mk__line":/* @__PURE__ */Object.freeze({rowGap:0,columnGap:6,marginTop:1,fontSize:13,lineHeight:18.2}),".efh-mk__line b":/* @__PURE__ */Object.freeze({fontSize:17}),".efh-none":/* @__PURE__ */Object.freeze({paddingTop:0}),".efh-none__scene":/* @__PURE__ */Object.freeze({marginBottom:16,marginLeft:-16}),".efh-none__t":/* @__PURE__ */Object.freeze({fontSize:22,lineHeight:25.3,letterSpacing:-.44}),".efh-none__lead":/* @__PURE__ */Object.freeze({marginTop:8,fontSize:15,lineHeight:22.5}),".efh-ways":/* @__PURE__ */Object.freeze({gap:12,marginTop:16}),".efh-way":/* @__PURE__ */Object.freeze({columnGap:12,paddingTop:16,borderRadius:20}),".efh-way__w":/* @__PURE__ */Object.freeze({gap:2}),".efh-way__t":/* @__PURE__ */Object.freeze({fontSize:16,lineHeight:20.8}),".efh-way__x":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75}),".efh-peek__labs .efh-card__title":/* @__PURE__ */Object.freeze({marginBottom:8}),".efh-peek__g":/* @__PURE__ */Object.freeze({fontSize:15,lineHeight:21.75,marginBottom:6}),".efh-peek__g b":/* @__PURE__ */Object.freeze({fontSize:16})}),RAPH_RN_SAY=/* @__PURE__ */Object.freeze({viewBox:[0,0,240,64],path:{x0:12,y0:60,cx:120,cy:-4,x1:228,y1:60},width:210,headX:.34,headTop:0,gap:2,fontSize:22,fontWeight:"500",beats:4,keyframes:[{offset:0,opacity:0},{offset:.025,opacity:1},{offset:.052,opacity:1},{offset:.077,opacity:0},{offset:1,opacity:0}],durationMs:44e3,easing:"ease-in-out",delayMs:1200,staggerMs:3600}),RAPH_RN_SCENE=/* @__PURE__ */Object.freeze({height:212,grassHeight:64,petHeight:150,petBottom:16,petAspect:.731,grassSize:[1520,479],petSize:[307,420]});var R=RAPH_RN_RULES;function raphPx(selector,prop){let v=R[selector]?.[prop];return typeof v=="number"?v:Number.NaN}var n=raphPx;function raphPct(selector,prop){let v=R[selector]?.[prop];return typeof v=="string"&&v.endsWith("%")?Number(v.slice(0,-1))/100:Number.NaN}var RAPH_RN_METRICS=/* @__PURE__ */Object.freeze({gap:n(".efh","gap"),sheetPadTop:n(".efh-sheet","paddingTop"),sheetPadX:n(".efh-sheet","paddingLeft"),sheetPadBottom:n(".efh-sheet","paddingBottom"),sheetRadius:n(".efh-sheet","borderTopLeftRadius"),sheetGap:n(".efh-sheet","marginTop"),cardPad:n(".efh-card","paddingTop"),cardRadius:n(".efh-card","borderRadius"),name:n(".efh-name","fontSize"),cardTitle:n(".efh-card__title","fontSize"),rowTitle:n(".efh-mk__name","fontSize"),body:n(".efh","fontSize"),small:n(".efh-meta","fontSize"),mono:n(".efh-label","fontSize"),tileNum:n(".efh-tile__num","fontSize"),big:n(".efh-wt b","fontSize"),button:n(".efh-btn","minHeight"),rowButton:n(".efh-btn--row","minHeight"),pill:n(".efh-pill","minHeight"),plot:n(".efh-wchart__plot","height"),rowRadius:n(".efh-due li","borderRadius"),tileGap:n(".efh-tiles","gap"),icon:n(".efh-ico","width")});function sameColour(a,b){return a.trim().toLowerCase()===b.trim().toLowerCase()}function mix(a,b,t){let over=withAlpha(a,t);return(over!==null?flattenOnto(over,b):null)??b}var same=(a,b)=>parseColor(a)===parseColor(b);function raphIdentity(theme){if(theme.brightness!=="light")return false;let c=theme.color,k=EVERFUR_LIGHT.color;return same(c.primary,k.primary)&&same(c.brandInk,k.brandInk)&&same(c.onPrimary,k.onPrimary)&&same(c.accent,k.accent)&&same(c.accentEdge,k.accentEdge)}function brandTints(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),dark=theme.brightness==="dark",identity=raphIdentity(theme),compiled=(dark?EVERFUR_DARK:EVERFUR_LIGHT).color,accentSet=!same(c.accent,compiled.accent),ground=dark?c.surface:P.efWhite,tint=(hue,lightT)=>mix(hue,ground,dark?.18:lightT),tintSage=identity?P.tintSage:tint(v.primary,.105),topFill=accentSet?v.accent:tintSage;return{tintSage:tintSage,chevron:identity?P.icoSage:mix(c.brandInk,ground,.527),rowGround:identity?P.bgMist:tint(v.primary,.059),tintPartner:accentSet?tint(v.accent,.14):P.embCyan1,topFill:topFill,plainEdge:identity?P.plainEdge:withAlpha(c.brandInk,.2)??c.structureEdge,topKicker:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink3:P.topKicker,P.topInk]),topInk:v3InkOn(topFill,[accentSet?v.onAccent:dark?v.ink:P.topInk,P.topInk])}}function recordsSheetLook(theme){let c=theme.color,P=RAPH_RN_PALETTE,v=v3Palette(theme),tints=brandTints(theme),accentOnFill=raphIdentity(theme)?P.go:sameColour(c.accent,c.primary)?c.onPrimary:c.accent;return theme.brightness==="dark"?/* @__PURE__ */Object.freeze({dark:true,paper:v.paper,ground:c.background,card:v.card,text:v.ink,muted:v.ink3,line:c.structureEdge,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:c.success,goTint:c.badgeBgPositive,alert:v.riskInk,alertDeep:v.riskInk,alertTint:c.badgeBgCritical,watch:c.badgeBgCaution,wind:P.efSkyBlue,tintBlue:c.surfaceSubtle,tintYellow:c.surfaceSubtle,barTrack:c.structureEdge,...tints}):/* @__PURE__ */Object.freeze({dark:false,paper:v.paper,ground:P.efWhite,card:P.efWhite,text:P.efBlack,muted:P.muted,line:P.line,ink:c.brandInk,fill:v.primary,onFill:v.onPrimary,accentOnFill:accentOnFill,accent:v.accent,go:P.go,goTint:P.tintGo,alert:P.alert,alertDeep:P.alertDeep,alertTint:P.tintRed,watch:P.watch,wind:P.efSkyBlue,tintBlue:P.tintBlue,tintYellow:P.tintYellow,barTrack:P.barTrack,...tints})}function isRecordsSheetIdentity(theme){return raphIdentity(theme)}function partnerAccentSet(theme){let compiled=(theme.brightness==="dark"?EVERFUR_DARK:EVERFUR_LIGHT).color;return!same(theme.color.accent,compiled.accent)}function firstFontFamily(stack){if(stack===void 0)return null;let first=stack.split(",")[0]?.trim().replace(/^["']|["']$/g,"").trim()??"";return first.length>0?first:null}function recordsSheetKitTheme(theme,palette,fonts){let font=firstFontFamily(fonts?.font),mono=firstFontFamily(fonts?.mono),raph=palette==="raph";if(!raph&&font===null&&mono===null)return theme;let type=theme.type,families={...type.families,...font!==null?{regular:font,medium:font,bold:font}:{},...mono!==null?{mono:mono,monoMedium:mono,monoBold:mono}:{}},namedFaces={...type.namedFaces,...font!==null?{regular:false,medium:false,bold:false}:{},...mono!==null?{mono:false,monoMedium:false,monoBold:false}:{}};return{...theme,...raph?{brightness:"light",highContrast:false,color:EVERFUR_LIGHT.color}:{},type:{...type,families:families,namedFaces:namedFaces,family:families.regular,mono:families.mono}}}function hubLook(theme){let look2=recordsSheetLook(theme);if(look2.dark)/* @__PURE__ */
|
|
818
|
+
return Object.freeze({dark:true,bg:look2.ground,white:look2.card,text:look2.text,muted:look2.muted,line:look2.line,charcoal:look2.muted,ink:look2.ink,fill:look2.fill,onFill:look2.onFill,accentOnFill:look2.accentOnFill,go:look2.go,alert:look2.alert,alertDeep:look2.alertDeep,yellow:look2.watch,tintSage:look2.tintSage,tintPink:look2.tintPartner,tintPinkSoft:look2.card,tintBlue:look2.tintBlue,tintYellow:look2.tintYellow,tintYellowEdge:look2.watch,tintRed:look2.alertTint,tintGo:look2.goTint,icoGrey:look2.muted,icoSage:look2.chevron,icoBlue:look2.wind,barTrack:look2.barTrack,pillPlainEdge:look2.plainEdge,chartLine:look2.text,chartGrid:look2.line,chartBand:look2.goTint,legacyText:look2.text,legacyMuted:look2.muted,legacyBorder:look2.line,brand:look2.ink,brandSoft:withAlpha(look2.ink,.1)??look2.tintSage});let identity=isRecordsSheetIdentity(theme),brand=identity?APP_HUB_PALETTE.ink:look2.ink;/* @__PURE__ */
|
|
819
|
+
return Object.freeze({dark:false,bg:APP_HUB_PALETTE.bg,white:APP_HUB_PALETTE.white,text:APP_HUB_PALETTE.text,muted:APP_HUB_PALETTE.muted,line:APP_HUB_PALETTE.line,charcoal:APP_HUB_PALETTE.charcoal,ink:brand,fill:identity?APP_HUB_PALETTE.ink:look2.fill,onFill:identity?APP_HUB_PALETTE.white:look2.onFill,accentOnFill:identity?APP_HUB_PALETTE.go:look2.accentOnFill,go:APP_HUB_PALETTE.go,alert:APP_HUB_PALETTE.alert,alertDeep:APP_HUB_PALETTE.alertDeep,yellow:APP_HUB_PALETTE.yellow,tintSage:identity?APP_HUB_PALETTE.tintSage:look2.tintSage,tintPink:identity||!partnerAccentSet(theme)?APP_HUB_PALETTE.tintPink:look2.tintPartner,tintPinkSoft:APP_HUB_PALETTE.tintPinkSoft,tintBlue:APP_HUB_PALETTE.tintBlue,tintYellow:APP_HUB_PALETTE.tintYellow,tintYellowEdge:APP_HUB_PALETTE.tintYellowEdge,tintRed:APP_HUB_PALETTE.tintRed,tintGo:APP_HUB_PALETTE.tintGo,icoGrey:APP_HUB_PALETTE.icoGrey,icoSage:identity?APP_HUB_PALETTE.icoSage:look2.chevron,icoBlue:APP_HUB_PALETTE.icoBlue,barTrack:APP_HUB_PALETTE.barTrack,pillPlainEdge:identity?APP_HUB_PALETTE.pillPlainEdge:look2.plainEdge,chartLine:APP_HUB.chart.lineColor,chartGrid:APP_HUB.chart.gridColor,chartBand:APP_HUB.chart.bandColor,legacyText:APP_HUB_LEGACY.textPrimary,legacyMuted:APP_HUB_LEGACY.textMuted,legacyBorder:APP_HUB_LEGACY.border,brand:identity?APP_HUB_LEGACY.brand:brand,brandSoft:identity?APP_HUB_LEGACY.brandSoft:withAlpha(brand,.1)??look2.tintSage})}var HubContext=react.createContext(null);function buildKit(theme,handFamily){let look2=hubLook(theme),faceOf=key=>key==="hand"?handFamily!==null?{fontFamily:handFamily}:face(theme,"regular"):face(theme,key),cache2=/* @__PURE__ */new Map;return{theme:theme,look:look2,type:name=>{let hit=cache2.get(name);if(hit!==void 0)return hit;let t=APP_HUB_TYPE[name],style={...faceOf(t.face),fontSize:t.size,lineHeight:t.lineHeight,color:look2[t.color],...t.letterSpacing!==0?{letterSpacing:t.letterSpacing}:{},...t.upper===true?{textTransform:"uppercase"}:{}};return cache2.set(name,style),style},face:faceOf}}function HubKitProvider({handFamily:handFamily,theme:override,children:children}){let own=useEverfurTheme(),theme=override??own,kit=react.useMemo(()=>buildKit(theme,handFamily),[theme,handFamily]);/* @__PURE__ */
|
|
795
820
|
return jsxRuntime.jsx(HubContext.Provider,{value:kit,children:children})}function useHub(){let theme=useEverfurTheme(),own=react.useMemo(()=>buildKit(theme,null),[theme]);return react.useContext(HubContext)??own}function HubText({variant:variant="bodySm",color:color,style:style,children:children,...rest}){let{type:type}=useHub();/* @__PURE__ */
|
|
796
|
-
return jsxRuntime.jsx(Text,{tier:variant==="screenTitle"||variant==="cardTitle"?"heading":variant==="button"||variant==="buttonRow"?"control":variant==="pill"||variant==="labelMono"||variant==="chip"?"compact":"content",...rest,style:[type(variant),color!==void 0?{color:color}:null,style],children:children})}var HIDDEN4={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"};function HubIcon({name:name,size:size=24,color:color,style:style}){let{look:
|
|
797
|
-
return jsxRuntime.jsx(reactNative.View,{style:[{width:size,height:size,alignItems:"center",justifyContent:"center"},style],...HIDDEN4,children:glyph})}function HubCard({title:title,titleEnd:titleEnd,style:style,children:children,testID:testID}){let{look:
|
|
798
|
-
return jsxRuntime.jsxs(reactNative.View,{style:[{padding:APP_HUB.card.pad,backgroundColor:
|
|
799
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:title}),titleEnd]}):null,children]})}function HubPill({label:
|
|
800
|
-
return jsxRuntime.jsx(reactNative.View,{testID:testID,style:[{alignSelf:"flex-start",maxWidth:"100%",minHeight:APP_HUB.pill.minHeight,paddingHorizontal:APP_HUB.pill.padX,borderRadius:999,justifyContent:"center",backgroundColor:t.bg},t.edge!==void 0?{borderWidth:t.w,borderColor:t.edge}:null],children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"pill",color:t.fg,numberOfLines:1,children:
|
|
801
|
-
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:onPress===void 0,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??
|
|
802
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:size==="row"?"buttonRow":"button",color:fg,numberOfLines:1,style:[size==="md"&&!isText?{fontSize:APP_HUB.button.mdLabel}:null,variant==="secondary"&&!bold?faceOf("regular"):null],children:
|
|
803
|
-
return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,hitSlop:4,accessibilityRole:"button",accessibilityLabel:
|
|
804
|
-
return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,disabled:disabled,hitSlop:4,accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},style:{width:d,height:d,borderRadius:d/2,alignItems:"center",justifyContent:"center",borderWidth:1.5,borderColor:look.ink,backgroundColor:look.white},testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:18,style:rotate!==0?{transform:[{rotate:`${rotate}deg`}]}:void 0})})}var DAY_MS2=864e5,DUE_SOON_DAYS2=30,WEEKS_WINDOW_DAYS=60,LB_PER_KG2=2.20462,MONTH_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],MONTH_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"],WEEKDAY=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function ms(iso){if(iso==null||iso.trim()==="")return null;let t=Date.parse(iso);return Number.isNaN(t)?null:t}function calendarDay(iso){let t=ms(iso);if(t===null)return null;let at=new Date(t),y=at.getUTCFullYear(),m=at.getUTCMonth(),d=at.getUTCDate();return{y:y,m:m,d:d,ms:Date.UTC(y,m,d)}}function today(nowMs){let n2=new Date(nowMs);return{y:n2.getFullYear(),ms:Date.UTC(n2.getFullYear(),n2.getMonth(),n2.getDate()),weekday:n2.getDay()}}function oneDecimal(value){let r=Math.round(value*10)/10;return Number.isInteger(r)?String(r):r.toFixed(1)}function hubMeta(breed,ageYears,weight){let age=typeof ageYears=="number"&&Number.isFinite(ageYears)&&ageYears>0?hubAge(Math.floor(ageYears*12+1e-9)):null,parts=[breed?.trim()||null,age,weight?.primary??null].filter(p=>p!==null);return parts.length>0?parts.join(" · "):null}var ACRONYMS=/* @__PURE__ */Object.freeze({dhpp:"DHPP",dhlpp:"DHLPP",dhppi:"DHPPi",dapp:"DAPP",dap:"DAP",fvrcp:"FVRCP",felv:"FeLV",fiv:"FIV",hw:"HW",bcs:"BCS","4dx":"4DX"});function humanizeKey(key){return key.split(/[_\s]+/).filter(Boolean).map(w=>ACRONYMS[w.toLowerCase()]??w.charAt(0).toUpperCase()+w.slice(1)).join(" ")}function iconForKey(key){let k=key.toLowerCase();return k.includes("vacc")||k.includes("booster")||k.includes("rabies")||k.includes("dhpp")?"syringe":k.includes("test")||k.includes("screen")||k.includes("fecal")||k.includes("heartworm")||k.includes("worm")?"flask-sm":"calendar"}function hubUpcoming(items,nowMs){let byKey=/* @__PURE__ */new Map;for(let item of items){let key=item.careItemKey?.trim()||item.title,held=byKey.get(key),a=ms(item.dueAt),b=held===void 0?null:ms(held.dueAt);(held===void 0||a!==null&&(b===null||a<b))&&byKey.set(key,item)}let t=today(nowMs);return[...byKey.entries()].map(([key,item])=>{let due=calendarDay(item.dueAt),label=item.careItemKey?.trim()?humanizeKey(item.careItemKey.trim()):item.title;if(due===null)return{at:Number.POSITIVE_INFINITY,row:{key:key,label:label,when:HUB_COPY.noDueDate,tone:"upcoming",icon:iconForKey(key),pill:{label:HUB_COPY.later,tone:"later"}}};let diff=Math.round((ms(item.dueAt)-nowMs)/DAY_MS2),tone=diff<0?"overdue":diff<=DUE_SOON_DAYS2?"dueSoon":"upcoming",relative=diff<0?HUB_COPY.overdueBy(-diff):diff===0?HUB_COPY.dueToday:HUB_COPY.dueIn(diff),shortDue=`${MONTH_SHORT[due.m]} ${due.d}`,days=Math.round((due.ms-t.ms)/DAY_MS2),when;tone==="overdue"||days<0?when=HUB_COPY.withDue(relative,shortDue):days===0?when=relative:days<=6?when=new Date(due.ms).getUTCDay()>t.weekday?HUB_COPY.thisDay(HUB_COPY.dueOn(shortDue),WEEKDAY[new Date(due.ms).getUTCDay()]):HUB_COPY.dueOn(shortDue):days<WEEKS_WINDOW_DAYS?when=HUB_COPY.inWeeks(HUB_COPY.dueOn(shortDue),Math.round(days/7)):when=HUB_COPY.dueOn(due.y===t.y?MONTH_LONG[due.m]:`${MONTH_LONG[due.m]} ${due.y}`);let pill=tone==="dueSoon"?{label:HUB_COPY.dueSoon,tone:"soon"}:tone==="upcoming"?{label:HUB_COPY.later,tone:"later"}:null;return{at:due.ms,row:{key:key,label:label,when:when,tone:tone,icon:iconForKey(key),pill:pill}}}).sort((a,b)=>a.at-b.at).slice(0,APP_HUB.upcoming.maxRows).map(r=>r.row)}function hubTiles(record,markers,depth,timeline){let summaryTotal=markers!==null&&!markers.withheld?markers.summary?.totalMarkers??markers.markers.length:0,labResults=record!==null&&!record.withheld?record.entities.filter(e=>e.category==="lab_result").length:0,labsTotal=summaryTotal+labResults,labsNoun=labResults>0?HUB_COPY.results(labsTotal):HUB_COPY.markers(labsTotal),encounters=depth!==null&&!depth.withheld?depth.encounters:[],visits=timeline!==null&&!timeline.withheld?timeline.visits:[],latest=[...encounters.map(e=>calendarDay(e.date)),...encounters.length>0?[]:visits.map(v=>calendarDay(v.visitDate))].filter(d=>d!==null).sort((a,b)=>b.ms-a.ms)[0]??null,visitDate=latest===null?null:`${String(latest.m+1).padStart(2,"0")}.${String(latest.d).padStart(2,"0")}.${latest.y}`,rails=timeline!==null&&!timeline.withheld?timeline.visits.length+timeline.vaccines.length+timeline.weights.length+timeline.medications.length:0,series=record!==null&&!record.withheld?record.entitySeries.filter(s=>/^(medication|problem)[:|]/.test(s.key)&&s.points.length>0).length:0;return{labsTotal:labsTotal,labsNoun:labsNoun,screeningsPill:null,visitDate:visitDate,timelineCount:rails+series}}function hubWeight(record,timeline,unit){let fromTimeline=timeline!==null&&!timeline.withheld?timeline.weights.filter(w=>w.weightKg!==null&&Number.isFinite(w.weightKg)).map(w=>({kg:w.weightKg,date:w.observedOn})):[],fromRecord=record!==null&&!record.withheld?record.entities.filter(e=>e.category==="body_weight"&&e.value!==null).map(e=>{let v=Number(e.value);return{kg:/lb/i.test(e.unit??"")?v/LB_PER_KG2:v,date:e.observedAt}}).filter(p=>Number.isFinite(p.kg)&&p.kg>0):[],raw=(fromTimeline.length>0?fromTimeline:fromRecord).slice().sort((a,b)=>(ms(a.date)??0)-(ms(b.date)??0));if(raw.length===0)return null;let kgs=raw.map(p=>p.kg),band=null;if(kgs.length>=2){let sorted=kgs.slice().sort((a,b)=>a-b),mid=Math.floor(sorted.length/2),center=sorted.length%2===1?sorted[mid]:(sorted[mid-1]+sorted[mid])/2;center>0&&(band={lowKg:center*(1-APP_HUB.chart.bandPct),highKg:center*(1+APP_HUB.chart.bandPct)})}let points=raw.map(p=>({...p,status:band===null?null:p.kg>band.highKg?"over":p.kg<band.lowKg?"under":"in"})),latest=kgs[kgs.length-1],lb2=`${oneDecimal(latest*LB_PER_KG2)} lb`,kg=`${oneDecimal(latest)} kg`;return{primary:unit==="kg"?kg:lb2,secondary:unit==="kg"?lb2:kg,unit:unit,points:points,band:band}}function kitMonthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}function monthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${d.getUTCFullYear()}`}var clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v));function anchorClampX(x,width,anchor,safeLeft,safeRight){return anchor==="start"?clamp(x,safeLeft,Math.max(safeLeft,safeRight-width)):anchor==="end"?clamp(x,Math.min(safeRight,safeLeft+width),safeRight):clamp(x,safeLeft+width/2,Math.max(safeLeft+width/2,safeRight-width/2))}function pickIndices(count,max){if(count<=0)return[];if(count<=max)return Array.from({length:count},(_,i)=>i);let out=/* @__PURE__ */new Set;for(let i=0;i<max;i+=1)out.add(Math.round(i*(count-1)/(max-1)));return[...out]}var MAX_VALUE_LABELS=8,VALUE_ASCENT_RATIO=.82,VALUE_TOP_PAD=2,AXIS_CHAR_RATIO=.6;function hubChart(weight,width){let G=APP_HUB.chart,plotTop=G.plotTop,plotBottom=G.height-G.axisBand,plotH=plotBottom-plotTop,toShown=kg=>weight.unit==="kg"?kg:kg*LB_PER_KG2,points=weight.points.slice(-36),values=points.map(p=>p.kg),yOf,yBandTop=0,yBandBottom=0,band=weight.band,hasBand=band!==null&&band.highKg>band.lowKg;if(hasBand){let mid=(band.highKg+band.lowKg)/2,half=(band.highKg-band.lowKg)/2,reach=values.reduce((m,v)=>Math.max(m,Math.abs(v-mid)),0),domainHalf=Math.max(half/(G.bandTo-G.bandFrom),reach/G.reach),top=mid+domainHalf;yOf=v=>plotTop+(top-v)/(2*domainHalf)*plotH,yBandTop=yOf(band.highKg),yBandBottom=yOf(band.lowKg)}else{let lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.15;lo-=pad,hi+=pad,yOf=v=>plotBottom-(v-lo)/(hi-lo)*plotH}let dataLeft=hasBand?G.dataLeft:64,plotLeft=hasBand?G.plotLeft:12,dataRight=width-G.rightInset,n2=points.length,colX=i=>n2<=1?(dataLeft+dataRight)/2:dataLeft+i/(n2-1)*(dataRight-dataLeft),labels=points.map(p=>oneDecimal(toShown(p.kg))),maxChars=labels.reduce((m,t)=>Math.max(m,t.length),1),pitch=n2>1?(dataRight-dataLeft)/(n2-1):dataRight-dataLeft,valueFont=clamp(Math.min(G.labelMax,(pitch-G.edgePad)/(maxChars*G.labelCharWidth)),G.labelMin,G.labelMax),dots=points.map((p,i)=>{let x=colX(i),y=yOf(p.kg),label=labels[i],anchor=i===0?"start":i===n2-1?"end":"middle",ascent=valueFont*VALUE_ASCENT_RATIO,maxBaseline=plotBottom-2,below=y+G.dot+G.labelGap+ascent,preferBelow=p.status==="under"&&below<=maxBaseline,labelBaseline=clamp(preferBelow?below:y-G.dot-G.labelGap,VALUE_TOP_PAD+ascent,maxBaseline),labelX=anchorClampX(x,label.length*G.labelCharWidth*valueFont,anchor,G.edgePad,width-G.edgePad);return{x:x,y:y,status:p.status,label:label,labelX:labelX,labelAnchor:anchor,labelBaseline:labelBaseline,spoken:HUB_COPY.pointLabel(monthLabel(p.date),label,weight.unit)}}),months=pickIndices(n2,G.maxTicks).flatMap(i=>{let label=hasBand?kitMonthLabel(points[i].date):monthLabel(points[i].date);if(label===null)return[];let anchor=i===0?"start":i===n2-1?"end":"middle";return[{x:anchorClampX(colX(i),label.length*AXIS_CHAR_RATIO*G.monthSize,anchor,G.edgePad,width-G.edgePad),anchor:anchor,label:label}]}),lineH=G.legendLine,baselines=(lines,top,bottom)=>{let h=lines*lineH,start=clamp((top+bottom)/2-h/2,0,Math.max(0,plotBottom-h));return Array.from({length:lines},(_,i)=>start+i*lineH+lineH/2+G.legendSize*.35)},legend=hasBand?[{zone:"over",lines:HUB_COPY.legendOver,top:plotTop,bottom:yBandTop},{zone:"in",lines:HUB_COPY.legendStable,top:yBandTop,bottom:yBandBottom},{zone:"under",lines:HUB_COPY.legendUnder,top:yBandBottom,bottom:plotBottom}].map(z12=>({zone:z12.zone,lines:z12.lines,baselines:baselines(z12.lines.length,z12.top,z12.bottom)})):[],shown=values.map(toShown),latest=shown[shown.length-1]??0,first=shown[0]??0,trend=latest>first?"rising":latest<first?"falling":"steady",summary=HUB_COPY.trendSummary(shown.length,oneDecimal(latest),trend,hasBand?oneDecimal(toShown(band.lowKg)):null,hasBand?oneDecimal(toShown(band.highKg)):null);return{width:width,hasBand:hasBand,yBandTop:yBandTop,yBandBottom:yBandBottom,plotTop:plotTop,plotBottom:plotBottom,plotLeft:plotLeft,dataRight:dataRight,cols:points.map((_,i)=>colX(i)),dots:dots,showValues:n2<=MAX_VALUE_LABELS,valueFont:valueFont,months:months,legend:legend,summary:summary}}function hubOnFile(record){if(record===null||record.withheld)return[];let bySource=/* @__PURE__ */new Map;for(let doc of Object.values(record.documents)){let name=documentTitle(doc),entry=bySource.get(name)??{pages:0,latest:null};entry.pages+=doc.pageCount!==null&&doc.pageCount>0?doc.pageCount:0,doc.receivedAt!==null&&ms(doc.receivedAt)!==null&&(entry.latest===null||doc.receivedAt>entry.latest)&&(entry.latest=doc.receivedAt),bySource.set(name,entry)}return[...bySource.entries()].sort(([,a],[,b])=>(a.latest??"").localeCompare(b.latest??"")).map(([name,e])=>{let day=e.latest!==null?new Date(ms(e.latest)):null,parts=[e.pages>0?HUB_COPY.pages(e.pages):null,day!==null?`${MONTH_SHORT[day.getMonth()]} ${day.getDate()}`:null].filter(p=>p!==null);return{key:name,name:name,meta:parts.length>0?parts.join(" · "):null}})}function recordsDate(iso){let t=ms(iso);if(t===null)return null;let d=new Date(t);return`${MONTH_SHORT[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`}var VERSION=typeof __EVERFUR_SDK_VERSION__=="string"&&__EVERFUR_SDK_VERSION__.length>0?__EVERFUR_SDK_VERSION__:SDK_VERSION,ORIGIN=typeof __EVERFUR_CDN_ORIGIN__=="string"&&__EVERFUR_CDN_ORIGIN__.length>0?__EVERFUR_CDN_ORIGIN__:"https://sdk.everfur.com",RECORDS_GRASS_URL=`${ORIGIN}/${VERSION}/assets/grass.webp`;var RECORDS_GRASS_SOURCE=/* @__PURE__ */Object.freeze({uri:RECORDS_GRASS_URL}),easeOut=null,EASE_OUT=t=>(easeOut??=reactNative.Easing.bezier(.23,1,.32,1))(t);function useHeroSettle(grassHeight,reduced){let start=reduced?1:0,petFade=react.useRef(new reactNative.Animated.Value(start)).current,petRise=react.useRef(new reactNative.Animated.Value(start)).current,grassGrow=react.useRef(new reactNative.Animated.Value(start)).current,grassFade=react.useRef(new reactNative.Animated.Value(start)).current,played=react.useRef(reduced);react.useEffect(()=>{if(reduced){for(let v of[petFade,petRise,grassGrow,grassFade])v.setValue(1);return}if(played.current)return;played.current=true;let timing=(v,duration,delay=0)=>reactNative.Animated.timing(v,{toValue:1,duration:duration,delay:delay,easing:EASE_OUT,useNativeDriver:true}),run=reactNative.Animated.parallel([timing(petFade,400,60),timing(petRise,700,60),timing(grassGrow,820),timing(grassFade,360)]);return run.start(),()=>run.stop()},[reduced,petFade,petRise,grassGrow,grassFade]);let refs=react.useRef(null);if(refs.current===null||refs.current.pet.opacity!==petFade){let scale=grassGrow.interpolate({inputRange:[0,1],outputRange:[.35,1]}),drop=grassGrow.interpolate({inputRange:[0,1],outputRange:[grassHeight*.65/2,0]});refs.current={pet:{opacity:petFade,transform:[{translateY:petRise.interpolate({inputRange:[0,1],outputRange:[16,0]})}]},grass:{opacity:grassFade,transform:[{translateY:drop},{scaleY:scale}]}}}return refs.current}function RiseIn({index:index,reduced:reduced,children:children}){let p=react.useRef(new reactNative.Animated.Value(reduced?1:0)).current;return react.useEffect(()=>{if(reduced){p.setValue(1);return}let run=reactNative.Animated.timing(p,{toValue:1,duration:400,delay:index*60,easing:EASE_OUT,useNativeDriver:true});return run.start(),()=>run.stop()},[reduced,index,p]),/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:{opacity:p,transform:[{translateY:p.interpolate({inputRange:[0,1],outputRange:[8,0]})}]},children:children})}function HubPetArt({art:art,onError:onError,reduced:reduced}){return art.status!=="art"?null:/* @__PURE__ */jsxRuntime.jsx(PetImage,{url:art.url,onError:onError,reduced:reduced},art.key)}function PetImage({url:url,onError:onError,reduced:reduced}){let opacity=react.useRef(new reactNative.Animated.Value(0)).current,onLoad=()=>{if(reduced){opacity.setValue(1);return}reactNative.Animated.timing(opacity,{toValue:1,duration:200,easing:EASE_OUT,useNativeDriver:true}).start()};/* @__PURE__ */
|
|
821
|
+
return jsxRuntime.jsx(Text,{tier:variant==="screenTitle"||variant==="cardTitle"?"heading":variant==="button"||variant==="buttonRow"?"control":variant==="pill"||variant==="labelMono"||variant==="chip"?"compact":"content",...rest,style:[type(variant),color!==void 0?{color:color}:null,style],children:children})}var HIDDEN4={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"};function HubIcon({name:name,size:size=24,color:color,style:style}){let{look:look2}=useHub(),c=color??look2.ink,glyph;switch(name){case"flask":glyph=/* @__PURE__ */jsxRuntime.jsx(FlaskGlyph,{size:size,color:c});break;case"flask-sm":glyph=/* @__PURE__ */jsxRuntime.jsx(FlaskGlyph,{size:size,color:c});break;case"syringe":glyph=/* @__PURE__ */jsxRuntime.jsx(SyringeGlyph,{size:size,color:c});break;case"calendar":glyph=/* @__PURE__ */jsxRuntime.jsx(CalendarGlyph,{size:size,color:c});break;case"shield":glyph=/* @__PURE__ */jsxRuntime.jsx(ShieldGlyph,{size:size,color:c});break;case"folder":glyph=/* @__PURE__ */jsxRuntime.jsx(FolderGlyph,{size:size,color:c});break;case"clock":glyph=/* @__PURE__ */jsxRuntime.jsx(ClockFaceGlyph,{size:size,color:c});break;case"clip":glyph=/* @__PURE__ */jsxRuntime.jsx(ClipboardGlyph,{size:size,color:c});break;case"download":glyph=/* @__PURE__ */jsxRuntime.jsx(DownloadGlyph2,{size:size,color:c});break;case"upload":glyph=/* @__PURE__ */jsxRuntime.jsx(UploadArrowGlyph,{size:size,color:c});break;case"thermo":glyph=/* @__PURE__ */jsxRuntime.jsx(ThermoGlyph,{size:size,color:c});break;case"heart":glyph=/* @__PURE__ */jsxRuntime.jsx(HeartGlyph,{size:size,color:c});break;case"wind":glyph=/* @__PURE__ */jsxRuntime.jsx(WindGlyph,{size:size,color:c});break;case"file":glyph=/* @__PURE__ */jsxRuntime.jsx(FileGlyph,{size:size,color:c});break;case"check":glyph=/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:size,color:c});break;case"chevron":glyph=/* @__PURE__ */jsxRuntime.jsx(ChevronGlyph,{size:size,color:c,direction:"right"});break;default:glyph=null}/* @__PURE__ */
|
|
822
|
+
return jsxRuntime.jsx(reactNative.View,{style:[{width:size,height:size,alignItems:"center",justifyContent:"center"},style],...HIDDEN4,children:glyph})}function HubCard({title:title,titleEnd:titleEnd,style:style,children:children,testID:testID}){let{look:look2}=useHub();/* @__PURE__ */
|
|
823
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{padding:APP_HUB.card.pad,backgroundColor:look2.white,borderWidth:APP_HUB.card.border,borderColor:look2.line,borderRadius:APP_HUB.card.radius},style],testID:testID,children:[title!==void 0?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",gap:APP_HUB.card.headGap,marginBottom:APP_HUB.card.headBottom},children:[
|
|
824
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:title}),titleEnd]}):null,children]})}function HubPill({label:label2,tone:tone="plain",testID:testID}){let{look:look2}=useHub(),t={stable:{bg:look2.tintGo,fg:look2.ink},overdue:{bg:look2.white,fg:look2.alert,edge:look2.alert,w:APP_HUB.pill.edgeThin},soon:{bg:look2.white,fg:look2.ink,edge:look2.tintYellowEdge,w:APP_HUB.pill.edgeThin},later:{bg:look2.white,fg:look2.muted,edge:look2.line,w:APP_HUB.pill.edgeThin},clear:{bg:look2.white,fg:look2.go,edge:look2.go,w:APP_HUB.pill.edgeThick},plain:{bg:look2.white,fg:look2.ink,edge:look2.pillPlainEdge,w:APP_HUB.pill.edgeThick},high:{bg:look2.white,fg:look2.alert,edge:look2.alert,w:APP_HUB.pill.edgeThin}}[tone];/* @__PURE__ */
|
|
825
|
+
return jsxRuntime.jsx(reactNative.View,{testID:testID,style:[{alignSelf:"flex-start",maxWidth:"100%",minHeight:APP_HUB.pill.minHeight,paddingHorizontal:APP_HUB.pill.padX,borderRadius:999,justifyContent:"center",backgroundColor:t.bg},t.edge!==void 0?{borderWidth:t.w,borderColor:t.edge}:null],children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"pill",color:t.fg,numberOfLines:1,children:label2})})}function HubButton({label:label2,onPress:onPress,variant:variant="primary",size:size="md",icon:icon,block:block=false,bold:bold=false,style:style,accessibilityLabel:accessibilityLabel,accessibilityHint:accessibilityHint,testID:testID}){let{look:look2,face:faceOf}=useHub(),isText=variant==="text",fg=variant==="primary"?look2.onFill:look2.ink,h=size==="md"?APP_HUB.button.md:size==="sm"?APP_HUB.button.sm:APP_HUB.button.row,padX=size==="md"?APP_HUB.button.padMd:size==="sm"?APP_HUB.button.padSm:APP_HUB.button.padRow,iconSize=size==="row"?APP_HUB.button.iconRow:size==="sm"?APP_HUB.button.iconSm:APP_HUB.button.iconMd,box3=isText?{flexDirection:"row",alignItems:"center",gap:APP_HUB.button.textGap,minHeight:APP_HUB.button.textMinHeight}:[{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:APP_HUB.button.gap,borderRadius:999,minHeight:h,paddingHorizontal:padX},variant==="primary"?{backgroundColor:look2.fill,borderWidth:APP_HUB.button.edge,borderColor:look2.white}:{backgroundColor:"transparent",borderWidth:APP_HUB.button.edge,borderColor:look2.ink}];/* @__PURE__ */
|
|
826
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,disabled:onPress===void 0,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label2,...accessibilityHint!==void 0?{accessibilityHint:accessibilityHint}:{},hitSlop:size==="row"||isText?4:void 0,style:[block?{alignSelf:"stretch"}:null,box3,style],testID:testID,children:[icon!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:iconSize,color:fg}):null,
|
|
827
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:size==="row"?"buttonRow":"button",color:fg,numberOfLines:1,style:[size==="md"&&!isText?{fontSize:APP_HUB.button.mdLabel}:null,variant==="secondary"&&!bold?faceOf("regular"):null],children:label2})]})}function HubChip({label:label2,selected:selected,onPress:onPress,testID:testID}){let{look:look2}=useHub();/* @__PURE__ */
|
|
828
|
+
return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,hitSlop:4,accessibilityRole:"button",accessibilityLabel:label2,accessibilityState:{selected:selected},style:{flexDirection:"row",alignItems:"center",gap:6,borderRadius:999,minHeight:APP_HUB.peek.chipHeight,paddingHorizontal:APP_HUB.peek.chipPadX,borderWidth:1.5,borderColor:selected?look2.fill:look2.line,backgroundColor:selected?look2.fill:look2.white},testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"chip",color:selected?look2.onFill:look2.ink,numberOfLines:1,children:label2})})}function HubRound({icon:icon,rotate:rotate=0,label:label2,disabled:disabled,onPress:onPress,testID:testID}){let{look:look2}=useHub(),d=APP_HUB.peek.roundButton;/* @__PURE__ */
|
|
829
|
+
return jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,disabled:disabled,hitSlop:4,accessibilityRole:"button",accessibilityLabel:label2,accessibilityState:{disabled:disabled},style:{width:d,height:d,borderRadius:d/2,alignItems:"center",justifyContent:"center",borderWidth:1.5,borderColor:look2.ink,backgroundColor:look2.white},testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:18,style:rotate!==0?{transform:[{rotate:`${rotate}deg`}]}:void 0})})}var DAY_MS2=864e5,DUE_SOON_DAYS2=30,WEEKS_WINDOW_DAYS=60,LB_PER_KG2=2.20462,MONTH_SHORT=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],MONTH_LONG=["January","February","March","April","May","June","July","August","September","October","November","December"],WEEKDAY=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function ms(iso){if(iso==null||iso.trim()==="")return null;let t=Date.parse(iso);return Number.isNaN(t)?null:t}function calendarDay(iso){let t=ms(iso);if(t===null)return null;let at=new Date(t),y=at.getUTCFullYear(),m=at.getUTCMonth(),d=at.getUTCDate();return{y:y,m:m,d:d,ms:Date.UTC(y,m,d)}}function today(nowMs){let n2=new Date(nowMs);return{y:n2.getFullYear(),ms:Date.UTC(n2.getFullYear(),n2.getMonth(),n2.getDate()),weekday:n2.getDay()}}function oneDecimal(value){let r=Math.round(value*10)/10;return Number.isInteger(r)?String(r):r.toFixed(1)}function hubMeta(breed,ageYears,weight){let age=typeof ageYears=="number"&&Number.isFinite(ageYears)&&ageYears>0?hubAge(Math.floor(ageYears*12+1e-9)):null,parts=[breed?.trim()||null,age,weight?.primary??null].filter(p=>p!==null);return parts.length>0?parts.join(" · "):null}var ACRONYMS=/* @__PURE__ */Object.freeze({dhpp:"DHPP",dhlpp:"DHLPP",dhppi:"DHPPi",dapp:"DAPP",dap:"DAP",fvrcp:"FVRCP",felv:"FeLV",fiv:"FIV",hw:"HW",bcs:"BCS","4dx":"4DX"});function humanizeKey(key){return key.split(/[_\s]+/).filter(Boolean).map(w=>ACRONYMS[w.toLowerCase()]??w.charAt(0).toUpperCase()+w.slice(1)).join(" ")}function iconForKey(key){let k=key.toLowerCase();return k.includes("vacc")||k.includes("booster")||k.includes("rabies")||k.includes("dhpp")?"syringe":k.includes("test")||k.includes("screen")||k.includes("fecal")||k.includes("heartworm")||k.includes("worm")?"flask-sm":"calendar"}function hubUpcoming(items,nowMs){let byKey=/* @__PURE__ */new Map;for(let item of items){let key=item.careItemKey?.trim()||item.title,held=byKey.get(key),a=ms(item.dueAt),b=held===void 0?null:ms(held.dueAt);(held===void 0||a!==null&&(b===null||a<b))&&byKey.set(key,item)}let t=today(nowMs);return[...byKey.entries()].map(([key,item])=>{let due=calendarDay(item.dueAt),label2=item.careItemKey?.trim()?humanizeKey(item.careItemKey.trim()):item.title;if(due===null)return{at:Number.POSITIVE_INFINITY,row:{key:key,label:label2,when:HUB_COPY.noDueDate,tone:"upcoming",icon:iconForKey(key),pill:{label:HUB_COPY.later,tone:"later"}}};let diff=Math.round((ms(item.dueAt)-nowMs)/DAY_MS2),tone=diff<0?"overdue":diff<=DUE_SOON_DAYS2?"dueSoon":"upcoming",relative=diff<0?HUB_COPY.overdueBy(-diff):diff===0?HUB_COPY.dueToday:HUB_COPY.dueIn(diff),shortDue=`${MONTH_SHORT[due.m]} ${due.d}`,days=Math.round((due.ms-t.ms)/DAY_MS2),when;tone==="overdue"||days<0?when=HUB_COPY.withDue(relative,shortDue):days===0?when=relative:days<=6?when=new Date(due.ms).getUTCDay()>t.weekday?HUB_COPY.thisDay(HUB_COPY.dueOn(shortDue),WEEKDAY[new Date(due.ms).getUTCDay()]):HUB_COPY.dueOn(shortDue):days<WEEKS_WINDOW_DAYS?when=HUB_COPY.inWeeks(HUB_COPY.dueOn(shortDue),Math.round(days/7)):when=HUB_COPY.dueOn(due.y===t.y?MONTH_LONG[due.m]:`${MONTH_LONG[due.m]} ${due.y}`);let pill=tone==="dueSoon"?{label:HUB_COPY.dueSoon,tone:"soon"}:tone==="upcoming"?{label:HUB_COPY.later,tone:"later"}:null;return{at:due.ms,row:{key:key,label:label2,when:when,tone:tone,icon:iconForKey(key),pill:pill}}}).sort((a,b)=>a.at-b.at).slice(0,APP_HUB.upcoming.maxRows).map(r=>r.row)}function hubTiles(record,markers,depth,timeline){let readable=markers!==null&&!markers.withheld,labsTotal=readable?markers.summary?.totalMarkers??markers.markers.length:0,labsNoun=HEALTH_TAB_SHARED_COPY.results(labsTotal),rollup=healthTabScreenings(readable?markers.markers:[]),screeningsPill=rollup!==null?{label:rollup.label,tone:rollup.flagged?"high":"clear",markerId:rollup.markerId}:null,encounters=depth!==null&&!depth.withheld?depth.encounters:[],visits=timeline!==null&&!timeline.withheld?timeline.visits:[],latest=[...encounters.map(e=>calendarDay(e.date)),...encounters.length>0?[]:visits.map(v=>calendarDay(v.visitDate))].filter(d=>d!==null).sort((a,b)=>b.ms-a.ms)[0]??null,visitDate=latest===null?null:`${String(latest.m+1).padStart(2,"0")}.${String(latest.d).padStart(2,"0")}.${latest.y}`,rails=timeline!==null&&!timeline.withheld?timeline.visits.length+timeline.vaccines.length+timeline.weights.length+timeline.medications.length:0,series=record!==null&&!record.withheld?record.entitySeries.filter(s=>/^(medication|problem)[:|]/.test(s.key)&&s.points.length>0).length:0;return{labsTotal:labsTotal,labsNoun:labsNoun,screeningsPill:screeningsPill,visitDate:visitDate,timelineCount:rails+series}}function hubWeight(record,timeline,unit){let fromTimeline=timeline!==null&&!timeline.withheld?timeline.weights.filter(w=>w.weightKg!==null&&Number.isFinite(w.weightKg)).map(w=>({kg:w.weightKg,date:w.observedOn})):[],fromRecord=record!==null&&!record.withheld?record.entities.filter(e=>e.category==="body_weight"&&e.value!==null).map(e=>{let v=Number(e.value);return{kg:/lb/i.test(e.unit??"")?v/LB_PER_KG2:v,date:e.observedAt}}).filter(p=>Number.isFinite(p.kg)&&p.kg>0):[],raw=(fromTimeline.length>0?fromTimeline:fromRecord).slice().sort((a,b)=>(ms(a.date)??0)-(ms(b.date)??0));if(raw.length===0)return null;let kgs=raw.map(p=>p.kg),band=null;if(kgs.length>=2){let sorted=kgs.slice().sort((a,b)=>a-b),mid=Math.floor(sorted.length/2),center=sorted.length%2===1?sorted[mid]:(sorted[mid-1]+sorted[mid])/2;center>0&&(band={lowKg:center*(1-APP_HUB.chart.bandPct),highKg:center*(1+APP_HUB.chart.bandPct)})}let points=raw.map(p=>({...p,status:band===null?null:p.kg>band.highKg?"over":p.kg<band.lowKg?"under":"in"})),latest=kgs[kgs.length-1],lb2=`${oneDecimal(latest*LB_PER_KG2)} lb`,kg=`${oneDecimal(latest)} kg`,only=raw.length===1?dayMs(raw[0].date):null;return{primary:unit==="kg"?kg:lb2,secondary:unit==="kg"?lb2:kg,unit:unit,points:points,band:band,date:only!==null?healthTabDate(only):null}}function kitMonthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${String(d.getUTCFullYear()%100).padStart(2,"0")}`}function monthLabel(date2){let t=ms(date2);if(t===null)return null;let d=new Date(t);return`${d.getUTCMonth()+1}/${d.getUTCFullYear()}`}var clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v));function anchorClampX(x,width,anchor,safeLeft,safeRight){return anchor==="start"?clamp(x,safeLeft,Math.max(safeLeft,safeRight-width)):anchor==="end"?clamp(x,Math.min(safeRight,safeLeft+width),safeRight):clamp(x,safeLeft+width/2,Math.max(safeLeft+width/2,safeRight-width/2))}function pickIndices(count,max){if(count<=0)return[];if(count<=max)return Array.from({length:count},(_,i)=>i);let out=/* @__PURE__ */new Set;for(let i=0;i<max;i+=1)out.add(Math.round(i*(count-1)/(max-1)));return[...out]}var MAX_VALUE_LABELS=8,VALUE_ASCENT_RATIO=.82,VALUE_TOP_PAD=2,AXIS_CHAR_RATIO=.6;function hubChart(weight,width){let G=APP_HUB.chart,plotTop=G.plotTop,plotBottom=G.height-G.axisBand,plotH=plotBottom-plotTop,toShown=kg=>weight.unit==="kg"?kg:kg*LB_PER_KG2,points=weight.points.slice(-36),values=points.map(p=>p.kg),yOf,yBandTop=0,yBandBottom=0,band=weight.band,hasBand=band!==null&&band.highKg>band.lowKg;if(hasBand){let mid=(band.highKg+band.lowKg)/2,half=(band.highKg-band.lowKg)/2,reach=values.reduce((m,v)=>Math.max(m,Math.abs(v-mid)),0),domainHalf=Math.max(half/(G.bandTo-G.bandFrom),reach/G.reach),top=mid+domainHalf;yOf=v=>plotTop+(top-v)/(2*domainHalf)*plotH,yBandTop=yOf(band.highKg),yBandBottom=yOf(band.lowKg)}else{let lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.15;lo-=pad,hi+=pad,yOf=v=>plotBottom-(v-lo)/(hi-lo)*plotH}let dataLeft=hasBand?G.dataLeft:64,plotLeft=hasBand?G.plotLeft:12,dataRight=width-G.rightInset,n2=points.length,colX=i=>n2<=1?(dataLeft+dataRight)/2:dataLeft+i/(n2-1)*(dataRight-dataLeft),labels=points.map(p=>oneDecimal(toShown(p.kg))),maxChars=labels.reduce((m,t)=>Math.max(m,t.length),1),pitch=n2>1?(dataRight-dataLeft)/(n2-1):dataRight-dataLeft,valueFont=clamp(Math.min(G.labelMax,(pitch-G.edgePad)/(maxChars*G.labelCharWidth)),G.labelMin,G.labelMax),dots=points.map((p,i)=>{let x=colX(i),y=yOf(p.kg),label2=labels[i],anchor=i===0?"start":i===n2-1?"end":"middle",ascent=valueFont*VALUE_ASCENT_RATIO,maxBaseline=plotBottom-2,below=y+G.dot+G.labelGap+ascent,preferBelow=p.status==="under"&&below<=maxBaseline,labelBaseline=clamp(preferBelow?below:y-G.dot-G.labelGap,VALUE_TOP_PAD+ascent,maxBaseline),labelX=anchorClampX(x,label2.length*G.labelCharWidth*valueFont,anchor,G.edgePad,width-G.edgePad);return{x:x,y:y,status:p.status,label:label2,labelX:labelX,labelAnchor:anchor,labelBaseline:labelBaseline,spoken:HUB_COPY.pointLabel(monthLabel(p.date),label2,weight.unit)}}),months=pickIndices(n2,G.maxTicks).flatMap(i=>{let label2=hasBand?kitMonthLabel(points[i].date):monthLabel(points[i].date);if(label2===null)return[];let anchor=i===0?"start":i===n2-1?"end":"middle";return[{x:anchorClampX(colX(i),label2.length*AXIS_CHAR_RATIO*G.monthSize,anchor,G.edgePad,width-G.edgePad),anchor:anchor,label:label2}]}),lineH=G.legendLine,baselines=(lines,top,bottom)=>{let h=lines*lineH,start=clamp((top+bottom)/2-h/2,0,Math.max(0,plotBottom-h));return Array.from({length:lines},(_,i)=>start+i*lineH+lineH/2+G.legendSize*.35)},legend=hasBand?[{zone:"over",lines:HUB_COPY.legendOver,top:plotTop,bottom:yBandTop},{zone:"in",lines:HUB_COPY.legendStable,top:yBandTop,bottom:yBandBottom},{zone:"under",lines:HUB_COPY.legendUnder,top:yBandBottom,bottom:plotBottom}].map(z12=>({zone:z12.zone,lines:z12.lines,baselines:baselines(z12.lines.length,z12.top,z12.bottom)})):[],shown=values.map(toShown),latest=shown[shown.length-1]??0,first=shown[0]??0,trend=latest>first?"rising":latest<first?"falling":"steady",summary=HUB_COPY.trendSummary(shown.length,oneDecimal(latest),trend,hasBand?oneDecimal(toShown(band.lowKg)):null,hasBand?oneDecimal(toShown(band.highKg)):null);return{width:width,hasBand:hasBand,yBandTop:yBandTop,yBandBottom:yBandBottom,plotTop:plotTop,plotBottom:plotBottom,plotLeft:plotLeft,dataRight:dataRight,cols:points.map((_,i)=>colX(i)),dots:dots,showValues:n2<=MAX_VALUE_LABELS,valueFont:valueFont,months:months,legend:legend,summary:summary}}function hubOnFile(record,depth){return healthTabSources(record,depth).map(src=>({key:src.key,name:src.name,meta:src.meta.length>0?src.meta:null}))}function recordsDate(iso){let t=ms(iso);if(t===null)return null;let d=new Date(t);return`${MONTH_SHORT[d.getMonth()]} ${d.getDate()}, ${d.getFullYear()}`}var VERSION=typeof __EVERFUR_SDK_VERSION__=="string"&&__EVERFUR_SDK_VERSION__.length>0?__EVERFUR_SDK_VERSION__:SDK_VERSION,ORIGIN=typeof __EVERFUR_CDN_ORIGIN__=="string"&&__EVERFUR_CDN_ORIGIN__.length>0?__EVERFUR_CDN_ORIGIN__:"https://sdk.everfur.com",RECORDS_GRASS_URL=`${ORIGIN}/${VERSION}/assets/grass.webp`;var RECORDS_GRASS_SOURCE=/* @__PURE__ */Object.freeze({uri:RECORDS_GRASS_URL}),easeOut=null,EASE_OUT=t=>(easeOut??=reactNative.Easing.bezier(.23,1,.32,1))(t);function useHeroSettle(grassHeight,reduced){let start=reduced?1:0,petFade=react.useRef(new reactNative.Animated.Value(start)).current,petRise=react.useRef(new reactNative.Animated.Value(start)).current,grassGrow=react.useRef(new reactNative.Animated.Value(start)).current,grassFade=react.useRef(new reactNative.Animated.Value(start)).current,played=react.useRef(reduced);react.useEffect(()=>{if(reduced){for(let v of[petFade,petRise,grassGrow,grassFade])v.setValue(1);return}if(played.current)return;played.current=true;let timing=(v,duration,delay=0)=>reactNative.Animated.timing(v,{toValue:1,duration:duration,delay:delay,easing:EASE_OUT,useNativeDriver:true}),run=reactNative.Animated.parallel([timing(petFade,400,60),timing(petRise,700,60),timing(grassGrow,820),timing(grassFade,360)]);return run.start(),()=>run.stop()},[reduced,petFade,petRise,grassGrow,grassFade]);let refs=react.useRef(null);if(refs.current===null||refs.current.pet.opacity!==petFade){let scale=grassGrow.interpolate({inputRange:[0,1],outputRange:[.35,1]}),drop=grassGrow.interpolate({inputRange:[0,1],outputRange:[grassHeight*.65/2,0]});refs.current={pet:{opacity:petFade,transform:[{translateY:petRise.interpolate({inputRange:[0,1],outputRange:[16,0]})}]},grass:{opacity:grassFade,transform:[{translateY:drop},{scaleY:scale}]}}}return refs.current}function RiseIn({index:index,reduced:reduced,children:children}){let p=react.useRef(new reactNative.Animated.Value(reduced?1:0)).current;return react.useEffect(()=>{if(reduced){p.setValue(1);return}let run=reactNative.Animated.timing(p,{toValue:1,duration:400,delay:index*60,easing:EASE_OUT,useNativeDriver:true});return run.start(),()=>run.stop()},[reduced,index,p]),/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:{opacity:p,transform:[{translateY:p.interpolate({inputRange:[0,1],outputRange:[8,0]})}]},children:children})}function HubPetArt({art:art,onError:onError,reduced:reduced}){return art.status!=="art"?null:/* @__PURE__ */jsxRuntime.jsx(PetImage,{url:art.url,onError:onError,reduced:reduced},art.key)}function PetImage({url:url,onError:onError,reduced:reduced}){let opacity=react.useRef(new reactNative.Animated.Value(0)).current,onLoad=()=>{if(reduced){opacity.setValue(1);return}reactNative.Animated.timing(opacity,{toValue:1,duration:200,easing:EASE_OUT,useNativeDriver:true}).start()};/* @__PURE__ */
|
|
805
830
|
return jsxRuntime.jsx(reactNative.View,{style:{width:"100%",height:"100%"},testID:"everfur-records-sheet-pet-art",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.Image,{source:{uri:url},onLoad:onLoad,onError:onError,resizeMode:"contain",style:{width:"100%",height:"100%",opacity:opacity}})})}var HUB_MOTION=/* @__PURE__ */Object.freeze({reveal:480,revealFade:320,revealStagger:60,revealMaxSteps:8,revealRiseBlock:14,rollDigits:900,rollDigitStagger:55,chartDraw:850,slideTravel:48,slideMs:320}),easeOut2=null,HUB_EASE_OUT=t=>(easeOut2??=reactNative.Easing.bezier(.23,1,.32,1))(t);function hubRevealDelay(index){return Math.min(Math.max(0,index),HUB_MOTION.revealMaxSteps-1)*HUB_MOTION.revealStagger}function HubReveal({index:index,reduced:reduced,style:style,testID:testID,children:children}){let rise=react.useRef(new reactNative.Animated.Value(reduced?1:0)).current,fade=react.useRef(new reactNative.Animated.Value(reduced?1:0)).current,played=react.useRef(reduced);react.useEffect(()=>{if(reduced){rise.setValue(1),fade.setValue(1);return}if(played.current)return;let delay=hubRevealDelay(index),run=reactNative.Animated.parallel([reactNative.Animated.timing(rise,{toValue:1,duration:HUB_MOTION.reveal,delay:delay,easing:HUB_EASE_OUT,useNativeDriver:true}),reactNative.Animated.timing(fade,{toValue:1,duration:HUB_MOTION.revealFade,delay:delay,easing:HUB_EASE_OUT,useNativeDriver:true})]);return run.start(({finished:finished})=>{finished&&(played.current=true)}),()=>run.stop()},[reduced,index,rise,fade]);let moving={opacity:fade,transform:[{translateY:rise.interpolate({inputRange:[0,1],outputRange:[HUB_MOTION.revealRiseBlock,0]})}]};/* @__PURE__ */
|
|
806
831
|
return jsxRuntime.jsx(reactNative.Animated.View,{style:[style,moving],testID:testID,children:children})}function useHubDraw(ready,reduced){let p=react.useRef(new reactNative.Animated.Value(reduced?1:0)).current,played=react.useRef(reduced);return react.useEffect(()=>{if(reduced){p.setValue(1);return}if(!ready||played.current)return;let run=reactNative.Animated.timing(p,{toValue:1,duration:HUB_MOTION.chartDraw,easing:HUB_EASE_OUT,useNativeDriver:true});return run.start(({finished:finished})=>{finished&&(played.current=true)}),()=>run.stop()},[ready,reduced,p]),p}function hubSegmentSpans(points){let lengths=points.slice(1).map((b,i)=>Math.hypot(b.x-points[i].x,b.y-points[i].y)),total=lengths.reduce((a,b)=>a+b,0),at=0;return lengths.map(len=>{let from=total>0?at/total:0;return at+=len,[from,total>0?at/total:1]})}function hubSegmentDraw(p,span,length){let[from,to]=span,end=to>from?to:from+1e-4,scaleX=p.interpolate({inputRange:[from,end],outputRange:[1e-4,1],extrapolate:"clamp"});return{translateX:p.interpolate({inputRange:[from,end],outputRange:[-length/2,0],extrapolate:"clamp"}),scaleX:scaleX}}function hubDotAt(spans,i){return i<=0?0:spans[i-1]?.[1]??1}function hubDotShown(p,at){return p.interpolate({inputRange:[at-.0011,at-.001],outputRange:[0,1],extrapolate:"clamp"})}function useHubSlideStep(index,reduced){let prev=react.useRef(index),x=react.useRef(new reactNative.Animated.Value(0)).current,o=react.useRef(new reactNative.Animated.Value(1)).current;return react.useEffect(()=>{let dir=Math.sign(index-prev.current);if(prev.current=index,dir===0||reduced)return;x.setValue(dir*HUB_MOTION.slideTravel),o.setValue(0);let run=reactNative.Animated.parallel([reactNative.Animated.timing(x,{toValue:0,duration:HUB_MOTION.slideMs,easing:HUB_EASE_OUT,useNativeDriver:true}),reactNative.Animated.timing(o,{toValue:1,duration:HUB_MOTION.slideMs,easing:HUB_EASE_OUT,useNativeDriver:true})]);return run.start(),()=>run.stop()},[index,reduced,x,o]),react.useRef({opacity:o,transform:[{translateX:x}]}).current}function hubRollPlan(text4){return Array.from(text4,char=>({char:char,digit:/\d/.test(char)?Number(char):null}))}function hubRollEase(x){let t=Math.min(1,Math.max(0,x));return 1-Math.pow(1-t,3)}function HubRollingDigits({text:text4,reduced:reduced,renderText:renderText,testID:testID}){let[rolling,setRolling]=react.useState(()=>!reduced&&/\d/.test(text4)),first=react.useRef(text4);return react.useEffect(()=>{first.current!==text4&&setRolling(false)},[text4]),react.useEffect(()=>{reduced&&setRolling(false)},[reduced]),rolling?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"text",accessibilityLabel:text4,children:[
|
|
807
832
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{opacity:0},importantForAccessibility:"no-hide-descendants",accessibilityElementsHidden:true,children:renderText(text4,testID!==void 0?{testID:testID}:{})}),
|
|
808
833
|
/* @__PURE__ */jsxRuntime.jsx(RollOverlay,{text:text4,renderText:renderText,onDone:()=>setRolling(false)})]}):renderText(text4,testID!==void 0?{testID:testID}:{})}function RollOverlay({text:text4,renderText:renderText,onDone:onDone}){let plan=hubRollPlan(text4),digits=plan.filter(c=>c.digit!==null).length,total=HUB_MOTION.rollDigits+Math.max(0,digits-1)*HUB_MOTION.rollDigitStagger,t=react.useRef(new reactNative.Animated.Value(0)).current,done=react.useRef(onDone);done.current=onDone,react.useEffect(()=>{let run=reactNative.Animated.timing(t,{toValue:total,duration:total,easing:reactNative.Easing.linear,useNativeDriver:true});return run.start(({finished:finished})=>{finished&&done.current()}),()=>run.stop()},[t,total]);let order=-1;/* @__PURE__ */
|
|
809
834
|
return jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:0,right:0,bottom:0,flexDirection:"row",alignItems:"flex-end"},pointerEvents:"none",importantForAccessibility:"no-hide-descendants",accessibilityElementsHidden:true,children:plan.map((cell,i)=>cell.digit===null?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:renderText(cell.char)},i):(order+=1,/* @__PURE__ */jsxRuntime.jsx(RollCell,{cell:cell,t:t,delay:order*HUB_MOTION.rollDigitStagger,renderText:renderText},i)))})}var DIGITS=[0,1,2,3,4,5,6,7,8,9],ROLL_STEPS=24;function RollCell({cell:cell,t:t,delay:delay,renderText:renderText}){let[lh,setLh]=react.useState(0),onLayout=e=>{let h=e.nativeEvent.layout.height;h>0&&h!==lh&&setLh(h)},to=cell.digit??0,inputRange=[],outputRange=[];for(let s=0;s<=ROLL_STEPS;s+=1){let x=s/ROLL_STEPS;inputRange.push(delay+x*HUB_MOTION.rollDigits),outputRange.push(-to*lh*hubRollEase(x))}let translateY=t.interpolate({inputRange:inputRange,outputRange:outputRange,extrapolate:"clamp"});/* @__PURE__ */
|
|
810
835
|
return jsxRuntime.jsxs(reactNative.View,{style:{overflow:"hidden"},onLayout:onLayout,children:[
|
|
811
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{opacity:0},children:renderText(cell.char)}),lh>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:{position:"absolute",left:0,right:0,top:0,transform:[{translateY:translateY}]},children:DIGITS.map(d=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{height:lh},children:renderText(String(d))},d))}):null]})}function arcGeometry(width){let scale=width/(RAPH_RN_SAY.viewBox[2]-RAPH_RN_SAY.viewBox[0]),font=RAPH_RN_SAY.fontSize*scale,line2=Math.round(font*1.25),{x0:x0,y0:y0,cx:cx,cy:cy,x1:x1,y1:y1}=RAPH_RN_SAY.path,pt=t=>{let u=1-t;return[(u*u*x0+2*u*t*cx+t*t*x1)*scale,(u*u*y0+2*u*t*cy+t*t*y1)*scale]},STEPS=120,table=[{len:0,t:0}],[px,py]=pt(0),total=0;for(let i=1;i<=STEPS;i+=1){let t=i/STEPS,[x,y]=pt(t);total+=Math.hypot(x-px,y-py),table.push({len:total,t:t}),px=x,py=y}let at=len=>{let clamped=Math.min(total,Math.max(0,len)),i=1;for(;i<table.length-1&&table[i].len<clamped;)i+=1;let a=table[i-1],b=table[i],t=a.t+(b.t-a.t)*((clamped-a.len)/Math.max(1e-6,b.len-a.len)),[x,y]=pt(t),u=1-t,dx=2*u*(cx-x0)+2*t*(x1-cx),dy=2*u*(cy-y0)+2*t*(y1-cy);return{x:x,y:y,angle:Math.atan2(dy,dx)}};return{width:width,boxH:(RAPH_RN_SAY.viewBox[3]-RAPH_RN_SAY.viewBox[1])*scale,font:font,line:line2,baseline:(line2-font)/2+font*.8,length:total,at:at}}var ARC=arcGeometry(RAPH_RN_SAY.width);function sayArcAt(width){return width===RAPH_RN_SAY.width?ARC:arcGeometry(width)}function ArcLine({line:line2,text:text4,geom:geom,opacity:opacity}){let chars=react.useMemo(()=>Array.from(line2),[line2]),[widths,setWidths]=react.useState(()=>chars.map(()=>null)),onMeasure=i=>e=>{let w=e.nativeEvent.layout.width;setWidths(prev=>prev[i]===w?prev:prev.map((v,k)=>k===i?w:v))},ready=widths.every(w=>w!==null),placed=null;if(ready){let ws=widths,total=ws.reduce((a,b)=>a+b,0),run=geom.length/2-total/2;placed=chars.map((ch,i)=>{let w=ws[i],p=geom.at(run+w/2);run+=w;let up=geom.baseline-geom.line/2,cx=p.x+Math.sin(p.angle)*up,cy=p.y-Math.cos(p.angle)*up;/* @__PURE__ */
|
|
836
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{opacity:0},children:renderText(cell.char)}),lh>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:{position:"absolute",left:0,right:0,top:0,transform:[{translateY:translateY}]},children:DIGITS.map(d=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{height:lh},children:renderText(String(d))},d))}):null]})}function resolveRecordsSheetStage(stage){return stage===void 0||!("grassSrc"in stage)?stage:{grassSource:{uri:stage.grassSrc},petSource:{uri:stage.petSrc},...stage.head!==void 0?{head:stage.head}:{},...stage.handFontFamily!==void 0?{handFontFamily:stage.handFontFamily}:{}}}function arcGeometry(width){let scale=width/(RAPH_RN_SAY.viewBox[2]-RAPH_RN_SAY.viewBox[0]),font=RAPH_RN_SAY.fontSize*scale,line2=Math.round(font*1.25),{x0:x0,y0:y0,cx:cx,cy:cy,x1:x1,y1:y1}=RAPH_RN_SAY.path,pt=t=>{let u=1-t;return[(u*u*x0+2*u*t*cx+t*t*x1)*scale,(u*u*y0+2*u*t*cy+t*t*y1)*scale]},STEPS=120,table=[{len:0,t:0}],[px,py]=pt(0),total=0;for(let i=1;i<=STEPS;i+=1){let t=i/STEPS,[x,y]=pt(t);total+=Math.hypot(x-px,y-py),table.push({len:total,t:t}),px=x,py=y}let at=len=>{let clamped=Math.min(total,Math.max(0,len)),i=1;for(;i<table.length-1&&table[i].len<clamped;)i+=1;let a=table[i-1],b=table[i],t=a.t+(b.t-a.t)*((clamped-a.len)/Math.max(1e-6,b.len-a.len)),[x,y]=pt(t),u=1-t,dx=2*u*(cx-x0)+2*t*(x1-cx),dy=2*u*(cy-y0)+2*t*(y1-cy);return{x:x,y:y,angle:Math.atan2(dy,dx)}};return{width:width,boxH:(RAPH_RN_SAY.viewBox[3]-RAPH_RN_SAY.viewBox[1])*scale,font:font,line:line2,baseline:(line2-font)/2+font*.8,length:total,at:at}}var ARC=arcGeometry(RAPH_RN_SAY.width);function sayArcAt(width){return width===RAPH_RN_SAY.width?ARC:arcGeometry(width)}function ArcLine({line:line2,text:text4,geom:geom,opacity:opacity}){let chars=react.useMemo(()=>Array.from(line2),[line2]),[widths,setWidths]=react.useState(()=>chars.map(()=>null)),onMeasure=i=>e=>{let w=e.nativeEvent.layout.width;setWidths(prev=>prev[i]===w?prev:prev.map((v,k)=>k===i?w:v))},ready=widths.every(w=>w!==null),placed=null;if(ready){let ws=widths,total=ws.reduce((a,b)=>a+b,0),run=geom.length/2-total/2;placed=chars.map((ch,i)=>{let w=ws[i],p=geom.at(run+w/2);run+=w;let up=geom.baseline-geom.line/2,cx=p.x+Math.sin(p.angle)*up,cy=p.y-Math.cos(p.angle)*up;/* @__PURE__ */
|
|
812
837
|
return jsxRuntime.jsx(Text,{allowFontScaling:false,style:[text4,{position:"absolute",left:cx-w/2,top:cy-geom.line/2,width:w,textAlign:"center",transform:[{rotate:`${p.angle}rad`}]}],children:ch},i)})}/* @__PURE__ */
|
|
813
838
|
return jsxRuntime.jsxs(reactNative.Animated.View,{style:{position:"absolute",left:0,top:0,right:0,bottom:0,opacity:opacity},children:[
|
|
814
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:0,width:geom.width*4,flexDirection:"row",opacity:0},children:chars.map((ch,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{allowFontScaling:false,style:[text4,{flexShrink:0}],onLayout:onMeasure(i),children:ch},i))}),placed]})}var HIDDEN5={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},SAY=sayArcAt(APP_HUB.hero.sayWidth),GRASS_H=APP_HUB.hero.stageHeight*APP_HUB.hero.grassFraction;function vitalNumber(value){let n2=Number(value);return value.trim()!==""&&Number.isFinite(n2)?String(n2):value}var SAY_CYCLE_MS=44e3,SAY_FADE_MS=1100,SAY_HOLD_MS=1188,SAY_FIRST_MS=1200,SAY_STEP_MS=3600;function SayPhrase({text:text4,index:index,family:family}){let{look:
|
|
815
|
-
return jsxRuntime.jsx(RiseIn,{index:rank,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.
|
|
839
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:0,width:geom.width*4,flexDirection:"row",opacity:0},children:chars.map((ch,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{allowFontScaling:false,style:[text4,{flexShrink:0}],onLayout:onMeasure(i),children:ch},i))}),placed]})}var HIDDEN5={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},SAY=sayArcAt(APP_HUB.hero.sayWidth),GRASS_H=APP_HUB.hero.stageHeight*APP_HUB.hero.grassFraction;function vitalNumber(value){let n2=Number(value);return value.trim()!==""&&Number.isFinite(n2)?String(n2):value}var SAY_CYCLE_MS=44e3,SAY_FADE_MS=1100,SAY_HOLD_MS=1188,SAY_FIRST_MS=1200,SAY_STEP_MS=3600;function SayPhrase({text:text4,index:index,family:family}){let{look:look2}=useHub(),opacity=react.useRef(new reactNative.Animated.Value(0)).current;return react.useEffect(()=>{opacity.setValue(0);let ease=reactNative.Easing.inOut(reactNative.Easing.ease),run=reactNative.Animated.sequence([reactNative.Animated.delay(SAY_FIRST_MS+index*SAY_STEP_MS),reactNative.Animated.loop(reactNative.Animated.sequence([reactNative.Animated.timing(opacity,{toValue:1,duration:SAY_FADE_MS,easing:ease,useNativeDriver:true}),reactNative.Animated.delay(SAY_HOLD_MS),reactNative.Animated.timing(opacity,{toValue:0,duration:SAY_FADE_MS,easing:ease,useNativeDriver:true}),reactNative.Animated.delay(SAY_CYCLE_MS-SAY_FADE_MS*2-SAY_HOLD_MS)]))]);return run.start(),()=>run.stop()},[index,opacity]),/* @__PURE__ */jsxRuntime.jsx(ArcLine,{line:text4,geom:SAY,opacity:opacity,text:{fontFamily:family,fontWeight:"500",fontSize:SAY.font,lineHeight:SAY.line,color:look2.ink}})}function HubSay({family:family}){let{look:look2}=useHub();return useEverfurTheme().motion.reducedMotion?/* @__PURE__ */jsxRuntime.jsx(ArcLine,{line:HUB_COPY.sayLine,geom:SAY,opacity:1,text:{fontFamily:family,fontWeight:"500",fontSize:SAY.font,lineHeight:SAY.line,color:look2.ink}}):/* @__PURE__ */jsxRuntime.jsx(jsxRuntime.Fragment,{children:HUB_COPY.sayPhrases.map((text4,index)=>/* @__PURE__ */jsxRuntime.jsx(SayPhrase,{text:text4,index:index,family:family},text4))})}function HubHero({name:name,meta:meta,stage:stage,art:art,handFontFamily:handFontFamily,say:say,vitals:vitals,vitalsName:vitalsName,renderStage:renderStage,exam:exam,onOpenExam:onOpenExam}){let{look:look2,face:face2}=useHub(),reduced=useEverfurTheme().motion.reducedMotion,[popOpen,setPopOpen]=react.useState(false),pop=exam!=null,staged=stage!==void 0||renderStage===void 0,settle=useHeroSettle(GRASS_H,reduced),grass=stage?.grassSource??RECORDS_GRASS_SOURCE,[grassFailed,setGrassFailed]=react.useState(null),grassKey=sourceKey(grass),list=vitals.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:staged?{position:"absolute",top:APP_HUB.hero.vitalsTop,left:APP_HUB.hero.vitalsLeft}:{paddingHorizontal:APP_HUB.hero.vitalsLeft,marginTop:4},accessibilityLabel:HUB_COPY.vitalsLabel(vitalsName),testID:"everfur-records-sheet-vitals",children:vitals.map((v,rank)=>{let value=vitalNumber(v.value),nameWord=v.kind==="temp"?HUB_COPY.temperature:v.kind==="heart"?HUB_COPY.heartRate:HUB_COPY.breathing,icon=v.kind==="temp"?"thermo":v.kind==="heart"?"heart":"wind",color=v.kind==="temp"?look2.ink:v.kind==="heart"?look2.alert:look2.icoBlue;/* @__PURE__ */
|
|
840
|
+
return jsxRuntime.jsx(RiseIn,{index:rank,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{disabled:!pop,onPress:()=>setPopOpen(was=>!was),accessible:true,...pop?{accessibilityRole:"button",accessibilityState:{expanded:popOpen}}:{},accessibilityLabel:HUB_COPY.vitalLabel(nameWord,value,v.unit??"",pop),style:{flexDirection:"row",alignItems:"center",gap:APP_HUB.hero.vitalGap,minHeight:APP_HUB.hero.vitalMinHeight,paddingHorizontal:APP_HUB.hero.vitalPadX},testID:`everfur-records-sheet-vital-${v.kind}`,children:[
|
|
816
841
|
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:APP_HUB.hero.vitalIcon,color:color}),
|
|
817
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:
|
|
842
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:look2.text,style:{fontSize:APP_HUB.hero.vitalValueSize},children:value}),v.unit?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",style:[face2("medium"),{fontSize:APP_HUB.hero.vitalUnitSize}],children:v.unit}):null]})},v.kind)})}):null,popCard=pop&&popOpen?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessibilityLiveRegion:"polite",style:{marginTop:8,marginHorizontal:APP_HUB.screen.padX,padding:APP_HUB.card.pad,borderRadius:APP_HUB.card.radius,backgroundColor:look2.white,borderWidth:1,borderColor:look2.line},testID:"everfur-records-sheet-vitals-from",children:[
|
|
843
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HEALTH_TAB_SHARED_COPY.vitalsFrom(exam.vet,exam.date)}),
|
|
844
|
+
/* @__PURE__ */jsxRuntime.jsx(AnnounceLine,{line:HEALTH_TAB_SHARED_COPY.vitalsFrom(exam.vet,exam.date)}),onOpenExam!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HEALTH_TAB_SHARED_COPY.examNotes,variant:"text",onPress:onOpenExam,testID:"everfur-records-sheet-vitals-exam-notes"}):null]}):null,hand=handFontFamily;/* @__PURE__ */
|
|
818
845
|
return jsxRuntime.jsxs(reactNative.View,{style:{marginTop:4,marginHorizontal:-APP_HUB.screen.padX},testID:"everfur-records-hub-hero",children:[
|
|
819
846
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[{flexDirection:"row",alignItems:"center",gap:8,paddingHorizontal:APP_HUB.screen.padX},say?null:{minHeight:APP_HUB.peek.roundButton}],testID:"everfur-records-sheet-head",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"screenTitle",accessibilityRole:"header",numberOfLines:1,testID:"everfur-records-sheet-name",style:[face2("bold"),{flexShrink:1,fontSize:APP_HUB.hero.nameSize,lineHeight:APP_HUB.hero.nameLineHeight,letterSpacing:APP_HUB.hero.nameTracking}],children:name})}),meta!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",testID:"everfur-records-sheet-meta",style:{marginTop:APP_HUB.hero.metaTop,paddingHorizontal:APP_HUB.screen.padX,lineHeight:APP_HUB.hero.metaLineHeight,textTransform:"uppercase",letterSpacing:APP_HUB.hero.metaTracking},children:meta}):null,staged?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{height:APP_HUB.hero.stageHeight,marginTop:APP_HUB.hero.stageTop,overflow:"hidden"},testID:"everfur-records-sheet-stage",children:[
|
|
820
847
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[{position:"absolute",left:0,right:0,bottom:0,height:GRASS_H,overflow:"hidden"},settle.grass],...HIDDEN5,children:grassFailed===grassKey?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:grass,onError:()=>setGrassFailed(grassKey),style:{position:"absolute",top:0,left:0,right:0,height:"100%"},resizeMode:"cover",testID:"everfur-records-sheet-grass"})}),
|
|
821
848
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:[{position:"absolute",left:0,right:0,top:say?APP_HUB.hero.sayHeight-4:APP_HUB.hero.petTop,bottom:APP_HUB.hero.petBottom,alignItems:"center"},settle.pet],...HIDDEN5,children:stage!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Image,{source:stage.petSource,style:{width:"100%",height:"100%"},resizeMode:"contain"}):/* @__PURE__ */jsxRuntime.jsx(HubPetArt,{art:art.art,onError:art.onError,reduced:reduced})}),say&&hand!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,left:"50%",width:APP_HUB.hero.sayWidth,height:APP_HUB.hero.sayHeight,marginLeft:-APP_HUB.hero.sayWidth/2},testID:"everfur-records-sheet-say",...HIDDEN5,children:/* @__PURE__ */jsxRuntime.jsx(HubSay,{family:hand})}):null,list,
|
|
822
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,right:0,bottom:0,height:APP_HUB.hero.lawnOverlap,borderTopLeftRadius:APP_HUB.hero.lawnRadius,borderTopRightRadius:APP_HUB.hero.lawnRadius,backgroundColor:
|
|
849
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,right:0,bottom:0,height:APP_HUB.hero.lawnOverlap,borderTopLeftRadius:APP_HUB.hero.lawnRadius,borderTopRightRadius:APP_HUB.hero.lawnRadius,backgroundColor:look2.white},...HIDDEN5})]}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[renderStage!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:renderStage,fallback:null,resetKey:name}):null,list]}),popCard]})}function HubPrompt({title:title,canAct:canAct,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload,note:note}){let reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
823
850
|
return jsxRuntime.jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(HubCard,{title:title,testID:"everfur-records-records-prompt",children:[
|
|
824
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),canAct&&canRequest?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.requestFromClinic,icon:"download",block:true,onPress:onRequest,style:{marginTop:12},testID:"everfur-records-sheet-none-request"}):null,canAct&&canRequest&¬e?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{marginTop:12},children:note}):null,canAct?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",variant:"secondary",block:true,onPress:onUpload,style:{marginTop:12},testID:"everfur-records-sheet-none-upload"}):null]})})}function HubUpcoming({rows:rows,items:items,onViewAll:onViewAll,renderAction:renderAction}){let{look:
|
|
851
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),canAct&&canRequest?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.requestFromClinic,icon:"download",block:true,onPress:onRequest,style:{marginTop:12},testID:"everfur-records-sheet-none-request"}):null,canAct&&canRequest&¬e?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{marginTop:12},children:note}):null,canAct?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",variant:"secondary",block:true,onPress:onUpload,style:{marginTop:12},testID:"everfur-records-sheet-none-upload"}):null]})})}function HubUpcoming({rows:rows,items:items,onViewAll:onViewAll,renderAction:renderAction}){let{look:look2}=useHub(),U=APP_HUB.upcoming,reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
825
852
|
return jsxRuntime.jsx(HubCard,{title:HUB_COPY.upcomingCare,titleEnd:onViewAll!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.viewAll,variant:"text",onPress:onViewAll,testID:"everfur-records-sheet-upcoming-all"}):void 0,testID:"everfur-records-hub-upcoming",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:U.listGap,marginHorizontal:-U.bleed},children:rows.map((row,index)=>{let overdue=row.tone==="overdue",item=items.get(row.key);/* @__PURE__ */
|
|
826
|
-
return jsxRuntime.jsx(RiseIn,{index:index,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[{flexDirection:"row",alignItems:"center",gap:U.rowGap,paddingVertical:U.rowPadY,paddingHorizontal:U.rowPadX,borderRadius:U.rowRadius},overdue?{backgroundColor:
|
|
853
|
+
return jsxRuntime.jsx(RiseIn,{index:index,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[{flexDirection:"row",alignItems:"center",gap:U.rowGap,paddingVertical:U.rowPadY,paddingHorizontal:U.rowPadX,borderRadius:U.rowRadius},overdue?{backgroundColor:look2.tintRed}:null],testID:`everfur-records-sheet-due-${index}`,children:[
|
|
827
854
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,flexDirection:"row",alignItems:"center",gap:U.rowGap},accessible:true,accessibilityLabel:`${row.label}, ${row.when}`,children:[
|
|
828
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:row.icon,size:U.icon,color:overdue?
|
|
855
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:row.icon,size:U.icon,color:overdue?look2.alert:look2.icoGrey}),
|
|
829
856
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,minWidth:0},children:[
|
|
830
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",numberOfLines:2,color:overdue?
|
|
831
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",numberOfLines:2,color:overdue?
|
|
832
|
-
return jsxRuntime.jsx(HubCard,{title:HUB_COPY.upcomingCare,testID:"everfur-records-hub-upcoming-empty",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.nothingDue(name)})})}function Tile({index:index,tint:tint,icon:icon,title:title,label:
|
|
857
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",numberOfLines:2,color:overdue?look2.alertDeep:void 0,style:{fontSize:17,lineHeight:22},children:row.label}),
|
|
858
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",numberOfLines:2,color:overdue?look2.alert:void 0,children:row.when})]})]}),overdue&&renderAction!==void 0&&item!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderAction(item),fallback:null,resetKey:item}):row.pill!==null?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:row.pill.label,tone:row.pill.tone}):null]})},row.key)})})})}function HubUpcomingEmpty({name:name}){/* @__PURE__ */
|
|
859
|
+
return jsxRuntime.jsx(HubCard,{title:HUB_COPY.upcomingCare,testID:"everfur-records-hub-upcoming-empty",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.nothingDue(name)})})}function Tile({index:index,tint:tint,icon:icon,title:title,label:label2,foot:foot,onOpen:onOpen,testID:testID}){let{look:look2}=useHub(),G=APP_HUB.tiles,inner=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
833
860
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between"},children:[
|
|
834
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:G.icon}),onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:G.chevron,color:
|
|
861
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:G.icon}),onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:G.chevron,color:look2.icoSage}):null]}),
|
|
835
862
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:{lineHeight:G.titleLineHeight},children:title}),
|
|
836
863
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{minHeight:G.footMinHeight,flexDirection:"row",alignItems:"center"},children:foot})]}),box3={padding:G.pad,borderRadius:G.radius,gap:G.innerGap,backgroundColor:tint},reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
837
|
-
return jsxRuntime.jsx(HubReveal,{index:index,reduced:reduced,style:{width:"48%",flexGrow:1},children:onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:
|
|
864
|
+
return jsxRuntime.jsx(HubReveal,{index:index,reduced:reduced,style:{width:"48%",flexGrow:1},children:onOpen!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onOpen,accessibilityRole:"button",accessibilityLabel:label2,style:box3,testID:testID,children:inner}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:box3,accessible:true,accessibilityLabel:label2,testID:testID,children:inner})})}function HubTilesSection({tiles:tiles,labsUnknown:labsUnknown,onOpenLabs:onOpenLabs,onOpenScreenings:onOpenScreenings,onOpenVisits:onOpenVisits,onOpenTimeline:onOpenTimeline}){let{look:look2}=useHub(),G=APP_HUB.tiles;/* @__PURE__ */
|
|
838
865
|
return jsxRuntime.jsxs(reactNative.View,{style:{marginTop:G.top},testID:"everfur-records-hub-records",children:[
|
|
839
866
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{marginBottom:G.titleBottom},children:HUB_COPY.recordsHistory}),
|
|
840
867
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",gap:G.gap},children:[
|
|
841
|
-
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:0,tint:
|
|
868
|
+
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:0,tint:look2.tintSage,icon:"flask",title:HUB_COPY.labs,label:labsUnknown?HUB_COPY.labsA11yUnknown:HUB_COPY.labsA11y(tiles.labsTotal,tiles.labsNoun),onOpen:onOpenLabs,testID:"everfur-records-sheet-tile-labs",foot:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"baseline",gap:G.countGap},children:[
|
|
842
869
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:{fontSize:G.numSize,lineHeight:G.numLineHeight,letterSpacing:G.numTracking},testID:"everfur-records-sheet-labs-count",children:labsUnknown?HUB_COPY.labsCountUnknown:String(tiles.labsTotal)}),labsUnknown?null:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:tiles.labsNoun})]})}),
|
|
843
|
-
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:1,tint:
|
|
844
|
-
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:2,tint:
|
|
845
|
-
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:3,tint:
|
|
846
|
-
return jsxRuntime.jsx(Text,{allowFontScaling:false,numberOfLines:1,style:[style,{position:"absolute",top:top,fontSize:size,lineHeight:size},place],children:children})}function WeightChart({weight:weight}){let{look:
|
|
870
|
+
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:1,tint:look2.tintPink,icon:"shield",title:HUB_COPY.screenings,label:HUB_COPY.screeningsA11y(tiles.screeningsPill?.label??null),onOpen:onOpenScreenings,testID:"everfur-records-sheet-tile-screenings",foot:tiles.screeningsPill!==null?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:tiles.screeningsPill.label,tone:tiles.screeningsPill.tone}):/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:HEALTH_TAB_SHARED_COPY.noScreenings})}),
|
|
871
|
+
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:2,tint:look2.tintBlue,icon:"folder",title:HUB_COPY.visits,label:HUB_COPY.visitsA11y(tiles.visitDate),onOpen:onOpenVisits,testID:"everfur-records-sheet-tile-record",foot:tiles.visitDate!==null?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:tiles.visitDate,tone:"plain"}):/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:HEALTH_TAB_SHARED_COPY.noVisits})}),
|
|
872
|
+
/* @__PURE__ */jsxRuntime.jsx(Tile,{index:3,tint:look2.tintYellow,icon:"clock",title:HUB_COPY.timeline,label:HUB_COPY.timelineA11y(tiles.timelineCount),onOpen:onOpenTimeline,testID:"everfur-records-sheet-tile-timeline",foot:tiles.timelineCount>0?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:HUB_COPY.events(tiles.timelineCount),tone:"plain"}):null})]})]})}var BASELINE=.85;function ChartText({x:x,y:y,anchor:anchor,size:size,style:style,children:children}){let top=y-size*BASELINE,W=160,place=anchor==="start"?{left:x}:anchor==="end"?{left:x-W,width:W,textAlign:"right"}:{left:x-W/2,width:W,textAlign:"center"};/* @__PURE__ */
|
|
873
|
+
return jsxRuntime.jsx(Text,{allowFontScaling:false,numberOfLines:1,style:[style,{position:"absolute",top:top,fontSize:size,lineHeight:size},place],children:children})}function WeightChart({weight:weight}){let{look:look2,face:face2}=useHub(),[width,setWidth]=react.useState(0),[selected,setSelected]=react.useState(null),reduced=useEverfurTheme().motion.reducedMotion,draw=useHubDraw(width>0,reduced),onLayout=e=>{let w=Math.round(e.nativeEvent.layout.width);w>0&&w!==width&&setWidth(w)},G=APP_HUB.chart;if(width===0)/* @__PURE__ */return jsxRuntime.jsx(reactNative.View,{onLayout:onLayout,style:{height:G.height}});let c=hubChart(weight,width),ring=G.dot+G.dotRing/2,pitch=c.cols.length>1?c.cols[1]-c.cols[0]:c.dataRight-(c.cols[0]??0),pick2=selected!==null?c.dots[selected]??null:null,spans=hubSegmentSpans(c.dots);/* @__PURE__ */
|
|
847
874
|
return jsxRuntime.jsxs(reactNative.View,{onLayout:onLayout,style:{height:G.height},children:[
|
|
848
875
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{accessible:true,accessibilityRole:"image",accessibilityLabel:c.summary,style:{position:"absolute",left:0,top:0,right:0,bottom:0},children:[c.hasBand?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
849
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:c.plotTop,width:G.indicatorWidth,height:c.plotBottom-c.plotTop,borderRadius:G.indicatorWidth/2,backgroundColor:
|
|
850
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:c.yBandTop,width:G.indicatorWidth,height:Math.max(0,c.yBandBottom-c.yBandTop),borderRadius:G.indicatorWidth/2,backgroundColor:
|
|
851
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:c.plotLeft,top:c.yBandTop,width:Math.max(0,c.dataRight-c.plotLeft),height:Math.max(0,c.yBandBottom-c.yBandTop),backgroundColor:
|
|
852
|
-
return jsxRuntime.jsx(reactNative.Animated.View,{style:{position:"absolute",left:(a.x+b.x)/2-(len+w)/2,top:(a.y+b.y)/2-w/2,width:len+w,height:w,borderRadius:w/2,backgroundColor:
|
|
876
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:c.plotTop,width:G.indicatorWidth,height:c.plotBottom-c.plotTop,borderRadius:G.indicatorWidth/2,backgroundColor:look2.chartGrid}}),
|
|
877
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:0,top:c.yBandTop,width:G.indicatorWidth,height:Math.max(0,c.yBandBottom-c.yBandTop),borderRadius:G.indicatorWidth/2,backgroundColor:look2.go}}),
|
|
878
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:c.plotLeft,top:c.yBandTop,width:Math.max(0,c.dataRight-c.plotLeft),height:Math.max(0,c.yBandBottom-c.yBandTop),backgroundColor:look2.chartBand}})]}):null,c.cols.map((x,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:x-.5,top:c.plotTop,width:1,height:c.plotBottom-c.plotTop,backgroundColor:look2.chartGrid}},`g-${i}`)),c.hasBand?[c.yBandTop,c.yBandBottom].map((y,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:c.plotLeft,top:y-.5,width:Math.max(0,c.dataRight-c.plotLeft),height:1,backgroundColor:look2.line}},`e-${i}`)):null,c.dots.slice(1).map((b,i)=>{let a=c.dots[i],len=Math.hypot(b.x-a.x,b.y-a.y),w=G.lineWidth,grow=hubSegmentDraw(draw,spans[i],len+w);/* @__PURE__ */
|
|
879
|
+
return jsxRuntime.jsx(reactNative.Animated.View,{style:{position:"absolute",left:(a.x+b.x)/2-(len+w)/2,top:(a.y+b.y)/2-w/2,width:len+w,height:w,borderRadius:w/2,backgroundColor:look2.chartLine,transform:[{rotate:`${Math.atan2(b.y-a.y,b.x-a.x)}rad`},{translateX:grow.translateX},{scaleX:grow.scaleX}]}},`l-${i}`)}),c.dots.map((d,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Animated.View,{style:{position:"absolute",left:d.x-ring,top:d.y-ring,width:ring*2,height:ring*2,borderRadius:ring,borderWidth:G.dotRing,borderColor:look2.white,backgroundColor:d.status==="over"||d.status==="under"?look2.yellow:look2.go,opacity:hubDotShown(draw,hubDotAt(spans,i))}},`d-${i}`)),c.showValues?c.dots.map((d,i)=>/* @__PURE__ */jsxRuntime.jsx(ChartText,{x:d.labelX,y:d.labelBaseline,anchor:d.labelAnchor,size:c.valueFont,style:[face2("bold"),{color:look2.text}],children:d.label},`v-${i}`)):null,c.legend.flatMap(z12=>z12.lines.map((line2,i)=>/* @__PURE__ */jsxRuntime.jsx(ChartText,{x:G.legendX,y:z12.baselines[i],anchor:"start",size:G.legendSize,style:[face2("monoBold"),{color:look2.charcoal,letterSpacing:G.legendTracking}],children:line2},`k-${z12.zone}-${i}`))),c.months.map((m,i)=>/* @__PURE__ */jsxRuntime.jsx(ChartText,{x:m.x,y:G.monthY,anchor:m.anchor,size:G.monthSize,style:[face2("mono"),{color:look2.muted}],children:m.label},`m-${i}`))]}),c.dots.map((d,i)=>{let half=pitch/2;/* @__PURE__ */
|
|
853
880
|
return jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setSelected(cur=>cur===i?null:i),accessibilityRole:"button",accessibilityLabel:d.spoken,style:{position:"absolute",left:Math.max(0,d.x-half),top:c.plotTop,width:Math.max(1,half*2),height:Math.max(1,c.plotBottom-c.plotTop)}},`t-${i}`)}),pick2!==null?
|
|
854
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:{position:"absolute",width:92,height:40,borderRadius:8,paddingHorizontal:8,paddingVertical:5,backgroundColor:
|
|
881
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{pointerEvents:"none",style:{position:"absolute",width:92,height:40,borderRadius:8,paddingHorizontal:8,paddingVertical:5,backgroundColor:look2.chartLine,alignItems:"center",justifyContent:"center",left:Math.min(Math.max(pick2.x-46,G.edgePad),Math.max(G.edgePad,width-92-G.edgePad)),top:pick2.y-40-G.dot-4>=0?pick2.y-40-G.dot-4:pick2.y+G.dot+4},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("bold"),{fontSize:13,color:look2.white}],children:`${pick2.label} ${weight.unit}`})}):null]})}var petMeta={textTransform:"uppercase",letterSpacing:APP_HUB.hero.metaTracking,lineHeight:APP_HUB.hero.metaLineHeight};function HubWeightCard({weight:weight,name:name}){let{look:look2}=useHub(),W=APP_HUB.weight,reduced=useEverfurTheme().motion.reducedMotion;if(weight===null)/* @__PURE__ */
|
|
855
882
|
return jsxRuntime.jsx(HubReveal,{index:3,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsx(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.noWeights(name)})})});let num5={fontSize:W.numSize,lineHeight:W.numLineHeight,letterSpacing:W.numTracking};/* @__PURE__ */
|
|
856
883
|
return jsxRuntime.jsx(HubReveal,{index:3,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(HubCard,{title:HUB_COPY.weight,testID:"everfur-records-hub-weight",children:[
|
|
857
884
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:W.headGap,marginBottom:W.headBottom},children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"baseline",gap:W.numGap},children:[
|
|
858
|
-
/* @__PURE__ */jsxRuntime.jsx(HubRollingDigits,{text:weight.primary,reduced:reduced,testID:"everfur-records-sheet-weight-latest",renderText:(text4,extra)=>/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:[num5,extra?.style],...extra?.testID!==void 0?{testID:extra.testID}:{},children:text4})}),weight.secondary!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:
|
|
859
|
-
/* @__PURE__ */jsxRuntime.jsx(WeightChart,{weight:weight}),weight.band!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:HUB_COPY.estimatedRange}):null]}):
|
|
860
|
-
|
|
885
|
+
/* @__PURE__ */jsxRuntime.jsx(HubRollingDigits,{text:weight.primary,reduced:reduced,testID:"everfur-records-sheet-weight-latest",renderText:(text4,extra)=>/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:[num5,extra?.style],...extra?.testID!==void 0?{testID:extra.testID}:{},children:text4})}),weight.secondary!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:look2.muted,children:weight.secondary}):null]})}),weight.points.length>=2?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[
|
|
886
|
+
/* @__PURE__ */jsxRuntime.jsx(WeightChart,{weight:weight}),weight.band!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:HUB_COPY.estimatedRange}):null]}):weight.points.length===1?
|
|
887
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:8},children:[weight.date!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",style:petMeta,testID:"everfur-records-sheet-weight-date",children:weight.date}):null,
|
|
888
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",style:petMeta,testID:"everfur-records-sheet-weight-single",children:HEALTH_TAB_SHARED_COPY.oneReading})]}):null]})})}function SeeWhereItStands({onPress:onPress,testID:testID="everfur-records-sheet-on-the-way-go"}){/* @__PURE__ */
|
|
889
|
+
return jsxRuntime.jsx(HubButton,{label:SHEET_COPY.seeWhereItStands,variant:"secondary",size:"sm",icon:"chevron",onPress:onPress,style:{alignSelf:"flex-start"},testID:testID})}function HubInFlight({lines:lines,onOpenRequest:onOpenRequest}){return lines.length===0?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:12},testID:"everfur-records-sheet-in-flight",children:lines.map(line2=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:8,alignItems:"flex-start"},testID:"everfur-records-sheet-on-the-way",children:[
|
|
890
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:line2.text}),onOpenRequest!==void 0?/* @__PURE__ */jsxRuntime.jsx(SeeWhereItStands,{onPress:()=>onOpenRequest(line2.requestId)}):null]},line2.key))})}function HubAddRecords({words:words2,sources:sources,canRequest:canRequest,onRequest:onRequest,onUpload:onUpload,note:note,inFlight:inFlight=[],onOpenRequest:onOpenRequest,uploadHint:uploadHint}){let{look:look2}=useHub(),A=APP_HUB.add,reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
891
|
+
return jsxRuntime.jsx(HubReveal,{index:4,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsx(HubCard,{style:{backgroundColor:look2.tintPinkSoft},testID:"everfur-records-hub-add-records",children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:A.gap},children:[
|
|
861
892
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",gap:A.headGap},children:[
|
|
862
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"clip",size:A.icon,color:
|
|
893
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"clip",size:A.icon,color:look2.alert}),
|
|
863
894
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",style:{flex:1},children:HUB_COPY.addRecords(words2.name)})]}),
|
|
864
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),
|
|
895
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:HUB_COPY.moreThanOneClinic}),
|
|
896
|
+
/* @__PURE__ */jsxRuntime.jsx(HubInFlight,{lines:inFlight,onOpenRequest:onOpenRequest}),sources.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:A.sourcesGap,marginTop:A.sourcesTop},accessibilityLabel:HUB_COPY.onFileNow,testID:"everfur-records-sheet-sources",children:sources.map(src=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:A.sourceColumnGap,paddingVertical:A.sourcePadY,paddingHorizontal:A.sourcePadX,borderRadius:A.sourceRadius,backgroundColor:look2.white},children:[
|
|
865
897
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",style:{flexShrink:1},children:src.name}),src.meta!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:src.meta}):null]},src.key))}):null,
|
|
866
898
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:A.actsGap,paddingTop:A.actsTop},children:[canRequest?/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.requestFromClinic,icon:"download",size:"sm",block:true,onPress:onRequest,testID:"everfur-records-sheet-request"}):null,canRequest?note:null,
|
|
867
|
-
/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",size:"sm",variant:"secondary",bold:true,block:true,onPress:onUpload,style:{backgroundColor:
|
|
868
|
-
return jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",gap:16,paddingBottom:last?0:20},accessible:true,accessibilityLabel:when!==null?`${title}. ${when}`:title,testID:`${testID}-${state}`,children:[last?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:D/2-1,top:D+2,bottom:2,width:2,borderRadius:1,backgroundColor:state==="done"?
|
|
869
|
-
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{width:D,height:D,borderRadius:D/2,borderWidth:2,borderColor:state!=="next"?
|
|
899
|
+
/* @__PURE__ */jsxRuntime.jsx(HubButton,{label:HUB_COPY.uploadDocument,icon:"upload",size:"sm",variant:"secondary",bold:true,block:true,onPress:onUpload,...uploadHint!==void 0?{accessibilityHint:uploadHint}:{},style:{backgroundColor:look2.white,borderRadius:999},testID:"everfur-records-sheet-upload"})]})]})})})}function Step({state:state,title:title,when:when,last:last=false,testID:testID}){let{look:look2}=useHub(),D=APP_HUB.onTheWay.dot;/* @__PURE__ */
|
|
900
|
+
return jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",gap:16,paddingBottom:last?0:20},accessible:true,accessibilityLabel:when!==null?`${title}. ${when}`:title,testID:`${testID}-${state}`,children:[last?null:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:D/2-1,top:D+2,bottom:2,width:2,borderRadius:1,backgroundColor:state==="done"?look2.ink:look2.line}}),
|
|
901
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{width:D,height:D,borderRadius:D/2,borderWidth:2,borderColor:state!=="next"?look2.ink:look2.line,backgroundColor:state==="done"?look2.fill:look2.white,alignItems:"center",justifyContent:"center"},children:[state==="done"?/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:16,color:look2.onFill}):null,state==="now"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:10,height:10,borderRadius:5,backgroundColor:look2.go}}):null]}),
|
|
870
902
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,minWidth:0,paddingTop:3,gap:2},children:[
|
|
871
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:state==="next"?
|
|
872
|
-
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:`${title}. ${text4}`,style:[{flexDirection:"row",alignItems:"center",gap:12,padding:O.wayPad,borderRadius:O.wayRadius},ink?{backgroundColor:
|
|
903
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:state==="next"?look2.muted:void 0,style:{fontSize:17,lineHeight:22},children:title}),when!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:when}):null]})]})}function Way({ink:ink,icon:icon,title:title,text:text4,onPress:onPress,testID:testID}){let{look:look2}=useHub(),fg=ink?look2.onFill:look2.ink,O=APP_HUB.onTheWay;/* @__PURE__ */
|
|
904
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:`${title}. ${text4}`,style:[{flexDirection:"row",alignItems:"center",gap:12,padding:O.wayPad,borderRadius:O.wayRadius},ink?{backgroundColor:look2.fill}:{borderWidth:1.5,borderStyle:"dashed",borderColor:look2.ink,backgroundColor:look2.white}],testID:testID,children:[
|
|
873
905
|
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icon,size:O.wayIcon,color:fg}),
|
|
874
906
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,minWidth:0,gap:2},children:[
|
|
875
907
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:fg,style:{fontSize:17,lineHeight:22},children:title}),
|
|
876
908
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:fg,children:text4})]}),
|
|
877
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:20,color:ink?
|
|
909
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:20,color:ink?look2.accentOnFill:look2.ink})]})}function HubOnTheWay({words:words2,request:request,steps:steps,sentWhen:sentWhen,canAct:canAct,canRequest:canRequest,onAnotherClinic:onAnotherClinic,onUpload:onUpload,onOpenRequest:onOpenRequest}){let whose=words2.poss==="her"||words2.poss==="his"?words2.poss:`${words2.name}’s`,O=APP_HUB.onTheWay,[sent,waiting,inTab]=steps,clinic=request.clinicName?.trim()||null,status=request.statusLabel.trim()||null,waitingLine=request.waitingExpectation?.trim()||(waiting==="now"?status:null),reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
878
910
|
return jsxRuntime.jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(HubCard,{testID:"everfur-records-hub-on-the-way",children:[
|
|
879
911
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"screenTitle",accessibilityRole:"header",style:{fontSize:O.titleSize,lineHeight:O.titleLineHeight,letterSpacing:O.titleTracking},children:HUB_COPY.onTheWay(words2.Name)}),
|
|
880
912
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"body",style:{marginTop:8},children:HUB_COPY.clinicsTake}),
|
|
881
913
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{marginTop:16},accessibilityRole:"list",testID:"everfur-records-sheet-tracker",children:[
|
|
882
914
|
/* @__PURE__ */jsxRuntime.jsx(Step,{state:sent,title:HUB_COPY.requestSentTo(clinic),when:sentWhen!==null?HUB_COPY.signedRelease(sentWhen):null,testID:"everfur-records-sheet-step-sent"}),
|
|
883
915
|
/* @__PURE__ */jsxRuntime.jsx(Step,{state:waiting,title:HUB_COPY.waitingFor(whose),when:waitingLine,testID:"everfur-records-sheet-step-waiting"}),
|
|
884
|
-
/* @__PURE__ */jsxRuntime.jsx(Step,{state:inTab,last:true,title:HUB_COPY.inHealthTab(whose),when:inTab==="now"?status:HUB_COPY.everyPageRead,testID:"everfur-records-sheet-step-ready"})]}),canAct?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:12,marginTop:16},testID:"everfur-records-sheet-none-ways",children:[canRequest?/* @__PURE__ */jsxRuntime.jsx(Way,{ink:true,icon:"download",title:HUB_COPY.anotherClinic,text:HUB_COPY.anotherClinicText,onPress:onAnotherClinic,testID:"everfur-records-sheet-another-clinic"}):null,
|
|
885
|
-
/* @__PURE__ */jsxRuntime.jsx(Way,{ink:false,icon:"upload",title:HUB_COPY.uploadDocument,text:HUB_COPY.uploadText,onPress:onUpload,testID:"everfur-records-sheet-none-upload"})]}):null]})})}function RailDot({state:state}){let{look:
|
|
886
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:2,height:6,borderRadius:1,backgroundColor:
|
|
887
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:2,height:2,borderRadius:1,marginTop:1.5,backgroundColor:
|
|
888
|
-
return jsxRuntime.jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{borderRadius:P.radius,backgroundColor:
|
|
889
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("bold"),{flex:1,fontSize:P.titleSize,lineHeight:P.titleLineHeight,color:
|
|
916
|
+
/* @__PURE__ */jsxRuntime.jsx(Step,{state:inTab,last:true,title:HUB_COPY.inHealthTab(whose),when:inTab==="now"?status:HUB_COPY.everyPageRead,testID:"everfur-records-sheet-step-ready"})]}),onOpenRequest!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{marginTop:16},children:/* @__PURE__ */jsxRuntime.jsx(SeeWhereItStands,{onPress:onOpenRequest})}):null,canAct?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:12,marginTop:16},testID:"everfur-records-sheet-none-ways",children:[canRequest?/* @__PURE__ */jsxRuntime.jsx(Way,{ink:true,icon:"download",title:HUB_COPY.anotherClinic,text:HUB_COPY.anotherClinicText,onPress:onAnotherClinic,testID:"everfur-records-sheet-another-clinic"}):null,
|
|
917
|
+
/* @__PURE__ */jsxRuntime.jsx(Way,{ink:false,icon:"upload",title:HUB_COPY.uploadDocument,text:HUB_COPY.uploadText,onPress:onUpload,testID:"everfur-records-sheet-none-upload"})]}):null]})})}function RailDot({state:state}){let{look:look2}=useHub(),box3={width:APP_HUB_TIMELINE.dot,height:APP_HUB_TIMELINE.dot,borderRadius:APP_HUB_TIMELINE.dot/2,alignItems:"center",justifyContent:"center"};return state==="done"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[box3,{backgroundColor:look2.brand}],...HIDDEN5,children:/* @__PURE__ */jsxRuntime.jsx(CheckGlyph,{size:APP_HUB_TIMELINE.check,color:look2.white})}):state==="failed"?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[box3,{backgroundColor:look2.alert}],...HIDDEN5,children:[
|
|
918
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:2,height:6,borderRadius:1,backgroundColor:look2.white}}),
|
|
919
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:2,height:2,borderRadius:1,marginTop:1.5,backgroundColor:look2.white}})]}):state==="current"?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[box3,{borderWidth:APP_HUB_TIMELINE.ring,borderColor:look2.brand,backgroundColor:look2.white}],...HIDDEN5,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:APP_HUB_TIMELINE.core,height:APP_HUB_TIMELINE.core,borderRadius:APP_HUB_TIMELINE.core/2,backgroundColor:look2.brand}})}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[box3,{borderWidth:APP_HUB_TIMELINE.ring,borderColor:look2.legacyBorder,backgroundColor:look2.white}],...HIDDEN5})}function HubInProgress({words:words2,request:request,onOpenRequest:onOpenRequest}){let{look:look2,face:face2}=useHub(),P=APP_HUB.inProgress,events=buildRequestRail(request),title=request.clinicName?.trim()||HUB_COPY.requestTitle(words2.Name),status=request.statusLabel.trim(),reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
920
|
+
return jsxRuntime.jsx(HubReveal,{index:1,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{borderRadius:P.radius,backgroundColor:look2.white,padding:P.pad,gap:P.gap},accessibilityRole:"summary",accessibilityLabel:HUB_COPY.requestA11y(words2.name,status),testID:"everfur-records-records-in-progress",children:[
|
|
921
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:8},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("bold"),{flex:1,fontSize:P.titleSize,lineHeight:P.titleLineHeight,color:look2.legacyText}],children:title})}),
|
|
890
922
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityRole:"summary",testID:"everfur-records-sheet-rail",children:events.map((event,idx)=>{let date2=event.at!==null?recordsDate(event.at):null,a11yState=event.state==="done"?"completed":event.state==="current"?"in progress":event.state==="failed"?"needs attention":"not started",upcoming=event.state==="upcoming";/* @__PURE__ */
|
|
891
923
|
return jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"flex-start",gap:APP_HUB_TIMELINE.rowGap},accessibilityRole:"text",accessibilityLabel:[event.title,event.detail,date2,a11yState].filter(Boolean).join(", "),testID:`everfur-records-sheet-rail-${event.key}`,children:[
|
|
892
924
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{alignItems:"center",width:APP_HUB_TIMELINE.dot,alignSelf:"stretch"},children:[
|
|
893
|
-
/* @__PURE__ */jsxRuntime.jsx(RailDot,{state:event.state}),idx<events.length-1?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:APP_HUB_TIMELINE.rail,flex:1,minHeight:APP_HUB_TIMELINE.railMin,marginVertical:APP_HUB_TIMELINE.railGap,backgroundColor:event.state==="done"?
|
|
925
|
+
/* @__PURE__ */jsxRuntime.jsx(RailDot,{state:event.state}),idx<events.length-1?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{width:APP_HUB_TIMELINE.rail,flex:1,minHeight:APP_HUB_TIMELINE.railMin,marginVertical:APP_HUB_TIMELINE.railGap,backgroundColor:event.state==="done"?look2.brand:look2.legacyBorder},...HIDDEN5}):null]}),
|
|
894
926
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,paddingBottom:APP_HUB_TIMELINE.bodyBottom,gap:APP_HUB_TIMELINE.bodyGap},children:[
|
|
895
927
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:APP_HUB_TIMELINE.titleGap},children:[
|
|
896
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2(upcoming?"regular":"bold"),{flex:1,fontSize:APP_HUB_TIMELINE.titleSize,lineHeight:APP_HUB_TIMELINE.titleLineHeight,color:event.state==="current"?
|
|
928
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2(upcoming?"regular":"bold"),{flex:1,fontSize:APP_HUB_TIMELINE.titleSize,lineHeight:APP_HUB_TIMELINE.titleLineHeight,color:event.state==="current"?look2.brand:event.state==="failed"?look2.alert:upcoming?look2.legacyMuted:look2.legacyText}],children:event.title}),date2!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("regular"),{fontSize:APP_HUB_TIMELINE.dateSize,lineHeight:APP_HUB_TIMELINE.dateLineHeight,color:look2.legacyMuted}],children:date2}):null]}),event.detail!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("regular"),{fontSize:APP_HUB_TIMELINE.detailSize,lineHeight:APP_HUB_TIMELINE.detailLineHeight,color:look2.legacyMuted},upcoming?{opacity:APP_HUB_TIMELINE.upcomingOpacity}:null],children:event.detail}):null]})]},event.key)})}),status.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{borderRadius:P.statusRadius,backgroundColor:look2.brandSoft,padding:P.statusPad},children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[face2("regular"),{fontSize:P.statusSize,lineHeight:P.statusLineHeight,color:look2.legacyText}],children:status})}):null,onOpenRequest!==void 0?/* @__PURE__ */jsxRuntime.jsx(SeeWhereItStands,{onPress:onOpenRequest}):null]})})}function HubMedications({medications:medications}){let{look:look2}=useHub(),reduced=useEverfurTheme().motion.reducedMotion;return medications===null?null:/* @__PURE__ */jsxRuntime.jsx(HubReveal,{index:5,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsx(HubCard,{title:SHEET_COPY.takingNow,testID:"everfur-records-sheet-meds",children:medications.current.length===0?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:SHEET_COPY.noCurrentMeds}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{accessibilityRole:"list",style:{gap:APP_HUB.upcoming.listGap},children:medications.current.map((m,index)=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[{paddingVertical:APP_HUB.upcoming.rowPadY},index===0?null:{borderTopWidth:1,borderTopColor:look2.line}],testID:`everfur-records-sheet-med-${m.key}`,children:[
|
|
929
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:m.name}),m.detail!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:m.detail}):null]},m.key))})})})}function HubHistory({words:words2,history:history,onOpenMarker:onOpenMarker}){let{look:look2}=useHub(),reduced=useEverfurTheme().motion.reducedMotion;return history.length===0?null:/* @__PURE__ */jsxRuntime.jsx(HubReveal,{index:6,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsx(HubCard,{title:SHEET_COPY.history,titleEnd:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:SHEET_COPY.theirClinic(words2)}),testID:"everfur-records-sheet-history",children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:12},children:history.map(year=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:8},children:[
|
|
930
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"labelMono",accessibilityRole:"header",children:year.year}),year.items.map(item=>{let text4=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
931
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",children:item.date}),
|
|
932
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:item.alert?look2.alertDeep:void 0,style:{fontSize:17,lineHeight:22},children:item.title}),item.text!==null?/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:item.text}):null]}),box3={gap:2,paddingLeft:12,borderLeftWidth:2,borderLeftColor:item.alert?look2.alert:look2.line},markerId=item.markerId;return markerId!==null?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>onOpenMarker(markerId),accessibilityRole:"button",accessibilityLabel:[item.date,item.title,item.text].filter(t=>t!==null&&t.length>0).join(", "),style:box3,testID:`everfur-records-sheet-history-marker-${markerId}`,children:text4},item.key):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:box3,accessible:true,testID:`everfur-records-sheet-history-${item.key}`,children:text4},item.key)})]},year.year))})})})}function MarkerLine({marker:marker}){let{look:look2}=useHub(),S=APP_HUB.peek,alert=marker.flag!==void 0;/* @__PURE__ */
|
|
897
933
|
return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
898
934
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",gap:S.markerTopGap},children:[
|
|
899
935
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flex:1,minWidth:0},children:[
|
|
900
936
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},children:[
|
|
901
937
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:marker.name}),alert?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:HUB_COPY.high,tone:"high"}):null]}),
|
|
902
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:
|
|
938
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:look2.muted,children:marker.what})]}),
|
|
903
939
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"baseline",gap:S.valueGap},children:[
|
|
904
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:alert?
|
|
905
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",color:
|
|
906
|
-
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{height:S.barHeight,borderRadius:999,backgroundColor:
|
|
907
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999,backgroundColor:
|
|
908
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:-(S.barDot-S.barHeight)/2,left:`${marker.at}%`,width:S.barDot,height:S.barDot,marginLeft:-S.barDot/2,borderRadius:S.barDot/2,borderWidth:S.barDotRing,borderColor:
|
|
909
|
-
return jsxRuntime.jsxs(reactNative.View,{style:[{borderRadius:S.markerRadius},open?{backgroundColor:
|
|
910
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setOpen(o=>!o),accessibilityRole:"button",accessibilityState:{expanded:open},style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius,backgroundColor:
|
|
911
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:
|
|
940
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:alert?look2.alert:void 0,style:{fontSize:17,lineHeight:22},children:marker.value}),
|
|
941
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",color:look2.muted,children:marker.unit})]})]}),
|
|
942
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{height:S.barHeight,borderRadius:999,backgroundColor:look2.barTrack},...HIDDEN5,children:[
|
|
943
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999,backgroundColor:look2.go}}),
|
|
944
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",top:-(S.barDot-S.barHeight)/2,left:`${marker.at}%`,width:S.barDot,height:S.barDot,marginLeft:-S.barDot/2,borderRadius:S.barDot/2,borderWidth:S.barDotRing,borderColor:look2.white,backgroundColor:alert?look2.alert:look2.ink}})]})]})}function FlaggedMarker({marker:marker,name:name,poss:poss}){let{look:look2}=useHub(),S=APP_HUB.peek,[open,setOpen]=react.useState(false);/* @__PURE__ */
|
|
945
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{borderRadius:S.markerRadius},open?{backgroundColor:look2.tintRed}:null],children:[
|
|
946
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:()=>setOpen(o=>!o),accessibilityRole:"button",accessibilityState:{expanded:open},style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius,backgroundColor:look2.tintRed},testID:`everfur-records-sheet-sample-flag-${marker.name}`,children:/* @__PURE__ */jsxRuntime.jsx(MarkerLine,{marker:marker})}),open?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:8,paddingHorizontal:S.markerPad,paddingBottom:S.markerPad,alignItems:"flex-start"},testID:"everfur-records-sheet-sample-flag-note",children:/* @__PURE__ */jsxRuntime.jsxs(HubText,{variant:"bodySm",children:[
|
|
947
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",color:look2.alertDeep,children:HUB_COPY.sampleNotTheirs(name)}),HUB_COPY.sampleNote(poss)]})}):null]})}function FromPage({from:from}){let{look:look2,face:face2}=useHub(),S=APP_HUB.peek,[open,setOpen]=react.useState(false),meta=[face2("mono"),{color:look2.muted}];/* @__PURE__ */
|
|
912
948
|
return jsxRuntime.jsxs(reactNative.View,{style:{marginTop:8},testID:"everfur-records-sheet-sample-from",children:[
|
|
913
949
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.Pressable,{onPress:()=>setOpen(v=>!v),accessibilityRole:"button",accessibilityLabel:from.cap,accessibilityState:{expanded:open},style:[{flexDirection:"row",alignItems:"center",gap:S.fromGap,minHeight:S.fromMinHeight,alignSelf:"flex-start"},open?{marginBottom:8}:null],testID:"everfur-records-sheet-sample-from-cap",children:[
|
|
914
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"file",size:S.fromIcon,color:
|
|
950
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"file",size:S.fromIcon,color:look2.icoSage}),
|
|
915
951
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"buttonRow",style:{lineHeight:20},children:from.cap}),
|
|
916
|
-
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:S.fromChevron,style:open?{transform:[{rotate:"90deg"}]}:void 0})]}),open?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:4,padding:12,borderWidth:1,borderColor:
|
|
952
|
+
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:"chevron",size:S.fromChevron,style:open?{transform:[{rotate:"90deg"}]}:void 0})]}),open?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:4,padding:12,borderWidth:1,borderColor:look2.line,borderRadius:10,backgroundColor:look2.white},testID:"everfur-records-sheet-sample-doc",children:[
|
|
917
953
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8},children:[
|
|
918
954
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",children:from.who}),
|
|
919
955
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[meta,{fontSize:12,lineHeight:18}],children:from.page})]}),
|
|
920
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flexDirection:"row"},children:HUB_COPY.columns.map((head,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:[meta,{flex:i===0?1.1:1,paddingHorizontal:8,paddingBottom:2,fontSize:12,lineHeight:16,letterSpacing:.48,textTransform:"uppercase"}],children:head},head))}),from.rows.map(r=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[{flexDirection:"row",marginTop:3,borderRadius:6},r.lit===true?{backgroundColor:
|
|
956
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flexDirection:"row"},children:HUB_COPY.columns.map((head,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:[meta,{flex:i===0?1.1:1,paddingHorizontal:8,paddingBottom:2,fontSize:12,lineHeight:16,letterSpacing:.48,textTransform:"uppercase"}],children:head},head))}),from.rows.map(r=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[{flexDirection:"row",marginTop:3,borderRadius:6},r.lit===true?{backgroundColor:look2.tintYellow}:null],children:[r.test,r.result,r.unit,r.range].map((cell,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{numberOfLines:1,style:[face2("mono"),{flex:i===0?1.1:1,paddingHorizontal:8,paddingVertical:5,fontSize:13,lineHeight:18,color:look2.text,fontVariant:["tabular-nums"]}],children:cell},i))},r.test))]}):null]})}var DOG_ONLY=/heartworm|4dx/i;function HubSamplePeek({name:name,poss:poss="her",species:species}){let{look:look2}=useHub(),S=APP_HUB.peek,[index,setIndex]=react.useState(0),last=HUB_SAMPLE_GROUPS.length-1,group=HUB_SAMPLE_GROUPS[index],dog=species!==null&&/^(dog|canine)$/i.test(species.trim()),tints={pink:look2.tintPink,blue:look2.tintBlue,yellow:look2.tintYellow},icons={screenings:"shield",visits:"folder",timeline:"clock"},reduced=useEverfurTheme().motion.reducedMotion,slide=useHubSlideStep(index,reduced);/* @__PURE__ */
|
|
921
957
|
return jsxRuntime.jsxs(reactNative.View,{style:{marginTop:S.top},testID:"everfur-records-sample-peek",children:[
|
|
922
958
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:S.headGap},children:[
|
|
923
959
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"cardTitle",accessibilityRole:"header",children:HUB_COPY.recordsHistory}),
|
|
@@ -931,31 +967,32 @@ return jsxRuntime.jsxs(reactNative.View,{style:{marginTop:S.top},testID:"everfur
|
|
|
931
967
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{horizontal:true,showsHorizontalScrollIndicator:false,style:{marginTop:S.chipsTop,flexGrow:0},contentContainerStyle:{flexDirection:"row",gap:S.chipsGap},accessibilityLabel:HUB_COPY.markerGroups,children:HUB_SAMPLE_GROUPS.map((g,i)=>/* @__PURE__ */jsxRuntime.jsx(HubChip,{label:g.chip,selected:i===index,onPress:()=>setIndex(i),testID:`everfur-records-sheet-sample-group-${g.key}`},g.key))}),
|
|
932
968
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.Animated.View,{style:[{marginTop:S.slideTop,gap:S.slideGap},slide],accessibilityLabel:HUB_COPY.slideOf(group.chip,index+1,HUB_SAMPLE_GROUPS.length),testID:"everfur-records-sheet-sample-slide",children:[
|
|
933
969
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",style:{fontSize:17,lineHeight:22},children:group.chip}),
|
|
934
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",style:{marginTop:S.slideLeadTop,marginBottom:S.slideLeadBottom},children:group.lead}),group.markers.map(m=>m.flag!==void 0?/* @__PURE__ */jsxRuntime.jsx(FlaggedMarker,{marker:m,name:name},m.name):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius},children:/* @__PURE__ */jsxRuntime.jsx(MarkerLine,{marker:m})},m.name)),
|
|
970
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",style:{marginTop:S.slideLeadTop,marginBottom:S.slideLeadBottom},children:group.lead}),group.markers.map(m=>m.flag!==void 0?/* @__PURE__ */jsxRuntime.jsx(FlaggedMarker,{marker:m,name:name,poss:poss},m.name):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:S.markerGap,padding:S.markerPad,borderRadius:S.markerRadius},children:/* @__PURE__ */jsxRuntime.jsx(MarkerLine,{marker:m})},m.name)),
|
|
935
971
|
/* @__PURE__ */jsxRuntime.jsx(FromPage,{from:group.from},group.key)]})]})}),
|
|
936
972
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:S.moreGap,marginTop:S.moreTop},testID:"everfur-records-sheet-sample-more",children:HUB_SAMPLE_MORE.map((card,ci)=>{let rows=dog?card.rows:card.rows.filter(r=>!DOG_ONLY.test(r.title));return rows.length===0?null:/* @__PURE__ */jsxRuntime.jsx(HubReveal,{index:ci+1,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{gap:S.moreInnerGap,padding:S.morePad,borderRadius:S.moreRadius,backgroundColor:tints[card.tint]},testID:`everfur-records-sheet-sample-${card.key}`,children:[
|
|
937
973
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",alignItems:"center",gap:S.moreHeadGap},children:[
|
|
938
974
|
/* @__PURE__ */jsxRuntime.jsx(HubIcon,{name:icons[card.key],size:S.moreIcon}),
|
|
939
975
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySmBold",accessibilityRole:"header",style:{fontSize:17,lineHeight:22},children:card.title})]}),
|
|
940
976
|
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",children:card.lead}),
|
|
941
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:S.rowsGap},children:rows.map(row=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:S.rowMinHeight,paddingVertical:S.rowPadY,paddingHorizontal:S.rowPadX,borderRadius:S.rowRadius,backgroundColor:
|
|
942
|
-
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",style:{flexShrink:1},children:row.title}),row.pill!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:row.pill,tone:row.tone??"plain"}):/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"labelMono",color:
|
|
977
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{gap:S.rowsGap},children:rows.map(row=>/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:S.rowMinHeight,paddingVertical:S.rowPadY,paddingHorizontal:S.rowPadX,borderRadius:S.rowRadius,backgroundColor:look2.white},children:[
|
|
978
|
+
/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",style:{flexShrink:1},children:row.title}),row.pill!==void 0?/* @__PURE__ */jsxRuntime.jsx(HubPill,{label:row.pill,tone:row.tone??"plain"}):/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"labelMono",color:look2.muted,children:row.text??""})]},row.title))})]})},card.key)})})]})}function HubLegal(){let reduced=useEverfurTheme().motion.reducedMotion;/* @__PURE__ */
|
|
943
979
|
return jsxRuntime.jsx(HubReveal,{index:5,reduced:reduced,children:/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{marginTop:APP_HUB.screen.legalTop},testID:"everfur-records-hub-legal",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"fine",style:{textAlign:"center"},accessibilityRole:"text",testID:"records-footnote",children:HUB_COPY.legal})})})}function sourceKey(source){return source!==null&&typeof source=="object"&&typeof source.uri=="string"?source.uri:source}var HIDDEN6={accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",pointerEvents:"none"},STAGE_PET_HEIGHT=raphPx(".efh-stage","height")*raphPct(".efh-stage__pet","height");function SheetIcon({kind:kind,size:size=RAPH_RN_METRICS.icon,color:color}){let glyph;switch(kind){case"flask":glyph=/* @__PURE__ */jsxRuntime.jsx(FlaskGlyph,{size:size,color:color});break;case"thermo":glyph=/* @__PURE__ */jsxRuntime.jsx(ThermoGlyph,{size:size,color:color});break;case"heart":glyph=/* @__PURE__ */jsxRuntime.jsx(HeartGlyph,{size:size,color:color});break;case"wind":glyph=/* @__PURE__ */jsxRuntime.jsx(WindGlyph,{size:size,color:color});break;case"shield":glyph=/* @__PURE__ */jsxRuntime.jsx(ShieldGlyph,{size:size,color:color});break;case"folder":glyph=/* @__PURE__ */jsxRuntime.jsx(FolderGlyph,{size:size,color:color});break;case"clip":glyph=/* @__PURE__ */jsxRuntime.jsx(ClipboardGlyph,{size:size,color:color});break;case"clock":glyph=/* @__PURE__ */jsxRuntime.jsx(ClockFaceGlyph,{size:size,color:color});break;case"calendar":glyph=/* @__PURE__ */jsxRuntime.jsx(CalendarGlyph,{size:size,color:color});break;case"chevron":glyph=/* @__PURE__ */jsxRuntime.jsx(ChevronGlyph,{size:size,color:color,direction:"right"});break;case"upload":glyph=/* @__PURE__ */jsxRuntime.jsx(UploadArrowGlyph,{size:size,color:color});break;case"download":glyph=/* @__PURE__ */jsxRuntime.jsx(DownloadGlyph2,{size:size,color:color});break;default:glyph=null}/* @__PURE__ */
|
|
944
|
-
return jsxRuntime.jsx(reactNative.View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},...HIDDEN6,children:glyph})}var SheetKitContext=react.createContext(null);function useSheetKitValue(){let
|
|
945
|
-
return jsxRuntime.jsx(reactNative.View,{style:[s.pill,small?s.pillSmall:null,tones[tone],style],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[s.pillText,small?s.pillTextSmall:null,{color:ink}],children:
|
|
946
|
-
return jsxRuntime.jsx(reactNative.View,{style:[s.card,style],testID:testID,children:children})}function SheetButton({kind:kind,label:
|
|
947
|
-
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:
|
|
948
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[s.buttonText,row?s.buttonTextRow:null,{color:ink}],children:
|
|
980
|
+
return jsxRuntime.jsx(reactNative.View,{style:{width:size,height:size,alignItems:"center",justifyContent:"center"},...HIDDEN6,children:glyph})}var SheetKitContext=react.createContext(null);function useSheetKitValue(override){let own=useEverfurTheme(),theme=override??own;return react.useMemo(()=>{let look2=recordsSheetLook(theme);return{theme:theme,look:look2,s:makeSheetStyles(theme,look2)}},[theme])}function useRecordsSheetKitTheme(palette,fonts){let theme=useEverfurTheme(),font=fonts?.font,mono=fonts?.mono;return react.useMemo(()=>recordsSheetKitTheme(theme,palette,{...font!==void 0?{font:font}:{},...mono!==void 0?{mono:mono}:{}}),[theme,palette,font,mono])}var SheetKitProvider=SheetKitContext.Provider;function useSheetKit(){let own=useSheetKitValue();return react.useContext(SheetKitContext)??own}function SheetPill({label:label2,tone:tone,small:small=false,style:style,testID:testID}){let{s:s,look:look2}=useSheetKit();if(label2.trim().length===0)return null;let pad=small?7:10,edge=(width,color)=>({backgroundColor:look2.card,borderWidth:width,borderColor:color,paddingHorizontal:pad-width}),tones={watch:{backgroundColor:look2.watch},stable:{backgroundColor:look2.goTint},later:edge(1.25,look2.line),clear:edge(1.5,look2.go),plain:edge(1.5,look2.plainEdge),high:edge(1.25,look2.alert)},ink=tone==="later"?look2.muted:tone==="clear"?look2.go:tone==="high"?look2.alert:look2.ink;/* @__PURE__ */
|
|
981
|
+
return jsxRuntime.jsx(reactNative.View,{style:[s.pill,small?s.pillSmall:null,tones[tone],style],testID:testID,children:/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"compact",style:[s.pillText,small?s.pillTextSmall:null,{color:ink}],children:label2})})}function SheetCard({children:children,style:style,testID:testID}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
982
|
+
return jsxRuntime.jsx(reactNative.View,{style:[s.card,style],testID:testID,children:children})}function SheetButton({kind:kind,label:label2,icon:icon,onPress:onPress,row:row=false,testID:testID}){let{s:s,look:look2,theme:theme}=useSheetKit(),still=theme.motion.reducedMotion,ink=kind==="ink"?look2.onFill:look2.ink;/* @__PURE__ */
|
|
983
|
+
return jsxRuntime.jsxs(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label2,testID:testID,style:({pressed:pressed})=>[s.button,row?s.buttonRow:null,kind==="ink"?{backgroundColor:look2.fill}:{backgroundColor:look2.card,borderWidth:1.5,borderColor:look2.ink},pressed&&!still?{transform:[{scale:RECORDS_MOTION.pressScale}]}:null],children:[icon!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:icon,size:20,color:ink}):null,
|
|
984
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{tier:"control",style:[s.buttonText,row?s.buttonTextRow:null,{color:ink}],children:label2})]})}function SheetMarkerRow({name:name,value:value,unit:unit,range:range,at:at,pill:pill,testID:testID}){let{s:s,look:look2}=useSheetKit();/* @__PURE__ */
|
|
949
985
|
return jsxRuntime.jsxs(reactNative.View,{style:s.mk,testID:testID,children:[
|
|
950
986
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkText,children:[
|
|
951
987
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkNameRow,children:[
|
|
952
988
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkName,children:name}),pill!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:pill,tone:"high"}):null]}),
|
|
953
989
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkLine,children:[
|
|
954
990
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkValue,children:value}),unit?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkLineText,children:unit}):null,range!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.mkLineText,children:`· ${range}`}):null]})]}),at!==null?/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.mkBar,...HIDDEN6,children:[
|
|
955
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarIn,{backgroundColor:
|
|
956
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarDot,{left:`${at}%`,backgroundColor:
|
|
957
|
-
return jsxRuntime.jsx(reactNative.View,{style:ABSOLUTE_FILL,onLayout:onLayout,...HIDDEN6,children:segments.map(seg=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:seg.left,top:seg.top,width:seg.length,height:1.5,backgroundColor:color,transform:[{rotate:`${seg.angle}deg`}]}},seg.key))})}function makeSheetStyles(theme,look){let body=face(theme,"regular"),bold=face(theme,"bold"),heading=headingFace(theme,"bold"),mono=face(theme,"mono"),monoBold=face(theme,"monoBold"),lh=(size,ratio)=>lh100(size*ratio);return reactNative.StyleSheet.create({scroll:{flexGrow:1},topSlot:{paddingHorizontal:RAPH_RN_METRICS.sheetPadX},sheet:{flexGrow:1,gap:RAPH_RN_METRICS.gap,paddingTop:RAPH_RN_METRICS.sheetPadTop,paddingHorizontal:RAPH_RN_METRICS.sheetPadX,paddingBottom:RAPH_RN_METRICS.sheetPadBottom,borderTopLeftRadius:RAPH_RN_METRICS.sheetRadius,borderTopRightRadius:RAPH_RN_METRICS.sheetRadius,backgroundColor:look.ground},sheetUnderSlot:{marginTop:RAPH_RN_METRICS.sheetGap},card:{padding:RAPH_RN_METRICS.cardPad,backgroundColor:look.card,borderRadius:RAPH_RN_METRICS.cardRadius,shadowColor:"#000000",shadowOpacity:look.dark?0:.09,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:look.dark?0:1,borderWidth:look.dark?1:0,borderColor:look.line},cardHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:12},cardTitle:{...heading,fontSize:RAPH_RN_METRICS.cardTitle,lineHeight:lh(RAPH_RN_METRICS.cardTitle,1.25),letterSpacing:-.36,color:look.ink},cardTitleGap:{marginBottom:12},sec:{marginTop:8,marginBottom:12},head:{marginBottom:raphPx(".efh-head","marginBottom")},name:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.44,color:look.ink,flexShrink:1},meta:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),letterSpacing:.26,textTransform:"uppercase",color:look.muted},label:{...monoBold,marginTop:raphPx(".efh-head__from","marginTop"),fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},vitals:{flexDirection:"row",gap:8,marginTop:8},stage:{position:"relative",height:raphPx(".efh-stage","height"),marginTop:raphPx(".efh-stage","marginTop"),marginHorizontal:raphPx(".efh-stage","marginLeft"),overflow:"hidden"},stageGrass:{position:"absolute",left:0,right:0,bottom:0,height:`${raphPct(".efh-stage__grass","height")*100}%`,overflow:"hidden"},stagePet:{position:"absolute",left:`${raphPct(".efh-stage__pet","left")*100}%`,bottom:raphPx(".efh-stage__pet","bottom"),height:STAGE_PET_HEIGHT},stageVitals:{position:"absolute",top:raphPx(".efh-stage .efh-vitals","top"),left:raphPx(".efh-stage .efh-vitals","left"),gap:raphPx(".efh-stage .efh-vitals","gap")},vital:{flex:1,minWidth:0},vitalTop:{flexDirection:"row",alignItems:"center",gap:6},vitalValue:{...bold,fontSize:17,lineHeight:lh(17,1.2),color:look.ink},vitalUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},vitalLabel:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},due:{gap:4,marginHorizontal:-12},dueRow:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius},dueText:{flex:1,minWidth:0,gap:2},duePill:{alignSelf:"center"},dueTitle:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},dueWhen:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},pill:{minHeight:RAPH_RN_METRICS.pill,paddingHorizontal:10,borderRadius:999,alignItems:"center",justifyContent:"center",alignSelf:"flex-start"},pillSmall:{minHeight:22,paddingHorizontal:7},pillText:{...monoBold,fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,letterSpacing:.72,textTransform:"uppercase"},pillTextSmall:{fontSize:10.5,letterSpacing:.21},tiles:{flexDirection:"row",flexWrap:"wrap",gap:RAPH_RN_METRICS.tileGap},tile:{flexGrow:1,flexBasis:"45%",minWidth:0,gap:8,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},tileTop:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between"},tileTitle:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.25),letterSpacing:-.15,color:look.ink},tileFoot:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8,minHeight:28},tileNum:{...bold,fontSize:RAPH_RN_METRICS.tileNum,lineHeight:RAPH_RN_METRICS.tileNum+2,letterSpacing:-.4,color:look.ink},tileUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},emptyLine:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),color:look.muted},wt:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8},wtValue:{...bold,fontSize:RAPH_RN_METRICS.big,lineHeight:RAPH_RN_METRICS.big+4,letterSpacing:-.64,color:look.ink},wtSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},chart:{marginTop:20},plot:{position:"relative",height:RAPH_RN_METRICS.plot},point:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-6,borderRadius:6,borderWidth:1.5,borderColor:look.card},pointLabel:{...face(theme,"medium"),position:"absolute",bottom:16,width:64,left:-26,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,color:look.dark?look.text:RAPH_CHARCOAL},xAxis:{position:"relative",height:18,marginTop:8},xTick:{...mono,position:"absolute",top:0,width:56,marginLeft:-28,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.3),color:look.muted},key:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:12},keyDot:{width:12,height:12,borderRadius:6,backgroundColor:look.ink},keyText:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look.muted},tlKey:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},tlKeyDot:{width:10,height:10,borderRadius:5,borderWidth:2.5,borderColor:look.ink,backgroundColor:look.card},tlYear:{...monoBold,marginTop:20,marginBottom:12,marginLeft:40,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look.muted},tlItem:{position:"relative",flexDirection:"row",gap:16,paddingBottom:24},tlItemLast:{paddingBottom:0},tlRail:{position:"absolute",left:11,top:22,bottom:-2,width:2,borderRadius:1,backgroundColor:look.line},tlRailEnd:{bottom:12},tlDot:{width:16,height:16,marginTop:3,marginHorizontal:4,borderRadius:8,borderWidth:3,borderColor:look.ink,backgroundColor:look.card},tlBody:{flex:1,minWidth:0},tlBtn:{marginTop:-8,marginHorizontal:-8,paddingVertical:8,paddingLeft:8,paddingRight:36,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},tlChevron:{position:"absolute",right:8,top:"50%",marginTop:-10},tlDate:{...mono,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.48,textTransform:"uppercase",color:look.muted},tlTitle:{...bold,marginTop:2,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},tlText:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},pull:{paddingTop:4,paddingBottom:24,paddingLeft:40},pullStep:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.ink},pullBar:{height:6,marginTop:10,overflow:"hidden",borderRadius:999,backgroundColor:look.line},pullFill:{height:"100%",backgroundColor:look.accent},failed:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.alertTint},failedText:{...bold,flex:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.alertDeep},add:{gap:12},addHead:{flexDirection:"row",alignItems:"center",gap:8},addLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},sources:{gap:6},source:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:12,paddingVertical:10,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.rowGround},sourceLabel:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},sourceDetail:{...body,fontSize:RAPH_RN_METRICS.small,color:look.muted},addActs:{gap:12,paddingTop:4},button:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,minHeight:RAPH_RN_METRICS.button,paddingHorizontal:20,borderRadius:999},buttonRow:{minHeight:RAPH_RN_METRICS.rowButton,paddingHorizontal:16},buttonText:{...bold,fontSize:16,lineHeight:20},buttonTextRow:{fontSize:RAPH_RN_METRICS.body},noneWithScene:{paddingTop:raphPx(".efh-none","paddingTop")},scene:{position:"relative",height:RAPH_RN_SCENE.height,marginHorizontal:raphPx(".efh-none__scene","marginLeft"),marginBottom:raphPx(".efh-none__scene","marginBottom"),overflow:"hidden",borderTopLeftRadius:RAPH_RN_METRICS.cardRadius,borderTopRightRadius:RAPH_RN_METRICS.cardRadius},sceneGrass:{position:"absolute",left:0,right:0,bottom:0,height:RAPH_RN_SCENE.grassHeight,overflow:"hidden"},scenePet:{position:"absolute",left:"50%",bottom:RAPH_RN_SCENE.petBottom,height:RAPH_RN_SCENE.petHeight},noneTitle:{...heading,fontSize:raphPx(".efh-none__t","fontSize"),lineHeight:raphPx(".efh-none__t","lineHeight"),letterSpacing:raphPx(".efh-none__t","letterSpacing"),color:look.ink},noneLead:{...body,marginTop:raphPx(".efh-none__lead","marginTop"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.text},noneLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:4,marginTop:raphPx(".efh-none__lead","marginTop")},noneLineText:{...body,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.text},noneLink:{...bold,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.ink,textDecorationLine:"underline"},repeatLine:{...bold,marginTop:raphPx(".efh-ways","gap"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look.ink},ways:{gap:raphPx(".efh-ways","gap"),marginTop:raphPx(".efh-ways","marginTop")},way:{flexDirection:"row",alignItems:"center",gap:raphPx(".efh-way","columnGap"),padding:raphPx(".efh-way","paddingTop"),borderRadius:raphPx(".efh-way","borderRadius")},wayText:{flex:1,minWidth:0,gap:raphPx(".efh-way__w","gap")},wayTitle:{...bold,fontSize:raphPx(".efh-way__t","fontSize"),lineHeight:raphPx(".efh-way__t","lineHeight")},wayDetail:{...body,fontSize:raphPx(".efh-way__x","fontSize"),lineHeight:raphPx(".efh-way__x","lineHeight")},tracker:{marginTop:16},step:{flexDirection:"row",gap:16,paddingBottom:20},stepLast:{paddingBottom:0},stepRail:{position:"absolute",left:TRACKER_DOT/2-1,top:TRACKER_DOT+2,bottom:2,width:2,borderRadius:1,backgroundColor:look.line},stepRailDone:{backgroundColor:look.ink},stepDot:{width:TRACKER_DOT,height:TRACKER_DOT,borderRadius:TRACKER_DOT/2,borderWidth:2,borderColor:look.line,backgroundColor:look.card,alignItems:"center",justifyContent:"center"},stepDotOn:{borderColor:look.ink},stepDotDone:{backgroundColor:look.fill,borderColor:look.fill},stepNow:{width:10,height:10,borderRadius:5,backgroundColor:look.accent},stepText:{flex:1,minWidth:0,paddingTop:3,gap:2},stepTitle:{...bold,fontSize:raphPx(".efh-mk__name","fontSize"),lineHeight:22,color:look.ink},stepWhen:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look.muted},peek:{gap:12,marginTop:12},peekHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:12},peekLead:{...body,marginTop:-4,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},peekLabsTitle:{marginBottom:raphPx(".efh-peek__labs .efh-card__title","marginBottom")},peekGroup:{marginBottom:raphPx(".efh-peek__g","marginBottom")},peekGroupTitle:{...bold,fontSize:raphPx(".efh-peek__g b","fontSize"),lineHeight:lh100(raphPx(".efh-peek__g b","fontSize")*(raphPx(".efh-peek__g","lineHeight")/raphPx(".efh-peek__g","fontSize"))),color:look.ink},peekGroupLead:{...body,fontSize:raphPx(".efh-peek__g","fontSize"),lineHeight:raphPx(".efh-peek__g","lineHeight"),color:look.muted},more:{gap:10},moreCard:{gap:10,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},moreHead:{flexDirection:"row",alignItems:"center",gap:8},moreTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3),color:look.ink},moreLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look.text},moreRows:{gap:6},moreRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingVertical:8,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look.card},moreRowLabel:{...body,flexShrink:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look.text},moreWhen:{...mono,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.24,color:look.muted},note:{...body,marginTop:raphPx(".efh-sheet .rec-note","marginTop"),fontSize:raphPx(".rec-note","fontSize"),textAlign:"center",color:look.muted},mks:{gap:2,marginHorizontal:-8},mk:{flexDirection:"row",alignItems:"center",gap:12,paddingVertical:10,paddingHorizontal:8},mkText:{flex:1,minWidth:0},mkNameRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},mkName:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look.ink},mkLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",rowGap:raphPx(".efh-mk__line","rowGap"),columnGap:raphPx(".efh-mk__line","columnGap"),marginTop:raphPx(".efh-mk__line","marginTop")},mkLineText:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look.muted,fontVariant:["tabular-nums"]},mkValue:{...bold,fontSize:raphPx(".efh-mk__line b","fontSize"),lineHeight:lh100(raphPx(".efh-mk__line b","fontSize")*(raphPx(".efh-mk__line","lineHeight")/raphPx(".efh-mk__line","fontSize"))),color:look.text,fontVariant:["tabular-nums"]},mkBar:{position:"relative",width:96,height:6,borderRadius:999,backgroundColor:look.barTrack},mkBarIn:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999},mkBarDot:{position:"absolute",top:-2,width:10,height:10,marginLeft:-5,borderRadius:5,borderWidth:2},topRisk:{gap:8,backgroundColor:look.topFill,borderRadius:22,borderWidth:0,shadowOpacity:0,elevation:0},topRiskKicker:{flexDirection:"row",alignItems:"center",gap:6},topRiskDot:{width:8,height:8,borderRadius:4,backgroundColor:look.alert},topRiskK:{...monoBold,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.72,textTransform:"uppercase",color:look.topKicker},topRiskText:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.35),color:look.topInk},disclaimer:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),textAlign:"center",color:look.muted},lab:{gap:RAPH_RN_METRICS.gap,paddingTop:8,paddingHorizontal:16,paddingBottom:32,backgroundColor:look.ground},labTitle:{...face(theme,"medium"),fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.33,color:look.ink},labMeta:{...mono,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.45),color:look.muted},latest:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:12,rowGap:4},latestSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look.muted},change:{...body,marginTop:12,fontSize:RAPH_RN_METRICS.body,color:look.text},changeLead:{...bold,color:look.ink},ctx:{gap:12},ctxText:{...body,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.55),color:look.text},labBody:{flexDirection:"row",gap:8},rail:{width:8,height:RAPH_RN_METRICS.plot,overflow:"hidden",borderRadius:2},legend:{width:82,height:RAPH_RN_METRICS.plot,position:"relative"},range:{...monoBold,position:"absolute",left:0,right:0,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.2),letterSpacing:.24,textTransform:"uppercase",color:look.dark?look.text:RAPH_CHARCOAL},band:{position:"absolute",left:0,right:0,top:"25%",height:"50%",backgroundColor:look.goTint}})}var RAPH_CHARCOAL="#3D3D3D",TRACKER_DOT=28,lh100=value=>Math.round(value*100)/100;function EverfurRecordsLabDetail({petRef:petRef,petName:petName,markerId:markerId,renderExtra:renderExtra,onAsk:onAsk,renderAskButton:renderAskButton,style:style}){let view=useRecordsMarkers(petRef).markers,model=view===null||view.withheld?null:buildSheetLabModel(view,markerId);if(model===null)return null;let marker=view?.markers.find(m=>m.markerId===markerId)??null;/* @__PURE__ */
|
|
958
|
-
return jsxRuntime.jsx(
|
|
991
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarIn,{backgroundColor:look2.go}]}),
|
|
992
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.mkBarDot,{left:`${at}%`,backgroundColor:look2.ink,borderColor:look2.card}]})]}):null]})}function ChartLine({points:points,color:color}){let[box3,setBox]=react.useState(null),onLayout=e=>{let{width:width,height:height}=e.nativeEvent.layout;(box3===null||box3.w!==width||box3.h!==height)&&setBox({w:width,h:height})},segments=box3===null?[]:points.slice(1).map((p,i)=>{let a=points[i]??p,x1=a.x/100*box3.w,y1=a.y/100*box3.h,x2=p.x/100*box3.w,y2=p.y/100*box3.h,length=Math.hypot(x2-x1,y2-y1),angle=Math.atan2(y2-y1,x2-x1)*180/Math.PI;return{key:i,left:(x1+x2)/2-length/2,top:(y1+y2)/2-.75,length:length,angle:angle}});/* @__PURE__ */
|
|
993
|
+
return jsxRuntime.jsx(reactNative.View,{style:ABSOLUTE_FILL,onLayout:onLayout,...HIDDEN6,children:segments.map(seg=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{position:"absolute",left:seg.left,top:seg.top,width:seg.length,height:1.5,backgroundColor:color,transform:[{rotate:`${seg.angle}deg`}]}},seg.key))})}function makeSheetStyles(theme,look2){let body=face(theme,"regular"),bold=face(theme,"bold"),heading=headingFace(theme,"bold"),mono=face(theme,"mono"),monoBold=face(theme,"monoBold"),lh=(size,ratio)=>lh100(size*ratio);return reactNative.StyleSheet.create({scroll:{flexGrow:1},topSlot:{paddingHorizontal:RAPH_RN_METRICS.sheetPadX},sheet:{flexGrow:1,gap:RAPH_RN_METRICS.gap,paddingTop:RAPH_RN_METRICS.sheetPadTop,paddingHorizontal:RAPH_RN_METRICS.sheetPadX,paddingBottom:RAPH_RN_METRICS.sheetPadBottom,borderTopLeftRadius:RAPH_RN_METRICS.sheetRadius,borderTopRightRadius:RAPH_RN_METRICS.sheetRadius,backgroundColor:look2.ground},sheetUnderSlot:{marginTop:RAPH_RN_METRICS.sheetGap},card:{padding:RAPH_RN_METRICS.cardPad,backgroundColor:look2.card,borderRadius:RAPH_RN_METRICS.cardRadius,shadowColor:"#000000",shadowOpacity:look2.dark?0:.09,shadowRadius:3,shadowOffset:{width:0,height:1},elevation:look2.dark?0:1,borderWidth:look2.dark?1:0,borderColor:look2.line},cardHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:8,marginBottom:12},cardTitle:{...heading,fontSize:RAPH_RN_METRICS.cardTitle,lineHeight:lh(RAPH_RN_METRICS.cardTitle,1.25),letterSpacing:-.36,color:look2.ink},cardTitleGap:{marginBottom:12},sec:{marginTop:8,marginBottom:12},head:{marginBottom:raphPx(".efh-head","marginBottom")},name:{...heading,fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.44,color:look2.ink,flexShrink:1},meta:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),letterSpacing:.26,textTransform:"uppercase",color:look2.muted},label:{...monoBold,marginTop:raphPx(".efh-head__from","marginTop"),fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look2.muted},vitals:{flexDirection:"row",gap:8,marginTop:8},stage:{position:"relative",height:raphPx(".efh-stage","height"),marginTop:raphPx(".efh-stage","marginTop"),marginHorizontal:raphPx(".efh-stage","marginLeft"),overflow:"hidden"},stageGrass:{position:"absolute",left:0,right:0,bottom:0,height:`${raphPct(".efh-stage__grass","height")*100}%`,overflow:"hidden"},stagePet:{position:"absolute",left:`${raphPct(".efh-stage__pet","left")*100}%`,bottom:raphPx(".efh-stage__pet","bottom"),height:STAGE_PET_HEIGHT},stageVitals:{position:"absolute",top:raphPx(".efh-stage .efh-vitals","top"),left:raphPx(".efh-stage .efh-vitals","left"),gap:raphPx(".efh-stage .efh-vitals","gap")},vital:{flex:1,minWidth:0},vitalTop:{flexDirection:"row",alignItems:"center",gap:6},vitalValue:{...bold,fontSize:17,lineHeight:lh(17,1.2),color:look2.ink},vitalUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look2.muted},vitalLabel:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look2.muted},due:{gap:4,marginHorizontal:-12},dueRow:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius},dueText:{flex:1,minWidth:0,gap:2},duePill:{alignSelf:"center"},dueTitle:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look2.ink},dueWhen:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look2.muted},pill:{minHeight:RAPH_RN_METRICS.pill,paddingHorizontal:10,borderRadius:999,alignItems:"center",justifyContent:"center",alignSelf:"flex-start"},pillSmall:{minHeight:22,paddingHorizontal:7},pillText:{...monoBold,fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,letterSpacing:.72,textTransform:"uppercase"},pillTextSmall:{fontSize:10.5,letterSpacing:.21},tiles:{flexDirection:"row",flexWrap:"wrap",gap:RAPH_RN_METRICS.tileGap},tile:{flexGrow:1,flexBasis:"45%",minWidth:0,gap:8,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},tileTop:{flexDirection:"row",alignItems:"flex-start",justifyContent:"space-between"},tileTitle:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.25),letterSpacing:-.15,color:look2.ink},tileFoot:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8,minHeight:28},tileNum:{...bold,fontSize:RAPH_RN_METRICS.tileNum,lineHeight:RAPH_RN_METRICS.tileNum+2,letterSpacing:-.4,color:look2.ink},tileUnit:{...body,fontSize:RAPH_RN_METRICS.small,color:look2.muted},emptyLine:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),color:look2.muted},wt:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",gap:8},wtValue:{...bold,fontSize:RAPH_RN_METRICS.big,lineHeight:RAPH_RN_METRICS.big+4,letterSpacing:-.64,color:look2.ink},wtSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look2.muted},chart:{marginTop:20},plot:{position:"relative",height:RAPH_RN_METRICS.plot},point:{position:"absolute",width:12,height:12,marginLeft:-6,marginTop:-6,borderRadius:6,borderWidth:1.5,borderColor:look2.card},pointLabel:{...face(theme,"medium"),position:"absolute",bottom:16,width:64,left:-26,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:RAPH_RN_METRICS.mono+2,color:look2.dark?look2.text:RAPH_CHARCOAL},xAxis:{position:"relative",height:18,marginTop:8},xTick:{...mono,position:"absolute",top:0,width:56,marginLeft:-28,textAlign:"center",fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.3),color:look2.muted},key:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:12},keyDot:{width:12,height:12,borderRadius:6,backgroundColor:look2.ink},keyText:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.4),color:look2.muted},tlKey:{flexDirection:"row",alignItems:"center",gap:6,marginBottom:4},tlKeyDot:{width:10,height:10,borderRadius:5,borderWidth:2.5,borderColor:look2.ink,backgroundColor:look2.card},tlYear:{...monoBold,marginTop:20,marginBottom:12,marginLeft:40,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.72,textTransform:"uppercase",color:look2.muted},tlItem:{position:"relative",flexDirection:"row",gap:16,paddingBottom:24},tlItemLast:{paddingBottom:0},tlRail:{position:"absolute",left:11,top:22,bottom:-2,width:2,borderRadius:1,backgroundColor:look2.line},tlRailEnd:{bottom:12},tlDot:{width:16,height:16,marginTop:3,marginHorizontal:4,borderRadius:8,borderWidth:3,borderColor:look2.ink,backgroundColor:look2.card},tlBody:{flex:1,minWidth:0},tlBtn:{marginTop:-8,marginHorizontal:-8,paddingVertical:8,paddingLeft:8,paddingRight:36,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look2.alertTint},tlChevron:{position:"absolute",right:8,top:"50%",marginTop:-10},tlDate:{...mono,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.4),letterSpacing:.48,textTransform:"uppercase",color:look2.muted},tlTitle:{...bold,marginTop:2,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look2.ink},tlText:{...body,marginTop:2,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look2.text},pull:{paddingTop:4,paddingBottom:24,paddingLeft:40},pullStep:{...bold,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look2.ink},pullBar:{height:6,marginTop:10,overflow:"hidden",borderRadius:999,backgroundColor:look2.line},pullFill:{height:"100%",backgroundColor:look2.accent},failed:{flexDirection:"row",alignItems:"center",gap:12,padding:12,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look2.alertTint},failedText:{...bold,flex:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look2.alertDeep},add:{gap:12},addHead:{flexDirection:"row",alignItems:"center",gap:8},addLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look2.text},sources:{gap:6},source:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",columnGap:12,paddingVertical:10,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look2.rowGround},sourceLabel:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look2.text},sourceDetail:{...body,fontSize:RAPH_RN_METRICS.small,color:look2.muted},addActs:{gap:12,paddingTop:4},button:{flexDirection:"row",alignItems:"center",justifyContent:"center",gap:8,minHeight:RAPH_RN_METRICS.button,paddingHorizontal:20,borderRadius:999},buttonRow:{minHeight:RAPH_RN_METRICS.rowButton,paddingHorizontal:16},buttonText:{...bold,fontSize:16,lineHeight:20},buttonTextRow:{fontSize:RAPH_RN_METRICS.body},noneWithScene:{paddingTop:raphPx(".efh-none","paddingTop")},scene:{position:"relative",height:RAPH_RN_SCENE.height,marginHorizontal:raphPx(".efh-none__scene","marginLeft"),marginBottom:raphPx(".efh-none__scene","marginBottom"),overflow:"hidden",borderTopLeftRadius:RAPH_RN_METRICS.cardRadius,borderTopRightRadius:RAPH_RN_METRICS.cardRadius},sceneGrass:{position:"absolute",left:0,right:0,bottom:0,height:RAPH_RN_SCENE.grassHeight,overflow:"hidden"},scenePet:{position:"absolute",left:"50%",bottom:RAPH_RN_SCENE.petBottom,height:RAPH_RN_SCENE.petHeight},noneTitle:{...heading,fontSize:raphPx(".efh-none__t","fontSize"),lineHeight:raphPx(".efh-none__t","lineHeight"),letterSpacing:raphPx(".efh-none__t","letterSpacing"),color:look2.ink},noneLead:{...body,marginTop:raphPx(".efh-none__lead","marginTop"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look2.text},noneLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:4,marginTop:raphPx(".efh-none__lead","marginTop")},noneLineText:{...body,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look2.text},noneLink:{...bold,fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look2.ink,textDecorationLine:"underline"},repeatLine:{...bold,marginTop:raphPx(".efh-ways","gap"),fontSize:raphPx(".efh-none__lead","fontSize"),lineHeight:raphPx(".efh-none__lead","lineHeight"),color:look2.ink},ways:{gap:raphPx(".efh-ways","gap"),marginTop:raphPx(".efh-ways","marginTop")},way:{flexDirection:"row",alignItems:"center",gap:raphPx(".efh-way","columnGap"),padding:raphPx(".efh-way","paddingTop"),borderRadius:raphPx(".efh-way","borderRadius")},wayText:{flex:1,minWidth:0,gap:raphPx(".efh-way__w","gap")},wayTitle:{...bold,fontSize:raphPx(".efh-way__t","fontSize"),lineHeight:raphPx(".efh-way__t","lineHeight")},wayDetail:{...body,fontSize:raphPx(".efh-way__x","fontSize"),lineHeight:raphPx(".efh-way__x","lineHeight")},tracker:{marginTop:16},step:{flexDirection:"row",gap:16,paddingBottom:20},stepLast:{paddingBottom:0},stepRail:{position:"absolute",left:TRACKER_DOT/2-1,top:TRACKER_DOT+2,bottom:2,width:2,borderRadius:1,backgroundColor:look2.line},stepRailDone:{backgroundColor:look2.ink},stepDot:{width:TRACKER_DOT,height:TRACKER_DOT,borderRadius:TRACKER_DOT/2,borderWidth:2,borderColor:look2.line,backgroundColor:look2.card,alignItems:"center",justifyContent:"center"},stepDotOn:{borderColor:look2.ink},stepDotDone:{backgroundColor:look2.fill,borderColor:look2.fill},stepNow:{width:10,height:10,borderRadius:5,backgroundColor:look2.accent},stepText:{flex:1,minWidth:0,paddingTop:3,gap:2},stepTitle:{...bold,fontSize:raphPx(".efh-mk__name","fontSize"),lineHeight:22,color:look2.ink},stepWhen:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look2.muted},peek:{gap:12,marginTop:12},peekHead:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:12},peekLead:{...body,marginTop:-4,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look2.text},peekLabsTitle:{marginBottom:raphPx(".efh-peek__labs .efh-card__title","marginBottom")},peekGroup:{marginBottom:raphPx(".efh-peek__g","marginBottom")},peekGroupTitle:{...bold,fontSize:raphPx(".efh-peek__g b","fontSize"),lineHeight:lh100(raphPx(".efh-peek__g b","fontSize")*(raphPx(".efh-peek__g","lineHeight")/raphPx(".efh-peek__g","fontSize"))),color:look2.ink},peekGroupLead:{...body,fontSize:raphPx(".efh-peek__g","fontSize"),lineHeight:raphPx(".efh-peek__g","lineHeight"),color:look2.muted},more:{gap:10},moreCard:{gap:10,padding:16,borderRadius:RAPH_RN_METRICS.cardRadius},moreHead:{flexDirection:"row",alignItems:"center",gap:8},moreTitle:{...bold,fontSize:16,lineHeight:lh(16,1.3),color:look2.ink},moreLead:{...body,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.5),color:look2.text},moreRows:{gap:6},moreRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:12,minHeight:44,paddingVertical:8,paddingHorizontal:14,borderRadius:RAPH_RN_METRICS.rowRadius,backgroundColor:look2.card},moreRowLabel:{...body,flexShrink:1,fontSize:RAPH_RN_METRICS.body,lineHeight:lh(RAPH_RN_METRICS.body,1.4),color:look2.text},moreWhen:{...mono,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.24,color:look2.muted},note:{...body,marginTop:raphPx(".efh-sheet .rec-note","marginTop"),fontSize:raphPx(".rec-note","fontSize"),textAlign:"center",color:look2.muted},mks:{gap:2,marginHorizontal:-8},mk:{flexDirection:"row",alignItems:"center",gap:12,paddingVertical:10,paddingHorizontal:8},mkText:{flex:1,minWidth:0},mkNameRow:{flexDirection:"row",flexWrap:"wrap",alignItems:"center",gap:8},mkName:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.3),color:look2.ink},mkLine:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",rowGap:raphPx(".efh-mk__line","rowGap"),columnGap:raphPx(".efh-mk__line","columnGap"),marginTop:raphPx(".efh-mk__line","marginTop")},mkLineText:{...body,fontSize:raphPx(".efh-mk__line","fontSize"),lineHeight:raphPx(".efh-mk__line","lineHeight"),color:look2.muted,fontVariant:["tabular-nums"]},mkValue:{...bold,fontSize:raphPx(".efh-mk__line b","fontSize"),lineHeight:lh100(raphPx(".efh-mk__line b","fontSize")*(raphPx(".efh-mk__line","lineHeight")/raphPx(".efh-mk__line","fontSize"))),color:look2.text,fontVariant:["tabular-nums"]},mkBar:{position:"relative",width:96,height:6,borderRadius:999,backgroundColor:look2.barTrack},mkBarIn:{position:"absolute",top:0,bottom:0,left:"20%",right:"20%",borderRadius:999},mkBarDot:{position:"absolute",top:-2,width:10,height:10,marginLeft:-5,borderRadius:5,borderWidth:2},topRisk:{gap:8,backgroundColor:look2.topFill,borderRadius:22,borderWidth:0,shadowOpacity:0,elevation:0},topRiskKicker:{flexDirection:"row",alignItems:"center",gap:6},topRiskDot:{width:8,height:8,borderRadius:4,backgroundColor:look2.alert},topRiskK:{...monoBold,fontSize:RAPH_RN_METRICS.mono,letterSpacing:.72,textTransform:"uppercase",color:look2.topKicker},topRiskText:{...bold,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.35),color:look2.topInk},disclaimer:{...body,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.5),textAlign:"center",color:look2.muted},lab:{gap:RAPH_RN_METRICS.gap,paddingTop:8,paddingHorizontal:16,paddingBottom:32,backgroundColor:look2.ground},labTitle:{...face(theme,"medium"),fontSize:RAPH_RN_METRICS.name,lineHeight:lh(RAPH_RN_METRICS.name,1.2),letterSpacing:-.33,color:look2.ink},labMeta:{...mono,fontSize:RAPH_RN_METRICS.small,lineHeight:lh(RAPH_RN_METRICS.small,1.45),color:look2.muted},latest:{flexDirection:"row",flexWrap:"wrap",alignItems:"baseline",columnGap:12,rowGap:4},latestSub:{...body,fontSize:RAPH_RN_METRICS.body,color:look2.muted},change:{...body,marginTop:12,fontSize:RAPH_RN_METRICS.body,color:look2.text},changeLead:{...bold,color:look2.ink},ctx:{gap:12},ctxText:{...body,fontSize:RAPH_RN_METRICS.rowTitle,lineHeight:lh(RAPH_RN_METRICS.rowTitle,1.55),color:look2.text},labBody:{flexDirection:"row",gap:8},rail:{width:8,height:RAPH_RN_METRICS.plot,overflow:"hidden",borderRadius:2},legend:{width:82,height:RAPH_RN_METRICS.plot,position:"relative"},range:{...monoBold,position:"absolute",left:0,right:0,fontSize:RAPH_RN_METRICS.mono,lineHeight:lh(RAPH_RN_METRICS.mono,1.2),letterSpacing:.24,textTransform:"uppercase",color:look2.dark?look2.text:RAPH_CHARCOAL},band:{position:"absolute",left:0,right:0,top:"25%",height:"50%",backgroundColor:look2.goTint}})}var RAPH_CHARCOAL="#3D3D3D",TRACKER_DOT=28,lh100=value=>Math.round(value*100)/100;function EverfurRecordsLabDetail({palette:palette,fonts:fonts,...rest}){return palette===void 0&&fonts===void 0?/* @__PURE__ */jsxRuntime.jsx(LabDetail,{...rest}):/* @__PURE__ */jsxRuntime.jsx(LabKit,{palette:palette,fonts:fonts,children:/* @__PURE__ */jsxRuntime.jsx(LabDetail,{...rest})})}function LabKit({palette:palette,fonts:fonts,children:children}){let kitTheme=useRecordsSheetKitTheme(palette,fonts),kit=useSheetKitValue(kitTheme);/* @__PURE__ */
|
|
994
|
+
return jsxRuntime.jsx(SheetKitProvider,{value:kit,children:children})}function LabDetail({petRef:petRef,petName:petName,markerId:markerId,renderExtra:renderExtra,onAsk:onAsk,renderAskButton:renderAskButton,style:style}){let view=useRecordsMarkers(petRef).markers,model=view===null||view.withheld?null:buildSheetLabModel(view,markerId);if(model===null)return null;let marker=view?.markers.find(m=>m.markerId===markerId)??null;/* @__PURE__ */
|
|
995
|
+
return jsxRuntime.jsx(LabBody,{model:model,renderExtra:renderExtra,ask:onAsk!==void 0&&marker!==null?()=>{let built=buildMarkerAskPrompt(petName,{canonicalName:marker.name,markerId:marker.markerId,latestValueText:model.latest,statusText:model.pill,trajectoryText:null,meaningText:marker.meaning});onAsk(built.prompt,built.entityRef)}:void 0,renderAskButton:renderAskButton,style:style})}function LabBody({model:model,renderExtra:renderExtra,ask:ask,renderAskButton:renderAskButton,style:style}){let{s:s,look:look2}=useSheetKit();/* @__PURE__ */
|
|
959
996
|
return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.lab,style],testID:`everfur-records-lab-${model.markerId}`,children:[
|
|
960
997
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{children:[
|
|
961
998
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.labTitle,accessibilityRole:"header",children:model.name}),model.meta!==null?/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.labMeta,children:model.meta}):null]}),
|
|
@@ -963,7 +1000,7 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.lab,styl
|
|
|
963
1000
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.cardHead,children:[
|
|
964
1001
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:SHEET_COPY.latestReading}),model.pill!==null?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:model.pill,tone:model.flagged?"high":"clear"}):null]}),
|
|
965
1002
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.latest,children:[
|
|
966
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.wtValue,{color:model.flagged?
|
|
1003
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.wtValue,{color:model.flagged?look2.alert:look2.ink}],children:model.latest}),
|
|
967
1004
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.latestSub,children:model.latestSub})]}),
|
|
968
1005
|
/* @__PURE__ */jsxRuntime.jsx(LabChart,{model:model}),model.change!==null?/* @__PURE__ */jsxRuntime.jsxs(Text,{style:s.change,children:[
|
|
969
1006
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.changeLead,children:model.change.lead}),model.change.rest]}):null]}),renderExtra!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderExtra(model.markerId),fallback:null,resetKey:model.markerId}):null,model.meaning.length>0?/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
@@ -971,44 +1008,49 @@ return jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:[s.lab,styl
|
|
|
971
1008
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.ctx,children:model.meaning.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.ctxText,children:p},i))})]}):null,model.groups.map((g,gi)=>/* @__PURE__ */jsxRuntime.jsxs(SheetCard,{children:[
|
|
972
1009
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.cardHead,children:[
|
|
973
1010
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.cardTitle,accessibilityRole:"header",children:g.title}),g.allInRange?/* @__PURE__ */jsxRuntime.jsx(SheetPill,{label:SHEET_COPY.inRange,tone:"clear"}):null]}),
|
|
974
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.mks,children:g.rows.map(r=>/* @__PURE__ */jsxRuntime.jsx(SheetMarkerRow,{name:r.name,value:r.value,unit:r.unit,range:r.range,at:r.at,pill:r.flag==="above"?SHEET_COPY.high:r.flag==="below"?SHEET_COPY.belowRangePill:null},r.markerId))})]},`${g.title}-${gi}`)),ask===void 0?null:renderAskButton!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderAskButton(ask,SHEET_COPY.askAboutThis),fallback:null,resetKey:model.markerId}):/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",label:SHEET_COPY.askAboutThis,onPress:ask,testID:"everfur-records-lab-ask"})]})}function LabChart({model:model}){let{s:s,look:
|
|
1011
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.mks,children:g.rows.map(r=>/* @__PURE__ */jsxRuntime.jsx(SheetMarkerRow,{name:r.name,value:r.value,unit:r.unit,range:r.range,at:r.at,pill:r.flag==="above"?SHEET_COPY.high:r.flag==="below"?SHEET_COPY.belowRangePill:null},r.markerId))})]},`${g.title}-${gi}`)),ask===void 0?null:renderAskButton!==void 0?/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>renderAskButton(ask,SHEET_COPY.askAboutThis),fallback:null,resetKey:model.markerId}):/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",label:SHEET_COPY.askAboutThis,onPress:ask,testID:"everfur-records-lab-ask"})]})}function LabChart({model:model}){let{s:s,look:look2}=useSheetKit();if(model.chart.length===0)return null;let banded=model.hasRange;/* @__PURE__ */
|
|
975
1012
|
return jsxRuntime.jsxs(reactNative.View,{style:s.chart,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",children:[
|
|
976
1013
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.labBody,children:[banded?/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
977
1014
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.rail,children:[
|
|
978
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:
|
|
979
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:2,backgroundColor:
|
|
980
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:
|
|
1015
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:look2.alert}}),
|
|
1016
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:2,backgroundColor:look2.go}}),
|
|
1017
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1,backgroundColor:look2.line}})]}),
|
|
981
1018
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.legend,children:[
|
|
982
1019
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"6%"}],children:SHEET_COPY.above}),
|
|
983
1020
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"44%"}],children:SHEET_COPY.inRange}),
|
|
984
1021
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.range,{top:"82%"}],children:SHEET_COPY.below})]})]}):null,
|
|
985
|
-
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[s.plot,{flex:1}],children:[banded?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.band}):null,model.chart.length>1?/* @__PURE__ */jsxRuntime.jsx(ChartLine,{points:model.chart,color:
|
|
1022
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[s.plot,{flex:1}],children:[banded?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.band}):null,model.chart.length>1?/* @__PURE__ */jsxRuntime.jsx(ChartLine,{points:model.chart,color:look2.ink}):null,model.chart.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.point,{left:`${p.x}%`,top:`${p.y}%`,backgroundColor:p.out?look2.alert:look2.ink}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.pointLabel,p.out?{color:look2.alert}:null],children:p.label})},i))]})]}),
|
|
986
1023
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.xAxis,banded?{marginLeft:106}:null],children:model.chart.map((p,i)=>/* @__PURE__ */jsxRuntime.jsx(Text,{style:[s.xTick,{left:`${p.x}%`}],children:p.tick},i))})]})}function capitalize(text4){return text4.length===0?text4:text4.charAt(0).toUpperCase()+text4.slice(1)}function pronounFromSex(sex){return sex==="female"?"her":sex==="male"?"his":null}function rnSheetWords(name,pronoun){let trimmed=name?.trim()??"",shown=trimmed.length>0?trimmed:NAMELESS_PET,words2=sheetPetWords(shown,pronoun);/* @__PURE__ */
|
|
987
|
-
return Object.freeze({...words2,Poss:capitalize(words2.Poss)})}function rnSheetHeading(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:RECORD_SCREEN_COPY.document.namelessPet}var RN_SHEET_APP_COPY=/* @__PURE__ */Object.freeze({topRiskKicker:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,today:"Today"});function rnOpenRequest(requests,petRef){return requests.filter(r=>r.petRef===petRef&&!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0]??null}function rnOpenClinicRequest(requests,petRef){return rnOpenRequest(requests.filter(r=>!isOwnerUpload(r)),petRef)}function isOwnerUpload(request){return request.source==="owner_provided"}function rnTrackerSteps(status){switch(status){case"received":case"parsing":case"in_review":case"published":return["done","done","now"];case"awaiting_clinic":return["done","now","next"];default:return["now","next","next"]}}var MONTH_SHORT2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function rnTrackerWhen(iso,nowMs){let ms2=dayMs(iso);if(ms2===null)return null;let d=new Date(ms2),now=new Date(nowMs),sameDay=d.getFullYear()===now.getFullYear()&&d.getMonth()===now.getMonth()&&d.getDate()===now.getDate(),h=d.getHours(),time=`${h%12===0?12:h%12}:${String(d.getMinutes()).padStart(2,"0")} ${h<12?"AM":"PM"}`;return`${sameDay?RN_SHEET_APP_COPY.today:`${MONTH_SHORT2[d.getMonth()]??""} ${d.getDate()}`}, ${time}`}var RECORDS_SHEET_RN_COPY=/* @__PURE__ */Object.freeze({undatedPill:""});function rnFailedRequest(requests,petRef){let mine=requests.filter(r=>r.petRef===petRef);if(mine.some(r=>!isTerminalStatus(r.status)))return null;let latest=[...mine].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(latest===void 0||latest.status!=="failed"&&latest.status!=="revoked")return null;let
|
|
988
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(SheetKitProvider,{value:kit,children:/* @__PURE__ */jsxRuntime.jsx(HubKitProvider,{handFamily:handFamilyOf(rest.options),
|
|
989
|
-
|
|
1024
|
+
return Object.freeze({...words2,Poss:capitalize(words2.Poss)})}function rnSheetHeading(name){let trimmed=name?.trim()??"";return trimmed.length>0?trimmed:RECORD_SCREEN_COPY.document.namelessPet}var RN_SHEET_APP_COPY=/* @__PURE__ */Object.freeze({topRiskKicker:w=>`${w.Poss} top risk`,seePlan:w=>`See ${w.poss} Health Plan`,today:"Today"});function rnOpenRequest(requests,petRef){return requests.filter(r=>r.petRef===petRef&&!isTerminalStatus(r.status)).sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0]??null}function rnOpenClinicRequest(requests,petRef){return rnOpenRequest(requests.filter(r=>!isOwnerUpload(r)),petRef)}function isOwnerUpload(request){return request.source==="owner_provided"}function rnTrackerSteps(status){switch(status){case"received":case"parsing":case"in_review":case"published":return["done","done","now"];case"awaiting_clinic":return["done","now","next"];default:return["now","next","next"]}}var MONTH_SHORT2=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function rnTrackerWhen(iso,nowMs){let ms2=dayMs(iso);if(ms2===null)return null;let d=new Date(ms2),now=new Date(nowMs),sameDay=d.getFullYear()===now.getFullYear()&&d.getMonth()===now.getMonth()&&d.getDate()===now.getDate(),h=d.getHours(),time=`${h%12===0?12:h%12}:${String(d.getMinutes()).padStart(2,"0")} ${h<12?"AM":"PM"}`;return`${sameDay?RN_SHEET_APP_COPY.today:`${MONTH_SHORT2[d.getMonth()]??""} ${d.getDate()}`}, ${time}`}var RECORDS_SHEET_RN_COPY=/* @__PURE__ */Object.freeze({undatedPill:""});function rnFailedRequest(requests,petRef){let mine=requests.filter(r=>r.petRef===petRef);if(mine.some(r=>!isTerminalStatus(r.status)))return null;let latest=[...mine].sort((a,b)=>(dayMs(b.updatedAt)??0)-(dayMs(a.updatedAt)??0))[0];if(latest===void 0||latest.status!=="failed"&&latest.status!=="revoked")return null;let label2=selectPrimaryLabel(latest).trim();return label2.length>0?{id:latest.id,label:label2}:null}function rnTopRiskText(focus){if(focus==null)return null;let risk=[focus.risk?.lead?.trim()??"",focus.risk?.body?.trim()??""].filter(p=>p.length>0).join(" ");if(risk.length>0)return risk;let title=focus.title.trim();return title.length>0?title:null}function planPageSex(pet){return pet?.sex??null}function recordSex(record){if(record==null||record.withheld)return null;let value=record.identity.find(r=>r.label.trim().toLowerCase()==="sex")?.value.trim().toLowerCase()??"";return value.length===0?null:/\bfemale\b/.test(value)||/^(f|fs)$/.test(value)?"female":/\bmale\b/.test(value)||/^(m|mn)$/.test(value)?"male":null}var readDepth4=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty4=value=>!value.available,readTimeline2=(client,petRef)=>client.getTimeline(petRef),timelineEmpty2=value=>value.isEmpty,NO_OPTIONS=/* @__PURE__ */Object.freeze({});function handFamilyOf(options){let fontsHand=firstFontFamily(options?.fonts?.hand);return options?.stage!==void 0?options.stage.handFontFamily??fontsHand:options?.handFontFamily!==void 0?options.handFontFamily:fontsHand!==null?fontsHand:reactNative.Platform.OS==="android"||reactNative.Platform.OS==="web"?"cursive":null}function EverfurRecordsSheet(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),kitTheme=useRecordsSheetKitTheme(rest.options?.palette,rest.options?.fonts),kit=useSheetKitValue(kitTheme),{userRef:userRef}=useEverfurContext();/* @__PURE__ */
|
|
1025
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxRuntime.jsx(SheetKitProvider,{value:kit,children:/* @__PURE__ */jsxRuntime.jsx(HubKitProvider,{handFamily:handFamilyOf(rest.options),theme:kitTheme,children:userRef===null?
|
|
1026
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:[{flex:1},style],testID:"everfur-records-sheet-session-required",children:[
|
|
1027
|
+
/* @__PURE__ */jsxRuntime.jsx(SessionRequiredState,{}),
|
|
1028
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]}):/* @__PURE__ */jsxRuntime.jsx(SheetScreen,{...rest,style:style})})})})}function SheetScreen({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,options:options=NO_OPTIONS,style:style}){let{s:s,look:look2}=useSheetKit(),hub=useHub(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true}),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth4,depthEmpty4),timeline=useRecordsDepthRead(petRef,readTimeline2,timelineEmpty2),{pets:pets}=useEverfurPets(),pet=pets.find(p=>p.petRef===petRef)??null,presentationInput=react.useMemo(()=>options.topRiskLine===void 0?options.presentation??null:{...options.presentation,recordsTopRiskLine:options.topRiskLine},[options.presentation,options.topRiskLine]),presentation=useEverfurPresentation(presentationInput),stage=react.useMemo(()=>resolveRecordsSheetStage(options.stage),[options.stage]);useConsentTextWarning2(consentVersion,consentText);let canGrant=react.useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=react.useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),clinicDecision=useCapability("recordsClinic"),canRequest=clinicDecision.enabled||clinicDecision.isPending,[labOpen,setLabOpen]=react.useState(null),active=options.active??true,[foreground,setForeground]=react.useState(()=>reactNative.AppState.currentState!=="background");react.useEffect(()=>{let subscription=reactNative.AppState.addEventListener("change",state2=>setForeground(state2==="active"));return()=>subscription.remove()},[]);let now=useCoarseNow(options.nowMs,active&&foreground),reducedMotion=useEverfurTheme().motion.reducedMotion,petArt=useRecordsPetArt(stage===void 0&&options.renderStage===void 0?petRef:null,{reducedMotion:reducedMotion,isFocused:active&&foreground}),knownPronoun=options.pronoun??pronounFromSex(options.sex)??pronounFromSex(recordSex(records.record))??null,needPlanForSex=knownPronoun===null&&records.status!=="loading",planCapability=useCapability("healthPlan"),plan=useHealthPlanPage({petRef:petRef,enabled:planCapability.enabled&&(presentation.recordsTopRiskLine||needPlanForSex)}),planPet=plan.page?.pet??null,pronoun=knownPronoun??pronounFromSex(planPageSex(planPet)),name=petName?.trim()||pet?.name?.trim()||planPet?.name?.trim()||"",species=options.species??pet?.species??planPet?.species??null,unit=options.weightUnit??"lb",words2=rnSheetWords(name,pronoun),breed=pet?.breed??planPet?.breed??null,model=react.useMemo(()=>buildRecordsSheetModel({words:words2,record:records.record,depth:depth.value,markers:markers.markers,timeline:timeline.value,requests:records.requests,breed:breed,petWeightKg:pet?.weightKg??planPet?.weightKg??null,nowMs:now}),[name,pronoun,records.record,records.requests,depth.value,markers.markers,timeline.value,pet,planPet,now]),weight=react.useMemo(()=>hubWeight(records.record,timeline.value,unit),[records.record,timeline.value,unit]),scrollRef=react.useRef(null),columnY=react.useRef(0),historyY=react.useRef(0),meta=hubMeta(breed,pet?.ageYears??null,weight),failed=rnFailedRequest(records.requests,petRef),topRisk=presentation.recordsTopRiskLine?rnTopRiskText(plan.page?.page?.focus):null,disclaimer=[markers.markers?.disclaimer,records.record?.disclaimer,timeline.value?.disclaimer].map(d=>d?.trim()??"").find(d=>d.length>0)??"";react.useEffect(()=>{if(labOpen===null||!active)return;let sub=reactNative.BackHandler.addEventListener("hardwareBackPress",()=>(setLabOpen(null),true));return()=>{sub.remove()}},[labOpen,active]);let openMarker=markerId=>{options.onOpenMarker!==void 0?options.onOpenMarker(markerId):setLabOpen(markerId)},openRequest=rnOpenRequest(records.requests,petRef),canAct=onNavigate!==void 0,go={request:()=>{if(options.onRequestFromClinic!==void 0){let result=options.onRequestFromClinic({petRef:petRef});result!==void 0&&typeof result.then=="function"&&result.then(()=>records.refresh(),()=>records.refresh()).then(void 0,()=>{})}else onNavigate?.({name:"clinicPicker"})},upload:()=>onNavigate?.({name:"upload"}),record:()=>onNavigate?.({name:"record"})},openHistory=model.history.length>0?()=>scrollRef.current?.scrollTo({y:Math.max(0,columnY.current+historyY.current),animated:!reducedMotion}):canAct?go.record:void 0,openRequestById=canAct?requestId2=>onNavigate?.({name:"request",requestId:requestId2}):void 0,retryAll=()=>Promise.all([records.refresh(),markers.refresh(),depth.refresh(),timeline.refresh()].map(p=>Promise.resolve(p).then(void 0,()=>{}))).then(()=>{}),refreshControl=useRecordsPullToRefresh(retryAll,"everfur-records-sheet-refresh"),petRequests=react.useMemo(()=>records.requests.filter(r=>r.petRef===petRef),[records.requests,petRef]),inFlight=react.useMemo(()=>healthTabOnTheWay(name,petRequests),[name,petRequests]),uploadHint=acceptsPhotos(records.uploadContentTypes)?SHEET_COPY.uploadDetail:HEALTH_TAB_SHARED_COPY.uploadFormatHint,exam=vitalsExam(depth.value,records.record!==null?sheetVitals(records.record).observedMs:null),note=useRequestedNote(),requested=rnOpenClinicRequest(records.requests,petRef)?.clinicName?.trim()||null,requestOnce=requested!==null?note.show:go.request,requestedNote=requested!==null&¬e.on?/* @__PURE__ */jsxRuntime.jsx(RequestedNote,{clinic:requested},note.shown):null;if(labOpen!==null)/* @__PURE__ */
|
|
1029
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{flex:1,backgroundColor:look2.ground},style],children:[
|
|
990
1030
|
/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:rnSheetHeading(name),onBack:()=>setLabOpen(null),testID:"everfur-records-lab-header"}),
|
|
991
1031
|
/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsLabDetail,{petRef:petRef,markerId:labOpen,...name.length>0?{petName:name}:{},...onAsk?{onAsk:onAsk}:{}}),
|
|
992
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]});let body,state="full",onHub=true,failedLine=failed!==null?/* @__PURE__ */jsxRuntime.jsx(FailedLine,{label:failed.label,onPress:canAct?()=>onNavigate?.({name:"request",requestId:failed.id}):void 0}):null,topSlot=options.renderTopSlot!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.topSlot,{marginBottom:APP_HUB.screen.gap}],testID:"everfur-records-sheet-top-slot",children:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>options.renderTopSlot?.({clearResultsFilter:presentation.recordsClearResultsFilter})??null,fallback:null,resetKey:petRef})}):null,foot=disclaimer.length>0&&!disclaimerRepeatsFootnote(disclaimer)?/* @__PURE__ */jsxRuntime.jsx(HubDisclaimer,{text:disclaimer}):null,column={paddingHorizontal:APP_HUB.screen.padX,gap:APP_HUB.screen.gap},hero=say=>/* @__PURE__ */jsxRuntime.jsx(HubHero,{name:name.length>0?words2.Name:rnSheetHeading(name),meta:meta,stage:
|
|
993
|
-
/* @__PURE__ */jsxRuntime.
|
|
994
|
-
/* @__PURE__ */jsxRuntime.
|
|
995
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
996
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
997
|
-
/* @__PURE__ */jsxRuntime.
|
|
998
|
-
/* @__PURE__ */jsxRuntime.
|
|
999
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
1000
|
-
/* @__PURE__ */jsxRuntime.jsx(
|
|
1032
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]});let body,state="full",onHub=true,failedLine=failed!==null?/* @__PURE__ */jsxRuntime.jsx(FailedLine,{label:failed.label,onPress:canAct?()=>onNavigate?.({name:"request",requestId:failed.id}):void 0}):null,topSlot=options.renderTopSlot!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:[s.topSlot,{marginBottom:APP_HUB.screen.gap}],testID:"everfur-records-sheet-top-slot",children:/* @__PURE__ */jsxRuntime.jsx(HostRender,{render:()=>options.renderTopSlot?.({clearResultsFilter:presentation.recordsClearResultsFilter})??null,fallback:null,resetKey:petRef})}):null,topRiskLine=topRisk!==null?/* @__PURE__ */jsxRuntime.jsx(TopRisk,{words:words2,text:topRisk,onOpenPlan:options.onOpenPlan}):null,foot=disclaimer.length>0&&!disclaimerRepeatsFootnote(disclaimer)?/* @__PURE__ */jsxRuntime.jsx(HubDisclaimer,{text:disclaimer}):null,column={paddingHorizontal:APP_HUB.screen.padX,gap:APP_HUB.screen.gap},hero=say=>/* @__PURE__ */jsxRuntime.jsx(HubHero,{name:name.length>0?words2.Name:rnSheetHeading(name),meta:meta,stage:stage,art:petArt,handFontFamily:handFamilyOf(options),say:say,vitals:say?[]:model.vitals,vitalsName:words2.name,renderStage:options.renderStage,exam:say?null:exam,onOpenExam:canAct?go.record:void 0});if(records.status==="loading"&&records.record===null)body=/* @__PURE__ */jsxRuntime.jsx(DashboardSkeleton,{testID:"everfur-records-sheet-loading"}),state="loading",onHub=false;else if(records.status==="error"){let view=selectErrorView(records,canGrant);isConsentGate(view)?(state="consent",body=/* @__PURE__ */jsxRuntime.jsxs(reactNative.ScrollView,{contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},refreshControl:refreshControl,children:[topSlot,
|
|
1033
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:column,testID:"everfur-records-sheet-content",children:[topRiskLine,renderErrorFamily(records,onGrant,canGrant,consentText),canAct?/* @__PURE__ */jsxRuntime.jsx(HubAddRecords,{words:words2,sources:[],canRequest:canRequest,onRequest:requestOnce,onUpload:go.upload,note:requestedNote,uploadHint:uploadHint}):null,
|
|
1034
|
+
/* @__PURE__ */jsxRuntime.jsx(HubLegal,{})]})]})):view.kind==="error"||view.kind==="pet_not_found"?(state="error",onHub=false,body=/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(view.error),message:view.error.displayMessage,onAction:view.error.retryable?retryAll:void 0,testID:"everfur-records-sheet-error"})):(state=view.kind,onHub=false,body=renderErrorFamily(records,onGrant,canGrant,consentText))}else if(model.state!=="full")state=openRequest===null?"none":isOwnerUpload(openRequest)?"processing":"onTheWay",body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},refreshControl:refreshControl,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{testID:"everfur-records-sheet-content",style:options.style,children:[topSlot,
|
|
1035
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:column,children:[hero(true),topRiskLine,failedLine,state==="onTheWay"&&openRequest!==null?/* @__PURE__ */jsxRuntime.jsx(HubOnTheWay,{words:words2,request:openRequest,steps:rnTrackerSteps(openRequest.status),sentWhen:rnTrackerWhen(openRequest.createdAt,now),canAct:canAct,canRequest:canRequest,onAnotherClinic:go.request,onUpload:go.upload,onOpenRequest:openRequestById!==void 0?()=>openRequestById(openRequest.id):void 0}):state==="processing"&&openRequest!==null?/* @__PURE__ */jsxRuntime.jsx(HubInProgress,{words:words2,request:openRequest,onOpenRequest:openRequestById!==void 0?()=>openRequestById(openRequest.id):void 0}):/* @__PURE__ */jsxRuntime.jsx(HubPrompt,{title:options.noVet===true?HUB_COPY.noVetTitle(words2):HUB_COPY.addRecords(words2.name),canAct:canAct,canRequest:canRequest,onRequest:requestOnce,onUpload:go.upload,note:requestedNote}),weight!==null?/* @__PURE__ */jsxRuntime.jsx(HubWeightCard,{weight:weight,name:words2.name}):null,
|
|
1036
|
+
/* @__PURE__ */jsxRuntime.jsx(HubSamplePeek,{name:words2.name,poss:words2.poss,species:species}),foot,
|
|
1037
|
+
/* @__PURE__ */jsxRuntime.jsx(HubLegal,{})]})]})});else{let rows=hubUpcoming(records.record?.forwardLooking??[],now),items=new Map((records.record?.forwardLooking??[]).map(item=>[item.careItemKey?.trim()||item.title,item])),tiles=hubTiles(records.record,markers.markers,depth.value,timeline.value),featured=model.featuredMarkerId,screeningsAt=tiles.screeningsPill?.markerId??null,partialFailed=markers.status==="error"||timeline.status==="error",partialError=(markers.status==="error"?markers.error:null)??(timeline.status==="error"?timeline.error:null);body=/* @__PURE__ */jsxRuntime.jsx(reactNative.ScrollView,{ref:scrollRef,contentContainerStyle:{paddingBottom:APP_HUB.screen.padBottom},refreshControl:refreshControl,children:/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{testID:"everfur-records-sheet-content",style:options.style,children:[topSlot,
|
|
1038
|
+
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:column,onLayout:e=>{columnY.current=e.nativeEvent.layout.y},children:[hero(false),topRiskLine,failedLine,partialFailed?
|
|
1039
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsEmptyState,{variant:recordsEmptyVariantForError(partialError),onAction:retryAll,testID:"everfur-records-sheet-partial-error"}):null,rows.length>0?/* @__PURE__ */jsxRuntime.jsx(HubUpcoming,{rows:rows,items:items,onViewAll:openHistory,renderAction:options.renderUpcomingCareAction}):/* @__PURE__ */jsxRuntime.jsx(HubUpcomingEmpty,{name:words2.name}),
|
|
1040
|
+
/* @__PURE__ */jsxRuntime.jsx(HubTilesSection,{tiles:tiles,labsUnknown:markers.status==="loading"||markers.status==="error",onOpenLabs:featured!==null?()=>openMarker(featured):canAct?go.record:void 0,onOpenScreenings:options.onOpenScreenings??(screeningsAt!==null?()=>openMarker(screeningsAt):canAct?go.record:void 0),onOpenVisits:canAct?go.record:void 0,onOpenTimeline:openHistory}),
|
|
1041
|
+
/* @__PURE__ */jsxRuntime.jsx(HubWeightCard,{weight:weight,name:words2.name}),canAct?/* @__PURE__ */jsxRuntime.jsx(HubAddRecords,{words:words2,sources:hubOnFile(records.record,depth.value),canRequest:canRequest,onRequest:requestOnce,onUpload:go.upload,note:requestedNote,inFlight:inFlight,onOpenRequest:openRequestById,uploadHint:uploadHint}):null,
|
|
1042
|
+
/* @__PURE__ */jsxRuntime.jsx(HubMedications,{medications:model.medications}),model.history.length>0?/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{onLayout:e=>{historyY.current=e.nativeEvent.layout.y},testID:"everfur-records-sheet-history-anchor",children:/* @__PURE__ */jsxRuntime.jsx(HubHistory,{words:words2,history:model.history,onOpenMarker:openMarker})}):null,foot,
|
|
1001
1043
|
/* @__PURE__ */jsxRuntime.jsx(HubLegal,{})]})]})})}/* @__PURE__ */
|
|
1002
|
-
return jsxRuntime.jsxs(reactNative.View,{style:[{flex:1,backgroundColor:onHub?hub.look.bg:
|
|
1003
|
-
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),onHub?null:/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var NOTE_MS=2600;function useRequestedNote(){let[on,setOn]=react.useState(false),[shown,setShown]=react.useState(0),timer=react.useRef(null);react.useEffect(()=>()=>{timer.current!==null&&clearTimeout(timer.current)},[]);let show=react.useCallback(()=>{timer.current!==null&&clearTimeout(timer.current),setOn(true),setShown(n2=>n2+1),timer.current=setTimeout(()=>{timer.current=null,setOn(false)},NOTE_MS)},[]);return{on:on,shown:shown,show:show}}function RequestedNote({clinic:clinic}){let{look:
|
|
1004
|
-
return jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",style:{paddingVertical:APP_HUB.upcoming.rowPadY,paddingHorizontal:APP_HUB.card.pad,borderRadius:APP_HUB.card.radius,backgroundColor:
|
|
1044
|
+
return jsxRuntime.jsxs(reactNative.View,{style:[{flex:1,backgroundColor:onHub?hub.look.bg:look2.ground},style],testID:"everfur-records-sheet",children:[onBack!==void 0?/* @__PURE__ */jsxRuntime.jsx(ScreenHeader,{title:DASHBOARD_COPY.titleNative(petName),onBack:onBack,testID:"everfur-records-sheet-header"}):null,
|
|
1045
|
+
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:{flex:1},testID:`everfur-records-sheet-state-${state}`,children:body}),onHub?null:/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}var NOTE_MS=2600;function useRequestedNote(){let[on,setOn]=react.useState(false),[shown,setShown]=react.useState(0),timer=react.useRef(null);react.useEffect(()=>()=>{timer.current!==null&&clearTimeout(timer.current)},[]);let show=react.useCallback(()=>{timer.current!==null&&clearTimeout(timer.current),setOn(true),setShown(n2=>n2+1),timer.current=setTimeout(()=>{timer.current=null,setOn(false)},NOTE_MS)},[]);return{on:on,shown:shown,show:show}}function RequestedNote({clinic:clinic}){let{look:look2}=useHub();/* @__PURE__ */
|
|
1046
|
+
return jsxRuntime.jsx(reactNative.View,{accessibilityLiveRegion:"polite",style:{paddingVertical:APP_HUB.upcoming.rowPadY,paddingHorizontal:APP_HUB.card.pad,borderRadius:APP_HUB.card.radius,backgroundColor:look2.fill},testID:"everfur-records-sheet-requested-note",children:/* @__PURE__ */jsxRuntime.jsx(HubText,{variant:"bodySm",color:look2.onFill,children:SHEET_COPY.requestedFrom(clinic)})})}function HubDisclaimer({text:text4}){let{type:type}=useHub();/* @__PURE__ */
|
|
1005
1047
|
return jsxRuntime.jsx(Text,{style:[type("fine"),{textAlign:"center",marginTop:APP_HUB.screen.legalTop}],testID:"everfur-records-sheet-disclaimer",children:text4})}function TopRisk({words:words2,text:text4,onOpenPlan:onOpenPlan}){let{s:s}=useSheetKit();/* @__PURE__ */
|
|
1006
1048
|
return jsxRuntime.jsxs(SheetCard,{style:s.topRisk,testID:"everfur-records-sheet-top-risk",children:[
|
|
1007
1049
|
/* @__PURE__ */jsxRuntime.jsxs(reactNative.View,{style:s.topRiskKicker,children:[
|
|
1008
1050
|
/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.topRiskDot}),
|
|
1009
1051
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.topRiskK,children:RN_SHEET_APP_COPY.topRiskKicker(words2)})]}),
|
|
1010
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.topRiskText,children:text4}),onOpenPlan!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",row:true,label:RN_SHEET_APP_COPY.seePlan(words2),onPress:onOpenPlan,testID:"everfur-records-sheet-top-risk-plan"}):null]})}function FailedLine({label:
|
|
1011
|
-
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.failedText,children:
|
|
1052
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.topRiskText,children:text4}),onOpenPlan!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetButton,{kind:"ink",row:true,label:RN_SHEET_APP_COPY.seePlan(words2),onPress:onOpenPlan,testID:"everfur-records-sheet-top-risk-plan"}):null]})}function FailedLine({label:label2,onPress:onPress}){let{s:s,look:look2}=useSheetKit(),inner=/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
1053
|
+
/* @__PURE__ */jsxRuntime.jsx(Text,{style:s.failedText,children:label2}),onPress!==void 0?/* @__PURE__ */jsxRuntime.jsx(SheetIcon,{kind:"chevron",size:20,color:look2.alertDeep}):null]});return onPress!==void 0?/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{onPress:onPress,accessibilityRole:"button",accessibilityLabel:label2,style:s.failed,testID:"everfur-records-sheet-failed",children:inner}):/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{style:s.failed,testID:"everfur-records-sheet-failed",children:inner})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,uploadTransport:uploadTransport,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,onExit:onExit,style:style,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location,sheet:sheet=true,onNavigate:hostNavigate,alwaysShowWays:alwaysShowWays,renderUpcomingCareAction:renderUpcomingCareAction,noVet:noVet,weightUnit:weightUnit,onOpenPlan:onOpenPlan,onOpenScreenings:onOpenScreenings,onRequestFromClinic:onRequestFromClinic}=guardHostProps(props,["onExit","onNavigate"]),sheetOptions=react.useMemo(()=>sheet===false?null:{...definedProps({renderUpcomingCareAction:renderUpcomingCareAction,noVet:noVet,weightUnit:weightUnit,onOpenPlan:onOpenPlan,onOpenScreenings:onOpenScreenings,onRequestFromClinic:onRequestFromClinic}),...typeof sheet=="object"?definedProps(sheet):{}},[sheet,renderUpcomingCareAction,noVet,weightUnit,onOpenPlan,onOpenScreenings,onRequestFromClinic]),[nav,dispatch]=react.useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;react.useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=reactNative.BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=react.useCallback(to=>{hostNavigate?hostNavigate(to):dispatch({type:"navigate",screen:to})},[hostNavigate]),onBack=react.useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location?{location:location}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},uploads={...onPickDocument?{onPickDocument:onPickDocument}:{},...onPickPhotos?{onPickPhotos:onPickPhotos}:{},...uploadTransport?{uploadTransport:uploadTransport}:{}},pending=renderPending?{renderPending:renderPending}:{};switch(screen.name){case"dashboard":return sheetOptions!==null?/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsSheet,{petRef:petRef,...seams,...records,...pending,options:sheetOptions,style:style}):/* @__PURE__ */jsxRuntime.jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,...alwaysShowWays===true?{alwaysShowWays:alwaysShowWays}:{},style:style});case"request":/* @__PURE__ */
|
|
1012
1054
|
return jsxRuntime.jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...records,...uploads,...pending,style:style});case"timeline":/* @__PURE__ */
|
|
1013
1055
|
return jsxRuntime.jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,style:style});case"record":/* @__PURE__ */
|
|
1014
1056
|
return jsxRuntime.jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,style:style});case"document":/* @__PURE__ */
|
|
@@ -1019,15 +1061,16 @@ return jsxRuntime.jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??
|
|
|
1019
1061
|
return jsxRuntime.jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},style:style});case"upload":/* @__PURE__ */
|
|
1020
1062
|
return jsxRuntime.jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...uploads,...pending,style:style});case"requests":/* @__PURE__ */
|
|
1021
1063
|
return jsxRuntime.jsx(EverfurRecordsRequests,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,style:style});default:return assertNever(screen)}}var EverfurRecords=EverfurRecordsFlow;function EverfurClinicRequest(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
1022
|
-
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useClinicRequestForm(props,props.controller??runtimeController,props.onCaptureSignature??padCapture),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),field={minHeight:44,padding:theme.space.sm,borderWidth:1,borderColor:theme.color.borderHairlineGreen,borderRadius:theme.radius.sm,color:theme.color.text.primary,backgroundColor:theme.color.surface},input={...field,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},text4={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(
|
|
1064
|
+
return jsxRuntime.jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsxRuntime.jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=react.useState(null),padCapture=react.useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),form=useClinicRequestForm(props,props.controller??runtimeController,props.onCaptureSignature??padCapture),signed=props.onCaptureSignature!==void 0||png!==null,theme=useEverfurTheme(),field={minHeight:44,padding:theme.space.sm,borderWidth:1,borderColor:theme.color.borderHairlineGreen,borderRadius:theme.radius.sm,color:theme.color.text.primary,backgroundColor:theme.color.surface},input={...field,...slotBox(theme.slots.input,1),...slotText(theme.slots.input)},text4={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(label2,action,disabled=false,testID)=>/* @__PURE__ */jsxRuntime.jsx(reactNative.Pressable,{accessibilityRole:"button",accessibilityLabel:label2,accessibilityState:{disabled:disabled},disabled:disabled,onPress:action,...testID?{testID:testID}:{},style:[field,{justifyContent:"center",opacity:disabled?.5:1}],children:/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:label2})});/* @__PURE__ */
|
|
1023
1065
|
return jsxRuntime.jsxs(reactNative.View,{accessibilityLabel:CLINIC_REQUEST_COPY.title,style:[{backgroundColor:theme.color.surface,padding:theme.space.lg,gap:theme.space.md,borderRadius:theme.radius.lg,minHeight:120},props.style],children:[
|
|
1024
1066
|
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:[text4,{...headingFace(theme,"bold"),fontSize:theme.type.size.heading}],children:CLINIC_REQUEST_COPY.title}),
|
|
1025
1067
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:props.petName}),form.created?/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
1026
1068
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.ownerName}),
|
|
1027
1069
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:input,value:form.ownerName,maxLength:200,editable:!form.busy,autoComplete:"name",onChangeText:form.setOwnerName}),
|
|
1028
1070
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.clinic}),
|
|
1029
|
-
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:input,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,onChangeText:form.setQuery}),button(CLINIC_REQUEST_COPY.search,()=>{form.search()},form.busy||form.searching||form.query.trim().length<2),form.searching&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text4,testID:"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},clinic.id)),form.hasMoreClinics&&button(CLINIC_REQUEST_COPY.moreClinics,form.showMoreClinics,form.busy),form.needsEmail&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
1071
|
+
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:input,value:form.query,placeholder:CLINIC_REQUEST_COPY.placeholder,placeholderTextColor:theme.color.text.placeholder,maxLength:200,editable:!form.busy,onChangeText:form.setQuery}),button(CLINIC_REQUEST_COPY.search,()=>{form.search()},form.busy||form.searching||form.query.trim().length<2),form.searching&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text4,testID:"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxRuntime.jsx(reactNative.View,{children:button([clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),()=>form.selectClinic(clinic),form.busy)},clinic.id)),form.hasMoreClinics&&button(CLINIC_REQUEST_COPY.moreClinics,form.showMoreClinics,form.busy,"records-clinic-results-more"),form.needsEmail&&/* @__PURE__ */jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[
|
|
1030
1072
|
/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:CLINIC_REQUEST_COPY.email}),
|
|
1031
1073
|
/* @__PURE__ */jsxRuntime.jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.email,style:input,value:form.email,placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,placeholderTextColor:theme.color.text.placeholder,maxLength:320,editable:!form.busy,keyboardType:"email-address",autoCapitalize:"none",autoCorrect:false,onChangeText:form.setEmail})]}),
|
|
1032
1074
|
/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"header",style:text4,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsxRuntime.jsx(Text,{style:text4,children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityLiveRegion:"polite",style:text4,children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsxRuntime.jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",style:text4,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsxRuntime.jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:text4,children:form.error.displayMessage}),!form.copy&&form.error&&button(RECORDS_COPY.retry,form.retryCopy),button(form.busy?CLINIC_REQUEST_COPY.sending:CLINIC_REQUEST_COPY.send,()=>{form.submit()},form.busy||!form.ready||!signed)]}),props.onClose&&button(CLINIC_REQUEST_COPY.cancel,props.onClose,form.busy),
|
|
1033
|
-
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}
|
|
1075
|
+
/* @__PURE__ */jsxRuntime.jsx(RecordsFootnote,{})]})}function recordsSheet(options={}){/* @__PURE__ */
|
|
1076
|
+
return Object.freeze({...options})}var look=hubLook(EVERFUR_LIGHT),label=APP_HUB_TYPE.buttonRow,RECORDS_SHEET_ROW_BUTTON_STYLE=/* @__PURE__ */Object.freeze({style:/* @__PURE__ */Object.freeze({flexDirection:"row",alignItems:"center",justifyContent:"center",gap:APP_HUB.button.gap,borderRadius:999,minHeight:APP_HUB.button.row,paddingHorizontal:APP_HUB.button.padRow,backgroundColor:look.fill,borderWidth:APP_HUB.button.edge,borderColor:look.white}),labelStyle:/* @__PURE__ */Object.freeze({...face(EVERFUR_LIGHT,"bold"),fontSize:label.size,lineHeight:label.lineHeight,letterSpacing:label.letterSpacing,color:look.onFill})});exports.EverfurClinicPicker=EverfurClinicPicker;exports.EverfurClinicRequest=EverfurClinicRequest;exports.EverfurClinicRequestBatch=EverfurClinicRequestBatch;exports.EverfurRecordDetail=EverfurRecordDetail;exports.EverfurRecordDocument=EverfurRecordDocument;exports.EverfurRecords=EverfurRecords;exports.EverfurRecordsConsent=EverfurRecordsConsent;exports.EverfurRecordsDashboard=EverfurRecordsDashboard;exports.EverfurRecordsFlow=EverfurRecordsFlow;exports.EverfurRecordsLabDetail=EverfurRecordsLabDetail;exports.EverfurRecordsRequest=EverfurRecordsRequest;exports.EverfurRecordsRequests=EverfurRecordsRequests;exports.EverfurRecordsSheet=EverfurRecordsSheet;exports.EverfurRecordsUpload=EverfurRecordsUpload;exports.RECORDS_CLINIC_BATCH_MAX=RECORDS_CLINIC_BATCH_MAX;exports.RECORDS_SHEET_RN_COPY=RECORDS_SHEET_RN_COPY;exports.RECORDS_SHEET_ROW_BUTTON_STYLE=RECORDS_SHEET_ROW_BUTTON_STYLE;exports.RECORDS_TERMINAL=RECORDS_TERMINAL;exports.REQUEST_TIMELINE_TITLES=REQUEST_TIMELINE_TITLES;exports.RequestDocumentsList=RequestDocumentsList;exports.SignaturePad=SignaturePad;exports.acceptsPhotos=acceptsPhotos;exports.applyFactOverlay=applyFactOverlay;exports.buildRequestTimeline=buildRequestTimeline;exports.currentRecordsScreen=currentRecordsScreen;exports.deriveRecordsDashboardState=deriveRecordsDashboardState;exports.initialRecordsNav=initialRecordsNav;exports.isFactEditable=isFactEditable;exports.isTerminalStatus=isTerminalStatus;exports.pickPetRecordsRequest=pickPetRecordsRequest;exports.popRecordsNav=popRecordsNav;exports.pushRecordsNav=pushRecordsNav;exports.recordsDenialReasonOf=recordsDenialReasonOf;exports.recordsNavReducer=recordsNavReducer;exports.recordsSheet=recordsSheet;exports.recordsSheetLook=recordsSheetLook;exports.registerRnSignature=registerRnSignature;exports.replaceRecordsNav=replaceRecordsNav;exports.resetRecordsNav=resetRecordsNav;exports.selectClinicCall=selectClinicCall;exports.selectDashboardView=selectDashboardView;exports.selectPrimaryLabel=selectPrimaryLabel;exports.selectRequestList=selectRequestList;exports.selectRequestTitle=selectRequestTitle;exports.transitionRecordsNav=transitionRecordsNav;exports.useEverfurRecords=useEverfurRecords;exports.useEverfurRecordsClinic=useEverfurRecordsClinic;exports.useEverfurRecordsClinicBatch=useEverfurRecordsClinicBatch;exports.useRecordFactEdit=useRecordFactEdit;exports.useRecordPdfLink=useRecordPdfLink;exports.useRecordShares=useRecordShares;exports.useRecordsMarkers=useRecordsMarkers;
|