@everfur/sdk 0.8.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +91 -0
- package/README.md +1 -1
- package/dist/{Chat-Cv9EYMYA.d.ts → Chat-BoVmqEeF.d.ts} +3 -3
- package/dist/{Chat-s2vcPbw3.d.cts → Chat-DbHkTbqz.d.cts} +3 -3
- package/dist/{DepthViews-DNRY0Ugm.d.ts → DepthViews-BzwflaJ3.d.ts} +1 -1
- package/dist/{DepthViews-Cz7mSW7p.d.cts → DepthViews-Chyp69Ue.d.cts} +1 -1
- package/dist/{DepthViews-DvNixbxg.d.cts → DepthViews-DK7EJ6Hp.d.cts} +1 -1
- package/dist/{DepthViews-CVxUHOJ-.d.ts → DepthViews-yO1H371y.d.ts} +1 -1
- package/dist/{ErrorPolicyPort-NFDPe-5w.d.cts → ErrorPolicyPort-10s3HJCt.d.cts} +1 -1
- package/dist/{ErrorPolicyPort-DwSnmGcX.d.ts → ErrorPolicyPort-C3nNSS_j.d.ts} +1 -1
- package/dist/{EverfurError-pEXDbUJ1.d.cts → EverfurError-DeBqRpQV.d.cts} +1 -1
- package/dist/{EverfurError-pEXDbUJ1.d.ts → EverfurError-DeBqRpQV.d.ts} +1 -1
- package/dist/{EverfurResult-dtl8ERAw.d.cts → EverfurResult-COlXj1wq.d.cts} +1 -1
- package/dist/{EverfurResult-sKkoXew0.d.ts → EverfurResult-ClPTS0P2.d.ts} +1 -1
- package/dist/{IntakeMedia-BFZfBLjB.d.cts → IntakeMedia-B-_vA9ZB.d.cts} +2 -1
- package/dist/{IntakeMedia-C8GlN_GK.d.ts → IntakeMedia-CIoTXAWs.d.ts} +2 -1
- package/dist/animations/index.cjs +2 -2
- package/dist/animations/index.d.cts +6 -6
- package/dist/animations/index.d.ts +6 -6
- package/dist/animations/index.js +2 -2
- package/dist/{attachments-y3EcOX_w.d.cts → attachments-B7TrtyfH.d.cts} +3 -3
- package/dist/{attachments-y_aO4hlk.d.ts → attachments-BmMrn9tU.d.ts} +7 -7
- package/dist/{attachments-BaslXMdS.d.ts → attachments-Dcb19rMP.d.ts} +3 -3
- package/dist/{attachments-DbFwz4iq.d.cts → attachments-Dnpqk1Gl.d.cts} +7 -7
- package/dist/{bookingCopy-4i1R7klo.d.cts → bookingCopy-C153FHEC.d.cts} +7 -6
- package/dist/{bookingCopy-B3UMITD-.d.ts → bookingCopy-DR0-SmqH.d.ts} +7 -6
- package/dist/{branding-BwEu68C8.d.cts → branding-BCfwLj0h.d.cts} +99 -6
- package/dist/{branding-BYEqU855.d.ts → branding-DJf4h12Q.d.ts} +99 -6
- package/dist/{callRoom-B1qq_D-4.d.ts → callRoom-B92eH_ij.d.ts} +1 -1
- package/dist/{callRoom-DfZTWFXh.d.cts → callRoom-BhIdadyV.d.cts} +1 -1
- package/dist/{casesRepository-SI0zp5YH.d.ts → casesRepository-BXdwCWQF.d.ts} +2 -2
- package/dist/{casesRepository-B6Z0XBIb.d.cts → casesRepository-DC9lEQez.d.cts} +2 -2
- package/dist/chat/index.cjs +27 -25
- package/dist/chat/index.d.cts +12 -12
- package/dist/chat/index.d.ts +12 -12
- package/dist/chat/index.js +27 -25
- package/dist/client/index.cjs +8 -8
- package/dist/client/index.d.cts +14 -14
- package/dist/client/index.d.ts +14 -14
- package/dist/client/index.js +8 -8
- package/dist/{config-v5k6NsK_.d.cts → config-BRyNmzhx.d.cts} +3 -3
- package/dist/{config-Cvo47voG.d.ts → config-DdK2czhD.d.ts} +3 -3
- package/dist/consent/index.cjs +3 -3
- package/dist/consent/index.d.cts +9 -9
- package/dist/consent/index.d.ts +9 -9
- package/dist/consent/index.js +3 -3
- package/dist/{context-cZ7NZ0sG.d.ts → context-_EyjBNKI.d.ts} +9 -9
- package/dist/{context-BZOtJbBO.d.cts → context-jaONuHXM.d.cts} +9 -9
- package/dist/{copy-CZBUHbyS.d.ts → copy-BJpRsqK-.d.ts} +5 -5
- package/dist/{copy-ChJupm1p.d.cts → copy-D8iSBQE6.d.cts} +5 -5
- package/dist/core/index.cjs +5 -5
- package/dist/core/index.d.cts +19 -19
- package/dist/core/index.d.ts +19 -19
- package/dist/core/index.js +5 -5
- package/dist/{depth-CRyU7-pf.d.cts → depth-DJ1KGMww.d.cts} +6 -6
- package/dist/{depth-vNpwOkZ8.d.ts → depth-bKpg3L9r.d.ts} +6 -6
- package/dist/{entitlementRepository-Bv8nSYRd.d.cts → entitlementRepository-4x_tBE73.d.cts} +4 -4
- package/dist/{entitlementRepository-CUdxbQrP.d.ts → entitlementRepository-CojBLazH.d.ts} +4 -4
- package/dist/{identity-B8GkH53J.d.ts → identity-A8fVB518.d.ts} +2 -2
- package/dist/{identity-BHaMJ3KK.d.cts → identity-CmxZ4GR0.d.cts} +2 -2
- package/dist/index.cjs +31 -29
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +31 -29
- package/dist/{models-DzvqEjMm.d.cts → models-A4A5S7AG.d.cts} +1 -1
- package/dist/{models-CrbUwbuS.d.ts → models-CnXY5LuO.d.ts} +1 -1
- package/dist/notifications/index.cjs +1 -1
- package/dist/notifications/index.d.cts +5 -5
- package/dist/notifications/index.d.ts +5 -5
- package/dist/notifications/index.js +1 -1
- package/dist/{pets-BI7Ji8hi.d.cts → pets-DjBlY7yg.d.cts} +2 -2
- package/dist/{pets-Dnn-DK1T.d.ts → pets-e5RjSP6O.d.ts} +2 -2
- package/dist/{petsRepository-B2lO1sKS.d.ts → petsRepository-CQh8paML.d.ts} +2 -2
- package/dist/{petsRepository-BP9nhM1R.d.cts → petsRepository-DkQ2fwZY.d.cts} +2 -2
- package/dist/photo/index.cjs +2 -2
- package/dist/photo/index.d.cts +3 -3
- package/dist/photo/index.d.ts +3 -3
- package/dist/photo/index.js +2 -2
- package/dist/{ports-C40S2V14.d.cts → ports-2voZkqty.d.cts} +7 -7
- package/dist/{ports-BUXF0Rp3.d.ts → ports-CzVBbI_A.d.ts} +7 -7
- package/dist/records/depth/index.cjs +7 -7
- package/dist/records/depth/index.d.cts +11 -11
- package/dist/records/depth/index.d.ts +11 -11
- package/dist/records/depth/index.js +7 -7
- package/dist/records/index.cjs +33 -33
- package/dist/records/index.d.cts +14 -14
- package/dist/records/index.d.ts +14 -14
- package/dist/records/index.js +33 -33
- package/dist/{requestFunnel-BxNVGyGm.d.cts → requestFunnel-CA0ANsWj.d.cts} +5 -5
- package/dist/{requestFunnel-BrOijMcw.d.ts → requestFunnel-CQ42Kf9G.d.ts} +5 -5
- package/dist/{runtimeTypes-DOO3f-W-.d.cts → runtimeTypes-BxtQXaYi.d.cts} +7 -7
- package/dist/{runtimeTypes-CvI1ZH8j.d.ts → runtimeTypes-C0tI7s-V.d.ts} +7 -7
- package/dist/server/events/index.cjs +2 -2
- package/dist/server/events/index.d.cts +4 -4
- package/dist/server/events/index.d.ts +4 -4
- package/dist/server/events/index.js +2 -2
- package/dist/server/index.cjs +2 -2
- package/dist/server/index.d.cts +5 -5
- package/dist/server/index.d.ts +5 -5
- package/dist/server/index.js +2 -2
- package/dist/televet/booking/index.cjs +20 -17
- package/dist/televet/booking/index.d.cts +12 -12
- package/dist/televet/booking/index.d.ts +12 -12
- package/dist/televet/booking/index.js +20 -17
- package/dist/televet/call/index.cjs +1 -1
- package/dist/televet/call/index.d.cts +2 -2
- package/dist/televet/call/index.d.ts +2 -2
- package/dist/televet/call/index.js +1 -1
- package/dist/televet/index.cjs +3 -3
- package/dist/televet/index.d.cts +7 -7
- package/dist/televet/index.d.ts +7 -7
- package/dist/televet/index.js +3 -3
- package/dist/testing/index.cjs +2 -2
- package/dist/testing/index.d.cts +3 -3
- package/dist/testing/index.d.ts +3 -3
- package/dist/testing/index.js +2 -2
- package/dist/testing/rn/index.cjs +2 -2
- package/dist/testing/rn/index.d.cts +13 -13
- package/dist/testing/rn/index.d.ts +13 -13
- package/dist/testing/rn/index.js +2 -2
- package/dist/testing/web/index.cjs +1 -1
- package/dist/testing/web/index.d.cts +14 -14
- package/dist/testing/web/index.d.ts +14 -14
- package/dist/testing/web/index.js +1 -1
- package/dist/{timelineRows-CEx2TzYB.d.ts → timelineRows-GSpzKLla.d.ts} +1 -1
- package/dist/{timelineRows-Dffceql_.d.cts → timelineRows-WFv_3EOi.d.cts} +1 -1
- package/dist/{tokens-Tzo1KBND.d.cts → tokens-DLj8OnLH.d.cts} +51 -6
- package/dist/{tokens-Tzo1KBND.d.ts → tokens-DLj8OnLH.d.ts} +51 -6
- package/dist/{typeStyle-C3IG9Sft.d.ts → typeStyle-BxVyF71R.d.ts} +11 -3
- package/dist/{typeStyle-CZ3Tj60N.d.cts → typeStyle-DJedEu14.d.cts} +11 -3
- package/dist/{useRecordsDepth-D6a6-_u_.d.cts → useRecordsDepth-BL5Pf3oK.d.cts} +4 -4
- package/dist/{useRecordsDepth-DuPUJFDQ.d.ts → useRecordsDepth-BQF0Zynl.d.ts} +4 -4
- package/dist/{useVetVisit-RPBOabl8.d.ts → useVetVisit-DmWa7lt1.d.ts} +2 -2
- package/dist/{useVetVisit-BQX_aTJs.d.cts → useVetVisit-PtBjNwZr.d.cts} +2 -2
- package/dist/video/index.cjs +2 -2
- package/dist/video/index.d.cts +3 -3
- package/dist/video/index.d.ts +3 -3
- package/dist/video/index.js +2 -2
- package/dist/{view-UFwCG1Pn.d.cts → view-D3kOelPL.d.cts} +5 -5
- package/dist/{view-BSmN5RWf.d.ts → view-rgB1iqWO.d.ts} +5 -5
- package/dist/web/consent/index.cjs +3 -3
- package/dist/web/consent/index.d.cts +9 -9
- package/dist/web/consent/index.d.ts +9 -9
- package/dist/web/consent/index.js +3 -3
- package/dist/web/index.cjs +35 -34
- package/dist/web/index.d.cts +29 -23
- package/dist/web/index.d.ts +29 -23
- package/dist/web/index.js +35 -34
- package/dist/web/notifications/index.cjs +1 -1
- package/dist/web/notifications/index.d.cts +7 -7
- package/dist/web/notifications/index.d.ts +7 -7
- package/dist/web/notifications/index.js +1 -1
- package/dist/web/records/depth/index.cjs +10 -9
- package/dist/web/records/depth/index.d.cts +11 -11
- package/dist/web/records/depth/index.d.ts +11 -11
- package/dist/web/records/depth/index.js +10 -9
- package/dist/web/records/index.cjs +54 -51
- package/dist/web/records/index.d.cts +15 -15
- package/dist/web/records/index.d.ts +15 -15
- package/dist/web/records/index.js +55 -52
- package/dist/web/televet/booking/index.cjs +24 -22
- package/dist/web/televet/booking/index.d.cts +18 -15
- package/dist/web/televet/booking/index.d.ts +18 -15
- package/dist/web/televet/booking/index.js +24 -22
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.d.cts +2 -2
- package/dist/web/televet/call/index.d.ts +2 -2
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +2 -2
- package/dist/web/televet/index.d.cts +5 -5
- package/dist/web/televet/index.d.ts +5 -5
- package/dist/web/televet/index.js +2 -2
- package/package.json +1 -1
package/dist/records/index.js
CHANGED
|
@@ -85,7 +85,7 @@ import{createContext,forwardRef,createElement,useRef,useMemo,useState,useCallbac
|
|
|
85
85
|
/* @__PURE__ */Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),
|
|
86
86
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
87
87
|
/* @__PURE__ */Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),
|
|
88
|
-
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:
|
|
88
|
+
/* @__PURE__ */Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(row=>row.wireCode));var NORMALIZED_FOLD=/* @__PURE__ */Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),CONTRACT_ERROR_ROWS=/* @__PURE__ */Object.freeze(CONTRACT_RETRYABILITY.map(generated=>/* @__PURE__ */Object.freeze({wireCode:generated.wireCode,envelope:generated.envelope,retryable:generated.retryable,normalized:NORMALIZED_FOLD[generated.wireCode]}))),BY_KEY=new Map(CONTRACT_ERROR_ROWS.map(r=>[r.envelope+r.wireCode.toUpperCase(),r])),ENVELOPE_LOOKUP_ORDER=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(CONTRACT_ERROR_ROWS.map(r=>r.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(wireCode,envelope){if(typeof wireCode!="string")return;let key=wireCode.trim().toUpperCase();if(key.length!==0)for(let candidate of[envelope??"http_envelope",...ENVELOPE_LOOKUP_ORDER]){let row=BY_KEY.get(candidate+key);if(row)return row}}var CATEGORY_OF=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function categoryFor(code){return CATEGORY_OF[code]}function fromWire(wire){let contractRow=contractErrorFor(wire);if(contractRow)return contractRow.normalized;let upper=(wire??"").trim().toUpperCase(),canonical=upper.replace(/[^A-Z0-9]/g,"");if(canonical==="AUTHREJECTED")return"authRejected";if(upper.startsWith("AUTH"))return"authExpired";switch(canonical){case"DAILYQUOTAEXCEEDED":case"QUOTAEXCEEDED":return"quotaExceeded";case"RATELIMITED":case"TOOMANYREQUESTS":case"TELEVETRATELIMITED":return"rateLimited";case"IDEMPOTENCYKEYCONFLICT":case"IDEMPOTENCYCONFLICT":return"idempotencyConflict";case"ACCESSDENIED":case"FORBIDDEN":return"accessDenied";case"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";case"NOTFOUND":case"CONVERSATIONNOTFOUND":return"conversationNotFound";case"PETNOTFOUND":return"petNotFound";case"TIMEOUT":case"STREAMTIMEOUT":return"streamTimeout";case"MEDIAUPLOADFAILED":case"UNRECOGNIZEDVIDEOFORMAT":case"FILETOOSMALL":return"mediaUploadFailed";case"MODERATIONBLOCKED":return"moderationBlocked";case"UPSTREAMLLMTIMEOUT":return"upstreamLlmTimeout";case"INTERNALERROR":case"INTERNALSERVERERROR":return"internalError";case"STREAMINCOMPLETE":case"CHATSTREAMINCOMPLETE":return"streamIncomplete";case"INVALIDANALYSISTYPE":case"INVALIDUPLOADPURPOSE":return"unknown";default:return"unknown"}}var AUTO_RETRYABLE_CODES=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(code){return AUTO_RETRYABLE_CODES.has(code)}var RETRYABLE_CONTRACT_CODES=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(code){return isAutoRetryable(code)||RETRYABLE_CONTRACT_CODES.has(code)}var BACKOFF_BASE_MS=500,BACKOFF_CAP_MS=8e3,MAX_RETRY_ATTEMPTS=4;function backoffDelayMs(attempt,rng=Math.random){let bounded=Math.max(0,attempt),ceiling=Math.min(BACKOFF_BASE_MS*2**bounded,BACKOFF_CAP_MS);return Math.floor(rng()*ceiling)}var ACCESS_DENIED_COPY="This feature isn't available on your account right now.",VALIDATION_FAILED_COPY="Something in that request was not right. Check the details and try again.",USER_FACING_COPY=/* @__PURE__ */Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:ACCESS_DENIED_COPY,paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:VALIDATION_FAILED_COPY,sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",identitySignatureRequired:ACCESS_DENIED_COPY,runtimeDisposed:VALIDATION_FAILED_COPY,unknown:"Something went wrong. Please try again."});function userFacingError(code){return USER_FACING_COPY[code]}function defineHidden(target,key,value){Object.defineProperty(target,key,{value:value,enumerable:false,writable:false,configurable:false})}var REASON_CODE_SHAPE=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(code,opts){let row=contractErrorFor(opts?.wireCode,opts?.wireEnvelope),error={code:code,category:categoryFor(code),retryable:opts?.retryable??isRetryableCode(code),displayMessage:userFacingError(code)};opts?.httpStatus!==void 0&&(error.httpStatus=opts.httpStatus),opts?.requestId&&(error.requestId=opts.requestId),typeof opts?.reasonCode=="string"&&REASON_CODE_SHAPE.test(opts.reasonCode)&&(error.reasonCode=opts.reasonCode);let wait=opts?.retryAfterSeconds;if(typeof wait=="number"&&Number.isFinite(wait)&&wait>=0&&(error.retryAfterSeconds=Math.round(wait)),row);return opts?.wireMessage&&defineHidden(error,"wireMessage",opts.wireMessage),opts?.raw!==void 0&&opts.raw!==null&&defineHidden(error,"raw",opts.raw),/* @__PURE__ */Object.freeze(error)}function ok(value,warning){/* @__PURE__ */
|
|
89
89
|
return Object.freeze({ok:true,value:value})}function err(error){/* @__PURE__ */
|
|
90
90
|
return Object.freeze({ok:false,error:error})}var EverfurConfigError=class _EverfurConfigError extends Error{constructor(kind,message){super(message),this.name="EverfurConfigError",this.kind=kind,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var RECORD_SHARE_AUDIENCES=/* @__PURE__ */Object.freeze(["vet","groomer","boarding"]),https=/* @__PURE__ */z.string().min(1).refine(value=>value.startsWith("https://")),str=/* @__PURE__ */z.string().nullish(),audienceField=/* @__PURE__ */z.unknown().optional(),linkSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),share_url:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),listSchema=/* @__PURE__ */z.object({shares:/* @__PURE__ */z.array(/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,created_at:str,view_count:/* @__PURE__ */z.number().int().nonnegative().nullish(),last_viewed_at:str,audience:audienceField})).optional()}),pdfSchema=/* @__PURE__ */z.object({download_url:https,expires_at:str}),emailSchema=/* @__PURE__ */z.object({share_id:/* @__PURE__ */z.string().min(1),expires_at:str,audience:audienceField}),scopeSchema=/* @__PURE__ */z.object({audience:/* @__PURE__ */z.string().min(1),sections:/* @__PURE__ */z.array(/* @__PURE__ */z.string()),entity_types:/* @__PURE__ */z.array(/* @__PURE__ */z.string()).nullable()}),SHARE_RECIPIENT_EMAIL_MAX=254;function isShareRecipientEmail(value){let trimmed=value.trim();return trimmed.length>0&&trimmed.length<=SHARE_RECIPIENT_EMAIL_MAX&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(trimmed)}var isAudience=value=>typeof value=="string"&&RECORD_SHARE_AUDIENCES.includes(value);function audienceOf(value){return isAudience(value)?value:null}function mapShareAudiences(wire){let parsed=z.array(scopeSchema).safeParse(wire);if(!parsed.success)/* @__PURE__ */return Object.freeze([]);let seen=/* @__PURE__ */new Set,scopes=[];for(let scope of parsed.data)!isAudience(scope.audience)||seen.has(scope.audience)||(seen.add(scope.audience),scopes.push(/* @__PURE__ */Object.freeze({audience:scope.audience,sections:/* @__PURE__ */Object.freeze([...scope.sections]),entityTypes:scope.entity_types===null?null:/* @__PURE__ */Object.freeze([...scope.entity_types])}))/* @__PURE__ */);return Object.freeze(scopes)}function resolveShareUrl(shareUrl,apiBaseUrl){let trimmed=shareUrl.trim();if(trimmed.length===0)return null;try{let absolute=/^[a-z][a-z0-9+.-]*:/i.test(trimmed)?new URL(trimmed):apiBaseUrl!==void 0?new URL(trimmed,apiBaseUrl):null;return absolute===null||absolute.protocol!=="https:"?null:absolute.toString()}catch{return null}}function mapRecordShareLink(wire,apiBaseUrl){let parsed=linkSchema.safeParse(wire);if(!parsed.success)return null;let shareUrl=resolveShareUrl(parsed.data.share_url,apiBaseUrl);return shareUrl===null?null:/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,shareUrl:shareUrl,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)})}function mapRecordShareList(wire){let parsed=listSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze((parsed.data.shares??[]).map(share=>/* @__PURE__ */Object.freeze({shareId:share.share_id,expiresAt:share.expires_at??null,createdAt:share.created_at??null,viewCount:share.view_count??0,lastViewedAt:share.last_viewed_at??null,audience:audienceOf(share.audience)}))):null}function mapRecordShareEmailReceipt(wire){let parsed=emailSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({shareId:parsed.data.share_id,expiresAt:parsed.data.expires_at??null,audience:audienceOf(parsed.data.audience)}):null}function mapRecordPdfLink(wire){let parsed=pdfSchema.safeParse(wire);return parsed.success?/* @__PURE__ */Object.freeze({downloadUrl:parsed.data.download_url,expiresAt:parsed.data.expires_at??null}):null}var RECORDS_PDF_CONTENT_TYPE="application/pdf",RECORDS_PHOTO_CONTENT_TYPES=/* @__PURE__ */Object.freeze(["image/jpeg","image/png","image/heic","image/heif"]),isPhotoType=value=>RECORDS_PHOTO_CONTENT_TYPES.includes(value);function isAcceptedUploadType(type,types){return type===RECORDS_PDF_CONTENT_TYPE||types!==void 0&&isPhotoType(type)&&types.includes(type)}var RECORDS_FEATURES_PDF_ONLY=/* @__PURE__ */Object.freeze({features:/* @__PURE__ */Object.freeze({}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE]),shareAudiences:/* @__PURE__ */Object.freeze([])}),featuresSchema=/* @__PURE__ */z.object({features:/* @__PURE__ */z.record(/* @__PURE__ */z.boolean()),upload_content_types:/* @__PURE__ */z.array(/* @__PURE__ */z.string()).nullish(),share_audiences:/* @__PURE__ */z.unknown().optional()});function mapRecordsFeatures(wire){let parsed=featuresSchema.safeParse(wire);if(!parsed.success)return RECORDS_FEATURES_PDF_ONLY;let listed=parsed.data.upload_content_types??[],photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>listed.includes(type));/* @__PURE__ */
|
|
91
91
|
return Object.freeze({features:/* @__PURE__ */Object.freeze({...parsed.data.features}),uploadContentTypes:/* @__PURE__ */Object.freeze([RECORDS_PDF_CONTENT_TYPE,...photos]),shareAudiences:mapShareAudiences(parsed.data.share_audiences)})}function acceptsPhotos(types){return types!==void 0&&types.some(isPhotoType)}var KNOWN_STATUSES=/* @__PURE__ */new Set(["requested","awaiting_clinic","awaiting_upload","received","parsing","in_review","published","failed","revoked"]),STATUS_ALIASES=/* @__PURE__ */Object.freeze({submitted:"requested",sent:"requested",dispatching:"requested",awaiting_response:"awaiting_clinic",clinic_responded_no_records:"awaiting_clinic",records_received:"received",parsing_failed:"in_review",review_email_failed:"in_review",clinic_declined:"failed"});function normalizeStatus(raw){let aliased=Object.prototype.hasOwnProperty.call(STATUS_ALIASES,raw)?STATUS_ALIASES[raw]:void 0;if(aliased!==void 0)return aliased;let value=raw;return KNOWN_STATUSES.has(value)?value:"parsing"}function normalizeOrigin(raw){return raw==="owner_reported"||raw==="clinic_document"?raw:null}var requestSchema=/* @__PURE__ */z.object({request_id:/* @__PURE__ */z.string().min(1),pet_ref:/* @__PURE__ */z.string().min(1),status:/* @__PURE__ */z.string(),simple_status:/* @__PURE__ */z.string().nullish(),simple_status_detail:/* @__PURE__ */z.string().nullish(),status_label:/* @__PURE__ */z.string().optional(),dispatch_status:/* @__PURE__ */z.string().nullish(),can_retry_send:/* @__PURE__ */z.boolean().optional(),can_revoke:/* @__PURE__ */z.boolean().optional(),can_convert_to_upload:/* @__PURE__ */z.boolean().optional(),can_update_clinic_email:/* @__PURE__ */z.boolean().optional(),reminder_count:/* @__PURE__ */z.number().int().nonnegative().optional(),last_reminder_at:/* @__PURE__ */z.string().nullish(),waiting_expectation:/* @__PURE__ */z.string().nullish(),document_count:/* @__PURE__ */z.number().optional(),held_item_count:/* @__PURE__ */z.number().optional(),received_at:/* @__PURE__ */z.string().nullish(),parsing_started_at:/* @__PURE__ */z.string().nullish(),review_started_at:/* @__PURE__ */z.string().nullish(),created_at:/* @__PURE__ */z.string().optional(),updated_at:/* @__PURE__ */z.string().optional(),source:/* @__PURE__ */z.string().nullish().catch(null),action_needed_label:/* @__PURE__ */z.string().nullish().catch(null),failure_reason:/* @__PURE__ */z.string().nullish().catch(null),failure_code:/* @__PURE__ */z.string().nullish().catch(null),recovery_stage:/* @__PURE__ */z.string().nullish().catch(null),show_clinic_phone:/* @__PURE__ */z.boolean().optional().catch(void 0),clinic_name:/* @__PURE__ */z.string().nullish().catch(null),clinic_email:/* @__PURE__ */z.string().nullish().catch(null),clinic_phone:/* @__PURE__ */z.string().nullish().catch(null),converted_to_upload_at:/* @__PURE__ */z.string().nullish().catch(null),request_group_id:/* @__PURE__ */z.string().nullish().catch(null)}).passthrough();function mapRequestView(wire){let parsed=requestSchema.safeParse(wire);if(!parsed.success)return null;let w=parsed.data,simpleStatus=normalizeSimpleStatus(w.simple_status),status=simpleStatus==="requested"&&(w.status==="awaiting_upload"||w.simple_status_detail==="awaiting_owner_upload")?"awaiting_upload":simpleStatus==="parsing"&&(w.simple_status_detail==="in_review"||w.simple_status_detail==="review_email_failed")?"in_review":simpleStatus??normalizeStatus(w.status);/* @__PURE__ */
|
|
@@ -102,7 +102,7 @@ return Object.freeze({send:send,authorize:authorize,stream:stream})}function ass
|
|
|
102
102
|
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]=createContext(null));EverfurContext.displayName??="EverfurContext";function useEverfurContext(){let ctx=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=useCallback(()=>recordsConsentEpochOf(petRef),[petRef]);return 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=useRef(opts.uploadTransport);ownTransport.current=opts.uploadTransport;let hasOwnTransport=opts.uploadTransport!==void 0,{runtime:runtime,userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext(),scope=useMemo(()=>({}),[runtime,userRef,petRef,scopeEpoch,opts.controller]),activeScope=useRef(scope),[binding,setBinding]=useState({scope:scope,controller:opts.controller??null}),controller=opts.controller??(binding.scope===scope?binding.controller:null),[snapshot,setSnapshot]=useState({scope:scope,value:INITIAL}),snap=snapshot.scope===scope?snapshot.value:INITIAL,setSnap=useCallback(update=>{setSnapshot(current=>current.scope===scope?{scope:scope,value:update(current.value)}:current)},[scope]),generation=useRef(0);useEffect(()=>(activeScope.current=scope,setSnapshot({scope:scope,value:INITIAL}),()=>{activeScope.current=null,generation.current+=1}),[scope]),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=useCallback(partial=>{setSnap(current=>({...current,...partial}))},[setSnap]),load=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]);useEffect(()=>(load(),()=>{generation.current+=1}),[load]);let readUploadFeatures=opts.readUploadFeatures===true;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=useMemo(()=>newestRequest(snap.requests),[snap.requests]),activeId=activeRequest?.id??null,activeStatus=activeRequest?.status??null,pollsRef=useRef(0),polledIdRef=useRef(null),[pollEpoch,rearmPolls]=useReducer(n=>n+1,0);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=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=useCallback((key,update)=>{setSnap(c=>({...c,uploadQueue:c.uploadQueue.map(item=>item.key===key?update(item):item)}))},[setSnap]),uploadDocuments=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=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=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=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=useCallback(()=>load(),[load]),status=selectStatus(snap,controller!==null);return 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__ */
|
|
103
103
|
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__ */
|
|
104
104
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
105
|
-
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}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}}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)"},EVERFUR_LIGHT=deepFreeze({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},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)"};deepFreeze({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return 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 createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...props,...ref===null?{}:{ref:ref}})});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]]}}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}`,resultsCountDraft:count=>`DRAFT COPY [[${String(count)} clinics found: the spoken count of search results]]`,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,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} 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,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,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]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location?.latitude,lng=location?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),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]),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;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=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=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n=>n+1),[]);return 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__ */
|
|
105
|
+
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]=createContext(EVERFUR_LIGHT));EverfurThemeContext.displayName??="EverfurThemeContext";function useEverfurTheme(){return 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 createElement(Text$1,cap===void 0?props:{maxFontSizeMultiplier:cap,...props})}var TextInput=forwardRef(function(props,ref){return createElement(TextInput$1,{...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 base=face(theme,fallback);return base.fontWeight===void 0||headingWeight===null?base:{fontFamily:base.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}`,resultsCountDraft:count=>`DRAFT COPY [[${String(count)} clinics found: the spoken count of search results]]`,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,outOfRange,unknown)=>`Marker summary: ${total} ${total===1?"marker":"markers"}, ${inRange} in range, ${outOfRange} 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,date)=>`Latest reading ${reading}, ${status}, collected ${date}`,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]=useState(""),[debouncedQuery,setDebounced]=useState(""),[clinics,setClinics]=useState([]),[cursor,setCursor]=useState(null),[recent,setRecent]=useState([]),[recentLoading,setRecentLoading]=useState(true),[initialLoading,setInitialLoading]=useState(false),[loadingMore,setLoadingMore]=useState(false),[error,setError]=useState(null),[pageError,setPageError]=useState(null),[attempt,setAttempt]=useState(0),generation=useRef(0),live=useRef(true),lat=location?.latitude,lng=location?.longitude,bias=useMemo(()=>lat!==void 0&&lng!==void 0?{latitude:lat,longitude:lng}:void 0,[lat,lng]);useEffect(()=>(live.current=true,()=>{live.current=false,generation.current+=1}),[controller]),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]),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;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=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=useCallback(value=>setQueryValue(value),[]),retry=useCallback(()=>setAttempt(n=>n+1),[]);return 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__ */
|
|
106
106
|
return Object.freeze({key:clinic?.id??`free:${freeText??""}`,clinic:clinic,freeText:freeText,email:email2,idempotencyKey:idempotencyKey})}var RECORDS_CLINIC_BATCH_MAX=10,uuid=/* @__PURE__ */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)=>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__ */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__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */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__ */z.object({petRef:text(128),ownerName:text(200).refine(value=>value.trim().length>0&&!hasControl(value)),authorizationVersion:text(64),clinics:/* @__PURE__ */z.array(clinicSchema).min(1).max(RECORDS_CLINIC_BATCH_MAX)}).strict(),responseSchema=/* @__PURE__ */z.object({request_group_id:uuid,pet_ref:/* @__PURE__ */z.string(),created_count:/* @__PURE__ */z.number().int().nonnegative(),failed_count:/* @__PURE__ */z.number().int().nonnegative(),results:/* @__PURE__ */z.array(/* @__PURE__ */z.object({idempotency_key:/* @__PURE__ */z.string(),clinic_id:/* @__PURE__ */uuid.nullable().optional(),clinic_free_text:/* @__PURE__ */z.string().nullable().optional(),created:/* @__PURE__ */z.boolean(),request:/* @__PURE__ */z.unknown().optional(),failure_code:/* @__PURE__ */z.string().nullable().optional(),failure_reason:/* @__PURE__ */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__ */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__ */z.object({clinics:/* @__PURE__ */z.array(/* @__PURE__ */z.object({clinic_id:uuid2,name:/* @__PURE__ */z.string().min(1),address:/* @__PURE__ */z.string().nullable(),phone:/* @__PURE__ */z.string().nullable(),email_status:/* @__PURE__ */z.string(),distance_km:/* @__PURE__ */z.number().finite().nonnegative().nullable()})),next_cursor:/* @__PURE__ */z.string().nullable().optional()}),copySchema=/* @__PURE__ */z.object({authorization_version:/* @__PURE__ */z.string().min(1),scope_template:/* @__PURE__ */z.string().min(1),authorization_template:/* @__PURE__ */z.string().min(1)}),signaturePolicySchema=/* @__PURE__ */z.object({upload_id:/* @__PURE__ */z.string().min(1),upload_url:/* @__PURE__ */z.string().url().refine(value=>value.startsWith("https://")),upload_fields:/* @__PURE__ */z.record(/* @__PURE__ */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=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__ */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)=>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__ */z.object({limit:/* @__PURE__ */z.number().int().min(1).max(25).optional()}).strict(),searchSchema=/* @__PURE__ */z.object({query:text2(200,0).optional(),location:/* @__PURE__ */z.object({latitude:/* @__PURE__ */z.number().finite().min(-90).max(90),longitude:/* @__PURE__ */z.number().finite().min(-180).max(180)}).strict().optional(),limit:/* @__PURE__ */z.number().int().min(1).max(100).optional(),cursor:text2(512,0).optional()}).strict(),createSchema=/* @__PURE__ */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__ */z.string().min(1).max(2*1024*1024).optional(),idempotencyKey:/* @__PURE__ */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=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicController({repository:createHttpRecordsClinicRepository({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})})},[runtime,userRef,scopeEpoch]),active=useRef(controller);return useEffect(()=>(active.current=controller,()=>{active.current=null}),[controller]),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=useMemo(()=>{let{services:services}=runtime.registry;return createRecordsClinicBatchClient({auth:services.authFor(userRef),...services.errorPolicy?{errorPolicy:services.errorPolicy}:{}})},[runtime,userRef,scopeEpoch]),active=useRef(client);return useEffect(()=>(active.current=client,()=>{active.current=null}),[client]),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 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 createElement(HostRenderBoundary,{fallback:fallback,resetKey:resetKey,children: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"])});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__ */
|
|
107
107
|
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
108
108
|
return Object.freeze({reason:userFacingError("accessDenied"),level:"user_entitlement",recoverable:false})}function freezeDecision(d){let base={name:d.name,enabled:d.enabled,isPending:d.isPending,limits:/* @__PURE__ */Object.freeze({...d.limits})};return d.disabled!==void 0&&(base.disabled=d.disabled),/* @__PURE__ */Object.freeze(base)}function useCapability(name){let{runtime:runtime}=useEverfurContext(),store=runtime.entitlements,snapshot=useSyncExternalStore(store.subscribe,store.getSnapshot,store.getSnapshot);return 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=useMemo(()=>selectView(decision),[decision]);switch(view){case"enabled":return children;case"pending":return renderPending?/* @__PURE__ */jsx(HostRender,{render:renderPending,fallback:/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
@@ -119,7 +119,7 @@ return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
|
119
119
|
return jsxs(View,{style:box(size),...HIDDEN,children:[
|
|
120
120
|
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:ringAt,left:ringAt,width:outer,height:outer,borderRadius:outer,borderWidth:w,borderColor:color}}),
|
|
121
121
|
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:middle-w/2,left:middle-(length+w)/2,width:length+w,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:"45deg"}]}})]})}function RecordsFootnote(props){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles2(theme),[theme]);/* @__PURE__ */
|
|
122
|
-
return jsx(Text,{style:[styles.footnote,props.style],accessibilityRole:"text",testID:"records-footnote",children:RECORDS_FOOTNOTE})}function makeStyles2(theme){let{color:color,space:space,type:type}=theme;return StyleSheet.create({footnote:{...face(theme,"regular"),paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.lg,textAlign:"center",fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,backgroundColor:color.background}})}
|
|
122
|
+
return jsx(Text,{style:[styles.footnote,props.style],accessibilityRole:"text",testID:"records-footnote",children:RECORDS_FOOTNOTE})}function makeStyles2(theme){let{color:color,space:space,type:type}=theme;return StyleSheet.create({footnote:{...face(theme,"regular"),paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.lg,textAlign:"center",fontSize:type.size.caption,lineHeight:Math.round(type.size.caption*type.lineHeight.normal),color:color.text.muted,backgroundColor:color.background}})}var RECORDS_EMPTY_COPY=/* @__PURE__ */Object.freeze({idle:/* @__PURE__ */Object.freeze({title:"Find your pet’s clinic",body:"Search for the clinic that holds your pet’s records. We’ll request them on your behalf once you sign the authorization.",action:null}),no_requests:/* @__PURE__ */Object.freeze({title:"No record requests yet",body:"When you request records from a clinic, you’ll be able to track every step here.",action:null}),no_records:/* @__PURE__ */Object.freeze({title:"Nothing to show just yet",body:"Once your pet’s records arrive and our team reviews them, lab trends and visits will appear here.",action:null}),rate_limited:/* @__PURE__ */Object.freeze({title:"Slow down a moment",body:"You’ve made a lot of requests just now. You can try again shortly.",action:"Try again"}),service_unavailable:/* @__PURE__ */Object.freeze({title:"Records search is temporarily down",body:"We’re working on it. Please try again in a few minutes.",action:"Try again"}),error:/* @__PURE__ */Object.freeze({title:"Couldn’t reach Everfur",body:"Check your connection and try again.",action:"Try again"})}),RATE_LIMIT_COOLDOWN_S=60;function coolingActionLabel(seconds){return`Try again in ${seconds}s`}var COOLING_A11Y_LABEL="Try again, available shortly";var HIDDEN2={pointerEvents:"none",accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants"};function box2(size){return{width:size,height:size,alignItems:"center",justifyContent:"center"}}function stroke2(size){return Math.max(1.5,Math.round(size/11*10)/10)}function bar(color,w,length,at,angle=0){return{position:"absolute",top:at.top-w/2,left:at.left-length/2,width:length,height:w,borderRadius:w,backgroundColor:color,transform:[{rotate:`${angle}deg`}]}}function FileTextGlyph({size:size,color:color}){let w=stroke2(size),line2=(top,width)=>({position:"absolute",top:size*top,left:size*.3,width:size*width,height:w,borderRadius:w,backgroundColor:color});/* @__PURE__ */
|
|
123
123
|
return jsxs(View,{style:box2(size),...HIDDEN2,children:[
|
|
124
124
|
/* @__PURE__ */jsx(View,{style:{position:"absolute",top:size*.06,left:size*.16,width:size*.68,height:size*.88,borderWidth:w,borderColor:color,borderRadius:size*.1}}),
|
|
125
125
|
/* @__PURE__ */jsx(View,{style:line2(.36,.4)}),
|
|
@@ -162,9 +162,9 @@ return jsx(WifiOffGlyph,{size:size,color:color});default:return null}}function R
|
|
|
162
162
|
return jsxs(View,{style:styles.container,accessibilityRole:"summary",testID:testID,children:[
|
|
163
163
|
/* @__PURE__ */jsx(View,{style:styles.glyph,accessibilityElementsHidden:true,importantForAccessibility:"no-hide-descendants",testID:"records-empty-glyph",children:/* @__PURE__ */jsx(RecordsEmptyGlyph,{variant:variant,size:GLYPH_SIZE,color:theme.color.brandInk})}),
|
|
164
164
|
/* @__PURE__ */jsx(Text,{style:styles.title,children:copy.title}),
|
|
165
|
-
/* @__PURE__ */jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx(Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return 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 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:{...
|
|
166
|
-
|
|
167
|
-
/* @__PURE__ */jsx(
|
|
165
|
+
/* @__PURE__ */jsx(Text,{style:styles.body,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx(Pressable,{onPress:onAction,disabled:cooling,accessibilityRole:"button",accessibilityLabel:cooling?COOLING_A11Y_LABEL:label,accessibilityState:{disabled:cooling},style:[styles.action,cooling?styles.actionDisabled:null],testID:testID?`${testID}-action`:`records-empty-${variant}-action`,children:/* @__PURE__ */jsx(Text,{style:styles.actionLabel,children:label})}):null]})}function useStyles(){let theme=useEverfurTheme();return 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 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)}})}function useBrandImage(uri){let[failed,setFailed]=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__ */jsx(View,{style:barStyle,...testID===void 0?{}:{testID:testID},children:/* @__PURE__ */jsx(Image,{source:{uri:logoUrl},style:logoStyle,resizeMode:"contain",accessible:true,accessibilityRole:"image",accessibilityLabel:name,onError:image.onError})})}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__ */jsxs(View,{style:logoUrl===null?styles.row:styles.rowUnderLogo,testID:testID,children:[onBack?/* @__PURE__ */jsx(Pressable,{onPress:onBack,accessibilityRole:"button",accessibilityLabel:BACK_LABEL,hitSlop:12,style:styles.back,testID:testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsx(View,{style:styles.chevron,accessibilityElementsHidden:true,importantForAccessibility:"no"})}):/* @__PURE__ */jsx(View,{style:styles.back}),title.trim().length>0?/* @__PURE__ */jsx(Text,{style:variant==="document"?styles.documentTitle:styles.title,accessibilityRole:"header",numberOfLines:1,children:title}):/* @__PURE__ */jsx(View,{style:styles.spacer,accessibilityElementsHidden:true,importantForAccessibility:"no",testID:testID?`${testID}-spacer`:void 0}),
|
|
166
|
+
/* @__PURE__ */jsx(View,{style:styles.right,children:right??/* @__PURE__ */jsx(View,{style:styles.back})})]});return logoUrl===null?row:/* @__PURE__ */jsxs(View,{style:styles.bar,children:[
|
|
167
|
+
/* @__PURE__ */jsx(BrandLogo,{logoUrl:logoUrl,name:theme.meta.displayName,barStyle:styles.logoBar,logoStyle:styles.logo,testID:testID?`${testID}-logo`:void 0}),row]})}function ListGlyph2(){let styles=useStyles2();/* @__PURE__ */
|
|
168
168
|
return jsxs(View,{style:styles.listGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
169
169
|
/* @__PURE__ */jsx(View,{style:styles.listBar}),
|
|
170
170
|
/* @__PURE__ */jsx(View,{style:styles.listBar}),
|
|
@@ -181,9 +181,9 @@ return jsxs(View,{style:styles.sendGlyph,accessibilityElementsHidden:true,import
|
|
|
181
181
|
return jsxs(View,{style:styles.downloadGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:[
|
|
182
182
|
/* @__PURE__ */jsx(View,{style:styles.downloadStem}),
|
|
183
183
|
/* @__PURE__ */jsx(View,{style:styles.downloadHead}),
|
|
184
|
-
/* @__PURE__ */jsx(View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type}=theme,touch=space.xxl+space.md,chevron=space.md,stroke3=space.xs/2,glyph=space.lg+space.xs+space.xs/2;return StyleSheet.create({row:{
|
|
184
|
+
/* @__PURE__ */jsx(View,{style:styles.downloadTray})]})}function useStyles2(){let theme=useEverfurTheme();return 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 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},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},sendBody:{position:"absolute",left:0,top:0,right:0,bottom:0,borderWidth:stroke3,borderColor:ink,transform:[{rotate:"45deg"}],borderRadius:stroke3},sendFold:{position:"absolute",left:0,right:0,top:"50%",height:stroke3,backgroundColor:ink},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__ */
|
|
185
185
|
return jsxs(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__ */jsx(Text,{style:{fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
186
|
-
/* @__PURE__ */jsx(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__ */jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===FOOTNOTE}var BUTTON_HEIGHT=52,SHEET_SCRIM="rgba(0,0,0,0.4)";function useScreenStyles(){let theme=useEverfurTheme();return useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs(View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
|
|
186
|
+
/* @__PURE__ */jsx(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__ */jsx(Text,{style:{fontSize:type.size.body,color:color.brandInk},children:exitLabel})})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}var RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var normalize=text3=>text3.replace(/\s+/gu," ").trim().replace(/\.$/u,"").toLowerCase(),FOOTNOTE=normalize(RECORDS_FOOTNOTE);function disclaimerRepeatsFootnote(disclaimer){let text3=normalize(disclaimer);return text3.length===0||text3===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(n){if(!Number.isFinite(n))return null;let int=Math.trunc(n)>>>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(n){return Number.isFinite(n)?Math.min(255,Math.max(0,Math.round(n))):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(n){return n.toString(16).padStart(2,"0")}var WHITE="#FFFFFF",BLACK="#000000";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,mix=(f,g)=>Math.round(f*a+g*(1-a));return{r:mix(fg.r,bg.r),g:mix(fg.g,bg.g),b:mix(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)}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,mix=(a,b)=>Math.round(a+(b-a)*t),candidate=rgbToHex(mix(from.r,to.r),mix(from.g,to.g),mix(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,same=(a,b)=>parseColor(a)===parseColor(b);return{success:!same(c.success,compiled.success),warning:!same(c.warningStrong,compiled.warningStrong)||!same(c.cautionAccent,compiled.cautionAccent),info:!(same(c.info,c.brandInk)&&same(c.badgeBgInfo,c.brandSoft)&&same(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 useMemo(()=>makeScreenStyles(theme),[theme])}function DisclaimerBand({disclaimer:disclaimer,style:style}){let styles=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs(View,{style:[styles.band,style],accessible:true,accessibilityRole:"text",accessibilityLabel:DASHBOARD_COPY.important(disclaimer),testID:"records-disclaimer-band",children:[
|
|
187
187
|
/* @__PURE__ */jsx(View,{style:styles.infoGlyph,accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{style:styles.infoGlyphText,children:"i"})}),
|
|
188
188
|
/* @__PURE__ */jsx(Text,{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,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,text3=kind==="primary"?styles.pillPrimaryLabel:kind==="danger"?styles.pillDangerLabel:kind==="ask"?styles.pillAskLabel:kind==="link"?styles.pillLinkLabel:styles.pillOutlineLabel;/* @__PURE__ */
|
|
189
189
|
return jsxs(Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole:"button",accessibilityLabel:accessibilityLabel??label,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__ */jsx(ActivityIndicator,{size:"small",color:kind==="primary"?theme.color.onPrimary:theme.color.brandInk}):null,
|
|
@@ -191,7 +191,7 @@ return jsxs(Pressable,{onPress:onPress,disabled:disabled||busy,accessibilityRole
|
|
|
191
191
|
return jsx(View,{style:[styles.chip,sentence?styles.chipSentence:null,bg],testID:testID,children:/* @__PURE__ */jsx(Text,{style:[styles.chipText,sentence?styles.chipSentenceText:null,fg],children:label})})}var CHIP_WORD_MAX=24;function SectionHeader({title:title,count:count}){let styles=useScreenStyles();/* @__PURE__ */
|
|
192
192
|
return jsxs(View,{style:styles.sectionHeader,children:[
|
|
193
193
|
/* @__PURE__ */jsx(Text,{style:styles.sectionTitle,accessibilityRole:"header",children:title}),count!==void 0?/* @__PURE__ */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__ */
|
|
194
|
-
return jsx(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=StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),cardText=slotText(slots.recordCard),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,color.brandInk)},...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:{...text3(size.subtitle,lineHeight.snug,color.text.primary,"bold"),letterSpacing:-.4},sectionCount:{...text3(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(slots.recordCard,hairline)},creamCard:{borderRadius:radius.lg,borderWidth:1,borderColor:color.borderRingCream,backgroundColor:color.surfaceCream,padding:space.lg,gap:space.md,...slotBox(slots.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:{...text3(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(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:{...text3(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text3(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:{...text3(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text3(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text3(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text3(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text3(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},infoNoteText:{flex:1,...text3(size.bodyTight,lineHeight.normal,color.text.primary)},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,...text3(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text3(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,...text3(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},bandText:{flex:1,...text3(size.caption,lineHeight.normal,color.text.secondary)},infoGlyph:{width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,borderWidth:1,borderColor:color.text.secondary,alignItems:"center",justifyContent:"center"},infoGlyphText:{...text3(size.small,lineHeight.tight,color.text.secondary,"bold")},chevron:{width:space.sm,height:space.sm,borderTopWidth:space.xs/2,borderRightWidth:space.xs/2,borderColor:color.text.muted},lead:{paddingHorizontal:space.sm,...text3(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},fieldLabel:{...text3(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text3(size.caption,lineHeight.normal,color.text.muted),bodyText:text3(size.body,lineHeight.normal,color.text.primary)})}}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){let month=MONTHS[Number(iso[2])-1];return month===void 0?"-":`${month} ${Number(iso[3])}, ${iso[1]}`}let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return`${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`}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}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:date=>`Measured ${date}`,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:date=>`Expires ${date}`});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 num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}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 date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].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:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,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:date=>`Generated ${formatRecordsDate(date)}`,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 ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}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__ */
|
|
194
|
+
return jsx(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=StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(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)},...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:{...text3(size.subtitle,lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4},sectionCount:{...text3(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:{...text3(size.body,lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(size.caption,lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(size.body+1,lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(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:{...text3(size.tiny+1,lineHeight.snug,color.text.primary,"monoBold"),letterSpacing:.7,textTransform:"uppercase"},chipSentence:{borderRadius:radius.md,paddingVertical:space.xs,alignSelf:"stretch"},chipSentenceText:{...text3(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:{...text3(size.body,lineHeight.snug,color.onPrimary,"bold"),...slotText(slots.primaryButton)},pillOutline:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:"transparent"},pillOutlineLabel:{...text3(size.body,lineHeight.snug,color.brandInk,"bold")},pillDanger:{borderWidth:1.4,borderColor:color.danger,backgroundColor:color.surface},pillDangerLabel:{...text3(size.bodyTight,lineHeight.snug,color.danger,"bold")},pillAsk:{borderWidth:hairline,borderColor:color.borderRingCream,backgroundColor:color.surface},pillAskLabel:{...text3(size.body,lineHeight.snug,color.text.primary,"bold")},pillLink:{minHeight:touch,backgroundColor:"transparent",paddingHorizontal:space.sm},pillLinkLabel:{...text3(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,...text3(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,...text3(size.bodyTight,lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},statusText:text3(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,...text3(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,...text3(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:{...text3(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,...text3(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:{...text3(size.bodyTight,lineHeight.normal,color.text.secondary,"medium")},muted:text3(size.caption,lineHeight.normal,color.text.muted),bodyText:text3(size.body,lineHeight.normal,color.text.primary)})}}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){let month=MONTHS[Number(iso[2])-1];return month===void 0?"-":`${month} ${Number(iso[3])}, ${iso[1]}`}let ms=Date.parse(at);if(Number.isNaN(ms))return"-";let date=new Date(ms);return`${MONTHS[date.getUTCMonth()]} ${date.getUTCDate()}, ${date.getUTCFullYear()}`}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}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:date=>`Measured ${date}`,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:date=>`Expires ${date}`});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 num3=value.toFixed(3).replace(/\.?0+$/,"");return unit?`${num3} ${unit}`:num3}function labDetailLine(at,trajectory,pointCount){let traj=trajectoryLabel(trajectory,pointCount);return at?`${DEPTH_COPY.measured(formatRecordsDate(at))}${traj?` · ${traj}`:""}`:traj}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 date=receivedAt?formatRecordsDate(receivedAt):null,parts=[pageCount!==null&&Number.isInteger(pageCount)&&pageCount>0?`${pageCount} ${pageCount===1?"page":"pages"}`:null,date].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:date=>`Last done ${date}`,overdue:"Overdue",due:date=>`Due ${date}`,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:date=>`Generated ${formatRecordsDate(date)}`,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 ms=Date.parse(expiresAt);return Number.isNaN(ms)?false:ms<=nowMs}function formatShareExpiry(expiresAt,expired){let date=formatRecordsDate(expiresAt);return date==="-"?expired?"Expired":"No expiry date":expired?`Expired ${date}`:`Expires ${date}`}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__ */
|
|
195
195
|
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__ */
|
|
196
196
|
return jsx(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__ */jsxs(View,{style:styles.actionRow,children:[
|
|
197
197
|
/* @__PURE__ */jsxs(View,{style:styles.actionLeft,children:[
|
|
@@ -272,14 +272,14 @@ return jsxs(View,{style:[styles.root,style],children:[
|
|
|
272
272
|
return jsxs(Pressable,{onPress:()=>onSelect(clinic),accessibilityRole:"button",accessibilityLabel:CLINIC_PICKER_COPY.selectA11y(summary),hitSlop:8,style:styles.item,testID:`records-clinic-${clinic.id}`,children:[
|
|
273
273
|
/* @__PURE__ */jsxs(View,{style:styles.itemHeader,children:[
|
|
274
274
|
/* @__PURE__ */jsx(Text,{style:styles.itemName,numberOfLines:1,children:clinic.name}),distance?/* @__PURE__ */jsx(Text,{style:styles.itemDistance,accessibilityElementsHidden:true,importantForAccessibility:"no",children:distance}):null]}),clinic.address?/* @__PURE__ */jsx(Text,{style:styles.itemAddress,numberOfLines:2,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsx(Text,{style:styles.itemPhone,numberOfLines:1,accessibilityElementsHidden:true,importantForAccessibility:"no",children:clinic.phone}):null,
|
|
275
|
-
/* @__PURE__ */jsx(View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */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 useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return StyleSheet.create({lead:{...text3(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},howTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),letterSpacing:-.4},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:text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),howStepBody:text3(type.size.caption,type.lineHeight.normal,color.text.secondary),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},searchInput:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0},clearGlyph:text3(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:{...text3(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},fallbackHeader:{flexDirection:"row",alignItems:"center",gap:space.md,minHeight:space.xxl+space.md},fallbackCopy:{flex:1,gap:space.xs/2},fallbackTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},fallbackSubtitle:text3(type.size.caption,type.lineHeight.normal,color.text.muted),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},itemHeader:{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:space.sm},itemName:{flex:1,...text3(type.size.body,type.lineHeight.snug,color.brandInk,"bold")},itemDistance:{...face(theme,"mono"),fontSize:type.size.tiny,lineHeight:type.size.body,color:color.text.muted},itemAddress:text3(type.size.caption,type.lineHeight.normal,color.text.primary),itemPhone:text3(type.size.caption,type.lineHeight.normal,color.text.muted),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:{...text3(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:{...text3(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:n=>`Send ${n} ${n===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]=useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=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,text3=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text3)?null:text3}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinic,setClinic]=useState(null),[email2,setEmail]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[created,setCreated]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null),captureAbort=useRef(null),lifetime=useRef(0);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]),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]),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]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[drafts,setDrafts]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[outcome,setOutcome]=useState(null),[group,setGroup]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),lifetime=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),signature=useRef(null),captureAbort=useRef(null);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]),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]),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),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),props.petName,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()&&props.petName.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:props.petName,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=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,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=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return 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__ */jsx(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),text3=name.trim();if(text3.length===0)return bitmap;let chars=[...text3],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 byte of bytes)a=(a+byte)%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 n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=c>>>0}}let crc=4294967295;for(let byte of bytes)crc=crcTable[(crc^byte)&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]=useState("draw"),[typed,setTyped]=useState(""),[strokes,setStrokes]=useState([]),[width,setWidth]=useState(0),current=useRef([]),drawing=useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=useRef(scale);scaleRef.current=scale;let disabledRef=useRef(disabled);disabledRef.current=disabled,useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+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=useMemo(()=>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=useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
275
|
+
/* @__PURE__ */jsx(View,{style:[styles.badge,badge.tone==="positive"?styles.badgePositive:badge.tone==="caution"?styles.badgeCaution:styles.badgeNeutral],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */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 useMemo(()=>makeLocalStyles(theme),[theme])}function makeLocalStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text3=(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 StyleSheet.create({lead:{...text3(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:{...text3(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:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},howStepBody:{...text3(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,...text3(type.size.body,type.lineHeight.snug,color.text.primary),paddingVertical:0,...slotText(theme.slots.input)},clearGlyph:text3(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:{...text3(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:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...cardText},fallbackSubtitle:{...text3(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,...text3(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:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),...cardText},itemPhone:{...text3(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:{...text3(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:{...text3(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:n=>`Send ${n} ${n===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]=useState({list:clinics,shown:CLINIC_FORM_RESULTS_STEP}),shown=state.list===clinics?state.shown:CLINIC_FORM_RESULTS_STEP,showMore=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,text3=copy.scopeTemplate.replace(/\{([^{}]+)\}/g,(_,key)=>Object.prototype.hasOwnProperty.call(fields,key)?fields[key]??"":(unknown=true,""));return unknown||/[{}]/.test(text3)?null:text3}function clinicNeedsEmail(clinic){return clinic===null||clinic.emailStatus!=="verified"&&clinic.emailStatus!=="unverified"}function useClinicRequestForm(props,controller,capture){let[ownerName,setOwner]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinic,setClinic]=useState(null),[email2,setEmail]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[created,setCreated]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),attempt=useRef(null),captureAbort=useRef(null),lifetime=useRef(0);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]),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]),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]=useState(props.ownerName),[query,setQueryValue]=useState(""),[clinics,setClinics]=useState([]),[recent,setRecent]=useState([]),[drafts,setDrafts]=useState([]),[copy,setCopy]=useState(null),[error,setError]=useState(null),[busy,setBusy]=useState(false),[searching,setSearching]=useState(false),[outcome,setOutcome]=useState(null),[group,setGroup]=useState(null),[copyAttempt,setCopyAttempt]=useState(0),active=useRef(false),locked=useRef(false),generation=useRef(0),lifetime=useRef(0),keyFactory=useRef(defaultIdempotencyKeyFactory()),signature=useRef(null),captureAbort=useRef(null);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]),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]),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),scopes=copy?names.map(name=>renderClinicScope(copy,ownerName.trim(),props.petName,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()&&props.petName.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:props.petName,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=useRef(null),[reading,setReading]=useState(null),frame=useRef(null),retry=useRef(null),mounted=useRef(true),stopRetry=useCallback(()=>{retry.current!==null&&clearTimeout(retry.current),retry.current=null},[]);useEffect(()=>(mounted.current=true,()=>{mounted.current=false,stopRetry()}),[stopRetry]);let measure=useCallback(function measureAt(attempt){probeRef.current?.measureInWindow((_x,windowY)=>{let at=frame.current;if(!mounted.current||at===null)return;let next=readWindowTops(windowY,at.y,at.height,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=useCallback(event=>{let{y:y,height:height}=event.nativeEvent.layout;frame.current={y:y,height:height},stopRetry(),measure(0)},[measure,stopRetry]);return 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__ */jsx(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),text3=name.trim();if(text3.length===0)return bitmap;let chars=[...text3],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 n=0;n<256;n+=1){let c=n;for(let k=0;k<8;k+=1)c=c&1?3988292384^c>>>1:c>>>1;crcTable[n]=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]=useState("draw"),[typed,setTyped]=useState(""),[strokes,setStrokes]=useState([]),[width,setWidth]=useState(0),current=useRef([]),drawing=useRef(null),scale=width>0?SIGNATURE_CANVAS.width/width:1,scaleRef=useRef(scale);scaleRef.current=scale;let disabledRef=useRef(disabled);disabledRef.current=disabled,useEffect(()=>{if(mode==="type"){callHost(onChange,typed.trim().length>0?encodeSignaturePng(rasterizeTypedName(typed)):null);return}let points=strokes.reduce((n,stroke3)=>n+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=useMemo(()=>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=useCallback(()=>{disabledRef.current||(current.current=[],drawing.current=null,setStrokes([]),setTyped(""))},[]),toggle=useCallback(()=>{clear(),setMode(m=>m==="draw"?"type":"draw")},[clear]),onLayout=event=>setWidth(event.nativeEvent.layout.width);/* @__PURE__ */
|
|
276
276
|
return jsxs(View,{style:styles.container,testID:"records-signature-pad",children:[
|
|
277
277
|
/* @__PURE__ */jsx(Text,{style:styles.label,children:mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),mode==="type"?/* @__PURE__ */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,
|
|
278
278
|
/* @__PURE__ */jsx(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__ */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__ */
|
|
279
279
|
return jsx(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)})}),
|
|
280
280
|
/* @__PURE__ */jsxs(View,{style:styles.actions,children:[
|
|
281
281
|
/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:CLINIC_REQUEST_COPY.clear,accessibilityState:{disabled:disabled},disabled:disabled,onPress:clear,style:styles.button,children:/* @__PURE__ */jsx(Text,{style:styles.buttonLabel,children:CLINIC_REQUEST_COPY.clear})}),
|
|
282
|
-
/* @__PURE__ */jsx(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__ */jsx(Text,{style:styles.buttonLabel,children:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw})})]})]})}function useStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeStyles6(theme),[theme])}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme;return 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},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__ */
|
|
282
|
+
/* @__PURE__ */jsx(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__ */jsx(Text,{style:styles.buttonLabel,children:mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw})})]})]})}function useStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeStyles6(theme),[theme])}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme;return 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__ */
|
|
283
283
|
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}var IOS=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]=useState(null),padCapture=useCallback(async()=>png===null?null:{signaturePngBase64:png},[png]),register=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=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&&(Keyboard.dismiss(),form.search())},option=(key,clinic)=>{let detail=clinicDetail(clinic);/* @__PURE__ */
|
|
284
284
|
return jsxs(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:[
|
|
285
285
|
/* @__PURE__ */jsx(Text,{style:local.optionName,children:clinic.name}),detail?/* @__PURE__ */jsx(Text,{style:styles.muted,children:detail}):null]},key)};/* @__PURE__ */
|
|
@@ -307,7 +307,7 @@ return jsxs(View,{style:local.option,accessible:true,accessibilityRole:"text",ac
|
|
|
307
307
|
/* @__PURE__ */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__ */jsx(Pill,{label:CLINIC_BATCH_COPY.addClinic,kind:"link",disabled:form.busy,onPress:form.addFreeText,testID:"records-batch-add-typed"}):null,form.searching?/* @__PURE__ */jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading}):null,form.recent.length>0?/* @__PURE__ */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__ */jsx(Pill,{label:CLINIC_REQUEST_COPY.moreClinics,kind:"link",disabled:form.busy,onPress:form.showMoreClinics}):null]})]}),
|
|
308
308
|
/* @__PURE__ */jsxs(View,{style:local.scopeCard,accessibilityRole:"summary",testID:"records-batch-scope",children:[
|
|
309
309
|
/* @__PURE__ */jsx(Text,{accessibilityRole:"header",style:local.sectionTitle,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsx(Text,{style:local.scopeText,testID:"records-batch-scope-text",children:form.drafts.length>0&&form.ownerName.trim()?form.scopeText??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsx(Text,{accessibilityLiveRegion:"polite",style:styles.muted,children:RECORDS_COPY.loading})]}),!props.onCaptureSignature&&/* @__PURE__ */jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",style:styles.bodyText,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsx(View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsx(Text,{style:styles.errorText,children:form.error.displayMessage})}),!form.copy&&form.error&&/* @__PURE__ */jsx(Pill,{label:RECORDS_COPY.retry,kind:"outline",onPress:form.retryCopy})]}),
|
|
310
|
-
/* @__PURE__ */jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsx(View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return StyleSheet.create({header:{flexDirection:"row",alignItems:"center",gap:space.md,paddingHorizontal:space.lg,paddingTop:space.xs,paddingBottom:space.md},title:{flex:1,...text3(type.size.heading,type.lineHeight.snug,color.brandInk,"bold")},close:{minHeight:touch,minWidth:touch,alignItems:"center",justifyContent:"center"},closeLabel:text3(type.size.body,type.lineHeight.snug,color.linkInk,"bold"),content:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.lg},lead:text3(type.size.body,type.lineHeight.normal,color.text.muted),block:{gap:space.sm},sectionTitle:text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"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},optionName:text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),draft:{gap:space.sm,borderRadius:radius.md,borderWidth:1,borderColor:color.brandBorder,backgroundColor:color.surface,padding:space.md},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},scopeText:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.secondary),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__ */z.string().nullish(),num=/* @__PURE__ */z.number().nullish(),pointSchema=/* @__PURE__ */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__ */z.boolean().nullish()}),latestSchema=/* @__PURE__ */z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,status:str2}),markerSchema=/* @__PURE__ */z.object({marker_id:/* @__PURE__ */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__ */z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */z.object({total_markers:/* @__PURE__ */z.number().int().nonnegative(),in_range_count:/* @__PURE__ */z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */z.number().int().nonnegative(),unknown_count:/* @__PURE__ */z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */z.object({markers:/* @__PURE__ */z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */z.string().optional(),featured_marker_id:str2});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
310
|
+
/* @__PURE__ */jsx(RecordsFootnote,{})]}),form.outcome?null:/* @__PURE__ */jsx(View,{style:[local.footer,{paddingBottom:Math.max(insets.bottom,theme.space.md)}],testID:"records-batch-footer",children:/* @__PURE__ */jsx(Pill,{label:sendLabel,disabled:form.busy||!form.ready||!signed,busy:form.busy,onPress:()=>{Keyboard.dismiss(),form.submit()},testID:"records-batch-send"})})]})]})}function useLocalStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles2(theme),[theme])}function makeLocalStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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,...text3(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:text3(type.size.body,type.lineHeight.snug,color.linkInk,"bold"),content:{paddingHorizontal:space.lg,paddingBottom:space.xl,gap:space.lg},lead:text3(type.size.body,type.lineHeight.normal,color.text.muted),block:{gap:space.sm},sectionTitle:{...text3(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:{...text3(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:{...text3(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__ */z.string().nullish(),num=/* @__PURE__ */z.number().nullish(),pointSchema=/* @__PURE__ */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__ */z.boolean().nullish()}),latestSchema=/* @__PURE__ */z.object({collected_at:str2,at:str2,value:num,unit:str2,qualitative_result:str2,status:str2}),markerSchema=/* @__PURE__ */z.object({marker_id:/* @__PURE__ */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__ */z.array(pointSchema).optional()}),summarySchema=/* @__PURE__ */z.object({total_markers:/* @__PURE__ */z.number().int().nonnegative(),in_range_count:/* @__PURE__ */z.number().int().nonnegative(),out_of_range_count:/* @__PURE__ */z.number().int().nonnegative(),unknown_count:/* @__PURE__ */z.number().int().nonnegative()}),markersSchema=/* @__PURE__ */z.object({markers:/* @__PURE__ */z.array(markerSchema).optional(),summary:/* @__PURE__ */summarySchema.nullish(),disclaimer:/* @__PURE__ */z.string().optional(),featured_marker_id:str2});function isObject2(v){return typeof v=="object"&&v!==null&&!Array.isArray(v)}function withheldMarkers(pet){/* @__PURE__ */
|
|
311
311
|
return Object.freeze({petRef:pet,withheld:true,markers:/* @__PURE__ */Object.freeze([]),summary:null,disclaimer:"",featuredMarkerId:null})}function mapRecordMarkers(petRef,wire){let w=isObject2(wire)?wire:{},pet=typeof w.pet_ref=="string"&&w.pet_ref.length>0?w.pet_ref:petRef;if(w.withheld===true)return withheldMarkers(pet);let parsed=markersSchema.safeParse(w);if(!parsed.success)return withheldMarkers(pet);let m=parsed.data,point=p=>/* @__PURE__ */Object.freeze({at:p.collected_at??p.at??null,value:p.value??null,unit:p.unit??null,qualitativeResult:p.qualitative_result??null,refLow:p.ref_low??null,refHigh:p.ref_high??null,status:p.status??null,sourceClinic:p.source_clinic??null,docId:p.source_doc_id??p.doc_id??null,reviewed:p.reviewed===true}),markers=(m.markers??[]).map(marker=>/* @__PURE__ */Object.freeze({markerId:marker.marker_id,name:marker.canonical_name??marker.name??marker.marker_id,loincCode:marker.loinc_code??null,unit:marker.canonical_unit??marker.unit??null,panel:marker.panel_name??marker.panel??null,meaning:marker.meaning_text??marker.meaning??null,latest:marker.latest?/* @__PURE__ */Object.freeze({at:marker.latest.collected_at??marker.latest.at??null,value:marker.latest.value??null,unit:marker.latest.unit??null,qualitativeResult:marker.latest.qualitative_result??null,status:marker.latest.status??null}):null,trajectory:marker.trajectory??null,points:/* @__PURE__ */Object.freeze((marker.points??[]).map(point))}));/* @__PURE__ */
|
|
312
312
|
return Object.freeze({petRef:pet,withheld:false,markers:/* @__PURE__ */Object.freeze(markers),summary:m.summary?/* @__PURE__ */Object.freeze({totalMarkers:m.summary.total_markers,inRangeCount:m.summary.in_range_count,outOfRangeCount:m.summary.out_of_range_count,unknownCount:m.summary.unknown_count}):null,disclaimer:m.disclaimer??"",featuredMarkerId:m.featured_marker_id??null})}var https2=/* @__PURE__ */z.string().min(1).refine(value=>value.startsWith("https://")),itemSchema=/* @__PURE__ */z.object({source_doc_id:/* @__PURE__ */z.string().min(1),file_name:/* @__PURE__ */z.string().nullish(),doc_format:/* @__PURE__ */z.string().nullish(),byte_size:/* @__PURE__ */z.number().int().nonnegative().nullish(),received_at:/* @__PURE__ */z.string().nullish(),download_url:https2,expires_in_seconds:/* @__PURE__ */z.number().int().nonnegative().nullish()}),listSchema2=/* @__PURE__ */z.object({items:/* @__PURE__ */z.array(/* @__PURE__ */z.unknown()).optional()});function mapRequestDocuments(wire){let parsed=listSchema2.safeParse(wire);if(!parsed.success)return null;let rows=[];for(let raw of parsed.data.items??[]){let item=itemSchema.safeParse(raw);item.success&&rows.push(
|
|
313
313
|
/* @__PURE__ */Object.freeze({sourceDocId:item.data.source_doc_id,fileName:item.data.file_name??null,docFormat:item.data.doc_format??null,byteSize:item.data.byte_size??null,receivedAt:item.data.received_at??null,downloadUrl:item.data.download_url,expiresInSeconds:item.data.expires_in_seconds??0}))}/* @__PURE__ */
|
|
@@ -354,7 +354,7 @@ return jsx(Pressable,{onPress:()=>form.pickReuseSignature(selected?null:sig.sign
|
|
|
354
354
|
/* @__PURE__ */jsx(Text,{style:local.scopeHeading,accessibilityRole:"header",children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
355
355
|
/* @__PURE__ */jsx(Text,{style:local.scopeBody,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsx(View,{style:styles.errorBanner,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:/* @__PURE__ */jsx(Text,{style:styles.errorText,children:form.error})}):null,form.created?/* @__PURE__ */jsx(Text,{accessibilityLiveRegion:"polite",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
356
356
|
/* @__PURE__ */jsx(View,{style:local.footer,testID:"records-consent-footer",children:/* @__PURE__ */jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onPress:()=>{Keyboard.dismiss(),form.submit()},style:local.submit,testID:"records-consent-submit"})})]}),
|
|
357
|
-
/* @__PURE__ */jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xl+space.xs,gap:space.lg+space.xs/2},lead:text3(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},nextCard:{borderRadius:radius.lg,backgroundColor:color.surfaceSubtle,padding:space.lg,gap:space.sm},scopeHeading:{...text3(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:-.4},scopeBody:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),bullets:{gap:space.sm},bulletRow:{flexDirection:"row",alignItems:"flex-start",gap:space.sm},check:{...text3(type.size.body,type.lineHeight.normal,color.brandInk,"bold")},bulletText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},retentionRow:{paddingTop:space.xs,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},retentionText:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),serverScope:{...text3(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:{...text3(type.size.body,type.lineHeight.tight,color.surface,"bold")},toggleLabel:{flex:1,...text3(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:{...text3(type.size.bodyTight,type.lineHeight.snug,color.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.xxl,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background},submit:{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__ */
|
|
357
|
+
/* @__PURE__ */jsx(RecordsFootnote,{})]})}function useLocalStyles3(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles3(theme),[theme])}function makeLocalStyles3(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return StyleSheet.create({content:{paddingHorizontal:space.lg,paddingBottom:space.xl+space.xs,gap:space.lg+space.xs/2},lead:text3(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:{...text3(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),letterSpacing:-.4,...slotText(theme.slots.card)},scopeBody:{...text3(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:{...text3(type.size.body,type.lineHeight.normal,color.brandInk,"bold")},bulletText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},retentionRow:{paddingTop:space.xs,borderTopWidth:1,borderTopColor:color.borderHairlineGreen},retentionText:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),serverScope:{...text3(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:{...text3(type.size.body,type.lineHeight.tight,color.surface,"bold")},toggleLabel:{flex:1,...text3(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:{...text3(type.size.bodyTight,type.lineHeight.snug,color.linkInk,"bold"),textDecorationLine:"underline"},footer:{paddingHorizontal:space.lg,paddingTop:space.md,paddingBottom:space.xxl,borderTopWidth:hairline,borderTopColor:color.borderHairlineGreen,backgroundColor:color.background},submit:{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__ */
|
|
358
358
|
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 lead(petName){return petName?.trim()||"my pet"}function clause(text3){let t=text3.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"} ${formatRecordsDate(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__ */
|
|
359
359
|
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__ */
|
|
360
360
|
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 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__ */
|
|
@@ -369,7 +369,7 @@ return jsxs(View,{style:styles.card,accessibilityRole:"summary",testID:testID,ch
|
|
|
369
369
|
/* @__PURE__ */jsx(Badge,{count:outOfRangeCount,label:MARKER_SUMMARY_COPY.outOfRange,color:theme.color.danger,styles:styles}),
|
|
370
370
|
/* @__PURE__ */jsx(Badge,{count:inRangeCount,label:MARKER_SUMMARY_COPY.inRange,color:theme.color.success,styles:styles}),unknownCount>0?/* @__PURE__ */jsx(Badge,{count:unknownCount,label:MARKER_SUMMARY_COPY.noRange,color:theme.color.text.muted,styles:styles}):null]}):null,
|
|
371
371
|
/* @__PURE__ */jsx(Text,{style:styles.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsx(Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:MARKER_SUMMARY_COPY.ask,style:styles.ask,testID:"marker-summary-ask",children:/* @__PURE__ */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__ */jsx(View,{style:[styles.piece,{transform:[{rotate:`${piece.start}deg`}]}],pointerEvents:"none",testID:`marker-ring-${segment.key}`,children:/* @__PURE__ */jsx(View,{style:styles.window,children:/* @__PURE__ */jsx(View,{style:[styles.halfRing,{borderTopColor:segment.color,borderRightColor:segment.color,transform:[{rotate:`${piece.sweep-135}deg`}]}]})})},index))}function Badge({count:count,label:label,color:color,styles:styles}){/* @__PURE__ */
|
|
372
|
-
return jsx(View,{style:[styles.badge,{borderColor:color}],children:/* @__PURE__ */jsx(Text,{style:[styles.badgeText,{color:color}],children:`${count} ${label}`})})}function useStyles5(){let theme=useEverfurTheme();return useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=StyleSheet.hairlineWidth,cardText=slotText(slots
|
|
372
|
+
return jsx(View,{style:[styles.badge,{borderColor:color}],children:/* @__PURE__ */jsx(Text,{style:[styles.badgeText,{color:color}],children:`${count} ${label}`})})}function useStyles5(){let theme=useEverfurTheme();return useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=StyleSheet.hairlineWidth,cardText=slotText(recordCardSlot(slots));return 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=useMemo(()=>buildMarkerChart(marker),[marker]),latestReading=marker.latest?formatMarkerReading(marker.latest.value,marker.unit,marker.latest.qualitativeResult):null;/* @__PURE__ */
|
|
373
373
|
return jsx(View,{style:[styles.page,width!==void 0?{width:width}:null],testID:`marker-card-${marker.markerId}`,children:/* @__PURE__ */jsxs(View,{style:styles.card,children:[
|
|
374
374
|
/* @__PURE__ */jsxs(View,{style:styles.headerRow,children:[
|
|
375
375
|
/* @__PURE__ */jsxs(View,{style:styles.nameColumn,children:[
|
|
@@ -397,7 +397,7 @@ return jsxs(Modal,{transparent:true,visible:true,animationType:"slide",onRequest
|
|
|
397
397
|
/* @__PURE__ */jsxs(View,{style:styles.sheetBody,children:[
|
|
398
398
|
/* @__PURE__ */jsxs(View,{style:styles.valueRow,children:[
|
|
399
399
|
/* @__PURE__ */jsx(Text,{style:styles.sheetName,children:marker.name}),
|
|
400
|
-
/* @__PURE__ */jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsx(View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */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__ */jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsx(Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=StyleSheet.hairlineWidth,dot=space.md,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg}),cardText=slotText(slots.
|
|
400
|
+
/* @__PURE__ */jsx(Text,{style:styles.sheetValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsx(View,{style:styles.reviewed,accessibilityRole:"text",children:/* @__PURE__ */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__ */jsx(Text,{style:styles.unverified,accessibilityRole:"text",children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsx(Pressable,{onPress:onAsk,accessibilityRole:"button",accessibilityLabel:PROVENANCE_COPY.ask,style:[screen.pill,screen.pillAsk],testID:"marker-provenance-ask",children:/* @__PURE__ */jsx(Text,{style:screen.pillAskLabel,children:PROVENANCE_COPY.ask})}):null]})]})]})}function useStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,hairline=StyleSheet.hairlineWidth,dot=space.md,text3=(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={...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},valueText=text3(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold");return 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:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},trajectory:{...text3(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:{...text3(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center",...cardText},singleHint:{...text3(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:{...text3(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,...text3(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:{...text3(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:{...text3(type.size.tiny,type.lineHeight.normal,color.success,"medium")},detailRow:{gap:space.xs/2},detailLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted,"medium"),...dialogText},detailValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary),...dialogText},unverified:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...dialogText}})}var FACT_EDIT_COPY=/* @__PURE__ */Object.freeze({editA11y:label=>`Edit ${label}. Correct or remove this record detail.`,title:label=>`Edit ${label}`,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__ */
|
|
401
401
|
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]=useState(EMPTY_FACT_OVERLAY),[busy,setBusy]=useState(false),[error,setError]=useState(null),scope=useMemo(()=>({}),[client,petRef,userRef]),[darkScope,setDarkScope]=useState(null),markDark=useCallback(()=>setDarkScope(scope),[scope]),available=userRef!==null&&darkScope!==scope,locked=useRef(false),mintRef=useRef(opts.newIdempotencyKey);mintRef.current=opts.newIdempotencyKey;let mint=useCallback(()=>(mintRef.current??defaultFactKey)(),[]),settle=useCallback((result,rollback,mode)=>{if(setBusy(false),!result.ok){if(rollback(),isDarkRouteError(result.error)){markDark();return}setError(factEditErrorMessage(result.error,mode))}},[markDark]),edit=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=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=useCallback(()=>setError(null),[]);return 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 ms=Date.parse(value);return Number.isNaN(ms)?null:ms}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 ms=toMillis(at);return ms===null?VACCINE_UNDATED_GROUP:String(new Date(ms).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__ */
|
|
402
402
|
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__ */
|
|
403
403
|
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]=useState(false),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
@@ -420,7 +420,7 @@ return jsx(Modal,{transparent:true,visible:true,animationType:"slide",onRequestC
|
|
|
420
420
|
/* @__PURE__ */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"}),
|
|
421
421
|
/* @__PURE__ */jsx(Pill,{label:FACT_EDIT_COPY.keep,kind:"outline",disabled:busy,onPress:()=>setConfirmingRemove(false),style:styles.confirmButton,testID:"fact-edit-remove-cancel"})]})]}):/* @__PURE__ */jsxs(View,{style:styles.actions,children:[
|
|
422
422
|
/* @__PURE__ */jsx(Pill,{label:busy?FACT_EDIT_COPY.saving:FACT_EDIT_COPY.save,busy:busy,disabled:!changed,onPress:submitEdit,testID:"fact-edit-save"}),
|
|
423
|
-
/* @__PURE__ */jsx(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__ */jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return 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,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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},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:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},helper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),helperError:{color:errorColor},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:text3(type.size.verdict,type.lineHeight.tight,color.text.primary),actions:{gap:space.sm},removeButton:{minHeight:touch,alignItems:"center",justifyContent:"center"},removeDisabled:{opacity:.5},removeText:{...text3(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}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=useMemo(()=>factEdit?applyFactOverlay(record.entities,factEdit.overlay):record.entities,[record.entities,factEdit]),byType=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=useMemo(()=>selectVaccineGroups(entities),[entities]),documents=Object.values(record.documents),ask=(build,label,testID)=>onAsk?/* @__PURE__ */jsx(Pressable,{onPress:()=>{let built=build();onAsk(built.prompt,built.entityRef)},accessibilityRole:"button",accessibilityLabel:label,style:[styles.pill,styles.pillAsk,local.ask],testID:testID,children:/* @__PURE__ */jsx(Text,{style:styles.pillAskLabel,children:label})}):null,editable=factEdit!==void 0&&factEdit.available;/* @__PURE__ */
|
|
423
|
+
/* @__PURE__ */jsx(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__ */jsx(Text,{style:styles.removeText,children:FACT_EDIT_COPY.remove})})]})]})]})})}function useStyles7(){let theme=useEverfurTheme();return 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,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.dialog)},helper:{...text3(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:{...text3(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:{...text3(type.size.bodyTight,type.lineHeight.snug,color.danger,"bold")},confirmBlock:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.badgeBgCritical},confirmText:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),confirmRow:{flexDirection:"row",gap:space.sm},confirmButton:{flex:1}})}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=useMemo(()=>factEdit?applyFactOverlay(record.entities,factEdit.overlay):record.entities,[record.entities,factEdit]),byType=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=useMemo(()=>selectVaccineGroups(entities),[entities]),documents=Object.values(record.documents),ask=(build,label,testID)=>onAsk?/* @__PURE__ */jsx(Pressable,{onPress:()=>{let built=build();onAsk(built.prompt,built.entityRef)},accessibilityRole:"button",accessibilityLabel:label,style:[styles.pill,styles.pillAsk,local.ask],testID:testID,children:/* @__PURE__ */jsx(Text,{style:styles.pillAskLabel,children:label})}):null,editable=factEdit!==void 0&&factEdit.available;/* @__PURE__ */
|
|
424
424
|
return jsxs(Fragment,{children:[
|
|
425
425
|
/* @__PURE__ */jsxs(View,{style:local.sections,children:[depth&&depth.conflicts.length>0?/* @__PURE__ */jsxs(View,{style:styles.section,testID:"record-section-conflicts",children:[
|
|
426
426
|
/* @__PURE__ */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__ */
|
|
@@ -433,7 +433,7 @@ return jsxs(View,{style:[local.conflictCard,{borderColor:styles.chipTones[meta.t
|
|
|
433
433
|
/* @__PURE__ */jsx(Text,{style:styles.rowMuted,children:[candidate.docId?record.documents[candidate.docId]?.title??RECORD_SCREEN_COPY.uploadedDocument: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__ */jsxs(View,{style:styles.section,testID:"record-section-completeness",children:[
|
|
434
434
|
/* @__PURE__ */jsx(SectionHeader,{title:RECORD_SCREEN_COPY.whatsOnFile}),
|
|
435
435
|
/* @__PURE__ */jsxs(View,{style:styles.card,children:[
|
|
436
|
-
/* @__PURE__ */jsx(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(([label,present])=>/* @__PURE__ */jsx(View,{style:[local.coveragePill,present?styles.chipTones.positive.bg:styles.chipTones.neutral.bg],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:{color:styles.rowMuted.color}],children:label})},label))}),
|
|
436
|
+
/* @__PURE__ */jsx(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(([label,present])=>/* @__PURE__ */jsx(View,{style:[local.coveragePill,present?[styles.chipTones.positive.bg,local.coverageOnFile]:[styles.chipTones.neutral.bg,local.coverageRest]],accessible:true,accessibilityRole:"text",accessibilityLabel:`${label}: ${present?RECORD_SCREEN_COPY.onFile:RECORD_SCREEN_COPY.noneOnFile}`,children:/* @__PURE__ */jsx(Text,{style:[local.coverageText,present?styles.chipTones.positive.fg:[{color:styles.rowMuted.color},local.coverageRestText]],children:label})},label))}),
|
|
437
437
|
/* @__PURE__ */jsxs(View,{style:local.metaRow,children:[
|
|
438
438
|
/* @__PURE__ */jsx(Text,{style:local.metaText,children:RECORD_SCREEN_COPY.documentsOnFile(depth.completeness.documentsIngested)}),depth.completeness.documentsInReview>0?/* @__PURE__ */jsx(Chip,{label:RECORD_SCREEN_COPY.inReviewChip(depth.completeness.documentsInReview),tone:"warning"}):null,heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)>0?/* @__PURE__ */jsx(View,{accessible:true,accessibilityRole:"text",accessibilityLabel:RECORD_SCREEN_COPY.beingVerifiedA11y(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),children:/* @__PURE__ */jsx(Chip,{label:RECORD_SCREEN_COPY.beingVerified(heldCount(depth.completeness.heldTotal,depth.completeness.entitiesPendingReview)),tone:"warning"})}):null]}),depth.completeness.earliestRecordAt||depth.completeness.latestRecordAt?/* @__PURE__ */jsx(View,{style:local.metaRow,children:/* @__PURE__ */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__ */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__ */jsxs(View,{style:styles.section,testID:"record-section-documents",children:[
|
|
439
439
|
/* @__PURE__ */jsx(SectionHeader,{title:RECORD_SCREEN_COPY.documents,count:documents.length}),
|
|
@@ -481,14 +481,14 @@ return jsxs(View,{style:[styles.row,index>0?styles.rowDivider:null],children:[
|
|
|
481
481
|
/* @__PURE__ */jsx(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__ */
|
|
482
482
|
return jsx(View,{style:[styles.row,index>0?styles.rowDivider:null],children:/* @__PURE__ */jsxs(View,{style:styles.rowMain,children:[
|
|
483
483
|
/* @__PURE__ */jsx(Text,{style:styles.rowTitle,children:encounter.type?humanize(encounter.type):DEPTH_COPY.visit}),detail?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:detail}):null]})},encounter.encounterId)})})]}):null]}),
|
|
484
|
-
/* @__PURE__ */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 useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth;return 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},conflictHead:{flexDirection:"row",alignItems:"center",gap:space.sm},conflictTitle:{flex:1,...face(theme,"bold"),fontSize:type.size.body,lineHeight:Math.round(type.size.body*type.lineHeight.snug),color:color.text.primary},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},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){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=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]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=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]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(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 rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,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]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);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)}function inArtifactWords(events,request,petName){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;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(),events=buildRequestTimeline(request,{petName:petName??null});/* @__PURE__ */
|
|
484
|
+
/* @__PURE__ */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 useMemo(()=>makeLocalStyles4(theme),[theme])}function makeLocalStyles4(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth;return 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:slotBox(theme.slots.chip),coverageRestText:slotText(theme.slots.chip),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){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment3)},[consentVersion,consentText,isDevelopment3])}function useRnColorScheme(){let colorScheme=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]=useState(false);return useEffect(()=>{let mounted=true,query=AccessibilityInfo?.isReduceMotionEnabled;if(typeof query=="function"){let result=query.call(AccessibilityInfo);result!=null&&typeof result.then=="function"&&result.then(value=>{mounted&&setReduced(value===true)},()=>{})}let subscription=AccessibilityInfo?.addEventListener?.("reduceMotionChanged",value=>setReduced(value===true));return()=>{mounted=false,subscription?.remove?.()}},[]),reduced}function readFontScale(){let read=PixelRatio?.getFontScale;if(typeof read!="function")return 1;try{let scale=read.call(PixelRatio);return typeof scale=="number"&&Number.isFinite(scale)&&scale>0?scale:1}catch{return 1}}function subscribeFontScale(onChange){let subscribe2=Dimensions?.addEventListener;if(typeof subscribe2!="function")return()=>{};let subscription=subscribe2.call(Dimensions,"change",onChange);return()=>subscription?.remove?.()}function useRnTextScale(){return useSyncExternalStore(subscribeFontScale,readFontScale,readFontScale)}function platformOS(){try{let os=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]=useState(false);return useEffect(()=>{let mounted=true,{query:query,event:event}=contrastSignal(),read=AccessibilityInfo?.[query];if(typeof read!="function")return()=>{};try{let result=read.call(AccessibilityInfo);isThenable2(result)&&Promise.resolve(result).then(value=>{mounted&&setOn(value===!0)},()=>{})}catch{}let subscribe2=AccessibilityInfo?.addEventListener,subscription=typeof subscribe2=="function"?subscribe2.call(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 rnThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useRnColorScheme,useReducedMotion:useRnReducedMotion,useTextScale:useRnTextScale,useHighContrast:useRnHighContrast,scaleTypeSizes:false,platformMonoFamily:rnPlatformMonoFamily,isFontRegistered:rnIsFontRegistered,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]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState(null),[confirmingRevoke,setConfirmingRevoke]=useState(false),[settled,setSettled]=useState(null),locked=useRef(false),active=useRef(false),generation=useRef(0);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)}function inArtifactWords(events,request,petName){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;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(),events=buildRequestTimeline(request,{petName:petName??null});/* @__PURE__ */
|
|
485
485
|
return jsx(View,{style:styles.container,accessibilityRole:"summary",children:events.map((event,idx)=>/* @__PURE__ */jsx(TimelineRow,{event:event,isLast:idx===events.length-1,styles:styles},event.key))})}function TimelineRow({event:event,isLast:isLast,styles:styles}){let date=event.at?formatRecordsDate(event.at):null,a11yParts=[event.title,event.detail,date,A11Y_STATE[event.state]].filter(Boolean);/* @__PURE__ */
|
|
486
486
|
return jsxs(View,{style:styles.row,accessible:true,accessibilityRole:"text",accessibilityLabel:a11yParts.join(", "),testID:`records-timeline-${event.key}`,children:[
|
|
487
487
|
/* @__PURE__ */jsxs(View,{style:styles.railColumn,children:[
|
|
488
488
|
/* @__PURE__ */jsx(TimelineDot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsx(View,{style:[styles.connector,event.state==="done"&&styles.connectorDone],accessibilityElementsHidden:true,importantForAccessibility:"no"})]}),
|
|
489
489
|
/* @__PURE__ */jsxs(View,{style:styles.body,children:[
|
|
490
490
|
/* @__PURE__ */jsxs(View,{style:styles.titleRow,children:[
|
|
491
|
-
/* @__PURE__ */jsx(Text,{style:[styles.title,event.state==="current"&&styles.titleCurrent,event.state==="failed"&&styles.titleFailed,event.state==="upcoming"&&styles.titleUpcoming],children:event.title}),event.state==="current"?/* @__PURE__ */jsx(View,{style:styles.now,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date?/* @__PURE__ */jsx(Text,{style:styles.date,children:date}):null]}),event.detail?/* @__PURE__ */jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function useStyles8(){let theme=useEverfurTheme();return useMemo(()=>makeStyles10(theme),[theme])}function makeStyles10(theme){let{color:color,type:type}=theme,{size:size}=type;return 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},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 renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
491
|
+
/* @__PURE__ */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__ */jsx(View,{style:styles.now,children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.nowText,children:NOW})}):null,date?/* @__PURE__ */jsx(Text,{style:styles.date,children:date}):null]}),event.detail?/* @__PURE__ */jsx(Text,{style:[styles.detail,event.state==="upcoming"&&styles.detailUpcoming],children:event.detail}):null]})]})}function TimelineDot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotDone],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{tier:"badge",style:[styles.glyph,styles.glyphOnBrand],children:"✓"})}):state==="failed"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotFailed],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(Text,{tier:"badge",style:styles.glyph,children:"!"})}):state==="current"?/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotCurrent],accessibilityElementsHidden:true,importantForAccessibility:"no",children:/* @__PURE__ */jsx(View,{style:styles.dotCurrentCore})}):/* @__PURE__ */jsx(View,{style:[styles.dot,styles.dotUpcoming],accessibilityElementsHidden:true,importantForAccessibility:"no"})}function useStyles8(){let theme=useEverfurTheme();return useMemo(()=>makeStyles10(theme),[theme])}function makeStyles10(theme){let{color:color,type:type}=theme,{size:size}=type;return 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 renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
492
492
|
return jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
493
493
|
return jsx(ConsentUnavailableState,{});case"session_required":/* @__PURE__ */
|
|
494
494
|
return jsx(SessionRequiredState,{});case"withheld":/* @__PURE__ */
|
|
@@ -500,7 +500,7 @@ return jsxs(View,{style:styles.uploadRow,testID:`records-upload-file-${item.stat
|
|
|
500
500
|
/* @__PURE__ */jsxs(View,{style:styles.uploadRowHead,children:[
|
|
501
501
|
/* @__PURE__ */jsx(Text,{style:styles.rowLabel,children:item.name??""}),
|
|
502
502
|
/* @__PURE__ */jsx(Text,{style:styles.rowValue,children:uploadItemStatusLabel(item)})]}),item.status==="uploading"?/* @__PURE__ */jsx(View,{style:styles.progressTrack,accessibilityRole:"progressbar",accessibilityValue:{min:0,max:100,now:pct2},children:/* @__PURE__ */jsx(View,{style:[styles.progressFill,{width:`${pct2}%`}]})}):null,item.status==="failed"&&item.error?/* @__PURE__ */jsx(Text,{style:styles.timelineMeta,children:item.error.displayMessage}):null]},item.key)})}):null]})}function ConsentRequiredState({onGrant:onGrant,consentText:consentText}){let styles=useStyles9(),text3=presentConsentText(consentText);return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(RECORDS_COPY.consentRequired)},[]),/* @__PURE__ */jsxs(View,{style:styles.centered,testID:"records-consent-gate",children:[
|
|
503
|
-
/* @__PURE__ */jsx(Text,{style:styles.
|
|
503
|
+
/* @__PURE__ */jsx(Text,{style:styles.askText,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",children:RECORDS_COPY.consentRequired}),text3!==null?/* @__PURE__ */jsx(Text,{style:styles.disclaimer,testID:"records-consent-gate-body",children:text3}):null,
|
|
504
504
|
/* @__PURE__ */jsx(Pressable,{onPress:onGrant,accessibilityRole:"button",accessibilityLabel:RECORDS_COPY.allow,style:styles.primaryButton,children:/* @__PURE__ */jsx(Text,{style:styles.primaryLabel,children:RECORDS_COPY.allow})})]})}function AlertState({label:label,glyph:glyph}){let styles=useStyles9();return useEffect(()=>{AccessibilityInfo.announceForAccessibility?.(label)},[label]),/* @__PURE__ */jsxs(View,{style:styles.centered,accessible:true,accessibilityRole:"alert",accessibilityLiveRegion:"assertive",accessibilityLabel:label,children:[
|
|
505
505
|
/* @__PURE__ */jsx(View,{style:glyph==="withheld"?styles.withheldGlyph:styles.emptyGlyph}),
|
|
506
506
|
/* @__PURE__ */jsx(Text,{style:styles.errorText,children:label})]})}function ConsentUnavailableState(){/* @__PURE__ */
|
|
@@ -511,7 +511,7 @@ return jsx(AlertState,{label:RECORDS_COPY.recordUnavailable,glyph:"withheld"})}f
|
|
|
511
511
|
return jsxs(View,{style:styles.callCard,accessibilityRole:"summary",children:[
|
|
512
512
|
/* @__PURE__ */jsx(Text,{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
|
|
513
513
|
/* @__PURE__ */jsx(Text,{style:styles.timelineMeta,children:intro}),
|
|
514
|
-
/* @__PURE__ */jsx(Pressable,{onPress:()=>{Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles9(){let theme=useEverfurTheme();return useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(slots
|
|
514
|
+
/* @__PURE__ */jsx(Pressable,{onPress:()=>{Linking?.openURL?.(call.dial)},accessibilityRole:"button",accessibilityLabel:CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,testID:"records-call-clinic",children:/* @__PURE__ */jsx(Text,{style:styles.linkLabel,children:CALL_CLINIC_COPY.call})})]})}function useStyles9(){let theme=useEverfurTheme();return useMemo(()=>makeStyles11(theme),[theme])}function makeStyles11(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,{size:size,lineHeight:lineHeight,letterSpacing:letterSpacing}=type,card=slotBox(recordCardSlot(slots),StyleSheet.hairlineWidth),cardText=slotText(recordCardSlot(slots)),lh=(fontSize,multiplier)=>Math.round(fontSize*multiplier),hairline=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 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}})}function EverfurRecordsRequests(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
515
515
|
return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsx(RequestsBody,{...rest,style:style})})}function RequestsBody({petRef:petRef,petName:petName,controller:controller,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk,style:style}){let styles=useScreenStyles(),local=useLocalStyles5(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),requests=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__ */jsx(RequestSkeleton,{testID:"records-list-loading"}):records.status==="error"&&requests.length===0?body=/* @__PURE__ */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__ */jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-list-empty"}):body=/* @__PURE__ */jsx(ScrollView,{contentContainerStyle:local.list,testID:"records-list-results",children:requests.map(request=>/* @__PURE__ */jsx(RequestRow,{request:request,onOpen:onNavigate?()=>onNavigate({name:"request",requestId:request.id}):void 0,onAsk:ask?()=>ask(request):void 0},request.id))}),/* @__PURE__ */jsxs(View,{style:[styles.root,style],children:[
|
|
516
516
|
/* @__PURE__ */jsx(ScreenHeader,{title:REQUEST_LIST_COPY.title,onBack:onBack,testID:"records-list-header"}),requests.length>0?/* @__PURE__ */jsx(Text,{style:local.subtitle,testID:"records-list-subtitle",children:REQUEST_LIST_COPY.subtitle(petName)}):null,
|
|
517
517
|
/* @__PURE__ */jsx(View,{style:styles.body,children:body}),onNavigate?/* @__PURE__ */jsxs(View,{style:local.footer,children:[
|
|
@@ -528,7 +528,7 @@ return jsxs(View,{style:local.row,testID:`records-request-row-${request.id}`,chi
|
|
|
528
528
|
/* @__PURE__ */jsxs(View,{style:local.cardText,children:[
|
|
529
529
|
/* @__PURE__ */jsx(Text,{style:local.cardTitle,children:view.title}),
|
|
530
530
|
/* @__PURE__ */jsx(Text,{style:local.cardSubtitle,children:view.subtitle})]}),
|
|
531
|
-
/* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles5(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles5(theme),[theme])}function makeLocalStyles5(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 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},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:{...
|
|
531
|
+
/* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles5(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles5(theme),[theme])}function makeLocalStyles5(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 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,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]);/* @__PURE__ */
|
|
532
532
|
return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */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=useLocalStyles6(),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]=useState(null),onPointPress=useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=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,dashboardState=deriveRecordsDashboardState({hasMarkers:hasMarkers,requests:records.requests,petRef:petRef}),view=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}),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__ */jsxs(Fragment,{children:[markers.markers?.summary?/* @__PURE__ */jsx(View,{style:styles.inset,children:/* @__PURE__ */jsx(MarkerSummaryCard,{summary:markers.markers.summary,onAsk:askSummary,testID:"dashboard-marker-summary"})}):null,
|
|
533
533
|
/* @__PURE__ */jsx(Text,{style:styles.lead,children:DASHBOARD_COPY.lead(petName)}),
|
|
534
534
|
/* @__PURE__ */jsx(MarkerTrendCarousel,{markers:markerList,onPointPress:onPointPress,onAsk:askMarker})]}),actions=withRecord=>onNavigate?/* @__PURE__ */jsxs(View,{style:[styles.inset,local.actions],children:[withRecord?/* @__PURE__ */jsx(ActionRow,{glyph:"record",label:DASHBOARD_COPY.viewFullRecord,onPress:()=>onNavigate({name:"record"}),testID:"dashboard-full-record-action"}):null,
|
|
@@ -569,7 +569,7 @@ return jsxs(View,{style:local.inProgressCard,testID:"dashboard-in-progress-card"
|
|
|
569
569
|
return jsxs(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:[
|
|
570
570
|
/* @__PURE__ */jsxs(View,{style:local.wayText,children:[
|
|
571
571
|
/* @__PURE__ */jsx(Text,{style:local.wayTitle,children:title}),sub?/* @__PURE__ */jsx(Text,{style:local.waySub,children:sub}):null]}),
|
|
572
|
-
/* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md;return 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},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},inProgressCard:{borderRadius:radius.lg,backgroundColor:color.surface,borderWidth:1,borderColor:color.borderRingCream,padding:space.lg,gap:space.lg},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},wayDashed:{borderStyle:"dashed",borderColor:color.brandBorderStrong},wayText:{flex:1,gap:space.xs/2},wayTitle:{...
|
|
572
|
+
/* @__PURE__ */jsx(Chevron,{})]})}function useLocalStyles6(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles6(theme),[theme])}function makeLocalStyles6(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=StyleSheet.hairlineWidth,touch=space.xxl+space.md,card=theme.slots.card,cardText=slotText(card);return 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 ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}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__ */
|
|
573
573
|
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__ */
|
|
574
574
|
return jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsx(ScreenHeader,{title:DEPTH_COPY.timeline,onBack:guardHost(onBack),testID:"timeline-header"}),loading:/* @__PURE__ */jsx(TimelineSkeleton,{testID:"timeline-loading"}),empty:/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",testID:"timeline-empty"}),render:timeline=>/* @__PURE__ */jsx(TimelineBody,{timeline:timeline})})}function EverfurDocumentContributions({petRef:petRef,docId:docId,style:style,onBack:onBack}){let read=useCallback((client,pet)=>client.getDocumentContributions(pet,docId),[docId]),state=useRecordsDepthRead(petRef,read,contributionsEmpty,docId),title=state.value?.document?.title?.trim()||DEPTH_COPY.uploadedDocument;/* @__PURE__ */
|
|
575
575
|
return jsx(DepthSurface,{state:state,style:style,onBack:onBack,header:/* @__PURE__ */jsx(ScreenHeader,{title:title,onBack:guardHost(onBack),testID:"contributions-header"}),empty:/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",testID:"contributions-empty"}),render:view=>/* @__PURE__ */jsx(ContributionsBody,{view:view})})}function DepthSurface({state:state,style:style,header:header,loading:loading,empty:empty,render:render,onBack:onBack}){let styles=useStyles10();/* @__PURE__ */
|
|
@@ -587,9 +587,9 @@ return jsxs(ScrollView,{style:styles.list,contentContainerStyle:styles.timelineC
|
|
|
587
587
|
return jsxs(ScrollView,{style:styles.list,contentContainerStyle:styles.listContent,accessibilityLabel:RECORDS_COPY.records,children:[view.document?.receivedAt?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(view.document.receivedAt)}):null,
|
|
588
588
|
/* @__PURE__ */jsx(View,{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxs(View,{style:styles.row,accessible:true,accessibilityRole:"text",children:[
|
|
589
589
|
/* @__PURE__ */jsx(Text,{style:styles.rowTitle,children:entity.label}),
|
|
590
|
-
/* @__PURE__ */jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return 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=StyleSheet.hairlineWidth,minSurface=space.xxl*3+space.xl,touchTarget=space.xxl+space.md,errorColor=theme.brightness==="dark"?color.errorRed:color.danger,cardText=slotText(slots.recordCard),text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text3(fontSize,multiplier,fg,weight),...cardText});return 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:{...text3(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:{...text3(size.heading,lineHeight.snug,color.text.primary,"bold")},card:{gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,borderWidth:hairline,borderColor:color.brandBorder,...slotBox(slots.recordCard,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")},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:{...text3(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:{...text3(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,...text3(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:{...text3(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]=useState(null),[loading,setLoading]=useState(true),[error,setError]=useState(null),[lit,setLit]=useState(null),available=lit===true,[urls,setUrls]=useState({}),[creating,setCreating]=useState(false),[revokingId,setRevokingId]=useState(null),[preparingPdf,setPreparingPdf]=useState(false),[consentRequired,setConsentRequired]=useState(false),[sending,setSending]=useState(false),[featuresState,setFeaturesState]=useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=useRef(0),live=useRef(true),load=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]);useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),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=useRef(consentEpoch);useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=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=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=useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=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=useCallback(()=>{setConsentRequired(false),load()},[load]),rows=useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return 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=useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=useState({scope:scope,lit:null});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 useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=useState(false),[error,setError]=useState(null),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=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 useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}async function shareLinkViaOs(url){await Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await Share.share(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__ */
|
|
590
|
+
/* @__PURE__ */jsx(Text,{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsx(Text,{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useStyles10(){let theme=useEverfurTheme();return 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=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)),text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:lh(fontSize,multiplier),color:fg}),inCard=(fontSize,multiplier,fg,weight="regular")=>({...text3(fontSize,multiplier,fg,weight),...cardText});return 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:{...text3(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:{...text3(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:{...text3(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:{...text3(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,...text3(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:{...text3(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]=useState(null),[loading,setLoading]=useState(true),[error,setError]=useState(null),[lit,setLit]=useState(null),available=lit===true,[urls,setUrls]=useState({}),[creating,setCreating]=useState(false),[revokingId,setRevokingId]=useState(null),[preparingPdf,setPreparingPdf]=useState(false),[consentRequired,setConsentRequired]=useState(false),[sending,setSending]=useState(false),[featuresState,setFeaturesState]=useState(null),recordsFeatures=featuresState!==null&&featuresState.client===client?featuresState.value:RECORDS_FEATURES_PDF_ONLY,shareAudiences=recordsFeatures.shareAudiences,consentEpoch=useRecordsConsentEpoch(petRef),generation=useRef(0),live=useRef(true),load=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]);useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]),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=useRef(consentEpoch);useEffect(()=>{seenEpoch.current!==consentEpoch&&(seenEpoch.current=consentEpoch,setUrls({}),setConsentRequired(true),load())},[consentEpoch,load]);let createLink=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=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=useCallback(async shareId=>{setRevokingId(shareId);let result=await client.revokeShare(petRef,shareId);return live.current&&(setRevokingId(null),load()),result},[client,petRef,load]),pdfLink=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=useCallback(()=>{setConsentRequired(false),load()},[load]),rows=useMemo(()=>buildShareRows(shares??[],urls,now()),[shares,urls,now]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated",features=recordsFeatures.features;return 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=useMemo(()=>({}),[client,petRef,userRef]),[state,setState]=useState({scope:scope,lit:null});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 useMemo(()=>({lit:lit}),[lit])}function useRecordPdfLink(petRef){let client=useEverfurRecordsDepthClient(),available=useRecordsDepthProbe(petRef).lit===true,[preparing,setPreparing]=useState(false),[error,setError]=useState(null),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let pdfLink=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 useMemo(()=>({preparing:preparing,available:available,error:error,pdfLink:pdfLink}),[preparing,available,error,pdfLink])}async function shareLinkViaOs(url){await Share.share({message:SHARE_COPY.shareMessage(url),url:url})}async function shareFileLinkViaOs(url){await Share.share(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__ */
|
|
591
591
|
return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */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=useLocalStyles7(),theme=useEverfurTheme(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth2,depthEmpty2),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=useMemo(()=>makeGrantHandler(records,consentVersion),[records,consentVersion]),depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[shareFailed,setShareFailed]=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__ */jsx(View,{style:local.centered,accessible:true,accessibilityRole:"progressbar",accessibilityLabel:DASHBOARD_COPY.loading,testID:"record-document-loading",children:/* @__PURE__ */jsx(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__ */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__ */jsx(View,{style:local.centered,testID:"record-document-empty",children:/* @__PURE__ */jsx(Text,{style:local.emptyText,children:COPY.empty})}):(documentShown=true,body=/* @__PURE__ */jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxs(View,{style:[styles.root,local.root,style],children:[
|
|
592
|
-
/* @__PURE__ */jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsx(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__ */jsx(ActivityIndicator,{size:"small",color:theme.color.brandInk}):/* @__PURE__ */jsx(DownloadGlyph,{})}):void 0}),pdf.error?/* @__PURE__ */jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",children:pdf.error.displayMessage}):shareFailed?/* @__PURE__ */jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:SHARE_COPY.toasts.pdfShareSheet}):null,
|
|
592
|
+
/* @__PURE__ */jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsx(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__ */jsx(ActivityIndicator,{size:"small",color:theme.slots.header?.textColor??theme.color.brandInk}):/* @__PURE__ */jsx(DownloadGlyph,{})}):void 0}),pdf.error?/* @__PURE__ */jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",children:pdf.error.displayMessage}):shareFailed?/* @__PURE__ */jsx(Text,{style:[styles.errorText,local.inset],accessibilityRole:"alert",testID:"record-document-share-failed",children:SHARE_COPY.toasts.pdfShareSheet}):null,
|
|
593
593
|
/* @__PURE__ */jsx(View,{style:styles.body,children:body}),
|
|
594
594
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let local=useLocalStyles7(),groups=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__ */jsxs(View,{style:local.section,testID:testID,children:[
|
|
595
595
|
/* @__PURE__ */jsxs(View,{style:local.sectionHeader,children:[
|
|
@@ -658,7 +658,7 @@ return jsx(Pressable,{onPress:()=>setAudience(option),accessibilityRole:"radio",
|
|
|
658
658
|
/* @__PURE__ */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}`}),
|
|
659
659
|
/* @__PURE__ */jsx(Pill,{label:SHARE_COPY.keep,kind:"outline",disabled:shares.revokingId===row.shareId,onPress:()=>setPendingRevokeId(null),testID:`share-revoke-cancel-${row.shareId}`})]})]}):/* @__PURE__ */jsxs(View,{style:styles.rowActions,children:[onCopy?/* @__PURE__ */jsx(Pill,{label:SHARE_COPY.copyLink,kind:"outline",disabled:row.shareUrl===null,accessibilityHint:row.a11yLabel,onPress:()=>onCopyRow(row),testID:`share-copy-${row.shareId}`}):null,
|
|
660
660
|
/* @__PURE__ */jsx(Pill,{label:SHARE_COPY.turnOff,kind:"danger",accessibilityLabel:SHARE_COPY.turnOffA11y(row.actionContext),onPress:()=>setPendingRevokeId(row.shareId),testID:`share-ask-revoke-${row.shareId}`})]})]},row.shareId))})]}):null]}),
|
|
661
|
-
/* @__PURE__ */jsx(View,{style:screen.inset})]})]})})}function useStyles11(){let theme=useEverfurTheme();return useMemo(()=>makeStyles13(theme),[theme])}function makeStyles13(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,hairline=StyleSheet.hairlineWidth,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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},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:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},helper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),terms:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:text3(type.size.verdict,type.lineHeight.tight,color.text.primary),scroll:{flexGrow:0},body:{gap:space.lg,paddingBottom:space.sm},actions:{gap:space.sm},form:{gap:space.sm,paddingBottom:space.sm},fieldLabel:{...text3(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},choiceOn:{borderWidth:1.5,borderColor:color.brandInk,backgroundColor:color.brandSoft},choiceTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium")},choiceTitleOn:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},included:{gap:space.xs},includedRow:{flexDirection:"row",gap:space.sm},includedLine:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),includedText:{flex:1},field:{...text3(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},placeholder:{color:color.text.placeholder},notice:{...text3(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:{...text3(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},stateTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},stateBody:text3(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},statusLine:{flexDirection:"row",alignItems:"center",gap:space.sm},statusDot:{width:space.sm,height:space.sm,borderRadius:space.xs},status:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.primary,"bold")},expiry:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted)},created:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),url:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},confirm:{gap:space.sm},confirmText:{...text3(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__ */
|
|
661
|
+
/* @__PURE__ */jsx(View,{style:screen.inset})]})]})})}function useStyles11(){let theme=useEverfurTheme();return useMemo(()=>makeStyles13(theme),[theme])}function makeStyles13(theme){let{color:color,space:space,radius:radius,type:type}=theme,touch=space.xxl+space.md,hairline=StyleSheet.hairlineWidth,text3=(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 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:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...dialogText},helper:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...dialogText},terms:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},closeButton:{width:touch,height:touch,alignItems:"center",justifyContent:"center"},closeGlyph:{...text3(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:{...text3(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:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...slotText(tab)},choiceTitleOn:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},included:{gap:space.xs},includedRow:{flexDirection:"row",gap:space.sm},includedLine:text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),includedText:{flex:1},field:{...text3(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:{...text3(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:{...text3(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:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")},stateBody:text3(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:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.primary,"bold")},expiry:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted)},created:text3(type.size.tiny,type.lineHeight.normal,color.text.muted),url:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary,"mono")},rowActions:{flexDirection:"row",flexWrap:"wrap",gap:space.sm},confirm:{gap:space.sm},confirmText:{...text3(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__ */
|
|
662
662
|
return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */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=useLocalStyles8(),records=useEverfurRecords(controller?{petRef:petRef,controller:controller}:{petRef:petRef}),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),factEdit=useRecordFactEdit(petRef),shareProbe=useRecordsDepthProbe(petRef),[sharing,setSharing]=useState(false);useConsentTextWarning2(consentVersion,consentText);let canGrant=useMemo(()=>canGrantConsent(consentVersion,records.consent),[consentVersion,records.consent]),onGrant=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,body;if(records.status==="loading"||depth.status==="loading"&&record!==null&&!record.isEmpty)body=/* @__PURE__ */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__ */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__ */jsxs(ScrollView,{contentContainerStyle:styles.content,testID:"everfur-record-empty",children:[
|
|
663
663
|
/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
664
664
|
/* @__PURE__ */jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsx(ScrollView,{contentContainerStyle:local.content,testID:"everfur-record",children:/* @__PURE__ */jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
@@ -688,7 +688,7 @@ return jsxs(View,{style:local.card,testID:"records-upload-card",children:[
|
|
|
688
688
|
/* @__PURE__ */jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.takePhotoMeta})]}):null,canChoosePhotos?/* @__PURE__ */jsx(View,{style:local.action,children:/* @__PURE__ */jsx(Pill,{label:UPLOAD_PHOTO_COPY.choosePhotos,kind:"outline",disabled:!canUpload,onPress:pickPhotos,testID:"records-upload-choose-photos"})}):null,
|
|
689
689
|
/* @__PURE__ */jsxs(View,{style:local.action,children:[
|
|
690
690
|
/* @__PURE__ */jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick,testID:"records-upload-choose"}),
|
|
691
|
-
/* @__PURE__ */jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick,testID:"records-upload-choose"})]})}function useLocalStyles9(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles9(theme),[theme])}var UPLOAD_GLYPH=24;function makeLocalStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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:{...text3(type.size.heading+space.xs/2,type.lineHeight.snug,color.brandInk,"bold"),textAlign:"center"},subtitle:{...text3(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},cardTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")},cardSubtitle:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),uploadingRow:{flexDirection:"row",alignItems:"center",gap:space.sm},progressText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary)},settled:{gap:space.sm},success:text3(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:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted)})}function EverfurRecordsRequest(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
691
|
+
/* @__PURE__ */jsx(Text,{style:local.actionMeta,children:UPLOAD_PHOTO_COPY.chooseFileMeta})]})]}):/* @__PURE__ */jsx(Pill,{label:UPLOAD_COPY.chooseFiles,disabled:!canUpload,onPress:pick,testID:"records-upload-choose"})]})}function useLocalStyles9(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles9(theme),[theme])}var UPLOAD_GLYPH=24;function makeLocalStyles9(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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:{...text3(type.size.heading+space.xs/2,type.lineHeight.snug,color.brandInk,"bold"),...headingFace(theme,"bold"),textAlign:"center"},subtitle:{...text3(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:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold"),...slotText(theme.slots.card)},cardSubtitle:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...slotText(theme.slots.card)},uploadingRow:{flexDirection:"row",alignItems:"center",gap:space.sm},progressText:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary)},settled:{gap:space.sm},success:text3(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:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted)})}function EverfurRecordsRequest(props){let{style:style,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack"]);/* @__PURE__ */
|
|
692
692
|
return jsx(CapabilityGate,{capability:"records",style:style,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */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__ */jsx(RequestSkeleton,{testID:"records-request-loading"}):records.status==="error"&&records.error?body=/* @__PURE__ */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__ */jsx(RecordsEmptyState,{variant:"no_requests",testID:"records-request-missing"}):userRef===null?body=/* @__PURE__ */jsx(RecordsEmptyState,{variant:"error",testID:"records-request-error"}):body=/* @__PURE__ */jsx(RequestDetail,{petName:petName,request:request,records:records,canUpload:canUpload,onPickDocument:onPickDocument,onPickPhotos:onPickPhotos,onNavigate:onNavigate,nowMs:nowMs,refreshControl:refreshControl},JSON.stringify([userRef,scopeEpoch,request.id])),/* @__PURE__ */jsxs(View,{style:[styles.root,style],children:[
|
|
693
693
|
/* @__PURE__ */jsx(ScreenHeader,{title:title,onBack:onBack,testID:"records-request-header"}),
|
|
694
694
|
/* @__PURE__ */jsx(KeyboardAvoidingView,{behavior:"padding",style:styles.body,children:body}),
|
|
@@ -716,7 +716,7 @@ return jsxs(ScrollView,{contentContainerStyle:local.content,keyboardShouldPersis
|
|
|
716
716
|
/* @__PURE__ */jsx(Text,{style:local.confirmTitle,accessibilityRole:"header",children:RECORDS_RECOVERY_COPY.cancelQuestion}),
|
|
717
717
|
/* @__PURE__ */jsx(Text,{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
718
718
|
/* @__PURE__ */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"}),
|
|
719
|
-
/* @__PURE__ */jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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},cardTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:-.4},detailRow:{flexDirection:"row",alignItems:"baseline",justifyContent:"space-between",gap:space.lg},detailValue:{flexShrink:1,textAlign:"right",...text3(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:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"bold")},failureTitleCritical:{color:color.danger},failureTitleCaution:{color:color.warningStrong},emailBlock:{gap:space.sm},callBlock:{gap:space.sm},block:{gap:space.sm},confirmTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")}})}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}=guardHostProps(props,["onExit"]),[nav,dispatch]=useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=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":/* @__PURE__ */
|
|
719
|
+
/* @__PURE__ */jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onPress:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onPress:form.askRevoke,testID:"records-revoke"}):null]})}function useLocalStyles10(){let theme=useEverfurTheme();return useMemo(()=>makeLocalStyles10(theme),[theme])}function makeLocalStyles10(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(fontSize,multiplier,fg,weight="regular")=>({...face(theme,weight),fontSize:fontSize,lineHeight:Math.round(fontSize*multiplier),color:fg});return 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:{...text3(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",...text3(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:{...text3(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},confirmTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFace(theme,"bold")}})}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}=guardHostProps(props,["onExit"]),[nav,dispatch]=useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length;useEffect(()=>{let onBackPress=()=>depth<=1?false:(dispatch({type:"pop"}),true),subscription=BackHandler.addEventListener("hardwareBackPress",onBackPress);return()=>{subscription.remove()}},[depth]);let onNavigate=useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=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":/* @__PURE__ */
|
|
720
720
|
return jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,style:style});case"request":/* @__PURE__ */
|
|
721
721
|
return jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...records,...uploads,...pending,style:style});case"timeline":/* @__PURE__ */
|
|
722
722
|
return jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,style:style});case"record":/* @__PURE__ */
|
|
@@ -728,15 +728,15 @@ return jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??"",ownerNam
|
|
|
728
728
|
return jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},style:style});case"upload":/* @__PURE__ */
|
|
729
729
|
return jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...uploads,...pending,style:style});case"requests":/* @__PURE__ */
|
|
730
730
|
return 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__ */
|
|
731
|
-
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=useState(null),padCapture=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},text3={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(label,action,disabled=false)=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},disabled:disabled,onPress:action,style:[field,{justifyContent:"center",opacity:disabled?.5:1}],children:/* @__PURE__ */jsx(Text,{style:text3,children:label})});/* @__PURE__ */
|
|
731
|
+
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(ClinicRequestBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function ClinicRequestBody(props){let runtimeController=useEverfurRecordsClinic(),[png,setPng]=useState(null),padCapture=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)},text3={color:theme.color.text.primary,fontSize:theme.type.size.body},button=(label,action,disabled=false)=>/* @__PURE__ */jsx(Pressable,{accessibilityRole:"button",accessibilityLabel:label,accessibilityState:{disabled:disabled},disabled:disabled,onPress:action,style:[field,{justifyContent:"center",opacity:disabled?.5:1}],children:/* @__PURE__ */jsx(Text,{style:text3,children:label})});/* @__PURE__ */
|
|
732
732
|
return jsxs(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:[
|
|
733
|
-
/* @__PURE__ */jsx(Text,{accessibilityRole:"header",style:[text3,{...
|
|
733
|
+
/* @__PURE__ */jsx(Text,{accessibilityRole:"header",style:[text3,{...headingFace(theme,"bold"),fontSize:theme.type.size.heading}],children:CLINIC_REQUEST_COPY.title}),
|
|
734
734
|
/* @__PURE__ */jsx(Text,{style:text3,children:props.petName}),form.created?/* @__PURE__ */jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxs(Fragment,{children:[
|
|
735
735
|
/* @__PURE__ */jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.ownerName}),
|
|
736
|
-
/* @__PURE__ */jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:
|
|
736
|
+
/* @__PURE__ */jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.ownerName,style:input,value:form.ownerName,maxLength:200,editable:!form.busy,autoComplete:"name",onChangeText:form.setOwnerName}),
|
|
737
737
|
/* @__PURE__ */jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.clinic}),
|
|
738
|
-
/* @__PURE__ */jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.clinic,style:
|
|
738
|
+
/* @__PURE__ */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__ */jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsx(Text,{accessibilityRole:"header",style:text3,testID:"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsx(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__ */jsx(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__ */jsxs(Fragment,{children:[
|
|
739
739
|
/* @__PURE__ */jsx(Text,{style:text3,children:CLINIC_REQUEST_COPY.email}),
|
|
740
|
-
/* @__PURE__ */jsx(TextInput,{accessibilityLabel:CLINIC_REQUEST_COPY.email,style:
|
|
740
|
+
/* @__PURE__ */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})]}),
|
|
741
741
|
/* @__PURE__ */jsx(Text,{accessibilityRole:"header",style:text3,children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsx(Text,{style:text3,children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsx(Text,{accessibilityLiveRegion:"polite",style:text3,children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsx(SignaturePad,{onChange:setPng,disabled:form.busy}),!signed&&form.ready&&/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",style:text3,children:CLINIC_REQUEST_COPY.missingSignature}),form.error&&/* @__PURE__ */jsx(Text,{accessibilityRole:"alert",accessibilityLiveRegion:"assertive",style:text3,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),
|
|
742
742
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})}export{EverfurClinicPicker,EverfurClinicRequest,EverfurClinicRequestBatch,EverfurRecordDetail,EverfurRecordDocument,EverfurRecords,EverfurRecordsConsent,EverfurRecordsDashboard,EverfurRecordsFlow,EverfurRecordsRequest,EverfurRecordsRequests,EverfurRecordsUpload,RECORDS_CLINIC_BATCH_MAX,RECORDS_TERMINAL,REQUEST_TIMELINE_TITLES,SignaturePad,acceptsPhotos,applyFactOverlay,buildRequestTimeline,currentRecordsScreen,deriveRecordsDashboardState,initialRecordsNav,isFactEditable,isTerminalStatus,pickPetRecordsRequest,popRecordsNav,pushRecordsNav,recordsDenialReasonOf,recordsNavReducer,registerRnSignature,replaceRecordsNav,resetRecordsNav,selectClinicCall,selectDashboardView,selectPrimaryLabel,selectRequestList,selectRequestTitle,transitionRecordsNav,useEverfurRecords,useEverfurRecordsClinic,useEverfurRecordsClinicBatch,useRecordFactEdit,useRecordPdfLink,useRecordShares,useRecordsMarkers};
|