@medplum/react 3.2.30 → 3.2.31

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.
@@ -62,7 +62,7 @@
62
62
  }
63
63
  }
64
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((0,import_core19.formatHumanName)(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}var import_jsx_runtime12=require("react/jsx-runtime");function Header(props){let profile=(0,import_react_hooks6.useMedplumProfile)(),[userMenuOpened,setUserMenuOpened]=(0,import_react8.useState)(!1);return(0,import_jsx_runtime12.jsx)(import_core20.AppShell.Header,{p:8,style:{zIndex:101},children:(0,import_jsx_runtime12.jsxs)(import_core20.Group,{justify:"space-between",children:[(0,import_jsx_runtime12.jsxs)(import_core20.Group,{gap:"xs",children:[(0,import_jsx_runtime12.jsx)(import_core20.UnstyledButton,{className:Header_default.logoButton,onClick:props.navbarToggle,children:props.logo}),!props.headerSearchDisabled&&(0,import_jsx_runtime12.jsx)(HeaderSearchInput,{pathname:props.pathname,searchParams:props.searchParams})]}),(0,import_jsx_runtime12.jsxs)(import_core20.Group,{gap:"lg",pr:"sm",children:[props.notifications,(0,import_jsx_runtime12.jsxs)(import_core20.Menu,{width:260,shadow:"xl",position:"bottom-end",transitionProps:{transition:"pop-top-right"},opened:userMenuOpened,onClose:()=>setUserMenuOpened(!1),children:[(0,import_jsx_runtime12.jsx)(import_core20.Menu.Target,{children:(0,import_jsx_runtime12.jsx)(import_core20.UnstyledButton,{className:clsx_default(Header_default.user,{[Header_default.userActive]:userMenuOpened}),onClick:()=>setUserMenuOpened(o=>!o),children:(0,import_jsx_runtime12.jsxs)(import_core20.Group,{gap:7,children:[(0,import_jsx_runtime12.jsx)(ResourceAvatar,{value:profile,radius:"xl",size:24}),(0,import_jsx_runtime12.jsx)(import_core20.Text,{size:"sm",className:Header_default.userName,children:(0,import_core21.formatHumanName)(profile?.name?.[0])}),(0,import_jsx_runtime12.jsx)(IconChevronDown,{size:12,stroke:1.5})]})})}),(0,import_jsx_runtime12.jsx)(import_core20.Menu.Dropdown,{children:(0,import_jsx_runtime12.jsx)(HeaderDropdown,{version:props.version})})]})]})]})})}var import_core25=require("@mantine/core"),import_react_hooks9=require("@medplum/react-hooks");var import_react12=require("react");var import_core22=require("@mantine/core"),import_notifications2=require("@mantine/notifications"),import_core23=require("@medplum/core"),import_react_hooks7=require("@medplum/react-hooks");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}var import_jsx_runtime13=require("react/jsx-runtime");function Form(props){return(0,import_jsx_runtime13.jsx)("form",{style:props.style,"data-testid":props.testid,onSubmit:e=>{e.preventDefault();let formData=parseForm(e.target);props.onSubmit&&props.onSubmit(formData)},children:props.children})}var import_jsx_runtime14=require("react/jsx-runtime");function BookmarkDialog(props){let medplum=(0,import_react_hooks7.useMedplum)(),config=medplum.getUserConfiguration();function submitHandler(formData){let{menuname,bookmarkname:name}=formData,target=`${props.pathname}?${props.searchParams.toString()}`,newConfig=(0,import_core23.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"}),(0,import_notifications2.showNotification)({color:"green",message:"Success"}),props.onOk()}).catch(err=>{(0,import_notifications2.showNotification)({color:"red",message:(0,import_core23.normalizeErrorString)(err)})})}return(0,import_jsx_runtime14.jsx)(import_core22.Modal,{title:"Add Bookmark",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:(0,import_jsx_runtime14.jsx)(Form,{onSubmit:submitHandler,children:(0,import_jsx_runtime14.jsxs)(import_core22.Stack,{children:[(0,import_jsx_runtime14.jsx)(SelectMenu,{config}),(0,import_jsx_runtime14.jsx)(import_core22.TextInput,{label:"Bookmark Name",type:"text",name:"bookmarkname",placeholder:"Bookmark Name",withAsterisk:!0}),(0,import_jsx_runtime14.jsx)(import_core22.Group,{justify:"flex-end",children:(0,import_jsx_runtime14.jsx)(import_core22.Button,{mt:"sm",type:"submit",children:"OK"})})]})})})}function SelectMenu(props){function userConfigToMenu(config){return config?.menu?.map(menu=>menu.title)}let menus=userConfigToMenu(props.config);return(0,import_jsx_runtime14.jsx)(import_core22.NativeSelect,{name:"menuname",defaultValue:menus[0],label:"Select Menu Option",data:menus,withAsterisk:!0})}var import_react11=require("react");var import_react10=require("react");var import_core24=require("@mantine/core"),import_react_hooks8=require("@medplum/react-hooks"),import_react9=require("react");var import_jsx_runtime15=require("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=(0,import_react_hooks8.useMedplum)(),{binding,creatable,clearable,expandParams,withHelpText,...rest}=props,loadValues=(0,import_react9.useCallback)(async(input,signal)=>{if(!binding)return[];let valueSetElements=(await medplum.valueSetExpand({...expandParams,url:binding,filter:input},{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(0,import_jsx_runtime15.jsx)(AsyncAutocomplete,{...rest,creatable:creatable??!0,clearable:clearable??!0,toOption:toOption2,loadOptions:loadValues,onCreate:createValue,itemComponent:withHelpText?ItemComponent2:void 0})}var ItemComponent2=(0,import_react9.forwardRef)(({label,resource,active,...others},ref)=>(0,import_jsx_runtime15.jsx)("div",{ref,...others,children:(0,import_jsx_runtime15.jsxs)(import_core24.Group,{wrap:"nowrap",gap:"xs",children:[active&&(0,import_jsx_runtime15.jsx)(IconCheck,{size:12}),(0,import_jsx_runtime15.jsxs)("div",{children:[(0,import_jsx_runtime15.jsx)(import_core24.Text,{children:label}),(0,import_jsx_runtime15.jsx)(import_core24.Text,{size:"xs",c:"dimmed",children:`${resource.system}#${resource.code}`})]})]})}));var import_jsx_runtime16=require("react/jsx-runtime");function CodeInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,...rest}=props,[value,setValue]=(0,import_react10.useState)(defaultValue2);function handleChange(newValues){let newValue=newValues[0],newCode=valueSetElementToCode(newValue);setValue(newCode),onChange&&onChange(newCode)}return(0,import_jsx_runtime16.jsx)(ValueSetAutocomplete,{defaultValue:codeToValueSetElement(value),onChange:handleChange,withHelpText:withHelpText??!0,...rest})}function codeToValueSetElement(code){return code?{code}:void 0}function valueSetElementToCode(element){return element?.code}var import_jsx_runtime17=require("react/jsx-runtime");function ResourceTypeInput(props){let[resourceType,setResourceType]=(0,import_react11.useState)(props.defaultValue),onChange=props.onChange,setResourceTypeWrapper=(0,import_react11.useCallback)(newResourceType=>{setResourceType(newResourceType),onChange&&onChange(newResourceType)},[onChange]);return(0,import_jsx_runtime17.jsx)(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"};var import_jsx_runtime18=require("react/jsx-runtime");function Navbar(props){let navigate=(0,import_react_hooks9.useMedplumNavigate)(),activeLink=getActiveLink(props.pathname,props.searchParams,props.menus),[bookmarkDialogVisible,setBookmarkDialogVisible]=(0,import_react12.useState)(!1);function onLinkClick(e,to){e.stopPropagation(),e.preventDefault(),navigate(to),window.innerWidth<768&&props.closeNavbar()}function navigateResourceType(resourceType){resourceType&&navigate(`/${resourceType}`)}return(0,import_jsx_runtime18.jsxs)(import_jsx_runtime18.Fragment,{children:[(0,import_jsx_runtime18.jsx)(import_core25.AppShell.Navbar,{children:(0,import_jsx_runtime18.jsxs)(import_core25.ScrollArea,{p:"xs",children:[!props.resourceTypeSearchDisabled&&(0,import_jsx_runtime18.jsx)(import_core25.AppShell.Section,{mb:"sm",children:(0,import_jsx_runtime18.jsx)(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",maxValues:0,onChange:newValue=>navigateResourceType(newValue)},window.location.pathname)}),(0,import_jsx_runtime18.jsxs)(import_core25.AppShell.Section,{grow:!0,children:[props.menus?.map(menu=>(0,import_jsx_runtime18.jsxs)(import_react12.Fragment,{children:[(0,import_jsx_runtime18.jsx)(import_core25.Text,{className:Navbar_default.menuTitle,children:menu.title}),menu.links?.map(link=>(0,import_jsx_runtime18.jsxs)(NavbarLink,{to:link.href,active:link.href===activeLink?.href,onClick:e=>onLinkClick(e,link.href),children:[(0,import_jsx_runtime18.jsx)(NavLinkIcon,{to:link.href,icon:link.icon}),(0,import_jsx_runtime18.jsx)("span",{children:link.label})]},link.href))]},`menu-${menu.title}`)),props.displayAddBookmark&&(0,import_jsx_runtime18.jsx)(import_core25.Button,{variant:"subtle",size:"xs",mt:"xl",leftSection:(0,import_jsx_runtime18.jsx)(IconPlus,{size:"0.75rem"}),onClick:()=>setBookmarkDialogVisible(!0),children:"Add Bookmark"})]})]})}),props.pathname&&props.searchParams&&(0,import_jsx_runtime18.jsx)(BookmarkDialog,{pathname:props.pathname,searchParams:props.searchParams,visible:bookmarkDialogVisible,onOk:()=>setBookmarkDialogVisible(!1),onCancel:()=>setBookmarkDialogVisible(!1)})]})}function NavbarLink(props){return(0,import_jsx_runtime18.jsx)(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:(0,import_jsx_runtime18.jsx)(import_core25.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}var import_jsx_runtime19=require("react/jsx-runtime");function AppShell(props){let[navbarOpen,setNavbarOpen]=(0,import_react13.useState)(localStorage.navbarOpen==="true"),medplum=(0,import_react_hooks10.useMedplum)(),profile=(0,import_react_hooks10.useMedplumProfile)();(0,import_react13.useEffect)(()=>{function eventListener(){(0,import_notifications3.showNotification)({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()?(0,import_jsx_runtime19.jsx)(Loading,{}):(0,import_jsx_runtime19.jsxs)(import_core26.AppShell,{header:{height:60},navbar:{width:250,breakpoint:"sm",collapsed:{desktop:!profile||!navbarOpen,mobile:!profile||!navbarOpen}},padding:0,children:[profile&&(0,import_jsx_runtime19.jsx)(Header,{pathname:props.pathname,searchParams:props.searchParams,headerSearchDisabled:props.headerSearchDisabled,logo:props.logo,version:props.version,navbarToggle:toggleNavbar,notifications:props.notifications}),profile&&navbarOpen?(0,import_jsx_runtime19.jsx)(Navbar,{pathname:props.pathname,searchParams:props.searchParams,menus:props.menus,closeNavbar,displayAddBookmark:props.displayAddBookmark,resourceTypeSearchDisabled:props.resourceTypeSearchDisabled}):void 0,(0,import_jsx_runtime19.jsx)(import_core26.AppShell.Main,{className:AppShell_default.main,children:(0,import_jsx_runtime19.jsx)(ErrorBoundary,{children:(0,import_jsx_runtime19.jsx)(import_react13.Suspense,{fallback:(0,import_jsx_runtime19.jsx)(Loading,{}),children:props.children})})})]})}var import_core27=require("@mantine/core"),import_core28=require("@medplum/core"),import_react_hooks11=require("@medplum/react-hooks");var import_react14=require("react");var import_jsx_runtime20=require("react/jsx-runtime"),CCDA_VIEWER_URL="https://ccda.medplum.com";function CcdaDisplay(props){let{url}=props,[shouldSend,setShouldSend]=(0,import_react14.useState)(!1),iframeRef=(0,import_react14.useRef)(null);return(0,import_react14.useEffect)(()=>{url&&shouldSend&&iframeRef.current&&(sendCommand(iframeRef.current,{command:"loadCcdaXml",value:url}).catch(console.error),setShouldSend(!1))},[url,shouldSend]),url?(0,import_jsx_runtime20.jsx)("div",{"data-testid":"ccda-iframe",style:{maxWidth:props.maxWidth,minHeight:400},children:(0,import_jsx_runtime20.jsx)("iframe",{title:"C-CDA Viewer",width:"100%",height:"400",ref:iframeRef,src:CCDA_VIEWER_URL,allowFullScreen:!0,frameBorder:0,seamless:!0,onLoad:()=>setShouldSend(!0)})}):null}var import_jsx_runtime21=require("react/jsx-runtime");function AttachmentDisplay(props){let{contentType,url:uncachedUrl,title}=props.value??{},url=(0,import_react_hooks11.useCachedBinaryUrl)(uncachedUrl);return url?(0,import_jsx_runtime21.jsxs)("div",{"data-testid":"attachment-display",children:[contentType?.startsWith("image/")&&(0,import_jsx_runtime21.jsx)("img",{"data-testid":"attachment-image",style:{maxWidth:props.maxWidth},src:url,alt:title}),contentType?.startsWith("video/")&&(0,import_jsx_runtime21.jsx)("video",{"data-testid":"attachment-video",style:{maxWidth:props.maxWidth},controls:!0,children:(0,import_jsx_runtime21.jsx)("source",{type:contentType,src:url})}),(contentType?.startsWith("text/")||contentType==="application/json"||contentType==="application/pdf")&&(0,import_jsx_runtime21.jsx)("div",{"data-testid":"attachment-iframe",style:{maxWidth:props.maxWidth,minHeight:400},children:(0,import_jsx_runtime21.jsx)("iframe",{width:"100%",height:"400",src:url+"#navpanes=0",allowFullScreen:!0,frameBorder:0,seamless:!0})}),contentType===import_core28.ContentType.CDA_XML&&(0,import_jsx_runtime21.jsx)(CcdaDisplay,{url}),(0,import_jsx_runtime21.jsx)("div",{"data-testid":"download-link",style:{padding:"2px 16px 16px 16px"},children:(0,import_jsx_runtime21.jsx)(import_core27.Anchor,{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"};var import_jsx_runtime22=require("react/jsx-runtime");function DescriptionList(props){let{children,compact}=props;return(0,import_jsx_runtime22.jsx)("dl",{className:clsx_default(DescriptionList_default.root,{[DescriptionList_default.compact]:compact}),children})}function DescriptionListEntry(props){return(0,import_jsx_runtime22.jsxs)(import_jsx_runtime22.Fragment,{children:[(0,import_jsx_runtime22.jsx)("dt",{children:props.term}),(0,import_jsx_runtime22.jsx)("dd",{children:props.children})]})}var import_core29=require("@medplum/core"),import_jsx_runtime23=require("react/jsx-runtime");function AttachmentArrayDisplay(props){let attachmentElements=props.values?.map((v,index)=>(0,import_jsx_runtime23.jsx)("div",{children:(0,import_jsx_runtime23.jsx)(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(!(0,import_core29.isPopulated)(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();content=(0,import_jsx_runtime23.jsx)(DescriptionListEntry,{term:(0,import_core29.getPathDisplayName)(key),children:attachmentElements})}else content=(0,import_jsx_runtime23.jsx)(import_jsx_runtime23.Fragment,{children:attachmentElements});return content}var import_core31=require("@mantine/core");var import_react16=require("react");var import_core30=require("@medplum/core"),import_react_hooks12=require("@medplum/react-hooks"),import_react15=require("react");var import_jsx_runtime24=require("react/jsx-runtime");function AttachmentButton(props){let medplum=(0,import_react_hooks12.useMedplum)(),fileInputRef=(0,import_react15.useRef)(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((0,import_core30.normalizeOperationOutcome)(err))}))}return(0,import_jsx_runtime24.jsxs)(import_jsx_runtime24.Fragment,{children:[(0,import_jsx_runtime24.jsx)("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})]})}var import_jsx_runtime25=require("react/jsx-runtime");function AttachmentArrayInput(props){let[values,setValues]=(0,import_react16.useState)(props.defaultValue??[]),valuesRef=(0,import_react16.useRef)();valuesRef.current=values;function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}return(0,import_jsx_runtime25.jsxs)("table",{style:{width:"100%"},children:[(0,import_jsx_runtime25.jsxs)("colgroup",{children:[(0,import_jsx_runtime25.jsx)("col",{width:"97%"}),(0,import_jsx_runtime25.jsx)("col",{width:"3%"})]}),(0,import_jsx_runtime25.jsxs)("tbody",{children:[values.map((v,index)=>(0,import_jsx_runtime25.jsxs)("tr",{children:[(0,import_jsx_runtime25.jsx)("td",{children:(0,import_jsx_runtime25.jsx)(AttachmentDisplay,{value:v,maxWidth:200})}),(0,import_jsx_runtime25.jsx)("td",{children:(0,import_jsx_runtime25.jsx)(import_core31.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:(0,import_jsx_runtime25.jsx)(IconCircleMinus,{})})})]},`${index}-${values.length}`)),(0,import_jsx_runtime25.jsxs)("tr",{children:[(0,import_jsx_runtime25.jsx)("td",{}),(0,import_jsx_runtime25.jsx)("td",{children:(0,import_jsx_runtime25.jsx)(AttachmentButton,{disabled:props.disabled,onUpload:attachment=>{setValuesWrapper([...valuesRef.current,attachment])},children:props2=>(0,import_jsx_runtime25.jsx)(import_core31.ActionIcon,{...props2,title:"Add",variant:"subtle",size:"sm",color:props2.disabled?"gray":"green",children:(0,import_jsx_runtime25.jsx)(IconCloudUpload,{})})})})]})]})]})}var import_core32=require("@mantine/core"),import_react17=require("react");var import_jsx_runtime26=require("react/jsx-runtime");function AttachmentInput(props){let[value,setValue]=(0,import_react17.useState)(props.defaultValue);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return value?(0,import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment,{children:[(0,import_jsx_runtime26.jsx)(AttachmentDisplay,{value,maxWidth:200}),(0,import_jsx_runtime26.jsx)(import_core32.Button,{disabled:props.disabled,onClick:e=>{killEvent(e),setValueWrapper(void 0)},children:"Remove"})]}):(0,import_jsx_runtime26.jsx)(AttachmentButton,{disabled:props.disabled,securityContext:props.securityContext,onUpload:setValueWrapper,children:props2=>(0,import_jsx_runtime26.jsx)(import_core32.Button,{...props2,children:"Upload..."})})}var import_core41=require("@medplum/core"),import_react_hooks16=require("@medplum/react-hooks"),import_react21=require("react");var import_core33=require("@mantine/core");var Container_default={root:"Container_root"};var import_jsx_runtime27=require("react/jsx-runtime");function Container(props){let{children,...others}=props;return(0,import_jsx_runtime27.jsx)(import_core33.Container,{className:Container_default.root,...others,children})}var import_core34=require("@mantine/core");var Panel_default={paper:"Panel_paper",fill:"Panel_fill"};var import_jsx_runtime28=require("react/jsx-runtime");function Panel(props){let{width,fill,className,children,...rest}=props,style=width?{maxWidth:width}:void 0;return(0,import_jsx_runtime28.jsx)(import_core34.Paper,{className:clsx_default(Panel_default.paper,fill&&Panel_default.fill,className),style,shadow:"sm",radius:"sm",withBorder:!0,...rest,children})}var import_jsx_runtime29=require("react/jsx-runtime");function Document(props){let{children,...others}=props;return(0,import_jsx_runtime29.jsx)(Container,{children:(0,import_jsx_runtime29.jsx)(Panel,{...others,children})})}var import_core35=require("@mantine/core"),import_core36=require("@medplum/core"),import_react_hooks13=require("@medplum/react-hooks"),import_react18=require("react");var import_jsx_runtime30=require("react/jsx-runtime");function Logo(props){return(0,import_jsx_runtime30.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 491 491",style:{width:props.size,height:props.size},children:[(0,import_jsx_runtime30.jsx)("title",{children:"Medplum Logo"}),(0,import_jsx_runtime30.jsx)("path",{fill:props.fill??"#ad7136",d:"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z"}),(0,import_jsx_runtime30.jsx)("path",{fill:props.fill??"#946af9",d:"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z"}),(0,import_jsx_runtime30.jsx)("path",{fill:props.fill??"#7857c5",d:"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z"}),(0,import_jsx_runtime30.jsx)("path",{fill:props.fill??"#40bc26",d:"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z"}),(0,import_jsx_runtime30.jsx)("path",{fill:props.fill??"#33961e",d:"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z"})]})}function getErrorsForInput(outcome,expression){return outcome?.issue?.filter(issue=>isExpressionMatch(issue.expression?.[0],expression))?.map(issue=>issue.details?.text)?.join(`
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}var import_jsx_runtime31=require("react/jsx-runtime");function NewProjectForm(props){let medplum=(0,import_react_hooks13.useMedplum)(),[outcome,setOutcome]=(0,import_react18.useState)();return(0,import_jsx_runtime31.jsxs)(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome((0,import_core36.normalizeOperationOutcome)(err))}},children:[(0,import_jsx_runtime31.jsxs)(import_core35.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime31.jsx)(Logo,{size:32}),(0,import_jsx_runtime31.jsx)(import_core35.Title,{children:"Create project"})]}),(0,import_jsx_runtime31.jsxs)(import_core35.Stack,{gap:"xl",children:[(0,import_jsx_runtime31.jsx)(import_core35.TextInput,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")}),(0,import_jsx_runtime31.jsxs)(import_core35.Text,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",(0,import_jsx_runtime31.jsx)(import_core35.Anchor,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime31.jsx)(import_core35.Anchor,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]}),(0,import_jsx_runtime31.jsx)(import_core35.Group,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:(0,import_jsx_runtime31.jsx)(import_core35.Button,{type:"submit",children:"Create project"})})]})}var import_core39=require("@mantine/core"),import_core40=require("@medplum/core"),import_react_hooks15=require("@medplum/react-hooks"),import_react20=require("react");var import_react_hooks14=require("@medplum/react-hooks"),import_react19=require("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)}var import_jsx_runtime32=require("react/jsx-runtime");function GoogleButton(props){let medplum=(0,import_react_hooks14.useMedplum)(),{googleClientId,handleGoogleCredential}=props,parentRef=(0,import_react19.useRef)(null),[scriptLoaded,setScriptLoaded]=(0,import_react19.useState)(typeof google<"u"),[initialized,setInitialized]=(0,import_react19.useState)(!1),[buttonRendered,setButtonRendered]=(0,import_react19.useState)(!1);return(0,import_react19.useEffect)(()=>{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?(0,import_jsx_runtime32.jsx)("div",{ref:parentRef}):null}function getGoogleClientId(clientId){if(clientId)return clientId;if(typeof window<"u"){let origin=window.location.protocol+"//"+window.location.host;if(("undefined"?.split(",")??[]).includes(origin))return"__GOOGLE_CLIENT_ID__"}}var import_core37=require("@mantine/core"),import_core38=require("@medplum/core");var import_jsx_runtime33=require("react/jsx-runtime");function OperationOutcomeAlert(props){let issues=props.outcome?.issue||props.issues;return!issues||issues.length===0?null:(0,import_jsx_runtime33.jsx)(import_core37.Alert,{icon:(0,import_jsx_runtime33.jsx)(IconAlertCircle,{size:16}),color:"red",children:issues.map(issue=>(0,import_jsx_runtime33.jsx)("div",{"data-testid":"text-field-error",children:(0,import_core38.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)}})})}var import_jsx_runtime34=require("react/jsx-runtime");function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=(0,import_react_hooks15.useMedplum)(),[outcome,setOutcome]=(0,import_react20.useState)(),issues=getIssuesForExpression(outcome,void 0);return(0,import_react20.useEffect)(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),(0,import_jsx_runtime34.jsxs)(Form,{onSubmit:async formData=>{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((0,import_core40.normalizeOperationOutcome)(err))}},children:[(0,import_jsx_runtime34.jsx)(import_core39.Center,{style:{flexDirection:"column"},children:props.children}),(0,import_jsx_runtime34.jsx)(OperationOutcomeAlert,{issues}),googleClientId&&(0,import_jsx_runtime34.jsxs)(import_jsx_runtime34.Fragment,{children:[(0,import_jsx_runtime34.jsx)(import_core39.Group,{justify:"center",p:"xl",style:{height:70},children:(0,import_jsx_runtime34.jsx)(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((0,import_core40.normalizeOperationOutcome)(err))}}})}),(0,import_jsx_runtime34.jsx)(import_core39.Divider,{label:"or",labelPosition:"center",my:"lg"})]}),(0,import_jsx_runtime34.jsxs)(import_core39.Stack,{gap:"xl",children:[(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),(0,import_jsx_runtime34.jsx)(import_core39.PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")}),(0,import_jsx_runtime34.jsxs)(import_core39.Text,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),(0,import_jsx_runtime34.jsxs)(import_core39.Text,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]}),(0,import_jsx_runtime34.jsxs)(import_core39.Group,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[(0,import_jsx_runtime34.jsx)(import_core39.Checkbox,{name:"remember",label:"Remember me",size:"xs"}),(0,import_jsx_runtime34.jsx)(import_core39.Button,{type:"submit",children:"Create account"})]})]})}var import_jsx_runtime35=require("react/jsx-runtime");function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=(0,import_react_hooks16.useMedplum)(),[login,setLogin]=(0,import_react21.useState)(),[outcome,setOutcome]=(0,import_react21.useState)();(0,import_react21.useEffect)(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome((0,import_core41.normalizeOperationOutcome)(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(0,import_jsx_runtime35.jsxs)(Document,{width:450,children:[outcome&&(0,import_jsx_runtime35.jsx)("pre",{children:JSON.stringify(outcome,null,2)}),!login&&(0,import_jsx_runtime35.jsx)(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&(0,import_jsx_runtime35.jsx)(NewProjectForm,{login,handleAuthResponse})]})}var import_notifications4=require("@mantine/notifications"),import_core49=require("@medplum/core"),import_react_hooks20=require("@medplum/react-hooks"),import_react25=require("react");var import_core42=require("@mantine/core"),import_core43=require("@medplum/core"),import_react_hooks17=require("@medplum/react-hooks"),import_react22=require("react");var import_jsx_runtime36=require("react/jsx-runtime");function AuthenticationForm(props){let[email,setEmail]=(0,import_react22.useState)();return email?(0,import_jsx_runtime36.jsx)(PasswordForm,{email,...props}):(0,import_jsx_runtime36.jsx)(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=(0,import_react_hooks17.useMedplum)(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=(0,import_react22.useState)(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=(0,import_react22.useCallback)(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),window.location.assign(url.toString()),!0},[medplum,baseLoginRequest]),handleSubmit=(0,import_react22.useCallback)(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=(0,import_react22.useCallback)(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome((0,import_core43.normalizeOperationOutcome)(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return(0,import_jsx_runtime36.jsxs)(Form,{onSubmit:handleSubmit,children:[(0,import_jsx_runtime36.jsx)(import_core42.Center,{style:{flexDirection:"column"},children}),(0,import_jsx_runtime36.jsx)(OperationOutcomeAlert,{issues}),googleClientId&&(0,import_jsx_runtime36.jsxs)(import_jsx_runtime36.Fragment,{children:[(0,import_jsx_runtime36.jsx)(import_core42.Group,{justify:"center",p:"xl",style:{height:70},children:(0,import_jsx_runtime36.jsx)(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.Divider,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.TextInput,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")}),(0,import_jsx_runtime36.jsxs)(import_core42.Group,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[(0,import_jsx_runtime36.jsx)("div",{children:onRegister&&(0,import_jsx_runtime36.jsx)(import_core42.Anchor,{component:"button",type:"button",color:"dimmed",onClick:onRegister,size:"xs",children:"Register"})}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.Button,{type:"submit",children:"Next"})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=(0,import_react_hooks17.useMedplum)(),[outcome,setOutcome]=(0,import_react22.useState)(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=(0,import_react22.useCallback)(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome((0,import_core43.normalizeOperationOutcome)(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return(0,import_jsx_runtime36.jsxs)(Form,{onSubmit:handleSubmit,children:[(0,import_jsx_runtime36.jsx)(import_core42.Center,{style:{flexDirection:"column"},children}),(0,import_jsx_runtime36.jsx)(OperationOutcomeAlert,{issues}),(0,import_jsx_runtime36.jsx)(import_core42.Stack,{gap:"xl",children:(0,import_jsx_runtime36.jsx)(import_core42.PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password")})}),(0,import_jsx_runtime36.jsxs)(import_core42.Group,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[onForgotPassword&&(0,import_jsx_runtime36.jsx)(import_core42.Anchor,{component:"button",type:"button",c:"dimmed",onClick:onForgotPassword,size:"xs",children:"Forgot password"}),(0,import_jsx_runtime36.jsx)(import_core42.Checkbox,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),(0,import_jsx_runtime36.jsx)(import_core42.Button,{type:"submit",children:"Sign in"})]})]})}var import_core44=require("@mantine/core"),import_core45=require("@medplum/core"),import_react_hooks18=require("@medplum/react-hooks"),import_react23=require("react");var import_jsx_runtime37=require("react/jsx-runtime");function ChooseProfileForm(props){let medplum=(0,import_react_hooks18.useMedplum)(),combobox=(0,import_core44.useCombobox)(),[search,setSearch]=(0,import_react23.useState)(""),[outcome,setOutcome]=(0,import_react23.useState)();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((0,import_core45.normalizeOperationOutcome)(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Option,{value:item.id,children:(0,import_jsx_runtime37.jsx)(SelectOption,{...item})},item.id));return(0,import_jsx_runtime37.jsxs)(import_core44.Stack,{children:[(0,import_jsx_runtime37.jsxs)(import_core44.Flex,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[(0,import_jsx_runtime37.jsx)(Logo,{size:32}),(0,import_jsx_runtime37.jsx)(import_core44.Title,{order:3,children:"Choose profile"})]}),(0,import_jsx_runtime37.jsx)(OperationOutcomeAlert,{outcome}),(0,import_jsx_runtime37.jsxs)(import_core44.Combobox,{store:combobox,onOptionSubmit:handleValueSelect,children:[(0,import_jsx_runtime37.jsx)(import_core44.Combobox.EventsTarget,{children:(0,import_jsx_runtime37.jsx)(import_core44.TextInput,{placeholder:"Search",value:search,onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),(0,import_jsx_runtime37.jsx)("div",{children:(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Options,{children:options.length>0?options:(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Empty,{children:"Nothing found..."})})})]})]})}function SelectOption(membership){return(0,import_jsx_runtime37.jsxs)(import_core44.Group,{children:[(0,import_jsx_runtime37.jsx)(import_core44.Avatar,{radius:"xl"}),(0,import_jsx_runtime37.jsxs)("div",{children:[(0,import_jsx_runtime37.jsx)(import_core44.Text,{fz:"sm",fw:500,children:membership.profile?.display}),(0,import_jsx_runtime37.jsx)(import_core44.Text,{fz:"xs",opacity:.6,children:membership.project?.display})]})]})}var import_core46=require("@mantine/core"),import_react_hooks19=require("@medplum/react-hooks");var import_jsx_runtime38=require("react/jsx-runtime");function ChooseScopeForm(props){let medplum=(0,import_react_hooks19.useMedplum)();return(0,import_jsx_runtime38.jsx)(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:(0,import_jsx_runtime38.jsxs)(import_core46.Stack,{children:[(0,import_jsx_runtime38.jsxs)(import_core46.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime38.jsx)(Logo,{size:32}),(0,import_jsx_runtime38.jsx)(import_core46.Title,{children:"Choose scope"})]}),(0,import_jsx_runtime38.jsx)(import_core46.Stack,{children:(props.scope??"openid").split(" ").map(scopeName=>(0,import_jsx_runtime38.jsx)(import_core46.Checkbox,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName))}),(0,import_jsx_runtime38.jsx)(import_core46.Group,{justify:"flex-end",mt:"xl",children:(0,import_jsx_runtime38.jsx)(import_core46.Button,{type:"submit",children:"Set scope"})})]})})}var import_core47=require("@mantine/core"),import_core48=require("@medplum/core");var import_react24=require("react");var import_jsx_runtime39=require("react/jsx-runtime");function MfaForm(props){let[errorMessage,setErrorMessage]=(0,import_react24.useState)();return(0,import_jsx_runtime39.jsx)(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData).catch(err=>setErrorMessage((0,import_core48.normalizeErrorString)(err)))},children:(0,import_jsx_runtime39.jsxs)(import_core47.Stack,{children:[(0,import_jsx_runtime39.jsxs)(import_core47.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime39.jsx)(Logo,{size:32}),(0,import_jsx_runtime39.jsx)(import_core47.Title,{children:"Enter MFA code"})]}),errorMessage&&(0,import_jsx_runtime39.jsx)(import_core47.Alert,{icon:(0,import_jsx_runtime39.jsx)(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),(0,import_jsx_runtime39.jsx)(import_core47.Stack,{children:(0,import_jsx_runtime39.jsx)(import_core47.TextInput,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),(0,import_jsx_runtime39.jsx)(import_core47.Group,{justify:"flex-end",mt:"xl",children:(0,import_jsx_runtime39.jsx)(import_core47.Button,{type:"submit",children:"Submit code"})})]})})}var import_jsx_runtime40=require("react/jsx-runtime");function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=(0,import_react_hooks20.useMedplum)(),[login,setLogin]=(0,import_react25.useState)(),loginRequested=(0,import_react25.useRef)(!1),[mfaRequired,setAuthenticatorRequired]=(0,import_react25.useState)(!1),[memberships,setMemberships]=(0,import_react25.useState)(),handleCode=(0,import_react25.useCallback)(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>(0,import_notifications4.showNotification)({color:"red",message:(0,import_core49.normalizeErrorString)(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=(0,import_react25.useCallback)(response=>{setAuthenticatorRequired(!!response.mfaRequired),response.login&&setLogin(response.login),response.memberships&&setMemberships(response.memberships),response.code&&(chooseScopes?setMemberships(void 0):handleCode(response.code))},[chooseScopes,handleCode]),handleScopeResponse=(0,import_react25.useCallback)(response=>{handleCode(response.code)},[handleCode]);return(0,import_react25.useEffect)(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>(0,import_notifications4.showNotification)({color:"red",message:(0,import_core49.normalizeErrorString)(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),(0,import_jsx_runtime40.jsx)(Document,{width:450,px:"sm",py:"md",children:login?mfaRequired?(0,import_jsx_runtime40.jsx)(MfaForm,{onSubmit:async fields=>{let res=await medplum.post("auth/mfa/verify",{login,token:fields.token});handleAuthResponse(res)}}):memberships?(0,import_jsx_runtime40.jsx)(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.projectId==="new"?(0,import_jsx_runtime40.jsx)(NewProjectForm,{login,handleAuthResponse}):props.chooseScopes?(0,import_jsx_runtime40.jsx)(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):(0,import_jsx_runtime40.jsx)("div",{children:"Success"}):(0,import_jsx_runtime40.jsx)(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}var import_core63=require("@medplum/core");var import_core61=require("@mantine/core"),import_core62=require("@medplum/core");var import_core50=require("@medplum/core"),import_jsx_runtime41=require("react/jsx-runtime");function CodeableConceptDisplay(props){return(0,import_jsx_runtime41.jsx)(import_jsx_runtime41.Fragment,{children:(0,import_core50.formatCodeableConcept)(props.value)})}var import_core51=require("@medplum/core"),import_jsx_runtime42=require("react/jsx-runtime");function CodingDisplay(props){return(0,import_jsx_runtime42.jsx)(import_jsx_runtime42.Fragment,{children:(0,import_core51.formatCoding)(props.value)})}var import_jsx_runtime43=require("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("]")),(0,import_jsx_runtime43.jsx)(import_jsx_runtime43.Fragment,{children:builder.join("").trim()})}var import_jsx_runtime44=require("react/jsx-runtime");function ContactDetailDisplay(props){let contactDetail=props.value;return contactDetail?(0,import_jsx_runtime44.jsxs)(import_jsx_runtime44.Fragment,{children:[contactDetail.name,contactDetail.name&&": ",contactDetail.telecom?.map(telecom=>(0,import_jsx_runtime44.jsx)(ContactPointDisplay,{value:telecom},`telecom-${contactDetail.name}-${telecom.value}`))]}):null}var import_jsx_runtime45=require("react/jsx-runtime");function IdentifierDisplay(props){return(0,import_jsx_runtime45.jsxs)("div",{children:[props.value?.system,": ",props.value?.value]})}var import_core52=require("@medplum/core"),import_jsx_runtime46=require("react/jsx-runtime");function MoneyDisplay(props){return(0,import_jsx_runtime46.jsx)(import_jsx_runtime46.Fragment,{children:(0,import_core52.formatMoney)(props.value)})}var import_core53=require("@medplum/core"),import_jsx_runtime47=require("react/jsx-runtime");function QuantityDisplay(props){return(0,import_jsx_runtime47.jsx)(import_jsx_runtime47.Fragment,{children:(0,import_core53.formatQuantity)(props.value)})}var import_core54=require("@medplum/core"),import_jsx_runtime48=require("react/jsx-runtime");function RangeDisplay(props){return(0,import_jsx_runtime48.jsx)(import_jsx_runtime48.Fragment,{children:(0,import_core54.formatRange)(props.value)})}var import_jsx_runtime49=require("react/jsx-runtime");function RatioDisplay(props){let value=props.value;return value?(0,import_jsx_runtime49.jsxs)(import_jsx_runtime49.Fragment,{children:[(0,import_jsx_runtime49.jsx)(QuantityDisplay,{value:value.numerator}),"\xA0/\xA0",(0,import_jsx_runtime49.jsx)(QuantityDisplay,{value:value.denominator})]}):null}var import_core55=require("@medplum/core");var import_jsx_runtime50=require("react/jsx-runtime");function ReferenceDisplay(props){if(!props.value)return null;let displayString=props.value.display||props.value.reference||(0,import_core55.stringify)(props.value);return props.link!==!1&&props.value.reference?(0,import_jsx_runtime50.jsx)(MedplumLink,{to:props.value,children:displayString}):(0,import_jsx_runtime50.jsx)(import_jsx_runtime50.Fragment,{children:displayString})}var import_core58=require("@medplum/core");var import_react27=require("react");var import_core56=require("@medplum/core");function assignValuesIntoSlices(values,slices,slicing,profileUrl){if(!(0,import_core56.isPopulated)(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=(0,import_core56.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(!(0,import_core56.isSliceDefinitionWithTypes)(slice)){console.debug("Unsupported slice definition",slice);continue}let profileUrl;(0,import_core56.isPopulated)(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=(0,import_core56.tryGetProfile)(profileUrl);slice.typeSchema=typeSchema}}resolve(supportedSlices)}).catch(reject)})}var import_react_hooks21=require("@medplum/react-hooks");var import_core57=require("@medplum/core"),import_react26=require("react");var import_jsx_runtime51=require("react/jsx-runtime");function maybeWrapWithContext(ContextProvider,contextValue,contents){return contextValue!==void 0?(0,import_jsx_runtime51.jsx)(ContextProvider,{value:contextValue,children:contents}):contents}var import_jsx_runtime52=require("react/jsx-runtime");function SliceDisplay(props){let{slice,property}=props,sliceElements=slice.typeSchema?.elements??slice.elements,parentContext=(0,import_react26.useContext)(ElementsContext),contextValue=(0,import_react26.useMemo)(()=>{if((0,import_core57.isPopulated)(sliceElements))return(0,import_core57.buildElementsContext)({parentContext,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentContext,props.path,slice.typeSchema?.url,sliceElements]);return maybeWrapWithContext(ElementsContext.Provider,contextValue,(0,import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment,{children:props.value.map((value,valueIndex)=>(0,import_jsx_runtime52.jsx)("div",{children:(0,import_jsx_runtime52.jsx)(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}`))}))}var import_jsx_runtime53=require("react/jsx-runtime");function ResourceArrayDisplay(props){let{property,propertyType}=props,medplum=(0,import_react_hooks21.useMedplum)(),values=(0,import_react27.useMemo)(()=>Array.isArray(props.values)?props.values:[],[props.values]),[loading,setLoading]=(0,import_react27.useState)(!0),[slices,setSlices]=(0,import_react27.useState)([]),[slicedValues,setSlicedValues]=(0,import_react27.useState)(()=>[values]),ctx=(0,import_react27.useContext)(ElementsContext);if((0,import_react27.useEffect)(()=>{prepareSlices({medplum,property}).then(slices2=>{setSlices(slices2);let slicedValues2=assignValuesIntoSlices(values,slices2,property.slicing,ctx.profileUrl);setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,ctx.profileUrl,setSlicedValues,values]),loading)return(0,import_jsx_runtime53.jsx)("div",{children:"Loading..."});let nonSliceContent;if(property.type[0]?.code!=="Extension"){let nonSliceValues=slicedValues[slices.length],nonSliceElements=nonSliceValues.map((value,valueIndex)=>(0,import_jsx_runtime53.jsx)("div",{children:(0,import_jsx_runtime53.jsx)(ResourcePropertyDisplay,{path:props.path,arrayElement:!0,property,propertyType,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${nonSliceValues.length}`));if(props.includeDescriptionListEntry){if(!(0,import_core58.isPopulated)(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();nonSliceContent=(0,import_jsx_runtime53.jsx)(DescriptionListEntry,{term:(0,import_core58.getPathDisplayName)(key),children:nonSliceElements})}else nonSliceContent=(0,import_jsx_runtime53.jsx)(import_jsx_runtime53.Fragment,{children:nonSliceElements})}return(0,import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment,{children:[slices.map((slice,sliceIndex)=>{if(!props.path)throw Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);let sliceDisplay=(0,import_jsx_runtime53.jsx)(SliceDisplay,{path:props.path,slice,property,value:slicedValues[sliceIndex],ignoreMissingValues:props.ignoreMissingValues,link:props.link},slice.name);return props.includeDescriptionListEntry&&(sliceDisplay=(0,import_jsx_runtime53.jsx)(DescriptionListEntry,{term:(0,import_core58.getPathDisplayName)(slice.name),children:sliceDisplay},slice.name)),sliceDisplay}),nonSliceContent]})}var import_core60=require("@medplum/core"),import_react_hooks22=require("@medplum/react-hooks"),import_react28=require("react");var import_core59=require("@medplum/core");function getValueAndType(context,path,profileUrl){let typedResult=(0,import_core59.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=(0,import_core59.getTypedPropertyValueWithSchema)(typedValue,path,element);return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}var import_jsx_runtime54=require("react/jsx-runtime");function ExtensionDisplay(props){let{elementDefinitionType}=props,medplum=(0,import_react_hooks22.useMedplum)(),ctx=(0,import_react28.useContext)(ElementsContext),[typeSchema,setTypeSchema]=(0,import_react28.useState)((0,import_core60.getDataType)("Extension")),profileUrl=(0,import_react28.useMemo)(()=>{if((0,import_core60.isPopulated)(elementDefinitionType?.profile))return elementDefinitionType.profile[0]},[elementDefinitionType]),[loadingProfile,setLoadingProfile]=(0,import_react28.useState)(profileUrl!==void 0);if((0,import_react28.useEffect)(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>{let profile=(0,import_core60.tryGetProfile)(profileUrl);setLoadingProfile(!1),profile&&setTypeSchema(profile)}).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!(0,import_core60.isProfileLoaded)(profileUrl)))return(0,import_jsx_runtime54.jsx)("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(0,import_jsx_runtime54.jsx)(ResourcePropertyDisplay,{propertyType,value:propertyValue})}return(0,import_jsx_runtime54.jsx)(BackboneElementDisplay,{path:props.path,value:{type:typeSchema.type,value:props.value},compact:props.compact,ignoreMissingValues:props.ignoreMissingValues,link:props.link,profileUrl})}var import_jsx_runtime55=require("react/jsx-runtime");function ResourcePropertyDisplay(props){let{property,propertyType,value}=props;if(property?.path?.endsWith(".id"))return(0,import_jsx_runtime55.jsxs)(import_core61.Box,{component:"div",style:{display:"flex",gap:3,alignItems:"center"},children:[value,!(0,import_core62.isEmpty)(value)&&(0,import_jsx_runtime55.jsx)(import_core61.CopyButton,{value,timeout:2e3,children:({copied,copy})=>(0,import_jsx_runtime55.jsx)(import_core61.Tooltip,{label:copied?"Copied":"Copy",withArrow:!0,position:"right",children:(0,import_jsx_runtime55.jsx)(import_core61.ActionIcon,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,children:copied?(0,import_jsx_runtime55.jsx)(IconCheck,{size:"1rem"}):(0,import_jsx_runtime55.jsx)(IconCopy,{size:"1rem"})})})})]});if(property&&(property.isArray||property.max>1)&&!props.arrayElement)return propertyType===import_core62.PropertyType.Attachment?(0,import_jsx_runtime55.jsx)(AttachmentArrayDisplay,{values:value,maxWidth:props.maxWidth,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,property,path:props.path}):(0,import_jsx_runtime55.jsx)(ResourceArrayDisplay,{path:props.path,property,propertyType,values:value,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,ignoreMissingValues:props.ignoreMissingValues,link:props.link});switch(propertyType){case import_core62.PropertyType.boolean:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value===void 0?"":(!!value).toString()});case import_core62.PropertyType.SystemString:case import_core62.PropertyType.string:return(0,import_jsx_runtime55.jsx)("div",{style:{whiteSpace:"pre-wrap"},children:value});case import_core62.PropertyType.code:case import_core62.PropertyType.date:case import_core62.PropertyType.decimal:case import_core62.PropertyType.id:case import_core62.PropertyType.integer:case import_core62.PropertyType.positiveInt:case import_core62.PropertyType.unsignedInt:case import_core62.PropertyType.uri:case import_core62.PropertyType.url:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value});case import_core62.PropertyType.canonical:return(0,import_jsx_runtime55.jsx)(ReferenceDisplay,{value:{reference:value},link:props.link});case import_core62.PropertyType.dateTime:case import_core62.PropertyType.instant:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatDateTime)(value)});case import_core62.PropertyType.markdown:return(0,import_jsx_runtime55.jsx)("pre",{children:value});case import_core62.PropertyType.Address:return(0,import_jsx_runtime55.jsx)(AddressDisplay,{value});case import_core62.PropertyType.Annotation:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value?.text});case import_core62.PropertyType.Attachment:return(0,import_jsx_runtime55.jsx)(AttachmentDisplay,{value,maxWidth:props.maxWidth});case import_core62.PropertyType.CodeableConcept:return(0,import_jsx_runtime55.jsx)(CodeableConceptDisplay,{value});case import_core62.PropertyType.Coding:return(0,import_jsx_runtime55.jsx)(CodingDisplay,{value});case import_core62.PropertyType.ContactDetail:return(0,import_jsx_runtime55.jsx)(ContactDetailDisplay,{value});case import_core62.PropertyType.ContactPoint:return(0,import_jsx_runtime55.jsx)(ContactPointDisplay,{value});case import_core62.PropertyType.HumanName:return(0,import_jsx_runtime55.jsx)(HumanNameDisplay,{value});case import_core62.PropertyType.Identifier:return(0,import_jsx_runtime55.jsx)(IdentifierDisplay,{value});case import_core62.PropertyType.Money:return(0,import_jsx_runtime55.jsx)(MoneyDisplay,{value});case import_core62.PropertyType.Period:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatPeriod)(value)});case import_core62.PropertyType.Quantity:case import_core62.PropertyType.Duration:return(0,import_jsx_runtime55.jsx)(QuantityDisplay,{value});case import_core62.PropertyType.Range:return(0,import_jsx_runtime55.jsx)(RangeDisplay,{value});case import_core62.PropertyType.Ratio:return(0,import_jsx_runtime55.jsx)(RatioDisplay,{value});case import_core62.PropertyType.Reference:return(0,import_jsx_runtime55.jsx)(ReferenceDisplay,{value,link:props.link});case import_core62.PropertyType.Timing:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatTiming)(value)});case import_core62.PropertyType.Dosage:case import_core62.PropertyType.UsageContext:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return(0,import_jsx_runtime55.jsx)(BackboneElementDisplay,{path:props.path,value:{type:propertyType,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues});case import_core62.PropertyType.Extension:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return(0,import_jsx_runtime55.jsx)(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(0,import_jsx_runtime55.jsx)(BackboneElementDisplay,{path:props.path,value:{type:property.type[0].code,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues})}}var import_react29=require("react");var import_jsx_runtime56=require("react/jsx-runtime"),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=(0,import_react29.useContext)(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=(0,import_react29.useMemo)(()=>(0,import_core63.tryGetDataType)(typeName,profileUrl),[profileUrl,typeName]),newElementsContext=(0,import_react29.useMemo)(()=>{if(typeSchema)return(0,import_core63.buildElementsContext)({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if((0,import_core63.isEmpty)(value))return null;if(!typeSchema)return(0,import_jsx_runtime56.jsxs)("div",{children:[typeName,"\xA0not implemented"]});if(typeof value=="object"&&"name"in value&&Object.keys(value).length===1&&typeof value.name=="string")return(0,import_jsx_runtime56.jsx)("div",{children:value.name});let elementsContext=newElementsContext??parentElementsContext;return maybeWrapWithContext(ElementsContext.Provider,newElementsContext,(0,import_jsx_runtime56.jsx)(DescriptionList,{compact:props.compact,children:Object.entries(elementsContext.elements).map(([key,property])=>{if(EXTENSION_KEYS2.includes(key)&&(0,import_core63.isEmpty)(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)&&(0,import_core63.isEmpty)(propertyValue)||props.path.endsWith(".extension")&&(key==="url"||key==="id"))return null;let isArrayProperty=property.max>1||property.isArray,resourcePropertyDisplay=(0,import_jsx_runtime56.jsx)(ResourcePropertyDisplay,{property,propertyType,path:props.path+"."+key,value:propertyValue,ignoreMissingValues:props.ignoreMissingValues,includeArrayDescriptionListEntry:isArrayProperty,link:props.link},key);return isArrayProperty?resourcePropertyDisplay:(0,import_jsx_runtime56.jsx)(DescriptionListEntry,{term:(0,import_core63.getPathDisplayName)(key),children:resourcePropertyDisplay},key)})}))}var import_core97=require("@medplum/core"),import_react52=require("react");var import_core95=require("@mantine/core"),import_core96=require("@medplum/core"),import_react51=require("react");var import_core65=require("@mantine/core"),import_react30=require("react");var import_core64=require("@mantine/core"),import_jsx_runtime57=require("react/jsx-runtime"),READ_ONLY_TOOLTIP_TEXT="Read Only";function maybeWrapWithTooltip(tooltipText,children){return tooltipText?(0,import_jsx_runtime57.jsx)(import_core64.Tooltip.Floating,{label:tooltipText,children}):children}var FormSection_default={dimmed:"FormSection_dimmed",preserveBreaks:"FormSection_preserveBreaks"};var import_jsx_runtime58=require("react/jsx-runtime");function CheckboxFormSection(props){let{debugMode}=(0,import_react30.useContext)(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,(0,import_jsx_runtime58.jsxs)(import_core65.Group,{wrap:"nowrap","data-testid":props.testId,children:[(0,import_jsx_runtime58.jsx)("div",{children:props.children}),(0,import_jsx_runtime58.jsx)("div",{children:(0,import_jsx_runtime58.jsx)(import_core65.Input.Wrapper,{id:props.htmlFor,label,classNames:{label:props?.readonly?FormSection_default.dimmed:void 0},description:props.description,withAsterisk:props.withAsterisk,children:null})})]}))}var import_core66=require("@mantine/core"),import_react31=require("react");var import_jsx_runtime59=require("react/jsx-runtime");function FormSection(props){let{debugMode}=(0,import_react31.useContext)(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,(0,import_jsx_runtime59.jsx)(import_core66.Input.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}))}var import_core67=require("@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]",(0,import_core67.capitalize)(type.code));compoundKey in obj&&delete obj[compoundKey]}return(0,import_core67.isEmpty)(value)?obj[propName]=void 0:obj[propName]=value,obj}function isSupportedProfileStructureDefinition(profile){return!!profile&&!(0,import_core67.isEmpty)(profile.url)&&!(0,import_core67.isEmpty)(profile.name)}var import_core93=require("@mantine/core"),import_core94=require("@medplum/core"),import_react50=require("react");var import_react32=require("react");var import_jsx_runtime60=require("react/jsx-runtime");function CodeableConceptInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,outcome:_outcome,path:_path,valuePath:_valuePath,...rest}=props,[value,setValue]=(0,import_react32.useState)(defaultValue2);function handleChange(newValues){let newConcept=valueSetElementToCodeableConcept(newValues);setValue(newConcept),onChange&&onChange(newConcept)}return(0,import_jsx_runtime60.jsx)(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}))}}var import_react33=require("react");var import_jsx_runtime61=require("react/jsx-runtime");function CodingInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,...rest}=props,[value,setValue]=(0,import_react33.useState)(defaultValue2);function handleChange(newValues){let newValue=newValues[0],newConcept=newValue&&valueSetElementToCoding(newValue);setValue(newConcept),onChange&&onChange(newConcept)}return(0,import_jsx_runtime61.jsx)(ValueSetAutocomplete,{defaultValue:value&&codingToValueSetElement(value),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}}var import_core69=require("@mantine/core"),import_react35=require("react");var import_core68=require("@mantine/core"),import_react34=require("react");var import_jsx_runtime62=require("react/jsx-runtime");function ContactPointInput(props){let{path,outcome}=props,{elementsByPath,getExtendedProps}=(0,import_react34.useContext)(ElementsContext),[contactPoint,setContactPoint]=(0,import_react34.useState)(props.defaultValue),ref=(0,import_react34.useRef)();ref.current=contactPoint;let[systemElement,useElement,valueElement]=(0,import_react34.useMemo)(()=>["system","use","value"].map(field=>elementsByPath[path+"."+field]),[elementsByPath,path]),[systemProps,useProps,valueProps]=(0,import_react34.useMemo)(()=>["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(0,import_jsx_runtime62.jsxs)(import_core68.Group,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[(0,import_jsx_runtime62.jsx)(import_core68.NativeSelect,{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")}),(0,import_jsx_runtime62.jsx)(import_core68.NativeSelect,{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")}),(0,import_jsx_runtime62.jsx)(import_core68.TextInput,{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")})]})}var import_jsx_runtime63=require("react/jsx-runtime");function ContactDetailInput(props){let[contactPoint,setContactDetail]=(0,import_react35.useState)(props.defaultValue),ref=(0,import_react35.useRef)();ref.current=contactPoint;let{getExtendedProps}=(0,import_react35.useContext)(ElementsContext),[nameProps,telecomProps]=(0,import_react35.useMemo)(()=>["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(0,import_jsx_runtime63.jsxs)(import_core69.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime63.jsx)(import_core69.TextInput,{disabled:props.disabled||nameProps?.readonly,"data-testid":props.name+"-name",name:props.name+"-name",placeholder:"Name",style:{width:180},defaultValue:contactPoint?.name,onChange:e=>setName(e.currentTarget.value)}),(0,import_jsx_runtime63.jsx)(ContactPointInput,{disabled:props.disabled||telecomProps?.readonly,name:props.name+"-telecom",path:props.path+".telecom",defaultValue:contactPoint?.telecom?.[0],onChange:setTelecom,outcome:props.outcome})]})}var import_core71=require("@mantine/core");var import_core70=require("@medplum/core");function convertIsoToLocal(isoString){if(!isoString)return"";let date=new Date(isoString);return(0,import_core70.isValidDate)(date)?date.toLocaleDateString("sv")+"T"+date.toLocaleTimeString("sv"):""}function convertLocalToIso(localString){if(!localString)return"";let date=new Date(localString);return(0,import_core70.isValidDate)(date)?date.toISOString():""}var import_jsx_runtime64=require("react/jsx-runtime");function DateTimeInput(props){return(0,import_jsx_runtime64.jsx)(import_core71.TextInput,{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(),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"}var import_core72=require("@medplum/core"),import_react_hooks23=require("@medplum/react-hooks"),import_react36=require("react");var import_jsx_runtime65=require("react/jsx-runtime");function ExtensionInput(props){let{propertyType}=props,medplum=(0,import_react_hooks23.useMedplum)(),profileUrl=(0,import_react36.useMemo)(()=>{if((0,import_core72.isPopulated)(propertyType.profile))return propertyType.profile[0]},[propertyType]),[loadingProfile,setLoadingProfile]=(0,import_react36.useState)(profileUrl!==void 0);return(0,import_react36.useEffect)(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>setLoadingProfile(!1)).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!(0,import_core72.isProfileLoaded)(profileUrl))?(0,import_jsx_runtime65.jsx)("div",{children:"Loading..."}):(0,import_jsx_runtime65.jsx)(BackboneElementInput,{profileUrl,path:props.path,typeName:"Extension",defaultValue:props.defaultValue,onChange:props.onChange})}var import_core73=require("@mantine/core"),import_react37=require("react");var import_jsx_runtime66=require("react/jsx-runtime");function HumanNameInput(props){let{outcome,path}=props,[value,setValue]=(0,import_react37.useState)(props.defaultValue),{getExtendedProps}=(0,import_react37.useContext)(ElementsContext),[useProps,prefixProps,givenProps,familyProps,suffixProps]=(0,import_react37.useMemo)(()=>["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(0,import_jsx_runtime66.jsxs)(import_core73.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime66.jsx)(import_core73.NativeSelect,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")})]})}var import_core74=require("@mantine/core"),import_react38=require("react");var import_jsx_runtime67=require("react/jsx-runtime");function IdentifierInput(props){let[value,setValue]=(0,import_react38.useState)(props.defaultValue),{elementsByPath,getExtendedProps}=(0,import_react38.useContext)(ElementsContext),[systemElement,valueElement]=(0,import_react38.useMemo)(()=>["system","value"].map(field=>elementsByPath[props.path+"."+field]),[elementsByPath,props.path]),[systemProps,valueProps]=(0,import_react38.useMemo)(()=>["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(0,import_jsx_runtime67.jsxs)(import_core74.Group,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[(0,import_jsx_runtime67.jsx)(import_core74.TextInput,{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")}),(0,import_jsx_runtime67.jsx)(import_core74.TextInput,{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")})]})}var import_core75=require("@mantine/core");var import_react39=require("react");var import_jsx_runtime68=require("react/jsx-runtime"),data=["USD","EUR","CAD","GBP","AUD"];function MoneyInput(props){let{onChange}=props,[value,setValue]=(0,import_react39.useState)(props.defaultValue),{getExtendedProps}=(0,import_react39.useContext)(ElementsContext),[currencyProps,valueProps]=(0,import_react39.useMemo)(()=>["currency","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]),setValueWrapper=(0,import_react39.useCallback)(newValue=>{setValue(newValue),onChange&&onChange(newValue)},[onChange]),handleCurrencyChange=(0,import_react39.useCallback)(e=>{setValueWrapper({...value,currency:e.currentTarget.value})},[value,setValueWrapper]),handleValueChange=(0,import_react39.useCallback)(e=>{setValueWrapper({...value,value:e.currentTarget.valueAsNumber})},[value,setValueWrapper]),select=(0,import_jsx_runtime68.jsx)(import_core75.NativeSelect,{disabled:props.disabled||currencyProps?.readonly,defaultValue:value?.currency,data,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:handleCurrencyChange});return(0,import_jsx_runtime68.jsx)(import_core75.TextInput,{disabled:props.disabled||valueProps?.readonly,type:"number",name:props.name,label:props.label,placeholder:props.placeholder??"Value",defaultValue:value?.value?.toString()??"USD",leftSection:(0,import_jsx_runtime68.jsx)(IconCurrencyDollar,{size:14}),rightSection:select,rightSectionWidth:92,onChange:handleValueChange})}var import_core76=require("@mantine/core"),import_react40=require("react");var import_jsx_runtime69=require("react/jsx-runtime");function PeriodInput(props){let[value,setValue]=(0,import_react40.useState)(props.defaultValue),{getExtendedProps}=(0,import_react40.useContext)(ElementsContext),[startProps,endProps]=(0,import_react40.useMemo)(()=>["start","end"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime69.jsxs)(import_core76.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime69.jsx)(DateTimeInput,{disabled:props.disabled||startProps?.readonly,name:props.name+".start",placeholder:"Start",defaultValue:value?.start,onChange:newValue=>setValueWrapper({...value,start:newValue})}),(0,import_jsx_runtime69.jsx)(DateTimeInput,{disabled:props.disabled||endProps?.readonly,name:props.name+".end",placeholder:"End",defaultValue:value?.end,onChange:newValue=>setValueWrapper({...value,end:newValue})})]})}var import_core77=require("@mantine/core"),import_react41=require("react");var import_jsx_runtime70=require("react/jsx-runtime");function QuantityInput(props){let[value,setValue]=(0,import_react41.useState)(props.defaultValue),{getExtendedProps}=(0,import_react41.useContext)(ElementsContext),[comparatorProps,valueProps,unitProps]=(0,import_react41.useMemo)(()=>["comparator","value","unit"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime70.jsxs)(import_core77.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime70.jsx)(import_core77.NativeSelect,{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})}),(0,import_jsx_runtime70.jsx)(import_core77.TextInput,{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)})}}),(0,import_jsx_runtime70.jsx)(import_core77.TextInput,{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)}var import_core78=require("@mantine/core"),import_react42=require("react");var import_jsx_runtime71=require("react/jsx-runtime");function RangeInput(props){let[value,setValue]=(0,import_react42.useState)(props.defaultValue),{getExtendedProps}=(0,import_react42.useContext)(ElementsContext),[lowProps,highProps]=(0,import_react42.useMemo)(()=>["low","high"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime71.jsxs)(import_core78.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime71.jsx)(QuantityInput,{path:props.path+".low",disabled:props.disabled||lowProps?.readonly,name:props.name+"-low",defaultValue:value?.low,onChange:v=>setValueWrapper({...value,low:v})}),(0,import_jsx_runtime71.jsx)(QuantityInput,{path:props.path+".high",disabled:props.disabled||highProps?.readonly,name:props.name+"-high",defaultValue:value?.high,onChange:v=>setValueWrapper({...value,high:v})})]})}var import_core79=require("@mantine/core"),import_react43=require("react");var import_jsx_runtime72=require("react/jsx-runtime");function RatioInput(props){let[value,setValue]=(0,import_react43.useState)(props.defaultValue),{getExtendedProps}=(0,import_react43.useContext)(ElementsContext),[numeratorProps,denominatorProps]=(0,import_react43.useMemo)(()=>["numerator","denominator"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime72.jsxs)(import_core79.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime72.jsx)(QuantityInput,{path:props.path+".numerator",disabled:props.disabled||numeratorProps?.readonly,name:props.name+"-numerator",defaultValue:value?.numerator,onChange:v=>setValueWrapper({...value,numerator:v})}),(0,import_jsx_runtime72.jsx)(QuantityInput,{path:props.path+".denominator",disabled:props.disabled||denominatorProps?.readonly,name:props.name+"-denominator",defaultValue:value?.denominator,onChange:v=>setValueWrapper({...value,denominator:v})})]})}var import_core82=require("@mantine/core"),import_core83=require("@medplum/core"),import_react_hooks25=require("@medplum/react-hooks"),import_react45=require("react");var import_core80=require("@mantine/core"),import_core81=require("@medplum/core"),import_react_hooks24=require("@medplum/react-hooks"),import_react44=require("react");var import_jsx_runtime73=require("react/jsx-runtime"),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:(0,import_core81.getReferenceString)(resource),label:(0,import_core81.getDisplayString)(resource),resource}}function ResourceInput(props){let medplum=(0,import_react_hooks24.useMedplum)(),{resourceType,searchCriteria}=props,[outcome,setOutcome]=(0,import_react44.useState)(),defaultValue2=(0,import_react_hooks24.useResource)(props.defaultValue,setOutcome),ItemComponent3=props.itemComponent??DefaultItemComponent2,onChange=props.onChange,loadValues=(0,import_react44.useCallback)(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=(0,import_react44.useCallback)(newResources=>{onChange&&onChange(newResources[0])},[onChange]);return(0,import_core81.isPopulated)(props.defaultValue)&&!outcome&&!defaultValue2?null:(0,import_jsx_runtime73.jsx)(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=(0,import_react44.forwardRef)(({label,resource,active:_active,...others},ref)=>(0,import_jsx_runtime73.jsx)("div",{ref,...others,children:(0,import_jsx_runtime73.jsxs)(import_core80.Group,{wrap:"nowrap",children:[(0,import_jsx_runtime73.jsx)(ResourceAvatar,{value:resource}),(0,import_jsx_runtime73.jsxs)("div",{children:[(0,import_jsx_runtime73.jsx)(import_core80.Text,{children:label}),(0,import_jsx_runtime73.jsx)(import_core80.Text,{size:"xs",c:"dimmed",children:resource.birthDate||resource.id})]})]})}));function getSearchParamForResourceType(resourceType){return SEARCH_CODES[resourceType]??(NAME_RESOURCE_TYPES.includes(resourceType)?"name":"_id")}var import_jsx_runtime74=require("react/jsx-runtime");function ReferenceInput(props){let{onChange}=props,medplum=(0,import_react_hooks25.useMedplum)(),[value,setValue]=(0,import_react45.useState)(props.defaultValue),[targetTypes,setTargetTypes]=(0,import_react45.useState)(()=>createTargetTypes(props.targetTypes)),[targetType,setTargetType]=(0,import_react45.useState)(()=>getInitialTargetType(props.defaultValue,targetTypes)),promiseCache=(0,import_react45.useRef)(new import_core83.LRUCache),searchCriteria=(0,import_react45.useMemo)(()=>targetType?.type==="profile"?{...props.searchCriteria,_profile:targetType.value}:props.searchCriteria,[props.searchCriteria,targetType]);(0,import_react45.useEffect)(()=>{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?(0,import_core83.isPopulated)(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 import_core83.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=(0,import_react45.useCallback)(item=>{let newValue=item?(0,import_core83.createReference)(item):void 0;setValue(newValue),onChange&&onChange(newValue)},[onChange]),typeSelectOptions=(0,import_react45.useMemo)(()=>targetTypes?targetTypes.map(tt=>({value:tt.value,label:tt.type==="profile"?tt.title??tt.name??tt.resourceType??tt.value:tt.value})):[],[targetTypes]);return(0,import_jsx_runtime74.jsxs)(import_core82.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[targetTypes&&targetTypes.length>1&&(0,import_jsx_runtime74.jsx)(import_core82.NativeSelect,{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&&(0,import_jsx_runtime74.jsx)(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"}),(0,import_jsx_runtime74.jsx)(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=(0,import_core83.tryGetProfile)(profileUrl);if(profile)return{type:profile.type,name:profile.name,title:profile.title};let query=`{
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}var import_jsx_runtime31=require("react/jsx-runtime");function NewProjectForm(props){let medplum=(0,import_react_hooks13.useMedplum)(),[outcome,setOutcome]=(0,import_react18.useState)();return(0,import_jsx_runtime31.jsxs)(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome((0,import_core36.normalizeOperationOutcome)(err))}},children:[(0,import_jsx_runtime31.jsxs)(import_core35.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime31.jsx)(Logo,{size:32}),(0,import_jsx_runtime31.jsx)(import_core35.Title,{children:"Create project"})]}),(0,import_jsx_runtime31.jsxs)(import_core35.Stack,{gap:"xl",children:[(0,import_jsx_runtime31.jsx)(import_core35.TextInput,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")}),(0,import_jsx_runtime31.jsxs)(import_core35.Text,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",(0,import_jsx_runtime31.jsx)(import_core35.Anchor,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime31.jsx)(import_core35.Anchor,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]}),(0,import_jsx_runtime31.jsx)(import_core35.Group,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:(0,import_jsx_runtime31.jsx)(import_core35.Button,{type:"submit",children:"Create project"})})]})}var import_core39=require("@mantine/core"),import_core40=require("@medplum/core"),import_react_hooks15=require("@medplum/react-hooks"),import_react20=require("react");var import_react_hooks14=require("@medplum/react-hooks"),import_react19=require("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)}var import_jsx_runtime32=require("react/jsx-runtime");function GoogleButton(props){let medplum=(0,import_react_hooks14.useMedplum)(),{googleClientId,handleGoogleCredential}=props,parentRef=(0,import_react19.useRef)(null),[scriptLoaded,setScriptLoaded]=(0,import_react19.useState)(typeof google<"u"),[initialized,setInitialized]=(0,import_react19.useState)(!1),[buttonRendered,setButtonRendered]=(0,import_react19.useState)(!1);return(0,import_react19.useEffect)(()=>{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?(0,import_jsx_runtime32.jsx)("div",{ref:parentRef}):null}function getGoogleClientId(clientId){if(clientId)return clientId;if(typeof window<"u"){let origin=window.location.protocol+"//"+window.location.host;if(("undefined"?.split(",")??[]).includes(origin))return"__GOOGLE_CLIENT_ID__"}}var import_core37=require("@mantine/core"),import_core38=require("@medplum/core");var import_jsx_runtime33=require("react/jsx-runtime");function OperationOutcomeAlert(props){let issues=props.outcome?.issue||props.issues;return!issues||issues.length===0?null:(0,import_jsx_runtime33.jsx)(import_core37.Alert,{icon:(0,import_jsx_runtime33.jsx)(IconAlertCircle,{size:16}),color:"red",children:issues.map(issue=>(0,import_jsx_runtime33.jsx)("div",{"data-testid":"text-field-error",children:(0,import_core38.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)}})})}var import_jsx_runtime34=require("react/jsx-runtime");function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=(0,import_react_hooks15.useMedplum)(),[outcome,setOutcome]=(0,import_react20.useState)(),issues=getIssuesForExpression(outcome,void 0);return(0,import_react20.useEffect)(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),(0,import_jsx_runtime34.jsxs)(Form,{onSubmit:async formData=>{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((0,import_core40.normalizeOperationOutcome)(err))}},children:[(0,import_jsx_runtime34.jsx)(import_core39.Center,{style:{flexDirection:"column"},children:props.children}),(0,import_jsx_runtime34.jsx)(OperationOutcomeAlert,{issues}),googleClientId&&(0,import_jsx_runtime34.jsxs)(import_jsx_runtime34.Fragment,{children:[(0,import_jsx_runtime34.jsx)(import_core39.Group,{justify:"center",p:"xl",style:{height:70},children:(0,import_jsx_runtime34.jsx)(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((0,import_core40.normalizeOperationOutcome)(err))}}})}),(0,import_jsx_runtime34.jsx)(import_core39.Divider,{label:"or",labelPosition:"center",my:"lg"})]}),(0,import_jsx_runtime34.jsxs)(import_core39.Stack,{gap:"xl",children:[(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),(0,import_jsx_runtime34.jsx)(import_core39.TextInput,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),(0,import_jsx_runtime34.jsx)(import_core39.PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")}),(0,import_jsx_runtime34.jsxs)(import_core39.Text,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),(0,import_jsx_runtime34.jsxs)(import_core39.Text,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",(0,import_jsx_runtime34.jsx)(import_core39.Anchor,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]}),(0,import_jsx_runtime34.jsxs)(import_core39.Group,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[(0,import_jsx_runtime34.jsx)(import_core39.Checkbox,{name:"remember",label:"Remember me",size:"xs"}),(0,import_jsx_runtime34.jsx)(import_core39.Button,{type:"submit",children:"Create account"})]})]})}var import_jsx_runtime35=require("react/jsx-runtime");function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=(0,import_react_hooks16.useMedplum)(),[login,setLogin]=(0,import_react21.useState)(),[outcome,setOutcome]=(0,import_react21.useState)();(0,import_react21.useEffect)(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome((0,import_core41.normalizeOperationOutcome)(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(0,import_jsx_runtime35.jsxs)(Document,{width:450,children:[outcome&&(0,import_jsx_runtime35.jsx)("pre",{children:JSON.stringify(outcome,null,2)}),!login&&(0,import_jsx_runtime35.jsx)(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&(0,import_jsx_runtime35.jsx)(NewProjectForm,{login,handleAuthResponse})]})}var import_notifications4=require("@mantine/notifications"),import_core49=require("@medplum/core"),import_react_hooks20=require("@medplum/react-hooks"),import_react25=require("react");var import_core42=require("@mantine/core"),import_core43=require("@medplum/core"),import_react_hooks17=require("@medplum/react-hooks"),import_react22=require("react");var import_jsx_runtime36=require("react/jsx-runtime");function AuthenticationForm(props){let[email,setEmail]=(0,import_react22.useState)();return email?(0,import_jsx_runtime36.jsx)(PasswordForm,{email,...props}):(0,import_jsx_runtime36.jsx)(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=(0,import_react_hooks17.useMedplum)(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=(0,import_react22.useState)(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=(0,import_react22.useCallback)(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),window.location.assign(url.toString()),!0},[medplum,baseLoginRequest]),handleSubmit=(0,import_react22.useCallback)(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=(0,import_react22.useCallback)(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome((0,import_core43.normalizeOperationOutcome)(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return(0,import_jsx_runtime36.jsxs)(Form,{onSubmit:handleSubmit,children:[(0,import_jsx_runtime36.jsx)(import_core42.Center,{style:{flexDirection:"column"},children}),(0,import_jsx_runtime36.jsx)(OperationOutcomeAlert,{issues}),googleClientId&&(0,import_jsx_runtime36.jsxs)(import_jsx_runtime36.Fragment,{children:[(0,import_jsx_runtime36.jsx)(import_core42.Group,{justify:"center",p:"xl",style:{height:70},children:(0,import_jsx_runtime36.jsx)(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.Divider,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.TextInput,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")}),(0,import_jsx_runtime36.jsxs)(import_core42.Group,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[(0,import_jsx_runtime36.jsx)("div",{children:onRegister&&(0,import_jsx_runtime36.jsx)(import_core42.Anchor,{component:"button",type:"button",color:"dimmed",onClick:onRegister,size:"xs",children:"Register"})}),!disableEmailAuth&&(0,import_jsx_runtime36.jsx)(import_core42.Button,{type:"submit",children:"Next"})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=(0,import_react_hooks17.useMedplum)(),[outcome,setOutcome]=(0,import_react22.useState)(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=(0,import_react22.useCallback)(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome((0,import_core43.normalizeOperationOutcome)(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return(0,import_jsx_runtime36.jsxs)(Form,{onSubmit:handleSubmit,children:[(0,import_jsx_runtime36.jsx)(import_core42.Center,{style:{flexDirection:"column"},children}),(0,import_jsx_runtime36.jsx)(OperationOutcomeAlert,{issues}),(0,import_jsx_runtime36.jsx)(import_core42.Stack,{gap:"xl",children:(0,import_jsx_runtime36.jsx)(import_core42.PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password")})}),(0,import_jsx_runtime36.jsxs)(import_core42.Group,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[onForgotPassword&&(0,import_jsx_runtime36.jsx)(import_core42.Anchor,{component:"button",type:"button",c:"dimmed",onClick:onForgotPassword,size:"xs",children:"Forgot password"}),(0,import_jsx_runtime36.jsx)(import_core42.Checkbox,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),(0,import_jsx_runtime36.jsx)(import_core42.Button,{type:"submit",children:"Sign in"})]})]})}var import_core44=require("@mantine/core"),import_core45=require("@medplum/core"),import_react_hooks18=require("@medplum/react-hooks"),import_react23=require("react");var import_jsx_runtime37=require("react/jsx-runtime");function ChooseProfileForm(props){let medplum=(0,import_react_hooks18.useMedplum)(),combobox=(0,import_core44.useCombobox)(),[search,setSearch]=(0,import_react23.useState)(""),[outcome,setOutcome]=(0,import_react23.useState)();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((0,import_core45.normalizeOperationOutcome)(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Option,{value:item.id,children:(0,import_jsx_runtime37.jsx)(SelectOption,{...item})},item.id));return(0,import_jsx_runtime37.jsxs)(import_core44.Stack,{children:[(0,import_jsx_runtime37.jsxs)(import_core44.Flex,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[(0,import_jsx_runtime37.jsx)(Logo,{size:32}),(0,import_jsx_runtime37.jsx)(import_core44.Title,{order:3,children:"Choose profile"})]}),(0,import_jsx_runtime37.jsx)(OperationOutcomeAlert,{outcome}),(0,import_jsx_runtime37.jsxs)(import_core44.Combobox,{store:combobox,onOptionSubmit:handleValueSelect,children:[(0,import_jsx_runtime37.jsx)(import_core44.Combobox.EventsTarget,{children:(0,import_jsx_runtime37.jsx)(import_core44.TextInput,{placeholder:"Search",value:search,onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),(0,import_jsx_runtime37.jsx)("div",{children:(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Options,{children:options.length>0?options:(0,import_jsx_runtime37.jsx)(import_core44.Combobox.Empty,{children:"Nothing found..."})})})]})]})}function SelectOption(membership){return(0,import_jsx_runtime37.jsxs)(import_core44.Group,{children:[(0,import_jsx_runtime37.jsx)(import_core44.Avatar,{radius:"xl"}),(0,import_jsx_runtime37.jsxs)("div",{children:[(0,import_jsx_runtime37.jsx)(import_core44.Text,{fz:"sm",fw:500,children:membership.profile?.display}),(0,import_jsx_runtime37.jsx)(import_core44.Text,{fz:"xs",opacity:.6,children:membership.project?.display})]})]})}var import_core46=require("@mantine/core"),import_react_hooks19=require("@medplum/react-hooks");var import_jsx_runtime38=require("react/jsx-runtime"),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=(0,import_react_hooks19.useMedplum)();return(0,import_jsx_runtime38.jsx)(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:(0,import_jsx_runtime38.jsxs)(import_core46.Stack,{children:[(0,import_jsx_runtime38.jsxs)(import_core46.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime38.jsx)(Logo,{size:32}),(0,import_jsx_runtime38.jsx)(import_core46.Title,{children:"Choose scope"})]}),(0,import_jsx_runtime38.jsx)(import_core46.Stack,{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]),(0,import_jsx_runtime38.jsxs)(import_jsx_runtime38.Fragment,{children:[(0,import_jsx_runtime38.jsx)(import_core46.Checkbox,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName),additionalScopes?.map(scope=>(0,import_jsx_runtime38.jsx)(import_core46.Checkbox,{id:scope,name:scope,label:scope},scope))]})})}),(0,import_jsx_runtime38.jsx)(import_core46.Group,{justify:"flex-end",mt:"xl",children:(0,import_jsx_runtime38.jsx)(import_core46.Button,{type:"submit",children:"Set scope"})})]})})}var import_core47=require("@mantine/core"),import_core48=require("@medplum/core");var import_react24=require("react");var import_jsx_runtime39=require("react/jsx-runtime");function MfaForm(props){let[errorMessage,setErrorMessage]=(0,import_react24.useState)();return(0,import_jsx_runtime39.jsx)(Form,{onSubmit:formData=>{setErrorMessage(void 0),props.onSubmit(formData).catch(err=>setErrorMessage((0,import_core48.normalizeErrorString)(err)))},children:(0,import_jsx_runtime39.jsxs)(import_core47.Stack,{children:[(0,import_jsx_runtime39.jsxs)(import_core47.Center,{style:{flexDirection:"column"},children:[(0,import_jsx_runtime39.jsx)(Logo,{size:32}),(0,import_jsx_runtime39.jsx)(import_core47.Title,{children:"Enter MFA code"})]}),errorMessage&&(0,import_jsx_runtime39.jsx)(import_core47.Alert,{icon:(0,import_jsx_runtime39.jsx)(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),(0,import_jsx_runtime39.jsx)(import_core47.Stack,{children:(0,import_jsx_runtime39.jsx)(import_core47.TextInput,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),(0,import_jsx_runtime39.jsx)(import_core47.Group,{justify:"flex-end",mt:"xl",children:(0,import_jsx_runtime39.jsx)(import_core47.Button,{type:"submit",children:"Submit code"})})]})})}var import_jsx_runtime40=require("react/jsx-runtime");function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=(0,import_react_hooks20.useMedplum)(),[login,setLogin]=(0,import_react25.useState)(),loginRequested=(0,import_react25.useRef)(!1),[mfaRequired,setAuthenticatorRequired]=(0,import_react25.useState)(!1),[memberships,setMemberships]=(0,import_react25.useState)(),handleCode=(0,import_react25.useCallback)(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>(0,import_notifications4.showNotification)({color:"red",message:(0,import_core49.normalizeErrorString)(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=(0,import_react25.useCallback)(response=>{setAuthenticatorRequired(!!response.mfaRequired),response.login&&setLogin(response.login),response.memberships&&setMemberships(response.memberships),response.code&&(chooseScopes?setMemberships(void 0):handleCode(response.code))},[chooseScopes,handleCode]),handleScopeResponse=(0,import_react25.useCallback)(response=>{handleCode(response.code)},[handleCode]);return(0,import_react25.useEffect)(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>(0,import_notifications4.showNotification)({color:"red",message:(0,import_core49.normalizeErrorString)(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),(0,import_jsx_runtime40.jsx)(Document,{width:450,px:"sm",py:"md",children:login?mfaRequired?(0,import_jsx_runtime40.jsx)(MfaForm,{onSubmit:async fields=>{let res=await medplum.post("auth/mfa/verify",{login,token:fields.token});handleAuthResponse(res)}}):memberships?(0,import_jsx_runtime40.jsx)(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.projectId==="new"?(0,import_jsx_runtime40.jsx)(NewProjectForm,{login,handleAuthResponse}):props.chooseScopes?(0,import_jsx_runtime40.jsx)(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):(0,import_jsx_runtime40.jsx)("div",{children:"Success"}):(0,import_jsx_runtime40.jsx)(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}var import_core63=require("@medplum/core");var import_core61=require("@mantine/core"),import_core62=require("@medplum/core");var import_core50=require("@medplum/core"),import_jsx_runtime41=require("react/jsx-runtime");function CodeableConceptDisplay(props){return(0,import_jsx_runtime41.jsx)(import_jsx_runtime41.Fragment,{children:(0,import_core50.formatCodeableConcept)(props.value)})}var import_core51=require("@medplum/core"),import_jsx_runtime42=require("react/jsx-runtime");function CodingDisplay(props){return(0,import_jsx_runtime42.jsx)(import_jsx_runtime42.Fragment,{children:(0,import_core51.formatCoding)(props.value)})}var import_jsx_runtime43=require("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("]")),(0,import_jsx_runtime43.jsx)(import_jsx_runtime43.Fragment,{children:builder.join("").trim()})}var import_jsx_runtime44=require("react/jsx-runtime");function ContactDetailDisplay(props){let contactDetail=props.value;return contactDetail?(0,import_jsx_runtime44.jsxs)(import_jsx_runtime44.Fragment,{children:[contactDetail.name,contactDetail.name&&": ",contactDetail.telecom?.map(telecom=>(0,import_jsx_runtime44.jsx)(ContactPointDisplay,{value:telecom},`telecom-${contactDetail.name}-${telecom.value}`))]}):null}var import_jsx_runtime45=require("react/jsx-runtime");function IdentifierDisplay(props){return(0,import_jsx_runtime45.jsxs)("div",{children:[props.value?.system,": ",props.value?.value]})}var import_core52=require("@medplum/core"),import_jsx_runtime46=require("react/jsx-runtime");function MoneyDisplay(props){return(0,import_jsx_runtime46.jsx)(import_jsx_runtime46.Fragment,{children:(0,import_core52.formatMoney)(props.value)})}var import_core53=require("@medplum/core"),import_jsx_runtime47=require("react/jsx-runtime");function QuantityDisplay(props){return(0,import_jsx_runtime47.jsx)(import_jsx_runtime47.Fragment,{children:(0,import_core53.formatQuantity)(props.value)})}var import_core54=require("@medplum/core"),import_jsx_runtime48=require("react/jsx-runtime");function RangeDisplay(props){return(0,import_jsx_runtime48.jsx)(import_jsx_runtime48.Fragment,{children:(0,import_core54.formatRange)(props.value)})}var import_jsx_runtime49=require("react/jsx-runtime");function RatioDisplay(props){let value=props.value;return value?(0,import_jsx_runtime49.jsxs)(import_jsx_runtime49.Fragment,{children:[(0,import_jsx_runtime49.jsx)(QuantityDisplay,{value:value.numerator}),"\xA0/\xA0",(0,import_jsx_runtime49.jsx)(QuantityDisplay,{value:value.denominator})]}):null}var import_core55=require("@medplum/core");var import_jsx_runtime50=require("react/jsx-runtime");function ReferenceDisplay(props){if(!props.value)return null;let displayString=props.value.display||props.value.reference||(0,import_core55.stringify)(props.value);return props.link!==!1&&props.value.reference?(0,import_jsx_runtime50.jsx)(MedplumLink,{to:props.value,children:displayString}):(0,import_jsx_runtime50.jsx)(import_jsx_runtime50.Fragment,{children:displayString})}var import_core58=require("@medplum/core");var import_react27=require("react");var import_core56=require("@medplum/core");function assignValuesIntoSlices(values,slices,slicing,profileUrl){if(!(0,import_core56.isPopulated)(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=(0,import_core56.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(!(0,import_core56.isSliceDefinitionWithTypes)(slice)){console.debug("Unsupported slice definition",slice);continue}let profileUrl;(0,import_core56.isPopulated)(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=(0,import_core56.tryGetProfile)(profileUrl);slice.typeSchema=typeSchema}}resolve(supportedSlices)}).catch(reject)})}var import_react_hooks21=require("@medplum/react-hooks");var import_core57=require("@medplum/core"),import_react26=require("react");var import_jsx_runtime51=require("react/jsx-runtime");function maybeWrapWithContext(ContextProvider,contextValue,contents){return contextValue!==void 0?(0,import_jsx_runtime51.jsx)(ContextProvider,{value:contextValue,children:contents}):contents}var import_jsx_runtime52=require("react/jsx-runtime");function SliceDisplay(props){let{slice,property}=props,sliceElements=slice.typeSchema?.elements??slice.elements,parentContext=(0,import_react26.useContext)(ElementsContext),contextValue=(0,import_react26.useMemo)(()=>{if((0,import_core57.isPopulated)(sliceElements))return(0,import_core57.buildElementsContext)({parentContext,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentContext,props.path,slice.typeSchema?.url,sliceElements]);return maybeWrapWithContext(ElementsContext.Provider,contextValue,(0,import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment,{children:props.value.map((value,valueIndex)=>(0,import_jsx_runtime52.jsx)("div",{children:(0,import_jsx_runtime52.jsx)(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}`))}))}var import_jsx_runtime53=require("react/jsx-runtime");function ResourceArrayDisplay(props){let{property,propertyType}=props,medplum=(0,import_react_hooks21.useMedplum)(),values=(0,import_react27.useMemo)(()=>Array.isArray(props.values)?props.values:[],[props.values]),[loading,setLoading]=(0,import_react27.useState)(!0),[slices,setSlices]=(0,import_react27.useState)([]),[slicedValues,setSlicedValues]=(0,import_react27.useState)(()=>[values]),ctx=(0,import_react27.useContext)(ElementsContext);if((0,import_react27.useEffect)(()=>{prepareSlices({medplum,property}).then(slices2=>{setSlices(slices2);let slicedValues2=assignValuesIntoSlices(values,slices2,property.slicing,ctx.profileUrl);setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,ctx.profileUrl,setSlicedValues,values]),loading)return(0,import_jsx_runtime53.jsx)("div",{children:"Loading..."});let nonSliceContent;if(property.type[0]?.code!=="Extension"){let nonSliceValues=slicedValues[slices.length],nonSliceElements=nonSliceValues.map((value,valueIndex)=>(0,import_jsx_runtime53.jsx)("div",{children:(0,import_jsx_runtime53.jsx)(ResourcePropertyDisplay,{path:props.path,arrayElement:!0,property,propertyType,value,ignoreMissingValues:props.ignoreMissingValues,link:props.link})},`${valueIndex}-${nonSliceValues.length}`));if(props.includeDescriptionListEntry){if(!(0,import_core58.isPopulated)(props.path))throw new Error("props.path is required when includeDescriptionListEntry is true");let key=props.path.split(".").pop();nonSliceContent=(0,import_jsx_runtime53.jsx)(DescriptionListEntry,{term:(0,import_core58.getPathDisplayName)(key),children:nonSliceElements})}else nonSliceContent=(0,import_jsx_runtime53.jsx)(import_jsx_runtime53.Fragment,{children:nonSliceElements})}return(0,import_jsx_runtime53.jsxs)(import_jsx_runtime53.Fragment,{children:[slices.map((slice,sliceIndex)=>{if(!props.path)throw Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);let sliceDisplay=(0,import_jsx_runtime53.jsx)(SliceDisplay,{path:props.path,slice,property,value:slicedValues[sliceIndex],ignoreMissingValues:props.ignoreMissingValues,link:props.link},slice.name);return props.includeDescriptionListEntry&&(sliceDisplay=(0,import_jsx_runtime53.jsx)(DescriptionListEntry,{term:(0,import_core58.getPathDisplayName)(slice.name),children:sliceDisplay},slice.name)),sliceDisplay}),nonSliceContent]})}var import_core60=require("@medplum/core"),import_react_hooks22=require("@medplum/react-hooks"),import_react28=require("react");var import_core59=require("@medplum/core");function getValueAndType(context,path,profileUrl){let typedResult=(0,import_core59.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=(0,import_core59.getTypedPropertyValueWithSchema)(typedValue,path,element);return typedResult?Array.isArray(typedResult)?[typedResult.map(e=>e.value),typedResult[0].type]:[typedResult.value,typedResult.type]:[void 0,"undefined"]}var import_jsx_runtime54=require("react/jsx-runtime");function ExtensionDisplay(props){let{elementDefinitionType}=props,medplum=(0,import_react_hooks22.useMedplum)(),ctx=(0,import_react28.useContext)(ElementsContext),[typeSchema,setTypeSchema]=(0,import_react28.useState)((0,import_core60.getDataType)("Extension")),profileUrl=(0,import_react28.useMemo)(()=>{if((0,import_core60.isPopulated)(elementDefinitionType?.profile))return elementDefinitionType.profile[0]},[elementDefinitionType]),[loadingProfile,setLoadingProfile]=(0,import_react28.useState)(profileUrl!==void 0);if((0,import_react28.useEffect)(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>{let profile=(0,import_core60.tryGetProfile)(profileUrl);setLoadingProfile(!1),profile&&setTypeSchema(profile)}).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!(0,import_core60.isProfileLoaded)(profileUrl)))return(0,import_jsx_runtime54.jsx)("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(0,import_jsx_runtime54.jsx)(ResourcePropertyDisplay,{propertyType,value:propertyValue})}return(0,import_jsx_runtime54.jsx)(BackboneElementDisplay,{path:props.path,value:{type:typeSchema.type,value:props.value},compact:props.compact,ignoreMissingValues:props.ignoreMissingValues,link:props.link,profileUrl})}var import_jsx_runtime55=require("react/jsx-runtime");function ResourcePropertyDisplay(props){let{property,propertyType,value}=props;if(property?.path?.endsWith(".id"))return(0,import_jsx_runtime55.jsxs)(import_core61.Box,{component:"div",style:{display:"flex",gap:3,alignItems:"center"},children:[value,!(0,import_core62.isEmpty)(value)&&(0,import_jsx_runtime55.jsx)(import_core61.CopyButton,{value,timeout:2e3,children:({copied,copy})=>(0,import_jsx_runtime55.jsx)(import_core61.Tooltip,{label:copied?"Copied":"Copy",withArrow:!0,position:"right",children:(0,import_jsx_runtime55.jsx)(import_core61.ActionIcon,{variant:"subtle",color:copied?"teal":"gray",onClick:copy,children:copied?(0,import_jsx_runtime55.jsx)(IconCheck,{size:"1rem"}):(0,import_jsx_runtime55.jsx)(IconCopy,{size:"1rem"})})})})]});if(property&&(property.isArray||property.max>1)&&!props.arrayElement)return propertyType===import_core62.PropertyType.Attachment?(0,import_jsx_runtime55.jsx)(AttachmentArrayDisplay,{values:value,maxWidth:props.maxWidth,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,property,path:props.path}):(0,import_jsx_runtime55.jsx)(ResourceArrayDisplay,{path:props.path,property,propertyType,values:value,includeDescriptionListEntry:props.includeArrayDescriptionListEntry,ignoreMissingValues:props.ignoreMissingValues,link:props.link});switch(propertyType){case import_core62.PropertyType.boolean:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value===void 0?"":(!!value).toString()});case import_core62.PropertyType.SystemString:case import_core62.PropertyType.string:return(0,import_jsx_runtime55.jsx)("div",{style:{whiteSpace:"pre-wrap"},children:value});case import_core62.PropertyType.code:case import_core62.PropertyType.date:case import_core62.PropertyType.decimal:case import_core62.PropertyType.id:case import_core62.PropertyType.integer:case import_core62.PropertyType.positiveInt:case import_core62.PropertyType.unsignedInt:case import_core62.PropertyType.uri:case import_core62.PropertyType.url:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value});case import_core62.PropertyType.canonical:return(0,import_jsx_runtime55.jsx)(ReferenceDisplay,{value:{reference:value},link:props.link});case import_core62.PropertyType.dateTime:case import_core62.PropertyType.instant:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatDateTime)(value)});case import_core62.PropertyType.markdown:return(0,import_jsx_runtime55.jsx)("pre",{children:value});case import_core62.PropertyType.Address:return(0,import_jsx_runtime55.jsx)(AddressDisplay,{value});case import_core62.PropertyType.Annotation:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:value?.text});case import_core62.PropertyType.Attachment:return(0,import_jsx_runtime55.jsx)(AttachmentDisplay,{value,maxWidth:props.maxWidth});case import_core62.PropertyType.CodeableConcept:return(0,import_jsx_runtime55.jsx)(CodeableConceptDisplay,{value});case import_core62.PropertyType.Coding:return(0,import_jsx_runtime55.jsx)(CodingDisplay,{value});case import_core62.PropertyType.ContactDetail:return(0,import_jsx_runtime55.jsx)(ContactDetailDisplay,{value});case import_core62.PropertyType.ContactPoint:return(0,import_jsx_runtime55.jsx)(ContactPointDisplay,{value});case import_core62.PropertyType.HumanName:return(0,import_jsx_runtime55.jsx)(HumanNameDisplay,{value});case import_core62.PropertyType.Identifier:return(0,import_jsx_runtime55.jsx)(IdentifierDisplay,{value});case import_core62.PropertyType.Money:return(0,import_jsx_runtime55.jsx)(MoneyDisplay,{value});case import_core62.PropertyType.Period:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatPeriod)(value)});case import_core62.PropertyType.Quantity:case import_core62.PropertyType.Duration:return(0,import_jsx_runtime55.jsx)(QuantityDisplay,{value});case import_core62.PropertyType.Range:return(0,import_jsx_runtime55.jsx)(RangeDisplay,{value});case import_core62.PropertyType.Ratio:return(0,import_jsx_runtime55.jsx)(RatioDisplay,{value});case import_core62.PropertyType.Reference:return(0,import_jsx_runtime55.jsx)(ReferenceDisplay,{value,link:props.link});case import_core62.PropertyType.Timing:return(0,import_jsx_runtime55.jsx)(import_jsx_runtime55.Fragment,{children:(0,import_core62.formatTiming)(value)});case import_core62.PropertyType.Dosage:case import_core62.PropertyType.UsageContext:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return(0,import_jsx_runtime55.jsx)(BackboneElementDisplay,{path:props.path,value:{type:propertyType,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues});case import_core62.PropertyType.Extension:if(!props.path)throw Error(`Displaying property of type ${props.propertyType} requires path`);return(0,import_jsx_runtime55.jsx)(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(0,import_jsx_runtime55.jsx)(BackboneElementDisplay,{path:props.path,value:{type:property.type[0].code,value},compact:!0,ignoreMissingValues:props.ignoreMissingValues})}}var import_react29=require("react");var import_jsx_runtime56=require("react/jsx-runtime"),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=(0,import_react29.useContext)(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=(0,import_react29.useMemo)(()=>(0,import_core63.tryGetDataType)(typeName,profileUrl),[profileUrl,typeName]),newElementsContext=(0,import_react29.useMemo)(()=>{if(typeSchema)return(0,import_core63.buildElementsContext)({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);if((0,import_core63.isEmpty)(value))return null;if(!typeSchema)return(0,import_jsx_runtime56.jsxs)("div",{children:[typeName,"\xA0not implemented"]});if(typeof value=="object"&&"name"in value&&Object.keys(value).length===1&&typeof value.name=="string")return(0,import_jsx_runtime56.jsx)("div",{children:value.name});let elementsContext=newElementsContext??parentElementsContext;return maybeWrapWithContext(ElementsContext.Provider,newElementsContext,(0,import_jsx_runtime56.jsx)(DescriptionList,{compact:props.compact,children:Object.entries(elementsContext.elements).map(([key,property])=>{if(EXTENSION_KEYS2.includes(key)&&(0,import_core63.isEmpty)(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)&&(0,import_core63.isEmpty)(propertyValue)||props.path.endsWith(".extension")&&(key==="url"||key==="id"))return null;let isArrayProperty=property.max>1||property.isArray,resourcePropertyDisplay=(0,import_jsx_runtime56.jsx)(ResourcePropertyDisplay,{property,propertyType,path:props.path+"."+key,value:propertyValue,ignoreMissingValues:props.ignoreMissingValues,includeArrayDescriptionListEntry:isArrayProperty,link:props.link},key);return isArrayProperty?resourcePropertyDisplay:(0,import_jsx_runtime56.jsx)(DescriptionListEntry,{term:(0,import_core63.getPathDisplayName)(key),children:resourcePropertyDisplay},key)})}))}var import_core97=require("@medplum/core"),import_react52=require("react");var import_core95=require("@mantine/core"),import_core96=require("@medplum/core"),import_react51=require("react");var import_core65=require("@mantine/core"),import_react30=require("react");var import_core64=require("@mantine/core"),import_jsx_runtime57=require("react/jsx-runtime"),READ_ONLY_TOOLTIP_TEXT="Read Only";function maybeWrapWithTooltip(tooltipText,children){return tooltipText?(0,import_jsx_runtime57.jsx)(import_core64.Tooltip.Floating,{label:tooltipText,children}):children}var FormSection_default={dimmed:"FormSection_dimmed",preserveBreaks:"FormSection_preserveBreaks"};var import_jsx_runtime58=require("react/jsx-runtime");function CheckboxFormSection(props){let{debugMode}=(0,import_react30.useContext)(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,(0,import_jsx_runtime58.jsxs)(import_core65.Group,{wrap:"nowrap","data-testid":props.testId,children:[(0,import_jsx_runtime58.jsx)("div",{children:props.children}),(0,import_jsx_runtime58.jsx)("div",{children:(0,import_jsx_runtime58.jsx)(import_core65.Input.Wrapper,{id:props.htmlFor,label,classNames:{label:props?.readonly?FormSection_default.dimmed:void 0},description:props.description,withAsterisk:props.withAsterisk,children:null})})]}))}var import_core66=require("@mantine/core"),import_react31=require("react");var import_jsx_runtime59=require("react/jsx-runtime");function FormSection(props){let{debugMode}=(0,import_react31.useContext)(ElementsContext),label;return debugMode&&props.fhirPath?label=`${props.title} - ${props.fhirPath}`:label=props.title,maybeWrapWithTooltip(props?.readonly?READ_ONLY_TOOLTIP_TEXT:void 0,(0,import_jsx_runtime59.jsx)(import_core66.Input.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}))}var import_core67=require("@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]",(0,import_core67.capitalize)(type.code));compoundKey in obj&&delete obj[compoundKey]}return(0,import_core67.isEmpty)(value)?obj[propName]=void 0:obj[propName]=value,obj}function isSupportedProfileStructureDefinition(profile){return!!profile&&!(0,import_core67.isEmpty)(profile.url)&&!(0,import_core67.isEmpty)(profile.name)}var import_core93=require("@mantine/core"),import_core94=require("@medplum/core"),import_react50=require("react");var import_react32=require("react");var import_jsx_runtime60=require("react/jsx-runtime");function CodeableConceptInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,outcome:_outcome,path:_path,valuePath:_valuePath,...rest}=props,[value,setValue]=(0,import_react32.useState)(defaultValue2);function handleChange(newValues){let newConcept=valueSetElementToCodeableConcept(newValues);setValue(newConcept),onChange&&onChange(newConcept)}return(0,import_jsx_runtime60.jsx)(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}))}}var import_react33=require("react");var import_jsx_runtime61=require("react/jsx-runtime");function CodingInput(props){let{defaultValue:defaultValue2,onChange,withHelpText,...rest}=props,[value,setValue]=(0,import_react33.useState)(defaultValue2);function handleChange(newValues){let newValue=newValues[0],newConcept=newValue&&valueSetElementToCoding(newValue);setValue(newConcept),onChange&&onChange(newConcept)}return(0,import_jsx_runtime61.jsx)(ValueSetAutocomplete,{defaultValue:value&&codingToValueSetElement(value),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}}var import_core69=require("@mantine/core"),import_react35=require("react");var import_core68=require("@mantine/core"),import_react34=require("react");var import_jsx_runtime62=require("react/jsx-runtime");function ContactPointInput(props){let{path,outcome}=props,{elementsByPath,getExtendedProps}=(0,import_react34.useContext)(ElementsContext),[contactPoint,setContactPoint]=(0,import_react34.useState)(props.defaultValue),ref=(0,import_react34.useRef)();ref.current=contactPoint;let[systemElement,useElement,valueElement]=(0,import_react34.useMemo)(()=>["system","use","value"].map(field=>elementsByPath[path+"."+field]),[elementsByPath,path]),[systemProps,useProps,valueProps]=(0,import_react34.useMemo)(()=>["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(0,import_jsx_runtime62.jsxs)(import_core68.Group,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[(0,import_jsx_runtime62.jsx)(import_core68.NativeSelect,{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")}),(0,import_jsx_runtime62.jsx)(import_core68.NativeSelect,{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")}),(0,import_jsx_runtime62.jsx)(import_core68.TextInput,{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")})]})}var import_jsx_runtime63=require("react/jsx-runtime");function ContactDetailInput(props){let[contactPoint,setContactDetail]=(0,import_react35.useState)(props.defaultValue),ref=(0,import_react35.useRef)();ref.current=contactPoint;let{getExtendedProps}=(0,import_react35.useContext)(ElementsContext),[nameProps,telecomProps]=(0,import_react35.useMemo)(()=>["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(0,import_jsx_runtime63.jsxs)(import_core69.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime63.jsx)(import_core69.TextInput,{disabled:props.disabled||nameProps?.readonly,"data-testid":props.name+"-name",name:props.name+"-name",placeholder:"Name",style:{width:180},defaultValue:contactPoint?.name,onChange:e=>setName(e.currentTarget.value)}),(0,import_jsx_runtime63.jsx)(ContactPointInput,{disabled:props.disabled||telecomProps?.readonly,name:props.name+"-telecom",path:props.path+".telecom",defaultValue:contactPoint?.telecom?.[0],onChange:setTelecom,outcome:props.outcome})]})}var import_core71=require("@mantine/core");var import_core70=require("@medplum/core");function convertIsoToLocal(isoString){if(!isoString)return"";let date=new Date(isoString);return(0,import_core70.isValidDate)(date)?date.toLocaleDateString("sv")+"T"+date.toLocaleTimeString("sv"):""}function convertLocalToIso(localString){if(!localString)return"";let date=new Date(localString);return(0,import_core70.isValidDate)(date)?date.toISOString():""}var import_jsx_runtime64=require("react/jsx-runtime");function DateTimeInput(props){return(0,import_jsx_runtime64.jsx)(import_core71.TextInput,{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(),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"}var import_core72=require("@medplum/core"),import_react_hooks23=require("@medplum/react-hooks"),import_react36=require("react");var import_jsx_runtime65=require("react/jsx-runtime");function ExtensionInput(props){let{propertyType}=props,medplum=(0,import_react_hooks23.useMedplum)(),profileUrl=(0,import_react36.useMemo)(()=>{if((0,import_core72.isPopulated)(propertyType.profile))return propertyType.profile[0]},[propertyType]),[loadingProfile,setLoadingProfile]=(0,import_react36.useState)(profileUrl!==void 0);return(0,import_react36.useEffect)(()=>{profileUrl&&(setLoadingProfile(!0),medplum.requestProfileSchema(profileUrl).then(()=>setLoadingProfile(!1)).catch(reason=>{setLoadingProfile(!1),console.warn(reason)}))},[medplum,profileUrl]),profileUrl&&(loadingProfile||!(0,import_core72.isProfileLoaded)(profileUrl))?(0,import_jsx_runtime65.jsx)("div",{children:"Loading..."}):(0,import_jsx_runtime65.jsx)(BackboneElementInput,{profileUrl,path:props.path,typeName:"Extension",defaultValue:props.defaultValue,onChange:props.onChange})}var import_core73=require("@mantine/core"),import_react37=require("react");var import_jsx_runtime66=require("react/jsx-runtime");function HumanNameInput(props){let{outcome,path}=props,[value,setValue]=(0,import_react37.useState)(props.defaultValue),{getExtendedProps}=(0,import_react37.useContext)(ElementsContext),[useProps,prefixProps,givenProps,familyProps,suffixProps]=(0,import_react37.useMemo)(()=>["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(0,import_jsx_runtime66.jsxs)(import_core73.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime66.jsx)(import_core73.NativeSelect,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")}),(0,import_jsx_runtime66.jsx)(import_core73.TextInput,{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")})]})}var import_core74=require("@mantine/core"),import_react38=require("react");var import_jsx_runtime67=require("react/jsx-runtime");function IdentifierInput(props){let[value,setValue]=(0,import_react38.useState)(props.defaultValue),{elementsByPath,getExtendedProps}=(0,import_react38.useContext)(ElementsContext),[systemElement,valueElement]=(0,import_react38.useMemo)(()=>["system","value"].map(field=>elementsByPath[props.path+"."+field]),[elementsByPath,props.path]),[systemProps,valueProps]=(0,import_react38.useMemo)(()=>["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(0,import_jsx_runtime67.jsxs)(import_core74.Group,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[(0,import_jsx_runtime67.jsx)(import_core74.TextInput,{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")}),(0,import_jsx_runtime67.jsx)(import_core74.TextInput,{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")})]})}var import_core75=require("@mantine/core");var import_react39=require("react");var import_jsx_runtime68=require("react/jsx-runtime"),data=["USD","EUR","CAD","GBP","AUD"];function MoneyInput(props){let{onChange}=props,[value,setValue]=(0,import_react39.useState)(props.defaultValue),{getExtendedProps}=(0,import_react39.useContext)(ElementsContext),[currencyProps,valueProps]=(0,import_react39.useMemo)(()=>["currency","value"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]),setValueWrapper=(0,import_react39.useCallback)(newValue=>{setValue(newValue),onChange&&onChange(newValue)},[onChange]),handleCurrencyChange=(0,import_react39.useCallback)(e=>{setValueWrapper({...value,currency:e.currentTarget.value})},[value,setValueWrapper]),handleValueChange=(0,import_react39.useCallback)(e=>{setValueWrapper({...value,value:e.currentTarget.valueAsNumber})},[value,setValueWrapper]),select=(0,import_jsx_runtime68.jsx)(import_core75.NativeSelect,{disabled:props.disabled||currencyProps?.readonly,defaultValue:value?.currency,data,styles:{input:{fontWeight:500,borderTopLeftRadius:0,borderBottomLeftRadius:0,width:92}},onChange:handleCurrencyChange});return(0,import_jsx_runtime68.jsx)(import_core75.TextInput,{disabled:props.disabled||valueProps?.readonly,type:"number",name:props.name,label:props.label,placeholder:props.placeholder??"Value",defaultValue:value?.value?.toString()??"USD",leftSection:(0,import_jsx_runtime68.jsx)(IconCurrencyDollar,{size:14}),rightSection:select,rightSectionWidth:92,onChange:handleValueChange})}var import_core76=require("@mantine/core"),import_react40=require("react");var import_jsx_runtime69=require("react/jsx-runtime");function PeriodInput(props){let[value,setValue]=(0,import_react40.useState)(props.defaultValue),{getExtendedProps}=(0,import_react40.useContext)(ElementsContext),[startProps,endProps]=(0,import_react40.useMemo)(()=>["start","end"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime69.jsxs)(import_core76.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime69.jsx)(DateTimeInput,{disabled:props.disabled||startProps?.readonly,name:props.name+".start",placeholder:"Start",defaultValue:value?.start,onChange:newValue=>setValueWrapper({...value,start:newValue})}),(0,import_jsx_runtime69.jsx)(DateTimeInput,{disabled:props.disabled||endProps?.readonly,name:props.name+".end",placeholder:"End",defaultValue:value?.end,onChange:newValue=>setValueWrapper({...value,end:newValue})})]})}var import_core77=require("@mantine/core"),import_react41=require("react");var import_jsx_runtime70=require("react/jsx-runtime");function QuantityInput(props){let[value,setValue]=(0,import_react41.useState)(props.defaultValue),{getExtendedProps}=(0,import_react41.useContext)(ElementsContext),[comparatorProps,valueProps,unitProps]=(0,import_react41.useMemo)(()=>["comparator","value","unit"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime70.jsxs)(import_core77.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime70.jsx)(import_core77.NativeSelect,{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})}),(0,import_jsx_runtime70.jsx)(import_core77.TextInput,{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)})}}),(0,import_jsx_runtime70.jsx)(import_core77.TextInput,{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)}var import_core78=require("@mantine/core"),import_react42=require("react");var import_jsx_runtime71=require("react/jsx-runtime");function RangeInput(props){let[value,setValue]=(0,import_react42.useState)(props.defaultValue),{getExtendedProps}=(0,import_react42.useContext)(ElementsContext),[lowProps,highProps]=(0,import_react42.useMemo)(()=>["low","high"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime71.jsxs)(import_core78.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime71.jsx)(QuantityInput,{path:props.path+".low",disabled:props.disabled||lowProps?.readonly,name:props.name+"-low",defaultValue:value?.low,onChange:v=>setValueWrapper({...value,low:v})}),(0,import_jsx_runtime71.jsx)(QuantityInput,{path:props.path+".high",disabled:props.disabled||highProps?.readonly,name:props.name+"-high",defaultValue:value?.high,onChange:v=>setValueWrapper({...value,high:v})})]})}var import_core79=require("@mantine/core"),import_react43=require("react");var import_jsx_runtime72=require("react/jsx-runtime");function RatioInput(props){let[value,setValue]=(0,import_react43.useState)(props.defaultValue),{getExtendedProps}=(0,import_react43.useContext)(ElementsContext),[numeratorProps,denominatorProps]=(0,import_react43.useMemo)(()=>["numerator","denominator"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}return(0,import_jsx_runtime72.jsxs)(import_core79.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[(0,import_jsx_runtime72.jsx)(QuantityInput,{path:props.path+".numerator",disabled:props.disabled||numeratorProps?.readonly,name:props.name+"-numerator",defaultValue:value?.numerator,onChange:v=>setValueWrapper({...value,numerator:v})}),(0,import_jsx_runtime72.jsx)(QuantityInput,{path:props.path+".denominator",disabled:props.disabled||denominatorProps?.readonly,name:props.name+"-denominator",defaultValue:value?.denominator,onChange:v=>setValueWrapper({...value,denominator:v})})]})}var import_core82=require("@mantine/core"),import_core83=require("@medplum/core"),import_react_hooks25=require("@medplum/react-hooks"),import_react45=require("react");var import_core80=require("@mantine/core"),import_core81=require("@medplum/core"),import_react_hooks24=require("@medplum/react-hooks"),import_react44=require("react");var import_jsx_runtime73=require("react/jsx-runtime"),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:(0,import_core81.getReferenceString)(resource),label:(0,import_core81.getDisplayString)(resource),resource}}function ResourceInput(props){let medplum=(0,import_react_hooks24.useMedplum)(),{resourceType,searchCriteria}=props,[outcome,setOutcome]=(0,import_react44.useState)(),defaultValue2=(0,import_react_hooks24.useResource)(props.defaultValue,setOutcome),ItemComponent3=props.itemComponent??DefaultItemComponent2,onChange=props.onChange,loadValues=(0,import_react44.useCallback)(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=(0,import_react44.useCallback)(newResources=>{onChange&&onChange(newResources[0])},[onChange]);return(0,import_core81.isPopulated)(props.defaultValue)&&!outcome&&!defaultValue2?null:(0,import_jsx_runtime73.jsx)(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=(0,import_react44.forwardRef)(({label,resource,active:_active,...others},ref)=>(0,import_jsx_runtime73.jsx)("div",{ref,...others,children:(0,import_jsx_runtime73.jsxs)(import_core80.Group,{wrap:"nowrap",children:[(0,import_jsx_runtime73.jsx)(ResourceAvatar,{value:resource}),(0,import_jsx_runtime73.jsxs)("div",{children:[(0,import_jsx_runtime73.jsx)(import_core80.Text,{children:label}),(0,import_jsx_runtime73.jsx)(import_core80.Text,{size:"xs",c:"dimmed",children:resource.birthDate||resource.id})]})]})}));function getSearchParamForResourceType(resourceType){return SEARCH_CODES[resourceType]??(NAME_RESOURCE_TYPES.includes(resourceType)?"name":"_id")}var import_jsx_runtime74=require("react/jsx-runtime");function ReferenceInput(props){let{onChange}=props,medplum=(0,import_react_hooks25.useMedplum)(),[value,setValue]=(0,import_react45.useState)(props.defaultValue),[targetTypes,setTargetTypes]=(0,import_react45.useState)(()=>createTargetTypes(props.targetTypes)),[targetType,setTargetType]=(0,import_react45.useState)(()=>getInitialTargetType(props.defaultValue,targetTypes)),promiseCache=(0,import_react45.useRef)(new import_core83.LRUCache),searchCriteria=(0,import_react45.useMemo)(()=>targetType?.type==="profile"?{...props.searchCriteria,_profile:targetType.value}:props.searchCriteria,[props.searchCriteria,targetType]);(0,import_react45.useEffect)(()=>{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?(0,import_core83.isPopulated)(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 import_core83.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=(0,import_react45.useCallback)(item=>{let newValue=item?(0,import_core83.createReference)(item):void 0;setValue(newValue),onChange&&onChange(newValue)},[onChange]),typeSelectOptions=(0,import_react45.useMemo)(()=>targetTypes?targetTypes.map(tt=>({value:tt.value,label:tt.type==="profile"?tt.title??tt.name??tt.resourceType??tt.value:tt.value})):[],[targetTypes]);return(0,import_jsx_runtime74.jsxs)(import_core82.Group,{gap:"xs",grow:!0,wrap:"nowrap",children:[targetTypes&&targetTypes.length>1&&(0,import_jsx_runtime74.jsx)(import_core82.NativeSelect,{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&&(0,import_jsx_runtime74.jsx)(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"}),(0,import_jsx_runtime74.jsx)(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=(0,import_core83.tryGetProfile)(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,
68
68
  name,