@medplum/react 4.4.3 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -61,7 +61,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
61
61
  display
62
62
  }
63
63
  }
64
- }`.replace(/\s+/g," ")}function getResourcesFromResponse(response,query){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),sortByRelevance(dedupeResources(resources),query).slice(0,5)}function dedupeResources(resources){let ids=new Set,result=[];for(let resource of resources)ids.has(resource.id)||(ids.add(resource.id),result.push(resource));return result}function sortByRelevance(resources,query){return resources.sort((a,b)=>getResourceScore(b,query)-getResourceScore(a,query))}function getResourceScore(resource,query){let bestScore=0;if(resource.identifier)for(let identifier of resource.identifier)bestScore=Math.max(bestScore,getStringScore(identifier.value,query));if(resource.resourceType==="Patient"&&resource.name)for(let name of resource.name)bestScore=Math.max(bestScore,getStringScore(formatHumanName2(name),query));return bestScore}function getStringScore(str,query){if(!str)return 0;let index=str.toLowerCase().indexOf(query.toLowerCase());return index<0?0:100-index}import{jsx as jsx12,jsxs as jsxs5}from"react/jsx-runtime";function Header(props){let profile=useMedplumProfile2(),[userMenuOpened,setUserMenuOpened]=useState4(!1);return jsx12(MantineAppShell.Header,{p:8,style:{zIndex:101},children:jsxs5(Group5,{justify:"space-between",children:[jsxs5(Group5,{gap:"xs",children:[jsx12(UnstyledButton,{className:Header_default.logoButton,onClick:props.navbarToggle,children:props.logo}),!props.headerSearchDisabled&&jsx12(HeaderSearchInput,{pathname:props.pathname,searchParams:props.searchParams})]}),jsxs5(Group5,{gap:"lg",pr:"sm",children:[props.notifications,jsxs5(Menu2,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:userMenuOpened,onClose:()=>setUserMenuOpened(!1),children:[jsx12(Menu2.Target,{children:jsx12(UnstyledButton,{className:clsx_default(Header_default.user,{[Header_default.userActive]:userMenuOpened}),onClick:()=>setUserMenuOpened(o=>!o),children:jsxs5(Group5,{gap:7,children:[jsx12(ResourceAvatar,{value:profile,radius:"xl",size:24}),jsx12(Text3,{size:"sm",className:Header_default.userName,children:formatHumanName3(profile?.name?.[0])}),jsx12(IconChevronDown,{size:12,stroke:1.5})]})})}),jsx12(Menu2.Dropdown,{children:jsx12(HeaderDropdown,{version:props.version})})]})]})]})})}import{Button as Button2,AppShell as MantineAppShell2,ScrollArea,Space,Text as Text5}from"@mantine/core";import{useMedplumNavigate as useMedplumNavigate3}from"@medplum/react-hooks";import{Fragment as Fragment4,useState as useState8}from"react";import{Group as Group6,Modal,NativeSelect as NativeSelect2,Stack as Stack2,TextInput as TextInput3}from"@mantine/core";import{showNotification as showNotification2}from"@mantine/notifications";import{deepClone,normalizeErrorString as normalizeErrorString3}from"@medplum/core";import{useMedplum as useMedplum2}from"@medplum/react-hooks";import{useState as useState5}from"react";import{createContext as createContext2}from"react";var FormContext=createContext2({submitting:!1});FormContext.displayName="FormContext";function parseForm(form){let result={};for(let element of Array.from(form.elements))element instanceof HTMLInputElement?parseInputElement(result,element):element instanceof HTMLTextAreaElement?result[element.name]=element.value:element instanceof HTMLSelectElement&&parseSelectElement(result,element);return result}function parseInputElement(result,el){el.disabled||(el.type==="checkbox"||el.type==="radio")&&!el.checked||(result[el.name]=el.value)}function parseSelectElement(result,el){result[el.name]=el.value}import{jsx as jsx13}from"react/jsx-runtime";function Form(props){let[submitting,setSubmitting]=useState5(!1);return jsx13(FormContext.Provider,{value:{submitting},children:jsx13("form",{style:props.style,"data-testid":props.testid,onSubmit:e=>{e.preventDefault();let formData=parseForm(e.target);if(props.onSubmit){setSubmitting(!0);let result=props.onSubmit(formData);result?.then?result.catch(console.error).finally(()=>{setSubmitting(!1)}):setSubmitting(!1)}},children:props.children})})}import{Button}from"@mantine/core";import{useContext as useContext2}from"react";import{jsx as jsx14}from"react/jsx-runtime";function SubmitButton(props){let{children,...buttonProps}=props,{submitting}=useContext2(FormContext);return jsx14(Button,{type:"submit",loading:submitting,...buttonProps,children})}import{jsx as jsx15,jsxs as jsxs6}from"react/jsx-runtime";function BookmarkDialog(props){let medplum=useMedplum2(),config=medplum.getUserConfiguration();function submitHandler(formData){let{menuname,bookmarkname:name}=formData,target=`${props.pathname}?${props.searchParams.toString()}`,newConfig=deepClone(config);newConfig.menu?.find(({title})=>title===menuname)?.link?.push({name,target}),medplum.updateResource(newConfig).then(res=>{config.menu=res.menu,medplum.dispatchEvent({type:"change"}),showNotification2({color:"green",message:"Success"}),props.onOk()}).catch(err=>{showNotification2({color:"red",message:normalizeErrorString3(err)})})}return jsx15(Modal,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:jsx15(Form,{onSubmit:submitHandler,children:jsxs6(Stack2,{children:[jsx15(SelectMenu,{config}),jsx15(TextInput3,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),jsx15(Group6,{justify:"flex-end",children:jsx15(SubmitButton,{mt:"sm",children:"OK"})})]})})})}function SelectMenu(props){function userConfigToMenu(config){return config?.menu?.map(menu=>menu.title)}let menus=userConfigToMenu(props.config);return jsx15(NativeSelect2,{name:"menuname",defaultValue:menus[0],label:"Select Menu Option",data:menus,withAsterisk:!0})}import{useCallback as useCallback4,useState as useState7}from"react";import{useState as useState6}from"react";import{Group as Group7,Text as Text4}from"@mantine/core";import{useMedplum as useMedplum3}from"@medplum/react-hooks";import{forwardRef as forwardRef3,useCallback as useCallback3}from"react";import{jsx as jsx16,jsxs as jsxs7}from"react/jsx-runtime";function toKey(element){return typeof element.code=="string"?element.code:JSON.stringify(element)}function getDisplay(item){return typeof item.display=="string"?item.display:toKey(item)}function toOption2(element){return{value:toKey(element),label:getDisplay(element),resource:element}}function createValue(input){return{code:input,display:input}}function ValueSetAutocomplete(props){let medplum=useMedplum3(),{binding,creatable,clearable,expandParams,withHelpText,...rest}=props,loadValues=useCallback3(async(input,signal)=>{if(!binding)return[];let valueSetElements=(await medplum.valueSetExpand({...expandParams,url:binding,filter:input,count:10},{signal})).expansion?.contains??[],newData=[];for(let valueSetElement of valueSetElements)valueSetElement.code&&!newData.some(item=>item.code===valueSetElement.code)&&newData.push(valueSetElement);return newData},[medplum,expandParams,binding]);return jsx16(AsyncAutocomplete,{...rest,creatable:creatable??!0,clearable:clearable??!0,toOption:toOption2,loadOptions:loadValues,onCreate:createValue,itemComponent:withHelpText?ItemComponent2:void 0})}var ItemComponent2=forwardRef3(({label,resource,active,...others},ref)=>jsx16("div",{ref,...others,children:jsxs7(Group7,{wrap:"nowrap",gap:"xs",children:[active&&jsx16(IconCheck,{size:12}),jsxs7("div",{children:[jsx16(Text4,{children:label}),jsx16(Text4,{size:"xs",c:"dimmed",children:`${resource.system}#${resource.code}`})]})]})}));import{jsx as jsx17}from"react/jsx-runtime";function CodeInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,...rest}=props,[value,setValue]=useState6(defaultValue2);function handleChange(newValues){let newValue=newValues[0],newCode=valueSetElementToCode(newValue);setValue(newCode),onChange&&onChange(newCode)}return jsx17(ValueSetAutocomplete,{defaultValue:codeToValueSetElement(value),onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codeToValueSetElement(code){return code?{code}:void 0}function valueSetElementToCode(element){return element?.code}import{jsx as jsx18}from"react/jsx-runtime";function ResourceTypeInput(props){let[resourceType,setResourceType]=useState7(props.defaultValue),onChange=props.onChange,setResourceTypeWrapper=useCallback4(newResourceType=>{setResourceType(newResourceType),onChange&&onChange(newResourceType)},[onChange]);return jsx18(CodeInput,{disabled:props.disabled,"data-autofocus":props.autoFocus,"data-testid":props.testId,defaultValue:resourceType,onChange:setResourceTypeWrapper,name:props.name,placeholder:props.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:props.maxValues??1,clearable:!1,withHelpText:!1})}var Navbar_default={menuTitle:"Navbar_menuTitle",link:"Navbar_link",linkActive:"Navbar_linkActive"};import{Fragment as Fragment5,jsx as jsx19,jsxs as jsxs8}from"react/jsx-runtime";function Navbar(props){let navigate=useMedplumNavigate3(),activeLink=getActiveLink(props.pathname,props.searchParams,props.menus),[bookmarkDialogVisible,setBookmarkDialogVisible]=useState8(!1);function onLinkClick(e,to){e.stopPropagation(),e.preventDefault(),navigate(to),window.innerWidth<768&&props.closeNavbar()}function navigateResourceType(resourceType){resourceType&&navigate(`/${resourceType}`)}return jsxs8(Fragment5,{children:[jsx19(MantineAppShell2.Navbar,{children:jsxs8(ScrollArea,{p:"xs",children:[!props.resourceTypeSearchDisabled&&jsx19(MantineAppShell2.Section,{mb:"sm",children:jsx19(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:newValue=>navigateResourceType(newValue)},window.location.pathname)}),jsxs8(MantineAppShell2.Section,{grow:!0,children:[props.menus?.map(menu=>jsxs8(Fragment4,{children:[jsx19(Text5,{className:Navbar_default.menuTitle,children:menu.title}),menu.links?.map(link=>jsxs8(NavbarLink,{to:link.href,active:link.href===activeLink?.href,onClick:e=>onLinkClick(e,link.href),children:[jsx19(NavLinkIcon,{icon:link.icon}),jsx19("span",{children:link.label})]},link.href))]},`menu-${menu.title}`)),props.displayAddBookmark&&jsx19(Button2,{variant:"subtle",size:"xs",mt:"xl",leftSection:jsx19(IconPlus,{size:"0.75rem"}),onClick:()=>setBookmarkDialogVisible(!0),children:"Add Bookmark"})]})]})}),props.pathname&&props.searchParams&&jsx19(BookmarkDialog,{pathname:props.pathname,searchParams:props.searchParams,visible:bookmarkDialogVisible,onOk:()=>setBookmarkDialogVisible(!1),onCancel:()=>setBookmarkDialogVisible(!1)})]})}function NavbarLink(props){return jsx19(MedplumLink,{onClick:props.onClick,to:props.to,className:clsx_default(Navbar_default.link,{[Navbar_default.linkActive]:props.active}),children:props.children})}function NavLinkIcon(props){return props.icon?props.icon:jsx19(Space,{w:30})}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)&&currentSearchParams.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 jsx20,jsxs as jsxs9}from"react/jsx-runtime";function AppShell(props){let[navbarOpen,setNavbarOpen]=useState9(localStorage.navbarOpen==="true"),medplum=useMedplum4(),profile=useMedplumProfile3();useEffect2(()=>{function eventListener(){showNotification3({id:"offline",color:"red",message:"No connection to server",autoClose:!1})}return medplum.addEventListener("offline",eventListener),()=>medplum.removeEventListener("offline",eventListener)},[medplum]);function setNavbarOpenWrapper(open){localStorage.navbarOpen=open.toString(),setNavbarOpen(open)}function closeNavbar(){setNavbarOpenWrapper(!1)}function toggleNavbar(){setNavbarOpenWrapper(!navbarOpen)}return medplum.isLoading()?jsx20(Loading,{}):jsxs9(MantineAppShell3,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!profile||!navbarOpen,mobile:!profile||!navbarOpen}},padding:0,children:[profile&&jsx20(Header,{pathname:props.pathname,searchParams:props.searchParams,headerSearchDisabled:props.headerSearchDisabled,logo:props.logo,version:props.version,navbarToggle:toggleNavbar,notifications:props.notifications}),profile&&navbarOpen?jsx20(Navbar,{pathname:props.pathname,searchParams:props.searchParams,menus:props.menus,closeNavbar,displayAddBookmark:props.displayAddBookmark,resourceTypeSearchDisabled:props.resourceTypeSearchDisabled}):void 0,jsx20(MantineAppShell3.Main,{className:AppShell_default.main,children:jsx20(ErrorBoundary,{children:jsx20(Suspense,{fallback:jsx20(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 Button3}from"@mantine/core";import{useEffect as useEffect3,useRef as useRef3,useState as useState10}from"react";import{Fragment as Fragment6,jsx as jsx21,jsxs as jsxs10}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]=useState10(!1),iframeRef=useRef3(null),[validationResult,setValidationResult]=useState10(),[validating,setValidating]=useState10(!1);useEffect3(()=>{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?jsxs10("div",{"data-testid":"ccda-iframe",style:{maxWidth:props.maxWidth},children:[jsx21("div",{style:{minHeight:400},children:jsx21("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:iframeRef,src:CCDA_VIEWER_URL,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>setShouldSend(!0)})}),jsxs10("div",{style:{marginTop:"10px",marginBottom:"10px",display:"flex",alignItems:"center"},children:[jsx21(Button3,{type:"button",onClick:validateCcda,disabled:validating,children:validating?"Validating...":"Validate"}),validationResult&&jsxs10(Fragment6,{children:[jsxs10("div",{style:{marginLeft:"15px"},children:[jsx21("strong",{children:"Validation Results:"})," ",getErrorCount()," errors found"]}),jsx21(Button3,{type:"button",onClick:downloadResults,color:"green",style:{marginLeft:"auto"},children:"Download Full Results"})]})]})]}):null}import{jsx as jsx22,jsxs as jsxs11}from"react/jsx-runtime";function AttachmentDisplay(props){let{contentType,url:uncachedUrl,title}=props.value??{},url=useCachedBinaryUrl2(uncachedUrl);return url?jsxs11("div",{"data-testid":"attachment-display",children:[contentType?.startsWith("image/")&&jsx22("img",{"data-testid":"attachment-image",style:{maxWidth:props.maxWidth},src:url,alt:title}),contentType?.startsWith("video/")&&jsx22("video",{"data-testid":"attachment-video",style:{maxWidth:props.maxWidth},controls:!0,children:jsx22("source",{type:contentType,src:url})}),(contentType?.startsWith("text/")||contentType==="application/json"||contentType==="application/pdf")&&jsx22("div",{"data-testid":"attachment-iframe",style:{maxWidth:props.maxWidth,minHeight:400},children:jsx22("iframe",{title:"Attachment",width:"100%",height:"400",src:url+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),contentType===ContentType2.CDA_XML&&jsx22(CcdaDisplay,{url}),jsx22("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:jsx22(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}var DescriptionList_default={root:"DescriptionList_root",compact:"DescriptionList_compact"};import{Fragment as Fragment7,jsx as jsx23,jsxs as jsxs12}from"react/jsx-runtime";function DescriptionList(props){let{children,compact}=props;return jsx23("dl",{className:clsx_default(DescriptionList_default.root,{[DescriptionList_default.compact]:compact}),children})}function DescriptionListEntry(props){return jsxs12(Fragment7,{children:[jsx23("dt",{children:props.term}),jsx23("dd",{children:props.children})]})}import{Fragment as Fragment8,jsx as jsx24}from"react/jsx-runtime";function AttachmentArrayDisplay(props){let attachmentElements=props.values?.map((v,index)=>jsx24("div",{children:jsx24(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=jsx24(DescriptionListEntry,{term:getPathDisplayName(key),children:attachmentElements})}else content=jsx24(Fragment8,{children:attachmentElements});return content}import{ActionIcon}from"@mantine/core";import{useRef as useRef5,useState as useState11}from"react";import{normalizeOperationOutcome}from"@medplum/core";import{useMedplum as useMedplum5}from"@medplum/react-hooks";import{useRef as useRef4}from"react";import{Fragment as Fragment9,jsx as jsx25,jsxs as jsxs13}from"react/jsx-runtime";function AttachmentButton(props){let medplum=useMedplum5(),fileInputRef=useRef4(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 jsxs13(Fragment9,{children:[jsx25("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 jsx26,jsxs as jsxs14}from"react/jsx-runtime";function AttachmentArrayInput(props){let[values,setValues]=useState11(props.defaultValue??[]),valuesRef=useRef5(values);valuesRef.current=values;function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}return jsxs14("table",{style:{width:"100%"},children:[jsxs14("colgroup",{children:[jsx26("col",{width:"97%"}),jsx26("col",{width:"3%"})]}),jsxs14("tbody",{children:[values.map((v,index)=>jsxs14("tr",{children:[jsx26("td",{children:jsx26(AttachmentDisplay,{value:v,maxWidth:200})}),jsx26("td",{children:jsx26(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:jsx26(IconCircleMinus,{})})})]},`${index}-${values.length}`)),jsxs14("tr",{children:[jsx26("td",{}),jsx26("td",{children:jsx26(AttachmentButton,{disabled:props.disabled,onUpload:attachment=>{setValuesWrapper([...valuesRef.current,attachment])},children:props2=>jsx26(ActionIcon,{...props2,title:"Add",variant:"subtle",size:"sm",color:props2.disabled?"gray":"green",children:jsx26(IconCloudUpload,{})})})})]})]})]})}import{Button as Button4}from"@mantine/core";import{useState as useState12}from"react";import{Fragment as Fragment10,jsx as jsx27,jsxs as jsxs15}from"react/jsx-runtime";function AttachmentInput(props){let[value,setValue]=useState12(props.defaultValue);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return value?jsxs15(Fragment10,{children:[jsx27(AttachmentDisplay,{value,maxWidth:200}),jsx27(Button4,{disabled:props.disabled,onClick:e=>{killEvent(e),setValueWrapper(void 0)},children:"Remove"})]}):jsx27(AttachmentButton,{disabled:props.disabled,securityContext:props.securityContext,onUpload:setValueWrapper,children:props2=>jsx27(Button4,{...props2,children:"Upload..."})})}import{Alert as Alert2,Center as Center2,Group as Group8,Stack as Stack3,Text as Text6,TextInput as TextInput4,Title}from"@mantine/core";import{normalizeErrorString as normalizeErrorString4}from"@medplum/core";import{useState as useState13}from"react";import{jsx as jsx28,jsxs as jsxs16}from"react/jsx-runtime";function Logo(props){let overrideUrl=import.meta.env.MEDPLUM_LOGO_URL;return overrideUrl?jsx28("img",{src:overrideUrl,alt:"Logo",style:{maxHeight:props.size}}):jsxs16("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 180 180",style:{width:props.size,height:props.size},children:[jsx28("title",{children:"Medplum Logo"}),jsx28("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"})]})}import{jsx as jsx29,jsxs as jsxs17}from"react/jsx-runtime";function MfaForm(props){let[errorMessage,setErrorMessage]=useState13();return jsx29(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData)?.catch(err=>setErrorMessage(normalizeErrorString4(err)))},children:jsxs17(Stack3,{children:[jsxs17(Center2,{style:{flexDirection:"column"},children:[jsx29(Logo,{size:32}),jsx29(Title,{children:props.title})]}),errorMessage&&jsx29(Alert2,{icon:jsx29(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),props.qrCodeUrl&&jsxs17(Stack3,{align:"center",children:[jsx29(Text6,{children:"Scan this QR code with your authenticator app."}),jsx29("img",{src:props.qrCodeUrl,alt:"Multi Factor Auth QR Code"})]}),jsx29(Stack3,{children:jsx29(TextInput4,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),jsx29(Group8,{justify:"flex-end",mt:"xl",children:jsx29(SubmitButton,{children:props.buttonText})})]})})}import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useMedplum as useMedplum9}from"@medplum/react-hooks";import{useEffect as useEffect6,useState as useState17}from"react";import{Container as MantineContainer}from"@mantine/core";var Container_default={root:"Container_root"};import{jsx as jsx30}from"react/jsx-runtime";function Container(props){let{children,...others}=props;return jsx30(MantineContainer,{className:Container_default.root,...others,children})}import{Paper}from"@mantine/core";var Panel_default={paper:"Panel_paper",fill:"Panel_fill"};import{jsx as jsx31}from"react/jsx-runtime";function Panel(props){let{width,fill,className,children,...rest}=props,style=width?{maxWidth:width}:void 0;return jsx31(Paper,{className:clsx_default(Panel_default.paper,fill&&Panel_default.fill,className),style,shadow:"sm",radius:"sm",withBorder:!0,...rest,children})}import{jsx as jsx32}from"react/jsx-runtime";function Document(props){let{children,...others}=props;return jsx32(Container,{children:jsx32(Panel,{...others,children})})}import{Anchor as Anchor3,Center as Center3,Group as Group9,Stack as Stack4,Text as Text7,TextInput as TextInput5,Title as Title2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome2}from"@medplum/core";import{useMedplum as useMedplum6}from"@medplum/react-hooks";import{useState as useState14}from"react";function getErrorsForInput(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))?.map(issue=>issue.details?.text)?.join(`
64
+ }`.replace(/\s+/g," ")}function getResourcesFromResponse(response,query){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),sortByRelevance(dedupeResources(resources),query).slice(0,5)}function dedupeResources(resources){let ids=new Set,result=[];for(let resource of resources)ids.has(resource.id)||(ids.add(resource.id),result.push(resource));return result}function sortByRelevance(resources,query){return resources.sort((a,b)=>getResourceScore(b,query)-getResourceScore(a,query))}function getResourceScore(resource,query){let bestScore=0;if(resource.identifier)for(let identifier of resource.identifier)bestScore=Math.max(bestScore,getStringScore(identifier.value,query));if(resource.resourceType==="Patient"&&resource.name)for(let name of resource.name)bestScore=Math.max(bestScore,getStringScore(formatHumanName2(name),query));return bestScore}function getStringScore(str,query){if(!str)return 0;let index=str.toLowerCase().indexOf(query.toLowerCase());return index<0?0:100-index}import{jsx as jsx12,jsxs as jsxs5}from"react/jsx-runtime";function Header(props){let profile=useMedplumProfile2(),[userMenuOpened,setUserMenuOpened]=useState4(!1);return jsx12(MantineAppShell.Header,{p:8,style:{zIndex:101},children:jsxs5(Group5,{justify:"space-between",children:[jsxs5(Group5,{gap:"xs",children:[jsx12(UnstyledButton,{className:Header_default.logoButton,onClick:props.navbarToggle,children:props.logo}),!props.headerSearchDisabled&&jsx12(HeaderSearchInput,{pathname:props.pathname,searchParams:props.searchParams})]}),jsxs5(Group5,{gap:"lg",pr:"sm",children:[props.notifications,jsxs5(Menu2,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:userMenuOpened,onClose:()=>setUserMenuOpened(!1),children:[jsx12(Menu2.Target,{children:jsx12(UnstyledButton,{className:clsx_default(Header_default.user,{[Header_default.userActive]:userMenuOpened}),onClick:()=>setUserMenuOpened(o=>!o),children:jsxs5(Group5,{gap:7,children:[jsx12(ResourceAvatar,{value:profile,radius:"xl",size:24}),jsx12(Text3,{size:"sm",className:Header_default.userName,children:formatHumanName3(profile?.name?.[0])}),jsx12(IconChevronDown,{size:12,stroke:1.5})]})})}),jsx12(Menu2.Dropdown,{children:jsx12(HeaderDropdown,{version:props.version})})]})]})]})})}import{Button as Button2,AppShell as MantineAppShell2,ScrollArea,Space,Text as Text5}from"@mantine/core";import{useMedplumNavigate as useMedplumNavigate3}from"@medplum/react-hooks";import{Fragment as Fragment4,useState as useState8}from"react";import{Group as Group6,Modal,NativeSelect as NativeSelect2,Stack as Stack2,TextInput as TextInput3}from"@mantine/core";import{showNotification as showNotification2}from"@mantine/notifications";import{deepClone,normalizeErrorString as normalizeErrorString3}from"@medplum/core";import{useMedplum as useMedplum2}from"@medplum/react-hooks";import{useState as useState5}from"react";import{createContext as createContext2}from"react";var FormContext=createContext2({submitting:!1});FormContext.displayName="FormContext";function parseForm(form){let result={};for(let element of Array.from(form.elements))element instanceof HTMLInputElement?parseInputElement(result,element):element instanceof HTMLTextAreaElement?result[element.name]=element.value:element instanceof HTMLSelectElement&&parseSelectElement(result,element);return result}function parseInputElement(result,el){el.disabled||(el.type==="checkbox"||el.type==="radio")&&!el.checked||(result[el.name]=el.value)}function parseSelectElement(result,el){result[el.name]=el.value}import{jsx as jsx13}from"react/jsx-runtime";function Form(props){let[submitting,setSubmitting]=useState5(!1);return jsx13(FormContext.Provider,{value:{submitting},children:jsx13("form",{style:props.style,"data-testid":props.testid,onSubmit:e=>{e.preventDefault();let formData=parseForm(e.target);if(props.onSubmit){setSubmitting(!0);let result=props.onSubmit(formData);result?.then?result.catch(console.error).finally(()=>{setSubmitting(!1)}):setSubmitting(!1)}},children:props.children})})}import{Button}from"@mantine/core";import{useContext as useContext2}from"react";import{jsx as jsx14}from"react/jsx-runtime";function SubmitButton(props){let{children,...buttonProps}=props,{submitting}=useContext2(FormContext);return jsx14(Button,{type:"submit",loading:submitting,...buttonProps,children})}import{jsx as jsx15,jsxs as jsxs6}from"react/jsx-runtime";function BookmarkDialog(props){let medplum=useMedplum2(),config=medplum.getUserConfiguration();function submitHandler(formData){let{menuname,bookmarkname:name}=formData,target=`${props.pathname}?${props.searchParams.toString()}`,newConfig=deepClone(config);newConfig.menu?.find(({title})=>title===menuname)?.link?.push({name,target}),medplum.updateResource(newConfig).then(res=>{config.menu=res.menu,medplum.dispatchEvent({type:"change"}),showNotification2({color:"green",message:"Success"}),props.onOk()}).catch(err=>{showNotification2({color:"red",message:normalizeErrorString3(err)})})}return jsx15(Modal,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:jsx15(Form,{onSubmit:submitHandler,children:jsxs6(Stack2,{children:[jsx15(SelectMenu,{config}),jsx15(TextInput3,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),jsx15(Group6,{justify:"flex-end",children:jsx15(SubmitButton,{mt:"sm",children:"OK"})})]})})})}function SelectMenu(props){function userConfigToMenu(config){return config?.menu?.map(menu=>menu.title)}let menus=userConfigToMenu(props.config);return jsx15(NativeSelect2,{name:"menuname",defaultValue:menus[0],label:"Select Menu Option",data:menus,withAsterisk:!0})}import{useCallback as useCallback4,useState as useState7}from"react";import{useState as useState6}from"react";import{Group as Group7,Text as Text4}from"@mantine/core";import{useMedplum as useMedplum3}from"@medplum/react-hooks";import{forwardRef as forwardRef3,useCallback as useCallback3}from"react";import{jsx as jsx16,jsxs as jsxs7}from"react/jsx-runtime";function toKey(element){return typeof element.code=="string"?element.code:JSON.stringify(element)}function getDisplay(item){return typeof item.display=="string"?item.display:toKey(item)}function toOption2(element){return{value:toKey(element),label:getDisplay(element),resource:element}}function createValue(input){return{code:input,display:input}}function ValueSetAutocomplete(props){let medplum=useMedplum3(),{binding,creatable,clearable,expandParams,withHelpText,...rest}=props,loadValues=useCallback3(async(input,signal)=>{if(!binding)return[];let valueSetElements=(await medplum.valueSetExpand({...expandParams,url:binding,filter:input,count:10},{signal})).expansion?.contains??[],newData=[];for(let valueSetElement of valueSetElements)valueSetElement.code&&!newData.some(item=>item.code===valueSetElement.code)&&newData.push(valueSetElement);return newData},[medplum,expandParams,binding]);return jsx16(AsyncAutocomplete,{...rest,creatable:creatable??!0,clearable:clearable??!0,toOption:toOption2,loadOptions:loadValues,onCreate:createValue,itemComponent:withHelpText?ItemComponent2:void 0})}var ItemComponent2=forwardRef3(({label,resource,active,...others},ref)=>jsx16("div",{ref,...others,children:jsxs7(Group7,{wrap:"nowrap",gap:"xs",children:[active&&jsx16(IconCheck,{size:12}),jsxs7("div",{children:[jsx16(Text4,{children:label}),jsx16(Text4,{size:"xs",c:"dimmed",children:`${resource.system}#${resource.code}`})]})]})}));import{jsx as jsx17}from"react/jsx-runtime";function CodeInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,...rest}=props,[value,setValue]=useState6(defaultValue2);function handleChange(newValues){let newValue=newValues[0],newCode=valueSetElementToCode(newValue);setValue(newCode),onChange&&onChange(newCode)}return jsx17(ValueSetAutocomplete,{defaultValue:codeToValueSetElement(value),onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codeToValueSetElement(code){return code?{code}:void 0}function valueSetElementToCode(element){return element?.code}import{jsx as jsx18}from"react/jsx-runtime";function ResourceTypeInput(props){let[resourceType,setResourceType]=useState7(props.defaultValue),onChange=props.onChange,setResourceTypeWrapper=useCallback4(newResourceType=>{setResourceType(newResourceType),onChange&&onChange(newResourceType)},[onChange]);return jsx18(CodeInput,{disabled:props.disabled,"data-autofocus":props.autoFocus,"data-testid":props.testId,defaultValue:resourceType,onChange:setResourceTypeWrapper,name:props.name,placeholder:props.placeholder,binding:"https://medplum.com/fhir/ValueSet/resource-types",creatable:!1,maxValues:props.maxValues??1,clearable:!1,withHelpText:!1})}var Navbar_default={menuTitle:"Navbar_menuTitle",link:"Navbar_link",linkActive:"Navbar_linkActive"};import{Fragment as Fragment5,jsx as jsx19,jsxs as jsxs8}from"react/jsx-runtime";function Navbar(props){let navigate=useMedplumNavigate3(),activeLink=getActiveLink(props.pathname,props.searchParams,props.menus),[bookmarkDialogVisible,setBookmarkDialogVisible]=useState8(!1);function onLinkClick(e,to){e.stopPropagation(),e.preventDefault(),navigate(to),window.innerWidth<768&&props.closeNavbar()}function navigateResourceType(resourceType){resourceType&&navigate(`/${resourceType}`)}return jsxs8(Fragment5,{children:[jsx19(MantineAppShell2.Navbar,{children:jsxs8(ScrollArea,{p:"xs",children:[!props.resourceTypeSearchDisabled&&jsx19(MantineAppShell2.Section,{mb:"sm",children:jsx19(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:newValue=>navigateResourceType(newValue)},window.location.pathname)}),jsxs8(MantineAppShell2.Section,{grow:!0,children:[props.menus?.map(menu=>jsxs8(Fragment4,{children:[jsx19(Text5,{className:Navbar_default.menuTitle,children:menu.title}),menu.links?.map(link=>jsxs8(NavbarLink,{to:link.href,active:link.href===activeLink?.href,onClick:e=>onLinkClick(e,link.href),children:[jsx19(NavLinkIcon,{icon:link.icon}),jsx19("span",{children:link.label})]},link.href))]},`menu-${menu.title}`)),props.displayAddBookmark&&jsx19(Button2,{variant:"subtle",size:"xs",mt:"xl",leftSection:jsx19(IconPlus,{size:"0.75rem"}),onClick:()=>setBookmarkDialogVisible(!0),children:"Add Bookmark"})]})]})}),props.pathname&&props.searchParams&&jsx19(BookmarkDialog,{pathname:props.pathname,searchParams:props.searchParams,visible:bookmarkDialogVisible,onOk:()=>setBookmarkDialogVisible(!1),onCancel:()=>setBookmarkDialogVisible(!1)})]})}function NavbarLink(props){return jsx19(MedplumLink,{onClick:props.onClick,to:props.to,className:clsx_default(Navbar_default.link,{[Navbar_default.linkActive]:props.active}),children:props.children})}function NavLinkIcon(props){return props.icon?props.icon:jsx19(Space,{w:30})}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)&&currentSearchParams.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 jsx20,jsxs as jsxs9}from"react/jsx-runtime";function AppShell(props){let[navbarOpen,setNavbarOpen]=useState9(localStorage.navbarOpen==="true"),medplum=useMedplum4(),profile=useMedplumProfile3();useEffect2(()=>{function eventListener(){showNotification3({id:"offline",color:"red",message:"No connection to server",autoClose:!1})}return medplum.addEventListener("offline",eventListener),()=>medplum.removeEventListener("offline",eventListener)},[medplum]);function setNavbarOpenWrapper(open){localStorage.navbarOpen=open.toString(),setNavbarOpen(open)}function closeNavbar(){setNavbarOpenWrapper(!1)}function toggleNavbar(){setNavbarOpenWrapper(!navbarOpen)}return medplum.isLoading()?jsx20(Loading,{}):jsxs9(MantineAppShell3,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!profile||!navbarOpen,mobile:!profile||!navbarOpen}},padding:0,children:[profile&&jsx20(Header,{pathname:props.pathname,searchParams:props.searchParams,headerSearchDisabled:props.headerSearchDisabled,logo:props.logo,version:props.version,navbarToggle:toggleNavbar,notifications:props.notifications}),profile&&navbarOpen?jsx20(Navbar,{pathname:props.pathname,searchParams:props.searchParams,menus:props.menus,closeNavbar,displayAddBookmark:props.displayAddBookmark,resourceTypeSearchDisabled:props.resourceTypeSearchDisabled}):void 0,jsx20(MantineAppShell3.Main,{className:AppShell_default.main,children:jsx20(ErrorBoundary,{children:jsx20(Suspense,{fallback:jsx20(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 Button3}from"@mantine/core";import{useEffect as useEffect3,useRef as useRef3,useState as useState10}from"react";import{Fragment as Fragment6,jsx as jsx21,jsxs as jsxs10}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]=useState10(!1),iframeRef=useRef3(null),[validationResult,setValidationResult]=useState10(),[validating,setValidating]=useState10(!1);useEffect3(()=>{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?jsxs10("div",{"data-testid":"ccda-iframe",style:{maxWidth:props.maxWidth},children:[jsx21("div",{style:{minHeight:400},children:jsx21("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:iframeRef,src:CCDA_VIEWER_URL,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>setShouldSend(!0)})}),jsxs10("div",{style:{marginTop:"10px",marginBottom:"10px",display:"flex",alignItems:"center"},children:[jsx21(Button3,{type:"button",onClick:validateCcda,disabled:validating,children:validating?"Validating...":"Validate"}),validationResult&&jsxs10(Fragment6,{children:[jsxs10("div",{style:{marginLeft:"15px"},children:[jsx21("strong",{children:"Validation Results:"})," ",getErrorCount()," errors found"]}),jsx21(Button3,{type:"button",onClick:downloadResults,color:"green",style:{marginLeft:"auto"},children:"Download Full Results"})]})]})]}):null}import{jsx as jsx22,jsxs as jsxs11}from"react/jsx-runtime";function AttachmentDisplay(props){let{contentType,url:uncachedUrl,title}=props.value??{},url=useCachedBinaryUrl2(uncachedUrl);return url?jsxs11("div",{"data-testid":"attachment-display",children:[contentType?.startsWith("image/")&&jsx22("img",{"data-testid":"attachment-image",style:{maxWidth:props.maxWidth},src:url,alt:title}),contentType?.startsWith("video/")&&jsx22("video",{"data-testid":"attachment-video",style:{maxWidth:props.maxWidth},controls:!0,children:jsx22("source",{type:contentType,src:url})}),(contentType?.startsWith("text/")||contentType==="application/json"||contentType==="application/pdf")&&jsx22("div",{"data-testid":"attachment-iframe",style:{maxWidth:props.maxWidth,minHeight:400},children:jsx22("iframe",{title:"Attachment",width:"100%",height:"400",src:url+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),contentType===ContentType2.CDA_XML&&jsx22(CcdaDisplay,{url}),jsx22("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:jsx22(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}var DescriptionList_default={root:"DescriptionList_root",compact:"DescriptionList_compact"};import{Fragment as Fragment7,jsx as jsx23,jsxs as jsxs12}from"react/jsx-runtime";function DescriptionList(props){let{children,compact}=props;return jsx23("dl",{className:clsx_default(DescriptionList_default.root,{[DescriptionList_default.compact]:compact}),children})}function DescriptionListEntry(props){return jsxs12(Fragment7,{children:[jsx23("dt",{children:props.term}),jsx23("dd",{children:props.children})]})}import{Fragment as Fragment8,jsx as jsx24}from"react/jsx-runtime";function AttachmentArrayDisplay(props){let attachmentElements=props.values?.map((v,index)=>jsx24("div",{children:jsx24(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=jsx24(DescriptionListEntry,{term:getPathDisplayName(key),children:attachmentElements})}else content=jsx24(Fragment8,{children:attachmentElements});return content}import{ActionIcon}from"@mantine/core";import{useRef as useRef5,useState as useState11}from"react";import{normalizeOperationOutcome}from"@medplum/core";import{useMedplum as useMedplum5}from"@medplum/react-hooks";import{useRef as useRef4}from"react";import{Fragment as Fragment9,jsx as jsx25,jsxs as jsxs13}from"react/jsx-runtime";function AttachmentButton(props){let medplum=useMedplum5(),fileInputRef=useRef4(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 jsxs13(Fragment9,{children:[jsx25("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 jsx26,jsxs as jsxs14}from"react/jsx-runtime";function AttachmentArrayInput(props){let[values,setValues]=useState11(props.defaultValue??[]),valuesRef=useRef5(values);valuesRef.current=values;function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}return jsxs14("table",{style:{width:"100%"},children:[jsxs14("colgroup",{children:[jsx26("col",{width:"97%"}),jsx26("col",{width:"3%"})]}),jsxs14("tbody",{children:[values.map((v,index)=>jsxs14("tr",{children:[jsx26("td",{children:jsx26(AttachmentDisplay,{value:v,maxWidth:200})}),jsx26("td",{children:jsx26(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:jsx26(IconCircleMinus,{})})})]},`${index}-${values.length}`)),jsxs14("tr",{children:[jsx26("td",{}),jsx26("td",{children:jsx26(AttachmentButton,{disabled:props.disabled,onUpload:attachment=>{setValuesWrapper([...valuesRef.current,attachment])},children:props2=>jsx26(ActionIcon,{...props2,title:"Add",variant:"subtle",size:"sm",color:props2.disabled?"gray":"green",children:jsx26(IconCloudUpload,{})})})})]})]})]})}import{Button as Button4}from"@mantine/core";import{useState as useState12}from"react";import{Fragment as Fragment10,jsx as jsx27,jsxs as jsxs15}from"react/jsx-runtime";function AttachmentInput(props){let[value,setValue]=useState12(props.defaultValue);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return value?jsxs15(Fragment10,{children:[jsx27(AttachmentDisplay,{value,maxWidth:200}),jsx27(Button4,{disabled:props.disabled,onClick:e=>{killEvent(e),setValueWrapper(void 0)},children:"Remove"})]}):jsx27(AttachmentButton,{disabled:props.disabled,securityContext:props.securityContext,onUpload:setValueWrapper,children:props2=>jsx27(Button4,{...props2,children:"Upload..."})})}import{Alert as Alert2,Center as Center2,Group as Group8,Stack as Stack3,Text as Text6,TextInput as TextInput4,Title}from"@mantine/core";import{normalizeErrorString as normalizeErrorString4}from"@medplum/core";import{useState as useState13}from"react";import{jsx as jsx28,jsxs as jsxs16}from"react/jsx-runtime";function Logo(props){let overrideUrl=import.meta.env.MEDPLUM_LOGO_URL;return overrideUrl?jsx28("img",{src:overrideUrl,alt:"Logo",style:{maxHeight:props.size}}):jsxs16("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 180 180",style:{width:props.size,height:props.size},children:[jsx28("title",{children:"Medplum Logo"}),jsx28("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"})]})}import{jsx as jsx29,jsxs as jsxs17}from"react/jsx-runtime";function MfaForm(props){let[errorMessage,setErrorMessage]=useState13();return jsx29(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData)?.catch(err=>setErrorMessage(normalizeErrorString4(err)))},children:jsxs17(Stack3,{children:[jsxs17(Center2,{style:{flexDirection:"column"},children:[jsx29(Logo,{size:32}),jsx29(Title,{children:props.title})]}),errorMessage&&jsx29(Alert2,{icon:jsx29(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),props.qrCodeUrl&&jsxs17(Stack3,{align:"center",children:[jsx29(Text6,{children:"Scan this QR code with your authenticator app."}),jsx29("img",{src:props.qrCodeUrl,alt:"Multi Factor Auth QR Code"})]}),jsx29(Stack3,{children:jsx29(TextInput4,{name:"token",label:"MFA code",autoComplete:"one-time-code",required:!0,autoFocus:!0})}),jsx29(Group8,{justify:"flex-end",mt:"xl",children:jsx29(SubmitButton,{children:props.buttonText})})]})})}import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useMedplum as useMedplum9}from"@medplum/react-hooks";import{useEffect as useEffect6,useState as useState17}from"react";import{Container as MantineContainer}from"@mantine/core";var Container_default={root:"Container_root"};import{jsx as jsx30}from"react/jsx-runtime";function Container(props){let{children,...others}=props;return jsx30(MantineContainer,{className:Container_default.root,...others,children})}import{Paper}from"@mantine/core";var Panel_default={paper:"Panel_paper",fill:"Panel_fill"};import{jsx as jsx31}from"react/jsx-runtime";function Panel(props){let{width,fill,className,children,...rest}=props,style=width?{maxWidth:width}:void 0;return jsx31(Paper,{className:clsx_default(Panel_default.paper,fill&&Panel_default.fill,className),style,shadow:"sm",radius:"sm",withBorder:!0,...rest,children})}import{jsx as jsx32}from"react/jsx-runtime";function Document(props){let{children,...others}=props;return jsx32(Container,{children:jsx32(Panel,{...others,children})})}import{Anchor as Anchor3,Center as Center3,Group as Group9,Stack as Stack4,Text as Text7,TextInput as TextInput5,Title as Title2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome2}from"@medplum/core";import{useMedplum as useMedplum6}from"@medplum/react-hooks";import{useState as useState14}from"react";function getErrorsForInput(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))?.map(issue=>issue.details?.text)?.join(`
65
65
  `)}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 NewProjectForm(props){let medplum=useMedplum6(),[outcome,setOutcome]=useState14();return jsxs18(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome(normalizeOperationOutcome2(err))}},children:[jsxs18(Center3,{style:{flexDirection:"column"},children:[jsx33(Logo,{size:32}),jsx33(Title2,{children:"Create project"})]}),jsxs18(Stack4,{gap:"xl",children:[jsx33(TextInput5,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")}),jsxs18(Text7,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx33(Anchor3,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx33(Anchor3,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]}),jsx33(Group9,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:jsx33(SubmitButton,{children:"Create project"})})]})}import{Anchor as Anchor4,Center as Center4,Checkbox,Divider,Group as Group10,PasswordInput,Stack as Stack5,Text as Text8,TextInput as TextInput6}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome3}from"@medplum/core";import{useMedplum as useMedplum8}from"@medplum/react-hooks";import{useEffect as useEffect5,useState as useState16}from"react";import{useMedplum as useMedplum7}from"@medplum/react-hooks";import{useEffect as useEffect4,useRef as useRef6,useState as useState15}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 jsx34}from"react/jsx-runtime";function GoogleButton(props){let medplum=useMedplum7(),{googleClientId,handleGoogleCredential}=props,parentRef=useRef6(null),[scriptLoaded,setScriptLoaded]=useState15(typeof google<"u"),[initialized,setInitialized]=useState15(!1),[buttonRendered,setButtonRendered]=useState15(!1);return useEffect4(()=>{if(typeof google>"u"){createScriptTag("https://accounts.google.com/gsi/client",()=>setScriptLoaded(!0));return}initialized||(google.accounts.id.initialize({client_id:googleClientId,callback:handleGoogleCredential}),setInitialized(!0)),parentRef.current&&!buttonRendered&&(google.accounts.id.renderButton(parentRef.current,{}),setButtonRendered(!0))},[medplum,googleClientId,initialized,scriptLoaded,parentRef,buttonRendered,handleGoogleCredential]),googleClientId?jsx34("div",{ref:parentRef}):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__"}import{Alert as Alert3}from"@mantine/core";import{operationOutcomeIssueToString}from"@medplum/core";import{jsx as jsx35}from"react/jsx-runtime";function OperationOutcomeAlert(props){let issues=props.outcome?.issue||props.issues;return!issues||issues.length===0?null:jsx35(Alert3,{icon:jsx35(IconAlertCircle,{size:16}),color:"red",children:issues.map(issue=>jsx35("div",{"data-testid":"text-field-error",children:operationOutcomeIssueToString(issue)},issue.details?.text))})}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 jsx36,jsxs as jsxs19}from"react/jsx-runtime";function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=useMedplum8(),[outcome,setOutcome]=useState16(),issues=getIssuesForExpression(outcome,void 0);return useEffect5(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsxs19(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(normalizeOperationOutcome3(err))}},children:[jsx36(Center4,{style:{flexDirection:"column"},children:props.children}),jsx36(OperationOutcomeAlert,{issues}),googleClientId&&jsxs19(Fragment11,{children:[jsx36(Group10,{justify:"center",p:"xl",style:{height:70},children:jsx36(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(normalizeOperationOutcome3(err))}}})}),jsx36(Divider,{label:"or",labelPosition:"center",my:"lg"})]}),jsxs19(Stack5,{gap:"xl",children:[jsx36(TextInput6,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),jsx36(TextInput6,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),jsx36(TextInput6,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),jsx36(PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")}),jsxs19(Text8,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx36(Anchor4,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx36(Anchor4,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),jsxs19(Text8,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",jsx36(Anchor4,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx36(Anchor4,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]}),jsxs19(Group10,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[jsx36(Checkbox,{name:"remember",label:"Remember me",size:"xs"}),jsx36(SubmitButton,{children:"Create account"})]})]})}import{jsx as jsx37,jsxs as jsxs20}from"react/jsx-runtime";function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=useMedplum9(),[login,setLogin]=useState17(),[outcome,setOutcome]=useState17();useEffect6(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome4(err)))},[medplum,type,projectId,login,onSuccess]);function handleAuthResponse(response){response.code?medplum.processCode(response.code).then(()=>onSuccess()).catch(console.log):response.login&&setLogin(response.login)}return jsxs20(Document,{width:450,children:[outcome&&jsx37("pre",{children:JSON.stringify(outcome,null,2)}),!login&&jsx37(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&jsx37(NewProjectForm,{login,handleAuthResponse})]})}import{showNotification as showNotification4}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString5}from"@medplum/core";import{useMedplum as useMedplum13}from"@medplum/react-hooks";import{useCallback as useCallback6,useEffect as useEffect7,useRef as useRef7,useState as useState20}from"react";import{Anchor as Anchor5,Center as Center5,Checkbox as Checkbox2,Divider as Divider2,Group as Group11,PasswordInput as PasswordInput2,Stack as Stack6,TextInput as TextInput7}from"@mantine/core";import{locationUtils as locationUtils4,normalizeOperationOutcome as normalizeOperationOutcome5}from"@medplum/core";import{useMedplum as useMedplum10}from"@medplum/react-hooks";import{useCallback as useCallback5,useState as useState18}from"react";import{Fragment as Fragment12,jsx as jsx38,jsxs as jsxs21}from"react/jsx-runtime";function AuthenticationForm(props){let[email,setEmail]=useState18();return email?jsx38(PasswordForm,{email,...props}):jsx38(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=useMedplum10(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=useState18(),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}),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(normalizeOperationOutcome5(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return jsxs21(Form,{onSubmit:handleSubmit,children:[jsx38(Center5,{style:{flexDirection:"column"},children}),jsx38(OperationOutcomeAlert,{issues}),googleClientId&&jsxs21(Fragment12,{children:[jsx38(Group11,{justify:"center",p:"xl",style:{height:70},children:jsx38(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&jsx38(Divider2,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&jsx38(TextInput7,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")}),jsxs21(Group11,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[jsx38("div",{children:onRegister&&jsx38(Anchor5,{component:"button",type:"button",c:"dimmed",onClick:onRegister,size:"xs","data-dashlane-ignore":"true","data-lp-ignore":"true","data-no-autofill":"true","data-form-type":"navigation",children:"Register"})}),!disableEmailAuth&&jsx38(SubmitButton,{children:"Next"})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=useMedplum10(),[outcome,setOutcome]=useState18(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=useCallback5(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome5(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return jsxs21(Form,{onSubmit:handleSubmit,children:[jsx38(Center5,{style:{flexDirection:"column"},children}),jsx38(OperationOutcomeAlert,{issues}),jsx38(Stack6,{gap:"xl",children:jsx38(PasswordInput2,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password")})}),jsxs21(Group11,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[onForgotPassword&&jsx38(Anchor5,{component:"button",type:"button",c:"dimmed",onClick:onForgotPassword,size:"xs",children:"Forgot password"}),jsx38(Checkbox2,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),jsx38(SubmitButton,{children:"Sign in"})]})]})}import{Avatar as Avatar3,Combobox as Combobox2,Flex,Group as Group12,Stack as Stack7,Text as Text9,TextInput as TextInput8,Title as Title3,useCombobox as useCombobox2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome6}from"@medplum/core";import{useMedplum as useMedplum11}from"@medplum/react-hooks";import{useState as useState19}from"react";import{jsx as jsx39,jsxs as jsxs22}from"react/jsx-runtime";function ChooseProfileForm(props){let medplum=useMedplum11(),combobox=useCombobox2(),[search,setSearch]=useState19(""),[outcome,setOutcome]=useState19();function filterDisplay(display){return!!display?.toLowerCase()?.includes(search.toLowerCase())}function filterMembership(membership){return filterDisplay(membership.profile?.display)||filterDisplay(membership.project?.display)}function handleValueSelect(membershipId){medplum.post("auth/profile",{login:props.login,profile:membershipId}).then(props.handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome6(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>jsx39(Combobox2.Option,{value:item.id,children:jsx39(SelectOption,{...item})},item.id));return jsxs22(Stack7,{children:[jsxs22(Flex,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[jsx39(Logo,{size:32}),jsx39(Title3,{order:3,children:"Choose profile"})]}),jsx39(OperationOutcomeAlert,{outcome}),jsxs22(Combobox2,{store:combobox,onOptionSubmit:handleValueSelect,children:[jsx39(Combobox2.EventsTarget,{children:jsx39(TextInput8,{placeholder:"Search",value:search,onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),jsx39("div",{children:jsx39(Combobox2.Options,{children:options.length>0?options:jsx39(Combobox2.Empty,{children:"Nothing found..."})})})]})]})}function SelectOption(membership){return jsxs22(Group12,{children:[jsx39(Avatar3,{radius:"xl"}),jsxs22("div",{children:[jsx39(Text9,{fz:"sm",fw:500,children:membership.profile?.display}),jsx39(Text9,{fz:"xs",opacity:.6,children:membership.project?.display})]})]})}import{Center as Center6,Checkbox as Checkbox3,Group as Group13,Stack as Stack8,Title as Title4}from"@mantine/core";import{useMedplum as useMedplum12}from"@medplum/react-hooks";import{Fragment as Fragment13}from"react/jsx-runtime";import{jsx as jsx40,jsxs as jsxs23}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=useMedplum12();return jsx40(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:jsxs23(Stack8,{children:[jsxs23(Center6,{style:{flexDirection:"column"},children:[jsx40(Logo,{size:32}),jsx40(Title4,{children:"Choose scope"})]}),jsx40(Stack8,{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]),jsxs23(Fragment13,{children:[jsx40(Checkbox3,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName),additionalScopes?.map(scope=>jsx40(Checkbox3,{id:scope,name:scope,label:scope},scope))]},scopeName+"_group")})}),jsx40(Group13,{justify:"flex-end",mt:"xl",children:jsx40(SubmitButton,{children:"Set scope"})})]})})}import{jsx as jsx41}from"react/jsx-runtime";function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=useMedplum13(),[login,setLogin]=useState20(),loginRequested=useRef7(!1),[mfaEnrollRequired,setMfaEnrollRequired]=useState20(!1),[enrollQrCode,setEnrollQrCode]=useState20(),[mfaRequired,setMfaRequired]=useState20(!1),[memberships,setMemberships]=useState20(),handleCode=useCallback6(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>showNotification4({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=>showNotification4({color:"red",message:normalizeErrorString5(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),jsx41(Document,{width:450,px:"sm",py:"md",children:login?mfaEnrollRequired&&enrollQrCode?jsx41(MfaForm,{title:"Enroll in MFA",buttonText:"Enroll",qrCodeUrl:enrollQrCode,onSubmit:async fields=>{let res=await medplum.post("auth/mfa/login-enroll",{login,token:fields.token});handleAuthResponse(res)}}):mfaRequired?jsx41(MfaForm,{title:"Enter MFA code",buttonText:"Submit code",onSubmit:async fields=>{let res=await medplum.post("auth/mfa/verify",{login,token:fields.token});handleAuthResponse(res)}}):memberships?jsx41(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.projectId==="new"?jsx41(NewProjectForm,{login,handleAuthResponse}):props.chooseScopes?jsx41(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):jsx41("div",{children:"Success"}):jsx41(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 ActionIcon2,CopyButton,Flex as Flex2,Tooltip}from"@mantine/core";import{PropertyType,formatDateTime,formatPeriod,formatTiming,isEmpty}from"@medplum/core";import{useState as useState23}from"react";import{formatCodeableConcept}from"@medplum/core";import{Fragment as Fragment14,jsx as jsx42}from"react/jsx-runtime";function CodeableConceptDisplay(props){return jsx42(Fragment14,{children:formatCodeableConcept(props.value)})}import{formatCoding}from"@medplum/core";import{Fragment as Fragment15,jsx as jsx43}from"react/jsx-runtime";function CodingDisplay(props){return jsx43(Fragment15,{children:formatCoding(props.value)})}import{Fragment as Fragment16,jsx as jsx44}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("]")),jsx44(Fragment16,{children:builder.join("").trim()})}import{Fragment as Fragment17,jsx as jsx45,jsxs as jsxs24}from"react/jsx-runtime";function ContactDetailDisplay(props){let contactDetail=props.value;return contactDetail?jsxs24(Fragment17,{children:[contactDetail.name,contactDetail.name&&": ",contactDetail.telecom?.map(telecom=>jsx45(ContactPointDisplay,{value:telecom},`telecom-${contactDetail.name}-${telecom.value}`))]}):null}import{getDataType,isPopulated as isPopulated3,isProfileLoaded,tryGetProfile}from"@medplum/core";import{useMedplum as useMedplum14}from"@medplum/react-hooks";import{useContext as useContext3,useEffect as useEffect8,useMemo as useMemo3,useState as useState21}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 jsx46}from"react/jsx-runtime";function ExtensionDisplay(props){let{elementDefinitionType}=props,medplum=useMedplum14(),ctx=useContext3(ElementsContext),[typeSchema,setTypeSchema]=useState21(getDataType("Extension")),profileUrl=useMemo3(()=>{if(isPopulated3(elementDefinitionType?.profile))return elementDefinitionType.profile[0]},[elementDefinitionType]),[loadingProfile,setLoadingProfile]=useState21(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 jsx46("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 jsx46(ResourcePropertyDisplay,{propertyType,value:propertyValue})}return jsx46(BackboneElementDisplay,{path:props.path,value:{type:typeSchema.type,value:props.value},compact:props.compact,ignoreMissingValues:props.ignoreMissingValues,link:props.link,profileUrl})}import{jsxs as jsxs25}from"react/jsx-runtime";function IdentifierDisplay(props){return jsxs25("div",{children:[props.value?.system,": ",props.value?.value]})}import{formatMoney}from"@medplum/core";import{Fragment as Fragment18,jsx as jsx47}from"react/jsx-runtime";function MoneyDisplay(props){return jsx47(Fragment18,{children:formatMoney(props.value)})}import{formatQuantity}from"@medplum/core";import{Fragment as Fragment19,jsx as jsx48}from"react/jsx-runtime";function QuantityDisplay(props){return jsx48(Fragment19,{children:formatQuantity(props.value)})}import{formatRange}from"@medplum/core";import{Fragment as Fragment20,jsx as jsx49}from"react/jsx-runtime";function RangeDisplay(props){return jsx49(Fragment20,{children:formatRange(props.value)})}import{Fragment as Fragment21,jsx as jsx50,jsxs as jsxs26}from"react/jsx-runtime";function RatioDisplay(props){let value=props.value;return value?jsxs26(Fragment21,{children:[jsx50(QuantityDisplay,{value:value.numerator}),"\xA0/\xA0",jsx50(QuantityDisplay,{value:value.denominator})]}):null}import{stringify}from"@medplum/core";import{Fragment as Fragment22,jsx as jsx51}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?jsx51(MedplumLink,{to:props.value,children:displayString}):jsx51(Fragment22,{children:displayString})}import{Group as Group14,Text as Text10}from"@mantine/core";import{getPathDisplayName as getPathDisplayName2,isPopulated as isPopulated6}from"@medplum/core";import{useMedplum as useMedplum15}from"@medplum/react-hooks";import{useContext as useContext5,useEffect as useEffect9,useMemo as useMemo5,useState as useState22}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 jsx52}from"react/jsx-runtime";function maybeWrapWithContext(ContextProvider,contextValue,contents){return contextValue!==void 0?jsx52(ContextProvider,{value:contextValue,children:contents}):contents}import{Fragment as Fragment23,jsx as jsx53}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,jsx53(Fragment23,{children:props.value.map((value,valueIndex)=>jsx53("div",{children:jsx53(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 Fragment24,jsx as jsx54,jsxs as jsxs27}from"react/jsx-runtime";var MAX_ARRAY_SIZE=50;function ResourceArrayDisplay(props){let{property,propertyType}=props,medplum=useMedplum15(),values=useMemo5(()=>Array.isArray(props.values)?props.values:[],[props.values]),[loading,setLoading]=useState22(!0),[slices,setSlices]=useState22([]),[slicedValues,setSlicedValues]=useState22(()=>[values]),[valuesLength,setValuesLength]=useState22(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 jsx54("div",{children:"Loading..."});let nonSliceContent;if(property.type[0]?.code!=="Extension"){let nonSliceValues=slicedValues[slices.length],nonSliceElements=nonSliceValues.map((value,valueIndex)=>jsx54("div",{children:jsx54(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=jsx54(DescriptionListEntry,{term:getPathDisplayName2(key),children:nonSliceElements})}else nonSliceContent=jsx54(Fragment24,{children:nonSliceElements})}return jsxs27(Fragment24,{children:[slices.map((slice,sliceIndex)=>{if(!props.path)throw Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);let sliceDisplay=jsx54(SliceDisplay,{path:props.path,slice,property,value:slicedValues[sliceIndex],ignoreMissingValues:props.ignoreMissingValues,link:props.link},slice.name);return props.includeDescriptionListEntry&&(sliceDisplay=jsx54(DescriptionListEntry,{term:getPathDisplayName2(slice.name),children:sliceDisplay},slice.name)),sliceDisplay}),nonSliceContent,valuesLength>MAX_ARRAY_SIZE&&jsx54(Group14,{justify:"right",children:jsxs27(Text10,{children:["... ",valuesLength," total values"]})})]})}import{Fragment as Fragment25,jsx as jsx55,jsxs as jsxs28}from"react/jsx-runtime";function ResourcePropertyDisplay(props){let{property,propertyType,value}=props;if(property?.path?.endsWith(".id"))return jsxs28(Flex2,{gap:3,align:"center",children:[value,!isEmpty(value)&&jsx55(CopyButton,{value,timeout:2e3,children:({copied,copy})=>jsx55(Tooltip,{label:copied?"Copied":"Copy",withArrow:!0,position:"right",children:jsx55(ActionIcon2,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,children:copied?jsx55(IconCheck,{size:"1rem"}):jsx55(IconCopy,{size:"1rem"})})})})]});if(property&&(property.isArray||property.max>1)&&!props.arrayElement)return propertyType===PropertyType.Attachment?jsx55(AttachmentArrayDisplay,{values:value,maxWidth:props.maxWidth,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,property,path:props.path}):jsx55(ResourceArrayDisplay,{path:props.path,property,propertyType,values:value,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,ignoreMissingValues:props.ignoreMissingValues,link:props.link});switch(propertyType){case PropertyType.boolean:return jsx55(Fragment25,{children:value===void 0?"":(!!value).toString()});case PropertyType.SystemString:case PropertyType.string:return props.property?.path?.toLowerCase().includes("secret")?jsx55(SecretFieldDisplay,{value}):jsx55("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:return jsx55(Fragment25,{children:value});case PropertyType.canonical:return jsx55(ReferenceDisplay,{value:{reference:value},link:props.link});case PropertyType.dateTime:case PropertyType.instant:return jsx55(Fragment25,{children:formatDateTime(value)});case PropertyType.markdown:return jsx55("pre",{children:value});case PropertyType.Address:return jsx55(AddressDisplay,{value});case PropertyType.Annotation:return jsx55(Fragment25,{children:value?.text});case PropertyType.Attachment:return jsx55(AttachmentDisplay,{value,maxWidth:props.maxWidth});case PropertyType.CodeableConcept:return jsx55(CodeableConceptDisplay,{value});case PropertyType.Coding:return jsx55(CodingDisplay,{value});case PropertyType.ContactDetail:return jsx55(ContactDetailDisplay,{value});case PropertyType.ContactPoint:return jsx55(ContactPointDisplay,{value});case PropertyType.HumanName:return jsx55(HumanNameDisplay,{value});case PropertyType.Identifier:return jsx55(IdentifierDisplay,{value});case PropertyType.Money:return jsx55(MoneyDisplay,{value});case PropertyType.Period:return jsx55(Fragment25,{children:formatPeriod(value)});case PropertyType.Quantity:case PropertyType.Duration:return jsx55(QuantityDisplay,{value});case PropertyType.Range:return jsx55(RangeDisplay,{value});case PropertyType.Ratio:return jsx55(RatioDisplay,{value});case PropertyType.Reference:return jsx55(ReferenceDisplay,{value,link:props.link});case PropertyType.Timing:return jsx55(Fragment25,{children:formatTiming(value)});case PropertyType.Dosage:case PropertyType.UsageContext:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return jsx55(BackboneElementDisplay,{path:props.path,value:{type:propertyType,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues});case PropertyType.Extension:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return jsx55(ExtensionDisplay,{path:props.path,value,compact:!0,ignoreMissingValues:props.ignoreMissingValues,elementDefinitionType:props.elementDefinitionType});default:if(!property)throw Error(`Displaying property of type ${props.propertyType} requires element schema`);if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return jsx55(BackboneElementDisplay,{path:props.path,value:{type:property.type[0].code,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues})}}function SecretFieldDisplay(props){let[isVisible,setIsVisible]=useState23(!1),secretValue=props.value??"",hasValue=!isEmpty(secretValue),MASK="\u2022".repeat(8);return jsxs28(Flex2,{gap:3,align:"center",children:[isVisible?jsx55("div",{style:{whiteSpace:"pre-wrap"},children:secretValue}):jsx55("div",{style:{whiteSpace:"pre-wrap"},"aria-hidden":"true",children:hasValue?MASK:""}),hasValue&&jsxs28(Fragment25,{children:[jsx55(CopyButton,{value:props.value,timeout:2e3,children:({copied,copy})=>jsx55(Tooltip,{label:copied?"Copied":"Copy secret",withArrow:!0,position:"right",children:jsx55(ActionIcon2,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,"aria-label":copied?"Copied":"Copy secret",children:copied?jsx55(IconCheck,{size:"1rem"}):jsx55(IconCopy,{size:"1rem"})})})}),jsx55(Tooltip,{label:isVisible?"Hide secret":"Show secret",withArrow:!0,position:"right",children:jsx55(ActionIcon2,{variant:"subtle",color:"gray",onClick:()=>setIsVisible(!isVisible),"aria-label":isVisible?"Hide secret":"Show secret",children:isVisible?jsx55(IconEyeOff,{size:"1rem"}):jsx55(IconEye,{size:"1rem"})})})]})]})}import{jsx as jsx56,jsxs as jsxs29}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 jsxs29("div",{children:[typeName,"\xA0not implemented"]});if(typeof value=="object"&&"name"in value&&Object.keys(value).length===1&&typeof value.name=="string")return jsx56("div",{children:value.name});let elementsContext=newElementsContext??parentElementsContext;return maybeWrapWithContext(ElementsContext.Provider,newElementsContext,jsx56(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=jsx56(ResourcePropertyDisplay,{property,propertyType,path:props.path+"."+key,value:propertyValue,ignoreMissingValues:props.ignoreMissingValues,includeArrayDescriptionListEntry:isArrayProperty,link:props.link},key);return isArrayProperty?resourcePropertyDisplay:jsx56(DescriptionListEntry,{term:getPathDisplayName3(key),children:resourcePropertyDisplay},key)})}))}import{buildElementsContext as buildElementsContext4,tryGetDataType as tryGetDataType2}from"@medplum/core";import{useContext as useContext23,useMemo as useMemo22,useState as useState44}from"react";import{Stack as Stack12}from"@mantine/core";import{getPathDisplayName as getPathDisplayName5}from"@medplum/core";import{useContext as useContext22,useMemo as useMemo21,useState as useState43}from"react";import{Group as Group15,Input}from"@mantine/core";import{useContext as useContext7}from"react";var FormSection_default={dimmed:"FormSection_dimmed",preserveBreaks:"FormSection_preserveBreaks"};import{Tooltip as Tooltip2}from"@mantine/core";import{jsx as jsx57}from"react/jsx-runtime";var READ_ONLY_TOOLTIP_TEXT="Read Only";function maybeWrapWithTooltip(tooltipText,children){return tooltipText?jsx57(Tooltip2.Floating,{label:tooltipText,children}):children}import{jsx as jsx58,jsxs as jsxs30}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,jsxs30(Group15,{wrap:"nowrap","data-testid":props.testId,children:[jsx58("div",{children:props.children}),jsx58("div",{children:jsx58(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 jsx59}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,jsx59(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 Group29,NativeSelect as NativeSelect9,Textarea as Textarea2,TextInput as TextInput17}from"@mantine/core";import{applyDefaultValuesToElement,capitalize as capitalize2,getPathDifference,HTTP_HL7_ORG,isComplexTypeCode,isEmpty as isEmpty6,isPopulated as isPopulated11,PropertyType as PropertyType2}from"@medplum/core";import{useContext as useContext21,useMemo as useMemo20,useState as useState42}from"react";import{useState as useState24}from"react";import{jsx as jsx60}from"react/jsx-runtime";function CodeableConceptInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,outcome:_outcome,path:_path,valuePath:_valuePath,...rest}=props,[value,setValue]=useState24(defaultValue2);function handleChange(newValues){let newConcept=valueSetElementToCodeableConcept(newValues);setValue(newConcept),onChange&&onChange(newConcept)}return jsx60(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 useState25}from"react";import{jsx as jsx61}from"react/jsx-runtime";function CodingInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,response,...rest}=props,[value,setValue]=useState25(response?.answer?.[0]?.valueCoding??defaultValue2);function handleChange(newValues){let newValue=newValues[0],newConcept=newValue&&valueSetElementToCoding(newValue);setValue(newConcept),onChange&&onChange(newConcept)}return jsx61(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 Group17,TextInput as TextInput10}from"@mantine/core";import{useContext as useContext10,useMemo as useMemo8,useRef as useRef9,useState as useState27}from"react";import{Group as Group16,NativeSelect as NativeSelect3,TextInput as TextInput9}from"@mantine/core";import{useContext as useContext9,useMemo as useMemo7,useRef as useRef8,useState as useState26}from"react";import{jsx as jsx62,jsxs as jsxs31}from"react/jsx-runtime";function ContactPointInput(props){let{path,outcome}=props,{elementsByPath,getExtendedProps}=useContext9(ElementsContext),[contactPoint,setContactPoint]=useState26(props.defaultValue),ref=useRef8(contactPoint);ref.current=contactPoint;let[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={...ref.current,system};system||delete newValue.system,setContactPointWrapper(newValue)}function setUse(use){let newValue={...ref.current,use};use||delete newValue.use,setContactPointWrapper(newValue)}function setValue(value){let newValue={...ref.current,value};value||delete newValue.value,setContactPointWrapper(newValue)}let errorPath=props.valuePath??path;return jsxs31(Group16,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx62(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")}),jsx62(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")}),jsx62(TextInput9,{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 jsx63,jsxs as jsxs32}from"react/jsx-runtime";function ContactDetailInput(props){let[contactDetail,setContactDetail]=useState27(props.defaultValue),ref=useRef9(contactDetail);ref.current=contactDetail;let{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={...ref.current,name};name||delete newValue.name,setContactDetailWrapper(newValue)}function setTelecom(telecom){let newValue={...ref.current,telecom:telecom&&[telecom]};telecom||delete newValue.telecom,setContactDetailWrapper(newValue)}return jsxs32(Group17,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx63(TextInput10,{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)}),jsx63(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 TextInput11}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 jsx64}from"react/jsx-runtime";function DateTimeInput(props){return jsx64(TextInput11,{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 useMedplum16}from"@medplum/react-hooks";import{useEffect as useEffect10,useMemo as useMemo9,useState as useState28}from"react";import{jsx as jsx65}from"react/jsx-runtime";function ExtensionInput(props){let{propertyType}=props,medplum=useMedplum16(),profileUrl=useMemo9(()=>{if(isPopulated7(propertyType.profile))return propertyType.profile[0]},[propertyType]),[loadingProfile,setLoadingProfile]=useState28(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))?jsx65("div",{children:"Loading..."}):jsx65(BackboneElementInput,{profileUrl,path:props.path,typeName:"Extension",defaultValue:props.defaultValue,onChange:props.onChange})}import{Group as Group18,NativeSelect as NativeSelect4,TextInput as TextInput12}from"@mantine/core";import{useContext as useContext11,useMemo as useMemo10,useState as useState29}from"react";import{jsx as jsx66,jsxs as jsxs33}from"react/jsx-runtime";function HumanNameInput(props){let{outcome,path}=props,[value,setValue]=useState29(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 jsxs33(Group18,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx66(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")}),jsx66(TextInput12,{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")}),jsx66(TextInput12,{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")}),jsx66(TextInput12,{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")}),jsx66(TextInput12,{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 Group19,TextInput as TextInput13}from"@mantine/core";import{useContext as useContext12,useMemo as useMemo11,useState as useState30}from"react";import{jsx as jsx67,jsxs as jsxs34}from"react/jsx-runtime";function IdentifierInput(props){let[value,setValue]=useState30(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 jsxs34(Group19,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx67(TextInput13,{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")}),jsx67(TextInput13,{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 TextInput14}from"@mantine/core";import{useCallback as useCallback7,useContext as useContext13,useMemo as useMemo12,useState as useState31}from"react";import{jsx as jsx68}from"react/jsx-runtime";var data=["USD","EUR","CAD","GBP","AUD"];function MoneyInput(props){let{onChange}=props,[value,setValue]=useState31(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=jsx68(NativeSelect5,{disabled:props.disabled||currencyProps?.readonly,defaultValue:value?.currency,data,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:handleCurrencyChange});return jsx68(TextInput14,{disabled:props.disabled||valueProps?.readonly,type:"number",name:props.name,label:props.label,placeholder:props.placeholder??"Value",defaultValue:value?.value?.toString()??"USD",leftSection:jsx68(IconCurrencyDollar,{size:14}),rightSection:select,rightSectionWidth:92,onChange:handleValueChange})}import{Group as Group20}from"@mantine/core";import{useContext as useContext14,useMemo as useMemo13,useState as useState32}from"react";import{jsx as jsx69,jsxs as jsxs35}from"react/jsx-runtime";function PeriodInput(props){let[value,setValue]=useState32(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 jsxs35(Group20,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx69(DateTimeInput,{disabled:props.disabled||startProps?.readonly,name:props.name+".start",placeholder:"Start",defaultValue:value?.start,onChange:newValue=>setValueWrapper({...value,start:newValue})}),jsx69(DateTimeInput,{disabled:props.disabled||endProps?.readonly,name:props.name+".end",placeholder:"End",defaultValue:value?.end,onChange:newValue=>setValueWrapper({...value,end:newValue})})]})}import{Group as Group21,NativeSelect as NativeSelect6,TextInput as TextInput15}from"@mantine/core";import{useContext as useContext15,useMemo as useMemo14,useState as useState33}from"react";import{jsx as jsx70,jsxs as jsxs36}from"react/jsx-runtime";function QuantityInput(props){let[value,setValue]=useState33(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 jsxs36(Group21,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx70(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})}),jsx70(TextInput15,{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)})}}),jsx70(TextInput15,{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 parseFloat(str)}import{Group as Group22}from"@mantine/core";import{useContext as useContext16,useMemo as useMemo15,useState as useState34}from"react";import{jsx as jsx71,jsxs as jsxs37}from"react/jsx-runtime";function RangeInput(props){let[value,setValue]=useState34(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 jsxs37(Group22,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx71(QuantityInput,{path:props.path+".low",disabled:props.disabled||lowProps?.readonly,name:props.name+"-low",defaultValue:value?.low,onChange:v=>setValueWrapper({...value,low:v})}),jsx71(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 Group23}from"@mantine/core";import{useContext as useContext17,useMemo as useMemo16,useState as useState35}from"react";import{jsx as jsx72,jsxs as jsxs38}from"react/jsx-runtime";function RatioInput(props){let[value,setValue]=useState35(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 jsxs38(Group23,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx72(QuantityInput,{path:props.path+".numerator",disabled:props.disabled||numeratorProps?.readonly,name:props.name+"-numerator",defaultValue:value?.numerator,onChange:v=>setValueWrapper({...value,numerator:v})}),jsx72(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 Group25,NativeSelect as NativeSelect7}from"@mantine/core";import{LRUCache,ReadablePromise,createReference as createReference2,isEmpty as isEmpty4,isPopulated as isPopulated9,tryGetProfile as tryGetProfile3}from"@medplum/core";import{useMedplum as useMedplum18}from"@medplum/react-hooks";import{useCallback as useCallback9,useEffect as useEffect11,useMemo as useMemo17,useRef as useRef10,useState as useState37}from"react";import{Group as Group24,Text as Text11}from"@mantine/core";import{getDisplayString as getDisplayString3,getReferenceString as getReferenceString3,isPopulated as isPopulated8}from"@medplum/core";import{useMedplum as useMedplum17,useResource as useResource2}from"@medplum/react-hooks";import{forwardRef as forwardRef4,useCallback as useCallback8,useState as useState36}from"react";import{jsx as jsx73,jsxs as jsxs39}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 ResourceInput(props){let medplum=useMedplum17(),{resourceType,searchCriteria}=props,[outcome,setOutcome]=useState36(),defaultValue2=useResource2(props.defaultValue,setOutcome),ItemComponent3=props.itemComponent??DefaultItemComponent2,onChange=props.onChange,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[0])},[onChange]);return isPopulated8(props.defaultValue)&&!outcome&&!defaultValue2?null:jsx73(AsyncAutocomplete,{disabled:props.disabled,name:props.name,label:props.label,error:props.error,required:props.required,itemComponent:ItemComponent3,defaultValue:defaultValue2,placeholder:props.placeholder,maxValues:1,toOption:toOption3,loadOptions:loadValues,onChange:handleChange,clearable:!0})}var DefaultItemComponent2=forwardRef4(({label,resource,active:_active,...others},ref)=>jsx73("div",{ref,...others,children:jsxs39(Group24,{wrap:"nowrap",children:[jsx73(ResourceAvatar,{value:resource}),jsxs39("div",{children:[jsx73(Text11,{children:label}),jsx73(Text11,{size:"xs",c:"dimmed",children:resource.birthDate||resource.id})]})]})}));function getSearchParamForResourceType(resourceType){return SEARCH_CODES[resourceType]??(NAME_RESOURCE_TYPES.includes(resourceType)?"name":"_id")}import{Fragment as Fragment26,jsx as jsx74,jsxs as jsxs40}from"react/jsx-runtime";function ReferenceInput(props){let{onChange}=props,medplum=useMedplum18(),[value,setValue]=useState37(props.defaultValue),[targetTypes,setTargetTypes]=useState37(()=>createTargetTypes(props.targetTypes)),[targetType,setTargetType]=useState37(()=>getInitialTargetType(props.defaultValue,targetTypes)),promiseCache=useRef10(new LRUCache),searchCriteria=useMemo17(()=>targetType?.type==="profile"?{...props.searchCriteria,_profile:targetType.value}:props.searchCriteria,[props.searchCriteria,targetType]);useEffect11(()=>{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?isPopulated9(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=useCallback9(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 jsxs40(Fragment26,{children:[props.name&&jsx74("input",{type:"hidden",name:props.name,value:value?.reference??""}),jsxs40(Group25,{gap:"xs",grow:!0,wrap:"nowrap",children:[targetTypes&&targetTypes.length>1&&jsx74(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&&jsx74(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"}),jsx74(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=`{
66
66
  StructureDefinitionList(url: "${profileUrl}", _sort: "_lastUpdated", _count: 1) {
67
67
  type,