@everfur/sdk 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +1 -1
- package/dist/{Chat-s2vcPbw3.d.cts → Chat-Cb3Y8VwS.d.cts} +3 -3
- package/dist/{Chat-Cv9EYMYA.d.ts → Chat-ClhB_8sp.d.ts} +3 -3
- package/dist/{DepthViews-CVxUHOJ-.d.ts → DepthViews-BSkuUGBB.d.ts} +1 -1
- package/dist/{DepthViews-DNRY0Ugm.d.ts → DepthViews-CSCS-tZg.d.ts} +1 -1
- package/dist/{DepthViews-Cz7mSW7p.d.cts → DepthViews-CW1z8pnl.d.cts} +1 -1
- package/dist/{DepthViews-DvNixbxg.d.cts → DepthViews-DDiPxyzg.d.cts} +1 -1
- package/dist/animations/index.cjs +1 -1
- package/dist/animations/index.d.cts +3 -3
- package/dist/animations/index.d.ts +3 -3
- package/dist/animations/index.js +1 -1
- package/dist/{attachments-y3EcOX_w.d.cts → attachments-BD70jZZL.d.cts} +2 -2
- package/dist/{attachments-y_aO4hlk.d.ts → attachments-CC7aHpwZ.d.ts} +5 -5
- package/dist/{attachments-BaslXMdS.d.ts → attachments-DAUy3vPR.d.ts} +2 -2
- package/dist/{attachments-DbFwz4iq.d.cts → attachments-DaOaIBNf.d.cts} +5 -5
- package/dist/{bookingCopy-B3UMITD-.d.ts → bookingCopy-CUW9Gdzc.d.ts} +2 -2
- package/dist/{bookingCopy-4i1R7klo.d.cts → bookingCopy-oEjqkiNA.d.cts} +2 -2
- package/dist/{branding-BYEqU855.d.ts → branding-aGleD_ki.d.ts} +99 -6
- package/dist/{branding-BwEu68C8.d.cts → branding-ctD0B2Th.d.cts} +99 -6
- package/dist/{casesRepository-B6Z0XBIb.d.cts → casesRepository-Bzs7aw4t.d.cts} +1 -1
- package/dist/{casesRepository-SI0zp5YH.d.ts → casesRepository-CywqL6mj.d.ts} +1 -1
- package/dist/chat/index.cjs +20 -18
- package/dist/chat/index.d.cts +9 -9
- package/dist/chat/index.d.ts +9 -9
- package/dist/chat/index.js +20 -18
- package/dist/client/index.cjs +7 -7
- package/dist/client/index.d.cts +10 -10
- package/dist/client/index.d.ts +10 -10
- package/dist/client/index.js +7 -7
- package/dist/{config-Cvo47voG.d.ts → config-BysLVhku.d.ts} +1 -1
- package/dist/{config-v5k6NsK_.d.cts → config-EZzEyS-c.d.cts} +1 -1
- package/dist/consent/index.cjs +1 -1
- package/dist/consent/index.d.cts +5 -5
- package/dist/consent/index.d.ts +5 -5
- package/dist/consent/index.js +1 -1
- package/dist/{context-BZOtJbBO.d.cts → context-DUwYArkM.d.cts} +7 -7
- package/dist/{context-cZ7NZ0sG.d.ts → context-DpfgbnOU.d.ts} +7 -7
- package/dist/{copy-ChJupm1p.d.cts → copy-DK4r9oGz.d.cts} +2 -2
- package/dist/{copy-CZBUHbyS.d.ts → copy-LxZGnFXJ.d.ts} +2 -2
- package/dist/core/index.cjs +2 -2
- package/dist/core/index.d.cts +15 -15
- package/dist/core/index.d.ts +15 -15
- package/dist/core/index.js +2 -2
- package/dist/{depth-CRyU7-pf.d.cts → depth-DAd77kRe.d.cts} +2 -2
- package/dist/{depth-vNpwOkZ8.d.ts → depth-Mk7quUNa.d.ts} +2 -2
- package/dist/{entitlementRepository-CUdxbQrP.d.ts → entitlementRepository-CrD0O7VR.d.ts} +3 -3
- package/dist/{entitlementRepository-Bv8nSYRd.d.cts → entitlementRepository-Dra_4FU_.d.cts} +3 -3
- package/dist/{identity-BHaMJ3KK.d.cts → identity-75whJXyP.d.cts} +1 -1
- package/dist/{identity-B8GkH53J.d.ts → identity-BiyMDMrR.d.ts} +1 -1
- package/dist/index.cjs +24 -22
- package/dist/index.d.cts +16 -16
- package/dist/index.d.ts +16 -16
- package/dist/index.js +24 -22
- package/dist/notifications/index.d.cts +2 -2
- package/dist/notifications/index.d.ts +2 -2
- package/dist/{pets-BI7Ji8hi.d.cts → pets-DoXxTw4x.d.cts} +1 -1
- package/dist/{pets-Dnn-DK1T.d.ts → pets-W2BuLYko.d.ts} +1 -1
- package/dist/{petsRepository-B2lO1sKS.d.ts → petsRepository-ByMzq1Z9.d.ts} +1 -1
- package/dist/{petsRepository-BP9nhM1R.d.cts → petsRepository-yyoo0k2I.d.cts} +1 -1
- package/dist/photo/index.cjs +1 -1
- package/dist/photo/index.js +1 -1
- package/dist/{ports-C40S2V14.d.cts → ports-BeVJYP0_.d.cts} +4 -4
- package/dist/{ports-BUXF0Rp3.d.ts → ports-zYl8S_lI.d.ts} +4 -4
- package/dist/records/depth/index.cjs +6 -6
- package/dist/records/depth/index.d.cts +7 -7
- package/dist/records/depth/index.d.ts +7 -7
- package/dist/records/depth/index.js +6 -6
- package/dist/records/index.cjs +30 -30
- package/dist/records/index.d.cts +9 -9
- package/dist/records/index.d.ts +9 -9
- package/dist/records/index.js +30 -30
- package/dist/{requestFunnel-BrOijMcw.d.ts → requestFunnel-BPeBZdKp.d.ts} +2 -2
- package/dist/{requestFunnel-BxNVGyGm.d.cts → requestFunnel-DHeSzCT6.d.cts} +2 -2
- package/dist/{runtimeTypes-CvI1ZH8j.d.ts → runtimeTypes-Cc207nbn.d.ts} +5 -5
- package/dist/{runtimeTypes-DOO3f-W-.d.cts → runtimeTypes-DgMizQKz.d.cts} +5 -5
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.d.cts +2 -2
- package/dist/server/events/index.d.ts +2 -2
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +3 -3
- package/dist/server/index.d.ts +3 -3
- package/dist/server/index.js +1 -1
- package/dist/televet/booking/index.cjs +15 -13
- package/dist/televet/booking/index.d.cts +6 -6
- package/dist/televet/booking/index.d.ts +6 -6
- package/dist/televet/booking/index.js +15 -13
- package/dist/televet/call/index.cjs +1 -1
- package/dist/televet/call/index.js +1 -1
- package/dist/televet/index.cjs +1 -1
- package/dist/televet/index.js +1 -1
- package/dist/testing/index.d.cts +1 -1
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/rn/index.cjs +1 -1
- package/dist/testing/rn/index.d.cts +9 -9
- package/dist/testing/rn/index.d.ts +9 -9
- package/dist/testing/rn/index.js +1 -1
- package/dist/testing/web/index.d.cts +9 -9
- package/dist/testing/web/index.d.ts +9 -9
- package/dist/{timelineRows-CEx2TzYB.d.ts → timelineRows-D22vGN9t.d.ts} +1 -1
- package/dist/{timelineRows-Dffceql_.d.cts → timelineRows-DUQIWSjc.d.cts} +1 -1
- package/dist/{tokens-Tzo1KBND.d.cts → tokens-RAKZj7M8.d.cts} +47 -4
- package/dist/{tokens-Tzo1KBND.d.ts → tokens-RAKZj7M8.d.ts} +47 -4
- package/dist/{typeStyle-C3IG9Sft.d.ts → typeStyle-DVj8iCC1.d.ts} +11 -3
- package/dist/{typeStyle-CZ3Tj60N.d.cts → typeStyle-Nt7w0rhE.d.cts} +11 -3
- package/dist/{useRecordsDepth-DuPUJFDQ.d.ts → useRecordsDepth-C0Qfoghi.d.ts} +1 -1
- package/dist/{useRecordsDepth-D6a6-_u_.d.cts → useRecordsDepth-Mbysp548.d.cts} +1 -1
- package/dist/video/index.cjs +1 -1
- package/dist/video/index.js +1 -1
- package/dist/{view-UFwCG1Pn.d.cts → view-CskIgOFV.d.cts} +2 -2
- package/dist/{view-BSmN5RWf.d.ts → view-DqKXtxEZ.d.ts} +2 -2
- package/dist/web/consent/index.cjs +1 -1
- package/dist/web/consent/index.d.cts +5 -5
- package/dist/web/consent/index.d.ts +5 -5
- package/dist/web/consent/index.js +1 -1
- package/dist/web/index.cjs +29 -28
- package/dist/web/index.d.cts +26 -20
- package/dist/web/index.d.ts +26 -20
- package/dist/web/index.js +29 -28
- package/dist/web/notifications/index.d.cts +3 -3
- package/dist/web/notifications/index.d.ts +3 -3
- package/dist/web/records/depth/index.cjs +9 -8
- package/dist/web/records/depth/index.d.cts +7 -7
- package/dist/web/records/depth/index.d.ts +7 -7
- package/dist/web/records/depth/index.js +9 -8
- package/dist/web/records/index.cjs +51 -49
- package/dist/web/records/index.d.cts +9 -9
- package/dist/web/records/index.d.ts +9 -9
- package/dist/web/records/index.js +52 -50
- package/dist/web/televet/booking/index.cjs +21 -19
- package/dist/web/televet/booking/index.d.cts +11 -11
- package/dist/web/televet/booking/index.d.ts +11 -11
- package/dist/web/televet/booking/index.js +21 -19
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/televet/index.cjs +1 -1
- package/dist/web/televet/index.js +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{createContext,useRef,useMemo,useState,useCallback,useEffect,useReducer,useId,useContext,useSyncExternalStore,createElement,Component}from"react";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
2
|
+
import{createContext,useRef,useMemo,useState,useCallback,useEffect,useReducer,useId,useContext,useSyncExternalStore,createElement,Component,useLayoutEffect}from"react";import{z}from"zod";import{jsx,jsxs,Fragment}from"react/jsx-runtime";var CONTRACT_RETRYABILITY=/* @__PURE__ */Object.freeze([
|
|
3
3
|
/* @__PURE__ */Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),
|
|
4
4
|
/* @__PURE__ */Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),
|
|
5
5
|
/* @__PURE__ */Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),
|
|
@@ -104,16 +104,17 @@ return Object.freeze(tagged)}var PET_NOT_REGISTERED="pet_not_registered";functio
|
|
|
104
104
|
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__ */
|
|
105
105
|
return Object.freeze({stack:/* @__PURE__ */Object.freeze([...state.stack,screen])})}function replaceRecordsNav(state,screen){/* @__PURE__ */
|
|
106
106
|
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}}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 heldItemsLabel(count){return`${count} ${RECORDS_COPY.beingReviewed}`}function selectRequestList(requests){let sorted=[...requests].sort((a,b)=>a.updatedAt!==b.updatedAt?a.updatedAt>b.updatedAt?-1:1:a.createdAt!==b.createdAt?a.createdAt>b.createdAt?-1:1:0);/* @__PURE__ */
|
|
107
|
-
return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=request.actionNeededLabel?.trim()??"";return action.length>0?action:request.statusLabel}function selectClinicCall(request){if(request.showClinicPhone!==true)return null;let phone=request.clinicPhone?.trim()??"";return phone.length===0?null:{phone:phone,dial:`tel:${phone.replace(/[^+\d]/g,"")}`,clinicName:request.clinicName?.trim()||null}}function selectRequestStatusTone(request){switch(request.wireStatus??request.status){case"published":return"positive";case"failed":case"clinic_declined":return"critical";case"revoked":return"neutral";case"clinic_responded_no_records":case"awaiting_upload":case"records_received":case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return"warning";default:return"info"}}var 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 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)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});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
|
+
return Object.freeze(sorted)}function selectPrimaryLabel(request){let action=request.actionNeededLabel?.trim()??"";return action.length>0?action:request.statusLabel}function selectClinicCall(request){if(request.showClinicPhone!==true)return null;let phone=request.clinicPhone?.trim()??"";return phone.length===0?null:{phone:phone,dial:`tel:${phone.replace(/[^+\d]/g,"")}`,clinicName:request.clinicName?.trim()||null}}function selectRequestStatusTone(request){switch(request.wireStatus??request.status){case"published":return"positive";case"failed":case"clinic_declined":return"critical";case"revoked":return"neutral";case"clinic_responded_no_records":case"awaiting_upload":case"records_received":case"parsing":case"parsing_failed":case"in_review":case"review_email_failed":return"warning";default:return"info"}}var 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 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)}var FACE_WEIGHT=/* @__PURE__ */Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});var SYSTEM_UI_STACK='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',RN_SYSTEM_FAMILY="System";function cssFontFamily(family){let named=family.trim();return named.length===0||named===RN_SYSTEM_FAMILY?SYSTEM_UI_STACK:`${quote(named)}, ${SYSTEM_UI_STACK}`}function cssMonoFamily(mono){let named=mono.trim();return named.length===0||named==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${quote(named)}, ui-monospace, Menlo, Consolas, monospace`}function quote(family){return`"${family.replace(/[\\"]/g,"\\$&")}"`}function faceCss(theme,weight){let type=theme.type,family=type.families[weight];return{fontFamily:weight==="mono"||weight==="monoMedium"||weight==="monoBold"?cssMonoFamily(family):cssFontFamily(family),fontWeight:type.namedFaces[weight]?type.weight.regular:type.weight[FACE_WEIGHT[weight]]}}function headingFaceCss(theme,fallback="bold"){let{headingFamily:headingFamily,headingWeight:headingWeight}=theme.type,base=faceCss(theme,fallback);return headingFamily===null&&headingWeight===null?base:headingFamily!==null?{fontFamily:cssFontFamily(headingFamily),fontWeight:headingWeight??theme.type.weight[FACE_WEIGHT[fallback]]}:theme.type.namedFaces[fallback]||headingWeight===null?base:{fontFamily:base.fontFamily,fontWeight:headingWeight}}var SURFACE_ROOT_RESET=/* @__PURE__ */Object.freeze({textAlign:"start"});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__ */
|
|
108
108
|
return Object.freeze({reason:explicit.reason,level:explicit.level,recoverable:explicit.recoverable})}/* @__PURE__ */
|
|
109
109
|
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,className:className}=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,className:className})}):/* @__PURE__ */jsx(PendingSkeleton,{capability:capability,style:style,className:className});case"disabled":return renderDisabled?/* @__PURE__ */jsx(HostRender,{render:()=>renderDisabled(decision),fallback:/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className}),resetKey:decision}):/* @__PURE__ */jsx(OffState,{decision:decision,style:style,className:className});default:return assertNever(view)}}function PendingSkeleton({capability:capability,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]);/* @__PURE__ */
|
|
110
110
|
return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${capability}`,className:className,style:{...styles.offstate,...style},children:/* @__PURE__ */jsx("div",{style:styles.skeletonBar})})}function OffState({decision:decision,style:style,className:className}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles(theme),[theme]),message=decision.disabled?.reason??"";/* @__PURE__ */
|
|
111
111
|
return jsx("div",{className:className,style:{...styles.offstate,...style},children:message.length>0?/* @__PURE__ */jsx("p",{style:styles.offstateText,children:message}):null})}function makeStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{offstate:{...SURFACE_ROOT_RESET,boxSizing:"border-box",minHeight:MIN_OFFSTATE_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${space.md}px ${space.lg}px`,backgroundColor:color.surfaceCream,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`},offstateText:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.body,lineHeight:`${Math.round(type.size.body*type.lineHeight.normal)}px`,color:color.text.muted},skeletonBar:{height:space.md,borderRadius:radius.xs,backgroundColor:color.brandSofter}}}var DEFAULT_ROOT_HEADING_LEVEL=2;function headingLevel(value){return typeof value!="number"||!Number.isInteger(value)?DEFAULT_ROOT_HEADING_LEVEL:value<1?1:value>6?6:value}function nextHeadingLevel(level){return level>=6?6:level+1}function headingTag(level){return`h${String(level)}`}var NESTED_HEADING_LEVEL_DEFAULT=nextHeadingLevel(DEFAULT_ROOT_HEADING_LEVEL);createContext(NESTED_HEADING_LEVEL_DEFAULT);var RecordsFootnoteDrawnAbove=createContext(false);function RecordsFootnote(props){let theme=useEverfurTheme(),style=useMemo(()=>footnoteStyle(theme),[theme]);return useContext(RecordsFootnoteDrawnAbove)?null:/* @__PURE__ */jsx("p",{role:"note",className:props.className,style:{...style,...props.style},"data-testid":"records-footnote",children:RECORDS_FOOTNOTE})}function footnoteStyle(theme){let{color:color,space:space,type:type}=theme;return{...SURFACE_ROOT_RESET,boxSizing:"border-box",margin:0,padding:`${space.md}px ${space.lg}px ${space.lg}px`,textAlign:"center",...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted,backgroundColor:color.background}}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"}),TYPED_SIGNATURE_MAX_LENGTH=100;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 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,location2){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=location2?.latitude,lng=location2?.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__ */
|
|
112
112
|
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 VISUALLY_HIDDEN=/* @__PURE__ */Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var MIN_HEIGHT=120,MIN_TARGET=44;function RecordsGateOffState({reason:reason,onExit:onExit,exitLabel:exitLabel,style:style,className:className}){let{color:color,space:space,radius:radius,type:type}=useEverfurTheme();/* @__PURE__ */
|
|
113
113
|
return jsxs("div",{className:className,"data-testid":"records-gate-off",style:{boxSizing:"border-box",minHeight:MIN_HEIGHT,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"flex-start",gap:space.md,padding:space.lg,borderRadius:radius.md,border:`1px solid ${color.brandBorder}`,backgroundColor:color.surfaceCream,color:color.text.primary,...style},children:[reason.length>0?/* @__PURE__ */jsx("p",{style:{margin:0,fontSize:type.size.bodyTight,color:color.text.muted},children:reason}):null,
|
|
114
|
-
/* @__PURE__ */jsx("button",{type:"button",onClick:onExit,"data-testid":"records-gate-off-exit",style:{minHeight:MIN_TARGET,padding:`0 ${space.lg}px`,borderRadius:radius.pill,border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk,font:"inherit",fontSize:type.size.body,cursor:"pointer"},children:exitLabel})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}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 slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}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}
|
|
115
|
-
return
|
|
116
|
-
|
|
114
|
+
/* @__PURE__ */jsx("button",{type:"button",onClick:onExit,"data-testid":"records-gate-off-exit",style:{minHeight:MIN_TARGET,padding:`0 ${space.lg}px`,borderRadius:radius.pill,border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk,font:"inherit",fontSize:type.size.body,cursor:"pointer"},children:exitLabel})]})}function recordsGateExit(onExit,exitLabel){return onExit===void 0?{}:{renderDisabled:decision=>/* @__PURE__ */jsx(RecordsGateOffState,{reason:decision.disabled?.reason??"",onExit:onExit,exitLabel:exitLabel})}}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")}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))}}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 slotBoxCss(slot,borderWidth){let box=slotBox(slot,borderWidth),out={};return box.backgroundColor!==void 0&&(out.backgroundColor=box.backgroundColor),box.borderColor!==void 0&&(out.border=`${box.borderWidth??1}px solid ${box.borderColor}`),box.borderRadius!==void 0&&(out.borderRadius=box.borderRadius),out}function recordCardSlot(slots){return slots.recordCard??slots.card}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 BrandImage({src:src,alt:alt,decorative:decorative=false,style:style,height:height,fallback:fallback=null,onFailed:onFailed}){let[failed,setFailed]=useState(null);return src===null||failed===src?fallback:/* @__PURE__ */jsx("img",{src:src,alt:decorative?"":alt,...decorative?{"aria-hidden":true}:{},...height===void 0?{}:{height:height},style:style,decoding:"async",referrerPolicy:"no-referrer",onError:()=>{setFailed(src),onFailed?.()}})}var LOGO_HEIGHT=28,LOGO_MAX_WIDTH=160,LOGO_STYLE=/* @__PURE__ */Object.freeze({display:"block",height:LOGO_HEIGHT,width:"auto",maxWidth:LOGO_MAX_WIDTH,objectFit:"contain"});function BrandLogo({logoUrl:logoUrl,name:name,styles:styles}){/* @__PURE__ */
|
|
115
|
+
return jsx(BrandImage,{src:logoUrl,alt:name,height:LOGO_HEIGHT,style:styles?.logo??LOGO_STYLE})}function slotCss(slot,borderWidth){return{...slotBoxCss(slot,borderWidth),...slotText(slot)}}var RECORDS_EASE_OUT=/* @__PURE__ */Object.freeze([.23,1,.32,1]),RECORDS_MOTION=/* @__PURE__ */Object.freeze({pressScale:.97,pressMs:160,riseWebPx:16,riseNativePx:14,fadeMs:320,moveMs:480,staggerMs:55,maxSteps:8});var EASE=cssCubicBezier(RECORDS_EASE_OUT);function usePressScale(disabled=false){let theme=useEverfurTheme(),[pressed,setPressed]=useState(false),still=theme.motion.reducedMotion||disabled,down=useCallback(()=>setPressed(true),[]),up=useCallback(()=>setPressed(false),[]);return{style:still?{}:{transform:pressed?`scale(${RECORDS_MOTION.pressScale})`:"none",transition:`transform ${RECORDS_MOTION.pressMs}ms ${EASE}`},handlers:{onPointerDown:down,onPointerUp:up,onPointerLeave:up,onPointerCancel:up}}}function useSectionRise(){let reduced=useEverfurTheme().motion.reducedMotion,ran=useRef(false),animations=useRef([]);return useEffect(()=>()=>{for(let animation of animations.current)animation.cancel()},[]),useCallback(node=>{node===null||ran.current||reduced||(ran.current=true,Array.from(node.children).forEach((child,index)=>{if(typeof child.animate!="function")return;let delay=Math.min(index,RECORDS_MOTION.maxSteps-1)*RECORDS_MOTION.staggerMs;try{animations.current.push(child.animate([{transform:`translateY(${RECORDS_MOTION.riseWebPx}px)`},{transform:"none"}],{duration:RECORDS_MOTION.moveMs,delay:delay,easing:EASE,fill:"backwards"}),child.animate([{opacity:0},{opacity:1}],{duration:RECORDS_MOTION.fadeMs,delay:delay,easing:EASE,fill:"backwards"}))}catch{}}))},[reduced])}var SCREEN_HEADING_ATTR="data-ef-screen-heading";function focusTook(el){return el.focus(),document.activeElement===el}function focusScreen(root){let heading=root.querySelector(`[${SCREEN_HEADING_ATTR}]`);if(heading!==null&&(heading.textContent??"").trim().length>0&&focusTook(heading)||focusTook(root))return;let screenRoot=root.firstElementChild;screenRoot instanceof HTMLElement&&(screenRoot.hasAttribute("tabindex")||(screenRoot.setAttribute("tabindex","-1"),screenRoot.style.outline="none"),screenRoot.focus())}var NOT_SEEN=/* @__PURE__ */Symbol("records.screenFocus.notSeen");function useFocusScreenOnChange(screen,onMount=false){let rootRef=useRef(null),seen=useRef(onMount?NOT_SEEN:screen);return useEffect(()=>{if(Object.is(seen.current,screen))return;seen.current=screen;let root=rootRef.current;root!==null&&focusScreen(root)},[screen]),rootRef}var MIN_SURFACE_HEIGHT=120,MIN_TOUCH_TARGET=44,BUTTON_HEIGHT=52,BACK_LABEL="Back";function useScreenStyles(){let theme=useEverfurTheme(),styles=useMemo(()=>makeScreenStyles(theme),[theme]);return{theme:theme,styles:styles}}function ScreenHeader({title:title,onBack:onBack,right:right,testID:testID,variant:variant="brand"}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
116
|
+
return jsxs("header",{style:styles.headerRow,"data-testid":testID,children:[onBack?/* @__PURE__ */jsx("button",{type:"button",onClick:onBack,"aria-label":BACK_LABEL,style:{...styles.iconButton,...styles.headerText},"data-testid":testID?`${testID}-back`:void 0,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.backChevron})}):/* @__PURE__ */jsx("span",{style:styles.iconButton}),title.trim().length>0?/* @__PURE__ */jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:variant==="document"?styles.documentTitle:styles.headerTitle,children:title}):/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.headerTitle,"data-testid":testID?`${testID}-spacer`:void 0}),
|
|
117
|
+
/* @__PURE__ */jsxs("div",{style:styles.headerRight,children:[variant==="brand"?/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles.headerLogo}):null,right??/* @__PURE__ */jsx("span",{style:styles.iconButton})]})]})}function DisclaimerBand({disclaimer:disclaimer,style:style}){let{styles:styles}=useScreenStyles();return disclaimerRepeatsFootnote(disclaimer)?null:/* @__PURE__ */jsxs("p",{role:"note","aria-label":DASHBOARD_COPY.important(disclaimer),style:{...styles.band,...style},"data-testid":"records-disclaimer-band",children:[
|
|
117
118
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.infoGlyph,children:"i"}),
|
|
118
119
|
/* @__PURE__ */jsx("span",{style:styles.bandText,children:disclaimer})]})}function Pill({label:label,onClick:onClick,kind:kind="primary",disabled:disabled=false,busy:busy=false,ariaLabel:ariaLabel,ariaDescribedBy:ariaDescribedBy,testID:testID,style:style}){let{styles:styles}=useScreenStyles(),press=usePressScale(disabled||busy),box=kind==="primary"?styles.pillPrimary:kind==="outline"?styles.pillOutline:kind==="danger"?styles.pillDanger:kind==="ask"?styles.pillAsk:styles.pillLink;/* @__PURE__ */
|
|
119
120
|
return jsx("button",{type:"button",onClick:onClick,disabled:disabled||busy,"aria-busy":busy,"aria-label":ariaLabel,"aria-describedby":ariaDescribedBy,...press.handlers,style:{...styles.pill,...box,...disabled?styles.pillDisabled:{},...press.style,...style},"data-testid":testID,children:label})}function Chip({label:label,tone:tone="neutral",testID:testID}){let{styles:styles}=useScreenStyles(),sentence=label.length>CHIP_WORD_MAX;/* @__PURE__ */
|
|
@@ -128,7 +129,7 @@ return jsx("svg",{"aria-hidden":"true",focusable:"false",width:18,height:18,view
|
|
|
128
129
|
/* @__PURE__ */jsx("circle",{cx:"18",cy:"19",r:"3"}),
|
|
129
130
|
/* @__PURE__ */jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),
|
|
130
131
|
/* @__PURE__ */jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]})})}function Chevron({direction:direction="right"}){let{styles:styles}=useScreenStyles(),rotate=direction==="right"?"45deg":direction==="down"?"135deg":"-45deg";/* @__PURE__ */
|
|
131
|
-
return jsx("span",{"aria-hidden":"true",style:{...styles.chevron,transform:`rotate(${rotate})`}})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),cardText=slotText(slots.recordCard),errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({backgroundColor:bg,color:fg,border:"1.5px solid transparent"}),edge=(line,fg)=>({backgroundColor:color.surface,color:fg,border:`1.5px solid ${line}`}),cardEdge=`1px solid ${color.borderRingCream}`,button={boxSizing:"border-box",minHeight:BUTTON_HEIGHT,minWidth:MIN_TOUCH_TARGET,padding:`${space.md}px ${space.lg+space.xs/2}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:space.sm,textDecoration:"none"};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)},root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},content:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.lg}px ${space.xxl}px`},contentTight:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.sm}px ${space.xxl}px`},inset:{padding:`0 ${space.sm}px`},headerRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm,padding:`${space.xs}px ${space.lg}px ${space.md}px`},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,display:"inline-flex",alignItems:"center",justifyContent:"center",border:0,background:"transparent",cursor:"pointer",padding:0,color:color.brandInk,flexShrink:0},backChevron:{display:"block",width:space.md,height:space.md,borderLeft:`2px solid ${color.brandInk}`,borderBottom:`2px solid ${color.brandInk}`,transform:"rotate(45deg)",marginLeft:space.xs},headerTitle:{...text3(type.size.heading,type.lineHeight.tight,color.brandInk,"bold"),flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},documentTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),flex:1,textAlign:"center"},headerRight:{display:"flex",alignItems:"center",gap:space.sm+space.xs/2},section:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:space.sm,padding:`0 ${space.xs}px`},sectionTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),letterSpacing:"-0.02em"},sectionCount:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.muted,"medium")},card:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surface,padding:`${space.xs}px ${space.lg}px`,margin:0,listStyle:"none",...slotBoxCss(slots.recordCard,1)},creamCard:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surfaceCream,padding:space.lg,display:"flex",flexDirection:"column",gap:space.md,...slotBoxCss(slots.recordCard,1)},row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.md,padding:`${space.md}px 0`},rowDivider:{borderTop:`1px solid ${color.borderHairlineGreen}`},rowMain:{flex:1,minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},chip:{boxSizing:"border-box",display:"inline-flex",alignItems:"center",minHeight:24,borderRadius:radius.pill,padding:`0 ${space.sm+space.xs/2}px`,...faceCss(theme,"monoBold"),fontSize:type.size.tiny+1,lineHeight:lh(type.size.tiny+1,type.lineHeight.snug),letterSpacing:"0.06em",textTransform:"uppercase",whiteSpace:"nowrap"},pill:button,pillPrimary:{border:0,backgroundColor:color.brand,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},pillOutline:{border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk},pillDanger:{border:`1.4px solid ${color.danger}`,backgroundColor:color.surface,color:color.danger,fontSize:type.size.bodyTight},pillAsk:{border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,color:color.text.primary},pillLink:{minHeight:MIN_TOUCH_TARGET,border:0,backgroundColor:"transparent",color:color.linkInk,padding:`${space.sm}px`},pillDisabled:{opacity:.5,cursor:"default"},infoNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary)},cautionNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2,...text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary)},errorBanner:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md,...text3(type.size.bodyTight,type.lineHeight.normal,errorColor)},errorText:text3(type.size.bodyTight,type.lineHeight.normal,errorColor),band:{display:"flex",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:0},bandText:{flex:1,...text3(type.size.caption,type.lineHeight.normal,color.text.secondary)},infoGlyph:{boxSizing:"border-box",flexShrink:0,width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,border:`1px solid ${color.text.secondary}`,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.small,color:color.text.secondary},chevron:{display:"inline-block",width:space.sm,height:space.sm,borderTop:`2px solid ${color.text.muted}`,borderRight:`2px solid ${color.text.muted}`,flexShrink:0},chipSentence:{...faceCss(theme,"medium"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),letterSpacing:"normal",textTransform:"none",whiteSpace:"normal",borderRadius:radius.md,padding:`${space.xs}px ${space.sm+space.xs/2}px`},lead:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),padding:`0 ${space.sm}px`},subLead:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),padding:`0 ${space.lg}px ${space.md}px`},field:{boxSizing:"border-box",display:"block",width:"100%",minHeight:MIN_TOUCH_TARGET,padding:`${space.sm}px ${space.md}px`,border:`1px solid ${color.borderHairlineGreen}`,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...faceCss(theme,"regular"),fontSize:type.size.body},fieldLabel:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium"),display:"block",marginBottom:space.xs},muted:text3(type.size.caption,type.lineHeight.normal,color.text.muted),bodyText:text3(type.size.body,type.lineHeight.normal,color.text.primary),mono:faceCss(theme,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:space.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,borderRadius:radius.xl-1,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},sheetHeader:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},sheetTitle:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},sheetHelper:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),closeGlyph:{fontSize:type.size.verdict,lineHeight:1,color:color.text.primary}}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}function formatShortDate(at){if(at===null||at.length===0)return"";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let year=iso[1]??"",month=iso[2]??"",day=iso[3]??"";return`${Number(month)}/${Number(day)}/${year.slice(2)}`}let ms=Date.parse(at);if(Number.isNaN(ms))return at;let date=new Date(ms);return`${date.getUTCMonth()+1}/${date.getUTCDate()}/${String(date.getUTCFullYear()).slice(2)}`}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){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 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 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__ */
|
|
132
|
+
return jsx("span",{"aria-hidden":"true",style:{...styles.chevron,transform:`rotate(${rotate})`}})}function makeScreenStyles(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),headerInk=slots.header?.textColor??color.brandInk,bannerText=slotText(slots.banner),dialogText=slotText(slots.dialog),errorColor=theme.brightness==="dark"?color.errorRed:color.danger,tone=(bg,fg)=>({backgroundColor:bg,color:fg,border:"1.5px solid transparent"}),edge=(line,fg)=>({backgroundColor:color.surface,color:fg,border:`1.5px solid ${line}`}),cardEdge=`1px solid ${color.borderRingCream}`,button={boxSizing:"border-box",minHeight:BUTTON_HEIGHT,minWidth:MIN_TOUCH_TARGET,padding:`${space.md}px ${space.lg+space.xs/2}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:space.sm,textDecoration:"none"};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,brandedStatus(theme).success?color.success:color.brandInk)},root:{...SURFACE_ROOT_RESET,boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},content:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.lg}px ${space.xxl}px`},contentTight:{display:"flex",flexDirection:"column",gap:space.lg,padding:`0 ${space.sm}px ${space.xxl}px`},inset:{padding:`0 ${space.sm}px`},headerRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm,padding:`${space.xs}px ${space.lg}px ${space.md}px`,...slotCss(slots.header)},headerText:slotText(slots.header),headerSlot:slotCss(slots.header,1),headerInk:headerInk,headerLogo:{logo:{display:"block",height:28,width:"auto",maxWidth:96,objectFit:"contain",flexShrink:0}},pageLogo:{logo:{display:"block",height:28,width:"auto",maxWidth:160,objectFit:"contain",alignSelf:"flex-start"}},iconButton:{boxSizing:"border-box",width:MIN_TOUCH_TARGET,height:MIN_TOUCH_TARGET,display:"inline-flex",alignItems:"center",justifyContent:"center",border:0,background:"transparent",cursor:"pointer",padding:0,color:color.brandInk,flexShrink:0},backChevron:{display:"block",width:space.md,height:space.md,borderLeft:`2px solid ${headerInk}`,borderBottom:`2px solid ${headerInk}`,transform:"rotate(45deg)",marginLeft:space.xs},headerTitle:{...text3(type.size.heading,type.lineHeight.tight,color.brandInk,"bold"),...headingFaceCss(theme,"bold"),flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...slotText(slots.header)},documentTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold"),flex:1,textAlign:"center",...slotText(slots.header)},headerRight:{display:"flex",alignItems:"center",gap:space.sm+space.xs/2},section:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:space.sm,padding:`0 ${space.xs}px`},sectionTitle:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold"),letterSpacing:"-0.02em"},sectionCount:{...text3(type.size.bodyTight,type.lineHeight.snug,color.text.muted,"medium")},card:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surface,padding:`${space.xs}px ${space.lg}px`,margin:0,listStyle:"none",...slotBoxCss(recordCard,1)},creamCard:{boxSizing:"border-box",borderRadius:radius.lg,border:cardEdge,backgroundColor:color.surfaceCream,padding:space.lg,display:"flex",flexDirection:"column",gap:space.md,...slotBoxCss(recordCard,1)},cardSlot:slotBoxCss(recordCard,1),cardInk:cardText,row:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.md,padding:`${space.md}px 0`},rowDivider:{borderTop:`1px solid ${color.borderHairlineGreen}`},rowMain:{flex:1,minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:space.xs+space.xs/2},rowTitle:{...text3(type.size.body,type.lineHeight.snug,color.text.primary,"medium"),...cardText},rowDetail:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),marginTop:space.xs/2,...cardText},rowValue:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),marginTop:space.xs/2,...cardText},rowMuted:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),...cardText},chip:{boxSizing:"border-box",display:"inline-flex",alignItems:"center",minHeight:24,borderRadius:radius.pill,padding:`0 ${space.sm+space.xs/2}px`,...faceCss(theme,"monoBold"),fontSize:type.size.tiny+1,lineHeight:lh(type.size.tiny+1,type.lineHeight.snug),letterSpacing:"0.06em",textTransform:"uppercase",whiteSpace:"nowrap"},pill:button,pillPrimary:{border:0,backgroundColor:color.brand,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},pillOutline:{border:`1.5px solid ${color.brandInk}`,backgroundColor:"transparent",color:color.brandInk},pillDanger:{border:`1.4px solid ${color.danger}`,backgroundColor:color.surface,color:color.danger,fontSize:type.size.bodyTight},pillAsk:{border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,color:color.text.primary},pillLink:{minHeight:MIN_TOUCH_TARGET,border:0,backgroundColor:"transparent",color:color.linkInk,padding:`${space.sm}px`},pillDisabled:{opacity:.5,cursor:"default"},infoNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.brandSoft,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary),...slotCss(slots.banner)},cautionNote:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCaution,padding:`${space.sm+space.xs/2}px ${space.md}px`,...text3(type.size.bodyTight,type.lineHeight.normal,color.warningStrong)},statusCard:{borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2,...text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary)},errorBanner:{display:"flex",gap:space.sm,borderRadius:radius.md-space.xs/2,backgroundColor:color.badgeBgCritical,padding:space.md,...text3(type.size.bodyTight,type.lineHeight.normal,errorColor)},errorText:text3(type.size.bodyTight,type.lineHeight.normal,errorColor),band:{display:"flex",alignItems:"flex-start",gap:space.sm,borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:0,...slotCss(slots.banner)},bandText:{flex:1,...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),...bannerText},infoGlyph:{boxSizing:"border-box",flexShrink:0,width:space.md+space.xs/2,height:space.md+space.xs/2,borderRadius:radius.pill,border:`1px solid ${slots.banner?.textColor??color.text.secondary}`,display:"inline-flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.small,color:color.text.secondary,...bannerText},chevron:{display:"inline-block",width:space.sm,height:space.sm,borderTop:`2px solid ${color.text.muted}`,borderRight:`2px solid ${color.text.muted}`,flexShrink:0},chipSentence:{...faceCss(theme,"medium"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),letterSpacing:"normal",textTransform:"none",whiteSpace:"normal",borderRadius:radius.md,padding:`${space.xs}px ${space.sm+space.xs/2}px`},lead:{...text3(type.size.body+1,type.lineHeight.snug,color.text.primary,"bold"),padding:`0 ${space.sm}px`},subLead:{...text3(type.size.body,type.lineHeight.normal,color.text.muted),padding:`0 ${space.lg}px ${space.md}px`},field:{boxSizing:"border-box",display:"block",width:"100%",minHeight:MIN_TOUCH_TARGET,padding:`${space.sm}px ${space.md}px`,border:`1px solid ${color.borderHairlineGreen}`,borderRadius:radius.sm,color:color.text.primary,backgroundColor:color.surface,...faceCss(theme,"regular"),fontSize:type.size.body,...slotCss(slots.input,1)},inputSlot:slotCss(slots.input,1),inputText:slotText(slots.input),fieldLabel:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.secondary,"medium"),display:"block",marginBottom:space.xs},muted:text3(type.size.caption,type.lineHeight.normal,color.text.muted),bodyText:text3(type.size.body,type.lineHeight.normal,color.text.primary),mono:faceCss(theme,"mono"),plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},dialogFrame:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",margin:0,padding:0,border:0,backgroundColor:"transparent",overflow:"hidden"},dialogScrim:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:"100%",padding:space.lg,backgroundColor:"rgba(0,0,0,0.4)"},dialogScrimSide:{boxSizing:"border-box",display:"flex",alignItems:"stretch",justifyContent:"flex-end",width:"100%",height:"100%",backgroundColor:"rgba(0,0,0,0.4)"},dialogPanel:{boxSizing:"border-box",width:"100%",maxWidth:560,maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,borderRadius:radius.xl-1,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},dialogPanelSide:{boxSizing:"border-box",width:"min(100vw, 480px)",height:"100%",maxHeight:"100%",overflowY:"auto",backgroundColor:color.surface,padding:`${space.lg}px ${space.lg+space.xs+space.xs/2}px`,display:"flex",flexDirection:"column",gap:space.md,...faceCss(theme,"regular"),color:color.text.primary},dialogSlot:slotCss(slots.dialog),dialogSlotSide:{...slotCss(slots.dialog),...slots.dialog?.borderRadius===void 0?null:{borderRadius:`${slots.dialog.borderRadius}px 0 0 ${slots.dialog.borderRadius}px`}},sheetHeader:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm},sheetTitle:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold"),...dialogText},sheetHelper:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),...dialogText},closeGlyph:{fontSize:type.size.verdict,lineHeight:1,color:color.text.primary,...dialogText}}}function formatEntityValue(value,unit){return value===null?"":unit?`${value} ${unit}`:value}function formatShortDate(at){if(at===null||at.length===0)return"";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){let year=iso[1]??"",month=iso[2]??"",day=iso[3]??"";return`${Number(month)}/${Number(day)}/${year.slice(2)}`}let ms=Date.parse(at);if(Number.isNaN(ms))return at;let date=new Date(ms);return`${date.getUTCMonth()+1}/${date.getUTCDate()}/${String(date.getUTCFullYear()).slice(2)}`}var MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function formatRecordsDate(at){if(!at)return"-";let iso=/^(\d{4})-(\d{2})-(\d{2})/.exec(at);if(iso!==null){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 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 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__ */
|
|
132
133
|
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__ */
|
|
133
134
|
return jsx("span",{"aria-hidden":"true",style:{display:"block",width:width,height:height,borderRadius:radius??radii.xs,backgroundColor:color.skeleton,flexShrink:0,...style}})}var DONUT=180,DISCLAIMER_H=44,TIMELINE_SEPARATOR_INSET=62;function DashboardSkeleton({testID:testID}){let s=useStyles(),action=key=>/* @__PURE__ */jsxs("div",{style:s.actionRow,children:[
|
|
134
135
|
/* @__PURE__ */jsxs("div",{style:s.actionLeft,children:[
|
|
@@ -179,14 +180,14 @@ return jsx("div",{role:"progressbar","aria-label":SHARE_COPY.loadingLinks,"aria-
|
|
|
179
180
|
return jsxs("section",{role:"status",style:s.empty,"data-testid":testID,children:[
|
|
180
181
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:s.emptyGlyph}),
|
|
181
182
|
/* @__PURE__ */jsx("h3",{style:s.emptyTitle,children:copy.title}),
|
|
182
|
-
/* @__PURE__ */jsx("p",{style:s.emptyBody,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx("button",{type:"button",onClick:onAction,disabled:cooling,"aria-label":cooling?COOLING_A11Y_LABEL:label,style:{...s.emptyAction,...cooling?s.emptyActionDisabled:{}},"data-testid":testID?`${testID}-action`:`records-empty-${variant}-action`,children:label}):null]})}function useStyles(){let theme=useEverfurTheme();return useMemo(()=>makeStyles2(theme),[theme])}function makeStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=`1px solid ${color.brandBorder}`;return{dashboard:{display:"flex",flexDirection:"column",gap:space.lg,padding:`${space.xs}px ${space.sm}px 0`,backgroundColor:color.background},inset:{padding:`0 ${space.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.md+space.xs/2,borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:`${space.lg+space.xs}px ${space.lg}px`},badges:{display:"flex",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:space.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,border:hairline,backgroundColor:color.surface,padding:space.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:space.md},request:{display:"flex",flexDirection:"column",gap:space.lg+space.xs/2,padding:`${space.xs}px ${space.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs+space.xs/2,paddingBottom:space.lg+space.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},timeline:{backgroundColor:color.background},timelineDisclaimer:{padding:`${space.xs}px ${space.lg}px ${space.md}px`},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:1,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{display:"flex",flexDirection:"column",gap:space.md},clinicRow:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.lg-space.xs/2,border:hairline,backgroundColor:color.surface,padding:`${space.md+space.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline},shareRow:{display:"flex",flexDirection:"column",gap:space.xs+space.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm+space.xs/2,padding:`${space.xxl}px ${space.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:color.brandSoft,border:hairline,marginBottom:space.xs},emptyTitle:{margin:0,...
|
|
183
|
+
/* @__PURE__ */jsx("p",{style:s.emptyBody,children:message??copy.body}),label!==null&&onAction?/* @__PURE__ */jsx("button",{type:"button",onClick:onAction,disabled:cooling,"aria-label":cooling?COOLING_A11Y_LABEL:label,style:{...s.emptyAction,...cooling?s.emptyActionDisabled:{}},"data-testid":testID?`${testID}-action`:`records-empty-${variant}-action`,children:label}):null]})}function useStyles(){let theme=useEverfurTheme();return useMemo(()=>makeStyles2(theme),[theme])}function makeStyles2(theme){let{color:color,space:space,radius:radius,type:type}=theme,hairline=`1px solid ${color.brandBorder}`;return{dashboard:{display:"flex",flexDirection:"column",gap:space.lg,padding:`${space.xs}px ${space.sm}px 0`,backgroundColor:color.background},inset:{padding:`0 ${space.sm}px`},summaryCard:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.md+space.xs/2,borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:`${space.lg+space.xs}px ${space.lg}px`},badges:{display:"flex",gap:space.md},carouselCard:{borderRadius:radius.lg-space.xs,border:hairline,backgroundColor:color.surface,padding:space.lg},dots:{display:"flex",alignItems:"center",justifyContent:"center",gap:space.xs+space.xs/2},centered:{display:"flex",justifyContent:"center"},actions:{display:"flex",flexDirection:"column",gap:space.sm+space.xs/2},actionRow:{display:"flex",alignItems:"center",justifyContent:"space-between",borderRadius:radius.md,border:hairline,backgroundColor:color.surface,padding:space.lg},actionLeft:{flex:1,display:"flex",alignItems:"center",gap:space.md},request:{display:"flex",flexDirection:"column",gap:space.lg+space.xs/2,padding:`${space.xs}px ${space.lg}px 0`},railRow:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs/2,width:24},railBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs+space.xs/2,paddingBottom:space.lg+space.xs/2},statusCard:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.md,backgroundColor:color.brandSoft,padding:space.md+space.xs/2},timeline:{backgroundColor:color.background},timelineDisclaimer:{padding:`${space.xs}px ${space.lg}px ${space.md}px`},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1},timelineTop:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},timelineSeparator:{height:1,backgroundColor:color.brandBorder,marginLeft:TIMELINE_SEPARATOR_INSET},clinics:{display:"flex",flexDirection:"column",gap:space.md},clinicRow:{display:"flex",flexDirection:"column",gap:space.sm,borderRadius:radius.lg-space.xs/2,border:hairline,backgroundColor:color.surface,padding:`${space.md+space.xs/2}px`},shares:{display:"flex",flexDirection:"column",gap:space.md,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline},shareRow:{display:"flex",flexDirection:"column",gap:space.xs+space.xs/2},empty:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm+space.xs/2,padding:`${space.xxl}px ${space.xl}px`,textAlign:"center"},emptyGlyph:{boxSizing:"border-box",width:22,height:22,borderRadius:11,backgroundColor:color.brandSoft,border:hairline,marginBottom:space.xs},emptyTitle:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:`${Math.round(type.size.subtitle*type.lineHeight.snug)-1}px`,color:color.brandInk},emptyBody:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.bodyTight,lineHeight:`${Math.round(type.size.bodyTight*type.lineHeight.normal)}px`,color:color.text.muted,maxWidth:320},emptyAction:{boxSizing:"border-box",marginTop:space.sm,minHeight:40,borderRadius:radius.pill,padding:`0 ${space.lg+space.xs/2}px`,backgroundColor:color.brand,color:color.onPrimary,border:0,cursor:"pointer",...faceCss(theme,"bold"),fontSize:type.size.bodyTight},emptyActionDisabled:{opacity:.5,cursor:"default"}}}var EMAIL=/^[^@\s]+@[^@\s]+\.[^@\s]+$/;function EverfurClinicPicker(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
183
184
|
return jsx(CapabilityGate,{capability:"recordsClinic",style:props.style,className:props.className,...recordsGateExit(props.onBack,BACK_LABEL),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(PickerBody,{...guardHostProps(props,["onNavigate","onBack"])},JSON.stringify([userRef,scopeEpoch,props.petRef]))})}function PickerBody({petRef:petRef,petName:petName,controller:controller,recordsController:recordsController,location:location2,onNavigate:onNavigate,onBack:onBack,style:style,className:className}){let{theme:theme,styles:styles}=useScreenStyles(),runtimeController=useEverfurRecordsClinic(),picker=useClinicPicker(controller??runtimeController,location2),records=useEverfurRecords(recordsController?{petRef:petRef,controller:recordsController}:{petRef:petRef}),keyFactory=useRef(defaultIdempotencyKeyFactory()),[starting,setStarting]=useState(false),[startError,setStartError]=useState(null),[fallbackOpen,setFallbackOpen]=useState(false),[fallbackName,setFallbackName]=useState(""),[fallbackNameDirty,setFallbackNameDirty]=useState(false),[fallbackEmail,setFallbackEmail]=useState(""),[fallbackTouched,setFallbackTouched]=useState(false),select=useCallback(clinic=>{onNavigate?.({name:"consent",clinic:clinicDraftFor(clinic,null,"",keyFactory.current())})},[onNavigate]),startUpload=()=>{starting||(setStarting(true),setStartError(null),records.createRequest(`records-upload-${Date.now().toString(36)}`).then(result=>{if(setStarting(false),!result.ok){setStartError(REQUEST_SCREEN_COPY.errors.start);return}onNavigate?.({name:"request",requestId:result.value.id})}))},displayName=fallbackNameDirty?fallbackName:picker.query,fallbackEmailValid=EMAIL.test(fallbackEmail.trim()),canContinue=displayName.trim().length>0&&fallbackEmailValid,fallbackEmailWrong=fallbackTouched&&fallbackEmail.trim().length>0&&!fallbackEmailValid,listData=picker.isSearchActive?picker.clinics:picker.recent,emptyVariant=picker.isSearchActive?picker.error?recordsEmptyVariantForError(picker.error):!picker.initialLoading&&picker.clinics.length===0?"idle":null:picker.recent.length>0||picker.recentLoading?null:"idle",block={display:"flex",flexDirection:"column",gap:theme.space.sm},resultsAnnouncement=picker.isSearchActive&&!picker.initialLoading&&!picker.error&&picker.clinics.length>0?CLINIC_PICKER_COPY.resultsCountDraft(picker.clinics.length):"",onScroll=event=>{let el=event.currentTarget;el.scrollTop+el.clientHeight>=el.scrollHeight-el.clientHeight*.6&&picker.loadMore()};/* @__PURE__ */
|
|
184
185
|
return jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-clinic-picker",children:[
|
|
185
186
|
/* @__PURE__ */jsx(ScreenHeader,{title:CLINIC_PICKER_COPY.titleFor(petName),onBack:onBack,testID:"records-clinic-header"}),
|
|
186
187
|
/* @__PURE__ */jsx("p",{style:styles.subLead,"data-testid":"records-clinic-lead",children:CLINIC_PICKER_COPY.leadWeb}),
|
|
187
188
|
/* @__PURE__ */jsx("label",{htmlFor:"records-clinic-search",style:{...styles.fieldLabel,padding:`0 ${theme.space.lg}px`},children:CLINIC_PICKER_COPY.searchLabelWeb}),
|
|
188
|
-
/* @__PURE__ */jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm,margin:`0 ${theme.space.lg}px ${theme.space.sm}px`,padding:`0 ${theme.space.md+theme.space.xs/2}px`,height:44,borderRadius:22,backgroundColor:theme.color.surfaceSubtle,border:`1px solid ${theme.color.borderHairlineGreen}
|
|
189
|
-
/* @__PURE__ */jsx("input",{id:"records-clinic-search",type:"search",value:picker.query,onChange:event=>picker.setQuery(event.target.value),placeholder:CLINIC_PICKER_COPY.placeholder,maxLength:200,autoComplete:"off",style:{flex:1,border:0,background:"transparent",font:"inherit",fontSize:theme.type.size.body,color:theme.color.text.primary,outline:"none"},"data-testid":"records-clinic-search-input"}),picker.query.length>0?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>picker.setQuery(""),"aria-label":CLINIC_PICKER_COPY.clearSearch,style:{...styles.iconButton,width:32,height:32},"data-testid":"records-clinic-search-clear",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.closeGlyph,children:"×"})}):null]}),onNavigate?/* @__PURE__ */jsxs("div",{style:{...block,padding:`0 ${theme.space.lg}px ${theme.space.md}px`},children:[startError?/* @__PURE__ */jsx("p",{role:"alert",style:styles.errorBanner,children:startError}):null,
|
|
189
|
+
/* @__PURE__ */jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm,margin:`0 ${theme.space.lg}px ${theme.space.sm}px`,padding:`0 ${theme.space.md+theme.space.xs/2}px`,height:44,borderRadius:22,backgroundColor:theme.color.surfaceSubtle,border:`1px solid ${theme.color.borderHairlineGreen}`,...styles.inputSlot},children:[
|
|
190
|
+
/* @__PURE__ */jsx("input",{id:"records-clinic-search",type:"search",value:picker.query,onChange:event=>picker.setQuery(event.target.value),placeholder:CLINIC_PICKER_COPY.placeholder,maxLength:200,autoComplete:"off",style:{flex:1,border:0,background:"transparent",font:"inherit",fontSize:theme.type.size.body,color:theme.color.text.primary,outline:"none",...styles.inputText},"data-testid":"records-clinic-search-input"}),picker.query.length>0?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>picker.setQuery(""),"aria-label":CLINIC_PICKER_COPY.clearSearch,style:{...styles.iconButton,width:32,height:32},"data-testid":"records-clinic-search-clear",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.closeGlyph,children:"×"})}):null]}),onNavigate?/* @__PURE__ */jsxs("div",{style:{...block,padding:`0 ${theme.space.lg}px ${theme.space.md}px`},children:[startError?/* @__PURE__ */jsx("p",{role:"alert",style:styles.errorBanner,children:startError}):null,
|
|
190
191
|
/* @__PURE__ */jsx(Pill,{label:starting?CLINIC_PICKER_COPY.uploadOwnStarting:CLINIC_PICKER_COPY.uploadOwn,kind:"outline",busy:starting,onClick:startUpload,testID:"records-clinic-upload-own"})]}):null,
|
|
191
192
|
/* @__PURE__ */jsx("p",{role:"status",style:VISUALLY_HIDDEN,"data-testid":"records-clinic-results-status",children:resultsAnnouncement}),
|
|
192
193
|
/* @__PURE__ */jsxs("div",{style:{...styles.body,...styles.content,gap:theme.space.md},onScroll:picker.isSearchActive?onScroll:void 0,"data-testid":"records-clinic-results",children:[picker.isSearchActive?/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,borderStyle:"dashed",padding:`${theme.space.md}px ${theme.space.md+theme.space.xs/2}px`},"data-testid":"records-clinic-fallback-card",children:[
|
|
@@ -202,27 +203,27 @@ return jsxs("div",{className:className,style:{...styles.root,...style},"data-tes
|
|
|
202
203
|
/* @__PURE__ */jsx("p",{style:styles.muted,children:CLINIC_PICKER_COPY.fallback.reviewNote}),
|
|
203
204
|
/* @__PURE__ */jsx(Pill,{label:CLINIC_PICKER_COPY.fallback.submit,disabled:!canContinue||!onNavigate,onClick:()=>onNavigate?.({name:"consent",clinic:clinicDraftFor(null,displayName.trim(),fallbackEmail.trim().toLowerCase(),keyFactory.current())}),testID:"records-clinic-fallback-submit"})]}):null]}):picker.recent.length>0?/* @__PURE__ */jsx("h3",{style:{...styles.fieldLabel,...faceCss(theme,"bold"),textTransform:"uppercase",marginBottom:0},"data-testid":"records-clinic-recent-label",children:CLINIC_PICKER_COPY.recentlyUsed}):null,picker.isSearchActive&&picker.initialLoading?/* @__PURE__ */jsx(ClinicsSkeleton,{testID:"records-clinic-page-loading"}):null,
|
|
204
205
|
/* @__PURE__ */jsx("ul",{style:{...styles.plainList,gap:theme.space.md},children:listData.map(clinic=>{let badge=clinicEmailStatusBadge(clinic.emailStatus),distance=formatClinicDistanceLabel(clinic.distanceKm),summary=[clinic.name,clinic.address,clinic.phone?`phone ${clinic.phone}`:null,distance?formatClinicDistanceForA11y(clinic.distanceKm):null,badge.a11y].filter(Boolean).join(", "),tone=badge.tone==="positive"?{backgroundColor:theme.color.badgeBgPositive,color:theme.color.success}:badge.tone==="caution"?{backgroundColor:theme.color.badgeBgCaution,color:theme.color.cautionAccent}:{backgroundColor:theme.color.badgeBgNeutral,color:theme.color.text.muted};/* @__PURE__ */
|
|
205
|
-
return jsx("li",{children:/* @__PURE__ */jsxs("button",{type:"button",onClick:()=>select(clinic),"aria-label":CLINIC_PICKER_COPY.selectA11y(summary),style:{...styles.creamCard,backgroundColor:theme.color.surface,width:"100%",textAlign:"left",cursor:"pointer",gap:theme.space.sm,padding:`${theme.space.md}px ${theme.space.md+theme.space.xs/2}px`,font:"inherit",color:"inherit"},"data-testid":`records-clinic-${clinic.id}`,children:[
|
|
206
|
+
return jsx("li",{children:/* @__PURE__ */jsxs("button",{type:"button",onClick:()=>select(clinic),"aria-label":CLINIC_PICKER_COPY.selectA11y(summary),style:{...styles.creamCard,backgroundColor:theme.color.surface,width:"100%",textAlign:"left",cursor:"pointer",gap:theme.space.sm,padding:`${theme.space.md}px ${theme.space.md+theme.space.xs/2}px`,font:"inherit",color:"inherit",...styles.cardSlot},"data-testid":`records-clinic-${clinic.id}`,children:[
|
|
206
207
|
/* @__PURE__ */jsxs("span",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
207
208
|
/* @__PURE__ */jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold"),color:theme.color.brandInk},children:clinic.name}),distance?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{...styles.muted,...styles.mono},children:distance}):null]}),clinic.address?/* @__PURE__ */jsx("span",{style:styles.rowDetail,children:clinic.address}):null,clinic.phone?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.rowMuted,children:clinic.phone}):null,
|
|
208
209
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{...styles.chip,...tone,...faceCss(theme,"bold"),fontSize:theme.type.size.micro,alignSelf:"flex-start"},children:badge.label})]})},clinic.id)})}),emptyVariant&&!picker.initialLoading?/* @__PURE__ */jsx(RecordsEmptyState,{variant:emptyVariant,message:picker.isSearchActive&&emptyVariant==="idle"?CLINIC_PICKER_COPY.noMatch(picker.debouncedQuery):picker.error?.displayMessage,onAction:picker.error?.retryable===true?picker.retry:void 0,testID:"records-clinic-empty"}):null,
|
|
209
210
|
/* @__PURE__ */jsxs("div",{style:block,children:[picker.loadingMore?/* @__PURE__ */jsx("p",{role:"status",style:{...styles.muted,textAlign:"center"},"data-testid":"records-clinic-loading-more",children:CLINIC_PICKER_COPY.loadingMore}):null,picker.pageError?/* @__PURE__ */jsx("button",{type:"button",onClick:picker.loadMore,style:{...styles.pill,...styles.pillLink},"data-testid":"records-clinic-page-error-retry",children:CLINIC_PICKER_COPY.loadMoreFailed}):null]}),
|
|
210
211
|
/* @__PURE__ */jsx(HowItWorks,{petName:petName})]}),
|
|
211
212
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})}function HowItWorks({petName:petName}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
212
|
-
return jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0},"aria-label":CLINIC_PICKER_COPY.howItWorks,"data-testid":"records-clinic-how",children:[
|
|
213
|
-
/* @__PURE__ */jsx("h3",{style:styles.sectionTitle,children:CLINIC_PICKER_COPY.howItWorks}),
|
|
213
|
+
return jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0,...styles.cardSlot},"aria-label":CLINIC_PICKER_COPY.howItWorks,"data-testid":"records-clinic-how",children:[
|
|
214
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,...styles.cardInk},children:CLINIC_PICKER_COPY.howItWorks}),
|
|
214
215
|
/* @__PURE__ */jsx("ol",{style:{...styles.plainList,gap:theme.space.md},children:CLINIC_PICKER_COPY.howSteps(petNameOr(petName)).map((step,index)=>/* @__PURE__ */jsxs("li",{style:{display:"flex",gap:theme.space.md},children:[
|
|
215
216
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{...styles.mono,...faceCss(theme,"monoBold"),fontSize:theme.type.size.caption,color:theme.color.brandInk,minWidth:theme.space.xl},children:String(index+1).padStart(2,"0")}),
|
|
216
217
|
/* @__PURE__ */jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2},children:[
|
|
217
218
|
/* @__PURE__ */jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:step.title}),
|
|
218
|
-
/* @__PURE__ */jsx("span",{style:styles.rowDetail,children:step.body})]})]},step.title))})]})}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}var MAX_INLINE_SIGNATURE_BASE64=2*1024*1024;function inlineSignatureFits(base64){return base64.length>0&&base64.length<=MAX_INLINE_SIGNATURE_BASE64}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 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)}}}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}}function paintClinicTypedSignature(context,name,width,height){context.clearRect(0,0,width,height);let text3=name.trim();if(!text3)return;let maxWidth=Math.max(1,width-32),size=Math.min(44,Math.max(16,Math.round(height*.34))),font=()=>{context.font=`italic 700 ${size}px Georgia, "Times New Roman", serif`};for(font();size>12&&context.measureText(text3).width>maxWidth;)size-=2,font();context.textAlign="center",context.textBaseline="middle",context.fillText(text3,width/2,height/2,maxWidth)}function paintSignatureStrokes(context,strokes,width,height){context.clearRect(0,0,width,height);for(let points of strokes){let first=points[0];if(first!==void 0){context.beginPath(),context.moveTo(first[0],first[1]),points.length===1&&context.lineTo(first[0],first[1]);for(let index=1;index<points.length;index+=1){let point=points[index];point!==void 0&&context.lineTo(point[0],point[1])}context.stroke()}}}async function registerClinicSignature(canvas,controller,signal,fetchImpl=fetch){return uploadClinicSignature(await canvasPng(canvas,signal),controller,signal,fetchImpl)}async function captureClinicSignature(canvas,controller,signal,fetchImpl=fetch){let png=await canvasPng(canvas,signal);try{return await uploadClinicSignature(png,controller,signal,fetchImpl)}catch(error){if(!isSignatureUploadLegFailure(error)||signal.aborted)throw failure()}let inline=await blobBase64(png);if(!inlineSignatureFits(inline)||signal.aborted)throw failure();return{signaturePngBase64:inline}}var failure=()=>new Error("Signature upload failed");async function canvasPng(canvas,signal){let png=await new Promise(resolve=>canvas.toBlob(resolve,"image/png"));if(!png||!png.size||png.size>2*1024*1024||signal.aborted)throw failure();return png}async function uploadClinicSignature(png,controller,signal,fetchImpl){let initiated=await controller.initiateSignatureUpload(png.size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw failure();let body=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))body.append(key,value);body.append("file",png,"signature.png");let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,9e4);try{if(!(await fetchImpl(initiated.value.uploadUrl,{method:"POST",body:body,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:uploadAbort.signal})).ok||signal.aborted)throw failure()}catch{throw signal.aborted?failure():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw failure();return{signatureId:completed.value}}function blobBase64(blob){return new Promise((resolve,reject)=>{let reader=new FileReader;reader.onload=()=>{let url=typeof reader.result=="string"?reader.result:"",comma=url.indexOf(",");comma<0?reject(failure()):resolve(url.slice(comma+1))},reader.onerror=()=>reject(failure()),reader.readAsDataURL(blob)})}var MIN_DRAWN_POINTS=8,DEFAULT_PAD_WIDTH=480,DEFAULT_PAD_HEIGHT=160;function useSignatureCanvas(onEdit){let canvas=useRef(null),drawing=useRef(false),strokes=useRef([]),[mode,setMode]=useState("draw"),[typed,setTypedValue]=useState(""),[signed,setSigned]=useState(false),typedRef=useRef(typed);typedRef.current=typed;let repaint=useCallback(()=>{let element=canvas.current,ctx=element?.getContext("2d");if(!element||!ctx)return;let ratio=typeof window<"u"&&window.devicePixelRatio||1;ctx.setTransform(ratio,0,0,ratio,0,0);let width=element.width/ratio,height=element.height/ratio;if(typedRef.current.trim().length>0){ctx.fillStyle="#111",paintClinicTypedSignature(ctx,typedRef.current,width,height);return}ctx.lineWidth=2,ctx.lineCap="round",ctx.lineJoin="round",ctx.strokeStyle="#111",paintSignatureStrokes(ctx,strokes.current,width,height)},[]);useEffect(()=>{let element=canvas.current;if(!element)return;let resize=()=>{let rect=element.getBoundingClientRect(),ratio=typeof window<"u"&&window.devicePixelRatio||1,width=Math.max(1,Math.round((rect.width||element.clientWidth||DEFAULT_PAD_WIDTH)*ratio)),height=Math.max(1,Math.round((rect.height||element.clientHeight||DEFAULT_PAD_HEIGHT)*ratio));element.width!==width&&(element.width=width),element.height!==height&&(element.height=height),repaint()};if(resize(),typeof ResizeObserver>"u")return;let observer=new ResizeObserver(resize);return observer.observe(element),()=>observer.disconnect()},[repaint]);let clear=useCallback(()=>{onEdit?.(),strokes.current=[],setSigned(false),setTypedValue(""),typedRef.current="",repaint()},[onEdit,repaint]),point=event=>{let rect=event.currentTarget.getBoundingClientRect();return[event.clientX-rect.left,event.clientY-rect.top]},countPoints=()=>strokes.current.reduce((total,stroke)=>total+stroke.length,0);return{canvas:canvas,mode:mode,typed:typed,signed:signed,clear:clear,setTyped(value){onEdit?.(),setTypedValue(value),typedRef.current=value,setSigned(!!value.trim()),repaint()},toggle(){clear(),setMode(m=>m==="draw"?"type":"draw")},onPointerDown(event){mode==="draw"&&(onEdit?.(),drawing.current=true,event.currentTarget.setPointerCapture(event.pointerId),strokes.current=[...strokes.current,[point(event)]],repaint())},onPointerMove(event){if(!drawing.current||mode!=="draw")return;let current=strokes.current[strokes.current.length-1];current!==void 0&&(strokes.current=[...strokes.current.slice(0,-1),[...current,point(event)]],repaint(),setSigned(countPoints()>=MIN_DRAWN_POINTS))},onPointerUp(){drawing.current=false},register(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):registerClinicSignature(canvas.current,controller,signal)},capture(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):captureClinicSignature(canvas.current,controller,signal)}}}function SignatureCanvas({pad:pad,disabled:disabled}){let theme=useEverfurTheme(),typedName=pad.mode==="type"?pad.typed.trim():"",field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},button={...field,cursor:"pointer"};/* @__PURE__ */
|
|
219
|
+
/* @__PURE__ */jsx("span",{style:styles.rowDetail,children:step.body})]})]},step.title))})]})}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}var MAX_INLINE_SIGNATURE_BASE64=2*1024*1024;function inlineSignatureFits(base64){return base64.length>0&&base64.length<=MAX_INLINE_SIGNATURE_BASE64}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 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)}}}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}}function paintClinicTypedSignature(context,name,width,height){context.clearRect(0,0,width,height);let text3=name.trim();if(!text3)return;let maxWidth=Math.max(1,width-32),size=Math.min(44,Math.max(16,Math.round(height*.34))),font=()=>{context.font=`italic 700 ${size}px Georgia, "Times New Roman", serif`};for(font();size>12&&context.measureText(text3).width>maxWidth;)size-=2,font();context.textAlign="center",context.textBaseline="middle",context.fillText(text3,width/2,height/2,maxWidth)}function paintSignatureStrokes(context,strokes,width,height){context.clearRect(0,0,width,height);for(let points of strokes){let first=points[0];if(first!==void 0){context.beginPath(),context.moveTo(first[0],first[1]),points.length===1&&context.lineTo(first[0],first[1]);for(let index=1;index<points.length;index+=1){let point=points[index];point!==void 0&&context.lineTo(point[0],point[1])}context.stroke()}}}async function registerClinicSignature(canvas,controller,signal,fetchImpl=fetch){return uploadClinicSignature(await canvasPng(canvas,signal),controller,signal,fetchImpl)}async function captureClinicSignature(canvas,controller,signal,fetchImpl=fetch){let png=await canvasPng(canvas,signal);try{return await uploadClinicSignature(png,controller,signal,fetchImpl)}catch(error){if(!isSignatureUploadLegFailure(error)||signal.aborted)throw failure()}let inline=await blobBase64(png);if(!inlineSignatureFits(inline)||signal.aborted)throw failure();return{signaturePngBase64:inline}}var failure=()=>new Error("Signature upload failed");async function canvasPng(canvas,signal){let png=await new Promise(resolve=>canvas.toBlob(resolve,"image/png"));if(!png||!png.size||png.size>2*1024*1024||signal.aborted)throw failure();return png}async function uploadClinicSignature(png,controller,signal,fetchImpl){let initiated=await controller.initiateSignatureUpload(png.size);if(!initiated.ok||signal.aborted||!trustedSignatureUploadUrl(initiated.value.uploadUrl))throw failure();let body=new FormData;for(let[key,value]of Object.entries(initiated.value.uploadFields))body.append(key,value);body.append("file",png,"signature.png");let uploadAbort=new AbortController,onAbort=()=>uploadAbort.abort();signal.addEventListener("abort",onAbort,{once:true});let timer=setTimeout(onAbort,9e4);try{if(!(await fetchImpl(initiated.value.uploadUrl,{method:"POST",body:body,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",signal:uploadAbort.signal})).ok||signal.aborted)throw failure()}catch{throw signal.aborted?failure():new SignatureUploadLegError}finally{clearTimeout(timer),signal.removeEventListener("abort",onAbort)}let completed=await controller.completeSignatureUpload(initiated.value.uploadId);if(!completed.ok||signal.aborted)throw failure();return{signatureId:completed.value}}function blobBase64(blob){return new Promise((resolve,reject)=>{let reader=new FileReader;reader.onload=()=>{let url=typeof reader.result=="string"?reader.result:"",comma=url.indexOf(",");comma<0?reject(failure()):resolve(url.slice(comma+1))},reader.onerror=()=>reject(failure()),reader.readAsDataURL(blob)})}var MIN_DRAWN_POINTS=8,DEFAULT_PAD_WIDTH=480,DEFAULT_PAD_HEIGHT=160;function useSignatureCanvas(onEdit){let canvas=useRef(null),drawing=useRef(false),strokes=useRef([]),[mode,setMode]=useState("draw"),[typed,setTypedValue]=useState(""),[signed,setSigned]=useState(false),typedRef=useRef(typed);typedRef.current=typed;let repaint=useCallback(()=>{let element=canvas.current,ctx=element?.getContext("2d");if(!element||!ctx)return;let ratio=typeof window<"u"&&window.devicePixelRatio||1;ctx.setTransform(ratio,0,0,ratio,0,0);let width=element.width/ratio,height=element.height/ratio;if(typedRef.current.trim().length>0){ctx.fillStyle="#111",paintClinicTypedSignature(ctx,typedRef.current,width,height);return}ctx.lineWidth=2,ctx.lineCap="round",ctx.lineJoin="round",ctx.strokeStyle="#111",paintSignatureStrokes(ctx,strokes.current,width,height)},[]);useEffect(()=>{let element=canvas.current;if(!element)return;let resize=()=>{let rect=element.getBoundingClientRect(),ratio=typeof window<"u"&&window.devicePixelRatio||1,width=Math.max(1,Math.round((rect.width||element.clientWidth||DEFAULT_PAD_WIDTH)*ratio)),height=Math.max(1,Math.round((rect.height||element.clientHeight||DEFAULT_PAD_HEIGHT)*ratio));element.width!==width&&(element.width=width),element.height!==height&&(element.height=height),repaint()};if(resize(),typeof ResizeObserver>"u")return;let observer=new ResizeObserver(resize);return observer.observe(element),()=>observer.disconnect()},[repaint]);let clear=useCallback(()=>{onEdit?.(),strokes.current=[],setSigned(false),setTypedValue(""),typedRef.current="",repaint()},[onEdit,repaint]),point=event=>{let rect=event.currentTarget.getBoundingClientRect();return[event.clientX-rect.left,event.clientY-rect.top]},countPoints=()=>strokes.current.reduce((total,stroke)=>total+stroke.length,0);return{canvas:canvas,mode:mode,typed:typed,signed:signed,clear:clear,setTyped(value){onEdit?.(),setTypedValue(value),typedRef.current=value,setSigned(!!value.trim()),repaint()},toggle(){clear(),setMode(m=>m==="draw"?"type":"draw")},onPointerDown(event){mode==="draw"&&(onEdit?.(),drawing.current=true,event.currentTarget.setPointerCapture(event.pointerId),strokes.current=[...strokes.current,[point(event)]],repaint())},onPointerMove(event){if(!drawing.current||mode!=="draw")return;let current=strokes.current[strokes.current.length-1];current!==void 0&&(strokes.current=[...strokes.current.slice(0,-1),[...current,point(event)]],repaint(),setSigned(countPoints()>=MIN_DRAWN_POINTS))},onPointerUp(){drawing.current=false},register(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):registerClinicSignature(canvas.current,controller,signal)},capture(controller,signal){return!canvas.current||!signed?Promise.reject(new Error("Signature upload failed")):captureClinicSignature(canvas.current,controller,signal)}}}function SignatureCanvas({pad:pad,disabled:disabled}){let theme=useEverfurTheme(),typedName=pad.mode==="type"?pad.typed.trim():"",field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},inputSlot=slotCss(theme.slots.input,1),button={...field,cursor:"pointer"};/* @__PURE__ */
|
|
219
220
|
return jsxs("div",{children:[
|
|
220
221
|
/* @__PURE__ */jsx("p",{style:{margin:`0 0 ${theme.space.sm}px`},children:pad.mode==="draw"?CLINIC_REQUEST_COPY.draw:CLINIC_REQUEST_COPY.type}),
|
|
221
|
-
/* @__PURE__ */jsx("button",{type:"button",style:{...button,alignSelf:"flex-start",marginBottom:theme.space.sm,textDecoration:"underline"},disabled:disabled,onClick:pad.toggle,"data-testid":"records-consent-sign-mode-toggle",children:pad.mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw}),pad.mode==="type"&&/* @__PURE__ */jsx("input",{"aria-label":CLINIC_REQUEST_COPY.type,style:{...field,display:"block",width:"100%",boxSizing:"border-box"},maxLength:TYPED_SIGNATURE_MAX_LENGTH,value:pad.typed,disabled:disabled,autoComplete:"off",onChange:event=>pad.setTyped(event.target.value)}),
|
|
222
|
+
/* @__PURE__ */jsx("button",{type:"button",style:{...button,alignSelf:"flex-start",marginBottom:theme.space.sm,textDecoration:"underline"},disabled:disabled,onClick:pad.toggle,"data-testid":"records-consent-sign-mode-toggle",children:pad.mode==="draw"?CLINIC_REQUEST_COPY.toType:CLINIC_REQUEST_COPY.toDraw}),pad.mode==="type"&&/* @__PURE__ */jsx("input",{"aria-label":CLINIC_REQUEST_COPY.type,style:{...field,display:"block",width:"100%",boxSizing:"border-box",...inputSlot},maxLength:TYPED_SIGNATURE_MAX_LENGTH,value:pad.typed,disabled:disabled,autoComplete:"off",onChange:event=>pad.setTyped(event.target.value)}),
|
|
222
223
|
/* @__PURE__ */jsx("canvas",{ref:pad.canvas,role:"img","aria-label":typedName.length>0?CLINIC_REQUEST_COPY.typedSignatureA11y(typedName):CLINIC_REQUEST_COPY.sign,style:{display:"block",width:"100%",height:160,maxWidth:"100%",boxSizing:"border-box",touchAction:"none",background:"#fff",border:`1px solid ${theme.color.borderHairlineGreen}`,...disabled?{opacity:.6,pointerEvents:"none"}:{},...pad.mode==="type"?{pointerEvents:"none"}:{}},onPointerDown:event=>{disabled||pad.onPointerDown(event)},onPointerMove:event=>{disabled||pad.onPointerMove(event)},onPointerUp:pad.onPointerUp,onPointerCancel:pad.onPointerUp}),
|
|
223
224
|
/* @__PURE__ */jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm,marginTop:theme.space.sm},children:[
|
|
224
225
|
/* @__PURE__ */jsx("p",{style:{margin:0,fontSize:theme.type.size.tiny,color:theme.color.text.muted},"data-testid":"records-signature-hint",children:pad.signed||pad.mode==="type"?" ":CLINIC_REQUEST_COPY.drawHint}),pad.mode==="type"?null:/* @__PURE__ */jsx("button",{type:"button",style:button,disabled:disabled,onClick:pad.clear,"aria-label":CLINIC_REQUEST_COPY.clearA11y,"data-testid":"records-signature-clear",children:CLINIC_REQUEST_COPY.clear})]})]})}function EverfurClinicRequestBatch(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
225
|
-
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function BatchBody(props){let runtimeController=useEverfurRecordsClinic(),runtimeBatch=useEverfurRecordsClinicBatch(),controller=props.controller??runtimeController,theme=useEverfurTheme(),pad=useSignatureCanvas(),form=useClinicBatchForm(props,controller,props.batchClient??runtimeBatch,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null)),signed=props.onCaptureSignature!==void 0||pad.signed,field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},input={...field,display:"block",width:"100%",boxSizing:"border-box"},button={...field,cursor:"pointer"},muted={margin:0,color:theme.color.text.muted,fontSize:theme.type.size.bodyTight},clinicLabel=clinic=>[clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),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;/* @__PURE__ */
|
|
226
|
+
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx("p",{role:"alert",children:RECORDS_COPY.sessionRequired}):/* @__PURE__ */jsx(BatchBody,{...guardHostProps(props,["onClose","onCreated"])},JSON.stringify([userRef,scopeEpoch,props.petRef,props.petName]))})}function BatchBody(props){let runtimeController=useEverfurRecordsClinic(),runtimeBatch=useEverfurRecordsClinicBatch(),controller=props.controller??runtimeController,theme=useEverfurTheme(),pad=useSignatureCanvas(),form=useClinicBatchForm(props,controller,props.batchClient??runtimeBatch,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null)),signed=props.onCaptureSignature!==void 0||pad.signed,field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},input={...field,display:"block",width:"100%",boxSizing:"border-box",...slotCss(theme.slots.input,1)},button={...field,cursor:"pointer"},muted={margin:0,color:theme.color.text.muted,fontSize:theme.type.size.bodyTight},clinicLabel=clinic=>[clinic.name,clinic.address,clinic.phone].filter(Boolean).join(", "),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;/* @__PURE__ */
|
|
226
227
|
return jsxs("section",{className:props.className,"aria-label":title,style:{...SURFACE_ROOT_RESET,background:theme.color.surface,color:theme.color.text.primary,padding:theme.space.lg,borderRadius:theme.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...props.style},children:[
|
|
227
228
|
/* @__PURE__ */jsx("h2",{style:{margin:0,fontSize:theme.type.size.heading},children:title}),
|
|
228
229
|
/* @__PURE__ */jsx("p",{style:{margin:`${theme.space.sm}px 0 ${theme.space.lg}px`},children:props.petName}),form.outcome?/* @__PURE__ */jsxs("div",{style:{display:"grid",gap:theme.space.sm},"data-testid":"records-batch-result",children:[
|
|
@@ -259,7 +260,7 @@ return jsxs("div",{className:className,style:{...styles.root,...style},"data-tes
|
|
|
259
260
|
/* @__PURE__ */jsx("p",{style:styles.subLead,"data-testid":"records-consent-lead",children:RECORDS_CONSENT_COPY.leadWeb(petName)}),
|
|
260
261
|
/* @__PURE__ */jsxs("div",{ref:rise,style:{...styles.body,...styles.content,gap:theme.space.lg+theme.space.xs/2},"data-testid":"records-consent",children:[
|
|
261
262
|
/* @__PURE__ */jsxs("section",{style:styles.creamCard,"aria-label":RECORDS_CONSENT_COPY.scopeHeading,children:[
|
|
262
|
-
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:RECORDS_CONSENT_COPY.scopeHeading}),
|
|
263
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk,...styles.cardInk},children:RECORDS_CONSENT_COPY.scopeHeading}),
|
|
263
264
|
/* @__PURE__ */jsx("p",{style:styles.bodyText,children:RECORDS_CONSENT_COPY.scopeBody}),
|
|
264
265
|
/* @__PURE__ */jsx("ul",{style:{...styles.plainList,gap:theme.space.sm},children:RECORDS_CONSENT_COPY.whatWeDo.map(line=>/* @__PURE__ */jsxs("li",{style:{...styles.bodyText,display:"flex",gap:theme.space.sm},children:[
|
|
265
266
|
/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{color:theme.color.brandInk,...faceCss(theme,"bold")},children:"✓"}),
|
|
@@ -282,8 +283,8 @@ return jsx("button",{type:"button",onClick:()=>form.pickReuseSignature(selected?
|
|
|
282
283
|
/* @__PURE__ */jsx("p",{style:styles.muted,children:RECORDS_CONSENT_COPY.reuseHint})]}):null,
|
|
283
284
|
/* @__PURE__ */jsx(SignatureCanvas,{pad:pad,disabled:busy}),
|
|
284
285
|
/* @__PURE__ */jsx("p",{style:styles.muted,children:RECORDS_CONSENT_COPY.signatureHint(form.clinicName)}),form.signatureLastMissing?/* @__PURE__ */jsx("p",{style:styles.muted,"data-testid":"records-consent-signature-required",children:RECORDS_CONSENT_COPY.missingSignatureError}):null]}),
|
|
285
|
-
/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0},"aria-label":RECORDS_CONSENT_COPY.whatHappensNext,"data-testid":"records-consent-next",children:[
|
|
286
|
-
/* @__PURE__ */jsx("h3",{style:styles.sectionTitle,children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
286
|
+
/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surfaceSubtle,border:0,...styles.cardSlot},"aria-label":RECORDS_CONSENT_COPY.whatHappensNext,"data-testid":"records-consent-next",children:[
|
|
287
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,...styles.cardInk},children:RECORDS_CONSENT_COPY.whatHappensNext}),
|
|
287
288
|
/* @__PURE__ */jsx("p",{style:styles.bodyText,children:RECORDS_CONSENT_COPY.whatHappensNextBody})]}),form.error?/* @__PURE__ */jsx("p",{role:"alert","aria-live":"assertive",style:styles.errorBanner,children:form.error}):null,form.created?/* @__PURE__ */jsx("p",{role:"status",style:styles.bodyText,children:form.created.statusLabel||RECORDS_COPY.records}):null]}),
|
|
288
289
|
/* @__PURE__ */jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm,padding:`${theme.space.md}px ${theme.space.lg}px ${theme.space.xxl}px`,borderTop:`1px solid ${theme.color.borderHairlineGreen}`,backgroundColor:theme.color.background},children:[onBack?/* @__PURE__ */jsx(Pill,{label:BACK_LABEL,kind:"link",disabled:busy,onClick:onBack,style:{flex:"0 0 auto"},testID:"records-consent-cancel"}):null,
|
|
289
290
|
/* @__PURE__ */jsx(Pill,{label:busy?RECORDS_CONSENT_COPY.submitting:RECORDS_CONSENT_COPY.submit,disabled:!form.ready,busy:busy,onClick:()=>{form.submit()},style:{flex:"1 1 12rem",minWidth:0,minHeight:54},testID:"records-consent-submit"})]}),
|
|
@@ -305,31 +306,31 @@ return jsxs("section",{"aria-label":DEPTH_COPY.timeline,style:styles.timelineLis
|
|
|
305
306
|
return jsxs("section",{"aria-label":RECORDS_COPY.records,style:styles.list,children:[view.document?.receivedAt?/* @__PURE__ */jsx("p",{style:styles.rowDetail,children:formatRecordsDate(view.document.receivedAt)}):null,
|
|
306
307
|
/* @__PURE__ */jsx("dl",{style:styles.card,children:view.contributions.map(entity=>/* @__PURE__ */jsxs("div",{style:styles.row,children:[
|
|
307
308
|
/* @__PURE__ */jsx("dt",{style:styles.rowTitle,children:entity.label}),
|
|
308
|
-
/* @__PURE__ */jsx("dd",{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsx("dd",{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useDepthTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles3(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),cardText=slotText(slots.recordCard),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),hairline=`1px solid ${color.brandBorder}`,errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT2,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT2,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:radius.pill,border:`3px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},section:{display:"flex",flexDirection:"column",gap:space.sm},heading:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:space.sm,margin:0,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...slotBoxCss(slots.recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:space.sm},row:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},date:inCard(type.size.caption,type.lineHeight.normal,color.text.muted),rowTitle:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"bold")},rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),rowMuted:{...inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),alignSelf:"flex-start",padding:`${space.xs}px ${space.sm}px`,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:space.xxl},timelineBand:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:`${space.xs}px ${space.lg}px ${space.md}px`},timelineSeparated:{borderTop:`1px solid ${color.brandBorder}`,marginLeft:TIMELINE_SEPARATOR_INSET,paddingLeft:0},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:radius.pill,backgroundColor:color.brandSoft,border:hairline},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1,minWidth:0},timelineKind:{...faceCss(theme,"mono"),fontSize:type.size.micro,lineHeight:`${type.size.bodyTight}px`,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(type.size.body,type.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])}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,isDevelopment2){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment2()===!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,isDevelopment2){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment2)},[consentVersion,consentText,isDevelopment2])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face=>(fonts.add(face),!0)).catch(()=>!1)}catch{}loads.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face of FACES){let url=fontUrls[face];url!=null&&loadBrandFont(families[face],url,namedFaces[face]?weight.regular:weight[FACE_WEIGHT[face]])}},[families,fontUrls,weight,namedFaces])}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});var isDevelopment=()=>webThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment)}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."});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 pct=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:`${pct}%`;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 PDF_SIGNATURE=[37,80,68,70,45],JPEG_SIGNATURE=[255,216,255],PNG_SIGNATURE=[137,80,78,71,13,10,26,10],HEAD_BYTES=12,BMFF_BRANDS=/* @__PURE__ */Object.freeze({heic:"image/heic",heix:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif"}),RECORDS_DOCUMENT_ACCEPT="application/pdf,.pdf",PHOTO_ACCEPT=/* @__PURE__ */Object.freeze({"image/jpeg":"image/jpeg,.jpg,.jpeg","image/png":"image/png,.png","image/heic":"image/heic,.heic","image/heif":"image/heif,.heif"});function recordsDocumentAccept(types){let photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>isAcceptedUploadType(type,types));return[RECORDS_DOCUMENT_ACCEPT,...photos.map(type=>PHOTO_ACCEPT[type])].join(",")}var NOT_A_PDF="application/octet-stream",WEB_FILE_URI="file:web-document";async function readHead(blob,length){let head=blob.slice(0,length);try{return typeof head.arrayBuffer=="function"?new Uint8Array(await head.arrayBuffer()):await new Promise(resolve=>{let reader=new FileReader;reader.onload=()=>{resolve(reader.result instanceof ArrayBuffer?new Uint8Array(reader.result):new Uint8Array)},reader.onerror=()=>resolve(new Uint8Array),reader.readAsArrayBuffer(head)})}catch{return new Uint8Array}}async function isPdfBlob(blob){if(blob.size<PDF_SIGNATURE.length)return false;let head=await readHead(blob,PDF_SIGNATURE.length);return startsWith(head,PDF_SIGNATURE)}function startsWith(head,signature,offset=0){return head.length>=offset+signature.length&&signature.every((byte,index)=>head[offset+index]===byte)}function photoTypeOf(head){return startsWith(head,JPEG_SIGNATURE)?"image/jpeg":startsWith(head,PNG_SIGNATURE)?"image/png":head.length>=HEAD_BYTES&&String.fromCharCode(...head.slice(4,8))==="ftyp"?BMFF_BRANDS[String.fromCharCode(...head.slice(8,12))]??null:null}async function detectedType(blob,types){if(await isPdfBlob(blob))return RECORDS_UPLOAD_CONTENT_TYPE;if(!RECORDS_PHOTO_CONTENT_TYPES.some(type=>isAcceptedUploadType(type,types)))return null;let photo=photoTypeOf(await readHead(blob,HEAD_BYTES));return photo!==null&&isAcceptedUploadType(photo,types)?photo:null}async function fileToHandle(file,types){let detected=await detectedType(file,types),rawName=file.name,name=typeof rawName=="string"?rawName:void 0;/* @__PURE__ */
|
|
309
|
+
/* @__PURE__ */jsx("dd",{style:styles.rowValue,children:formatEntityValue(entity.value,entity.unit)}),entity.observedAt?/* @__PURE__ */jsx("dd",{style:styles.rowDetail,children:formatRecordsDate(entity.observedAt)}):null]},entity.key))})]})}function useDepthTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles3(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles3(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),recordCard=recordCardSlot(slots),cardText=slotText(recordCard),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),hairline=`1px solid ${color.brandBorder}`,errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT2,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT2,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:24,height:24,borderRadius:radius.pill,border:`3px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{boxSizing:"border-box",width:40,height:40,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET2,minWidth:MIN_TOUCH_TARGET2,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},section:{display:"flex",flexDirection:"column",gap:space.sm},heading:{...text3(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold")},card:{boxSizing:"border-box",listStyle:"none",display:"flex",flexDirection:"column",gap:space.sm,margin:0,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...slotBoxCss(recordCard,1)},plainList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:space.sm},row:{display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},topLine:{display:"flex",justifyContent:"space-between",gap:space.md},kindLabel:{...inCard(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},date:inCard(type.size.caption,type.lineHeight.normal,color.text.muted),rowTitle:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"bold")},rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowDetail:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),rowMuted:{...inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),opacity:.7},chip:{...text3(type.size.caption,type.lineHeight.normal,color.text.primary),alignSelf:"flex-start",padding:`${space.xs}px ${space.sm}px`,borderRadius:radius.pill},chipNeutral:{backgroundColor:color.badgeBgNeutral},chipCaution:{backgroundColor:color.badgeBgCaution},chipCritical:{backgroundColor:color.badgeBgCritical},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted),timelineList:{display:"flex",flexDirection:"column",paddingBottom:space.xxl},timelineBand:{...text3(type.size.caption,type.lineHeight.normal,color.text.secondary),borderRadius:radius.md-space.xs/2,padding:space.md,backgroundColor:color.brandSoft,margin:`${space.xs}px ${space.lg}px ${space.md}px`,...slotCss(slots.banner)},timelineSeparated:{borderTop:`1px solid ${color.brandBorder}`,marginLeft:TIMELINE_SEPARATOR_INSET,paddingLeft:0},timelineRow:{display:"flex",gap:space.md,padding:`${space.md+space.xs/2}px ${space.lg}px`},timelineBubble:{boxSizing:"border-box",flexShrink:0,width:34,height:34,borderRadius:radius.pill,backgroundColor:color.brandSoft,border:hairline},timelineBody:{flex:1,display:"flex",flexDirection:"column",gap:space.xs-1,minWidth:0},timelineKind:{...faceCss(theme,"mono"),fontSize:type.size.micro,lineHeight:`${type.size.bodyTight}px`,letterSpacing:type.letterSpacing.eyebrow/3,textTransform:"uppercase",color:color.text.secondary},timelineTitle:{...text3(type.size.body,type.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])}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,isDevelopment2){if(warned||!isConsentTextMissing(consentVersion,consentText))return;let development=false;try{development=isDevelopment2()===!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,isDevelopment2){useEffect(()=>{warnIfConsentTextMissing(consentVersion,consentText,isDevelopment2)},[consentVersion,consentText,isDevelopment2])}function isWebDevelopment(){try{return process.env.NODE_ENV!=="production"}catch{return false}}var URL_MAX_LENGTH=2048;function fontSourceUrl(value){if(typeof value!="string")return null;let trimmed=value.trim();return trimmed.length===0||trimmed.length>URL_MAX_LENGTH?null:/^https:\/\/[^\s"'()\\<>]+$/i.test(trimmed)?trimmed:null}var loads=/* @__PURE__ */new Map,warned2=/* @__PURE__ */new Set,useBeforePaintEffect=typeof document>"u"?useEffect:useLayoutEffect;function keyOf(source){return source.cssSrc!==void 0?`css\n${source.cssSrc}`:`file\n${source.family}\n${source.src??""}\n${source.weight??"400"}\n${source.style??"normal"}`}function warnOnce(source,warn){if(!warn)return;let url=source.cssSrc??source.src??"",message=`[everfur] A font in appearance.fonts did not load: "${source.family}" from ${url}. The text renders in the fallback font. If your page sets a Content-Security-Policy, allow this host in font-src`+(source.cssSrc!==void 0?" and style-src (and the font files the stylesheet names in font-src).":".");if(!warned2.has(message)){warned2.add(message);try{globalThis.console?.warn?.(message)}catch{}}}function existingLink(href){let links=document.getElementsByTagName("link");for(let index=0;index<links.length;index+=1){let link=links[index];if(link.rel==="stylesheet"&&link.getAttribute("href")===href)return link}return null}function loadStylesheet(href){return existingLink(href)!==null?Promise.resolve(true):new Promise(resolve=>{let link=document.createElement("link");link.rel="stylesheet",link.href=href,link.setAttribute("data-everfur-font",""),link.addEventListener("load",()=>resolve(true)),link.addEventListener("error",()=>resolve(false)),document.head.appendChild(link)})}function loadFile(source){let fonts=document.fonts;return new FontFace(source.family,`url("${source.src}")`,{display:"swap",weight:source.weight??"400",style:source.style??"normal"}).load().then(face=>(fonts.add(face),true)).catch(()=>false)}function loadFontSource(source,warn=false){let key=keyOf(source),load=loads.get(key);if(load===void 0){load=Promise.resolve(false);try{if(typeof document<"u"){let css=source.cssSrc===void 0?null:fontSourceUrl(source.cssSrc),src=source.src===void 0?null:fontSourceUrl(source.src);css!==null?load=loadStylesheet(css):src!==null&&(load=loadFile({...source,src:src}))}}catch{load=Promise.resolve(false)}let settled=load.then(ok2=>(ok2||warnOnce(source,warn),ok2));loads.set(key,settled),load=settled}return load}function useFontSources(theme,isDevelopment2){let sources=theme.type.fontSources;useBeforePaintEffect(()=>{if(sources.length===0)return;let warn=false;try{warn=isDevelopment2()}catch{}for(let source of sources)loadFontSource(source,warn)},[sources,isDevelopment2])}var BRAND_FONT_URL=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function isBrandFontUrl(url){return BRAND_FONT_URL.test(url)&&!url.includes("..")}var loads2=/* @__PURE__ */new Map;function loadBrandFont(family,fontUrl,weight="400"){let name=family.trim(),key=`${name}\n${fontUrl}\n${weight}`,load=loads2.get(key);if(load===void 0){if(load=Promise.resolve(false),fontUrl!==null&&name!==""&&name!=="System"&&isBrandFontUrl(fontUrl))try{let fonts=document.fonts;load=new FontFace(name,`url("${fontUrl}") format("woff2")`,{display:"swap",weight:weight}).load().then(face=>(fonts.add(face),!0)).catch(()=>!1)}catch{}loads2.set(key,load)}return load}var FACES=["regular","medium","bold","mono","monoMedium","monoBold"];function useBrandFont(theme){let{families:families,fontUrls:fontUrls,weight:weight,namedFaces:namedFaces}=theme.type;useEffect(()=>{for(let face of FACES){let url=fontUrls[face];url!=null&&loadBrandFont(families[face],url,namedFaces[face]?weight.regular:weight[FACE_WEIGHT[face]])}},[families,fontUrls,weight,namedFaces]),useFontSources(theme,isWebDevelopment)}function queryFor(query){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(query)??null}catch{return null}}function subscribeTo(query){return onChange=>{let mql=queryFor(query);return mql===null||typeof mql.addEventListener!="function"?()=>{}:(mql.addEventListener("change",onChange),()=>mql.removeEventListener?.("change",onChange))}}var DARK="(prefers-color-scheme: dark)",LIGHT="(prefers-color-scheme: light)",REDUCED_MOTION="(prefers-reduced-motion: reduce)",MORE_CONTRAST="(prefers-contrast: more)",subscribeDark=subscribeTo(DARK),subscribeReducedMotion=subscribeTo(REDUCED_MOTION),subscribeMoreContrast=subscribeTo(MORE_CONTRAST);function readColorScheme(){let dark=queryFor(DARK);return dark===null?null:dark.matches?"dark":queryFor(LIGHT)?.matches?"light":null}function readReducedMotion(){return queryFor(REDUCED_MOTION)?.matches===true}function readMoreContrast(){return queryFor(MORE_CONTRAST)?.matches===true}var DEFAULT_FONT_PX=16,frameDocument2=false;var cachedScale=null;function fontPx(element){return Number.parseFloat(window.getComputedStyle(element).fontSize)}function probeDefaultPx(){let parent=document.body??document.documentElement,probe=document.createElement("span");probe.setAttribute("aria-hidden","true"),probe.style.setProperty("position","absolute","important"),probe.style.setProperty("visibility","hidden","important"),probe.style.setProperty("font-size","medium","important"),parent.appendChild(probe);try{return fontPx(probe)}finally{probe.remove()}}function measureTextScale(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let px=frameDocument2?fontPx(document.documentElement):probeDefaultPx();return Number.isFinite(px)&&px>0?px/DEFAULT_FONT_PX:1}catch{return 1}}function readTextScale(){return cachedScale===null&&(cachedScale=measureTextScale()),cachedScale}function subscribeTextScale(onChange){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let onResize=()=>{cachedScale=null,onChange()};return window.addEventListener("resize",onResize),()=>window.removeEventListener("resize",onResize)}function useWebColorScheme(){return useSyncExternalStore(subscribeDark,readColorScheme,()=>null)}function useWebReducedMotion(){return useSyncExternalStore(subscribeReducedMotion,readReducedMotion,()=>false)}function useWebHighContrast(){return useSyncExternalStore(subscribeMoreContrast,readMoreContrast,()=>false)}function useWebTextScale(){return useSyncExternalStore(subscribeTextScale,readTextScale,()=>1)}var webThemeSeams=/* @__PURE__ */Object.freeze({useColorScheme:useWebColorScheme,useReducedMotion:useWebReducedMotion,useTextScale:useWebTextScale,useHighContrast:useWebHighContrast,scaleTypeSizes:true,useResolvedTheme:useBrandFont,isDevelopment:isWebDevelopment});var isDevelopment=()=>webThemeSeams.isDevelopment?.()===true;function useConsentTextWarning2(consentVersion,consentText){useConsentTextWarning(consentVersion,consentText,isDevelopment)}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."});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 pct=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:`${pct}%`;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 PDF_SIGNATURE=[37,80,68,70,45],JPEG_SIGNATURE=[255,216,255],PNG_SIGNATURE=[137,80,78,71,13,10,26,10],HEAD_BYTES=12,BMFF_BRANDS=/* @__PURE__ */Object.freeze({heic:"image/heic",heix:"image/heic",heim:"image/heic",heis:"image/heic",mif1:"image/heif",msf1:"image/heif"}),RECORDS_DOCUMENT_ACCEPT="application/pdf,.pdf",PHOTO_ACCEPT=/* @__PURE__ */Object.freeze({"image/jpeg":"image/jpeg,.jpg,.jpeg","image/png":"image/png,.png","image/heic":"image/heic,.heic","image/heif":"image/heif,.heif"});function recordsDocumentAccept(types){let photos=RECORDS_PHOTO_CONTENT_TYPES.filter(type=>isAcceptedUploadType(type,types));return[RECORDS_DOCUMENT_ACCEPT,...photos.map(type=>PHOTO_ACCEPT[type])].join(",")}var NOT_A_PDF="application/octet-stream",WEB_FILE_URI="file:web-document";async function readHead(blob,length){let head=blob.slice(0,length);try{return typeof head.arrayBuffer=="function"?new Uint8Array(await head.arrayBuffer()):await new Promise(resolve=>{let reader=new FileReader;reader.onload=()=>{resolve(reader.result instanceof ArrayBuffer?new Uint8Array(reader.result):new Uint8Array)},reader.onerror=()=>resolve(new Uint8Array),reader.readAsArrayBuffer(head)})}catch{return new Uint8Array}}async function isPdfBlob(blob){if(blob.size<PDF_SIGNATURE.length)return false;let head=await readHead(blob,PDF_SIGNATURE.length);return startsWith(head,PDF_SIGNATURE)}function startsWith(head,signature,offset=0){return head.length>=offset+signature.length&&signature.every((byte2,index)=>head[offset+index]===byte2)}function photoTypeOf(head){return startsWith(head,JPEG_SIGNATURE)?"image/jpeg":startsWith(head,PNG_SIGNATURE)?"image/png":head.length>=HEAD_BYTES&&String.fromCharCode(...head.slice(4,8))==="ftyp"?BMFF_BRANDS[String.fromCharCode(...head.slice(8,12))]??null:null}async function detectedType(blob,types){if(await isPdfBlob(blob))return RECORDS_UPLOAD_CONTENT_TYPE;if(!RECORDS_PHOTO_CONTENT_TYPES.some(type=>isAcceptedUploadType(type,types)))return null;let photo=photoTypeOf(await readHead(blob,HEAD_BYTES));return photo!==null&&isAcceptedUploadType(photo,types)?photo:null}async function fileToHandle(file,types){let detected=await detectedType(file,types),rawName=file.name,name=typeof rawName=="string"?rawName:void 0;/* @__PURE__ */
|
|
309
310
|
return Object.freeze({uri:WEB_FILE_URI,mimeType:detected??NOT_A_PDF,sizeBytes:file.size,blob:file,...name!==void 0?{name:name}:{}})}function isUploadableHandle(handle,types){let size=handle.sizeBytes;return isAcceptedUploadType(handle.mimeType,types)&&typeof size=="number"&&Number.isFinite(size)&&size>0&&size<=MAX_UPLOAD_BYTES}function pickDocument(doc=document,types){return new Promise(resolve=>{let input=doc.createElement("input");input.type="file",input.accept=recordsDocumentAccept(types),input.hidden=true;let done=()=>{input.remove()};input.addEventListener("change",()=>{let file=input.files?.[0];if(done(),file===void 0){resolve(null);return}fileToHandle(file,types).then(resolve)},{once:true}),input.addEventListener("cancel",()=>{done(),resolve(null)},{once:true}),doc.body.appendChild(input),input.click()})}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";function RequestTimeline({request:request,petName:petName}){let styles=useStyles2(),events=buildRequestTimeline(request,{petName:petName??null});
|
|
310
311
|
/* @__PURE__ */
|
|
311
|
-
return jsx("ol",{style:styles.list,"aria-label":REQUEST_SCREEN_COPY.timelineA11y,"data-testid":"records-timeline",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,title={...styles.title,...event.state==="current"?styles.titleCurrent:{},...event.state==="failed"?styles.titleFailed:{},...event.state==="upcoming"?styles.titleUpcoming:{}};/* @__PURE__ */
|
|
312
|
+
return jsx("ol",{style:styles.list,"aria-label":REQUEST_SCREEN_COPY.timelineA11y,"data-testid":"records-timeline",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,title={...styles.title,...event.state==="current"?styles.titleCurrent:{},...event.state==="failed"?styles.titleFailed:{},...event.state==="upcoming"?styles.titleUpcoming:{},...event.key==="ready"&&(event.state==="done"||event.state==="current")?styles.titleReady:{}};/* @__PURE__ */
|
|
312
313
|
return jsxs("li",{style:styles.row,"data-testid":`records-timeline-${event.key}`,children:[
|
|
313
314
|
/* @__PURE__ */jsxs("div",{style:styles.railColumn,"aria-hidden":"true",children:[
|
|
314
315
|
/* @__PURE__ */jsx(Dot,{state:event.state,styles:styles}),isLast?null:/* @__PURE__ */jsx("div",{style:{...styles.connector,...event.state==="done"?styles.connectorDone:{}}})]}),
|
|
315
316
|
/* @__PURE__ */jsxs("div",{style:styles.body,children:[
|
|
316
317
|
/* @__PURE__ */jsxs("div",{style:styles.titleRow,children:[
|
|
317
318
|
/* @__PURE__ */jsxs("span",{style:title,children:[event.title,event.state==="current"?/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:styles.now,children:NOW}):null]}),date&&event.at?/* @__PURE__ */jsx("time",{dateTime:event.at,style:styles.date,children:date}):null]}),event.detail?/* @__PURE__ */jsx("span",{style:{...styles.detail,...event.state==="upcoming"?styles.detailUpcoming:{}},children:event.detail}):null,
|
|
318
|
-
/* @__PURE__ */jsx("span",{style:styles.srOnly,children:A11Y_STATE[event.state]})]})]})}function Dot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotDone},children:"✓"}):state==="failed"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotFailed},children:"!"}):state==="current"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotCurrent},children:/* @__PURE__ */jsx("div",{style:styles.dotCurrentCore})}):/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotUpcoming}})}function useStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type,radius:radius}=theme,lh=size=>`${Math.round(size*type.lineHeight.snug)}px`,dot={boxSizing:"border-box",width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,display:"flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.caption,lineHeight:lh(type.size.caption)};return{list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",alignSelf:"stretch",width:DOT_SIZE,flexShrink:0},body:{flex:1,minWidth:0,paddingTop:space.xs/2,paddingBottom:space.lg+space.xs/2,display:"flex",flexDirection:"column",gap:space.xs/2},titleRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},dot:dot,dotDone:{backgroundColor:color.brand,color:color.onPrimary,border:`2px solid ${color.primaryEdge}`},dotFailed:{backgroundColor:color.danger,color:color.onDanger},dotCurrent:{border:`2px solid ${color.brandInk}`,backgroundColor:color.surface},dotCurrentCore:{width:10,height:10,borderRadius:5,backgroundColor:color.mark},dotUpcoming:{border:`2px solid ${color.structureEdge}`,backgroundColor:color.surface},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,margin:"2px 0"},connectorDone:{backgroundColor:color.primaryEdge},title:{flex:1,display:"flex",flexWrap:"wrap",alignItems:"center",gap:space.sm,...faceCss(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight),color:color.text.primary},titleCurrent:{color:color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...faceCss(theme,"regular")},date:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption),color:color.text.muted},detail:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted},now:{display:"inline-flex",alignItems:"center",minHeight:20,padding:`0 ${space.sm}px`,borderRadius:radius.pill,backgroundColor:color.highlight,color:color.onHighlight,...faceCss(theme,"monoBold"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny),letterSpacing:"0.06em",textTransform:"uppercase"},detailUpcoming:{opacity:.7},srOnly:{position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0}}}function isFinitePoint(point){return point.value!==null&&Number.isFinite(point.value)}function pointDisplay(point){return point.display!==null&&point.display.length>0?point.display:point.value!==null?String(point.value):""}function buildTrendModel(series){let primary=series.find(s=>s.points.some(isFinitePoint));if(primary===void 0)return null;let numeric2=primary.points.filter(isFinitePoint),first=numeric2[0];if(first===void 0)return null;let values=numeric2.map(p=>p.value),lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,xInset=6,count=numeric2.length,points=numeric2.map((p,index)=>({xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:(yMax-p.value)/span*100})),bandTopPct=(yMax-hi)/span*100,bandBottomPct=(yMax-lo)/span*100,minPoint=numeric2.reduce((acc,p)=>p.value<acc.value?p:acc,first),maxPoint=numeric2.reduce((acc,p)=>p.value>acc.value?p:acc,first),lastNumeric=numeric2[numeric2.length-1]??first,latest=primary.points[primary.points.length-1]??lastNumeric,latestDisplay=pointDisplay(latest),heroDisplay=latestDisplay.length>0?latestDisplay:pointDisplay(lastNumeric);return{label:primary.label,heroDisplay:heroDisplay,minDisplay:pointDisplay(minPoint),maxDisplay:pointDisplay(maxPoint),firstDate:formatShortDate(primary.points[0]?.at??null),lastDate:formatShortDate(latest.at),points:points,bandTopPct:bandTopPct,bandBottomPct:bandBottomPct}}function entityTypeOf(key){let separator=key.indexOf(":");return separator<=0?null:key.slice(0,separator)}function groupSeriesByEntityType(series,order,labelFor){let byType=/* @__PURE__ */new Map,firstSeen=[];for(let one of series){let type=entityTypeOf(one.key)??"",bucket=byType.get(type);bucket===void 0?(byType.set(type,[one]),firstSeen.push(type)):bucket.push(one)}let listed=order.filter(type=>byType.has(type)),rest=firstSeen.filter(type=>!listed.includes(type));/* @__PURE__ */
|
|
319
|
+
/* @__PURE__ */jsx("span",{style:styles.srOnly,children:A11Y_STATE[event.state]})]})]})}function Dot({state:state,styles:styles}){return state==="done"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotDone},children:"✓"}):state==="failed"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotFailed},children:"!"}):state==="current"?/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotCurrent},children:/* @__PURE__ */jsx("div",{style:styles.dotCurrentCore})}):/* @__PURE__ */jsx("div",{style:{...styles.dot,...styles.dotUpcoming}})}function useStyles2(){let theme=useEverfurTheme();return useMemo(()=>makeStyles4(theme),[theme])}function makeStyles4(theme){let{color:color,space:space,type:type,radius:radius}=theme,lh=size=>`${Math.round(size*type.lineHeight.snug)}px`,dot={boxSizing:"border-box",width:DOT_SIZE,height:DOT_SIZE,borderRadius:DOT_SIZE/2,display:"flex",alignItems:"center",justifyContent:"center",...faceCss(theme,"bold"),fontSize:type.size.caption,lineHeight:lh(type.size.caption)};return{list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{display:"flex",alignItems:"flex-start",gap:space.md},railColumn:{display:"flex",flexDirection:"column",alignItems:"center",alignSelf:"stretch",width:DOT_SIZE,flexShrink:0},body:{flex:1,minWidth:0,paddingTop:space.xs/2,paddingBottom:space.lg+space.xs/2,display:"flex",flexDirection:"column",gap:space.xs/2},titleRow:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:space.sm},dot:dot,dotDone:{backgroundColor:color.brand,color:color.onPrimary,border:`2px solid ${color.primaryEdge}`},dotFailed:{backgroundColor:color.danger,color:color.onDanger},dotCurrent:{border:`2px solid ${color.brandInk}`,backgroundColor:color.surface},dotCurrentCore:{width:10,height:10,borderRadius:5,backgroundColor:color.mark},dotUpcoming:{border:`2px solid ${color.structureEdge}`,backgroundColor:color.surface},connector:{width:2,flex:1,minHeight:22,backgroundColor:color.structureEdge,margin:"2px 0"},connectorDone:{backgroundColor:color.primaryEdge},title:{flex:1,display:"flex",flexWrap:"wrap",alignItems:"center",gap:space.sm,...faceCss(theme,"bold"),fontSize:type.size.bodyTight,lineHeight:lh(type.size.bodyTight),color:color.text.primary},titleCurrent:{color:color.brandInk},titleFailed:{color:color.danger},titleUpcoming:{color:color.text.muted,...faceCss(theme,"regular")},titleReady:brandedStatus(theme).success?{color:color.success}:{},date:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption),color:color.text.muted},detail:{...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.normal)}px`,color:color.text.muted},now:{display:"inline-flex",alignItems:"center",minHeight:20,padding:`0 ${space.sm}px`,borderRadius:radius.pill,backgroundColor:color.highlight,color:color.onHighlight,...faceCss(theme,"monoBold"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny),letterSpacing:"0.06em",textTransform:"uppercase"},detailUpcoming:{opacity:.7},srOnly:{position:"absolute",width:1,height:1,margin:-1,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",whiteSpace:"nowrap",border:0}}}function isFinitePoint(point){return point.value!==null&&Number.isFinite(point.value)}function pointDisplay(point){return point.display!==null&&point.display.length>0?point.display:point.value!==null?String(point.value):""}function buildTrendModel(series){let primary=series.find(s=>s.points.some(isFinitePoint));if(primary===void 0)return null;let numeric2=primary.points.filter(isFinitePoint),first=numeric2[0];if(first===void 0)return null;let values=numeric2.map(p=>p.value),lo=Math.min(...values),hi=Math.max(...values);lo===hi&&(lo-=1,hi+=1);let pad=(hi-lo)*.18,yMin=lo-pad,yMax=hi+pad,span=yMax-yMin,xInset=6,count=numeric2.length,points=numeric2.map((p,index)=>({xPct:count<=1?50:xInset+index/(count-1)*(100-2*xInset),yPct:(yMax-p.value)/span*100})),bandTopPct=(yMax-hi)/span*100,bandBottomPct=(yMax-lo)/span*100,minPoint=numeric2.reduce((acc,p)=>p.value<acc.value?p:acc,first),maxPoint=numeric2.reduce((acc,p)=>p.value>acc.value?p:acc,first),lastNumeric=numeric2[numeric2.length-1]??first,latest=primary.points[primary.points.length-1]??lastNumeric,latestDisplay=pointDisplay(latest),heroDisplay=latestDisplay.length>0?latestDisplay:pointDisplay(lastNumeric);return{label:primary.label,heroDisplay:heroDisplay,minDisplay:pointDisplay(minPoint),maxDisplay:pointDisplay(maxPoint),firstDate:formatShortDate(primary.points[0]?.at??null),lastDate:formatShortDate(latest.at),points:points,bandTopPct:bandTopPct,bandBottomPct:bandBottomPct}}function entityTypeOf(key){let separator=key.indexOf(":");return separator<=0?null:key.slice(0,separator)}function groupSeriesByEntityType(series,order,labelFor){let byType=/* @__PURE__ */new Map,firstSeen=[];for(let one of series){let type=entityTypeOf(one.key)??"",bucket=byType.get(type);bucket===void 0?(byType.set(type,[one]),firstSeen.push(type)):bucket.push(one)}let listed=order.filter(type=>byType.has(type)),rest=firstSeen.filter(type=>!listed.includes(type));/* @__PURE__ */
|
|
319
320
|
return Object.freeze([...listed,...rest].map(type=>/* @__PURE__ */Object.freeze({entityType:type.length>0?type:null,label:type.length>0?labelFor(type):null,series:/* @__PURE__ */Object.freeze([...byType.get(type)??[]])})))}function TrendRangeCard({series:series}){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles5(theme),[theme]),groups=useMemo(()=>groupSeriesByEntityType(series,ENTITY_SECTION_ORDER,entityTypeLabel),[series]);return groups.length===0?null:/* @__PURE__ */jsxs("section",{"aria-label":RECORD_SCREEN_COPY.careTimeline,style:styles.section,children:[
|
|
320
321
|
/* @__PURE__ */jsxs("div",{children:[
|
|
321
322
|
/* @__PURE__ */jsx("h3",{style:styles.sectionTitle,children:RECORD_SCREEN_COPY.careTimeline}),
|
|
322
323
|
/* @__PURE__ */jsx("p",{style:styles.sectionSub,children:RECORD_SCREEN_COPY.careTimelineSub})]}),groups.map(group=>/* @__PURE__ */jsxs("div",{style:styles.group,children:[group.label===null?null:/* @__PURE__ */jsx("p",{style:styles.eyebrow,children:group.label}),group.series.map(one=>/* @__PURE__ */jsx(SeriesChart,{series:one,styles:styles},one.key))]},group.entityType??"_"))]})}function SeriesChart({series:series,styles:styles}){let model=useMemo(()=>buildTrendModel([series]),[series]);if(model===null){let display=series.points[series.points.length-1]?.display??null;/* @__PURE__ */
|
|
323
324
|
return jsxs("div",{style:styles.card,children:[
|
|
324
|
-
/* @__PURE__ */jsx("p",{style:styles.eyebrow,children:series.label}),display!==null&&display.length>0?/* @__PURE__ */jsx("p",{style:styles.hero,children:display}):null]})}/* @__PURE__ */
|
|
325
|
+
/* @__PURE__ */jsx("p",{style:{...styles.eyebrow,...styles.cardInk},children:series.label}),display!==null&&display.length>0?/* @__PURE__ */jsx("p",{style:{...styles.hero,...styles.cardInk},children:display}):null]})}/* @__PURE__ */
|
|
325
326
|
return jsx(TrendChart,{model:model,styles:styles})}function TrendChart({model:model,styles:styles}){let summary=model.heroDisplay.length>0?`${model.label}, ${model.heroDisplay}`:model.label,bandHeightPct=Math.max(0,model.bandBottomPct-model.bandTopPct),last=model.points.length-1;/* @__PURE__ */
|
|
326
327
|
return jsxs("div",{style:styles.card,children:[
|
|
327
328
|
/* @__PURE__ */jsxs("div",{role:"img","aria-label":summary,children:[
|
|
328
|
-
/* @__PURE__ */jsx("p",{style:styles.eyebrow,children:model.label}),model.heroDisplay.length>0?/* @__PURE__ */jsx("p",{style:styles.hero,children:model.heroDisplay}):null]}),
|
|
329
|
+
/* @__PURE__ */jsx("p",{style:{...styles.eyebrow,...styles.cardInk},children:model.label}),model.heroDisplay.length>0?/* @__PURE__ */jsx("p",{style:{...styles.hero,...styles.cardInk},children:model.heroDisplay}):null]}),
|
|
329
330
|
/* @__PURE__ */jsxs("div",{"aria-hidden":"true",style:styles.plot,children:[model.points.map((p,index)=>/* @__PURE__ */jsx("div",{style:{...styles.guide,left:`${p.xPct}%`}},`g-${index}`)),
|
|
330
331
|
/* @__PURE__ */jsx("div",{style:{...styles.band,top:`${model.bandTopPct}%`,height:`${bandHeightPct}%`}}),model.points.map((p,index)=>/* @__PURE__ */jsx("div",{style:{...styles.point,...index===last?styles.pointLatest:null,left:`${p.xPct}%`,top:`${p.yPct}%`}},`pt-${index}`)),model.maxDisplay.length>0?/* @__PURE__ */jsx("span",{style:{...styles.edgeLabel,top:`${model.bandTopPct}%`},children:model.maxDisplay}):null,model.minDisplay.length>0?/* @__PURE__ */jsx("span",{style:{...styles.edgeLabel,top:`${model.bandBottomPct}%`},children:model.minDisplay}):null]}),model.firstDate.length>0||model.lastDate.length>0?/* @__PURE__ */jsxs("div",{"aria-hidden":"true",style:styles.dates,children:[
|
|
331
332
|
/* @__PURE__ */jsx("span",{children:model.firstDate}),
|
|
332
|
-
/* @__PURE__ */jsx("span",{children:model.lastDate})]}):null]})}function makeStyles5(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,dot=space.sm;return{section:{display:"flex",flexDirection:"column",gap:space.lg},sectionTitle:{margin:0,...
|
|
333
|
+
/* @__PURE__ */jsx("span",{children:model.lastDate})]}):null]})}function makeStyles5(theme){let{color:color,space:space,radius:radius,type:type}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,dot=space.sm,recordCard=recordCardSlot(theme.slots),cardText=slotText(recordCard);return{section:{display:"flex",flexDirection:"column",gap:space.lg},sectionTitle:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.subtitle,lineHeight:lh(type.size.subtitle,type.lineHeight.snug),letterSpacing:"-0.02em",color:color.text.primary},sectionSub:{margin:`${space.xs}px 0 0`,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted},group:{display:"flex",flexDirection:"column",gap:space.sm},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm,padding:space.lg,borderRadius:radius.lg,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderRingCream}`,...slotBoxCss(recordCard,1)},cardInk:cardText,eyebrow:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:lh(type.size.caption,type.lineHeight.normal),color:color.text.muted,letterSpacing:type.letterSpacing.eyebrow,textTransform:"uppercase",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},hero:{margin:0,...faceCss(theme,"bold"),fontSize:type.size.verdict,lineHeight:lh(type.size.verdict,type.lineHeight.tight),color:color.text.primary,letterSpacing:type.letterSpacing.tight},plot:{position:"relative",height:space.xxl*3,marginTop:space.xs},guide:{position:"absolute",top:0,bottom:0,width:1,backgroundColor:color.borderHairlineGreen},band:{position:"absolute",left:space.xs,right:space.xs,borderRadius:radius.sm,backgroundColor:color.brandSoft},point:{boxSizing:"border-box",position:"absolute",width:dot,height:dot,marginLeft:-(dot/2),marginTop:-(dot/2),borderRadius:radius.pill,backgroundColor:color.brand,border:`1px solid ${color.surfaceCream}`},pointLatest:{backgroundColor:color.accent,borderColor:color.onAccent},edgeLabel:{position:"absolute",right:0,marginTop:-space.sm,...faceCss(theme,"medium"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.tight),color:color.text.muted,whiteSpace:"nowrap",...cardText},dates:{display:"flex",justifyContent:"space-between",...faceCss(theme,"regular"),fontSize:type.size.tiny,lineHeight:lh(type.size.tiny,type.lineHeight.normal),color:color.text.muted,...cardText}}}var SPINNER_DELAY_MS2=300,SPINNER_LOOP_MS=900,MIN_SURFACE_HEIGHT3=120,MIN_TOUCH_TARGET3=44,GLYPH_SIZE=40,SPINNER_SIZE=24,SPINNER_STROKE=3;function renderErrorFamily(records,onGrant,canGrant,consentText){let errorView=selectErrorView(records,canGrant);switch(errorView.kind){case"consent_required":/* @__PURE__ */
|
|
333
334
|
return jsx(ConsentRequiredState,{onGrant:onGrant,consentText:consentText});case"consent_unavailable":/* @__PURE__ */
|
|
334
335
|
return jsx(AlertState,{label:RECORDS_COPY.consentRequired,glyph:"empty"});case"session_required":/* @__PURE__ */
|
|
335
336
|
return jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"});case"withheld":/* @__PURE__ */
|
|
@@ -350,10 +351,10 @@ return jsxs("div",{role:"alert","aria-live":"assertive",style:styles.centered,ch
|
|
|
350
351
|
return jsxs("div",{style:styles.callCard,children:[
|
|
351
352
|
/* @__PURE__ */jsx("p",{style:styles.timelineLabel,children:CALL_CLINIC_COPY.heading}),
|
|
352
353
|
/* @__PURE__ */jsx("p",{style:styles.timelineMeta,children:intro}),
|
|
353
|
-
/* @__PURE__ */jsx("a",{href:call.dial,"aria-label":CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,"data-testid":"records-call-clinic",children:CALL_CLINIC_COPY.call})]})}function useRecordsTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,hairline=`1px solid ${color.brandBorder}`,card=slotBoxCss(slots
|
|
354
|
+
/* @__PURE__ */jsx("a",{href:call.dial,"aria-label":CALL_CLINIC_COPY.callAt(call.phone),style:styles.linkButton,"data-testid":"records-call-clinic",children:CALL_CLINIC_COPY.call})]})}function useRecordsTheme(){let theme=useEverfurTheme(),styles=useMemo(()=>makeStyles6(theme),[theme]);return{theme:theme,styles:styles}}function makeStyles6(theme){let{color:color,space:space,radius:radius,type:type,slots:slots}=theme,lh=(size,multiplier)=>`${Math.round(size*multiplier)}px`,hairline=`1px solid ${color.brandBorder}`,card=slotBoxCss(recordCardSlot(slots),1),cardText=slotText(recordCardSlot(slots)),text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:lh(size,multiplier),color:fg}),inCard=(size,multiplier,fg,weight="regular")=>({...text3(size,multiplier,fg,weight),...cardText}),button={boxSizing:"border-box",minHeight:MIN_TOUCH_TARGET3,minWidth:MIN_TOUCH_TARGET3,padding:`${space.md}px ${space.xl}px`,borderRadius:radius.pill,...faceCss(theme,"bold"),fontSize:type.size.body,letterSpacing:type.letterSpacing.tight},glyph={boxSizing:"border-box",width:GLYPH_SIZE,height:GLYPH_SIZE},errorColor=theme.brightness==="dark"?color.errorRed:color.danger;return{container:{boxSizing:"border-box",display:"flex",flexDirection:"column",minHeight:MIN_SURFACE_HEIGHT3,height:"100%",backgroundColor:color.background,color:color.text.primary,...faceCss(theme,"regular")},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",overflowY:"auto"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:MIN_SURFACE_HEIGHT3,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:space.lg,padding:space.xl,textAlign:"center"},spinner:{boxSizing:"border-box",width:SPINNER_SIZE,height:SPINNER_SIZE,borderRadius:radius.pill,border:`${SPINNER_STROKE}px solid ${color.brandSofter}`,borderTopColor:color.brandInk},emptyGlyph:{...glyph,borderRadius:radius.lg,backgroundColor:color.brandSoft,border:hairline},withheldGlyph:{...glyph,borderRadius:radius.sm,backgroundColor:color.badgeBgCaution,border:`1px solid ${color.cautionAccent}`},alertText:text3(type.size.subtitle,type.lineHeight.snug,color.text.secondary),errorText:text3(type.size.subtitle,type.lineHeight.snug,errorColor),primaryButton:{...button,border:0,cursor:"pointer",backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},disabledButton:{...button,border:hairline,cursor:"default",backgroundColor:color.surfaceSubtle,color:color.text.muted},list:{display:"flex",flexDirection:"column",gap:space.md,padding:space.lg},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.xs,padding:`${space.md}px ${space.lg}px`,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...card},cardTitle:{...inCard(type.size.heading,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold"),letterSpacing:type.letterSpacing.tight},callCard:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm,padding:space.md,borderRadius:radius.md,backgroundColor:color.surfaceCream,border:hairline,...card},linkButton:{...button,display:"inline-flex",alignItems:"center",justifyContent:"center",alignSelf:"flex-start",textDecoration:"none",border:0,backgroundColor:color.primary,color:color.onPrimary,...slotBoxCss(slots.primaryButton),...slotText(slots.primaryButton)},timelineLabel:{...inCard(type.size.subtitle,type.lineHeight.snug,color.text.secondary,"bold")},timelineMeta:inCard(type.size.bodyTight,type.lineHeight.normal,color.text.muted),row:{display:"flex",justifyContent:"space-between",gap:space.md,padding:`${space.xs}px 0`,borderBottom:`1px solid ${color.borderHairlineGreen}`},rowLabel:inCard(type.size.body,type.lineHeight.normal,color.text.muted),rowValue:{...inCard(type.size.body,type.lineHeight.normal,color.text.primary,"medium"),textAlign:"right"},disclaimer:text3(type.size.caption,type.lineHeight.normal,color.text.muted)}}var RECORD_PDF_FILENAME="everfur-record.pdf";function copyText(text3){return typeof navigator>"u"||!navigator.clipboard?Promise.reject(new Error("clipboard unavailable")):navigator.clipboard.writeText(text3)}function isAbort(error){return typeof error=="object"&&error!==null&&error.name==="AbortError"}async function shareLinkInPlace(url,copy=copyText){let nav=typeof navigator>"u"?void 0:navigator;if(nav!==void 0&&typeof nav.share=="function")try{return await nav.share({url:url}),"shared"}catch(error){if(isAbort(error))return"dismissed"}return await copy(url),"copied"}function inPlaceRoute(url,base){let parsed;try{parsed=new URL(url,base)}catch{return null}if(parsed.protocol==="blob:"||parsed.protocol==="data:")return"download";if(base!==void 0)try{if(new URL(base).origin===parsed.origin)return"download"}catch{}let disposition=parsed.searchParams.get("response-content-disposition");return disposition!==null&&/^\s*attachment\b/i.test(disposition)?"attachment":null}function locationHref(){return typeof location>"u"?void 0:location.href}function isFramedDocument(win=(typeof window>"u"?void 0:window)){if(win===void 0)return false;try{return win.self!==win.top}catch{return true}}function clickDownload(href,filename){let anchor=document.createElement("a");anchor.href=href,anchor.download=filename,anchor.rel="noopener",anchor.style.display="none",document.body.appendChild(anchor);try{anchor.click()}finally{anchor.remove()}}var SAVE_FRAME_TTL_MS=6e4;function saveThroughNestedFrame(href){let frame=document.createElement("iframe");frame.setAttribute("sandbox","allow-downloads"),frame.setAttribute("aria-hidden","true"),frame.tabIndex=-1,frame.style.display="none",frame.src=href,document.body.appendChild(frame),setTimeout(()=>frame.remove(),SAVE_FRAME_TTL_MS)}async function downloadInPlace(url,filename,framed=isFramedDocument()){if(typeof document>"u")return false;let route=inPlaceRoute(url,locationHref());if(route==="attachment"&&framed)return saveThroughNestedFrame(url),true;if(route!==null)return clickDownload(url,filename),true;let blob;try{let response=await fetch(url,{credentials:"omit"});if(!response.ok)return!1;blob=await response.blob()}catch{return false}let objectUrl=URL.createObjectURL(blob);try{clickDownload(objectUrl,filename)}finally{setTimeout(()=>URL.revokeObjectURL(objectUrl),1e4)}return true}var COPY=RECORD_SCREEN_COPY.document,DOCUMENT_ENTITY_ORDER=/* @__PURE__ */Object.freeze(["medication","vaccination","problem","allergy","procedure","body_weight","vital"]),readDepth=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty=value=>!value.available;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 EverfurRecordDocument(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onBack"]),{userRef:userRef}=useEverfurContext(),{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
354
355
|
return jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxs("div",{className:className,style:{...styles.root,backgroundColor:theme.color.surface,...style},"data-testid":"record-document-screen",children:[userRef===null?/* @__PURE__ */jsx("div",{style:styles.body,children:/* @__PURE__ */jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsx(DocumentBody,{...rest}),
|
|
355
356
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})})}function DocumentBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onBack:onBack,onOpenUrl:onOpenUrl}){let{theme:theme,styles:styles}=useScreenStyles(),s=useDocStyles(),recordsOpts=useMemo(()=>controller?{petRef:petRef,controller:controller}:{petRef:petRef},[petRef,controller]),records=useEverfurRecords(recordsOpts),depth=useRecordsDepthRead(petRef,readDepth,depthEmpty),pdf=useRecordPdfLink(petRef);useConsentTextWarning2(consentVersion,consentText);let canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},depthView=depth.value!==null&&!depth.value.withheld&&depth.value.available?depth.value:null,record=records.record,[saveFailed,setSaveFailed]=useState(false),download=()=>{setSaveFailed(false),pdf.pdfLink().then(result=>{result.ok&&(onOpenUrl?callHostAsync(onOpenUrl,result.value.downloadUrl,"record_pdf"):downloadInPlace(result.value.downloadUrl,RECORD_PDF_FILENAME).then(saved=>setSaveFailed(!saved)))})},body,documentShown=false;if(records.status==="loading"||depth.status==="loading"&&record!==null)body=/* @__PURE__ */jsx("div",{"data-testid":"record-document-loading",children:/* @__PURE__ */jsx(LoadingState2,{})});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("p",{style:s.empty,"data-testid":"record-document-empty",children:COPY.empty}):(documentShown=true,body=/* @__PURE__ */jsx(RecordDocument,{record:record,depth:depthView,petName:petName,wordmark:theme.meta.displayName})/* @__PURE__ */);return jsxs(Fragment,{children:[
|
|
356
|
-
/* @__PURE__ */jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsx("button",{type:"button",onClick:download,disabled:pdf.preparing,"aria-busy":pdf.preparing,"aria-label":COPY.download,style:styles.iconButton,"data-testid":"record-document-download",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{display:"block",width:12,height:12,borderLeft:`2px solid ${
|
|
357
|
+
/* @__PURE__ */jsx(ScreenHeader,{title:COPY.titleFor(petName),variant:"document",onBack:onBack,testID:"record-document-header",right:pdf.available&&documentShown?/* @__PURE__ */jsx("button",{type:"button",onClick:download,disabled:pdf.preparing,"aria-busy":pdf.preparing,"aria-label":COPY.download,style:styles.iconButton,"data-testid":"record-document-download",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{display:"block",width:12,height:12,borderLeft:`2px solid ${styles.headerInk}`,borderBottom:`2px solid ${styles.headerInk}`,transform:"rotate(-45deg)"}})}):void 0}),pdf.error?/* @__PURE__ */jsx("p",{role:"alert",style:{...styles.errorText,padding:`0 ${theme.space.lg}px`},children:pdf.error.displayMessage}):saveFailed?/* @__PURE__ */jsx("p",{role:"alert",style:{...styles.errorText,padding:`0 ${theme.space.lg}px`},"data-testid":"record-document-save-failed",children:shareErrorMessage(null,"download")}):null,
|
|
357
358
|
/* @__PURE__ */jsx("div",{style:styles.body,children:body})]})}function RecordDocument({record:record,depth:depth,petName:petName,wordmark:wordmark}){let s=useDocStyles(),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("section",{style:s.section,"data-testid":testID,children:[
|
|
358
359
|
/* @__PURE__ */jsxs("div",{style:s.sectionHeader,children:[
|
|
359
360
|
/* @__PURE__ */jsx("h3",{style:s.sectionTitle,children:title}),
|
|
@@ -383,7 +384,7 @@ return jsxs("div",{style:row(index),children:[
|
|
|
383
384
|
/* @__PURE__ */jsx("span",{style:s.noteLabel,children:soapSectionLabel(sec.section)}),
|
|
384
385
|
/* @__PURE__ */jsx("p",{style:s.noteBody,children:sec.text})]},`${sec.section}-${i}`))]},note.noteId)),"record-document-notes"):null,disclaimerRepeatsFootnote(record.disclaimer)?null:/* @__PURE__ */jsx("p",{style:s.disclaimer,children:record.disclaimer})]})}function useDocStyles(){let theme=useEverfurTheme();return useMemo(()=>makeDocStyles(theme),[theme])}function makeDocStyles(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:`${Math.round(size*multiplier)}px`,color:fg}),monoText=(size,fg)=>({margin:0,...faceCss(theme,"mono"),fontSize:size,lineHeight:`${size+space.xs-1}px`,color:fg,letterSpacing:type.letterSpacing.eyebrow/2,textTransform:"uppercase"}),hairline=`1px solid ${color.borderHairlineGreen}`;return{empty:{...text3(type.size.body,type.lineHeight.normal,color.text.muted,"medium"),textAlign:"center",padding:`${space.xxl}px ${space.xxl}px`},page:{padding:`0 ${space.lg+space.xs}px ${space.xxl+space.lg}px`,...faceCss(theme,"regular")},letterhead:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.xs+space.xs/2,padding:`${space.md}px 0 ${space.lg+space.xs+space.xs/2}px`,borderBottom:`2px solid ${color.brandInk}`,marginBottom:space.sm},wordmark:{...text3(type.size.heading,type.lineHeight.snug,color.brandInk,"bold"),letterSpacing:type.letterSpacing.headerBrand},docTitle:{...monoText(type.size.caption,color.brandInk),marginTop:space.sm+space.xs/2,letterSpacing:type.letterSpacing.eyebrow+.4},petName:text3(type.size.verdict+space.xs/2,type.lineHeight.tight,color.text.primary),generated:{...monoText(type.size.tiny,color.text.muted),textTransform:"none"},section:{marginTop:space.lg+space.xs+space.xs/2},sectionHeader:{display:"flex",alignItems:"center",gap:space.sm+space.xs/2,marginBottom:space.sm},sectionTitle:monoText(type.size.tiny,color.brandInk),rule:{flex:1,height:1,backgroundColor:color.borderHairlineGreen},row:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.md+space.xs/2,padding:`${space.sm+1}px 0`},rowDivider:{borderTop:hairline},rowFlag:{backgroundColor:color.badgeBgCritical,margin:`0 -${space.sm}px`,padding:`${space.sm+1}px ${space.sm}px`,borderRadius:radius.xs},rowMain:{display:"flex",flexDirection:"column",minWidth:0},rowRight:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:space.xs/2},rowLabel:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"medium")},rowValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary,"bold"),textAlign:"right"},alert:{color:color.danger},rowMeta:{marginTop:space.xs/2,...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,color:color.text.muted},markerStatus:monoText(type.size.micro,color.text.muted),block:{padding:`${space.sm+space.xs/2}px 0`},blockDate:{...monoText(type.size.tiny,color.text.muted),display:"block",marginBottom:space.xs+space.xs/2},fieldRow:{display:"flex",alignItems:"flex-start",gap:space.md+space.xs/2,padding:`${space.xs-1}px 0`},fieldLabel:{width:120,flexShrink:0,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted,"medium")},fieldValue:{flex:1,...text3(type.size.bodyTight,type.lineHeight.normal,color.text.primary,"medium")},noteSection:{marginTop:space.sm},noteLabel:{...monoText(type.size.tiny,color.brandInk),display:"block",marginBottom:space.xs/2},noteBody:text3(type.size.bodyTight,type.lineHeight.relaxed,color.text.primary),disclaimer:{...text3(type.size.tiny,type.lineHeight.relaxed,color.text.muted),marginTop:radius.xl,paddingTop:space.md+space.xs/2,borderTop:hairline}}}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__ */
|
|
385
386
|
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 FALLBACK_TITLE=/* @__PURE__ */Object.freeze({vaccination:"Vaccination",medication:"Medication",problem:"Problem",body_weight:"Weight",allergy:"Allergy",vital:"Vital",lab_result:"Lab result",parasite_prevention:"Preventive"}),GIVEN_PREFIX="Given",ISO_DATE_PREFIX=/^\d{4}-\d{2}-\d{2}/,DETAIL_SEPARATOR=" · ";function joinDetail(parts){let kept=parts.filter(part=>part!==null&&part.trim().length>0);return kept.length>0?kept.join(DETAIL_SEPARATOR):null}function rowTitle(facts,humanizeCategory){let label=facts.label.trim();if(label.length>0)return label;let fallback=FALLBACK_TITLE[facts.category];return fallback!==void 0?fallback:humanizeCategory(facts.category)}function entityRowSummary(facts,fmt){let title=rowTitle(facts,fmt.humanize),value=fmt.formatEntityValue(facts.value,facts.unit),shownValue=value.trim().length>0?value:null,rawDate=facts.observedAt!==null&&facts.observedAt.trim().length>0?fmt.formatRecordsDate(facts.observedAt):null,observed=rawDate!==null&&rawDate!=="-"?rawDate:null;switch(facts.category){case"vaccination":{let valueIsDate=facts.value!==null&&ISO_DATE_PREFIX.test(facts.value.trim()),givenOn=valueIsDate?fmt.formatRecordsDate(facts.value):observed;return givenOn!==null&&givenOn!=="-"?{title:title,detail:joinDetail([`${GIVEN_PREFIX} ${givenOn}`,valueIsDate?null:shownValue])}:{title:title,detail:joinDetail([shownValue])}}case"medication":return{title:title,detail:joinDetail([observed])};case"problem":return{title:title,detail:joinDetail([observed])};case"body_weight":return{title:title,detail:joinDetail([observed])};case"allergy":return{title:title,detail:joinDetail([observed])};case"vital":return{title:title,detail:joinDetail([shownValue,observed])};case"lab_result":return{title:title,detail:joinDetail([shownValue,observed])};default:return{title:title,detail:joinDetail([shownValue,observed])}}}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 FOCUSABLE='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function isDialogElement(node){return node.tagName==="DIALOG"}function useModalDialog(open,onClose,returnFocusTo,options){let escapeAtKeyDown=options?.escapeAtKeyDown===true,dialogRef=useRef(null),wasOpen=useRef(false),opener=useRef(null),trigger=useRef(returnFocusTo);trigger.current=returnFocusTo;let restoreFocus=useCallback(()=>{if(!wasOpen.current)return;wasOpen.current=false;let target=trigger.current===void 0?opener.current:trigger.current.current;target&&target.isConnected&&target.focus(),(!target||!target.isConnected||document.activeElement===target)&&(opener.current=null)},[]);useEffect(()=>{let node=dialogRef.current;if(!wasOpen.current){let active=typeof document>"u"?null:document.activeElement;active!==null&&node!==null&&node.contains(active)||(opener.current=active instanceof HTMLElement?active:null)}if(wasOpen.current=true,node===null)return;if(!isDialogElement(node)){node.contains(document.activeElement)||(node.querySelector(FOCUSABLE)??node).focus();return}let dialog=node;typeof dialog.showModal=="function"?dialog.open||dialog.showModal():dialog.setAttribute("open","")},[open,restoreFocus]),useEffect(()=>restoreFocus,[restoreFocus]),useEffect(()=>{let node=dialogRef.current;if(node===null||!isDialogElement(node))return;let dialog=node;if(typeof dialog.showModal!="function")return;let lastFocused=null,onFocusIn=event=>{event.target instanceof HTMLElement&&(lastFocused=event.target)},onNativeClose=()=>{if(!dialog.isConnected||dialog.open)return;let back=lastFocused;dialog.showModal(),back!==null&&back.isConnected&&dialog.contains(back)&&document.activeElement!==back&&back.focus()};return dialog.addEventListener("focusin",onFocusIn),dialog.addEventListener("close",onNativeClose),()=>{dialog.removeEventListener("focusin",onFocusIn),dialog.removeEventListener("close",onNativeClose)}},[open]);let onKeyDown=useCallback(event=>{let node=dialogRef.current;if(node===null)return;if(event.key==="Escape"&&!isDialogElement(node)){event.preventDefault(),event.stopPropagation(),onClose();return}if(event.key==="Escape"&&escapeAtKeyDown);if(event.key!=="Tab")return;let focusable=Array.from(node.querySelectorAll(FOCUSABLE)),first=focusable[0],last=focusable[focusable.length-1];if(!first||!last){event.preventDefault();return}let active=document.activeElement;event.shiftKey&&(active===first||!node.contains(active))?(event.preventDefault(),last.focus()):!event.shiftKey&&(active===last||!node.contains(active))&&(event.preventDefault(),first.focus())},[onClose,escapeAtKeyDown]),onCancel=useCallback(event=>{event.target===event.currentTarget&&(event.preventDefault(),onClose())},[onClose]);return{dialogRef:dialogRef,onKeyDown:onKeyDown,onCancel:onCancel}}var FOCUSABLE2='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function RecordsDialog({label:label,onClose:onClose,shape:shape="modal",returnFocusTo:returnFocusTo,panelStyle:panelStyle,testID:testID,children:children}){let{styles:styles}=useScreenStyles(),dialog=useModalDialog(true,onClose,returnFocusTo);useEffect(()=>{let node=dialog.dialogRef.current;node===null||node.contains(document.activeElement)||(node.querySelector(FOCUSABLE2)??node).focus()},[dialog.dialogRef]);let side=shape==="side";/* @__PURE__ */
|
|
386
|
-
return jsx("dialog",{ref:dialog.dialogRef,"aria-label":label,"aria-modal":"true",onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.dialogFrame,"data-testid":testID,children:/* @__PURE__ */jsx("div",{style:side?styles.dialogScrimSide:styles.dialogScrim,onClick:event=>{event.target===event.currentTarget&&onClose()},"data-testid":testID?`${testID}-scrim`:void 0,children:/* @__PURE__ */jsx("div",{style:{...side?styles.dialogPanelSide:styles.dialogPanel,...panelStyle},children:children})})})}function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let{theme:theme,styles:styles}=useScreenStyles(),[open,setOpen]=useState(false),trigger=useRef(null),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
387
|
+
return jsx("dialog",{ref:dialog.dialogRef,"aria-label":label,"aria-modal":"true",onCancel:dialog.onCancel,onKeyDown:dialog.onKeyDown,style:styles.dialogFrame,"data-testid":testID,children:/* @__PURE__ */jsx("div",{style:side?styles.dialogScrimSide:styles.dialogScrim,onClick:event=>{event.target===event.currentTarget&&onClose()},"data-testid":testID?`${testID}-scrim`:void 0,children:/* @__PURE__ */jsx("div",{style:{...side?styles.dialogPanelSide:styles.dialogPanel,...panelStyle,...side?styles.dialogSlotSide:styles.dialogSlot},children:children})})})}function FactEditAffordance({entity:entity,factEdit:factEdit,children:children}){let{theme:theme,styles:styles}=useScreenStyles(),[open,setOpen]=useState(false),trigger=useRef(null),label=entity.label.trim()||FACT_EDIT_COPY.detail;/* @__PURE__ */
|
|
387
388
|
return jsxs("div",{style:{display:"flex",alignItems:"center",gap:theme.space.sm},children:[
|
|
388
389
|
/* @__PURE__ */jsx("div",{style:{flex:1,minWidth:0},children:children}),
|
|
389
390
|
/* @__PURE__ */jsx("button",{ref:trigger,type:"button",onClick:()=>setOpen(true),"aria-label":FACT_EDIT_COPY.editA11y(label),style:styles.iconButton,"data-testid":`fact-edit-open-${entity.canonicalKey??entity.key}`,children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{display:"block",width:theme.space.md+theme.space.xs/2,height:2,backgroundColor:theme.color.brand,borderRadius:theme.radius.pill,transform:"rotate(-45deg)"}})}),open?/* @__PURE__ */jsx(FactEditSheet,{entity:entity,title:label,factEdit:factEdit,onClose:()=>setOpen(false),returnFocusTo:trigger}):null]})}function FactEditSheet({entity:entity,title:title,factEdit:factEdit,onClose:onClose,returnFocusTo:returnFocusTo}){let{theme:theme,styles:styles}=useScreenStyles(),[draft,setDraft]=useState(entity.value??""),[localError,setLocalError]=useState(null),[confirmingRemove,setConfirmingRemove]=useState(false);useEffect(()=>{factEdit.clearError()},[factEdit]);let changed=draft.trim().length>0&&draft.trim()!==(entity.value??"").trim(),error=localError??factEdit.error,busy=factEdit.busy,submitEdit=()=>{if(!changed){setLocalError(FACT_EDIT_COPY.noChange);return}setLocalError(null),factEdit.edit(entity,draft).then(result=>{result.ok&&onClose()})},submitRemove=()=>{setLocalError(null),factEdit.remove(entity).then(result=>{result.ok?onClose():setConfirmingRemove(false)})},fieldId=`fact-edit-${entity.key}`;
|
|
@@ -504,7 +505,7 @@ return jsx(CapabilityGate,{capability:"records",style:style,className:className,
|
|
|
504
505
|
/* @__PURE__ */jsx(RecordsEmptyState,{variant:"no_records",message:inReview>0?RECORD_SCREEN_COPY.inReview(inReview):void 0}),
|
|
505
506
|
/* @__PURE__ */jsx(DisclaimerBand,{disclaimer:record?.disclaimer??""})]})}else body=/* @__PURE__ */jsx("div",{ref:rise,style:{...styles.content,gap:theme.space.lg+theme.space.xs,paddingBottom:theme.space.xxl+theme.space.sm},"data-testid":"everfur-record",children:/* @__PURE__ */jsx(RecordSections,{record:record,depth:depthView,petName:petName,onNavigate:onNavigate,onAsk:onAsk,factEdit:factEdit})});/* @__PURE__ */
|
|
506
507
|
return jsxs(Fragment,{children:[
|
|
507
|
-
/* @__PURE__ */jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||onNavigate?/* @__PURE__ */jsxs(Fragment,{children:[onNavigate?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onNavigate({name:"clinicBatch"}),"aria-label":RECORD_SCREEN_COPY.requestClinicsA11y,style:styles.iconButton,"data-testid":"everfur-record-request-clinics",children:/* @__PURE__ */jsx(HeaderGlyph,{name:"send",color:
|
|
508
|
+
/* @__PURE__ */jsx(ScreenHeader,{title:RECORD_SCREEN_COPY.title,onBack:onBack,testID:"everfur-record-header",right:shareable||onNavigate?/* @__PURE__ */jsxs(Fragment,{children:[onNavigate?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onNavigate({name:"clinicBatch"}),"aria-label":RECORD_SCREEN_COPY.requestClinicsA11y,style:styles.iconButton,"data-testid":"everfur-record-request-clinics",children:/* @__PURE__ */jsx(HeaderGlyph,{name:"send",color:styles.headerInk})}):null,shareable?/* @__PURE__ */jsx("button",{ref:shareTrigger,type:"button",onClick:()=>setSharing(true),"aria-label":SHARE_COPY.openA11yFor(petName),style:styles.iconButton,"data-testid":"everfur-record-share",children:/* @__PURE__ */jsx(HeaderGlyph,{name:"share2",color:styles.headerInk})}):null]}):void 0}),
|
|
508
509
|
/* @__PURE__ */jsx("div",{style:styles.body,children:body}),sharing?/* @__PURE__ */jsx(ShareSheet,{petRef:petRef,petName:petName,onClose:()=>setSharing(false),returnFocusTo:shareTrigger,onNavigate:onNavigate,...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{}}):null]})}var REQUEST_DOCUMENTS_COPY=/* @__PURE__ */Object.freeze({download:"Download",downloadA11y:title=>`Download, ${title}`,listA11y:"You added these records"});function formatBytes(bytes){return bytes<1024?`${bytes} B`:bytes<1024*1024?`${(bytes/1024).toFixed(1)} KB`:`${(bytes/(1024*1024)).toFixed(1)} MB`}function formatLabel(docFormat){let trimmed=docFormat?.trim();return trimmed?trimmed.toUpperCase():null}function requestDocumentRows(items){/* @__PURE__ */
|
|
509
510
|
return Object.freeze(items.map(item=>{let format=formatLabel(item.docFormat),date=item.receivedAt?formatRecordsDate(item.receivedAt):null,title=item.fileName??format??date??item.sourceDocId,meta=[item.fileName!==null&&format!==null&&item.fileName.toUpperCase().endsWith(`.${format}`)||title===format?null:format,item.byteSize!==null?formatBytes(item.byteSize):null,title===date?null:date].filter(part=>!!part).join(" · ");/* @__PURE__ */
|
|
510
511
|
return Object.freeze({key:item.sourceDocId,title:title,meta:meta||null,downloadUrl:item.downloadUrl})}))}function requestDocumentFileName(item){let base=item.fileName?.trim()||item.sourceDocId,extension=item.docFormat?.trim().toLowerCase().replace(/^\./,"")??"";return extension.length===0||base.toLowerCase().endsWith(`.${extension}`)?base:`${base}.${extension}`}function useRequestDocuments(requestId2,opts={}){let enabled=opts.enabled??true,client=useEverfurRecordsDepthClient(),{userRef:userRef}=useEverfurContext(),[documents,setDocuments]=useState(null),[loading,setLoading]=useState(enabled),[error,setError]=useState(null),generation=useRef(0),live=useRef(true),load=useCallback(async()=>{let gen=generation.current+=1;if(!enabled||userRef===null){setDocuments(null),setError(null),setLoading(false);return}setLoading(true),setError(null);let result=await client.listRequestDocuments(requestId2);gen!==generation.current||!live.current||(result.ok?setDocuments(result.value):(setDocuments(null),setError(result.error)),setLoading(false))},[client,enabled,requestId2,userRef]);useEffect(()=>(live.current=true,load(),()=>{live.current=false,generation.current+=1}),[load]);let rows=useMemo(()=>documents===null?[]:requestDocumentRows(documents),[documents]),refresh=useCallback(()=>{load()},[load]),status=loading?"loading":error!==null?"error":rows.length===0?"empty":"populated";return useMemo(()=>({status:status,rows:rows,error:error,refresh:refresh}),[status,rows,error,refresh])}function RequestDocumentsList({requestId:requestId2,open:open=true,onOpenUrl:onOpenUrl,testID:testID="records-request-documents"}){let{theme:theme,styles:styles}=useScreenStyles(),documents=useRequestDocuments(requestId2,{enabled:open}),client=useEverfurRecordsDepthClient(),[savingKey,setSavingKey]=useState(null),[failedKey,setFailedKey]=useState(null),live=useRef(true);useEffect(()=>(live.current=true,()=>{live.current=false}),[]);let save=async row=>{setSavingKey(row.key),setFailedKey(null);let fresh=await client.listRequestDocuments(requestId2),doc=fresh.ok?fresh.value.find(item=>item.sourceDocId===row.key)??null:null,failed=doc===null;doc!==null&&live.current&&(onOpenUrl?await callHostAsync(onOpenUrl,doc.downloadUrl,"request_document"):failed=!await downloadInPlace(doc.downloadUrl,requestDocumentFileName(doc))),live.current&&(setSavingKey(null),failed&&setFailedKey(row.key))};return open?documents.status==="loading"?/* @__PURE__ */jsx("div",{style:{paddingTop:theme.space.sm},"aria-busy":"true","data-testid":`${testID}-loading`,children:/* @__PURE__ */jsx(SkeletonBlock,{width:"100%",height:theme.space.lg+theme.space.md})}):documents.status==="error"?/* @__PURE__ */jsxs("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:theme.space.sm,paddingTop:theme.space.sm},"data-testid":`${testID}-error`,children:[
|
|
@@ -522,8 +523,8 @@ return jsxs(Fragment,{children:[
|
|
|
522
523
|
/* @__PURE__ */jsx("h2",{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:{...styles.sectionTitle,fontSize:theme.type.size.heading,color:theme.color.brandInk},"data-testid":"upload-title",children:UPLOAD_COPY.screenTitle}),
|
|
523
524
|
/* @__PURE__ */jsx("p",{style:{...styles.muted,fontSize:theme.type.size.body,maxWidth:340},children:UPLOAD_COPY.subtitle(petName)})]}),
|
|
524
525
|
/* @__PURE__ */jsx(UploadRecordCard,{records:records,requestId:null,canUpload:canUpload,onDone:onNavigate?requestId2=>onNavigate({name:"request",requestId:requestId2}):void 0})]})]})}function UploadRecordCard({records:records,requestId:requestId2,canUpload:canUpload,onDone:onDone}){let{theme:theme,styles:styles}=useScreenStyles(),inputRef=useRef(null),hintId=`records-upload-format-hint-${requestId2??"new"}`,[pickError,setPickError]=useState(null),[batchCount,setBatchCount]=useState(0),[pending,setPending]=useState(false),resolvedId=useRef(requestId2),failedFiles=useRef([]),rows=records.uploadQueue.filter(item=>item.status!=="skipped"),done=rows.filter(item=>item.status==="done").length,failed=rows.filter(item=>item.status==="failed").length,settled=!records.isUploading&&!pending&&batchCount>0,types=records.uploadContentTypes,photos=acceptsPhotos(types),run=useCallback(async picked=>{let{uploadable:uploadable,skipped:skipped}=classifyPick(picked,types),refusal=skippedFilesMessage(skipped,photos);if(uploadable.length===0){refusal!==null&&setPickError(refusal);return}setPickError(refusal),setPending(true);try{let target=resolvedId.current;if(target===null){let created=await records.createRequest(`records-upload-${Date.now().toString(36)}`);if(!created.ok){setPickError(UPLOAD_COPY.errors.start);return}target=created.value.id,resolvedId.current=target}setBatchCount(n=>n+1);let outcome=await records.uploadDocuments(target,uploadable);failedFiles.current=outcome.flatMap((item,index)=>item.status==="failed"&&uploadable[index]!==void 0?[uploadable[index]]:[])}finally{setPending(false)}},[records,types,photos]),onChange=event=>{let files=Array.from(event.currentTarget.files??[]);event.currentTarget.value="",!(files.length===0||!canUpload)&&(async()=>{let handles=[];for(let file of files)handles.push(await fileToHandle(file,types));await run(handles)})()},pick=()=>inputRef.current?.click(),busy=records.isUploading||pending;/* @__PURE__ */
|
|
525
|
-
return jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"data-testid":"records-upload-card",children:[
|
|
526
|
-
/* @__PURE__ */jsx("h3",{style:{...styles.rowTitle,...
|
|
526
|
+
return jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface,...styles.cardSlot},"data-testid":"records-upload-card",children:[
|
|
527
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.rowTitle,...headingFaceCss(theme,"bold"),fontSize:theme.type.size.subtitle},children:UPLOAD_COPY.cardTitle}),
|
|
527
528
|
/* @__PURE__ */jsx("p",{id:hintId,style:styles.muted,children:photos?UPLOAD_PHOTO_COPY.note:UPLOAD_COPY.cardSubtitle}),
|
|
528
529
|
/* @__PURE__ */jsx("input",{ref:inputRef,type:"file",accept:recordsDocumentAccept(types),multiple:true,tabIndex:-1,"aria-hidden":"true",hidden:true,disabled:!canUpload,onChange:onChange,"data-testid":"records-upload-input"}),pickError?/* @__PURE__ */jsx("p",{role:"alert",style:styles.errorBanner,children:pickError}):null,
|
|
529
530
|
/* @__PURE__ */jsx(UploadQueue,{records:records}),busy?/* @__PURE__ */jsx("p",{style:styles.muted,children:UPLOAD_COPY.uploading(done,rows.length)}):settled?/* @__PURE__ */jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.sm},children:[done>0?/* @__PURE__ */jsx("p",{role:"status",style:styles.bodyText,children:UPLOAD_COPY.received(done)}):null,failed>0?/* @__PURE__ */jsx(Pill,{label:UPLOAD_COPY.retryFailed(failed),kind:"link",onClick:()=>{run(failedFiles.current)},testID:"records-upload-retry-failed"}):null,
|
|
@@ -549,10 +550,10 @@ return jsxs("div",{ref:rise,style:{...styles.content,gap:theme.space.lg+theme.sp
|
|
|
549
550
|
/* @__PURE__ */jsx("p",{style:styles.bodyText,children:RECORDS_RECOVERY_COPY.cancelConsequence}),
|
|
550
551
|
/* @__PURE__ */jsx(Pill,{label:form.busy&&lastAction==="revoke"?REQUEST_SCREEN_COPY.cancelling:REQUEST_SCREEN_COPY.cancel,kind:"danger",busy:form.busy&&lastAction==="revoke",onClick:()=>run("revoke",form.revoke),testID:"records-revoke-do"}),
|
|
551
552
|
/* @__PURE__ */jsx(Pill,{label:RECORDS_RECOVERY_COPY.keepRequest,kind:"outline",disabled:form.busy,onClick:form.keepRequest,testID:"records-revoke-keep"})]}):/* @__PURE__ */jsx(Pill,{label:REQUEST_SCREEN_COPY.cancel,kind:"danger",disabled:form.busy,onClick:form.askRevoke,testID:"records-revoke"}):null,
|
|
552
|
-
/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"aria-label":REQUEST_SCREEN_COPY.whereItStands,"data-testid":"records-request-where",children:[
|
|
553
|
-
/* @__PURE__ */jsx("h3",{style:styles.sectionTitle,children:REQUEST_SCREEN_COPY.whereItStands}),
|
|
554
|
-
/* @__PURE__ */jsx(RequestTimeline,{request:current,petName:petName})]}),clinicRequest?/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface},"aria-label":REQUEST_SCREEN_COPY.details,"data-testid":"records-request-details",children:[
|
|
555
|
-
/* @__PURE__ */jsx("h3",{style:styles.sectionTitle,children:REQUEST_SCREEN_COPY.details}),
|
|
553
|
+
/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface,...styles.cardSlot},"aria-label":REQUEST_SCREEN_COPY.whereItStands,"data-testid":"records-request-where",children:[
|
|
554
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,...styles.cardInk},children:REQUEST_SCREEN_COPY.whereItStands}),
|
|
555
|
+
/* @__PURE__ */jsx(RequestTimeline,{request:current,petName:petName})]}),clinicRequest?/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,backgroundColor:theme.color.surface,...styles.cardSlot},"aria-label":REQUEST_SCREEN_COPY.details,"data-testid":"records-request-details",children:[
|
|
556
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,...styles.cardInk},children:REQUEST_SCREEN_COPY.details}),
|
|
556
557
|
/* @__PURE__ */jsxs("dl",{style:{margin:0,display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"baseline",columnGap:theme.space.lg,rowGap:theme.space.sm},children:[
|
|
557
558
|
/* @__PURE__ */jsx("dt",{style:styles.muted,children:REQUEST_SCREEN_COPY.detailsClinic}),
|
|
558
559
|
/* @__PURE__ */jsx("dd",{style:{...styles.bodyText,margin:0},children:clinicName}),sentDate!=="-"?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
@@ -584,9 +585,10 @@ return jsxs(Fragment,{children:[
|
|
|
584
585
|
return jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsx("div",{style:column,children:/* @__PURE__ */jsx(DashboardSkeleton,{testID:"everfur-records-page-loading"})})});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():void 0,testID:"everfur-records-page-error"}):renderErrorFamily(records,onGrant,canGrant,consentText);/* @__PURE__ */
|
|
585
586
|
return jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsx("div",{style:column,children:body})})}/* @__PURE__ */
|
|
586
587
|
return jsx("div",{style:{...styles.body,...PAGE_BODY},children:/* @__PURE__ */jsxs("div",{style:column,"data-testid":"everfur-records-page-content",children:[
|
|
587
|
-
/* @__PURE__ */jsxs("header",{style:{...styles.creamCard,gap:theme.space.md,padding:`${theme.space.lg+theme.space.xs}px ${theme.space.lg+theme.space.md}px
|
|
588
|
+
/* @__PURE__ */jsxs("header",{style:{...styles.creamCard,gap:theme.space.md,padding:`${theme.space.lg+theme.space.xs}px ${theme.space.lg+theme.space.md}px`,...styles.headerSlot},"data-testid":"everfur-records-page-header",children:[
|
|
589
|
+
/* @__PURE__ */jsx(BrandLogo,{logoUrl:theme.meta.logoUrl,name:theme.meta.displayName,styles:styles.pageLogo}),
|
|
588
590
|
/* @__PURE__ */jsx(PageTitle,{tabIndex:-1,[SCREEN_HEADING_ATTR]:"",style:{...styles.headerTitle,whiteSpace:"normal",overflow:"visible"},children:CONSUMER_PAGE_COPY.titleFor(petName)}),
|
|
589
|
-
/* @__PURE__ */jsx("p",{style:styles.bodyText,children:CONSUMER_PAGE_COPY.lead}),
|
|
591
|
+
/* @__PURE__ */jsx("p",{style:{...styles.bodyText,...styles.headerText},children:CONSUMER_PAGE_COPY.lead}),
|
|
590
592
|
/* @__PURE__ */jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:theme.space.sm},"data-testid":"everfur-records-page-actions",children:[canRequestFromClinic?/* @__PURE__ */jsx(Pill,{label:CONSUMER_PAGE_COPY.requestRecords,onClick:()=>navigate({name:"clinicPicker"}),testID:"everfur-records-page-request-records"}):null,
|
|
591
593
|
/* @__PURE__ */jsx(Pill,{label:CONSUMER_PAGE_COPY.uploadAction,kind:"outline",onClick:()=>navigate({name:"upload"}),testID:"everfur-records-page-upload-action"}),onAsk?/* @__PURE__ */jsx(Pill,{label:CONSUMER_PAGE_COPY.askA11y(petName),kind:"ask",ariaLabel:CONSUMER_PAGE_COPY.askA11y(petName),onClick:()=>onAsk(buildRecordsPageAskPrompt(petName),{type:"marker_summary",id:petRef}),testID:"everfur-records-page-ask"}):null]}),
|
|
592
594
|
/* @__PURE__ */jsxs("nav",{style:{display:"flex",flexWrap:"wrap",columnGap:theme.space.lg,rowGap:theme.space.xs},"data-testid":"everfur-records-page-links",children:[
|
|
@@ -605,18 +607,18 @@ return jsxs("section",{role:"group","aria-label":MARKER_SUMMARY_COPY.title,style
|
|
|
605
607
|
/* @__PURE__ */jsx("span",{style:s.centerLabel,children:totalMarkers===1?MARKER_SUMMARY_COPY.marker:MARKER_SUMMARY_COPY.markers})]})]})}),arcs.length>0?/* @__PURE__ */jsxs("div",{style:s.badges,children:[
|
|
606
608
|
/* @__PURE__ */jsx("span",{style:{...s.badge,borderColor:theme.color.danger,color:theme.color.danger},children:`${outOfRangeCount} ${MARKER_SUMMARY_COPY.outOfRange}`}),
|
|
607
609
|
/* @__PURE__ */jsx("span",{style:{...s.badge,borderColor:theme.color.success,color:theme.color.success},children:`${inRangeCount} ${MARKER_SUMMARY_COPY.inRange}`}),unknownCount>0?/* @__PURE__ */jsx("span",{style:{...s.badge,borderColor:theme.color.text.muted,color:theme.color.text.muted},children:`${unknownCount} ${MARKER_SUMMARY_COPY.noRange}`}):null]}):null,
|
|
608
|
-
/* @__PURE__ */jsx("p",{style:s.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-summary-ask",children:MARKER_SUMMARY_COPY.ask}):null]})}function useStyles3(){let theme=useEverfurTheme();return useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme;return{card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm+space.xs/2,borderRadius:radius.lg,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderRingCream}`,padding:space.lg},title:{margin:0,...
|
|
610
|
+
/* @__PURE__ */jsx("p",{style:s.subtitle,children:MARKER_SUMMARY_COPY.subtitle}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-summary-ask",children:MARKER_SUMMARY_COPY.ask}):null]})}function useStyles3(){let theme=useEverfurTheme();return useMemo(()=>makeStyles7(theme),[theme])}function makeStyles7(theme){let{color:color,space:space,radius:radius,type:type}=theme,recordCard=recordCardSlot(theme.slots),cardText=slotText(recordCard);return{card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.sm+space.xs/2,borderRadius:radius.lg,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderRingCream}`,padding:space.lg,...slotBoxCss(recordCard,1)},title:{margin:0,...headingFaceCss(theme,"bold"),fontSize:type.size.subtitle,color:color.brandInk,letterSpacing:"-0.02em",...cardText},ringRow:{display:"flex",justifyContent:"center"},ringWrap:{position:"relative",width:SIZE,height:SIZE},center:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",pointerEvents:"none"},centerCount:{...faceCss(theme,"medium"),fontSize:type.size.verdict*2,lineHeight:1.1,color:color.text.primary,...cardText},centerLabel:{...faceCss(theme,"medium"),fontSize:type.size.heading-1,lineHeight:1.2,color:color.text.primary,...cardText},badges:{display:"flex",flexWrap:"wrap",justifyContent:"center",gap:space.sm},badge:{border:"1px solid",borderRadius:radius.pill,padding:`${space.xs}px ${space.sm+space.xs/2}px`,...faceCss(theme,"mono"),fontSize:type.size.nano,lineHeight:`${type.size.tiny}px`,textTransform:"uppercase",letterSpacing:type.letterSpacing.headerBrand/2},subtitle:{margin:0,...faceCss(theme,"regular"),fontSize:type.size.caption,lineHeight:`${Math.round(type.size.caption*type.lineHeight.relaxed)}px`,color:color.text.primary,...cardText}}}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}}var PLOT_W=100,PLOT_H=44;function MarkerTrendCard({marker:marker,onPointPress:onPointPress,onAsk:onAsk}){let s=useStyles4(),{theme:theme,styles:styles}=useScreenStyles(),status=markerStatusLabel(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__ */
|
|
609
611
|
return jsx("li",{style:s.page,"data-testid":`marker-card-${marker.markerId}`,children:/* @__PURE__ */jsxs("article",{style:s.card,children:[
|
|
610
612
|
/* @__PURE__ */jsxs("div",{style:s.headerRow,children:[
|
|
611
613
|
/* @__PURE__ */jsxs("div",{style:s.nameColumn,children:[
|
|
612
|
-
/* @__PURE__ */jsx("span",{style:s.markerName,children:marker.name}),marker.unit?/* @__PURE__ */jsx("span",{style:s.unit,children:marker.unit}):null]}),
|
|
614
|
+
/* @__PURE__ */jsx("span",{style:{...s.markerName,...s.cardInk},children:marker.name}),marker.unit?/* @__PURE__ */jsx("span",{style:{...s.unit,...s.cardInk},children:marker.unit}):null]}),
|
|
613
615
|
/* @__PURE__ */jsx("span",{"aria-label":MARKER_CARD_COPY.status(status.label),children:/* @__PURE__ */jsx(Chip,{label:status.label,tone:markerStatusTone(marker.latest?.status??null)})})]}),marker.latest&&latestReading!==null?/* @__PURE__ */jsxs("div",{style:s.latestRow,children:[
|
|
614
|
-
/* @__PURE__ */jsx("span",{style:{...s.latestValue,...status.outOfRange?s.latestValueDanger:
|
|
615
|
-
/* @__PURE__ */jsx("span",{style:s.latestDate,children:formatRecordsDate(marker.latest.at)})]}):null,traj?/* @__PURE__ */jsx("p",{style:s.trajectory,children:traj}):null,chart!==null?/* @__PURE__ */jsxs("div",{style:s.chartWrap,children:[
|
|
616
|
+
/* @__PURE__ */jsx("span",{style:{...s.latestValue,...status.outOfRange?s.latestValueDanger:s.cardInk},"aria-label":MARKER_CARD_COPY.latestA11y(latestReading,status.label,formatRecordsDate(marker.latest.at)),children:latestReading}),
|
|
617
|
+
/* @__PURE__ */jsx("span",{style:{...s.latestDate,...s.cardInk},children:formatRecordsDate(marker.latest.at)})]}):null,traj?/* @__PURE__ */jsx("p",{style:{...s.trajectory,...s.cardInk},children:traj}):null,chart!==null?/* @__PURE__ */jsxs("div",{style:s.chartWrap,children:[
|
|
616
618
|
/* @__PURE__ */jsxs("svg",{viewBox:`0 0 ${PLOT_W} ${PLOT_H}`,preserveAspectRatio:"none",style:s.plot,"aria-hidden":"true",focusable:"false",children:[chart.band?/* @__PURE__ */jsx("rect",{x:0,y:chart.band.topPct/100*PLOT_H,width:PLOT_W,height:Math.max(0,(chart.band.bottomPct-chart.band.topPct)/100*PLOT_H),fill:theme.color.badgeBgPositive}):null,chart.points.length>1?/* @__PURE__ */jsx("polyline",{fill:"none",stroke:theme.color.brandBorder,strokeWidth:.6,vectorEffect:"non-scaling-stroke",points:chart.points.map(p=>`${p.xPct},${p.yPct/100*PLOT_H}`).join(" ")}):null]}),
|
|
617
619
|
/* @__PURE__ */jsx("div",{style:s.dotLayer,children:chart.points.map(p=>/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onPointPress(marker,p.point),"aria-label":markerPointSpoken(marker,p.point),style:{...s.dot,...p.status==="above"||p.status==="below"?s.dotDanger:{},left:`${p.xPct}%`,top:`${p.yPct}%`},"data-testid":`marker-point-${marker.markerId}-${p.index}`},p.index))}),
|
|
618
620
|
/* @__PURE__ */jsx("ul",{"aria-label":MARKER_CARD_COPY.readingsA11y(marker.name),style:s.a11yTable,children:marker.points.map((point,index)=>/* @__PURE__ */jsx("li",{children:markerPointSpoken(marker,point)},index))}),
|
|
619
|
-
/* @__PURE__ */jsx("p",{style:marker.points.length===1?s.singleHint:s.tapHint,children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsx("p",{style:s.emptyBody,children:MARKER_CARD_COPY.empty}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onAsk(marker),style:{...styles.pill,...styles.pillAsk},"data-testid":`marker-ask-${marker.markerId}`,children:MARKER_CARD_COPY.askNamed(marker.name)}):null]})})}function MarkerTrendCarousel({markers:markers,onPointPress:onPointPress,onAsk:onAsk}){let s=useStyles4(),[activeIndex,setActiveIndex]=useState(0),onScroll=event=>{let el=event.currentTarget;el.clientWidth<=0||setActiveIndex(Math.max(0,Math.min(Math.round(el.scrollLeft/el.clientWidth),markers.length-1)))},active=markers[activeIndex]??null;/* @__PURE__ */
|
|
621
|
+
/* @__PURE__ */jsx("p",{style:{...marker.points.length===1?s.singleHint:s.tapHint,...s.cardInk},children:marker.points.length===1?MARKER_CARD_COPY.singleHint:MARKER_CARD_COPY.tapHint})]}):/* @__PURE__ */jsx("p",{style:{...s.emptyBody,...s.cardInk},children:MARKER_CARD_COPY.empty}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onAsk(marker),style:{...styles.pill,...styles.pillAsk},"data-testid":`marker-ask-${marker.markerId}`,children:MARKER_CARD_COPY.askNamed(marker.name)}):null]})})}function MarkerTrendCarousel({markers:markers,onPointPress:onPointPress,onAsk:onAsk}){let s=useStyles4(),[activeIndex,setActiveIndex]=useState(0),onScroll=event=>{let el=event.currentTarget;el.clientWidth<=0||setActiveIndex(Math.max(0,Math.min(Math.round(el.scrollLeft/el.clientWidth),markers.length-1)))},active=markers[activeIndex]??null;/* @__PURE__ */
|
|
620
622
|
return jsxs("div",{style:s.carousel,"data-testid":"marker-carousel",children:[
|
|
621
623
|
/* @__PURE__ */jsx("ul",{style:s.track,onScroll:onScroll,children:markers.map(marker=>/* @__PURE__ */jsx(MarkerTrendCard,{marker:marker,onPointPress:onPointPress,onAsk:onAsk},marker.markerId))}),
|
|
622
624
|
/* @__PURE__ */jsxs("div",{style:s.footer,"aria-label":MARKER_CAROUSEL_COPY.a11y(active?.name??null,activeIndex,markers.length),children:[
|
|
@@ -632,7 +634,7 @@ return jsxs(RecordsDialog,{label:PROVENANCE_COPY.title,onClose:onClose,panelStyl
|
|
|
632
634
|
/* @__PURE__ */jsxs("div",{style:s.valueRow,children:[
|
|
633
635
|
/* @__PURE__ */jsx("span",{style:s.markerName,children:marker.name}),
|
|
634
636
|
/* @__PURE__ */jsx("span",{style:s.latestValue,children:formatMarkerReading(point.value,marker.unit,point.qualitativeResult)})]}),point.reviewed?/* @__PURE__ */jsx("span",{style:s.reviewed,children:PROVENANCE_COPY.reviewed}):null,
|
|
635
|
-
/* @__PURE__ */jsxs("dl",{style:s.details,children:[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("p",{style:s.unverified,children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-provenance-ask",children:PROVENANCE_COPY.ask}):null]})}function useStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:`${Math.round(size*multiplier)}px`,color:fg}),dot=space.md;return{page:{flex:"0 0 100%",scrollSnapAlign:"start",boxSizing:"border-box",padding:`0 ${space.sm}px`,listStyle:"none"},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,borderRadius:radius.lg,border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,padding:space.lg},headerRow:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,display:"flex",flexDirection:"column",gap:space.xs/2,minWidth:0},markerName:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold")},unit:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,color:color.text.muted},latestRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...text3(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold")},latestValueDanger:{color:color.danger},latestDate:text3(type.size.caption,type.lineHeight.normal,color.text.muted),trajectory:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),chartWrap:{position:"relative",display:"flex",flexDirection:"column",gap:space.sm},plot:{display:"block",width:"100%",height:140,borderRadius:radius.sm,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderHairlineGreen}`},dotLayer:{position:"absolute",left:0,right:0,top:0,height:140},dot:{position:"absolute",boxSizing:"border-box",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,border:`2px solid ${color.surface}`,padding:0,cursor:"pointer"},dotDanger:{backgroundColor:color.danger},a11yTable:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",margin:0,padding:0,listStyle:"none"},tapHint:{...text3(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center"},singleHint:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},emptyBody:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",padding:`${space.xxl+space.xs}px 0`},carousel:{display:"flex",flexDirection:"column"},track:{display:"flex",overflowX:"auto",scrollSnapType:"x mandatory",margin:0,padding:0,listStyle:"none"},footer:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{display:"flex",gap:space.xs+space.xs/2},dotIndicator:{display:"block",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:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},sheetBg:{backgroundColor:color.surfaceCream},valueRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,padding:`${space.xs}px ${space.sm+space.xs/2}px`,backgroundColor:color.badgeBgPositive,...text3(type.size.tiny,type.lineHeight.normal,color.success,"medium")},details:{margin:0,display:"flex",flexDirection:"column",gap:space.md},detailRow:{display:"flex",flexDirection:"column",gap:space.xs/2},detailLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},detailValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary),marginLeft:0},unverified:text3(type.size.caption,type.lineHeight.normal,color.text.muted)}}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
637
|
+
/* @__PURE__ */jsxs("dl",{style:s.details,children:[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("p",{style:s.unverified,children:PROVENANCE_COPY.unverified}),onAsk?/* @__PURE__ */jsx("button",{type:"button",onClick:onAsk,style:{...styles.pill,...styles.pillAsk},"data-testid":"marker-provenance-ask",children:PROVENANCE_COPY.ask}):null]})}function useStyles4(){let theme=useEverfurTheme();return useMemo(()=>makeStyles8(theme),[theme])}function makeStyles8(theme){let{color:color,space:space,radius:radius,type:type}=theme,text3=(size,multiplier,fg,weight="regular")=>({margin:0,...faceCss(theme,weight),fontSize:size,lineHeight:`${Math.round(size*multiplier)}px`,color:fg}),dot=space.md,recordCard=recordCardSlot(theme.slots);return{page:{flex:"0 0 100%",scrollSnapAlign:"start",boxSizing:"border-box",padding:`0 ${space.sm}px`,listStyle:"none"},card:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:space.md,borderRadius:radius.lg,border:`1px solid ${color.borderRingCream}`,backgroundColor:color.surface,padding:space.lg,...slotBoxCss(recordCard,1)},cardInk:slotText(recordCard),headerRow:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:space.sm+space.xs/2},nameColumn:{flex:1,display:"flex",flexDirection:"column",gap:space.xs/2,minWidth:0},markerName:{...text3(type.size.subtitle,type.lineHeight.snug,color.text.primary,"bold"),...headingFaceCss(theme,"bold")},unit:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,color:color.text.muted},latestRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},latestValue:{...text3(type.size.verdict+space.xs,type.lineHeight.tight,color.text.primary,"bold")},latestValueDanger:{color:color.danger},latestDate:text3(type.size.caption,type.lineHeight.normal,color.text.muted),trajectory:text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),chartWrap:{position:"relative",display:"flex",flexDirection:"column",gap:space.sm},plot:{display:"block",width:"100%",height:140,borderRadius:radius.sm,backgroundColor:color.surfaceCream,border:`1px solid ${color.borderHairlineGreen}`},dotLayer:{position:"absolute",left:0,right:0,top:0,height:140},dot:{position:"absolute",boxSizing:"border-box",width:dot,height:dot,borderRadius:dot/2,marginLeft:-dot/2,marginTop:-dot/2,backgroundColor:color.brand,border:`2px solid ${color.surface}`,padding:0,cursor:"pointer"},dotDanger:{backgroundColor:color.danger},a11yTable:{position:"absolute",width:1,height:1,overflow:"hidden",clip:"rect(0 0 0 0)",margin:0,padding:0,listStyle:"none"},tapHint:{...text3(type.size.tiny,type.lineHeight.normal,color.text.placeholder),textAlign:"center"},singleHint:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted),textAlign:"center"},emptyBody:{...text3(type.size.bodyTight,type.lineHeight.normal,color.text.muted),textAlign:"center",padding:`${space.xxl+space.xs}px 0`},carousel:{display:"flex",flexDirection:"column"},track:{display:"flex",overflowX:"auto",scrollSnapType:"x mandatory",margin:0,padding:0,listStyle:"none"},footer:{display:"flex",flexDirection:"column",alignItems:"center",gap:space.sm,paddingTop:space.md},dots:{display:"flex",gap:space.xs+space.xs/2},dotIndicator:{display:"block",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:{...faceCss(theme,"mono"),fontSize:type.size.tiny,lineHeight:`${type.size.body}px`,letterSpacing:type.letterSpacing.eyebrow/3,color:color.text.muted},sheetBg:{backgroundColor:color.surfaceCream},valueRow:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:space.md},reviewed:{alignSelf:"flex-start",borderRadius:radius.pill,padding:`${space.xs}px ${space.sm+space.xs/2}px`,backgroundColor:color.badgeBgPositive,...text3(type.size.tiny,type.lineHeight.normal,color.success,"medium")},details:{margin:0,display:"flex",flexDirection:"column",gap:space.md},detailRow:{display:"flex",flexDirection:"column",gap:space.xs/2},detailLabel:{...text3(type.size.caption,type.lineHeight.normal,color.text.muted,"medium")},detailValue:{...text3(type.size.body,type.lineHeight.normal,color.text.primary),marginLeft:0},unverified:text3(type.size.caption,type.lineHeight.normal,color.text.muted)}}var readDepth3=(client,petRef)=>client.getRecordDepth(petRef),depthEmpty3=value=>!value.available;function EverfurRecordsDashboard(props){let{style:style,className:className,renderPending:renderPending,...rest}=guardHostProps(props,["onNavigate","onBack","onAsk"]),{userRef:userRef}=useEverfurContext(),{styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
636
638
|
return jsx(CapabilityGate,{capability:"records",style:style,className:className,...renderPending?{renderPending:renderPending}:{},...recordsGateExit(rest.onBack,BACK_LABEL),children:/* @__PURE__ */jsxs("div",{className:className,style:{...styles.root,...style},"data-testid":"records-dashboard",children:[userRef===null?/* @__PURE__ */jsx("div",{style:styles.body,children:/* @__PURE__ */jsx(AlertState,{label:RECORDS_COPY.sessionRequired,glyph:"empty"})}):/* @__PURE__ */jsx(DashboardBody,{...rest}),
|
|
637
639
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})})}function DashboardBody({petRef:petRef,petName:petName,controller:controller,consentVersion:consentVersion,consentText:consentText,onNavigate:onNavigate,onBack:onBack,onAsk:onAsk}){let{theme:theme,styles:styles}=useScreenStyles(),recordsOpts=useMemo(()=>controller?{petRef:petRef,controller:controller,readUploadFeatures:true}:{petRef:petRef,readUploadFeatures:true},[petRef,controller]),records=useEverfurRecords(recordsOpts),markers=useRecordsMarkers(petRef),depth=useRecordsDepthRead(petRef,readDepth3,depthEmpty3),[provenance,setProvenance]=useState(null),onPointPress=useCallback((marker,point)=>setProvenance({marker:marker,point:point}),[]);useConsentTextWarning2(consentVersion,consentText);let canGrant=canGrantConsent(consentVersion,records.consent),onGrant=()=>{let version=resolveConsentVersion(consentVersion,records.consent);version.length!==0&&records.grantConsent(version,`records-consent-${Date.now().toString(36)}`)},markerList=markers.markers?.markers??[],hasMarkers=markerList.length>0,hasFullRecord=records.record!==null&&!records.record.isEmpty&&!records.record.withheld,drivingRequest=pickPetRecordsRequest(records.requests,petRef),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),rise=useSectionRise(),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,actionRow=(label,onClick,testID)=>/* @__PURE__ */jsxs("button",{type:"button",onClick:onClick,"aria-label":label,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",borderRadius:theme.radius.lg,border:`1px solid ${theme.color.borderRingCream}`,backgroundColor:theme.color.surface,padding:theme.space.lg,cursor:"pointer",font:"inherit",color:theme.color.text.primary,textAlign:"left"},"data-testid":testID,children:[
|
|
638
640
|
/* @__PURE__ */jsxs("span",{style:{display:"flex",alignItems:"center",gap:theme.space.md},children:[
|
|
@@ -646,7 +648,7 @@ return jsx(CapabilityGate,{capability:"records",style:style,className:className,
|
|
|
646
648
|
/* @__PURE__ */jsx(WayCard,{title:REQUEST_PROMPT_COPY.uploadDocument,...acceptsPhotos(records.uploadContentTypes)?{sub:IN_PROGRESS_COPY.uploadDocumentPhotoSub}:{},dashed:true,onClick:()=>onNavigate({name:"upload"}),testID:"dashboard-way-upload"})]}):null,
|
|
647
649
|
/* @__PURE__ */jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"none":body=/* @__PURE__ */jsxs("div",{ref:rise,style:styles.content,"data-testid":"dashboard-request-prompt",children:[
|
|
648
650
|
/* @__PURE__ */jsxs("section",{style:{...styles.creamCard,gap:theme.space.md},children:[
|
|
649
|
-
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:REQUEST_PROMPT_COPY.firstRecordTitle(petName)}),
|
|
651
|
+
/* @__PURE__ */jsx("h3",{style:{...styles.sectionTitle,color:theme.color.brandInk,...styles.cardInk},children:REQUEST_PROMPT_COPY.firstRecordTitle(petName)}),
|
|
650
652
|
/* @__PURE__ */jsx("p",{style:styles.bodyText,children:REQUEST_PROMPT_COPY.body}),onNavigate?/* @__PURE__ */jsxs(Fragment,{children:[
|
|
651
653
|
/* @__PURE__ */jsx("p",{style:styles.muted,children:REQUEST_PROMPT_COPY.requestFromClinicSub}),
|
|
652
654
|
/* @__PURE__ */jsx(Pill,{label:REQUEST_PROMPT_COPY.requestFromClinic,onClick:()=>onNavigate({name:"clinicPicker"}),testID:"dashboard-request-prompt-clinic"}),
|
|
@@ -654,14 +656,14 @@ return jsx(CapabilityGate,{capability:"records",style:style,className:className,
|
|
|
654
656
|
/* @__PURE__ */jsx(DisclaimerBand,{disclaimer:disclaimer})]});break;case"labs_only":body=/* @__PURE__ */jsxs("div",{ref:rise,style:styles.contentTight,"data-testid":"dashboard-labs-only",children:[labs,
|
|
655
657
|
/* @__PURE__ */jsx("div",{style:styles.inset,children:/* @__PURE__ */jsx(DisclaimerBand,{disclaimer:disclaimer})}),actions(false)]});break;default:body=assertNever(view)}/* @__PURE__ */
|
|
656
658
|
return jsxs(Fragment,{children:[
|
|
657
|
-
/* @__PURE__ */jsx(ScreenHeader,{title:DASHBOARD_COPY.titleWeb(petName),onBack:onBack,testID:"dashboard-header",right:onNavigate?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onNavigate({name:"timeline"}),"aria-label":DASHBOARD_COPY.openTimeline,style:styles.iconButton,"data-testid":"dashboard-timeline-link",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:4},children:[0,1,2].map(i=>/* @__PURE__ */jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:theme.color.brand}},i))})}):void 0}),
|
|
659
|
+
/* @__PURE__ */jsx(ScreenHeader,{title:DASHBOARD_COPY.titleWeb(petName),onBack:onBack,testID:"dashboard-header",right:onNavigate?/* @__PURE__ */jsx("button",{type:"button",onClick:()=>onNavigate({name:"timeline"}),"aria-label":DASHBOARD_COPY.openTimeline,style:styles.iconButton,"data-testid":"dashboard-timeline-link",children:/* @__PURE__ */jsx("span",{"aria-hidden":"true",style:{display:"flex",flexDirection:"column",gap:4},children:[0,1,2].map(i=>/* @__PURE__ */jsx("span",{style:{display:"block",width:18,height:2,borderRadius:2,backgroundColor:theme.slots.header?.textColor??theme.color.brand}},i))})}):void 0}),
|
|
658
660
|
/* @__PURE__ */jsx("div",{style:styles.body,children:body}),
|
|
659
661
|
/* @__PURE__ */jsx(MarkerProvenanceDialog,{marker:provenance?.marker??null,point:provenance?.point??null,onClose:()=>setProvenance(null),onAsk:askReading})]})}function InProgressCard({request:request,petName:petName,onOpen:onOpen,onAsk:onAsk}){let{theme:theme,styles:styles}=useScreenStyles(),title=IN_PROGRESS_COPY.title(petName),clinic=request.clinicName?.trim()??"",status=selectPrimaryLabel(request),content=/* @__PURE__ */jsxs("div",{style:{display:"flex",flexDirection:"column",gap:theme.space.lg},children:[
|
|
660
662
|
/* @__PURE__ */jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:theme.space.sm},children:[
|
|
661
663
|
/* @__PURE__ */jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2,minWidth:0},children:[
|
|
662
|
-
/* @__PURE__ */jsx("span",{style:{...styles.sectionTitle,color:theme.color.brandInk},children:title}),clinic.length>0?/* @__PURE__ */jsx("span",{style:styles.rowDetail,children:clinic}):null]}),onOpen?/* @__PURE__ */jsx(Chevron,{}):null]}),
|
|
664
|
+
/* @__PURE__ */jsx("span",{style:{...styles.sectionTitle,color:theme.color.brandInk,...styles.cardInk},children:title}),clinic.length>0?/* @__PURE__ */jsx("span",{style:styles.rowDetail,children:clinic}):null]}),onOpen?/* @__PURE__ */jsx(Chevron,{}):null]}),
|
|
663
665
|
/* @__PURE__ */jsx(RequestTimeline,{request:request,petName:petName}),status.length>0?/* @__PURE__ */jsx("p",{style:styles.statusCard,children:status}):null]});/* @__PURE__ */
|
|
664
|
-
return jsxs("section",{"aria-label":onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),style:{...styles.creamCard,backgroundColor:theme.color.surface,padding:theme.space.lg+theme.space.xs/2,gap:theme.space.lg},"data-testid":"dashboard-in-progress-card",children:[onOpen?/* @__PURE__ */jsx("button",{type:"button",onClick:onOpen,"aria-label":[title,clinic,status].filter(part=>part.length>0).join(". "),style:{background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit",width:"100%"},"data-testid":"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onClick:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,ariaLabel:ariaLabel,dashed:dashed=false,onClick:onClick,testID:testID}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
666
|
+
return jsxs("section",{"aria-label":onOpen?void 0:IN_PROGRESS_COPY.a11y(petName),style:{...styles.creamCard,backgroundColor:theme.color.surface,padding:theme.space.lg+theme.space.xs/2,gap:theme.space.lg,...styles.cardSlot},"data-testid":"dashboard-in-progress-card",children:[onOpen?/* @__PURE__ */jsx("button",{type:"button",onClick:onOpen,"aria-label":[title,clinic,status].filter(part=>part.length>0).join(". "),style:{background:"transparent",border:0,padding:0,cursor:"pointer",textAlign:"left",font:"inherit",color:"inherit",width:"100%"},"data-testid":"dashboard-in-progress-open",children:content}):content,onAsk?/* @__PURE__ */jsx(Pill,{label:IN_PROGRESS_COPY.ask,kind:"ask",onClick:onAsk,testID:"dashboard-in-progress-ask"}):null]})}function WayCard({title:title,sub:sub,ariaLabel:ariaLabel,dashed:dashed=false,onClick:onClick,testID:testID}){let{theme:theme,styles:styles}=useScreenStyles();/* @__PURE__ */
|
|
665
667
|
return jsxs("button",{type:"button",onClick:onClick,"aria-label":ariaLabel,style:{...styles.creamCard,width:"100%",textAlign:"left",cursor:"pointer",font:"inherit",color:"inherit",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:theme.space.md,...dashed?{borderStyle:"dashed",borderColor:theme.color.brandBorderStrong}:{}},"data-testid":testID,children:[
|
|
666
668
|
/* @__PURE__ */jsxs("span",{style:{display:"flex",flexDirection:"column",gap:theme.space.xs/2},children:[
|
|
667
669
|
/* @__PURE__ */jsx("span",{style:{...styles.rowTitle,...faceCss(theme,"bold")},children:title}),sub?/* @__PURE__ */jsx("span",{style:styles.muted,children:sub}):null]}),
|
|
@@ -673,16 +675,16 @@ return jsx(CapabilityGate,{capability:"records",style:style,className:className,
|
|
|
673
675
|
/* @__PURE__ */jsx(Pill,{label:CONSUMER_PAGE_COPY.uploadAction,kind:"outline",onClick:()=>onNavigate({name:"upload"}),testID:"records-requests-upload"})]}):null,body]})})]})}function EverfurRecordsFlow(props){let{petRef:petRef,petName:petName,controller:controller,clinicController:clinicController,consentVersion:consentVersion,consentText:consentText,ownerName:ownerName,onCaptureSignature:onCaptureSignature,initialScreen:initialScreen,historyMode:historyMode="memory",onExit:onExit,style:style,className:className,renderPending:renderPending,onOpenUrl:onOpenUrl,onCopy:onCopy,onAsk:onAsk,location:location2}=guardHostProps(props,["onExit"]),[nav,dispatch]=useReducer(recordsNavReducer,initialScreen,initialRecordsNav),screen=currentRecordsScreen(nav),depth=nav.stack.length,depthRef=useRef(depth);depthRef.current=depth;let pushedRef=useRef(depth),fromHistoryRef=useRef(false);useEffect(()=>{if(historyMode!=="browser"||typeof window>"u")return;let onPopState=event=>{let state=event.state;(typeof state?.efRecords=="number"?state.efRecords:1)<depthRef.current&&(fromHistoryRef.current=true,dispatch({type:"pop"}))};return window.addEventListener("popstate",onPopState),()=>window.removeEventListener("popstate",onPopState)},[historyMode]),useEffect(()=>{if(historyMode!=="browser"||typeof window>"u")return;let pushed=pushedRef.current;depth>pushed?window.history.pushState({efRecords:depth},""):depth<pushed&&!fromHistoryRef.current&&window.history.go(depth-pushed),fromHistoryRef.current=false,pushedRef.current=depth},[historyMode,depth]);let onNavigate=useCallback(to=>dispatch({type:"navigate",screen:to}),[]),onBack=useMemo(()=>popRecordsNav(nav).handled?()=>dispatch({type:"pop"}):onExit,[nav,onExit]),focusRoot=useFocusScreenOnChange(screen,initialScreen!==void 0),seams={onNavigate:onNavigate,...onBack?{onBack:onBack}:{},...petName!==void 0?{petName:petName}:{},...onOpenUrl?{onOpenUrl:onOpenUrl}:{},...onCopy?{onCopy:onCopy}:{},...onAsk?{onAsk:onAsk}:{},...location2?{location:location2}:{}},records={...controller?{controller:controller}:{},...consentVersion!==void 0?{consentVersion:consentVersion}:{},...consentText!==void 0?{consentText:consentText}:{}},box={...style?{style:style}:{},...className!==void 0?{className:className}:{}},pending=renderPending?{renderPending:renderPending}:{},content;switch(screen.name){case"dashboard":content=/* @__PURE__ */jsx(EverfurRecordsDashboard,{petRef:petRef,...seams,...records,...pending,...box});break;case"request":content=/* @__PURE__ */jsx(EverfurRecordsRequest,{petRef:petRef,requestId:screen.requestId,...seams,...controller?{controller:controller}:{},...pending,...box});break;case"timeline":content=/* @__PURE__ */jsx(EverfurRecordsTimeline,{petRef:petRef,...seams,...box});break;case"record":content=/* @__PURE__ */jsx(EverfurRecordDetail,{petRef:petRef,...seams,...records,...pending,...box});break;case"document":content=/* @__PURE__ */jsx(EverfurRecordDocument,{petRef:petRef,...seams,...records,...pending,...box});break;case"contributions":content=/* @__PURE__ */jsx(EverfurDocumentContributions,{petRef:petRef,docId:screen.docId,...seams,...box});break;case"clinicPicker":content=/* @__PURE__ */jsx(EverfurClinicPicker,{petRef:petRef,...seams,...clinicController?{controller:clinicController}:{},...controller?{recordsController:controller}:{},...box});break;case"clinicBatch":content=/* @__PURE__ */jsx(EverfurClinicRequestBatch,{petRef:petRef,petName:petName??"",ownerName:ownerName??"",...onBack?{onClose:onBack}:{},onCreated:()=>dispatch({type:"navigate",screen:{name:"dashboard"}}),...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},...box});break;case"consent":content=/* @__PURE__ */jsx(EverfurRecordsConsent,{petRef:petRef,clinic:screen.clinic,...seams,...ownerName!==void 0?{ownerName:ownerName}:{},...onCaptureSignature?{onCaptureSignature:onCaptureSignature}:{},...clinicController?{controller:clinicController}:{},...box});break;case"upload":content=/* @__PURE__ */jsx(EverfurRecordsUpload,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,...box});break;case"requests":content=/* @__PURE__ */jsx(EverfurRecordsRequests,{petRef:petRef,...seams,...controller?{controller:controller}:{},...pending,...box});break;default:content=assertNever(screen)}
|
|
674
676
|
/* @__PURE__ */
|
|
675
677
|
return jsx("div",{ref:focusRoot,style:FLOW_ROOT,"data-testid":"everfur-records-flow",children:content})}var FLOW_ROOT=/* @__PURE__ */Object.freeze({display:"contents"}),EverfurRecords=EverfurRecordsFlow;function EverfurClinicRequest(props){let{userRef:userRef,scopeEpoch:scopeEpoch}=useEverfurContext();/* @__PURE__ */
|
|
676
|
-
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx("p",{role:"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(),controller=props.controller??runtimeController,theme=useEverfurTheme(),formRef={current:null},pad=useSignatureCanvas(()=>formRef.current?.invalidate()),form=useClinicRequestForm(props,controller,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null));formRef.current=form;let field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},button={...field,cursor:"pointer"},clear=()=>{form.busy||pad.clear()};/* @__PURE__ */
|
|
678
|
+
return jsx(CapabilityGate,{capability:"recordsClinic",...recordsGateExit(props.onClose,CLINIC_REQUEST_COPY.cancel),children:userRef===null?/* @__PURE__ */jsx("p",{role:"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(),controller=props.controller??runtimeController,theme=useEverfurTheme(),formRef={current:null},pad=useSignatureCanvas(()=>formRef.current?.invalidate()),form=useClinicRequestForm(props,controller,props.onCaptureSignature??(async context=>pad.signed?pad.capture(controller,context.signal):null));formRef.current=form;let field={minHeight:44,padding:theme.space.sm,border:`1px solid ${theme.color.borderHairlineGreen}`,borderRadius:theme.radius.sm,background:theme.color.surface,color:theme.color.text.primary,font:"inherit"},inputSlot=slotCss(theme.slots.input,1),button={...field,cursor:"pointer"},clear=()=>{form.busy||pad.clear()};/* @__PURE__ */
|
|
677
679
|
return jsxs("section",{className:props.className,"aria-label":CLINIC_REQUEST_COPY.title,style:{background:theme.color.surface,color:theme.color.text.primary,padding:theme.space.lg,borderRadius:theme.radius.lg,minHeight:120,minWidth:0,overflowWrap:"anywhere",...props.style},children:[
|
|
678
680
|
/* @__PURE__ */jsx("h2",{style:{margin:0,fontSize:theme.type.size.heading},children:CLINIC_REQUEST_COPY.title}),
|
|
679
681
|
/* @__PURE__ */jsx("p",{style:{margin:`${theme.space.sm}px 0 ${theme.space.lg}px`},children:props.petName}),form.created?/* @__PURE__ */jsx("p",{role:"status",children:form.created.statusLabel||RECORDS_COPY.records}):/* @__PURE__ */jsxs("div",{style:{display:"grid",gap:theme.space.md},children:[
|
|
680
682
|
/* @__PURE__ */jsxs("label",{children:[CLINIC_REQUEST_COPY.ownerName,
|
|
681
|
-
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},maxLength:200,value:form.ownerName,disabled:form.busy,autoComplete:"name",onChange:event=>{clear(),form.setOwnerName(event.target.value)}})]}),
|
|
683
|
+
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box",...inputSlot},maxLength:200,value:form.ownerName,disabled:form.busy,autoComplete:"name",onChange:event=>{clear(),form.setOwnerName(event.target.value)}})]}),
|
|
682
684
|
/* @__PURE__ */jsxs("label",{children:[CLINIC_REQUEST_COPY.clinic,
|
|
683
|
-
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},placeholder:CLINIC_REQUEST_COPY.placeholder,maxLength:200,value:form.query,disabled:form.busy,autoComplete:"off",onChange:event=>{clear(),form.setQuery(event.target.value)}})]}),
|
|
685
|
+
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box",...inputSlot},placeholder:CLINIC_REQUEST_COPY.placeholder,maxLength:200,value:form.query,disabled:form.busy,autoComplete:"off",onChange:event=>{clear(),form.setQuery(event.target.value)}})]}),
|
|
684
686
|
/* @__PURE__ */jsx("button",{type:"button",style:button,disabled:form.busy||form.searching||form.query.trim().length<2,onClick:()=>{form.search()},children:CLINIC_REQUEST_COPY.search}),form.searching&&/* @__PURE__ */jsx("p",{role:"status",children:RECORDS_COPY.loading}),form.recent.length>0&&/* @__PURE__ */jsx("h3",{style:{margin:`${theme.space.sm}px 0 0`,fontSize:theme.type.size.subtitle},"data-testid":"records-clinic-recent-label",children:CLINIC_REQUEST_COPY.recentlyUsed}),form.recent.map(clinic=>/* @__PURE__ */jsxs("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{clear(),form.selectClinic(clinic)},children:[clinic.name,clinic.address?`, ${clinic.address}`:"",clinic.phone?`, ${clinic.phone}`:""]},`recent-${clinic.id}`)),form.visibleClinics.map(clinic=>/* @__PURE__ */jsxs("button",{type:"button",style:button,disabled:form.busy,onClick:()=>{clear(),form.selectClinic(clinic)},children:[clinic.name,clinic.address?`, ${clinic.address}`:"",clinic.phone?`, ${clinic.phone}`:""]},clinic.id)),form.hasMoreClinics&&/* @__PURE__ */jsx("button",{type:"button",style:button,disabled:form.busy,onClick:form.showMoreClinics,"data-testid":"records-clinic-results-more",children:CLINIC_REQUEST_COPY.moreClinics}),form.needsEmail&&/* @__PURE__ */jsxs("label",{children:[CLINIC_REQUEST_COPY.email,
|
|
685
|
-
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box"},type:"email",placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,maxLength:320,autoComplete:"off",value:form.email,disabled:form.busy,onChange:event=>{clear(),form.setEmail(event.target.value)}})]}),
|
|
687
|
+
/* @__PURE__ */jsx("input",{style:{...field,display:"block",width:"100%",boxSizing:"border-box",...inputSlot},type:"email",placeholder:CLINIC_REQUEST_COPY.emailPlaceholder,maxLength:320,autoComplete:"off",value:form.email,disabled:form.busy,onChange:event=>{clear(),form.setEmail(event.target.value)}})]}),
|
|
686
688
|
/* @__PURE__ */jsx("h3",{style:{margin:`${theme.space.sm}px 0 0`,fontSize:theme.type.size.subtitle},children:CLINIC_REQUEST_COPY.scopeHeading}),form.copy?/* @__PURE__ */jsx("p",{style:{whiteSpace:"pre-wrap",margin:0},children:form.query.trim()&&form.ownerName.trim()?form.scope??makeEverfurError("internalError").displayMessage:RECORDS_COPY.consentRequired}):!form.error&&/* @__PURE__ */jsx("p",{role:"status",children:RECORDS_COPY.loading}),!props.onCaptureSignature&&/* @__PURE__ */jsx(SignatureCanvas,{pad:pad,disabled:form.busy}),form.error&&/* @__PURE__ */jsx("p",{role:"alert",children:form.error.displayMessage}),!form.copy&&form.error&&/* @__PURE__ */jsx("button",{type:"button",style:button,onClick:form.retryCopy,children:RECORDS_COPY.retry}),
|
|
687
689
|
/* @__PURE__ */jsx("button",{type:"button",style:{...button,background:theme.color.primary,color:theme.color.onPrimary,opacity:form.busy||!form.ready||!props.onCaptureSignature&&!pad.signed?.5:1},disabled:form.busy||!form.ready||!props.onCaptureSignature&&!pad.signed,onClick:()=>{form.submit()},children:form.busy?CLINIC_REQUEST_COPY.sending:CLINIC_REQUEST_COPY.send})]}),props.onClose&&/* @__PURE__ */jsx("button",{type:"button",style:button,disabled:form.busy,onClick:props.onClose,children:CLINIC_REQUEST_COPY.cancel}),
|
|
688
690
|
/* @__PURE__ */jsx(RecordsFootnote,{})]})}var FILE_FIELD="file",NO_BYTES="records upload: the file handle carries no bytes",FAILED="records upload failed";function createWebRecordsUploadTransport(options={}){let makeXhr=options.xhr??(()=>new XMLHttpRequest);/* @__PURE__ */
|