@medplum/react 5.1.8 → 5.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +2 -2
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +3 -3
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +14 -14
package/dist/esm/index.mjs
CHANGED
|
@@ -100,15 +100,15 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
100
100
|
subject { display }
|
|
101
101
|
}
|
|
102
102
|
}`.replaceAll(/\s+/g," ")}function getResourcesFromResponse2(response){let resources=[];return response.data.Patients1&&resources.push(...response.data.Patients1),response.data.Patients2&&resources.push(...response.data.Patients2),response.data.ServiceRequestList&&resources.push(...response.data.ServiceRequestList),dedupeResources2(resources)}function dedupeResources2(resources){let ids=new Set,result=[];for(let resource of resources)resource.id&&!ids.has(resource.id)&&(ids.add(resource.id),result.push(resource));return result}function patientsToActions(patients,navigate){let patientActions=patients.filter(p=>!!p.id).map(patient=>({id:patient.id,label:patient.name?formatHumanName4(patient.name[0]):patient.id,description:patient.birthDate,leftSection:jsx19(ResourceAvatar,{value:patient,radius:"xl",size:24}),onClick:()=>navigate(`/Patient/${patient.id}`)}));return patientActions.length>0?[{group:"Patients",actions:patientActions}]:[]}function resourcesToActions(resources,resourceTypes,navigate){let result=[],resourceTypeActions=resourceTypes.map(rt=>({id:`resource-type-${rt.code}`,label:rt.display??rt.code??"",description:"Resource Type",onClick:()=>navigate(`/${rt.code}`)}));resourceTypeActions.length>0&&result.push({group:"Resource Types",actions:resourceTypeActions});let patientActions=[],serviceRequestActions=[];for(let resource of resources)resource.resourceType==="Patient"&&resource.id?patientActions.push({id:resource.id,label:resource.name?formatHumanName4(resource.name[0]):resource.id,description:resource.birthDate,leftSection:jsx19(ResourceAvatar,{value:resource,radius:"xl",size:24}),onClick:()=>navigate(`/Patient/${resource.id}`)}):resource.resourceType==="ServiceRequest"&&resource.id&&serviceRequestActions.push({id:resource.id,label:resource.id,description:resource.subject?.display,onClick:()=>navigate(`/ServiceRequest/${resource.id}`)});return patientActions.length>0&&result.push({group:"Patients",actions:patientActions}),serviceRequestActions.length>0&&result.push({group:"Service Requests",actions:serviceRequestActions}),result}import{Fragment as Fragment5,jsx as jsx20,jsxs as jsxs9}from"react/jsx-runtime";function Navbar(props){let navigate=useMedplumNavigate4(),profile=useMedplumProfile3(),activeLink=getActiveLink(props.pathname,props.searchParams,props.menus),[userMenuOpened,setUserMenuOpened]=useState10(!1),[bookmarkDialogVisible,setBookmarkDialogVisible]=useState10(!1);function onLinkClick2(e,to){e.stopPropagation(),e.preventDefault(),navigate(to),window.innerWidth<768&&props.closeNavbar()}function navigateResourceType(resourceType){resourceType&&navigate(`/${resourceType}`)}let opened=props.opened??!0;return jsxs9(Fragment5,{children:[jsxs9(MantineAppShell2.Navbar,{id:"navbar",className:Navbar_default.navbar,children:[props.logo&&jsx20(MantineAppShell2.Section,{px:"xs",pt:"xs",pb:"4px",children:jsx20(UnstyledButton2,{className:Navbar_default.logoButton,onClick:props.navbarToggle,"aria-expanded":opened,"aria-controls":"navbar","aria-label":"Medplum Logo",children:props.logo})}),jsx20(ScrollArea,{px:"xs",pb:"xs",pt:"sm",h:"100%",children:jsxs9(MantineAppShell2.Section,{grow:!0,children:[props.spotlightEnabled&&jsx20(Box,{mb:2,children:jsx20(Tooltip,{label:"Search",position:"right",transitionProps:{duration:0},disabled:opened,children:jsxs9(UnstyledButton2,{className:Navbar_default.link,onClick:()=>spotlight.open(),"aria-label":"Search",children:[jsx20(IconSearch,{size:"1.2rem"}),jsx20("span",{className:Navbar_default.linkLabel,"data-opened":opened||void 0,children:"Search"})]})})}),props.spotlightEnabled&&jsx20(Spotlight,{patientsOnly:props.patientsOnly}),!props.resourceTypeSearchDisabled&&jsx20(MantineAppShell2.Section,{mb:"sm",children:jsx20(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:newValue=>navigateResourceType(newValue)},window.location.pathname)}),props.menus?.map((menu,index)=>jsxs9(Fragment4,{children:[menu.title&&jsx20(Text6,{className:Navbar_default.menuTitle,"data-opened":opened||void 0,children:menu.title}),jsx20(Stack4,{gap:"2",children:menu.links?.map(link=>link.notificationCount?jsx20(NavbarLinkWithSubscription,{to:link.href,active:link.href===activeLink?.href,onClick:e=>onLinkClick2(e,link.href),icon:link.icon,label:link.label??"",opened,alert:link.alert,notificationCount:link.notificationCount,onDismiss:link.onDismiss},link.href):jsx20(NavbarLinkContent,{to:link.href,active:link.href===activeLink?.href,onClick:e=>onLinkClick2(e,link.href),icon:link.icon,label:link.label??"",opened,alert:link.alert,count:link.count,onDismiss:link.onDismiss},link.href))})]},`menu-${menu.title??index}`)),props.displayAddBookmark&&jsx20(Tooltip,{label:"Add Bookmark",position:"right",transitionProps:{duration:0},disabled:opened,children:jsxs9(UnstyledButton2,{className:`${Navbar_default.link} ${Navbar_default.addBookmarkLink}`,onClick:()=>setBookmarkDialogVisible(!0),children:[jsx20(IconCirclePlus,{}),jsx20("span",{className:Navbar_default.linkLabel,"data-opened":opened||void 0,children:"Add Bookmark"})]})})]})}),props.userMenuEnabled&&jsxs9(MantineAppShell2.Section,{px:"xs",py:"xs",children:[jsx20(Tooltip,{label:opened?"Close Sidebar":"Open Sidebar",position:"right",transitionProps:{duration:0},children:jsx20(UnstyledButton2,{className:Navbar_default.toggleButton,"aria-label":opened?"Close Sidebar":"Open Sidebar",onClick:props.navbarToggle,"aria-expanded":opened,"aria-controls":"navbar",children:jsx20(IconLayoutSidebar,{})})}),jsx20(Divider,{my:"xs",mx:6,className:Navbar_default.divider}),jsxs9(Menu3,{width:260,shadow:"xl",position:"top-start",transitionProps:{transition:"fade-up"},opened:userMenuOpened,onClose:()=>setUserMenuOpened(!1),children:[jsx20(Menu3.Target,{children:jsxs9(UnstyledButton2,{className:Navbar_default.link,pl:"7","aria-label":"User menu","data-active":userMenuOpened||void 0,onClick:()=>setUserMenuOpened(o=>!o),bd:"1px 0 0 0 solid var(--mantine-color-gray-200)",children:[jsx20(ResourceAvatar,{value:profile,radius:"xl",size:24}),jsx20("span",{className:Navbar_default.linkLabel,"data-opened":opened||void 0,children:formatHumanName5(profile?.name?.[0])})]})}),jsx20(Menu3.Dropdown,{children:jsx20(HeaderDropdown,{version:props.version,showLayoutVersionToggle:props.showLayoutVersionToggle})})]})]})]}),props.pathname&&props.searchParams&&jsx20(BookmarkDialog,{pathname:props.pathname,searchParams:props.searchParams,visible:bookmarkDialogVisible,onOk:()=>setBookmarkDialogVisible(!1),onCancel:()=>setBookmarkDialogVisible(!1)})]})}function NavbarLinkContent(props){let{to,icon,label,onClick,active,count,alert,opened,onDismiss}=props,showCount=count!==void 0&&count>0,iconElement=icon??jsx20(IconBookmark,{}),showDot=showCount&&alert&&!opened;function handleDismiss(e){e.preventDefault(),e.stopPropagation(),onDismiss?.()}return jsx20(Tooltip,{label,position:"right",transitionProps:{duration:0},disabled:opened,children:jsxs9(MedplumLink,{to,onClick,className:Navbar_default.link,"data-active":active||void 0,children:[jsxs9("span",{className:Navbar_default.iconWrapper,children:[iconElement,showDot&&jsx20("span",{className:Navbar_default.alertDot})]}),jsx20("span",{className:Navbar_default.linkLabel,"data-opened":opened||void 0,children:label}),showCount&&jsx20("span",{className:Navbar_default.linkCount,"data-opened":opened||void 0,"data-alert":alert||void 0,children:count.toLocaleString()}),onDismiss&&opened&&jsx20(Tooltip,{label:"Dismiss",openDelay:500,children:jsx20(UnstyledButton2,{"aria-label":"Dismiss",className:Navbar_default.dismissButton,onClick:handleDismiss,children:jsx20(IconX,{size:14})})})]})})}function NavbarLinkWithSubscription(props){let count=useNotificationCount(props.notificationCount);return jsx20(NavbarLinkContent,{to:props.to,active:props.active,onClick:props.onClick,icon:props.icon,label:props.label,opened:props.opened,alert:props.alert,count,onDismiss:props.onDismiss})}function getActiveLink(currentPathname,currentSearchParams,menus){if(!currentPathname||!currentSearchParams||!menus)return;let bestLink,bestScore=0;for(let menu of menus)if(menu.links)for(let link of menu.links){let score=getLinkScore(currentPathname,currentSearchParams,link.href);score>bestScore&&(bestScore=score,bestLink=link)}return bestLink}function getLinkScore(currentPathname,currentSearchParams,linkHref){let linkUrl=new URL(linkHref,"https://example.com");if(currentPathname!==linkUrl.pathname)return 0;let ignoredParams=["_count","_offset"];for(let[key,value]of linkUrl.searchParams.entries())if(!ignoredParams.includes(key)&¤tSearchParams.get(key)!==value)return 0;let count=1;for(let[key,value]of currentSearchParams.entries())ignoredParams.includes(key)||linkUrl.searchParams.get(key)===value&&count++;return count}import{jsx as jsx21,jsxs as jsxs10}from"react/jsx-runtime";var OPEN_WIDTH=250,CLOSED_WIDTH=59;function AppShell(props){let[navbarOpen,setNavbarOpen]=useState11(localStorage.navbarOpen==="true"),[layoutVersion]=useState11(props.layoutVersion??localStorage.appShellLayoutVersion??"v1"),medplum=useMedplum5(),profile=useMedplumProfile4();function setNavbarOpenWrapper(open){localStorage.navbarOpen=open.toString(),setNavbarOpen(open)}function closeNavbar(){setNavbarOpenWrapper(!1)}function toggleNavbar(){setNavbarOpenWrapper(!navbarOpen)}if(medplum.isLoading())return jsx21(Loading,{});let headerProp,navbarProp,headerComponent,navbarComponent;return layoutVersion==="v2"?(headerProp={height:0},navbarProp={width:navbarOpen?OPEN_WIDTH:CLOSED_WIDTH,breakpoint:0,collapsed:{desktop:!profile,mobile:!profile}},headerComponent=void 0,navbarComponent=profile?jsx21(Navbar,{logo:props.logo,pathname:props.pathname,searchParams:props.searchParams,menus:props.menus,navbarToggle:toggleNavbar,closeNavbar,displayAddBookmark:props.displayAddBookmark,resourceTypeSearchDisabled:!0,opened:navbarOpen,spotlightEnabled:!0,patientsOnly:props.spotlightPatientsOnly,userMenuEnabled:!0,version:props.version,showLayoutVersionToggle:props.showLayoutVersionToggle}):void 0):(headerProp={height:60},navbarProp={width:OPEN_WIDTH,breakpoint:"sm",collapsed:{desktop:!profile||!navbarOpen,mobile:!profile||!navbarOpen}},headerComponent=profile&&jsx21(Header,{pathname:props.pathname,searchParams:props.searchParams,headerSearchDisabled:props.headerSearchDisabled,logo:props.logo,version:props.version,navbarOpen,navbarToggle:toggleNavbar,notifications:props.notifications}),navbarComponent=profile&&navbarOpen?jsx21(Navbar,{pathname:props.pathname,searchParams:props.searchParams,menus:props.menus,navbarToggle:toggleNavbar,closeNavbar,displayAddBookmark:props.displayAddBookmark,resourceTypeSearchDisabled:props.resourceTypeSearchDisabled,patientsOnly:props.spotlightPatientsOnly}):void 0),jsxs10(MantineAppShell3,{header:headerProp,navbar:navbarProp,padding:0,children:[headerComponent,navbarComponent,jsx21(MantineAppShell3.Main,{className:AppShell_default.main,children:jsx21(ErrorBoundary,{children:jsx21(Suspense,{fallback:jsx21(Loading,{}),children:props.children})})})]})}import{getPathDisplayName,isPopulated as isPopulated2}from"@medplum/core";import{Anchor as Anchor2}from"@mantine/core";import{ContentType as ContentType2}from"@medplum/core";import{useCachedBinaryUrl as useCachedBinaryUrl2}from"@medplum/react-hooks";import{Button as Button2}from"@mantine/core";import{useEffect as useEffect2,useRef as useRef2,useState as useState12}from"react";import{Fragment as Fragment6,jsx as jsx22,jsxs as jsxs11}from"react/jsx-runtime";var CCDA_VIEWER_URL="https://ccda.medplum.com",BASE_VALIDATION_URL="https://ccda-validator.medplum.com/";function CcdaDisplay(props){let{url}=props,[shouldSend,setShouldSend]=useState12(!1),iframeRef=useRef2(null),[validationResult,setValidationResult]=useState12(),[validating,setValidating]=useState12(!1);useEffect2(()=>{url&&shouldSend&&iframeRef.current&&(sendCommand(iframeRef.current,{command:"loadCcdaXml",value:url}).catch(console.error),setShouldSend(!1))},[url,shouldSend]);let validateCcda=async()=>{if(url)try{setValidating(!0);let ccdaContent=await(await fetch(url)).text(),formData=new FormData;formData.append("ccdaFile",new Blob([ccdaContent],{type:"text/xml"}),"ccda.xml");let validationUrl=`${BASE_VALIDATION_URL}referenceccdaservice/?validationObjective=C-CDA_IG_Plus_Vocab&referenceFileName=No%20scenario%20File&curesUpdate=true&severityLevel=WARNING`,validationResponse=await fetch(validationUrl,{method:"POST",body:formData,credentials:"omit",redirect:"manual"});if(!validationResponse.ok)throw new Error(`Validation failed: ${validationResponse.status} ${validationResponse.statusText}`);let validationResult2=await validationResponse.json();setValidationResult(validationResult2)}catch(error){setValidationResult(void 0),console.error("CCDA validation error:",error)}finally{setValidating(!1)}},downloadResults=()=>{if(!validationResult)return;let resultsJson=JSON.stringify(validationResult,null,2);exportJsonFile(resultsJson,"ccda-validation-results")},getErrorCount=()=>validationResult?validationResult.resultsMetaData.resultMetaData.filter(item=>item?.type.includes("Error")).reduce((sum,item)=>sum+(item.count||0),0):0;return url?jsxs11("div",{"data-testid":"ccda-iframe",style:{maxWidth:props.maxWidth},children:[jsx22("div",{style:{minHeight:400},children:jsx22("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:iframeRef,src:CCDA_VIEWER_URL,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>setShouldSend(!0)})}),jsxs11("div",{style:{marginTop:"10px",marginBottom:"10px",display:"flex",alignItems:"center"},children:[jsx22(Button2,{type:"button",onClick:validateCcda,disabled:validating,children:validating?"Validating...":"Validate"}),validationResult&&jsxs11(Fragment6,{children:[jsxs11("div",{style:{marginLeft:"15px"},children:[jsx22("strong",{children:"Validation Results:"})," ",getErrorCount()," errors found"]}),jsx22(Button2,{type:"button",onClick:downloadResults,color:"green",style:{marginLeft:"auto"},children:"Download Full Results"})]})]})]}):null}import{jsx as jsx23,jsxs as jsxs12}from"react/jsx-runtime";function AttachmentDisplay(props){let{contentType,url:uncachedUrl,title}=props.value??{},url=useCachedBinaryUrl2(uncachedUrl);return url?jsxs12("div",{"data-testid":"attachment-display",children:[contentType?.startsWith("image/")&&jsx23("img",{"data-testid":"attachment-image",style:{maxWidth:props.maxWidth},src:url,alt:title}),contentType?.startsWith("video/")&&jsx23("video",{"data-testid":"attachment-video",style:{maxWidth:props.maxWidth},controls:!0,children:jsx23("source",{type:contentType,src:url})}),(contentType?.startsWith("text/")||contentType==="application/json"||contentType==="application/pdf")&&jsx23("div",{"data-testid":"attachment-iframe",style:{maxWidth:props.maxWidth,minHeight:400},children:jsx23("iframe",{title:"Attachment",width:"100%",height:"400",src:url+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),contentType===ContentType2.CDA_XML&&jsx23(CcdaDisplay,{url}),jsx23("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:jsx23(Anchor2,{href:uncachedUrl,"data-testid":"attachment-details",target:"_blank",rel:"noopener noreferrer",download:getDownloadName(title),children:title||"Download"})})]}):null}function getDownloadName(title){return title?.includes(".")?title:void 0}function r(e){var t,f,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=" "),n+=f)}else for(f in e)e[f]&&(n&&(n+=" "),n+=f);return n}function clsx(){for(var e,t,f=0,n="",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=" "),n+=t);return n}var clsx_default=clsx;var DescriptionList_default={root:"DescriptionList_root",compact:"DescriptionList_compact"};import{Fragment as Fragment7,jsx as jsx24,jsxs as jsxs13}from"react/jsx-runtime";function DescriptionList(props){let{children,compact}=props;return jsx24("dl",{className:clsx_default(DescriptionList_default.root,{[DescriptionList_default.compact]:compact}),children})}function DescriptionListEntry(props){return jsxs13(Fragment7,{children:[jsx24("dt",{children:props.term}),jsx24("dd",{children:props.children})]})}import{Fragment as Fragment8,jsx as jsx25}from"react/jsx-runtime";function AttachmentArrayDisplay(props){let attachmentElements=props.values?.map((v,index)=>jsx25("div",{children:jsx25(AttachmentDisplay,{value:v,maxWidth:props.maxWidth})},"attatchment-"+index)),content;if(props.includeDescriptionListEntry){if(props.property===void 0)throw new Error("props.property is required when includeDescriptionListEntry is true");if(!isPopulated2(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();content=jsx25(DescriptionListEntry,{term:getPathDisplayName(key),children:attachmentElements})}else content=jsx25(Fragment8,{children:attachmentElements});return content}import{ActionIcon}from"@mantine/core";import{useState as useState13}from"react";import{normalizeOperationOutcome}from"@medplum/core";import{useMedplum as useMedplum6}from"@medplum/react-hooks";import{useRef as useRef3}from"react";import{Fragment as Fragment9,jsx as jsx26,jsxs as jsxs14}from"react/jsx-runtime";function AttachmentButton(props){let medplum=useMedplum6(),fileInputRef=useRef3(null);function onClick(e){killEvent(e),fileInputRef.current?.click()}function onFileChange(e){killEvent(e);let files=e.target.files;files&&Array.from(files).forEach(processFile)}function processFile(file){!file||!file.name||(props.onUploadStart&&props.onUploadStart(),medplum.createAttachment({data:file,contentType:file.type||"application/octet-stream",filename:file.name,securityContext:props.securityContext,onProgress:props.onUploadProgress}).then(attachment=>props.onUpload(attachment)).catch(err=>{props.onUploadError&&props.onUploadError(normalizeOperationOutcome(err))}))}return jsxs14(Fragment9,{children:[jsx26("input",{disabled:props.disabled,type:"file","data-testid":"upload-file-input",style:{display:"none"},ref:fileInputRef,onChange:e=>onFileChange(e)}),props.children({onClick,disabled:props.disabled})]})}import{jsx as jsx27,jsxs as jsxs15}from"react/jsx-runtime";function AttachmentArrayInput(props){let[values,setValues]=useState13(props.defaultValue??[]);function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}return jsxs15("table",{style:{width:"100%"},children:[jsxs15("colgroup",{children:[jsx27("col",{width:"97%"}),jsx27("col",{width:"3%"})]}),jsxs15("tbody",{children:[values.map((v,index)=>jsxs15("tr",{children:[jsx27("td",{children:jsx27(AttachmentDisplay,{value:v,maxWidth:200})}),jsx27("td",{children:jsx27(ActionIcon,{disabled:props.disabled,title:"Remove",variant:"subtle",size:"sm",color:"gray",onClick:e=>{killEvent(e);let copy=values.slice();copy.splice(index,1),setValuesWrapper(copy)},children:jsx27(IconCircleMinus,{})})})]},`${index}-${values.length}`)),jsxs15("tr",{children:[jsx27("td",{}),jsx27("td",{children:jsx27(AttachmentButton,{disabled:props.disabled,onUpload:attachment=>{setValuesWrapper([...values,attachment])},children:props2=>jsx27(ActionIcon,{...props2,title:"Add",variant:"subtle",size:"sm",color:props2.disabled?"gray":"green",children:jsx27(IconCloudUpload,{})})})})]})]})]})}import{Button as Button3}from"@mantine/core";import{useState as useState14}from"react";import{Fragment as Fragment10,jsx as jsx28,jsxs as jsxs16}from"react/jsx-runtime";function AttachmentInput(props){let[value,setValue]=useState14(props.defaultValue);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return value?jsxs16(Fragment10,{children:[jsx28(AttachmentDisplay,{value,maxWidth:200}),jsx28(Button3,{disabled:props.disabled,onClick:e=>{killEvent(e),setValueWrapper(void 0)},children:"Remove"})]}):jsx28(AttachmentButton,{disabled:props.disabled,securityContext:props.securityContext,onUpload:setValueWrapper,children:props2=>jsx28(Button3,{...props2,children:"Upload..."})})}import{Button as Button4,Flex,Group as Group8,PasswordInput,Stack as Stack5,Title}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome2}from"@medplum/core";import{useMedplum as useMedplum7}from"@medplum/react-hooks";import{useState as useState15}from"react";import{Container as MantineContainer}from"@mantine/core";var Container_default={root:"Container_root"};import{jsx as jsx29}from"react/jsx-runtime";function Container(props){let{children,...others}=props;return jsx29(MantineContainer,{className:Container_default.root,...others,children})}import{Paper}from"@mantine/core";var Panel_default={paper:"Panel_paper",fill:"Panel_fill"};import{jsx as jsx30}from"react/jsx-runtime";function Panel(props){let{width,fill,className,children,...rest}=props,style=width?{maxWidth:width}:void 0;return jsx30(Paper,{className:clsx_default(Panel_default.paper,fill&&Panel_default.fill,className),style,shadow:"sm",radius:"sm",withBorder:!0,...rest,children})}import{jsx as jsx31}from"react/jsx-runtime";function Document(props){let{children,...others}=props;return jsx31(Container,{children:jsx31(Panel,{...others,children})})}import{jsx as jsx32,jsxs as jsxs17}from"react/jsx-runtime";function Logo(props){let overrideUrl=import.meta.env.MEDPLUM_LOGO_URL;return overrideUrl?jsx32("img",{src:overrideUrl,alt:"Logo",style:{maxHeight:props.size}}):jsxs17("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 180 180",style:{width:props.size,height:props.size},children:[jsx32("title",{children:"Medplum Logo"}),jsx32("path",{fill:props.fill??"#9c36b5",d:"M84 56c-3-15-15-24-23-28l5-10c8 2 14 8 20 14 0-12 1-16 5-21 8-9 13-9 41-9 0 7 1 18-3 24-7 9-16 7-41 8 5 8 7 14 8 22 36-24 74-7 74 39 0 42-40 83-80 83s-80-41-80-83c0-46 38-63 74-39Zm-3 43H65c-4 0-7 3-7 7v4c0 4 3 7 7 7h16v16c0 4 3 7 7 7h4c4 0 7-3 7-7v-16h16c4 0 7-3 7-7v-4c0-4-3-7-7-7H99V83c0-4-3-7-7-7h-4c-4 0-7 3-7 7z"})]})}function getErrorsForInput(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))?.map(issue=>issue.details?.text)?.join(`
|
|
103
|
-
`)}function getIssuesForExpression(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))}var ARRAY_INDEX_REGEX=/\[\d+\]/;function isExpressionMatch(expr1,expr2){let isExpr1Indexed=typeof expr1=="string"&&ARRAY_INDEX_REGEX.test(expr1),isExpr2Indexed=typeof expr2=="string"&&ARRAY_INDEX_REGEX.test(expr2);if(isExpr1Indexed!==isExpr2Indexed&&(expr1=expr1?.replace(ARRAY_INDEX_REGEX,""),expr2=expr2?.replace(ARRAY_INDEX_REGEX,"")),expr1===expr2)return!0;if(!expr1||!expr2)return!1;let dot1=expr1.indexOf(".");if(dot1>=0&&expr1.substring(dot1+1)===expr2)return!0;let dot2=expr2.indexOf(".");return dot2>=0&&expr2.substring(dot2+1)===expr1}import{jsx as jsx33,jsxs as jsxs18}from"react/jsx-runtime";function ChangePasswordForm(props){let{onSuccess}=props,medplum=useMedplum7(),[outcome,setOutcome]=useState15(),[success,setSuccess]=useState15(!1);return jsx33(Document,{width:450,children:jsxs18(Form,{onSubmit:formData=>{setOutcome(void 0),medplum.post("auth/changepassword",formData).then(()=>{setSuccess(!0),onSuccess?.()}).catch(err=>setOutcome(normalizeOperationOutcome2(err)))},children:[jsxs18(Flex,{direction:"column",align:"center",justify:"center",children:[jsx33(Logo,{size:32}),jsx33(Title,{children:"Change password"})]}),!success&&jsxs18(Stack5,{gap:"xl",mt:"xl",children:[jsx33(PasswordInput,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"oldPassword")}),jsx33(PasswordInput,{name:"newPassword",label:"New password",required:!0,error:getErrorsForInput(outcome,"newPassword")}),jsx33(PasswordInput,{name:"confirmPassword",label:"Confirm new password",required:!0,error:getErrorsForInput(outcome,"confirmPassword")}),jsx33(Group8,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:jsx33(Button4,{type:"submit",children:"Change password"})})]}),success&&jsx33("div",{"data-testid":"success",children:"Password changed successfully"})]})})}import{Alert as Alert2,Center as Center2,Image as Image2,Stack as Stack6,Text as Text7,TextInput as TextInput4,Title as Title2}from"@mantine/core";import{normalizeErrorString as normalizeErrorString4}from"@medplum/core";import{useState as useState16}from"react";import{jsx as jsx34,jsxs as jsxs19}from"react/jsx-runtime";function MfaForm(props){let[errorMessage,setErrorMessage]=useState16();return jsxs19(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData)?.catch(err=>setErrorMessage(normalizeErrorString4(err)))},children:[jsxs19(Center2,{style:{flexDirection:"column"},children:[jsx34(Logo,{size:32}),jsx34(Title2,{order:3,py:"lg",children:props.title}),!props.qrCodeUrl&&props.description&&jsx34(Text7,{c:"dimmed",mb:"lg",mt:"-lg",children:props.description})]}),errorMessage&&jsx34(Alert2,{icon:jsx34(IconAlertCircle,{size:16}),title:"Error",color:"red",mb:"lg",children:errorMessage}),props.qrCodeUrl&&jsx34(Center2,{children:jsxs19(Stack6,{mb:"xl",children:[props.description&&jsx34(Text7,{c:"dimmed",mb:"md",mt:"-lg",ta:"center",children:props.description}),jsx34(Image2,{src:props.qrCodeUrl,alt:"Multi Factor Auth QR Code",w:"60%",mx:"auto",radius:"md",p:"xs",bg:"var(--mantine-color-white)",style:{border:"1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4))"}})]})}),jsx34(Stack6,{gap:"sm",children:jsx34(TextInput4,{name:"token",label:"MFA code",autoComplete:"one-time-code",required:!0,autoFocus:!0})}),jsx34(Stack6,{gap:"xs",pt:"md",children:jsx34(SubmitButton,{fullWidth:!0,children:props.buttonText})})]})}import{normalizeOperationOutcome as normalizeOperationOutcome5}from"@medplum/core";import{useMedplum as useMedplum10}from"@medplum/react-hooks";import{useEffect as useEffect5,useState as useState20}from"react";import{Alert as Alert3}from"@mantine/core";import{operationOutcomeIssueToString}from"@medplum/core";import{jsx as jsx35}from"react/jsx-runtime";function OperationOutcomeAlert(props){let{outcome,issues:issuesProp,...spacingProps}=props,issues=outcome?.issue||issuesProp;return!issues||issues.length===0?null:jsx35(Alert3,{icon:jsx35(IconAlertCircle,{size:16}),color:"red",...spacingProps,children:issues.map(issue=>jsx35("div",{"data-testid":"text-field-error",children:operationOutcomeIssueToString(issue)},issue.details?.text))})}import{Anchor as Anchor3,Flex as Flex2,Stack as Stack7,Text as Text8,TextInput as TextInput5,Title as Title3}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome3}from"@medplum/core";import{useMedplum as useMedplum8}from"@medplum/react-hooks";import{useState as useState17}from"react";import{jsx as jsx36,jsxs as jsxs20}from"react/jsx-runtime";function NewProjectForm(props){let medplum=useMedplum8(),[outcome,setOutcome]=useState17(),issues=getIssuesForExpression(outcome,void 0);return jsxs20(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome(normalizeOperationOutcome3(err))}},children:[jsxs20(Flex2,{direction:"column",align:"center",justify:"center",children:[jsx36(Logo,{size:32}),jsx36(Title3,{order:3,py:"lg",children:"Create a new project"})]}),jsx36(OperationOutcomeAlert,{issues,mb:"lg"}),jsx36(Stack7,{gap:"sm",children:jsx36(TextInput5,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")})}),jsxs20(Stack7,{gap:"xs",mt:"md",children:[jsx36(SubmitButton,{fullWidth:!0,children:"Create Project"}),jsxs20(Text8,{c:"dimmed",size:"xs",pt:"lg",ta:"center",children:['By clicking "Create Project" you agree to the Medplum'," ",jsx36(Anchor3,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx36(Anchor3,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]})]})}import{Anchor as Anchor4,Box as Box3,Checkbox,Divider as Divider2,Flex as Flex3,PasswordInput as PasswordInput2,Stack as Stack8,Text as Text9,TextInput as TextInput6}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useMedplum as useMedplum9}from"@medplum/react-hooks";import{useEffect as useEffect4,useState as useState19}from"react";import{Box as Box2}from"@mantine/core";import{useEffect as useEffect3,useRef as useRef4,useState as useState18}from"react";function createScriptTag(src,onload){let head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.async=!0,script.src=src,script.onload=onload??null,head.appendChild(script)}import{jsx as jsx37}from"react/jsx-runtime";function GoogleButton(props){let{googleClientId,handleGoogleCredential}=props,parentRef=useRef4(null),[scriptLoaded,setScriptLoaded]=useState18(typeof google<"u"),initializedRef=useRef4(!1),buttonRenderedRef=useRef4(!1);return useEffect3(()=>{if(typeof google>"u"){createScriptTag("https://accounts.google.com/gsi/client",()=>setScriptLoaded(!0));return}initializedRef.current||(google.accounts.id.initialize({client_id:googleClientId,callback:handleGoogleCredential}),initializedRef.current=!0),parentRef.current&&!buttonRenderedRef.current&&(google.accounts.id.renderButton(parentRef.current,{type:"standard",logo_alignment:"center",width:parentRef.current.clientWidth}),buttonRenderedRef.current=!0)},[googleClientId,scriptLoaded,handleGoogleCredential]),googleClientId?jsx37(Box2,{ref:parentRef,w:"100%",h:40,display:"flex",style:{justifyContent:"center"}}):null}import{locationUtils as locationUtils3}from"@medplum/core";function getGoogleClientId(clientId){if(clientId)return clientId;let origin=locationUtils3.getOrigin();if(origin&&("undefined"?.split(",")??[]).includes(origin))return"__GOOGLE_CLIENT_ID__"}function initRecaptcha(siteKey){typeof grecaptcha>"u"&&createScriptTag("https://www.google.com/recaptcha/api.js?render="+siteKey)}function getRecaptcha(siteKey){return new Promise((resolve,reject)=>{grecaptcha.ready(async()=>{try{resolve(await grecaptcha.execute(siteKey,{action:"submit"}))}catch(err){reject(err)}})})}import{Fragment as Fragment11,jsx as jsx38,jsxs as jsxs21}from"react/jsx-runtime";function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=useMedplum9(),[outcome,setOutcome]=useState19(),issues=getIssuesForExpression(outcome,void 0);return useEffect4(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsxs21(Form,{onSubmit:async formData=>{setOutcome(void 0);try{let recaptchaToken="";recaptchaSiteKey&&(recaptchaToken=await getRecaptcha(recaptchaSiteKey)),props.handleAuthResponse(await medplum.startNewUser({projectId:props.projectId,clientId:props.clientId,firstName:formData.firstName,lastName:formData.lastName,email:formData.email,password:formData.password,remember:formData.remember==="true",recaptchaSiteKey,recaptchaToken}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}},children:[jsx38(Flex3,{direction:"column",align:"center",justify:"center",children:props.children}),jsx38(OperationOutcomeAlert,{issues,mb:"lg"}),googleClientId&&jsxs21(Fragment11,{children:[jsx38(Box3,{style:{minHeight:40},children:jsx38(GoogleButton,{googleClientId,handleGoogleCredential:async response=>{try{props.handleAuthResponse(await medplum.startGoogleLogin({googleClientId:response.clientId,googleCredential:response.credential,projectId:props.projectId,createUser:!0}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}}})}),jsx38(Divider2,{label:"or",labelPosition:"center",my:"lg"})]}),jsxs21(Stack8,{gap:"sm",children:[jsx38(TextInput6,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),jsx38(TextInput6,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),jsx38(TextInput6,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),jsx38(PasswordInput2,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")})]}),jsxs21(Stack8,{gap:"xs",children:[jsx38(Checkbox,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1},pt:"md",pb:"xs"}),jsx38(SubmitButton,{fullWidth:!0,children:"Register Account"}),jsxs21(Text9,{c:"dimmed",size:"xs",pt:"lg",ta:"center",children:['By clicking "Register Account" you agree to the Medplum'," ",jsx38(Anchor4,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx38(Anchor4,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),jsxs21(Text9,{c:"dimmed",size:"xs",ta:"center",children:["This site is protected by reCAPTCHA and the Google"," ",jsx38(Anchor4,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx38(Anchor4,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]})]})}import{jsx as jsx39,jsxs as jsxs22}from"react/jsx-runtime";function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=useMedplum10(),[login,setLogin]=useState20(),[outcome,setOutcome]=useState20();useEffect5(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome5(err)))},[medplum,type,projectId,login,onSuccess]);function handleAuthResponse(response){response.code?medplum.processCode(response.code).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome5(err))):response.login&&setLogin(response.login)}let issues=getIssuesForExpression(outcome,void 0);return jsxs22(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:[jsx39(OperationOutcomeAlert,{issues,mb:"lg"}),!login&&jsx39(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&jsx39(NewProjectForm,{login,handleAuthResponse})]})}import{Anchor as Anchor5,Flex as Flex4,Stack as Stack9,Text as Text10,TextInput as TextInput7,Title as Title4}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome6}from"@medplum/core";import{useMedplum as useMedplum11}from"@medplum/react-hooks";import{useEffect as useEffect6,useState as useState21}from"react";import{Fragment as Fragment12,jsx as jsx40,jsxs as jsxs23}from"react/jsx-runtime";function ResetPasswordForm(props){let{projectId,recaptchaSiteKey,onSuccess,onSignIn,onRegister}=props,medplum=useMedplum11(),[outcome,setOutcome]=useState21(),[success,setSuccess]=useState21(!1);return useEffect6(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsx40(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:jsxs23(Form,{onSubmit:async formData=>{setOutcome(void 0);try{let recaptchaToken="";recaptchaSiteKey&&(recaptchaToken=await getRecaptcha(recaptchaSiteKey)),await medplum.post("auth/resetpassword",{...formData,projectId,recaptchaToken}),setSuccess(!0),onSuccess?.()}catch(err){setOutcome(normalizeOperationOutcome6(err))}},children:[jsxs23(Flex4,{direction:"column",align:"center",justify:"center",children:[jsx40(Logo,{size:32}),jsx40(Title4,{order:3,py:"lg",children:"Reset your password"})]}),jsx40(OperationOutcomeAlert,{issues:getIssuesForExpression(outcome,void 0),mb:"lg"}),!success&&jsxs23(Fragment12,{children:[jsx40(Stack9,{gap:"sm",mb:"md",children:jsx40(TextInput7,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")})}),jsxs23(Stack9,{gap:"xs",children:[jsx40(SubmitButton,{fullWidth:!0,children:"Reset Password"}),onSignIn&&jsx40(Text10,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:jsx40(Anchor5,{onClick:onSignIn,children:"Back to Sign In"})}),onRegister&&jsxs23(Text10,{size:"sm",mt:"none",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:["Don't have an account? ",jsx40(Anchor5,{onClick:onRegister,children:"Sign Up"})]})]})]}),success&&jsx40(Text10,{c:"dimmed",size:"sm",ta:"center",mt:"md",children:"If the account exists on our system, a password reset email will be sent."})]})})}import{Anchor as Anchor6,Button as Button5,Flex as Flex5,Group as Group9,PasswordInput as PasswordInput3,Stack as Stack10,Title as Title5}from"@mantine/core";import{badRequest,normalizeOperationOutcome as normalizeOperationOutcome7}from"@medplum/core";import{useMedplum as useMedplum12}from"@medplum/react-hooks";import{useState as useState22}from"react";import{jsx as jsx41,jsxs as jsxs24}from"react/jsx-runtime";function SetPasswordForm(props){let{id,secret,onSuccess,onSignIn}=props,medplum=useMedplum12(),[outcome,setOutcome]=useState22(),[success,setSuccess]=useState22(!1),issues=getIssuesForExpression(outcome,void 0);return jsxs24(Document,{width:450,children:[jsx41(OperationOutcomeAlert,{issues}),jsxs24(Form,{onSubmit:formData=>{if(formData.password!==formData.confirmPassword){setOutcome(badRequest("Passwords do not match","confirmPassword"));return}setOutcome(void 0),medplum.post("auth/setpassword",{id,secret,password:formData.password}).then(()=>{setSuccess(!0),onSuccess?.()}).catch(err=>setOutcome(normalizeOperationOutcome7(err)))},children:[jsxs24(Flex5,{direction:"column",align:"center",justify:"center",children:[jsx41(Logo,{size:32}),jsx41(Title5,{children:"Set password"})]}),!success&&jsxs24(Stack10,{children:[jsx41(PasswordInput3,{name:"password",label:"New password",required:!0,error:getErrorsForInput(outcome,"password")}),jsx41(PasswordInput3,{name:"confirmPassword",label:"Confirm new password",required:!0,error:getErrorsForInput(outcome,"confirmPassword")}),jsx41(Group9,{justify:"flex-end",mt:"xl",children:jsx41(Button5,{type:"submit",children:"Set password"})})]}),success&&jsxs24("div",{"data-testid":"success",children:["Password set. You can now\xA0",onSignIn?jsx41(Anchor6,{component:"button",type:"button",onClick:onSignIn,children:"sign in"}):"sign in","."]})]})]})}import{showNotification as showNotification3}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString5}from"@medplum/core";import{useMedplum as useMedplum16}from"@medplum/react-hooks";import{useCallback as useCallback6,useEffect as useEffect7,useRef as useRef5,useState as useState25}from"react";import{ActionIcon as ActionIcon2,Anchor as Anchor7,Box as Box4,Checkbox as Checkbox2,Divider as Divider3,Flex as Flex6,PasswordInput as PasswordInput4,Stack as Stack11,Text as Text11,TextInput as TextInput8}from"@mantine/core";import{locationUtils as locationUtils4,normalizeOperationOutcome as normalizeOperationOutcome8}from"@medplum/core";import{useMedplum as useMedplum13}from"@medplum/react-hooks";import{useCallback as useCallback5,useState as useState23}from"react";import{Fragment as Fragment13,jsx as jsx42,jsxs as jsxs25}from"react/jsx-runtime";function AuthenticationForm(props){let[email,setEmail]=useState23();return email?jsx42(PasswordForm,{email,resetEmail:()=>setEmail(void 0),...props}):jsx42(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=useMedplum13(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=useState23(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=useCallback5(async authMethod=>{if(!authMethod.authorizeUrl)return!1;let state=JSON.stringify({...await medplum.ensureCodeChallenge(baseLoginRequest),domain:authMethod.domain,returnTo:locationUtils4.getLocation()}),url=new URL(authMethod.authorizeUrl);return url.searchParams.set("state",state),locationUtils4.assign(url.toString()),!0},[medplum,baseLoginRequest]),handleSubmit=useCallback5(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=useCallback5(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome(normalizeOperationOutcome8(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return jsxs25(Form,{onSubmit:handleSubmit,children:[jsx42(Flex6,{direction:"column",align:"center",justify:"center",children}),jsx42(OperationOutcomeAlert,{issues,mb:"lg"}),googleClientId&&jsxs25(Fragment13,{children:[jsx42(Box4,{style:{minHeight:40},children:jsx42(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&jsx42(Divider3,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&jsx42(TextInput8,{name:"email",type:"email",label:"Email",mb:"md",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email"),"data-testid":"auth.email"}),jsxs25(Stack11,{gap:"xs",children:[!disableEmailAuth&&jsx42(SubmitButton,{fullWidth:!0,children:"Continue"}),onRegister&&jsxs25(Text11,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:["Don\u2019t have an account? ",jsx42(Anchor7,{onClick:onRegister,children:"Register"})]})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=useMedplum13(),[outcome,setOutcome]=useState23(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=useCallback5(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome8(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return jsxs25(Form,{onSubmit:handleSubmit,children:[jsx42(Flex6,{direction:"column",align:"center",justify:"center",children}),jsx42(OperationOutcomeAlert,{issues,mb:"lg"}),jsxs25(Stack11,{gap:"sm",children:[jsx42(TextInput8,{label:"Email",value:props.email,disabled:!0,rightSectionWidth:36,rightSection:jsx42(ActionIcon2,{variant:"subtle",color:"gray",onClick:props.resetEmail,"aria-label":"Change email",children:jsx42(IconPencil,{size:"1rem",stroke:1.5})})}),jsx42(PasswordInput4,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password"),"data-testid":"auth.password"})]}),jsxs25(Stack11,{gap:"xs",children:[jsx42(Checkbox2,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1},pt:"md",pb:"xs"}),jsx42(SubmitButton,{children:"Sign In"}),onForgotPassword&&jsx42(Text11,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:jsx42(Anchor7,{onClick:onForgotPassword,children:"Reset Password"})})]})]})}import{Anchor as Anchor8,Box as Box5,Combobox as Combobox2,Flex as Flex7,Group as Group10,Stack as Stack12,Text as Text12,TextInput as TextInput9,Title as Title6,useCombobox as useCombobox2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome9}from"@medplum/core";import{useMedplum as useMedplum14}from"@medplum/react-hooks";import{useState as useState24}from"react";var ChooseProfileForm_default={option:"ChooseProfileForm_option",iconBox:"ChooseProfileForm_iconBox"};import{jsx as jsx43,jsxs as jsxs26}from"react/jsx-runtime";function ChooseProfileForm(props){let medplum=useMedplum14(),combobox=useCombobox2(),[search,setSearch]=useState24(""),[outcome,setOutcome]=useState24();function filterDisplay(display){return!!display?.toLowerCase()?.includes(search.toLowerCase())}function filterMembership(membership){return filterDisplay(membership.profile?.display)||filterDisplay(membership.project?.display)||filterDisplay(getMembershipLabel(membership))}function handleValueSelect(membershipId){medplum.post("auth/profile",{login:props.login,profile:membershipId}).then(props.handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome9(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>jsx43(Combobox2.Option,{value:item.id,className:ChooseProfileForm_default.option,children:jsx43(SelectOption,{...item})},item.id));return jsxs26(Stack12,{gap:"0",children:[jsxs26(Flex7,{justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[jsx43(Logo,{size:32}),jsx43(Title6,{order:3,py:"lg",children:"Choose a Project"})]}),jsx43(OperationOutcomeAlert,{outcome,mb:"lg"}),jsxs26(Combobox2,{store:combobox,onOptionSubmit:handleValueSelect,children:[jsx43(Combobox2.EventsTarget,{children:jsx43(TextInput9,{placeholder:"Search",value:search,mb:"md",autoFocus:!0,leftSection:jsx43(IconSearch,{size:16}),onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),jsx43("div",{children:jsx43(Combobox2.Options,{style:{marginLeft:"-10px",marginRight:"-10px",marginBottom:"-10px"},children:options.length>0?options:jsx43(Combobox2.Empty,{children:"Nothing found..."})})})]}),jsx43(Text12,{size:"sm",ta:"center",mt:"md",children:jsx43(Anchor8,{component:"button",type:"button",onClick:()=>{window.location.href=`/signin?project=new&login=${props.login}`},children:"Create a new project"})})]})}function getMembershipLabel(membership){return membership.identifier?.find(i=>i.system==="https://medplum.com/identifier/label")?.value}function SelectOption(membership){let label=getMembershipLabel(membership);return jsxs26(Group10,{gap:"xs",align:"center",children:[jsx43(Box5,{className:ChooseProfileForm_default.iconBox,children:jsx43(IconBriefcase,{size:16,stroke:2})}),jsxs26("div",{children:[jsxs26(Text12,{size:"sm",fw:500,children:[membership.project?.display," ",label?` - ${label}`:""]}),jsx43(Text12,{size:"xs",c:"dimmed",children:membership.profile?.display})]})]})}import{Checkbox as Checkbox3,Flex as Flex8,Group as Group11,Stack as Stack13,Title as Title7}from"@mantine/core";import{useMedplum as useMedplum15}from"@medplum/react-hooks";import{Fragment as Fragment14}from"react/jsx-runtime";import{jsx as jsx44,jsxs as jsxs27}from"react/jsx-runtime";var openConditionScope=/^patient\/Condition\.(?:\*|c?r?u?d?s?)$/,encounterDiagnosis="?category=http://terminology.hl7.org/CodeSystem/condition-category|encounter-diagnosis",problemListItem="?category=http://terminology.hl7.org/CodeSystem/condition-category|problem-list-item",healthConcern="?category=http://hl7.org/fhir/us/core/CodeSystem/condition-category|health-concern",openObservationScope=/^patient\/Observation\.(?:\*|c?r?u?d?s?)$/,clinicalTest="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-observation-category|clinical-test",laboratory="?category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory",socialHistory="?category=http://terminology.hl7.org/CodeSystem/observation-category|social-history",sdoh="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-category|sdoh",survey="?category=http://terminology.hl7.org/CodeSystem/observation-category|survey",vitalSigns="?category=http://terminology.hl7.org/CodeSystem/observation-category|vital-signs";function ChooseScopeForm(props){let medplum=useMedplum15();return jsx44(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:jsxs27(Stack13,{children:[jsxs27(Flex8,{direction:"column",align:"center",justify:"center",children:[jsx44(Logo,{size:32}),jsx44(Title7,{order:3,py:"lg",children:"Choose scope"})]}),jsx44(Stack13,{children:(props.scope??"openid").split(" ").map(scopeName=>{let additionalScopes;return openConditionScope.test(scopeName)?additionalScopes=[scopeName+encounterDiagnosis,scopeName+problemListItem,scopeName+healthConcern]:openObservationScope.test(scopeName)&&(additionalScopes=[scopeName+clinicalTest,scopeName+laboratory,scopeName+socialHistory,scopeName+sdoh,scopeName+survey,scopeName+vitalSigns]),jsxs27(Fragment14,{children:[jsx44(Checkbox3,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName),additionalScopes?.map(scope=>jsx44(Checkbox3,{id:scope,name:scope,label:scope},scope))]},scopeName+"_group")})}),jsx44(Group11,{justify:"flex-end",mt:"xl",children:jsx44(SubmitButton,{fullWidth:!0,children:"Set Scope"})})]})})}import{jsx as jsx45}from"react/jsx-runtime";function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=useMedplum16(),[login,setLogin]=useState25(),loginRequested=useRef5(!1),[mfaEnrollRequired,setMfaEnrollRequired]=useState25(!1),[enrollQrCode,setEnrollQrCode]=useState25(),[mfaRequired,setMfaRequired]=useState25(!1),[memberships,setMemberships]=useState25(),handleCode=useCallback6(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>showNotification3({color:"red",message:normalizeErrorString5(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=useCallback6(response=>{setMfaEnrollRequired(!!response.mfaEnrollRequired),setEnrollQrCode(response.enrollQrCode),setMfaRequired(!!response.mfaRequired),response.login&&setLogin(response.login),response.memberships&&setMemberships(response.memberships),response.code&&(chooseScopes?setMemberships(void 0):handleCode(response.code))},[chooseScopes,handleCode]),handleScopeResponse=useCallback6(response=>{handleCode(response.code)},[handleCode]);return useEffect7(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>showNotification3({color:"red",message:normalizeErrorString5(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),jsx45(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:login?mfaEnrollRequired&&enrollQrCode?jsx45(MfaForm,{title:"Enroll in MFA",description:"Scan this QR code with your authenticator app.",buttonText:"Enroll",qrCodeUrl:enrollQrCode,onSubmit:async fields=>{let res=await medplum.post("auth/mfa/login-enroll",{login,token:fields.token});handleAuthResponse(res)}}):mfaRequired?jsx45(MfaForm,{title:"Enter MFA code",description:"Enter the code from your authenticator app.",buttonText:"Submit Code",onSubmit:async fields=>{let res=await medplum.post("auth/mfa/verify",{login,token:fields.token});handleAuthResponse(res)}}):props.projectId==="new"?jsx45(NewProjectForm,{login,handleAuthResponse}):memberships?jsx45(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.chooseScopes?jsx45(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):jsx45("div",{children:"Success"}):jsx45(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}import{buildElementsContext as buildElementsContext2,getPathDisplayName as getPathDisplayName3,isEmpty as isEmpty2,tryGetDataType}from"@medplum/core";import{useContext as useContext6,useMemo as useMemo6}from"react";import{ActionIcon as ActionIcon3,CopyButton,Flex as Flex9,Tooltip as Tooltip2}from"@mantine/core";import{PropertyType,formatDateTime,formatPeriod,formatTiming,formatWallTime,isEmpty}from"@medplum/core";import{useState as useState28}from"react";import{formatCodeableConcept}from"@medplum/core";import{Fragment as Fragment15,jsx as jsx46}from"react/jsx-runtime";function CodeableConceptDisplay(props){return jsx46(Fragment15,{children:formatCodeableConcept(props.value)})}import{formatCoding}from"@medplum/core";import{Fragment as Fragment16,jsx as jsx47}from"react/jsx-runtime";function CodingDisplay(props){return jsx47(Fragment16,{children:formatCoding(props.value,props.includeCode)})}import{Fragment as Fragment17,jsx as jsx48}from"react/jsx-runtime";function ContactPointDisplay(props){let contactPoint=props.value;if(!contactPoint)return null;let builder=[];return contactPoint.value&&builder.push(contactPoint.value),(contactPoint.use||contactPoint.system)&&(builder.push(" ["),contactPoint.use&&builder.push(contactPoint.use),contactPoint.use&&contactPoint.system&&builder.push(" "),contactPoint.system&&builder.push(contactPoint.system),builder.push("]")),jsx48(Fragment17,{children:builder.join("").trim()})}import{Fragment as Fragment18,jsx as jsx49,jsxs as jsxs28}from"react/jsx-runtime";function ContactDetailDisplay(props){let contactDetail=props.value;return contactDetail?jsxs28(Fragment18,{children:[contactDetail.name,contactDetail.name&&": ",contactDetail.telecom?.map(telecom=>jsx49(ContactPointDisplay,{value:telecom},`telecom-${contactDetail.name}-${telecom.value}`))]}):null}import{getDataType,isPopulated as isPopulated3,isProfileLoaded,tryGetProfile}from"@medplum/core";import{useMedplum as useMedplum17}from"@medplum/react-hooks";import{useContext as useContext3,useEffect as useEffect8,useMemo as useMemo3,useState as useState26}from"react";import{getTypedPropertyValue,getTypedPropertyValueWithSchema}from"@medplum/core";function getValueAndType(context,path,profileUrl){let typedResult=getTypedPropertyValue(context,path,{profileUrl});return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}function getValueAndTypeFromElement(typedValue,path,element){let typedResult=getTypedPropertyValueWithSchema(typedValue,path,element);return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}import{jsx as jsx50}from"react/jsx-runtime";function ExtensionDisplay(props){let{elementDefinitionType}=props,medplum=useMedplum17(),ctx=useContext3(ElementsContext),[typeSchema,setTypeSchema]=useState26(getDataType("Extension")),profileUrl=useMemo3(()=>{if(isPopulated3(elementDefinitionType?.profile))return elementDefinitionType.profile[0]},[elementDefinitionType]),[loadingProfile,setLoadingProfile]=useState26(profileUrl!==void 0);if(useEffect8(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>{let profile=tryGetProfile(profileUrl);setLoadingProfile(!1),profile&&setTypeSchema(profile)}).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!isProfileLoaded(profileUrl)))return jsx50("div",{children:"Loading..."});if(typeSchema.elements["value[x]"]?.max!==0){let[propertyValue,propertyType]=getValueAndType({type:"Extension",value:props.value},"value[x]",profileUrl??ctx.profileUrl);return jsx50(ResourcePropertyDisplay,{propertyType,value:propertyValue})}return jsx50(BackboneElementDisplay,{path:props.path,value:{type:typeSchema.type,value:props.value},compact:props.compact,ignoreMissingValues:props.ignoreMissingValues,link:props.link,profileUrl})}import{jsxs as jsxs29}from"react/jsx-runtime";function IdentifierDisplay(props){return jsxs29("div",{children:[props.value?.system,": ",props.value?.value]})}import{formatMoney}from"@medplum/core";import{Fragment as Fragment19,jsx as jsx51}from"react/jsx-runtime";function MoneyDisplay(props){return jsx51(Fragment19,{children:formatMoney(props.value)})}import{formatQuantity}from"@medplum/core";import{Fragment as Fragment20,jsx as jsx52}from"react/jsx-runtime";function QuantityDisplay(props){return jsx52(Fragment20,{children:formatQuantity(props.value,props.precision)})}import{formatRange}from"@medplum/core";import{Fragment as Fragment21,jsx as jsx53}from"react/jsx-runtime";function RangeDisplay(props){return jsx53(Fragment21,{children:formatRange(props.value,props.precision,props.exclusive)})}import{Fragment as Fragment22,jsx as jsx54,jsxs as jsxs30}from"react/jsx-runtime";function RatioDisplay(props){let value=props.value;return value?jsxs30(Fragment22,{children:[jsx54(QuantityDisplay,{value:value.numerator,precision:props.precision}),"\xA0/\xA0",jsx54(QuantityDisplay,{value:value.denominator,precision:props.precision})]}):null}import{stringify}from"@medplum/core";import{Fragment as Fragment23,jsx as jsx55}from"react/jsx-runtime";function ReferenceDisplay(props){if(!props.value)return null;let displayString=props.value.display||props.value.reference||stringify(props.value);return props.link!==!1&&props.value.reference?jsx55(MedplumLink,{to:props.value,children:displayString}):jsx55(Fragment23,{children:displayString})}import{Group as Group12,Text as Text13}from"@mantine/core";import{getPathDisplayName as getPathDisplayName2,isPopulated as isPopulated6}from"@medplum/core";import{useMedplum as useMedplum18}from"@medplum/react-hooks";import{useContext as useContext5,useEffect as useEffect9,useMemo as useMemo5,useState as useState27}from"react";import{getValueSliceName,isPopulated as isPopulated4,isSliceDefinitionWithTypes,tryGetProfile as tryGetProfile2}from"@medplum/core";function assignValuesIntoSlices(values,slices,slicing,profileUrl){if(!isPopulated4(slicing?.slices))return[values];let slicedValues=new Array(slices.length+1);for(let i=0;i<slicedValues.length;i++)slicedValues[i]=[];for(let value of values){let sliceName=getValueSliceName(value,slices,slicing.discriminator,profileUrl),sliceIndex=sliceName?slices.findIndex(slice=>slice.name===sliceName):-1;sliceIndex===-1&&(sliceIndex=slices.length),slicedValues[sliceIndex].push(value)}return slicedValues}async function prepareSlices({medplum,property}){return new Promise((resolve,reject)=>{if(!property.slicing){resolve([]);return}let supportedSlices=[],profileUrls=[],promises=[];for(let slice of property.slicing.slices){if(!isSliceDefinitionWithTypes(slice)){console.debug("Unsupported slice definition",slice);continue}let profileUrl;isPopulated4(slice.elements)||(profileUrl=slice.type[0]?.profile?.[0]),supportedSlices.push(slice),profileUrls.push(profileUrl),profileUrl&&promises.push(medplum.requestProfileSchema(profileUrl))}Promise.all(promises).then(()=>{for(let i=0;i<supportedSlices.length;i++){let slice=supportedSlices[i],profileUrl=profileUrls[i];if(profileUrl){let typeSchema=tryGetProfile2(profileUrl);slice.typeSchema=typeSchema}}resolve(supportedSlices)}).catch(reject)})}import{buildElementsContext,isPopulated as isPopulated5}from"@medplum/core";import{useContext as useContext4,useMemo as useMemo4}from"react";import{jsx as jsx56}from"react/jsx-runtime";function maybeWrapWithContext(ContextProvider,contextValue,contents){return contextValue!==void 0?jsx56(ContextProvider,{value:contextValue,children:contents}):contents}import{Fragment as Fragment24,jsx as jsx57}from"react/jsx-runtime";function SliceDisplay(props){let{slice,property}=props,sliceElements=slice.typeSchema?.elements??slice.elements,parentContext=useContext4(ElementsContext),contextValue=useMemo4(()=>{if(isPopulated5(sliceElements))return buildElementsContext({parentContext,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentContext,props.path,slice.typeSchema?.url,sliceElements]);return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx57(Fragment24,{children:props.value.map((value,valueIndex)=>jsx57("div",{children:jsx57(ResourcePropertyDisplay,{property,path:props.path,arrayElement:!0,elementDefinitionType:slice.type[0],propertyType:slice.type[0].code,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${props.value.length}`))}))}import{Fragment as Fragment25,jsx as jsx58,jsxs as jsxs31}from"react/jsx-runtime";var MAX_ARRAY_SIZE=50;function ResourceArrayDisplay(props){let{property,propertyType}=props,medplum=useMedplum18(),values=useMemo5(()=>Array.isArray(props.values)?props.values:[],[props.values]),[loading,setLoading]=useState27(!0),[slices,setSlices]=useState27([]),[slicedValues,setSlicedValues]=useState27(()=>[values]),[valuesLength,setValuesLength]=useState27(0),ctx=useContext5(ElementsContext);if(useEffect9(()=>{prepareSlices({medplum,property}).then(slices2=>{setValuesLength(values.length),setSlices(slices2);let limitedValues=values.slice(0,MAX_ARRAY_SIZE),slicedValues2=assignValuesIntoSlices(limitedValues,slices2,property.slicing,ctx.profileUrl);setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,ctx.profileUrl,setSlicedValues,values]),loading)return jsx58("div",{children:"Loading..."});let nonSliceContent;if(property.type[0]?.code!=="Extension"){let nonSliceValues=slicedValues[slices.length],nonSliceElements=nonSliceValues.map((value,valueIndex)=>jsx58("div",{children:jsx58(ResourcePropertyDisplay,{path:props.path,arrayElement:!0,property,propertyType,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${nonSliceValues.length}`));if(props.includeDescriptionListEntry){if(!isPopulated6(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();nonSliceContent=jsx58(DescriptionListEntry,{term:getPathDisplayName2(key),children:nonSliceElements})}else nonSliceContent=jsx58(Fragment25,{children:nonSliceElements})}return jsxs31(Fragment25,{children:[slices.map((slice,sliceIndex)=>{if(!props.path)throw new Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);let sliceDisplay=jsx58(SliceDisplay,{path:props.path,slice,property,value:slicedValues[sliceIndex],ignoreMissingValues:props.ignoreMissingValues,link:props.link},slice.name);return props.includeDescriptionListEntry&&(sliceDisplay=jsx58(DescriptionListEntry,{term:getPathDisplayName2(slice.name),children:sliceDisplay},slice.name)),sliceDisplay}),nonSliceContent,valuesLength>MAX_ARRAY_SIZE&&jsx58(Group12,{justify:"right",children:jsxs31(Text13,{children:["... ",valuesLength," total values"]})})]})}import{Fragment as Fragment26,jsx as jsx59,jsxs as jsxs32}from"react/jsx-runtime";function ResourcePropertyDisplay(props){let{property,propertyType,value}=props;if(property?.path?.endsWith(".id"))return jsxs32(Flex9,{gap:3,align:"center",children:[value,!isEmpty(value)&&jsx59(CopyButton,{value,timeout:2e3,children:({copied,copy})=>jsx59(Tooltip2,{label:copied?"Copied":"Copy",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,children:copied?jsx59(IconCheck,{size:"1rem"}):jsx59(IconCopy,{size:"1rem"})})})})]});if(property&&(property.isArray||property.max>1)&&!props.arrayElement)return propertyType===PropertyType.Attachment?jsx59(AttachmentArrayDisplay,{values:value,maxWidth:props.maxWidth,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,property,path:props.path}):jsx59(ResourceArrayDisplay,{path:props.path,property,propertyType,values:value,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,ignoreMissingValues:props.ignoreMissingValues,link:props.link});switch(propertyType){case PropertyType.boolean:return jsx59(Fragment26,{children:value===void 0?"":(!!value).toString()});case PropertyType.SystemString:case PropertyType.string:return props.property?.path?.toLowerCase().includes("secret")?jsx59(SecretFieldDisplay,{value}):jsx59("div",{style:{whiteSpace:"pre-wrap"},children:value});case PropertyType.code:case PropertyType.date:case PropertyType.decimal:case PropertyType.id:case PropertyType.integer:case PropertyType.positiveInt:case PropertyType.unsignedInt:case PropertyType.uri:case PropertyType.url:case PropertyType.xhtml:return jsx59(Fragment26,{children:value});case PropertyType.canonical:return jsx59(ReferenceDisplay,{value:{reference:value},link:props.link});case PropertyType.dateTime:case PropertyType.instant:return jsx59(Fragment26,{children:formatDateTime(value)});case PropertyType.time:return jsx59(Fragment26,{children:formatWallTime(value)});case PropertyType.markdown:return jsx59("pre",{children:value});case PropertyType.Address:return jsx59(AddressDisplay,{value});case PropertyType.Annotation:return jsx59(Fragment26,{children:value?.text});case PropertyType.Attachment:return jsx59(AttachmentDisplay,{value,maxWidth:props.maxWidth});case PropertyType.CodeableConcept:return jsx59(CodeableConceptDisplay,{value});case PropertyType.Coding:return jsx59(CodingDisplay,{value});case PropertyType.ContactDetail:return jsx59(ContactDetailDisplay,{value});case PropertyType.ContactPoint:return jsx59(ContactPointDisplay,{value});case PropertyType.HumanName:return jsx59(HumanNameDisplay,{value});case PropertyType.Identifier:return jsx59(IdentifierDisplay,{value});case PropertyType.Money:return jsx59(MoneyDisplay,{value});case PropertyType.Period:return jsx59(Fragment26,{children:formatPeriod(value)});case PropertyType.Quantity:case PropertyType.Duration:return jsx59(QuantityDisplay,{value});case PropertyType.Range:return jsx59(RangeDisplay,{value});case PropertyType.Ratio:return jsx59(RatioDisplay,{value});case PropertyType.Reference:return jsx59(ReferenceDisplay,{value,link:props.link});case PropertyType.Timing:return jsx59(Fragment26,{children:formatTiming(value)});case PropertyType.Dosage:case PropertyType.UsageContext:if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(BackboneElementDisplay,{path:props.path,value:{type:propertyType,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues});case PropertyType.Extension:if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(ExtensionDisplay,{path:props.path,value,compact:!0,ignoreMissingValues:props.ignoreMissingValues,elementDefinitionType:props.elementDefinitionType});default:if(!property)throw new Error(`Displaying property of type ${props.propertyType} requires element schema`);if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(BackboneElementDisplay,{path:props.path,value:{type:property.type[0].code,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues})}}function SecretFieldDisplay(props){let[isVisible,setIsVisible]=useState28(!1),secretValue=props.value??"",hasValue=!isEmpty(secretValue),MASK="\u2022".repeat(8);return jsxs32(Flex9,{gap:3,align:"center",children:[isVisible?jsx59("div",{style:{whiteSpace:"pre-wrap"},children:secretValue}):jsx59("div",{style:{whiteSpace:"pre-wrap"},"aria-hidden":"true",children:hasValue?MASK:""}),hasValue&&jsxs32(Fragment26,{children:[jsx59(CopyButton,{value:props.value,timeout:2e3,children:({copied,copy})=>jsx59(Tooltip2,{label:copied?"Copied":"Copy secret",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,"aria-label":copied?"Copied":"Copy secret",children:copied?jsx59(IconCheck,{size:"1rem"}):jsx59(IconCopy,{size:"1rem"})})})}),jsx59(Tooltip2,{label:isVisible?"Hide secret":"Show secret",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:"gray",onClick:()=>setIsVisible(!isVisible),"aria-label":isVisible?"Hide secret":"Show secret",children:isVisible?jsx59(IconEyeOff,{size:"1rem"}):jsx59(IconEye,{size:"1rem"})})})]})]})}import{jsx as jsx60,jsxs as jsxs33}from"react/jsx-runtime";var EXTENSION_KEYS2=["extension","modifierExtension"],IGNORED_PROPERTIES2=DEFAULT_IGNORED_PROPERTIES.filter(prop=>!EXTENSION_KEYS2.includes(prop));function BackboneElementDisplay(props){let typedValue=props.value,{value,type:typeName}=typedValue,parentElementsContext=useContext6(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=useMemo6(()=>tryGetDataType(typeName,profileUrl),[profileUrl,typeName]),newElementsContext=useMemo6(()=>{if(typeSchema)return buildElementsContext2({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if(isEmpty2(value))return null;if(!typeSchema)return jsxs33("div",{children:[typeName,"\xA0not implemented"]});if(typeof value=="object"&&"name"in value&&Object.keys(value).length===1&&typeof value.name=="string")return jsx60("div",{children:value.name});let elementsContext=newElementsContext??parentElementsContext;return maybeWrapWithContext(ElementsContext.Provider,newElementsContext,jsx60(DescriptionList,{compact:props.compact,children:Object.entries(elementsContext.elements).map(([key,property])=>{if(EXTENSION_KEYS2.includes(key)&&isEmpty2(property.slicing?.slices))return null;if(IGNORED_PROPERTIES2.includes(key))return null;if(DEFAULT_IGNORED_NON_NESTED_PROPERTIES.includes(key)&&property.path.split(".").length===2||key.includes("."))return null;let[propertyValue,propertyType]=getValueAndType(typedValue,key,elementsContext.profileUrl);if((props.ignoreMissingValues||property.max===0)&&isEmpty2(propertyValue)||props.path.endsWith(".extension")&&(key==="url"||key==="id"))return null;let isArrayProperty=property.max>1||property.isArray,resourcePropertyDisplay=jsx60(ResourcePropertyDisplay,{property,propertyType,path:props.path+"."+key,value:propertyValue,ignoreMissingValues:props.ignoreMissingValues,includeArrayDescriptionListEntry:isArrayProperty,link:props.link},key);return isArrayProperty?resourcePropertyDisplay:jsx60(DescriptionListEntry,{term:getPathDisplayName3(key),children:resourcePropertyDisplay},key)})}))}import{Box as Box7}from"@mantine/core";import{buildElementsContext as buildElementsContext4,tryGetDataType as tryGetDataType2}from"@medplum/core";import{useContext as useContext23,useMemo as useMemo22,useState as useState49}from"react";import{Stack as Stack17}from"@mantine/core";import{getPathDisplayName as getPathDisplayName5}from"@medplum/core";import{useContext as useContext22,useMemo as useMemo21,useState as useState48}from"react";import{Group as Group13,Input}from"@mantine/core";import{useContext as useContext7}from"react";var FormSection_default={dimmed:"FormSection_dimmed",preserveBreaks:"FormSection_preserveBreaks"};import{Tooltip as Tooltip3}from"@mantine/core";import{jsx as jsx61}from"react/jsx-runtime";var READ_ONLY_TOOLTIP_TEXT="Read Only";function maybeWrapWithTooltip(tooltipText,children){return tooltipText?jsx61(Tooltip3.Floating,{label:tooltipText,children}):children}import{jsx as jsx62,jsxs as jsxs34}from"react/jsx-runtime";function CheckboxFormSection(props){let{debugMode}=useContext7(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,jsxs34(Group13,{wrap:"nowrap","data-testid":props.testId,children:[jsx62("div",{children:props.children}),jsx62("div",{children:jsx62(Input.Wrapper,{id:props.htmlFor,label,classNames:{label:props?.readonly?FormSection_default.dimmed:void 0},description:props.description,withAsterisk:props.withAsterisk,children:null})})]}))}import{Input as Input2}from"@mantine/core";import{useContext as useContext8}from"react";import{jsx as jsx63}from"react/jsx-runtime";function FormSection(props){let{debugMode}=useContext8(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,jsx63(Input2.Wrapper,{id:props.htmlFor,label,classNames:{label:clsx_default({[FormSection_default.dimmed]:props?.readonly},FormSection_default.preserveBreaks)},description:props.description,withAsterisk:props.withAsterisk,error:getErrorsForInput(props.outcome,props.errorExpression??props.htmlFor),"data-testid":props.testId,children:props.children}))}import{capitalize,isEmpty as isEmpty3}from"@medplum/core";function setPropertyValue(obj,key,propName,elementDefinition,value){let types=elementDefinition.type;if(types.length>1)for(let type of types){let compoundKey=key.replace("[x]",capitalize(type.code));compoundKey in obj&&delete obj[compoundKey]}return isEmpty3(value)?obj[propName]=void 0:obj[propName]=value,obj}function isSupportedProfileStructureDefinition(profile){return!!profile&&!isEmpty3(profile.url)&&!isEmpty3(profile.name)}import{Checkbox as Checkbox4,Group as Group27,NativeSelect as NativeSelect9,Textarea as Textarea2,TextInput as TextInput18}from"@mantine/core";import{applyDefaultValuesToElement,capitalize as capitalize2,getPathDifference,HTTP_HL7_ORG,isComplexTypeCode,isEmpty as isEmpty6,isPopulated as isPopulated10,PropertyType as PropertyType2}from"@medplum/core";import{useContext as useContext21,useMemo as useMemo20,useState as useState47}from"react";import{useState as useState29}from"react";import{jsx as jsx64}from"react/jsx-runtime";function CodeableConceptInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,outcome:_outcome,path:_path,valuePath:_valuePath,...rest}=props,[value,setValue]=useState29(defaultValue2);function handleChange(newValues){let newConcept=valueSetElementToCodeableConcept(newValues);setValue(newConcept),onChange&&onChange(newConcept)}return jsx64(ValueSetAutocomplete,{defaultValue:value&&codeableConceptToValueSetElement(value),onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codeableConceptToValueSetElement(concept){return concept.coding?.map(c=>({system:c.system,code:c.code,display:c.display}))}function valueSetElementToCodeableConcept(elements){if(elements.length!==0)return{coding:elements.map(e=>({system:e.system,code:e.code,display:e.display}))}}import{useState as useState30}from"react";import{jsx as jsx65}from"react/jsx-runtime";function CodingInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,response,...rest}=props,[value,setValue]=useState30(response?.answer?.[0]?.valueCoding??defaultValue2);function handleChange(newValues){let newValue=newValues[0],newConcept=newValue&&valueSetElementToCoding(newValue);setValue(newConcept),onChange&&onChange(newConcept)}return jsx65(ValueSetAutocomplete,{defaultValue:value?codingToValueSetElement(value):void 0,maxValues:1,onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codingToValueSetElement(coding){return{system:coding.system,code:coding.code,display:coding.display}}function valueSetElementToCoding(element){return{system:element.system,code:element.code,display:element.display}}import{Group as Group15,TextInput as TextInput11}from"@mantine/core";import{useContext as useContext10,useMemo as useMemo8,useState as useState32}from"react";import{Group as Group14,NativeSelect as NativeSelect3,TextInput as TextInput10}from"@mantine/core";import{useContext as useContext9,useMemo as useMemo7,useState as useState31}from"react";import{jsx as jsx66,jsxs as jsxs35}from"react/jsx-runtime";function ContactPointInput(props){let{path,outcome}=props,{elementsByPath,getExtendedProps}=useContext9(ElementsContext),[contactPoint,setContactPoint]=useState31(props.defaultValue),[systemElement,useElement,valueElement]=useMemo7(()=>["system","use","value"].map(field=>elementsByPath[path+"."+field]),[elementsByPath,path]),[systemProps,useProps,valueProps]=useMemo7(()=>["system","use","value"].map(field=>getExtendedProps(path+"."+field)),[getExtendedProps,path]);function setContactPointWrapper(newValue){newValue&&Object.keys(newValue).length===0&&(newValue=void 0),setContactPoint(newValue),props.onChange&&props.onChange(newValue)}function setSystem(system){let newValue={...contactPoint,system};system||delete newValue.system,setContactPointWrapper(newValue)}function setUse(use){let newValue={...contactPoint,use};use||delete newValue.use,setContactPointWrapper(newValue)}function setValue(value){let newValue={...contactPoint,value};value||delete newValue.value,setContactPointWrapper(newValue)}let errorPath=props.valuePath??path;return jsxs35(Group14,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx66(NativeSelect3,{disabled:props.disabled||systemProps?.readonly,"data-testid":"system",defaultValue:contactPoint?.system,required:(systemElement?.min??0)>0,onChange:e=>setSystem(e.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:getErrorsForInput(outcome,errorPath+".system")}),jsx66(NativeSelect3,{disabled:props.disabled||useProps?.readonly,"data-testid":"use",defaultValue:contactPoint?.use,required:(useElement?.min??0)>0,onChange:e=>setUse(e.currentTarget.value),data:["","home","work","temp","old","mobile"],error:getErrorsForInput(outcome,errorPath+".use")}),jsx66(TextInput10,{disabled:props.disabled||valueProps?.readonly,placeholder:"Value",defaultValue:contactPoint?.value,required:(valueElement?.min??0)>0,onChange:e=>setValue(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".value")})]})}import{jsx as jsx67,jsxs as jsxs36}from"react/jsx-runtime";function ContactDetailInput(props){let[contactDetail,setContactDetail]=useState32(props.defaultValue),{getExtendedProps}=useContext10(ElementsContext),[nameProps,telecomProps]=useMemo8(()=>["name","telecom"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setContactDetailWrapper(newValue){setContactDetail(newValue),props.onChange&&props.onChange(newValue)}function setName(name){let newValue={...contactDetail,name};name||delete newValue.name,setContactDetailWrapper(newValue)}function setTelecom(telecom){let newValue={...contactDetail,telecom:telecom&&[telecom]};telecom||delete newValue.telecom,setContactDetailWrapper(newValue)}return jsxs36(Group15,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx67(TextInput11,{disabled:props.disabled||nameProps?.readonly,"data-testid":props.name+"-name",name:props.name+"-name",placeholder:"Name",style:{width:180},defaultValue:contactDetail?.name,onChange:e=>setName(e.currentTarget.value)}),jsx67(ContactPointInput,{disabled:props.disabled||telecomProps?.readonly,name:props.name+"-telecom",path:props.path+".telecom",defaultValue:contactDetail?.telecom?.[0],onChange:setTelecom,outcome:props.outcome})]})}import{TextInput as TextInput12}from"@mantine/core";import{isValidDate}from"@medplum/core";function convertIsoToLocal(isoString){if(!isoString)return"";let date=new Date(isoString);return isValidDate(date)?date.toLocaleDateString("sv")+"T"+date.toLocaleTimeString("sv"):""}function convertLocalToIso(localString){if(!localString)return"";let date=new Date(localString);return isValidDate(date)?date.toISOString():""}import{jsx as jsx68}from"react/jsx-runtime";function DateTimeInput(props){return jsx68(TextInput12,{id:props.name,name:props.name,label:props.label,"data-autofocus":props.autoFocus,"data-testid":props["data-testid"]??props.name,placeholder:props.placeholder,required:props.required,disabled:props.disabled,type:getInputType(),step:1,defaultValue:convertIsoToLocal(props.defaultValue),autoFocus:props.autoFocus,error:getErrorsForInput(props.outcome,props.name),onChange:e=>{if(props.onChange){let newValue=e.currentTarget.value;props.onChange(convertLocalToIso(newValue))}}})}function getInputType(){return"datetime-local"}import{isPopulated as isPopulated7,isProfileLoaded as isProfileLoaded2}from"@medplum/core";import{useMedplum as useMedplum19}from"@medplum/react-hooks";import{useEffect as useEffect10,useMemo as useMemo9,useState as useState33}from"react";import{jsx as jsx69}from"react/jsx-runtime";function ExtensionInput(props){let{propertyType}=props,medplum=useMedplum19(),profileUrl=useMemo9(()=>{if(isPopulated7(propertyType.profile))return propertyType.profile[0]},[propertyType]),[loadingProfile,setLoadingProfile]=useState33(profileUrl!==void 0);return useEffect10(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>setLoadingProfile(!1)).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!isProfileLoaded2(profileUrl))?jsx69("div",{children:"Loading..."}):jsx69(BackboneElementInput,{profileUrl,path:props.path,typeName:"Extension",defaultValue:props.defaultValue,onChange:props.onChange})}import{Group as Group16,NativeSelect as NativeSelect4,TextInput as TextInput13}from"@mantine/core";import{useContext as useContext11,useMemo as useMemo10,useState as useState34}from"react";import{jsx as jsx70,jsxs as jsxs37}from"react/jsx-runtime";function HumanNameInput(props){let{outcome,path}=props,[value,setValue]=useState34(props.defaultValue),{getExtendedProps}=useContext11(ElementsContext),[useProps,prefixProps,givenProps,familyProps,suffixProps]=useMemo10(()=>["use","prefix","given","family","suffix"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}function setUse(use){setValueWrapper({...value,use:use||void 0})}function setPrefix(prefix){setValueWrapper({...value,prefix:prefix?prefix.split(" "):void 0})}function setGiven(given){setValueWrapper({...value,given:given?given.split(" "):void 0})}function setFamily(family){setValueWrapper({...value,family:family||void 0})}function setSuffix(suffix){setValueWrapper({...value,suffix:suffix?suffix.split(" "):void 0})}let errorPath=props.valuePath??path;return jsxs37(Group16,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx70(NativeSelect4,{disabled:props.disabled||useProps?.readonly,defaultValue:value?.use,name:props.name+"-use","data-testid":"use",onChange:e=>setUse(e.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:getErrorsForInput(outcome,errorPath+".use")}),jsx70(TextInput13,{disabled:props.disabled||prefixProps?.readonly,placeholder:"Prefix",name:props.name+"-prefix",defaultValue:value?.prefix?.join(" "),onChange:e=>setPrefix(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".prefix")}),jsx70(TextInput13,{disabled:props.disabled||givenProps?.readonly,placeholder:"Given",name:props.name+"-given",defaultValue:value?.given?.join(" "),onChange:e=>setGiven(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".given")}),jsx70(TextInput13,{disabled:props.disabled||familyProps?.readonly,name:props.name+"-family",placeholder:"Family",defaultValue:value?.family,onChange:e=>setFamily(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".family")}),jsx70(TextInput13,{disabled:props.disabled||suffixProps?.readonly,placeholder:"Suffix",name:props.name+"-suffix",defaultValue:value?.suffix?.join(" "),onChange:e=>setSuffix(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".suffix")})]})}import{Group as Group17,TextInput as TextInput14}from"@mantine/core";import{useContext as useContext12,useMemo as useMemo11,useState as useState35}from"react";import{jsx as jsx71,jsxs as jsxs38}from"react/jsx-runtime";function IdentifierInput(props){let[value,setValue]=useState35(props.defaultValue),{elementsByPath,getExtendedProps}=useContext12(ElementsContext),[systemElement,valueElement]=useMemo11(()=>["system","value"].map(field=>elementsByPath[props.path+"."+field]),[elementsByPath,props.path]),[systemProps,valueProps]=useMemo11(()=>["system","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}let errorPath=props.valuePath??props.path;return jsxs38(Group17,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx71(TextInput14,{disabled:props.disabled||systemProps?.readonly,placeholder:"System",required:(systemElement?.min??0)>0,defaultValue:value?.system,onChange:e=>setValueWrapper({...value,system:e.currentTarget.value}),error:getErrorsForInput(props.outcome,errorPath+".system")}),jsx71(TextInput14,{disabled:props.disabled||valueProps?.readonly,placeholder:"Value",required:(valueElement?.min??0)>0,defaultValue:value?.value,onChange:e=>setValueWrapper({...value,value:e.currentTarget.value}),error:getErrorsForInput(props.outcome,errorPath+".value")})]})}import{NativeSelect as NativeSelect5,TextInput as TextInput15}from"@mantine/core";import{useCallback as useCallback7,useContext as useContext13,useMemo as useMemo12,useState as useState36}from"react";import{jsx as jsx72}from"react/jsx-runtime";var data=["USD","EUR","CAD","GBP","AUD"];function MoneyInput(props){let{onChange}=props,[value,setValue]=useState36(props.defaultValue),{getExtendedProps}=useContext13(ElementsContext),[currencyProps,valueProps]=useMemo12(()=>["currency","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]),setValueWrapper=useCallback7(newValue=>{setValue(newValue),onChange&&onChange(newValue)},[onChange]),handleCurrencyChange=useCallback7(e=>{setValueWrapper({...value,currency:e.currentTarget.value})},[value,setValueWrapper]),handleValueChange=useCallback7(e=>{setValueWrapper({...value,value:e.currentTarget.valueAsNumber})},[value,setValueWrapper]),select=jsx72(NativeSelect5,{disabled:props.disabled||currencyProps?.readonly,defaultValue:value?.currency,data,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:handleCurrencyChange});return jsx72(TextInput15,{disabled:props.disabled||valueProps?.readonly,type:"number",name:props.name,label:props.label,placeholder:props.placeholder??"Value",defaultValue:value?.value?.toString()??"USD",leftSection:jsx72(IconCurrencyDollar,{size:14}),rightSection:select,rightSectionWidth:92,onChange:handleValueChange})}import{Group as Group18}from"@mantine/core";import{useContext as useContext14,useMemo as useMemo13,useState as useState37}from"react";import{jsx as jsx73,jsxs as jsxs39}from"react/jsx-runtime";function PeriodInput(props){let[value,setValue]=useState37(props.defaultValue),{getExtendedProps}=useContext14(ElementsContext),[startProps,endProps]=useMemo13(()=>["start","end"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs39(Group18,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx73(DateTimeInput,{disabled:props.disabled||startProps?.readonly,name:props.name+".start",placeholder:"Start",defaultValue:value?.start,onChange:newValue=>setValueWrapper({...value,start:newValue})}),jsx73(DateTimeInput,{disabled:props.disabled||endProps?.readonly,name:props.name+".end",placeholder:"End",defaultValue:value?.end,onChange:newValue=>setValueWrapper({...value,end:newValue})})]})}import{Group as Group19,NativeSelect as NativeSelect6,TextInput as TextInput16}from"@mantine/core";import{useContext as useContext15,useMemo as useMemo14,useState as useState38}from"react";import{jsx as jsx74,jsxs as jsxs40}from"react/jsx-runtime";function QuantityInput(props){let[value,setValue]=useState38(props.defaultValue),{getExtendedProps}=useContext15(ElementsContext),[comparatorProps,valueProps,unitProps]=useMemo14(()=>["comparator","value","unit"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs40(Group19,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx74(NativeSelect6,{disabled:props.disabled||comparatorProps?.readonly,style:{width:80},"data-testid":props.name+"-comparator",defaultValue:value?.comparator,data:["","<","<=",">=",">"],onChange:e=>setValueWrapper({...value,comparator:e.currentTarget.value})}),jsx74(TextInput16,{disabled:props.disabled||valueProps?.readonly,id:props.name,name:props.name,required:props.required,"data-autofocus":props.autoFocus,"data-testid":props.name+"-value",type:"number",placeholder:"Value",defaultValue:value?.value,autoFocus:props.autoFocus,step:"any",onWheel:e=>{props.disableWheel&&e.currentTarget.blur()},onChange:e=>{setValueWrapper({...value,value:tryParseNumber(e.currentTarget.value)})}}),jsx74(TextInput16,{disabled:props.disabled||unitProps?.readonly,placeholder:"Unit","data-testid":props.name+"-unit",defaultValue:value?.unit,onChange:e=>setValueWrapper({...value,unit:e.currentTarget.value})})]})}function tryParseNumber(str){if(str)return Number.parseFloat(str)}import{Group as Group20}from"@mantine/core";import{useContext as useContext16,useMemo as useMemo15,useState as useState39}from"react";import{jsx as jsx75,jsxs as jsxs41}from"react/jsx-runtime";function RangeInput(props){let[value,setValue]=useState39(props.defaultValue),{getExtendedProps}=useContext16(ElementsContext),[lowProps,highProps]=useMemo15(()=>["low","high"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs41(Group20,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx75(QuantityInput,{path:props.path+".low",disabled:props.disabled||lowProps?.readonly,name:props.name+"-low",defaultValue:value?.low,onChange:v=>setValueWrapper({...value,low:v})}),jsx75(QuantityInput,{path:props.path+".high",disabled:props.disabled||highProps?.readonly,name:props.name+"-high",defaultValue:value?.high,onChange:v=>setValueWrapper({...value,high:v})})]})}import{Group as Group21}from"@mantine/core";import{useContext as useContext17,useMemo as useMemo16,useState as useState40}from"react";import{jsx as jsx76,jsxs as jsxs42}from"react/jsx-runtime";function RatioInput(props){let[value,setValue]=useState40(props.defaultValue),{getExtendedProps}=useContext17(ElementsContext),[numeratorProps,denominatorProps]=useMemo16(()=>["numerator","denominator"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs42(Group21,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx76(QuantityInput,{path:props.path+".numerator",disabled:props.disabled||numeratorProps?.readonly,name:props.name+"-numerator",defaultValue:value?.numerator,onChange:v=>setValueWrapper({...value,numerator:v})}),jsx76(QuantityInput,{path:props.path+".denominator",disabled:props.disabled||denominatorProps?.readonly,name:props.name+"-denominator",defaultValue:value?.denominator,onChange:v=>setValueWrapper({...value,denominator:v})})]})}import{Group as Group23,NativeSelect as NativeSelect7}from"@mantine/core";import{LRUCache,ReadablePromise,createReference as createReference2,isEmpty as isEmpty4,isPopulated as isPopulated8,tryGetProfile as tryGetProfile3}from"@medplum/core";import{useMedplum as useMedplum21}from"@medplum/react-hooks";import{useCallback as useCallback10,useEffect as useEffect12,useMemo as useMemo17,useRef as useRef7,useState as useState42}from"react";import{useCallback as useCallback9}from"react";import{Group as Group22,Text as Text14}from"@mantine/core";import{getDisplayString as getDisplayString3,getReferenceString as getReferenceString3,isReference as isReference2,isResource as isResource2}from"@medplum/core";import{useMedplum as useMedplum20}from"@medplum/react-hooks";import{forwardRef as forwardRef4,useCallback as useCallback8,useEffect as useEffect11,useRef as useRef6,useState as useState41}from"react";import{jsx as jsx77,jsxs as jsxs43}from"react/jsx-runtime";var SEARCH_CODES={Device:"device-name",Observation:"code",Subscription:"criteria",User:"email:contains"},NAME_RESOURCE_TYPES=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","ResearchStudy","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function toOption3(resource){return{value:getReferenceString3(resource)??"",label:getDisplayString3(resource),resource}}function getSearchParamForResourceType(resourceType){return SEARCH_CODES[resourceType]??(NAME_RESOURCE_TYPES.includes(resourceType)?"name":"_id")}var DefaultResourceItemComponent=forwardRef4(({label,resource,active:_active,...others},ref)=>jsx77("div",{ref,...others,children:jsxs43(Group22,{wrap:"nowrap",children:[jsx77(ResourceAvatar,{value:resource}),jsxs43("div",{children:[jsx77(Text14,{children:label}),jsx77(Text14,{size:"xs",c:"dimmed",children:resource.birthDate||resource.id})]})]})}));DefaultResourceItemComponent.displayName="DefaultResourceItemComponent";function MultiResourceInput(props){let medplum=useMedplum20(),{resourceType,searchCriteria}=props,ItemComponent3=props.itemComponent??DefaultResourceItemComponent,onChange=props.onChange,initialDefaultValue=useRef6(props.defaultValue),[defaultResources,setDefaultResources]=useState41(!props.defaultValue||props.defaultValue.length===0?[]:void 0);useEffect11(()=>{let cancelled=!1,items=initialDefaultValue.current;return items&&items.length>0&&Promise.allSettled(items.map(item=>isResource2(item)?Promise.resolve(item):isReference2(item)?medplum.readReference(item):Promise.reject(new Error("Not a resolvable item")))).then(settled=>{cancelled||setDefaultResources(settled.filter(r2=>r2.status==="fulfilled").map(r2=>r2.value))}).catch(()=>{}),()=>{cancelled=!0}},[medplum]);let loadValues=useCallback8(async(input,signal)=>{let searchCode=getSearchParamForResourceType(resourceType),searchParams=new URLSearchParams({[searchCode]:input??"",_count:"10",...searchCriteria});return await medplum.searchResources(resourceType,searchParams,{signal})},[medplum,resourceType,searchCriteria]),handleChange=useCallback8(newResources=>{onChange&&onChange(newResources)},[onChange]);return defaultResources===void 0?null:jsx77(AsyncAutocomplete,{disabled:props.disabled,name:props.name,label:props.label,error:props.error,required:props.required,itemComponent:ItemComponent3,defaultValue:defaultResources,placeholder:props.placeholder,maxValues:props.maxValues,toOption:toOption3,loadOptions:loadValues,onChange:handleChange,clearable:!0})}import{jsx as jsx78}from"react/jsx-runtime";function ResourceInput(props){let onChange=props.onChange,handleChange=useCallback9(newResources=>{onChange&&onChange(newResources[0])},[onChange]);return jsx78(MultiResourceInput,{resourceType:props.resourceType,name:props.name,defaultValue:props.defaultValue?[props.defaultValue]:void 0,searchCriteria:props.searchCriteria,placeholder:props.placeholder,required:props.required,itemComponent:props.itemComponent,onChange:handleChange,disabled:props.disabled,label:props.label,error:props.error,maxValues:1})}import{Fragment as Fragment27,jsx as jsx79,jsxs as jsxs44}from"react/jsx-runtime";function ReferenceInput(props){let{onChange}=props,medplum=useMedplum21(),[value,setValue]=useState42(props.defaultValue),[targetTypes,setTargetTypes]=useState42(()=>createTargetTypes(props.targetTypes)),[targetType,setTargetType]=useState42(()=>getInitialTargetType(props.defaultValue,targetTypes)),promiseCache=useRef7(new LRUCache),searchCriteria=useMemo17(()=>targetType?.type==="profile"?{...props.searchCriteria,_profile:targetType.value}:props.searchCriteria,[props.searchCriteria,targetType]);useEffect12(()=>{let anyToFetch=!1,newTargetTypePromises=targetTypes?.map(tt=>{if(!shouldFetchResourceType(tt))return Promise.resolve(tt);anyToFetch=!0;let cacheKey=tt.value,cached=promiseCache.current.get(cacheKey);if(cached)return cached;let promise=fetchResourceTypeOfProfile(medplum,tt.value).then(profile=>{let newTargetType={...tt};return profile?isPopulated8(profile.type)?(newTargetType.resourceType=profile.type,newTargetType.name=profile.name,newTargetType.title=profile.title):(console.error(`StructureDefinition.type missing for ${tt.value}`),newTargetType.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${tt.value}`),newTargetType.error="StructureDefinition not found"),newTargetType}).catch(reason=>(console.error(reason),{...tt,error:reason})),readablePromise=new ReadablePromise(promise);return promiseCache.current.set(cacheKey,readablePromise),readablePromise});!newTargetTypePromises||!anyToFetch||Promise.all(newTargetTypePromises).then(newTargetTypes=>{if(setTargetTypes(newTargetTypes),!targetType)return;let index=newTargetTypes.findIndex(tt=>tt.value===targetType.value||tt.resourceType===targetType.resourceType);if(index===-1){console.debug(`defaultValue had unexpected resourceType: ${targetType.resourceType}`);return}setTargetType(newTargetTypes[index])}).catch(console.error)},[medplum,targetType,targetTypes]);let setValueHelper=useCallback10(item=>{let newValue=item?createReference2(item):void 0;setValue(newValue),onChange&&onChange(newValue)},[onChange]),typeSelectOptions=useMemo17(()=>targetTypes?targetTypes.map(tt=>({value:tt.value,label:tt.type==="profile"?tt.title??tt.name??tt.resourceType??tt.value:tt.value})):[],[targetTypes]);return jsxs44(Fragment27,{children:[props.name&&jsx79("input",{type:"hidden",name:props.name,value:value?.reference??""}),jsxs44(Group23,{gap:"xs",grow:!0,wrap:"nowrap",children:[targetTypes&&targetTypes.length>1&&jsx79(NativeSelect7,{name:props.name+"-resourceType",disabled:props.disabled,"data-autofocus":props.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:targetType?.resourceType,autoFocus:props.autoFocus,onChange:e=>{let newValue=e.currentTarget.value,newTargetType=targetTypes.find(tt=>tt.value===newValue);setTargetType(newTargetType)},data:typeSelectOptions}),!targetTypes&&jsx79(ResourceTypeInput,{disabled:props.disabled,autoFocus:props.autoFocus,testId:"reference-input-resource-type-input",defaultValue:targetType?.resourceType,onChange:newResourceType=>{setTargetType(newResourceType?{type:"resourceType",value:newResourceType,resourceType:newResourceType}:void 0)},name:props.name+"-resourceType",placeholder:"Resource Type"}),jsx79(ResourceInput,{resourceType:targetType?.resourceType,name:props.name+"-id",required:props.required,placeholder:props.placeholder,defaultValue:value,searchCriteria,onChange:setValueHelper,disabled:props.disabled})]})]})}function createTargetTypes(resourceTypesAndProfileUrls){if(!resourceTypesAndProfileUrls||resourceTypesAndProfileUrls.length===0||resourceTypesAndProfileUrls.length===1&&resourceTypesAndProfileUrls[0]==="Resource")return;let results=[];for(let value of resourceTypesAndProfileUrls)value.includes("/")?results.push({type:"profile",value}):results.push({type:"resourceType",value,resourceType:value});return results}function getInitialTargetType(defaultValue2,targetTypes){let defaultValueResourceType=defaultValue2?.reference?.split("/")[0];if(defaultValueResourceType){let targetType=targetTypes?.find(tt=>tt.resourceType===defaultValueResourceType);return targetType||{type:"resourceType",value:defaultValueResourceType,resourceType:defaultValueResourceType}}if(targetTypes&&targetTypes.length>0)return targetTypes[0]}async function fetchResourceTypeOfProfile(medplum,profileUrl){let profile=tryGetProfile3(profileUrl);if(profile)return{type:profile.type,name:profile.name,title:profile.title};let query=`{
|
|
103
|
+
`)}function getIssuesForExpression(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))}var ARRAY_INDEX_REGEX=/\[\d+\]/;function isExpressionMatch(expr1,expr2){let isExpr1Indexed=typeof expr1=="string"&&ARRAY_INDEX_REGEX.test(expr1),isExpr2Indexed=typeof expr2=="string"&&ARRAY_INDEX_REGEX.test(expr2);if(isExpr1Indexed!==isExpr2Indexed&&(expr1=expr1?.replace(ARRAY_INDEX_REGEX,""),expr2=expr2?.replace(ARRAY_INDEX_REGEX,"")),expr1===expr2)return!0;if(!expr1||!expr2)return!1;let dot1=expr1.indexOf(".");if(dot1>=0&&expr1.substring(dot1+1)===expr2)return!0;let dot2=expr2.indexOf(".");return dot2>=0&&expr2.substring(dot2+1)===expr1}import{jsx as jsx33,jsxs as jsxs18}from"react/jsx-runtime";function ChangePasswordForm(props){let{onSuccess}=props,medplum=useMedplum7(),[outcome,setOutcome]=useState15(),[success,setSuccess]=useState15(!1);return jsx33(Document,{width:450,children:jsxs18(Form,{onSubmit:formData=>{setOutcome(void 0),medplum.post("auth/changepassword",formData).then(()=>{setSuccess(!0),onSuccess?.()}).catch(err=>setOutcome(normalizeOperationOutcome2(err)))},children:[jsxs18(Flex,{direction:"column",align:"center",justify:"center",children:[jsx33(Logo,{size:32}),jsx33(Title,{children:"Change password"})]}),!success&&jsxs18(Stack5,{gap:"xl",mt:"xl",children:[jsx33(PasswordInput,{name:"oldPassword",label:"Old password",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"oldPassword")}),jsx33(PasswordInput,{name:"newPassword",label:"New password",required:!0,error:getErrorsForInput(outcome,"newPassword")}),jsx33(PasswordInput,{name:"confirmPassword",label:"Confirm new password",required:!0,error:getErrorsForInput(outcome,"confirmPassword")}),jsx33(Group8,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:jsx33(Button4,{type:"submit",children:"Change password"})})]}),success&&jsx33("div",{"data-testid":"success",children:"Password changed successfully"})]})})}import{Alert as Alert2,Center as Center2,Image as Image2,Stack as Stack6,Text as Text7,TextInput as TextInput4,Title as Title2}from"@mantine/core";import{normalizeErrorString as normalizeErrorString4}from"@medplum/core";import{useState as useState16}from"react";import{jsx as jsx34,jsxs as jsxs19}from"react/jsx-runtime";function MfaForm(props){let[errorMessage,setErrorMessage]=useState16();return jsxs19(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData)?.catch(err=>setErrorMessage(normalizeErrorString4(err)))},children:[jsxs19(Center2,{style:{flexDirection:"column"},children:[jsx34(Logo,{size:32}),jsx34(Title2,{order:3,py:"lg",children:props.title}),!props.qrCodeUrl&&props.description&&jsx34(Text7,{c:"dimmed",mb:"lg",mt:"-lg",children:props.description})]}),errorMessage&&jsx34(Alert2,{icon:jsx34(IconAlertCircle,{size:16}),title:"Error",color:"red",mb:"lg",children:errorMessage}),props.qrCodeUrl&&jsx34(Center2,{children:jsxs19(Stack6,{mb:"xl",children:[props.description&&jsx34(Text7,{c:"dimmed",mb:"md",mt:"-lg",ta:"center",children:props.description}),jsx34(Image2,{src:props.qrCodeUrl,alt:"Multi Factor Auth QR Code",w:"60%",mx:"auto",radius:"md",p:"xs",bg:"var(--mantine-color-white)",style:{border:"1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4))"}})]})}),jsx34(Stack6,{gap:"sm",children:jsx34(TextInput4,{name:"token",label:"MFA code",autoComplete:"one-time-code",required:!0,autoFocus:!0})}),jsx34(Stack6,{gap:"xs",pt:"md",children:jsx34(SubmitButton,{fullWidth:!0,children:props.buttonText})})]})}import{normalizeOperationOutcome as normalizeOperationOutcome5}from"@medplum/core";import{useMedplum as useMedplum10}from"@medplum/react-hooks";import{useEffect as useEffect5,useState as useState20}from"react";import{Alert as Alert3}from"@mantine/core";import{operationOutcomeIssueToString}from"@medplum/core";import{jsx as jsx35}from"react/jsx-runtime";function OperationOutcomeAlert(props){let{outcome,issues:issuesProp,...spacingProps}=props,issues=outcome?.issue||issuesProp;return!issues||issues.length===0?null:jsx35(Alert3,{icon:jsx35(IconAlertCircle,{size:16}),color:"red",...spacingProps,children:issues.map(issue=>jsx35("div",{"data-testid":"text-field-error",children:operationOutcomeIssueToString(issue)},issue.details?.text))})}import{Anchor as Anchor3,Flex as Flex2,Stack as Stack7,Text as Text8,TextInput as TextInput5,Title as Title3}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome3}from"@medplum/core";import{useMedplum as useMedplum8}from"@medplum/react-hooks";import{useState as useState17}from"react";import{jsx as jsx36,jsxs as jsxs20}from"react/jsx-runtime";function NewProjectForm(props){let medplum=useMedplum8(),[outcome,setOutcome]=useState17(),issues=getIssuesForExpression(outcome,void 0);return jsxs20(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome(normalizeOperationOutcome3(err))}},children:[jsxs20(Flex2,{direction:"column",align:"center",justify:"center",children:[jsx36(Logo,{size:32}),jsx36(Title3,{order:3,py:"lg",children:"Create a new project"})]}),jsx36(OperationOutcomeAlert,{issues,mb:"lg"}),jsx36(Stack7,{gap:"sm",children:jsx36(TextInput5,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")})}),jsxs20(Stack7,{gap:"xs",mt:"md",children:[jsx36(SubmitButton,{fullWidth:!0,children:"Create Project"}),jsxs20(Text8,{c:"dimmed",size:"xs",pt:"lg",ta:"center",children:['By clicking "Create Project" you agree to the Medplum'," ",jsx36(Anchor3,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx36(Anchor3,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]})]})}import{Anchor as Anchor4,Box as Box3,Checkbox,Divider as Divider2,Flex as Flex3,PasswordInput as PasswordInput2,Stack as Stack8,Text as Text9,TextInput as TextInput6}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useMedplum as useMedplum9}from"@medplum/react-hooks";import{useEffect as useEffect4,useState as useState19}from"react";import{Box as Box2}from"@mantine/core";import{useEffect as useEffect3,useRef as useRef4,useState as useState18}from"react";function createScriptTag(src,onload){let head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.async=!0,script.src=src,script.onload=onload??null,head.appendChild(script)}import{jsx as jsx37}from"react/jsx-runtime";function GoogleButton(props){let{googleClientId,handleGoogleCredential}=props,parentRef=useRef4(null),[scriptLoaded,setScriptLoaded]=useState18(typeof google<"u"),initializedRef=useRef4(!1),buttonRenderedRef=useRef4(!1);return useEffect3(()=>{if(typeof google>"u"){createScriptTag("https://accounts.google.com/gsi/client",()=>setScriptLoaded(!0));return}initializedRef.current||(google.accounts.id.initialize({client_id:googleClientId,callback:handleGoogleCredential}),initializedRef.current=!0),parentRef.current&&!buttonRenderedRef.current&&(google.accounts.id.renderButton(parentRef.current,{type:"standard",logo_alignment:"center",width:parentRef.current.clientWidth}),buttonRenderedRef.current=!0)},[googleClientId,scriptLoaded,handleGoogleCredential]),googleClientId?jsx37(Box2,{ref:parentRef,w:"100%",h:40,display:"flex",style:{justifyContent:"center"}}):null}import{locationUtils as locationUtils3}from"@medplum/core";function getGoogleClientId(clientId){if(clientId)return clientId;let origin=locationUtils3.getOrigin();if(origin&&("undefined"?.split(",")??[]).includes(origin))return"__GOOGLE_CLIENT_ID__"}function initRecaptcha(siteKey){typeof grecaptcha>"u"&&createScriptTag("https://www.google.com/recaptcha/api.js?render="+siteKey)}function getRecaptcha(siteKey){return new Promise((resolve,reject)=>{grecaptcha.ready(async()=>{try{resolve(await grecaptcha.execute(siteKey,{action:"submit"}))}catch(err){reject(err)}})})}import{Fragment as Fragment11,jsx as jsx38,jsxs as jsxs21}from"react/jsx-runtime";function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=useMedplum9(),[outcome,setOutcome]=useState19(),issues=getIssuesForExpression(outcome,void 0);return useEffect4(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsxs21(Form,{onSubmit:async formData=>{setOutcome(void 0);try{let recaptchaToken="";recaptchaSiteKey&&(recaptchaToken=await getRecaptcha(recaptchaSiteKey)),props.handleAuthResponse(await medplum.startNewUser({projectId:props.projectId,clientId:props.clientId,firstName:formData.firstName,lastName:formData.lastName,email:formData.email,password:formData.password,remember:formData.remember==="true",recaptchaSiteKey,recaptchaToken}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}},children:[jsx38(Flex3,{direction:"column",align:"center",justify:"center",children:props.children}),jsx38(OperationOutcomeAlert,{issues,mb:"lg"}),googleClientId&&jsxs21(Fragment11,{children:[jsx38(Box3,{style:{minHeight:40},children:jsx38(GoogleButton,{googleClientId,handleGoogleCredential:async response=>{try{props.handleAuthResponse(await medplum.startGoogleLogin({googleClientId:response.clientId,googleCredential:response.credential,projectId:props.projectId,createUser:!0}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}}})}),jsx38(Divider2,{label:"or",labelPosition:"center",my:"lg"})]}),jsxs21(Stack8,{gap:"sm",children:[jsx38(TextInput6,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),jsx38(TextInput6,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),jsx38(TextInput6,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),jsx38(PasswordInput2,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")})]}),jsxs21(Stack8,{gap:"xs",children:[jsx38(Checkbox,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1},pt:"md",pb:"xs"}),jsx38(SubmitButton,{fullWidth:!0,children:"Register Account"}),jsxs21(Text9,{c:"dimmed",size:"xs",pt:"lg",ta:"center",children:['By clicking "Register Account" you agree to the Medplum'," ",jsx38(Anchor4,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx38(Anchor4,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),jsxs21(Text9,{c:"dimmed",size:"xs",ta:"center",children:["This site is protected by reCAPTCHA and the Google"," ",jsx38(Anchor4,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx38(Anchor4,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]})]})}import{jsx as jsx39,jsxs as jsxs22}from"react/jsx-runtime";function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=useMedplum10(),[login,setLogin]=useState20(),[outcome,setOutcome]=useState20();useEffect5(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome5(err)))},[medplum,type,projectId,login,onSuccess]);function handleAuthResponse(response){response.code?medplum.processCode(response.code).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome5(err))):response.login&&setLogin(response.login)}let issues=getIssuesForExpression(outcome,void 0);return jsxs22(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:[jsx39(OperationOutcomeAlert,{issues,mb:"lg"}),!login&&jsx39(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&jsx39(NewProjectForm,{login,handleAuthResponse})]})}import{Anchor as Anchor5,Flex as Flex4,Stack as Stack9,Text as Text10,TextInput as TextInput7,Title as Title4}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome6}from"@medplum/core";import{useMedplum as useMedplum11}from"@medplum/react-hooks";import{useEffect as useEffect6,useState as useState21}from"react";import{Fragment as Fragment12,jsx as jsx40,jsxs as jsxs23}from"react/jsx-runtime";function ResetPasswordForm(props){let{projectId,recaptchaSiteKey,onSuccess,onSignIn,onRegister}=props,medplum=useMedplum11(),[outcome,setOutcome]=useState21(),[success,setSuccess]=useState21(!1);return useEffect6(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsx40(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:jsxs23(Form,{onSubmit:async formData=>{setOutcome(void 0);try{let recaptchaToken="";recaptchaSiteKey&&(recaptchaToken=await getRecaptcha(recaptchaSiteKey)),await medplum.post("auth/resetpassword",{...formData,projectId,recaptchaToken}),setSuccess(!0),onSuccess?.()}catch(err){setOutcome(normalizeOperationOutcome6(err))}},children:[jsxs23(Flex4,{direction:"column",align:"center",justify:"center",children:[jsx40(Logo,{size:32}),jsx40(Title4,{order:3,py:"lg",children:"Reset your password"})]}),jsx40(OperationOutcomeAlert,{issues:getIssuesForExpression(outcome,void 0),mb:"lg"}),!success&&jsxs23(Fragment12,{children:[jsx40(Stack9,{gap:"sm",mb:"md",children:jsx40(TextInput7,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")})}),jsxs23(Stack9,{gap:"xs",children:[jsx40(SubmitButton,{fullWidth:!0,children:"Reset Password"}),onSignIn&&jsx40(Text10,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:jsx40(Anchor5,{onClick:onSignIn,children:"Back to Sign In"})}),onRegister&&jsxs23(Text10,{size:"sm",mt:"none",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:["Don't have an account? ",jsx40(Anchor5,{onClick:onRegister,children:"Sign Up"})]})]})]}),success&&jsx40(Text10,{c:"dimmed",size:"sm",ta:"center",mt:"md",children:"If the account exists on our system, a password reset email will be sent."})]})})}import{Anchor as Anchor6,Button as Button5,Flex as Flex5,Group as Group9,PasswordInput as PasswordInput3,Stack as Stack10,Title as Title5}from"@mantine/core";import{badRequest,normalizeOperationOutcome as normalizeOperationOutcome7}from"@medplum/core";import{useMedplum as useMedplum12}from"@medplum/react-hooks";import{useState as useState22}from"react";import{jsx as jsx41,jsxs as jsxs24}from"react/jsx-runtime";function SetPasswordForm(props){let{id,secret,onSuccess,onSignIn}=props,medplum=useMedplum12(),[outcome,setOutcome]=useState22(),[success,setSuccess]=useState22(!1),issues=getIssuesForExpression(outcome,void 0);return jsxs24(Document,{width:450,children:[jsx41(OperationOutcomeAlert,{issues}),jsxs24(Form,{onSubmit:formData=>{if(formData.password!==formData.confirmPassword){setOutcome(badRequest("Passwords do not match","confirmPassword"));return}setOutcome(void 0),medplum.post("auth/setpassword",{id,secret,password:formData.password}).then(()=>{setSuccess(!0),onSuccess?.()}).catch(err=>setOutcome(normalizeOperationOutcome7(err)))},children:[jsxs24(Flex5,{direction:"column",align:"center",justify:"center",children:[jsx41(Logo,{size:32}),jsx41(Title5,{children:"Set password"})]}),!success&&jsxs24(Stack10,{children:[jsx41(PasswordInput3,{name:"password",label:"New password",required:!0,error:getErrorsForInput(outcome,"password")}),jsx41(PasswordInput3,{name:"confirmPassword",label:"Confirm new password",required:!0,error:getErrorsForInput(outcome,"confirmPassword")}),jsx41(Group9,{justify:"flex-end",mt:"xl",children:jsx41(Button5,{type:"submit",children:"Set password"})})]}),success&&jsxs24("div",{"data-testid":"success",children:["Password set. You can now\xA0",onSignIn?jsx41(Anchor6,{component:"button",type:"button",onClick:onSignIn,children:"sign in"}):"sign in","."]})]})]})}import{showNotification as showNotification3}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString5}from"@medplum/core";import{useMedplum as useMedplum16}from"@medplum/react-hooks";import{useCallback as useCallback6,useEffect as useEffect7,useRef as useRef5,useState as useState25}from"react";import{ActionIcon as ActionIcon2,Anchor as Anchor7,Box as Box4,Checkbox as Checkbox2,Divider as Divider3,Flex as Flex6,PasswordInput as PasswordInput4,Stack as Stack11,Text as Text11,TextInput as TextInput8}from"@mantine/core";import{locationUtils as locationUtils4,normalizeOperationOutcome as normalizeOperationOutcome8}from"@medplum/core";import{useMedplum as useMedplum13}from"@medplum/react-hooks";import{useCallback as useCallback5,useState as useState23}from"react";import{Fragment as Fragment13,jsx as jsx42,jsxs as jsxs25}from"react/jsx-runtime";function AuthenticationForm(props){let[email,setEmail]=useState23();return email?jsx42(PasswordForm,{email,resetEmail:()=>setEmail(void 0),...props}):jsx42(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=useMedplum13(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=useState23(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=useCallback5(async authMethod=>{if(!authMethod.authorizeUrl)return!1;let state=JSON.stringify({...await medplum.ensureCodeChallenge(baseLoginRequest),domain:authMethod.domain,returnTo:locationUtils4.getLocation()}),url=new URL(authMethod.authorizeUrl);return url.searchParams.set("state",state),locationUtils4.assign(url.toString()),!0},[medplum,baseLoginRequest]),handleSubmit=useCallback5(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=useCallback5(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome(normalizeOperationOutcome8(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return jsxs25(Form,{onSubmit:handleSubmit,children:[jsx42(Flex6,{direction:"column",align:"center",justify:"center",children}),jsx42(OperationOutcomeAlert,{issues,mb:"lg"}),googleClientId&&jsxs25(Fragment13,{children:[jsx42(Box4,{style:{minHeight:40},children:jsx42(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&jsx42(Divider3,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&jsx42(TextInput8,{name:"email",type:"email",label:"Email",mb:"md",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email"),"data-testid":"auth.email"}),jsxs25(Stack11,{gap:"xs",children:[!disableEmailAuth&&jsx42(SubmitButton,{fullWidth:!0,children:"Continue"}),onRegister&&jsxs25(Text11,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:["Don\u2019t have an account? ",jsx42(Anchor7,{onClick:onRegister,children:"Register"})]})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=useMedplum13(),[outcome,setOutcome]=useState23(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=useCallback5(formData=>medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome8(err))),[medplum,baseLoginRequest,handleAuthResponse]);return jsxs25(Form,{onSubmit:handleSubmit,children:[jsx42(Flex6,{direction:"column",align:"center",justify:"center",children}),jsx42(OperationOutcomeAlert,{issues,mb:"lg"}),jsxs25(Stack11,{gap:"sm",children:[jsx42(TextInput8,{label:"Email",value:props.email,disabled:!0,rightSectionWidth:36,rightSection:jsx42(ActionIcon2,{variant:"subtle",color:"gray",onClick:props.resetEmail,"aria-label":"Change email",children:jsx42(IconPencil,{size:"1rem",stroke:1.5})})}),jsx42(PasswordInput4,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password"),"data-testid":"auth.password"})]}),jsxs25(Stack11,{gap:"xs",children:[jsx42(Checkbox2,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1},pt:"md",pb:"xs"}),jsx42(SubmitButton,{children:"Sign In"}),onForgotPassword&&jsx42(Text11,{size:"sm",mt:"lg",c:"dimmed",style:{textAlign:"center"},"data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:jsx42(Anchor7,{onClick:onForgotPassword,children:"Reset Password"})})]})]})}import{Anchor as Anchor8,Box as Box5,Combobox as Combobox2,Flex as Flex7,Group as Group10,Stack as Stack12,Text as Text12,TextInput as TextInput9,Title as Title6,useCombobox as useCombobox2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome9}from"@medplum/core";import{useMedplum as useMedplum14}from"@medplum/react-hooks";import{useState as useState24}from"react";var ChooseProfileForm_default={option:"ChooseProfileForm_option",iconBox:"ChooseProfileForm_iconBox"};import{jsx as jsx43,jsxs as jsxs26}from"react/jsx-runtime";function ChooseProfileForm(props){let medplum=useMedplum14(),combobox=useCombobox2(),[search,setSearch]=useState24(""),[outcome,setOutcome]=useState24();function filterDisplay(display){return!!display?.toLowerCase()?.includes(search.toLowerCase())}function filterMembership(membership){return filterDisplay(membership.profile?.display)||filterDisplay(membership.project?.display)||filterDisplay(getMembershipLabel(membership))}function handleValueSelect(membershipId){medplum.post("auth/profile",{login:props.login,profile:membershipId}).then(props.handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome9(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>jsx43(Combobox2.Option,{value:item.id,className:ChooseProfileForm_default.option,children:jsx43(SelectOption,{...item})},item.id));return jsxs26(Stack12,{gap:"0",children:[jsxs26(Flex7,{justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[jsx43(Logo,{size:32}),jsx43(Title6,{order:3,py:"lg",children:"Choose a Project"})]}),jsx43(OperationOutcomeAlert,{outcome,mb:"lg"}),jsxs26(Combobox2,{store:combobox,onOptionSubmit:handleValueSelect,children:[jsx43(Combobox2.EventsTarget,{children:jsx43(TextInput9,{placeholder:"Search",value:search,mb:"md",autoFocus:!0,leftSection:jsx43(IconSearch,{size:16}),onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),jsx43("div",{children:jsx43(Combobox2.Options,{style:{marginLeft:"-10px",marginRight:"-10px",marginBottom:"-10px"},children:options.length>0?options:jsx43(Combobox2.Empty,{children:"Nothing found..."})})})]}),jsx43(Text12,{size:"sm",ta:"center",mt:"md",children:jsx43(Anchor8,{component:"button",type:"button",onClick:()=>{window.location.href=`/signin?project=new&login=${props.login}`},children:"Create a new project"})})]})}function getMembershipLabel(membership){return membership.identifier?.find(i=>i.system==="https://medplum.com/identifier/label")?.value}function SelectOption(membership){let label=getMembershipLabel(membership);return jsxs26(Group10,{gap:"xs",align:"center",children:[jsx43(Box5,{className:ChooseProfileForm_default.iconBox,children:jsx43(IconBriefcase,{size:16,stroke:2})}),jsxs26("div",{children:[jsxs26(Text12,{size:"sm",fw:500,children:[membership.project?.display," ",label?` - ${label}`:""]}),jsx43(Text12,{size:"xs",c:"dimmed",children:membership.profile?.display})]})]})}import{Checkbox as Checkbox3,Flex as Flex8,Group as Group11,Stack as Stack13,Title as Title7}from"@mantine/core";import{useMedplum as useMedplum15}from"@medplum/react-hooks";import{Fragment as Fragment14}from"react/jsx-runtime";import{jsx as jsx44,jsxs as jsxs27}from"react/jsx-runtime";var openConditionScope=/^patient\/Condition\.(?:\*|c?r?u?d?s?)$/,encounterDiagnosis="?category=http://terminology.hl7.org/CodeSystem/condition-category|encounter-diagnosis",problemListItem="?category=http://terminology.hl7.org/CodeSystem/condition-category|problem-list-item",healthConcern="?category=http://hl7.org/fhir/us/core/CodeSystem/condition-category|health-concern",openObservationScope=/^patient\/Observation\.(?:\*|c?r?u?d?s?)$/,clinicalTest="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-observation-category|clinical-test",laboratory="?category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory",socialHistory="?category=http://terminology.hl7.org/CodeSystem/observation-category|social-history",sdoh="?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-category|sdoh",survey="?category=http://terminology.hl7.org/CodeSystem/observation-category|survey",vitalSigns="?category=http://terminology.hl7.org/CodeSystem/observation-category|vital-signs";function ChooseScopeForm(props){let medplum=useMedplum15();return jsx44(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:jsxs27(Stack13,{children:[jsxs27(Flex8,{direction:"column",align:"center",justify:"center",children:[jsx44(Logo,{size:32}),jsx44(Title7,{order:3,py:"lg",children:"Choose scope"})]}),jsx44(Stack13,{children:(props.scope??"openid").split(" ").map(scopeName=>{let additionalScopes;return openConditionScope.test(scopeName)?additionalScopes=[scopeName+encounterDiagnosis,scopeName+problemListItem,scopeName+healthConcern]:openObservationScope.test(scopeName)&&(additionalScopes=[scopeName+clinicalTest,scopeName+laboratory,scopeName+socialHistory,scopeName+sdoh,scopeName+survey,scopeName+vitalSigns]),jsxs27(Fragment14,{children:[jsx44(Checkbox3,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName),additionalScopes?.map(scope=>jsx44(Checkbox3,{id:scope,name:scope,label:scope},scope))]},scopeName+"_group")})}),jsx44(Group11,{justify:"flex-end",mt:"xl",children:jsx44(SubmitButton,{fullWidth:!0,children:"Set Scope"})})]})})}import{jsx as jsx45}from"react/jsx-runtime";function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=useMedplum16(),[login,setLogin]=useState25(),loginRequested=useRef5(!1),[mfaEnrollRequired,setMfaEnrollRequired]=useState25(!1),[enrollQrCode,setEnrollQrCode]=useState25(),[mfaRequired,setMfaRequired]=useState25(!1),[memberships,setMemberships]=useState25(),handleCode=useCallback6(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>showNotification3({color:"red",message:normalizeErrorString5(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=useCallback6(response=>{setMfaEnrollRequired(!!response.mfaEnrollRequired),setEnrollQrCode(response.enrollQrCode),setMfaRequired(!!response.mfaRequired),response.login&&setLogin(response.login),response.memberships&&setMemberships(response.memberships),response.code&&(chooseScopes?setMemberships(void 0):handleCode(response.code))},[chooseScopes,handleCode]),handleScopeResponse=useCallback6(response=>{handleCode(response.code)},[handleCode]);return useEffect7(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>showNotification3({color:"red",message:normalizeErrorString5(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),jsx45(Document,{width:400,px:"xl",py:"xl",bdrs:"md",children:login?mfaEnrollRequired&&enrollQrCode?jsx45(MfaForm,{title:"Enroll in MFA",description:"Scan this QR code with your authenticator app.",buttonText:"Enroll",qrCodeUrl:enrollQrCode,onSubmit:async fields=>{let res=await medplum.post("auth/mfa/login-enroll",{login,token:fields.token});handleAuthResponse(res)}}):mfaRequired?jsx45(MfaForm,{title:"Enter MFA code",description:"Enter the code from your authenticator app.",buttonText:"Submit Code",onSubmit:async fields=>{let res=await medplum.post("auth/mfa/verify",{login,token:fields.token});handleAuthResponse(res)}}):props.projectId==="new"?jsx45(NewProjectForm,{login,handleAuthResponse}):memberships?jsx45(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.chooseScopes?jsx45(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):jsx45("div",{children:"Success"}):jsx45(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}import{buildElementsContext as buildElementsContext2,getPathDisplayName as getPathDisplayName3,isEmpty as isEmpty2,tryGetDataType}from"@medplum/core";import{useContext as useContext6,useMemo as useMemo6}from"react";import{ActionIcon as ActionIcon3,CopyButton,Flex as Flex9,Tooltip as Tooltip2}from"@mantine/core";import{PropertyType,formatDateTime,formatPeriod,formatTiming,formatWallTime,isEmpty}from"@medplum/core";import{useState as useState28}from"react";import{formatCodeableConcept}from"@medplum/core";import{Fragment as Fragment15,jsx as jsx46}from"react/jsx-runtime";function CodeableConceptDisplay(props){return jsx46(Fragment15,{children:formatCodeableConcept(props.value)})}import{formatCoding}from"@medplum/core";import{Fragment as Fragment16,jsx as jsx47}from"react/jsx-runtime";function CodingDisplay(props){return jsx47(Fragment16,{children:formatCoding(props.value,props.includeCode)})}import{Fragment as Fragment17,jsx as jsx48}from"react/jsx-runtime";function ContactPointDisplay(props){let contactPoint=props.value;if(!contactPoint)return null;let builder=[];return contactPoint.value&&builder.push(contactPoint.value),(contactPoint.use||contactPoint.system)&&(builder.push(" ["),contactPoint.use&&builder.push(contactPoint.use),contactPoint.use&&contactPoint.system&&builder.push(" "),contactPoint.system&&builder.push(contactPoint.system),builder.push("]")),jsx48(Fragment17,{children:builder.join("").trim()})}import{Fragment as Fragment18,jsx as jsx49,jsxs as jsxs28}from"react/jsx-runtime";function ContactDetailDisplay(props){let contactDetail=props.value;return contactDetail?jsxs28(Fragment18,{children:[contactDetail.name,contactDetail.name&&": ",contactDetail.telecom?.map(telecom=>jsx49(ContactPointDisplay,{value:telecom},`telecom-${contactDetail.name}-${telecom.value}`))]}):null}import{getDataType,isPopulated as isPopulated3,isProfileLoaded,tryGetProfile}from"@medplum/core";import{useMedplum as useMedplum17}from"@medplum/react-hooks";import{useContext as useContext3,useEffect as useEffect8,useMemo as useMemo3,useState as useState26}from"react";import{getTypedPropertyValue,getTypedPropertyValueWithSchema}from"@medplum/core";function getValueAndType(context,path,profileUrl){let typedResult=getTypedPropertyValue(context,path,{profileUrl});return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}function getValueAndTypeFromElement(typedValue,path,element){let typedResult=getTypedPropertyValueWithSchema(typedValue,path,element);return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}import{jsx as jsx50}from"react/jsx-runtime";function ExtensionDisplay(props){let{elementDefinitionType}=props,medplum=useMedplum17(),ctx=useContext3(ElementsContext),[typeSchema,setTypeSchema]=useState26(getDataType("Extension")),profileUrl=useMemo3(()=>{if(isPopulated3(elementDefinitionType?.profile))return elementDefinitionType.profile[0]},[elementDefinitionType]),[loadingProfile,setLoadingProfile]=useState26(profileUrl!==void 0);if(useEffect8(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>{let profile=tryGetProfile(profileUrl);setLoadingProfile(!1),profile&&setTypeSchema(profile)}).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!isProfileLoaded(profileUrl)))return jsx50("div",{children:"Loading..."});if(typeSchema.elements["value[x]"]?.max!==0){let[propertyValue,propertyType]=getValueAndType({type:"Extension",value:props.value},"value[x]",profileUrl??ctx.profileUrl);return jsx50(ResourcePropertyDisplay,{propertyType,value:propertyValue})}return jsx50(BackboneElementDisplay,{path:props.path,value:{type:typeSchema.type,value:props.value},compact:props.compact,ignoreMissingValues:props.ignoreMissingValues,link:props.link,profileUrl})}import{jsxs as jsxs29}from"react/jsx-runtime";function IdentifierDisplay(props){return jsxs29("div",{children:[props.value?.system,": ",props.value?.value]})}import{formatMoney}from"@medplum/core";import{Fragment as Fragment19,jsx as jsx51}from"react/jsx-runtime";function MoneyDisplay(props){return jsx51(Fragment19,{children:formatMoney(props.value)})}import{formatQuantity}from"@medplum/core";import{Fragment as Fragment20,jsx as jsx52}from"react/jsx-runtime";function QuantityDisplay(props){return jsx52(Fragment20,{children:formatQuantity(props.value,props.precision)})}import{formatRange}from"@medplum/core";import{Fragment as Fragment21,jsx as jsx53}from"react/jsx-runtime";function RangeDisplay(props){return jsx53(Fragment21,{children:formatRange(props.value,props.precision,props.exclusive)})}import{Fragment as Fragment22,jsx as jsx54,jsxs as jsxs30}from"react/jsx-runtime";function RatioDisplay(props){let value=props.value;return value?jsxs30(Fragment22,{children:[jsx54(QuantityDisplay,{value:value.numerator,precision:props.precision}),"\xA0/\xA0",jsx54(QuantityDisplay,{value:value.denominator,precision:props.precision})]}):null}import{stringify}from"@medplum/core";import{Fragment as Fragment23,jsx as jsx55}from"react/jsx-runtime";function ReferenceDisplay(props){if(!props.value)return null;let displayString=props.value.display||props.value.reference||stringify(props.value);return props.link!==!1&&props.value.reference?jsx55(MedplumLink,{to:props.value,children:displayString}):jsx55(Fragment23,{children:displayString})}import{Group as Group12,Text as Text13}from"@mantine/core";import{getPathDisplayName as getPathDisplayName2,isPopulated as isPopulated6}from"@medplum/core";import{useMedplum as useMedplum18}from"@medplum/react-hooks";import{useContext as useContext5,useEffect as useEffect9,useMemo as useMemo5,useState as useState27}from"react";import{getValueSliceName,isPopulated as isPopulated4,isSliceDefinitionWithTypes,tryGetProfile as tryGetProfile2}from"@medplum/core";function assignValuesIntoSlices(values,slices,slicing,profileUrl){if(!isPopulated4(slicing?.slices))return[values];let slicedValues=new Array(slices.length+1);for(let i=0;i<slicedValues.length;i++)slicedValues[i]=[];for(let value of values){let sliceName=getValueSliceName(value,slices,slicing.discriminator,profileUrl),sliceIndex=sliceName?slices.findIndex(slice=>slice.name===sliceName):-1;sliceIndex===-1&&(sliceIndex=slices.length),slicedValues[sliceIndex].push(value)}return slicedValues}async function prepareSlices({medplum,property}){return new Promise((resolve,reject)=>{if(!property.slicing){resolve([]);return}let supportedSlices=[],profileUrls=[],promises=[];for(let slice of property.slicing.slices){if(!isSliceDefinitionWithTypes(slice)){console.debug("Unsupported slice definition",slice);continue}let profileUrl;isPopulated4(slice.elements)||(profileUrl=slice.type[0]?.profile?.[0]),supportedSlices.push(slice),profileUrls.push(profileUrl),profileUrl&&promises.push(medplum.requestProfileSchema(profileUrl))}Promise.all(promises).then(()=>{for(let i=0;i<supportedSlices.length;i++){let slice=supportedSlices[i],profileUrl=profileUrls[i];if(profileUrl){let typeSchema=tryGetProfile2(profileUrl);slice.typeSchema=typeSchema}}resolve(supportedSlices)}).catch(reject)})}import{buildElementsContext,isPopulated as isPopulated5}from"@medplum/core";import{useContext as useContext4,useMemo as useMemo4}from"react";import{jsx as jsx56}from"react/jsx-runtime";function maybeWrapWithContext(ContextProvider,contextValue,contents){return contextValue!==void 0?jsx56(ContextProvider,{value:contextValue,children:contents}):contents}import{Fragment as Fragment24,jsx as jsx57}from"react/jsx-runtime";function SliceDisplay(props){let{slice,property}=props,sliceElements=slice.typeSchema?.elements??slice.elements,parentContext=useContext4(ElementsContext),contextValue=useMemo4(()=>{if(isPopulated5(sliceElements))return buildElementsContext({parentContext,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentContext,props.path,slice.typeSchema?.url,sliceElements]);return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx57(Fragment24,{children:props.value.map((value,valueIndex)=>jsx57("div",{children:jsx57(ResourcePropertyDisplay,{property,path:props.path,arrayElement:!0,elementDefinitionType:slice.type[0],propertyType:slice.type[0].code,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${props.value.length}`))}))}import{Fragment as Fragment25,jsx as jsx58,jsxs as jsxs31}from"react/jsx-runtime";var MAX_ARRAY_SIZE=50;function ResourceArrayDisplay(props){let{property,propertyType}=props,medplum=useMedplum18(),values=useMemo5(()=>Array.isArray(props.values)?props.values:[],[props.values]),[loading,setLoading]=useState27(!0),[slices,setSlices]=useState27([]),[slicedValues,setSlicedValues]=useState27(()=>[values]),[valuesLength,setValuesLength]=useState27(0),ctx=useContext5(ElementsContext);if(useEffect9(()=>{prepareSlices({medplum,property}).then(slices2=>{setValuesLength(values.length),setSlices(slices2);let limitedValues=values.slice(0,MAX_ARRAY_SIZE),slicedValues2=assignValuesIntoSlices(limitedValues,slices2,property.slicing,ctx.profileUrl);setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,ctx.profileUrl,setSlicedValues,values]),loading)return jsx58("div",{children:"Loading..."});let nonSliceContent;if(property.type[0]?.code!=="Extension"){let nonSliceValues=slicedValues[slices.length],nonSliceElements=nonSliceValues.map((value,valueIndex)=>jsx58("div",{children:jsx58(ResourcePropertyDisplay,{path:props.path,arrayElement:!0,property,propertyType,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${nonSliceValues.length}`));if(props.includeDescriptionListEntry){if(!isPopulated6(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();nonSliceContent=jsx58(DescriptionListEntry,{term:getPathDisplayName2(key),children:nonSliceElements})}else nonSliceContent=jsx58(Fragment25,{children:nonSliceElements})}return jsxs31(Fragment25,{children:[slices.map((slice,sliceIndex)=>{if(!props.path)throw new Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);let sliceDisplay=jsx58(SliceDisplay,{path:props.path,slice,property,value:slicedValues[sliceIndex],ignoreMissingValues:props.ignoreMissingValues,link:props.link},slice.name);return props.includeDescriptionListEntry&&(sliceDisplay=jsx58(DescriptionListEntry,{term:getPathDisplayName2(slice.name),children:sliceDisplay},slice.name)),sliceDisplay}),nonSliceContent,valuesLength>MAX_ARRAY_SIZE&&jsx58(Group12,{justify:"right",children:jsxs31(Text13,{children:["... ",valuesLength," total values"]})})]})}import{Fragment as Fragment26,jsx as jsx59,jsxs as jsxs32}from"react/jsx-runtime";function ResourcePropertyDisplay(props){let{property,propertyType,value}=props;if(property?.path?.endsWith(".id"))return jsxs32(Flex9,{gap:3,align:"center",children:[value,!isEmpty(value)&&jsx59(CopyButton,{value,timeout:2e3,children:({copied,copy})=>jsx59(Tooltip2,{label:copied?"Copied":"Copy",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,children:copied?jsx59(IconCheck,{size:"1rem"}):jsx59(IconCopy,{size:"1rem"})})})})]});if(property&&(property.isArray||property.max>1)&&!props.arrayElement)return propertyType===PropertyType.Attachment?jsx59(AttachmentArrayDisplay,{values:value,maxWidth:props.maxWidth,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,property,path:props.path}):jsx59(ResourceArrayDisplay,{path:props.path,property,propertyType,values:value,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,ignoreMissingValues:props.ignoreMissingValues,link:props.link});switch(propertyType){case PropertyType.boolean:return jsx59(Fragment26,{children:value===void 0?"":(!!value).toString()});case PropertyType.SystemString:case PropertyType.string:return props.property?.path?.toLowerCase().includes("secret")?jsx59(SecretFieldDisplay,{value}):jsx59("div",{style:{whiteSpace:"pre-wrap"},children:value});case PropertyType.code:case PropertyType.date:case PropertyType.decimal:case PropertyType.id:case PropertyType.integer:case PropertyType.positiveInt:case PropertyType.unsignedInt:case PropertyType.uri:case PropertyType.url:case PropertyType.xhtml:return jsx59(Fragment26,{children:value});case PropertyType.canonical:return jsx59(ReferenceDisplay,{value:{reference:value},link:props.link});case PropertyType.dateTime:case PropertyType.instant:return jsx59(Fragment26,{children:formatDateTime(value)});case PropertyType.time:return jsx59(Fragment26,{children:formatWallTime(value)});case PropertyType.markdown:return jsx59("pre",{children:value});case PropertyType.Address:return jsx59(AddressDisplay,{value});case PropertyType.Annotation:return jsx59(Fragment26,{children:value?.text});case PropertyType.Attachment:return jsx59(AttachmentDisplay,{value,maxWidth:props.maxWidth});case PropertyType.CodeableConcept:return jsx59(CodeableConceptDisplay,{value});case PropertyType.Coding:return jsx59(CodingDisplay,{value});case PropertyType.ContactDetail:return jsx59(ContactDetailDisplay,{value});case PropertyType.ContactPoint:return jsx59(ContactPointDisplay,{value});case PropertyType.HumanName:return jsx59(HumanNameDisplay,{value});case PropertyType.Identifier:return jsx59(IdentifierDisplay,{value});case PropertyType.Money:return jsx59(MoneyDisplay,{value});case PropertyType.Period:return jsx59(Fragment26,{children:formatPeriod(value)});case PropertyType.Quantity:case PropertyType.Duration:return jsx59(QuantityDisplay,{value});case PropertyType.Range:return jsx59(RangeDisplay,{value});case PropertyType.Ratio:return jsx59(RatioDisplay,{value});case PropertyType.Reference:return jsx59(ReferenceDisplay,{value,link:props.link});case PropertyType.Timing:return jsx59(Fragment26,{children:formatTiming(value)});case PropertyType.Dosage:case PropertyType.UsageContext:if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(BackboneElementDisplay,{path:props.path,value:{type:propertyType,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues});case PropertyType.Extension:if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(ExtensionDisplay,{path:props.path,value,compact:!0,ignoreMissingValues:props.ignoreMissingValues,elementDefinitionType:props.elementDefinitionType});default:if(!property)throw new Error(`Displaying property of type ${props.propertyType} requires element schema`);if(!props.path)throw new Error(`Displaying property of type ${props.propertyType} requires path`);return jsx59(BackboneElementDisplay,{path:props.path,value:{type:property.type[0].code,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues})}}function SecretFieldDisplay(props){let[isVisible,setIsVisible]=useState28(!1),secretValue=props.value??"",hasValue=!isEmpty(secretValue),MASK="\u2022".repeat(8);return jsxs32(Flex9,{gap:3,align:"center",children:[isVisible?jsx59("div",{style:{whiteSpace:"pre-wrap"},children:secretValue}):jsx59("div",{style:{whiteSpace:"pre-wrap"},"aria-hidden":"true",children:hasValue?MASK:""}),hasValue&&jsxs32(Fragment26,{children:[jsx59(CopyButton,{value:props.value,timeout:2e3,children:({copied,copy})=>jsx59(Tooltip2,{label:copied?"Copied":"Copy secret",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,"aria-label":copied?"Copied":"Copy secret",children:copied?jsx59(IconCheck,{size:"1rem"}):jsx59(IconCopy,{size:"1rem"})})})}),jsx59(Tooltip2,{label:isVisible?"Hide secret":"Show secret",withArrow:!0,position:"right",children:jsx59(ActionIcon3,{variant:"subtle",color:"gray",onClick:()=>setIsVisible(!isVisible),"aria-label":isVisible?"Hide secret":"Show secret",children:isVisible?jsx59(IconEyeOff,{size:"1rem"}):jsx59(IconEye,{size:"1rem"})})})]})]})}import{jsx as jsx60,jsxs as jsxs33}from"react/jsx-runtime";var EXTENSION_KEYS2=["extension","modifierExtension"],IGNORED_PROPERTIES2=DEFAULT_IGNORED_PROPERTIES.filter(prop=>!EXTENSION_KEYS2.includes(prop));function BackboneElementDisplay(props){let typedValue=props.value,{value,type:typeName}=typedValue,parentElementsContext=useContext6(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=useMemo6(()=>tryGetDataType(typeName,profileUrl),[profileUrl,typeName]),newElementsContext=useMemo6(()=>{if(typeSchema)return buildElementsContext2({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if(isEmpty2(value))return null;if(!typeSchema)return jsxs33("div",{children:[typeName,"\xA0not implemented"]});if(typeof value=="object"&&"name"in value&&Object.keys(value).length===1&&typeof value.name=="string")return jsx60("div",{children:value.name});let elementsContext=newElementsContext??parentElementsContext;return maybeWrapWithContext(ElementsContext.Provider,newElementsContext,jsx60(DescriptionList,{compact:props.compact,children:Object.entries(elementsContext.elements).map(([key,property])=>{if(EXTENSION_KEYS2.includes(key)&&isEmpty2(property.slicing?.slices))return null;if(IGNORED_PROPERTIES2.includes(key))return null;if(DEFAULT_IGNORED_NON_NESTED_PROPERTIES.includes(key)&&property.path.split(".").length===2||key.includes("."))return null;let[propertyValue,propertyType]=getValueAndType(typedValue,key,elementsContext.profileUrl);if((props.ignoreMissingValues||property.max===0)&&isEmpty2(propertyValue)||props.path.endsWith(".extension")&&(key==="url"||key==="id"))return null;let isArrayProperty=property.max>1||property.isArray,resourcePropertyDisplay=jsx60(ResourcePropertyDisplay,{property,propertyType,path:props.path+"."+key,value:propertyValue,ignoreMissingValues:props.ignoreMissingValues,includeArrayDescriptionListEntry:isArrayProperty,link:props.link},key);return isArrayProperty?resourcePropertyDisplay:jsx60(DescriptionListEntry,{term:getPathDisplayName3(key),children:resourcePropertyDisplay},key)})}))}import{Box as Box7}from"@mantine/core";import{buildElementsContext as buildElementsContext4,tryGetDataType as tryGetDataType2}from"@medplum/core";import{useContext as useContext23,useMemo as useMemo22,useState as useState49}from"react";import{Stack as Stack17}from"@mantine/core";import{getPathDisplayName as getPathDisplayName5}from"@medplum/core";import{useContext as useContext22,useMemo as useMemo21,useState as useState48}from"react";import{Group as Group13,Input}from"@mantine/core";import{useContext as useContext7}from"react";var FormSection_default={dimmed:"FormSection_dimmed",preserveBreaks:"FormSection_preserveBreaks"};import{Tooltip as Tooltip3}from"@mantine/core";import{jsx as jsx61}from"react/jsx-runtime";var READ_ONLY_TOOLTIP_TEXT="Read Only";function maybeWrapWithTooltip(tooltipText,children){return tooltipText?jsx61(Tooltip3.Floating,{label:tooltipText,children}):children}import{jsx as jsx62,jsxs as jsxs34}from"react/jsx-runtime";function CheckboxFormSection(props){let{debugMode}=useContext7(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,jsxs34(Group13,{wrap:"nowrap","data-testid":props.testId,children:[jsx62("div",{children:props.children}),jsx62("div",{children:jsx62(Input.Wrapper,{id:props.htmlFor,label,classNames:{label:props?.readonly?FormSection_default.dimmed:void 0},description:props.description,withAsterisk:props.withAsterisk,children:null})})]}))}import{Input as Input2}from"@mantine/core";import{useContext as useContext8}from"react";import{jsx as jsx63}from"react/jsx-runtime";function FormSection(props){let{debugMode}=useContext8(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,jsx63(Input2.Wrapper,{id:props.htmlFor,label,classNames:{label:clsx_default({[FormSection_default.dimmed]:props?.readonly},FormSection_default.preserveBreaks)},description:props.description,withAsterisk:props.withAsterisk,error:getErrorsForInput(props.outcome,props.errorExpression??props.htmlFor),"data-testid":props.testId,children:props.children}))}import{capitalize,isEmpty as isEmpty3}from"@medplum/core";function setPropertyValue(obj,key,propName,elementDefinition,value){let types=elementDefinition.type;if(types.length>1)for(let type of types){let compoundKey=key.replace("[x]",capitalize(type.code));compoundKey in obj&&delete obj[compoundKey]}return isEmpty3(value)?obj[propName]=void 0:obj[propName]=value,obj}function isSupportedProfileStructureDefinition(profile){return!!profile&&!isEmpty3(profile.url)&&!isEmpty3(profile.name)}import{Checkbox as Checkbox4,Group as Group27,NativeSelect as NativeSelect9,Textarea as Textarea2,TextInput as TextInput18}from"@mantine/core";import{applyDefaultValuesToElement,capitalize as capitalize2,getPathDifference,HTTP_HL7_ORG,isComplexTypeCode,isEmpty as isEmpty6,isPopulated as isPopulated10,PropertyType as PropertyType2}from"@medplum/core";import{useContext as useContext21,useMemo as useMemo20,useState as useState47}from"react";import{useState as useState29}from"react";import{jsx as jsx64}from"react/jsx-runtime";function CodeableConceptInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,outcome:_outcome,path:_path,valuePath:_valuePath,...rest}=props,[value,setValue]=useState29(defaultValue2);function handleChange(newValues){let newConcept=valueSetElementToCodeableConcept(newValues);setValue(newConcept),onChange&&onChange(newConcept)}return jsx64(ValueSetAutocomplete,{defaultValue:value&&codeableConceptToValueSetElement(value),onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codeableConceptToValueSetElement(concept){return concept.coding?.map(c=>({system:c.system,code:c.code,display:c.display}))}function valueSetElementToCodeableConcept(elements){if(elements.length!==0)return{coding:elements.map(e=>({system:e.system,code:e.code,display:e.display}))}}import{useState as useState30}from"react";import{jsx as jsx65}from"react/jsx-runtime";function CodingInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,response,...rest}=props,[value,setValue]=useState30(response?.answer?.[0]?.valueCoding??defaultValue2);function handleChange(newValues){let newValue=newValues[0],newConcept=newValue&&valueSetElementToCoding(newValue);setValue(newConcept),onChange&&onChange(newConcept)}return jsx65(ValueSetAutocomplete,{defaultValue:value?codingToValueSetElement(value):void 0,maxValues:1,onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codingToValueSetElement(coding){return{system:coding.system,code:coding.code,display:coding.display}}function valueSetElementToCoding(element){return{system:element.system,code:element.code,display:element.display}}import{Group as Group15,TextInput as TextInput11}from"@mantine/core";import{useContext as useContext10,useMemo as useMemo8,useState as useState32}from"react";import{Group as Group14,NativeSelect as NativeSelect3,TextInput as TextInput10}from"@mantine/core";import{useContext as useContext9,useMemo as useMemo7,useState as useState31}from"react";import{jsx as jsx66,jsxs as jsxs35}from"react/jsx-runtime";function ContactPointInput(props){let{path,outcome}=props,{elementsByPath,getExtendedProps}=useContext9(ElementsContext),[contactPoint,setContactPoint]=useState31(props.defaultValue),[systemElement,useElement,valueElement]=useMemo7(()=>["system","use","value"].map(field=>elementsByPath[path+"."+field]),[elementsByPath,path]),[systemProps,useProps,valueProps]=useMemo7(()=>["system","use","value"].map(field=>getExtendedProps(path+"."+field)),[getExtendedProps,path]);function setContactPointWrapper(newValue){newValue&&Object.keys(newValue).length===0&&(newValue=void 0),setContactPoint(newValue),props.onChange&&props.onChange(newValue)}function setSystem(system){let newValue={...contactPoint,system};system||delete newValue.system,setContactPointWrapper(newValue)}function setUse(use){let newValue={...contactPoint,use};use||delete newValue.use,setContactPointWrapper(newValue)}function setValue(value){let newValue={...contactPoint,value};value||delete newValue.value,setContactPointWrapper(newValue)}let errorPath=props.valuePath??path;return jsxs35(Group14,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx66(NativeSelect3,{disabled:props.disabled||systemProps?.readonly,"data-testid":"system",defaultValue:contactPoint?.system,required:(systemElement?.min??0)>0,onChange:e=>setSystem(e.currentTarget.value),data:["","email","phone","fax","pager","sms","other"],error:getErrorsForInput(outcome,errorPath+".system")}),jsx66(NativeSelect3,{disabled:props.disabled||useProps?.readonly,"data-testid":"use",defaultValue:contactPoint?.use,required:(useElement?.min??0)>0,onChange:e=>setUse(e.currentTarget.value),data:["","home","work","temp","old","mobile"],error:getErrorsForInput(outcome,errorPath+".use")}),jsx66(TextInput10,{disabled:props.disabled||valueProps?.readonly,placeholder:"Value",defaultValue:contactPoint?.value,required:(valueElement?.min??0)>0,onChange:e=>setValue(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".value")})]})}import{jsx as jsx67,jsxs as jsxs36}from"react/jsx-runtime";function ContactDetailInput(props){let[contactDetail,setContactDetail]=useState32(props.defaultValue),{getExtendedProps}=useContext10(ElementsContext),[nameProps,telecomProps]=useMemo8(()=>["name","telecom"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setContactDetailWrapper(newValue){setContactDetail(newValue),props.onChange&&props.onChange(newValue)}function setName(name){let newValue={...contactDetail,name};name||delete newValue.name,setContactDetailWrapper(newValue)}function setTelecom(telecom){let newValue={...contactDetail,telecom:telecom&&[telecom]};telecom||delete newValue.telecom,setContactDetailWrapper(newValue)}return jsxs36(Group15,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx67(TextInput11,{disabled:props.disabled||nameProps?.readonly,"data-testid":props.name+"-name",name:props.name+"-name",placeholder:"Name",style:{width:180},defaultValue:contactDetail?.name,onChange:e=>setName(e.currentTarget.value)}),jsx67(ContactPointInput,{disabled:props.disabled||telecomProps?.readonly,name:props.name+"-telecom",path:props.path+".telecom",defaultValue:contactDetail?.telecom?.[0],onChange:setTelecom,outcome:props.outcome})]})}import{TextInput as TextInput12}from"@mantine/core";import{isValidDate}from"@medplum/core";function convertIsoToLocal(isoString){if(!isoString)return"";let date=new Date(isoString);return isValidDate(date)?date.toLocaleDateString("sv")+"T"+date.toLocaleTimeString("sv"):""}function convertLocalToIso(localString){if(!localString)return"";let date=new Date(localString);return isValidDate(date)?date.toISOString():""}import{jsx as jsx68}from"react/jsx-runtime";function DateTimeInput(props){return jsx68(TextInput12,{id:props.name,name:props.name,label:props.label,"data-autofocus":props.autoFocus,"data-testid":props["data-testid"]??props.name,placeholder:props.placeholder,required:props.required,disabled:props.disabled,type:getInputType(),step:1,defaultValue:convertIsoToLocal(props.defaultValue),autoFocus:props.autoFocus,error:getErrorsForInput(props.outcome,props.name),onChange:e=>{if(props.onChange){let newValue=e.currentTarget.value;props.onChange(convertLocalToIso(newValue))}}})}function getInputType(){return"datetime-local"}import{isPopulated as isPopulated7,isProfileLoaded as isProfileLoaded2}from"@medplum/core";import{useMedplum as useMedplum19}from"@medplum/react-hooks";import{useEffect as useEffect10,useMemo as useMemo9,useState as useState33}from"react";import{jsx as jsx69}from"react/jsx-runtime";function ExtensionInput(props){let{propertyType}=props,medplum=useMedplum19(),profileUrl=useMemo9(()=>{if(isPopulated7(propertyType.profile))return propertyType.profile[0]},[propertyType]),[loadingProfile,setLoadingProfile]=useState33(profileUrl!==void 0);return useEffect10(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>setLoadingProfile(!1)).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!isProfileLoaded2(profileUrl))?jsx69("div",{children:"Loading..."}):jsx69(BackboneElementInput,{profileUrl,path:props.path,typeName:"Extension",defaultValue:props.defaultValue,onChange:props.onChange})}import{Group as Group16,NativeSelect as NativeSelect4,TextInput as TextInput13}from"@mantine/core";import{useContext as useContext11,useMemo as useMemo10,useState as useState34}from"react";import{jsx as jsx70,jsxs as jsxs37}from"react/jsx-runtime";function HumanNameInput(props){let{outcome,path}=props,[value,setValue]=useState34(props.defaultValue),{getExtendedProps}=useContext11(ElementsContext),[useProps,prefixProps,givenProps,familyProps,suffixProps]=useMemo10(()=>["use","prefix","given","family","suffix"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}function setUse(use){setValueWrapper({...value,use:use||void 0})}function setPrefix(prefix){setValueWrapper({...value,prefix:prefix?prefix.split(" "):void 0})}function setGiven(given){setValueWrapper({...value,given:given?given.split(" "):void 0})}function setFamily(family){setValueWrapper({...value,family:family||void 0})}function setSuffix(suffix){setValueWrapper({...value,suffix:suffix?suffix.split(" "):void 0})}let errorPath=props.valuePath??path;return jsxs37(Group16,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx70(NativeSelect4,{disabled:props.disabled||useProps?.readonly,defaultValue:value?.use,name:props.name+"-use","data-testid":"use",onChange:e=>setUse(e.currentTarget.value),data:["","temp","old","usual","official","nickname","anonymous","maiden"],error:getErrorsForInput(outcome,errorPath+".use")}),jsx70(TextInput13,{disabled:props.disabled||prefixProps?.readonly,placeholder:"Prefix",name:props.name+"-prefix",defaultValue:value?.prefix?.join(" "),onChange:e=>setPrefix(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".prefix")}),jsx70(TextInput13,{disabled:props.disabled||givenProps?.readonly,placeholder:"Given",name:props.name+"-given",defaultValue:value?.given?.join(" "),onChange:e=>setGiven(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".given")}),jsx70(TextInput13,{disabled:props.disabled||familyProps?.readonly,name:props.name+"-family",placeholder:"Family",defaultValue:value?.family,onChange:e=>setFamily(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".family")}),jsx70(TextInput13,{disabled:props.disabled||suffixProps?.readonly,placeholder:"Suffix",name:props.name+"-suffix",defaultValue:value?.suffix?.join(" "),onChange:e=>setSuffix(e.currentTarget.value),error:getErrorsForInput(outcome,errorPath+".suffix")})]})}import{Group as Group17,TextInput as TextInput14}from"@mantine/core";import{useContext as useContext12,useMemo as useMemo11,useState as useState35}from"react";import{jsx as jsx71,jsxs as jsxs38}from"react/jsx-runtime";function IdentifierInput(props){let[value,setValue]=useState35(props.defaultValue),{elementsByPath,getExtendedProps}=useContext12(ElementsContext),[systemElement,valueElement]=useMemo11(()=>["system","value"].map(field=>elementsByPath[props.path+"."+field]),[elementsByPath,props.path]),[systemProps,valueProps]=useMemo11(()=>["system","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}let errorPath=props.valuePath??props.path;return jsxs38(Group17,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx71(TextInput14,{disabled:props.disabled||systemProps?.readonly,placeholder:"System",required:(systemElement?.min??0)>0,defaultValue:value?.system,onChange:e=>setValueWrapper({...value,system:e.currentTarget.value}),error:getErrorsForInput(props.outcome,errorPath+".system")}),jsx71(TextInput14,{disabled:props.disabled||valueProps?.readonly,placeholder:"Value",required:(valueElement?.min??0)>0,defaultValue:value?.value,onChange:e=>setValueWrapper({...value,value:e.currentTarget.value}),error:getErrorsForInput(props.outcome,errorPath+".value")})]})}import{NativeSelect as NativeSelect5,TextInput as TextInput15}from"@mantine/core";import{useCallback as useCallback7,useContext as useContext13,useMemo as useMemo12,useState as useState36}from"react";import{jsx as jsx72}from"react/jsx-runtime";var data=["USD","EUR","CAD","GBP","AUD"];function MoneyInput(props){let{onChange}=props,[value,setValue]=useState36(props.defaultValue),{getExtendedProps}=useContext13(ElementsContext),[currencyProps,valueProps]=useMemo12(()=>["currency","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]),setValueWrapper=useCallback7(newValue=>{setValue(newValue),onChange&&onChange(newValue)},[onChange]),handleCurrencyChange=useCallback7(e=>{setValueWrapper({...value,currency:e.currentTarget.value})},[value,setValueWrapper]),handleValueChange=useCallback7(e=>{setValueWrapper({...value,value:e.currentTarget.valueAsNumber})},[value,setValueWrapper]),select=jsx72(NativeSelect5,{disabled:props.disabled||currencyProps?.readonly,defaultValue:value?.currency,data,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:handleCurrencyChange});return jsx72(TextInput15,{disabled:props.disabled||valueProps?.readonly,type:"number",name:props.name,label:props.label,placeholder:props.placeholder??"Value",defaultValue:value?.value?.toString()??"USD",leftSection:jsx72(IconCurrencyDollar,{size:14}),rightSection:select,rightSectionWidth:92,onChange:handleValueChange})}import{Group as Group18}from"@mantine/core";import{useContext as useContext14,useMemo as useMemo13,useState as useState37}from"react";import{jsx as jsx73,jsxs as jsxs39}from"react/jsx-runtime";function PeriodInput(props){let[value,setValue]=useState37(props.defaultValue),{getExtendedProps}=useContext14(ElementsContext),[startProps,endProps]=useMemo13(()=>["start","end"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs39(Group18,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx73(DateTimeInput,{disabled:props.disabled||startProps?.readonly,name:props.name+".start",placeholder:"Start",defaultValue:value?.start,onChange:newValue=>setValueWrapper({...value,start:newValue})}),jsx73(DateTimeInput,{disabled:props.disabled||endProps?.readonly,name:props.name+".end",placeholder:"End",defaultValue:value?.end,onChange:newValue=>setValueWrapper({...value,end:newValue})})]})}import{Group as Group19,NativeSelect as NativeSelect6,TextInput as TextInput16}from"@mantine/core";import{useContext as useContext15,useMemo as useMemo14,useState as useState38}from"react";import{jsx as jsx74,jsxs as jsxs40}from"react/jsx-runtime";function QuantityInput(props){let[value,setValue]=useState38(props.defaultValue),{getExtendedProps}=useContext15(ElementsContext),[comparatorProps,valueProps,unitProps]=useMemo14(()=>["comparator","value","unit"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs40(Group19,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx74(NativeSelect6,{disabled:props.disabled||comparatorProps?.readonly,style:{width:80},"data-testid":props.name+"-comparator",defaultValue:value?.comparator,data:["","<","<=",">=",">"],onChange:e=>setValueWrapper({...value,comparator:e.currentTarget.value})}),jsx74(TextInput16,{disabled:props.disabled||valueProps?.readonly,id:props.name,name:props.name,required:props.required,"data-autofocus":props.autoFocus,"data-testid":props.name+"-value",type:"number",placeholder:"Value",defaultValue:value?.value,autoFocus:props.autoFocus,step:"any",onWheel:e=>{props.disableWheel&&e.currentTarget.blur()},onChange:e=>{setValueWrapper({...value,value:tryParseNumber(e.currentTarget.value)})}}),jsx74(TextInput16,{disabled:props.disabled||unitProps?.readonly,placeholder:"Unit","data-testid":props.name+"-unit",defaultValue:value?.unit,onChange:e=>setValueWrapper({...value,unit:e.currentTarget.value})})]})}function tryParseNumber(str){if(str)return Number.parseFloat(str)}import{Group as Group20}from"@mantine/core";import{useContext as useContext16,useMemo as useMemo15,useState as useState39}from"react";import{jsx as jsx75,jsxs as jsxs41}from"react/jsx-runtime";function RangeInput(props){let[value,setValue]=useState39(props.defaultValue),{getExtendedProps}=useContext16(ElementsContext),[lowProps,highProps]=useMemo15(()=>["low","high"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs41(Group20,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx75(QuantityInput,{path:props.path+".low",disabled:props.disabled||lowProps?.readonly,name:props.name+"-low",defaultValue:value?.low,onChange:v=>setValueWrapper({...value,low:v})}),jsx75(QuantityInput,{path:props.path+".high",disabled:props.disabled||highProps?.readonly,name:props.name+"-high",defaultValue:value?.high,onChange:v=>setValueWrapper({...value,high:v})})]})}import{Group as Group21}from"@mantine/core";import{useContext as useContext17,useMemo as useMemo16,useState as useState40}from"react";import{jsx as jsx76,jsxs as jsxs42}from"react/jsx-runtime";function RatioInput(props){let[value,setValue]=useState40(props.defaultValue),{getExtendedProps}=useContext17(ElementsContext),[numeratorProps,denominatorProps]=useMemo16(()=>["numerator","denominator"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return jsxs42(Group21,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx76(QuantityInput,{path:props.path+".numerator",disabled:props.disabled||numeratorProps?.readonly,name:props.name+"-numerator",defaultValue:value?.numerator,onChange:v=>setValueWrapper({...value,numerator:v})}),jsx76(QuantityInput,{path:props.path+".denominator",disabled:props.disabled||denominatorProps?.readonly,name:props.name+"-denominator",defaultValue:value?.denominator,onChange:v=>setValueWrapper({...value,denominator:v})})]})}import{Group as Group23,NativeSelect as NativeSelect7}from"@mantine/core";import{LRUCache,ReadablePromise,createReference as createReference2,isEmpty as isEmpty4,isPopulated as isPopulated8,tryGetProfile as tryGetProfile3}from"@medplum/core";import{useMedplum as useMedplum21}from"@medplum/react-hooks";import{useCallback as useCallback10,useEffect as useEffect12,useMemo as useMemo17,useRef as useRef7,useState as useState42}from"react";import{useCallback as useCallback9}from"react";import{Group as Group22,Text as Text14}from"@mantine/core";import{getDisplayString as getDisplayString3,getReferenceString as getReferenceString3,isReference as isReference2,isResource as isResource2}from"@medplum/core";import{useMedplum as useMedplum20}from"@medplum/react-hooks";import{forwardRef as forwardRef4,useCallback as useCallback8,useEffect as useEffect11,useRef as useRef6,useState as useState41}from"react";import{jsx as jsx77,jsxs as jsxs43}from"react/jsx-runtime";var SEARCH_CODES={Device:"device-name",Observation:"code",Subscription:"criteria",User:"email:contains"},NAME_RESOURCE_TYPES=["AccessPolicy","Account","ActivityDefinition","Bot","CapabilityStatement","CareTeam","ClientApplication","CodeSystem","CompartmentDefinition","ConceptMap","EffectEvidenceSynthesis","Endpoint","EventDefinition","Evidence","EvidenceVariable","ExampleScenario","GraphDefinition","Group","HealthcareService","ImplementationGuide","InsurancePlan","Library","Location","Measure","MedicinalProduct","MessageDefinition","NamingSystem","OperationDefinition","Organization","Patient","Person","PlanDefinition","Practitioner","Project","Questionnaire","RelatedPerson","ResearchDefinition","ResearchElementDefinition","ResearchStudy","RiskEvidenceSynthesis","SearchParameter","StructureDefinition","StructureMap","TerminologyCapabilities","TestScript","UserConfiguration","ValueSet"];function toOption3(resource){return{value:getReferenceString3(resource)??"",label:getDisplayString3(resource),resource}}function getSearchParamForResourceType(resourceType){return SEARCH_CODES[resourceType]??(NAME_RESOURCE_TYPES.includes(resourceType)?"name":"_id")}var DefaultResourceItemComponent=forwardRef4(({label,resource,active:_active,...others},ref)=>jsx77("div",{ref,...others,children:jsxs43(Group22,{wrap:"nowrap",children:[jsx77(ResourceAvatar,{value:resource}),jsxs43("div",{children:[jsx77(Text14,{children:label}),jsx77(Text14,{size:"xs",c:"dimmed",children:resource.birthDate||resource.id})]})]})}));DefaultResourceItemComponent.displayName="DefaultResourceItemComponent";function MultiResourceInput(props){let medplum=useMedplum20(),{resourceType,searchCriteria}=props,ItemComponent3=props.itemComponent??DefaultResourceItemComponent,onChange=props.onChange,initialDefaultValue=useRef6(props.defaultValue),[defaultResources,setDefaultResources]=useState41(!props.defaultValue||props.defaultValue.length===0?[]:void 0);useEffect11(()=>{let cancelled=!1,items=initialDefaultValue.current;return items&&items.length>0&&Promise.allSettled(items.map(item=>isResource2(item)?Promise.resolve(item):isReference2(item)?medplum.readReference(item):Promise.reject(new Error("Not a resolvable item")))).then(settled=>{cancelled||setDefaultResources(settled.filter(r2=>r2.status==="fulfilled").map(r2=>r2.value))}).catch(()=>{}),()=>{cancelled=!0}},[medplum]);let loadValues=useCallback8(async(input,signal)=>{let searchCode=getSearchParamForResourceType(resourceType),searchParams=new URLSearchParams({[searchCode]:input??"",_count:"10",...searchCriteria});return await medplum.searchResources(resourceType,searchParams,{signal})},[medplum,resourceType,searchCriteria]),handleChange=useCallback8(newResources=>{onChange&&onChange(newResources)},[onChange]);return defaultResources===void 0?null:jsx77(AsyncAutocomplete,{disabled:props.disabled,name:props.name,label:props.label,error:props.error,required:props.required,itemComponent:ItemComponent3,defaultValue:defaultResources,placeholder:props.placeholder,maxValues:props.maxValues,toOption:toOption3,loadOptions:loadValues,onChange:handleChange,clearable:!0})}import{jsx as jsx78}from"react/jsx-runtime";function ResourceInput(props){let onChange=props.onChange,handleChange=useCallback9(newResources=>{onChange&&onChange(newResources[0])},[onChange]);return jsx78(MultiResourceInput,{resourceType:props.resourceType,name:props.name,defaultValue:props.defaultValue?[props.defaultValue]:void 0,searchCriteria:props.searchCriteria,placeholder:props.placeholder,required:props.required,itemComponent:props.itemComponent,onChange:handleChange,disabled:props.disabled,label:props.label,error:props.error,maxValues:1})}import{Fragment as Fragment27,jsx as jsx79,jsxs as jsxs44}from"react/jsx-runtime";function ReferenceInput(props){let{onChange}=props,medplum=useMedplum21(),[value,setValue]=useState42(props.defaultValue),[targetTypes,setTargetTypes]=useState42(()=>createTargetTypes(props.targetTypes)),[targetType,setTargetType]=useState42(()=>getInitialTargetType(props.defaultValue,targetTypes)),promiseCache=useRef7(new LRUCache),searchCriteria=useMemo17(()=>targetType?.type==="profile"?{...props.searchCriteria,_profile:targetType.value}:props.searchCriteria,[props.searchCriteria,targetType]);useEffect12(()=>{let anyToFetch=!1,newTargetTypePromises=targetTypes?.map(tt=>{if(!shouldFetchResourceType(tt))return Promise.resolve(tt);anyToFetch=!0;let cacheKey=tt.value,cached=promiseCache.current.get(cacheKey);if(cached)return cached;let promise=fetchResourceTypeOfProfile(medplum,tt.value).then(profile=>{let newTargetType={...tt};return profile?isPopulated8(profile.type)?(newTargetType.resourceType=profile.type,newTargetType.name=profile.name,newTargetType.title=profile.title):(console.error(`StructureDefinition.type missing for ${tt.value}`),newTargetType.error="StructureDefinition.type missing"):(console.error(`StructureDefinition not found for ${tt.value}`),newTargetType.error="StructureDefinition not found"),newTargetType}).catch(reason=>(console.error(reason),{...tt,error:reason})),readablePromise=new ReadablePromise(promise);return promiseCache.current.set(cacheKey,readablePromise),readablePromise});!newTargetTypePromises||!anyToFetch||Promise.all(newTargetTypePromises).then(newTargetTypes=>{if(setTargetTypes(newTargetTypes),!targetType)return;let index=newTargetTypes.findIndex(tt=>tt.value===targetType.value||tt.resourceType===targetType.resourceType);if(index===-1){console.debug(`defaultValue had unexpected resourceType: ${targetType.resourceType}`);return}setTargetType(newTargetTypes[index])}).catch(console.error)},[medplum,targetType,targetTypes]);let setValueHelper=useCallback10(item=>{let newValue=item?createReference2(item):void 0;setValue(newValue),onChange&&onChange(newValue)},[onChange]),typeSelectOptions=useMemo17(()=>targetTypes?targetTypes.map(tt=>({value:tt.value,label:tt.type==="profile"?tt.title??tt.name??tt.resourceType??tt.value:tt.value})):[],[targetTypes]);return jsxs44(Fragment27,{children:[props.name&&jsx79("input",{type:"hidden",name:props.name,value:value?.reference??""}),jsxs44(Group23,{gap:"xs",grow:!0,wrap:"nowrap",children:[targetTypes&&targetTypes.length>1&&jsx79(NativeSelect7,{name:props.name+"-resourceType",disabled:props.disabled,"data-autofocus":props.autoFocus,"data-testid":"reference-input-resource-type-select",defaultValue:targetType?.resourceType,autoFocus:props.autoFocus,onChange:e=>{let newValue=e.currentTarget.value,newTargetType=targetTypes.find(tt=>tt.value===newValue);setTargetType(newTargetType)},data:typeSelectOptions}),!targetTypes&&jsx79(ResourceTypeInput,{disabled:props.disabled,autoFocus:props.autoFocus,testId:"reference-input-resource-type-input",defaultValue:targetType?.resourceType,onChange:newResourceType=>{setTargetType(newResourceType?{type:"resourceType",value:newResourceType,resourceType:newResourceType}:void 0)},name:props.name+"-resourceType",placeholder:"Resource Type"}),jsx79(ResourceInput,{resourceType:targetType?.resourceType,name:props.name+"-id",required:props.required,placeholder:props.placeholder,defaultValue:value,searchCriteria,onChange:setValueHelper,disabled:props.disabled})]})]})}function createTargetTypes(resourceTypesAndProfileUrls){if(!resourceTypesAndProfileUrls||resourceTypesAndProfileUrls.length===0||resourceTypesAndProfileUrls.length===1&&resourceTypesAndProfileUrls[0]==="Resource")return;let results=[];for(let value of resourceTypesAndProfileUrls)value.includes("/")?results.push({type:"profile",value}):results.push({type:"resourceType",value,resourceType:value});return results}function getInitialTargetType(defaultValue2,targetTypes){let defaultValueResourceType=defaultValue2?.reference?.split("/")[0];if(defaultValueResourceType){let targetType=targetTypes?.find(tt=>tt.resourceType===defaultValueResourceType);return targetType||{type:"resourceType",value:defaultValueResourceType,resourceType:defaultValueResourceType}}if(targetTypes&&targetTypes.length>0)return targetTypes[0]}async function fetchResourceTypeOfProfile(medplum,profileUrl){let profile=tryGetProfile3(profileUrl);if(profile)return{type:profile.type,name:profile.name,title:profile.title};let query=`{
|
|
104
104
|
StructureDefinitionList(url: "${profileUrl}", _sort: "_lastUpdated", _count: 1) {
|
|
105
105
|
type,
|
|
106
106
|
name,
|
|
107
107
|
title,
|
|
108
108
|
}
|
|
109
|
-
}`.replaceAll(/\s+/g," ");return(await medplum.graphql(query)).data.StructureDefinitionList[0]}function shouldFetchResourceType(targetType){return targetType.type==="profile"&&!targetType?.error&&isEmpty4(targetType.resourceType)}import{Group as Group25,Stack as Stack15,Text as Text16}from"@mantine/core";import{getPathDisplayName as getPathDisplayName4}from"@medplum/core";import{useMedplum as useMedplum22}from"@medplum/react-hooks";import{useContext as useContext19,useEffect as useEffect13,useState as useState44}from"react";function getValuePath(elementPath,valuePath,arrayIndex){return valuePath===void 0?elementPath:arrayIndex===void 0?valuePath:`${valuePath}[${arrayIndex}]`}import{Group as Group24,Stack as Stack14,Text as Text15}from"@mantine/core";import{buildElementsContext as buildElementsContext3,getPropertyDisplayName,isEmpty as isEmpty5,isPopulated as isPopulated9}from"@medplum/core";import{useContext as useContext18,useMemo as useMemo18,useState as useState43}from"react";var ResourceArrayInput_default={indented:"ResourceArrayInput_indented"};import{ActionIcon as ActionIcon4,Button as Button6}from"@mantine/core";import{jsx as jsx80}from"react/jsx-runtime";function ArrayAddButton({propertyDisplayName,onClick,testId}){let text=propertyDisplayName?`Add ${propertyDisplayName}`:"Add";return propertyDisplayName?jsx80(Button6,{title:text,size:"sm",color:"green.6",variant:"subtle","data-testid":testId,leftSection:jsx80(IconCirclePlus,{size:"1.25rem"}),onClick,children:text}):jsx80(ActionIcon4,{title:text,color:"green.6","data-testid":testId,onClick,children:jsx80(IconCirclePlus,{size:"1.25rem"})})}import{ActionIcon as ActionIcon5}from"@mantine/core";import{jsx as jsx81}from"react/jsx-runtime";function ArrayRemoveButton({propertyDisplayName,onClick,testId}){return jsx81(ActionIcon5,{title:propertyDisplayName?`Remove ${propertyDisplayName}`:"Remove",color:"red.5","data-testid":testId,variant:"subtle",onClick,children:jsx81(IconCircleMinus,{size:"1.25rem"})})}import{jsx as jsx82,jsxs as jsxs45}from"react/jsx-runtime";function SliceInput(props){let{slice,property}=props,[values,setValues]=useState43(props.defaultValue),sliceElements=slice.typeSchema?.elements??slice.elements,parentElementsContextValue=useContext18(ElementsContext),contextValue=useMemo18(()=>{if(isPopulated9(sliceElements))return buildElementsContext3({parentContext:parentElementsContextValue,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentElementsContextValue,props.path,slice.typeSchema?.url,sliceElements]);function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}let required=slice.min>0,indentedStack=isEmpty5(slice.elements),propertyDisplayName=getPropertyDisplayName(slice.name),showEmptyMessage=props.property.readonly&&values.length===0;return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx82(FormSection,{title:propertyDisplayName,description:slice.definition,withAsterisk:required,fhirPath:`${property.path}:${slice.name}`,testId:props.testId,readonly:props.property.readonly,children:showEmptyMessage?jsx82(Text15,{c:"dimmed",children:"(empty)"}):jsxs45(Stack14,{className:indentedStack?ResourceArrayInput_default.indented:void 0,children:[values.map((value,valueIndex)=>jsxs45(Group24,{wrap:"nowrap",children:[jsx82("div",{style:{flexGrow:1},"data-testid":props.testId&&`${props.testId}-elements-${valueIndex}`,children:jsx82(ElementDefinitionTypeInput,{elementDefinitionType:slice.type[0],name:slice.name,defaultValue:value,onChange:newValue=>{let newValues=[...values];newValues[valueIndex]=newValue,setValuesWrapper(newValues)},outcome:props.outcome,min:slice.min,max:slice.max,binding:slice.binding,path:props.path,valuePath:void 0,readOnly:props.property.readonly})}),!props.property.readonly&&values.length>slice.min&&jsx82(ArrayRemoveButton,{propertyDisplayName,testId:props.testId&&`${props.testId}-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newValues=[...values];newValues.splice(valueIndex,1),setValuesWrapper(newValues)}})]},`${valueIndex}-${values.length}`)),!props.property.readonly&&values.length<slice.max&&jsx82(Group24,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx82(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newValues=[...values,void 0];setValuesWrapper(newValues)},testId:props.testId&&`${props.testId}-add`})})]})}))}import{jsx as jsx83,jsxs as jsxs46}from"react/jsx-runtime";function ResourceArrayInput(props){let{property}=props,medplum=useMedplum22(),[loading,setLoading]=useState44(!0),[slices,setSlices]=useState44([]),[defaultValue2]=useState44(()=>Array.isArray(props.defaultValue)?props.defaultValue:[]),[slicedValues,setSlicedValues]=useState44(()=>[defaultValue2]),ctx=useContext19(ElementsContext),propertyTypeCode=property.type[0]?.code;useEffect13(()=>{prepareSlices({medplum,property}).then(slices2=>{setSlices(slices2);let slicedValues2=assignValuesIntoSlices(defaultValue2,slices2,property.slicing,ctx.profileUrl);addPlaceholderValues(slicedValues2,slices2),setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,defaultValue2,ctx.profileUrl,setSlicedValues]);function setValuesWrapper(newValues,sliceIndex){let newSlicedValues=[...slicedValues];if(newSlicedValues[sliceIndex]=newValues,setSlicedValues(newSlicedValues),props.onChange){let cleaned=newSlicedValues.flat().filter(val=>val!==void 0);props.onChange(cleaned)}}if(loading)return jsx83("div",{children:"Loading..."});let nonSliceIndex=slices.length,nonSliceValues=slicedValues[nonSliceIndex],showNonSliceValues=!(props.hideNonSliceValues??(propertyTypeCode==="Extension"&&slices.length>0)),propertyDisplayName=getPathDisplayName4(property.path),showEmptyMessage=props.property.readonly&&slices.length===0&&defaultValue2.length===0;return jsxs46(Stack15,{className:props.indent?ResourceArrayInput_default.indented:void 0,children:[showEmptyMessage&&jsx83(Text16,{c:"dimmed",children:"(empty)"}),slices.map((slice,sliceIndex)=>jsx83(SliceInput,{slice,path:props.path,valuePath:props.valuePath,property,defaultValue:slicedValues[sliceIndex],onChange:newValue=>{setValuesWrapper(newValue,sliceIndex)},testId:`slice-${slice.name}`},slice.name)),showNonSliceValues&&nonSliceValues.map((value,valueIndex)=>jsxs46(Group25,{wrap:"nowrap",style:{flexGrow:1},children:[jsx83("div",{style:{flexGrow:1},children:jsx83(ResourcePropertyInput,{arrayElement:!0,property:props.property,name:props.name+"."+valueIndex,path:props.path,valuePath:getValuePath(props.path,props.valuePath,valueIndex),defaultValue:value,onChange:newValue=>{let newNonSliceValues=[...nonSliceValues];newNonSliceValues[valueIndex]=newValue,setValuesWrapper(newNonSliceValues,nonSliceIndex)},defaultPropertyType:void 0,outcome:props.outcome})}),!props.property.readonly&&jsx83(ArrayRemoveButton,{propertyDisplayName,testId:`nonsliced-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.splice(valueIndex,1),setValuesWrapper(newNonSliceValues,nonSliceIndex)}})]},`${valueIndex}-${nonSliceValues.length}`)),!props.property.readonly&&showNonSliceValues&&slicedValues.flat().length<property.max&&jsx83(Group25,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx83(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.push(void 0),setValuesWrapper(newNonSliceValues,nonSliceIndex)},testId:"nonsliced-add"})})]})}function addPlaceholderValues(slicedValues,slices){for(let sliceIndex=0;sliceIndex<slices.length;sliceIndex++){let slice=slices[sliceIndex],sliceValues=slicedValues[sliceIndex];for(;sliceValues.length<slice.min;)sliceValues.push(void 0)}}import{ActionIcon as ActionIcon6,Flex as Flex10,Textarea}from"@mantine/core";import{useClipboard}from"@mantine/hooks";import{showNotification as showNotification4}from"@mantine/notifications";import{useRef as useRef8,useState as useState45}from"react";import{jsx as jsx84,jsxs as jsxs47}from"react/jsx-runtime";function SensitiveTextarea(props){let[revealed,setRevealed]=useState45(!1),clipboard=useClipboard(),ref=useRef8(null),styles={...props.styles};return revealed||(styles.input||(styles.input={}),styles.input.WebkitTextSecurity="disc"),jsxs47(Flex10,{gap:"xs",children:[jsx84(Textarea,{...props,styles:{...styles,root:{...styles.root??{},flexGrow:1}},ref,autosize:!0,minRows:1,onFocus:()=>setRevealed(!0),onBlur:()=>setRevealed(!1)}),jsx84(ActionIcon6,{title:"Copy secret",onClick:()=>{clipboard.copy(ref.current?.value),showNotification4({color:"green",message:"Copied"})},children:jsx84(IconCopy,{})})]})}import{Box as Box6,Button as Button7,Chip,Group as Group26,Modal as Modal2,NativeSelect as NativeSelect8,Stack as Stack16,Switch,TextInput as TextInput17}from"@mantine/core";import{formatTiming as formatTiming2}from"@medplum/core";import{useContext as useContext20,useMemo as useMemo19,useRef as useRef9,useState as useState46}from"react";import{Fragment as Fragment28,jsx as jsx85,jsxs as jsxs48}from"react/jsx-runtime";var daysOfWeek=["sun","mon","tue","wed","thu","fri","sat"];function TimingInput(props){let[value,setValue]=useState46(props.defaultValue),[open,setOpen]=useState46(!props.disabled&&(props.defaultModalOpen??!1));return jsxs48(Fragment28,{children:[jsxs48(Group26,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx85("span",{"data-testid":"timinginput-display",children:formatTiming2(value)||"No repeat"}),jsx85(Button7,{disabled:props.disabled,onClick:()=>setOpen(!0),children:"Edit"})]}),!props.disabled&&jsx85(TimingEditorDialog,{path:props.path,visible:open,defaultValue:value,onOk:newValue=>{props.onChange&&props.onChange(newValue),setValue(newValue),setOpen(!1)},onCancel:()=>setOpen(!1)})]})}var defaultValue={repeat:{period:1,periodUnit:"d"}};function TimingEditorDialog(props){let[value,setValue]=useState46(props.defaultValue||defaultValue),[timeOfDayItems,setTimeOfDayItems]=useState46(()=>(props.defaultValue?.repeat?.timeOfDay??[]).map((v,i)=>({id:i,value:v}))),nextTimeOfDayId=useRef9(timeOfDayItems.length),{getExtendedProps}=useContext20(ElementsContext),[eventProps,repeatProps,repeatPeriodProps,repeatPeriodUnitProps,repeatDayOfWeekProps,repeatTimeOfDayProps]=useMemo19(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek","repeat.timeOfDay"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setStart(newStart){setValue(value2=>({...value2,event:[newStart]}))}function setRepeat(repeat){setValue(value2=>({...value2,repeat}))}function setPeriod(period){setValue(value2=>({...value2,repeat:{...value2.repeat,period}}))}function setPeriodUnit(periodUnit){setValue(value2=>({...value2,repeat:{...value2.repeat,periodUnit}}))}function setDaysOfWeek(dayOfWeek){setValue(value2=>({...value2,repeat:{...value2.repeat,dayOfWeek}}))}function setTimeOfDay(updater){setTimeOfDayItems(items=>{let newItems=updater(items),timeOfDay=newItems.map(item=>item.value);return setValue(value2=>({...value2,repeat:{...value2.repeat,timeOfDay}})),newItems})}return jsx85(Modal2,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>props.onCancel(),children:jsxs48(Stack16,{gap:"md",children:[jsx85(FormSection,{title:"Starts on",htmlFor:"timing-dialog-start",children:jsx85(DateTimeInput,{disabled:eventProps?.readonly,name:"timing-dialog-start",onChange:newValue=>setStart(newValue)})}),jsx85(Switch,{disabled:repeatProps?.readonly,label:"Repeat",checked:!!value.repeat,onChange:e=>setRepeat(e.currentTarget.checked?defaultValue.repeat:void 0)}),value.repeat&&jsxs48(Fragment28,{children:[jsx85(FormSection,{title:"Repeat every",htmlFor:"timing-dialog-period",children:jsxs48(Group26,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx85(TextInput17,{disabled:repeatPeriodProps?.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:value.repeat.period||1,onChange:e=>setPeriod(Number.parseInt(e.currentTarget.value,10)||1)}),jsx85(NativeSelect8,{disabled:repeatPeriodUnitProps?.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:value.repeat.periodUnit,onChange:e=>setPeriodUnit(e.currentTarget.value),data:[{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),value.repeat.periodUnit==="wk"&&jsx85(FormSection,{title:"Repeat on",children:jsx85(Chip.Group,{multiple:!0,onChange:setDaysOfWeek,value:value.repeat?.dayOfWeek,children:jsx85(Group26,{justify:"space-between",mt:"xs",gap:"xs",children:daysOfWeek.map(day=>jsx85(Chip,{value:day,size:"xs",radius:"xl",disabled:repeatDayOfWeekProps?.readonly,checked:(value.repeat?.dayOfWeek??[]).includes(day),children:day.charAt(0).toUpperCase()},day))})})}),jsx85(FormSection,{title:"At times",children:jsxs48(Stack16,{mt:"xs",children:[timeOfDayItems.map((item,idx)=>jsxs48(Group26,{children:[jsx85(TextInput17,{disabled:repeatTimeOfDayProps?.readonly,type:"time",id:`timing-dialog-repeat-timeOfDay[${idx}]`,name:`timing-dialog-repeat-timeOfDay[${idx}]`,"data-testid":`timing-repeat-timeOfDay-input-${idx}`,defaultValue:item.value.slice(0,5),onChange:e=>{let newValue=`${e.currentTarget.value}:00`;setTimeOfDay(items=>items.with(idx,{...item,value:newValue}))},style:{flexGrow:1}}),jsx85(ArrayRemoveButton,{testId:`timing-repeat-timeOfDay-remove-${idx}`,onClick:()=>setTimeOfDay(items=>items.toSpliced(idx,1))})]},item.id)),jsx85(Box6,{children:jsx85(ArrayAddButton,{propertyDisplayName:"Time of Day",onClick:()=>setTimeOfDay(items=>{let id=nextTimeOfDayId.current++;return items.concat({id,value:"00:00:00"})})})})]})})]}),jsx85(Group26,{justify:"flex-end",children:jsx85(Button7,{onClick:()=>props.onOk(value),children:"OK"})})]})})}import{jsx as jsx86,jsxs as jsxs49}from"react/jsx-runtime";function ResourcePropertyInput(props){let{property,name,onChange,defaultValue:defaultValue2}=props,defaultPropertyType=props.defaultPropertyType&&props.defaultPropertyType!=="undefined"?props.defaultPropertyType:property.type[0].code,propertyTypes=property.type;if((property.isArray||property.max>1)&&!props.arrayElement){if(defaultPropertyType===PropertyType2.Attachment)return jsx86(AttachmentArrayInput,{name,defaultValue:defaultValue2,onChange,disabled:property.readonly});let indent=propertyTypes[0]?.code!==PropertyType2.Extension;return jsx86(ResourceArrayInput,{property,name,path:props.path,valuePath:props.valuePath,defaultValue:defaultValue2,indent,onChange,outcome:props.outcome})}else return propertyTypes.length>1?jsx86(ElementDefinitionInputSelector,{elementDefinitionTypes:propertyTypes,...props}):jsx86(ElementDefinitionTypeInput,{name,defaultValue:defaultValue2,onChange:newValue=>{if(props.onChange){let newPropName=props.name.replace("[x]",capitalize2(propertyTypes[0].code));props.onChange(newValue,newPropName)}},outcome:props.outcome,elementDefinitionType:propertyTypes[0],min:property.min,max:property.min,binding:property.binding,path:props.path,valuePath:props.valuePath,readOnly:property.readonly})}function ElementDefinitionInputSelector(props){let propertyTypes=props.elementDefinitionTypes,initialPropertyType;props.defaultPropertyType&&(initialPropertyType=propertyTypes.find(t=>t.code===props.defaultPropertyType)),initialPropertyType||(initialPropertyType=propertyTypes[0]);let[selectedType,setSelectedType]=useState47(initialPropertyType);return jsxs49(Group27,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx86(NativeSelect9,{disabled:props.property.readonly,style:{width:"200px"},defaultValue:selectedType.code,"data-testid":props.name&&props.name+"-selector",onChange:e=>{setSelectedType(propertyTypes.find(type=>type.code===e.currentTarget.value))},data:propertyTypes.map(type=>({value:type.code,label:type.code}))}),jsx86(ElementDefinitionTypeInput,{name:props.name,defaultValue:props.defaultValue,outcome:props.outcome,elementDefinitionType:selectedType,onChange:newValue=>{props.onChange&&props.onChange(newValue,props.name.replace("[x]",capitalize2(selectedType.code)))},min:props.property.min,max:props.property.max,binding:props.property.binding,path:props.property.path,valuePath:props.valuePath,readOnly:props.property.readonly})]})}function ElementDefinitionTypeInput(props){let{name,onChange,outcome,binding,path,valuePath,readOnly}=props,required=props.min!==void 0&&props.min>0,propertyType=props.elementDefinitionType.code,elementsContext=useContext21(ElementsContext),defaultValue2=useMemo20(()=>{if(!isComplexTypeCode(propertyType)||!isEmpty6(props.defaultValue))return props.defaultValue;let withDefaults=Object.create(null);if(elementsContext.path===props.path)applyDefaultValuesToElement(withDefaults,elementsContext.elements);else{let key=getPathDifference(elementsContext.path,props.path);if(key===void 0)return props.defaultValue;applyDefaultValuesToElement(withDefaults,elementsContext.elements,key)}return isPopulated10(withDefaults)?withDefaults:props.defaultValue},[propertyType,elementsContext.path,elementsContext.elements,props.path,props.defaultValue]);if(!propertyType)return jsx86("div",{children:"Property type not specified "});function getComplexInputProps(){return{name,defaultValue:defaultValue2,onChange,outcome,path,valuePath,disabled:readOnly}}function getPrimitiveInputProps(){let error=getErrorsForInput(props.outcome,valuePath??path);return{id:name,name,"data-testid":name,defaultValue:defaultValue2,required,error,disabled:readOnly}}switch(propertyType){case PropertyType2.SystemString:case PropertyType2.canonical:case PropertyType2.string:case PropertyType2.uri:case PropertyType2.url:return props.path==="Project.secret.value[x]"||props.path==="ClientApplication.certificateTrustStore"?jsx86(SensitiveTextarea,{...getPrimitiveInputProps(),onChange:e=>{props.onChange&&props.onChange(e.currentTarget.value)}}):jsx86(TextInput18,{...getPrimitiveInputProps(),onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.date:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"date",onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.time:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"time",step:1,onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.dateTime:case PropertyType2.instant:return jsx86(DateTimeInput,{...getPrimitiveInputProps(),onChange,outcome});case PropertyType2.decimal:case PropertyType2.integer:case PropertyType2.positiveInt:case PropertyType2.unsignedInt:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"number",step:propertyType===PropertyType2.decimal?"any":"1",onChange:e=>{if(onChange){let num=e.currentTarget.valueAsNumber;onChange(Number.isNaN(num)?void 0:num)}}});case PropertyType2.code:return jsx86(CodeInput,{...getPrimitiveInputProps(),error:void 0,onChange,binding:binding?.valueSet,creatable:!0,maxValues:1});case PropertyType2.boolean:return jsx86(Checkbox4,{...getPrimitiveInputProps(),defaultChecked:!!defaultValue2,onChange:e=>{onChange&&onChange(e.currentTarget.checked)}});case PropertyType2.base64Binary:case PropertyType2.markdown:case PropertyType2.xhtml:return jsx86(Textarea2,{...getPrimitiveInputProps(),spellCheck:propertyType!==PropertyType2.base64Binary,onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.Address:return jsx86(AddressInput,{...getComplexInputProps()});case PropertyType2.Annotation:return jsx86(AnnotationInput,{...getComplexInputProps()});case PropertyType2.Attachment:return jsx86(AttachmentInput,{...getComplexInputProps()});case PropertyType2.CodeableConcept:return jsx86(CodeableConceptInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.Coding:return jsx86(CodingInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.ContactDetail:return jsx86(ContactDetailInput,{...getComplexInputProps()});case PropertyType2.ContactPoint:return jsx86(ContactPointInput,{...getComplexInputProps()});case PropertyType2.Extension:return jsx86(ExtensionInput,{...getComplexInputProps(),propertyType:props.elementDefinitionType});case PropertyType2.HumanName:return jsx86(HumanNameInput,{...getComplexInputProps()});case PropertyType2.Identifier:return jsx86(IdentifierInput,{...getComplexInputProps()});case PropertyType2.Money:return jsx86(MoneyInput,{...getComplexInputProps()});case PropertyType2.Period:return jsx86(PeriodInput,{...getComplexInputProps()});case PropertyType2.Duration:case PropertyType2.Quantity:return jsx86(QuantityInput,{...getComplexInputProps()});case PropertyType2.Range:return jsx86(RangeInput,{...getComplexInputProps()});case PropertyType2.Ratio:return jsx86(RatioInput,{...getComplexInputProps()});case PropertyType2.Reference:return jsx86(ReferenceInput,{...getComplexInputProps(),targetTypes:getTargetTypes(props.elementDefinitionType)});case PropertyType2.Timing:return jsx86(TimingInput,{...getComplexInputProps()});case PropertyType2.Dosage:case PropertyType2.UsageContext:default:return jsx86(BackboneElementInput,{...getComplexInputProps(),typeName:propertyType})}}var RESOURCE_TYPE_URL_PREFIXES=[`${HTTP_HL7_ORG}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function getTargetTypes(elementDefinitionType){return elementDefinitionType?.targetProfile?.map(p=>{let resourceTypePrefix=RESOURCE_TYPE_URL_PREFIXES.find(prefix=>p.startsWith(prefix));return resourceTypePrefix?p.slice(resourceTypePrefix.length):p})}import{jsx as jsx87}from"react/jsx-runtime";function ElementsInput(props){let[value,setValue]=useState48(props.defaultValue??{}),elementsContext=useContext22(ElementsContext),elementsToRender=useMemo21(()=>getElementsToRender(elementsContext.elements),[elementsContext.elements]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}let typedValue={type:props.type,value};return jsx87(Stack17,{style:{flexGrow:1},"data-testid":props.testId,children:elementsToRender.map(([key,element])=>{let[propertyValue,propertyType]=getValueAndTypeFromElement(typedValue,key,element),required=element.min!==void 0&&element.min>0,valuePath=props.valuePath?props.valuePath+"."+key:void 0,resourcePropertyInput=jsx87(ResourcePropertyInput,{property:element,name:key,path:props.path+"."+key,valuePath,defaultValue:propertyValue,defaultPropertyType:propertyType,onChange:(newValue,propName)=>{setValueWrapper(setPropertyValue({...value},key,propName??key,element,newValue))},outcome:props.outcome},key);return props.type==="Extension"||EXTENSION_KEYS.includes(key)?resourcePropertyInput:element.type.length===1&&element.type[0].code==="boolean"?jsx87(CheckboxFormSection,{title:getPathDisplayName5(key),description:element.description,htmlFor:key,fhirPath:element.path,withAsterisk:required,readonly:element.readonly,children:resourcePropertyInput},key):jsx87(FormSection,{title:getPathDisplayName5(key),description:element.description,withAsterisk:required,htmlFor:key,outcome:props.outcome,fhirPath:element.path,errorExpression:valuePath,readonly:element.readonly,children:resourcePropertyInput},key)})})}var BackboneElementInput_default={nested:"BackboneElementInput_nested"};import{jsx as jsx88,jsxs as jsxs50}from"react/jsx-runtime";function BackboneElementInput(props){let[defaultValue2]=useState49(()=>props.defaultValue??{}),parentElementsContext=useContext23(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=useMemo22(()=>tryGetDataType2(props.typeName,profileUrl),[props.typeName,profileUrl]),type=typeSchema?.type??props.typeName,contextValue=useMemo22(()=>{if(typeSchema)return buildElementsContext4({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if(!typeSchema)return jsxs50("div",{children:[type,"\xA0not implemented"]});let isNested=parentElementsContext.path!=="";return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx88(Box7,{className:clsx_default({[BackboneElementInput_default.nested]:isNested}),children:jsx88(ElementsInput,{path:props.path,valuePath:props.valuePath,type,defaultValue:defaultValue2,onChange:props.onChange,outcome:props.outcome})}))}import{Button as Button8,Group as Group28}from"@mantine/core";import{useMemo as useMemo23,useState as useState50}from"react";var CalendarInput_default={table:"CalendarInput_table"};function getMonthString(date){return date.toLocaleString("default",{month:"long"})+" "+date.getFullYear()}function getStartMonth(){let result=new Date;return result.setDate(1),result.setHours(0,0,0,0),result}import{jsx as jsx89,jsxs as jsxs51}from"react/jsx-runtime";function CalendarInput(props){let{onChangeMonth,onClick}=props,[month,setMonth]=useState50(getStartMonth);function moveMonth(delta){setMonth(currMonth=>{let newMonth=new Date(currMonth.getTime());return newMonth.setMonth(currMonth.getMonth()+delta),onChangeMonth(newMonth),newMonth})}let grid=useMemo23(()=>buildGrid(month,props.slots),[month,props.slots]);return jsxs51("div",{children:[jsxs51(Group28,{justify:"space-between",gap:"xs",grow:!0,wrap:"nowrap",children:[jsx89("p",{style:{flex:1},children:getMonthString(month)}),jsxs51(Group28,{justify:"flex-end",gap:"xs",children:[jsx89(Button8,{variant:"outline","aria-label":"Previous month",onClick:()=>moveMonth(-1),children:"<"}),jsx89(Button8,{variant:"outline","aria-label":"Next month",onClick:()=>moveMonth(1),children:">"})]})]}),jsxs51("table",{className:CalendarInput_default.table,children:[jsx89("thead",{children:jsxs51("tr",{children:[jsx89("th",{children:"SUN"}),jsx89("th",{children:"MON"}),jsx89("th",{children:"TUE"}),jsx89("th",{children:"WED"}),jsx89("th",{children:"THU"}),jsx89("th",{children:"FRI"}),jsx89("th",{children:"SAT"})]})}),jsx89("tbody",{children:grid.map((week,weekIndex)=>jsx89("tr",{children:week.map((day,dayIndex)=>jsx89("td",{children:day&&jsx89(Button8,{variant:"light",disabled:!day.available,onClick:()=>onClick(day.date),children:day.date.getDate()})},"day-"+dayIndex))},"week-"+weekIndex))})]})]})}function buildGrid(startDate,slots){let d=new Date(startDate.getFullYear(),startDate.getMonth()),grid=[],row=[];for(let i=0;i<d.getDay();i++)row.push(void 0);for(;d.getMonth()===startDate.getMonth();)row.push({date:new Date(d.getTime()),available:isDayAvailable(d,slots)}),d.getDay()===6&&(grid.push(row),row=[]),d.setDate(d.getDate()+1);if(d.getDay()!==0){for(let i=d.getDay();i<7;i++)row.push(void 0);grid.push(row)}return grid}function isDayAvailable(day,slots){for(let slot of slots){let slotStart=new Date(slot.start);if(slotStart.getFullYear()===day.getFullYear()&&slotStart.getMonth()===day.getMonth()&&slotStart.getDate()===day.getDate())return!0}return!1}import{ActionIcon as ActionIcon7,Group as Group29,LoadingOverlay,Menu as Menu4,Paper as Paper2,Popover,ScrollArea as ScrollArea2,Skeleton,Stack as Stack19,Text as Text18,TextInput as TextInput20,Title as Title8}from"@mantine/core";import{useResizeObserver}from"@mantine/hooks";import{showNotification as showNotification5}from"@mantine/notifications";import{getDisplayString as getDisplayString4,getReferenceString as getReferenceString5,normalizeErrorString as normalizeErrorString6}from"@medplum/core";import{useCachedBinaryUrl as useCachedBinaryUrl3,useMedplum as useMedplum24,useResource as useResource2,useSubscription}from"@medplum/react-hooks";import{useCallback as useCallback11,useEffect as useEffect15,useMemo as useMemo24,useRef as useRef10,useState as useState52}from"react";var BaseChat_default={chatPaper:"BaseChat_chatPaper",chatTitle:"BaseChat_chatTitle",chatBody:"BaseChat_chatBody",chatScrollArea:"BaseChat_chatScrollArea",chatInputContainer:"BaseChat_chatInputContainer",chatPendingFile:"BaseChat_chatPendingFile",chatBubbleOuterWrap:"BaseChat_chatBubbleOuterWrap",chatBubbleRightAlignedInnerWrap:"BaseChat_chatBubbleRightAlignedInnerWrap",chatBubbleLeftAlignedInnerWrap:"BaseChat_chatBubbleLeftAlignedInnerWrap",chatBubble:"BaseChat_chatBubble",chatBubbleNameRight:"BaseChat_chatBubbleNameRight",chatBubbleAttachmentWithText:"BaseChat_chatBubbleAttachmentWithText",chatBubbleAttachmentIcon:"BaseChat_chatBubbleAttachmentIcon",chatBubbleMenu:"BaseChat_chatBubbleMenu"};import{Box as Box8,Divider as Divider4,Loader as Loader3,Stack as Stack18,Text as Text17,TextInput as TextInput19,UnstyledButton as UnstyledButton3}from"@mantine/core";import{useDebouncedCallback as useDebouncedCallback2}from"@mantine/hooks";import{getReferenceString as getReferenceString4}from"@medplum/core";import{useMedplum as useMedplum23}from"@medplum/react-hooks";import{useEffect as useEffect14,useState as useState51}from"react";import{jsx as jsx90,jsxs as jsxs52}from"react/jsx-runtime";function DocumentPicker({subjectRef,onSelect,onUpload}){let medplum=useMedplum23(),[search,setSearch]=useState51(""),[docs,setDocs]=useState51([]),[loading,setLoading]=useState51(!0),subjectRefStr=subjectRef?getReferenceString4(subjectRef):void 0,fetchDocs=useDebouncedCallback2(async query=>{setLoading(!0);try{let params=new URLSearchParams;subjectRefStr&¶ms.set("subject",subjectRefStr),query.trim()&¶ms.set("description:contains",query.trim()),params.set("_sort","-date"),params.set("_count","5");let results=await medplum.searchResources("DocumentReference",params);setDocs([...results])}catch(err){console.error(err)}finally{setLoading(!1)}},300);useEffect14(()=>{fetchDocs(search)},[fetchDocs,search]);let getDocName=doc=>doc.description??doc.content?.[0]?.attachment?.title??"Untitled";return jsxs52(Stack18,{gap:0,w:280,children:[jsx90(Text17,{fw:500,fz:"sm",px:"sm",pt:"sm",pb:"xs",children:"Attachments"}),jsx90(Box8,{px:"sm",pb:"xs",children:jsx90(TextInput19,{placeholder:"Search for a Document...",size:"xs",value:search,onChange:e=>setSearch(e.currentTarget.value)})}),jsx90(Divider4,{}),loading?jsx90(Box8,{py:"sm",style:{display:"flex",justifyContent:"center"},children:jsx90(Loader3,{size:"xs"})}):jsxs52(Stack18,{gap:0,children:[docs.map(doc=>jsxs52(UnstyledButton3,{px:"sm",py:"xs",onClick:()=>onSelect(doc),style:{display:"flex",alignItems:"center",gap:8},children:[jsx90(IconFileText,{size:"1rem",style:{flexShrink:0,color:"var(--mantine-color-blue-6)"}}),jsx90(Text17,{fz:"sm",truncate:!0,children:getDocName(doc)})]},doc.id)),docs.length===0&&jsx90(Text17,{fz:"xs",c:"dimmed",px:"sm",py:"xs",children:"No documents found"})]}),jsx90(Divider4,{}),jsxs52(UnstyledButton3,{px:"sm",py:"xs",onClick:onUpload,style:{display:"flex",alignItems:"center",gap:8},children:[jsx90(IconPaperclip,{size:"1rem",style:{flexShrink:0,color:"var(--mantine-color-gray-6)"}}),jsx90(Text17,{fz:"sm",c:"dimmed",children:"Upload an image, pdf, etc."})]})]})}import{jsx as jsx91,jsxs as jsxs53}from"react/jsx-runtime";function toSafeUrl(url){if(url)try{let{protocol}=new URL(url);return protocol==="https:"||protocol==="http:"||protocol==="blob:"?url:void 0}catch{return}}function showError(message){showNotification5({color:"red",title:"Error",message,autoClose:!1})}function parseSentTime(communication){return new Date(communication.sent??0).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function upsertCommunications(communications,received,setCommunications){let newCommunications=[...communications],foundNew=!1;for(let comm of received){let existingIdx=newCommunications.findIndex(c=>c.id===comm.id);existingIdx!==-1?newCommunications[existingIdx]=comm:(newCommunications.push(comm),foundNew=!0)}foundNew&&newCommunications.sort((a,b)=>!a.sent&&!b.sent?0:a.sent?b.sent?a.sent.localeCompare(b.sent):1:-1),setCommunications(newCommunications)}function BaseChat(props){let{title,communications,setCommunications,query,sendMessage,onMessageReceived,onMessageUpdated,inputDisabled,onError,excludeHeader=!1,uploadEnabled=!1,attachmentSubjectRef,onViewInDocuments,...paperProps}=props,medplum=useMedplum24(),inputRef=useRef10(null),scrollAreaRef=useRef10(null),firstScrollRef=useRef10(!0),initialLoadRef=useRef10(!0),[profile,setProfile]=useState52(medplum.getProfile()),[reconnecting,setReconnecting]=useState52(!1),[loading,setLoading]=useState52(!0),[pendingFile,setPendingFile]=useState52(void 0),[pendingDocRef,setPendingDocRef]=useState52(void 0),[pickerOpen,setPickerOpen]=useState52(!1),fileInputRef=useRef10(null);loading||(initialLoadRef.current=!1);let profileRefStr=useMemo24(()=>profile?getReferenceString5(medplum.getProfile()):"",[profile,medplum]),searchMessages=useCallback11(async()=>{setLoading(!0);let searchParams=new URLSearchParams(query);searchParams.append("_sort","-sent"),searchParams.append("sent:missing","false");let searchResult=await medplum.searchResources("Communication",searchParams,{cache:"no-cache"});upsertCommunications(communicationsRef.current,searchResult,setCommunications),setLoading(!1)},[medplum,setCommunications,query]);useEffect15(()=>{searchMessages().catch(err=>showNotification5({color:"red",message:normalizeErrorString6(err)}))},[searchMessages]),useSubscription(`Communication?${query}`,bundle=>{let communication=bundle.entry?.[1]?.resource;upsertCommunications(communicationsRef.current,[communication],setCommunications),getReferenceString5(communication.sender)!==profileRefStr&&(communicationsRef.current.find(c=>c.id===communication.id)?onMessageUpdated?.(communication):onMessageReceived?.(communication))},{onWebSocketClose:useCallback11(()=>{reconnecting||setReconnecting(!0),showNotification5({color:"red",message:"Live chat disconnected. Attempting to reconnect..."})},[reconnecting]),onWebSocketOpen:useCallback11(()=>{reconnecting&&showNotification5({color:"green",message:"Live chat reconnected."})},[reconnecting]),onSubscriptionConnect:useCallback11(()=>{reconnecting&&(searchMessages().catch(err=>showNotification5({color:"red",message:normalizeErrorString6(err)})),setReconnecting(!1))},[reconnecting,searchMessages]),onError:useCallback11(err=>{onError?onError(err):showError(normalizeErrorString6(err))},[onError])});let sendMessageInternal=useCallback11(formData=>{if(inputDisabled)return;let message=formData.message?.trim()??"";!message&&!pendingFile&&!pendingDocRef||(inputRef.current&&(inputRef.current.value=""),fileInputRef.current&&(fileInputRef.current.value=""),sendMessage(message,pendingFile,pendingDocRef),setPendingFile(void 0),setPendingDocRef(void 0),scrollToBottomRef.current=!0)},[inputDisabled,sendMessage,pendingFile,pendingDocRef]);useEffect15(()=>{let latestProfile=medplum.getProfile();profile?.id!==latestProfile?.id&&(setProfile(latestProfile),setCommunications([]))});let[parentRef,parentRect]=useResizeObserver(),communicationsRef=useRef10(communications);communicationsRef.current=communications;let prevCommunicationsRef=useRef10(communications),scrollToBottomRef=useRef10(!0);useEffect15(()=>{communications!==prevCommunicationsRef.current&&(scrollToBottomRef.current=!0),prevCommunicationsRef.current=communications},[communications]),useEffect15(()=>{scrollToBottomRef.current&&scrollAreaRef.current?.scrollTo&&(scrollAreaRef.current.scrollTo({top:scrollAreaRef.current.scrollHeight,...firstScrollRef.current?{duration:0}:{behavior:"smooth"}}),firstScrollRef.current=!1,scrollToBottomRef.current=!1)});let myLastDeliveredId=useMemo24(()=>{let i=communications.length;for(;i--;){let comm=communications[i];if(comm.sender?.reference===profileRefStr&&comm.received)return comm.id}return""},[communications,profileRefStr]);return profile?jsxs53(Paper2,{className:BaseChat_default.chatPaper,p:0,radius:"md",...paperProps,children:[!excludeHeader&&jsx91(Title8,{order:2,className:BaseChat_default.chatTitle,children:title}),jsx91("div",{className:BaseChat_default.chatBody,ref:parentRef,children:initialLoadRef.current?jsxs53(Stack19,{align:"stretch",mt:"lg",children:[jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(Skeleton,{height:38,circle:!0,ml:"md"}),jsx91(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]}),jsxs53(Group29,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(ChatBubbleSkeleton,{alignment:"right",parentWidth:parentRect.width}),jsx91(Skeleton,{height:38,circle:!0,mr:"md"})]}),jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(Skeleton,{height:38,circle:!0,ml:"md"}),jsx91(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]})]},"skeleton-chat-messages"):jsxs53(ScrollArea2,{viewportRef:scrollAreaRef,className:BaseChat_default.chatScrollArea,h:parentRect.height,children:[jsx91(LoadingOverlay,{visible:loading||reconnecting,style:{width:parentRect.width,height:parentRect.height,position:"absolute",zIndex:1}}),communications.map((c,i)=>{let prevCommunication=i>0?communications[i-1]:void 0,prevCommTime=prevCommunication?parseSentTime(prevCommunication):void 0,currCommTime=parseSentTime(c),showDelivered=!!c.received&&c.id===myLastDeliveredId,payloads=c.payload??[],contentRef=payloads.find(p=>p.contentReference)?.contentReference,contentAttachment=payloads.find(p=>p.contentAttachment)?.contentAttachment,hasAttachment=!!(contentRef||contentAttachment),isSender=c.sender?.reference===profileRefStr,menu=hasAttachment?jsx91(ChatBubbleMenu,{contentRef,contentAttachment,onViewInDocuments}):null;return jsxs53(Stack19,{align:"stretch",children:[(!prevCommTime||currCommTime!==prevCommTime)&&jsx91(Text18,{fz:"xs",ta:"center",children:currCommTime}),isSender?jsxs53(Group29,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91("div",{className:BaseChat_default.chatBubbleMenu,children:menu}),jsx91(ChatBubble,{alignment:"right",communication:c,showDelivered}),jsx91(ResourceAvatar,{radius:"xl",color:"orange",value:c.sender,mb:showDelivered?void 0:"sm"})]}):jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(ResourceAvatar,{radius:"xl",value:c.sender,mb:"sm"}),jsx91(ChatBubble,{alignment:"left",communication:c}),jsx91("div",{className:BaseChat_default.chatBubbleMenu,children:menu})]})]},`${c.id}--${c.meta?.versionId??"no-version"}`)})]})}),jsxs53("div",{className:BaseChat_default.chatInputContainer,children:[(pendingFile||pendingDocRef)&&jsxs53(Group29,{className:BaseChat_default.chatPendingFile,gap:4,align:"center",wrap:"nowrap",children:[pendingDocRef?jsx91(IconFileText,{size:"0.75rem"}):jsx91(IconPaperclip,{size:"0.75rem"}),jsx91(Text18,{fz:"xs",c:"dimmed",flex:1,truncate:!0,children:pendingDocRef?pendingDocRef.description??pendingDocRef.content?.[0]?.attachment?.title??"Document":pendingFile?.name}),jsx91(ActionIcon7,{size:"xs",variant:"subtle",color:"red",onClick:()=>{setPendingDocRef(void 0),setPendingFile(void 0),fileInputRef.current&&(fileInputRef.current.value="")},"aria-label":"Remove attachment",children:jsx91(IconX,{size:"0.75rem"})})]}),jsx91("input",{ref:fileInputRef,type:"file",style:{display:"none"},disabled:inputDisabled,onChange:e=>{let file=e.target.files?.[0];file&&(setPendingFile(file),setPendingDocRef(void 0))}}),jsx91(Form,{onSubmit:sendMessageInternal,children:jsx91(TextInput20,{ref:inputRef,name:"message",placeholder:inputDisabled?"Replies are disabled":"Type a message...",radius:"xl",leftSectionWidth:42,rightSectionWidth:42,disabled:inputDisabled,leftSection:!inputDisabled&&uploadEnabled?jsxs53(Popover,{opened:pickerOpen,onChange:setPickerOpen,position:"top-start",withArrow:!0,shadow:"md",withinPortal:!0,children:[jsx91(Popover.Target,{children:jsx91(ActionIcon7,{onClick:()=>setPickerOpen(o=>!o),size:"1.5rem",radius:"xl",color:pendingFile||pendingDocRef?"blue":"gray",variant:pendingFile||pendingDocRef?"filled":"subtle","aria-label":"Attach file",children:jsx91(IconPaperclip,{size:"1rem",stroke:1.5})})}),jsx91(Popover.Dropdown,{p:0,children:jsx91(DocumentPicker,{subjectRef:attachmentSubjectRef,onSelect:doc=>{setPendingDocRef(doc),setPendingFile(void 0),setPickerOpen(!1)},onUpload:()=>{setPickerOpen(!1),fileInputRef.current?.click()}})})]}):void 0,rightSection:inputDisabled?void 0:jsx91(ActionIcon7,{type:"submit",size:"1.5rem",radius:"xl",color:"blue",variant:"filled","aria-label":"Send message",children:jsx91(IconArrowRight,{size:"1rem",stroke:1.5})})})})]})]}):null}function ChatBubble(props){let{communication,alignment,showDelivered}=props,payloads=communication.payload??[],textContent=payloads.find(p=>p.contentString)?.contentString??"",contentRef=payloads.find(p=>p.contentReference)?.contentReference,attachment=payloads.find(p=>p.contentAttachment)?.contentAttachment,sentTime=new Date(communication.sent??-1),seenTime=new Date(communication.received??-1),senderResource=useResource2(communication.sender);return jsxs53("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsxs53(Text18,{fz:"xs",mb:"xs",fw:500,className:alignment==="right"?BaseChat_default.chatBubbleNameRight:void 0,"aria-label":"Sender name",children:[senderResource?getDisplayString4(senderResource):"[Unknown sender]","\xA0\xB7\xA0",jsx91(Text18,{span:!0,c:"dimmed",fz:"xs",children:Number.isNaN(sentTime.getTime())?"":sentTime.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})})]}),jsx91("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsxs53("div",{className:BaseChat_default.chatBubble,children:[textContent&&jsx91("span",{children:textContent}),contentRef&&jsx91(ChatBubbleDocumentReference,{reference:contentRef,hasText:!!textContent}),attachment&&jsx91(ChatBubbleAttachment,{attachment,hasText:!!textContent})]})}),showDelivered&&jsxs53("div",{style:{textAlign:"right"},children:["Delivered ",seenTime.getHours(),":",seenTime.getMinutes().toString().length===1?"0":"",seenTime.getMinutes()]})]})}function ChatBubbleAttachment({attachment,hasText}){return jsx91("div",{className:hasText?BaseChat_default.chatBubbleAttachmentWithText:void 0,children:jsxs53(Group29,{gap:4,wrap:"nowrap",children:[jsx91("span",{className:BaseChat_default.chatBubbleAttachmentIcon,children:jsx91(IconPaperclip,{size:"0.75rem"})}),jsx91(Text18,{fz:"xs",truncate:!0,children:attachment.title??"File attached"})]})})}function ChatBubbleDocumentReference({reference,hasText}){let attachment=useResource2(reference)?.content?.[0]?.attachment;return attachment?jsx91(ChatBubbleAttachment,{attachment,hasText}):null}function ChatBubbleMenu({contentRef,contentAttachment,onViewInDocuments}){let docRef=useResource2(contentRef),attachment=contentRef?docRef?.content?.[0]?.attachment:contentAttachment,cachedUrl=useCachedBinaryUrl3(attachment?.url),handleDownload=()=>{let href=toSafeUrl(cachedUrl??attachment?.url);href&&window.open(href,"_blank","noopener,noreferrer")};return jsxs53(Menu4,{withinPortal:!0,position:"bottom-start",shadow:"md",children:[jsx91(Menu4.Target,{children:jsx91(ActionIcon7,{variant:"outline",color:"gray",radius:"xl",size:"sm","aria-label":"Attachment options",children:jsx91(IconDots,{size:"0.75rem"})})}),jsxs53(Menu4.Dropdown,{children:[contentRef&&onViewInDocuments&&jsx91(Menu4.Item,{leftSection:jsx91(IconFileExport,{size:"0.9rem"}),onClick:()=>onViewInDocuments(contentRef),children:"View in Documents"}),jsx91(Menu4.Item,{leftSection:jsx91(IconDownload,{size:"0.9rem"}),onClick:handleDownload,children:"Download"})]})]})}function ChatBubbleSkeleton(props){let{alignment,parentWidth}=props;return jsxs53("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx91("div",{className:BaseChat_default.chatBubbleName,"aria-label":"Placeholder sender name",children:jsx91("div",{style:{position:"relative"},children:jsx91(Skeleton,{height:14,width:"100px",radius:"l",ml:alignment==="left"?"sm":void 0,style:alignment==="right"?{position:"absolute",right:5,top:-15}:void 0})})}),jsx91("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx91("div",{className:BaseChat_default.chatBubble,children:jsx91(Skeleton,{height:14,width:parentWidth*.5,radius:"l"})})})]})}import{ActionIcon as ActionIcon8}from"@mantine/core";import{useMedplumProfile as useMedplumProfile5}from"@medplum/react-hooks";import{useEffect as useEffect16,useState as useState53}from"react";var ChatModal_default={iconContainer:"ChatModal_iconContainer",icon:"ChatModal_icon",chatModalContainer:"ChatModal_chatModalContainer"};import{Fragment as Fragment29,jsx as jsx92,jsxs as jsxs54}from"react/jsx-runtime";function ChatModal(props){let{open,children}=props,profile=useMedplumProfile5(),[opened,setOpened]=useState53(open??!1);return useEffect16(()=>{setOpened(prevVal=>open??prevVal)},[open]),profile?jsxs54(Fragment29,{children:[opened&&jsx92("div",{className:ChatModal_default.chatModalContainer,children}),opened?jsx92("div",{className:ChatModal_default.iconContainer,children:jsx92(ActionIcon8,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!1),"aria-label":"Close chat",children:jsx92(IconChevronDown,{size:"1.625rem"})})}):jsx92("div",{className:ChatModal_default.iconContainer,children:jsx92(ActionIcon8,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!0),"aria-label":"Open chat",children:jsx92(IconChevronUp,{size:"1.625rem"})})})]}):null}import{createReference as createReference3,formatCodeableConcept as formatCodeableConcept2,getReferenceString as getReferenceString6}from"@medplum/core";import{useMedplum as useMedplum25,useMedplumProfile as useMedplumProfile6,usePrevious}from"@medplum/react-hooks";import{useCallback as useCallback12,useEffect as useEffect17,useMemo as useMemo25,useState as useState54}from"react";import{jsx as jsx93}from"react/jsx-runtime";function ThreadChat(props){let{thread,title,onMessageSent,inputDisabled,excludeHeader,uploadEnabled,onError,onViewInDocuments}=props,medplum=useMedplum25(),profile=useMedplumProfile6(),prevThreadId=usePrevious(thread?.id),[communications,setCommunications]=useState54([]),profileRef=useMemo25(()=>profile?createReference3(profile):void 0,[profile]),threadRef=useMemo25(()=>createReference3(thread),[thread]);useEffect17(()=>{thread?.id!==prevThreadId&&setCommunications([])},[thread?.id,prevThreadId]);let sendMessage=useCallback12((message,file,existingDocRef)=>{let profileRefStr=profileRef?getReferenceString6(profileRef):void 0;if(!profileRefStr)return;(async()=>{let payload=[];if(message&&payload.push({contentString:message}),existingDocRef)payload.push({contentReference:createReference3(existingDocRef)});else if(file){let docRef=await medplum.createDocumentReference({data:file,contentType:file.type||"application/octet-stream",filename:file.name,additionalFields:{...thread.subject?{subject:thread.subject}:{},description:file.name}});payload.push({contentReference:createReference3(docRef)})}let communication=await medplum.createResource({resourceType:"Communication",status:"in-progress",sender:profileRef,recipient:thread.recipient?.filter(ref=>getReferenceString6(ref)!==profileRefStr)??[],sent:new Date().toISOString(),payload,partOf:[threadRef],subject:thread.subject});setCommunications([...communications,communication]),onMessageSent?.(communication)})().catch(console.error)},[medplum,profileRef,thread,threadRef,communications,onMessageSent]),onMessageReceived=useMemo25(()=>thread.recipient?.length===2?message=>{message.received&&message.status==="completed"||medplum.updateResource({...message,received:message.received??new Date().toISOString(),status:"completed"}).catch(console.error)}:void 0,[medplum,thread.recipient?.length]);return profile?jsx93(BaseChat,{title:title??(thread?.topic?formatCodeableConcept2(thread.topic):"[No thread title]"),communications,setCommunications,query:`part-of=Communication/${thread.id}`,sendMessage,onMessageReceived,inputDisabled,excludeHeader,uploadEnabled,onError,attachmentSubjectRef:thread.subject,onViewInDocuments}):null}import{Divider as Divider5,Stack as Stack21}from"@mantine/core";import{Fragment as Fragment30}from"react";import{Group as Group30,Stack as Stack20,Text as Text19}from"@mantine/core";import{formatDateTime as formatDateTime2,formatHumanName as formatHumanName6}from"@medplum/core";import{useResource as useResource3}from"@medplum/react-hooks";var ChatListItem_default={content:"ChatListItem_content",contentContainer:"ChatListItem_contentContainer",selected:"ChatListItem_selected"};import{jsx as jsx94,jsxs as jsxs55}from"react/jsx-runtime";var ChatListItem=props=>{let{topic,lastCommunication,isSelected,getThreadUri}=props,patientResource=useResource3(topic.subject),patientName=formatHumanName6(patientResource?.name?.[0]),lastMsg=lastCommunication?.payload?.[0]?.contentString,trimmedMsg=lastMsg?.length&&lastMsg.length>100?lastMsg.slice(0,100)+"...":lastMsg,senderName=lastCommunication?.sender?.display?`${lastCommunication?.sender?.display}: `:"",content=trimmedMsg?`${senderName} ${trimmedMsg}`:"No messages available",topicName=topic.topic?.text??content;return jsx94(MedplumLink,{to:getThreadUri(topic),underline:"never",children:jsxs55(Group30,{p:"xs",align:"center",wrap:"nowrap",className:clsx_default(ChatListItem_default.contentContainer,{[ChatListItem_default.selected]:isSelected}),children:[jsx94(ResourceAvatar,{value:topic.subject,radius:"xl",size:36}),jsxs55(Stack20,{gap:0,children:[jsx94(Text19,{size:"sm",fw:700,truncate:"end",children:patientName}),jsx94(Text19,{size:"sm",fw:400,lineClamp:2,className:ChatListItem_default.content,children:topicName}),jsx94(Text19,{size:"xs",style:{marginTop:2},children:lastCommunication?formatDateTime2(lastCommunication.sent):""})]})]})})};import{jsx as jsx95,jsxs as jsxs56}from"react/jsx-runtime";var ChatList=props=>{let{threads,selectedCommunication,getThreadUri}=props;return jsx95(Stack21,{gap:0,children:threads.map(thread=>{let topicCommunication=thread[0],lastCommunication=thread[1],_isSelected=selectedCommunication?.id===topicCommunication.id;return jsxs56(Fragment30,{children:[jsx95(ChatListItem,{topic:topicCommunication,lastCommunication,isSelected:_isSelected,getThreadUri}),jsx95(Divider5,{})]},topicCommunication.id)})})};import{Button as Button11,Modal as Modal3,Stack as Stack25,Text as Text22,TextInput as TextInput22}from"@mantine/core";import{showNotification as showNotification6}from"@mantine/notifications";import{createReference as createReference6,HTTP_HL7_ORG as HTTP_HL7_ORG4,normalizeErrorString as normalizeErrorString7}from"@medplum/core";import{useMedplum as useMedplum29,useMedplumProfile as useMedplumProfile7}from"@medplum/react-hooks";import{useMemo as useMemo27,useState as useState57}from"react";import{Group as Group33,Stack as Stack24,Text as Text21,Title as Title10}from"@mantine/core";import{createReference as createReference5,getExtension as getExtension2,getReferenceString as getReferenceString7}from"@medplum/core";import{QUESTIONNAIRE_SIGNATURE_REQUIRED_URL,QUESTIONNAIRE_SIGNATURE_RESPONSE_URL,useMedplum as useMedplum28,useQuestionnaireForm}from"@medplum/react-hooks";import{useCallback as useCallback13,useEffect as useEffect20,useLayoutEffect as useLayoutEffect3,useMemo as useMemo26,useRef as useRef12,useState as useState56}from"react";import{Button as Button9,Paper as Paper3}from"@mantine/core";import{createReference as createReference4,HTTP_HL7_ORG as HTTP_HL7_ORG2}from"@medplum/core";import{useMedplum as useMedplum26}from"@medplum/react-hooks";import{useEffect as useEffect18,useLayoutEffect as useLayoutEffect2,useRef as useRef11}from"react";var Point=class{constructor(x,y,pressure,time){__publicField(this,"x");__publicField(this,"y");__publicField(this,"pressure");__publicField(this,"time");if(isNaN(x)||isNaN(y))throw new Error(`Point is invalid: (${x}, ${y})`);this.x=+x,this.y=+y,this.pressure=pressure||0,this.time=time||Date.now()}distanceTo(start){return Math.sqrt(Math.pow(this.x-start.x,2)+Math.pow(this.y-start.y,2))}equals(other){return this.x===other.x&&this.y===other.y&&this.pressure===other.pressure&&this.time===other.time}velocityFrom(start){return this.time!==start.time?this.distanceTo(start)/(this.time-start.time):0}},Bezier=class _Bezier{constructor(startPoint,control2,control1,endPoint,startWidth,endWidth){this.startPoint=startPoint,this.control2=control2,this.control1=control1,this.endPoint=endPoint,this.startWidth=startWidth,this.endWidth=endWidth}static fromPoints(points,widths){let c2=this.calculateControlPoints(points[0],points[1],points[2]).c2,c3=this.calculateControlPoints(points[1],points[2],points[3]).c1;return new _Bezier(points[1],c2,c3,points[2],widths.start,widths.end)}static calculateControlPoints(s1,s2,s3){let dx1=s1.x-s2.x,dy1=s1.y-s2.y,dx2=s2.x-s3.x,dy2=s2.y-s3.y,m1={x:(s1.x+s2.x)/2,y:(s1.y+s2.y)/2},m2={x:(s2.x+s3.x)/2,y:(s2.y+s3.y)/2},l1=Math.sqrt(dx1*dx1+dy1*dy1),l2=Math.sqrt(dx2*dx2+dy2*dy2),dxm=m1.x-m2.x,dym=m1.y-m2.y,k=l1+l2==0?0:l2/(l1+l2),cm={x:m2.x+dxm*k,y:m2.y+dym*k},tx=s2.x-cm.x,ty=s2.y-cm.y;return{c1:new Point(m1.x+tx,m1.y+ty),c2:new Point(m2.x+tx,m2.y+ty)}}length(){let length=0,px,py;for(let i=0;i<=10;i+=1){let t=i/10,cx=this.point(t,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),cy=this.point(t,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(i>0){let xdiff=cx-px,ydiff=cy-py;length+=Math.sqrt(xdiff*xdiff+ydiff*ydiff)}px=cx,py=cy}return length}point(t,start,c1,c2,end){return start*(1-t)*(1-t)*(1-t)+3*c1*(1-t)*(1-t)*t+3*c2*(1-t)*t*t+end*t*t*t}},SignatureEventTarget=class{constructor(){__publicField(this,"_et");try{this._et=new EventTarget}catch{this._et=document}}addEventListener(type,listener,options){this._et.addEventListener(type,listener,options)}dispatchEvent(event){return this._et.dispatchEvent(event)}removeEventListener(type,callback,options){this._et.removeEventListener(type,callback,options)}};function throttle(fn,wait=250){let previous=0,timeout=null,result,storedContext,storedArgs,later=()=>{previous=Date.now(),timeout=null,result=fn.apply(storedContext,storedArgs),timeout||(storedContext=null,storedArgs=[])};return function(...args){let now=Date.now(),remaining=wait-(now-previous);return storedContext=this,storedArgs=args,remaining<=0||remaining>wait?(timeout&&(clearTimeout(timeout),timeout=null),previous=now,result=fn.apply(storedContext,storedArgs),timeout||(storedContext=null,storedArgs=[])):timeout||(timeout=window.setTimeout(later,remaining)),result}}var SignaturePad=class _SignaturePad extends SignatureEventTarget{constructor(canvas,options={}){super();__publicField(this,"dotSize");__publicField(this,"minWidth");__publicField(this,"maxWidth");__publicField(this,"penColor");__publicField(this,"minDistance");__publicField(this,"velocityFilterWeight");__publicField(this,"compositeOperation");__publicField(this,"backgroundColor");__publicField(this,"throttle");__publicField(this,"canvasContextOptions");__publicField(this,"_ctx");__publicField(this,"_drawingStroke",!1);__publicField(this,"_isEmpty",!0);__publicField(this,"_dataUrl");__publicField(this,"_dataUrlOptions");__publicField(this,"_lastPoints",[]);__publicField(this,"_data",[]);__publicField(this,"_lastVelocity",0);__publicField(this,"_lastWidth",0);__publicField(this,"_strokeMoveUpdate");__publicField(this,"_strokePointerId");this.canvas=canvas,this.velocityFilterWeight=options.velocityFilterWeight||.7,this.minWidth=options.minWidth||.5,this.maxWidth=options.maxWidth||2.5,this.throttle=options.throttle??16,this.minDistance=options.minDistance??5,this.dotSize=options.dotSize||0,this.penColor=options.penColor||"black",this.backgroundColor=options.backgroundColor||"rgba(0,0,0,0)",this.compositeOperation=options.compositeOperation||"source-over",this.canvasContextOptions=options.canvasContextOptions??{},this._strokeMoveUpdate=this.throttle?throttle(_SignaturePad.prototype._strokeUpdate,this.throttle):_SignaturePad.prototype._strokeUpdate,this._handleMouseDown=this._handleMouseDown.bind(this),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this._handleTouchStart=this._handleTouchStart.bind(this),this._handleTouchMove=this._handleTouchMove.bind(this),this._handleTouchEnd=this._handleTouchEnd.bind(this),this._handlePointerDown=this._handlePointerDown.bind(this),this._handlePointerMove=this._handlePointerMove.bind(this),this._handlePointerUp=this._handlePointerUp.bind(this),this._handlePointerCancel=this._handlePointerCancel.bind(this),this._handleTouchCancel=this._handleTouchCancel.bind(this),this._ctx=canvas.getContext("2d",this.canvasContextOptions),this.clear(),this.on()}clear(){let{_ctx:ctx,canvas}=this;ctx.fillStyle=this.backgroundColor,ctx.clearRect(0,0,canvas.width,canvas.height),ctx.fillRect(0,0,canvas.width,canvas.height),this._data=[],this._reset(this._getPointGroupOptions()),this._isEmpty=!0,this._dataUrl=void 0,this._dataUrlOptions=void 0,this._strokePointerId=void 0}redraw(){let data2=this._data,dataUrl=this._dataUrl,dataUrlOptions=this._dataUrlOptions;this.clear(),dataUrl&&this.fromDataURL(dataUrl,dataUrlOptions),this.fromData(data2,{clear:!1})}fromDataURL(dataUrl,options={}){return new Promise((resolve,reject)=>{let image=new Image,ratio=options.ratio||window.devicePixelRatio||1,width=options.width||this.canvas.width/ratio,height=options.height||this.canvas.height/ratio,xOffset=options.xOffset||0,yOffset=options.yOffset||0;this._reset(this._getPointGroupOptions()),image.onload=()=>{this._ctx.drawImage(image,xOffset,yOffset,width,height),resolve()},image.onerror=error=>{reject(error)},image.crossOrigin="anonymous",image.src=dataUrl,this._isEmpty=!1,this._dataUrl=dataUrl,this._dataUrlOptions={...options}})}toDataURL(type="image/png",encoderOptions){return type==="image/svg+xml"?(typeof encoderOptions!="object"&&(encoderOptions=void 0),`data:image/svg+xml;base64,${btoa(this.toSVG(encoderOptions))}`):(typeof encoderOptions!="number"&&(encoderOptions=void 0),this.canvas.toDataURL(type,encoderOptions))}on(){this.canvas.style.touchAction="none",this.canvas.style.msTouchAction="none",this.canvas.style.userSelect="none",this.canvas.style.webkitUserSelect="none";let isIOS=/Macintosh/.test(navigator.userAgent)&&"ontouchstart"in document;window.PointerEvent&&!isIOS?this._handlePointerEvents():(this._handleMouseEvents(),"ontouchstart"in window&&this._handleTouchEvents())}off(){this.canvas.style.touchAction="auto",this.canvas.style.msTouchAction="auto",this.canvas.style.userSelect="auto",this.canvas.style.webkitUserSelect="auto",this.canvas.removeEventListener("pointerdown",this._handlePointerDown),this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this._removeMoveUpEventListeners()}_getListenerFunctions(){let canvasWindow=window.document===this.canvas.ownerDocument?window:this.canvas.ownerDocument.defaultView??this.canvas.ownerDocument;return{addEventListener:canvasWindow.addEventListener.bind(canvasWindow),removeEventListener:canvasWindow.removeEventListener.bind(canvasWindow)}}_removeMoveUpEventListeners(){let{removeEventListener}=this._getListenerFunctions();removeEventListener("pointermove",this._handlePointerMove),removeEventListener("pointerup",this._handlePointerUp),removeEventListener("pointercancel",this._handlePointerCancel),removeEventListener("mousemove",this._handleMouseMove),removeEventListener("mouseup",this._handleMouseUp),removeEventListener("touchmove",this._handleTouchMove),removeEventListener("touchend",this._handleTouchEnd),removeEventListener("touchcancel",this._handleTouchCancel)}isEmpty(){return this._isEmpty}fromData(pointGroups,{clear=!0}={}){clear&&this.clear(),this._fromData(pointGroups,this._drawCurve.bind(this),this._drawDot.bind(this)),this._data=this._data.concat(pointGroups)}toData(){return this._data}_isLeftButtonPressed(event,only){return only?event.buttons===1:(event.buttons&1)===1}_pointerEventToSignatureEvent(event){return{event,type:event.type,x:event.clientX,y:event.clientY,pressure:"pressure"in event?event.pressure:0}}_touchEventToSignatureEvent(event){let touch=event.changedTouches[0];return{event,type:event.type,x:touch.clientX,y:touch.clientY,pressure:touch.force}}_handleMouseDown(event){!this._isLeftButtonPressed(event,!0)||this._drawingStroke||this._strokeBegin(this._pointerEventToSignatureEvent(event))}_handleMouseMove(event){if(!this._isLeftButtonPressed(event,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(event),!1);return}this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event))}_handleMouseUp(event){this._isLeftButtonPressed(event)||this._strokeEnd(this._pointerEventToSignatureEvent(event))}_handleTouchStart(event){event.targetTouches.length!==1||this._drawingStroke||(event.cancelable&&event.preventDefault(),this._strokeBegin(this._touchEventToSignatureEvent(event)))}_handleTouchMove(event){if(event.targetTouches.length===1){if(event.cancelable&&event.preventDefault(),!this._drawingStroke){this._strokeEnd(this._touchEventToSignatureEvent(event),!1);return}this._strokeMoveUpdate(this._touchEventToSignatureEvent(event))}}_handleTouchEnd(event){event.targetTouches.length===0&&(event.cancelable&&event.preventDefault(),this._strokeEnd(this._touchEventToSignatureEvent(event)))}_handlePointerCancel(event){this._allowPointerId(event)&&(event.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(event),!1))}_handleTouchCancel(event){event.cancelable&&event.preventDefault(),this._strokeEnd(this._touchEventToSignatureEvent(event),!1)}_getPointerId(event){return event.persistentDeviceId||event.pointerId}_allowPointerId(event,allowUndefined=!1){return typeof this._strokePointerId>"u"?allowUndefined:this._getPointerId(event)===this._strokePointerId}_handlePointerDown(event){this._drawingStroke||!this._isLeftButtonPressed(event)||!this._allowPointerId(event,!0)||(this._strokePointerId=this._getPointerId(event),event.preventDefault(),this._strokeBegin(this._pointerEventToSignatureEvent(event)))}_handlePointerMove(event){if(this._allowPointerId(event)){if(!this._isLeftButtonPressed(event,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(event),!1);return}event.preventDefault(),this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event))}}_handlePointerUp(event){this._isLeftButtonPressed(event)||!this._allowPointerId(event)||(event.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(event)))}_getPointGroupOptions(group){return{penColor:group&&"penColor"in group?group.penColor:this.penColor,dotSize:group&&"dotSize"in group?group.dotSize:this.dotSize,minWidth:group&&"minWidth"in group?group.minWidth:this.minWidth,maxWidth:group&&"maxWidth"in group?group.maxWidth:this.maxWidth,velocityFilterWeight:group&&"velocityFilterWeight"in group?group.velocityFilterWeight:this.velocityFilterWeight,compositeOperation:group&&"compositeOperation"in group?group.compositeOperation:this.compositeOperation}}_strokeBegin(event){if(!this.dispatchEvent(new CustomEvent("beginStroke",{detail:event,cancelable:!0})))return;let{addEventListener}=this._getListenerFunctions();switch(event.event.type){case"mousedown":addEventListener("mousemove",this._handleMouseMove,{passive:!1}),addEventListener("mouseup",this._handleMouseUp,{passive:!1});break;case"touchstart":addEventListener("touchmove",this._handleTouchMove,{passive:!1}),addEventListener("touchend",this._handleTouchEnd,{passive:!1}),addEventListener("touchcancel",this._handleTouchCancel,{passive:!1});break;case"pointerdown":addEventListener("pointermove",this._handlePointerMove,{passive:!1}),addEventListener("pointerup",this._handlePointerUp,{passive:!1}),addEventListener("pointercancel",this._handlePointerCancel,{passive:!1});break;default:}this._drawingStroke=!0;let pointGroupOptions=this._getPointGroupOptions(),newPointGroup={...pointGroupOptions,points:[]};this._data.push(newPointGroup),this._reset(pointGroupOptions),this._strokeUpdate(event)}_strokeUpdate(event){if(!this._drawingStroke)return;if(this._data.length===0){this._strokeBegin(event);return}this.dispatchEvent(new CustomEvent("beforeUpdateStroke",{detail:event}));let point=this._createPoint(event.x,event.y,event.pressure),lastPointGroup=this._data[this._data.length-1],lastPoints=lastPointGroup.points,lastPoint=lastPoints.length>0&&lastPoints[lastPoints.length-1],isLastPointTooClose=lastPoint?point.distanceTo(lastPoint)<=this.minDistance:!1,pointGroupOptions=this._getPointGroupOptions(lastPointGroup);if(!lastPoint||!(lastPoint&&isLastPointTooClose)){let curve=this._addPoint(point,pointGroupOptions);lastPoint?curve&&this._drawCurve(curve,pointGroupOptions):this._drawDot(point,pointGroupOptions),lastPoints.push({time:point.time,x:point.x,y:point.y,pressure:point.pressure})}this.dispatchEvent(new CustomEvent("afterUpdateStroke",{detail:event}))}_strokeEnd(event,shouldUpdate=!0){this._removeMoveUpEventListeners(),this._drawingStroke&&(shouldUpdate&&this._strokeUpdate(event),this._drawingStroke=!1,this._strokePointerId=void 0,this.dispatchEvent(new CustomEvent("endStroke",{detail:event})))}_handlePointerEvents(){this._drawingStroke=!1,this.canvas.addEventListener("pointerdown",this._handlePointerDown,{passive:!1})}_handleMouseEvents(){this._drawingStroke=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown,{passive:!1})}_handleTouchEvents(){this.canvas.addEventListener("touchstart",this._handleTouchStart,{passive:!1})}_reset(options){this._lastPoints=[],this._lastVelocity=0,this._lastWidth=(options.minWidth+options.maxWidth)/2,this._ctx.fillStyle=options.penColor,this._ctx.globalCompositeOperation=options.compositeOperation}_createPoint(x,y,pressure){let rect=this.canvas.getBoundingClientRect();return new Point(x-rect.left,y-rect.top,pressure,new Date().getTime())}_addPoint(point,options){let{_lastPoints}=this;if(_lastPoints.push(point),_lastPoints.length>2){_lastPoints.length===3&&_lastPoints.unshift(_lastPoints[0]);let widths=this._calculateCurveWidths(_lastPoints[1],_lastPoints[2],options),curve=Bezier.fromPoints(_lastPoints,widths);return _lastPoints.shift(),curve}return null}_calculateCurveWidths(startPoint,endPoint,options){let velocity=options.velocityFilterWeight*endPoint.velocityFrom(startPoint)+(1-options.velocityFilterWeight)*this._lastVelocity,newWidth=this._strokeWidth(velocity,options),widths={end:newWidth,start:this._lastWidth};return this._lastVelocity=velocity,this._lastWidth=newWidth,widths}_strokeWidth(velocity,options){return Math.max(options.maxWidth/(velocity+1),options.minWidth)}_drawCurveSegment(x,y,width){let ctx=this._ctx;ctx.moveTo(x,y),ctx.arc(x,y,width,0,2*Math.PI,!1),this._isEmpty=!1}_drawCurve(curve,options){let ctx=this._ctx,widthDelta=curve.endWidth-curve.startWidth,drawSteps=Math.ceil(curve.length())*2;ctx.beginPath(),ctx.fillStyle=options.penColor;for(let i=0;i<drawSteps;i+=1){let t=i/drawSteps,tt=t*t,ttt=tt*t,u=1-t,uu=u*u,uuu=uu*u,x=uuu*curve.startPoint.x;x+=3*uu*t*curve.control1.x,x+=3*u*tt*curve.control2.x,x+=ttt*curve.endPoint.x;let y=uuu*curve.startPoint.y;y+=3*uu*t*curve.control1.y,y+=3*u*tt*curve.control2.y,y+=ttt*curve.endPoint.y;let width=Math.min(curve.startWidth+ttt*widthDelta,options.maxWidth);this._drawCurveSegment(x,y,width)}ctx.closePath(),ctx.fill()}_drawDot(point,options){let ctx=this._ctx,width=options.dotSize>0?options.dotSize:(options.minWidth+options.maxWidth)/2;ctx.beginPath(),this._drawCurveSegment(point.x,point.y,width),ctx.closePath(),ctx.fillStyle=options.penColor,ctx.fill()}_fromData(pointGroups,drawCurve,drawDot){for(let group of pointGroups){let{points}=group,pointGroupOptions=this._getPointGroupOptions(group);if(points.length>1)for(let j=0;j<points.length;j+=1){let basicPoint=points[j],point=new Point(basicPoint.x,basicPoint.y,basicPoint.pressure,basicPoint.time);j===0&&this._reset(pointGroupOptions);let curve=this._addPoint(point,pointGroupOptions);curve&&drawCurve(curve,pointGroupOptions)}else this._reset(pointGroupOptions),drawDot(points[0],pointGroupOptions)}}toSVG({includeBackgroundColor=!1,includeDataUrl=!1}={}){let pointGroups=this._data,ratio=Math.max(window.devicePixelRatio||1,1),minX=0,minY=0,maxX=this.canvas.width/ratio,maxY=this.canvas.height/ratio,svg=document.createElementNS("http://www.w3.org/2000/svg","svg");if(svg.setAttribute("xmlns","http://www.w3.org/2000/svg"),svg.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),svg.setAttribute("viewBox",`${minX} ${minY} ${maxX} ${maxY}`),svg.setAttribute("width",maxX.toString()),svg.setAttribute("height",maxY.toString()),includeBackgroundColor&&this.backgroundColor){let rect=document.createElement("rect");rect.setAttribute("width","100%"),rect.setAttribute("height","100%"),rect.setAttribute("fill",this.backgroundColor),svg.appendChild(rect)}if(includeDataUrl&&this._dataUrl){let ratio2=this._dataUrlOptions?.ratio||window.devicePixelRatio||1,width=this._dataUrlOptions?.width||this.canvas.width/ratio2,height=this._dataUrlOptions?.height||this.canvas.height/ratio2,xOffset=this._dataUrlOptions?.xOffset||0,yOffset=this._dataUrlOptions?.yOffset||0,image=document.createElement("image");image.setAttribute("x",xOffset.toString()),image.setAttribute("y",yOffset.toString()),image.setAttribute("width",width.toString()),image.setAttribute("height",height.toString()),image.setAttribute("preserveAspectRatio","none"),image.setAttribute("href",this._dataUrl),svg.appendChild(image)}return this._fromData(pointGroups,(curve,{penColor})=>{let path=document.createElement("path");if(!isNaN(curve.control1.x)&&!isNaN(curve.control1.y)&&!isNaN(curve.control2.x)&&!isNaN(curve.control2.y)){let attr=`M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(3)} C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;path.setAttribute("d",attr),path.setAttribute("stroke-width",(curve.endWidth*2.25).toFixed(3)),path.setAttribute("stroke",penColor),path.setAttribute("fill","none"),path.setAttribute("stroke-linecap","round"),svg.appendChild(path)}},(point,{penColor,dotSize,minWidth,maxWidth})=>{let circle=document.createElement("circle"),size=dotSize>0?dotSize:(minWidth+maxWidth)/2;circle.setAttribute("r",size.toString()),circle.setAttribute("cx",point.x.toString()),circle.setAttribute("cy",point.y.toString()),circle.setAttribute("fill",penColor),svg.appendChild(circle)}),svg.outerHTML}};import{jsx as jsx96,jsxs as jsxs57}from"react/jsx-runtime";function SignatureInput(props){let medplum=useMedplum26(),{width=500,height=200,defaultValue:defaultValue2,who,onChange,...rest}=props,canvasRef=useRef11(null),signaturePadRef=useRef11(null),onChangeRef=useRef11(onChange);return useLayoutEffect2(()=>{onChangeRef.current=onChange}),useEffect18(()=>{function handleEndStroke(){onChangeRef.current?.({type:[{system:HTTP_HL7_ORG2+"/fhir/signature-type",code:"ProofOfOrigin",display:"Proof of Origin"}],when:new Date().toISOString(),who:who??createReference4(medplum.getProfile()),data:signaturePadRef.current?.toDataURL().split(",")[1]})}if(canvasRef.current){let signaturePad=new SignaturePad(canvasRef.current);defaultValue2?.data&&signaturePad.fromDataURL(defaultValue2.data).catch(console.error),signaturePad.addEventListener("endStroke",handleEndStroke),signaturePadRef.current=signaturePad}return()=>{signaturePadRef.current&&signaturePadRef.current.removeEventListener("beginStroke",handleEndStroke)}},[medplum,defaultValue2,who]),jsxs57(Paper3,{withBorder:!0,p:0,w:width,h:height,pos:"relative",...rest,children:[jsx96("canvas",{ref:canvasRef,width,height,"aria-label":"Signature input area"}),jsx96(Button9,{onClick:()=>{signaturePadRef.current&&signaturePadRef.current.clear(),onChangeRef.current?.(void 0)},"aria-label":"Clear signature",pos:"absolute",top:0,right:0,size:"xs",leftSection:jsx96(IconTrash,{size:16}),variant:"subtle",color:"gray",children:"Clear"})]})}import{Stack as Stack23}from"@mantine/core";import{isQuestionEnabled,QuestionnaireItemType as QuestionnaireItemType3}from"@medplum/react-hooks";import{Title as Title9}from"@mantine/core";import{jsx as jsx97,jsxs as jsxs58}from"react/jsx-runtime";function QuestionnaireFormGroup(props){let newContext=[...props.context,props.responseItem];return jsxs58("div",{children:[props.item.text&&jsx97(Title9,{order:3,mb:"md",children:props.item.text}),jsx97(QuestionnaireFormItemArray,{formState:props.formState,context:newContext,items:props.item.item??[],responseItems:props.responseItem.item??[]})]},props.item.linkId)}import{Checkbox as Checkbox5,Group as Group31,MultiSelect,NativeSelect as NativeSelect10,Radio,Text as Text20,Textarea as Textarea3,TextInput as TextInput21}from"@mantine/core";import{capitalize as capitalize3,deepEquals,formatCoding as formatCoding2,getElementDefinition,getExtension,HTTP_HL7_ORG as HTTP_HL7_ORG3,stringify as stringify2,typedValueToString}from"@medplum/core";import{getItemAnswerOptionValue,getItemInitialValue,getNewMultiSelectValues,getQuestionnaireItemReferenceFilter,getQuestionnaireItemReferenceTargetTypes,QUESTIONNAIRE_ITEM_CONTROL_URL,QuestionnaireItemType,useMedplum as useMedplum27}from"@medplum/react-hooks";import{useEffect as useEffect19,useState as useState55}from"react";import{Fragment as Fragment31,jsx as jsx98,jsxs as jsxs59}from"react/jsx-runtime";var MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS=30,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS=50;function QuestionnaireFormItem(props){let formState=props.formState,item=props.item,response=props.responseItem;function onChangeAnswer(newResponseAnswer){if(formState&&props.context)if(item.repeats&&props.index!==void 0&&item.type!==QuestionnaireItemType.choice&&item.type!==QuestionnaireItemType.openChoice){let updatedAnswers=[...response.answer||[]];newResponseAnswer.length===0?updatedAnswers.splice(props.index,1):updatedAnswers[props.index]=newResponseAnswer[0],formState.onChangeAnswer(props.context,props.item,updatedAnswers)}else formState.onChangeAnswer(props.context,props.item,newResponseAnswer)}let type=item.type;if(!type)return null;let name=item.linkId;if(!name)return null;let inputId=item.repeats&&props.index!==void 0&&item.type!==QuestionnaireItemType.choice&&item.type!==QuestionnaireItemType.openChoice?`${name}-${props.index}`:name,initial;item.initial&&item.initial.length>0?initial=item.initial[0]:item.answerOption&&item.answerOption.length>0&&(initial=item.answerOption.find(option=>option.initialSelected));let defaultValue2=getCurrentAnswer(response,props.index)??getItemInitialValue(initial),validationError=getExtension(response,`${HTTP_HL7_ORG3}/fhir/StructureDefinition/questionnaire-validationError`),formComponent=null;switch(type){case QuestionnaireItemType.display:formComponent=jsx98("p",{children:props.item.text},props.item.linkId);break;case QuestionnaireItemType.boolean:formComponent=jsx98(CheckboxFormSection,{title:props.item.text,htmlFor:inputId,children:jsx98(Checkbox5,{id:inputId,name,required:props.required??item.required,defaultChecked:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueBoolean:e.currentTarget.checked}])})},props.item.linkId);break;case QuestionnaireItemType.decimal:formComponent=jsx98(TextInput21,{type:"number",step:"any",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer(e.currentTarget.value===""?[]:[{valueDecimal:e.currentTarget.valueAsNumber}])});break;case QuestionnaireItemType.integer:formComponent=jsx98(TextInput21,{type:"number",step:1,id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer(e.currentTarget.value===""?[]:[{valueInteger:e.currentTarget.valueAsNumber}])});break;case QuestionnaireItemType.date:formComponent=jsx98(TextInput21,{type:"date",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueDate:e.currentTarget.value}])});break;case QuestionnaireItemType.dateTime:formComponent=jsx98(DateTimeInput,{name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueDateTime:newValue}])});break;case QuestionnaireItemType.time:formComponent=jsx98(TextInput21,{type:"time",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueTime:e.currentTarget.value}])});break;case QuestionnaireItemType.string:case QuestionnaireItemType.url:formComponent=jsx98(TextInput21,{id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>{let value=e.currentTarget.value;onChangeAnswer(value===""?[]:[{valueString:value}])}});break;case QuestionnaireItemType.text:formComponent=jsx98(Textarea3,{id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>{let value=e.currentTarget.value;onChangeAnswer(value===""?[]:[{valueString:value}])}});break;case QuestionnaireItemType.attachment:formComponent=jsx98(Group31,{py:4,children:jsx98(AttachmentInput,{path:"",name:inputId,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueAttachment:newValue}])})});break;case QuestionnaireItemType.reference:formComponent=jsx98(ReferenceInput,{name:inputId,required:props.required??item.required,targetTypes:getQuestionnaireItemReferenceTargetTypes(item),searchCriteria:getQuestionnaireItemReferenceFilter(item,formState?.subject,formState?.encounter),defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueReference:newValue}])});break;case QuestionnaireItemType.quantity:formComponent=jsx98(QuantityInput,{path:"",name:inputId,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueQuantity:newValue}]),disableWheel:!0});break;case QuestionnaireItemType.choice:case QuestionnaireItemType.openChoice:{let{widget,multiselect}=resolveChoiceControl(item),sharedProps={name:inputId,item,required:props.required??item.required,initial,response,multiselect,onChangeAnswer};widget==="check-box"?formComponent=jsx98(QuestionnaireCheckboxInput,{...sharedProps}):widget==="drop-down"?formComponent=jsx98(QuestionnaireDropdownInput,{...sharedProps}):formComponent=jsx98(QuestionnaireRadioButtonInput,{...sharedProps})}break;default:return null}return jsxs59(Fragment31,{children:[formComponent,validationError?.valueString&&jsx98(Text20,{c:"red",size:"lg",mt:4,children:validationError.valueString})]})}function QuestionnaireDropdownInput(props){let{name,item,required,initial,onChangeAnswer,response,multiselect}=props;if(!item.answerOption?.length&&!item.answerValueSet)return jsx98(NoAnswerDisplay,{});let initialValue=getItemInitialValue(initial),defaultValue2=getCurrentAnswer(response)??initialValue,currentAnswer=getCurrentMultiSelectAnswer(response),isMultiSelect=item.repeats||multiselect;if(item.answerValueSet)return jsx98(ValueSetAutocomplete,{name,placeholder:"Select items",binding:item.answerValueSet,maxValues:isMultiSelect?void 0:1,required,onChange:values=>{isMultiSelect?values.length===0?onChangeAnswer([{}]):onChangeAnswer(values.map(coding=>({valueCoding:coding}))):onChangeAnswer([{valueCoding:values[0]}])},defaultValue:defaultValue2?.value});if(isMultiSelect){let{propertyName,data:data2}=formatSelectData(item);return jsx98(MultiSelect,{data:data2,placeholder:"Select items",searchable:!0,defaultValue:currentAnswer||[typedValueToString(initialValue)],required,onChange:selected=>{if(selected.length===0)onChangeAnswer([{}]);else{let values=getNewMultiSelectValues(selected,propertyName,item);onChangeAnswer(values)}}})}else{let data2=[""];if(item.answerOption)for(let option of item.answerOption){let optionValue=getItemAnswerOptionValue(option);data2.push(typedValueToString(optionValue))}return jsx98(NativeSelect10,{id:name,name,required,onChange:e=>{let index=e.currentTarget.selectedIndex;if(index===0){onChangeAnswer([{}]);return}let option=item.answerOption[index-1],optionValue=getItemAnswerOptionValue(option),propertyName="value"+capitalize3(optionValue.type);onChangeAnswer([{[propertyName]:optionValue.value}])},defaultValue:formatCoding2(defaultValue2?.value)||defaultValue2?.value,data:data2})}}function getValueSetOptions(valueSetUrl,medplum){return valueSetUrl?medplum.valueSetExpand({url:valueSetUrl,count:MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS+1}).then(valueSet=>valueSet.expansion?.contains??[]):Promise.resolve([])}function useValueSetOptions(valueSetUrl){let medplum=useMedplum27(),[valueSetOptions,setValueSetOptions]=useState55([]),[isLoading,setIsLoading]=useState55(!1);return useEffect19(()=>{async function loadValueSet(){if(valueSetUrl){setIsLoading(!0);try{let options=await getValueSetOptions(valueSetUrl,medplum);setValueSetOptions(options)}catch(err){console.error("Error loading value set:",err)}finally{setIsLoading(!1)}}}loadValueSet().catch(console.error)},[valueSetUrl,medplum]),[valueSetOptions,isLoading]}function getOptionsFromValueSet(valueSetOptions,name){return valueSetOptions.map((option,i)=>{let optionName=`${name}-valueset-${i}`,optionValue={type:"Coding",value:{system:option.system,code:option.code,display:option.display}};return[optionName,optionValue]})}function QuestionnaireRadioButtonInput(props){let{name,item,required,initial,onChangeAnswer,response}=props,valueElementDefinition=getElementDefinition("QuestionnaireItemAnswerOption","value[x]"),initialValue=getItemInitialValue(initial),[valueSetOptions,isLoading]=useValueSetOptions(item.answerValueSet),options=[],defaultValue2;if(item.answerValueSet)options.push(...getOptionsFromValueSet(valueSetOptions,name));else if(item.answerOption){let mappedOptions=item.answerOption.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS).map((option,i)=>{let optionName=`${name}-option-${i}`,optionValue=getItemAnswerOptionValue(option);return optionValue?.value?(initialValue&&stringify2(optionValue)===stringify2(initialValue)&&(defaultValue2=optionName),[optionName,optionValue]):null}).filter(option=>option!==null);options.push(...mappedOptions)}let defaultAnswer=getCurrentAnswer(response),answerLinkId=getCurrentRadioAnswer(options,defaultAnswer);if(isLoading)return jsx98(Text20,{children:"Loading options..."});if(options.length===0)return jsx98(NoAnswerDisplay,{});let limitedOptions=options.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS);return jsxs59(Fragment31,{children:[jsx98(Radio.Group,{name,value:answerLinkId??defaultValue2,required,onChange:newValue=>{let option=options.find(option2=>option2[0]===newValue);if(option){let optionValue=option[1],propertyName="value"+capitalize3(optionValue.type);onChangeAnswer([{[propertyName]:optionValue.value}])}},children:limitedOptions.map(([optionName,optionValue])=>jsx98(Radio,{id:optionName,value:optionName,py:4,required,label:jsx98(ResourcePropertyDisplay,{property:valueElementDefinition,propertyType:optionValue.type,value:optionValue.value})},optionName))}),(item.answerValueSet&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS||item.answerOption&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)&&jsxs59(Text20,{size:"sm",c:"dimmed",mt:"xs",children:["Showing first ",MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS," options"]})]})}function QuestionnaireCheckboxInput(props){let{name,item,onChangeAnswer,response}=props,valueElementDefinition=getElementDefinition("QuestionnaireItemAnswerOption","value[x]"),[valueSetOptions,isLoading]=useValueSetOptions(item.answerValueSet),initialSelectedValues=item.answerValueSet?(response?.answer?.map(a=>a.valueCoding)||[]).filter(c=>c!==void 0):getCurrentMultiSelectAnswer(response),[selectedValues,setSelectedValues]=useState55(initialSelectedValues),options=[];if(item.answerValueSet)options.push(...getOptionsFromValueSet(valueSetOptions,name));else if(item.answerOption){let mappedOptions=item.answerOption.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS).map((option,i)=>{let optionName=`${name}-option-${i}`,optionValue=getItemAnswerOptionValue(option);return optionValue?.value?[optionName,optionValue]:null}).filter(option=>option!==null);options.push(...mappedOptions)}if(isLoading)return jsx98(Text20,{children:"Loading options..."});if(options.length===0)return jsx98(NoAnswerDisplay,{});let limitedOptions=options.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS),handleCheckboxChange=(optionValue,selected)=>{if(item.answerValueSet){let currentCodings=selectedValues,newCodings;selected?newCodings=[...currentCodings,optionValue.value]:newCodings=currentCodings.filter(c=>!deepEquals(c,optionValue.value)),setSelectedValues(newCodings),newCodings.length===0?onChangeAnswer([{}]):onChangeAnswer(newCodings.map(coding=>({valueCoding:coding})))}else{let currentValues=selectedValues,optionValueStr=typedValueToString(optionValue),newValues;if(selected?newValues=[...currentValues,optionValueStr]:newValues=currentValues.filter(v=>v!==optionValueStr),setSelectedValues(newValues),newValues.length===0)onChangeAnswer([{}]);else{let values=getNewMultiSelectValues(newValues,"value"+capitalize3(optionValue.type),item);onChangeAnswer(values)}}};return jsxs59(Group31,{style:{flexDirection:"column",alignItems:"flex-start"},children:[limitedOptions.map(([optionName,optionValue])=>{let optionValueStr=typedValueToString(optionValue),isChecked=item.answerValueSet?selectedValues.some(coding=>deepEquals(coding,optionValue.value)):selectedValues.includes(optionValueStr);return jsx98(Checkbox5,{id:optionName,label:jsx98(ResourcePropertyDisplay,{property:valueElementDefinition,propertyType:optionValue.type,value:optionValue.value}),checked:isChecked,onChange:event=>handleCheckboxChange(optionValue,event.currentTarget.checked)},optionName)}),(item.answerValueSet&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS||item.answerOption&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)&&jsxs59(Text20,{size:"sm",c:"dimmed",children:["Showing first ",MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS," options"]})]})}function NoAnswerDisplay(){return jsx98(TextInput21,{disabled:!0,placeholder:"No Answers Defined"})}function getCurrentAnswer(response,index=0){return getItemAnswerOptionValue(response?.answer?.[index]??{})}function getCurrentMultiSelectAnswer(response){let results=response?.answer;return results?results.map(a=>getItemAnswerOptionValue(a)).map(type=>formatCoding2(type?.value)||type?.value).filter(Boolean):[]}function getCurrentRadioAnswer(options,defaultAnswer){return options.find(option=>deepEquals(option[1].value,defaultAnswer?.value))?.[0]}var choiceTypes=["drop-down","radio-button","check-box"];function resolveChoiceControl(item){let widget="radio-button",multiselect=!1;item.answerValueSet&&(widget="drop-down");for(let ext of item.extension??[]){if(ext.url!==QUESTIONNAIRE_ITEM_CONTROL_URL)continue;let code=ext.valueCodeableConcept?.coding?.[0]?.code;choiceTypes.includes(code)&&(widget=code),code==="multi-select"&&(multiselect=!0)}return widget==="radio-button"&&multiselect&&(widget="check-box"),{widget,multiselect}}function formatSelectData(item){if(item.answerOption?.length===0)return{propertyName:"",data:[]};let option=item.answerOption[0],optionValue=getItemAnswerOptionValue(option),propertyName="value"+capitalize3(optionValue.type),data2=(item.answerOption??[]).map(answerOption=>{let answerOptionValue=getItemAnswerOptionValue(answerOption),answerOptionValueStr=typedValueToString(answerOptionValue);return{value:answerOptionValueStr,label:answerOptionValueStr}});return{propertyName,data:data2}}import{Anchor as Anchor9}from"@mantine/core";import{Fragment as Fragment32,jsx as jsx99,jsxs as jsxs60}from"react/jsx-runtime";function QuestionnaireFormRepeatableGroup(props){return jsxs60(Fragment32,{children:[props.responseItems.map(response=>jsx99(QuestionnaireFormGroup,{formState:props.formState,context:props.context,item:props.item,responseItem:response},`group-${response.id}`)),jsx99(Anchor9,{onClick:()=>props.formState.onAddGroup(props.context,props.item),children:`Add Group: ${props.item.text}`})]})}import{Anchor as Anchor10,Stack as Stack22}from"@mantine/core";import{QuestionnaireItemType as QuestionnaireItemType2}from"@medplum/react-hooks";import{jsx as jsx100,jsxs as jsxs61}from"react/jsx-runtime";function QuestionnaireFormRepeatableItem(props){let{formState,context,item,responseItem}=props,isChoiceType=item.type===QuestionnaireItemType2.choice||item.type===QuestionnaireItemType2.openChoice,showAddButton=!isChoiceType,answers=!isChoiceType&&responseItem.answer&&responseItem.answer.length>0?responseItem.answer:[{}];return jsxs61(FormSection,{title:props.item.text,withAsterisk:props.item.required,children:[jsx100(Stack22,{gap:"xs",children:answers?.map((_,index)=>jsx100(QuestionnaireFormItem,{formState,context,item,responseItem,index},`${item.linkId}-${index}`))}),showAddButton&&jsx100(Anchor10,{onClick:()=>formState.onAddAnswer(context,item),children:"Add Item"})]},props.item.linkId)}import{jsx as jsx101}from"react/jsx-runtime";function QuestionnaireFormItemArray(props){let{formState,context,items,responseItems}=props;return jsx101(Stack23,{children:items.map((item,index)=>{if(!isQuestionEnabled(item,formState.questionnaireResponse))return null;if(item.type===QuestionnaireItemType3.display)return jsx101("p",{children:item.text},`display-${item.id}-${index}`);let filteredResponseItems=responseItems.filter(responseItem=>responseItem.linkId===item.linkId);return item.type===QuestionnaireItemType3.group&&item.repeats?jsx101(QuestionnaireFormRepeatableGroup,{formState,context,item,responseItems:filteredResponseItems},`repeating-group-${item.id}-${index}`):item.type===QuestionnaireItemType3.group?jsx101(QuestionnaireFormGroup,{formState,context,item,responseItem:filteredResponseItems[0]},`group-${item.id}-${index}`):item.type===QuestionnaireItemType3.boolean?jsx101(QuestionnaireFormItem,{formState,context,item,responseItem:filteredResponseItems[0],index:0},`boolean-item-${item.id}-${index}`):item.repeats?jsx101(QuestionnaireFormRepeatableItem,{formState,context,item,responseItem:filteredResponseItems[0]},`repeating-item-${item.id}-${index}`):jsx101(FormSection,{htmlFor:item.linkId,title:item.text,withAsterisk:item.required,children:jsx101(QuestionnaireFormItem,{formState,context,item,responseItem:filteredResponseItems[0],index:0})},`repeating-item-${item.id}-${index}`)})})}import{Button as Button10,Group as Group32,Stepper}from"@mantine/core";import{Fragment as Fragment33,jsx as jsx102,jsxs as jsxs62}from"react/jsx-runtime";function QuestionnaireFormStepper(props){let{formState,submitButtonText,excludeButtons,children}=props,pages=formState.pages,activePage=formState.activePage,showBackButton=activePage>0,showNextButton=activePage<pages.length-1,showSubmitButton=activePage===pages.length-1;return jsxs62(Fragment33,{children:[jsx102(Stepper,{active:activePage,allowNextStepsSelect:!1,p:6,children:pages.map((page,index)=>jsx102(Stepper.Step,{label:page.title,children:index===activePage&&children},page.linkId))}),!excludeButtons&&jsxs62(Group32,{justify:"flex-end",mt:"xl",gap:"xs",children:[showBackButton&&jsx102(Button10,{onClick:formState.onPrevPage,children:"Back"}),showNextButton&&jsx102(Button10,{onClick:e=>{e.currentTarget.closest("form").reportValidity()&&formState.onNextPage()},children:"Next"}),showSubmitButton&&jsx102(SubmitButton,{children:submitButtonText??"Submit"})]})]})}import{Fragment as Fragment34,jsx as jsx103,jsxs as jsxs63}from"react/jsx-runtime";function QuestionnaireForm(props){let medplum=useMedplum28(),[signatureRequiredSubmitted,setSignatureRequiredSubmitted]=useState56(!1),propsRef=useRef12(props),pendingChangeRef=useRef12(void 0);useLayoutEffect3(()=>{propsRef.current=props});let onFormChange=useCallback13(response=>{pendingChangeRef.current=response},[]),formState=useQuestionnaireForm({questionnaire:props.questionnaire,defaultValue:props.questionnaireResponse,subject:props.subject,encounter:props.encounter,source:props.source,disablePagination:props.disablePagination,onChange:onFormChange}),formStateRef=useRef12(formState);useLayoutEffect3(()=>{formStateRef.current=formState}),useEffect20(()=>{let pendingChange=pendingChangeRef.current;pendingChange&&(pendingChangeRef.current=void 0,setSignatureRequiredSubmitted(!1),propsRef.current.onChange?.(pendingChange))});let isSignatureRequired=useMemo26(()=>formState.loading?!1:!!getExtension2(formState.questionnaire,QUESTIONNAIRE_SIGNATURE_REQUIRED_URL),[formState]),hasSignature=useMemo26(()=>formState.loading?!1:!!formState.questionnaireResponse.extension?.find(ext=>ext.url===QUESTIONNAIRE_SIGNATURE_RESPONSE_URL),[formState]),handleSubmit=useCallback13(()=>{let formState2=formStateRef.current;if(formState2.loading)return;let onSubmit=propsRef.current.onSubmit;if(!onSubmit)return;if(isSignatureRequired&&!hasSignature){setSignatureRequiredSubmitted(!0);return}let questionnaire2=formState2.questionnaire,response=formState2.questionnaireResponse,subject=propsRef.current.subject,source=propsRef.current.source;if(!source){let profile=medplum.getProfile();profile&&(source=createReference5(profile))}onSubmit({...response,questionnaire:questionnaire2.url??getReferenceString7(questionnaire2),subject,source,authored:new Date().toISOString(),status:"completed"})},[medplum,isSignatureRequired,hasSignature]);return formState.loading?null:jsxs63(Form,{testid:"questionnaire-form",onSubmit:handleSubmit,children:[formState.questionnaire.title&&jsx103(Title10,{children:formState.questionnaire.title}),formState.pagination?jsx103(QuestionnaireFormStepper,{formState,submitButtonText:props.submitButtonText,excludeButtons:props.excludeButtons,children:jsx103(QuestionnaireFormItemArray,{formState,context:[],items:formState.items,responseItems:formState.responseItems})}):jsxs63(Fragment34,{children:[jsx103(QuestionnaireFormItemArray,{formState,context:[],items:formState.items,responseItems:formState.responseItems}),isSignatureRequired&&jsxs63(Stack24,{mt:"md",gap:0,children:[jsx103(Text21,{size:"sm",fw:500,children:"Signature"}),jsx103(SignatureInput,{onChange:formState.onChangeSignature}),!hasSignature&&signatureRequiredSubmitted&&jsx103(Text21,{c:"red",size:"sm",children:"Signature is required."})]}),!props.excludeButtons&&jsx103(Group33,{justify:"flex-end",mt:"xl",gap:"xs",children:jsx103(SubmitButton,{children:props.submitButtonText??"Submit"})})]})]})}import{jsx as jsx104,jsxs as jsxs64}from"react/jsx-runtime";var NewTopicDialog=props=>{let{subject,opened,onClose,onSubmit,allowPatientSelection=!1}=props,medplum=useMedplum29(),profile=useMedplumProfile7(),profileRef=useMemo27(()=>profile?createReference6(profile):void 0,[profile]),[topic,setTopic]=useState57(""),[practitioners,setPractitioners]=useState57(profile?.resourceType==="Practitioner"?[createReference6(profile)]:[]),[patient,setPatient]=useState57(subject?createReference6(subject):void 0),initialResponse=useMemo27(()=>{if(profile?.resourceType==="Practitioner")return{resourceType:"QuestionnaireResponse",status:"in-progress",item:[{linkId:"q1",answer:[{valueReference:createReference6(profile)}]}]}},[profile]);return jsx104(Modal3,{opened,onClose,title:"New Message",size:"md",children:jsxs64(Stack25,{gap:"xl",children:[jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Patient"}),allowPatientSelection&&jsx104(Text22,{c:"dimmed",children:"Select a patient"}),jsx104(ResourceInput,{resourceType:"Patient",name:"patient",required:!0,defaultValue:patient,disabled:!allowPatientSelection&&!!patient,onChange:value=>{setPatient(value?createReference6(value):void 0)}})]}),jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Practitioner (optional)"}),jsx104(Text22,{c:"dimmed",children:"Select one or more practitioners"}),jsx104(QuestionnaireForm,{questionnaire,questionnaireResponse:initialResponse,excludeButtons:!0,onChange:value=>{let references=value.item?.[0].answer?.map(item=>item.valueReference).filter(ref=>ref!==void 0)??[];setPractitioners(references)}})]}),jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Topic (optional)"}),jsx104(Text22,{c:"dimmed",children:"Enter a topic for the message"}),jsx104(TextInput22,{placeholder:"Enter your topic",value:topic,onChange:e=>setTopic(e.target.value)})]}),jsx104(Button11,{onClick:async()=>{if(!patient){showNotification6({title:"Error",message:"Please select a patient",color:"red"});return}let communication={resourceType:"Communication",status:"in-progress",subject:patient,sender:profileRef,recipient:[patient,...practitioners.map(practitioner=>({reference:practitioner.reference}))],topic:{text:topic}};try{let createdCommunication=await medplum.createResource(communication);onSubmit?.(createdCommunication),onClose()}catch(error){showNotification6({title:"Error",message:normalizeErrorString7(error),color:"red"})}},children:"Next"})]})})},questionnaire={resourceType:"Questionnaire",status:"active",item:[{linkId:"q1",type:"reference",repeats:!0,extension:[{url:`${HTTP_HL7_ORG4}/fhir/StructureDefinition/questionnaire-referenceResource`,valueCodeableConcept:{coding:[{system:`${HTTP_HL7_ORG4}/fhir/fhir-types`,display:"Practitioner",code:"Practitioner"}]}}]}]};import{ActionIcon as ActionIcon9,Checkbox as Checkbox6,CloseButton,Group as Group34,Indicator,Popover as Popover2,Stack as Stack26,Text as Text23,TextInput as TextInput23,Tooltip as Tooltip4}from"@mantine/core";import{useDebouncedCallback as useDebouncedCallback3,useDisclosure}from"@mantine/hooks";import{showNotification as showNotification7}from"@mantine/notifications";import{createReference as createReference7,formatHumanName as formatHumanName7,getReferenceString as getReferenceString8,normalizeErrorString as normalizeErrorString8}from"@medplum/core";import{useMedplum as useMedplum30,useMedplumProfile as useMedplumProfile8,useResource as useResource4}from"@medplum/react-hooks";import{useEffect as useEffect21,useMemo as useMemo28,useState as useState58}from"react";var ParticipantFilter_default={participantItem:"ParticipantFilter_participantItem"};import{jsx as jsx105,jsxs as jsxs65}from"react/jsx-runtime";function ParticipantFilter(props){let{selectedParticipants,onFilterChange}=props,[opened,{open,close}]=useDisclosure(!1),[searchQuery,setSearchQuery]=useState58(""),[searchResults,setSearchResults]=useState58([]),[isSearching,setIsSearching]=useState58(!1),medplum=useMedplum30(),profile=useMedplumProfile8(),currentUserParticipant=useMemo28(()=>{if(profile)return createReference7(profile)},[profile]),additionalParticipants=useMemo28(()=>{let currentUserRef=currentUserParticipant?.reference;return selectedParticipants.filter(p=>p.reference!==currentUserRef)},[selectedParticipants,currentUserParticipant]),debouncedSearch=useDebouncedCallback3(async query=>{if(!query.trim()){setSearchResults([]);return}setIsSearching(!0);try{let bundle=await medplum.search("Patient",{_type:"Patient,Practitioner",name:query,_count:"10"}),currentUserRef=currentUserParticipant?.reference,results=(bundle.entry??[]).map(entry=>entry.resource).filter(resource=>{if(!resource)return!1;let refString=getReferenceString8(resource);return!!refString&&refString!==currentUserRef}).map(resource=>createReference7(resource));setSearchResults(results)}catch(error){showNotification7({title:"Error",message:normalizeErrorString8(error),color:"red"}),setSearchResults([])}finally{setIsSearching(!1)}},300);useEffect21(()=>(debouncedSearch(searchQuery),debouncedSearch.cancel),[searchQuery,debouncedSearch]);let isSelected=participant=>selectedParticipants.some(p=>p.reference===participant.reference),toggleParticipant=participant=>{let newParticipants=isSelected(participant)?selectedParticipants.filter(p=>p.reference!==participant.reference):[...selectedParticipants,participant];onFilterChange(newParticipants)},removeParticipant=participant=>{let newParticipants=selectedParticipants.filter(p=>p.reference!==participant.reference);onFilterChange(newParticipants)},displayParticipants=useMemo28(()=>{let result=[];for(let p of additionalParticipants)result.some(r2=>r2.reference===p.reference)||result.push(p);if(searchQuery.trim()&&searchResults.length>0)for(let p of searchResults)currentUserParticipant?.reference!==p.reference&&(result.some(r2=>r2.reference===p.reference)||result.push(p));return result},[additionalParticipants,searchQuery,searchResults,currentUserParticipant]),hasActiveFilter=selectedParticipants.length>0;return jsxs65(Popover2,{opened,onChange:o=>!o&&close(),position:"bottom-start",width:360,shadow:"md",radius:"md",withinPortal:!0,children:[jsx105(Popover2.Target,{children:jsx105(Tooltip4,{label:"Message Participants",position:"bottom",openDelay:500,disabled:opened,children:jsx105(Indicator,{disabled:!hasActiveFilter,color:"blue",size:8,offset:4,children:jsx105(ActionIcon9,{variant:"transparent",onClick:opened?close:open,radius:"xl",size:32,className:"outline-icon-button","data-opened":opened||void 0,children:jsx105(IconUsers,{size:16})})})})}),jsx105(Popover2.Dropdown,{p:"md",children:jsxs65(Stack26,{gap:"md",children:[jsx105(Text23,{size:"xs",c:"dimmed",fw:500,children:"Message Participants"}),jsx105(TextInput23,{placeholder:"Search for a Patient or Practitioner...",value:searchQuery,autoFocus:!0,onChange:e=>setSearchQuery(e.target.value),rightSection:searchQuery?jsx105(CloseButton,{size:"sm",onClick:()=>setSearchQuery("")}):null}),jsxs65(Stack26,{gap:"xs",mah:250,style:{overflowY:"auto"},children:[currentUserParticipant&&jsx105(ParticipantItem,{participant:currentUserParticipant,isSelected:isSelected(currentUserParticipant),isCurrentUser:!0,onToggle:()=>toggleParticipant(currentUserParticipant)}),displayParticipants.map(participant=>jsx105(ParticipantItem,{participant,isSelected:isSelected(participant),isCurrentUser:!1,onToggle:()=>toggleParticipant(participant),onRemove:isSelected(participant)?()=>removeParticipant(participant):void 0},participant.reference)),isSearching&&jsx105(Text23,{size:"sm",c:"dimmed",ta:"center",children:"Searching..."}),searchQuery.trim()&&!isSearching&&searchResults.length===0&&jsx105(Text23,{size:"sm",c:"dimmed",ta:"center",children:"No results found"})]})]})})]})}function ParticipantItem(props){let{participant,isSelected,isCurrentUser,onToggle,onRemove}=props,patientResource=useResource4(participant);return patientResource?jsxs65(Group34,{justify:"space-between",wrap:"nowrap",className:ParticipantFilter_default.participantItem,children:[jsxs65(Group34,{gap:"sm",wrap:"nowrap",style:{flex:1,minWidth:0},children:[jsx105(Checkbox6,{checked:isSelected,onChange:onToggle}),jsx105(ResourceAvatar,{value:participant,radius:"xl",size:32}),jsxs65(Text23,{size:"sm",truncate:!0,style:{flex:1},children:[formatHumanName7(patientResource?.name?.[0]??{}),isCurrentUser&&jsxs65(Text23,{component:"span",c:"dimmed",size:"sm",children:[" ","(you)"]})]})]}),onRemove&&jsx105(CloseButton,{size:"sm",onClick:onRemove})]}):null}import{ActionIcon as ActionIcon12,Box as Box19,Button as Button12,Center as Center3,Divider as Divider7,Flex as Flex19,Group as Group52,Menu as Menu5,Pagination,Paper as Paper4,ScrollArea as ScrollArea3,Skeleton as Skeleton2,Stack as Stack37,Tabs,Text as Text38,ThemeIcon,Tooltip as Tooltip7}from"@mantine/core";import{useDisclosure as useDisclosure10}from"@mantine/hooks";import{showNotification as showNotification8}from"@mantine/notifications";import{getReferenceString as getReferenceString10,normalizeErrorString as normalizeErrorString10,Operator,parseSearchRequest}from"@medplum/core";import{useMedplumNavigate as useMedplumNavigate5,useThreadInbox}from"@medplum/react-hooks";import{useCallback as useCallback24,useEffect as useEffect25,useMemo as useMemo32}from"react";import{Divider as Divider6,Flex as Flex18,Group as Group51,Stack as Stack36,Text as Text37,Tooltip as Tooltip6}from"@mantine/core";import{formatHumanName as formatHumanName8,resolveId}from"@medplum/core";import{useMedplum as useMedplum39,usePatientSummaryData,useResource as useResource9}from"@medplum/react-hooks";import{useEffect as useEffect24,useMemo as useMemo31,useState as useState73}from"react";var PatientSummary_default={panel:"PatientSummary_panel",patientSummaryBadge:"PatientSummary_patientSummaryBadge",patientSummaryAddButton:"PatientSummary_patientSummaryAddButton",patientSummaryHeader:"PatientSummary_patientSummaryHeader",patientSummaryCollapseIcon:"PatientSummary_patientSummaryCollapseIcon",collapsed:"PatientSummary_collapsed"};import{Stack as Stack35}from"@mantine/core";import{calculateAgeString,formatAddress as formatAddress3}from"@medplum/core";import{Box as Box11,Flex as Flex11,Group as Group37,Modal as Modal4,Text as Text25}from"@mantine/core";import{useDisclosure as useDisclosure2}from"@mantine/hooks";import{getDisplayString as getDisplayString5}from"@medplum/core";import{useMedplum as useMedplum31}from"@medplum/react-hooks";import{useCallback as useCallback15,useMemo as useMemo29,useState as useState61}from"react";import{Badge}from"@mantine/core";import{jsx as jsx106}from"react/jsx-runtime";var statusToColor={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red",finished:"green",planned:"gray"};function StatusBadge(props){let{status,...badgeProps}=props;return jsx106(Badge,{color:props.color||statusToColor[status],...badgeProps,children:status.replaceAll("-"," ")})}import{Group as Group35,Stack as Stack27,TextInput as TextInput24}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG5,addProfileToResource,createReference as createReference8}from"@medplum/core";import{useCallback as useCallback14,useState as useState59}from"react";import{jsx as jsx107,jsxs as jsxs66}from"react/jsx-runtime";var HTTP="http://",PATIENT_ALLERGY_PROFILE=HTTP_HL7_ORG5+"/fhir/us/core/StructureDefinition/us-core-allergyintolerance";function AllergyDialog(props){let{patient,encounter,allergy,onSubmit}=props,[code,setCode]=useState59(allergy?.code),[clinicalStatus,setClinicalStatus]=useState59(allergy?.clinicalStatus),handleSubmit=useCallback14(formData=>{onSubmit(addProfileToResource({...allergy,resourceType:"AllergyIntolerance",patient:createReference8(patient),encounter:encounter?createReference8(encounter):void 0,code,clinicalStatus,onsetDateTime:formData.onsetDateTime?formData.onsetDateTime:void 0,reaction:formData.reaction?[{manifestation:[{text:formData.reaction}]}]:void 0},PATIENT_ALLERGY_PROFILE))},[patient,encounter,allergy,code,clinicalStatus,onSubmit]);return jsx107(Form,{onSubmit:handleSubmit,children:jsxs66(Stack27,{children:[jsx107(CodeableConceptInput,{name:"allergy",label:"Code",path:"AllergyIntolerance.code","data-autofocus":!0,binding:HTTP+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1186.8",maxValues:1,defaultValue:allergy?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx107(TextInput24,{name:"reaction",label:"Reaction",defaultValue:allergy?.reaction?.[0]?.manifestation?.[0]?.text}),jsx107(CodeableConceptInput,{name:"clinicalStatus",label:"Clinical Status",path:"AllergyIntolerance.clinicalStatus",binding:HTTP_HL7_ORG5+"/fhir/ValueSet/allergyintolerance-clinical",maxValues:1,defaultValue:allergy?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx107(DateTimeInput,{name:"onsetDateTime",label:"Onset",defaultValue:allergy?.recordedDate}),jsx107(Group35,{justify:"flex-end",gap:4,mt:"md",children:jsx107(SubmitButton,{children:"Save"})})]})},allergy?.id)}import{ActionIcon as ActionIcon10,Box as Box9,Collapse,Group as Group36,Text as Text24}from"@mantine/core";import{useState as useState60}from"react";var CollapsibleSection_default={root:"CollapsibleSection_root",header:"CollapsibleSection_header",chevron:"CollapsibleSection_chevron",title:"CollapsibleSection_title",addButton:"CollapsibleSection_addButton"};import{jsx as jsx108,jsxs as jsxs67}from"react/jsx-runtime";function CollapsibleSection(props){let{title,children,onAdd}=props,[collapsed,setCollapsed]=useState60(!1);return jsxs67(Box9,{className:CollapsibleSection_default.root,children:[jsxs67(Group36,{justify:"space-between",className:CollapsibleSection_default.header,children:[jsxs67(Group36,{gap:8,children:[jsx108(ActionIcon10,{variant:"subtle",onClick:()=>setCollapsed(c=>!c),"aria-label":collapsed?`Show ${title.toLowerCase()}`:`Hide ${title.toLowerCase()}`,className:CollapsibleSection_default.chevron,"data-collapsed":collapsed||void 0,size:"md",children:jsx108(IconChevronDown,{size:20})}),jsx108(Text24,{fz:"md",fw:800,onClick:()=>setCollapsed(c=>!c),className:CollapsibleSection_default.title,children:title})]}),onAdd&&jsx108(ActionIcon10,{role:"button","aria-label":"Add item",className:CollapsibleSection_default.addButton,variant:"subtle",onClick:e=>{killEvent(e),onAdd()},size:"md",children:jsx108(IconPlus,{size:18})})]}),jsx108(Collapse,{in:!collapsed,children:jsx108(Box9,{ml:"var(--mantine-spacing-xl)",mt:"xs",mb:"md",pl:4,children})})]})}import{ActionIcon as ActionIcon11,Box as Box10}from"@mantine/core";var SummaryItem_default={gradient:"SummaryItem_gradient",container:"SummaryItem_container",chevron:"SummaryItem_chevron",item:"SummaryItem_item",itemText:"SummaryItem_itemText"};import{jsx as jsx109,jsxs as jsxs68}from"react/jsx-runtime";function SummaryItem(props){let{children,onClick}=props;return jsxs68(Box10,{className:SummaryItem_default.item,onClick,children:[children,jsx109("div",{className:SummaryItem_default.gradient}),jsx109("div",{className:SummaryItem_default.container,children:jsx109(ActionIcon11,{className:SummaryItem_default.chevron,size:"md",variant:"transparent",tabIndex:-1,children:jsx109(IconChevronRight,{size:16,stroke:2.5})})})]})}import{Fragment as Fragment35,jsx as jsx110,jsxs as jsxs69}from"react/jsx-runtime";function Allergies(props){let medplum=useMedplum31(),{patient,encounter}=props,[allergies,setAllergies]=useState61(props.allergies),[opened,{open,close}]=useDisclosure2(!1),[editAllergy,setEditAllergy]=useState61(),sortedAllergies=useMemo29(()=>[...allergies].sort((a,b)=>{let aStatus=a.clinicalStatus?.coding?.[0]?.code,bStatus=b.clinicalStatus?.coding?.[0]?.code;return aStatus==="active"&&bStatus!=="active"?-1:aStatus!=="active"&&bStatus==="active"?1:getDisplayString5(a).localeCompare(getDisplayString5(b))}),[allergies]),handleSubmit=useCallback15(async allergy=>{if(allergy.id){let updatedAllergy=await medplum.updateResource(allergy);setAllergies(allergies.map(a=>a.id===updatedAllergy.id?updatedAllergy:a))}else{let newAllergy=await medplum.createResource(allergy);setAllergies([...allergies,newAllergy])}setEditAllergy(void 0),close()},[medplum,allergies,close]);return jsxs69(Fragment35,{children:[jsx110(CollapsibleSection,{title:"Allergies",onAdd:()=>{setEditAllergy(void 0),open()},children:sortedAllergies.length>0?jsx110(Box11,{children:jsx110(Flex11,{direction:"column",gap:8,children:sortedAllergies.map(allergy=>{let status=allergy.clinicalStatus?.coding?.[0]?.code||"unknown";return jsx110(SummaryItem,{onClick:()=>{setEditAllergy(allergy),open()},children:jsxs69(Box11,{children:[jsx110(Text25,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString5(allergy)}),jsx110(Group37,{mt:2,gap:4,children:status&&jsx110(StatusBadge,{color:getClinicalStatusColor(status),variant:"light",status})})]})},allergy.id)})})}):jsx110(Text25,{children:"(none)"})}),jsx110(Modal4,{opened,onClose:close,title:editAllergy?"Edit Allergy":"Add Allergy",children:jsx110(AllergyDialog,{patient,encounter,allergy:editAllergy,onSubmit:handleSubmit})})]})}function getClinicalStatusColor(status){if(!status)return"gray";switch(status){case"active":return"red";case"inactive":return"orange";case"resolved":return"blue";default:return"gray"}}import{Box as Box12,Flex as Flex12,Group as Group38,Text as Text26}from"@mantine/core";import{formatDate}from"@medplum/core";import{useResource as useResource5}from"@medplum/react-hooks";import{jsx as jsx111,jsxs as jsxs70}from"react/jsx-runtime";function CoverageItem(props){let{coverage,organization,onClickResource}=props,coverageResource=useResource5(coverage),organizationResource=useResource5(organization),payorName="Unknown Payor";organizationResource&&"name"in organizationResource&&typeof organizationResource.name=="string"&&(payorName=organizationResource.name);let detailsText=`ID: ${coverageResource?.subscriberId??"N/A"}${formatClassInfo(coverageResource)?` \xB7 ${formatClassInfo(coverageResource)}`:""}`;return jsx111(SummaryItem,{onClick:()=>{coverageResource&&onClickResource?.(coverageResource)},children:jsxs70(Box12,{children:[jsx111(Text26,{fw:500,className:PatientSummary_default.itemText,children:payorName}),jsx111(Text26,{fw:500,className:PatientSummary_default.itemText,children:detailsText}),jsxs70(Group38,{mt:2,gap:4,children:[jsx111(StatusBadge,{color:"green",variant:"light",status:"Active"}),jsxs70(Text26,{size:"xs",fw:500,color:"gray.6",children:["Ends ",formatDate(coverageResource?.period?.end)]})]})]})})}function Insurance(props){let{coverages,onClickResource}=props,activeCoverages=coverages.filter(coverage=>coverage.status==="active");return jsx111(CollapsibleSection,{title:"Insurance",children:activeCoverages.length>0?jsx111(Flex12,{direction:"column",gap:8,children:activeCoverages.map(coverage=>jsx111(CoverageItem,{coverage,organization:coverage.payor?.[0],onClickResource},coverage.id))}):jsx111(Text26,{children:"(none)"})})}function capitalizeWords(str){return str.split(" ").map(word=>word.charAt(0).toUpperCase()+word.slice(1).toLowerCase()).join(" ")}function formatClassInfo(coverage){return coverage?coverage.class?.filter(cls=>cls.type?.coding?.[0]?.code!=="plan").map(cls=>{let type=cls.type?.coding?.[0]?.code??"";return`${capitalizeWords(type)}: ${cls.value}`}).join(" \xB7 ")??"":""}import{Box as Box13,Flex as Flex13,Group as Group41,Modal as Modal5,Text as Text29}from"@mantine/core";import{useDisclosure as useDisclosure3}from"@mantine/hooks";import{formatDate as formatDate2,getDisplayString as getDisplayString7}from"@medplum/core";import{useState as useState64}from"react";import{Group as Group40,List,Stack as Stack29,Text as Text28,Title as Title11}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept3,formatDateTime as formatDateTime3,formatObservationValue,isReference as isReference3}from"@medplum/core";import{useMedplum as useMedplum32,useResource as useResource7}from"@medplum/react-hooks";import{useEffect as useEffect22,useState as useState63}from"react";import{Blockquote,Stack as Stack28}from"@mantine/core";var NoteDisplay_default={noteBody:"NoteDisplay_noteBody",noteCite:"NoteDisplay_noteCite",noteRoot:"NoteDisplay_noteRoot"};import{jsx as jsx112}from"react/jsx-runtime";function NoteDisplay({value}){return value?jsx112(Stack28,{justify:"flex-start",gap:"xs",children:value.map(note=>note.text&&jsx112(Blockquote,{classNames:{cite:NoteDisplay_default.noteCite,root:NoteDisplay_default.noteRoot},cite:note.authorReference?.display||note.authorString,icon:null,children:note.text},`note-${note.text}`))}):null}import{Group as Group39}from"@mantine/core";import{Text as Text27}from"@mantine/core";import{getDisplayString as getDisplayString6,isOk,normalizeErrorString as normalizeErrorString9}from"@medplum/core";import{useResource as useResource6}from"@medplum/react-hooks";import{useState as useState62}from"react";import{jsx as jsx113}from"react/jsx-runtime";function ResourceName(props){let{value,link,...rest}=props,[outcome,setOutcome]=useState62(),resource=useResource6(value,setOutcome),text;if(outcome&&!isOk(outcome))text=`[${normalizeErrorString9(outcome)}]`;else if(resource)text=getDisplayString6(resource);else return null;return link?jsx113(MedplumLink,{to:value,...rest,children:text}):jsx113(Text27,{component:"span",...rest,children:text})}import{jsx as jsx114,jsxs as jsxs71}from"react/jsx-runtime";function ResourceBadge(props){return jsxs71(Group39,{gap:"xs",children:[jsx114(ResourceAvatar,{size:24,radius:12,value:props.value,link:props.link}),jsx114(ResourceName,{value:props.value,link:props.link})]})}var DiagnosticReportDisplay_default={table:"DiagnosticReportDisplay_table",criticalRow:"DiagnosticReportDisplay_criticalRow",noteBody:"DiagnosticReportDisplay_noteBody",noteCite:"DiagnosticReportDisplay_noteCite",noteRoot:"DiagnosticReportDisplay_noteRoot"};import{Fragment as Fragment36,jsx as jsx115,jsxs as jsxs72}from"react/jsx-runtime";DiagnosticReportDisplay.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1,hideSubject:!1};function DiagnosticReportDisplay(props){let medplum=useMedplum32(),diagnosticReport=useResource7(props.value),[specimens,setSpecimens]=useState63();if(useEffect22(()=>{diagnosticReport?.specimen&&Promise.allSettled(diagnosticReport.specimen.map(ref=>medplum.readReference(ref))).then(outcomes=>outcomes.filter(outcome=>outcome.status==="fulfilled").map(outcome=>outcome.value)).then(setSpecimens).catch(console.error)},[medplum,diagnosticReport]),!diagnosticReport)return null;let specimenNotes=specimens?.flatMap(spec=>spec.note||[])||[];if(diagnosticReport.presentedForm&&diagnosticReport.presentedForm.length>0){let pf=diagnosticReport.presentedForm[0];pf.contentType?.startsWith("text/plain")&&pf.data&&specimenNotes.push({text:window.atob(pf.data)})}return jsxs72(Stack29,{children:[jsx115(Title11,{children:"Diagnostic Report"}),jsx115(DiagnosticReportHeader,{value:diagnosticReport,hideSubject:props.hideSubject}),specimens&&!props.hideSpecimenInfo&&SpecimenInfo(specimens),diagnosticReport.result&&jsx115(ObservationTable,{hideObservationNotes:props.hideObservationNotes,value:diagnosticReport.result}),specimenNotes.length>0&&jsx115(NoteDisplay,{value:specimenNotes})]})}function DiagnosticReportHeader({value,hideSubject=!1}){return jsxs72(Group40,{mt:"md",gap:30,children:[value.subject&&!hideSubject&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),jsx115(ResourceBadge,{value:value.subject,link:!0})]}),value.resultsInterpreter?.map(interpreter=>jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),jsx115(ResourceBadge,{value:interpreter,link:!0})]},interpreter.reference)),value.performer?.map(performer=>jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),jsx115(ResourceBadge,{value:performer,link:!0})]},performer.reference)),value.issued&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),jsx115(Text28,{children:formatDateTime3(value.issued)})]}),value.status&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),jsx115(StatusBadge,{status:value.status})]})]})}function SpecimenInfo(specimens){return jsxs72(Stack29,{gap:"xs",children:[jsx115(Title11,{order:2,size:"h6",children:"Specimens"}),jsx115(List,{type:"ordered",children:specimens?.map(specimen=>jsx115(List.Item,{ml:"sm",children:jsxs72(Group40,{gap:20,children:[jsxs72(Group40,{gap:5,children:[jsx115(Text28,{fw:500,children:"Collected:"})," ",formatDateTime3(specimen.collection?.collectedDateTime)]}),jsxs72(Group40,{gap:5,children:[jsx115(Text28,{fw:500,children:"Received:"})," ",formatDateTime3(specimen.receivedTime)]})]})},`specimen-${specimen.id}`))})]})}function ObservationTable(props){return jsxs72("table",{className:DiagnosticReportDisplay_default.table,children:[jsx115("thead",{children:jsxs72("tr",{children:[jsx115("th",{children:"Test"}),jsx115("th",{children:"Value"}),jsx115("th",{children:"Reference Range"}),jsx115("th",{children:"Interpretation"}),jsx115("th",{children:"Category"}),jsx115("th",{children:"Performer"}),jsx115("th",{children:"Status"})]})}),jsx115("tbody",{children:jsx115(ObservationRowGroup,{value:props.value,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes})})]})}function ObservationRowGroup(props){return jsx115(Fragment36,{children:props.value?.map(observation=>jsx115(ObservationRow,{value:observation,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes},`obs-${isReference3(observation)?observation.reference:observation.id}`))})}function ObservationRow(props){let observation=useResource7(props.value);if(!observation||props.ancestorIds?.includes(observation.id))return null;let displayNotes=!props.hideObservationNotes&&observation.note,critical=isCritical(observation);return jsxs72(Fragment36,{children:[jsxs72("tr",{className:clsx_default({[DiagnosticReportDisplay_default.criticalRow]:critical}),children:[jsx115("td",{rowSpan:displayNotes?2:1,children:jsx115(MedplumLink,{to:observation,children:jsx115(CodeableConceptDisplay,{value:observation.code})})}),jsx115("td",{children:jsx115(ObservationValueDisplay,{value:observation})}),jsx115("td",{children:jsx115(ReferenceRangeDisplay,{value:observation.referenceRange})}),jsx115("td",{children:observation.interpretation&&observation.interpretation.length>0&&jsx115(CodeableConceptDisplay,{value:observation.interpretation[0]})}),jsx115("td",{children:observation.category&&observation.category.length>0&&jsx115(Fragment36,{children:observation.category.map(concept=>jsx115("div",{children:jsx115(CodeableConceptDisplay,{value:concept})},`category-${formatCodeableConcept3(concept)}`))})}),jsx115("td",{children:observation.performer?.map(performer=>jsx115(ReferenceDisplay,{value:performer},performer.reference))}),jsx115("td",{children:observation.status&&jsx115(StatusBadge,{status:observation.status})})]}),observation.hasMember&&jsx115(ObservationRowGroup,{value:observation.hasMember,ancestorIds:props.ancestorIds?[...props.ancestorIds,observation.id]:[observation.id],hideObservationNotes:props.hideObservationNotes}),displayNotes&&jsx115("tr",{children:jsx115("td",{colSpan:6,children:jsx115(NoteDisplay,{value:observation.note})})})]})}function ObservationValueDisplay(props){let obs=props.value;return jsx115(Fragment36,{children:formatObservationValue(obs)})}function ReferenceRangeDisplay(props){let range=props.value&&props.value.length>0&&props.value[0];return range?range.text?jsx115(Fragment36,{children:range.text}):jsx115(RangeDisplay,{value:range}):null}function isCritical(observation){let code=observation.interpretation?.[0]?.coding?.[0]?.code;return code==="AA"||code==="LL"||code==="HH"||code==="A"}import{Fragment as Fragment37,jsx as jsx116,jsxs as jsxs73}from"react/jsx-runtime";function Labs(props){let{serviceRequests,diagnosticReports,onClickResource,onRequestLabs}=props,[selectedReport,setSelectedReport]=useState64(),[reportDialogOpened,{open:openReportDialog,close:closeReportDialog}]=useDisclosure3(!1),diagnosticReportsRequests=new Set,filteredDiagnosticReports=diagnosticReports.filter(report=>{let flag=isLaboratoryReport(report);return flag&&report.basedOn&&report.basedOn.forEach(basedOn=>{if(basedOn.reference?.startsWith("ServiceRequest/")){let[,id]=basedOn.reference.split("/");diagnosticReportsRequests.add(id)}}),flag}),completedRequisitionNumbers=new Set,filteredServiceRequests=serviceRequests.filter(request=>{if(request.id&&diagnosticReportsRequests.has(request.id)||request.basedOn&&request.basedOn.find(basedOn2=>{if(basedOn2.reference?.startsWith("ServiceRequest/")){let[,id]=basedOn2.reference.split("/");return diagnosticReportsRequests.has(id)}return!1}))return!1;let shouldFilter=shouldFilterRequest(request,completedRequisitionNumbers);return!shouldFilter&&request.requisition?.value&&completedRequisitionNumbers.add(request.requisition?.value),!shouldFilter}),handleDiagnosticReportClick=report=>{setSelectedReport(report),openReportDialog()};return jsxs73(Fragment37,{children:[jsx116(CollapsibleSection,{title:"Labs",onAdd:()=>onRequestLabs?.(),children:jsxs73(Flex13,{direction:"column",gap:8,children:[filteredServiceRequests.map(serviceRequest=>jsx116(SummaryItem,{onClick:()=>onClickResource?.(serviceRequest),children:jsxs73(Box13,{children:[jsx116(Text29,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString7(serviceRequest)}),jsxs73(Group41,{mt:2,gap:4,children:[serviceRequest.status&&jsx116(StatusBadge,{color:getStatusColor(serviceRequest.status),variant:"light",status:serviceRequest.status}),jsx116(Text29,{size:"xs",fw:500,c:"dimmed",children:formatDate2(serviceRequest.authoredOn)})]})]})},serviceRequest.id)),filteredDiagnosticReports.map(report=>jsx116(SummaryItem,{onClick:()=>handleDiagnosticReportClick(report),children:jsxs73(Box13,{children:[jsx116(Text29,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString7(report)}),jsxs73(Group41,{mt:2,gap:4,children:[report.status&&jsx116(StatusBadge,{color:getStatusColor(report.status),variant:"light",status:report.status}),jsx116(Text29,{size:"xs",fw:500,c:"dimmed",children:formatDate2(report.issued)})]})]})},report.id)),filteredServiceRequests.length===0&&filteredDiagnosticReports.length===0&&jsx116(Text29,{children:"(none)"})]})}),jsx116(Modal5,{opened:reportDialogOpened,onClose:closeReportDialog,size:"80%",children:selectedReport&&jsx116(DiagnosticReportDisplay,{value:selectedReport,hideSubject:!0})})]})}var getStatusColor=status=>{switch(status){case"active":return"indigo";case"final":return"teal";case"cancelled":return"red";default:return"gray"}};function hasLaboratoryCategory(category){if(!category.coding||!Array.isArray(category.coding))return!1;for(let coding of category.coding)if(coding.code==="LAB")return!0;return!1}function isLaboratoryReport(report){if(!report.category||!Array.isArray(report.category))return!1;for(let category of report.category)if(hasLaboratoryCategory(category))return!0;return!1}function shouldFilterRequest(request,completedRequisitionNumbers){if(["completed","draft","entered-in-error"].includes(request.status))return!0;let requisitionNumber=request.requisition?.value;return!!(requisitionNumber&&completedRequisitionNumbers.has(requisitionNumber))}import{Box as Box14,Flex as Flex14,Group as Group43,Modal as Modal6,Text as Text30}from"@mantine/core";import{useDisclosure as useDisclosure4}from"@mantine/hooks";import{getDisplayString as getDisplayString8}from"@medplum/core";import{useMedplum as useMedplum33}from"@medplum/react-hooks";import{useCallback as useCallback17,useState as useState66}from"react";import{Alert as Alert4,Group as Group42,Radio as Radio2,Stack as Stack30}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG6,addProfileToResource as addProfileToResource2,createReference as createReference9}from"@medplum/core";import{useMedplumProfile as useMedplumProfile9}from"@medplum/react-hooks";import{useCallback as useCallback16,useState as useState65}from"react";import{jsx as jsx117,jsxs as jsxs74}from"react/jsx-runtime";var HTTP2="http://",statusValues=["active","stopped","on-hold","cancelled","completed","entered-in-error","draft","unknown"];function MedicationDialog(props){let me=useMedplumProfile9(),{patient,encounter,medication,onSubmit}=props,[code,setCode]=useState65(medication?.medicationCodeableConcept),handleSubmit=useCallback16(formData=>{if(!me)throw new Error("Not signed in");onSubmit(addProfileToResource2({...medication,resourceType:"MedicationRequest",status:formData.status,intent:medication?.intent??"order",encounter:medication?.encounter??(encounter&&createReference9(encounter)),requester:medication?.requester??createReference9(me),medicationCodeableConcept:code,subject:createReference9(patient)},HTTP_HL7_ORG6+"/fhir/us/core/StructureDefinition/us-core-medicationrequest"))},[me,onSubmit,medication,encounter,code,patient]);return me?jsx117(Form,{onSubmit:handleSubmit,children:jsxs74(Stack30,{children:[jsx117(CodeableConceptInput,{name:"request",path:"MedicationRequest.medication[x]","data-autofocus":!0,binding:HTTP2+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1010.4",maxValues:1,defaultValue:medication?.medicationCodeableConcept,onChange:request=>setCode(request),outcome:void 0}),jsx117(Radio2.Group,{name:"status",label:"Request Status",required:!0,defaultValue:medication?.status,children:statusValues.map(sv=>jsx117(Radio2,{value:sv,label:sv,my:"xs",required:!0},sv))}),jsx117(Group42,{justify:"flex-end",gap:4,children:jsx117(SubmitButton,{children:"Save"})})]})}):jsx117(Alert4,{color:"red",children:"Not signed in"})}import{Fragment as Fragment38,jsx as jsx118,jsxs as jsxs75}from"react/jsx-runtime";function Medications(props){let medplum=useMedplum33(),[medicationRequests,setMedicationRequests]=useState66(props.medicationRequests),[editMedication,setEditMedication]=useState66(),[opened,{open,close}]=useDisclosure4(!1),handleSubmit=useCallback17(async medication=>{if(medication.id){let updatedMedication=await medplum.updateResource(medication);setMedicationRequests(medicationRequests.map(m=>m.id===updatedMedication.id?updatedMedication:m))}else{let newMedication=await medplum.createResource(medication);setMedicationRequests([newMedication,...medicationRequests])}setEditMedication(void 0),close()},[medplum,medicationRequests,close]);return jsxs75(Fragment38,{children:[jsx118(CollapsibleSection,{title:"Medications",onAdd:()=>{setEditMedication(void 0),open()},children:medicationRequests.length>0?jsx118(Flex14,{direction:"column",gap:8,children:medicationRequests.map(medication=>jsx118(SummaryItem,{onClick:()=>{setEditMedication(medication),open()},children:jsxs75(Box14,{children:[jsx118(Text30,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString8(medication)}),jsx118(Group43,{mt:2,gap:4,children:medication.status&&jsx118(StatusBadge,{color:getStatusColor2(medication.status),variant:"light",status:medication.status})})]})},medication.id))}):jsx118(Text30,{children:"(none)"})}),jsx118(Modal6,{opened,onClose:close,title:editMedication?"Edit Medication":"Add Medication",children:jsx118(MedicationDialog,{patient:props.patient,encounter:props.encounter,medication:editMedication,onSubmit:handleSubmit})})]})}function getStatusColor2(status){if(!status)return"gray";switch(status){case"active":return"green";case"stopped":return"red";case"on-hold":return"yellow";case"cancelled":return"red";case"completed":return"blue";case"entered-in-error":return"red";case"draft":return"gray";default:return"gray"}}import{Box as Box15,Group as Group44,Text as Text31,Tooltip as Tooltip5}from"@mantine/core";import{jsx as jsx119,jsxs as jsxs76}from"react/jsx-runtime";var PatientInfoItem=props=>{let{patient,value,icon,placeholder,label,onClickResource}=props,displayText=value||placeholder;return jsx119(SummaryItem,{onClick:()=>{onClickResource?.(patient)},children:jsx119(Box15,{className:PatientSummary_default.patientSummaryListItem,children:jsx119(Tooltip5,{label,position:"top-start",openDelay:650,children:jsxs76(Group44,{gap:"sm",align:"center",ml:6,mr:2,style:{cursor:"pointer",flexWrap:"nowrap",minWidth:0},children:[icon,jsx119(Text31,{fz:"sm",fw:400,truncate:!0,c:value?"inherit":"var(--mantine-color-gray-6)",children:displayText})]})})})})};import{capitalize as capitalize4,getExtension as getExtension3,HTTP_HL7_ORG as HTTP_HL7_ORG7}from"@medplum/core";function getGenderIdentity(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-genderIdentity`)?.valueCodeableConcept?.coding?.[0]?.display}function getBirthSex(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-birthsex`)?.valueCode}function getRace(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-race`)?.extension?.find(subExt=>subExt.url==="ombCategory")?.valueCoding?.display}function getEthnicity(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-ethnicity`)?.extension?.find(subExt=>subExt.url==="ombCategory")?.valueCoding?.display}function getGeneralPractitioner(patient){return patient.generalPractitioner?.[0]?.display}function formatPatientGenderDisplay(patient){let capitalizedGender=patient.gender?capitalize4(patient.gender):"",genderIdentity=getGenderIdentity(patient),birthSex=getBirthSex(patient),parts=[];return capitalizedGender&&parts.push(capitalizedGender),genderIdentity&&parts.push(genderIdentity),birthSex&&parts.push(`Born as ${birthSex}`),parts.join(" \xB7 ")}function formatPatientRaceEthnicityDisplay(patient){let race=getRace(patient),ethnicity=getEthnicity(patient),parts=[];return race&&parts.push(race),ethnicity&&parts.push(ethnicity),parts.join(" \xB7 ")}var getPreferredLanguage=patient=>{if(!patient.communication?.length)return;let preferred=patient.communication?.find(comm=>comm.preferred===!0);return preferred?.language?.coding?.[0]?.display?preferred.language.coding[0].display:patient.communication[0]?.language?.coding?.[0]?.display};import{Box as Box16,Flex as Flex15,Group as Group45,Loader as Loader4,Modal as Modal7,Text as Text32}from"@mantine/core";import{useDisclosure as useDisclosure5}from"@mantine/hooks";import{formatAddress as formatAddress2,getReferenceString as getReferenceString9,OperationOutcomeError}from"@medplum/core";import{useMedplum as useMedplum34,useResource as useResource8}from"@medplum/react-hooks";import{useCallback as useCallback18,useEffect as useEffect23,useMemo as useMemo30,useState as useState67}from"react";import{PATIENT_PREFERRED_PHARMACY_URL,PHARMACY_PREFERENCE_TYPE_SYSTEM,PHARMACY_TYPE_PREFERRED,PHARMACY_TYPE_PRIMARY,addPreferredPharmacyToPatient,createPreferredPharmacyExtension,getPreferredPharmaciesFromPatient,isAddPharmacyResponse,isOrganizationArray,removePreferredPharmacyFromPatient}from"@medplum/core";import{Fragment as Fragment39,jsx as jsx120,jsxs as jsxs77}from"react/jsx-runtime";function Pharmacies(props){let{patient:patientProp,onClickResource,pharmacyDialogComponent}=props,PharmacyDialogComponent=pharmacyDialogComponent,medplum=useMedplum34(),[opened,{open,close}]=useDisclosure5(!1),[resolvedPharmacies,setResolvedPharmacies]=useState67([]),[loadState,setLoadState]=useState67("loading"),patient=useResource8(patientProp),pharmacyRefs=useMemo30(()=>patient?getPreferredPharmaciesFromPatient(patient):[],[patient]);useEffect23(()=>{let cancelled=!1;return(async()=>{if(props.pharmacies){cancelled||(setResolvedPharmacies(props.pharmacies),setLoadState("loaded"));return}if(pharmacyRefs.length===0){cancelled||(setResolvedPharmacies([]),setLoadState("loaded"));return}setLoadState("loading");try{let results=await Promise.all(pharmacyRefs.map(async pharmacyRef=>{try{return{...await medplum.readReference(pharmacyRef.organizationRef),isPrimary:pharmacyRef.isPrimary}}catch(error){return isNotFoundError(error),null}}));if(!cancelled){let validResults=results.filter(result=>result!==null);setResolvedPharmacies(validResults),setLoadState(validResults.length===0&&pharmacyRefs.length>0?"error":"loaded")}}catch{cancelled||setLoadState("error")}})().catch(()=>{}),()=>{cancelled=!0}},[medplum,pharmacyRefs,props.pharmacies]);let handleSubmit=useCallback18(async _pharmacy=>{patient?.id&&medplum.invalidateUrl(getReferenceString9(patient)),close()},[medplum,patient,close]);return patient?jsxs77(Fragment39,{children:[jsx120(CollapsibleSection,{title:"Pharmacies",onAdd:pharmacyDialogComponent?open:void 0,children:loadState==="loading"?jsx120(Loader4,{size:"sm"}):loadState==="error"?jsx120(Text32,{c:"red",size:"sm",children:"Failed to load pharmacies"}):resolvedPharmacies.length===0?jsx120(Text32,{children:"(none)"}):jsx120(Box16,{children:jsx120(Flex15,{direction:"column",gap:8,children:resolvedPharmacies.map((pharmacy,index)=>jsx120(SummaryItem,{onClick:()=>onClickResource?.(pharmacy),children:jsxs77(Box16,{children:[jsx120(Text32,{fw:500,className:SummaryItem_default.itemText,children:pharmacy.name}),jsxs77(Group45,{mt:2,gap:4,children:[pharmacy.isPrimary&&jsx120(StatusBadge,{color:"blue",variant:"light",status:"primary"}),pharmacy.address?.[0]&&jsx120(Text32,{size:"xs",c:"dimmed",children:formatAddress2(pharmacy.address[0])})]})]})},pharmacy.id||index))})})}),PharmacyDialogComponent?jsx120(Modal7,{opened,onClose:close,title:"Add Pharmacy",size:"lg",children:jsx120(PharmacyDialogComponent,{patient,onSubmit:handleSubmit,onClose:close})}):null]}):jsx120(Fragment39,{})}function isNotFoundError(error){return error instanceof OperationOutcomeError?error.outcome.issue?.some(issue=>issue.code==="not-found")??!1:!1}import{Box as Box17,Flex as Flex16,Group as Group47,Modal as Modal8,Text as Text33}from"@mantine/core";import{useDisclosure as useDisclosure6}from"@mantine/hooks";import{formatDate as formatDate3,getDisplayString as getDisplayString9}from"@medplum/core";import{useMedplum as useMedplum35}from"@medplum/react-hooks";import{useCallback as useCallback20,useState as useState69}from"react";import{Group as Group46,Stack as Stack31}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG8,HTTP_TERMINOLOGY_HL7_ORG,addProfileToResource as addProfileToResource3,createReference as createReference10}from"@medplum/core";import{useCallback as useCallback19,useState as useState68}from"react";import{jsx as jsx121,jsxs as jsxs78}from"react/jsx-runtime";function ConditionDialog(props){let{patient,encounter,condition,onSubmit}=props,[code,setCode]=useState68(condition?.code),[clinicalStatus,setClinicalStatus]=useState68(condition?.clinicalStatus),handleSubmit=useCallback19(formData=>{let updatedCondition=addProfileToResource3({...condition,resourceType:"Condition",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG+"/CodeSystem/condition-category",code:"problem-list-item",display:"Problem List Item"}],text:"Problem List Item"}],subject:createReference10(patient),encounter:encounter&&createReference10(encounter),code,clinicalStatus,onsetDateTime:formData.onsetDateTime?convertLocalToIso(formData.onsetDateTime):void 0},HTTP_HL7_ORG8+"/fhir/us/core/StructureDefinition/us-core-condition-problems-health-concerns");onSubmit(updatedCondition)},[patient,encounter,condition,code,clinicalStatus,onSubmit]);return jsx121(Form,{onSubmit:handleSubmit,children:jsxs78(Stack31,{children:[jsx121(CodeableConceptInput,{name:"code",label:"Problem",path:"Condition.code","data-autofocus":!0,binding:HTTP_HL7_ORG8+"/fhir/us/core/ValueSet/us-core-condition-code",defaultValue:condition?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx121(CodeableConceptInput,{name:"clinicalStatus",label:"Status",path:"Condition.clinicalStatus",binding:HTTP_HL7_ORG8+"/fhir/ValueSet/condition-clinical",defaultValue:condition?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx121(DateTimeInput,{name:"onsetDateTime",label:"Dx Date",defaultValue:condition?.onsetDateTime,required:!0}),jsx121(Group46,{justify:"flex-end",gap:4,mt:"md",children:jsx121(SubmitButton,{children:"Save"})})]})},condition?.id)}import{Fragment as Fragment40,jsx as jsx122,jsxs as jsxs79}from"react/jsx-runtime";function ProblemList(props){let medplum=useMedplum35(),{patient,encounter}=props,[problems,setProblems]=useState69(props.problems.filter(c=>c.verificationStatus?.coding?.[0]?.code!=="entered-in-error")),[editCondition,setEditCondition]=useState69(),[opened,{open,close}]=useDisclosure6(!1),handleSubmit=useCallback20(async condition=>{if(condition.id){let updatedCondition=await medplum.updateResource(condition);setProblems(problems.map(p=>p.id===updatedCondition.id?updatedCondition:p))}else{let newCondition=await medplum.createResource(condition);setProblems([newCondition,...problems])}setEditCondition(void 0),close()},[medplum,problems,close]);return jsxs79(Fragment40,{children:[jsx122(CollapsibleSection,{title:"Problems",onAdd:()=>{setEditCondition(void 0),open()},children:problems.length>0?jsx122(Flex16,{direction:"column",gap:8,children:problems.map(problem=>jsx122(SummaryItem,{onClick:()=>{setEditCondition(problem),open()},children:jsxs79(Box17,{children:[jsx122(Text33,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString9(problem)}),jsxs79(Group47,{mt:2,gap:4,children:[problem.clinicalStatus?.coding?.[0]?.code&&jsx122(StatusBadge,{"data-testid":"status-badge",color:getStatusColor3(problem.clinicalStatus?.coding?.[0]?.code),variant:"light",status:problem.clinicalStatus?.coding?.[0]?.code}),jsx122(Text33,{size:"xs",fw:500,c:"dimmed",children:formatDate3(problem.onsetDateTime)})]})]})},problem.id))}):jsx122(Text33,{children:"(none)"})}),jsx122(Modal8,{opened,onClose:close,title:editCondition?"Edit Problem":"Add Problem",children:jsx122(ConditionDialog,{patient,encounter,condition:editCondition,onSubmit:handleSubmit})})]})}var getStatusColor3=status=>{if(!status)return"gray";switch(status){case"active":case"recurrence":case"relapse":return"green";case"inactive":return"orange";case"remission":return"blue";case"resolved":return"teal";default:return"gray"}};import{Box as Box18,Flex as Flex17,Group as Group48,Modal as Modal9,Radio as Radio3,Stack as Stack32,Text as Text34,UnstyledButton as UnstyledButton4}from"@mantine/core";import{useDisclosure as useDisclosure7}from"@mantine/hooks";import{createReference as createReference11,HTTP_HL7_ORG as HTTP_HL7_ORG9,HTTP_TERMINOLOGY_HL7_ORG as HTTP_TERMINOLOGY_HL7_ORG2,LOINC,SNOMED}from"@medplum/core";import{useMedplum as useMedplum36}from"@medplum/react-hooks";import{useCallback as useCallback21,useState as useState70}from"react";import{Fragment as Fragment41,jsx as jsx123,jsxs as jsxs80}from"react/jsx-runtime";var NULLFLAVOR=HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/v3-NullFlavor",CodesToText={38628009:"Homosexual",20430005:"Heterosexual",42035005:"Bisexual",OTH:"Other",UNK:"Unknown",ASKU:"Asked but no answer"},CodesToSystem={38628009:SNOMED,20430005:SNOMED,42035005:SNOMED,OTH:NULLFLAVOR,UNK:NULLFLAVOR,ASKU:NULLFLAVOR};function SexualOrientation(props){let{patient,encounter}=props,medplum=useMedplum36(),[sexualOrientation,setSexualOrientation]=useState70(props.sexualOrientation),[opened,{open,close}]=useDisclosure7(!1),[hoverIndex,setHoverIndex]=useState70(null),handleSubmit=useCallback21(formData=>{let code=formData.sexualOrientation;medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG9+"/fhir/us/core/ValueSet/us-core-sexual-orientation"]},status:"final",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC,code:"76690-7",display:"Sexual orientation"}],text:"Sexual orientation"},subject:createReference11(patient),encounter:encounter?createReference11(encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:CodesToSystem[code],code:formData.sexualOrientation}],text:CodesToText[code]}}).then(newSexualOrientation=>{setSexualOrientation(newSexualOrientation),close()}).catch(console.error)},[medplum,patient,encounter,close]);return jsxs80(Fragment41,{children:[jsx123(CollapsibleSection,{title:"Sexual Orientation",onAdd:()=>{open()},children:sexualOrientation?jsx123(Flex17,{direction:"column",gap:8,children:jsx123(Box18,{onMouseEnter:()=>setHoverIndex(0),onMouseLeave:()=>setHoverIndex(null),children:jsx123(UnstyledButton4,{"data-testid":"sexual-orientation-button",onClick:e=>{killEvent(e),props.onClickResource&&props.onClickResource(sexualOrientation)},children:jsx123(Box18,{pr:hoverIndex===0?24:0,children:jsx123(Text34,{size:"sm",fw:500,children:sexualOrientation.valueCodeableConcept?.text??"Unknown"})})})})}):jsx123(Text34,{children:"(none)"})}),jsx123(Modal9,{opened,onClose:close,title:"Set Sexual Orientation",children:jsx123(Form,{onSubmit:handleSubmit,children:jsxs80(Stack32,{children:[jsx123(Radio3.Group,{name:"sexualOrientation",label:"Sexual Orientation",required:!0,children:Object.entries(CodesToText).map(([code,text])=>jsx123(Radio3,{value:code,label:text,my:"xs"},code))}),jsx123(Group48,{justify:"flex-end",gap:4,mt:"md",children:jsx123(SubmitButton,{children:"Save"})})]})})})]})}import{Group as Group49,Modal as Modal10,Radio as Radio4,Stack as Stack33,Text as Text35,UnstyledButton as UnstyledButton5}from"@mantine/core";import{useDisclosure as useDisclosure8}from"@mantine/hooks";import{HTTP_HL7_ORG as HTTP_HL7_ORG10,LOINC as LOINC2,SNOMED as SNOMED2,createReference as createReference12,formatCodeableConcept as formatCodeableConcept4}from"@medplum/core";import{useMedplum as useMedplum37}from"@medplum/react-hooks";import{useCallback as useCallback22,useState as useState71}from"react";import{Fragment as Fragment42,jsx as jsx124,jsxs as jsxs81}from"react/jsx-runtime";var smokingStatusOptions={266919005:"Never smoked tobacco",266927001:"Tobacco smoking consumption unknown","428041000124106":"Occasional tobacco smoker","428061000124105":"Light tobacco smoker","428071000124103":"Heavy tobacco smoker",449868002:"Smokes tobacco daily",77176002:"Smoker",8517006:"Ex-smoker"};function SmokingStatus(props){let medplum=useMedplum37(),[smokingStatus,setSmokingStatus]=useState71(props.smokingStatus),[opened,{open,close}]=useDisclosure8(!1),handleSubmit=useCallback22(formData=>{medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG10+"/fhir/us/core/StructureDefinition/us-core-smokingstatus"]},status:"final",category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC2,code:"72166-2",display:"Tobacco smoking status"}],text:"Tobacco smoking status"},subject:createReference12(props.patient),encounter:props.encounter?createReference12(props.encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:SNOMED2,version:SNOMED2+"/731000124108",code:formData.smokingStatus}],text:smokingStatusOptions[formData.smokingStatus]}}).then(newSmokingStatus=>{setSmokingStatus(newSmokingStatus),close()}).catch(console.error)},[medplum,props.patient,props.encounter,close]);return jsxs81(Fragment42,{children:[jsx124(CollapsibleSection,{title:"Smoking Status",onAdd:()=>{open()},children:smokingStatus?.valueCodeableConcept?jsx124(UnstyledButton5,{"data-testid":"smoking-status-button",onClick:()=>props.onClickResource?.(smokingStatus),children:jsx124(Text35,{children:formatCodeableConcept4(smokingStatus.valueCodeableConcept)})}):jsx124(Text35,{children:"(none)"})}),jsx124(Modal10,{opened,onClose:close,title:"Set Smoking Status",children:jsx124(Form,{onSubmit:handleSubmit,children:jsxs81(Stack33,{children:[jsx124(Radio4.Group,{name:"smokingStatus",label:"Smoking Status",required:!0,children:Object.entries(smokingStatusOptions).map(([code,text])=>jsx124(Radio4,{value:code,label:text,my:"xs"},code))}),jsx124(Group49,{justify:"flex-end",gap:4,mt:"md",children:jsx124(SubmitButton,{children:"Save"})})]})})})]})}import{Group as Group50,Modal as Modal11,SimpleGrid,Stack as Stack34,Text as Text36,Textarea as Textarea4,TextInput as TextInput25}from"@mantine/core";import{useDisclosure as useDisclosure9}from"@mantine/hooks";import{formatQuantity as formatQuantity2}from"@medplum/core";import{useMedplum as useMedplum38}from"@medplum/react-hooks";import{useCallback as useCallback23,useState as useState72}from"react";import{LOINC as LOINC3,UCUM,createReference as createReference13}from"@medplum/core";function getObservationValue(obs,component){return component?obs.component?.find(c=>c.code?.coding?.[0].code===component)?.valueQuantity:obs.valueQuantity}function createObservation(patient,encounter,code,title,valueQuantity){if(isValidNumber(valueQuantity.value))return{...createBaseObservation(patient,encounter,code,title),valueQuantity}}function createCompoundObservation(patient,encounter,code,title,components){let component=components.filter(c=>isValidNumber(c.valueQuantity?.value));if(component.length!==0)return{...createBaseObservation(patient,encounter,code,title),component}}function createBaseObservation(patient,encounter,code,title){return{resourceType:"Observation",status:"preliminary",subject:createReference13(patient),encounter:encounter?createReference13(encounter):void 0,effectiveDateTime:new Date().toISOString(),category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"vital-signs",display:"Vital Signs"}]}],code:createLoincCode(code,title)}}function createLoincCode(code,display){return{coding:[{code,display,system:LOINC3}],text:display}}function createQuantity(value,unit){return{value,system:UCUM,unit,code:unit}}function isValidNumber(value){return value!==void 0&&!Number.isNaN(value)&&Number.isFinite(value)}import{Fragment as Fragment43,jsx as jsx125,jsxs as jsxs82}from"react/jsx-runtime";var BP="85354-9",SYSTOLIC="8480-6",DIASTOLIC="8462-4",LOINC_CODES=[{name:"systolic",short:"BP Sys",code:BP,component:SYSTOLIC,title:"Blood Pressure",unit:"mm[Hg]"},{name:"diastolic",short:"BP Dias",code:BP,component:DIASTOLIC,title:"Blood Pressure",unit:"mm[Hg]"},{name:"heartRate",short:"HR",code:"8867-4",title:"Heart Rate",unit:"/min"},{name:"bodyTemperature",short:"Temp",code:"8310-5",title:"Body Temperature",unit:"Cel"},{name:"respiratoryRate",short:"RR",code:"9279-1",title:"Respiratory Rate",unit:"/min"},{name:"height",short:"Ht",code:"8302-2",title:"Height",unit:"cm"},{name:"weight",short:"Wt",code:"29463-7",title:"Weight",unit:"kg"},{name:"bmi",short:"BMI",code:"39156-5",title:"BMI",unit:"kg/m2"},{name:"oxygen",short:"O2",code:"2708-6",title:"Oxygen",unit:"%"},{name:"headCircumference",short:"HC",code:"9843-4",title:"Head Circumference",unit:"cm"}];function Vitals(props){let medplum=useMedplum38(),{patient,encounter}=props,[vitals,setVitals]=useState72(props.vitals),[opened,{open,close}]=useDisclosure9(!1),handleSubmit=useCallback23(formData=>{let newObservations=[];newObservations.push(createCompoundObservation(patient,encounter,BP,"Blood pressure",[{code:createLoincCode(SYSTOLIC,"Systolic blood pressure"),valueQuantity:createQuantity(Number.parseFloat(formData.systolic),"mm[Hg]")},{code:createLoincCode(DIASTOLIC,"Diastolic blood pressure"),valueQuantity:createQuantity(Number.parseFloat(formData.diastolic),"mm[Hg]")}]));for(let meta of LOINC_CODES)meta.component||newObservations.push(createObservation(patient,encounter,meta.code,meta.title,createQuantity(Number.parseFloat(formData[meta.name]),meta.unit)));Promise.all(newObservations.filter(Boolean).map(obs=>medplum.createResource(obs))).then(newVitals=>setVitals([...newVitals,...vitals])).catch(console.error),close()},[medplum,patient,encounter,vitals,close]);return jsxs82(Fragment43,{children:[jsx125(CollapsibleSection,{title:"Vitals",onAdd:()=>{open()},children:jsx125(Stack34,{children:LOINC_CODES.map(meta=>{let obs=vitals.find(o=>o.code?.coding?.[0].code===meta.code);return jsxs82(Group50,{align:"center",children:[jsx125(Text36,{c:"dimmed",children:meta.short}),obs&&jsx125(Text36,{children:formatQuantity2(getObservationValue(obs,meta.component))})]},meta.name)})})}),jsx125(Modal11,{opened,onClose:close,title:"Add Vitals",children:jsxs82(Form,{onSubmit:handleSubmit,children:[jsx125(SimpleGrid,{cols:2,children:LOINC_CODES.map((meta,index)=>jsx125(TextInput25,{name:meta.name,label:meta.short,description:`${meta.title} (${meta.unit})`,"data-autofocus":index===0,autoFocus:index===0},meta.name))}),jsx125(Textarea4,{name:"notes",label:"Notes"}),jsx125(Group50,{justify:"flex-end",gap:4,mt:"md",children:jsx125(SubmitButton,{children:"Save"})})]})})]})}import{jsx as jsx126,jsxs as jsxs83}from"react/jsx-runtime";var DemographicsSection={key:"demographics",title:"Demographics",component:({patient,onClickResource})=>{let languageDisplay=getPreferredLanguage(patient);return jsxs83(Stack35,{gap:"xs",py:8,children:[jsx126(PatientInfoItem,{patient,value:patient.birthDate?`${patient.birthDate} (${calculateAgeString(patient.birthDate)})`:void 0,icon:jsx126(IconCake,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Birthdate",label:"Birthdate & Age",onClickResource}),jsx126(PatientInfoItem,{patient,value:patient.gender?formatPatientGenderDisplay(patient):void 0,icon:jsx126(IconEmpathize,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Gender & Identity",label:"Gender & Identity",onClickResource}),jsx126(PatientInfoItem,{patient,value:getRace(patient)||getEthnicity(patient)?formatPatientRaceEthnicityDisplay(patient):void 0,icon:jsx126(IconBinaryTree,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Race & Ethnicity",label:"Race & Ethnicity",onClickResource}),jsx126(PatientInfoItem,{patient,value:patient.address?.[0]?formatAddress3(patient.address[0]):void 0,icon:jsx126(IconMapPin,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Location",label:"Location",onClickResource}),jsx126(PatientInfoItem,{patient,value:languageDisplay,icon:jsx126(IconLanguage,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Language",label:"Language",onClickResource}),jsx126(PatientInfoItem,{patient,value:getGeneralPractitioner(patient),icon:jsx126(IconStethoscope,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add General Practitioner",label:"General Practitioner",onClickResource})]})}},InsuranceSection={key:"insurance",title:"Insurance",searches:[{key:"coverages",resourceType:"Coverage",patientParam:"beneficiary"}],component:({results,onClickResource})=>jsx126(Insurance,{coverages:results.coverages||[],onClickResource})},AllergiesSection={key:"allergies",title:"Allergies",searches:[{key:"allergies",resourceType:"AllergyIntolerance",patientParam:"patient"}],component:({results,patient,onClickResource})=>jsx126(Allergies,{patient,allergies:results.allergies||[],onClickResource})},ProblemListSection={key:"problemList",title:"Problems",searches:[{key:"conditions",resourceType:"Condition",patientParam:"patient"}],component:({results,patient,onClickResource})=>jsx126(ProblemList,{patient,problems:results.conditions||[],onClickResource})},MedicationsSection={key:"medications",title:"Medications",searches:[{key:"medications",resourceType:"MedicationRequest",patientParam:"subject"}],component:({results,patient,onClickResource})=>jsx126(Medications,{patient,medicationRequests:results.medications||[],onClickResource})};function createLabsSection(onRequestLabs){return{key:"labs",title:"Labs",searches:[{key:"serviceRequests",resourceType:"ServiceRequest",patientParam:"subject"},{key:"diagnosticReports",resourceType:"DiagnosticReport",patientParam:"subject"}],component:({results,patient,onClickResource})=>jsx126(Labs,{patient,serviceRequests:results.serviceRequests||[],diagnosticReports:results.diagnosticReports||[],onClickResource,onRequestLabs})}}var LabsSection=createLabsSection(),SexualOrientationSection={key:"sexualOrientation",title:"Sexual Orientation",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{code:"76690-7"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(SexualOrientation,{patient,sexualOrientation:observations[0],onClickResource})}},SmokingStatusSection={key:"smokingStatus",title:"Smoking Status",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{code:"72166-2"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(SmokingStatus,{patient,smokingStatus:observations[0],onClickResource})}},VitalsSection={key:"vitals",title:"Vitals",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{category:"vital-signs"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(Vitals,{patient,vitals:observations,onClickResource})}};function createPharmaciesSection(pharmacyDialogComponent){return{key:"pharmacies",title:"Pharmacies",component:({patient,onClickResource})=>jsx126(Pharmacies,{patient,onClickResource,pharmacyDialogComponent})}}var PharmaciesSection=createPharmaciesSection();function getDefaultSections(onRequestLabs){return[DemographicsSection,InsuranceSection,AllergiesSection,ProblemListSection,MedicationsSection,createLabsSection(onRequestLabs),SexualOrientationSection,SmokingStatusSection,VitalsSection,PharmaciesSection]}import{Fragment as Fragment44,jsx as jsx127,jsxs as jsxs84}from"react/jsx-runtime";function PatientSummary(props){let medplum=useMedplum39(),{patient:propsPatient,onClickResource,onRequestLabs}=props,patient=useResource9(propsPatient),[createdDate,setCreatedDate]=useState73(),defaultSections=useMemo31(()=>getDefaultSections(onRequestLabs),[onRequestLabs]),sections=props.sections??defaultSections,{sectionData,loading,error}=usePatientSummaryData(propsPatient,sections);return useEffect24(()=>{let id=resolveId(propsPatient);id&&medplum.readHistory("Patient",id).then(history=>{let lastUpdated=history.entry?.[history.entry.length-1]?.resource?.meta?.lastUpdated;setCreatedDate(typeof lastUpdated=="string"?lastUpdated:"")}).catch(()=>{})},[propsPatient,medplum]),patient?jsxs84(Flex18,{direction:"column",gap:"xs",w:"100%",h:"100%",className:PatientSummary_default.panel,children:[jsxs84(SummaryItem,{onClick:()=>{onClickResource?.(patient)},children:[jsxs84(Group51,{align:"center",gap:"sm",p:16,children:[jsx127(ResourceAvatar,{value:patient,size:48,radius:48,style:{border:"2px solid white"}}),jsxs84(Stack36,{gap:0,style:{flex:1,minWidth:0},children:[jsx127(Tooltip6,{label:formatHumanName8(patient.name?.[0]),position:"top-start",openDelay:650,children:jsx127(Text37,{fz:"h4",fw:800,truncate:!0,style:{minWidth:0},children:formatHumanName8(patient.name?.[0])})}),(()=>{let dateString=typeof createdDate=="string"&&createdDate.length>0?createdDate:void 0;if(!dateString)return null;let d=new Date(dateString);return jsxs84(Text37,{fz:"xs",mt:-2,fw:500,c:"gray.6",truncate:!0,style:{minWidth:0},children:["Patient since ",d.getMonth()+1,"/",d.getDate(),"/",d.getFullYear()]})})()]})]}),jsx127(Divider6,{})]}),jsxs84(Stack36,{gap:"xs",px:16,pt:12,pb:16,style:{flex:2,overflowY:"auto",minHeight:0},children:[error&&jsxs84(Text37,{c:"red",fz:"sm",children:["Error loading patient summary: ",error.message]}),!loading&§ions.length>0&&jsx127(Fragment44,{children:sections.map((section,index)=>{let SectionComponent=section.component;return jsxs84("div",{children:[jsx127(SectionComponent,{patient,onClickResource,results:sectionData[index]??{}}),jsx127(Divider6,{})]},section.key)})})]})]}):null}var ThreadInbox_default={container:"ThreadInbox_container",rightBorder:"ThreadInbox_rightBorder"};import{Fragment as Fragment45,jsx as jsx128,jsxs as jsxs85}from"react/jsx-runtime";function ThreadInbox(props){let{query,threadId,subject,showPatientSummary=!1,sections,onNew,getThreadUri,uploadEnabled,onViewInDocuments,onChange,inProgressUri,completedUri,allowPatientSelection=!1}=props,navigate=useMedplumNavigate5(),[modalOpened,{open:openModal,close:closeModal}]=useDisclosure10(!1),currentSearch=useMemo32(()=>parseSearchRequest(`Communication?${query}`),[query]),searchParams=useMemo32(()=>new URLSearchParams(query),[query]),itemsPerPage=Number.parseInt(searchParams.get("_count")||"20",10),currentOffset=Number.parseInt(searchParams.get("_offset")||"0",10),currentPage=Math.floor(currentOffset/itemsPerPage)+1,status=searchParams.get("status")||"in-progress",selectedParticipants=useMemo32(()=>(currentSearch.filters?.filter(f=>f.code==="recipient")??[]).flatMap(f=>f.value.split(",").filter(Boolean).map(ref=>({reference:ref}))),[currentSearch]),{loading,error,threadMessages,selectedThread,total,handleThreadStatusChange,addThreadMessage,refreshThreadMessages}=useThreadInbox({query,threadId}),handleParticipantsChange=useCallback24(participants=>{let otherFilters=currentSearch.filters?.filter(f=>f.code!=="recipient")??[],participantRefs=participants.map(p=>p.reference).filter(Boolean),newFilters=participantRefs.length>0?[...otherFilters,{code:"recipient",operator:Operator.EQUALS,value:participantRefs.join(",")}]:otherFilters;onChange({...currentSearch,filters:newFilters,offset:0})},[currentSearch,onChange]),skeletonTitleWidths=[80,72,68,64],skeletonSubtitleWidths=[85,78,70,60];useEffect25(()=>{error&&showNotification8({title:"Error",message:normalizeErrorString10(error),color:"red"})},[error]);let handleTopicStatusChangeWithErrorHandling=async newStatus=>{handleThreadStatusChange(newStatus);try{await refreshThreadMessages()}catch(error2){showNotification8({title:"Error",message:normalizeErrorString10(error2),color:"red"})}},handleNewTopicCompletion=message=>{addThreadMessage(message),onNew(message)};return jsxs85(Fragment45,{children:[jsx128("div",{className:ThreadInbox_default.container,children:jsxs85(Flex19,{direction:"row",h:"100%",w:"100%",children:[jsx128(Flex19,{direction:"column",w:380,h:"100%",className:ThreadInbox_default.rightBorder,children:jsxs85(Paper4,{h:"100%",style:{display:"flex",flexDirection:"column"},children:[jsxs85(ScrollArea3,{style:{flex:1},scrollbarSize:10,type:"hover",scrollHideDelay:250,children:[jsxs85(Flex19,{h:64,align:"center",justify:"space-between",p:"md",children:[jsx128(Tabs,{value:status,onChange:value=>{navigate(value==="in-progress"?inProgressUri:completedUri)},variant:"unstyled",className:"pill-tabs",children:jsxs85(Tabs.List,{children:[jsx128(Tabs.Tab,{value:"in-progress",children:"In Progress"}),jsx128(Tabs.Tab,{value:"completed",children:"Completed"})]})}),jsxs85(Group52,{gap:"xs",children:[jsx128(ParticipantFilter,{selectedParticipants,onFilterChange:handleParticipantsChange}),jsx128(Tooltip7,{label:"New Message",position:"bottom",openDelay:500,children:jsx128(ActionIcon12,{radius:"xl",variant:"filled",color:"blue",size:32,onClick:openModal,children:jsx128(IconPlus,{size:16})})})]})]}),jsx128(Divider7,{}),loading?jsx128(Stack37,{gap:"md",p:"md",children:Array.from({length:10}).map((_,index)=>{let titleWidth=skeletonTitleWidths[index%skeletonTitleWidths.length],subtitleWidth=skeletonSubtitleWidths[index%skeletonSubtitleWidths.length];return jsxs85(Flex19,{gap:"sm",align:"flex-start",children:[jsx128(Skeleton2,{height:40,width:40,radius:"50%"}),jsx128(Box19,{style:{flex:1},children:jsxs85(Flex19,{direction:"column",gap:"xs",children:[jsx128(Skeleton2,{height:16,width:`${titleWidth}%`}),jsx128(Skeleton2,{height:14,width:`${subtitleWidth}%`})]})})]},index)})}):threadMessages.length>0&&jsx128(ChatList,{threads:threadMessages,selectedCommunication:selectedThread,getThreadUri}),threadMessages.length===0&&!loading&&jsx128(EmptyMessagesState,{})]}),!loading&&total!==void 0&&total>itemsPerPage&&jsx128(Box19,{p:"md",children:jsx128(Center3,{children:jsx128(Pagination,{value:currentPage,total:Math.ceil(total/itemsPerPage),onChange:page=>{let offset=(page-1)*itemsPerPage;onChange({...currentSearch,offset})},size:"sm",siblings:1,boundaries:1})})})]})}),selectedThread?jsxs85(Fragment45,{children:[jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",className:ThreadInbox_default.rightBorder,children:jsx128(Paper4,{h:"100%",children:jsxs85(Stack37,{h:"100%",gap:0,children:[jsxs85(Flex19,{h:64,align:"center",justify:"space-between",p:"md",children:[jsx128(Text38,{fw:800,truncate:!0,fz:"lg",children:selectedThread.topic?.text??"Messages"}),jsxs85(Menu5,{position:"bottom-end",shadow:"md",children:[jsx128(Menu5.Target,{children:jsx128(Button12,{variant:"light",color:getStatusColor4(selectedThread.status),rightSection:selectedThread.status==="completed"?void 0:jsx128(IconChevronDown,{size:16}),radius:"xl",size:"sm",children:selectedThread.status.split("-").map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")})}),selectedThread.status!=="completed"&&jsx128(Menu5.Dropdown,{children:jsx128(Menu5.Item,{onClick:()=>handleTopicStatusChangeWithErrorHandling("completed"),children:"Completed"})})]})]}),jsx128(Divider7,{}),jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",children:jsx128(ThreadChat,{title:"Messages",thread:selectedThread,excludeHeader:!0,uploadEnabled,onViewInDocuments},`${getReferenceString10(selectedThread)}`)})]})})}),selectedThread.subject&&showPatientSummary&&jsx128(Flex19,{direction:"column",w:300,h:"100%",children:jsx128(ScrollArea3,{p:0,h:"100%",scrollbarSize:10,type:"hover",scrollHideDelay:250,children:jsx128(PatientSummary,{patient:selectedThread.subject,sections},selectedThread.id)})})]}):jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",children:jsx128(NoMessages,{})})]})}),jsx128(NewTopicDialog,{subject,opened:modalOpened,onClose:closeModal,onSubmit:handleNewTopicCompletion,allowPatientSelection})]})}function NoMessages(){return jsx128(Center3,{h:"100%",w:"100%",children:jsxs85(Stack37,{align:"center",gap:"md",children:[jsx128(ThemeIcon,{size:64,variant:"light",color:"gray",children:jsx128(IconMessageCircle,{size:32})}),jsx128(Stack37,{align:"center",gap:"xs",children:jsx128(Text38,{size:"sm",c:"dimmed",ta:"center",children:"Select a message from the list to view details"})})]})})}function getStatusColor4(status){return status==="completed"?"green":status==="stopped"?"red":"blue"}function EmptyMessagesState(){return jsx128(Flex19,{direction:"column",h:"100%",justify:"center",align:"center",children:jsxs85(Stack37,{align:"center",gap:"md",pt:"xl",children:[jsx128(IconMessageCircle,{size:64,color:"var(--mantine-color-gray-4)"}),jsx128(Text38,{size:"lg",c:"dimmed",fw:500,children:"No messages found"})]})})}import{ActionIcon as ActionIcon14,Button as Button14,Center as Center4,Group as Group54,Loader as Loader5,ScrollArea as ScrollArea4,TextInput as TextInput26}from"@mantine/core";import{showNotification as showNotification9,updateNotification}from"@mantine/notifications";import{createReference as createReference14,normalizeErrorString as normalizeErrorString11}from"@medplum/core";import{useMedplum as useMedplum42,useResource as useResource11}from"@medplum/react-hooks";import{useCallback as useCallback25,useEffect as useEffect28,useLayoutEffect as useLayoutEffect4,useRef as useRef13,useState as useState77}from"react";var import_rfc6902=__toESM(require_rfc6902(),1);import{Table as Table2}from"@mantine/core";import{arrayify,capitalize as capitalize5,evalFhirPathTyped,getSearchParameterDetails,toTypedValue}from"@medplum/core";import{useMedplum as useMedplum40}from"@medplum/react-hooks";import{useEffect as useEffect26,useMemo as useMemo33,useState as useState75}from"react";import{Button as Button13,Table}from"@mantine/core";import{useState as useState74}from"react";var ResourceDiffRow_default={removed:"ResourceDiffRow_removed",added:"ResourceDiffRow_added"};import{Fragment as Fragment46,jsx as jsx129,jsxs as jsxs86}from"react/jsx-runtime";function ResourceDiffRow(props){let{name,path,property,originalValue,revisedValue}=props,isAttachmentType=!!property?.type?.find(t=>t.code==="Attachment"),[isCollapsed,setIsCollapsed]=useState74(isAttachmentType),toggleCollapse=()=>setIsCollapsed(prev=>!prev);return jsx129(Fragment46,{children:isAttachmentType&&!isCollapsed||!isAttachmentType?jsx129(Fragment46,{children:jsxs86(Table.Tr,{children:[jsx129(Table.Td,{children:name}),jsx129(Table.Td,{className:ResourceDiffRow_default.removed,children:originalValue&&jsx129(ResourcePropertyDisplay,{path,property,propertyType:originalValue.type,value:originalValue.value,ignoreMissingValues:!0})}),jsx129(Table.Td,{className:ResourceDiffRow_default.added,children:revisedValue&&jsx129(ResourcePropertyDisplay,{path,property,propertyType:revisedValue.type,value:revisedValue.value,ignoreMissingValues:!0})})]})}):jsxs86(Table.Tr,{children:[jsx129(Table.Td,{children:name}),jsx129(Table.Td,{colSpan:2,style:{textAlign:"right"},children:jsx129(Button13,{onClick:toggleCollapse,variant:"light",children:"Expand"})})]})})}var ResourceDiffTable_default={root:"ResourceDiffTable_root",removed:"ResourceDiffTable_removed",added:"ResourceDiffTable_added"};import{jsx as jsx130,jsxs as jsxs87}from"react/jsx-runtime";function ResourceDiffTable(props){let medplum=useMedplum40(),{original,revised}=props,[schemaLoaded,setSchemaLoaded]=useState75(!1);useEffect26(()=>{medplum.requestSchema(props.original.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.original.resourceType]);let diffTable=useMemo33(()=>{if(!schemaLoaded)return null;let typedOriginal=[toTypedValue(original)],typedRevised=[toTypedValue(revised)],result=[],patch=mergePatchOperations((0,import_rfc6902.createPatch)(original,revised));for(let op of patch){let path=op.path,fhirPath=jsonPathToFhirPath(path),property=tryGetElementDefinition(original.resourceType,fhirPath),originalValue=op.op==="add"?void 0:evalFhirPathTyped(fhirPath,typedOriginal),revisedValue=op.op==="remove"?void 0:evalFhirPathTyped(fhirPath,typedRevised);result.push({key:`op-${op.op}-${op.path}`,name:`${capitalize5(op.op)} ${fhirPath}`,path:property?.path??original.resourceType+"."+fhirPath,property,originalValue:touchUpValue(property,originalValue),revisedValue:touchUpValue(property,revisedValue)})}return result},[schemaLoaded,original,revised]);return diffTable?jsxs87(Table2,{className:ResourceDiffTable_default.root,children:[jsx130(Table2.Thead,{children:jsxs87(Table2.Tr,{children:[jsx130(Table2.Th,{}),jsx130(Table2.Th,{children:"Before"}),jsx130(Table2.Th,{children:"After"})]})}),jsx130(Table2.Tbody,{children:diffTable.map(row=>{let{key,...rest}=row;return jsx130(ResourceDiffRow,{...rest},key)})})]}):null}function mergePatchOperations(patch){let result=[];for(let patchOperation of patch){let{op,path}=patchOperation;if(path.startsWith("/meta/author")||path.startsWith("/meta/compartment")||path.startsWith("/meta/lastUpdated")||path.startsWith("/meta/versionId"))continue;let count=patch.filter(el=>el.op===op&&el.path===path).length,resultOperation={op,path};count>1&&(op==="add"||op==="remove")&&/\/[0-9-]+$/.test(path)&&(resultOperation.op="replace",resultOperation.path=path.replace(/\/[^/]+$/,"")),result.some(el=>el.op===resultOperation.op&&el.path===resultOperation.path)||result.push(resultOperation)}return result}function jsonPathToFhirPath(path){let parts=path.split("/").filter(Boolean),result="";for(let i=0;i<parts.length;i++){let part=parts[i];part==="-"?result+=".last()":/^\d+$/.test(part)?result+=`[${part}]`:(i>0&&(result+="."),result+=part)}return result.endsWith(".url")&&(result=result.replace(/\.url$/,"")),result}function tryGetElementDefinition(resourceType,fhirPath){try{return getSearchParameterDetails(resourceType,{resourceType:"SearchParameter",base:[resourceType],code:resourceType+"."+fhirPath,expression:resourceType+"."+fhirPath})?.elementDefinitions?.[0]}catch(err){console.warn("Failed to get element definition",{resourceType,fhirPath,err});return}}function touchUpValue(property,input){return input&&{type:Array.isArray(input)?input[0].type:input.type,value:fixArray(input,!!property?.isArray)}}function fixArray(input,isArray){let inputValue=arrayify(input).flatMap(v=>v.value);return isArray?inputValue:inputValue[0]}import{AccessPolicyInteraction,satisfiedAccessPolicy,tryGetProfile as tryGetProfile4}from"@medplum/core";import{useMedplum as useMedplum41,useResource as useResource10}from"@medplum/react-hooks";import{useEffect as useEffect27,useMemo as useMemo34,useState as useState76}from"react";import{jsx as jsx131}from"react/jsx-runtime";function ResourceTable(props){let{profileUrl}=props,medplum=useMedplum41(),accessPolicy=medplum.getAccessPolicy(),value=useResource10(props.value),[schemaLoaded,setSchemaLoaded]=useState76(!1);useEffect27(()=>{if(value)if(profileUrl)medplum.requestProfileSchema(profileUrl,{expandProfile:!0}).then(()=>{tryGetProfile4(profileUrl)?setSchemaLoaded(!0):console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)});else{let schemaName=value.resourceType;medplum.requestSchema(schemaName).then(()=>{setSchemaLoaded(!0)}).catch(console.error)}},[medplum,profileUrl,value]);let accessPolicyResource=useMemo34(()=>value&&satisfiedAccessPolicy(value,AccessPolicyInteraction.READ,accessPolicy),[accessPolicy,value]);return!schemaLoaded||!value?null:jsx131(BackboneElementDisplay,{path:value.resourceType,value:{type:value.resourceType,value:props.forceUseInput?props.value:value},profileUrl,ignoreMissingValues:props.ignoreMissingValues,accessPolicyResource})}import{ActionIcon as ActionIcon13,Group as Group53,Menu as Menu6,Text as Text39}from"@mantine/core";import{formatDateTime as formatDateTime4,getReferenceString as getReferenceString11}from"@medplum/core";var Timeline_default={item:"Timeline_item",itemPadding:"Timeline_itemPadding"};import{jsx as jsx132,jsxs as jsxs88}from"react/jsx-runtime";function Timeline(props){return jsx132(Container,{children:props.children})}function TimelineItem(props){let{resource,profile,padding,popupMenuItems,...others}=props,author=profile??resource.meta?.author,dateTime=props.dateTime??resource.meta?.lastUpdated;return jsxs88(Panel,{"data-testid":"timeline-item",fill:!0,...others,children:[jsxs88(Group53,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[jsx132(ResourceAvatar,{value:author,link:!0,size:"md"}),jsxs88("div",{style:{flex:1},children:[jsx132(Text39,{size:"sm",children:jsx132(ResourceName,{c:"inherit",fw:500,value:author,link:!0})}),jsxs88(Text39,{size:"xs",children:[jsx132(MedplumLink,{c:"dimmed",to:props.resource,children:formatDateTime4(dateTime)}),jsx132(Text39,{component:"span",c:"dimmed",mx:8,children:"\xB7"}),jsx132(MedplumLink,{c:"dimmed",to:props.resource,children:props.resource.resourceType})]})]}),popupMenuItems&&jsxs88(Menu6,{position:"bottom-end",shadow:"md",width:200,children:[jsx132(Menu6.Target,{children:jsx132(ActionIcon13,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${getReferenceString11(props.resource)}`,children:jsx132(IconDots,{})})}),popupMenuItems]})]}),jsx132(ErrorBoundary,{children:jsx132("div",{className:clsx_default(Timeline_default.item,{[Timeline_default.itemPadding]:padding}),children:props.children})})]})}function sortByDateAndPriority(resources,timelineResource){resources.sort((a,b)=>{let priority1=getPriorityScore(a,timelineResource),priority2=getPriorityScore(b,timelineResource);return priority1>priority2?1:priority1<priority2?-1:getTime(a,timelineResource)-getTime(b,timelineResource)})}function getPriorityScore(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){let priority=resource.priority;if(typeof priority=="string")return{stat:4,asap:3,urgent:2}[priority]??0}return 0}function getTime(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){if(resource.resourceType==="Communication"&&resource.sent)return new Date(resource.sent).getTime();if((resource.resourceType==="DiagnosticReport"||resource.resourceType==="Media"||resource.resourceType==="Observation")&&resource.issued)return new Date(resource.issued).getTime();if(resource.resourceType==="DocumentReference"&&resource.date)return new Date(resource.date).getTime()}let dateTime=resource.meta?.lastUpdated;return dateTime?new Date(dateTime).getTime():0}function isSameResourceType(a,b){return!!b&&a.resourceType===b.resourceType&&a.id===b.id}var ResourceTimeline_default={pinnedComment:"ResourceTimeline_pinnedComment"};import{jsx as jsx133,jsxs as jsxs89}from"react/jsx-runtime";function ResourceTimeline(props){let medplum=useMedplum42(),sender=medplum.getProfile(),inputRef=useRef13(null),resource=useResource11(props.value),[history,setHistory]=useState77(),[items,setItems]=useState77([]),[countToShow,setCountToShow]=useState77(10),loadTimelineResources=props.loadTimelineResources,itemsRef=useRef13(items);useLayoutEffect4(()=>{itemsRef.current=items});let sortAndSetItems=useCallback25(newItems=>{sortByDateAndPriority(newItems,resource),newItems.reverse(),setItems(newItems)},[resource]),handleBatchResponse=useCallback25(batchResponse=>{let newItems=[];for(let settledResult of batchResponse){if(settledResult.status!=="fulfilled")continue;let bundle=settledResult.value;if(bundle.type==="history"&&setHistory(bundle),bundle.entry)for(let entry of bundle.entry)newItems.push(entry.resource)}sortAndSetItems(newItems)},[sortAndSetItems]),addResource=useCallback25(resource2=>sortAndSetItems([...itemsRef.current,resource2]),[sortAndSetItems]),loadTimeline=useCallback25(()=>{let resourceType,id;"resourceType"in props.value?(resourceType=props.value.resourceType,id=props.value.id):[resourceType,id]=props.value.reference?.split("/"),loadTimelineResources(medplum,resourceType,id).then(handleBatchResponse).catch(console.error)},[medplum,props.value,loadTimelineResources,handleBatchResponse]);useEffect28(()=>loadTimeline(),[loadTimeline]);function createComment(contentString){!resource||!props.createCommunication||medplum.createResource(props.createCommunication(resource,sender,contentString)).then(result=>addResource(result)).catch(console.error)}function createMedia(attachment){!resource||!props.createMedia||medplum.createResource(props.createMedia(resource,sender,attachment)).then(result=>addResource(result)).then(()=>updateNotification({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:jsx133(IconCheck,{size:16}),autoClose:2e3})).catch(reason=>updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString11(reason),icon:jsx133(IconFileAlert,{size:16}),autoClose:2e3}))}function onUploadStart(){showNotification9({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function onUploadProgress(e){updateNotification({id:"upload-notification",loading:!0,title:"Uploading...",message:getProgressMessage(e),autoClose:!1,withCloseButton:!1})}function onUploadError(outcome){updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString11(outcome),icon:jsx133(IconFileAlert,{size:16}),autoClose:2e3})}if(!resource)return jsx133(Center4,{style:{width:"100%",height:"100%"},children:jsx133(Loader5,{})});let itemsToShow=items.filter(item=>item).slice(0,countToShow);return jsxs89(Timeline,{children:[props.createCommunication&&jsx133(Panel,{children:jsx133(Form,{testid:"timeline-form",onSubmit:formData=>{createComment(formData.text);let input=inputRef.current;input&&(input.value="",input.focus())},children:jsxs89(Group54,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[jsx133(ResourceAvatar,{value:sender}),jsx133(TextInput26,{name:"text",ref:inputRef,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),jsx133(ActionIcon14,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:jsx133(IconMessage,{size:16})}),jsx133(AttachmentButton,{securityContext:createReference14(resource),onUpload:createMedia,onUploadStart,onUploadProgress,onUploadError,children:props2=>jsx133(ActionIcon14,{...props2,radius:"xl",color:"blue",variant:"filled",children:jsx133(IconCloudUpload,{size:16})})})]})})}),itemsToShow.map(item=>{let key=`${item.resourceType}/${item.id}/${item.meta?.versionId}`,menu=props.getMenu?props.getMenu({primaryResource:resource,currentResource:item,reloadTimeline:loadTimeline}):void 0;if(item.resourceType===resource.resourceType&&item.id===resource.id)return jsx133(HistoryTimelineItem,{history,resource:item,popupMenuItems:menu},key);switch(item.resourceType){case"AuditEvent":return jsx133(AuditEventTimelineItem,{resource:item,popupMenuItems:menu},key);case"Communication":return jsx133(CommunicationTimelineItem,{resource:item,popupMenuItems:menu},key);case"DiagnosticReport":return jsx133(DiagnosticReportTimelineItem,{resource:item,popupMenuItems:menu},key);case"Media":return jsx133(MediaTimelineItem,{resource:item,popupMenuItems:menu},key);default:return jsx133(TimelineItem,{resource:item,padding:!0,children:jsx133(ResourceTable,{value:item,ignoreMissingValues:!0})},key)}}),countToShow<items.length&&jsx133(Group54,{justify:"center",pb:"lg",children:jsx133(Button14,{onClick:()=>setCountToShow(countToShow+10),children:"Show More"})})]})}function HistoryTimelineItem(props){let{history,resource,...rest}=props,previous=getPrevious(history,resource);return previous?jsx133(TimelineItem,{resource,padding:!0,...rest,children:jsx133(ResourceDiffTable,{original:previous,revised:props.resource})}):jsxs89(TimelineItem,{resource,padding:!0,...rest,children:[jsx133("h3",{children:"Created"}),jsx133(ResourceTable,{value:resource,ignoreMissingValues:!0,forceUseInput:!0})]})}function getPrevious(history,version){let entries=history.entry??[],index=entries.findIndex(entry=>entry.resource?.meta?.versionId===version.meta?.versionId);if(!(index>=entries.length-1))return entries[index+1].resource}function CommunicationTimelineItem(props){let className=!props.resource.priority||props.resource.priority==="routine"?void 0:ResourceTimeline_default.pinnedComment;return jsx133(TimelineItem,{resource:props.resource,profile:props.resource.sender,dateTime:props.resource.sent,padding:!0,className,popupMenuItems:props.popupMenuItems,children:jsx133("p",{children:props.resource.payload?.[0]?.contentString})})}function MediaTimelineItem(props){let contentType=props.resource.content?.contentType,padding=contentType&&!contentType.startsWith("image/")&&!contentType.startsWith("video/")&&contentType!=="application/pdf";return jsx133(TimelineItem,{resource:props.resource,padding:!!padding,popupMenuItems:props.popupMenuItems,children:jsx133(AttachmentDisplay,{value:props.resource.content})})}function AuditEventTimelineItem(props){return jsx133(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx133(ScrollArea4,{children:jsx133("pre",{children:props.resource.outcomeDesc})})})}function DiagnosticReportTimelineItem(props){return jsx133(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx133(DiagnosticReportDisplay,{value:props.resource})})}function getProgressMessage(e){if(e.lengthComputable){let percent=100*e.loaded/e.total;return`Uploaded: ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)} ${percent.toFixed(2)}%`}return`Uploaded: ${formatFileSize(e.loaded)}`}function formatFileSize(bytes){if(bytes===0)return"0.00 B";let e=Math.floor(Math.log(bytes)/Math.log(1024));return(bytes/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP".charAt(e)+"B"}import{jsx as jsx134}from"react/jsx-runtime";function DefaultResourceTimeline(props){let{resource,...rest}=props;return jsx134(ResourceTimeline,{value:resource,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`;return Promise.allSettled([medplum.readHistory(resourceType,id),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count:100})])},...rest})}import{createReference as createReference15}from"@medplum/core";import{jsx as jsx135}from"react/jsx-runtime";function EncounterTimeline(props){let{encounter,...rest}=props;return jsx135(ResourceTimeline,{value:encounter,loadTimelineResources:async(medplum,_resourceType,id)=>Promise.allSettled([medplum.readHistory("Encounter",id),medplum.search("Communication","encounter=Encounter/"+id),medplum.search("Media","encounter=Encounter/"+id)]),createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",encounter:createReference15(resource),subject:resource.subject,sender:createReference15(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",encounter:createReference15(resource),subject:resource.subject,operator:createReference15(operator),issued:new Date().toISOString(),content}),...rest})}import{Button as Button19,Loader as Loader7,Table as Table4}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome11}from"@medplum/core";import{useMedplum as useMedplum44}from"@medplum/react-hooks";import{memo,useEffect as useEffect32,useState as useState82}from"react";import{evalFhirPath}from"@medplum/core";import{jsx as jsx136}from"react/jsx-runtime";function FhirPathDisplay(props){let value;try{value=evalFhirPath(props.path,props.resource)}catch(err){return console.warn("FhirPathDisplay:",err),null}if(value.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${value.length} elements [${JSON.stringify(value,null,2)}]`);return jsx136(ResourcePropertyDisplay,{value:value[0]||"",propertyType:props.propertyType})}import{ActionIcon as ActionIcon16,Button as Button18,Center as Center5,Group as Group57,Loader as Loader6,Menu as Menu8,Pagination as Pagination2,Table as Table3,Text as Text41,UnstyledButton as UnstyledButton6}from"@mantine/core";import{DEFAULT_SEARCH_COUNT as DEFAULT_SEARCH_COUNT2,deepEquals as deepEquals2,formatSearchQuery,isDataTypeLoaded,normalizeOperationOutcome as normalizeOperationOutcome10}from"@medplum/core";import{useMedplum as useMedplum43}from"@medplum/react-hooks";import{useCallback as useCallback26,useEffect as useEffect31,useLayoutEffect as useLayoutEffect6,useRef as useRef16,useState as useState81}from"react";import{Box as Box20,Button as Button15,Modal as Modal12,Text as Text40}from"@mantine/core";import{jsx as jsx137,jsxs as jsxs90}from"react/jsx-runtime";function SearchExportDialog(props){return jsxs90(Modal12,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:[jsxs90(Box20,{display:"flex",style:{justifyContent:"space-between"},children:[props.exportCsv&&jsx137(ExportButton,{text:"CSV",exportLogic:props.exportCsv,onCancel:props.onCancel}),props.exportTransactionBundle&&jsx137(ExportButton,{text:"Transaction Bundle",exportLogic:props.exportTransactionBundle,onCancel:props.onCancel})]}),jsx137(Text40,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function ExportButton(props){return jsx137(Button15,{onClick:()=>{props.exportLogic(),props.onCancel()},children:`Export as ${props.text}`})}import{Button as Button16,Group as Group55,Modal as Modal13,MultiSelect as MultiSelect2,Stack as Stack38}from"@mantine/core";import{getDataType as getDataType2,getSearchParameters,sortStringArray,stringify as stringify3}from"@medplum/core";import{useEffect as useEffect29,useMemo as useMemo35,useRef as useRef14,useState as useState78}from"react";import{capitalize as capitalize6,DEFAULT_SEARCH_COUNT,evalFhirPathTyped as evalFhirPathTyped2,formatDateTime as formatDateTime5,Operator as Operator2}from"@medplum/core";import{Fragment as Fragment47,jsx as jsx138}from"react/jsx-runtime";var searchParamToOperators={string:[Operator2.EQUALS,Operator2.NOT,Operator2.CONTAINS,Operator2.EXACT],fulltext:[Operator2.EQUALS,Operator2.NOT,Operator2.CONTAINS,Operator2.EXACT],token:[Operator2.EQUALS,Operator2.NOT,Operator2.TEXT],reference:[Operator2.EQUALS,Operator2.NOT],numeric:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS],quantity:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS],date:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS,Operator2.STARTS_AFTER,Operator2.ENDS_BEFORE,Operator2.APPROXIMATELY],datetime:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS,Operator2.STARTS_AFTER,Operator2.ENDS_BEFORE,Operator2.APPROXIMATELY],uri:[Operator2.EQUALS,Operator2.NOT,Operator2.ABOVE,Operator2.BELOW]},operatorNames={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",sw:"starts with",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function setFilters(definition,filters){return{...definition,filters,offset:0,name:void 0}}function clearFilters(definition){return setFilters(definition,[])}function clearFiltersOnField(definition,code){return setFilters(definition,(definition.filters??[]).filter(f=>f.code!==code))}function addFilter(definition,field,op,value,opt_clear){opt_clear&&(definition=clearFiltersOnField(definition,field));let nextFilters=[];return definition.filters&&nextFilters.push(...definition.filters),nextFilters.push({code:field,operator:op,value:value??""}),setFilters(definition,nextFilters)}function addField(definition,field){if(definition.fields?.includes(field))return definition;let newFields=[];return definition.fields&&newFields.push(...definition.fields),newFields.push(field),{...definition,fields:newFields,name:void 0}}function deleteFilter(definition,index){if(!definition.filters)return definition;let newFilters=[...definition.filters];return newFilters.splice(index,1),{...definition,filters:newFilters,name:void 0}}function addYesterdayFilter(definition,field){return addDayFilter(definition,field,-1)}function addTodayFilter(definition,field){return addDayFilter(definition,field,0)}function addTomorrowFilter(definition,field){return addDayFilter(definition,field,1)}function addDayFilter(definition,field,delta){let startTime=new Date;startTime.setDate(startTime.getDate()+delta),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setDate(endTime.getDate()+1),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addNext24HoursFilter(definition,field){let now=new Date,endTime=new Date(now.getTime()+1440*60*1e3);return addDateFilterBetween(definition,field,now,endTime)}function addLastMonthFilter(definition,field){return addMonthFilter(definition,field,-1)}function addThisMonthFilter(definition,field){return addMonthFilter(definition,field,0)}function addNextMonthFilter(definition,field){return addMonthFilter(definition,field,1)}function addMonthFilter(definition,field,delta){let startTime=new Date;startTime.setMonth(startTime.getMonth()+delta),startTime.setDate(1),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setMonth(endTime.getMonth()+1),endTime.setDate(1),endTime.setHours(0,0,0,0),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addYearToDateFilter(definition,field){let startTime=new Date;return startTime.setMonth(0),startTime.setDate(1),startTime.setHours(0,0,0,0),addDateFilterBetween(definition,field,startTime,new Date)}function addDateFilterBetween(definition,field,d1,d2){return definition=clearFiltersOnField(definition,field),definition=addDateFilterImpl(definition,field,Operator2.GREATER_THAN_OR_EQUALS,d1),definition=addDateFilterImpl(definition,field,Operator2.LESS_THAN_OR_EQUALS,d2),definition}function addDateFilterImpl(definition,field,op,value){return addFilter(definition,field,op,value.toISOString())}function addMissingFilter(definition,field,value=!0){return addFilter(definition,field,Operator2.MISSING,value.toString())}function setOffset(definition,offset){return definition.offset===offset?definition:{...definition,offset,name:void 0}}function setPage(definition,page){let count=definition.count??DEFAULT_SEARCH_COUNT,newOffset=(page-1)*count;return setOffset(definition,newOffset)}function setSort(definition,sort,desc){return sort===getSortField(definition)&&desc!==void 0&&desc===isSortDescending(definition)?definition:{...definition,sortRules:[{code:sort,descending:!!desc}],name:void 0}}function toggleSort(definition,key){let desc=!1;return getSortField(definition)===key&&(desc=!isSortDescending(definition)),setSort(definition,key,desc)}function getSortField(definition){let sortRules=definition.sortRules;if(!sortRules||sortRules.length===0)return;let field=sortRules[0].code;return field.startsWith("-")?field.substr(1):field}function isSortDescending(definition){let sortRules=definition.sortRules;return!sortRules||sortRules.length===0?!1:!!sortRules[0].descending}function getSearchOperators(searchParam){return searchParamToOperators[searchParam.type]}function getOpString(op){return operatorNames[op]??""}function buildFieldNameString(key){let tmp=key;return tmp.includes(".")&&(tmp=tmp.split(".").pop()),tmp==="versionId"?"Version ID":(tmp=tmp.replace("[x]",""),tmp=tmp.replaceAll(/([A-Z])/g," $1"),tmp=tmp.replaceAll(/[-_]/g," "),tmp=tmp.replaceAll(/\s+/g," "),tmp=tmp.trim(),tmp.toLowerCase()==="id"?"ID":tmp.split(/\s/).map(capitalize6).join(" "))}function renderValue(resource,field){let key=field.name;return key==="id"?jsx138(MedplumLink,{to:`/${resource.resourceType}/${resource.id}`,children:resource.id}):key==="meta.versionId"?resource.meta?.versionId:key==="_lastUpdated"?formatDateTime5(resource.meta?.lastUpdated):`${resource.resourceType}.${field.name}`===field.elementDefinition?.path?renderPropertyValue(resource,field.elementDefinition):field.searchParams?.length===1&&field.name===field.searchParams[0].code?renderSearchParameterValue(resource,field.searchParams[0]):null}function renderPropertyValue(resource,elementDefinition){let path=elementDefinition.path?.split(".")?.pop()?.replaceAll("[x]","")??"",[value,propertyType]=getValueAndType({type:resource.resourceType,value:resource},path);return value?jsx138(ResourcePropertyDisplay,{path:elementDefinition.path,property:elementDefinition,propertyType,value,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function renderSearchParameterValue(resource,searchParam){let value=evalFhirPathTyped2(searchParam.expression,[{type:resource.resourceType,value:resource}]);return!value||value.length===0?null:jsx138(Fragment47,{children:value.map((v,index)=>jsx138(ResourcePropertyDisplay,{propertyType:v.type,value:v.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${index}-${value.length}`))})}import{jsx as jsx139,jsxs as jsxs91}from"react/jsx-runtime";function SearchFieldEditor(props){let wasDropdownOpen=useRef14(!1),[state,setState]=useState78({search:JSON.parse(stringify3(props.search))}),[isDropdownOpen,setIsDropdownOpen]=useState78(!1);useEffect29(()=>{setState({search:props.search})},[props.search]);let allFields=useMemo35(()=>{if(!props.visible)return[];let resourceType=props.search.resourceType,typeSchema=getDataType2(resourceType),searchParams=getSearchParameters(resourceType);return sortStringArray(getFieldsList(typeSchema,searchParams)).map(field=>({value:field,label:buildFieldNameString(field)}))},[props.visible,props.search.resourceType]);function handleChange(newFields){setState({search:{...state.search,fields:newFields}})}return jsx139(Modal13,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>{props.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{wasDropdownOpen.current=isDropdownOpen},onClick:()=>{wasDropdownOpen.current||props.onCancel(),wasDropdownOpen.current=!1},children:jsx139("div",{"data-testid":"overlay-child"})},children:jsxs91(Stack38,{children:[jsx139(MultiSelect2,{style:{width:550},placeholder:"Select fields to display",data:allFields,value:state.search.fields??[],onChange:handleChange,onDropdownOpen:()=>setIsDropdownOpen(!0),onDropdownClose:()=>setIsDropdownOpen(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),jsx139(Group55,{justify:"flex-end",children:jsx139(Button16,{onClick:()=>props.onOk(state.search),children:"OK"})})]})})}function getFieldsList(typeSchema,searchParams){let result=[],keys=new Set,names=new Set;for(let key of Object.keys(typeSchema.elements))result.push(key),keys.add(key.toLowerCase()),names.add(buildFieldNameString(key));if(searchParams)for(let code of Object.keys(searchParams)){let name=buildFieldNameString(code);!keys.has(code)&&!names.has(name)&&(result.push(code),keys.add(code),names.add(name))}return result}import{ActionIcon as ActionIcon15,Group as Group56,Modal as Modal14,NativeSelect as NativeSelect11}from"@mantine/core";import{Operator as Operator3,deepClone as deepClone2,getSearchParameters as getSearchParameters2}from"@medplum/core";import{useEffect as useEffect30,useLayoutEffect as useLayoutEffect5,useRef as useRef15,useState as useState79}from"react";import{Checkbox as Checkbox7,TextInput as TextInput27}from"@mantine/core";import{getSearchParameterDetails as getSearchParameterDetails2,SearchParameterType}from"@medplum/core";import{jsx as jsx140}from"react/jsx-runtime";function SearchFilterValueInput(props){let details=getSearchParameterDetails2(props.resourceType,props.searchParam),name=props.name??"filter-value";switch(details.type){case SearchParameterType.REFERENCE:return jsx140(ReferenceInput,{name,defaultValue:props.defaultValue?{reference:props.defaultValue}:void 0,targetTypes:props.searchParam.target,autoFocus:props.autoFocus,onChange:newReference=>{newReference?props.onChange(newReference.reference):props.onChange("")}});case SearchParameterType.BOOLEAN:return jsx140(Checkbox7,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultChecked:props.defaultValue==="true",autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.checked.toString())});case SearchParameterType.DATE:return jsx140(TextInput27,{type:"date",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType.DATETIME:return jsx140(DateTimeInput,{name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:props.onChange});case SearchParameterType.NUMBER:return jsx140(TextInput27,{type:"number",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType.QUANTITY:return jsx140(QuantityInput,{name,path:"",defaultValue:tryParseQuantity(props.defaultValue),autoFocus:props.autoFocus,onChange:newQuantity=>{newQuantity?props.onChange(`${newQuantity.value}`):props.onChange("")}});default:return jsx140(TextInput27,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value),placeholder:"Search value"})}}function tryParseQuantity(value){if(value){let[valueString,systemString,unitString]=value.split("|");if(valueString)return{value:Number.parseFloat(valueString),system:systemString,unit:unitString}}}import{jsx as jsx141,jsxs as jsxs92}from"react/jsx-runtime";function SearchFilterEditor(props){let[search,setSearch]=useState79(deepClone2(props.search)),searchRef=useRef15(search);useLayoutEffect5(()=>{searchRef.current=search}),useEffect30(()=>{setSearch(deepClone2(props.search))},[props.search]);function onAddFilter(filter){setSearch(addFilter(searchRef.current,filter.code,filter.operator,filter.value))}let resourceType=props.search.resourceType,searchParams=getSearchParameters2(resourceType)??{},filters=search.filters||[];return jsx141(Modal14,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:props.visible,onClose:props.onCancel,children:jsxs92(Form,{onSubmit:()=>props.onOk(searchRef.current),children:[jsxs92("div",{children:[jsxs92("table",{children:[jsxs92("colgroup",{children:[jsx141("col",{style:{width:200}}),jsx141("col",{style:{width:200}}),jsx141("col",{style:{width:380}}),jsx141("col",{style:{width:40}})]}),jsx141("thead",{children:jsxs92("tr",{children:[jsx141("th",{children:"Field"}),jsx141("th",{children:"Operation"}),jsx141("th",{children:"Value"}),jsx141("th",{})]})}),jsx141("tbody",{children:filters.map((filter,index)=>jsx141(FilterRowInput,{id:`filter-${index}-row`,resourceType,searchParams,value:filter,onChange:newFilter=>{let newFilters=[...filters];newFilters[index]=newFilter,setSearch(setFilters(searchRef.current,newFilters))},onDelete:()=>setSearch(deleteFilter(searchRef.current,index))},`filter-${index}-row`))})]}),jsx141(ArrayAddButton,{propertyDisplayName:"Filter",onClick:()=>onAddFilter({})})]}),jsx141(Group56,{justify:"flex-end",mt:"xl",children:jsx141(SubmitButton,{children:"OK"})})]})})}function FilterRowInput(props){let value=props.value;function setFilterCode(newCode){props.onChange({code:newCode,operator:Operator3.EQUALS,value:""})}function setFilterOperator(newOperator){props.onChange({code:value.code,operator:newOperator,value:""})}function setFilterValue(newFilterValue){props.onChange({code:value.code,operator:value.operator,value:newFilterValue})}let searchParam=props.searchParams[value.code],operators=searchParam&&getSearchOperators(searchParam);return jsxs92("tr",{children:[jsx141("td",{children:jsx141(NativeSelect11,{"data-testid":`${props.id}-filter-field`,defaultValue:props.value.code,onChange:e=>setFilterCode(e.currentTarget.value),data:["",...Object.keys(props.searchParams).map(param=>({value:param,label:buildFieldNameString(param)}))]})}),jsx141("td",{children:operators&&jsx141(NativeSelect11,{"data-testid":`${props.id}-filter-operation`,defaultValue:value.operator,onChange:e=>setFilterOperator(e.currentTarget.value),data:["",...operators.map(op=>({value:op,label:getOpString(op)}))]},`${props.id}-filter-value-${props.value.code}`)}),jsx141("td",{children:searchParam&&value.operator&&jsx141(SearchFilterValueInput,{name:`${props.id}-filter-value`,resourceType:props.resourceType,searchParam,defaultValue:value.value,onChange:setFilterValue},`${props.id}-filter-value-${props.value.code}-${props.value.operator}`)}),jsx141("td",{children:props.onDelete&&jsx141(ActionIcon15,{variant:"outline",color:"red",radius:"xl","aria-label":"Delete filter",onClick:props.onDelete,children:jsx141(IconX,{style:{width:"70%",height:"70%"},stroke:1.5})})})]})}import{Button as Button17,Grid,Modal as Modal15}from"@mantine/core";import{useState as useState80}from"react";import{jsx as jsx142,jsxs as jsxs93}from"react/jsx-runtime";function SearchFilterValueDialog(props){let[value,setValue]=useState80(props.defaultValue??"");if(!props.searchParam||!props.filter)return null;function onOk(){props.onOk({...props.filter,value})}return jsx142(Modal15,{title:props.title,size:"xl",opened:props.visible,onClose:props.onCancel,children:jsx142(Form,{onSubmit:onOk,children:jsxs93(Grid,{children:[jsx142(Grid.Col,{span:10,children:jsx142(SearchFilterValueInput,{resourceType:props.resourceType,searchParam:props.searchParam,defaultValue:value,autoFocus:!0,onChange:setValue})}),jsx142(Grid.Col,{span:2,children:jsx142(Button17,{onClick:onOk,fullWidth:!0,children:"OK"})})]})})})}import{formatDateTime as formatDateTime6,getSearchParameterDetails as getSearchParameterDetails3,globalSchema,Operator as Operator4,SearchParameterType as SearchParameterType2}from"@medplum/core";import{Fragment as Fragment48,jsx as jsx143}from"react/jsx-runtime";function SearchFilterValueDisplay(props){let{resourceType,filter}=props,searchParam=globalSchema.types[resourceType].searchParams?.[filter.code];if(searchParam){if(searchParam.type==="reference"&&(filter.operator===Operator4.EQUALS||filter.operator===Operator4.NOT_EQUALS))return jsx143(ResourceName,{value:{reference:filter.value}});let searchParamDetails=getSearchParameterDetails3(resourceType,searchParam);if(filter.code==="_lastUpdated"||searchParamDetails.type===SearchParameterType2.DATETIME)return jsx143(Fragment48,{children:formatDateTime6(filter.value)})}return jsx143(Fragment48,{children:filter.value})}import{Menu as Menu7}from"@mantine/core";import{Operator as Operator5}from"@medplum/core";import{Fragment as Fragment49,jsx as jsx144,jsxs as jsxs94}from"react/jsx-runtime";function SearchPopupMenu(props){if(!props.searchParams)return null;function onSort(searchParam,desc){onChange(setSort(props.search,searchParam.code,desc))}function onClear(searchParam){onChange(clearFiltersOnField(props.search,searchParam.code))}function onPrompt(searchParam,operator){props.onPrompt(searchParam,{code:searchParam.code,operator,value:""})}function onChange(definition){props.onChange(definition)}return props.searchParams.length===1?jsx144(SearchParameterSubMenu,{search:props.search,searchParam:props.searchParams[0],onSort,onPrompt,onChange,onClear}):jsx144(Menu7.Dropdown,{children:props.searchParams.map(searchParam=>jsx144(Menu7.Item,{children:buildFieldNameString(searchParam.code)},searchParam.code))})}function SearchParameterSubMenu(props){switch(props.searchParam.type){case"date":return jsx144(DateFilterSubMenu,{...props});case"number":case"quantity":return jsx144(NumericFilterSubMenu,{...props});case"reference":return jsx144(ReferenceFilterSubMenu,{...props});case"string":return jsx144(TextFilterSubMenu,{...props});case"token":return jsx144(TokenFilterSubMenu,{...props});case"uri":return jsx144(UriFilterSubMenu,{...props});default:return jsxs94(Fragment49,{children:["Unknown search param type: ",props.searchParam.type]})}}function DateFilterSubMenu(props){let{searchParam}=props,code=searchParam.code;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Oldest to Newest"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Newest to Oldest"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT_EQUALS),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.ENDS_BEFORE),children:"Before..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.STARTS_AFTER),children:"After..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconBracketsContain,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Between..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addTomorrowFilter(props.search,code)),children:"Tomorrow"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addTodayFilter(props.search,code)),children:"Today"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addYesterdayFilter(props.search,code)),children:"Yesterday"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addNext24HoursFilter(props.search,code)),children:"Next 24 Hours"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addNextMonthFilter(props.search,code)),children:"Next Month"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addThisMonthFilter(props.search,code)),children:"This Month"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addLastMonthFilter(props.search,code)),children:"Last Month"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addYearToDateFilter(props.search,code)),children:"Year to date"}),jsx144(CommonMenuItems,{...props})]})}function NumericFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Smallest to Largest"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Largest to Smallest"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT_EQUALS),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.GREATER_THAN),children:"Greater than..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.LESS_THAN),children:"Less than..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),jsx144(CommonMenuItems,{...props})]})}function ReferenceFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(CommonMenuItems,{...props})]})}function TextFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort A to Z"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Z to A"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconBucket,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.CONTAINS),children:"Contains..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconBucketOff,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Does not contain..."}),jsx144(CommonMenuItems,{...props})]})}function TokenFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.TEXT),children:"Text contains..."}),jsx144(CommonMenuItems,{...props})]})}function UriFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(CommonMenuItems,{...props})]})}function CommonMenuItems(props){let{searchParam}=props,code=searchParam.code;return jsxs94(Fragment49,{children:[jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconBleach,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code)),children:"Missing"}),jsx144(Menu7.Item,{leftSection:jsx144(IconBleachOff,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code,!1)),children:"Not missing"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconX,{size:14}),onClick:()=>props.onClear(searchParam),children:"Clear filters"})]})}function getPaginationControlProps(controlName){switch(controlName){case"next":return{"aria-label":"Next page"};case"previous":return{"aria-label":"Previous page"};case"first":return{"aria-label":"First page"};case"last":return{"aria-label":"Last page"};default:return{}}}var SearchControl_default={root:"SearchControl_root",table:"SearchControl_table",tr:"SearchControl_tr",th:"SearchControl_th",control:"SearchControl_control",icon:"SearchControl_icon"};import{getElementDefinition as getElementDefinition2,getSearchParameter,getSearchParameterDetails as getSearchParameterDetails4,getSearchParameters as getSearchParameters3}from"@medplum/core";function getFieldDefinitions(search){let resourceType=search.resourceType,fields=[];for(let name of search.fields||["id","_lastUpdated"])fields.push(getFieldDefinition(resourceType,name));return fields}function getFieldDefinition(resourceType,name){if(name==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(name==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};let exactElementDefinition=getElementDefinition2(resourceType,name),exactSearchParam=getSearchParameter(resourceType,name.toLowerCase());if(exactElementDefinition&&exactSearchParam)return{name,elementDefinition:exactElementDefinition,searchParams:[exactSearchParam]};if(exactElementDefinition){let allSearchParams=getSearchParameters3(resourceType),searchParams;if(allSearchParams){let pathRegex=new RegExp(`${resourceType}\\.${name.replaceAll("[x]","")}([^\\w-]|$)`);searchParams=Object.values(allSearchParams).filter(p=>!!p.expression&&pathRegex.test(p?.expression)),searchParams.length===0&&(searchParams=void 0)}return{name,elementDefinition:exactElementDefinition,searchParams}}if(exactSearchParam){let details=getSearchParameterDetails4(resourceType,exactSearchParam);return{name,elementDefinition:details.elementDefinitions?.[0],searchParams:[exactSearchParam]}}return{name}}import{Fragment as Fragment50,jsx as jsx145,jsxs as jsxs95}from"react/jsx-runtime";var SearchChangeEvent=class extends Event{constructor(definition){super("change");__publicField(this,"definition");this.definition=definition}},SearchLoadEvent=class extends Event{constructor(response){super("load");__publicField(this,"response");this.response=response}},SearchClickEvent=class extends Event{constructor(resource,browserEvent){super("click");__publicField(this,"resource");__publicField(this,"browserEvent");this.resource=resource,this.browserEvent=browserEvent}};function SearchControl(props){let medplum=useMedplum43(),[outcome,setOutcome]=useState81(),{search,onLoad}=props,[memoizedSearch,setMemoizedSearch]=useState81(search);deepEquals2(search,memoizedSearch)||setMemoizedSearch(search);let[state,setState]=useState81({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),stateRef=useRef16(state);useLayoutEffect6(()=>{stateRef.current=state});let total=memoizedSearch.total??"accurate",loadResults=useCallback26(options=>{setOutcome(void 0),medplum.requestSchema(memoizedSearch.resourceType).then(()=>medplum.search(memoizedSearch.resourceType,formatSearchQuery({...memoizedSearch,total,fields:void 0}),options)).then(response=>{setState({...stateRef.current,searchResponse:response}),onLoad&&onLoad(new SearchLoadEvent(response))}).catch(reason=>{setState({...stateRef.current,searchResponse:void 0}),setOutcome(normalizeOperationOutcome10(reason))})},[medplum,memoizedSearch,total,onLoad]),refreshResults=useCallback26(()=>{setState({...stateRef.current,searchResponse:void 0}),loadResults({cache:"reload"})},[loadResults]);useEffect31(()=>{loadResults()},[loadResults]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...stateRef.current.selected};checked?newSelected[id]=!0:delete newSelected[id],setState({...stateRef.current,selected:newSelected})}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},searchResponse=stateRef.current.searchResponse;checked&&searchResponse?.entry&&searchResponse.entry.forEach(entry=>{entry.resource?.id&&(newSelected[entry.resource.id]=!0)}),setState({...stateRef.current,selected:newSelected})}function isAllSelected(){if(!state.searchResponse?.entry||state.searchResponse.entry.length===0)return!1;for(let e of state.searchResponse.entry)if(e.resource?.id&&!state.selected[e.resource.id])return!1;return!0}function emitSearchChange(newSearch){props.onChange&&props.onChange(new SearchChangeEvent(newSearch))}function handleRowClick(e,resource){if(isCheckboxCell(e.target)||e.button===2)return;killEvent(e);let isAux=isAuxClick(e);!isAux&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),isAux&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e))}function isExportPassed(){return!!(props.onExport??props.onExportCsv??props.onExportTransactionBundle)}if(outcome)return jsx145(OperationOutcomeAlert,{outcome});if(!isDataTypeLoaded(memoizedSearch.resourceType))return jsx145(Center5,{style:{width:"100%",height:"100%"},children:jsx145(Loader6,{})});let checkboxColumn=props.checkboxesEnabled,fields=getFieldDefinitions(memoizedSearch),resourceType=memoizedSearch.resourceType,lastResult=state.searchResponse,resources=lastResult?.entry?.map(e=>e.resource),buttonVariant="subtle",buttonColor="gray",iconSize=16,isMobile=window.innerWidth<768;return jsxs95("div",{className:SearchControl_default.root,"data-testid":"search-control",children:[!props.hideToolbar&&jsxs95(Group57,{justify:"space-between",mb:"xl",children:[jsxs95(Group57,{gap:2,children:[jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconColumns,{size:iconSize}),onClick:()=>setState({...stateRef.current,fieldEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Fields"}),jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconFilter,{size:iconSize}),onClick:()=>setState({...stateRef.current,filterEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Filters"}),props.onNew&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconFilePlus,{size:iconSize}),onClick:props.onNew,children:"New..."}),!isMobile&&isExportPassed()&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconTableExport,{size:iconSize}),onClick:props.onExport?props.onExport:()=>setState({...stateRef.current,exportDialogVisible:!0,dialogOpenTime:Date.now()}),children:"Export..."}),!isMobile&&props.onDelete&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconTrash,{size:iconSize}),onClick:()=>props.onDelete(Object.keys(state.selected)),children:"Delete..."}),!isMobile&&props.onBulk&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconBoxMultiple,{size:iconSize}),onClick:()=>props.onBulk(Object.keys(state.selected)),children:"Bulk..."})]}),jsxs95(Group57,{gap:2,children:[lastResult&&jsxs95(Text41,{size:"xs",c:"dimmed","data-testid":"count-display",children:[getStart(memoizedSearch,lastResult).toLocaleString(),"-",getEnd(memoizedSearch,lastResult).toLocaleString(),lastResult.total!==void 0&&` of ${memoizedSearch.total==="estimate"?"~":""}${lastResult.total?.toLocaleString()}`]}),jsx145(ActionIcon16,{variant:buttonVariant,color:buttonColor,title:"Refresh",onClick:refreshResults,children:jsx145(IconRefresh,{size:iconSize})})]})]}),jsxs95(Table3,{className:SearchControl_default.table,children:[jsxs95(Table3.Thead,{children:[jsxs95(Table3.Tr,{children:[checkboxColumn&&jsx145(Table3.Th,{children:jsx145("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx145(Table3.Th,{children:jsxs95(Menu8,{shadow:"md",width:240,position:"bottom-end",children:[jsx145(Menu8.Target,{children:jsx145(UnstyledButton6,{className:SearchControl_default.control,p:2,children:jsxs95(Group57,{justify:"space-between",wrap:"nowrap",children:[jsx145(Text41,{fw:500,children:buildFieldNameString(field.name)}),jsx145(Center5,{className:SearchControl_default.icon,children:jsx145(IconAdjustmentsHorizontal,{size:14,stroke:1.5})})]})})}),jsx145(SearchPopupMenu,{search:memoizedSearch,searchParams:field.searchParams,onPrompt:(searchParam,filter)=>{setState({...stateRef.current,filterDialogVisible:!0,filterDialogSearchParam:searchParam,filterDialogFilter:filter,dialogOpenTime:Date.now()})},onChange:result=>{emitSearchChange(result)}})]})},field.name))]}),!props.hideFilters&&jsxs95(Table3.Tr,{children:[checkboxColumn&&jsx145(Table3.Th,{}),fields.map(field=>jsx145(Table3.Th,{children:field.searchParams&&jsx145(FilterDescription,{resourceType,searchParams:field.searchParams,filters:memoizedSearch.filters})},field.name))]})]}),jsx145(Table3.Tbody,{children:resources?.map(resource=>resource&&jsxs95(Table3.Tr,{className:SearchControl_default.tr,"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx145(Table3.Td,{children:jsx145("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!state.selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx145(Table3.Td,{children:renderValue(resource,field)},field.name))]},resource.id))})]}),!resources?.length&&jsx145(Container,{children:jsx145(Center5,{style:{height:150},children:jsx145(Text41,{size:"xl",c:"dimmed",children:"No results"})})}),lastResult&&jsx145(Center5,{m:"md",p:"md",children:jsx145(Pagination2,{value:getPage(memoizedSearch),total:getTotalPages(memoizedSearch,lastResult),onChange:newPage=>emitSearchChange(setPage(memoizedSearch,newPage)),getControlProps:getPaginationControlProps})}),jsx145(SearchFieldEditor,{search:memoizedSearch,visible:state.fieldEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,fieldEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,fieldEditorVisible:!1})}},`search-field-editor-${state.dialogOpenTime}`),jsx145(SearchFilterEditor,{search:memoizedSearch,visible:state.filterEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,filterEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterEditorVisible:!1})}},`search-filter-editor-${state.dialogOpenTime}`),jsx145(SearchExportDialog,{visible:state.exportDialogVisible,exportCsv:props.onExportCsv,exportTransactionBundle:props.onExportTransactionBundle,onCancel:()=>{setState({...stateRef.current,exportDialogVisible:!1})}},`search-export-dialog-${state.dialogOpenTime}`),jsx145(SearchFilterValueDialog,{visible:state.filterDialogVisible,title:state.filterDialogSearchParam?.code?buildFieldNameString(state.filterDialogSearchParam.code):"",resourceType,searchParam:state.filterDialogSearchParam,filter:state.filterDialogFilter,defaultValue:"",onOk:filter=>{emitSearchChange(addFilter(memoizedSearch,filter.code,filter.operator,filter.value)),setState({...stateRef.current,filterDialogVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterDialogVisible:!1})}},`search-filter-dialog-${state.dialogOpenTime}`)]})}function FilterDescription(props){let filters=(props.filters??[]).filter(f=>props.searchParams.find(p=>p.code===f.code));return filters.length===0?jsx145("span",{children:"no filters"}):jsx145(Fragment50,{children:filters.map(filter=>jsxs95("div",{children:[getOpString(filter.operator),"\xA0",jsx145(SearchFilterValueDisplay,{resourceType:props.resourceType,filter})]},`filter-${filter.code}-${filter.operator}-${filter.value}`))})}function getPage(search){return Math.floor((search.offset??0)/(search.count??DEFAULT_SEARCH_COUNT2))+1}function getTotalPages(search,lastResult){let pageSize=search.count??DEFAULT_SEARCH_COUNT2,total=getTotal(search,lastResult);return Math.ceil(total/pageSize)}function getStart(search,lastResult){return Math.min(getTotal(search,lastResult),(search.offset??0)+1)}function getEnd(search,lastResult){return Math.max(getStart(search,lastResult)+(lastResult.entry?.length??0)-1,0)}function getTotal(search,lastResult){let total=lastResult.total;return total===void 0&&(total=(search.offset??0)+(lastResult.entry?.length??0)+(lastResult.link?.some(l=>l.relation==="next")?1:0)),total}import{jsx as jsx146,jsxs as jsxs96}from"react/jsx-runtime";function FhirPathTable(props){let medplum=useMedplum44(),[schemaLoaded,setSchemaLoaded]=useState82(!1),[outcome,setOutcome]=useState82(),{query,fields}=props,[response,setResponse]=useState82(),[selected,setSelected]=useState82({});useEffect32(()=>{setOutcome(void 0),medplum.graphql(query).then(setResponse).catch(err=>setOutcome(normalizeOperationOutcome11(err)))},[medplum,query]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...selected};checked?newSelected[id]=!0:delete newSelected[id],setSelected(newSelected)}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},resources=response?.data.ResourceList;checked&&resources&&resources.forEach(resource=>{resource.id&&(newSelected[resource.id]=!0)}),setSelected(newSelected)}function isAllSelected(){let resources=response?.data.ResourceList;if(!resources||resources.length===0)return!1;for(let resource of resources)if(resource.id&&!selected[resource.id])return!1;return!0}function handleRowClick(e,resource){isCheckboxCell(e.target)||(killEvent(e),e.button!==1&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),e.button===1&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e)))}if(useEffect32(()=>{medplum.requestSchema(props.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.resourceType]),!schemaLoaded)return jsx146(Loader7,{});let checkboxColumn=props.checkboxesEnabled;return jsxs96("div",{onContextMenu:e=>killEvent(e),"data-testid":"search-control",children:[jsxs96(Table4,{children:[jsx146(Table4.Thead,{children:jsxs96(Table4.Tr,{children:[checkboxColumn&&jsx146(Table4.Th,{children:jsx146("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx146(Table4.Th,{children:field.name},field.name))]})}),jsx146(Table4.Tbody,{children:response?.data.ResourceList.map(resource=>resource&&jsxs96(Table4.Tr,{"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx146(Table4.Td,{children:jsx146("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx146(Table4.Td,{children:jsx146(FhirPathDisplay,{propertyType:field.propertyType,path:field.fhirPath,resource})},field.name))]},resource.id))})]}),response?.data.ResourceList.length===0&&jsx146("div",{"data-testid":"empty-search",children:"No results"}),outcome&&jsx146("div",{"data-testid":"search-error",children:jsx146("pre",{style:{textAlign:"left"},children:JSON.stringify(outcome,void 0,2)})}),props.onBulk&&jsx146(Button19,{onClick:()=>props.onBulk(Object.keys(selected)),children:"Bulk..."})]})}var MemoizedFhirPathTable=memo(FhirPathTable);import{ScrollArea as ScrollArea5}from"@mantine/core";var InfoBar_default={root:"InfoBar_root",entry:"InfoBar_entry",key:"InfoBar_key",value:"InfoBar_value"};import{jsx as jsx147}from"react/jsx-runtime";function InfoBar(props){return jsx147(ScrollArea5,{children:jsx147("div",{className:InfoBar_default.root,children:props.children})})}InfoBar.Entry=function(props){return jsx147("div",{className:InfoBar_default.entry,children:props.children})};InfoBar.Key=function(props){return jsx147("div",{className:InfoBar_default.key,children:props.children})};InfoBar.Value=function(props){return jsx147("div",{className:InfoBar_default.value,children:props.children})};import{Anchor as Anchor11,Tabs as Tabs2}from"@mantine/core";import{isString,locationUtils as locationUtils5}from"@medplum/core";import{useMedplumNavigate as useMedplumNavigate6}from"@medplum/react-hooks";import{useState as useState83}from"react";var LinkTabs_default={list:"LinkTabs_list",link:"LinkTabs_link"};import{jsx as jsx148,jsxs as jsxs97}from"react/jsx-runtime";function LinkTabs(props){let{baseUrl,tabs:tabDefinitions,children,...rest}=props,tabs=normalizeTabDefinitions(tabDefinitions),navigate=useMedplumNavigate6(),[currentTab,setCurrentTab]=useState83(()=>{let tab=locationUtils5.getPathname().split("/").pop();return tab&&tabs.some(t=>t.value===tab)?tab:tabs[0].value});function onTabChange(newTabName){newTabName=newTabName||tabs[0].value,setCurrentTab(newTabName),navigate(`${baseUrl}/${newTabName}`)}return jsxs97(Tabs2,{value:currentTab.toLowerCase(),onChange:onTabChange,...rest,children:[jsx148(Tabs2.List,{className:LinkTabs_default.list,children:tabs.map(t=>jsx148(Tabs2.Tab,{value:t.value,children:jsx148(Anchor11,{className:LinkTabs_default.link,href:`${baseUrl}/${t.value}`,onClick:onLinkClick,children:t.label})},t.value))}),children]})}function normalizeTabDefinitions(tabs){return tabs.map(t=>isString(t)?{label:t,value:t.toLowerCase()}:t)}function onLinkClick(e){isAuxClick(e)||e.preventDefault()}import{Box as Box22,SimpleGrid as SimpleGrid2}from"@mantine/core";import{useResource as useResource12,useSearchOne}from"@medplum/react-hooks";import{Box as Box21,Flex as Flex20,Group as Group58,Paper as Paper5,RingProgress,Text as Text42,Title as Title12}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept5}from"@medplum/core";import{Fragment as Fragment51,jsx as jsx149,jsxs as jsxs98}from"react/jsx-runtime";function MeasureReportGroupDisplay(props){let{group}=props;return jsx149(Paper5,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:jsxs98(Group58,{children:[group.measureScore&&jsx149(MeasureScore,{group}),!group.measureScore&&jsx149(MeasureReportPopulation,{group})]})})}function MeasureTitle(props){let{measure}=props;return jsxs98(Fragment51,{children:[jsx149(Text42,{fz:"md",fw:500,mb:8,children:measure.title}),jsx149(Text42,{fz:"xs",c:"dimmed",mb:8,children:measure.subtitle})]})}function MeasureReportPopulation(props){let{group}=props,populations=group.population,numerator=populations?.find(p=>formatCodeableConcept5(p.code)==="numerator"),denominator=populations?.find(p=>formatCodeableConcept5(p.code)==="denominator"),numeratorCount=numerator?.count,denominatorCount=denominator?.count;if(denominatorCount===0)return jsxs98(Box21,{children:[jsx149(Title12,{order:3,children:"Not Applicable"}),jsx149(Text42,{children:`Denominator: ${denominatorCount}`})]});if(numeratorCount===void 0||denominatorCount===void 0)return jsxs98(Box21,{children:[jsx149(Title12,{order:3,children:"Insufficient Data"}),jsx149(Text42,{children:`Numerator: ${numeratorCount}`}),jsx149(Text42,{children:`Denominator: ${denominatorCount}`})]});let value=numeratorCount/denominatorCount*100;return jsx149(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value,color:groupColor(value)}],label:jsx149(Flex20,{justify:"center",children:jsxs98(Text42,{fw:700,fz:18,children:[numeratorCount," / ",denominatorCount]})})})}function MeasureScore(props){let{group}=props,unit=group.measureScore?.unit??group.measureScore?.code;return jsx149(Fragment51,{children:unit==="%"?jsx149(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value:groupValue(group),color:groupColor(group?.measureScore?.value??0)}],label:jsx149(Flex20,{justify:"center",children:jsx149(Text42,{fw:700,fz:18,children:jsx149(QuantityDisplay,{value:group.measureScore})})})}):jsx149(Flex20,{h:120,align:"center",children:jsx149(Title12,{order:3,children:jsx149(QuantityDisplay,{value:group.measureScore})})})})}function groupValue(group){let score=group.measureScore?.value,unit=group.measureScore?.unit;return score?score<=1&&unit==="%"?score*100:score:0}function groupColor(score){return score<=33?"red":score<=67?"yellow":"green"}import{jsx as jsx150,jsxs as jsxs99}from"react/jsx-runtime";function MeasureReportDisplay(props){let report=useResource12(props.measureReport),[measure]=useSearchOne("Measure",{url:report?.measure});return report?jsxs99(Box22,{children:[measure&&jsx150(MeasureTitle,{measure}),jsx150(SimpleGrid2,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:report.group?.map((group,idx)=>jsx150(MeasureReportGroupDisplay,{group},group.id??idx))})]}):null}import{ActionIcon as ActionIcon17,Indicator as Indicator2,Tooltip as Tooltip8}from"@mantine/core";import{useNotificationCount as useNotificationCount2}from"@medplum/react-hooks";import{jsx as jsx151}from"react/jsx-runtime";function NotificationIcon(props){let{resourceType,countCriteria,subscriptionCriteria}=props,unreadCount=useNotificationCount2({resourceType,countCriteria,subscriptionCriteria}),result=props.iconComponent;return props.onClick&&(result=jsx151(ActionIcon17,{variant:"subtle",color:"gray",size:"lg","aria-label":props.label,onClick:props.onClick,children:result})),props.tooltip&&(result=jsx151(Tooltip8,{label:props.tooltip,children:result})),unreadCount>0&&(result=jsx151(Indicator2,{inline:!0,label:unreadCount.toLocaleString(),size:16,offset:2,position:"bottom-end",color:"red",children:result})),result}import{ActionIcon as ActionIcon18,Alert as Alert5,Badge as Badge2,Box as Box23,Button as Button20,Checkbox as Checkbox8,Divider as Divider8,Group as Group59,Modal as Modal16,Stack as Stack39,Table as Table5,Text as Text43,Title as Title13}from"@mantine/core";import{notifications}from"@mantine/notifications";import{extractAccountReferences,normalizeErrorString as normalizeErrorString12}from"@medplum/core";import{useMedplum as useMedplum45}from"@medplum/react-hooks";import{useCallback as useCallback27,useMemo as useMemo36,useState as useState84}from"react";import{Fragment as Fragment52,jsx as jsx152,jsxs as jsxs100}from"react/jsx-runtime";var NOTIFICATION_ID="patient-accounts",NOTIFICATION_TITLE="Patient Accounts",ACCOUNT_TARGET_TYPES=["Organization","HealthcareService","CareTeam"];function PatientAccountsForm(props){let{patient}=props,medplum=useMedplum45(),isAdmin=medplum.isProjectAdmin()||medplum.isSuperAdmin(),originalAccounts=useMemo36(()=>extractAccountReferences(patient.meta)??[],[patient.meta]),[pendingAccounts,setPendingAccounts]=useState84(originalAccounts),[confirmModalOpen,setConfirmModalOpen]=useState84(!1),[propagate,setPropagate]=useState84(!0),[saving,setSaving]=useState84(!1),changes=useMemo36(()=>{let result=[];for(let account of pendingAccounts)originalAccounts.some(o=>o.reference===account.reference)||result.push({reference:account,type:"addition"});for(let account of originalAccounts)pendingAccounts.some(p=>p.reference===account.reference)||result.push({reference:account,type:"removal"});return result},[originalAccounts,pendingAccounts]),hasChanges=changes.length>0,handleAddAccount=useCallback27(value=>{value?.reference&&(pendingAccounts.some(a=>a.reference===value.reference)||setPendingAccounts(prev=>[...prev,value]))},[pendingAccounts]),handleRemoveAccount=useCallback27(referenceString=>{setPendingAccounts(prev=>prev.filter(a=>a.reference!==referenceString))},[]),handleSave=useCallback27(async()=>{let patientId=patient.id;if(!patientId){notifications.show({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"red",message:"Cannot update accounts: Patient resource has no ID.",icon:jsx152(IconX,{size:"1rem"}),autoClose:!1,withCloseButton:!0});return}setSaving(!0),setConfirmModalOpen(!1);let url=medplum.fhirUrl("Patient",patientId,"$set-accounts"),parameters={resourceType:"Parameters",parameter:[...pendingAccounts.map(account=>({name:"accounts",valueReference:{reference:account.reference}})),{name:"propagate",valueBoolean:propagate}]};notifications.show({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,loading:!0,message:propagate?"Saving account changes and propagating to compartment...":"Saving account changes...",autoClose:!1,withCloseButton:!1});try{let headers={};propagate&&(headers.Prefer="respond-async"),await medplum.post(url,parameters,void 0,{headers}),medplum.invalidateUrl(medplum.fhirUrl("Patient",patientId)),notifications.update({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"green",message:propagate?"Account changes saved. Compartment updates are being applied.":"Account changes saved.",icon:jsx152(IconCheck,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0}),props.onSaved?.()}catch(err){notifications.update({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"red",message:normalizeErrorString12(err),icon:jsx152(IconX,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}finally{setSaving(!1)}},[medplum,patient,pendingAccounts,propagate,props]);return isAdmin?jsxs100(Fragment52,{children:[jsxs100(Stack39,{children:[jsx152(Title13,{order:3,children:"Current Accounts"}),pendingAccounts.length===0?jsx152(Text43,{c:"dimmed",children:"No accounts assigned to this patient."}):jsxs100(Table5,{children:[jsx152(Table5.Thead,{children:jsxs100(Table5.Tr,{children:[jsx152(Table5.Th,{children:"Type"}),jsx152(Table5.Th,{children:"Account"}),jsx152(Table5.Th,{})]})}),jsx152(Table5.Tbody,{children:pendingAccounts.map(account=>jsxs100(Table5.Tr,{children:[jsx152(Table5.Td,{children:jsx152(AccountTypeBadge,{reference:account})}),jsx152(Table5.Td,{children:jsx152(ResourceBadge,{value:account,link:!0})}),jsx152(Table5.Td,{children:jsx152(ActionIcon18,{variant:"subtle",color:"red","aria-label":`Remove ${account.reference}`,onClick:()=>handleRemoveAccount(account.reference),children:jsx152(IconX,{size:16})})})]},account.reference))})]}),jsx152(Divider8,{}),jsx152(Title13,{order:4,children:"Add Account"}),jsx152(ReferenceInput,{name:"newAccount",placeholder:"Search for Organization, HealthcareService, or CareTeam...",targetTypes:ACCOUNT_TARGET_TYPES,onChange:value=>{value&&handleAddAccount(value)}}),hasChanges&&jsxs100(Fragment52,{children:[jsx152(Divider8,{}),jsx152(Title13,{order:4,children:"Pending Changes"}),jsx152(Stack39,{gap:"xs",children:changes.map(change=>jsxs100(Group59,{gap:"xs",children:[change.type==="addition"?jsx152(Badge2,{color:"green",variant:"light",leftSection:jsx152(IconPlus,{size:12}),children:"Add"}):jsx152(Badge2,{color:"red",variant:"light",leftSection:jsx152(IconMinus,{size:12}),children:"Remove"}),jsx152(ResourceBadge,{value:change.reference,link:!0})]},`${change.type}-${change.reference.reference}`))})]}),jsx152(Box23,{children:jsx152(Button20,{disabled:!hasChanges||saving,onClick:()=>setConfirmModalOpen(!0),children:"Save Changes"})})]}),jsx152(Modal16,{opened:confirmModalOpen,onClose:()=>setConfirmModalOpen(!1),title:"Confirm Account Changes",size:"md",keepMounted:!0,children:jsxs100(Stack39,{children:[jsxs100(Text43,{children:["The following changes will be applied to Patient"," ",jsxs100("strong",{children:[patient.name?.[0]?.given?.join(" ")," ",patient.name?.[0]?.family]}),":"]}),changes.filter(c=>c.type==="addition").length>0&&jsxs100(Box23,{children:[jsx152(Text43,{fw:600,c:"green",children:"Adding:"}),jsx152(Stack39,{gap:"xs",mt:"xs",children:changes.filter(c=>c.type==="addition").map(c=>jsxs100(Group59,{gap:"xs",children:[jsx152(IconPlus,{size:14,color:"green"}),jsx152(ResourceBadge,{value:c.reference})]},c.reference.reference))})]}),changes.filter(c=>c.type==="removal").length>0&&jsxs100(Box23,{children:[jsx152(Text43,{fw:600,c:"red",children:"Removing:"}),jsx152(Stack39,{gap:"xs",mt:"xs",children:changes.filter(c=>c.type==="removal").map(c=>jsxs100(Group59,{gap:"xs",children:[jsx152(IconMinus,{size:14,color:"red"}),jsx152(ResourceBadge,{value:c.reference})]},c.reference.reference))})]}),jsx152(Checkbox8,{label:"Propagate changes to all resources in this patient's compartment",checked:propagate,onChange:event=>setPropagate(event.currentTarget.checked)}),jsxs100(Group59,{justify:"right",mt:"md",children:[jsx152(Button20,{variant:"default",onClick:()=>setConfirmModalOpen(!1),children:"Cancel"}),jsx152(Button20,{onClick:handleSave,loading:saving,children:"Confirm"})]})]})})]}):jsx152(Alert5,{color:"blue",title:"Admin access required",children:"You need project admin access to manage patient account assignments."})}function AccountTypeBadge({reference}){let type=reference.reference?.split("/")[0]??"Unknown";return jsx152(Badge2,{variant:"light",color:{Organization:"blue",HealthcareService:"teal",CareTeam:"violet"}[type]??"gray",size:"sm",children:type})}import{Group as Group60,SegmentedControl as SegmentedControl2,Stack as Stack40}from"@mantine/core";import{notifications as notifications2}from"@mantine/notifications";import{ContentType as ContentType3,normalizeErrorString as normalizeErrorString13,resolveId as resolveId2}from"@medplum/core";import{useMedplum as useMedplum46}from"@medplum/react-hooks";import{useCallback as useCallback28}from"react";import{jsx as jsx153,jsxs as jsxs101}from"react/jsx-runtime";var NOTIFICATION_ID2="patient-export",NOTIFICATION_TITLE2="Patient Export",formats={everything:{operation:"$everything",extension:"json",contentType:ContentType3.FHIR_JSON},summary:{operation:"$summary",extension:"json",contentType:ContentType3.FHIR_JSON},ccda:{operation:"$ccda-export",extension:"xml",contentType:ContentType3.CDA_XML},ccdaReferral:{operation:"$ccda-export",type:"referral",extension:"xml",contentType:ContentType3.CDA_XML}};function PatientExportForm(props){let medplum=useMedplum46(),{patient}=props,handleSubmit=useCallback28(async data2=>{let patientId=resolveId2(patient),format=data2.format,{operation,type,contentType,extension}=formats[format],url=medplum.fhirUrl("Patient",patientId,operation),params={};type&&(params.type=type),data2.author&&(params.author={reference:data2.author}),data2.authoredOn&&(params.authoredOn=convertLocalToIso(data2.authoredOn)),data2.startDate&&(params.start=data2.startDate),data2.endDate&&(params.end=data2.endDate),notifications2.show({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,loading:!0,message:"Exporting...",autoClose:!1,withCloseButton:!1});try{let response=await medplum.post(url,params,void 0,{cache:"no-cache",headers:{Accept:contentType}}),fileName=`Patient-export-${patientId}-${new Date().toISOString().replaceAll(":","-")}.${extension}`;saveData(response,fileName,contentType),notifications2.update({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,color:"green",message:"Done",icon:jsx153(IconCheck,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0})}catch(err){notifications2.update({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,color:"red",message:normalizeErrorString13(err),icon:jsx153(IconX,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}},[medplum,patient]);return jsx153(Form,{onSubmit:handleSubmit,children:jsxs101(Stack40,{children:[jsx153(FormSection,{title:"Export Format",description:"Required",withAsterisk:!0,children:jsx153(SegmentedControl2,{name:"format",data:[{label:"FHIR Everything",value:"everything"},{label:"Patient Summary",value:"summary"},{label:"C-CDA",value:"ccda"},{label:"C-CDA Referral",value:"ccdaReferral"}],fullWidth:!0})}),jsx153(FormSection,{title:"Author",description:"Optional author for composition. Default value is current user.",children:jsx153(ReferenceInput,{name:"author",placeholder:"Author",targetTypes:["Organization","Practitioner","PractitionerRole"]})}),jsx153(FormSection,{title:"Authored On",description:"Optional date for composition authored on. Default value is current date.",children:jsx153(DateTimeInput,{name:"authoredOn",placeholder:"Authored on"})}),jsx153(FormSection,{title:"Start Date",description:"The start date of care. If no start date is provided, all records prior to the end date are in scope.",children:jsx153(DateTimeInput,{name:"startDate",placeholder:"Start date"})}),jsx153(FormSection,{title:"End Date",description:"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.",children:jsx153(DateTimeInput,{name:"endDate",placeholder:"End date"})}),jsx153(Group60,{justify:"right",children:jsx153(SubmitButton,{children:"Request Export"})})]})})}function saveData(data2,fileName,contentType){let content=typeof data2=="string"?data2:JSON.stringify(data2,null,2),blob=new Blob([content],{type:contentType}),url=window.URL.createObjectURL(blob),a=document.createElement("a");document.body.appendChild(a),a.style.display="none",a.href=url,a.download=fileName,a.click(),window.URL.revokeObjectURL(url)}import{calculateAgeString as calculateAgeString2}from"@medplum/core";import{useResource as useResource13}from"@medplum/react-hooks";function getDefaultColor(patient){if(patient.gender==="male")return"blue";if(patient.gender==="female")return"pink"}import{Fragment as Fragment53,jsx as jsx154,jsxs as jsxs102}from"react/jsx-runtime";function PatientHeader(props){let patient=useResource13(props.patient);return patient?jsxs102(InfoBar,{children:[jsx154(ResourceAvatar,{value:patient,size:"lg",color:getDefaultColor(patient)}),jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Name"}),jsx154(InfoBar.Value,{children:jsx154(MedplumLink,{to:patient,fw:500,children:patient.name?jsx154(HumanNameDisplay,{value:patient.name[0],options:{use:!1}}):"[blank]"})})]}),patient.birthDate&&jsxs102(Fragment53,{children:[jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"DoB"}),jsx154(InfoBar.Value,{children:patient.birthDate})]}),jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Age"}),jsx154(InfoBar.Value,{children:calculateAgeString2(patient.birthDate)})]})]}),patient.gender&&jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Gender"}),jsx154(InfoBar.Value,{children:patient.gender})]}),patient.address&&jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"State"}),jsx154(InfoBar.Value,{children:patient.address[0]?.state})]}),patient.identifier?.map(identifier=>jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:identifier?.system}),jsx154(InfoBar.Value,{children:identifier?.value})]},`${identifier?.system}-${identifier?.value}`))]}):null}import{Box as Box24,Button as Button21,Checkbox as Checkbox9,Flex as Flex21,Group as Group61,Loader as Loader8,Radio as Radio5,Stack as Stack41,Text as Text44,TextInput as TextInput28}from"@mantine/core";import{showNotification as showNotification10}from"@mantine/notifications";import{formatAddress as formatAddress4,normalizeErrorString as normalizeErrorString14}from"@medplum/core";import{useCallback as useCallback29,useState as useState85}from"react";var PharmacyDialog_default={pharmacyItem:"PharmacyDialog_pharmacyItem",pharmacyItemSelected:"PharmacyDialog_pharmacyItemSelected"};import{jsx as jsx155,jsxs as jsxs103}from"react/jsx-runtime";function getPharmacyKey(pharmacy,index){return pharmacy.identifier?.[0]?.value||`pharmacy-${index}`}function SearchForm({onSearch,searching}){return jsx155("form",{onSubmit:e=>{e.preventDefault();let formData=new FormData(e.currentTarget);onSearch(formData)},children:jsxs103(Stack41,{gap:"md",children:[jsx155(TextInput28,{name:"name",label:"Pharmacy Name",placeholder:"Enter pharmacy name (min 3 chars)"}),jsxs103(Group61,{grow:!0,children:[jsx155(TextInput28,{name:"city",label:"City",placeholder:"City (min 3 chars)"}),jsx155(TextInput28,{name:"state",label:"State",placeholder:"State (min 3 chars)"})]}),jsxs103(Group61,{grow:!0,children:[jsx155(TextInput28,{name:"zip",label:"Zip Code",placeholder:"Zip code (min 3 chars)"}),jsx155(TextInput28,{name:"phoneOrFax",label:"Phone or Fax",placeholder:"Phone or fax number"})]}),jsx155(TextInput28,{name:"address",label:"Address",placeholder:"Street address (min 3 chars)"}),jsx155(TextInput28,{name:"ncpdpID",label:"NCPDP ID",placeholder:"National Council for Prescription Drug Programs ID"}),jsx155(Button21,{type:"submit",loading:searching,children:"Search"})]})})}function PharmacyItem({pharmacy,pharmacyKey,isSelected,onSelect}){return jsx155(Box24,{p:"sm",className:isSelected?PharmacyDialog_default.pharmacyItemSelected:PharmacyDialog_default.pharmacyItem,onClick:onSelect,children:jsx155(Radio5,{value:pharmacyKey,label:jsxs103(Box24,{children:[jsx155(Text44,{fw:500,size:"sm",children:pharmacy.name}),pharmacy.address?.[0]&&jsx155(Text44,{size:"xs",c:"dimmed",children:formatAddress4(pharmacy.address[0])}),pharmacy.telecom?.find(t=>t.system==="phone")&&jsxs103(Text44,{size:"xs",c:"dimmed",children:["Phone: ",pharmacy.telecom.find(t=>t.system==="phone")?.value]}),pharmacy.telecom?.find(t=>t.system==="fax")&&jsxs103(Text44,{size:"xs",c:"dimmed",children:["Fax: ",pharmacy.telecom.find(t=>t.system==="fax")?.value]})]})})},pharmacyKey)}function SearchResults({searchResults,selectedPharmacy,onSelectPharmacy,setAsPrimary,onSetAsPrimary,onAddFavorite,onClose,adding}){return jsxs103(Box24,{mt:"xl",children:[jsxs103(Text44,{fw:600,mb:"md",children:["Search Results (",searchResults.length,")"]}),jsx155(Radio5.Group,{value:selectedPharmacy?getPharmacyKey(selectedPharmacy,searchResults.indexOf(selectedPharmacy)):"",onChange:value=>{let selected=searchResults.find((p,i)=>getPharmacyKey(p,i)===value);selected&&onSelectPharmacy(selected)},children:jsx155(Stack41,{gap:"sm",children:searchResults.map((pharmacy,index)=>{let pharmacyKey=getPharmacyKey(pharmacy,index),isSelected=selectedPharmacy?getPharmacyKey(selectedPharmacy,searchResults.indexOf(selectedPharmacy))===pharmacyKey:!1;return jsx155(PharmacyItem,{pharmacy,pharmacyKey,isSelected,onSelect:()=>onSelectPharmacy(pharmacy)},pharmacyKey)})})}),jsxs103(Flex21,{mt:"lg",gap:"md",align:"center",justify:"space-between",children:[jsx155(Checkbox9,{label:"Set as primary pharmacy",checked:setAsPrimary,onChange:e=>onSetAsPrimary(e.currentTarget.checked)}),jsxs103(Group61,{children:[jsx155(Button21,{variant:"subtle",onClick:onClose,children:"Cancel"}),jsx155(Button21,{onClick:onAddFavorite,disabled:!selectedPharmacy,loading:adding,children:"Add to Favorites"})]})]})]})}function PharmacyDialog(props){let{patient,onSubmit,onClose,onSearch,onAddToFavorites}=props,[searchResults,setSearchResults]=useState85([]),[searching,setSearching]=useState85(!1),[selectedPharmacy,setSelectedPharmacy]=useState85(),[setAsPrimary,setSetAsPrimary]=useState85(!1),[adding,setAdding]=useState85(!1),handleSearch=useCallback29(async formData=>{let searchParams={name:formData.get("name")||void 0,city:formData.get("city")||void 0,state:formData.get("state")||void 0,zip:formData.get("zip")||void 0,address:formData.get("address")||void 0,phoneOrFax:formData.get("phoneOrFax")||void 0,ncpdpID:formData.get("ncpdpID")||void 0},cleanParams=Object.fromEntries(Object.entries(searchParams).filter(([_,v])=>typeof v=="string"&&v.trim()!==""));if(Object.keys(cleanParams).length===0){showNotification10({color:"yellow",title:"Search Required",message:"Please enter at least one search criterion"});return}setSearching(!0),setSelectedPharmacy(void 0);try{let results=await onSearch(cleanParams);setSearchResults(results),results.length===0&&showNotification10({color:"blue",title:"No Results",message:"No pharmacies found matching your search criteria"})}catch(error){showNotification10({color:"red",title:"Search Error",message:normalizeErrorString14(error)})}finally{setSearching(!1)}},[onSearch]),handleAddFavorite=useCallback29(async()=>{if(!(!selectedPharmacy||!patient.id)){setAdding(!0);try{let response=await onAddToFavorites({patientId:patient.id,pharmacy:selectedPharmacy,setAsPrimary});response.success?(showNotification10({color:"green",title:"Success",message:response.message}),onSubmit(response.organization||selectedPharmacy)):showNotification10({color:"red",title:"Error",message:response.message})}catch(error){showNotification10({color:"red",title:"Error",message:normalizeErrorString14(error)})}finally{setAdding(!1)}}},[selectedPharmacy,patient.id,setAsPrimary,onAddToFavorites,onSubmit]);return jsxs103(Box24,{children:[jsx155(SearchForm,{onSearch:formData=>handleSearch(formData).catch(console.error),searching}),searching&&jsx155(Flex21,{justify:"center",mt:"xl",children:jsx155(Loader8,{})}),searchResults.length>0&&!searching&&jsx155(SearchResults,{searchResults,selectedPharmacy,onSelectPharmacy:setSelectedPharmacy,setAsPrimary,onSetAsPrimary:setSetAsPrimary,onAddFavorite:handleAddFavorite,onClose,adding})]})}import{Box as Box25,Flex as Flex22,Group as Group62,Text as Text45}from"@mantine/core";import{getDisplayString as coreGetDisplayString}from"@medplum/core";import{jsx as jsx156,jsxs as jsxs104}from"react/jsx-runtime";function summaryResourceListSection(options){return{key:options.key,title:options.title,searches:[{key:options.key,resourceType:options.search.resourceType,patientParam:options.search.patientParam,query:options.search.query}],component:context=>jsx156(ResourceListDisplay,{options,resources:context.results[options.key]??[],context})}}function ResourceListDisplay(props){let{options,context}=props,resources=[...props.resources];return options.filter&&(resources=resources.filter(options.filter)),options.sort&&resources.sort(options.sort),jsx156(CollapsibleSection,{title:options.title,onAdd:options.onAdd,children:resources.length>0?jsx156(Flex22,{direction:"column",gap:8,children:resources.map(resource=>{let displayString=options.getDisplayString?options.getDisplayString(resource):coreGetDisplayString(resource),status=options.getStatus?.(resource),secondaryText=options.getSecondaryText?.(resource);return jsx156(SummaryItem,{onClick:()=>context.onClickResource?.(resource),children:jsxs104(Box25,{children:[jsx156(Text45,{fw:500,className:SummaryItem_default.itemText,children:displayString}),(status||secondaryText)&&jsxs104(Group62,{mt:2,gap:4,children:[status&&jsx156(StatusBadge,{color:status.color,variant:"light",status:status.label}),secondaryText&&jsx156(Text45,{size:"xs",fw:500,c:"dimmed",children:secondaryText})]})]})},resource.id)})}):jsx156(Text45,{children:"(none)"})})}import{createReference as createReference16}from"@medplum/core";import{useCallback as useCallback30}from"react";import{jsx as jsx157}from"react/jsx-runtime";function PatientTimeline(props){let{patient,...rest}=props,loadTimelineResources=useCallback30((medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("Patient",id),medplum.search("Communication",{subject:ref,_count}),medplum.search("Device",{patient:ref,_count}),medplum.search("DeviceRequest",{patient:ref,_count}),medplum.search("DiagnosticReport",{subject:ref,_count}),medplum.search("Media",{subject:ref,_count}),medplum.search("ServiceRequest",{subject:ref,_count}),medplum.search("Task",{subject:ref,_count})])},[]);return jsx157(ResourceTimeline,{value:patient,loadTimelineResources,createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",subject:createReference16(resource),sender:createReference16(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",subject:createReference16(resource),operator:createReference16(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor12,Box as Box26,Button as Button22,CloseButton as CloseButton2,Flex as Flex23,Group as Group63,Loader as Loader9,NativeSelect as NativeSelect12,Paper as Paper6,Stack as Stack42,Text as Text46,TextInput as TextInput29}from"@mantine/core";import{getReferenceString as getReferenceString12}from"@medplum/core";import{useMedplum as useMedplum47,useResource as useResource14}from"@medplum/react-hooks";import{useEffect as useEffect33,useState as useState86}from"react";var PlanDefinitionBuilder_default={section:"PlanDefinitionBuilder_section",hovering:"PlanDefinitionBuilder_hovering",editing:"PlanDefinitionBuilder_editing"};import{jsx as jsx158,jsxs as jsxs105}from"react/jsx-runtime";function PlanDefinitionBuilder(props){let medplum=useMedplum47(),defaultValue2=useResource14(props.value),[schemaLoaded,setSchemaLoaded]=useState86(!1),[selectedKey,setSelectedKey]=useState86(),[hoverKey,setHoverKey]=useState86(),[value,setValue]=useState86();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}if(useEffect33(()=>{medplum.requestSchema("PlanDefinition").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect33(()=>(setValue(ensurePlanDefinitionKeys(defaultValue2??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]),!schemaLoaded||!value)return null;function changeProperty(property,newValue){setValue(prevValue=>({...prevValue,[property]:newValue}))}return jsx158("div",{children:jsxs105(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx158(TextInput29,{label:"Plan Title",py:"md",defaultValue:value.title,onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx158(ActionArrayBuilder,{actions:value.action||[],selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:x=>changeProperty("action",x)}),jsx158(SubmitButton,{children:"Save"})]})})}function ActionArrayBuilder(props){function changeAction(changedAction){props.onChange(props.actions.map(i=>i.id===changedAction.id?changedAction:i))}function addAction(addedAction){props.onChange([...props.actions,addedAction]),props.setSelectedKey(addedAction.id)}function removeAction(removedAction){props.onChange(props.actions.filter(i=>i!==removedAction))}return jsxs105(Stack42,{gap:"md",className:PlanDefinitionBuilder_default.section,children:[props.actions.map(action=>jsx158(ActionBuilder,{action,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,setHoverKey:props.setHoverKey,onChange:changeAction,onRemove:()=>removeAction(action)},action.id)),jsx158("div",{children:jsx158(Button22,{variant:"outline",onClick:e=>{killEvent(e),addAction({id:generateId()})},children:"Add action"})})]})}function ActionBuilder(props){let{action}=props;function onClick(e){e.stopPropagation(),props.setSelectedKey(props.action.id)}function onHover(e){killEvent(e),props.setHoverKey(props.action.id)}return jsx158("div",{onClick,onMouseOver:onHover,onFocus:onHover,children:jsx158(ActionEditor,{action,onChange:props.onChange,selectedKey:props.selectedKey,hoverKey:props.hoverKey,onRemove:props.onRemove})})}function ActionEditor(props){let{action}=props,[actionType,setActionType]=useState86(),medplum=useMedplum47(),[loading,setLoading]=useState86(!1),[resource,setResource]=useState86(),editing=props.selectedKey===props.action.id,hovering=props.hoverKey===props.action.id;function changeProperty(property,value){props.onChange({...action,[property]:value})}let className=clsx_default(PlanDefinitionBuilder_default.section,{[PlanDefinitionBuilder_default.hovering]:hovering&&!editing});return useEffect33(()=>{(async()=>{if(!action.definitionCanonical)return;setLoading(!0);let resource2=await medplum.readCanonical(["Questionnaire","ActivityDefinition"],action.definitionCanonical);setActionType(getInitialActionType(resource2)),setResource(resource2),setLoading(!1)})().catch(console.error)},[action.definitionCanonical,medplum]),loading?jsx158(Loader9,{}):jsxs105(Paper6,{"data-testid":action.id,className,p:0,radius:"sm",withBorder:!0,children:[jsxs105(Flex23,{w:"100%",p:"xs",bg:"gray.0",gap:"md",align:"center",justify:"space-between",children:[jsx158(TextInput29,{w:"100%",name:`actionTitle-${action.id}`,defaultValue:action.title,placeholder:"Title",onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx158(CloseButton2,{"data-testid":"close-button",onClick:props.onRemove})]}),editing&&jsxs105(Stack42,{gap:"xl",p:"md",children:[jsx158(Box26,{children:jsx158(TextInput29,{label:"Task Description",placeholder:"Enter task description",name:`actionDescription-${action.id}`,defaultValue:action.description,onChange:e=>changeProperty("description",e.currentTarget.value)})}),jsx158(Box26,{children:jsx158(NativeSelect12,{label:"Type of Action",value:actionType,onChange:e=>{let value=e.currentTarget.value==="standard"?void 0:e.currentTarget.value;setActionType(value),props.onChange({...props.action,definitionCanonical:value==="standard"?void 0:props.action.definitionCanonical})},data:[{value:"standard",label:"Standard task"},{value:"questionnaire",label:"Task with Questionnaire"},{value:"activitydefinition",label:"Task with Activity Definition"}]})}),actionType==="questionnaire"&&jsxs105(Stack42,{gap:0,children:[jsxs105(Group63,{gap:0,mb:"xs",children:[jsx158(Text46,{fw:600,children:"Select questionnaire"}),jsx158(Text46,{c:"red",children:"*"})]}),jsxs105(Text46,{size:"sm",c:"dimmed",mb:"sm",children:["Questionnaire to be shown in the task in Encounter view. You can create new one from"," ",jsx158(Anchor12,{href:"/Questionnaire",target:"_blank",c:"blue",children:"questionnaires list"})]}),jsx158(ActionResourceTypeBuilder,{resource,resourceType:"Questionnaire",action,onChange:props.onChange,placeholder:"Search for questionnaire"})]}),actionType==="activitydefinition"&&jsxs105(Stack42,{gap:0,children:[jsxs105(Group63,{gap:0,mb:"xs",children:[jsx158(Text46,{fw:600,children:"Select activity definition"}),jsx158(Text46,{c:"red",children:"*"})]}),jsxs105(Text46,{size:"sm",c:"dimmed",mb:"sm",children:["ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from"," ",jsx158(Anchor12,{href:"/ActivityDefinition",target:"_blank",c:"blue",children:"activity definitions list"})]}),jsx158(ActionResourceTypeBuilder,{resource,resourceType:"ActivityDefinition",action,onChange:props.onChange,placeholder:"Search for activity definition"})]})]})]})}function ActionResourceTypeBuilder(props){let{id}=props.action,{resource}=props;return jsx158(ResourceInput,{name:id,placeholder:props.placeholder,resourceType:props.resourceType,defaultValue:resource,onChange:newValue=>{newValue?props.onChange({...props.action,definitionCanonical:"url"in newValue?newValue.url:void 0,definitionUri:"url"in newValue?void 0:getReferenceString12(newValue)}):props.onChange({...props.action,definitionCanonical:void 0})}})}function getInitialActionType(resource){return resource===void 0?"standard":resource.resourceType.toLowerCase()}var nextId=1;function generateId(existing){if(existing){if(existing.startsWith("id-")){let existingNum=Number.parseInt(existing.substring(3),10);Number.isNaN(existingNum)||(nextId=Math.max(nextId,existingNum+1))}return existing}return"id-"+nextId++}function ensurePlanDefinitionKeys(planDefinition){return{...planDefinition,action:ensurePlanDefinitionActionKeys(planDefinition.action)}}function ensurePlanDefinitionActionKeys(actions){if(actions)return actions.map(action=>({...action,id:generateId(action.id),action:ensurePlanDefinitionActionKeys(action.action)}))}import{Anchor as Anchor13,Box as Box27,Group as Group64,NativeSelect as NativeSelect13,Space,Textarea as Textarea5,TextInput as TextInput30,Title as Title14}from"@mantine/core";import{getElementDefinition as getElementDefinition3,isResource as isResourceType}from"@medplum/core";import{getQuestionnaireItemReferenceTargetTypes as getQuestionnaireItemReferenceTargetTypes2,isChoiceQuestion,QUESTIONNAIRE_ITEM_CONTROL_URL as QUESTIONNAIRE_ITEM_CONTROL_URL2,QuestionnaireItemType as QuestionnaireItemType4,setQuestionnaireItemReferenceTargetTypes,useMedplum as useMedplum48,useResource as useResource15}from"@medplum/react-hooks";import{useEffect as useEffect34,useLayoutEffect as useLayoutEffect7,useRef as useRef17,useState as useState87}from"react";var QuestionnaireBuilder_default={section:"QuestionnaireBuilder_section",hovering:"QuestionnaireBuilder_hovering",editing:"QuestionnaireBuilder_editing",questionBody:"QuestionnaireBuilder_questionBody",topActions:"QuestionnaireBuilder_topActions",bottomActions:"QuestionnaireBuilder_bottomActions",movementActions:"QuestionnaireBuilder_movementActions",movementIcons:"QuestionnaireBuilder_movementIcons",columnAlignment:"QuestionnaireBuilder_columnAlignment",linkIdInput:"QuestionnaireBuilder_linkIdInput",typeSelect:"QuestionnaireBuilder_typeSelect",preserveBreaks:"QuestionnaireBuilder_preserveBreaks"};import{Fragment as Fragment54,jsx as jsx159,jsxs as jsxs106}from"react/jsx-runtime";function QuestionnaireBuilder(props){let medplum=useMedplum48(),defaultValue2=useResource15(props.questionnaire),[schemaLoaded,setSchemaLoaded]=useState87(!1),[value,setValue]=useState87(),[selectedKey,setSelectedKey]=useState87(),[hoverKey,setHoverKey]=useState87();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}useEffect34(()=>{medplum.requestSchema("Questionnaire").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect34(()=>(setValue(ensureQuestionnaireKeys(defaultValue2??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]);let handleChange=(questionnaire2,disableSubmit)=>{setValue(questionnaire2),props.autoSave&&!disableSubmit&&props.onSubmit&&props.onSubmit(questionnaire2)};return!schemaLoaded||!value?null:jsx159("div",{children:jsxs106(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx159(ItemBuilder,{item:value,selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:handleChange}),jsx159(SubmitButton,{children:"Save"})]})})}function ItemBuilder(props){let resource=props.item,item=props.item,isResource4=isResourceType(props.item),isContainer=isResource4||item.type===QuestionnaireItemType4.group,linkId=item.linkId??"[untitled]",editing=props.selectedKey===props.item.id,hovering=props.hoverKey===props.item.id,itemRef=useRef17(props.item);useLayoutEffect7(()=>{itemRef.current=props.item});function onClick(e){killEvent(e),props.setSelectedKey(props.item.id)}function onHover(e){killEvent(e),props.setHoverKey(props.item.id)}function changeItem(changedItem){let curr=itemRef.current;props.onChange({...curr,item:curr.item?.map(i=>i.id===changedItem.id?changedItem:i)})}function addItem(addedItem,disableSubmit){props.onChange({...props.item,item:[...props.item.item??[],addedItem]},disableSubmit)}function removeItem(removedItem){props.onChange({...props.item,item:props.item.item?.filter(i=>i!==removedItem)})}function changeProperty(property,value){props.onChange({...itemRef.current,[property]:value})}function updateItem(updatedItem){props.onChange({...props.item,...updatedItem})}function toggleRepeatable(item2){props.onChange({...props.item,item:props.item.item?.map(i=>i===item2?{...i,repeats:!i.repeats}:i)})}function moveItem(itemIndex,delta){let updatedItems=reorderItems(props.item.item,itemIndex,delta);props.onChange({...props.item,item:updatedItems})}let className=clsx_default(QuestionnaireBuilder_default.section,{[QuestionnaireBuilder_default.editing]:editing,[QuestionnaireBuilder_default.hovering]:hovering&&!editing});return jsxs106("div",{"data-testid":item.linkId,className,onClick,onMouseOver:onHover,onFocus:onHover,children:[jsx159("div",{className:QuestionnaireBuilder_default.questionBody,children:editing?jsxs106(Fragment54,{children:[isResource4&&jsx159(TextInput30,{size:"xl",defaultValue:resource.title,onBlur:e=>changeProperty("title",e.currentTarget.value)}),!isResource4&&jsx159(Textarea5,{autosize:!0,minRows:2,defaultValue:item.text,onBlur:e=>changeProperty("text",e.currentTarget.value)}),item.type==="reference"&&jsx159(ReferenceProfiles,{item,onChange:updateItem}),isChoiceQuestion(item)&&jsx159(AnswerBuilder,{item,onChange:item2=>updateItem(item2)})]}):jsxs106(Fragment54,{children:[resource.title&&jsx159(Title14,{children:resource.title}),item.text&&jsx159("div",{className:QuestionnaireBuilder_default.preserveBreaks,children:item.text}),!isContainer&&jsx159(QuestionnaireFormItem,{item,index:0,required:!1,responseItem:{linkId:item.linkId}})]})}),item.item?.map((item2,i)=>jsx159("div",{children:jsx159(ItemBuilder,{item:item2,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,isFirst:i===0,isLast:i===(props.item.item??[]).length-1,setHoverKey:props.setHoverKey,onChange:changeItem,onRemove:()=>removeItem(item2),onRepeatable:toggleRepeatable,onMoveUp:()=>moveItem(i,-1),onMoveDown:()=>moveItem(i,1)})},item2.id)),!isContainer&&jsx159("div",{className:QuestionnaireBuilder_default.topActions,children:editing?jsxs106(Fragment54,{children:[jsx159(TextInput30,{size:"xs",className:QuestionnaireBuilder_default.linkIdInput,defaultValue:item.linkId,onBlur:e=>changeProperty("linkId",e.currentTarget.value)}),!isContainer&&jsx159(NativeSelect13,{size:"xs",className:QuestionnaireBuilder_default.typeSelect,defaultValue:item.type,onChange:e=>changeProperty("type",e.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):jsx159("div",{children:linkId})}),!isResource4&&jsx159(Box27,{className:QuestionnaireBuilder_default.movementActions,children:jsxs106(Box27,{className:QuestionnaireBuilder_default.columnAlignment,children:[!props.isFirst&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveUp&&props.onMoveUp()},children:jsx159(IconArrowUp,{"data-testid":"up-button",size:15,className:QuestionnaireBuilder_default.movementIcons})}),!props.isLast&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveDown&&props.onMoveDown()},children:jsx159(IconArrowDown,{"data-testid":"down-button",size:15,className:QuestionnaireBuilder_default.movementIcons})})]})}),jsxs106("div",{className:QuestionnaireBuilder_default.bottomActions,children:[isContainer&&jsxs106(Fragment54,{children:[jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId2(),linkId:generateLinkId("q"),type:"string",text:"Question"})},children:"Add item"}),jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId2(),linkId:generateLinkId("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),isResource4&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem(createPage(),!0)},children:"Add Page"}),editing&&!isResource4&&jsxs106(Fragment54,{children:[jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onRepeatable&&props.onRepeatable(item)},children:item.repeats?"Remove Repeatable":"Make Repeatable"}),jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onRemove&&props.onRemove()},children:"Remove"})]})]})]})}function AnswerBuilder(props){let property=getElementDefinition3("QuestionnaireItemAnswerOption","value[x]"),options=props.item.answerOption??[];return jsxs106("div",{children:[props.item.answerValueSet!==void 0?jsx159(TextInput30,{placeholder:"Enter Value Set",defaultValue:props.item.answerValueSet,onChange:e=>props.onChange({...props.item,answerValueSet:e.target.value})}):jsx159(AnswerOptionsInput,{options,property,item:props.item,onChange:props.onChange}),jsxs106(Box27,{display:"flex",children:[jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerValueSet:void 0,answerOption:[...options,{id:generateId2()}]})},children:"Add choice"}),jsx159(Space,{w:"lg"}),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function AnswerOptionsInput(props){return jsx159("div",{children:props.options.map(option=>{let[propertyValue,propertyType]=getValueAndType({type:"QuestionnaireItemAnswerOption",value:option},"value");return jsxs106("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[jsx159("div",{children:jsx159(ResourcePropertyInput,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:props.property,defaultPropertyType:propertyType,defaultValue:propertyValue,onChange:(newValue,propName)=>{let newOptions=[...props.options],index=newOptions.findIndex(o=>o.id===option.id);newOptions[index]={id:option.id,[propName]:newValue},props.onChange({...props.item,answerOption:newOptions})},outcome:void 0},option.id)}),jsx159("div",{children:jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:props.options.filter(o=>o.id!==option.id)})},children:"Remove"})})]},option.id)})})}function ReferenceProfiles(props){let targetTypes=getQuestionnaireItemReferenceTargetTypes2(props.item)??[];return jsxs106(Fragment54,{children:[targetTypes.map((targetType,index)=>jsxs106(Group64,{children:[jsx159(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",defaultValue:targetType,onChange:newValue=>{props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.map(t=>t===targetType?newValue:t)))}}),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.filter(t=>t!==targetType)))},children:"Remove"})]},`${targetType}-${index}`)),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,[...targetTypes,""]))},children:"Add Resource Type"})]})}var nextLinkId=1,nextId2=1;function generateLinkId(prefix){return prefix+nextLinkId++}function generateId2(){return"id-"+nextId2++}function ensureQuestionnaireKeys(questionnaire2){return{...questionnaire2,id:questionnaire2.id||generateId2(),item:ensureQuestionnaireItemKeys(questionnaire2.item)}}function ensureQuestionnaireItemKeys(items){if(items)return items.forEach(item=>{item.id?.match(/^id-\d+$/)&&(nextId2=Math.max(nextId2,Number.parseInt(item.id.substring(3),10)+1)),item.linkId?.match(/^q\d+$/)&&(nextLinkId=Math.max(nextLinkId,Number.parseInt(item.linkId.substring(1),10)+1))}),items.map(item=>({...item,id:item.id||generateId2(),item:ensureQuestionnaireItemKeys(item.item),answerOption:ensureQuestionnaireOptionKeys(item.answerOption)}))}function ensureQuestionnaireOptionKeys(options){if(options)return options.map(option=>({...option,id:option.id||generateId2()}))}function createPage(){return{id:generateId2(),linkId:generateLinkId("s"),type:"group",text:"New Page",extension:[{url:QUESTIONNAIRE_ITEM_CONTROL_URL2,valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function reorderItems(items,itemIndex,delta){let currentItems=items??[],newIndex=itemIndex+delta;if(newIndex<0||newIndex>=currentItems.length)return currentItems;let updatedItems=[...currentItems];return[updatedItems[itemIndex],updatedItems[newIndex]]=[updatedItems[newIndex],updatedItems[itemIndex]],updatedItems}import{Stack as Stack44}from"@mantine/core";import{useResource as useResource16}from"@medplum/react-hooks";import{Stack as Stack43,Text as Text47}from"@mantine/core";import{formatDate as formatDate4}from"@medplum/core";import{useMemo as useMemo37}from"react";import{Fragment as Fragment55,jsx as jsx160,jsxs as jsxs107}from"react/jsx-runtime";function QuestionnaireResponseItemDisplay(props){let{item}=props,{text:title,answer,item:nestedAnswers}=item,renderContent=useMemo37(()=>answer&&answer.length>0?jsx160(Fragment55,{children:answer.map((ans,index)=>jsx160(AnswerDisplay,{answer:ans},`answer-${index}`))}):nestedAnswers&&nestedAnswers.length>0?jsx160(Fragment55,{children:nestedAnswers.map((nestedAnswer,index)=>jsx160(QuestionnaireResponseItemDisplay,{item:nestedAnswer},`nested-${nestedAnswer.id??index}`))}):jsx160(Text47,{c:"dimmed",children:"No answer"}),[answer,nestedAnswers]);return jsxs107(Stack43,{gap:0,pb:"xs",children:[jsx160(Text47,{size:"lg",fw:600,id:item.id?`question-${item.id}`:void 0,component:"h3",children:title}),renderContent]})}function AnswerDisplay({answer}){if(!answer)return jsx160(Text47,{c:"dimmed",children:"Invalid answer"});let validEntries=Object.entries(answer).filter(([,value2])=>value2!=null);if(validEntries.length===0)return jsx160(Text47,{c:"dimmed",children:"No valid answer data"});let[key,value]=validEntries[0];switch(key){case"valueInteger":return jsx160(Text47,{children:value});case"valueQuantity":return jsx160(QuantityDisplay,{value});case"valueString":return jsx160(Text47,{children:value});case"valueCoding":return jsx160(CodeableConceptDisplay,{value:{coding:[value]}});case"valueRange":return jsx160(RangeDisplay,{value});case"valueDateTime":return jsx160(Text47,{children:formatDate4(value)});case"valueBoolean":return jsx160(Text47,{children:value?"True":"False"});case"valueReference":return jsx160(Text47,{children:value.display??value.reference});default:return jsx160(Text47,{children:value.toString()})}}import{jsx as jsx161}from"react/jsx-runtime";function QuestionnaireResponseDisplay(props){let questionnaireResponse=useResource16(props.questionnaireResponse);return jsx161(Stack44,{gap:0,children:questionnaireResponse?.item?.map((item,index)=>jsx161(QuestionnaireResponseItemDisplay,{item},`item-${item.id??index}`))})}import{ActionIcon as ActionIcon19,Divider as Divider9,Group as Group65,NativeSelect as NativeSelect14,Stack as Stack45,Text as Text48,TextInput as TextInput31}from"@mantine/core";import{formatRange as formatRange2,getCodeBySystem}from"@medplum/core";import{useEffect as useEffect35,useState as useState88}from"react";var ReferenceRangeEditor_default={section:"ReferenceRangeEditor_section"};import{jsx as jsx162,jsxs as jsxs108}from"react/jsx-runtime";var intervalFilters=["gender","age","gestationalAge","context","appliesTo","category"],defaultProps={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function ReferenceRangeEditor(props){props=Object.assign(defaultProps,props);let defaultDefinition=props.definition,[intervalGroups,setIntervalGroups]=useState88([]),[groupId,setGroupId]=useState88(1),[intervalId,setIntervalId]=useState88(1);return useEffect35(()=>{let definition=ensureQualifiedIntervalKeys(defaultDefinition,setIntervalId);setIntervalGroups(groupQualifiedIntervals(definition.qualifiedInterval||[],setGroupId))},[defaultDefinition]),jsxs108(Form,{testid:"reference-range-editor",onSubmit:submitDefinition,children:[jsx162(Stack45,{children:intervalGroups.map(intervalGroup=>jsx162(ReferenceRangeGroupEditor,{unit:getUnitString(defaultDefinition.quantitativeDetails?.unit),onChange:changeInterval,onAdd:addInterval,onRemove:removeInterval,onRemoveGroup:removeGroup,intervalGroup},`group-${intervalGroup.id}`))}),jsx162(ActionIcon19,{title:"Add Group",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),addGroup({id:`group-id-${groupId}`,filters:{},intervals:[]}),setGroupId(id=>id+1)},children:jsx162(IconCirclePlus,{})}),jsx162(Group65,{justify:"flex-end",children:jsx162(SubmitButton,{children:"Save"})})]});function submitDefinition(){let qualifiedInterval=intervalGroups.flatMap(group=>group.intervals).filter(interval=>!isEmptyInterval(interval));props.onSubmit({...defaultDefinition,qualifiedInterval})}function addGroup(addedGroup){setIntervalGroups(currentGroups=>[...currentGroups,addedGroup])}function removeGroup(removedGroup){setIntervalGroups(currentGroups=>currentGroups.filter(group=>group.id!==removedGroup.id))}function changeInterval(groupId2,changedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2),index=currentGroup?.intervals.findIndex(interval=>interval.id===changedInterval.id);return index!==void 0&¤tGroup?.intervals[index]&&(currentGroup.intervals[index]=changedInterval),groups})}function addInterval(groupId2,addedInterval){addedInterval.id===void 0&&(addedInterval.id=`id-${intervalId}`,setIntervalId(id=>id+1)),setIntervalGroups(groups=>{groups=[...groups];let currentGroupIndex=groups.findIndex(g=>g.id===groupId2);if(currentGroupIndex!==-1){let currentGroup={...groups[currentGroupIndex]};addedInterval={...addedInterval,...currentGroup.filters},currentGroup.intervals=[...currentGroup.intervals,addedInterval],groups[currentGroupIndex]=currentGroup}return groups})}function removeInterval(groupId2,removedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2);return currentGroup&&(currentGroup.intervals=currentGroup.intervals.filter(interval=>interval.id!==removedInterval.id)),groups})}}function ReferenceRangeGroupEditor(props){let{intervalGroup,unit}=props;return jsx162(Container,{"data-testid":intervalGroup.id,className:ReferenceRangeEditor_default.section,children:jsxs108(Stack45,{gap:"lg",children:[jsx162(Group65,{justify:"flex-end",children:jsx162(ActionIcon19,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${intervalGroup.id}`,size:"sm",onClick:e=>{killEvent(e),props.onRemoveGroup(intervalGroup)},children:jsx162(IconCircleMinus,{})},`remove-group-button-${intervalGroup.id}`)}),jsx162(ReferenceRangeGroupFilters,{intervalGroup,onChange:props.onChange}),jsx162(Divider9,{}),intervalGroup.intervals.map(interval=>jsxs108(Stack45,{gap:"xs",children:[jsxs108(Group65,{children:[jsx162(TextInput31,{"data-testid":`condition-${interval.id}`,defaultValue:interval.condition,label:"Condition: ",size:"sm",onChange:e=>{killEvent(e),props.onChange(intervalGroup.id,{...interval,condition:e.currentTarget.value.trim()})}},`condition-${interval.id}`),jsx162(ActionIcon19,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${interval.id}`,onClick:e=>{killEvent(e),props.onRemove(intervalGroup.id,interval)},children:jsx162(IconCircleMinus,{})},`remove-interval-${interval.id}`)]}),jsx162(RangeInput,{path:"",onChange:range=>{props.onChange(intervalGroup.id,{...interval,range})},name:`range-${interval.id}`,defaultValue:interval.range},`range-${interval.id}`)]},`interval-${interval.id}`)),jsx162(ActionIcon19,{title:"Add Interval",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),props.onAdd(intervalGroup.id,{range:{low:{unit},high:{unit}}})},children:jsx162(IconCirclePlus,{})})]})})}function ReferenceRangeGroupFilters(props){let{intervalGroup,onChange}=props,age=intervalGroup.filters.age??{},ageWithDefaults={low:age.low?.unit?age.low:{...age.low,unit:"years",system:"http://unitsofmeasure.org"},high:age.high?.unit?age.high:{...age.high,unit:"years",system:"http://unitsofmeasure.org"}};return jsxs108(Stack45,{style:{maxWidth:"50%"},children:[jsx162(Group65,{children:jsx162(NativeSelect14,{data:["","male","female"],label:"Gender:",defaultValue:intervalGroup.filters.gender||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newGender=e.currentTarget.value;newGender===""&&(newGender=void 0),onChange(intervalGroup.id,{...interval,gender:newGender})}}})}),jsxs108(Group65,{gap:"xs",children:[jsx162(Text48,{component:"label",htmlFor:`div-age-${intervalGroup.id}`,children:"Age:"}),jsx162("div",{id:`div-age-${intervalGroup.id}`,children:jsx162(RangeInput,{path:"",name:`age-${intervalGroup.id}`,defaultValue:ageWithDefaults,onChange:ageRange=>{for(let interval of intervalGroup.intervals)onChange(intervalGroup.id,{...interval,age:ageRange})}},`age-${intervalGroup.id}`)})]}),jsx162(NativeSelect14,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:intervalGroup.filters.context?.text||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newEndocrine=e.currentTarget.value;newEndocrine===""?(newEndocrine=void 0,onChange(intervalGroup.id,{...interval,context:void 0})):onChange(intervalGroup.id,{...interval,context:{text:newEndocrine,coding:[{code:newEndocrine,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),jsx162(NativeSelect14,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:intervalGroup.filters.category,onChange:e=>{for(let interval of intervalGroup.intervals){let newCategory=e.currentTarget.value;newCategory===""?onChange(intervalGroup.id,{...interval,category:void 0}):onChange(intervalGroup.id,{...interval,category:newCategory})}}})]})}function ensureQualifiedIntervalKeys(definition,setIntervalId){let intervals=definition.qualifiedInterval||[],nextId3=Math.max(...intervals.map(interval=>{let existingNum=Number.parseInt(interval.id?.substring(3)||"",10);return Number.isNaN(existingNum)?Number.NEGATIVE_INFINITY:existingNum}))+1;return Number.isFinite(nextId3)||(nextId3=1),definition={...definition,qualifiedInterval:intervals.map(interval=>({...interval,id:interval.id||`id-${nextId3++}`}))},setIntervalId(nextId3),definition}function groupQualifiedIntervals(intervals,setGroupId){let groupId=1,groups={};for(let interval of intervals){let groupKey=generateGroupKey(interval);groupKey in groups||(groups[groupKey]={id:`group-id-${groupId++}`,filters:Object.fromEntries(intervalFilters.map(f=>[f,interval[f]])),intervals:[]}),groups[groupKey].intervals.push(interval)}return setGroupId(groupId),Object.values(groups)}function generateGroupKey(interval){return[`gender=${interval.gender}`,`age=${formatRange2(interval.age)}`,`gestationalAge=${formatRange2(interval.gestationalAge)}`,`context=${interval.context?.text}`,`appliesTo=${interval.appliesTo?.map(c=>c.text).join("+")}`,`category=${interval.category}`].join(":")}function getUnitString(unit){return unit&&(getCodeBySystem(unit,"http://unitsofmeasure.org")||unit.text)}function isEmptyInterval(interval){return interval.range?.low?.value===void 0&&interval.range?.high?.value===void 0}import{Button as Button23,Grid as Grid2,Text as Text49}from"@mantine/core";import{formatDateTime as formatDateTime7,getReferenceString as getReferenceString13}from"@medplum/core";import{useMedplum as useMedplum49,useResource as useResource17}from"@medplum/react-hooks";import{Fragment as Fragment56,useEffect as useEffect36,useState as useState89}from"react";import{jsx as jsx163,jsxs as jsxs109}from"react/jsx-runtime";function RequestGroupDisplay(props){let medplum=useMedplum49(),requestGroup=useResource17(props.value),[startedLoading,setStartedLoading]=useState89(!1),[responseBundle,setResponseBundle]=useState89();if(useEffect36(()=>{requestGroup&&!startedLoading&&(medplum.executeBatch(buildBatchRequest(requestGroup)).then(setResponseBundle).catch(console.log),setStartedLoading(!0))},[medplum,requestGroup,startedLoading]),!requestGroup||!responseBundle)return null;return jsx163(Grid2,{children:requestGroup.action?.map((action,index)=>{let task=action.resource&&findBundleEntry(action.resource),taskInput=task?.input?.[0]?.valueReference,taskOutput=task?.output?.[0]?.valueReference;return jsxs109(Fragment56,{children:[jsx163(Grid2.Col,{span:1,p:"md",children:task?.status==="completed"?jsx163(IconCheckbox,{}):jsx163(IconSquare,{color:"gray"})}),jsxs109(Grid2.Col,{span:9,p:"xs",children:[jsx163(Text49,{fw:500,children:action.title}),action.description&&jsx163("div",{children:action.description}),jsxs109("div",{children:["Last edited by\xA0",jsx163(ResourceName,{value:task?.meta?.author}),"\xA0on\xA0",formatDateTime7(task?.meta?.lastUpdated)]}),jsxs109("div",{children:["Status: ",jsx163(StatusBadge,{status:task?.status||"unknown"})]})]}),jsxs109(Grid2.Col,{span:2,p:"md",children:[taskInput&&!taskOutput&&jsx163(Button23,{onClick:()=>props.onStart(task,taskInput),children:"Start"}),taskInput&&taskOutput&&jsx163(Button23,{onClick:()=>props.onEdit(task,taskInput,taskOutput),children:"Edit"})]})]},`action-${index}`)})});function buildBatchRequest(request){let batchEntries=[];if(request.action)for(let action of request.action)action.resource?.reference&&batchEntries.push({request:{method:"GET",url:action.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:batchEntries}}function findBundleEntry(reference){for(let entry of responseBundle?.entry??[])if(entry.resource&&reference.reference===getReferenceString13(entry.resource))return entry.resource}}import{useMedplum as useMedplum50}from"@medplum/react-hooks";import{useEffect as useEffect37,useState as useState90}from"react";import{stringify as stringify4}from"@medplum/core";function diff(original,revised){let path=buildPath(original,revised);return buildRevisions(path,original,revised)}function buildPath(orig,rev){let N=orig.length,M=rev.length,MAX=N+M+1,size=1+2*MAX,middle=Math.trunc(size/2),diagonal=new Array(size);diagonal[middle+1]={i:0,j:-1,prev:void 0,snake:!0};for(let d=0;d<MAX;d++){for(let k=-d;k<=d;k+=2){let kmiddle=middle+k,kplus=kmiddle+1,kminus=kmiddle-1,kplusNode=diagonal[kplus],kminusNode=diagonal[kminus],prev,i=0;k===-d||k!==d&&kminusNode.i<kplusNode.i?(i=kplusNode.i,prev=kplusNode):(i=kminusNode.i+1,prev=kminusNode),diagonal[kminus]=void 0;let j=i-k,node={i,j,prev:previousSnake(prev),snake:!1};for(;i<N&&j<M&&orig[i]===rev[j];)i++,j++;if(i>node.i&&(node={i,j,prev:node,snake:!0}),diagonal[kmiddle]=node,i>=N&&j>=M)return diagonal[kmiddle]}diagonal[middle+d-1]=void 0}}function buildRevisions(startNode,orig,rev){let deltas=[],path=startNode;for(path.snake&&(path=path.prev);path?.prev&&path.prev.j>=0;){let i=path.i,j=path.j;path=path.prev;let ianchor=path.i,janchor=path.j,original={position:ianchor,lines:orig.slice(ianchor,i)},revised={position:janchor,lines:rev.slice(janchor,j)},type;original.lines.length===0&&revised.lines.length>0?type="insert":original.lines.length>0&&revised.lines.length===0?type="delete":type="change",deltas.push({original,revised,type}),path.snake&&(path=path.prev)}return deltas}function previousSnake(node){return node&&!node.snake&&node.prev?node.prev:node}function blame(history){let versions=(history.entry??[]).filter(entry=>!!entry.resource).map(entry=>({meta:entry.resource?.meta,lines:stringify4(entry.resource,!0).match(/[^\r\n]+/g)})).sort((a,b)=>a.meta.lastUpdated.localeCompare(b.meta.lastUpdated));if(!versions.length)return[];let table=versions[0].lines.map(line=>({id:versions[0].meta.versionId,meta:versions[0].meta,value:line,span:1}));return compareVersions(table,versions),combineSpans(table),table}function compareVersions(table,versions){for(let i=1;i<versions.length;i++){let revisions=diff(versions[i-1].lines,versions[i].lines);for(let revision of revisions){let position=revision.original.position,oldLines=revision.original.lines,newLines=revision.revised.lines;if((revision.type==="delete"||revision.type==="change")&&table.splice(position,oldLines.length),revision.type==="insert"||revision.type==="change")for(let k=0;k<revision.revised.lines.length;k++)table.splice(position+k,0,{id:versions[i].meta.versionId,meta:versions[i].meta,value:newLines[k],span:1})}}}function combineSpans(table){let start=0;for(;start<table.length;){let curr=start;for(;curr<table.length&&table[curr].id===table[start].id;)table[curr].span=-1,curr++;table[start].span=curr-start,start=curr}}var ResourceBlame_default={container:"ResourceBlame_container",root:"ResourceBlame_root",startRow:"ResourceBlame_startRow",normalRow:"ResourceBlame_normalRow",author:"ResourceBlame_author",dateTime:"ResourceBlame_dateTime",lineNumber:"ResourceBlame_lineNumber",line:"ResourceBlame_line",pre:"ResourceBlame_pre"};function getVersionUrl(resource,versionId){return`/${resource.resourceType}/${resource.id}/_history/${versionId}`}function getTimeString(lastUpdated){let seconds=Math.floor((Date.now()-Date.parse(lastUpdated))/1e3),years=Math.floor(seconds/31536e3);if(years>0)return pluralizeTime(years,"year");let months=Math.floor(seconds/2592e3);if(months>0)return pluralizeTime(months,"month");let days=Math.floor(seconds/86400);if(days>0)return pluralizeTime(days,"day");let hours=Math.floor(seconds/3600);if(hours>0)return pluralizeTime(hours,"hour");let minutes=Math.floor(seconds/60);return minutes>0?pluralizeTime(minutes,"minute"):pluralizeTime(seconds,"second")}function pluralizeTime(count,noun){return`${count} ${count===1?noun:noun+"s"} ago`}import{Fragment as Fragment57,jsx as jsx164,jsxs as jsxs110}from"react/jsx-runtime";function ResourceBlame(props){let medplum=useMedplum50(),[value,setValue]=useState90(props.history);if(useEffect37(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),!value)return jsx164("div",{children:"Loading..."});let resource=value.entry?.[0]?.resource;if(!resource)return null;let table=blame(value);return jsx164("div",{className:ResourceBlame_default.container,children:jsx164("table",{className:ResourceBlame_default.root,children:jsx164("tbody",{children:table.map((row,index)=>jsxs110("tr",{className:row.span>0?ResourceBlame_default.startRow:ResourceBlame_default.normalRow,children:[row.span>0&&jsxs110(Fragment57,{children:[jsx164("td",{className:ResourceBlame_default.author,rowSpan:row.span,children:jsx164(ResourceName,{value:row.meta.author,link:!0,fz:"xs"})}),jsx164("td",{className:ResourceBlame_default.dateTime,rowSpan:row.span,children:jsx164(MedplumLink,{to:getVersionUrl(resource,row.meta.versionId),fz:"xs",children:getTimeString(row.meta.lastUpdated)})})]}),jsx164("td",{className:ResourceBlame_default.lineNumber,children:index+1}),jsx164("td",{className:ResourceBlame_default.line,children:jsx164("pre",{className:ResourceBlame_default.pre,children:row.value})})]},"row-"+index))})})})}import{stringify as stringify5}from"@medplum/core";var ResourceDiff_default={removed:"ResourceDiff_removed",added:"ResourceDiff_added"};import{Fragment as Fragment58,jsx as jsx165,jsxs as jsxs111}from"react/jsx-runtime";function ResourceDiff(props){let originalResource=props.original,revisedResource=props.revised;props.ignoreMeta&&(originalResource={...originalResource,meta:void 0},revisedResource={...revisedResource,meta:void 0});let original=stringify5(originalResource,!0).match(/[^\r\n]+/g),revised=stringify5(revisedResource,!0).match(/[^\r\n]+/g),deltas=diff(original,revised);return jsx165("pre",{style:{color:"gray"},children:deltas.map((delta,index)=>jsx165(ChangeDiff,{delta},"delta"+index))})}function ChangeDiff(props){return jsxs111(Fragment58,{children:["...",jsx165("br",{}),props.delta.original.lines.length>0&&jsx165("div",{className:ResourceDiff_default.removed,children:props.delta.original.lines.join(`
|
|
109
|
+
}`.replaceAll(/\s+/g," ");return(await medplum.graphql(query)).data.StructureDefinitionList[0]}function shouldFetchResourceType(targetType){return targetType.type==="profile"&&!targetType?.error&&isEmpty4(targetType.resourceType)}import{Group as Group25,Stack as Stack15,Text as Text16}from"@mantine/core";import{getPathDisplayName as getPathDisplayName4}from"@medplum/core";import{useMedplum as useMedplum22}from"@medplum/react-hooks";import{useContext as useContext19,useEffect as useEffect13,useState as useState44}from"react";function getValuePath(elementPath,valuePath,arrayIndex){return valuePath===void 0?elementPath:arrayIndex===void 0?valuePath:`${valuePath}[${arrayIndex}]`}import{Group as Group24,Stack as Stack14,Text as Text15}from"@mantine/core";import{buildElementsContext as buildElementsContext3,getPropertyDisplayName,isEmpty as isEmpty5,isPopulated as isPopulated9}from"@medplum/core";import{useContext as useContext18,useMemo as useMemo18,useState as useState43}from"react";var ResourceArrayInput_default={indented:"ResourceArrayInput_indented"};import{ActionIcon as ActionIcon4,Button as Button6}from"@mantine/core";import{jsx as jsx80}from"react/jsx-runtime";function ArrayAddButton({propertyDisplayName,onClick,testId}){let text=propertyDisplayName?`Add ${propertyDisplayName}`:"Add";return propertyDisplayName?jsx80(Button6,{title:text,size:"sm",color:"green.6",variant:"subtle","data-testid":testId,leftSection:jsx80(IconCirclePlus,{size:"1.25rem"}),onClick,children:text}):jsx80(ActionIcon4,{title:text,color:"green.6","data-testid":testId,onClick,children:jsx80(IconCirclePlus,{size:"1.25rem"})})}import{ActionIcon as ActionIcon5}from"@mantine/core";import{jsx as jsx81}from"react/jsx-runtime";function ArrayRemoveButton({propertyDisplayName,onClick,testId}){return jsx81(ActionIcon5,{title:propertyDisplayName?`Remove ${propertyDisplayName}`:"Remove",color:"red.5","data-testid":testId,variant:"subtle",onClick,children:jsx81(IconCircleMinus,{size:"1.25rem"})})}import{jsx as jsx82,jsxs as jsxs45}from"react/jsx-runtime";function SliceInput(props){let{slice,property}=props,[values,setValues]=useState43(props.defaultValue),sliceElements=slice.typeSchema?.elements??slice.elements,parentElementsContextValue=useContext18(ElementsContext),contextValue=useMemo18(()=>{if(isPopulated9(sliceElements))return buildElementsContext3({parentContext:parentElementsContextValue,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentElementsContextValue,props.path,slice.typeSchema?.url,sliceElements]);function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}let required=slice.min>0,indentedStack=isEmpty5(slice.elements),propertyDisplayName=getPropertyDisplayName(slice.name),showEmptyMessage=props.property.readonly&&values.length===0;return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx82(FormSection,{title:propertyDisplayName,description:slice.definition,withAsterisk:required,fhirPath:`${property.path}:${slice.name}`,testId:props.testId,readonly:props.property.readonly,children:showEmptyMessage?jsx82(Text15,{c:"dimmed",children:"(empty)"}):jsxs45(Stack14,{className:indentedStack?ResourceArrayInput_default.indented:void 0,children:[values.map((value,valueIndex)=>jsxs45(Group24,{wrap:"nowrap",children:[jsx82("div",{style:{flexGrow:1},"data-testid":props.testId&&`${props.testId}-elements-${valueIndex}`,children:jsx82(ElementDefinitionTypeInput,{elementDefinitionType:slice.type[0],name:slice.name,defaultValue:value,onChange:newValue=>{let newValues=[...values];newValues[valueIndex]=newValue,setValuesWrapper(newValues)},outcome:props.outcome,min:slice.min,max:slice.max,binding:slice.binding,path:props.path,valuePath:void 0,readOnly:props.property.readonly})}),!props.property.readonly&&values.length>slice.min&&jsx82(ArrayRemoveButton,{propertyDisplayName,testId:props.testId&&`${props.testId}-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newValues=[...values];newValues.splice(valueIndex,1),setValuesWrapper(newValues)}})]},`${valueIndex}-${values.length}`)),!props.property.readonly&&values.length<slice.max&&jsx82(Group24,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx82(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newValues=[...values,void 0];setValuesWrapper(newValues)},testId:props.testId&&`${props.testId}-add`})})]})}))}import{jsx as jsx83,jsxs as jsxs46}from"react/jsx-runtime";function ResourceArrayInput(props){let{property}=props,medplum=useMedplum22(),[loading,setLoading]=useState44(!0),[slices,setSlices]=useState44([]),[defaultValue2]=useState44(()=>Array.isArray(props.defaultValue)?props.defaultValue:[]),[slicedValues,setSlicedValues]=useState44(()=>[defaultValue2]),ctx=useContext19(ElementsContext),propertyTypeCode=property.type[0]?.code;useEffect13(()=>{prepareSlices({medplum,property}).then(slices2=>{setSlices(slices2);let slicedValues2=assignValuesIntoSlices(defaultValue2,slices2,property.slicing,ctx.profileUrl);addPlaceholderValues(slicedValues2,slices2),setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,defaultValue2,ctx.profileUrl,setSlicedValues]);function setValuesWrapper(newValues,sliceIndex){let newSlicedValues=[...slicedValues];if(newSlicedValues[sliceIndex]=newValues,setSlicedValues(newSlicedValues),props.onChange){let cleaned=newSlicedValues.flat().filter(val=>val!==void 0);props.onChange(cleaned)}}if(loading)return jsx83("div",{children:"Loading..."});let nonSliceIndex=slices.length,nonSliceValues=slicedValues[nonSliceIndex],showNonSliceValues=!(props.hideNonSliceValues??(propertyTypeCode==="Extension"&&slices.length>0)),propertyDisplayName=getPathDisplayName4(property.path),showEmptyMessage=props.property.readonly&&slices.length===0&&defaultValue2.length===0;return jsxs46(Stack15,{className:props.indent?ResourceArrayInput_default.indented:void 0,children:[showEmptyMessage&&jsx83(Text16,{c:"dimmed",children:"(empty)"}),slices.map((slice,sliceIndex)=>jsx83(SliceInput,{slice,path:props.path,valuePath:props.valuePath,property,defaultValue:slicedValues[sliceIndex],onChange:newValue=>{setValuesWrapper(newValue,sliceIndex)},testId:`slice-${slice.name}`},slice.name)),showNonSliceValues&&nonSliceValues.map((value,valueIndex)=>jsxs46(Group25,{wrap:"nowrap",style:{flexGrow:1},children:[jsx83("div",{style:{flexGrow:1},children:jsx83(ResourcePropertyInput,{arrayElement:!0,property:props.property,name:props.name+"."+valueIndex,path:props.path,valuePath:getValuePath(props.path,props.valuePath,valueIndex),defaultValue:value,onChange:newValue=>{let newNonSliceValues=[...nonSliceValues];newNonSliceValues[valueIndex]=newValue,setValuesWrapper(newNonSliceValues,nonSliceIndex)},defaultPropertyType:void 0,outcome:props.outcome})}),!props.property.readonly&&jsx83(ArrayRemoveButton,{propertyDisplayName,testId:`nonsliced-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.splice(valueIndex,1),setValuesWrapper(newNonSliceValues,nonSliceIndex)}})]},`${valueIndex}-${nonSliceValues.length}`)),!props.property.readonly&&showNonSliceValues&&slicedValues.flat().length<property.max&&jsx83(Group25,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx83(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.push(void 0),setValuesWrapper(newNonSliceValues,nonSliceIndex)},testId:"nonsliced-add"})})]})}function addPlaceholderValues(slicedValues,slices){for(let sliceIndex=0;sliceIndex<slices.length;sliceIndex++){let slice=slices[sliceIndex],sliceValues=slicedValues[sliceIndex];for(;sliceValues.length<slice.min;)sliceValues.push(void 0)}}import{ActionIcon as ActionIcon6,Flex as Flex10,Textarea}from"@mantine/core";import{useClipboard}from"@mantine/hooks";import{showNotification as showNotification4}from"@mantine/notifications";import{useRef as useRef8,useState as useState45}from"react";import{jsx as jsx84,jsxs as jsxs47}from"react/jsx-runtime";function SensitiveTextarea(props){let[revealed,setRevealed]=useState45(!1),clipboard=useClipboard(),ref=useRef8(null),styles={...props.styles};return revealed||(styles.input||(styles.input={}),styles.input.WebkitTextSecurity="disc"),jsxs47(Flex10,{gap:"xs",children:[jsx84(Textarea,{...props,styles:{...styles,root:{...styles.root??{},flexGrow:1}},ref,autosize:!0,minRows:1,onFocus:()=>setRevealed(!0),onBlur:()=>setRevealed(!1)}),jsx84(ActionIcon6,{title:"Copy secret",onClick:()=>{clipboard.copy(ref.current?.value),showNotification4({color:"green",message:"Copied"})},children:jsx84(IconCopy,{})})]})}import{Box as Box6,Button as Button7,Chip,Group as Group26,Modal as Modal2,NativeSelect as NativeSelect8,Stack as Stack16,Switch,TextInput as TextInput17}from"@mantine/core";import{formatTiming as formatTiming2}from"@medplum/core";import{useContext as useContext20,useMemo as useMemo19,useRef as useRef9,useState as useState46}from"react";import{Fragment as Fragment28,jsx as jsx85,jsxs as jsxs48}from"react/jsx-runtime";var daysOfWeek=["sun","mon","tue","wed","thu","fri","sat"];function TimingInput(props){let[value,setValue]=useState46(props.defaultValue),[open,setOpen]=useState46(!props.disabled&&(props.defaultModalOpen??!1));return jsxs48(Fragment28,{children:[jsxs48(Group26,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx85("span",{"data-testid":"timinginput-display",children:formatTiming2(value)||"No repeat"}),jsx85(Button7,{disabled:props.disabled,onClick:()=>setOpen(!0),children:"Edit"})]}),!props.disabled&&jsx85(TimingEditorDialog,{path:props.path,visible:open,defaultValue:value,onOk:newValue=>{props.onChange&&props.onChange(newValue),setValue(newValue),setOpen(!1)},onCancel:()=>setOpen(!1)})]})}var defaultValue={repeat:{period:1,periodUnit:"d"}};function TimingEditorDialog(props){let[value,setValue]=useState46(props.defaultValue||defaultValue),[timeOfDayItems,setTimeOfDayItems]=useState46(()=>(props.defaultValue?.repeat?.timeOfDay??[]).map((v,i)=>({id:i,value:v}))),nextTimeOfDayId=useRef9(timeOfDayItems.length),{getExtendedProps}=useContext20(ElementsContext),[eventProps,repeatProps,repeatPeriodProps,repeatPeriodUnitProps,repeatDayOfWeekProps,repeatTimeOfDayProps]=useMemo19(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek","repeat.timeOfDay"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setStart(newStart){setValue(value2=>({...value2,event:[newStart]}))}function setRepeat(repeat){setValue(value2=>({...value2,repeat}))}function setPeriod(period){setValue(value2=>({...value2,repeat:{...value2.repeat,period}}))}function setPeriodUnit(periodUnit){setValue(value2=>({...value2,repeat:{...value2.repeat,periodUnit}}))}function setDaysOfWeek(dayOfWeek){setValue(value2=>({...value2,repeat:{...value2.repeat,dayOfWeek}}))}function setTimeOfDay(updater){setTimeOfDayItems(items=>{let newItems=updater(items),timeOfDay=newItems.map(item=>item.value);return setValue(value2=>({...value2,repeat:{...value2.repeat,timeOfDay}})),newItems})}return jsx85(Modal2,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>props.onCancel(),children:jsxs48(Stack16,{gap:"md",children:[jsx85(FormSection,{title:"Starts on",htmlFor:"timing-dialog-start",children:jsx85(DateTimeInput,{disabled:eventProps?.readonly,name:"timing-dialog-start",onChange:newValue=>setStart(newValue)})}),jsx85(Switch,{disabled:repeatProps?.readonly,label:"Repeat",checked:!!value.repeat,onChange:e=>setRepeat(e.currentTarget.checked?defaultValue.repeat:void 0)}),value.repeat&&jsxs48(Fragment28,{children:[jsx85(FormSection,{title:"Repeat every",htmlFor:"timing-dialog-period",children:jsxs48(Group26,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx85(TextInput17,{disabled:repeatPeriodProps?.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:value.repeat.period||1,onChange:e=>setPeriod(Number.parseInt(e.currentTarget.value,10)||1)}),jsx85(NativeSelect8,{disabled:repeatPeriodUnitProps?.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:value.repeat.periodUnit,onChange:e=>setPeriodUnit(e.currentTarget.value),data:[{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),value.repeat.periodUnit==="wk"&&jsx85(FormSection,{title:"Repeat on",children:jsx85(Chip.Group,{multiple:!0,onChange:setDaysOfWeek,value:value.repeat?.dayOfWeek,children:jsx85(Group26,{justify:"space-between",mt:"xs",gap:"xs",children:daysOfWeek.map(day=>jsx85(Chip,{value:day,size:"xs",radius:"xl",disabled:repeatDayOfWeekProps?.readonly,checked:(value.repeat?.dayOfWeek??[]).includes(day),children:day.charAt(0).toUpperCase()},day))})})}),jsx85(FormSection,{title:"At times",children:jsxs48(Stack16,{mt:"xs",children:[timeOfDayItems.map((item,idx)=>jsxs48(Group26,{children:[jsx85(TextInput17,{disabled:repeatTimeOfDayProps?.readonly,type:"time",id:`timing-dialog-repeat-timeOfDay[${idx}]`,name:`timing-dialog-repeat-timeOfDay[${idx}]`,"data-testid":`timing-repeat-timeOfDay-input-${idx}`,defaultValue:item.value.slice(0,5),onChange:e=>{let newValue=`${e.currentTarget.value}:00`;setTimeOfDay(items=>items.with(idx,{...item,value:newValue}))},style:{flexGrow:1}}),jsx85(ArrayRemoveButton,{testId:`timing-repeat-timeOfDay-remove-${idx}`,onClick:()=>setTimeOfDay(items=>items.toSpliced(idx,1))})]},item.id)),jsx85(Box6,{children:jsx85(ArrayAddButton,{propertyDisplayName:"Time of Day",onClick:()=>setTimeOfDay(items=>{let id=nextTimeOfDayId.current++;return items.concat({id,value:"00:00:00"})})})})]})})]}),jsx85(Group26,{justify:"flex-end",children:jsx85(Button7,{onClick:()=>props.onOk(value),children:"OK"})})]})})}import{jsx as jsx86,jsxs as jsxs49}from"react/jsx-runtime";function ResourcePropertyInput(props){let{property,name,onChange,defaultValue:defaultValue2}=props,defaultPropertyType=props.defaultPropertyType&&props.defaultPropertyType!=="undefined"?props.defaultPropertyType:property.type[0].code,propertyTypes=property.type;if((property.isArray||property.max>1)&&!props.arrayElement){if(defaultPropertyType===PropertyType2.Attachment)return jsx86(AttachmentArrayInput,{name,defaultValue:defaultValue2,onChange,disabled:property.readonly});let indent=propertyTypes[0]?.code!==PropertyType2.Extension;return jsx86(ResourceArrayInput,{property,name,path:props.path,valuePath:props.valuePath,defaultValue:defaultValue2,indent,onChange,outcome:props.outcome})}else return propertyTypes.length>1?jsx86(ElementDefinitionInputSelector,{elementDefinitionTypes:propertyTypes,...props}):jsx86(ElementDefinitionTypeInput,{name,defaultValue:defaultValue2,onChange:newValue=>{if(props.onChange){let newPropName=props.name.replace("[x]",capitalize2(propertyTypes[0].code));props.onChange(newValue,newPropName)}},outcome:props.outcome,elementDefinitionType:propertyTypes[0],min:property.min,max:property.min,binding:property.binding,path:props.path,valuePath:props.valuePath,readOnly:property.readonly})}function ElementDefinitionInputSelector(props){let propertyTypes=props.elementDefinitionTypes,initialPropertyType;props.defaultPropertyType&&(initialPropertyType=propertyTypes.find(t=>t.code===props.defaultPropertyType)),initialPropertyType||(initialPropertyType=propertyTypes[0]);let[selectedType,setSelectedType]=useState47(initialPropertyType);return jsxs49(Group27,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx86(NativeSelect9,{disabled:props.property.readonly,style:{width:"200px"},defaultValue:selectedType.code,"data-testid":props.name&&props.name+"-selector",onChange:e=>{setSelectedType(propertyTypes.find(type=>type.code===e.currentTarget.value))},data:propertyTypes.map(type=>({value:type.code,label:type.code}))}),jsx86(ElementDefinitionTypeInput,{name:props.name,defaultValue:props.defaultValue,outcome:props.outcome,elementDefinitionType:selectedType,onChange:newValue=>{props.onChange&&props.onChange(newValue,props.name.replace("[x]",capitalize2(selectedType.code)))},min:props.property.min,max:props.property.max,binding:props.property.binding,path:props.property.path,valuePath:props.valuePath,readOnly:props.property.readonly})]})}function ElementDefinitionTypeInput(props){let{name,onChange,outcome,binding,path,valuePath,readOnly}=props,required=props.min!==void 0&&props.min>0,propertyType=props.elementDefinitionType.code,elementsContext=useContext21(ElementsContext),defaultValue2=useMemo20(()=>{if(!isComplexTypeCode(propertyType)||!isEmpty6(props.defaultValue))return props.defaultValue;let withDefaults=Object.create(null);if(elementsContext.path===props.path)applyDefaultValuesToElement(withDefaults,elementsContext.elements);else{let key=getPathDifference(elementsContext.path,props.path);if(key===void 0)return props.defaultValue;applyDefaultValuesToElement(withDefaults,elementsContext.elements,key)}return isPopulated10(withDefaults)?withDefaults:props.defaultValue},[propertyType,elementsContext.path,elementsContext.elements,props.path,props.defaultValue]);if(!propertyType)return jsx86("div",{children:"Property type not specified "});function getComplexInputProps(){return{name,defaultValue:defaultValue2,onChange,outcome,path,valuePath,disabled:readOnly}}function getPrimitiveInputProps(){let error=getErrorsForInput(props.outcome,valuePath??path);return{id:name,name,"data-testid":name,defaultValue:defaultValue2,required,error,disabled:readOnly}}switch(propertyType){case PropertyType2.SystemString:case PropertyType2.canonical:case PropertyType2.string:case PropertyType2.uri:case PropertyType2.url:return props.path==="Project.secret.value[x]"||props.path==="ClientApplication.certificateTrustStore"?jsx86(SensitiveTextarea,{...getPrimitiveInputProps(),onChange:e=>{props.onChange&&props.onChange(e.currentTarget.value)}}):jsx86(TextInput18,{...getPrimitiveInputProps(),onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.date:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"date",onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.time:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"time",step:1,onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.dateTime:case PropertyType2.instant:return jsx86(DateTimeInput,{...getPrimitiveInputProps(),onChange,outcome});case PropertyType2.decimal:case PropertyType2.integer:case PropertyType2.positiveInt:case PropertyType2.unsignedInt:return jsx86(TextInput18,{...getPrimitiveInputProps(),type:"number",step:propertyType===PropertyType2.decimal?"any":"1",onChange:e=>{if(onChange){let num=e.currentTarget.valueAsNumber;onChange(Number.isNaN(num)?void 0:num)}}});case PropertyType2.code:return jsx86(CodeInput,{...getPrimitiveInputProps(),error:void 0,onChange,binding:binding?.valueSet,creatable:!0,maxValues:1});case PropertyType2.boolean:return jsx86(Checkbox4,{...getPrimitiveInputProps(),defaultChecked:!!defaultValue2,onChange:e=>{onChange&&onChange(e.currentTarget.checked)}});case PropertyType2.base64Binary:case PropertyType2.markdown:case PropertyType2.xhtml:return jsx86(Textarea2,{...getPrimitiveInputProps(),spellCheck:propertyType!==PropertyType2.base64Binary,onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.Address:return jsx86(AddressInput,{...getComplexInputProps()});case PropertyType2.Annotation:return jsx86(AnnotationInput,{...getComplexInputProps()});case PropertyType2.Attachment:return jsx86(AttachmentInput,{...getComplexInputProps()});case PropertyType2.CodeableConcept:return jsx86(CodeableConceptInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.Coding:return jsx86(CodingInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.ContactDetail:return jsx86(ContactDetailInput,{...getComplexInputProps()});case PropertyType2.ContactPoint:return jsx86(ContactPointInput,{...getComplexInputProps()});case PropertyType2.Extension:return jsx86(ExtensionInput,{...getComplexInputProps(),propertyType:props.elementDefinitionType});case PropertyType2.HumanName:return jsx86(HumanNameInput,{...getComplexInputProps()});case PropertyType2.Identifier:return jsx86(IdentifierInput,{...getComplexInputProps()});case PropertyType2.Money:return jsx86(MoneyInput,{...getComplexInputProps()});case PropertyType2.Period:return jsx86(PeriodInput,{...getComplexInputProps()});case PropertyType2.Duration:case PropertyType2.Quantity:return jsx86(QuantityInput,{...getComplexInputProps()});case PropertyType2.Range:return jsx86(RangeInput,{...getComplexInputProps()});case PropertyType2.Ratio:return jsx86(RatioInput,{...getComplexInputProps()});case PropertyType2.Reference:return jsx86(ReferenceInput,{...getComplexInputProps(),targetTypes:getTargetTypes(props.elementDefinitionType)});case PropertyType2.Timing:return jsx86(TimingInput,{...getComplexInputProps()});case PropertyType2.Dosage:case PropertyType2.UsageContext:default:return jsx86(BackboneElementInput,{...getComplexInputProps(),typeName:propertyType})}}var RESOURCE_TYPE_URL_PREFIXES=[`${HTTP_HL7_ORG}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function getTargetTypes(elementDefinitionType){return elementDefinitionType?.targetProfile?.map(p=>{let resourceTypePrefix=RESOURCE_TYPE_URL_PREFIXES.find(prefix=>p.startsWith(prefix));return resourceTypePrefix?p.slice(resourceTypePrefix.length):p})}import{jsx as jsx87}from"react/jsx-runtime";function ElementsInput(props){let[value,setValue]=useState48(props.defaultValue??{}),elementsContext=useContext22(ElementsContext),elementsToRender=useMemo21(()=>getElementsToRender(elementsContext.elements),[elementsContext.elements]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}let typedValue={type:props.type,value};return jsx87(Stack17,{style:{flexGrow:1},"data-testid":props.testId,children:elementsToRender.map(([key,element])=>{let[propertyValue,propertyType]=getValueAndTypeFromElement(typedValue,key,element),required=element.min!==void 0&&element.min>0,valuePath=props.valuePath?props.valuePath+"."+key:void 0,resourcePropertyInput=jsx87(ResourcePropertyInput,{property:element,name:key,path:props.path+"."+key,valuePath,defaultValue:propertyValue,defaultPropertyType:propertyType,onChange:(newValue,propName)=>{setValueWrapper(setPropertyValue({...value},key,propName??key,element,newValue))},outcome:props.outcome},key);return props.type==="Extension"||EXTENSION_KEYS.includes(key)?resourcePropertyInput:element.type.length===1&&element.type[0].code==="boolean"?jsx87(CheckboxFormSection,{title:getPathDisplayName5(key),description:element.description,htmlFor:key,fhirPath:element.path,withAsterisk:required,readonly:element.readonly,children:resourcePropertyInput},key):jsx87(FormSection,{title:getPathDisplayName5(key),description:element.description,withAsterisk:required,htmlFor:key,outcome:props.outcome,fhirPath:element.path,errorExpression:valuePath,readonly:element.readonly,children:resourcePropertyInput},key)})})}var BackboneElementInput_default={nested:"BackboneElementInput_nested"};import{jsx as jsx88,jsxs as jsxs50}from"react/jsx-runtime";function BackboneElementInput(props){let[defaultValue2]=useState49(()=>props.defaultValue??{}),parentElementsContext=useContext23(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=useMemo22(()=>tryGetDataType2(props.typeName,profileUrl),[props.typeName,profileUrl]),type=typeSchema?.type??props.typeName,contextValue=useMemo22(()=>{if(typeSchema)return buildElementsContext4({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if(!typeSchema)return jsxs50("div",{children:[type,"\xA0not implemented"]});let isNested=parentElementsContext.path!=="";return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx88(Box7,{className:clsx_default({[BackboneElementInput_default.nested]:isNested}),children:jsx88(ElementsInput,{path:props.path,valuePath:props.valuePath,type,defaultValue:defaultValue2,onChange:props.onChange,outcome:props.outcome})}))}import{Button as Button8,Group as Group28}from"@mantine/core";import{useMemo as useMemo23,useState as useState50}from"react";var CalendarInput_default={table:"CalendarInput_table"};function getMonthString(date){return date.toLocaleString("default",{month:"long"})+" "+date.getFullYear()}function getStartMonth(){let result=new Date;return result.setDate(1),result.setHours(0,0,0,0),result}import{jsx as jsx89,jsxs as jsxs51}from"react/jsx-runtime";function CalendarInput(props){let{onChangeMonth,onClick}=props,[month,setMonth]=useState50(getStartMonth);function moveMonth(delta){setMonth(currMonth=>{let newMonth=new Date(currMonth.getTime());return newMonth.setMonth(currMonth.getMonth()+delta),onChangeMonth(newMonth),newMonth})}let grid=useMemo23(()=>buildGrid(month,props.slots),[month,props.slots]);return jsxs51("div",{children:[jsxs51(Group28,{justify:"space-between",gap:"xs",grow:!0,wrap:"nowrap",children:[jsx89("p",{style:{flex:1},children:getMonthString(month)}),jsxs51(Group28,{justify:"flex-end",gap:"xs",children:[jsx89(Button8,{variant:"outline","aria-label":"Previous month",onClick:()=>moveMonth(-1),children:"<"}),jsx89(Button8,{variant:"outline","aria-label":"Next month",onClick:()=>moveMonth(1),children:">"})]})]}),jsxs51("table",{className:CalendarInput_default.table,children:[jsx89("thead",{children:jsxs51("tr",{children:[jsx89("th",{children:"SUN"}),jsx89("th",{children:"MON"}),jsx89("th",{children:"TUE"}),jsx89("th",{children:"WED"}),jsx89("th",{children:"THU"}),jsx89("th",{children:"FRI"}),jsx89("th",{children:"SAT"})]})}),jsx89("tbody",{children:grid.map((week,weekIndex)=>jsx89("tr",{children:week.map((day,dayIndex)=>jsx89("td",{children:day&&jsx89(Button8,{variant:"light",disabled:!day.available,onClick:()=>onClick(day.date),children:day.date.getDate()})},"day-"+dayIndex))},"week-"+weekIndex))})]})]})}function buildGrid(startDate,slots){let d=new Date(startDate.getFullYear(),startDate.getMonth()),grid=[],row=[];for(let i=0;i<d.getDay();i++)row.push(void 0);for(;d.getMonth()===startDate.getMonth();)row.push({date:new Date(d.getTime()),available:isDayAvailable(d,slots)}),d.getDay()===6&&(grid.push(row),row=[]),d.setDate(d.getDate()+1);if(d.getDay()!==0){for(let i=d.getDay();i<7;i++)row.push(void 0);grid.push(row)}return grid}function isDayAvailable(day,slots){for(let slot of slots){let slotStart=new Date(slot.start);if(slotStart.getFullYear()===day.getFullYear()&&slotStart.getMonth()===day.getMonth()&&slotStart.getDate()===day.getDate())return!0}return!1}import{ActionIcon as ActionIcon7,Group as Group29,LoadingOverlay,Menu as Menu4,Paper as Paper2,Popover,ScrollArea as ScrollArea2,Skeleton,Stack as Stack19,Text as Text18,TextInput as TextInput20,Title as Title8}from"@mantine/core";import{useResizeObserver}from"@mantine/hooks";import{showNotification as showNotification5}from"@mantine/notifications";import{getDisplayString as getDisplayString4,getReferenceString as getReferenceString5,normalizeErrorString as normalizeErrorString6}from"@medplum/core";import{useCachedBinaryUrl as useCachedBinaryUrl3,useMedplum as useMedplum24,useResource as useResource2,useSubscription}from"@medplum/react-hooks";import{useCallback as useCallback11,useEffect as useEffect15,useMemo as useMemo24,useRef as useRef10,useState as useState52}from"react";var BaseChat_default={chatPaper:"BaseChat_chatPaper",chatTitle:"BaseChat_chatTitle",chatBody:"BaseChat_chatBody",chatScrollArea:"BaseChat_chatScrollArea",chatInputContainer:"BaseChat_chatInputContainer",chatPendingFile:"BaseChat_chatPendingFile",chatBubbleOuterWrap:"BaseChat_chatBubbleOuterWrap",chatBubbleRightAlignedInnerWrap:"BaseChat_chatBubbleRightAlignedInnerWrap",chatBubbleLeftAlignedInnerWrap:"BaseChat_chatBubbleLeftAlignedInnerWrap",chatBubble:"BaseChat_chatBubble",chatBubbleNameRight:"BaseChat_chatBubbleNameRight",chatBubbleAttachmentWithText:"BaseChat_chatBubbleAttachmentWithText",chatBubbleAttachmentIcon:"BaseChat_chatBubbleAttachmentIcon",chatBubbleMenu:"BaseChat_chatBubbleMenu"};import{Box as Box8,Divider as Divider4,Loader as Loader3,Stack as Stack18,Text as Text17,TextInput as TextInput19,UnstyledButton as UnstyledButton3}from"@mantine/core";import{useDebouncedCallback as useDebouncedCallback2}from"@mantine/hooks";import{getReferenceString as getReferenceString4}from"@medplum/core";import{useMedplum as useMedplum23}from"@medplum/react-hooks";import{useEffect as useEffect14,useState as useState51}from"react";import{jsx as jsx90,jsxs as jsxs52}from"react/jsx-runtime";function DocumentPicker({subjectRef,onSelect,onUpload}){let medplum=useMedplum23(),[search,setSearch]=useState51(""),[docs,setDocs]=useState51([]),[loading,setLoading]=useState51(!0),subjectRefStr=subjectRef?getReferenceString4(subjectRef):void 0,fetchDocs=useDebouncedCallback2(async query=>{setLoading(!0);try{let params=new URLSearchParams;subjectRefStr&¶ms.set("subject",subjectRefStr),query.trim()&¶ms.set("description:contains",query.trim()),params.set("_sort","-date"),params.set("_count","5");let results=await medplum.searchResources("DocumentReference",params);setDocs([...results])}catch(err){console.error(err)}finally{setLoading(!1)}},300);useEffect14(()=>{fetchDocs(search)},[fetchDocs,search]);let getDocName=doc=>doc.description??doc.content?.[0]?.attachment?.title??"Untitled";return jsxs52(Stack18,{gap:0,w:280,children:[jsx90(Text17,{fw:500,fz:"sm",px:"sm",pt:"sm",pb:"xs",children:"Attachments"}),jsx90(Box8,{px:"sm",pb:"xs",children:jsx90(TextInput19,{placeholder:"Search for a Document...",size:"xs",value:search,onChange:e=>setSearch(e.currentTarget.value)})}),jsx90(Divider4,{}),loading?jsx90(Box8,{py:"sm",style:{display:"flex",justifyContent:"center"},children:jsx90(Loader3,{size:"xs"})}):jsxs52(Stack18,{gap:0,children:[docs.map(doc=>jsxs52(UnstyledButton3,{px:"sm",py:"xs",onClick:()=>onSelect(doc),style:{display:"flex",alignItems:"center",gap:8},children:[jsx90(IconFileText,{size:"1rem",style:{flexShrink:0,color:"var(--mantine-color-blue-6)"}}),jsx90(Text17,{fz:"sm",truncate:!0,children:getDocName(doc)})]},doc.id)),docs.length===0&&jsx90(Text17,{fz:"xs",c:"dimmed",px:"sm",py:"xs",children:"No documents found"})]}),jsx90(Divider4,{}),jsxs52(UnstyledButton3,{px:"sm",py:"xs",onClick:onUpload,style:{display:"flex",alignItems:"center",gap:8},children:[jsx90(IconPaperclip,{size:"1rem",style:{flexShrink:0,color:"var(--mantine-color-gray-6)"}}),jsx90(Text17,{fz:"sm",c:"dimmed",children:"Upload an image, pdf, etc."})]})]})}import{jsx as jsx91,jsxs as jsxs53}from"react/jsx-runtime";function toSafeUrl(url){if(url)try{let{protocol}=new URL(url);return protocol==="https:"||protocol==="http:"||protocol==="blob:"?url:void 0}catch{return}}function showError(message){showNotification5({color:"red",title:"Error",message,autoClose:!1})}function parseSentTime(communication){return new Date(communication.sent??0).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function upsertCommunications(communications,received,setCommunications){let newCommunications=[...communications],foundNew=!1;for(let comm of received){let existingIdx=newCommunications.findIndex(c=>c.id===comm.id);existingIdx!==-1?newCommunications[existingIdx]=comm:(newCommunications.push(comm),foundNew=!0)}foundNew&&newCommunications.sort((a,b)=>!a.sent&&!b.sent?0:a.sent?b.sent?a.sent.localeCompare(b.sent):1:-1),setCommunications(newCommunications)}function BaseChat(props){let{title,communications,setCommunications,query,sendMessage,onMessageReceived,onMessageUpdated,inputDisabled,onError,excludeHeader=!1,uploadEnabled=!1,attachmentSubjectRef,onViewInDocuments,...paperProps}=props,medplum=useMedplum24(),inputRef=useRef10(null),scrollAreaRef=useRef10(null),firstScrollRef=useRef10(!0),initialLoadRef=useRef10(!0),[profile,setProfile]=useState52(medplum.getProfile()),[reconnecting,setReconnecting]=useState52(!1),[loading,setLoading]=useState52(!0),[pendingFile,setPendingFile]=useState52(void 0),[pendingDocRef,setPendingDocRef]=useState52(void 0),[pickerOpen,setPickerOpen]=useState52(!1),fileInputRef=useRef10(null);loading||(initialLoadRef.current=!1);let profileRefStr=useMemo24(()=>profile?getReferenceString5(medplum.getProfile()):"",[profile,medplum]),searchMessages=useCallback11(async()=>{setLoading(!0);let searchParams=new URLSearchParams(query);searchParams.append("_sort","-sent"),searchParams.append("sent:missing","false");let searchResult=await medplum.searchResources("Communication",searchParams,{cache:"no-cache"});upsertCommunications(communicationsRef.current,searchResult,setCommunications),setLoading(!1)},[medplum,setCommunications,query]);useEffect15(()=>{searchMessages().catch(err=>showNotification5({color:"red",message:normalizeErrorString6(err)}))},[searchMessages]),useSubscription(`Communication?${query}`,bundle=>{let communication=bundle.entry?.[1]?.resource;upsertCommunications(communicationsRef.current,[communication],setCommunications),getReferenceString5(communication.sender)!==profileRefStr&&(communicationsRef.current.find(c=>c.id===communication.id)?onMessageUpdated?.(communication):onMessageReceived?.(communication))},{onWebSocketClose:useCallback11(()=>{reconnecting||setReconnecting(!0),showNotification5({color:"red",message:"Live chat disconnected. Attempting to reconnect..."})},[reconnecting]),onWebSocketOpen:useCallback11(()=>{reconnecting&&showNotification5({color:"green",message:"Live chat reconnected."})},[reconnecting]),onSubscriptionConnect:useCallback11(()=>{reconnecting&&(searchMessages().catch(err=>showNotification5({color:"red",message:normalizeErrorString6(err)})),setReconnecting(!1))},[reconnecting,searchMessages]),onError:useCallback11(err=>{onError?onError(err):showError(normalizeErrorString6(err))},[onError])});let sendMessageInternal=useCallback11(formData=>{if(inputDisabled)return;let message=formData.message?.trim()??"";!message&&!pendingFile&&!pendingDocRef||(inputRef.current&&(inputRef.current.value=""),fileInputRef.current&&(fileInputRef.current.value=""),sendMessage(message,pendingFile,pendingDocRef),setPendingFile(void 0),setPendingDocRef(void 0),scrollToBottomRef.current=!0)},[inputDisabled,sendMessage,pendingFile,pendingDocRef]);useEffect15(()=>{let latestProfile=medplum.getProfile();profile?.id!==latestProfile?.id&&(setProfile(latestProfile),setCommunications([]))});let[parentRef,parentRect]=useResizeObserver(),communicationsRef=useRef10(communications);communicationsRef.current=communications;let prevCommunicationsRef=useRef10(communications),scrollToBottomRef=useRef10(!0);useEffect15(()=>{communications!==prevCommunicationsRef.current&&(scrollToBottomRef.current=!0),prevCommunicationsRef.current=communications},[communications]),useEffect15(()=>{scrollToBottomRef.current&&scrollAreaRef.current?.scrollTo&&(scrollAreaRef.current.scrollTo({top:scrollAreaRef.current.scrollHeight,...firstScrollRef.current?{duration:0}:{behavior:"smooth"}}),firstScrollRef.current=!1,scrollToBottomRef.current=!1)});let myLastDeliveredId=useMemo24(()=>{let i=communications.length;for(;i--;){let comm=communications[i];if(comm.sender?.reference===profileRefStr&&comm.received)return comm.id}return""},[communications,profileRefStr]);return profile?jsxs53(Paper2,{className:BaseChat_default.chatPaper,p:0,radius:"md",...paperProps,children:[!excludeHeader&&jsx91(Title8,{order:2,className:BaseChat_default.chatTitle,children:title}),jsx91("div",{className:BaseChat_default.chatBody,ref:parentRef,children:initialLoadRef.current?jsxs53(Stack19,{align:"stretch",mt:"lg",children:[jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(Skeleton,{height:38,circle:!0,ml:"md"}),jsx91(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]}),jsxs53(Group29,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(ChatBubbleSkeleton,{alignment:"right",parentWidth:parentRect.width}),jsx91(Skeleton,{height:38,circle:!0,mr:"md"})]}),jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(Skeleton,{height:38,circle:!0,ml:"md"}),jsx91(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]})]},"skeleton-chat-messages"):jsxs53(ScrollArea2,{viewportRef:scrollAreaRef,className:BaseChat_default.chatScrollArea,h:parentRect.height,children:[jsx91(LoadingOverlay,{visible:loading||reconnecting,style:{width:parentRect.width,height:parentRect.height,position:"absolute",zIndex:1}}),communications.map((c,i)=>{let prevCommunication=i>0?communications[i-1]:void 0,prevCommTime=prevCommunication?parseSentTime(prevCommunication):void 0,currCommTime=parseSentTime(c),showDelivered=!!c.received&&c.id===myLastDeliveredId,payloads=c.payload??[],contentRef=payloads.find(p=>p.contentReference)?.contentReference,contentAttachment=payloads.find(p=>p.contentAttachment)?.contentAttachment,hasAttachment=!!(contentRef||contentAttachment),isSender=c.sender?.reference===profileRefStr,menu=hasAttachment?jsx91(ChatBubbleMenu,{contentRef,contentAttachment,onViewInDocuments}):null;return jsxs53(Stack19,{align:"stretch",children:[(!prevCommTime||currCommTime!==prevCommTime)&&jsx91(Text18,{fz:"xs",ta:"center",children:currCommTime}),isSender?jsxs53(Group29,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91("div",{className:BaseChat_default.chatBubbleMenu,children:menu}),jsx91(ChatBubble,{alignment:"right",communication:c,showDelivered}),jsx91(ResourceAvatar,{radius:"xl",color:"orange",value:c.sender,mb:showDelivered?void 0:"sm"})]}):jsxs53(Group29,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx91(ResourceAvatar,{radius:"xl",value:c.sender,mb:"sm"}),jsx91(ChatBubble,{alignment:"left",communication:c}),jsx91("div",{className:BaseChat_default.chatBubbleMenu,children:menu})]})]},`${c.id}--${c.meta?.versionId??"no-version"}`)})]})}),jsxs53("div",{className:BaseChat_default.chatInputContainer,children:[(pendingFile||pendingDocRef)&&jsxs53(Group29,{className:BaseChat_default.chatPendingFile,gap:4,align:"center",wrap:"nowrap",children:[pendingDocRef?jsx91(IconFileText,{size:"0.75rem"}):jsx91(IconPaperclip,{size:"0.75rem"}),jsx91(Text18,{fz:"xs",c:"dimmed",flex:1,truncate:!0,children:pendingDocRef?pendingDocRef.description??pendingDocRef.content?.[0]?.attachment?.title??"Document":pendingFile?.name}),jsx91(ActionIcon7,{size:"xs",variant:"subtle",color:"red",onClick:()=>{setPendingDocRef(void 0),setPendingFile(void 0),fileInputRef.current&&(fileInputRef.current.value="")},"aria-label":"Remove attachment",children:jsx91(IconX,{size:"0.75rem"})})]}),jsx91("input",{ref:fileInputRef,type:"file",style:{display:"none"},disabled:inputDisabled,onChange:e=>{let file=e.target.files?.[0];file&&(setPendingFile(file),setPendingDocRef(void 0))}}),jsx91(Form,{onSubmit:sendMessageInternal,children:jsx91(TextInput20,{ref:inputRef,name:"message",placeholder:inputDisabled?"Replies are disabled":"Type a message...",radius:"xl",leftSectionWidth:42,rightSectionWidth:42,disabled:inputDisabled,leftSection:!inputDisabled&&uploadEnabled?jsxs53(Popover,{opened:pickerOpen,onChange:setPickerOpen,position:"top-start",withArrow:!0,shadow:"md",withinPortal:!0,children:[jsx91(Popover.Target,{children:jsx91(ActionIcon7,{onClick:()=>setPickerOpen(o=>!o),size:"1.5rem",radius:"xl",color:pendingFile||pendingDocRef?"blue":"gray",variant:pendingFile||pendingDocRef?"filled":"subtle","aria-label":"Attach file",children:jsx91(IconPaperclip,{size:"1rem",stroke:1.5})})}),jsx91(Popover.Dropdown,{p:0,children:jsx91(DocumentPicker,{subjectRef:attachmentSubjectRef,onSelect:doc=>{setPendingDocRef(doc),setPendingFile(void 0),setPickerOpen(!1)},onUpload:()=>{setPickerOpen(!1),fileInputRef.current?.click()}})})]}):void 0,rightSection:inputDisabled?void 0:jsx91(ActionIcon7,{type:"submit",size:"1.5rem",radius:"xl",color:"blue",variant:"filled","aria-label":"Send message",children:jsx91(IconArrowRight,{size:"1rem",stroke:1.5})})})})]})]}):null}function ChatBubble(props){let{communication,alignment,showDelivered}=props,payloads=communication.payload??[],textContent=payloads.find(p=>p.contentString)?.contentString??"",contentRef=payloads.find(p=>p.contentReference)?.contentReference,attachment=payloads.find(p=>p.contentAttachment)?.contentAttachment,sentTime=new Date(communication.sent??-1),seenTime=new Date(communication.received??-1),senderResource=useResource2(communication.sender);return jsxs53("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsxs53(Text18,{fz:"xs",mb:"xs",fw:500,className:alignment==="right"?BaseChat_default.chatBubbleNameRight:void 0,"aria-label":"Sender name",children:[senderResource?getDisplayString4(senderResource):"[Unknown sender]","\xA0\xB7\xA0",jsx91(Text18,{span:!0,c:"dimmed",fz:"xs",children:Number.isNaN(sentTime.getTime())?"":sentTime.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})})]}),jsx91("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsxs53("div",{className:BaseChat_default.chatBubble,children:[textContent&&jsx91("span",{children:textContent}),contentRef&&jsx91(ChatBubbleDocumentReference,{reference:contentRef,hasText:!!textContent}),attachment&&jsx91(ChatBubbleAttachment,{attachment,hasText:!!textContent})]})}),showDelivered&&jsxs53("div",{style:{textAlign:"right"},children:["Delivered ",seenTime.getHours(),":",seenTime.getMinutes().toString().length===1?"0":"",seenTime.getMinutes()]})]})}function ChatBubbleAttachment({attachment,hasText}){return jsx91("div",{className:hasText?BaseChat_default.chatBubbleAttachmentWithText:void 0,children:jsxs53(Group29,{gap:4,wrap:"nowrap",children:[jsx91("span",{className:BaseChat_default.chatBubbleAttachmentIcon,children:jsx91(IconPaperclip,{size:"0.75rem"})}),jsx91(Text18,{fz:"xs",truncate:!0,children:attachment.title??"File attached"})]})})}function ChatBubbleDocumentReference({reference,hasText}){let attachment=useResource2(reference)?.content?.[0]?.attachment;return attachment?jsx91(ChatBubbleAttachment,{attachment,hasText}):null}function ChatBubbleMenu({contentRef,contentAttachment,onViewInDocuments}){let docRef=useResource2(contentRef),attachment=contentRef?docRef?.content?.[0]?.attachment:contentAttachment,cachedUrl=useCachedBinaryUrl3(attachment?.url),handleDownload=()=>{let href=toSafeUrl(cachedUrl??attachment?.url);href&&window.open(href,"_blank","noopener,noreferrer")};return jsxs53(Menu4,{withinPortal:!0,position:"bottom-start",shadow:"md",children:[jsx91(Menu4.Target,{children:jsx91(ActionIcon7,{variant:"outline",color:"gray",radius:"xl",size:"sm","aria-label":"Attachment options",children:jsx91(IconDots,{size:"0.75rem"})})}),jsxs53(Menu4.Dropdown,{children:[contentRef&&onViewInDocuments&&jsx91(Menu4.Item,{leftSection:jsx91(IconFileExport,{size:"0.9rem"}),onClick:()=>onViewInDocuments(contentRef),children:"View in Documents"}),jsx91(Menu4.Item,{leftSection:jsx91(IconDownload,{size:"0.9rem"}),onClick:handleDownload,children:"Download"})]})]})}function ChatBubbleSkeleton(props){let{alignment,parentWidth}=props;return jsxs53("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx91("div",{className:BaseChat_default.chatBubbleName,"aria-label":"Placeholder sender name",children:jsx91("div",{style:{position:"relative"},children:jsx91(Skeleton,{height:14,width:"100px",radius:"l",ml:alignment==="left"?"sm":void 0,style:alignment==="right"?{position:"absolute",right:5,top:-15}:void 0})})}),jsx91("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx91("div",{className:BaseChat_default.chatBubble,children:jsx91(Skeleton,{height:14,width:parentWidth*.5,radius:"l"})})})]})}import{ActionIcon as ActionIcon8}from"@mantine/core";import{useMedplumProfile as useMedplumProfile5}from"@medplum/react-hooks";import{useEffect as useEffect16,useState as useState53}from"react";var ChatModal_default={iconContainer:"ChatModal_iconContainer",icon:"ChatModal_icon",chatModalContainer:"ChatModal_chatModalContainer"};import{Fragment as Fragment29,jsx as jsx92,jsxs as jsxs54}from"react/jsx-runtime";function ChatModal(props){let{open,children}=props,profile=useMedplumProfile5(),[opened,setOpened]=useState53(open??!1);return useEffect16(()=>{setOpened(prevVal=>open??prevVal)},[open]),profile?jsxs54(Fragment29,{children:[opened&&jsx92("div",{className:ChatModal_default.chatModalContainer,children}),opened?jsx92("div",{className:ChatModal_default.iconContainer,children:jsx92(ActionIcon8,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!1),"aria-label":"Close chat",children:jsx92(IconChevronDown,{size:"1.625rem"})})}):jsx92("div",{className:ChatModal_default.iconContainer,children:jsx92(ActionIcon8,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!0),"aria-label":"Open chat",children:jsx92(IconChevronUp,{size:"1.625rem"})})})]}):null}import{createReference as createReference3,formatCodeableConcept as formatCodeableConcept2,getReferenceString as getReferenceString6}from"@medplum/core";import{useMedplum as useMedplum25,useMedplumProfile as useMedplumProfile6,usePrevious}from"@medplum/react-hooks";import{useCallback as useCallback12,useEffect as useEffect17,useMemo as useMemo25,useState as useState54}from"react";import{jsx as jsx93}from"react/jsx-runtime";function ThreadChat(props){let{thread,title,onMessageSent,inputDisabled,excludeHeader,uploadEnabled,onError,onViewInDocuments}=props,medplum=useMedplum25(),profile=useMedplumProfile6(),prevThreadId=usePrevious(thread?.id),[communications,setCommunications]=useState54([]),profileRef=useMemo25(()=>profile?createReference3(profile):void 0,[profile]),threadRef=useMemo25(()=>createReference3(thread),[thread]);useEffect17(()=>{thread?.id!==prevThreadId&&setCommunications([])},[thread?.id,prevThreadId]);let sendMessage=useCallback12((message,file,existingDocRef)=>{let profileRefStr=profileRef?getReferenceString6(profileRef):void 0;if(!profileRefStr)return;(async()=>{let payload=[];if(message&&payload.push({contentString:message}),existingDocRef)payload.push({contentReference:createReference3(existingDocRef)});else if(file){let docRef=await medplum.createDocumentReference({data:file,contentType:file.type||"application/octet-stream",filename:file.name,additionalFields:{...thread.subject?{subject:thread.subject}:{},description:file.name}});payload.push({contentReference:createReference3(docRef)})}let communication=await medplum.createResource({resourceType:"Communication",status:"in-progress",sender:profileRef,recipient:thread.recipient?.filter(ref=>getReferenceString6(ref)!==profileRefStr)??[],sent:new Date().toISOString(),payload,partOf:[threadRef],subject:thread.subject});setCommunications([...communications,communication]),onMessageSent?.(communication)})().catch(console.error)},[medplum,profileRef,thread,threadRef,communications,onMessageSent]),onMessageReceived=useMemo25(()=>thread.recipient?.length===2?message=>{message.received&&message.status==="completed"||medplum.updateResource({...message,received:message.received??new Date().toISOString(),status:"completed"}).catch(console.error)}:void 0,[medplum,thread.recipient?.length]);return profile?jsx93(BaseChat,{title:title??(thread?.topic?formatCodeableConcept2(thread.topic):"[No thread title]"),communications,setCommunications,query:`part-of=Communication/${thread.id}`,sendMessage,onMessageReceived,inputDisabled,excludeHeader,uploadEnabled,onError,attachmentSubjectRef:thread.subject,onViewInDocuments}):null}import{Divider as Divider5,Stack as Stack21}from"@mantine/core";import{Fragment as Fragment30}from"react";import{Group as Group30,Stack as Stack20,Text as Text19}from"@mantine/core";import{formatDateTime as formatDateTime2,formatHumanName as formatHumanName6}from"@medplum/core";import{useResource as useResource3}from"@medplum/react-hooks";var ChatListItem_default={content:"ChatListItem_content",contentContainer:"ChatListItem_contentContainer",selected:"ChatListItem_selected"};import{jsx as jsx94,jsxs as jsxs55}from"react/jsx-runtime";var ChatListItem=props=>{let{topic,lastCommunication,isSelected,getThreadUri}=props,patientResource=useResource3(topic.subject),patientName=formatHumanName6(patientResource?.name?.[0]),lastMsg=lastCommunication?.payload?.[0]?.contentString,trimmedMsg=lastMsg?.length&&lastMsg.length>100?lastMsg.slice(0,100)+"...":lastMsg,senderName=lastCommunication?.sender?.display?`${lastCommunication?.sender?.display}: `:"",content=trimmedMsg?`${senderName} ${trimmedMsg}`:"No messages available",topicName=topic.topic?.text??content;return jsx94(MedplumLink,{to:getThreadUri(topic),underline:"never",children:jsxs55(Group30,{p:"xs",align:"center",wrap:"nowrap",className:clsx_default(ChatListItem_default.contentContainer,{[ChatListItem_default.selected]:isSelected}),children:[jsx94(ResourceAvatar,{value:topic.subject,radius:"xl",size:36}),jsxs55(Stack20,{gap:0,children:[jsx94(Text19,{size:"sm",fw:700,truncate:"end",children:patientName}),jsx94(Text19,{size:"sm",fw:400,lineClamp:2,className:ChatListItem_default.content,children:topicName}),jsx94(Text19,{size:"xs",style:{marginTop:2},children:lastCommunication?formatDateTime2(lastCommunication.sent):""})]})]})})};import{jsx as jsx95,jsxs as jsxs56}from"react/jsx-runtime";var ChatList=props=>{let{threads,selectedCommunication,getThreadUri}=props;return jsx95(Stack21,{gap:0,children:threads.map(thread=>{let topicCommunication=thread[0],lastCommunication=thread[1],_isSelected=selectedCommunication?.id===topicCommunication.id;return jsxs56(Fragment30,{children:[jsx95(ChatListItem,{topic:topicCommunication,lastCommunication,isSelected:_isSelected,getThreadUri}),jsx95(Divider5,{})]},topicCommunication.id)})})};import{Button as Button11,Modal as Modal3,Stack as Stack25,Text as Text22,TextInput as TextInput22}from"@mantine/core";import{showNotification as showNotification6}from"@mantine/notifications";import{createReference as createReference6,HTTP_HL7_ORG as HTTP_HL7_ORG4,normalizeErrorString as normalizeErrorString7}from"@medplum/core";import{useMedplum as useMedplum29,useMedplumProfile as useMedplumProfile7}from"@medplum/react-hooks";import{useMemo as useMemo27,useState as useState57}from"react";import{Group as Group33,Stack as Stack24,Text as Text21,Title as Title10}from"@mantine/core";import{createReference as createReference5,getExtension as getExtension2,getReferenceString as getReferenceString7}from"@medplum/core";import{QUESTIONNAIRE_SIGNATURE_REQUIRED_URL,QUESTIONNAIRE_SIGNATURE_RESPONSE_URL,useMedplum as useMedplum28,useQuestionnaireForm}from"@medplum/react-hooks";import{useCallback as useCallback13,useEffect as useEffect20,useLayoutEffect as useLayoutEffect3,useMemo as useMemo26,useRef as useRef12,useState as useState56}from"react";import{Button as Button9,Paper as Paper3}from"@mantine/core";import{createReference as createReference4,HTTP_HL7_ORG as HTTP_HL7_ORG2}from"@medplum/core";import{useMedplum as useMedplum26}from"@medplum/react-hooks";import{useEffect as useEffect18,useLayoutEffect as useLayoutEffect2,useRef as useRef11}from"react";var Point=class{constructor(x,y,pressure,time){__publicField(this,"x");__publicField(this,"y");__publicField(this,"pressure");__publicField(this,"time");if(isNaN(x)||isNaN(y))throw new Error(`Point is invalid: (${x}, ${y})`);this.x=+x,this.y=+y,this.pressure=pressure||0,this.time=time||Date.now()}distanceTo(start){return Math.sqrt(Math.pow(this.x-start.x,2)+Math.pow(this.y-start.y,2))}equals(other){return this.x===other.x&&this.y===other.y&&this.pressure===other.pressure&&this.time===other.time}velocityFrom(start){return this.time!==start.time?this.distanceTo(start)/(this.time-start.time):0}},Bezier=class _Bezier{constructor(startPoint,control2,control1,endPoint,startWidth,endWidth){this.startPoint=startPoint,this.control2=control2,this.control1=control1,this.endPoint=endPoint,this.startWidth=startWidth,this.endWidth=endWidth}static fromPoints(points,widths){let c2=this.calculateControlPoints(points[0],points[1],points[2]).c2,c3=this.calculateControlPoints(points[1],points[2],points[3]).c1;return new _Bezier(points[1],c2,c3,points[2],widths.start,widths.end)}static calculateControlPoints(s1,s2,s3){let dx1=s1.x-s2.x,dy1=s1.y-s2.y,dx2=s2.x-s3.x,dy2=s2.y-s3.y,m1={x:(s1.x+s2.x)/2,y:(s1.y+s2.y)/2},m2={x:(s2.x+s3.x)/2,y:(s2.y+s3.y)/2},l1=Math.sqrt(dx1*dx1+dy1*dy1),l2=Math.sqrt(dx2*dx2+dy2*dy2),dxm=m1.x-m2.x,dym=m1.y-m2.y,k=l1+l2==0?0:l2/(l1+l2),cm={x:m2.x+dxm*k,y:m2.y+dym*k},tx=s2.x-cm.x,ty=s2.y-cm.y;return{c1:new Point(m1.x+tx,m1.y+ty),c2:new Point(m2.x+tx,m2.y+ty)}}length(){let length=0,px,py;for(let i=0;i<=10;i+=1){let t=i/10,cx=this.point(t,this.startPoint.x,this.control1.x,this.control2.x,this.endPoint.x),cy=this.point(t,this.startPoint.y,this.control1.y,this.control2.y,this.endPoint.y);if(i>0){let xdiff=cx-px,ydiff=cy-py;length+=Math.sqrt(xdiff*xdiff+ydiff*ydiff)}px=cx,py=cy}return length}point(t,start,c1,c2,end){return start*(1-t)*(1-t)*(1-t)+3*c1*(1-t)*(1-t)*t+3*c2*(1-t)*t*t+end*t*t*t}},SignatureEventTarget=class{constructor(){__publicField(this,"_et");try{this._et=new EventTarget}catch{this._et=document}}addEventListener(type,listener,options){this._et.addEventListener(type,listener,options)}dispatchEvent(event){return this._et.dispatchEvent(event)}removeEventListener(type,callback,options){this._et.removeEventListener(type,callback,options)}};function throttle(fn,wait=250){let previous=0,timeout=null,result,storedContext,storedArgs,later=()=>{previous=Date.now(),timeout=null,result=fn.apply(storedContext,storedArgs),timeout||(storedContext=null,storedArgs=[])};return function(...args){let now=Date.now(),remaining=wait-(now-previous);return storedContext=this,storedArgs=args,remaining<=0||remaining>wait?(timeout&&(clearTimeout(timeout),timeout=null),previous=now,result=fn.apply(storedContext,storedArgs),timeout||(storedContext=null,storedArgs=[])):timeout||(timeout=window.setTimeout(later,remaining)),result}}var SignaturePad=class _SignaturePad extends SignatureEventTarget{constructor(canvas,options={}){super();__publicField(this,"dotSize");__publicField(this,"minWidth");__publicField(this,"maxWidth");__publicField(this,"penColor");__publicField(this,"minDistance");__publicField(this,"velocityFilterWeight");__publicField(this,"compositeOperation");__publicField(this,"backgroundColor");__publicField(this,"throttle");__publicField(this,"canvasContextOptions");__publicField(this,"_ctx");__publicField(this,"_drawingStroke",!1);__publicField(this,"_isEmpty",!0);__publicField(this,"_dataUrl");__publicField(this,"_dataUrlOptions");__publicField(this,"_lastPoints",[]);__publicField(this,"_data",[]);__publicField(this,"_lastVelocity",0);__publicField(this,"_lastWidth",0);__publicField(this,"_strokeMoveUpdate");__publicField(this,"_strokePointerId");this.canvas=canvas,this.velocityFilterWeight=options.velocityFilterWeight||.7,this.minWidth=options.minWidth||.5,this.maxWidth=options.maxWidth||2.5,this.throttle=options.throttle??16,this.minDistance=options.minDistance??5,this.dotSize=options.dotSize||0,this.penColor=options.penColor||"black",this.backgroundColor=options.backgroundColor||"rgba(0,0,0,0)",this.compositeOperation=options.compositeOperation||"source-over",this.canvasContextOptions=options.canvasContextOptions??{},this._strokeMoveUpdate=this.throttle?throttle(_SignaturePad.prototype._strokeUpdate,this.throttle):_SignaturePad.prototype._strokeUpdate,this._handleMouseDown=this._handleMouseDown.bind(this),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this._handleTouchStart=this._handleTouchStart.bind(this),this._handleTouchMove=this._handleTouchMove.bind(this),this._handleTouchEnd=this._handleTouchEnd.bind(this),this._handlePointerDown=this._handlePointerDown.bind(this),this._handlePointerMove=this._handlePointerMove.bind(this),this._handlePointerUp=this._handlePointerUp.bind(this),this._handlePointerCancel=this._handlePointerCancel.bind(this),this._handleTouchCancel=this._handleTouchCancel.bind(this),this._ctx=canvas.getContext("2d",this.canvasContextOptions),this.clear(),this.on()}clear(){let{_ctx:ctx,canvas}=this;ctx.fillStyle=this.backgroundColor,ctx.clearRect(0,0,canvas.width,canvas.height),ctx.fillRect(0,0,canvas.width,canvas.height),this._data=[],this._reset(this._getPointGroupOptions()),this._isEmpty=!0,this._dataUrl=void 0,this._dataUrlOptions=void 0,this._strokePointerId=void 0}redraw(){let data2=this._data,dataUrl=this._dataUrl,dataUrlOptions=this._dataUrlOptions;this.clear(),dataUrl&&this.fromDataURL(dataUrl,dataUrlOptions),this.fromData(data2,{clear:!1})}fromDataURL(dataUrl,options={}){return new Promise((resolve,reject)=>{let image=new Image,ratio=options.ratio||window.devicePixelRatio||1,width=options.width||this.canvas.width/ratio,height=options.height||this.canvas.height/ratio,xOffset=options.xOffset||0,yOffset=options.yOffset||0;this._reset(this._getPointGroupOptions()),image.onload=()=>{this._ctx.drawImage(image,xOffset,yOffset,width,height),resolve()},image.onerror=error=>{reject(error)},image.crossOrigin="anonymous",image.src=dataUrl,this._isEmpty=!1,this._dataUrl=dataUrl,this._dataUrlOptions={...options}})}toDataURL(type="image/png",encoderOptions){return type==="image/svg+xml"?(typeof encoderOptions!="object"&&(encoderOptions=void 0),`data:image/svg+xml;base64,${btoa(this.toSVG(encoderOptions))}`):(typeof encoderOptions!="number"&&(encoderOptions=void 0),this.canvas.toDataURL(type,encoderOptions))}on(){this.canvas.style.touchAction="none",this.canvas.style.msTouchAction="none",this.canvas.style.userSelect="none",this.canvas.style.webkitUserSelect="none";let isIOS=/Macintosh/.test(navigator.userAgent)&&"ontouchstart"in document;window.PointerEvent&&!isIOS?this._handlePointerEvents():(this._handleMouseEvents(),"ontouchstart"in window&&this._handleTouchEvents())}off(){this.canvas.style.touchAction="auto",this.canvas.style.msTouchAction="auto",this.canvas.style.userSelect="auto",this.canvas.style.webkitUserSelect="auto",this.canvas.removeEventListener("pointerdown",this._handlePointerDown),this.canvas.removeEventListener("mousedown",this._handleMouseDown),this.canvas.removeEventListener("touchstart",this._handleTouchStart),this._removeMoveUpEventListeners()}_getListenerFunctions(){let canvasWindow=window.document===this.canvas.ownerDocument?window:this.canvas.ownerDocument.defaultView??this.canvas.ownerDocument;return{addEventListener:canvasWindow.addEventListener.bind(canvasWindow),removeEventListener:canvasWindow.removeEventListener.bind(canvasWindow)}}_removeMoveUpEventListeners(){let{removeEventListener}=this._getListenerFunctions();removeEventListener("pointermove",this._handlePointerMove),removeEventListener("pointerup",this._handlePointerUp),removeEventListener("pointercancel",this._handlePointerCancel),removeEventListener("mousemove",this._handleMouseMove),removeEventListener("mouseup",this._handleMouseUp),removeEventListener("touchmove",this._handleTouchMove),removeEventListener("touchend",this._handleTouchEnd),removeEventListener("touchcancel",this._handleTouchCancel)}isEmpty(){return this._isEmpty}fromData(pointGroups,{clear=!0}={}){clear&&this.clear(),this._fromData(pointGroups,this._drawCurve.bind(this),this._drawDot.bind(this)),this._data=this._data.concat(pointGroups)}toData(){return this._data}_isLeftButtonPressed(event,only){return only?event.buttons===1:(event.buttons&1)===1}_pointerEventToSignatureEvent(event){return{event,type:event.type,x:event.clientX,y:event.clientY,pressure:"pressure"in event?event.pressure:0}}_touchEventToSignatureEvent(event){let touch=event.changedTouches[0];return{event,type:event.type,x:touch.clientX,y:touch.clientY,pressure:touch.force}}_handleMouseDown(event){!this._isLeftButtonPressed(event,!0)||this._drawingStroke||this._strokeBegin(this._pointerEventToSignatureEvent(event))}_handleMouseMove(event){if(!this._isLeftButtonPressed(event,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(event),!1);return}this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event))}_handleMouseUp(event){this._isLeftButtonPressed(event)||this._strokeEnd(this._pointerEventToSignatureEvent(event))}_handleTouchStart(event){event.targetTouches.length!==1||this._drawingStroke||(event.cancelable&&event.preventDefault(),this._strokeBegin(this._touchEventToSignatureEvent(event)))}_handleTouchMove(event){if(event.targetTouches.length===1){if(event.cancelable&&event.preventDefault(),!this._drawingStroke){this._strokeEnd(this._touchEventToSignatureEvent(event),!1);return}this._strokeMoveUpdate(this._touchEventToSignatureEvent(event))}}_handleTouchEnd(event){event.targetTouches.length===0&&(event.cancelable&&event.preventDefault(),this._strokeEnd(this._touchEventToSignatureEvent(event)))}_handlePointerCancel(event){this._allowPointerId(event)&&(event.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(event),!1))}_handleTouchCancel(event){event.cancelable&&event.preventDefault(),this._strokeEnd(this._touchEventToSignatureEvent(event),!1)}_getPointerId(event){return event.persistentDeviceId||event.pointerId}_allowPointerId(event,allowUndefined=!1){return typeof this._strokePointerId>"u"?allowUndefined:this._getPointerId(event)===this._strokePointerId}_handlePointerDown(event){this._drawingStroke||!this._isLeftButtonPressed(event)||!this._allowPointerId(event,!0)||(this._strokePointerId=this._getPointerId(event),event.preventDefault(),this._strokeBegin(this._pointerEventToSignatureEvent(event)))}_handlePointerMove(event){if(this._allowPointerId(event)){if(!this._isLeftButtonPressed(event,!0)||!this._drawingStroke){this._strokeEnd(this._pointerEventToSignatureEvent(event),!1);return}event.preventDefault(),this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event))}}_handlePointerUp(event){this._isLeftButtonPressed(event)||!this._allowPointerId(event)||(event.preventDefault(),this._strokeEnd(this._pointerEventToSignatureEvent(event)))}_getPointGroupOptions(group){return{penColor:group&&"penColor"in group?group.penColor:this.penColor,dotSize:group&&"dotSize"in group?group.dotSize:this.dotSize,minWidth:group&&"minWidth"in group?group.minWidth:this.minWidth,maxWidth:group&&"maxWidth"in group?group.maxWidth:this.maxWidth,velocityFilterWeight:group&&"velocityFilterWeight"in group?group.velocityFilterWeight:this.velocityFilterWeight,compositeOperation:group&&"compositeOperation"in group?group.compositeOperation:this.compositeOperation}}_strokeBegin(event){if(!this.dispatchEvent(new CustomEvent("beginStroke",{detail:event,cancelable:!0})))return;let{addEventListener}=this._getListenerFunctions();switch(event.event.type){case"mousedown":addEventListener("mousemove",this._handleMouseMove,{passive:!1}),addEventListener("mouseup",this._handleMouseUp,{passive:!1});break;case"touchstart":addEventListener("touchmove",this._handleTouchMove,{passive:!1}),addEventListener("touchend",this._handleTouchEnd,{passive:!1}),addEventListener("touchcancel",this._handleTouchCancel,{passive:!1});break;case"pointerdown":addEventListener("pointermove",this._handlePointerMove,{passive:!1}),addEventListener("pointerup",this._handlePointerUp,{passive:!1}),addEventListener("pointercancel",this._handlePointerCancel,{passive:!1});break;default:}this._drawingStroke=!0;let pointGroupOptions=this._getPointGroupOptions(),newPointGroup={...pointGroupOptions,points:[]};this._data.push(newPointGroup),this._reset(pointGroupOptions),this._strokeUpdate(event)}_strokeUpdate(event){if(!this._drawingStroke)return;if(this._data.length===0){this._strokeBegin(event);return}this.dispatchEvent(new CustomEvent("beforeUpdateStroke",{detail:event}));let point=this._createPoint(event.x,event.y,event.pressure),lastPointGroup=this._data[this._data.length-1],lastPoints=lastPointGroup.points,lastPoint=lastPoints.length>0&&lastPoints[lastPoints.length-1],isLastPointTooClose=lastPoint?point.distanceTo(lastPoint)<=this.minDistance:!1,pointGroupOptions=this._getPointGroupOptions(lastPointGroup);if(!lastPoint||!(lastPoint&&isLastPointTooClose)){let curve=this._addPoint(point,pointGroupOptions);lastPoint?curve&&this._drawCurve(curve,pointGroupOptions):this._drawDot(point,pointGroupOptions),lastPoints.push({time:point.time,x:point.x,y:point.y,pressure:point.pressure})}this.dispatchEvent(new CustomEvent("afterUpdateStroke",{detail:event}))}_strokeEnd(event,shouldUpdate=!0){this._removeMoveUpEventListeners(),this._drawingStroke&&(shouldUpdate&&this._strokeUpdate(event),this._drawingStroke=!1,this._strokePointerId=void 0,this.dispatchEvent(new CustomEvent("endStroke",{detail:event})))}_handlePointerEvents(){this._drawingStroke=!1,this.canvas.addEventListener("pointerdown",this._handlePointerDown,{passive:!1})}_handleMouseEvents(){this._drawingStroke=!1,this.canvas.addEventListener("mousedown",this._handleMouseDown,{passive:!1})}_handleTouchEvents(){this.canvas.addEventListener("touchstart",this._handleTouchStart,{passive:!1})}_reset(options){this._lastPoints=[],this._lastVelocity=0,this._lastWidth=(options.minWidth+options.maxWidth)/2,this._ctx.fillStyle=options.penColor,this._ctx.globalCompositeOperation=options.compositeOperation}_createPoint(x,y,pressure){let rect=this.canvas.getBoundingClientRect();return new Point(x-rect.left,y-rect.top,pressure,new Date().getTime())}_addPoint(point,options){let{_lastPoints}=this;if(_lastPoints.push(point),_lastPoints.length>2){_lastPoints.length===3&&_lastPoints.unshift(_lastPoints[0]);let widths=this._calculateCurveWidths(_lastPoints[1],_lastPoints[2],options),curve=Bezier.fromPoints(_lastPoints,widths);return _lastPoints.shift(),curve}return null}_calculateCurveWidths(startPoint,endPoint,options){let velocity=options.velocityFilterWeight*endPoint.velocityFrom(startPoint)+(1-options.velocityFilterWeight)*this._lastVelocity,newWidth=this._strokeWidth(velocity,options),widths={end:newWidth,start:this._lastWidth};return this._lastVelocity=velocity,this._lastWidth=newWidth,widths}_strokeWidth(velocity,options){return Math.max(options.maxWidth/(velocity+1),options.minWidth)}_drawCurveSegment(x,y,width){let ctx=this._ctx;ctx.moveTo(x,y),ctx.arc(x,y,width,0,2*Math.PI,!1),this._isEmpty=!1}_drawCurve(curve,options){let ctx=this._ctx,widthDelta=curve.endWidth-curve.startWidth,drawSteps=Math.ceil(curve.length())*2;ctx.beginPath(),ctx.fillStyle=options.penColor;for(let i=0;i<drawSteps;i+=1){let t=i/drawSteps,tt=t*t,ttt=tt*t,u=1-t,uu=u*u,uuu=uu*u,x=uuu*curve.startPoint.x;x+=3*uu*t*curve.control1.x,x+=3*u*tt*curve.control2.x,x+=ttt*curve.endPoint.x;let y=uuu*curve.startPoint.y;y+=3*uu*t*curve.control1.y,y+=3*u*tt*curve.control2.y,y+=ttt*curve.endPoint.y;let width=Math.min(curve.startWidth+ttt*widthDelta,options.maxWidth);this._drawCurveSegment(x,y,width)}ctx.closePath(),ctx.fill()}_drawDot(point,options){let ctx=this._ctx,width=options.dotSize>0?options.dotSize:(options.minWidth+options.maxWidth)/2;ctx.beginPath(),this._drawCurveSegment(point.x,point.y,width),ctx.closePath(),ctx.fillStyle=options.penColor,ctx.fill()}_fromData(pointGroups,drawCurve,drawDot){for(let group of pointGroups){let{points}=group,pointGroupOptions=this._getPointGroupOptions(group);if(points.length>1)for(let j=0;j<points.length;j+=1){let basicPoint=points[j],point=new Point(basicPoint.x,basicPoint.y,basicPoint.pressure,basicPoint.time);j===0&&this._reset(pointGroupOptions);let curve=this._addPoint(point,pointGroupOptions);curve&&drawCurve(curve,pointGroupOptions)}else this._reset(pointGroupOptions),drawDot(points[0],pointGroupOptions)}}toSVG({includeBackgroundColor=!1,includeDataUrl=!1}={}){let pointGroups=this._data,ratio=Math.max(window.devicePixelRatio||1,1),minX=0,minY=0,maxX=this.canvas.width/ratio,maxY=this.canvas.height/ratio,svg=document.createElementNS("http://www.w3.org/2000/svg","svg");if(svg.setAttribute("xmlns","http://www.w3.org/2000/svg"),svg.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink"),svg.setAttribute("viewBox",`${minX} ${minY} ${maxX} ${maxY}`),svg.setAttribute("width",maxX.toString()),svg.setAttribute("height",maxY.toString()),includeBackgroundColor&&this.backgroundColor){let rect=document.createElement("rect");rect.setAttribute("width","100%"),rect.setAttribute("height","100%"),rect.setAttribute("fill",this.backgroundColor),svg.appendChild(rect)}if(includeDataUrl&&this._dataUrl){let ratio2=this._dataUrlOptions?.ratio||window.devicePixelRatio||1,width=this._dataUrlOptions?.width||this.canvas.width/ratio2,height=this._dataUrlOptions?.height||this.canvas.height/ratio2,xOffset=this._dataUrlOptions?.xOffset||0,yOffset=this._dataUrlOptions?.yOffset||0,image=document.createElement("image");image.setAttribute("x",xOffset.toString()),image.setAttribute("y",yOffset.toString()),image.setAttribute("width",width.toString()),image.setAttribute("height",height.toString()),image.setAttribute("preserveAspectRatio","none"),image.setAttribute("href",this._dataUrl),svg.appendChild(image)}return this._fromData(pointGroups,(curve,{penColor})=>{let path=document.createElement("path");if(!isNaN(curve.control1.x)&&!isNaN(curve.control1.y)&&!isNaN(curve.control2.x)&&!isNaN(curve.control2.y)){let attr=`M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(3)} C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;path.setAttribute("d",attr),path.setAttribute("stroke-width",(curve.endWidth*2.25).toFixed(3)),path.setAttribute("stroke",penColor),path.setAttribute("fill","none"),path.setAttribute("stroke-linecap","round"),svg.appendChild(path)}},(point,{penColor,dotSize,minWidth,maxWidth})=>{let circle=document.createElement("circle"),size=dotSize>0?dotSize:(minWidth+maxWidth)/2;circle.setAttribute("r",size.toString()),circle.setAttribute("cx",point.x.toString()),circle.setAttribute("cy",point.y.toString()),circle.setAttribute("fill",penColor),svg.appendChild(circle)}),svg.outerHTML}};import{jsx as jsx96,jsxs as jsxs57}from"react/jsx-runtime";function SignatureInput(props){let medplum=useMedplum26(),{width=500,height=200,defaultValue:defaultValue2,who,onChange,...rest}=props,canvasRef=useRef11(null),signaturePadRef=useRef11(null),onChangeRef=useRef11(onChange);return useLayoutEffect2(()=>{onChangeRef.current=onChange}),useEffect18(()=>{function handleEndStroke(){onChangeRef.current?.({type:[{system:HTTP_HL7_ORG2+"/fhir/signature-type",code:"ProofOfOrigin",display:"Proof of Origin"}],when:new Date().toISOString(),who:who??createReference4(medplum.getProfile()),data:signaturePadRef.current?.toDataURL().split(",")[1]})}if(canvasRef.current){let signaturePad=new SignaturePad(canvasRef.current);defaultValue2?.data&&signaturePad.fromDataURL(defaultValue2.data).catch(console.error),signaturePad.addEventListener("endStroke",handleEndStroke),signaturePadRef.current=signaturePad}return()=>{signaturePadRef.current&&signaturePadRef.current.removeEventListener("beginStroke",handleEndStroke)}},[medplum,defaultValue2,who]),jsxs57(Paper3,{withBorder:!0,p:0,w:width,h:height,pos:"relative",...rest,children:[jsx96("canvas",{ref:canvasRef,width,height,"aria-label":"Signature input area"}),jsx96(Button9,{onClick:()=>{signaturePadRef.current&&signaturePadRef.current.clear(),onChangeRef.current?.(void 0)},"aria-label":"Clear signature",pos:"absolute",top:0,right:0,size:"xs",leftSection:jsx96(IconTrash,{size:16}),variant:"subtle",color:"gray",children:"Clear"})]})}import{Stack as Stack23}from"@mantine/core";import{isQuestionEnabled,QuestionnaireItemType as QuestionnaireItemType3}from"@medplum/react-hooks";import{Title as Title9}from"@mantine/core";import{jsx as jsx97,jsxs as jsxs58}from"react/jsx-runtime";function QuestionnaireFormGroup(props){let newContext=[...props.context,props.responseItem];return jsxs58("div",{children:[props.item.text&&jsx97(Title9,{order:3,mb:"md",children:props.item.text}),jsx97(QuestionnaireFormItemArray,{formState:props.formState,context:newContext,items:props.item.item??[],responseItems:props.responseItem.item??[]})]},props.item.linkId)}import{Checkbox as Checkbox5,Group as Group31,MultiSelect,NativeSelect as NativeSelect10,Radio,Text as Text20,Textarea as Textarea3,TextInput as TextInput21}from"@mantine/core";import{capitalize as capitalize3,deepEquals,formatCoding as formatCoding2,getElementDefinition,getExtension,HTTP_HL7_ORG as HTTP_HL7_ORG3,stringify as stringify2,typedValueToString}from"@medplum/core";import{getItemAnswerOptionValue,getItemInitialValue,getNewMultiSelectValues,getQuestionnaireItemReferenceFilter,getQuestionnaireItemReferenceTargetTypes,QUESTIONNAIRE_ITEM_CONTROL_URL,QuestionnaireItemType,useMedplum as useMedplum27}from"@medplum/react-hooks";import{useEffect as useEffect19,useState as useState55}from"react";import{Fragment as Fragment31,jsx as jsx98,jsxs as jsxs59}from"react/jsx-runtime";var MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS=30,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS=50;function QuestionnaireFormItem(props){let formState=props.formState,item=props.item,response=props.responseItem;function onChangeAnswer(newResponseAnswer){if(formState&&props.context)if(item.repeats&&props.index!==void 0&&item.type!==QuestionnaireItemType.choice&&item.type!==QuestionnaireItemType.openChoice){let updatedAnswers=[...response.answer||[]];newResponseAnswer.length===0?updatedAnswers.splice(props.index,1):updatedAnswers[props.index]=newResponseAnswer[0],formState.onChangeAnswer(props.context,props.item,updatedAnswers)}else formState.onChangeAnswer(props.context,props.item,newResponseAnswer)}let type=item.type;if(!type)return null;let name=item.linkId;if(!name)return null;let inputId=item.repeats&&props.index!==void 0&&item.type!==QuestionnaireItemType.choice&&item.type!==QuestionnaireItemType.openChoice?`${name}-${props.index}`:name,initial;item.initial&&item.initial.length>0?initial=item.initial[0]:item.answerOption&&item.answerOption.length>0&&(initial=item.answerOption.find(option=>option.initialSelected));let defaultValue2=getCurrentAnswer(response,props.index)??getItemInitialValue(initial),validationError=getExtension(response,`${HTTP_HL7_ORG3}/fhir/StructureDefinition/questionnaire-validationError`),formComponent=null;switch(type){case QuestionnaireItemType.display:formComponent=jsx98("p",{children:props.item.text},props.item.linkId);break;case QuestionnaireItemType.boolean:formComponent=jsx98(CheckboxFormSection,{title:props.item.text,htmlFor:inputId,children:jsx98(Checkbox5,{id:inputId,name,required:props.required??item.required,defaultChecked:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueBoolean:e.currentTarget.checked}])})},props.item.linkId);break;case QuestionnaireItemType.decimal:formComponent=jsx98(TextInput21,{type:"number",step:"any",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer(e.currentTarget.value===""?[]:[{valueDecimal:e.currentTarget.valueAsNumber}])});break;case QuestionnaireItemType.integer:formComponent=jsx98(TextInput21,{type:"number",step:1,id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer(e.currentTarget.value===""?[]:[{valueInteger:e.currentTarget.valueAsNumber}])});break;case QuestionnaireItemType.date:formComponent=jsx98(TextInput21,{type:"date",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueDate:e.currentTarget.value}])});break;case QuestionnaireItemType.dateTime:formComponent=jsx98(DateTimeInput,{name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueDateTime:newValue}])});break;case QuestionnaireItemType.time:formComponent=jsx98(TextInput21,{type:"time",id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer([{valueTime:e.currentTarget.value}])});break;case QuestionnaireItemType.string:case QuestionnaireItemType.url:formComponent=jsx98(TextInput21,{id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>{let value=e.currentTarget.value;onChangeAnswer(value===""?[]:[{valueString:value}])}});break;case QuestionnaireItemType.text:formComponent=jsx98(Textarea3,{id:inputId,name,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:e=>{let value=e.currentTarget.value;onChangeAnswer(value===""?[]:[{valueString:value}])}});break;case QuestionnaireItemType.attachment:formComponent=jsx98(Group31,{py:4,children:jsx98(AttachmentInput,{path:"",name:inputId,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueAttachment:newValue}])})});break;case QuestionnaireItemType.reference:formComponent=jsx98(ReferenceInput,{name:inputId,required:props.required??item.required,targetTypes:getQuestionnaireItemReferenceTargetTypes(item),searchCriteria:getQuestionnaireItemReferenceFilter(item,formState?.subject,formState?.encounter),defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueReference:newValue}])});break;case QuestionnaireItemType.quantity:formComponent=jsx98(QuantityInput,{path:"",name:inputId,required:props.required??item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer([{valueQuantity:newValue}]),disableWheel:!0});break;case QuestionnaireItemType.choice:case QuestionnaireItemType.openChoice:{let{widget,multiselect}=resolveChoiceControl(item),sharedProps={name:inputId,item,required:props.required??item.required,initial,response,multiselect,onChangeAnswer};widget==="check-box"?formComponent=jsx98(QuestionnaireCheckboxInput,{...sharedProps}):widget==="drop-down"?formComponent=jsx98(QuestionnaireDropdownInput,{...sharedProps}):formComponent=jsx98(QuestionnaireRadioButtonInput,{...sharedProps})}break;default:return null}return jsxs59(Fragment31,{children:[formComponent,validationError?.valueString&&jsx98(Text20,{c:"red",size:"lg",mt:4,children:validationError.valueString})]})}function QuestionnaireDropdownInput(props){let{name,item,required,initial,onChangeAnswer,response,multiselect}=props;if(!item.answerOption?.length&&!item.answerValueSet)return jsx98(NoAnswerDisplay,{});let initialValue=getItemInitialValue(initial),defaultValue2=getCurrentAnswer(response)??initialValue,currentAnswer=getCurrentMultiSelectAnswer(response),isMultiSelect=item.repeats||multiselect;if(item.answerValueSet)return jsx98(ValueSetAutocomplete,{name,placeholder:"Select items",binding:item.answerValueSet,maxValues:isMultiSelect?void 0:1,required,onChange:values=>{isMultiSelect?values.length===0?onChangeAnswer([{}]):onChangeAnswer(values.map(coding=>({valueCoding:coding}))):onChangeAnswer([{valueCoding:values[0]}])},defaultValue:defaultValue2?.value});if(isMultiSelect){let{propertyName,data:data2}=formatSelectData(item);return jsx98(MultiSelect,{data:data2,placeholder:"Select items",searchable:!0,defaultValue:currentAnswer||[typedValueToString(initialValue)],required,onChange:selected=>{if(selected.length===0)onChangeAnswer([{}]);else{let values=getNewMultiSelectValues(selected,propertyName,item);onChangeAnswer(values)}}})}else{let data2=[""];if(item.answerOption)for(let option of item.answerOption){let optionValue=getItemAnswerOptionValue(option);data2.push(typedValueToString(optionValue))}return jsx98(NativeSelect10,{id:name,name,required,onChange:e=>{let index=e.currentTarget.selectedIndex;if(index===0){onChangeAnswer([{}]);return}let option=item.answerOption[index-1],optionValue=getItemAnswerOptionValue(option),propertyName="value"+capitalize3(optionValue.type);onChangeAnswer([{[propertyName]:optionValue.value}])},defaultValue:formatCoding2(defaultValue2?.value)||defaultValue2?.value,data:data2})}}function getValueSetOptions(valueSetUrl,medplum){return valueSetUrl?medplum.valueSetExpand({url:valueSetUrl,count:MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS+1}).then(valueSet=>valueSet.expansion?.contains??[]):Promise.resolve([])}function useValueSetOptions(valueSetUrl){let medplum=useMedplum27(),[valueSetOptions,setValueSetOptions]=useState55([]),[isLoading,setIsLoading]=useState55(!1);return useEffect19(()=>{async function loadValueSet(){if(valueSetUrl){setIsLoading(!0);try{let options=await getValueSetOptions(valueSetUrl,medplum);setValueSetOptions(options)}catch(err){console.error("Error loading value set:",err)}finally{setIsLoading(!1)}}}loadValueSet().catch(console.error)},[valueSetUrl,medplum]),[valueSetOptions,isLoading]}function getOptionsFromValueSet(valueSetOptions,name){return valueSetOptions.map((option,i)=>{let optionName=`${name}-valueset-${i}`,optionValue={type:"Coding",value:{system:option.system,code:option.code,display:option.display}};return[optionName,optionValue]})}function QuestionnaireRadioButtonInput(props){let{name,item,required,initial,onChangeAnswer,response}=props,valueElementDefinition=getElementDefinition("QuestionnaireItemAnswerOption","value[x]"),initialValue=getItemInitialValue(initial),[valueSetOptions,isLoading]=useValueSetOptions(item.answerValueSet),options=[],defaultValue2;if(item.answerValueSet)options.push(...getOptionsFromValueSet(valueSetOptions,name));else if(item.answerOption){let mappedOptions=item.answerOption.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS).map((option,i)=>{let optionName=`${name}-option-${i}`,optionValue=getItemAnswerOptionValue(option);return optionValue?.value?(initialValue&&stringify2(optionValue)===stringify2(initialValue)&&(defaultValue2=optionName),[optionName,optionValue]):null}).filter(option=>option!==null);options.push(...mappedOptions)}let defaultAnswer=getCurrentAnswer(response),answerLinkId=getCurrentRadioAnswer(options,defaultAnswer);if(isLoading)return jsx98(Text20,{children:"Loading options..."});if(options.length===0)return jsx98(NoAnswerDisplay,{});let limitedOptions=options.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS);return jsxs59(Fragment31,{children:[jsx98(Radio.Group,{name,value:answerLinkId??defaultValue2,required,onChange:newValue=>{let option=options.find(option2=>option2[0]===newValue);if(option){let optionValue=option[1],propertyName="value"+capitalize3(optionValue.type);onChangeAnswer([{[propertyName]:optionValue.value}])}},children:limitedOptions.map(([optionName,optionValue])=>jsx98(Radio,{id:optionName,value:optionName,py:4,required,label:jsx98(ResourcePropertyDisplay,{property:valueElementDefinition,propertyType:optionValue.type,value:optionValue.value})},optionName))}),(item.answerValueSet&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS||item.answerOption&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)&&jsxs59(Text20,{size:"sm",c:"dimmed",mt:"xs",children:["Showing first ",MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS," options"]})]})}function QuestionnaireCheckboxInput(props){let{name,item,onChangeAnswer,response}=props,valueElementDefinition=getElementDefinition("QuestionnaireItemAnswerOption","value[x]"),[valueSetOptions,isLoading]=useValueSetOptions(item.answerValueSet),initialSelectedValues=item.answerValueSet?(response?.answer?.map(a=>a.valueCoding)||[]).filter(c=>c!==void 0):getCurrentMultiSelectAnswer(response),[selectedValues,setSelectedValues]=useState55(initialSelectedValues),options=[];if(item.answerValueSet)options.push(...getOptionsFromValueSet(valueSetOptions,name));else if(item.answerOption){let mappedOptions=item.answerOption.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS).map((option,i)=>{let optionName=`${name}-option-${i}`,optionValue=getItemAnswerOptionValue(option);return optionValue?.value?[optionName,optionValue]:null}).filter(option=>option!==null);options.push(...mappedOptions)}if(isLoading)return jsx98(Text20,{children:"Loading options..."});if(options.length===0)return jsx98(NoAnswerDisplay,{});let limitedOptions=options.slice(0,MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS),handleCheckboxChange=(optionValue,selected)=>{if(item.answerValueSet){let currentCodings=selectedValues,newCodings;selected?newCodings=[...currentCodings,optionValue.value]:newCodings=currentCodings.filter(c=>!deepEquals(c,optionValue.value)),setSelectedValues(newCodings),newCodings.length===0?onChangeAnswer([{}]):onChangeAnswer(newCodings.map(coding=>({valueCoding:coding})))}else{let currentValues=selectedValues,optionValueStr=typedValueToString(optionValue),newValues;if(selected?newValues=[...currentValues,optionValueStr]:newValues=currentValues.filter(v=>v!==optionValueStr),setSelectedValues(newValues),newValues.length===0)onChangeAnswer([{}]);else{let values=getNewMultiSelectValues(newValues,"value"+capitalize3(optionValue.type),item);onChangeAnswer(values)}}};return jsxs59(Group31,{style:{flexDirection:"column",alignItems:"flex-start"},children:[limitedOptions.map(([optionName,optionValue])=>{let optionValueStr=typedValueToString(optionValue),isChecked=item.answerValueSet?selectedValues.some(coding=>deepEquals(coding,optionValue.value)):selectedValues.includes(optionValueStr);return jsx98(Checkbox5,{id:optionName,label:jsx98(ResourcePropertyDisplay,{property:valueElementDefinition,propertyType:optionValue.type,value:optionValue.value}),checked:isChecked,onChange:event=>handleCheckboxChange(optionValue,event.currentTarget.checked)},optionName)}),(item.answerValueSet&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS||item.answerOption&&options.length>MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)&&jsxs59(Text20,{size:"sm",c:"dimmed",children:["Showing first ",MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS," options"]})]})}function NoAnswerDisplay(){return jsx98(TextInput21,{disabled:!0,placeholder:"No Answers Defined"})}function getCurrentAnswer(response,index=0){return getItemAnswerOptionValue(response?.answer?.[index]??{})}function getCurrentMultiSelectAnswer(response){let results=response?.answer;return results?results.map(a=>getItemAnswerOptionValue(a)).map(type=>formatCoding2(type?.value)||type?.value).filter(Boolean):[]}function getCurrentRadioAnswer(options,defaultAnswer){return options.find(option=>deepEquals(option[1].value,defaultAnswer?.value))?.[0]}var choiceTypes=["drop-down","radio-button","check-box"];function resolveChoiceControl(item){let widget="radio-button",multiselect=!1;item.answerValueSet&&(widget="drop-down");for(let ext of item.extension??[]){if(ext.url!==QUESTIONNAIRE_ITEM_CONTROL_URL)continue;let code=ext.valueCodeableConcept?.coding?.[0]?.code;choiceTypes.includes(code)&&(widget=code),code==="multi-select"&&(multiselect=!0)}return widget==="radio-button"&&multiselect&&(widget="check-box"),{widget,multiselect}}function formatSelectData(item){if(item.answerOption?.length===0)return{propertyName:"",data:[]};let option=item.answerOption[0],optionValue=getItemAnswerOptionValue(option),propertyName="value"+capitalize3(optionValue.type),data2=(item.answerOption??[]).map(answerOption=>{let answerOptionValue=getItemAnswerOptionValue(answerOption),answerOptionValueStr=typedValueToString(answerOptionValue);return{value:answerOptionValueStr,label:answerOptionValueStr}});return{propertyName,data:data2}}import{Anchor as Anchor9}from"@mantine/core";import{Fragment as Fragment32,jsx as jsx99,jsxs as jsxs60}from"react/jsx-runtime";function QuestionnaireFormRepeatableGroup(props){return jsxs60(Fragment32,{children:[props.responseItems.map(response=>jsx99(QuestionnaireFormGroup,{formState:props.formState,context:props.context,item:props.item,responseItem:response},`group-${response.id}`)),jsx99(Anchor9,{onClick:()=>props.formState.onAddGroup(props.context,props.item),children:`Add Group: ${props.item.text}`})]})}import{Anchor as Anchor10,Stack as Stack22}from"@mantine/core";import{QuestionnaireItemType as QuestionnaireItemType2}from"@medplum/react-hooks";import{jsx as jsx100,jsxs as jsxs61}from"react/jsx-runtime";function QuestionnaireFormRepeatableItem(props){let{formState,context,item,responseItem}=props,isChoiceType=item.type===QuestionnaireItemType2.choice||item.type===QuestionnaireItemType2.openChoice,showAddButton=!isChoiceType,answers=!isChoiceType&&responseItem.answer&&responseItem.answer.length>0?responseItem.answer:[{}];return jsxs61(FormSection,{title:props.item.text,withAsterisk:props.item.required,children:[jsx100(Stack22,{gap:"xs",children:answers?.map((_,index)=>jsx100(QuestionnaireFormItem,{formState,context,item,responseItem,index},`${item.linkId}-${index}`))}),showAddButton&&jsx100(Anchor10,{onClick:()=>formState.onAddAnswer(context,item),children:"Add Item"})]},props.item.linkId)}import{jsx as jsx101}from"react/jsx-runtime";function QuestionnaireFormItemArray(props){let{formState,context,items,responseItems}=props;return jsx101(Stack23,{children:items.map((item,index)=>{if(!isQuestionEnabled(item,formState.questionnaireResponse))return null;if(item.type===QuestionnaireItemType3.display)return jsx101("p",{children:item.text},`display-${item.id}-${index}`);let filteredResponseItems=responseItems.filter(responseItem=>responseItem.linkId===item.linkId);return item.type===QuestionnaireItemType3.group&&item.repeats?jsx101(QuestionnaireFormRepeatableGroup,{formState,context,item,responseItems:filteredResponseItems},`repeating-group-${item.id}-${index}`):item.type===QuestionnaireItemType3.group?jsx101(QuestionnaireFormGroup,{formState,context,item,responseItem:filteredResponseItems[0]},`group-${item.id}-${index}`):item.type===QuestionnaireItemType3.boolean?jsx101(QuestionnaireFormItem,{formState,context,item,responseItem:filteredResponseItems[0],index:0},`boolean-item-${item.id}-${index}`):item.repeats?jsx101(QuestionnaireFormRepeatableItem,{formState,context,item,responseItem:filteredResponseItems[0]},`repeating-item-${item.id}-${index}`):jsx101(FormSection,{htmlFor:item.linkId,title:item.text,withAsterisk:item.required,children:jsx101(QuestionnaireFormItem,{formState,context,item,responseItem:filteredResponseItems[0],index:0})},`repeating-item-${item.id}-${index}`)})})}import{Button as Button10,Group as Group32,Stepper}from"@mantine/core";import{Fragment as Fragment33,jsx as jsx102,jsxs as jsxs62}from"react/jsx-runtime";function QuestionnaireFormStepper(props){let{formState,submitButtonText,excludeButtons,children}=props,pages=formState.pages,activePage=formState.activePage,showBackButton=activePage>0,showNextButton=activePage<pages.length-1,showSubmitButton=activePage===pages.length-1;return jsxs62(Fragment33,{children:[jsx102(Stepper,{active:activePage,allowNextStepsSelect:!1,p:6,children:pages.map((page,index)=>jsx102(Stepper.Step,{label:page.title,children:index===activePage&&children},page.linkId))}),!excludeButtons&&jsxs62(Group32,{justify:"flex-end",mt:"xl",gap:"xs",children:[showBackButton&&jsx102(Button10,{onClick:formState.onPrevPage,children:"Back"}),showNextButton&&jsx102(Button10,{onClick:e=>{e.currentTarget.closest("form").reportValidity()&&formState.onNextPage()},children:"Next"}),showSubmitButton&&jsx102(SubmitButton,{children:submitButtonText??"Submit"})]})]})}import{Fragment as Fragment34,jsx as jsx103,jsxs as jsxs63}from"react/jsx-runtime";function QuestionnaireForm(props){let medplum=useMedplum28(),[signatureRequiredSubmitted,setSignatureRequiredSubmitted]=useState56(!1),propsRef=useRef12(props),pendingChangeRef=useRef12(void 0);useLayoutEffect3(()=>{propsRef.current=props});let onFormChange=useCallback13(response=>{pendingChangeRef.current=response},[]),formState=useQuestionnaireForm({questionnaire:props.questionnaire,defaultValue:props.questionnaireResponse,subject:props.subject,encounter:props.encounter,source:props.source,disablePagination:props.disablePagination,onChange:onFormChange}),formStateRef=useRef12(formState);useLayoutEffect3(()=>{formStateRef.current=formState}),useEffect20(()=>{let pendingChange=pendingChangeRef.current;pendingChange&&(pendingChangeRef.current=void 0,setSignatureRequiredSubmitted(!1),propsRef.current.onChange?.(pendingChange))});let isSignatureRequired=useMemo26(()=>formState.loading?!1:!!getExtension2(formState.questionnaire,QUESTIONNAIRE_SIGNATURE_REQUIRED_URL),[formState]),hasSignature=useMemo26(()=>formState.loading?!1:!!formState.questionnaireResponse.extension?.find(ext=>ext.url===QUESTIONNAIRE_SIGNATURE_RESPONSE_URL),[formState]),handleSubmit=useCallback13(()=>{let formState2=formStateRef.current;if(formState2.loading)return;let onSubmit=propsRef.current.onSubmit;if(!onSubmit)return;if(isSignatureRequired&&!hasSignature){setSignatureRequiredSubmitted(!0);return}let questionnaire2=formState2.questionnaire,response=formState2.questionnaireResponse,subject=propsRef.current.subject,source=propsRef.current.source;if(!source){let profile=medplum.getProfile();profile&&(source=createReference5(profile))}onSubmit({...response,questionnaire:questionnaire2.url??getReferenceString7(questionnaire2),subject,source,authored:new Date().toISOString(),status:"completed"})},[medplum,isSignatureRequired,hasSignature]);return formState.loading?null:jsxs63(Form,{testid:"questionnaire-form",onSubmit:handleSubmit,children:[formState.questionnaire.title&&jsx103(Title10,{children:formState.questionnaire.title}),formState.pagination?jsx103(QuestionnaireFormStepper,{formState,submitButtonText:props.submitButtonText,excludeButtons:props.excludeButtons,children:jsx103(QuestionnaireFormItemArray,{formState,context:[],items:formState.items,responseItems:formState.responseItems})}):jsxs63(Fragment34,{children:[jsx103(QuestionnaireFormItemArray,{formState,context:[],items:formState.items,responseItems:formState.responseItems}),isSignatureRequired&&jsxs63(Stack24,{mt:"md",gap:0,children:[jsx103(Text21,{size:"sm",fw:500,children:"Signature"}),jsx103(SignatureInput,{onChange:formState.onChangeSignature}),!hasSignature&&signatureRequiredSubmitted&&jsx103(Text21,{c:"red",size:"sm",children:"Signature is required."})]}),!props.excludeButtons&&jsx103(Group33,{justify:"flex-end",mt:"xl",gap:"xs",children:jsx103(SubmitButton,{children:props.submitButtonText??"Submit"})})]})]})}import{jsx as jsx104,jsxs as jsxs64}from"react/jsx-runtime";var NewTopicDialog=props=>{let{subject,opened,onClose,onSubmit,allowPatientSelection=!1}=props,medplum=useMedplum29(),profile=useMedplumProfile7(),profileRef=useMemo27(()=>profile?createReference6(profile):void 0,[profile]),[topic,setTopic]=useState57(""),[practitioners,setPractitioners]=useState57(profile?.resourceType==="Practitioner"?[createReference6(profile)]:[]),[patient,setPatient]=useState57(subject?createReference6(subject):void 0),initialResponse=useMemo27(()=>{if(profile?.resourceType==="Practitioner")return{resourceType:"QuestionnaireResponse",status:"in-progress",item:[{linkId:"q1",answer:[{valueReference:createReference6(profile)}]}]}},[profile]);return jsx104(Modal3,{opened,onClose,title:"New Message",size:"md",children:jsxs64(Stack25,{gap:"xl",children:[jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Patient"}),allowPatientSelection&&jsx104(Text22,{c:"dimmed",children:"Select a patient"}),jsx104(ResourceInput,{resourceType:"Patient",name:"patient",required:!0,defaultValue:patient,disabled:!allowPatientSelection&&!!patient,onChange:value=>{setPatient(value?createReference6(value):void 0)}})]}),jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Practitioner (optional)"}),jsx104(Text22,{c:"dimmed",children:"Select one or more practitioners"}),jsx104(QuestionnaireForm,{questionnaire,questionnaireResponse:initialResponse,excludeButtons:!0,onChange:value=>{let references=value.item?.[0].answer?.map(item=>item.valueReference).filter(ref=>ref!==void 0)??[];setPractitioners(references)}})]}),jsxs64(Stack25,{gap:0,children:[jsx104(Text22,{fw:500,children:"Topic (optional)"}),jsx104(Text22,{c:"dimmed",children:"Enter a topic for the message"}),jsx104(TextInput22,{placeholder:"Enter your topic",value:topic,onChange:e=>setTopic(e.target.value)})]}),jsx104(Button11,{onClick:async()=>{if(!patient){showNotification6({title:"Error",message:"Please select a patient",color:"red"});return}let communication={resourceType:"Communication",status:"in-progress",subject:patient,sender:profileRef,recipient:[patient,...practitioners.map(practitioner=>({reference:practitioner.reference}))],topic:{text:topic}};try{let createdCommunication=await medplum.createResource(communication);onSubmit?.(createdCommunication),onClose()}catch(error){showNotification6({title:"Error",message:normalizeErrorString7(error),color:"red"})}},children:"Next"})]})})},questionnaire={resourceType:"Questionnaire",status:"active",item:[{linkId:"q1",type:"reference",repeats:!0,extension:[{url:`${HTTP_HL7_ORG4}/fhir/StructureDefinition/questionnaire-referenceResource`,valueCodeableConcept:{coding:[{system:`${HTTP_HL7_ORG4}/fhir/fhir-types`,display:"Practitioner",code:"Practitioner"}]}}]}]};import{ActionIcon as ActionIcon9,Checkbox as Checkbox6,CloseButton,Group as Group34,Indicator,Popover as Popover2,Stack as Stack26,Text as Text23,TextInput as TextInput23,Tooltip as Tooltip4}from"@mantine/core";import{useDebouncedCallback as useDebouncedCallback3,useDisclosure}from"@mantine/hooks";import{showNotification as showNotification7}from"@mantine/notifications";import{createReference as createReference7,formatHumanName as formatHumanName7,getReferenceString as getReferenceString8,normalizeErrorString as normalizeErrorString8}from"@medplum/core";import{useMedplum as useMedplum30,useMedplumProfile as useMedplumProfile8,useResource as useResource4}from"@medplum/react-hooks";import{useEffect as useEffect21,useMemo as useMemo28,useState as useState58}from"react";var ParticipantFilter_default={participantItem:"ParticipantFilter_participantItem"};import{jsx as jsx105,jsxs as jsxs65}from"react/jsx-runtime";function ParticipantFilter(props){let{selectedParticipants,onFilterChange}=props,[opened,{open,close}]=useDisclosure(!1),[searchQuery,setSearchQuery]=useState58(""),[searchResults,setSearchResults]=useState58([]),[isSearching,setIsSearching]=useState58(!1),medplum=useMedplum30(),profile=useMedplumProfile8(),currentUserParticipant=useMemo28(()=>{if(profile)return createReference7(profile)},[profile]),additionalParticipants=useMemo28(()=>{let currentUserRef=currentUserParticipant?.reference;return selectedParticipants.filter(p=>p.reference!==currentUserRef)},[selectedParticipants,currentUserParticipant]),debouncedSearch=useDebouncedCallback3(async query=>{if(!query.trim()){setSearchResults([]);return}setIsSearching(!0);try{let bundle=await medplum.search("Patient",{_type:"Patient,Practitioner",name:query,_count:"10"}),currentUserRef=currentUserParticipant?.reference,results=(bundle.entry??[]).map(entry=>entry.resource).filter(resource=>{if(!resource)return!1;let refString=getReferenceString8(resource);return!!refString&&refString!==currentUserRef}).map(resource=>createReference7(resource));setSearchResults(results)}catch(error){showNotification7({title:"Error",message:normalizeErrorString8(error),color:"red"}),setSearchResults([])}finally{setIsSearching(!1)}},300);useEffect21(()=>(debouncedSearch(searchQuery),debouncedSearch.cancel),[searchQuery,debouncedSearch]);let isSelected=participant=>selectedParticipants.some(p=>p.reference===participant.reference),toggleParticipant=participant=>{let newParticipants=isSelected(participant)?selectedParticipants.filter(p=>p.reference!==participant.reference):[...selectedParticipants,participant];onFilterChange(newParticipants)},removeParticipant=participant=>{let newParticipants=selectedParticipants.filter(p=>p.reference!==participant.reference);onFilterChange(newParticipants)},displayParticipants=useMemo28(()=>{let result=[];for(let p of additionalParticipants)result.some(r2=>r2.reference===p.reference)||result.push(p);if(searchQuery.trim()&&searchResults.length>0)for(let p of searchResults)currentUserParticipant?.reference!==p.reference&&(result.some(r2=>r2.reference===p.reference)||result.push(p));return result},[additionalParticipants,searchQuery,searchResults,currentUserParticipant]),hasActiveFilter=selectedParticipants.length>0;return jsxs65(Popover2,{opened,onChange:o=>!o&&close(),position:"bottom-start",width:360,shadow:"md",radius:"md",withinPortal:!0,children:[jsx105(Popover2.Target,{children:jsx105(Tooltip4,{label:"Message Participants",position:"bottom",openDelay:500,disabled:opened,children:jsx105(Indicator,{disabled:!hasActiveFilter,color:"blue",size:8,offset:4,children:jsx105(ActionIcon9,{variant:"transparent",onClick:opened?close:open,radius:"xl",size:32,className:"outline-icon-button","data-opened":opened||void 0,children:jsx105(IconUsers,{size:16})})})})}),jsx105(Popover2.Dropdown,{p:"md",children:jsxs65(Stack26,{gap:"md",children:[jsx105(Text23,{size:"xs",c:"dimmed",fw:500,children:"Message Participants"}),jsx105(TextInput23,{placeholder:"Search for a Patient or Practitioner...",value:searchQuery,autoFocus:!0,onChange:e=>setSearchQuery(e.target.value),rightSection:searchQuery?jsx105(CloseButton,{size:"sm",onClick:()=>setSearchQuery("")}):null}),jsxs65(Stack26,{gap:"xs",mah:250,style:{overflowY:"auto"},children:[currentUserParticipant&&jsx105(ParticipantItem,{participant:currentUserParticipant,isSelected:isSelected(currentUserParticipant),isCurrentUser:!0,onToggle:()=>toggleParticipant(currentUserParticipant)}),displayParticipants.map(participant=>jsx105(ParticipantItem,{participant,isSelected:isSelected(participant),isCurrentUser:!1,onToggle:()=>toggleParticipant(participant),onRemove:isSelected(participant)?()=>removeParticipant(participant):void 0},participant.reference)),isSearching&&jsx105(Text23,{size:"sm",c:"dimmed",ta:"center",children:"Searching..."}),searchQuery.trim()&&!isSearching&&searchResults.length===0&&jsx105(Text23,{size:"sm",c:"dimmed",ta:"center",children:"No results found"})]})]})})]})}function ParticipantItem(props){let{participant,isSelected,isCurrentUser,onToggle,onRemove}=props,patientResource=useResource4(participant);return patientResource?jsxs65(Group34,{justify:"space-between",wrap:"nowrap",className:ParticipantFilter_default.participantItem,children:[jsxs65(Group34,{gap:"sm",wrap:"nowrap",style:{flex:1,minWidth:0},children:[jsx105(Checkbox6,{checked:isSelected,onChange:onToggle}),jsx105(ResourceAvatar,{value:participant,radius:"xl",size:32}),jsxs65(Text23,{size:"sm",truncate:!0,style:{flex:1},children:[formatHumanName7(patientResource?.name?.[0]??{}),isCurrentUser&&jsxs65(Text23,{component:"span",c:"dimmed",size:"sm",children:[" ","(you)"]})]})]}),onRemove&&jsx105(CloseButton,{size:"sm",onClick:onRemove})]}):null}import{ActionIcon as ActionIcon12,Box as Box19,Button as Button12,Center as Center3,Divider as Divider7,Flex as Flex19,Group as Group52,Menu as Menu5,Pagination,Paper as Paper4,ScrollArea as ScrollArea3,Skeleton as Skeleton2,Stack as Stack37,Tabs,Text as Text38,ThemeIcon,Tooltip as Tooltip7}from"@mantine/core";import{useDisclosure as useDisclosure10}from"@mantine/hooks";import{showNotification as showNotification8}from"@mantine/notifications";import{getReferenceString as getReferenceString10,normalizeErrorString as normalizeErrorString10,Operator,parseSearchRequest}from"@medplum/core";import{useMedplumNavigate as useMedplumNavigate5,useThreadInbox}from"@medplum/react-hooks";import{useCallback as useCallback24,useEffect as useEffect25,useMemo as useMemo33}from"react";import{Divider as Divider6,Flex as Flex18,Group as Group51,Stack as Stack36,Text as Text37,Tooltip as Tooltip6}from"@mantine/core";import{formatHumanName as formatHumanName8,resolveId}from"@medplum/core";import{useMedplum as useMedplum39,usePatientSummaryData,useResource as useResource9}from"@medplum/react-hooks";import{useEffect as useEffect24,useMemo as useMemo32,useState as useState73}from"react";var PatientSummary_default={panel:"PatientSummary_panel",patientSummaryBadge:"PatientSummary_patientSummaryBadge",patientSummaryAddButton:"PatientSummary_patientSummaryAddButton",patientSummaryHeader:"PatientSummary_patientSummaryHeader",patientSummaryCollapseIcon:"PatientSummary_patientSummaryCollapseIcon",collapsed:"PatientSummary_collapsed"};import{Stack as Stack35}from"@mantine/core";import{calculateAgeString,formatAddress as formatAddress3}from"@medplum/core";import{Box as Box11,Flex as Flex11,Group as Group37,Modal as Modal4,Text as Text25}from"@mantine/core";import{useDisclosure as useDisclosure2}from"@mantine/hooks";import{getDisplayString as getDisplayString5}from"@medplum/core";import{useMedplum as useMedplum31}from"@medplum/react-hooks";import{useCallback as useCallback15,useMemo as useMemo29,useState as useState61}from"react";import{Badge}from"@mantine/core";import{jsx as jsx106}from"react/jsx-runtime";var statusToColor={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red",finished:"green",planned:"gray"};function StatusBadge(props){let{status,...badgeProps}=props;return jsx106(Badge,{color:props.color||statusToColor[status],...badgeProps,children:status.replaceAll("-"," ")})}import{Group as Group35,Stack as Stack27,TextInput as TextInput24}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG5,addProfileToResource,createReference as createReference8}from"@medplum/core";import{useCallback as useCallback14,useState as useState59}from"react";import{jsx as jsx107,jsxs as jsxs66}from"react/jsx-runtime";var HTTP="http://",PATIENT_ALLERGY_PROFILE=HTTP_HL7_ORG5+"/fhir/us/core/StructureDefinition/us-core-allergyintolerance";function AllergyDialog(props){let{patient,encounter,allergy,onSubmit}=props,[code,setCode]=useState59(allergy?.code),[clinicalStatus,setClinicalStatus]=useState59(allergy?.clinicalStatus),handleSubmit=useCallback14(formData=>{onSubmit(addProfileToResource({...allergy,resourceType:"AllergyIntolerance",patient:createReference8(patient),encounter:encounter?createReference8(encounter):void 0,code,clinicalStatus,onsetDateTime:formData.onsetDateTime?formData.onsetDateTime:void 0,reaction:formData.reaction?[{manifestation:[{text:formData.reaction}]}]:void 0},PATIENT_ALLERGY_PROFILE))},[patient,encounter,allergy,code,clinicalStatus,onSubmit]);return jsx107(Form,{onSubmit:handleSubmit,children:jsxs66(Stack27,{children:[jsx107(CodeableConceptInput,{name:"allergy",label:"Code",path:"AllergyIntolerance.code","data-autofocus":!0,binding:HTTP+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1186.8",maxValues:1,defaultValue:allergy?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx107(TextInput24,{name:"reaction",label:"Reaction",defaultValue:allergy?.reaction?.[0]?.manifestation?.[0]?.text}),jsx107(CodeableConceptInput,{name:"clinicalStatus",label:"Clinical Status",path:"AllergyIntolerance.clinicalStatus",binding:HTTP_HL7_ORG5+"/fhir/ValueSet/allergyintolerance-clinical",maxValues:1,defaultValue:allergy?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx107(DateTimeInput,{name:"onsetDateTime",label:"Onset",defaultValue:allergy?.recordedDate}),jsx107(Group35,{justify:"flex-end",gap:4,mt:"md",children:jsx107(SubmitButton,{children:"Save"})})]})},allergy?.id)}import{ActionIcon as ActionIcon10,Box as Box9,Collapse,Group as Group36,Text as Text24}from"@mantine/core";import{useState as useState60}from"react";var CollapsibleSection_default={root:"CollapsibleSection_root",header:"CollapsibleSection_header",chevron:"CollapsibleSection_chevron",title:"CollapsibleSection_title",addButton:"CollapsibleSection_addButton"};import{jsx as jsx108,jsxs as jsxs67}from"react/jsx-runtime";function CollapsibleSection(props){let{title,children,onAdd}=props,[collapsed,setCollapsed]=useState60(!1);return jsxs67(Box9,{className:CollapsibleSection_default.root,children:[jsxs67(Group36,{justify:"space-between",className:CollapsibleSection_default.header,children:[jsxs67(Group36,{gap:8,children:[jsx108(ActionIcon10,{variant:"subtle",onClick:()=>setCollapsed(c=>!c),"aria-label":collapsed?`Show ${title.toLowerCase()}`:`Hide ${title.toLowerCase()}`,className:CollapsibleSection_default.chevron,"data-collapsed":collapsed||void 0,size:"md",children:jsx108(IconChevronDown,{size:20})}),jsx108(Text24,{fz:"md",fw:800,onClick:()=>setCollapsed(c=>!c),className:CollapsibleSection_default.title,children:title})]}),onAdd&&jsx108(ActionIcon10,{role:"button","aria-label":"Add item",className:CollapsibleSection_default.addButton,variant:"subtle",onClick:e=>{killEvent(e),onAdd()},size:"md",children:jsx108(IconPlus,{size:18})})]}),jsx108(Collapse,{in:!collapsed,children:jsx108(Box9,{ml:"var(--mantine-spacing-xl)",mt:"xs",mb:"md",pl:4,children})})]})}import{ActionIcon as ActionIcon11,Box as Box10}from"@mantine/core";var SummaryItem_default={gradient:"SummaryItem_gradient",container:"SummaryItem_container",chevron:"SummaryItem_chevron",item:"SummaryItem_item",itemText:"SummaryItem_itemText"};import{jsx as jsx109,jsxs as jsxs68}from"react/jsx-runtime";function SummaryItem(props){let{children,onClick}=props;return jsxs68(Box10,{className:SummaryItem_default.item,onClick,children:[children,jsx109("div",{className:SummaryItem_default.gradient}),jsx109("div",{className:SummaryItem_default.container,children:jsx109(ActionIcon11,{className:SummaryItem_default.chevron,size:"md",variant:"transparent",tabIndex:-1,children:jsx109(IconChevronRight,{size:16,stroke:2.5})})})]})}import{Fragment as Fragment35,jsx as jsx110,jsxs as jsxs69}from"react/jsx-runtime";function Allergies(props){let medplum=useMedplum31(),{patient,encounter}=props,[allergies,setAllergies]=useState61(props.allergies),[opened,{open,close}]=useDisclosure2(!1),[editAllergy,setEditAllergy]=useState61(),sortedAllergies=useMemo29(()=>[...allergies].sort((a,b)=>{let aStatus=a.clinicalStatus?.coding?.[0]?.code,bStatus=b.clinicalStatus?.coding?.[0]?.code;return aStatus==="active"&&bStatus!=="active"?-1:aStatus!=="active"&&bStatus==="active"?1:getDisplayString5(a).localeCompare(getDisplayString5(b))}),[allergies]),handleSubmit=useCallback15(async allergy=>{if(allergy.id){let updatedAllergy=await medplum.updateResource(allergy);setAllergies(allergies.map(a=>a.id===updatedAllergy.id?updatedAllergy:a))}else{let newAllergy=await medplum.createResource(allergy);setAllergies([...allergies,newAllergy])}setEditAllergy(void 0),close()},[medplum,allergies,close]);return jsxs69(Fragment35,{children:[jsx110(CollapsibleSection,{title:"Allergies",onAdd:()=>{setEditAllergy(void 0),open()},children:sortedAllergies.length>0?jsx110(Box11,{children:jsx110(Flex11,{direction:"column",gap:8,children:sortedAllergies.map(allergy=>{let status=allergy.clinicalStatus?.coding?.[0]?.code||"unknown";return jsx110(SummaryItem,{onClick:()=>{setEditAllergy(allergy),open()},children:jsxs69(Box11,{children:[jsx110(Text25,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString5(allergy)}),jsx110(Group37,{mt:2,gap:4,children:status&&jsx110(StatusBadge,{color:getClinicalStatusColor(status),variant:"light",status})})]})},allergy.id)})})}):jsx110(Text25,{children:"(none)"})}),jsx110(Modal4,{opened,onClose:close,title:editAllergy?"Edit Allergy":"Add Allergy",children:jsx110(AllergyDialog,{patient,encounter,allergy:editAllergy,onSubmit:handleSubmit})})]})}function getClinicalStatusColor(status){if(!status)return"gray";switch(status){case"active":return"red";case"inactive":return"orange";case"resolved":return"blue";default:return"gray"}}import{Box as Box12,Flex as Flex12,Group as Group38,Text as Text26}from"@mantine/core";import{formatDate}from"@medplum/core";import{useResource as useResource5}from"@medplum/react-hooks";import{jsx as jsx111,jsxs as jsxs70}from"react/jsx-runtime";function CoverageItem(props){let{coverage,organization,onClickResource}=props,coverageResource=useResource5(coverage),organizationResource=useResource5(organization),payorName="Unknown Payor";organizationResource&&"name"in organizationResource&&typeof organizationResource.name=="string"&&(payorName=organizationResource.name);let detailsText=`ID: ${coverageResource?.subscriberId??"N/A"}${formatClassInfo(coverageResource)?` \xB7 ${formatClassInfo(coverageResource)}`:""}`;return jsx111(SummaryItem,{onClick:()=>{coverageResource&&onClickResource?.(coverageResource)},children:jsxs70(Box12,{children:[jsx111(Text26,{fw:500,className:PatientSummary_default.itemText,children:payorName}),jsx111(Text26,{fw:500,className:PatientSummary_default.itemText,children:detailsText}),jsxs70(Group38,{mt:2,gap:4,children:[jsx111(StatusBadge,{color:"green",variant:"light",status:"Active"}),jsxs70(Text26,{size:"xs",fw:500,color:"gray.6",children:["Ends ",formatDate(coverageResource?.period?.end)]})]})]})})}function Insurance(props){let{coverages,onClickResource}=props,activeCoverages=coverages.filter(coverage=>coverage.status==="active");return jsx111(CollapsibleSection,{title:"Insurance",children:activeCoverages.length>0?jsx111(Flex12,{direction:"column",gap:8,children:activeCoverages.map(coverage=>jsx111(CoverageItem,{coverage,organization:coverage.payor?.[0],onClickResource},coverage.id))}):jsx111(Text26,{children:"(none)"})})}function capitalizeWords(str){return str.split(" ").map(word=>word.charAt(0).toUpperCase()+word.slice(1).toLowerCase()).join(" ")}function formatClassInfo(coverage){return coverage?coverage.class?.filter(cls=>cls.type?.coding?.[0]?.code!=="plan").map(cls=>{let type=cls.type?.coding?.[0]?.code??"";return`${capitalizeWords(type)}: ${cls.value}`}).join(" \xB7 ")??"":""}import{Box as Box13,Flex as Flex13,Group as Group41,Modal as Modal5,Text as Text29}from"@mantine/core";import{useDisclosure as useDisclosure3}from"@mantine/hooks";import{formatDate as formatDate2,getDisplayString as getDisplayString7}from"@medplum/core";import{useState as useState64}from"react";import{Group as Group40,List,Stack as Stack29,Text as Text28,Title as Title11}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept3,formatDateTime as formatDateTime3,formatObservationValue,isReference as isReference3}from"@medplum/core";import{useMedplum as useMedplum32,useResource as useResource7}from"@medplum/react-hooks";import{useEffect as useEffect22,useState as useState63}from"react";import{Blockquote,Stack as Stack28}from"@mantine/core";var NoteDisplay_default={noteBody:"NoteDisplay_noteBody",noteCite:"NoteDisplay_noteCite",noteRoot:"NoteDisplay_noteRoot"};import{jsx as jsx112}from"react/jsx-runtime";function NoteDisplay({value}){return value?jsx112(Stack28,{justify:"flex-start",gap:"xs",children:value.map(note=>note.text&&jsx112(Blockquote,{classNames:{cite:NoteDisplay_default.noteCite,root:NoteDisplay_default.noteRoot},cite:note.authorReference?.display||note.authorString,icon:null,children:note.text},`note-${note.text}`))}):null}import{Group as Group39}from"@mantine/core";import{Text as Text27}from"@mantine/core";import{getDisplayString as getDisplayString6,isOk,normalizeErrorString as normalizeErrorString9}from"@medplum/core";import{useResource as useResource6}from"@medplum/react-hooks";import{useState as useState62}from"react";import{jsx as jsx113}from"react/jsx-runtime";function ResourceName(props){let{value,link,...rest}=props,[outcome,setOutcome]=useState62(),resource=useResource6(value,setOutcome),text;if(outcome&&!isOk(outcome))text=`[${normalizeErrorString9(outcome)}]`;else if(resource)text=getDisplayString6(resource);else return null;return link?jsx113(MedplumLink,{to:value,...rest,children:text}):jsx113(Text27,{component:"span",...rest,children:text})}import{jsx as jsx114,jsxs as jsxs71}from"react/jsx-runtime";function ResourceBadge(props){return jsxs71(Group39,{gap:"xs",children:[jsx114(ResourceAvatar,{size:24,radius:12,value:props.value,link:props.link}),jsx114(ResourceName,{value:props.value,link:props.link})]})}var DiagnosticReportDisplay_default={table:"DiagnosticReportDisplay_table",criticalRow:"DiagnosticReportDisplay_criticalRow",noteBody:"DiagnosticReportDisplay_noteBody",noteCite:"DiagnosticReportDisplay_noteCite",noteRoot:"DiagnosticReportDisplay_noteRoot"};import{Fragment as Fragment36,jsx as jsx115,jsxs as jsxs72}from"react/jsx-runtime";DiagnosticReportDisplay.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1,hideSubject:!1};function DiagnosticReportDisplay(props){let medplum=useMedplum32(),diagnosticReport=useResource7(props.value),[specimens,setSpecimens]=useState63();if(useEffect22(()=>{diagnosticReport?.specimen&&Promise.allSettled(diagnosticReport.specimen.map(ref=>medplum.readReference(ref))).then(outcomes=>outcomes.filter(outcome=>outcome.status==="fulfilled").map(outcome=>outcome.value)).then(setSpecimens).catch(console.error)},[medplum,diagnosticReport]),!diagnosticReport)return null;let specimenNotes=specimens?.flatMap(spec=>spec.note||[])||[];if(diagnosticReport.presentedForm&&diagnosticReport.presentedForm.length>0){let pf=diagnosticReport.presentedForm[0];pf.contentType?.startsWith("text/plain")&&pf.data&&specimenNotes.push({text:window.atob(pf.data)})}return jsxs72(Stack29,{children:[jsx115(Title11,{children:"Diagnostic Report"}),jsx115(DiagnosticReportHeader,{value:diagnosticReport,hideSubject:props.hideSubject}),specimens&&!props.hideSpecimenInfo&&SpecimenInfo(specimens),diagnosticReport.result&&jsx115(ObservationTable,{hideObservationNotes:props.hideObservationNotes,value:diagnosticReport.result}),specimenNotes.length>0&&jsx115(NoteDisplay,{value:specimenNotes})]})}function DiagnosticReportHeader({value,hideSubject=!1}){return jsxs72(Group40,{mt:"md",gap:30,children:[value.subject&&!hideSubject&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),jsx115(ResourceBadge,{value:value.subject,link:!0})]}),value.resultsInterpreter?.map(interpreter=>jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),jsx115(ResourceBadge,{value:interpreter,link:!0})]},interpreter.reference)),value.performer?.map(performer=>jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),jsx115(ResourceBadge,{value:performer,link:!0})]},performer.reference)),value.issued&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),jsx115(Text28,{children:formatDateTime3(value.issued)})]}),value.status&&jsxs72("div",{children:[jsx115(Text28,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),jsx115(StatusBadge,{status:value.status})]})]})}function SpecimenInfo(specimens){return jsxs72(Stack29,{gap:"xs",children:[jsx115(Title11,{order:2,size:"h6",children:"Specimens"}),jsx115(List,{type:"ordered",children:specimens?.map(specimen=>jsx115(List.Item,{ml:"sm",children:jsxs72(Group40,{gap:20,children:[jsxs72(Group40,{gap:5,children:[jsx115(Text28,{fw:500,children:"Collected:"})," ",formatDateTime3(specimen.collection?.collectedDateTime)]}),jsxs72(Group40,{gap:5,children:[jsx115(Text28,{fw:500,children:"Received:"})," ",formatDateTime3(specimen.receivedTime)]})]})},`specimen-${specimen.id}`))})]})}function ObservationTable(props){return jsxs72("table",{className:DiagnosticReportDisplay_default.table,children:[jsx115("thead",{children:jsxs72("tr",{children:[jsx115("th",{children:"Test"}),jsx115("th",{children:"Value"}),jsx115("th",{children:"Reference Range"}),jsx115("th",{children:"Interpretation"}),jsx115("th",{children:"Category"}),jsx115("th",{children:"Performer"}),jsx115("th",{children:"Status"})]})}),jsx115("tbody",{children:jsx115(ObservationRowGroup,{value:props.value,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes})})]})}function ObservationRowGroup(props){return jsx115(Fragment36,{children:props.value?.map(observation=>jsx115(ObservationRow,{value:observation,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes},`obs-${isReference3(observation)?observation.reference:observation.id}`))})}function ObservationRow(props){let observation=useResource7(props.value);if(!observation||props.ancestorIds?.includes(observation.id))return null;let displayNotes=!props.hideObservationNotes&&observation.note,critical=isCritical(observation);return jsxs72(Fragment36,{children:[jsxs72("tr",{className:clsx_default({[DiagnosticReportDisplay_default.criticalRow]:critical}),children:[jsx115("td",{rowSpan:displayNotes?2:1,children:jsx115(MedplumLink,{to:observation,children:jsx115(CodeableConceptDisplay,{value:observation.code})})}),jsx115("td",{children:jsx115(ObservationValueDisplay,{value:observation})}),jsx115("td",{children:jsx115(ReferenceRangeDisplay,{value:observation.referenceRange})}),jsx115("td",{children:observation.interpretation&&observation.interpretation.length>0&&jsx115(CodeableConceptDisplay,{value:observation.interpretation[0]})}),jsx115("td",{children:observation.category&&observation.category.length>0&&jsx115(Fragment36,{children:observation.category.map(concept=>jsx115("div",{children:jsx115(CodeableConceptDisplay,{value:concept})},`category-${formatCodeableConcept3(concept)}`))})}),jsx115("td",{children:observation.performer?.map(performer=>jsx115(ReferenceDisplay,{value:performer},performer.reference))}),jsx115("td",{children:observation.status&&jsx115(StatusBadge,{status:observation.status})})]}),observation.hasMember&&jsx115(ObservationRowGroup,{value:observation.hasMember,ancestorIds:props.ancestorIds?[...props.ancestorIds,observation.id]:[observation.id],hideObservationNotes:props.hideObservationNotes}),displayNotes&&jsx115("tr",{children:jsx115("td",{colSpan:6,children:jsx115(NoteDisplay,{value:observation.note})})})]})}function ObservationValueDisplay(props){let obs=props.value;return jsx115(Fragment36,{children:formatObservationValue(obs)})}function ReferenceRangeDisplay(props){let range=props.value&&props.value.length>0&&props.value[0];return range?range.text?jsx115(Fragment36,{children:range.text}):jsx115(RangeDisplay,{value:range}):null}function isCritical(observation){let code=observation.interpretation?.[0]?.coding?.[0]?.code;return code==="AA"||code==="LL"||code==="HH"||code==="A"}import{Fragment as Fragment37,jsx as jsx116,jsxs as jsxs73}from"react/jsx-runtime";function Labs(props){let{serviceRequests,diagnosticReports,onClickResource,onRequestLabs}=props,[selectedReport,setSelectedReport]=useState64(),[reportDialogOpened,{open:openReportDialog,close:closeReportDialog}]=useDisclosure3(!1),diagnosticReportsRequests=new Set,filteredDiagnosticReports=diagnosticReports.filter(report=>{let flag=isLaboratoryReport(report);return flag&&report.basedOn&&report.basedOn.forEach(basedOn=>{if(basedOn.reference?.startsWith("ServiceRequest/")){let[,id]=basedOn.reference.split("/");diagnosticReportsRequests.add(id)}}),flag}),completedRequisitionNumbers=new Set,filteredServiceRequests=serviceRequests.filter(request=>{if(request.id&&diagnosticReportsRequests.has(request.id)||request.basedOn&&request.basedOn.find(basedOn2=>{if(basedOn2.reference?.startsWith("ServiceRequest/")){let[,id]=basedOn2.reference.split("/");return diagnosticReportsRequests.has(id)}return!1}))return!1;let shouldFilter=shouldFilterRequest(request,completedRequisitionNumbers);return!shouldFilter&&request.requisition?.value&&completedRequisitionNumbers.add(request.requisition?.value),!shouldFilter}),handleDiagnosticReportClick=report=>{setSelectedReport(report),openReportDialog()};return jsxs73(Fragment37,{children:[jsx116(CollapsibleSection,{title:"Labs",onAdd:()=>onRequestLabs?.(),children:jsxs73(Flex13,{direction:"column",gap:8,children:[filteredServiceRequests.map(serviceRequest=>jsx116(SummaryItem,{onClick:()=>onClickResource?.(serviceRequest),children:jsxs73(Box13,{children:[jsx116(Text29,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString7(serviceRequest)}),jsxs73(Group41,{mt:2,gap:4,children:[serviceRequest.status&&jsx116(StatusBadge,{color:getStatusColor(serviceRequest.status),variant:"light",status:serviceRequest.status}),jsx116(Text29,{size:"xs",fw:500,c:"dimmed",children:formatDate2(serviceRequest.authoredOn)})]})]})},serviceRequest.id)),filteredDiagnosticReports.map(report=>jsx116(SummaryItem,{onClick:()=>handleDiagnosticReportClick(report),children:jsxs73(Box13,{children:[jsx116(Text29,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString7(report)}),jsxs73(Group41,{mt:2,gap:4,children:[report.status&&jsx116(StatusBadge,{color:getStatusColor(report.status),variant:"light",status:report.status}),jsx116(Text29,{size:"xs",fw:500,c:"dimmed",children:formatDate2(report.issued)})]})]})},report.id)),filteredServiceRequests.length===0&&filteredDiagnosticReports.length===0&&jsx116(Text29,{children:"(none)"})]})}),jsx116(Modal5,{opened:reportDialogOpened,onClose:closeReportDialog,size:"80%",children:selectedReport&&jsx116(DiagnosticReportDisplay,{value:selectedReport,hideSubject:!0})})]})}var getStatusColor=status=>{switch(status){case"active":return"indigo";case"final":return"teal";case"cancelled":return"red";default:return"gray"}};function hasLaboratoryCategory(category){if(!category.coding||!Array.isArray(category.coding))return!1;for(let coding of category.coding)if(coding.code==="LAB")return!0;return!1}function isLaboratoryReport(report){if(!report.category||!Array.isArray(report.category))return!1;for(let category of report.category)if(hasLaboratoryCategory(category))return!0;return!1}function shouldFilterRequest(request,completedRequisitionNumbers){if(["completed","draft","entered-in-error"].includes(request.status))return!0;let requisitionNumber=request.requisition?.value;return!!(requisitionNumber&&completedRequisitionNumbers.has(requisitionNumber))}import{Box as Box14,Flex as Flex14,Group as Group43,Modal as Modal6,Text as Text30}from"@mantine/core";import{useDisclosure as useDisclosure4}from"@mantine/hooks";import{getDisplayString as getDisplayString8}from"@medplum/core";import{useMedplum as useMedplum33}from"@medplum/react-hooks";import{useCallback as useCallback17,useState as useState66}from"react";import{Alert as Alert4,Group as Group42,Radio as Radio2,Stack as Stack30}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG6,addProfileToResource as addProfileToResource2,createReference as createReference9}from"@medplum/core";import{useMedplumProfile as useMedplumProfile9}from"@medplum/react-hooks";import{useCallback as useCallback16,useState as useState65}from"react";import{jsx as jsx117,jsxs as jsxs74}from"react/jsx-runtime";var HTTP2="http://",statusValues=["active","stopped","on-hold","cancelled","completed","entered-in-error","draft","unknown"];function MedicationDialog(props){let me=useMedplumProfile9(),{patient,encounter,medication,onSubmit}=props,[code,setCode]=useState65(medication?.medicationCodeableConcept),handleSubmit=useCallback16(formData=>{if(!me)throw new Error("Not signed in");onSubmit(addProfileToResource2({...medication,resourceType:"MedicationRequest",status:formData.status,intent:medication?.intent??"order",encounter:medication?.encounter??(encounter&&createReference9(encounter)),requester:medication?.requester??createReference9(me),medicationCodeableConcept:code,subject:createReference9(patient)},HTTP_HL7_ORG6+"/fhir/us/core/StructureDefinition/us-core-medicationrequest"))},[me,onSubmit,medication,encounter,code,patient]);return me?jsx117(Form,{onSubmit:handleSubmit,children:jsxs74(Stack30,{children:[jsx117(CodeableConceptInput,{name:"request",path:"MedicationRequest.medication[x]","data-autofocus":!0,binding:HTTP2+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1010.4",maxValues:1,defaultValue:medication?.medicationCodeableConcept,onChange:request=>setCode(request),outcome:void 0}),jsx117(Radio2.Group,{name:"status",label:"Request Status",required:!0,defaultValue:medication?.status,children:statusValues.map(sv=>jsx117(Radio2,{value:sv,label:sv,my:"xs",required:!0},sv))}),jsx117(Group42,{justify:"flex-end",gap:4,children:jsx117(SubmitButton,{children:"Save"})})]})}):jsx117(Alert4,{color:"red",children:"Not signed in"})}import{Fragment as Fragment38,jsx as jsx118,jsxs as jsxs75}from"react/jsx-runtime";function Medications(props){let medplum=useMedplum33(),[medicationRequests,setMedicationRequests]=useState66(props.medicationRequests),[editMedication,setEditMedication]=useState66(),[opened,{open,close}]=useDisclosure4(!1),handleSubmit=useCallback17(async medication=>{if(medication.id){let updatedMedication=await medplum.updateResource(medication);setMedicationRequests(medicationRequests.map(m=>m.id===updatedMedication.id?updatedMedication:m))}else{let newMedication=await medplum.createResource(medication);setMedicationRequests([newMedication,...medicationRequests])}setEditMedication(void 0),close()},[medplum,medicationRequests,close]);return jsxs75(Fragment38,{children:[jsx118(CollapsibleSection,{title:"Medications",onAdd:()=>{setEditMedication(void 0),open()},children:medicationRequests.length>0?jsx118(Flex14,{direction:"column",gap:8,children:medicationRequests.map(medication=>jsx118(SummaryItem,{onClick:()=>{setEditMedication(medication),open()},children:jsxs75(Box14,{children:[jsx118(Text30,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString8(medication)}),jsx118(Group43,{mt:2,gap:4,children:medication.status&&jsx118(StatusBadge,{color:getStatusColor2(medication.status),variant:"light",status:medication.status})})]})},medication.id))}):jsx118(Text30,{children:"(none)"})}),jsx118(Modal6,{opened,onClose:close,title:editMedication?"Edit Medication":"Add Medication",children:jsx118(MedicationDialog,{patient:props.patient,encounter:props.encounter,medication:editMedication,onSubmit:handleSubmit})})]})}function getStatusColor2(status){if(!status)return"gray";switch(status){case"active":return"green";case"stopped":return"red";case"on-hold":return"yellow";case"cancelled":return"red";case"completed":return"blue";case"entered-in-error":return"red";case"draft":return"gray";default:return"gray"}}import{Box as Box15,Group as Group44,Text as Text31,Tooltip as Tooltip5}from"@mantine/core";import{jsx as jsx119,jsxs as jsxs76}from"react/jsx-runtime";var PatientInfoItem=props=>{let{patient,value,icon,placeholder,label,onClickResource}=props,displayText=value||placeholder;return jsx119(SummaryItem,{onClick:()=>{onClickResource?.(patient)},children:jsx119(Box15,{className:PatientSummary_default.patientSummaryListItem,children:jsx119(Tooltip5,{label,position:"top-start",openDelay:650,children:jsxs76(Group44,{gap:"sm",align:"center",ml:6,mr:2,style:{cursor:"pointer",flexWrap:"nowrap",minWidth:0},children:[icon,jsx119(Text31,{fz:"sm",fw:400,truncate:!0,c:value?"inherit":"var(--mantine-color-gray-6)",children:displayText})]})})})})};import{capitalize as capitalize4,getExtension as getExtension3,HTTP_HL7_ORG as HTTP_HL7_ORG7}from"@medplum/core";function getGenderIdentity(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-genderIdentity`)?.valueCodeableConcept?.coding?.[0]?.display}function getBirthSex(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-birthsex`)?.valueCode}function getRace(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-race`)?.extension?.find(subExt=>subExt.url==="ombCategory")?.valueCoding?.display}function getEthnicity(patient){return getExtension3(patient,`${HTTP_HL7_ORG7}/fhir/us/core/StructureDefinition/us-core-ethnicity`)?.extension?.find(subExt=>subExt.url==="ombCategory")?.valueCoding?.display}function getGeneralPractitioner(patient){return patient.generalPractitioner?.[0]?.display}function formatPatientGenderDisplay(patient){let capitalizedGender=patient.gender?capitalize4(patient.gender):"",genderIdentity=getGenderIdentity(patient),birthSex=getBirthSex(patient),parts=[];return capitalizedGender&&parts.push(capitalizedGender),genderIdentity&&parts.push(genderIdentity),birthSex&&parts.push(`Born as ${birthSex}`),parts.join(" \xB7 ")}function formatPatientRaceEthnicityDisplay(patient){let race=getRace(patient),ethnicity=getEthnicity(patient),parts=[];return race&&parts.push(race),ethnicity&&parts.push(ethnicity),parts.join(" \xB7 ")}var getPreferredLanguage=patient=>{if(!patient.communication?.length)return;let preferred=patient.communication?.find(comm=>comm.preferred===!0);return preferred?.language?.coding?.[0]?.display?preferred.language.coding[0].display:patient.communication[0]?.language?.coding?.[0]?.display};import{Box as Box16,Flex as Flex15,Group as Group45,Loader as Loader4,Modal as Modal7,Text as Text32}from"@mantine/core";import{useDisclosure as useDisclosure5}from"@mantine/hooks";import{formatAddress as formatAddress2,getReferenceString as getReferenceString9,OperationOutcomeError}from"@medplum/core";import{useMedplum as useMedplum34,useResource as useResource8}from"@medplum/react-hooks";import{useCallback as useCallback18,useEffect as useEffect23,useMemo as useMemo30,useState as useState67}from"react";import{PATIENT_PREFERRED_PHARMACY_URL,PHARMACY_PREFERENCE_TYPE_SYSTEM,PHARMACY_TYPE_PREFERRED,PHARMACY_TYPE_PRIMARY,addPreferredPharmacyToPatient,createPreferredPharmacyExtension,getPreferredPharmaciesFromPatient,isAddPharmacyResponse,isOrganizationArray,removePreferredPharmacyFromPatient}from"@medplum/core";import{Fragment as Fragment39,jsx as jsx120,jsxs as jsxs77}from"react/jsx-runtime";function Pharmacies(props){let{patient:patientProp,onClickResource,pharmacyDialogComponent}=props,PharmacyDialogComponent=pharmacyDialogComponent,medplum=useMedplum34(),[opened,{open,close}]=useDisclosure5(!1),[resolvedPharmacies,setResolvedPharmacies]=useState67([]),[loadState,setLoadState]=useState67("loading"),patient=useResource8(patientProp),pharmacyRefs=useMemo30(()=>patient?getPreferredPharmaciesFromPatient(patient):[],[patient]);useEffect23(()=>{let cancelled=!1;return(async()=>{if(props.pharmacies){cancelled||(setResolvedPharmacies(props.pharmacies),setLoadState("loaded"));return}if(pharmacyRefs.length===0){cancelled||(setResolvedPharmacies([]),setLoadState("loaded"));return}setLoadState("loading");try{let results=await Promise.all(pharmacyRefs.map(async pharmacyRef=>{try{return{...await medplum.readReference(pharmacyRef.organizationRef),isPrimary:pharmacyRef.isPrimary}}catch(error){return isNotFoundError(error),null}}));if(!cancelled){let validResults=results.filter(result=>result!==null);setResolvedPharmacies(validResults),setLoadState(validResults.length===0&&pharmacyRefs.length>0?"error":"loaded")}}catch{cancelled||setLoadState("error")}})().catch(()=>{}),()=>{cancelled=!0}},[medplum,pharmacyRefs,props.pharmacies]);let handleSubmit=useCallback18(async _pharmacy=>{patient?.id&&medplum.invalidateUrl(getReferenceString9(patient)),close()},[medplum,patient,close]);return patient?jsxs77(Fragment39,{children:[jsx120(CollapsibleSection,{title:"Pharmacies",onAdd:pharmacyDialogComponent?open:void 0,children:loadState==="loading"?jsx120(Loader4,{size:"sm"}):loadState==="error"?jsx120(Text32,{c:"red",size:"sm",children:"Failed to load pharmacies"}):resolvedPharmacies.length===0?jsx120(Text32,{children:"(none)"}):jsx120(Box16,{children:jsx120(Flex15,{direction:"column",gap:8,children:resolvedPharmacies.map((pharmacy,index)=>jsx120(SummaryItem,{onClick:()=>onClickResource?.(pharmacy),children:jsxs77(Box16,{children:[jsx120(Text32,{fw:500,className:SummaryItem_default.itemText,children:pharmacy.name}),jsxs77(Group45,{mt:2,gap:4,children:[pharmacy.isPrimary&&jsx120(StatusBadge,{color:"blue",variant:"light",status:"primary"}),pharmacy.address?.[0]&&jsx120(Text32,{size:"xs",c:"dimmed",children:formatAddress2(pharmacy.address[0])})]})]})},pharmacy.id||index))})})}),PharmacyDialogComponent?jsx120(Modal7,{opened,onClose:close,title:"Add Pharmacy",size:"lg",children:jsx120(PharmacyDialogComponent,{patient,onSubmit:handleSubmit,onClose:close})}):null]}):jsx120(Fragment39,{})}function isNotFoundError(error){return error instanceof OperationOutcomeError?error.outcome.issue?.some(issue=>issue.code==="not-found")??!1:!1}import{Badge as Badge2,Box as Box17,Flex as Flex16,Group as Group47,Modal as Modal8,Text as Text33,UnstyledButton as UnstyledButton4}from"@mantine/core";import{useDisclosure as useDisclosure6}from"@mantine/hooks";import{formatDate as formatDate3,getDisplayString as getDisplayString9}from"@medplum/core";import{useMedplum as useMedplum35}from"@medplum/react-hooks";import{useCallback as useCallback20,useMemo as useMemo31,useState as useState69}from"react";import{Group as Group46,Stack as Stack31}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG8,HTTP_TERMINOLOGY_HL7_ORG,addProfileToResource as addProfileToResource3,createReference as createReference10}from"@medplum/core";import{useCallback as useCallback19,useState as useState68}from"react";import{jsx as jsx121,jsxs as jsxs78}from"react/jsx-runtime";function ConditionDialog(props){let{patient,encounter,condition,onSubmit}=props,[code,setCode]=useState68(condition?.code),[clinicalStatus,setClinicalStatus]=useState68(condition?.clinicalStatus),handleSubmit=useCallback19(formData=>{let updatedCondition=addProfileToResource3({...condition,resourceType:"Condition",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG+"/CodeSystem/condition-category",code:"problem-list-item",display:"Problem List Item"}],text:"Problem List Item"}],subject:createReference10(patient),encounter:encounter&&createReference10(encounter),code,clinicalStatus,onsetDateTime:formData.onsetDateTime?convertLocalToIso(formData.onsetDateTime):void 0},HTTP_HL7_ORG8+"/fhir/us/core/StructureDefinition/us-core-condition-problems-health-concerns");onSubmit(updatedCondition)},[patient,encounter,condition,code,clinicalStatus,onSubmit]);return jsx121(Form,{onSubmit:handleSubmit,children:jsxs78(Stack31,{children:[jsx121(CodeableConceptInput,{name:"code",label:"Problem",path:"Condition.code","data-autofocus":!0,binding:HTTP_HL7_ORG8+"/fhir/us/core/ValueSet/us-core-condition-code",defaultValue:condition?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx121(CodeableConceptInput,{name:"clinicalStatus",label:"Status",path:"Condition.clinicalStatus",binding:HTTP_HL7_ORG8+"/fhir/ValueSet/condition-clinical",defaultValue:condition?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx121(DateTimeInput,{name:"onsetDateTime",label:"Dx Date",defaultValue:condition?.onsetDateTime,required:!0}),jsx121(Group46,{justify:"flex-end",gap:4,mt:"md",children:jsx121(SubmitButton,{children:"Save"})})]})},condition?.id)}import{Fragment as Fragment40,jsx as jsx122,jsxs as jsxs79}from"react/jsx-runtime";function getCodeKey(condition){let coding=condition.code?.coding?.[0];return coding?.system&&coding?.code?`${coding.system}|${coding.code}`:coding?.code?coding.code:condition.code?.text??condition.id}function ProblemList(props){let medplum=useMedplum35(),{patient,encounter}=props,[problems,setProblems]=useState69(props.problems.filter(c=>c.verificationStatus?.coding?.[0]?.code!=="entered-in-error")),[editCondition,setEditCondition]=useState69(),[opened,{open,close}]=useDisclosure6(!1),[expandedGroups,setExpandedGroups]=useState69(()=>new Set),groupedProblems=useMemo31(()=>{let groups=new Map;for(let i=0;i<problems.length;i++){let problem=problems[i],key=getCodeKey(problem)??`ungrouped-${i}`,existing=groups.get(key);existing?existing.push(problem):groups.set(key,[problem])}return Array.from(groups.entries())},[problems]),toggleGroup=useCallback20(key=>{setExpandedGroups(prev=>{let next=new Set(prev);return next.has(key)?next.delete(key):next.add(key),next})},[]),handleSubmit=useCallback20(async condition=>{if(condition.id){let updatedCondition=await medplum.updateResource(condition);setProblems(problems.map(p=>p.id===updatedCondition.id?updatedCondition:p))}else{let newCondition=await medplum.createResource(condition);setProblems([newCondition,...problems])}setEditCondition(void 0),close()},[medplum,problems,close]);return jsxs79(Fragment40,{children:[jsx122(CollapsibleSection,{title:"Problems",onAdd:()=>{setEditCondition(void 0),open()},children:problems.length>0?jsx122(Flex16,{direction:"column",gap:8,children:groupedProblems.map(([key,group],groupIndex)=>{let isExpanded=expandedGroups.has(key),displayProblems=isExpanded?group:[group[0]],groupContentId=`problem-group-content-${groupIndex}`;return jsxs79(Box17,{children:[jsx122(Flex16,{direction:"column",gap:4,id:groupContentId,children:displayProblems.map(problem=>jsx122(SummaryItem,{onClick:()=>{setEditCondition(problem),open()},children:jsxs79(Box17,{children:[jsxs79(Group47,{gap:6,wrap:"nowrap",children:[jsx122(Text33,{fw:500,className:SummaryItem_default.itemText,children:getDisplayString9(problem)}),!isExpanded&&group.length>1&&jsxs79(Badge2,{size:"xs",color:"gray",variant:"light",style:{flexShrink:0},children:["+",group.length-1]})]}),jsxs79(Group47,{mt:2,gap:4,children:[problem.clinicalStatus?.coding?.[0]?.code&&jsx122(StatusBadge,{"data-testid":"status-badge",color:getStatusColor3(problem.clinicalStatus?.coding?.[0]?.code),variant:"light",status:problem.clinicalStatus?.coding?.[0]?.code}),jsx122(Text33,{size:"xs",fw:500,c:"dimmed",children:formatDate3(problem.onsetDateTime)})]})]})},problem.id))}),group.length>1&&jsx122(UnstyledButton4,{onClick:()=>toggleGroup(key),"aria-expanded":isExpanded,"aria-controls":groupContentId,pl:4,pt:2,style:{fontSize:"var(--mantine-font-size-xs)",color:"var(--mantine-color-dimmed)"},children:isExpanded?"Show less":`Show all ${group.length} entries`})]},key)})}):jsx122(Text33,{children:"(none)"})}),jsx122(Modal8,{opened,onClose:close,title:editCondition?"Edit Problem":"Add Problem",children:jsx122(ConditionDialog,{patient,encounter,condition:editCondition,onSubmit:handleSubmit})})]})}var getStatusColor3=status=>{if(!status)return"gray";switch(status){case"active":case"recurrence":case"relapse":return"green";case"inactive":return"orange";case"remission":return"blue";case"resolved":return"teal";default:return"gray"}};import{Box as Box18,Flex as Flex17,Group as Group48,Modal as Modal9,Radio as Radio3,Stack as Stack32,Text as Text34,UnstyledButton as UnstyledButton5}from"@mantine/core";import{useDisclosure as useDisclosure7}from"@mantine/hooks";import{createReference as createReference11,HTTP_HL7_ORG as HTTP_HL7_ORG9,HTTP_TERMINOLOGY_HL7_ORG as HTTP_TERMINOLOGY_HL7_ORG2,LOINC,SNOMED}from"@medplum/core";import{useMedplum as useMedplum36}from"@medplum/react-hooks";import{useCallback as useCallback21,useState as useState70}from"react";import{Fragment as Fragment41,jsx as jsx123,jsxs as jsxs80}from"react/jsx-runtime";var NULLFLAVOR=HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/v3-NullFlavor",CodesToText={38628009:"Homosexual",20430005:"Heterosexual",42035005:"Bisexual",OTH:"Other",UNK:"Unknown",ASKU:"Asked but no answer"},CodesToSystem={38628009:SNOMED,20430005:SNOMED,42035005:SNOMED,OTH:NULLFLAVOR,UNK:NULLFLAVOR,ASKU:NULLFLAVOR};function SexualOrientation(props){let{patient,encounter}=props,medplum=useMedplum36(),[sexualOrientation,setSexualOrientation]=useState70(props.sexualOrientation),[opened,{open,close}]=useDisclosure7(!1),[hoverIndex,setHoverIndex]=useState70(null),handleSubmit=useCallback21(formData=>{let code=formData.sexualOrientation;medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG9+"/fhir/us/core/ValueSet/us-core-sexual-orientation"]},status:"final",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC,code:"76690-7",display:"Sexual orientation"}],text:"Sexual orientation"},subject:createReference11(patient),encounter:encounter?createReference11(encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:CodesToSystem[code],code:formData.sexualOrientation}],text:CodesToText[code]}}).then(newSexualOrientation=>{setSexualOrientation(newSexualOrientation),close()}).catch(console.error)},[medplum,patient,encounter,close]);return jsxs80(Fragment41,{children:[jsx123(CollapsibleSection,{title:"Sexual Orientation",onAdd:()=>{open()},children:sexualOrientation?jsx123(Flex17,{direction:"column",gap:8,children:jsx123(Box18,{onMouseEnter:()=>setHoverIndex(0),onMouseLeave:()=>setHoverIndex(null),children:jsx123(UnstyledButton5,{"data-testid":"sexual-orientation-button",onClick:e=>{killEvent(e),props.onClickResource&&props.onClickResource(sexualOrientation)},children:jsx123(Box18,{pr:hoverIndex===0?24:0,children:jsx123(Text34,{size:"sm",fw:500,children:sexualOrientation.valueCodeableConcept?.text??"Unknown"})})})})}):jsx123(Text34,{children:"(none)"})}),jsx123(Modal9,{opened,onClose:close,title:"Set Sexual Orientation",children:jsx123(Form,{onSubmit:handleSubmit,children:jsxs80(Stack32,{children:[jsx123(Radio3.Group,{name:"sexualOrientation",label:"Sexual Orientation",required:!0,children:Object.entries(CodesToText).map(([code,text])=>jsx123(Radio3,{value:code,label:text,my:"xs"},code))}),jsx123(Group48,{justify:"flex-end",gap:4,mt:"md",children:jsx123(SubmitButton,{children:"Save"})})]})})})]})}import{Group as Group49,Modal as Modal10,Radio as Radio4,Stack as Stack33,Text as Text35,UnstyledButton as UnstyledButton6}from"@mantine/core";import{useDisclosure as useDisclosure8}from"@mantine/hooks";import{HTTP_HL7_ORG as HTTP_HL7_ORG10,LOINC as LOINC2,SNOMED as SNOMED2,createReference as createReference12,formatCodeableConcept as formatCodeableConcept4}from"@medplum/core";import{useMedplum as useMedplum37}from"@medplum/react-hooks";import{useCallback as useCallback22,useState as useState71}from"react";import{Fragment as Fragment42,jsx as jsx124,jsxs as jsxs81}from"react/jsx-runtime";var smokingStatusOptions={266919005:"Never smoked tobacco",266927001:"Tobacco smoking consumption unknown","428041000124106":"Occasional tobacco smoker","428061000124105":"Light tobacco smoker","428071000124103":"Heavy tobacco smoker",449868002:"Smokes tobacco daily",77176002:"Smoker",8517006:"Ex-smoker"};function SmokingStatus(props){let medplum=useMedplum37(),[smokingStatus,setSmokingStatus]=useState71(props.smokingStatus),[opened,{open,close}]=useDisclosure8(!1),handleSubmit=useCallback22(formData=>{medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG10+"/fhir/us/core/StructureDefinition/us-core-smokingstatus"]},status:"final",category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC2,code:"72166-2",display:"Tobacco smoking status"}],text:"Tobacco smoking status"},subject:createReference12(props.patient),encounter:props.encounter?createReference12(props.encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:SNOMED2,version:SNOMED2+"/731000124108",code:formData.smokingStatus}],text:smokingStatusOptions[formData.smokingStatus]}}).then(newSmokingStatus=>{setSmokingStatus(newSmokingStatus),close()}).catch(console.error)},[medplum,props.patient,props.encounter,close]);return jsxs81(Fragment42,{children:[jsx124(CollapsibleSection,{title:"Smoking Status",onAdd:()=>{open()},children:smokingStatus?.valueCodeableConcept?jsx124(UnstyledButton6,{"data-testid":"smoking-status-button",onClick:()=>props.onClickResource?.(smokingStatus),children:jsx124(Text35,{children:formatCodeableConcept4(smokingStatus.valueCodeableConcept)})}):jsx124(Text35,{children:"(none)"})}),jsx124(Modal10,{opened,onClose:close,title:"Set Smoking Status",children:jsx124(Form,{onSubmit:handleSubmit,children:jsxs81(Stack33,{children:[jsx124(Radio4.Group,{name:"smokingStatus",label:"Smoking Status",required:!0,children:Object.entries(smokingStatusOptions).map(([code,text])=>jsx124(Radio4,{value:code,label:text,my:"xs"},code))}),jsx124(Group49,{justify:"flex-end",gap:4,mt:"md",children:jsx124(SubmitButton,{children:"Save"})})]})})})]})}import{Group as Group50,Modal as Modal11,SimpleGrid,Stack as Stack34,Text as Text36,Textarea as Textarea4,TextInput as TextInput25}from"@mantine/core";import{useDisclosure as useDisclosure9}from"@mantine/hooks";import{formatQuantity as formatQuantity2}from"@medplum/core";import{useMedplum as useMedplum38}from"@medplum/react-hooks";import{useCallback as useCallback23,useState as useState72}from"react";import{LOINC as LOINC3,UCUM,createReference as createReference13}from"@medplum/core";function getObservationValue(obs,component){return component?obs.component?.find(c=>c.code?.coding?.[0].code===component)?.valueQuantity:obs.valueQuantity}function createObservation(patient,encounter,code,title,valueQuantity){if(isValidNumber(valueQuantity.value))return{...createBaseObservation(patient,encounter,code,title),valueQuantity}}function createCompoundObservation(patient,encounter,code,title,components){let component=components.filter(c=>isValidNumber(c.valueQuantity?.value));if(component.length!==0)return{...createBaseObservation(patient,encounter,code,title),component}}function createBaseObservation(patient,encounter,code,title){return{resourceType:"Observation",status:"preliminary",subject:createReference13(patient),encounter:encounter?createReference13(encounter):void 0,effectiveDateTime:new Date().toISOString(),category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"vital-signs",display:"Vital Signs"}]}],code:createLoincCode(code,title)}}function createLoincCode(code,display){return{coding:[{code,display,system:LOINC3}],text:display}}function createQuantity(value,unit){return{value,system:UCUM,unit,code:unit}}function isValidNumber(value){return value!==void 0&&!Number.isNaN(value)&&Number.isFinite(value)}import{Fragment as Fragment43,jsx as jsx125,jsxs as jsxs82}from"react/jsx-runtime";var BP="85354-9",SYSTOLIC="8480-6",DIASTOLIC="8462-4",LOINC_CODES=[{name:"systolic",short:"BP Sys",code:BP,component:SYSTOLIC,title:"Blood Pressure",unit:"mm[Hg]"},{name:"diastolic",short:"BP Dias",code:BP,component:DIASTOLIC,title:"Blood Pressure",unit:"mm[Hg]"},{name:"heartRate",short:"HR",code:"8867-4",title:"Heart Rate",unit:"/min"},{name:"bodyTemperature",short:"Temp",code:"8310-5",title:"Body Temperature",unit:"Cel"},{name:"respiratoryRate",short:"RR",code:"9279-1",title:"Respiratory Rate",unit:"/min"},{name:"height",short:"Ht",code:"8302-2",title:"Height",unit:"cm"},{name:"weight",short:"Wt",code:"29463-7",title:"Weight",unit:"kg"},{name:"bmi",short:"BMI",code:"39156-5",title:"BMI",unit:"kg/m2"},{name:"oxygen",short:"O2",code:"2708-6",title:"Oxygen",unit:"%"},{name:"headCircumference",short:"HC",code:"9843-4",title:"Head Circumference",unit:"cm"}];function Vitals(props){let medplum=useMedplum38(),{patient,encounter}=props,[vitals,setVitals]=useState72(props.vitals),[opened,{open,close}]=useDisclosure9(!1),handleSubmit=useCallback23(formData=>{let newObservations=[];newObservations.push(createCompoundObservation(patient,encounter,BP,"Blood pressure",[{code:createLoincCode(SYSTOLIC,"Systolic blood pressure"),valueQuantity:createQuantity(Number.parseFloat(formData.systolic),"mm[Hg]")},{code:createLoincCode(DIASTOLIC,"Diastolic blood pressure"),valueQuantity:createQuantity(Number.parseFloat(formData.diastolic),"mm[Hg]")}]));for(let meta of LOINC_CODES)meta.component||newObservations.push(createObservation(patient,encounter,meta.code,meta.title,createQuantity(Number.parseFloat(formData[meta.name]),meta.unit)));Promise.all(newObservations.filter(Boolean).map(obs=>medplum.createResource(obs))).then(newVitals=>setVitals([...newVitals,...vitals])).catch(console.error),close()},[medplum,patient,encounter,vitals,close]);return jsxs82(Fragment43,{children:[jsx125(CollapsibleSection,{title:"Vitals",onAdd:()=>{open()},children:jsx125(Stack34,{children:LOINC_CODES.map(meta=>{let obs=vitals.find(o=>o.code?.coding?.[0].code===meta.code);return jsxs82(Group50,{align:"center",children:[jsx125(Text36,{c:"dimmed",children:meta.short}),obs&&jsx125(Text36,{children:formatQuantity2(getObservationValue(obs,meta.component))})]},meta.name)})})}),jsx125(Modal11,{opened,onClose:close,title:"Add Vitals",children:jsxs82(Form,{onSubmit:handleSubmit,children:[jsx125(SimpleGrid,{cols:2,children:LOINC_CODES.map((meta,index)=>jsx125(TextInput25,{name:meta.name,label:meta.short,description:`${meta.title} (${meta.unit})`,"data-autofocus":index===0,autoFocus:index===0},meta.name))}),jsx125(Textarea4,{name:"notes",label:"Notes"}),jsx125(Group50,{justify:"flex-end",gap:4,mt:"md",children:jsx125(SubmitButton,{children:"Save"})})]})})]})}import{jsx as jsx126,jsxs as jsxs83}from"react/jsx-runtime";var DemographicsSection={key:"demographics",title:"Demographics",component:({patient,onClickResource})=>{let languageDisplay=getPreferredLanguage(patient);return jsxs83(Stack35,{gap:"xs",py:8,children:[jsx126(PatientInfoItem,{patient,value:patient.birthDate?`${patient.birthDate} (${calculateAgeString(patient.birthDate)})`:void 0,icon:jsx126(IconCake,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Birthdate",label:"Birthdate & Age",onClickResource}),jsx126(PatientInfoItem,{patient,value:patient.gender?formatPatientGenderDisplay(patient):void 0,icon:jsx126(IconEmpathize,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Gender & Identity",label:"Gender & Identity",onClickResource}),jsx126(PatientInfoItem,{patient,value:getRace(patient)||getEthnicity(patient)?formatPatientRaceEthnicityDisplay(patient):void 0,icon:jsx126(IconBinaryTree,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Race & Ethnicity",label:"Race & Ethnicity",onClickResource}),jsx126(PatientInfoItem,{patient,value:patient.address?.[0]?formatAddress3(patient.address[0]):void 0,icon:jsx126(IconMapPin,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Location",label:"Location",onClickResource}),jsx126(PatientInfoItem,{patient,value:languageDisplay,icon:jsx126(IconLanguage,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add Language",label:"Language",onClickResource}),jsx126(PatientInfoItem,{patient,value:getGeneralPractitioner(patient),icon:jsx126(IconStethoscope,{size:16,stroke:2,color:"var(--mantine-color-gray-6)"}),placeholder:"Add General Practitioner",label:"General Practitioner",onClickResource})]})}},InsuranceSection={key:"insurance",title:"Insurance",searches:[{key:"coverages",resourceType:"Coverage",patientParam:"beneficiary"}],component:({results,onClickResource})=>jsx126(Insurance,{coverages:results.coverages||[],onClickResource})},AllergiesSection={key:"allergies",title:"Allergies",searches:[{key:"allergies",resourceType:"AllergyIntolerance",patientParam:"patient"}],component:({results,patient,onClickResource})=>jsx126(Allergies,{patient,allergies:results.allergies||[],onClickResource})},ProblemListSection={key:"problemList",title:"Problems",searches:[{key:"conditions",resourceType:"Condition",patientParam:"patient"}],component:({results,patient,onClickResource})=>jsx126(ProblemList,{patient,problems:results.conditions||[],onClickResource})},MedicationsSection={key:"medications",title:"Medications",searches:[{key:"medications",resourceType:"MedicationRequest",patientParam:"subject"}],component:({results,patient,onClickResource})=>jsx126(Medications,{patient,medicationRequests:results.medications||[],onClickResource})};function createLabsSection(onRequestLabs){return{key:"labs",title:"Labs",searches:[{key:"serviceRequests",resourceType:"ServiceRequest",patientParam:"subject"},{key:"diagnosticReports",resourceType:"DiagnosticReport",patientParam:"subject"}],component:({results,patient,onClickResource})=>jsx126(Labs,{patient,serviceRequests:results.serviceRequests||[],diagnosticReports:results.diagnosticReports||[],onClickResource,onRequestLabs})}}var LabsSection=createLabsSection(),SexualOrientationSection={key:"sexualOrientation",title:"Sexual Orientation",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{code:"76690-7"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(SexualOrientation,{patient,sexualOrientation:observations[0],onClickResource})}},SmokingStatusSection={key:"smokingStatus",title:"Smoking Status",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{code:"72166-2"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(SmokingStatus,{patient,smokingStatus:observations[0],onClickResource})}},VitalsSection={key:"vitals",title:"Vitals",searches:[{key:"observations",resourceType:"Observation",patientParam:"subject",query:{category:"vital-signs"}}],component:({results,patient,onClickResource})=>{let observations=results.observations||[];return jsx126(Vitals,{patient,vitals:observations,onClickResource})}};function createPharmaciesSection(pharmacyDialogComponent){return{key:"pharmacies",title:"Pharmacies",component:({patient,onClickResource})=>jsx126(Pharmacies,{patient,onClickResource,pharmacyDialogComponent})}}var PharmaciesSection=createPharmaciesSection();function getDefaultSections(onRequestLabs){return[DemographicsSection,InsuranceSection,AllergiesSection,ProblemListSection,MedicationsSection,createLabsSection(onRequestLabs),SexualOrientationSection,SmokingStatusSection,VitalsSection,PharmaciesSection]}import{Fragment as Fragment44,jsx as jsx127,jsxs as jsxs84}from"react/jsx-runtime";function PatientSummary(props){let medplum=useMedplum39(),{patient:propsPatient,onClickResource,onRequestLabs}=props,patient=useResource9(propsPatient),[createdDate,setCreatedDate]=useState73(),defaultSections=useMemo32(()=>getDefaultSections(onRequestLabs),[onRequestLabs]),sections=props.sections??defaultSections,{sectionData,loading,error}=usePatientSummaryData(propsPatient,sections);return useEffect24(()=>{let id=resolveId(propsPatient);id&&medplum.readHistory("Patient",id).then(history=>{let lastUpdated=history.entry?.[history.entry.length-1]?.resource?.meta?.lastUpdated;setCreatedDate(typeof lastUpdated=="string"?lastUpdated:"")}).catch(()=>{})},[propsPatient,medplum]),patient?jsxs84(Flex18,{direction:"column",gap:"xs",w:"100%",h:"100%",className:PatientSummary_default.panel,children:[jsxs84(SummaryItem,{onClick:()=>{onClickResource?.(patient)},children:[jsxs84(Group51,{align:"center",gap:"sm",p:16,children:[jsx127(ResourceAvatar,{value:patient,size:48,radius:48,style:{border:"2px solid white"}}),jsxs84(Stack36,{gap:0,style:{flex:1,minWidth:0},children:[jsx127(Tooltip6,{label:formatHumanName8(patient.name?.[0]),position:"top-start",openDelay:650,children:jsx127(Text37,{fz:"h4",fw:800,truncate:!0,style:{minWidth:0},children:formatHumanName8(patient.name?.[0])})}),(()=>{let dateString=typeof createdDate=="string"&&createdDate.length>0?createdDate:void 0;if(!dateString)return null;let d=new Date(dateString);return jsxs84(Text37,{fz:"xs",mt:-2,fw:500,c:"gray.6",truncate:!0,style:{minWidth:0},children:["Patient since ",d.getMonth()+1,"/",d.getDate(),"/",d.getFullYear()]})})()]})]}),jsx127(Divider6,{})]}),jsxs84(Stack36,{gap:"xs",px:16,pt:12,pb:16,style:{flex:2,overflowY:"auto",minHeight:0},children:[error&&jsxs84(Text37,{c:"red",fz:"sm",children:["Error loading patient summary: ",error.message]}),!loading&§ions.length>0&&jsx127(Fragment44,{children:sections.map((section,index)=>{let SectionComponent=section.component;return jsxs84("div",{children:[jsx127(SectionComponent,{patient,onClickResource,results:sectionData[index]??{}}),jsx127(Divider6,{})]},section.key)})})]})]}):null}var ThreadInbox_default={container:"ThreadInbox_container",rightBorder:"ThreadInbox_rightBorder"};import{Fragment as Fragment45,jsx as jsx128,jsxs as jsxs85}from"react/jsx-runtime";function ThreadInbox(props){let{query,threadId,subject,showPatientSummary=!1,sections,onNew,getThreadUri,uploadEnabled,onViewInDocuments,onChange,inProgressUri,completedUri,allowPatientSelection=!1}=props,navigate=useMedplumNavigate5(),[modalOpened,{open:openModal,close:closeModal}]=useDisclosure10(!1),currentSearch=useMemo33(()=>parseSearchRequest(`Communication?${query}`),[query]),searchParams=useMemo33(()=>new URLSearchParams(query),[query]),itemsPerPage=Number.parseInt(searchParams.get("_count")||"20",10),currentOffset=Number.parseInt(searchParams.get("_offset")||"0",10),currentPage=Math.floor(currentOffset/itemsPerPage)+1,status=searchParams.get("status")||"in-progress",selectedParticipants=useMemo33(()=>(currentSearch.filters?.filter(f=>f.code==="recipient")??[]).flatMap(f=>f.value.split(",").filter(Boolean).map(ref=>({reference:ref}))),[currentSearch]),{loading,error,threadMessages,selectedThread,total,handleThreadStatusChange,addThreadMessage,refreshThreadMessages}=useThreadInbox({query,threadId}),handleParticipantsChange=useCallback24(participants=>{let otherFilters=currentSearch.filters?.filter(f=>f.code!=="recipient")??[],participantRefs=participants.map(p=>p.reference).filter(Boolean),newFilters=participantRefs.length>0?[...otherFilters,{code:"recipient",operator:Operator.EQUALS,value:participantRefs.join(",")}]:otherFilters;onChange({...currentSearch,filters:newFilters,offset:0})},[currentSearch,onChange]),skeletonTitleWidths=[80,72,68,64],skeletonSubtitleWidths=[85,78,70,60];useEffect25(()=>{error&&showNotification8({title:"Error",message:normalizeErrorString10(error),color:"red"})},[error]);let handleTopicStatusChangeWithErrorHandling=async newStatus=>{handleThreadStatusChange(newStatus);try{await refreshThreadMessages()}catch(error2){showNotification8({title:"Error",message:normalizeErrorString10(error2),color:"red"})}},handleNewTopicCompletion=message=>{addThreadMessage(message),onNew(message)};return jsxs85(Fragment45,{children:[jsx128("div",{className:ThreadInbox_default.container,children:jsxs85(Flex19,{direction:"row",h:"100%",w:"100%",children:[jsx128(Flex19,{direction:"column",w:380,h:"100%",className:ThreadInbox_default.rightBorder,children:jsxs85(Paper4,{h:"100%",style:{display:"flex",flexDirection:"column"},children:[jsxs85(ScrollArea3,{style:{flex:1},scrollbarSize:10,type:"hover",scrollHideDelay:250,children:[jsxs85(Flex19,{h:64,align:"center",justify:"space-between",p:"md",children:[jsx128(Tabs,{value:status,onChange:value=>{navigate(value==="in-progress"?inProgressUri:completedUri)},variant:"unstyled",className:"pill-tabs",children:jsxs85(Tabs.List,{children:[jsx128(Tabs.Tab,{value:"in-progress",children:"In Progress"}),jsx128(Tabs.Tab,{value:"completed",children:"Completed"})]})}),jsxs85(Group52,{gap:"xs",children:[jsx128(ParticipantFilter,{selectedParticipants,onFilterChange:handleParticipantsChange}),jsx128(Tooltip7,{label:"New Message",position:"bottom",openDelay:500,children:jsx128(ActionIcon12,{radius:"xl",variant:"filled",color:"blue",size:32,onClick:openModal,children:jsx128(IconPlus,{size:16})})})]})]}),jsx128(Divider7,{}),loading?jsx128(Stack37,{gap:"md",p:"md",children:Array.from({length:10}).map((_,index)=>{let titleWidth=skeletonTitleWidths[index%skeletonTitleWidths.length],subtitleWidth=skeletonSubtitleWidths[index%skeletonSubtitleWidths.length];return jsxs85(Flex19,{gap:"sm",align:"flex-start",children:[jsx128(Skeleton2,{height:40,width:40,radius:"50%"}),jsx128(Box19,{style:{flex:1},children:jsxs85(Flex19,{direction:"column",gap:"xs",children:[jsx128(Skeleton2,{height:16,width:`${titleWidth}%`}),jsx128(Skeleton2,{height:14,width:`${subtitleWidth}%`})]})})]},index)})}):threadMessages.length>0&&jsx128(ChatList,{threads:threadMessages,selectedCommunication:selectedThread,getThreadUri}),threadMessages.length===0&&!loading&&jsx128(EmptyMessagesState,{})]}),!loading&&total!==void 0&&total>itemsPerPage&&jsx128(Box19,{p:"md",children:jsx128(Center3,{children:jsx128(Pagination,{value:currentPage,total:Math.ceil(total/itemsPerPage),onChange:page=>{let offset=(page-1)*itemsPerPage;onChange({...currentSearch,offset})},size:"sm",siblings:1,boundaries:1})})})]})}),selectedThread?jsxs85(Fragment45,{children:[jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",className:ThreadInbox_default.rightBorder,children:jsx128(Paper4,{h:"100%",children:jsxs85(Stack37,{h:"100%",gap:0,children:[jsxs85(Flex19,{h:64,align:"center",justify:"space-between",p:"md",children:[jsx128(Text38,{fw:800,truncate:!0,fz:"lg",children:selectedThread.topic?.text??"Messages"}),jsxs85(Menu5,{position:"bottom-end",shadow:"md",children:[jsx128(Menu5.Target,{children:jsx128(Button12,{variant:"light",color:getStatusColor4(selectedThread.status),rightSection:selectedThread.status==="completed"?void 0:jsx128(IconChevronDown,{size:16}),radius:"xl",size:"sm",children:selectedThread.status.split("-").map(word=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")})}),selectedThread.status!=="completed"&&jsx128(Menu5.Dropdown,{children:jsx128(Menu5.Item,{onClick:()=>handleTopicStatusChangeWithErrorHandling("completed"),children:"Completed"})})]})]}),jsx128(Divider7,{}),jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",children:jsx128(ThreadChat,{title:"Messages",thread:selectedThread,excludeHeader:!0,uploadEnabled,onViewInDocuments},`${getReferenceString10(selectedThread)}`)})]})})}),selectedThread.subject&&showPatientSummary&&jsx128(Flex19,{direction:"column",w:300,h:"100%",children:jsx128(ScrollArea3,{p:0,h:"100%",scrollbarSize:10,type:"hover",scrollHideDelay:250,children:jsx128(PatientSummary,{patient:selectedThread.subject,sections},selectedThread.id)})})]}):jsx128(Flex19,{direction:"column",style:{flex:1},h:"100%",children:jsx128(NoMessages,{})})]})}),jsx128(NewTopicDialog,{subject,opened:modalOpened,onClose:closeModal,onSubmit:handleNewTopicCompletion,allowPatientSelection})]})}function NoMessages(){return jsx128(Center3,{h:"100%",w:"100%",children:jsxs85(Stack37,{align:"center",gap:"md",children:[jsx128(ThemeIcon,{size:64,variant:"light",color:"gray",children:jsx128(IconMessageCircle,{size:32})}),jsx128(Stack37,{align:"center",gap:"xs",children:jsx128(Text38,{size:"sm",c:"dimmed",ta:"center",children:"Select a message from the list to view details"})})]})})}function getStatusColor4(status){return status==="completed"?"green":status==="stopped"?"red":"blue"}function EmptyMessagesState(){return jsx128(Flex19,{direction:"column",h:"100%",justify:"center",align:"center",children:jsxs85(Stack37,{align:"center",gap:"md",pt:"xl",children:[jsx128(IconMessageCircle,{size:64,color:"var(--mantine-color-gray-4)"}),jsx128(Text38,{size:"lg",c:"dimmed",fw:500,children:"No messages found"})]})})}import{ActionIcon as ActionIcon14,Button as Button14,Center as Center4,Group as Group54,Loader as Loader5,ScrollArea as ScrollArea4,TextInput as TextInput26}from"@mantine/core";import{showNotification as showNotification9,updateNotification}from"@mantine/notifications";import{createReference as createReference14,normalizeErrorString as normalizeErrorString11}from"@medplum/core";import{useMedplum as useMedplum42,useResource as useResource11}from"@medplum/react-hooks";import{useCallback as useCallback25,useEffect as useEffect28,useLayoutEffect as useLayoutEffect4,useRef as useRef13,useState as useState77}from"react";var import_rfc6902=__toESM(require_rfc6902(),1);import{Table as Table2}from"@mantine/core";import{arrayify,capitalize as capitalize5,evalFhirPathTyped,getSearchParameterDetails,toTypedValue}from"@medplum/core";import{useMedplum as useMedplum40}from"@medplum/react-hooks";import{useEffect as useEffect26,useMemo as useMemo34,useState as useState75}from"react";import{Button as Button13,Table}from"@mantine/core";import{useState as useState74}from"react";var ResourceDiffRow_default={removed:"ResourceDiffRow_removed",added:"ResourceDiffRow_added"};import{Fragment as Fragment46,jsx as jsx129,jsxs as jsxs86}from"react/jsx-runtime";function ResourceDiffRow(props){let{name,path,property,originalValue,revisedValue}=props,isAttachmentType=!!property?.type?.find(t=>t.code==="Attachment"),[isCollapsed,setIsCollapsed]=useState74(isAttachmentType),toggleCollapse=()=>setIsCollapsed(prev=>!prev);return jsx129(Fragment46,{children:isAttachmentType&&!isCollapsed||!isAttachmentType?jsx129(Fragment46,{children:jsxs86(Table.Tr,{children:[jsx129(Table.Td,{children:name}),jsx129(Table.Td,{className:ResourceDiffRow_default.removed,children:originalValue&&jsx129(ResourcePropertyDisplay,{path,property,propertyType:originalValue.type,value:originalValue.value,ignoreMissingValues:!0})}),jsx129(Table.Td,{className:ResourceDiffRow_default.added,children:revisedValue&&jsx129(ResourcePropertyDisplay,{path,property,propertyType:revisedValue.type,value:revisedValue.value,ignoreMissingValues:!0})})]})}):jsxs86(Table.Tr,{children:[jsx129(Table.Td,{children:name}),jsx129(Table.Td,{colSpan:2,style:{textAlign:"right"},children:jsx129(Button13,{onClick:toggleCollapse,variant:"light",children:"Expand"})})]})})}var ResourceDiffTable_default={root:"ResourceDiffTable_root",removed:"ResourceDiffTable_removed",added:"ResourceDiffTable_added"};import{jsx as jsx130,jsxs as jsxs87}from"react/jsx-runtime";function ResourceDiffTable(props){let medplum=useMedplum40(),{original,revised}=props,[schemaLoaded,setSchemaLoaded]=useState75(!1);useEffect26(()=>{medplum.requestSchema(props.original.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.original.resourceType]);let diffTable=useMemo34(()=>{if(!schemaLoaded)return null;let typedOriginal=[toTypedValue(original)],typedRevised=[toTypedValue(revised)],result=[],patch=mergePatchOperations((0,import_rfc6902.createPatch)(original,revised));for(let op of patch){let path=op.path,fhirPath=jsonPathToFhirPath(path),property=tryGetElementDefinition(original.resourceType,fhirPath),originalValue=op.op==="add"?void 0:evalFhirPathTyped(fhirPath,typedOriginal),revisedValue=op.op==="remove"?void 0:evalFhirPathTyped(fhirPath,typedRevised);result.push({key:`op-${op.op}-${op.path}`,name:`${capitalize5(op.op)} ${fhirPath}`,path:property?.path??original.resourceType+"."+fhirPath,property,originalValue:touchUpValue(property,originalValue),revisedValue:touchUpValue(property,revisedValue)})}return result},[schemaLoaded,original,revised]);return diffTable?jsxs87(Table2,{className:ResourceDiffTable_default.root,children:[jsx130(Table2.Thead,{children:jsxs87(Table2.Tr,{children:[jsx130(Table2.Th,{}),jsx130(Table2.Th,{children:"Before"}),jsx130(Table2.Th,{children:"After"})]})}),jsx130(Table2.Tbody,{children:diffTable.map(row=>{let{key,...rest}=row;return jsx130(ResourceDiffRow,{...rest},key)})})]}):null}function mergePatchOperations(patch){let result=[];for(let patchOperation of patch){let{op,path}=patchOperation;if(path.startsWith("/meta/author")||path.startsWith("/meta/compartment")||path.startsWith("/meta/lastUpdated")||path.startsWith("/meta/versionId"))continue;let count=patch.filter(el=>el.op===op&&el.path===path).length,resultOperation={op,path};count>1&&(op==="add"||op==="remove")&&/\/[0-9-]+$/.test(path)&&(resultOperation.op="replace",resultOperation.path=path.replace(/\/[^/]+$/,"")),result.some(el=>el.op===resultOperation.op&&el.path===resultOperation.path)||result.push(resultOperation)}return result}function jsonPathToFhirPath(path){let parts=path.split("/").filter(Boolean),result="";for(let i=0;i<parts.length;i++){let part=parts[i];part==="-"?result+=".last()":/^\d+$/.test(part)?result+=`[${part}]`:(i>0&&(result+="."),result+=part)}return result.endsWith(".url")&&(result=result.replace(/\.url$/,"")),result}function tryGetElementDefinition(resourceType,fhirPath){try{return getSearchParameterDetails(resourceType,{resourceType:"SearchParameter",base:[resourceType],code:resourceType+"."+fhirPath,expression:resourceType+"."+fhirPath})?.elementDefinitions?.[0]}catch(err){console.warn("Failed to get element definition",{resourceType,fhirPath,err});return}}function touchUpValue(property,input){return input&&{type:Array.isArray(input)?input[0].type:input.type,value:fixArray(input,!!property?.isArray)}}function fixArray(input,isArray){let inputValue=arrayify(input).flatMap(v=>v.value);return isArray?inputValue:inputValue[0]}import{AccessPolicyInteraction,satisfiedAccessPolicy,tryGetProfile as tryGetProfile4}from"@medplum/core";import{useMedplum as useMedplum41,useResource as useResource10}from"@medplum/react-hooks";import{useEffect as useEffect27,useMemo as useMemo35,useState as useState76}from"react";import{jsx as jsx131}from"react/jsx-runtime";function ResourceTable(props){let{profileUrl}=props,medplum=useMedplum41(),accessPolicy=medplum.getAccessPolicy(),value=useResource10(props.value),[schemaLoaded,setSchemaLoaded]=useState76(!1);useEffect27(()=>{if(value)if(profileUrl)medplum.requestProfileSchema(profileUrl,{expandProfile:!0}).then(()=>{tryGetProfile4(profileUrl)?setSchemaLoaded(!0):console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)});else{let schemaName=value.resourceType;medplum.requestSchema(schemaName).then(()=>{setSchemaLoaded(!0)}).catch(console.error)}},[medplum,profileUrl,value]);let accessPolicyResource=useMemo35(()=>value&&satisfiedAccessPolicy(value,AccessPolicyInteraction.READ,accessPolicy),[accessPolicy,value]);return!schemaLoaded||!value?null:jsx131(BackboneElementDisplay,{path:value.resourceType,value:{type:value.resourceType,value:props.forceUseInput?props.value:value},profileUrl,ignoreMissingValues:props.ignoreMissingValues,accessPolicyResource})}import{ActionIcon as ActionIcon13,Group as Group53,Menu as Menu6,Text as Text39}from"@mantine/core";import{formatDateTime as formatDateTime4,getReferenceString as getReferenceString11}from"@medplum/core";var Timeline_default={item:"Timeline_item",itemPadding:"Timeline_itemPadding"};import{jsx as jsx132,jsxs as jsxs88}from"react/jsx-runtime";function Timeline(props){return jsx132(Container,{children:props.children})}function TimelineItem(props){let{resource,profile,padding,popupMenuItems,...others}=props,author=profile??resource.meta?.author,dateTime=props.dateTime??resource.meta?.lastUpdated;return jsxs88(Panel,{"data-testid":"timeline-item",fill:!0,...others,children:[jsxs88(Group53,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[jsx132(ResourceAvatar,{value:author,link:!0,size:"md"}),jsxs88("div",{style:{flex:1},children:[jsx132(Text39,{size:"sm",children:jsx132(ResourceName,{c:"inherit",fw:500,value:author,link:!0})}),jsxs88(Text39,{size:"xs",children:[jsx132(MedplumLink,{c:"dimmed",to:props.resource,children:formatDateTime4(dateTime)}),jsx132(Text39,{component:"span",c:"dimmed",mx:8,children:"\xB7"}),jsx132(MedplumLink,{c:"dimmed",to:props.resource,children:props.resource.resourceType})]})]}),popupMenuItems&&jsxs88(Menu6,{position:"bottom-end",shadow:"md",width:200,children:[jsx132(Menu6.Target,{children:jsx132(ActionIcon13,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${getReferenceString11(props.resource)}`,children:jsx132(IconDots,{})})}),popupMenuItems]})]}),jsx132(ErrorBoundary,{children:jsx132("div",{className:clsx_default(Timeline_default.item,{[Timeline_default.itemPadding]:padding}),children:props.children})})]})}function sortByDateAndPriority(resources,timelineResource){resources.sort((a,b)=>{let priority1=getPriorityScore(a,timelineResource),priority2=getPriorityScore(b,timelineResource);return priority1>priority2?1:priority1<priority2?-1:getTime(a,timelineResource)-getTime(b,timelineResource)})}function getPriorityScore(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){let priority=resource.priority;if(typeof priority=="string")return{stat:4,asap:3,urgent:2}[priority]??0}return 0}function getTime(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){if(resource.resourceType==="Communication"&&resource.sent)return new Date(resource.sent).getTime();if((resource.resourceType==="DiagnosticReport"||resource.resourceType==="Media"||resource.resourceType==="Observation")&&resource.issued)return new Date(resource.issued).getTime();if(resource.resourceType==="DocumentReference"&&resource.date)return new Date(resource.date).getTime()}let dateTime=resource.meta?.lastUpdated;return dateTime?new Date(dateTime).getTime():0}function isSameResourceType(a,b){return!!b&&a.resourceType===b.resourceType&&a.id===b.id}var ResourceTimeline_default={pinnedComment:"ResourceTimeline_pinnedComment"};import{jsx as jsx133,jsxs as jsxs89}from"react/jsx-runtime";function ResourceTimeline(props){let medplum=useMedplum42(),sender=medplum.getProfile(),inputRef=useRef13(null),resource=useResource11(props.value),[history,setHistory]=useState77(),[items,setItems]=useState77([]),[countToShow,setCountToShow]=useState77(10),loadTimelineResources=props.loadTimelineResources,itemsRef=useRef13(items);useLayoutEffect4(()=>{itemsRef.current=items});let sortAndSetItems=useCallback25(newItems=>{sortByDateAndPriority(newItems,resource),newItems.reverse(),setItems(newItems)},[resource]),handleBatchResponse=useCallback25(batchResponse=>{let newItems=[];for(let settledResult of batchResponse){if(settledResult.status!=="fulfilled")continue;let bundle=settledResult.value;if(bundle.type==="history"&&setHistory(bundle),bundle.entry)for(let entry of bundle.entry)newItems.push(entry.resource)}sortAndSetItems(newItems)},[sortAndSetItems]),addResource=useCallback25(resource2=>sortAndSetItems([...itemsRef.current,resource2]),[sortAndSetItems]),loadTimeline=useCallback25(()=>{let resourceType,id;"resourceType"in props.value?(resourceType=props.value.resourceType,id=props.value.id):[resourceType,id]=props.value.reference?.split("/"),loadTimelineResources(medplum,resourceType,id).then(handleBatchResponse).catch(console.error)},[medplum,props.value,loadTimelineResources,handleBatchResponse]);useEffect28(()=>loadTimeline(),[loadTimeline]);function createComment(contentString){!resource||!props.createCommunication||medplum.createResource(props.createCommunication(resource,sender,contentString)).then(result=>addResource(result)).catch(console.error)}function createMedia(attachment){!resource||!props.createMedia||medplum.createResource(props.createMedia(resource,sender,attachment)).then(result=>addResource(result)).then(()=>updateNotification({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:jsx133(IconCheck,{size:16}),autoClose:2e3})).catch(reason=>updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString11(reason),icon:jsx133(IconFileAlert,{size:16}),autoClose:2e3}))}function onUploadStart(){showNotification9({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function onUploadProgress(e){updateNotification({id:"upload-notification",loading:!0,title:"Uploading...",message:getProgressMessage(e),autoClose:!1,withCloseButton:!1})}function onUploadError(outcome){updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString11(outcome),icon:jsx133(IconFileAlert,{size:16}),autoClose:2e3})}if(!resource)return jsx133(Center4,{style:{width:"100%",height:"100%"},children:jsx133(Loader5,{})});let itemsToShow=items.filter(item=>item).slice(0,countToShow);return jsxs89(Timeline,{children:[props.createCommunication&&jsx133(Panel,{children:jsx133(Form,{testid:"timeline-form",onSubmit:formData=>{createComment(formData.text);let input=inputRef.current;input&&(input.value="",input.focus())},children:jsxs89(Group54,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[jsx133(ResourceAvatar,{value:sender}),jsx133(TextInput26,{name:"text",ref:inputRef,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),jsx133(ActionIcon14,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:jsx133(IconMessage,{size:16})}),jsx133(AttachmentButton,{securityContext:createReference14(resource),onUpload:createMedia,onUploadStart,onUploadProgress,onUploadError,children:props2=>jsx133(ActionIcon14,{...props2,radius:"xl",color:"blue",variant:"filled",children:jsx133(IconCloudUpload,{size:16})})})]})})}),itemsToShow.map(item=>{let key=`${item.resourceType}/${item.id}/${item.meta?.versionId}`,menu=props.getMenu?props.getMenu({primaryResource:resource,currentResource:item,reloadTimeline:loadTimeline}):void 0;if(item.resourceType===resource.resourceType&&item.id===resource.id)return jsx133(HistoryTimelineItem,{history,resource:item,popupMenuItems:menu},key);switch(item.resourceType){case"AuditEvent":return jsx133(AuditEventTimelineItem,{resource:item,popupMenuItems:menu},key);case"Communication":return jsx133(CommunicationTimelineItem,{resource:item,popupMenuItems:menu},key);case"DiagnosticReport":return jsx133(DiagnosticReportTimelineItem,{resource:item,popupMenuItems:menu},key);case"Media":return jsx133(MediaTimelineItem,{resource:item,popupMenuItems:menu},key);default:return jsx133(TimelineItem,{resource:item,padding:!0,children:jsx133(ResourceTable,{value:item,ignoreMissingValues:!0})},key)}}),countToShow<items.length&&jsx133(Group54,{justify:"center",pb:"lg",children:jsx133(Button14,{onClick:()=>setCountToShow(countToShow+10),children:"Show More"})})]})}function HistoryTimelineItem(props){let{history,resource,...rest}=props,previous=getPrevious(history,resource);return previous?jsx133(TimelineItem,{resource,padding:!0,...rest,children:jsx133(ResourceDiffTable,{original:previous,revised:props.resource})}):jsxs89(TimelineItem,{resource,padding:!0,...rest,children:[jsx133("h3",{children:"Created"}),jsx133(ResourceTable,{value:resource,ignoreMissingValues:!0,forceUseInput:!0})]})}function getPrevious(history,version){let entries=history.entry??[],index=entries.findIndex(entry=>entry.resource?.meta?.versionId===version.meta?.versionId);if(!(index>=entries.length-1))return entries[index+1].resource}function CommunicationTimelineItem(props){let className=!props.resource.priority||props.resource.priority==="routine"?void 0:ResourceTimeline_default.pinnedComment;return jsx133(TimelineItem,{resource:props.resource,profile:props.resource.sender,dateTime:props.resource.sent,padding:!0,className,popupMenuItems:props.popupMenuItems,children:jsx133("p",{children:props.resource.payload?.[0]?.contentString})})}function MediaTimelineItem(props){let contentType=props.resource.content?.contentType,padding=contentType&&!contentType.startsWith("image/")&&!contentType.startsWith("video/")&&contentType!=="application/pdf";return jsx133(TimelineItem,{resource:props.resource,padding:!!padding,popupMenuItems:props.popupMenuItems,children:jsx133(AttachmentDisplay,{value:props.resource.content})})}function AuditEventTimelineItem(props){return jsx133(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx133(ScrollArea4,{children:jsx133("pre",{children:props.resource.outcomeDesc})})})}function DiagnosticReportTimelineItem(props){return jsx133(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx133(DiagnosticReportDisplay,{value:props.resource})})}function getProgressMessage(e){if(e.lengthComputable){let percent=100*e.loaded/e.total;return`Uploaded: ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)} ${percent.toFixed(2)}%`}return`Uploaded: ${formatFileSize(e.loaded)}`}function formatFileSize(bytes){if(bytes===0)return"0.00 B";let e=Math.floor(Math.log(bytes)/Math.log(1024));return(bytes/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP".charAt(e)+"B"}import{jsx as jsx134}from"react/jsx-runtime";function DefaultResourceTimeline(props){let{resource,...rest}=props;return jsx134(ResourceTimeline,{value:resource,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`;return Promise.allSettled([medplum.readHistory(resourceType,id),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count:100})])},...rest})}import{createReference as createReference15}from"@medplum/core";import{jsx as jsx135}from"react/jsx-runtime";function EncounterTimeline(props){let{encounter,...rest}=props;return jsx135(ResourceTimeline,{value:encounter,loadTimelineResources:async(medplum,_resourceType,id)=>Promise.allSettled([medplum.readHistory("Encounter",id),medplum.search("Communication","encounter=Encounter/"+id),medplum.search("Media","encounter=Encounter/"+id)]),createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",encounter:createReference15(resource),subject:resource.subject,sender:createReference15(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",encounter:createReference15(resource),subject:resource.subject,operator:createReference15(operator),issued:new Date().toISOString(),content}),...rest})}import{Button as Button19,Loader as Loader7,Table as Table4}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome11}from"@medplum/core";import{useMedplum as useMedplum44}from"@medplum/react-hooks";import{memo,useEffect as useEffect32,useState as useState82}from"react";import{evalFhirPath}from"@medplum/core";import{jsx as jsx136}from"react/jsx-runtime";function FhirPathDisplay(props){let value;try{value=evalFhirPath(props.path,props.resource)}catch(err){return console.warn("FhirPathDisplay:",err),null}if(value.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${value.length} elements [${JSON.stringify(value,null,2)}]`);return jsx136(ResourcePropertyDisplay,{value:value[0]||"",propertyType:props.propertyType})}import{ActionIcon as ActionIcon16,Button as Button18,Center as Center5,Group as Group57,Loader as Loader6,Menu as Menu8,Pagination as Pagination2,Table as Table3,Text as Text41,UnstyledButton as UnstyledButton7}from"@mantine/core";import{DEFAULT_SEARCH_COUNT as DEFAULT_SEARCH_COUNT2,deepEquals as deepEquals2,formatSearchQuery,isDataTypeLoaded,normalizeOperationOutcome as normalizeOperationOutcome10}from"@medplum/core";import{useMedplum as useMedplum43}from"@medplum/react-hooks";import{useCallback as useCallback26,useEffect as useEffect31,useLayoutEffect as useLayoutEffect6,useRef as useRef16,useState as useState81}from"react";import{Box as Box20,Button as Button15,Modal as Modal12,Text as Text40}from"@mantine/core";import{jsx as jsx137,jsxs as jsxs90}from"react/jsx-runtime";function SearchExportDialog(props){return jsxs90(Modal12,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:[jsxs90(Box20,{display:"flex",style:{justifyContent:"space-between"},children:[props.exportCsv&&jsx137(ExportButton,{text:"CSV",exportLogic:props.exportCsv,onCancel:props.onCancel}),props.exportTransactionBundle&&jsx137(ExportButton,{text:"Transaction Bundle",exportLogic:props.exportTransactionBundle,onCancel:props.onCancel})]}),jsx137(Text40,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function ExportButton(props){return jsx137(Button15,{onClick:()=>{props.exportLogic(),props.onCancel()},children:`Export as ${props.text}`})}import{Button as Button16,Group as Group55,Modal as Modal13,MultiSelect as MultiSelect2,Stack as Stack38}from"@mantine/core";import{getDataType as getDataType2,getSearchParameters,sortStringArray,stringify as stringify3}from"@medplum/core";import{useEffect as useEffect29,useMemo as useMemo36,useRef as useRef14,useState as useState78}from"react";import{capitalize as capitalize6,DEFAULT_SEARCH_COUNT,evalFhirPathTyped as evalFhirPathTyped2,formatDateTime as formatDateTime5,Operator as Operator2}from"@medplum/core";import{Fragment as Fragment47,jsx as jsx138}from"react/jsx-runtime";var searchParamToOperators={string:[Operator2.EQUALS,Operator2.NOT,Operator2.CONTAINS,Operator2.EXACT],fulltext:[Operator2.EQUALS,Operator2.NOT,Operator2.CONTAINS,Operator2.EXACT],token:[Operator2.EQUALS,Operator2.NOT,Operator2.TEXT],reference:[Operator2.EQUALS,Operator2.NOT],numeric:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS],quantity:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS],date:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS,Operator2.STARTS_AFTER,Operator2.ENDS_BEFORE,Operator2.APPROXIMATELY],datetime:[Operator2.EQUALS,Operator2.NOT_EQUALS,Operator2.GREATER_THAN,Operator2.LESS_THAN,Operator2.GREATER_THAN_OR_EQUALS,Operator2.LESS_THAN_OR_EQUALS,Operator2.STARTS_AFTER,Operator2.ENDS_BEFORE,Operator2.APPROXIMATELY],uri:[Operator2.EQUALS,Operator2.NOT,Operator2.ABOVE,Operator2.BELOW]},operatorNames={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",sw:"starts with",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function setFilters(definition,filters){return{...definition,filters,offset:0,name:void 0}}function clearFilters(definition){return setFilters(definition,[])}function clearFiltersOnField(definition,code){return setFilters(definition,(definition.filters??[]).filter(f=>f.code!==code))}function addFilter(definition,field,op,value,opt_clear){opt_clear&&(definition=clearFiltersOnField(definition,field));let nextFilters=[];return definition.filters&&nextFilters.push(...definition.filters),nextFilters.push({code:field,operator:op,value:value??""}),setFilters(definition,nextFilters)}function addField(definition,field){if(definition.fields?.includes(field))return definition;let newFields=[];return definition.fields&&newFields.push(...definition.fields),newFields.push(field),{...definition,fields:newFields,name:void 0}}function deleteFilter(definition,index){if(!definition.filters)return definition;let newFilters=[...definition.filters];return newFilters.splice(index,1),{...definition,filters:newFilters,name:void 0}}function addYesterdayFilter(definition,field){return addDayFilter(definition,field,-1)}function addTodayFilter(definition,field){return addDayFilter(definition,field,0)}function addTomorrowFilter(definition,field){return addDayFilter(definition,field,1)}function addDayFilter(definition,field,delta){let startTime=new Date;startTime.setDate(startTime.getDate()+delta),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setDate(endTime.getDate()+1),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addNext24HoursFilter(definition,field){let now=new Date,endTime=new Date(now.getTime()+1440*60*1e3);return addDateFilterBetween(definition,field,now,endTime)}function addLastMonthFilter(definition,field){return addMonthFilter(definition,field,-1)}function addThisMonthFilter(definition,field){return addMonthFilter(definition,field,0)}function addNextMonthFilter(definition,field){return addMonthFilter(definition,field,1)}function addMonthFilter(definition,field,delta){let startTime=new Date;startTime.setMonth(startTime.getMonth()+delta),startTime.setDate(1),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setMonth(endTime.getMonth()+1),endTime.setDate(1),endTime.setHours(0,0,0,0),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addYearToDateFilter(definition,field){let startTime=new Date;return startTime.setMonth(0),startTime.setDate(1),startTime.setHours(0,0,0,0),addDateFilterBetween(definition,field,startTime,new Date)}function addDateFilterBetween(definition,field,d1,d2){return definition=clearFiltersOnField(definition,field),definition=addDateFilterImpl(definition,field,Operator2.GREATER_THAN_OR_EQUALS,d1),definition=addDateFilterImpl(definition,field,Operator2.LESS_THAN_OR_EQUALS,d2),definition}function addDateFilterImpl(definition,field,op,value){return addFilter(definition,field,op,value.toISOString())}function addMissingFilter(definition,field,value=!0){return addFilter(definition,field,Operator2.MISSING,value.toString())}function setOffset(definition,offset){return definition.offset===offset?definition:{...definition,offset,name:void 0}}function setPage(definition,page){let count=definition.count??DEFAULT_SEARCH_COUNT,newOffset=(page-1)*count;return setOffset(definition,newOffset)}function setSort(definition,sort,desc){return sort===getSortField(definition)&&desc!==void 0&&desc===isSortDescending(definition)?definition:{...definition,sortRules:[{code:sort,descending:!!desc}],name:void 0}}function toggleSort(definition,key){let desc=!1;return getSortField(definition)===key&&(desc=!isSortDescending(definition)),setSort(definition,key,desc)}function getSortField(definition){let sortRules=definition.sortRules;if(!sortRules||sortRules.length===0)return;let field=sortRules[0].code;return field.startsWith("-")?field.substr(1):field}function isSortDescending(definition){let sortRules=definition.sortRules;return!sortRules||sortRules.length===0?!1:!!sortRules[0].descending}function getSearchOperators(searchParam){return searchParamToOperators[searchParam.type]}function getOpString(op){return operatorNames[op]??""}function buildFieldNameString(key){let tmp=key;return tmp.includes(".")&&(tmp=tmp.split(".").pop()),tmp==="versionId"?"Version ID":(tmp=tmp.replace("[x]",""),tmp=tmp.replaceAll(/([A-Z])/g," $1"),tmp=tmp.replaceAll(/[-_]/g," "),tmp=tmp.replaceAll(/\s+/g," "),tmp=tmp.trim(),tmp.toLowerCase()==="id"?"ID":tmp.split(/\s/).map(capitalize6).join(" "))}function renderValue(resource,field){let key=field.name;return key==="id"?jsx138(MedplumLink,{to:`/${resource.resourceType}/${resource.id}`,children:resource.id}):key==="meta.versionId"?resource.meta?.versionId:key==="_lastUpdated"?formatDateTime5(resource.meta?.lastUpdated):`${resource.resourceType}.${field.name}`===field.elementDefinition?.path?renderPropertyValue(resource,field.elementDefinition):field.searchParams?.length===1&&field.name===field.searchParams[0].code?renderSearchParameterValue(resource,field.searchParams[0]):null}function renderPropertyValue(resource,elementDefinition){let path=elementDefinition.path?.split(".")?.pop()?.replaceAll("[x]","")??"",[value,propertyType]=getValueAndType({type:resource.resourceType,value:resource},path);return value?jsx138(ResourcePropertyDisplay,{path:elementDefinition.path,property:elementDefinition,propertyType,value,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function renderSearchParameterValue(resource,searchParam){let value=evalFhirPathTyped2(searchParam.expression,[{type:resource.resourceType,value:resource}]);return!value||value.length===0?null:jsx138(Fragment47,{children:value.map((v,index)=>jsx138(ResourcePropertyDisplay,{propertyType:v.type,value:v.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${index}-${value.length}`))})}import{jsx as jsx139,jsxs as jsxs91}from"react/jsx-runtime";function SearchFieldEditor(props){let wasDropdownOpen=useRef14(!1),[state,setState]=useState78({search:JSON.parse(stringify3(props.search))}),[isDropdownOpen,setIsDropdownOpen]=useState78(!1);useEffect29(()=>{setState({search:props.search})},[props.search]);let allFields=useMemo36(()=>{if(!props.visible)return[];let resourceType=props.search.resourceType,typeSchema=getDataType2(resourceType),searchParams=getSearchParameters(resourceType);return sortStringArray(getFieldsList(typeSchema,searchParams)).map(field=>({value:field,label:buildFieldNameString(field)}))},[props.visible,props.search.resourceType]);function handleChange(newFields){setState({search:{...state.search,fields:newFields}})}return jsx139(Modal13,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>{props.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{wasDropdownOpen.current=isDropdownOpen},onClick:()=>{wasDropdownOpen.current||props.onCancel(),wasDropdownOpen.current=!1},children:jsx139("div",{"data-testid":"overlay-child"})},children:jsxs91(Stack38,{children:[jsx139(MultiSelect2,{style:{width:550},placeholder:"Select fields to display",data:allFields,value:state.search.fields??[],onChange:handleChange,onDropdownOpen:()=>setIsDropdownOpen(!0),onDropdownClose:()=>setIsDropdownOpen(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),jsx139(Group55,{justify:"flex-end",children:jsx139(Button16,{onClick:()=>props.onOk(state.search),children:"OK"})})]})})}function getFieldsList(typeSchema,searchParams){let result=[],keys=new Set,names=new Set;for(let key of Object.keys(typeSchema.elements))result.push(key),keys.add(key.toLowerCase()),names.add(buildFieldNameString(key));if(searchParams)for(let code of Object.keys(searchParams)){let name=buildFieldNameString(code);!keys.has(code)&&!names.has(name)&&(result.push(code),keys.add(code),names.add(name))}return result}import{ActionIcon as ActionIcon15,Group as Group56,Modal as Modal14,NativeSelect as NativeSelect11}from"@mantine/core";import{Operator as Operator3,deepClone as deepClone2,getSearchParameters as getSearchParameters2}from"@medplum/core";import{useEffect as useEffect30,useLayoutEffect as useLayoutEffect5,useRef as useRef15,useState as useState79}from"react";import{Checkbox as Checkbox7,TextInput as TextInput27}from"@mantine/core";import{getSearchParameterDetails as getSearchParameterDetails2,SearchParameterType}from"@medplum/core";import{jsx as jsx140}from"react/jsx-runtime";function SearchFilterValueInput(props){let details=getSearchParameterDetails2(props.resourceType,props.searchParam),name=props.name??"filter-value";switch(details.type){case SearchParameterType.REFERENCE:return jsx140(ReferenceInput,{name,defaultValue:props.defaultValue?{reference:props.defaultValue}:void 0,targetTypes:props.searchParam.target,autoFocus:props.autoFocus,onChange:newReference=>{newReference?props.onChange(newReference.reference):props.onChange("")}});case SearchParameterType.BOOLEAN:return jsx140(Checkbox7,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultChecked:props.defaultValue==="true",autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.checked.toString())});case SearchParameterType.DATE:return jsx140(TextInput27,{type:"date",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType.DATETIME:return jsx140(DateTimeInput,{name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:props.onChange});case SearchParameterType.NUMBER:return jsx140(TextInput27,{type:"number",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType.QUANTITY:return jsx140(QuantityInput,{name,path:"",defaultValue:tryParseQuantity(props.defaultValue),autoFocus:props.autoFocus,onChange:newQuantity=>{newQuantity?props.onChange(`${newQuantity.value}`):props.onChange("")}});default:return jsx140(TextInput27,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value),placeholder:"Search value"})}}function tryParseQuantity(value){if(value){let[valueString,systemString,unitString]=value.split("|");if(valueString)return{value:Number.parseFloat(valueString),system:systemString,unit:unitString}}}import{jsx as jsx141,jsxs as jsxs92}from"react/jsx-runtime";function SearchFilterEditor(props){let[search,setSearch]=useState79(deepClone2(props.search)),searchRef=useRef15(search);useLayoutEffect5(()=>{searchRef.current=search}),useEffect30(()=>{setSearch(deepClone2(props.search))},[props.search]);function onAddFilter(filter){setSearch(addFilter(searchRef.current,filter.code,filter.operator,filter.value))}let resourceType=props.search.resourceType,searchParams=getSearchParameters2(resourceType)??{},filters=search.filters||[];return jsx141(Modal14,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:props.visible,onClose:props.onCancel,children:jsxs92(Form,{onSubmit:()=>props.onOk(searchRef.current),children:[jsxs92("div",{children:[jsxs92("table",{children:[jsxs92("colgroup",{children:[jsx141("col",{style:{width:200}}),jsx141("col",{style:{width:200}}),jsx141("col",{style:{width:380}}),jsx141("col",{style:{width:40}})]}),jsx141("thead",{children:jsxs92("tr",{children:[jsx141("th",{children:"Field"}),jsx141("th",{children:"Operation"}),jsx141("th",{children:"Value"}),jsx141("th",{})]})}),jsx141("tbody",{children:filters.map((filter,index)=>jsx141(FilterRowInput,{id:`filter-${index}-row`,resourceType,searchParams,value:filter,onChange:newFilter=>{let newFilters=[...filters];newFilters[index]=newFilter,setSearch(setFilters(searchRef.current,newFilters))},onDelete:()=>setSearch(deleteFilter(searchRef.current,index))},`filter-${index}-row`))})]}),jsx141(ArrayAddButton,{propertyDisplayName:"Filter",onClick:()=>onAddFilter({})})]}),jsx141(Group56,{justify:"flex-end",mt:"xl",children:jsx141(SubmitButton,{children:"OK"})})]})})}function FilterRowInput(props){let value=props.value;function setFilterCode(newCode){props.onChange({code:newCode,operator:Operator3.EQUALS,value:""})}function setFilterOperator(newOperator){props.onChange({code:value.code,operator:newOperator,value:""})}function setFilterValue(newFilterValue){props.onChange({code:value.code,operator:value.operator,value:newFilterValue})}let searchParam=props.searchParams[value.code],operators=searchParam&&getSearchOperators(searchParam);return jsxs92("tr",{children:[jsx141("td",{children:jsx141(NativeSelect11,{"data-testid":`${props.id}-filter-field`,defaultValue:props.value.code,onChange:e=>setFilterCode(e.currentTarget.value),data:["",...Object.keys(props.searchParams).map(param=>({value:param,label:buildFieldNameString(param)}))]})}),jsx141("td",{children:operators&&jsx141(NativeSelect11,{"data-testid":`${props.id}-filter-operation`,defaultValue:value.operator,onChange:e=>setFilterOperator(e.currentTarget.value),data:["",...operators.map(op=>({value:op,label:getOpString(op)}))]},`${props.id}-filter-value-${props.value.code}`)}),jsx141("td",{children:searchParam&&value.operator&&jsx141(SearchFilterValueInput,{name:`${props.id}-filter-value`,resourceType:props.resourceType,searchParam,defaultValue:value.value,onChange:setFilterValue},`${props.id}-filter-value-${props.value.code}-${props.value.operator}`)}),jsx141("td",{children:props.onDelete&&jsx141(ActionIcon15,{variant:"outline",color:"red",radius:"xl","aria-label":"Delete filter",onClick:props.onDelete,children:jsx141(IconX,{style:{width:"70%",height:"70%"},stroke:1.5})})})]})}import{Button as Button17,Grid,Modal as Modal15}from"@mantine/core";import{useState as useState80}from"react";import{jsx as jsx142,jsxs as jsxs93}from"react/jsx-runtime";function SearchFilterValueDialog(props){let[value,setValue]=useState80(props.defaultValue??"");if(!props.searchParam||!props.filter)return null;function onOk(){props.onOk({...props.filter,value})}return jsx142(Modal15,{title:props.title,size:"xl",opened:props.visible,onClose:props.onCancel,children:jsx142(Form,{onSubmit:onOk,children:jsxs93(Grid,{children:[jsx142(Grid.Col,{span:10,children:jsx142(SearchFilterValueInput,{resourceType:props.resourceType,searchParam:props.searchParam,defaultValue:value,autoFocus:!0,onChange:setValue})}),jsx142(Grid.Col,{span:2,children:jsx142(Button17,{onClick:onOk,fullWidth:!0,children:"OK"})})]})})})}import{formatDateTime as formatDateTime6,getSearchParameterDetails as getSearchParameterDetails3,globalSchema,Operator as Operator4,SearchParameterType as SearchParameterType2}from"@medplum/core";import{Fragment as Fragment48,jsx as jsx143}from"react/jsx-runtime";function SearchFilterValueDisplay(props){let{resourceType,filter}=props,searchParam=globalSchema.types[resourceType].searchParams?.[filter.code];if(searchParam){if(searchParam.type==="reference"&&(filter.operator===Operator4.EQUALS||filter.operator===Operator4.NOT_EQUALS))return jsx143(ResourceName,{value:{reference:filter.value}});let searchParamDetails=getSearchParameterDetails3(resourceType,searchParam);if(filter.code==="_lastUpdated"||searchParamDetails.type===SearchParameterType2.DATETIME)return jsx143(Fragment48,{children:formatDateTime6(filter.value)})}return jsx143(Fragment48,{children:filter.value})}import{Menu as Menu7}from"@mantine/core";import{Operator as Operator5}from"@medplum/core";import{Fragment as Fragment49,jsx as jsx144,jsxs as jsxs94}from"react/jsx-runtime";function SearchPopupMenu(props){if(!props.searchParams)return null;function onSort(searchParam,desc){onChange(setSort(props.search,searchParam.code,desc))}function onClear(searchParam){onChange(clearFiltersOnField(props.search,searchParam.code))}function onPrompt(searchParam,operator){props.onPrompt(searchParam,{code:searchParam.code,operator,value:""})}function onChange(definition){props.onChange(definition)}return props.searchParams.length===1?jsx144(SearchParameterSubMenu,{search:props.search,searchParam:props.searchParams[0],onSort,onPrompt,onChange,onClear}):jsx144(Menu7.Dropdown,{children:props.searchParams.map(searchParam=>jsx144(Menu7.Item,{children:buildFieldNameString(searchParam.code)},searchParam.code))})}function SearchParameterSubMenu(props){switch(props.searchParam.type){case"date":return jsx144(DateFilterSubMenu,{...props});case"number":case"quantity":return jsx144(NumericFilterSubMenu,{...props});case"reference":return jsx144(ReferenceFilterSubMenu,{...props});case"string":return jsx144(TextFilterSubMenu,{...props});case"token":return jsx144(TokenFilterSubMenu,{...props});case"uri":return jsx144(UriFilterSubMenu,{...props});default:return jsxs94(Fragment49,{children:["Unknown search param type: ",props.searchParam.type]})}}function DateFilterSubMenu(props){let{searchParam}=props,code=searchParam.code;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Oldest to Newest"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Newest to Oldest"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT_EQUALS),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.ENDS_BEFORE),children:"Before..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.STARTS_AFTER),children:"After..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconBracketsContain,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Between..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addTomorrowFilter(props.search,code)),children:"Tomorrow"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addTodayFilter(props.search,code)),children:"Today"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addYesterdayFilter(props.search,code)),children:"Yesterday"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addNext24HoursFilter(props.search,code)),children:"Next 24 Hours"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addNextMonthFilter(props.search,code)),children:"Next Month"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addThisMonthFilter(props.search,code)),children:"This Month"}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addLastMonthFilter(props.search,code)),children:"Last Month"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconCalendar,{size:14}),onClick:()=>props.onChange(addYearToDateFilter(props.search,code)),children:"Year to date"}),jsx144(CommonMenuItems,{...props})]})}function NumericFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Smallest to Largest"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Largest to Smallest"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT_EQUALS),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.GREATER_THAN),children:"Greater than..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.LESS_THAN),children:"Less than..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),jsx144(CommonMenuItems,{...props})]})}function ReferenceFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(CommonMenuItems,{...props})]})}function TextFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort A to Z"}),jsx144(Menu7.Item,{leftSection:jsx144(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Z to A"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconBucket,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.CONTAINS),children:"Contains..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconBucketOff,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Does not contain..."}),jsx144(CommonMenuItems,{...props})]})}function TokenFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.TEXT),children:"Text contains..."}),jsx144(CommonMenuItems,{...props})]})}function UriFilterSubMenu(props){let{searchParam}=props;return jsxs94(Menu7.Dropdown,{children:[jsx144(Menu7.Item,{leftSection:jsx144(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.EQUALS),children:"Equals..."}),jsx144(Menu7.Item,{leftSection:jsx144(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator5.NOT),children:"Does not equal..."}),jsx144(CommonMenuItems,{...props})]})}function CommonMenuItems(props){let{searchParam}=props,code=searchParam.code;return jsxs94(Fragment49,{children:[jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconBleach,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code)),children:"Missing"}),jsx144(Menu7.Item,{leftSection:jsx144(IconBleachOff,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code,!1)),children:"Not missing"}),jsx144(Menu7.Divider,{}),jsx144(Menu7.Item,{leftSection:jsx144(IconX,{size:14}),onClick:()=>props.onClear(searchParam),children:"Clear filters"})]})}function getPaginationControlProps(controlName){switch(controlName){case"next":return{"aria-label":"Next page"};case"previous":return{"aria-label":"Previous page"};case"first":return{"aria-label":"First page"};case"last":return{"aria-label":"Last page"};default:return{}}}var SearchControl_default={root:"SearchControl_root",table:"SearchControl_table",tr:"SearchControl_tr",th:"SearchControl_th",control:"SearchControl_control",icon:"SearchControl_icon"};import{getElementDefinition as getElementDefinition2,getSearchParameter,getSearchParameterDetails as getSearchParameterDetails4,getSearchParameters as getSearchParameters3}from"@medplum/core";function getFieldDefinitions(search){let resourceType=search.resourceType,fields=[];for(let name of search.fields||["id","_lastUpdated"])fields.push(getFieldDefinition(resourceType,name));return fields}function getFieldDefinition(resourceType,name){if(name==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(name==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};let exactElementDefinition=getElementDefinition2(resourceType,name),exactSearchParam=getSearchParameter(resourceType,name.toLowerCase());if(exactElementDefinition&&exactSearchParam)return{name,elementDefinition:exactElementDefinition,searchParams:[exactSearchParam]};if(exactElementDefinition){let allSearchParams=getSearchParameters3(resourceType),searchParams;if(allSearchParams){let pathRegex=new RegExp(`${resourceType}\\.${name.replaceAll("[x]","")}([^\\w-]|$)`);searchParams=Object.values(allSearchParams).filter(p=>!!p.expression&&pathRegex.test(p?.expression)),searchParams.length===0&&(searchParams=void 0)}return{name,elementDefinition:exactElementDefinition,searchParams}}if(exactSearchParam){let details=getSearchParameterDetails4(resourceType,exactSearchParam);return{name,elementDefinition:details.elementDefinitions?.[0],searchParams:[exactSearchParam]}}return{name}}import{Fragment as Fragment50,jsx as jsx145,jsxs as jsxs95}from"react/jsx-runtime";var SearchChangeEvent=class extends Event{constructor(definition){super("change");__publicField(this,"definition");this.definition=definition}},SearchLoadEvent=class extends Event{constructor(response){super("load");__publicField(this,"response");this.response=response}},SearchClickEvent=class extends Event{constructor(resource,browserEvent){super("click");__publicField(this,"resource");__publicField(this,"browserEvent");this.resource=resource,this.browserEvent=browserEvent}};function SearchControl(props){let medplum=useMedplum43(),[outcome,setOutcome]=useState81(),{search,onLoad}=props,[memoizedSearch,setMemoizedSearch]=useState81(search);deepEquals2(search,memoizedSearch)||setMemoizedSearch(search);let[state,setState]=useState81({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),stateRef=useRef16(state);useLayoutEffect6(()=>{stateRef.current=state});let total=memoizedSearch.total??"accurate",loadResults=useCallback26(options=>{setOutcome(void 0),medplum.requestSchema(memoizedSearch.resourceType).then(()=>medplum.search(memoizedSearch.resourceType,formatSearchQuery({...memoizedSearch,total,fields:void 0}),options)).then(response=>{setState({...stateRef.current,searchResponse:response}),onLoad&&onLoad(new SearchLoadEvent(response))}).catch(reason=>{setState({...stateRef.current,searchResponse:void 0}),setOutcome(normalizeOperationOutcome10(reason))})},[medplum,memoizedSearch,total,onLoad]),refreshResults=useCallback26(()=>{setState({...stateRef.current,searchResponse:void 0}),loadResults({cache:"reload"})},[loadResults]);useEffect31(()=>{loadResults()},[loadResults]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...stateRef.current.selected};checked?newSelected[id]=!0:delete newSelected[id],setState({...stateRef.current,selected:newSelected})}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},searchResponse=stateRef.current.searchResponse;checked&&searchResponse?.entry&&searchResponse.entry.forEach(entry=>{entry.resource?.id&&(newSelected[entry.resource.id]=!0)}),setState({...stateRef.current,selected:newSelected})}function isAllSelected(){if(!state.searchResponse?.entry||state.searchResponse.entry.length===0)return!1;for(let e of state.searchResponse.entry)if(e.resource?.id&&!state.selected[e.resource.id])return!1;return!0}function emitSearchChange(newSearch){props.onChange&&props.onChange(new SearchChangeEvent(newSearch))}function handleRowClick(e,resource){if(isCheckboxCell(e.target)||e.button===2)return;killEvent(e);let isAux=isAuxClick(e);!isAux&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),isAux&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e))}function isExportPassed(){return!!(props.onExport??props.onExportCsv??props.onExportTransactionBundle)}if(outcome)return jsx145(OperationOutcomeAlert,{outcome});if(!isDataTypeLoaded(memoizedSearch.resourceType))return jsx145(Center5,{style:{width:"100%",height:"100%"},children:jsx145(Loader6,{})});let checkboxColumn=props.checkboxesEnabled,fields=getFieldDefinitions(memoizedSearch),resourceType=memoizedSearch.resourceType,lastResult=state.searchResponse,resources=lastResult?.entry?.map(e=>e.resource),buttonVariant="subtle",buttonColor="gray",iconSize=16,isMobile=window.innerWidth<768;return jsxs95("div",{className:SearchControl_default.root,"data-testid":"search-control",children:[!props.hideToolbar&&jsxs95(Group57,{justify:"space-between",mb:"xl",children:[jsxs95(Group57,{gap:2,children:[jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconColumns,{size:iconSize}),onClick:()=>setState({...stateRef.current,fieldEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Fields"}),jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconFilter,{size:iconSize}),onClick:()=>setState({...stateRef.current,filterEditorVisible:!0,dialogOpenTime:Date.now()}),children:"Filters"}),props.onNew&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconFilePlus,{size:iconSize}),onClick:props.onNew,children:"New..."}),!isMobile&&isExportPassed()&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconTableExport,{size:iconSize}),onClick:props.onExport?props.onExport:()=>setState({...stateRef.current,exportDialogVisible:!0,dialogOpenTime:Date.now()}),children:"Export..."}),!isMobile&&props.onDelete&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconTrash,{size:iconSize}),onClick:()=>props.onDelete(Object.keys(state.selected)),children:"Delete..."}),!isMobile&&props.onBulk&&jsx145(Button18,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx145(IconBoxMultiple,{size:iconSize}),onClick:()=>props.onBulk(Object.keys(state.selected)),children:"Bulk..."})]}),jsxs95(Group57,{gap:2,children:[lastResult&&jsxs95(Text41,{size:"xs",c:"dimmed","data-testid":"count-display",children:[getStart(memoizedSearch,lastResult).toLocaleString(),"-",getEnd(memoizedSearch,lastResult).toLocaleString(),lastResult.total!==void 0&&` of ${memoizedSearch.total==="estimate"?"~":""}${lastResult.total?.toLocaleString()}`]}),jsx145(ActionIcon16,{variant:buttonVariant,color:buttonColor,title:"Refresh",onClick:refreshResults,children:jsx145(IconRefresh,{size:iconSize})})]})]}),jsxs95(Table3,{className:SearchControl_default.table,children:[jsxs95(Table3.Thead,{children:[jsxs95(Table3.Tr,{children:[checkboxColumn&&jsx145(Table3.Th,{children:jsx145("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx145(Table3.Th,{children:jsxs95(Menu8,{shadow:"md",width:240,position:"bottom-end",children:[jsx145(Menu8.Target,{children:jsx145(UnstyledButton7,{className:SearchControl_default.control,p:2,children:jsxs95(Group57,{justify:"space-between",wrap:"nowrap",children:[jsx145(Text41,{fw:500,children:buildFieldNameString(field.name)}),jsx145(Center5,{className:SearchControl_default.icon,children:jsx145(IconAdjustmentsHorizontal,{size:14,stroke:1.5})})]})})}),jsx145(SearchPopupMenu,{search:memoizedSearch,searchParams:field.searchParams,onPrompt:(searchParam,filter)=>{setState({...stateRef.current,filterDialogVisible:!0,filterDialogSearchParam:searchParam,filterDialogFilter:filter,dialogOpenTime:Date.now()})},onChange:result=>{emitSearchChange(result)}})]})},field.name))]}),!props.hideFilters&&jsxs95(Table3.Tr,{children:[checkboxColumn&&jsx145(Table3.Th,{}),fields.map(field=>jsx145(Table3.Th,{children:field.searchParams&&jsx145(FilterDescription,{resourceType,searchParams:field.searchParams,filters:memoizedSearch.filters})},field.name))]})]}),jsx145(Table3.Tbody,{children:resources?.map(resource=>resource&&jsxs95(Table3.Tr,{className:SearchControl_default.tr,"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx145(Table3.Td,{children:jsx145("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!state.selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx145(Table3.Td,{children:renderValue(resource,field)},field.name))]},resource.id))})]}),!resources?.length&&jsx145(Container,{children:jsx145(Center5,{style:{height:150},children:jsx145(Text41,{size:"xl",c:"dimmed",children:"No results"})})}),lastResult&&jsx145(Center5,{m:"md",p:"md",children:jsx145(Pagination2,{value:getPage(memoizedSearch),total:getTotalPages(memoizedSearch,lastResult),onChange:newPage=>emitSearchChange(setPage(memoizedSearch,newPage)),getControlProps:getPaginationControlProps})}),jsx145(SearchFieldEditor,{search:memoizedSearch,visible:state.fieldEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,fieldEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,fieldEditorVisible:!1})}},`search-field-editor-${state.dialogOpenTime}`),jsx145(SearchFilterEditor,{search:memoizedSearch,visible:state.filterEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,filterEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterEditorVisible:!1})}},`search-filter-editor-${state.dialogOpenTime}`),jsx145(SearchExportDialog,{visible:state.exportDialogVisible,exportCsv:props.onExportCsv,exportTransactionBundle:props.onExportTransactionBundle,onCancel:()=>{setState({...stateRef.current,exportDialogVisible:!1})}},`search-export-dialog-${state.dialogOpenTime}`),jsx145(SearchFilterValueDialog,{visible:state.filterDialogVisible,title:state.filterDialogSearchParam?.code?buildFieldNameString(state.filterDialogSearchParam.code):"",resourceType,searchParam:state.filterDialogSearchParam,filter:state.filterDialogFilter,defaultValue:"",onOk:filter=>{emitSearchChange(addFilter(memoizedSearch,filter.code,filter.operator,filter.value)),setState({...stateRef.current,filterDialogVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterDialogVisible:!1})}},`search-filter-dialog-${state.dialogOpenTime}`)]})}function FilterDescription(props){let filters=(props.filters??[]).filter(f=>props.searchParams.find(p=>p.code===f.code));return filters.length===0?jsx145("span",{children:"no filters"}):jsx145(Fragment50,{children:filters.map(filter=>jsxs95("div",{children:[getOpString(filter.operator),"\xA0",jsx145(SearchFilterValueDisplay,{resourceType:props.resourceType,filter})]},`filter-${filter.code}-${filter.operator}-${filter.value}`))})}function getPage(search){return Math.floor((search.offset??0)/(search.count??DEFAULT_SEARCH_COUNT2))+1}function getTotalPages(search,lastResult){let pageSize=search.count??DEFAULT_SEARCH_COUNT2,total=getTotal(search,lastResult);return Math.ceil(total/pageSize)}function getStart(search,lastResult){return Math.min(getTotal(search,lastResult),(search.offset??0)+1)}function getEnd(search,lastResult){return Math.max(getStart(search,lastResult)+(lastResult.entry?.length??0)-1,0)}function getTotal(search,lastResult){let total=lastResult.total;return total===void 0&&(total=(search.offset??0)+(lastResult.entry?.length??0)+(lastResult.link?.some(l=>l.relation==="next")?1:0)),total}import{jsx as jsx146,jsxs as jsxs96}from"react/jsx-runtime";function FhirPathTable(props){let medplum=useMedplum44(),[schemaLoaded,setSchemaLoaded]=useState82(!1),[outcome,setOutcome]=useState82(),{query,fields}=props,[response,setResponse]=useState82(),[selected,setSelected]=useState82({});useEffect32(()=>{setOutcome(void 0),medplum.graphql(query).then(setResponse).catch(err=>setOutcome(normalizeOperationOutcome11(err)))},[medplum,query]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...selected};checked?newSelected[id]=!0:delete newSelected[id],setSelected(newSelected)}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},resources=response?.data.ResourceList;checked&&resources&&resources.forEach(resource=>{resource.id&&(newSelected[resource.id]=!0)}),setSelected(newSelected)}function isAllSelected(){let resources=response?.data.ResourceList;if(!resources||resources.length===0)return!1;for(let resource of resources)if(resource.id&&!selected[resource.id])return!1;return!0}function handleRowClick(e,resource){isCheckboxCell(e.target)||(killEvent(e),e.button!==1&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),e.button===1&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e)))}if(useEffect32(()=>{medplum.requestSchema(props.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.resourceType]),!schemaLoaded)return jsx146(Loader7,{});let checkboxColumn=props.checkboxesEnabled;return jsxs96("div",{onContextMenu:e=>killEvent(e),"data-testid":"search-control",children:[jsxs96(Table4,{children:[jsx146(Table4.Thead,{children:jsxs96(Table4.Tr,{children:[checkboxColumn&&jsx146(Table4.Th,{children:jsx146("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx146(Table4.Th,{children:field.name},field.name))]})}),jsx146(Table4.Tbody,{children:response?.data.ResourceList.map(resource=>resource&&jsxs96(Table4.Tr,{"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx146(Table4.Td,{children:jsx146("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx146(Table4.Td,{children:jsx146(FhirPathDisplay,{propertyType:field.propertyType,path:field.fhirPath,resource})},field.name))]},resource.id))})]}),response?.data.ResourceList.length===0&&jsx146("div",{"data-testid":"empty-search",children:"No results"}),outcome&&jsx146("div",{"data-testid":"search-error",children:jsx146("pre",{style:{textAlign:"left"},children:JSON.stringify(outcome,void 0,2)})}),props.onBulk&&jsx146(Button19,{onClick:()=>props.onBulk(Object.keys(selected)),children:"Bulk..."})]})}var MemoizedFhirPathTable=memo(FhirPathTable);import{ScrollArea as ScrollArea5}from"@mantine/core";var InfoBar_default={root:"InfoBar_root",entry:"InfoBar_entry",key:"InfoBar_key",value:"InfoBar_value"};import{jsx as jsx147}from"react/jsx-runtime";function InfoBar(props){return jsx147(ScrollArea5,{children:jsx147("div",{className:InfoBar_default.root,children:props.children})})}InfoBar.Entry=function(props){return jsx147("div",{className:InfoBar_default.entry,children:props.children})};InfoBar.Key=function(props){return jsx147("div",{className:InfoBar_default.key,children:props.children})};InfoBar.Value=function(props){return jsx147("div",{className:InfoBar_default.value,children:props.children})};import{Anchor as Anchor11,Tabs as Tabs2}from"@mantine/core";import{isString,locationUtils as locationUtils5}from"@medplum/core";import{useMedplumNavigate as useMedplumNavigate6}from"@medplum/react-hooks";import{useState as useState83}from"react";var LinkTabs_default={list:"LinkTabs_list",link:"LinkTabs_link"};import{jsx as jsx148,jsxs as jsxs97}from"react/jsx-runtime";function LinkTabs(props){let{baseUrl,tabs:tabDefinitions,children,...rest}=props,tabs=normalizeTabDefinitions(tabDefinitions),navigate=useMedplumNavigate6(),[currentTab,setCurrentTab]=useState83(()=>{let tab=locationUtils5.getPathname().split("/").pop();return tab&&tabs.some(t=>t.value===tab)?tab:tabs[0].value});function onTabChange(newTabName){newTabName=newTabName||tabs[0].value,setCurrentTab(newTabName),navigate(`${baseUrl}/${newTabName}`)}return jsxs97(Tabs2,{value:currentTab.toLowerCase(),onChange:onTabChange,...rest,children:[jsx148(Tabs2.List,{className:LinkTabs_default.list,children:tabs.map(t=>jsx148(Tabs2.Tab,{value:t.value,children:jsx148(Anchor11,{className:LinkTabs_default.link,href:`${baseUrl}/${t.value}`,onClick:onLinkClick,children:t.label})},t.value))}),children]})}function normalizeTabDefinitions(tabs){return tabs.map(t=>isString(t)?{label:t,value:t.toLowerCase()}:t)}function onLinkClick(e){isAuxClick(e)||e.preventDefault()}import{Box as Box22,SimpleGrid as SimpleGrid2}from"@mantine/core";import{useResource as useResource12,useSearchOne}from"@medplum/react-hooks";import{Box as Box21,Flex as Flex20,Group as Group58,Paper as Paper5,RingProgress,Text as Text42,Title as Title12}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept5}from"@medplum/core";import{Fragment as Fragment51,jsx as jsx149,jsxs as jsxs98}from"react/jsx-runtime";function MeasureReportGroupDisplay(props){let{group}=props;return jsx149(Paper5,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:jsxs98(Group58,{children:[group.measureScore&&jsx149(MeasureScore,{group}),!group.measureScore&&jsx149(MeasureReportPopulation,{group})]})})}function MeasureTitle(props){let{measure}=props;return jsxs98(Fragment51,{children:[jsx149(Text42,{fz:"md",fw:500,mb:8,children:measure.title}),jsx149(Text42,{fz:"xs",c:"dimmed",mb:8,children:measure.subtitle})]})}function MeasureReportPopulation(props){let{group}=props,populations=group.population,numerator=populations?.find(p=>formatCodeableConcept5(p.code)==="numerator"),denominator=populations?.find(p=>formatCodeableConcept5(p.code)==="denominator"),numeratorCount=numerator?.count,denominatorCount=denominator?.count;if(denominatorCount===0)return jsxs98(Box21,{children:[jsx149(Title12,{order:3,children:"Not Applicable"}),jsx149(Text42,{children:`Denominator: ${denominatorCount}`})]});if(numeratorCount===void 0||denominatorCount===void 0)return jsxs98(Box21,{children:[jsx149(Title12,{order:3,children:"Insufficient Data"}),jsx149(Text42,{children:`Numerator: ${numeratorCount}`}),jsx149(Text42,{children:`Denominator: ${denominatorCount}`})]});let value=numeratorCount/denominatorCount*100;return jsx149(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value,color:groupColor(value)}],label:jsx149(Flex20,{justify:"center",children:jsxs98(Text42,{fw:700,fz:18,children:[numeratorCount," / ",denominatorCount]})})})}function MeasureScore(props){let{group}=props,unit=group.measureScore?.unit??group.measureScore?.code;return jsx149(Fragment51,{children:unit==="%"?jsx149(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value:groupValue(group),color:groupColor(group?.measureScore?.value??0)}],label:jsx149(Flex20,{justify:"center",children:jsx149(Text42,{fw:700,fz:18,children:jsx149(QuantityDisplay,{value:group.measureScore})})})}):jsx149(Flex20,{h:120,align:"center",children:jsx149(Title12,{order:3,children:jsx149(QuantityDisplay,{value:group.measureScore})})})})}function groupValue(group){let score=group.measureScore?.value,unit=group.measureScore?.unit;return score?score<=1&&unit==="%"?score*100:score:0}function groupColor(score){return score<=33?"red":score<=67?"yellow":"green"}import{jsx as jsx150,jsxs as jsxs99}from"react/jsx-runtime";function MeasureReportDisplay(props){let report=useResource12(props.measureReport),[measure]=useSearchOne("Measure",{url:report?.measure});return report?jsxs99(Box22,{children:[measure&&jsx150(MeasureTitle,{measure}),jsx150(SimpleGrid2,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:report.group?.map((group,idx)=>jsx150(MeasureReportGroupDisplay,{group},group.id??idx))})]}):null}import{ActionIcon as ActionIcon17,Indicator as Indicator2,Tooltip as Tooltip8}from"@mantine/core";import{useNotificationCount as useNotificationCount2}from"@medplum/react-hooks";import{jsx as jsx151}from"react/jsx-runtime";function NotificationIcon(props){let{resourceType,countCriteria,subscriptionCriteria}=props,unreadCount=useNotificationCount2({resourceType,countCriteria,subscriptionCriteria}),result=props.iconComponent;return props.onClick&&(result=jsx151(ActionIcon17,{variant:"subtle",color:"gray",size:"lg","aria-label":props.label,onClick:props.onClick,children:result})),props.tooltip&&(result=jsx151(Tooltip8,{label:props.tooltip,children:result})),unreadCount>0&&(result=jsx151(Indicator2,{inline:!0,label:unreadCount.toLocaleString(),size:16,offset:2,position:"bottom-end",color:"red",children:result})),result}import{ActionIcon as ActionIcon18,Alert as Alert5,Badge as Badge3,Box as Box23,Button as Button20,Checkbox as Checkbox8,Divider as Divider8,Group as Group59,Modal as Modal16,Stack as Stack39,Table as Table5,Text as Text43,Title as Title13}from"@mantine/core";import{notifications}from"@mantine/notifications";import{extractAccountReferences,normalizeErrorString as normalizeErrorString12}from"@medplum/core";import{useMedplum as useMedplum45}from"@medplum/react-hooks";import{useCallback as useCallback27,useMemo as useMemo37,useState as useState84}from"react";import{Fragment as Fragment52,jsx as jsx152,jsxs as jsxs100}from"react/jsx-runtime";var NOTIFICATION_ID="patient-accounts",NOTIFICATION_TITLE="Patient Accounts",ACCOUNT_TARGET_TYPES=["Organization","HealthcareService","CareTeam"];function PatientAccountsForm(props){let{patient}=props,medplum=useMedplum45(),isAdmin=medplum.isProjectAdmin()||medplum.isSuperAdmin(),originalAccounts=useMemo37(()=>extractAccountReferences(patient.meta)??[],[patient.meta]),[pendingAccounts,setPendingAccounts]=useState84(originalAccounts),[confirmModalOpen,setConfirmModalOpen]=useState84(!1),[propagate,setPropagate]=useState84(!0),[saving,setSaving]=useState84(!1),changes=useMemo37(()=>{let result=[];for(let account of pendingAccounts)originalAccounts.some(o=>o.reference===account.reference)||result.push({reference:account,type:"addition"});for(let account of originalAccounts)pendingAccounts.some(p=>p.reference===account.reference)||result.push({reference:account,type:"removal"});return result},[originalAccounts,pendingAccounts]),hasChanges=changes.length>0,handleAddAccount=useCallback27(value=>{value?.reference&&(pendingAccounts.some(a=>a.reference===value.reference)||setPendingAccounts(prev=>[...prev,value]))},[pendingAccounts]),handleRemoveAccount=useCallback27(referenceString=>{setPendingAccounts(prev=>prev.filter(a=>a.reference!==referenceString))},[]),handleSave=useCallback27(async()=>{let patientId=patient.id;if(!patientId){notifications.show({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"red",message:"Cannot update accounts: Patient resource has no ID.",icon:jsx152(IconX,{size:"1rem"}),autoClose:!1,withCloseButton:!0});return}setSaving(!0),setConfirmModalOpen(!1);let url=medplum.fhirUrl("Patient",patientId,"$set-accounts"),parameters={resourceType:"Parameters",parameter:[...pendingAccounts.map(account=>({name:"accounts",valueReference:{reference:account.reference}})),{name:"propagate",valueBoolean:propagate}]};notifications.show({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,loading:!0,message:propagate?"Saving account changes and propagating to compartment...":"Saving account changes...",autoClose:!1,withCloseButton:!1});try{let headers={};propagate&&(headers.Prefer="respond-async"),await medplum.post(url,parameters,void 0,{headers}),medplum.invalidateUrl(medplum.fhirUrl("Patient",patientId)),notifications.update({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"green",message:propagate?"Account changes saved. Compartment updates are being applied.":"Account changes saved.",icon:jsx152(IconCheck,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0}),props.onSaved?.()}catch(err){notifications.update({id:NOTIFICATION_ID,title:NOTIFICATION_TITLE,color:"red",message:normalizeErrorString12(err),icon:jsx152(IconX,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}finally{setSaving(!1)}},[medplum,patient,pendingAccounts,propagate,props]);return isAdmin?jsxs100(Fragment52,{children:[jsxs100(Stack39,{children:[jsx152(Title13,{order:3,children:"Current Accounts"}),pendingAccounts.length===0?jsx152(Text43,{c:"dimmed",children:"No accounts assigned to this patient."}):jsxs100(Table5,{children:[jsx152(Table5.Thead,{children:jsxs100(Table5.Tr,{children:[jsx152(Table5.Th,{children:"Type"}),jsx152(Table5.Th,{children:"Account"}),jsx152(Table5.Th,{})]})}),jsx152(Table5.Tbody,{children:pendingAccounts.map(account=>jsxs100(Table5.Tr,{children:[jsx152(Table5.Td,{children:jsx152(AccountTypeBadge,{reference:account})}),jsx152(Table5.Td,{children:jsx152(ResourceBadge,{value:account,link:!0})}),jsx152(Table5.Td,{children:jsx152(ActionIcon18,{variant:"subtle",color:"red","aria-label":`Remove ${account.reference}`,onClick:()=>handleRemoveAccount(account.reference),children:jsx152(IconX,{size:16})})})]},account.reference))})]}),jsx152(Divider8,{}),jsx152(Title13,{order:4,children:"Add Account"}),jsx152(ReferenceInput,{name:"newAccount",placeholder:"Search for Organization, HealthcareService, or CareTeam...",targetTypes:ACCOUNT_TARGET_TYPES,onChange:value=>{value&&handleAddAccount(value)}}),hasChanges&&jsxs100(Fragment52,{children:[jsx152(Divider8,{}),jsx152(Title13,{order:4,children:"Pending Changes"}),jsx152(Stack39,{gap:"xs",children:changes.map(change=>jsxs100(Group59,{gap:"xs",children:[change.type==="addition"?jsx152(Badge3,{color:"green",variant:"light",leftSection:jsx152(IconPlus,{size:12}),children:"Add"}):jsx152(Badge3,{color:"red",variant:"light",leftSection:jsx152(IconMinus,{size:12}),children:"Remove"}),jsx152(ResourceBadge,{value:change.reference,link:!0})]},`${change.type}-${change.reference.reference}`))})]}),jsx152(Box23,{children:jsx152(Button20,{disabled:!hasChanges||saving,onClick:()=>setConfirmModalOpen(!0),children:"Save Changes"})})]}),jsx152(Modal16,{opened:confirmModalOpen,onClose:()=>setConfirmModalOpen(!1),title:"Confirm Account Changes",size:"md",keepMounted:!0,children:jsxs100(Stack39,{children:[jsxs100(Text43,{children:["The following changes will be applied to Patient"," ",jsxs100("strong",{children:[patient.name?.[0]?.given?.join(" ")," ",patient.name?.[0]?.family]}),":"]}),changes.filter(c=>c.type==="addition").length>0&&jsxs100(Box23,{children:[jsx152(Text43,{fw:600,c:"green",children:"Adding:"}),jsx152(Stack39,{gap:"xs",mt:"xs",children:changes.filter(c=>c.type==="addition").map(c=>jsxs100(Group59,{gap:"xs",children:[jsx152(IconPlus,{size:14,color:"green"}),jsx152(ResourceBadge,{value:c.reference})]},c.reference.reference))})]}),changes.filter(c=>c.type==="removal").length>0&&jsxs100(Box23,{children:[jsx152(Text43,{fw:600,c:"red",children:"Removing:"}),jsx152(Stack39,{gap:"xs",mt:"xs",children:changes.filter(c=>c.type==="removal").map(c=>jsxs100(Group59,{gap:"xs",children:[jsx152(IconMinus,{size:14,color:"red"}),jsx152(ResourceBadge,{value:c.reference})]},c.reference.reference))})]}),jsx152(Checkbox8,{label:"Propagate changes to all resources in this patient's compartment",checked:propagate,onChange:event=>setPropagate(event.currentTarget.checked)}),jsxs100(Group59,{justify:"right",mt:"md",children:[jsx152(Button20,{variant:"default",onClick:()=>setConfirmModalOpen(!1),children:"Cancel"}),jsx152(Button20,{onClick:handleSave,loading:saving,children:"Confirm"})]})]})})]}):jsx152(Alert5,{color:"blue",title:"Admin access required",children:"You need project admin access to manage patient account assignments."})}function AccountTypeBadge({reference}){let type=reference.reference?.split("/")[0]??"Unknown";return jsx152(Badge3,{variant:"light",color:{Organization:"blue",HealthcareService:"teal",CareTeam:"violet"}[type]??"gray",size:"sm",children:type})}import{Group as Group60,SegmentedControl as SegmentedControl2,Stack as Stack40}from"@mantine/core";import{notifications as notifications2}from"@mantine/notifications";import{ContentType as ContentType3,normalizeErrorString as normalizeErrorString13,resolveId as resolveId2}from"@medplum/core";import{useMedplum as useMedplum46}from"@medplum/react-hooks";import{useCallback as useCallback28}from"react";import{jsx as jsx153,jsxs as jsxs101}from"react/jsx-runtime";var NOTIFICATION_ID2="patient-export",NOTIFICATION_TITLE2="Patient Export",formats={everything:{operation:"$everything",extension:"json",contentType:ContentType3.FHIR_JSON},summary:{operation:"$summary",extension:"json",contentType:ContentType3.FHIR_JSON},ccda:{operation:"$ccda-export",extension:"xml",contentType:ContentType3.CDA_XML},ccdaReferral:{operation:"$ccda-export",type:"referral",extension:"xml",contentType:ContentType3.CDA_XML}};function PatientExportForm(props){let medplum=useMedplum46(),{patient}=props,handleSubmit=useCallback28(async data2=>{let patientId=resolveId2(patient),format=data2.format,{operation,type,contentType,extension}=formats[format],url=medplum.fhirUrl("Patient",patientId,operation),params={};type&&(params.type=type),data2.author&&(params.author={reference:data2.author}),data2.authoredOn&&(params.authoredOn=convertLocalToIso(data2.authoredOn)),data2.startDate&&(params.start=data2.startDate),data2.endDate&&(params.end=data2.endDate),notifications2.show({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,loading:!0,message:"Exporting...",autoClose:!1,withCloseButton:!1});try{let response=await medplum.post(url,params,void 0,{cache:"no-cache",headers:{Accept:contentType}}),fileName=`Patient-export-${patientId}-${new Date().toISOString().replaceAll(":","-")}.${extension}`;saveData(response,fileName,contentType),notifications2.update({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,color:"green",message:"Done",icon:jsx153(IconCheck,{size:"1rem"}),loading:!1,autoClose:!0,withCloseButton:!0})}catch(err){notifications2.update({id:NOTIFICATION_ID2,title:NOTIFICATION_TITLE2,color:"red",message:normalizeErrorString13(err),icon:jsx153(IconX,{size:"1rem"}),loading:!1,autoClose:!1,withCloseButton:!0})}},[medplum,patient]);return jsx153(Form,{onSubmit:handleSubmit,children:jsxs101(Stack40,{children:[jsx153(FormSection,{title:"Export Format",description:"Required",withAsterisk:!0,children:jsx153(SegmentedControl2,{name:"format",data:[{label:"FHIR Everything",value:"everything"},{label:"Patient Summary",value:"summary"},{label:"C-CDA",value:"ccda"},{label:"C-CDA Referral",value:"ccdaReferral"}],fullWidth:!0})}),jsx153(FormSection,{title:"Author",description:"Optional author for composition. Default value is current user.",children:jsx153(ReferenceInput,{name:"author",placeholder:"Author",targetTypes:["Organization","Practitioner","PractitionerRole"]})}),jsx153(FormSection,{title:"Authored On",description:"Optional date for composition authored on. Default value is current date.",children:jsx153(DateTimeInput,{name:"authoredOn",placeholder:"Authored on"})}),jsx153(FormSection,{title:"Start Date",description:"The start date of care. If no start date is provided, all records prior to the end date are in scope.",children:jsx153(DateTimeInput,{name:"startDate",placeholder:"Start date"})}),jsx153(FormSection,{title:"End Date",description:"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.",children:jsx153(DateTimeInput,{name:"endDate",placeholder:"End date"})}),jsx153(Group60,{justify:"right",children:jsx153(SubmitButton,{children:"Request Export"})})]})})}function saveData(data2,fileName,contentType){let content=typeof data2=="string"?data2:JSON.stringify(data2,null,2),blob=new Blob([content],{type:contentType}),url=window.URL.createObjectURL(blob),a=document.createElement("a");document.body.appendChild(a),a.style.display="none",a.href=url,a.download=fileName,a.click(),window.URL.revokeObjectURL(url)}import{calculateAgeString as calculateAgeString2}from"@medplum/core";import{useResource as useResource13}from"@medplum/react-hooks";function getDefaultColor(patient){if(patient.gender==="male")return"blue";if(patient.gender==="female")return"pink"}import{Fragment as Fragment53,jsx as jsx154,jsxs as jsxs102}from"react/jsx-runtime";function PatientHeader(props){let patient=useResource13(props.patient);return patient?jsxs102(InfoBar,{children:[jsx154(ResourceAvatar,{value:patient,size:"lg",color:getDefaultColor(patient)}),jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Name"}),jsx154(InfoBar.Value,{children:jsx154(MedplumLink,{to:patient,fw:500,children:patient.name?jsx154(HumanNameDisplay,{value:patient.name[0],options:{use:!1}}):"[blank]"})})]}),patient.birthDate&&jsxs102(Fragment53,{children:[jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"DoB"}),jsx154(InfoBar.Value,{children:patient.birthDate})]}),jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Age"}),jsx154(InfoBar.Value,{children:calculateAgeString2(patient.birthDate)})]})]}),patient.gender&&jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"Gender"}),jsx154(InfoBar.Value,{children:patient.gender})]}),patient.address&&jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:"State"}),jsx154(InfoBar.Value,{children:patient.address[0]?.state})]}),patient.identifier?.map(identifier=>jsxs102(InfoBar.Entry,{children:[jsx154(InfoBar.Key,{children:identifier?.system}),jsx154(InfoBar.Value,{children:identifier?.value})]},`${identifier?.system}-${identifier?.value}`))]}):null}import{Box as Box24,Button as Button21,Checkbox as Checkbox9,Flex as Flex21,Group as Group61,Loader as Loader8,Radio as Radio5,Stack as Stack41,Text as Text44,TextInput as TextInput28}from"@mantine/core";import{showNotification as showNotification10}from"@mantine/notifications";import{formatAddress as formatAddress4,normalizeErrorString as normalizeErrorString14}from"@medplum/core";import{useCallback as useCallback29,useState as useState85}from"react";var PharmacyDialog_default={pharmacyItem:"PharmacyDialog_pharmacyItem",pharmacyItemSelected:"PharmacyDialog_pharmacyItemSelected"};import{jsx as jsx155,jsxs as jsxs103}from"react/jsx-runtime";function getPharmacyKey(pharmacy,index){return pharmacy.identifier?.[0]?.value||`pharmacy-${index}`}function SearchForm({onSearch,searching}){return jsx155("form",{onSubmit:e=>{e.preventDefault();let formData=new FormData(e.currentTarget);onSearch(formData)},children:jsxs103(Stack41,{gap:"md",children:[jsx155(TextInput28,{name:"name",label:"Pharmacy Name",placeholder:"Enter pharmacy name (min 3 chars)"}),jsxs103(Group61,{grow:!0,children:[jsx155(TextInput28,{name:"city",label:"City",placeholder:"City (min 3 chars)"}),jsx155(TextInput28,{name:"state",label:"State",placeholder:"State (min 3 chars)"})]}),jsxs103(Group61,{grow:!0,children:[jsx155(TextInput28,{name:"zip",label:"Zip Code",placeholder:"Zip code (min 3 chars)"}),jsx155(TextInput28,{name:"phoneOrFax",label:"Phone or Fax",placeholder:"Phone or fax number"})]}),jsx155(TextInput28,{name:"address",label:"Address",placeholder:"Street address (min 3 chars)"}),jsx155(TextInput28,{name:"ncpdpID",label:"NCPDP ID",placeholder:"National Council for Prescription Drug Programs ID"}),jsx155(Button21,{type:"submit",loading:searching,children:"Search"})]})})}function PharmacyItem({pharmacy,pharmacyKey,isSelected,onSelect}){return jsx155(Box24,{p:"sm",className:isSelected?PharmacyDialog_default.pharmacyItemSelected:PharmacyDialog_default.pharmacyItem,onClick:onSelect,children:jsx155(Radio5,{value:pharmacyKey,label:jsxs103(Box24,{children:[jsx155(Text44,{fw:500,size:"sm",children:pharmacy.name}),pharmacy.address?.[0]&&jsx155(Text44,{size:"xs",c:"dimmed",children:formatAddress4(pharmacy.address[0])}),pharmacy.telecom?.find(t=>t.system==="phone")&&jsxs103(Text44,{size:"xs",c:"dimmed",children:["Phone: ",pharmacy.telecom.find(t=>t.system==="phone")?.value]}),pharmacy.telecom?.find(t=>t.system==="fax")&&jsxs103(Text44,{size:"xs",c:"dimmed",children:["Fax: ",pharmacy.telecom.find(t=>t.system==="fax")?.value]})]})})},pharmacyKey)}function SearchResults({searchResults,selectedPharmacy,onSelectPharmacy,setAsPrimary,onSetAsPrimary,onAddFavorite,onClose,adding}){return jsxs103(Box24,{mt:"xl",children:[jsxs103(Text44,{fw:600,mb:"md",children:["Search Results (",searchResults.length,")"]}),jsx155(Radio5.Group,{value:selectedPharmacy?getPharmacyKey(selectedPharmacy,searchResults.indexOf(selectedPharmacy)):"",onChange:value=>{let selected=searchResults.find((p,i)=>getPharmacyKey(p,i)===value);selected&&onSelectPharmacy(selected)},children:jsx155(Stack41,{gap:"sm",children:searchResults.map((pharmacy,index)=>{let pharmacyKey=getPharmacyKey(pharmacy,index),isSelected=selectedPharmacy?getPharmacyKey(selectedPharmacy,searchResults.indexOf(selectedPharmacy))===pharmacyKey:!1;return jsx155(PharmacyItem,{pharmacy,pharmacyKey,isSelected,onSelect:()=>onSelectPharmacy(pharmacy)},pharmacyKey)})})}),jsxs103(Flex21,{mt:"lg",gap:"md",align:"center",justify:"space-between",children:[jsx155(Checkbox9,{label:"Set as primary pharmacy",checked:setAsPrimary,onChange:e=>onSetAsPrimary(e.currentTarget.checked)}),jsxs103(Group61,{children:[jsx155(Button21,{variant:"subtle",onClick:onClose,children:"Cancel"}),jsx155(Button21,{onClick:onAddFavorite,disabled:!selectedPharmacy,loading:adding,children:"Add to Favorites"})]})]})]})}function PharmacyDialog(props){let{patient,onSubmit,onClose,onSearch,onAddToFavorites}=props,[searchResults,setSearchResults]=useState85([]),[searching,setSearching]=useState85(!1),[selectedPharmacy,setSelectedPharmacy]=useState85(),[setAsPrimary,setSetAsPrimary]=useState85(!1),[adding,setAdding]=useState85(!1),handleSearch=useCallback29(async formData=>{let searchParams={name:formData.get("name")||void 0,city:formData.get("city")||void 0,state:formData.get("state")||void 0,zip:formData.get("zip")||void 0,address:formData.get("address")||void 0,phoneOrFax:formData.get("phoneOrFax")||void 0,ncpdpID:formData.get("ncpdpID")||void 0},cleanParams=Object.fromEntries(Object.entries(searchParams).filter(([_,v])=>typeof v=="string"&&v.trim()!==""));if(Object.keys(cleanParams).length===0){showNotification10({color:"yellow",title:"Search Required",message:"Please enter at least one search criterion"});return}setSearching(!0),setSelectedPharmacy(void 0);try{let results=await onSearch(cleanParams);setSearchResults(results),results.length===0&&showNotification10({color:"blue",title:"No Results",message:"No pharmacies found matching your search criteria"})}catch(error){showNotification10({color:"red",title:"Search Error",message:normalizeErrorString14(error)})}finally{setSearching(!1)}},[onSearch]),handleAddFavorite=useCallback29(async()=>{if(!(!selectedPharmacy||!patient.id)){setAdding(!0);try{let response=await onAddToFavorites({patientId:patient.id,pharmacy:selectedPharmacy,setAsPrimary});response.success?(showNotification10({color:"green",title:"Success",message:response.message}),onSubmit(response.organization||selectedPharmacy)):showNotification10({color:"red",title:"Error",message:response.message})}catch(error){showNotification10({color:"red",title:"Error",message:normalizeErrorString14(error)})}finally{setAdding(!1)}}},[selectedPharmacy,patient.id,setAsPrimary,onAddToFavorites,onSubmit]);return jsxs103(Box24,{children:[jsx155(SearchForm,{onSearch:formData=>handleSearch(formData).catch(console.error),searching}),searching&&jsx155(Flex21,{justify:"center",mt:"xl",children:jsx155(Loader8,{})}),searchResults.length>0&&!searching&&jsx155(SearchResults,{searchResults,selectedPharmacy,onSelectPharmacy:setSelectedPharmacy,setAsPrimary,onSetAsPrimary:setSetAsPrimary,onAddFavorite:handleAddFavorite,onClose,adding})]})}import{Box as Box25,Flex as Flex22,Group as Group62,Text as Text45}from"@mantine/core";import{getDisplayString as coreGetDisplayString}from"@medplum/core";import{jsx as jsx156,jsxs as jsxs104}from"react/jsx-runtime";function summaryResourceListSection(options){return{key:options.key,title:options.title,searches:[{key:options.key,resourceType:options.search.resourceType,patientParam:options.search.patientParam,query:options.search.query}],component:context=>jsx156(ResourceListDisplay,{options,resources:context.results[options.key]??[],context})}}function ResourceListDisplay(props){let{options,context}=props,resources=[...props.resources];return options.filter&&(resources=resources.filter(options.filter)),options.sort&&resources.sort(options.sort),jsx156(CollapsibleSection,{title:options.title,onAdd:options.onAdd,children:resources.length>0?jsx156(Flex22,{direction:"column",gap:8,children:resources.map(resource=>{let displayString=options.getDisplayString?options.getDisplayString(resource):coreGetDisplayString(resource),status=options.getStatus?.(resource),secondaryText=options.getSecondaryText?.(resource);return jsx156(SummaryItem,{onClick:()=>context.onClickResource?.(resource),children:jsxs104(Box25,{children:[jsx156(Text45,{fw:500,className:SummaryItem_default.itemText,children:displayString}),(status||secondaryText)&&jsxs104(Group62,{mt:2,gap:4,children:[status&&jsx156(StatusBadge,{color:status.color,variant:"light",status:status.label}),secondaryText&&jsx156(Text45,{size:"xs",fw:500,c:"dimmed",children:secondaryText})]})]})},resource.id)})}):jsx156(Text45,{children:"(none)"})})}import{createReference as createReference16}from"@medplum/core";import{useCallback as useCallback30}from"react";import{jsx as jsx157}from"react/jsx-runtime";function PatientTimeline(props){let{patient,...rest}=props,loadTimelineResources=useCallback30((medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("Patient",id),medplum.search("Communication",{subject:ref,_count}),medplum.search("Device",{patient:ref,_count}),medplum.search("DeviceRequest",{patient:ref,_count}),medplum.search("DiagnosticReport",{subject:ref,_count}),medplum.search("Media",{subject:ref,_count}),medplum.search("ServiceRequest",{subject:ref,_count}),medplum.search("Task",{subject:ref,_count})])},[]);return jsx157(ResourceTimeline,{value:patient,loadTimelineResources,createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",subject:createReference16(resource),sender:createReference16(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",subject:createReference16(resource),operator:createReference16(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor12,Box as Box26,Button as Button22,CloseButton as CloseButton2,Flex as Flex23,Group as Group63,Loader as Loader9,NativeSelect as NativeSelect12,Paper as Paper6,Stack as Stack42,Text as Text46,TextInput as TextInput29}from"@mantine/core";import{getReferenceString as getReferenceString12}from"@medplum/core";import{useMedplum as useMedplum47,useResource as useResource14}from"@medplum/react-hooks";import{useEffect as useEffect33,useState as useState86}from"react";var PlanDefinitionBuilder_default={section:"PlanDefinitionBuilder_section",hovering:"PlanDefinitionBuilder_hovering",editing:"PlanDefinitionBuilder_editing"};import{jsx as jsx158,jsxs as jsxs105}from"react/jsx-runtime";function PlanDefinitionBuilder(props){let medplum=useMedplum47(),defaultValue2=useResource14(props.value),[schemaLoaded,setSchemaLoaded]=useState86(!1),[selectedKey,setSelectedKey]=useState86(),[hoverKey,setHoverKey]=useState86(),[value,setValue]=useState86();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}if(useEffect33(()=>{medplum.requestSchema("PlanDefinition").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect33(()=>(setValue(ensurePlanDefinitionKeys(defaultValue2??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]),!schemaLoaded||!value)return null;function changeProperty(property,newValue){setValue(prevValue=>({...prevValue,[property]:newValue}))}return jsx158("div",{children:jsxs105(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx158(TextInput29,{label:"Plan Title",py:"md",defaultValue:value.title,onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx158(ActionArrayBuilder,{actions:value.action||[],selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:x=>changeProperty("action",x)}),jsx158(SubmitButton,{children:"Save"})]})})}function ActionArrayBuilder(props){function changeAction(changedAction){props.onChange(props.actions.map(i=>i.id===changedAction.id?changedAction:i))}function addAction(addedAction){props.onChange([...props.actions,addedAction]),props.setSelectedKey(addedAction.id)}function removeAction(removedAction){props.onChange(props.actions.filter(i=>i!==removedAction))}return jsxs105(Stack42,{gap:"md",className:PlanDefinitionBuilder_default.section,children:[props.actions.map(action=>jsx158(ActionBuilder,{action,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,setHoverKey:props.setHoverKey,onChange:changeAction,onRemove:()=>removeAction(action)},action.id)),jsx158("div",{children:jsx158(Button22,{variant:"outline",onClick:e=>{killEvent(e),addAction({id:generateId()})},children:"Add action"})})]})}function ActionBuilder(props){let{action}=props;function onClick(e){e.stopPropagation(),props.setSelectedKey(props.action.id)}function onHover(e){killEvent(e),props.setHoverKey(props.action.id)}return jsx158("div",{onClick,onMouseOver:onHover,onFocus:onHover,children:jsx158(ActionEditor,{action,onChange:props.onChange,selectedKey:props.selectedKey,hoverKey:props.hoverKey,onRemove:props.onRemove})})}function ActionEditor(props){let{action}=props,[actionType,setActionType]=useState86(),medplum=useMedplum47(),[loading,setLoading]=useState86(!1),[resource,setResource]=useState86(),editing=props.selectedKey===props.action.id,hovering=props.hoverKey===props.action.id;function changeProperty(property,value){props.onChange({...action,[property]:value})}let className=clsx_default(PlanDefinitionBuilder_default.section,{[PlanDefinitionBuilder_default.hovering]:hovering&&!editing});return useEffect33(()=>{(async()=>{if(!action.definitionCanonical)return;setLoading(!0);let resource2=await medplum.readCanonical(["Questionnaire","ActivityDefinition"],action.definitionCanonical);setActionType(getInitialActionType(resource2)),setResource(resource2),setLoading(!1)})().catch(console.error)},[action.definitionCanonical,medplum]),loading?jsx158(Loader9,{}):jsxs105(Paper6,{"data-testid":action.id,className,p:0,radius:"sm",withBorder:!0,children:[jsxs105(Flex23,{w:"100%",p:"xs",bg:"gray.0",gap:"md",align:"center",justify:"space-between",children:[jsx158(TextInput29,{w:"100%",name:`actionTitle-${action.id}`,defaultValue:action.title,placeholder:"Title",onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx158(CloseButton2,{"data-testid":"close-button",onClick:props.onRemove})]}),editing&&jsxs105(Stack42,{gap:"xl",p:"md",children:[jsx158(Box26,{children:jsx158(TextInput29,{label:"Task Description",placeholder:"Enter task description",name:`actionDescription-${action.id}`,defaultValue:action.description,onChange:e=>changeProperty("description",e.currentTarget.value)})}),jsx158(Box26,{children:jsx158(NativeSelect12,{label:"Type of Action",value:actionType,onChange:e=>{let value=e.currentTarget.value==="standard"?void 0:e.currentTarget.value;setActionType(value),props.onChange({...props.action,definitionCanonical:value==="standard"?void 0:props.action.definitionCanonical})},data:[{value:"standard",label:"Standard task"},{value:"questionnaire",label:"Task with Questionnaire"},{value:"activitydefinition",label:"Task with Activity Definition"}]})}),actionType==="questionnaire"&&jsxs105(Stack42,{gap:0,children:[jsxs105(Group63,{gap:0,mb:"xs",children:[jsx158(Text46,{fw:600,children:"Select questionnaire"}),jsx158(Text46,{c:"red",children:"*"})]}),jsxs105(Text46,{size:"sm",c:"dimmed",mb:"sm",children:["Questionnaire to be shown in the task in Encounter view. You can create new one from"," ",jsx158(Anchor12,{href:"/Questionnaire",target:"_blank",c:"blue",children:"questionnaires list"})]}),jsx158(ActionResourceTypeBuilder,{resource,resourceType:"Questionnaire",action,onChange:props.onChange,placeholder:"Search for questionnaire"})]}),actionType==="activitydefinition"&&jsxs105(Stack42,{gap:0,children:[jsxs105(Group63,{gap:0,mb:"xs",children:[jsx158(Text46,{fw:600,children:"Select activity definition"}),jsx158(Text46,{c:"red",children:"*"})]}),jsxs105(Text46,{size:"sm",c:"dimmed",mb:"sm",children:["ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from"," ",jsx158(Anchor12,{href:"/ActivityDefinition",target:"_blank",c:"blue",children:"activity definitions list"})]}),jsx158(ActionResourceTypeBuilder,{resource,resourceType:"ActivityDefinition",action,onChange:props.onChange,placeholder:"Search for activity definition"})]})]})]})}function ActionResourceTypeBuilder(props){let{id}=props.action,{resource}=props;return jsx158(ResourceInput,{name:id,placeholder:props.placeholder,resourceType:props.resourceType,defaultValue:resource,onChange:newValue=>{newValue?props.onChange({...props.action,definitionCanonical:"url"in newValue?newValue.url:void 0,definitionUri:"url"in newValue?void 0:getReferenceString12(newValue)}):props.onChange({...props.action,definitionCanonical:void 0})}})}function getInitialActionType(resource){return resource===void 0?"standard":resource.resourceType.toLowerCase()}var nextId=1;function generateId(existing){if(existing){if(existing.startsWith("id-")){let existingNum=Number.parseInt(existing.substring(3),10);Number.isNaN(existingNum)||(nextId=Math.max(nextId,existingNum+1))}return existing}return"id-"+nextId++}function ensurePlanDefinitionKeys(planDefinition){return{...planDefinition,action:ensurePlanDefinitionActionKeys(planDefinition.action)}}function ensurePlanDefinitionActionKeys(actions){if(actions)return actions.map(action=>({...action,id:generateId(action.id),action:ensurePlanDefinitionActionKeys(action.action)}))}import{Anchor as Anchor13,Box as Box27,Group as Group64,NativeSelect as NativeSelect13,Space,Textarea as Textarea5,TextInput as TextInput30,Title as Title14}from"@mantine/core";import{getElementDefinition as getElementDefinition3,isResource as isResourceType}from"@medplum/core";import{getQuestionnaireItemReferenceTargetTypes as getQuestionnaireItemReferenceTargetTypes2,isChoiceQuestion,QUESTIONNAIRE_ITEM_CONTROL_URL as QUESTIONNAIRE_ITEM_CONTROL_URL2,QuestionnaireItemType as QuestionnaireItemType4,setQuestionnaireItemReferenceTargetTypes,useMedplum as useMedplum48,useResource as useResource15}from"@medplum/react-hooks";import{useEffect as useEffect34,useLayoutEffect as useLayoutEffect7,useRef as useRef17,useState as useState87}from"react";var QuestionnaireBuilder_default={section:"QuestionnaireBuilder_section",hovering:"QuestionnaireBuilder_hovering",editing:"QuestionnaireBuilder_editing",questionBody:"QuestionnaireBuilder_questionBody",topActions:"QuestionnaireBuilder_topActions",bottomActions:"QuestionnaireBuilder_bottomActions",movementActions:"QuestionnaireBuilder_movementActions",movementIcons:"QuestionnaireBuilder_movementIcons",columnAlignment:"QuestionnaireBuilder_columnAlignment",linkIdInput:"QuestionnaireBuilder_linkIdInput",typeSelect:"QuestionnaireBuilder_typeSelect",preserveBreaks:"QuestionnaireBuilder_preserveBreaks"};import{Fragment as Fragment54,jsx as jsx159,jsxs as jsxs106}from"react/jsx-runtime";function QuestionnaireBuilder(props){let medplum=useMedplum48(),defaultValue2=useResource15(props.questionnaire),[schemaLoaded,setSchemaLoaded]=useState87(!1),[value,setValue]=useState87(),[selectedKey,setSelectedKey]=useState87(),[hoverKey,setHoverKey]=useState87();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}useEffect34(()=>{medplum.requestSchema("Questionnaire").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect34(()=>(setValue(ensureQuestionnaireKeys(defaultValue2??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]);let handleChange=(questionnaire2,disableSubmit)=>{setValue(questionnaire2),props.autoSave&&!disableSubmit&&props.onSubmit&&props.onSubmit(questionnaire2)};return!schemaLoaded||!value?null:jsx159("div",{children:jsxs106(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx159(ItemBuilder,{item:value,selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:handleChange}),jsx159(SubmitButton,{children:"Save"})]})})}function ItemBuilder(props){let resource=props.item,item=props.item,isResource4=isResourceType(props.item),isContainer=isResource4||item.type===QuestionnaireItemType4.group,linkId=item.linkId??"[untitled]",editing=props.selectedKey===props.item.id,hovering=props.hoverKey===props.item.id,itemRef=useRef17(props.item);useLayoutEffect7(()=>{itemRef.current=props.item});function onClick(e){killEvent(e),props.setSelectedKey(props.item.id)}function onHover(e){killEvent(e),props.setHoverKey(props.item.id)}function changeItem(changedItem){let curr=itemRef.current;props.onChange({...curr,item:curr.item?.map(i=>i.id===changedItem.id?changedItem:i)})}function addItem(addedItem,disableSubmit){props.onChange({...props.item,item:[...props.item.item??[],addedItem]},disableSubmit)}function removeItem(removedItem){props.onChange({...props.item,item:props.item.item?.filter(i=>i!==removedItem)})}function changeProperty(property,value){props.onChange({...itemRef.current,[property]:value})}function updateItem(updatedItem){props.onChange({...props.item,...updatedItem})}function toggleRepeatable(item2){props.onChange({...props.item,item:props.item.item?.map(i=>i===item2?{...i,repeats:!i.repeats}:i)})}function moveItem(itemIndex,delta){let updatedItems=reorderItems(props.item.item,itemIndex,delta);props.onChange({...props.item,item:updatedItems})}let className=clsx_default(QuestionnaireBuilder_default.section,{[QuestionnaireBuilder_default.editing]:editing,[QuestionnaireBuilder_default.hovering]:hovering&&!editing});return jsxs106("div",{"data-testid":item.linkId,className,onClick,onMouseOver:onHover,onFocus:onHover,children:[jsx159("div",{className:QuestionnaireBuilder_default.questionBody,children:editing?jsxs106(Fragment54,{children:[isResource4&&jsx159(TextInput30,{size:"xl",defaultValue:resource.title,onBlur:e=>changeProperty("title",e.currentTarget.value)}),!isResource4&&jsx159(Textarea5,{autosize:!0,minRows:2,defaultValue:item.text,onBlur:e=>changeProperty("text",e.currentTarget.value)}),item.type==="reference"&&jsx159(ReferenceProfiles,{item,onChange:updateItem}),isChoiceQuestion(item)&&jsx159(AnswerBuilder,{item,onChange:item2=>updateItem(item2)})]}):jsxs106(Fragment54,{children:[resource.title&&jsx159(Title14,{children:resource.title}),item.text&&jsx159("div",{className:QuestionnaireBuilder_default.preserveBreaks,children:item.text}),!isContainer&&jsx159(QuestionnaireFormItem,{item,index:0,required:!1,responseItem:{linkId:item.linkId}})]})}),item.item?.map((item2,i)=>jsx159("div",{children:jsx159(ItemBuilder,{item:item2,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,isFirst:i===0,isLast:i===(props.item.item??[]).length-1,setHoverKey:props.setHoverKey,onChange:changeItem,onRemove:()=>removeItem(item2),onRepeatable:toggleRepeatable,onMoveUp:()=>moveItem(i,-1),onMoveDown:()=>moveItem(i,1)})},item2.id)),!isContainer&&jsx159("div",{className:QuestionnaireBuilder_default.topActions,children:editing?jsxs106(Fragment54,{children:[jsx159(TextInput30,{size:"xs",className:QuestionnaireBuilder_default.linkIdInput,defaultValue:item.linkId,onBlur:e=>changeProperty("linkId",e.currentTarget.value)}),!isContainer&&jsx159(NativeSelect13,{size:"xs",className:QuestionnaireBuilder_default.typeSelect,defaultValue:item.type,onChange:e=>changeProperty("type",e.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):jsx159("div",{children:linkId})}),!isResource4&&jsx159(Box27,{className:QuestionnaireBuilder_default.movementActions,children:jsxs106(Box27,{className:QuestionnaireBuilder_default.columnAlignment,children:[!props.isFirst&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveUp&&props.onMoveUp()},children:jsx159(IconArrowUp,{"data-testid":"up-button",size:15,className:QuestionnaireBuilder_default.movementIcons})}),!props.isLast&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveDown&&props.onMoveDown()},children:jsx159(IconArrowDown,{"data-testid":"down-button",size:15,className:QuestionnaireBuilder_default.movementIcons})})]})}),jsxs106("div",{className:QuestionnaireBuilder_default.bottomActions,children:[isContainer&&jsxs106(Fragment54,{children:[jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId2(),linkId:generateLinkId("q"),type:"string",text:"Question"})},children:"Add item"}),jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId2(),linkId:generateLinkId("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),isResource4&&jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),addItem(createPage(),!0)},children:"Add Page"}),editing&&!isResource4&&jsxs106(Fragment54,{children:[jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onRepeatable&&props.onRepeatable(item)},children:item.repeats?"Remove Repeatable":"Make Repeatable"}),jsx159(Anchor13,{href:"#",onClick:e=>{e.preventDefault(),props.onRemove&&props.onRemove()},children:"Remove"})]})]})]})}function AnswerBuilder(props){let property=getElementDefinition3("QuestionnaireItemAnswerOption","value[x]"),options=props.item.answerOption??[];return jsxs106("div",{children:[props.item.answerValueSet!==void 0?jsx159(TextInput30,{placeholder:"Enter Value Set",defaultValue:props.item.answerValueSet,onChange:e=>props.onChange({...props.item,answerValueSet:e.target.value})}):jsx159(AnswerOptionsInput,{options,property,item:props.item,onChange:props.onChange}),jsxs106(Box27,{display:"flex",children:[jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerValueSet:void 0,answerOption:[...options,{id:generateId2()}]})},children:"Add choice"}),jsx159(Space,{w:"lg"}),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function AnswerOptionsInput(props){return jsx159("div",{children:props.options.map(option=>{let[propertyValue,propertyType]=getValueAndType({type:"QuestionnaireItemAnswerOption",value:option},"value");return jsxs106("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[jsx159("div",{children:jsx159(ResourcePropertyInput,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:props.property,defaultPropertyType:propertyType,defaultValue:propertyValue,onChange:(newValue,propName)=>{let newOptions=[...props.options],index=newOptions.findIndex(o=>o.id===option.id);newOptions[index]={id:option.id,[propName]:newValue},props.onChange({...props.item,answerOption:newOptions})},outcome:void 0},option.id)}),jsx159("div",{children:jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:props.options.filter(o=>o.id!==option.id)})},children:"Remove"})})]},option.id)})})}function ReferenceProfiles(props){let targetTypes=getQuestionnaireItemReferenceTargetTypes2(props.item)??[];return jsxs106(Fragment54,{children:[targetTypes.map((targetType,index)=>jsxs106(Group64,{children:[jsx159(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",defaultValue:targetType,onChange:newValue=>{props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.map(t=>t===targetType?newValue:t)))}}),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.filter(t=>t!==targetType)))},children:"Remove"})]},`${targetType}-${index}`)),jsx159(Anchor13,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,[...targetTypes,""]))},children:"Add Resource Type"})]})}var nextLinkId=1,nextId2=1;function generateLinkId(prefix){return prefix+nextLinkId++}function generateId2(){return"id-"+nextId2++}function ensureQuestionnaireKeys(questionnaire2){return{...questionnaire2,id:questionnaire2.id||generateId2(),item:ensureQuestionnaireItemKeys(questionnaire2.item)}}function ensureQuestionnaireItemKeys(items){if(items)return items.forEach(item=>{item.id?.match(/^id-\d+$/)&&(nextId2=Math.max(nextId2,Number.parseInt(item.id.substring(3),10)+1)),item.linkId?.match(/^q\d+$/)&&(nextLinkId=Math.max(nextLinkId,Number.parseInt(item.linkId.substring(1),10)+1))}),items.map(item=>({...item,id:item.id||generateId2(),item:ensureQuestionnaireItemKeys(item.item),answerOption:ensureQuestionnaireOptionKeys(item.answerOption)}))}function ensureQuestionnaireOptionKeys(options){if(options)return options.map(option=>({...option,id:option.id||generateId2()}))}function createPage(){return{id:generateId2(),linkId:generateLinkId("s"),type:"group",text:"New Page",extension:[{url:QUESTIONNAIRE_ITEM_CONTROL_URL2,valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function reorderItems(items,itemIndex,delta){let currentItems=items??[],newIndex=itemIndex+delta;if(newIndex<0||newIndex>=currentItems.length)return currentItems;let updatedItems=[...currentItems];return[updatedItems[itemIndex],updatedItems[newIndex]]=[updatedItems[newIndex],updatedItems[itemIndex]],updatedItems}import{Stack as Stack44}from"@mantine/core";import{useResource as useResource16}from"@medplum/react-hooks";import{Stack as Stack43,Text as Text47}from"@mantine/core";import{formatDate as formatDate4}from"@medplum/core";import{useMemo as useMemo38}from"react";import{Fragment as Fragment55,jsx as jsx160,jsxs as jsxs107}from"react/jsx-runtime";function QuestionnaireResponseItemDisplay(props){let{item}=props,{text:title,answer,item:nestedAnswers}=item,renderContent=useMemo38(()=>answer&&answer.length>0?jsx160(Fragment55,{children:answer.map((ans,index)=>jsx160(AnswerDisplay,{answer:ans},`answer-${index}`))}):nestedAnswers&&nestedAnswers.length>0?jsx160(Fragment55,{children:nestedAnswers.map((nestedAnswer,index)=>jsx160(QuestionnaireResponseItemDisplay,{item:nestedAnswer},`nested-${nestedAnswer.id??index}`))}):jsx160(Text47,{c:"dimmed",children:"No answer"}),[answer,nestedAnswers]);return jsxs107(Stack43,{gap:0,pb:"xs",children:[jsx160(Text47,{size:"lg",fw:600,id:item.id?`question-${item.id}`:void 0,component:"h3",children:title}),renderContent]})}function AnswerDisplay({answer}){if(!answer)return jsx160(Text47,{c:"dimmed",children:"Invalid answer"});let validEntries=Object.entries(answer).filter(([,value2])=>value2!=null);if(validEntries.length===0)return jsx160(Text47,{c:"dimmed",children:"No valid answer data"});let[key,value]=validEntries[0];switch(key){case"valueInteger":return jsx160(Text47,{children:value});case"valueQuantity":return jsx160(QuantityDisplay,{value});case"valueString":return jsx160(Text47,{children:value});case"valueCoding":return jsx160(CodeableConceptDisplay,{value:{coding:[value]}});case"valueRange":return jsx160(RangeDisplay,{value});case"valueDateTime":return jsx160(Text47,{children:formatDate4(value)});case"valueBoolean":return jsx160(Text47,{children:value?"True":"False"});case"valueReference":return jsx160(Text47,{children:value.display??value.reference});default:return jsx160(Text47,{children:value.toString()})}}import{jsx as jsx161}from"react/jsx-runtime";function QuestionnaireResponseDisplay(props){let questionnaireResponse=useResource16(props.questionnaireResponse);return jsx161(Stack44,{gap:0,children:questionnaireResponse?.item?.map((item,index)=>jsx161(QuestionnaireResponseItemDisplay,{item},`item-${item.id??index}`))})}import{ActionIcon as ActionIcon19,Divider as Divider9,Group as Group65,NativeSelect as NativeSelect14,Stack as Stack45,Text as Text48,TextInput as TextInput31}from"@mantine/core";import{formatRange as formatRange2,getCodeBySystem}from"@medplum/core";import{useEffect as useEffect35,useState as useState88}from"react";var ReferenceRangeEditor_default={section:"ReferenceRangeEditor_section"};import{jsx as jsx162,jsxs as jsxs108}from"react/jsx-runtime";var intervalFilters=["gender","age","gestationalAge","context","appliesTo","category"],defaultProps={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function ReferenceRangeEditor(props){props=Object.assign(defaultProps,props);let defaultDefinition=props.definition,[intervalGroups,setIntervalGroups]=useState88([]),[groupId,setGroupId]=useState88(1),[intervalId,setIntervalId]=useState88(1);return useEffect35(()=>{let definition=ensureQualifiedIntervalKeys(defaultDefinition,setIntervalId);setIntervalGroups(groupQualifiedIntervals(definition.qualifiedInterval||[],setGroupId))},[defaultDefinition]),jsxs108(Form,{testid:"reference-range-editor",onSubmit:submitDefinition,children:[jsx162(Stack45,{children:intervalGroups.map(intervalGroup=>jsx162(ReferenceRangeGroupEditor,{unit:getUnitString(defaultDefinition.quantitativeDetails?.unit),onChange:changeInterval,onAdd:addInterval,onRemove:removeInterval,onRemoveGroup:removeGroup,intervalGroup},`group-${intervalGroup.id}`))}),jsx162(ActionIcon19,{title:"Add Group",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),addGroup({id:`group-id-${groupId}`,filters:{},intervals:[]}),setGroupId(id=>id+1)},children:jsx162(IconCirclePlus,{})}),jsx162(Group65,{justify:"flex-end",children:jsx162(SubmitButton,{children:"Save"})})]});function submitDefinition(){let qualifiedInterval=intervalGroups.flatMap(group=>group.intervals).filter(interval=>!isEmptyInterval(interval));props.onSubmit({...defaultDefinition,qualifiedInterval})}function addGroup(addedGroup){setIntervalGroups(currentGroups=>[...currentGroups,addedGroup])}function removeGroup(removedGroup){setIntervalGroups(currentGroups=>currentGroups.filter(group=>group.id!==removedGroup.id))}function changeInterval(groupId2,changedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2),index=currentGroup?.intervals.findIndex(interval=>interval.id===changedInterval.id);return index!==void 0&¤tGroup?.intervals[index]&&(currentGroup.intervals[index]=changedInterval),groups})}function addInterval(groupId2,addedInterval){addedInterval.id===void 0&&(addedInterval.id=`id-${intervalId}`,setIntervalId(id=>id+1)),setIntervalGroups(groups=>{groups=[...groups];let currentGroupIndex=groups.findIndex(g=>g.id===groupId2);if(currentGroupIndex!==-1){let currentGroup={...groups[currentGroupIndex]};addedInterval={...addedInterval,...currentGroup.filters},currentGroup.intervals=[...currentGroup.intervals,addedInterval],groups[currentGroupIndex]=currentGroup}return groups})}function removeInterval(groupId2,removedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2);return currentGroup&&(currentGroup.intervals=currentGroup.intervals.filter(interval=>interval.id!==removedInterval.id)),groups})}}function ReferenceRangeGroupEditor(props){let{intervalGroup,unit}=props;return jsx162(Container,{"data-testid":intervalGroup.id,className:ReferenceRangeEditor_default.section,children:jsxs108(Stack45,{gap:"lg",children:[jsx162(Group65,{justify:"flex-end",children:jsx162(ActionIcon19,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${intervalGroup.id}`,size:"sm",onClick:e=>{killEvent(e),props.onRemoveGroup(intervalGroup)},children:jsx162(IconCircleMinus,{})},`remove-group-button-${intervalGroup.id}`)}),jsx162(ReferenceRangeGroupFilters,{intervalGroup,onChange:props.onChange}),jsx162(Divider9,{}),intervalGroup.intervals.map(interval=>jsxs108(Stack45,{gap:"xs",children:[jsxs108(Group65,{children:[jsx162(TextInput31,{"data-testid":`condition-${interval.id}`,defaultValue:interval.condition,label:"Condition: ",size:"sm",onChange:e=>{killEvent(e),props.onChange(intervalGroup.id,{...interval,condition:e.currentTarget.value.trim()})}},`condition-${interval.id}`),jsx162(ActionIcon19,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${interval.id}`,onClick:e=>{killEvent(e),props.onRemove(intervalGroup.id,interval)},children:jsx162(IconCircleMinus,{})},`remove-interval-${interval.id}`)]}),jsx162(RangeInput,{path:"",onChange:range=>{props.onChange(intervalGroup.id,{...interval,range})},name:`range-${interval.id}`,defaultValue:interval.range},`range-${interval.id}`)]},`interval-${interval.id}`)),jsx162(ActionIcon19,{title:"Add Interval",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),props.onAdd(intervalGroup.id,{range:{low:{unit},high:{unit}}})},children:jsx162(IconCirclePlus,{})})]})})}function ReferenceRangeGroupFilters(props){let{intervalGroup,onChange}=props,age=intervalGroup.filters.age??{},ageWithDefaults={low:age.low?.unit?age.low:{...age.low,unit:"years",system:"http://unitsofmeasure.org"},high:age.high?.unit?age.high:{...age.high,unit:"years",system:"http://unitsofmeasure.org"}};return jsxs108(Stack45,{style:{maxWidth:"50%"},children:[jsx162(Group65,{children:jsx162(NativeSelect14,{data:["","male","female"],label:"Gender:",defaultValue:intervalGroup.filters.gender||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newGender=e.currentTarget.value;newGender===""&&(newGender=void 0),onChange(intervalGroup.id,{...interval,gender:newGender})}}})}),jsxs108(Group65,{gap:"xs",children:[jsx162(Text48,{component:"label",htmlFor:`div-age-${intervalGroup.id}`,children:"Age:"}),jsx162("div",{id:`div-age-${intervalGroup.id}`,children:jsx162(RangeInput,{path:"",name:`age-${intervalGroup.id}`,defaultValue:ageWithDefaults,onChange:ageRange=>{for(let interval of intervalGroup.intervals)onChange(intervalGroup.id,{...interval,age:ageRange})}},`age-${intervalGroup.id}`)})]}),jsx162(NativeSelect14,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:intervalGroup.filters.context?.text||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newEndocrine=e.currentTarget.value;newEndocrine===""?(newEndocrine=void 0,onChange(intervalGroup.id,{...interval,context:void 0})):onChange(intervalGroup.id,{...interval,context:{text:newEndocrine,coding:[{code:newEndocrine,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),jsx162(NativeSelect14,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:intervalGroup.filters.category,onChange:e=>{for(let interval of intervalGroup.intervals){let newCategory=e.currentTarget.value;newCategory===""?onChange(intervalGroup.id,{...interval,category:void 0}):onChange(intervalGroup.id,{...interval,category:newCategory})}}})]})}function ensureQualifiedIntervalKeys(definition,setIntervalId){let intervals=definition.qualifiedInterval||[],nextId3=Math.max(...intervals.map(interval=>{let existingNum=Number.parseInt(interval.id?.substring(3)||"",10);return Number.isNaN(existingNum)?Number.NEGATIVE_INFINITY:existingNum}))+1;return Number.isFinite(nextId3)||(nextId3=1),definition={...definition,qualifiedInterval:intervals.map(interval=>({...interval,id:interval.id||`id-${nextId3++}`}))},setIntervalId(nextId3),definition}function groupQualifiedIntervals(intervals,setGroupId){let groupId=1,groups={};for(let interval of intervals){let groupKey=generateGroupKey(interval);groupKey in groups||(groups[groupKey]={id:`group-id-${groupId++}`,filters:Object.fromEntries(intervalFilters.map(f=>[f,interval[f]])),intervals:[]}),groups[groupKey].intervals.push(interval)}return setGroupId(groupId),Object.values(groups)}function generateGroupKey(interval){return[`gender=${interval.gender}`,`age=${formatRange2(interval.age)}`,`gestationalAge=${formatRange2(interval.gestationalAge)}`,`context=${interval.context?.text}`,`appliesTo=${interval.appliesTo?.map(c=>c.text).join("+")}`,`category=${interval.category}`].join(":")}function getUnitString(unit){return unit&&(getCodeBySystem(unit,"http://unitsofmeasure.org")||unit.text)}function isEmptyInterval(interval){return interval.range?.low?.value===void 0&&interval.range?.high?.value===void 0}import{Button as Button23,Grid as Grid2,Text as Text49}from"@mantine/core";import{formatDateTime as formatDateTime7,getReferenceString as getReferenceString13}from"@medplum/core";import{useMedplum as useMedplum49,useResource as useResource17}from"@medplum/react-hooks";import{Fragment as Fragment56,useEffect as useEffect36,useState as useState89}from"react";import{jsx as jsx163,jsxs as jsxs109}from"react/jsx-runtime";function RequestGroupDisplay(props){let medplum=useMedplum49(),requestGroup=useResource17(props.value),[startedLoading,setStartedLoading]=useState89(!1),[responseBundle,setResponseBundle]=useState89();if(useEffect36(()=>{requestGroup&&!startedLoading&&(medplum.executeBatch(buildBatchRequest(requestGroup)).then(setResponseBundle).catch(console.log),setStartedLoading(!0))},[medplum,requestGroup,startedLoading]),!requestGroup||!responseBundle)return null;return jsx163(Grid2,{children:requestGroup.action?.map((action,index)=>{let task=action.resource&&findBundleEntry(action.resource),taskInput=task?.input?.[0]?.valueReference,taskOutput=task?.output?.[0]?.valueReference;return jsxs109(Fragment56,{children:[jsx163(Grid2.Col,{span:1,p:"md",children:task?.status==="completed"?jsx163(IconCheckbox,{}):jsx163(IconSquare,{color:"gray"})}),jsxs109(Grid2.Col,{span:9,p:"xs",children:[jsx163(Text49,{fw:500,children:action.title}),action.description&&jsx163("div",{children:action.description}),jsxs109("div",{children:["Last edited by\xA0",jsx163(ResourceName,{value:task?.meta?.author}),"\xA0on\xA0",formatDateTime7(task?.meta?.lastUpdated)]}),jsxs109("div",{children:["Status: ",jsx163(StatusBadge,{status:task?.status||"unknown"})]})]}),jsxs109(Grid2.Col,{span:2,p:"md",children:[taskInput&&!taskOutput&&jsx163(Button23,{onClick:()=>props.onStart(task,taskInput),children:"Start"}),taskInput&&taskOutput&&jsx163(Button23,{onClick:()=>props.onEdit(task,taskInput,taskOutput),children:"Edit"})]})]},`action-${index}`)})});function buildBatchRequest(request){let batchEntries=[];if(request.action)for(let action of request.action)action.resource?.reference&&batchEntries.push({request:{method:"GET",url:action.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:batchEntries}}function findBundleEntry(reference){for(let entry of responseBundle?.entry??[])if(entry.resource&&reference.reference===getReferenceString13(entry.resource))return entry.resource}}import{useMedplum as useMedplum50}from"@medplum/react-hooks";import{useEffect as useEffect37,useState as useState90}from"react";import{stringify as stringify4}from"@medplum/core";function diff(original,revised){let path=buildPath(original,revised);return buildRevisions(path,original,revised)}function buildPath(orig,rev){let N=orig.length,M=rev.length,MAX=N+M+1,size=1+2*MAX,middle=Math.trunc(size/2),diagonal=new Array(size);diagonal[middle+1]={i:0,j:-1,prev:void 0,snake:!0};for(let d=0;d<MAX;d++){for(let k=-d;k<=d;k+=2){let kmiddle=middle+k,kplus=kmiddle+1,kminus=kmiddle-1,kplusNode=diagonal[kplus],kminusNode=diagonal[kminus],prev,i=0;k===-d||k!==d&&kminusNode.i<kplusNode.i?(i=kplusNode.i,prev=kplusNode):(i=kminusNode.i+1,prev=kminusNode),diagonal[kminus]=void 0;let j=i-k,node={i,j,prev:previousSnake(prev),snake:!1};for(;i<N&&j<M&&orig[i]===rev[j];)i++,j++;if(i>node.i&&(node={i,j,prev:node,snake:!0}),diagonal[kmiddle]=node,i>=N&&j>=M)return diagonal[kmiddle]}diagonal[middle+d-1]=void 0}}function buildRevisions(startNode,orig,rev){let deltas=[],path=startNode;for(path.snake&&(path=path.prev);path?.prev&&path.prev.j>=0;){let i=path.i,j=path.j;path=path.prev;let ianchor=path.i,janchor=path.j,original={position:ianchor,lines:orig.slice(ianchor,i)},revised={position:janchor,lines:rev.slice(janchor,j)},type;original.lines.length===0&&revised.lines.length>0?type="insert":original.lines.length>0&&revised.lines.length===0?type="delete":type="change",deltas.push({original,revised,type}),path.snake&&(path=path.prev)}return deltas}function previousSnake(node){return node&&!node.snake&&node.prev?node.prev:node}function blame(history){let versions=(history.entry??[]).filter(entry=>!!entry.resource).map(entry=>({meta:entry.resource?.meta,lines:stringify4(entry.resource,!0).match(/[^\r\n]+/g)})).sort((a,b)=>a.meta.lastUpdated.localeCompare(b.meta.lastUpdated));if(!versions.length)return[];let table=versions[0].lines.map(line=>({id:versions[0].meta.versionId,meta:versions[0].meta,value:line,span:1}));return compareVersions(table,versions),combineSpans(table),table}function compareVersions(table,versions){for(let i=1;i<versions.length;i++){let revisions=diff(versions[i-1].lines,versions[i].lines);for(let revision of revisions){let position=revision.original.position,oldLines=revision.original.lines,newLines=revision.revised.lines;if((revision.type==="delete"||revision.type==="change")&&table.splice(position,oldLines.length),revision.type==="insert"||revision.type==="change")for(let k=0;k<revision.revised.lines.length;k++)table.splice(position+k,0,{id:versions[i].meta.versionId,meta:versions[i].meta,value:newLines[k],span:1})}}}function combineSpans(table){let start=0;for(;start<table.length;){let curr=start;for(;curr<table.length&&table[curr].id===table[start].id;)table[curr].span=-1,curr++;table[start].span=curr-start,start=curr}}var ResourceBlame_default={container:"ResourceBlame_container",root:"ResourceBlame_root",startRow:"ResourceBlame_startRow",normalRow:"ResourceBlame_normalRow",author:"ResourceBlame_author",dateTime:"ResourceBlame_dateTime",lineNumber:"ResourceBlame_lineNumber",line:"ResourceBlame_line",pre:"ResourceBlame_pre"};function getVersionUrl(resource,versionId){return`/${resource.resourceType}/${resource.id}/_history/${versionId}`}function getTimeString(lastUpdated){let seconds=Math.floor((Date.now()-Date.parse(lastUpdated))/1e3),years=Math.floor(seconds/31536e3);if(years>0)return pluralizeTime(years,"year");let months=Math.floor(seconds/2592e3);if(months>0)return pluralizeTime(months,"month");let days=Math.floor(seconds/86400);if(days>0)return pluralizeTime(days,"day");let hours=Math.floor(seconds/3600);if(hours>0)return pluralizeTime(hours,"hour");let minutes=Math.floor(seconds/60);return minutes>0?pluralizeTime(minutes,"minute"):pluralizeTime(seconds,"second")}function pluralizeTime(count,noun){return`${count} ${count===1?noun:noun+"s"} ago`}import{Fragment as Fragment57,jsx as jsx164,jsxs as jsxs110}from"react/jsx-runtime";function ResourceBlame(props){let medplum=useMedplum50(),[value,setValue]=useState90(props.history);if(useEffect37(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),!value)return jsx164("div",{children:"Loading..."});let resource=value.entry?.[0]?.resource;if(!resource)return null;let table=blame(value);return jsx164("div",{className:ResourceBlame_default.container,children:jsx164("table",{className:ResourceBlame_default.root,children:jsx164("tbody",{children:table.map((row,index)=>jsxs110("tr",{className:row.span>0?ResourceBlame_default.startRow:ResourceBlame_default.normalRow,children:[row.span>0&&jsxs110(Fragment57,{children:[jsx164("td",{className:ResourceBlame_default.author,rowSpan:row.span,children:jsx164(ResourceName,{value:row.meta.author,link:!0,fz:"xs"})}),jsx164("td",{className:ResourceBlame_default.dateTime,rowSpan:row.span,children:jsx164(MedplumLink,{to:getVersionUrl(resource,row.meta.versionId),fz:"xs",children:getTimeString(row.meta.lastUpdated)})})]}),jsx164("td",{className:ResourceBlame_default.lineNumber,children:index+1}),jsx164("td",{className:ResourceBlame_default.line,children:jsx164("pre",{className:ResourceBlame_default.pre,children:row.value})})]},"row-"+index))})})})}import{stringify as stringify5}from"@medplum/core";var ResourceDiff_default={removed:"ResourceDiff_removed",added:"ResourceDiff_added"};import{Fragment as Fragment58,jsx as jsx165,jsxs as jsxs111}from"react/jsx-runtime";function ResourceDiff(props){let originalResource=props.original,revisedResource=props.revised;props.ignoreMeta&&(originalResource={...originalResource,meta:void 0},revisedResource={...revisedResource,meta:void 0});let original=stringify5(originalResource,!0).match(/[^\r\n]+/g)??["{","}"],revised=stringify5(revisedResource,!0).match(/[^\r\n]+/g)??["{","}"],deltas=diff(original,revised);return jsx165("pre",{style:{color:"gray"},children:deltas.map((delta,index)=>jsx165(ChangeDiff,{delta},"delta"+index))})}function ChangeDiff(props){return jsxs111(Fragment58,{children:["...",jsx165("br",{}),props.delta.original.lines.length>0&&jsx165("div",{className:ResourceDiff_default.removed,children:props.delta.original.lines.join(`
|
|
110
110
|
`)}),props.delta.revised.lines.length>0&&jsx165("div",{className:ResourceDiff_default.added,children:props.delta.revised.lines.join(`
|
|
111
|
-
`)}),"...",jsx165("br",{})]})}import{ActionIcon as ActionIcon20,Alert as Alert6,Button as Button24,Group as Group66,Menu as Menu9,Stack as Stack46,TextInput as TextInput32,useMantineTheme}from"@mantine/core";import{AccessPolicyInteraction as AccessPolicyInteraction2,applyDefaultValuesToResource,canWriteResourceType,isPopulated as isPopulated11,satisfiedAccessPolicy as satisfiedAccessPolicy2,tryGetProfile as tryGetProfile5}from"@medplum/core";import{useMedplum as useMedplum51,useResource as useResource18}from"@medplum/react-hooks";import{useEffect as useEffect38,useMemo as useMemo38,useState as useState91}from"react";var ResourceForm_default={splitButton:"ResourceForm_splitButton",menuControl:"ResourceForm_menuControl"};import{jsx as jsx166,jsxs as jsxs112}from"react/jsx-runtime";function ResourceForm(props){let{outcome}=props,medplum=useMedplum51(),defaultValue2=useResource18(props.defaultValue),resourceType=defaultValue2?.resourceType,[schemaLoaded,setSchemaLoaded]=useState91(!1),[value,setValue]=useState91(),accessPolicy=medplum.getAccessPolicy(),theme=useMantineTheme();useEffect38(()=>{if(defaultValue2)if(props.profileUrl){let profileUrl=props.profileUrl;medplum.requestProfileSchema(props.profileUrl,{expandProfile:!0}).then(()=>{let profile=tryGetProfile5(profileUrl);if(profile){setSchemaLoaded(!0);let modifiedDefaultValue=applyDefaultValuesToResource(defaultValue2,profile);setValue(modifiedDefaultValue)}else console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)})}else medplum.requestSchema(resourceType).then(()=>{setValue(defaultValue2),setSchemaLoaded(!0)}).catch(console.log)},[medplum,defaultValue2,resourceType,props.profileUrl]);let accessPolicyResource=useMemo38(()=>defaultValue2&&satisfiedAccessPolicy2(defaultValue2,AccessPolicyInteraction2.READ,accessPolicy),[accessPolicy,defaultValue2]),canWrite=useMemo38(()=>medplum.isSuperAdmin()||!accessPolicy||!isPopulated11(value?.resourceType)?!0:canWriteResourceType(accessPolicy,value?.resourceType),[medplum,accessPolicy,value?.resourceType]);return!schemaLoaded||!value?jsx166("div",{children:"Loading..."}):canWrite?jsxs112("form",{noValidate:!0,autoComplete:"off",onSubmit:e=>{e.preventDefault(),props.onSubmit&&props.onSubmit(value)},children:[jsxs112(Stack46,{mb:"xl",children:[jsx166(FormSection,{title:"Resource Type",htmlFor:"resourceType",outcome,children:jsx166(TextInput32,{name:"resourceType",defaultValue:value.resourceType,disabled:!0})}),jsx166(FormSection,{title:"ID",htmlFor:"id",outcome,children:jsx166(TextInput32,{name:"id",defaultValue:value.id,disabled:!0})})]}),jsx166(BackboneElementInput,{path:value.resourceType,valuePath:value.resourceType,typeName:resourceType,defaultValue:value,outcome,onChange:setValue,profileUrl:props.profileUrl,accessPolicyResource}),jsxs112(Group66,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[jsx166(Button24,{type:"submit",className:clsx_default((props.onPatch||props.onDelete)&&ResourceForm_default.splitButton),children:defaultValue2?.id?"Update":"Create"}),(props.onPatch||props.onDelete)&&jsxs112(Menu9,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[jsx166(Menu9.Target,{children:jsx166(ActionIcon20,{variant:"filled",color:theme.primaryColor,size:36,className:ResourceForm_default.menuControl,"aria-label":"More actions",children:jsx166(IconChevronDown,{size:14,stroke:1.5})})}),jsxs112(Menu9.Dropdown,{children:[props.onPatch&&jsx166(Menu9.Item,{leftSection:jsx166(IconEdit,{size:14,stroke:1.5}),onClick:()=>{props.onPatch(value)},children:"Patch"}),props.onDelete&&jsx166(Menu9.Item,{color:"red",leftSection:jsx166(IconTrash,{size:14,stroke:1.5,color:"red"}),onClick:()=>{props.onDelete(value)},children:"Delete"})]})]})]})]}):jsxs112(Alert6,{color:"red",title:"Permission denied",icon:jsx166(IconAlertCircle,{}),children:["Your access level prevents you from editing and creating ",value.resourceType," resources."]})}import{Table as Table6}from"@mantine/core";import{formatDateTime as formatDateTime8,normalizeErrorString as normalizeErrorString15}from"@medplum/core";import{useMedplum as useMedplum52}from"@medplum/react-hooks";import{useEffect as useEffect39,useState as useState92}from"react";import{jsx as jsx167,jsxs as jsxs113}from"react/jsx-runtime";function ResourceHistoryTable(props){let medplum=useMedplum52(),[value,setValue]=useState92(props.history);return useEffect39(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),value?jsxs113(Table6,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[jsx167(Table6.Thead,{children:jsxs113(Table6.Tr,{children:[jsx167(Table6.Th,{children:"Author"}),jsx167(Table6.Th,{children:"Date"}),jsx167(Table6.Th,{children:"Version"})]})}),jsx167(Table6.Tbody,{children:value.entry?.map((entry,index)=>jsx167(HistoryRow,{entry},"entry-"+index))})]}):jsx167("div",{children:"Loading..."})}function HistoryRow(props){let{response,resource}=props.entry;return resource?jsxs113(Table6.Tr,{children:[jsx167(Table6.Td,{children:jsx167(ResourceBadge,{value:resource.meta?.author,link:!0})}),jsx167(Table6.Td,{children:formatDateTime8(resource.meta?.lastUpdated)}),jsx167(Table6.Td,{children:jsx167(MedplumLink,{to:getVersionUrl2(resource),children:resource.meta?.versionId})})]}):jsx167(Table6.Tr,{children:jsx167(Table6.Td,{colSpan:3,children:normalizeErrorString15(response?.outcome)})})}function getVersionUrl2(resource){return`/${resource.resourceType}/${resource.id}/_history/${resource.meta?.versionId}`}import{Button as Button25,Loader as Loader10,Stack as Stack47,Text as Text50}from"@mantine/core";import{showNotification as showNotification11}from"@mantine/notifications";import{getReferenceString as getReferenceString14,isReference as isReference4,isResource as isResource3,normalizeErrorString as normalizeErrorString16}from"@medplum/core";import{useMedplum as useMedplum53}from"@medplum/react-hooks";import{useEffect as useEffect40,useMemo as useMemo39,useState as useState93}from"react";var Scheduler_default={container:"Scheduler_container",info:"Scheduler_info",selection:"Scheduler_selection"};import{jsx as jsx168,jsxs as jsxs114}from"react/jsx-runtime";function onlyPractitioner(schedule){let refs=schedule.actor.filter(ref=>isReference4(ref,"Practitioner"));if(refs.length===1)return refs[0]}function Scheduler(props){let medplum=useMedplum53(),[month,setMonth]=useState93(getStartMonth()),[date,setDate]=useState93(),[actor,setActor]=useState93(),[slots,setSlots]=useState93(),[selectedSlot,setSelectedSlot]=useState93(),handleSelectSlot=slot=>{setSelectedSlot(slot),props.onSelectSlot?.(slot)};useEffect40(()=>{props.schedule||setSlots([]),(props.fetchSlots??(async period=>{let scheduleArray=[];if(!Array.isArray(props.schedule))scheduleArray.push(isReference4(props.schedule,"Schedule")?props.schedule.reference:getReferenceString14(props.schedule));else for(let schedule of props.schedule)if(isReference4(schedule))scheduleArray.push(schedule.reference);else{let scheduleRef=getReferenceString14(schedule);scheduleArray.push(scheduleRef)}let slotSearchParams=new URLSearchParams([["_count","720"],["schedule",scheduleArray.join(",")],["start","gt"+period.start],["start","lt"+period.end]]);return medplum.searchResources("Slot",slotSearchParams)}))({start:getStart2(month),end:getEnd2(month)}).then(setSlots).catch(console.error)},[medplum,props.schedule,props.fetchSlots,month]),useEffect40(()=>{props.schedule&&!Array.isArray(props.schedule)&&(isResource3(props.schedule)?setActor(onlyPractitioner(props.schedule)):medplum.readReference(props.schedule).then(schedule=>setActor(onlyPractitioner(schedule))).catch(error=>{showNotification11({color:"red",title:"Error",message:normalizeErrorString16(error)})}))},[medplum,props.schedule]);let startTimeToSlotMap=useMemo39(()=>{if(!date)return null;let sortedSlots=(slots||[]).filter(slot=>new Date(slot.start).getTime()>date.getTime()&&new Date(slot.start).getTime()<date.getTime()+24*3600*1e3).sort((a,b)=>new Date(a.start).getTime()-new Date(b.start).getTime()),startTimeToSlotMap2=new Map;for(let slot of sortedSlots)startTimeToSlotMap2.set(formatTime(new Date(slot.start)),slot);return startTimeToSlotMap2},[slots,date]);return slots?jsxs114("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:[jsxs114("div",{className:Scheduler_default.info,children:[actor&&jsx168(ResourceAvatar,{value:actor,size:"xl"}),actor&&jsx168(Text50,{size:"xl",fw:500,children:jsx168(ResourceName,{value:actor})}),jsx168("p",{children:"1 hour"}),date&&jsx168("p",{children:date.toLocaleDateString()}),selectedSlot&&jsx168("p",{children:formatTime(new Date(selectedSlot.start))})]}),jsxs114("div",{className:Scheduler_default.selection,children:[!date&&jsxs114("div",{children:[jsx168("h3",{children:"Select date"}),jsx168(CalendarInput,{slots,onChangeMonth:setMonth,onClick:setDate})]}),date&&!selectedSlot&&jsxs114("div",{children:[jsx168("h3",{children:"Select time"}),jsx168(Stack47,{children:Array.from(startTimeToSlotMap?.entries()??[]).map(([startTime,slot])=>jsx168("div",{children:jsx168(Button25,{variant:"outline",style:{width:150},onClick:()=>handleSelectSlot(slot),children:startTime})},slot.id))})]}),props.children]})]}):jsx168("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:jsx168(Loader10,{})})}function getStart2(month){return formatSlotInstant(month.getTime())}function getEnd2(month){return formatSlotInstant(month.getTime()+744*60*60*1e3)}function formatSlotInstant(time){let date=new Date(Math.max(Date.now(),time));return date.setHours(0,0,0,0),date.toISOString()}function formatTime(date){return date.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}import{createReference as createReference17}from"@medplum/core";import{jsx as jsx169}from"react/jsx-runtime";function ServiceRequestTimeline(props){let{serviceRequest,...rest}=props;return jsx169(ResourceTimeline,{value:serviceRequest,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("ServiceRequest",id),medplum.search("Communication",{"based-on":ref,_count}),medplum.search("DiagnosticReport",{"based-on":ref,_count}),medplum.search("Media",{"based-on":ref,_count}),medplum.search("DocumentReference",{related:ref,_count}),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count})])},createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",basedOn:[createReference17(resource)],subject:resource.subject,sender:createReference17(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",basedOn:[createReference17(resource)],subject:resource.subject,operator:createReference17(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor14}from"@mantine/core";import{showNotification as showNotification12}from"@mantine/notifications";import{ensureTrailingSlash,normalizeErrorString as normalizeErrorString17}from"@medplum/core";import{useMedplum as useMedplum54,useResource as useResource19}from"@medplum/react-hooks";import{jsx as jsx170}from"react/jsx-runtime";function SmartAppLaunchLink(props){let medplum=useMedplum54(),{client,patient,encounter,children,...rest}=props,patientResource=useResource19(patient),encounterResource=useResource19(encounter);function launchApp(){let patientRef=patient,encounterRef=encounter;if(client.launchIdentifierSystems?.length){let patientIdentifierConfig=client.launchIdentifierSystems.find(config=>config.resourceType==="Patient");if(patientRef&&patientResource&&patientIdentifierConfig?.system){let identifier=patientResource.identifier?.find(i=>i.system===patientIdentifierConfig.system);identifier&&(patientRef={...patient,identifier})}let encounterIdentifierConfig=client.launchIdentifierSystems.find(config=>config.resourceType==="Encounter");if(encounterRef&&encounterResource&&encounterIdentifierConfig?.system){let identifier=encounterResource.identifier?.find(i=>i.system===encounterIdentifierConfig.system);identifier&&(encounterRef={...encounter,identifier})}}medplum.createResource({resourceType:"SmartAppLaunch",patient:patientRef,encounter:encounterRef,fhirContext:props.fhirContext}).then(result=>{let url=new URL(client.launchUri);url.searchParams.set("iss",ensureTrailingSlash(medplum.fhirUrl().toString())),url.searchParams.set("launch",result.id),window.open(url.toString(),"_blank")}).catch(err=>showNotification12({color:"red",message:normalizeErrorString17(err),autoClose:!1}))}return jsx170(Anchor14,{onClick:()=>launchApp(),...rest,children})}export{AddressDisplay,AddressInput,AllergiesSection,AnnotationInput,AppShell,AsyncAutocomplete,AttachmentArrayDisplay,AttachmentArrayInput,AttachmentButton,AttachmentDisplay,AttachmentInput,BackboneElementDisplay,BackboneElementInput,BaseChat,CalendarInput,ChangePasswordForm,ChatList,ChatListItem,ChatModal,CheckboxFormSection,CodeInput,CodeableConceptDisplay,CodeableConceptInput,CodingDisplay,CodingInput,ContactDetailDisplay,ContactDetailInput,ContactPointDisplay,ContactPointInput,Container,DateTimeInput,DefaultResourceItemComponent,DefaultResourceTimeline,DemographicsSection,DescriptionList,DescriptionListEntry,DiagnosticReportDisplay,Document,ElementDefinitionInputSelector,ElementDefinitionTypeInput,EncounterTimeline,ErrorBoundary,FhirPathTable,Form,FormSection,Header,HumanNameDisplay,HumanNameInput,IdentifierDisplay,IdentifierInput,InfoBar,InsuranceSection,LabsSection,LinkTabs,Loading,Logo,MeasureReportDisplay,MedicationsSection,MedplumLink,MemoizedFhirPathTable,MfaForm,MoneyDisplay,MoneyInput,MultiResourceInput,Navbar,NewTopicDialog,NoteDisplay,NotificationIcon,ObservationTable,OperationOutcomeAlert,PATIENT_PREFERRED_PHARMACY_URL,PHARMACY_PREFERENCE_TYPE_SYSTEM,PHARMACY_TYPE_PREFERRED,PHARMACY_TYPE_PRIMARY,Panel,ParticipantFilter,PatientAccountsForm,PatientExportForm,PatientHeader,PatientSummary,PatientTimeline,Pharmacies,PharmaciesSection,PharmacyDialog,PlanDefinitionBuilder,ProblemListSection,QuantityDisplay,QuantityInput,QuestionnaireBuilder,QuestionnaireForm,QuestionnaireResponseDisplay,RangeDisplay,RangeInput,RatioInput,ReferenceDisplay,ReferenceInput,ReferenceRangeEditor,ReferenceRangeGroupEditor,RegisterForm,RequestGroupDisplay,ResetPasswordForm,ResourceArrayDisplay,ResourceArrayInput,ResourceAvatar,ResourceBadge,ResourceBlame,ResourceDiff,ResourceDiffTable,ResourceForm,ResourceHistoryTable,ResourceInput,ResourceName,ResourcePropertyDisplay,ResourcePropertyInput,ResourceTable,ResourceTimeline,Scheduler,SearchChangeEvent,SearchClickEvent,SearchControl,SearchFieldEditor,SearchFilterEditor,SearchLoadEvent,ServiceRequestTimeline,SetPasswordForm,SexualOrientationSection,SignInForm,SignatureInput,SmartAppLaunchLink,SmokingStatusSection,Spotlight,StatusBadge,SubmitButton,ThreadChat,ThreadInbox,Timeline,TimelineItem,TimingInput,ValueSetAutocomplete,VitalsSection,addDateFilterBetween,addField,addFilter,addLastMonthFilter,addMissingFilter,addNext24HoursFilter,addNextMonthFilter,addPreferredPharmacyToPatient,addThisMonthFilter,addTodayFilter,addTomorrowFilter,addYearToDateFilter,addYesterdayFilter,buildFieldNameString,clearFilters,clearFiltersOnField,codingToValueSetElement,convertIsoToLocal,convertLocalToIso,createLabsSection,createPharmaciesSection,createPreferredPharmacyExtension,createScriptTag,deleteFilter,exportJsonFile,getAppName,getDefaultSections,getErrorsForInput,getFieldDefinitions,getIssuesForExpression,getOpString,getPaginationControlProps,getPreferredPharmaciesFromPatient,getRecaptcha,getSearchOperators,getSortField,getValuePath,initRecaptcha,isAddPharmacyResponse,isAuxClick,isCheckboxCell,isOrganizationArray,isSortDescending,isSupportedProfileStructureDefinition,killEvent,parseForm,removePreferredPharmacyFromPatient,renderValue,sendCommand,setFilters,setOffset,setPage,setPropertyValue,setSort,sortByDateAndPriority,summaryResourceListSection,toggleSort,valueSetElementToCoding};
|
|
111
|
+
`)}),"...",jsx165("br",{})]})}import{ActionIcon as ActionIcon20,Alert as Alert6,Button as Button24,Group as Group66,Menu as Menu9,Stack as Stack46,TextInput as TextInput32,useMantineTheme}from"@mantine/core";import{AccessPolicyInteraction as AccessPolicyInteraction2,applyDefaultValuesToResource,canWriteResourceType,isPopulated as isPopulated11,satisfiedAccessPolicy as satisfiedAccessPolicy2,tryGetProfile as tryGetProfile5}from"@medplum/core";import{useMedplum as useMedplum51,useResource as useResource18}from"@medplum/react-hooks";import{useEffect as useEffect38,useMemo as useMemo39,useState as useState91}from"react";var ResourceForm_default={splitButton:"ResourceForm_splitButton",menuControl:"ResourceForm_menuControl"};import{jsx as jsx166,jsxs as jsxs112}from"react/jsx-runtime";function ResourceForm(props){let{outcome}=props,medplum=useMedplum51(),defaultValue2=useResource18(props.defaultValue),resourceType=defaultValue2?.resourceType,[schemaLoaded,setSchemaLoaded]=useState91(!1),[value,setValue]=useState91(),accessPolicy=medplum.getAccessPolicy(),theme=useMantineTheme();useEffect38(()=>{if(defaultValue2)if(props.profileUrl){let profileUrl=props.profileUrl;medplum.requestProfileSchema(props.profileUrl,{expandProfile:!0}).then(()=>{let profile=tryGetProfile5(profileUrl);if(profile){setSchemaLoaded(!0);let modifiedDefaultValue=applyDefaultValuesToResource(defaultValue2,profile);setValue(modifiedDefaultValue)}else console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)})}else medplum.requestSchema(resourceType).then(()=>{setValue(defaultValue2),setSchemaLoaded(!0)}).catch(console.log)},[medplum,defaultValue2,resourceType,props.profileUrl]);let accessPolicyResource=useMemo39(()=>defaultValue2&&satisfiedAccessPolicy2(defaultValue2,AccessPolicyInteraction2.READ,accessPolicy),[accessPolicy,defaultValue2]),canWrite=useMemo39(()=>medplum.isSuperAdmin()||!accessPolicy||!isPopulated11(value?.resourceType)?!0:canWriteResourceType(accessPolicy,value?.resourceType),[medplum,accessPolicy,value?.resourceType]);return!schemaLoaded||!value?jsx166("div",{children:"Loading..."}):canWrite?jsxs112("form",{noValidate:!0,autoComplete:"off",onSubmit:e=>{e.preventDefault(),props.onSubmit&&props.onSubmit(value)},children:[jsxs112(Stack46,{mb:"xl",children:[jsx166(FormSection,{title:"Resource Type",htmlFor:"resourceType",outcome,children:jsx166(TextInput32,{name:"resourceType",defaultValue:value.resourceType,disabled:!0})}),jsx166(FormSection,{title:"ID",htmlFor:"id",outcome,children:jsx166(TextInput32,{name:"id",defaultValue:value.id,disabled:!0})})]}),jsx166(BackboneElementInput,{path:value.resourceType,valuePath:value.resourceType,typeName:resourceType,defaultValue:value,outcome,onChange:setValue,profileUrl:props.profileUrl,accessPolicyResource}),jsxs112(Group66,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[jsx166(Button24,{type:"submit",className:clsx_default((props.onPatch||props.onDelete)&&ResourceForm_default.splitButton),children:defaultValue2?.id?"Update":"Create"}),(props.onPatch||props.onDelete)&&jsxs112(Menu9,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[jsx166(Menu9.Target,{children:jsx166(ActionIcon20,{variant:"filled",color:theme.primaryColor,size:36,className:ResourceForm_default.menuControl,"aria-label":"More actions",children:jsx166(IconChevronDown,{size:14,stroke:1.5})})}),jsxs112(Menu9.Dropdown,{children:[props.onPatch&&jsx166(Menu9.Item,{leftSection:jsx166(IconEdit,{size:14,stroke:1.5}),onClick:()=>{props.onPatch(value)},children:"Patch"}),props.onDelete&&jsx166(Menu9.Item,{color:"red",leftSection:jsx166(IconTrash,{size:14,stroke:1.5,color:"red"}),onClick:()=>{props.onDelete(value)},children:"Delete"})]})]})]})]}):jsxs112(Alert6,{color:"red",title:"Permission denied",icon:jsx166(IconAlertCircle,{}),children:["Your access level prevents you from editing and creating ",value.resourceType," resources."]})}import{Table as Table6}from"@mantine/core";import{formatDateTime as formatDateTime8,normalizeErrorString as normalizeErrorString15}from"@medplum/core";import{useMedplum as useMedplum52}from"@medplum/react-hooks";import{useEffect as useEffect39,useState as useState92}from"react";import{jsx as jsx167,jsxs as jsxs113}from"react/jsx-runtime";function ResourceHistoryTable(props){let medplum=useMedplum52(),[value,setValue]=useState92(props.history);return useEffect39(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),value?jsxs113(Table6,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[jsx167(Table6.Thead,{children:jsxs113(Table6.Tr,{children:[jsx167(Table6.Th,{children:"Author"}),jsx167(Table6.Th,{children:"Date"}),jsx167(Table6.Th,{children:"Version"})]})}),jsx167(Table6.Tbody,{children:value.entry?.map((entry,index)=>jsx167(HistoryRow,{entry},"entry-"+index))})]}):jsx167("div",{children:"Loading..."})}function HistoryRow(props){let{response,resource}=props.entry;return resource?jsxs113(Table6.Tr,{children:[jsx167(Table6.Td,{children:jsx167(ResourceBadge,{value:resource.meta?.author,link:!0})}),jsx167(Table6.Td,{children:formatDateTime8(resource.meta?.lastUpdated)}),jsx167(Table6.Td,{children:jsx167(MedplumLink,{to:getVersionUrl2(resource),children:resource.meta?.versionId})})]}):jsx167(Table6.Tr,{children:jsx167(Table6.Td,{colSpan:3,children:normalizeErrorString15(response?.outcome)})})}function getVersionUrl2(resource){return`/${resource.resourceType}/${resource.id}/_history/${resource.meta?.versionId}`}import{Button as Button25,Loader as Loader10,Stack as Stack47,Text as Text50}from"@mantine/core";import{showNotification as showNotification11}from"@mantine/notifications";import{getReferenceString as getReferenceString14,isReference as isReference4,isResource as isResource3,normalizeErrorString as normalizeErrorString16}from"@medplum/core";import{useMedplum as useMedplum53}from"@medplum/react-hooks";import{useEffect as useEffect40,useMemo as useMemo40,useState as useState93}from"react";var Scheduler_default={container:"Scheduler_container",info:"Scheduler_info",selection:"Scheduler_selection"};import{jsx as jsx168,jsxs as jsxs114}from"react/jsx-runtime";function onlyPractitioner(schedule){let refs=schedule.actor.filter(ref=>isReference4(ref,"Practitioner"));if(refs.length===1)return refs[0]}function Scheduler(props){let medplum=useMedplum53(),[month,setMonth]=useState93(getStartMonth()),[date,setDate]=useState93(),[actor,setActor]=useState93(),[slots,setSlots]=useState93(),[selectedSlot,setSelectedSlot]=useState93(),handleSelectSlot=slot=>{setSelectedSlot(slot),props.onSelectSlot?.(slot)};useEffect40(()=>{props.schedule||setSlots([]),(props.fetchSlots??(async period=>{let scheduleArray=[];if(!Array.isArray(props.schedule))scheduleArray.push(isReference4(props.schedule,"Schedule")?props.schedule.reference:getReferenceString14(props.schedule));else for(let schedule of props.schedule)if(isReference4(schedule))scheduleArray.push(schedule.reference);else{let scheduleRef=getReferenceString14(schedule);scheduleArray.push(scheduleRef)}let slotSearchParams=new URLSearchParams([["_count","720"],["schedule",scheduleArray.join(",")],["start","gt"+period.start],["start","lt"+period.end]]);return medplum.searchResources("Slot",slotSearchParams)}))({start:getStart2(month),end:getEnd2(month)}).then(setSlots).catch(console.error)},[medplum,props.schedule,props.fetchSlots,month]),useEffect40(()=>{props.schedule&&!Array.isArray(props.schedule)&&(isResource3(props.schedule)?setActor(onlyPractitioner(props.schedule)):medplum.readReference(props.schedule).then(schedule=>setActor(onlyPractitioner(schedule))).catch(error=>{showNotification11({color:"red",title:"Error",message:normalizeErrorString16(error)})}))},[medplum,props.schedule]);let startTimeToSlotMap=useMemo40(()=>{if(!date)return null;let sortedSlots=(slots||[]).filter(slot=>new Date(slot.start).getTime()>date.getTime()&&new Date(slot.start).getTime()<date.getTime()+24*3600*1e3).sort((a,b)=>new Date(a.start).getTime()-new Date(b.start).getTime()),startTimeToSlotMap2=new Map;for(let slot of sortedSlots)startTimeToSlotMap2.set(formatTime(new Date(slot.start)),slot);return startTimeToSlotMap2},[slots,date]);return slots?jsxs114("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:[jsxs114("div",{className:Scheduler_default.info,children:[actor&&jsx168(ResourceAvatar,{value:actor,size:"xl"}),actor&&jsx168(Text50,{size:"xl",fw:500,children:jsx168(ResourceName,{value:actor})}),jsx168("p",{children:"1 hour"}),date&&jsx168("p",{children:date.toLocaleDateString()}),selectedSlot&&jsx168("p",{children:formatTime(new Date(selectedSlot.start))})]}),jsxs114("div",{className:Scheduler_default.selection,children:[!date&&jsxs114("div",{children:[jsx168("h3",{children:"Select date"}),jsx168(CalendarInput,{slots,onChangeMonth:setMonth,onClick:setDate})]}),date&&!selectedSlot&&jsxs114("div",{children:[jsx168("h3",{children:"Select time"}),jsx168(Stack47,{children:Array.from(startTimeToSlotMap?.entries()??[]).map(([startTime,slot])=>jsx168("div",{children:jsx168(Button25,{variant:"outline",style:{width:150},onClick:()=>handleSelectSlot(slot),children:startTime})},slot.id))})]}),props.children]})]}):jsx168("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:jsx168(Loader10,{})})}function getStart2(month){return formatSlotInstant(month.getTime())}function getEnd2(month){return formatSlotInstant(month.getTime()+744*60*60*1e3)}function formatSlotInstant(time){let date=new Date(Math.max(Date.now(),time));return date.setHours(0,0,0,0),date.toISOString()}function formatTime(date){return date.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}import{createReference as createReference17}from"@medplum/core";import{jsx as jsx169}from"react/jsx-runtime";function ServiceRequestTimeline(props){let{serviceRequest,...rest}=props;return jsx169(ResourceTimeline,{value:serviceRequest,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("ServiceRequest",id),medplum.search("Communication",{"based-on":ref,_count}),medplum.search("DiagnosticReport",{"based-on":ref,_count}),medplum.search("Media",{"based-on":ref,_count}),medplum.search("DocumentReference",{related:ref,_count}),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count})])},createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",basedOn:[createReference17(resource)],subject:resource.subject,sender:createReference17(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",basedOn:[createReference17(resource)],subject:resource.subject,operator:createReference17(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor14}from"@mantine/core";import{showNotification as showNotification12}from"@mantine/notifications";import{ensureTrailingSlash,normalizeErrorString as normalizeErrorString17}from"@medplum/core";import{useMedplum as useMedplum54,useResource as useResource19}from"@medplum/react-hooks";import{jsx as jsx170}from"react/jsx-runtime";function SmartAppLaunchLink(props){let medplum=useMedplum54(),{client,patient,encounter,children,...rest}=props,patientResource=useResource19(patient),encounterResource=useResource19(encounter);function launchApp(){let patientRef=patient,encounterRef=encounter;if(client.launchIdentifierSystems?.length){let patientIdentifierConfig=client.launchIdentifierSystems.find(config=>config.resourceType==="Patient");if(patientRef&&patientResource&&patientIdentifierConfig?.system){let identifier=patientResource.identifier?.find(i=>i.system===patientIdentifierConfig.system);identifier&&(patientRef={...patient,identifier})}let encounterIdentifierConfig=client.launchIdentifierSystems.find(config=>config.resourceType==="Encounter");if(encounterRef&&encounterResource&&encounterIdentifierConfig?.system){let identifier=encounterResource.identifier?.find(i=>i.system===encounterIdentifierConfig.system);identifier&&(encounterRef={...encounter,identifier})}}medplum.createResource({resourceType:"SmartAppLaunch",patient:patientRef,encounter:encounterRef,fhirContext:props.fhirContext}).then(result=>{let url=new URL(client.launchUri);url.searchParams.set("iss",ensureTrailingSlash(medplum.fhirUrl().toString())),url.searchParams.set("launch",result.id),window.open(url.toString(),"_blank")}).catch(err=>showNotification12({color:"red",message:normalizeErrorString17(err),autoClose:!1}))}return jsx170(Anchor14,{onClick:()=>launchApp(),...rest,children})}export{AddressDisplay,AddressInput,AllergiesSection,AnnotationInput,AppShell,AsyncAutocomplete,AttachmentArrayDisplay,AttachmentArrayInput,AttachmentButton,AttachmentDisplay,AttachmentInput,BackboneElementDisplay,BackboneElementInput,BaseChat,CalendarInput,ChangePasswordForm,ChatList,ChatListItem,ChatModal,CheckboxFormSection,CodeInput,CodeableConceptDisplay,CodeableConceptInput,CodingDisplay,CodingInput,ContactDetailDisplay,ContactDetailInput,ContactPointDisplay,ContactPointInput,Container,DateTimeInput,DefaultResourceItemComponent,DefaultResourceTimeline,DemographicsSection,DescriptionList,DescriptionListEntry,DiagnosticReportDisplay,Document,ElementDefinitionInputSelector,ElementDefinitionTypeInput,EncounterTimeline,ErrorBoundary,FhirPathTable,Form,FormSection,Header,HumanNameDisplay,HumanNameInput,IdentifierDisplay,IdentifierInput,InfoBar,InsuranceSection,LabsSection,LinkTabs,Loading,Logo,MeasureReportDisplay,MedicationsSection,MedplumLink,MemoizedFhirPathTable,MfaForm,MoneyDisplay,MoneyInput,MultiResourceInput,Navbar,NewTopicDialog,NoteDisplay,NotificationIcon,ObservationTable,OperationOutcomeAlert,PATIENT_PREFERRED_PHARMACY_URL,PHARMACY_PREFERENCE_TYPE_SYSTEM,PHARMACY_TYPE_PREFERRED,PHARMACY_TYPE_PRIMARY,Panel,ParticipantFilter,PatientAccountsForm,PatientExportForm,PatientHeader,PatientSummary,PatientTimeline,Pharmacies,PharmaciesSection,PharmacyDialog,PlanDefinitionBuilder,ProblemListSection,QuantityDisplay,QuantityInput,QuestionnaireBuilder,QuestionnaireForm,QuestionnaireResponseDisplay,RangeDisplay,RangeInput,RatioInput,ReferenceDisplay,ReferenceInput,ReferenceRangeEditor,ReferenceRangeGroupEditor,RegisterForm,RequestGroupDisplay,ResetPasswordForm,ResourceArrayDisplay,ResourceArrayInput,ResourceAvatar,ResourceBadge,ResourceBlame,ResourceDiff,ResourceDiffTable,ResourceForm,ResourceHistoryTable,ResourceInput,ResourceName,ResourcePropertyDisplay,ResourcePropertyInput,ResourceTable,ResourceTimeline,Scheduler,SearchChangeEvent,SearchClickEvent,SearchControl,SearchFieldEditor,SearchFilterEditor,SearchLoadEvent,ServiceRequestTimeline,SetPasswordForm,SexualOrientationSection,SignInForm,SignatureInput,SmartAppLaunchLink,SmokingStatusSection,Spotlight,StatusBadge,SubmitButton,ThreadChat,ThreadInbox,Timeline,TimelineItem,TimingInput,ValueSetAutocomplete,VitalsSection,addDateFilterBetween,addField,addFilter,addLastMonthFilter,addMissingFilter,addNext24HoursFilter,addNextMonthFilter,addPreferredPharmacyToPatient,addThisMonthFilter,addTodayFilter,addTomorrowFilter,addYearToDateFilter,addYesterdayFilter,buildFieldNameString,clearFilters,clearFiltersOnField,codingToValueSetElement,convertIsoToLocal,convertLocalToIso,createLabsSection,createPharmaciesSection,createPreferredPharmacyExtension,createScriptTag,deleteFilter,exportJsonFile,getAppName,getDefaultSections,getErrorsForInput,getFieldDefinitions,getIssuesForExpression,getOpString,getPaginationControlProps,getPreferredPharmaciesFromPatient,getRecaptcha,getSearchOperators,getSortField,getValuePath,initRecaptcha,isAddPharmacyResponse,isAuxClick,isCheckboxCell,isOrganizationArray,isSortDescending,isSupportedProfileStructureDefinition,killEvent,parseForm,removePreferredPharmacyFromPatient,renderValue,sendCommand,setFilters,setOffset,setPage,setPropertyValue,setSort,sortByDateAndPriority,summaryResourceListSection,toggleSort,valueSetElementToCoding};
|
|
112
112
|
/*! Bundled license information:
|
|
113
113
|
|
|
114
114
|
@tabler/icons-react/dist/esm/defaultAttributes.mjs:
|