@medplum/react 3.2.6 → 3.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +52 -52
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/cjs/index.d.ts +12 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.mjs +52 -52
- package/dist/esm/index.mjs.map +2 -2
- package/package.json +23 -22
package/dist/esm/index.mjs
CHANGED
|
@@ -70,12 +70,12 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
70
70
|
}
|
|
71
71
|
}`.replace(/\s+/g," ");return(await medplum.graphql(query)).data.StructureDefinitionList[0]}function shouldFetchResourceType(targetType){return targetType.type==="profile"&&!targetType?.error&&isEmpty4(targetType.resourceType)}import{Group as Group20,Stack as Stack4,Text as Text8}from"@mantine/core";import{getPathDisplayName as getPathDisplayName4}from"@medplum/core";import{useContext as useContext18,useEffect as useEffect7,useState as useState28}from"react";import{Group as Group19,Stack as Stack3,Text as Text7}from"@mantine/core";import{buildElementsContext as buildElementsContext3,getPropertyDisplayName,isEmpty as isEmpty5,isPopulated as isPopulated10}from"@medplum/core";import{useContext as useContext17,useMemo as useMemo18,useState as useState27}from"react";var ResourceArrayInput_default={indented:"ResourceArrayInput_indented"};import{ActionIcon as ActionIcon3,Button as Button4}from"@mantine/core";import{jsx as jsx59}from"react/jsx-runtime";function ArrayAddButton({propertyDisplayName,onClick,testId}){let text=propertyDisplayName?`Add ${propertyDisplayName}`:"Add";return propertyDisplayName?jsx59(Button4,{title:text,size:"sm",color:"green.6",variant:"subtle","data-testid":testId,leftSection:jsx59(IconCirclePlus,{size:"1.25rem"}),onClick,children:text}):jsx59(ActionIcon3,{title:text,color:"green.6","data-testid":testId,onClick,children:jsx59(IconCirclePlus,{size:"1.25rem"})})}import{ActionIcon as ActionIcon4}from"@mantine/core";import{jsx as jsx60}from"react/jsx-runtime";function ArrayRemoveButton({propertyDisplayName,onClick,testId}){return jsx60(ActionIcon4,{title:propertyDisplayName?`Remove ${propertyDisplayName}`:"Remove",color:"red.5","data-testid":testId,variant:"subtle",onClick,children:jsx60(IconCircleMinus,{size:"1.25rem"})})}import{jsx as jsx61,jsxs as jsxs32}from"react/jsx-runtime";function SliceInput(props){let{slice,property}=props,[values,setValues]=useState27(props.defaultValue),sliceElements=slice.typeSchema?.elements??slice.elements,parentElementsContextValue=useContext17(ElementsContext),contextValue=useMemo18(()=>{if(isPopulated10(sliceElements))return buildElementsContext3({parentContext:parentElementsContextValue,elements:sliceElements,path:props.path,profileUrl:slice.typeSchema?.url})},[parentElementsContextValue,props.path,slice.typeSchema?.url,sliceElements]);function setValuesWrapper(newValues){setValues(newValues),props.onChange&&props.onChange(newValues)}let required=slice.min>0,indentedStack=isEmpty5(slice.elements),propertyDisplayName=getPropertyDisplayName(slice.name),showEmptyMessage=props.property.readonly&&values.length===0;return maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx61(FormSection,{title:propertyDisplayName,description:slice.definition,withAsterisk:required,fhirPath:`${property.path}:${slice.name}`,testId:props.testId,readonly:props.property.readonly,children:showEmptyMessage?jsx61(Text7,{c:"dimmed",children:"(empty)"}):jsxs32(Stack3,{className:indentedStack?ResourceArrayInput_default.indented:void 0,children:[values.map((value,valueIndex)=>jsxs32(Group19,{wrap:"nowrap",children:[jsx61("div",{style:{flexGrow:1},"data-testid":props.testId&&`${props.testId}-elements-${valueIndex}`,children:jsx61(ElementDefinitionTypeInput,{elementDefinitionType:slice.type[0],name:slice.name,defaultValue:value,onChange:newValue=>{let newValues=[...values];newValues[valueIndex]=newValue,setValuesWrapper(newValues)},outcome:props.outcome,min:slice.min,max:slice.max,binding:slice.binding,path:props.path,valuePath:void 0,readOnly:props.property.readonly})}),!props.property.readonly&&values.length>slice.min&&jsx61(ArrayRemoveButton,{propertyDisplayName,testId:props.testId&&`${props.testId}-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newValues=[...values];newValues.splice(valueIndex,1),setValuesWrapper(newValues)}})]},`${valueIndex}-${values.length}`)),!props.property.readonly&&values.length<slice.max&&jsx61(Group19,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx61(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newValues=[...values,void 0];setValuesWrapper(newValues)},testId:props.testId&&`${props.testId}-add`})})]})}))}function getValuePath(elementPath,valuePath,arrayIndex){return valuePath===void 0?elementPath:arrayIndex===void 0?valuePath:`${valuePath}[${arrayIndex}]`}import{jsx as jsx62,jsxs as jsxs33}from"react/jsx-runtime";function ResourceArrayInput(props){let{property}=props,medplum=R(),[loading,setLoading]=useState28(!0),[slices,setSlices]=useState28([]),[defaultValue2]=useState28(()=>Array.isArray(props.defaultValue)?props.defaultValue:[]),[slicedValues,setSlicedValues]=useState28(()=>[defaultValue2]),ctx=useContext18(ElementsContext),propertyTypeCode=property.type[0]?.code;useEffect7(()=>{prepareSlices({medplum,property}).then(slices2=>{setSlices(slices2);let slicedValues2=assignValuesIntoSlices(defaultValue2,slices2,property.slicing,ctx.profileUrl);addPlaceholderValues(slicedValues2,slices2),setSlicedValues(slicedValues2),setLoading(!1)}).catch(reason=>{console.error(reason),setLoading(!1)})},[medplum,property,defaultValue2,ctx.profileUrl,setSlicedValues]);function setValuesWrapper(newValues,sliceIndex){let newSlicedValues=[...slicedValues];if(newSlicedValues[sliceIndex]=newValues,setSlicedValues(newSlicedValues),props.onChange){let cleaned=newSlicedValues.flat().filter(val=>val!==void 0);props.onChange(cleaned)}}if(loading)return jsx62("div",{children:"Loading..."});let nonSliceIndex=slices.length,nonSliceValues=slicedValues[nonSliceIndex],showNonSliceValues=!(props.hideNonSliceValues??(propertyTypeCode==="Extension"&&slices.length>0)),propertyDisplayName=getPathDisplayName4(property.path),showEmptyMessage=props.property.readonly&&slices.length===0&&defaultValue2.length===0;return jsxs33(Stack4,{className:props.indent?ResourceArrayInput_default.indented:void 0,children:[showEmptyMessage&&jsx62(Text8,{c:"dimmed",children:"(empty)"}),slices.map((slice,sliceIndex)=>jsx62(SliceInput,{slice,path:props.path,valuePath:props.valuePath,property,defaultValue:slicedValues[sliceIndex],onChange:newValue=>{setValuesWrapper(newValue,sliceIndex)},testId:`slice-${slice.name}`},slice.name)),showNonSliceValues&&nonSliceValues.map((value,valueIndex)=>jsxs33(Group20,{wrap:"nowrap",style:{flexGrow:1},children:[jsx62("div",{style:{flexGrow:1},children:jsx62(ResourcePropertyInput,{arrayElement:!0,property:props.property,name:props.name+"."+valueIndex,path:props.path,valuePath:getValuePath(props.path,props.valuePath,valueIndex),defaultValue:value,onChange:newValue=>{let newNonSliceValues=[...nonSliceValues];newNonSliceValues[valueIndex]=newValue,setValuesWrapper(newNonSliceValues,nonSliceIndex)},defaultPropertyType:void 0,outcome:props.outcome})}),!props.property.readonly&&jsx62(ArrayRemoveButton,{propertyDisplayName,testId:`nonsliced-remove-${valueIndex}`,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.splice(valueIndex,1),setValuesWrapper(newNonSliceValues,nonSliceIndex)}})]},`${valueIndex}-${nonSliceValues.length}`)),!props.property.readonly&&showNonSliceValues&&slicedValues.flat().length<property.max&&jsx62(Group20,{wrap:"nowrap",style:{justifyContent:"flex-start"},children:jsx62(ArrayAddButton,{propertyDisplayName,onClick:e=>{killEvent(e);let newNonSliceValues=[...nonSliceValues];newNonSliceValues.push(void 0),setValuesWrapper(newNonSliceValues,nonSliceIndex)},testId:"nonsliced-add"})})]})}function addPlaceholderValues(slicedValues,slices){for(let sliceIndex=0;sliceIndex<slices.length;sliceIndex++){let slice=slices[sliceIndex],sliceValues=slicedValues[sliceIndex];for(;sliceValues.length<slice.min;)sliceValues.push(void 0)}}import{ActionIcon as ActionIcon5,Flex,Textarea}from"@mantine/core";import{useClipboard}from"@mantine/hooks";import{showNotification as showNotification4}from"@mantine/notifications";import{useRef as useRef8,useState as useState29}from"react";import{jsx as jsx63,jsxs as jsxs34}from"react/jsx-runtime";function SensitiveTextarea(props){let[revealed,setRevealed]=useState29(!1),clipboard=useClipboard(),ref=useRef8(null),styles={...props.styles};return revealed||(styles.input||(styles.input={}),styles.input.WebkitTextSecurity="disc"),jsxs34(Flex,{gap:"xs",children:[jsx63(Textarea,{...props,styles:{...styles,root:{...styles.root??{},flexGrow:1}},ref,autosize:!0,minRows:1,onFocus:()=>setRevealed(!0),onBlur:()=>setRevealed(!1)}),jsx63(ActionIcon5,{title:"Copy secret",onClick:()=>{clipboard.copy(ref.current?.value),showNotification4({color:"green",message:"Copied"})},children:jsx63(IconCopy,{})})]})}import{Button as Button5,Chip,Group as Group21,Modal as Modal2,NativeSelect as NativeSelect8,Stack as Stack5,Switch,TextInput as TextInput11}from"@mantine/core";import{formatTiming as formatTiming2}from"@medplum/core";import{useContext as useContext19,useMemo as useMemo19,useRef as useRef9,useState as useState30}from"react";import{Fragment as Fragment22,jsx as jsx64,jsxs as jsxs35}from"react/jsx-runtime";var daysOfWeek=["sun","mon","tue","wed","thu","fri","sat"];function TimingInput(props){let[value,setValue]=useState30(props.defaultValue),[open,setOpen]=useState30(!props.disabled&&(props.defaultModalOpen??!1)),valueRef=useRef9();return valueRef.current=value,jsxs35(Fragment22,{children:[jsxs35(Group21,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx64("span",{children:formatTiming2(valueRef.current)||"No repeat"}),jsx64(Button5,{disabled:props.disabled,onClick:()=>setOpen(!0),children:"Edit"})]}),!props.disabled&&jsx64(TimingEditorDialog,{path:props.path,visible:open,defaultValue:valueRef.current,onOk:newValue=>{props.onChange&&props.onChange(newValue),setValue(newValue),setOpen(!1)},onCancel:()=>setOpen(!1)})]})}var defaultValue={repeat:{period:1,periodUnit:"d"}};function TimingEditorDialog(props){let[value,setValue]=useState30(props.defaultValue||defaultValue),{getExtendedProps}=useContext19(ElementsContext),[eventProps,repeatProps,repeatPeriodProps,repeatPeriodUnitProps,repeatDayOfWeekProps]=useMemo19(()=>["event","repeat","repeat.period","repeat.periodUnit","repeat.dayOfWeek"].map(field=>getExtendedProps(props.path+"."+field)),[getExtendedProps,props.path]),valueRef=useRef9();valueRef.current=value;function setStart(newStart){setValue({...valueRef.current,event:[newStart]})}function setRepeat(repeat){setValue({...valueRef.current,repeat})}function setPeriod(newPeriod){setRepeat({...valueRef.current?.repeat,period:newPeriod})}function setPeriodUnit(newPeriodUnit){setRepeat({...valueRef.current?.repeat,periodUnit:newPeriodUnit})}function setDaysOfWeek(newDaysOfWeek){setRepeat({...valueRef.current?.repeat,dayOfWeek:newDaysOfWeek})}return jsx64(Modal2,{title:"Timing",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>props.onCancel(),children:jsxs35(Stack5,{children:[jsx64(FormSection,{title:"Starts on",htmlFor:"timing-dialog-start",children:jsx64(DateTimeInput,{disabled:eventProps?.readonly,name:"timing-dialog-start",onChange:newValue=>setStart(newValue)})}),jsx64(Switch,{disabled:repeatProps?.readonly,label:"Repeat",checked:!!value.repeat,onChange:e=>setRepeat(e.currentTarget.checked?defaultValue.repeat:void 0)}),value.repeat&&jsxs35(Fragment22,{children:[jsx64(FormSection,{title:"Repeat every",htmlFor:"timing-dialog-period",children:jsxs35(Group21,{gap:"xs",grow:!0,wrap:"nowrap",children:[jsx64(TextInput11,{disabled:repeatPeriodProps?.readonly,type:"number",step:1,id:"timing-dialog-period",name:"timing-dialog-period",defaultValue:value.repeat.period||1,onChange:e=>setPeriod(parseInt(e.currentTarget.value,10)||1)}),jsx64(NativeSelect8,{disabled:repeatPeriodUnitProps?.readonly,id:"timing-dialog-periodUnit",name:"timing-dialog-periodUnit",defaultValue:value.repeat.periodUnit,onChange:e=>setPeriodUnit(e.currentTarget.value),data:[{label:"second",value:"s"},{label:"minute",value:"min"},{label:"hour",value:"h"},{label:"day",value:"d"},{label:"week",value:"wk"},{label:"month",value:"mo"},{label:"year",value:"a"}]})]})}),value.repeat.periodUnit==="wk"&&jsx64(FormSection,{title:"Repeat on",children:jsx64(Chip.Group,{multiple:!0,onChange:setDaysOfWeek,children:jsx64(Group21,{justify:"space-between",mt:"md",gap:"xs",children:daysOfWeek.map(day=>jsx64(Chip,{value:day,size:"xs",radius:"xl",disabled:repeatDayOfWeekProps?.readonly,children:day.charAt(0).toUpperCase()},day))})})})]}),jsx64(Group21,{justify:"flex-end",children:jsx64(Button5,{onClick:()=>props.onOk(value),children:"OK"})})]})})}import{jsx as jsx65,jsxs as jsxs36}from"react/jsx-runtime";function ResourcePropertyInput(props){let{property,name,onChange,defaultValue:defaultValue2}=props,defaultPropertyType=props.defaultPropertyType&&props.defaultPropertyType!=="undefined"?props.defaultPropertyType:property.type[0].code,propertyTypes=property.type;if((property.isArray||property.max>1)&&!props.arrayElement){if(defaultPropertyType===PropertyType2.Attachment)return jsx65(AttachmentArrayInput,{name,defaultValue:defaultValue2,onChange,disabled:property.readonly});let indent=propertyTypes[0]?.code!==PropertyType2.Extension;return jsx65(ResourceArrayInput,{property,name,path:props.path,valuePath:props.valuePath,defaultValue:defaultValue2,indent,onChange,outcome:props.outcome})}else return propertyTypes.length>1?jsx65(ElementDefinitionInputSelector,{elementDefinitionTypes:propertyTypes,...props}):jsx65(ElementDefinitionTypeInput,{name,defaultValue:defaultValue2,onChange:newValue=>{if(props.onChange){let newPropName=props.name.replace("[x]",capitalize2(propertyTypes[0].code));props.onChange(newValue,newPropName)}},outcome:props.outcome,elementDefinitionType:propertyTypes[0],min:property.min,max:property.min,binding:property.binding,path:props.path,valuePath:props.valuePath,readOnly:property.readonly})}function ElementDefinitionInputSelector(props){let propertyTypes=props.elementDefinitionTypes,initialPropertyType;props.defaultPropertyType&&(initialPropertyType=propertyTypes.find(t=>t.code===props.defaultPropertyType)),initialPropertyType||(initialPropertyType=propertyTypes[0]);let[selectedType,setSelectedType]=useState31(initialPropertyType);return jsxs36(Group22,{gap:"xs",grow:!0,wrap:"nowrap",align:"flex-start",children:[jsx65(NativeSelect9,{disabled:props.property.readonly,style:{width:"200px"},defaultValue:selectedType.code,"data-testid":props.name&&props.name+"-selector",onChange:e=>{setSelectedType(propertyTypes.find(type=>type.code===e.currentTarget.value))},data:propertyTypes.map(type=>({value:type.code,label:type.code}))}),jsx65(ElementDefinitionTypeInput,{name:props.name,defaultValue:props.defaultValue,outcome:props.outcome,elementDefinitionType:selectedType,onChange:newValue=>{props.onChange&&props.onChange(newValue,props.name.replace("[x]",capitalize2(selectedType.code)))},min:props.property.min,max:props.property.max,binding:props.property.binding,path:props.property.path,valuePath:props.valuePath,readOnly:props.property.readonly})]})}function ElementDefinitionTypeInput(props){let{name,onChange,outcome,binding,path,valuePath,readOnly}=props,required=props.min!==void 0&&props.min>0,propertyType=props.elementDefinitionType.code,elementsContext=useContext20(ElementsContext),defaultValue2=useMemo20(()=>{if(!isComplexTypeCode(propertyType)||!isEmpty6(props.defaultValue))return props.defaultValue;let withDefaults=Object.create(null);if(elementsContext.path===props.path)applyDefaultValuesToElement(withDefaults,elementsContext.elements);else{let key=getPathDifference(elementsContext.path,props.path);if(key===void 0)return props.defaultValue;applyDefaultValuesToElement(withDefaults,elementsContext.elements,key)}return isPopulated11(withDefaults)?withDefaults:props.defaultValue},[propertyType,elementsContext.path,elementsContext.elements,props.path,props.defaultValue]);if(!propertyType)return jsx65("div",{children:"Property type not specified "});function getComplexInputProps(){return{name,defaultValue:defaultValue2,onChange,outcome,path,valuePath,disabled:readOnly}}function getPrimitiveInputProps(){let error=getErrorsForInput(props.outcome,valuePath??path);return{id:name,name,"data-testid":name,defaultValue:defaultValue2,required,error,disabled:readOnly}}switch(propertyType){case PropertyType2.SystemString:case PropertyType2.canonical:case PropertyType2.string:case PropertyType2.time:case PropertyType2.uri:case PropertyType2.url:return props.path==="Project.secret.value[x]"?jsx65(SensitiveTextarea,{...getPrimitiveInputProps(),onChange:e=>{props.onChange&&props.onChange(e.currentTarget.value)}}):jsx65(TextInput12,{...getPrimitiveInputProps(),onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.date:return jsx65(TextInput12,{...getPrimitiveInputProps(),type:"date",onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.dateTime:case PropertyType2.instant:return jsx65(DateTimeInput,{...getPrimitiveInputProps(),onChange,outcome});case PropertyType2.decimal:case PropertyType2.integer:case PropertyType2.positiveInt:case PropertyType2.unsignedInt:return jsx65(TextInput12,{...getPrimitiveInputProps(),type:"number",step:propertyType===PropertyType2.decimal?"any":"1",onChange:e=>{if(onChange){let num=e.currentTarget.valueAsNumber;onChange(Number.isNaN(num)?void 0:num)}}});case PropertyType2.code:return jsx65(CodeInput,{...getPrimitiveInputProps(),error:void 0,onChange,binding:binding?.valueSet});case PropertyType2.boolean:return jsx65(Checkbox,{...getPrimitiveInputProps(),defaultChecked:!!defaultValue2,onChange:e=>{onChange&&onChange(e.currentTarget.checked)}});case PropertyType2.base64Binary:case PropertyType2.markdown:return jsx65(Textarea2,{...getPrimitiveInputProps(),spellCheck:propertyType!==PropertyType2.base64Binary,onChange:e=>{onChange&&onChange(e.currentTarget.value)}});case PropertyType2.Address:return jsx65(AddressInput,{...getComplexInputProps()});case PropertyType2.Annotation:return jsx65(AnnotationInput,{...getComplexInputProps()});case PropertyType2.Attachment:return jsx65(AttachmentInput,{...getComplexInputProps()});case PropertyType2.CodeableConcept:return jsx65(CodeableConceptInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.Coding:return jsx65(CodingInput,{binding:binding?.valueSet,...getComplexInputProps()});case PropertyType2.ContactDetail:return jsx65(ContactDetailInput,{...getComplexInputProps()});case PropertyType2.ContactPoint:return jsx65(ContactPointInput,{...getComplexInputProps()});case PropertyType2.Extension:return jsx65(ExtensionInput,{...getComplexInputProps(),propertyType:props.elementDefinitionType});case PropertyType2.HumanName:return jsx65(HumanNameInput,{...getComplexInputProps()});case PropertyType2.Identifier:return jsx65(IdentifierInput,{...getComplexInputProps()});case PropertyType2.Money:return jsx65(MoneyInput,{...getComplexInputProps()});case PropertyType2.Period:return jsx65(PeriodInput,{...getComplexInputProps()});case PropertyType2.Duration:case PropertyType2.Quantity:return jsx65(QuantityInput,{...getComplexInputProps()});case PropertyType2.Range:return jsx65(RangeInput,{...getComplexInputProps()});case PropertyType2.Ratio:return jsx65(RatioInput,{...getComplexInputProps()});case PropertyType2.Reference:return jsx65(ReferenceInput,{...getComplexInputProps(),targetTypes:getTargetTypes(props.elementDefinitionType)});case PropertyType2.Timing:return jsx65(TimingInput,{...getComplexInputProps()});case PropertyType2.Dosage:case PropertyType2.UsageContext:default:return jsx65(BackboneElementInput,{...getComplexInputProps(),typeName:propertyType})}}var RESOURCE_TYPE_URL_PREFIXES=[`${HTTP_HL7_ORG}/fhir/StructureDefinition/`,"https://medplum.com/fhir/StructureDefinition/"];function getTargetTypes(elementDefinitionType){return elementDefinitionType?.targetProfile?.map(p=>{let resourceTypePrefix=RESOURCE_TYPE_URL_PREFIXES.find(prefix=>p.startsWith(prefix));return resourceTypePrefix?p.slice(resourceTypePrefix.length):p})}import{jsx as jsx66}from"react/jsx-runtime";function ElementsInput(props){let[value,setValue]=useState32(props.defaultValue??{}),elementsContext=useContext21(ElementsContext),elementsToRender=useMemo21(()=>getElementsToRender(elementsContext.elements),[elementsContext.elements]);function setValueWrapper(newValue){setValue(newValue),props.onChange&&props.onChange(newValue)}let typedValue={type:props.type,value};return jsx66(Stack6,{style:{flexGrow:1},"data-testid":props.testId,children:elementsToRender.map(([key,element])=>{let[propertyValue,propertyType]=getValueAndTypeFromElement(typedValue,key,element),required=element.min!==void 0&&element.min>0,valuePath=props.valuePath?props.valuePath+"."+key:void 0,resourcePropertyInput=jsx66(ResourcePropertyInput,{property:element,name:key,path:props.path+"."+key,valuePath,defaultValue:propertyValue,defaultPropertyType:propertyType,onChange:(newValue,propName)=>{setValueWrapper(setPropertyValue({...value},key,propName??key,element,newValue))},outcome:props.outcome},key);return props.type==="Extension"||EXTENSION_KEYS.includes(key)?resourcePropertyInput:element.type.length===1&&element.type[0].code==="boolean"?jsx66(CheckboxFormSection,{title:getPathDisplayName5(key),description:element.description,htmlFor:key,fhirPath:element.path,withAsterisk:required,readonly:element.readonly,children:resourcePropertyInput},key):jsx66(FormSection,{title:getPathDisplayName5(key),description:element.description,withAsterisk:required,htmlFor:key,outcome:props.outcome,fhirPath:element.path,errorExpression:valuePath,readonly:element.readonly,children:resourcePropertyInput},key)})})}import{jsx as jsx67,jsxs as jsxs37}from"react/jsx-runtime";function BackboneElementInput(props){let[defaultValue2]=useState33(()=>props.defaultValue??{}),parentElementsContext=useContext22(ElementsContext),profileUrl=props.profileUrl??parentElementsContext?.profileUrl,typeSchema=useMemo22(()=>tryGetDataType2(props.typeName,profileUrl),[props.typeName,profileUrl]),type=typeSchema?.type??props.typeName,contextValue=useMemo22(()=>{if(typeSchema)return buildElementsContext4({parentContext:parentElementsContext,elements:typeSchema.elements,path:props.path,profileUrl:typeSchema.url,accessPolicyResource:props.accessPolicyResource})},[typeSchema,parentElementsContext,props.path,props.accessPolicyResource]);return typeSchema?maybeWrapWithContext(ElementsContext.Provider,contextValue,jsx67(ElementsInput,{path:props.path,valuePath:props.valuePath,type,defaultValue:defaultValue2,onChange:props.onChange,outcome:props.outcome})):jsxs37("div",{children:[type,"\xA0not implemented"]})}import{Button as Button6,Group as Group23}from"@mantine/core";import{useMemo as useMemo23,useState as useState34}from"react";var CalendarInput_default={table:"CalendarInput_table"};function getMonthString(date){return date.toLocaleString("default",{month:"long"})+" "+date.getFullYear()}function getStartMonth(){let result=new Date;return result.setDate(1),result.setHours(0,0,0,0),result}import{jsx as jsx68,jsxs as jsxs38}from"react/jsx-runtime";function CalendarInput(props){let{onChangeMonth,onClick}=props,[month,setMonth]=useState34(getStartMonth);function moveMonth(delta){setMonth(currMonth=>{let newMonth=new Date(currMonth.getTime());return newMonth.setMonth(currMonth.getMonth()+delta),onChangeMonth(newMonth),newMonth})}let grid=useMemo23(()=>buildGrid(month,props.slots),[month,props.slots]);return jsxs38("div",{children:[jsxs38(Group23,{justify:"space-between",gap:"xs",grow:!0,wrap:"nowrap",children:[jsx68("p",{style:{flex:1},children:getMonthString(month)}),jsxs38(Group23,{justify:"flex-end",gap:"xs",children:[jsx68(Button6,{variant:"outline","aria-label":"Previous month",onClick:()=>moveMonth(-1),children:"<"}),jsx68(Button6,{variant:"outline","aria-label":"Next month",onClick:()=>moveMonth(1),children:">"})]})]}),jsxs38("table",{className:CalendarInput_default.table,children:[jsx68("thead",{children:jsxs38("tr",{children:[jsx68("th",{children:"SUN"}),jsx68("th",{children:"MON"}),jsx68("th",{children:"TUE"}),jsx68("th",{children:"WED"}),jsx68("th",{children:"THU"}),jsx68("th",{children:"FRI"}),jsx68("th",{children:"SAT"})]})}),jsx68("tbody",{children:grid.map((week,weekIndex)=>jsx68("tr",{children:week.map((day,dayIndex)=>jsx68("td",{children:day&&jsx68(Button6,{variant:"light",disabled:!day.available,onClick:()=>onClick(day.date),children:day.date.getDate()})},"day-"+dayIndex))},"week-"+weekIndex))})]})]})}function buildGrid(startDate,slots){let d=new Date(startDate.getFullYear(),startDate.getMonth()),grid=[],row=[];for(let i=0;i<d.getDay();i++)row.push(void 0);for(;d.getMonth()===startDate.getMonth();)row.push({date:new Date(d.getTime()),available:isDayAvailable(d,slots)}),d.getDay()===6&&(grid.push(row),row=[]),d.setDate(d.getDate()+1);if(d.getDay()!==0){for(let i=d.getDay();i<7;i++)row.push(void 0);grid.push(row)}return grid}function isDayAvailable(day,slots){for(let slot of slots){let slotStart=new Date(slot.start);if(slotStart.getFullYear()===day.getFullYear()&&slotStart.getMonth()===day.getMonth()&&slotStart.getDate()===day.getDate())return!0}return!1}import{Container as MantineContainer}from"@mantine/core";var Container_default={root:"Container_root"};import{jsx as jsx69}from"react/jsx-runtime";function Container(props){let{children,...others}=props;return jsx69(MantineContainer,{className:Container_default.root,...others,children})}import{ActionIcon as ActionIcon7,Center as Center2,Group as Group27,Loader as Loader3,ScrollArea as ScrollArea2,TextInput as TextInput13}from"@mantine/core";import{showNotification as showNotification5,updateNotification}from"@mantine/notifications";import{createReference as createReference3,normalizeErrorString as normalizeErrorString5}from"@medplum/core";import{useCallback as useCallback8,useEffect as useEffect11,useRef as useRef10,useState as useState39}from"react";import{Group as Group25,List,Stack as Stack8,Text as Text10,Title}from"@mantine/core";import{capitalize as capitalize3,formatCodeableConcept as formatCodeableConcept2,formatDateTime as formatDateTime2,formatObservationValue,isReference as isReference2}from"@medplum/core";import{useEffect as useEffect8,useState as useState36}from"react";import{Blockquote,Stack as Stack7}from"@mantine/core";var NoteDisplay_default={noteBody:"NoteDisplay_noteBody",noteCite:"NoteDisplay_noteCite",noteRoot:"NoteDisplay_noteRoot"};import{jsx as jsx70}from"react/jsx-runtime";function NoteDisplay({value}){return value?jsx70(Stack7,{justify:"flex-start",gap:"xs",children:value.map(note=>note.text&&jsx70(Blockquote,{classNames:{cite:NoteDisplay_default.noteCite,root:NoteDisplay_default.noteRoot},cite:note.authorReference?.display||note.authorString,icon:null,children:note.text},`note-${note.text}`))}):null}import{Group as Group24}from"@mantine/core";import{Text as Text9}from"@mantine/core";import{getDisplayString as getDisplayString4,isOk,normalizeErrorString as normalizeErrorString4}from"@medplum/core";import{useState as useState35}from"react";import{jsx as jsx71}from"react/jsx-runtime";function ResourceName(props){let{value,link,...rest}=props,[outcome,setOutcome]=useState35(),resource=Me(value,setOutcome),text;if(outcome&&!isOk(outcome))text=`[${normalizeErrorString4(outcome)}]`;else if(resource)text=getDisplayString4(resource);else return null;return link?jsx71(MedplumLink,{to:value,...rest,children:text}):jsx71(Text9,{component:"span",...rest,children:text})}import{jsx as jsx72,jsxs as jsxs39}from"react/jsx-runtime";function ResourceBadge(props){return jsxs39(Group24,{gap:"xs",children:[jsx72(ResourceAvatar,{size:24,radius:12,value:props.value,link:props.link}),jsx72(ResourceName,{value:props.value,link:props.link})]})}import{Badge}from"@mantine/core";import{jsx as jsx73}from"react/jsx-runtime";var statusToColor={draft:"blue",active:"blue","on-hold":"yellow",revoked:"red",completed:"green","entered-in-error":"red",unknown:"gray",retired:"gray",registered:"blue",preliminary:"blue",final:"green",amended:"yellow",corrected:"yellow",cancelled:"red",requested:"blue",received:"blue",accepted:"blue",rejected:"red",ready:"blue","in-progress":"blue",failed:"red",proposed:"blue",pending:"blue",booked:"blue",arrived:"blue",fulfilled:"green",noshow:"red","checked-in":"blue",waitlist:"gray",routine:"gray",urgent:"red",asap:"red",stat:"red","not-done":"red",connected:"green",disconnected:"red"};function StatusBadge(props){return jsx73(Badge,{color:statusToColor[props.status],children:props.status})}var DiagnosticReportDisplay_default={table:"DiagnosticReportDisplay_table",criticalRow:"DiagnosticReportDisplay_criticalRow",noteBody:"DiagnosticReportDisplay_noteBody",noteCite:"DiagnosticReportDisplay_noteCite",noteRoot:"DiagnosticReportDisplay_noteRoot"};import{Fragment as Fragment23,jsx as jsx74,jsxs as jsxs40}from"react/jsx-runtime";DiagnosticReportDisplay.defaultProps={hideObservationNotes:!1,hideSpecimenInfo:!1};function DiagnosticReportDisplay(props){let medplum=R(),diagnosticReport=Me(props.value),[specimens,setSpecimens]=useState36();if(useEffect8(()=>{diagnosticReport?.specimen&&Promise.allSettled(diagnosticReport.specimen.map(ref=>medplum.readReference(ref))).then(outcomes=>outcomes.filter(outcome=>outcome.status==="fulfilled").map(outcome=>outcome.value)).then(setSpecimens).catch(console.error)},[medplum,diagnosticReport]),!diagnosticReport)return null;let specimenNotes=specimens?.flatMap(spec=>spec.note||[])||[];if(diagnosticReport.presentedForm&&diagnosticReport.presentedForm.length>0){let pf=diagnosticReport.presentedForm[0];pf.contentType?.startsWith("text/plain")&&pf.data&&specimenNotes.push({text:window.atob(pf.data)})}return jsxs40(Stack8,{children:[jsx74(Title,{children:"Diagnostic Report"}),jsx74(DiagnosticReportHeader,{value:diagnosticReport}),specimens&&!props.hideSpecimenInfo&&SpecimenInfo(specimens),diagnosticReport.result&&jsx74(ObservationTable,{hideObservationNotes:props.hideObservationNotes,value:diagnosticReport.result}),specimenNotes.length>0&&jsx74(NoteDisplay,{value:specimenNotes})]})}function DiagnosticReportHeader({value}){return jsxs40(Group25,{mt:"md",gap:30,children:[value.subject&&jsxs40("div",{children:[jsx74(Text10,{size:"xs",tt:"uppercase",c:"dimmed",children:"Subject"}),jsx74(ResourceBadge,{value:value.subject,link:!0})]}),value.resultsInterpreter?.map(interpreter=>jsxs40("div",{children:[jsx74(Text10,{size:"xs",tt:"uppercase",c:"dimmed",children:"Interpreter"}),jsx74(ResourceBadge,{value:interpreter,link:!0})]},interpreter.reference)),value.performer?.map(performer=>jsxs40("div",{children:[jsx74(Text10,{size:"xs",tt:"uppercase",c:"dimmed",children:"Performer"}),jsx74(ResourceBadge,{value:performer,link:!0})]},performer.reference)),value.issued&&jsxs40("div",{children:[jsx74(Text10,{size:"xs",tt:"uppercase",c:"dimmed",children:"Issued"}),jsx74(Text10,{children:formatDateTime2(value.issued)})]}),value.status&&jsxs40("div",{children:[jsx74(Text10,{size:"xs",tt:"uppercase",c:"dimmed",children:"Status"}),jsx74(Text10,{children:capitalize3(value.status)})]})]})}function SpecimenInfo(specimens){return jsxs40(Stack8,{gap:"xs",children:[jsx74(Title,{order:2,size:"h6",children:"Specimens"}),jsx74(List,{type:"ordered",children:specimens?.map(specimen=>jsx74(List.Item,{ml:"sm",children:jsxs40(Group25,{gap:20,children:[jsxs40(Group25,{gap:5,children:[jsx74(Text10,{fw:500,children:"Collected:"})," ",formatDateTime2(specimen.collection?.collectedDateTime)]}),jsxs40(Group25,{gap:5,children:[jsx74(Text10,{fw:500,children:"Received:"})," ",formatDateTime2(specimen.receivedTime)]})]})},`specimen-${specimen.id}`))})]})}function ObservationTable(props){return jsxs40("table",{className:DiagnosticReportDisplay_default.table,children:[jsx74("thead",{children:jsxs40("tr",{children:[jsx74("th",{children:"Test"}),jsx74("th",{children:"Value"}),jsx74("th",{children:"Reference Range"}),jsx74("th",{children:"Interpretation"}),jsx74("th",{children:"Category"}),jsx74("th",{children:"Performer"}),jsx74("th",{children:"Status"})]})}),jsx74("tbody",{children:jsx74(ObservationRowGroup,{value:props.value,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes})})]})}function ObservationRowGroup(props){return jsx74(Fragment23,{children:props.value?.map(observation=>jsx74(ObservationRow,{value:observation,ancestorIds:props.ancestorIds,hideObservationNotes:props.hideObservationNotes},`obs-${isReference2(observation)?observation.reference:observation.id}`))})}function ObservationRow(props){let observation=Me(props.value);if(!observation||props.ancestorIds?.includes(observation.id))return null;let displayNotes=!props.hideObservationNotes&&observation.note,critical=isCritical(observation);return jsxs40(Fragment23,{children:[jsxs40("tr",{className:clsx_default({[DiagnosticReportDisplay_default.criticalRow]:critical}),children:[jsx74("td",{rowSpan:displayNotes?2:1,children:jsx74(MedplumLink,{to:observation,children:jsx74(CodeableConceptDisplay,{value:observation.code})})}),jsx74("td",{children:jsx74(ObservationValueDisplay,{value:observation})}),jsx74("td",{children:jsx74(ReferenceRangeDisplay,{value:observation.referenceRange})}),jsx74("td",{children:observation.interpretation&&observation.interpretation.length>0&&jsx74(CodeableConceptDisplay,{value:observation.interpretation[0]})}),jsx74("td",{children:observation.category&&observation.category.length>0&&jsx74(Fragment23,{children:observation.category.map(concept=>jsx74("div",{children:jsx74(CodeableConceptDisplay,{value:concept})},`category-${formatCodeableConcept2(concept)}`))})}),jsx74("td",{children:observation.performer?.map(performer=>jsx74(ReferenceDisplay,{value:performer},performer.reference))}),jsx74("td",{children:observation.status&&jsx74(StatusBadge,{status:observation.status})})]}),observation.hasMember&&jsx74(ObservationRowGroup,{value:observation.hasMember,ancestorIds:props.ancestorIds?[...props.ancestorIds,observation.id]:[observation.id],hideObservationNotes:props.hideObservationNotes}),displayNotes&&jsx74("tr",{children:jsx74("td",{colSpan:6,children:jsx74(NoteDisplay,{value:observation.note})})})]})}function ObservationValueDisplay(props){let obs=props.value;return jsx74(Fragment23,{children:formatObservationValue(obs)})}function ReferenceRangeDisplay(props){let range=props.value&&props.value.length>0&&props.value[0];return range?range.text?jsx74(Fragment23,{children:range.text}):jsx74(RangeDisplay,{value:range}):null}function isCritical(observation){let code=observation.interpretation?.[0]?.coding?.[0]?.code;return code==="AA"||code==="LL"||code==="HH"||code==="A"}import{Paper}from"@mantine/core";var Panel_default={paper:"Panel_paper",fill:"Panel_fill"};import{jsx as jsx75}from"react/jsx-runtime";function Panel(props){let{width,fill,className,children,...rest}=props,style=width?{maxWidth:width}:void 0;return jsx75(Paper,{className:clsx_default(Panel_default.paper,fill&&Panel_default.fill,className),style,shadow:"sm",radius:"sm",withBorder:!0,...rest,children})}import{Table}from"@mantine/core";import{arrayify,capitalize as capitalize4,evalFhirPathTyped,getSearchParameterDetails,toTypedValue}from"@medplum/core";var import_rfc6902=__toESM(require_rfc6902(),1);import{useEffect as useEffect9,useMemo as useMemo24,useState as useState37}from"react";var ResourceDiffTable_default={root:"ResourceDiffTable_root",removed:"ResourceDiffTable_removed",added:"ResourceDiffTable_added"};import{jsx as jsx76,jsxs as jsxs41}from"react/jsx-runtime";function ResourceDiffTable(props){let medplum=R(),{original,revised}=props,[schemaLoaded,setSchemaLoaded]=useState37(!1);useEffect9(()=>{medplum.requestSchema(props.original.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.original.resourceType]);let diffTable=useMemo24(()=>{if(!schemaLoaded)return null;let typedOriginal=[toTypedValue(original)],typedRevised=[toTypedValue(revised)],result=[],patch=mergePatchOperations((0,import_rfc6902.createPatch)(original,revised));for(let op of patch){let path=op.path,fhirPath=jsonPathToFhirPath(path),property=tryGetElementDefinition(original.resourceType,fhirPath),originalValue=op.op==="add"?void 0:evalFhirPathTyped(fhirPath,typedOriginal),revisedValue=op.op==="remove"?void 0:evalFhirPathTyped(fhirPath,typedRevised);result.push({key:`op-${op.op}-${op.path}`,name:`${capitalize4(op.op)} ${fhirPath}`,path:property?.path??original.resourceType+"."+fhirPath,property,originalValue:touchUpValue(property,originalValue),revisedValue:touchUpValue(property,revisedValue)})}return result},[schemaLoaded,original,revised]);return diffTable?jsxs41(Table,{className:ResourceDiffTable_default.root,children:[jsx76(Table.Thead,{children:jsxs41(Table.Tr,{children:[jsx76(Table.Th,{}),jsx76(Table.Th,{children:"Before"}),jsx76(Table.Th,{children:"After"})]})}),jsx76(Table.Tbody,{children:diffTable.map(row=>jsxs41(Table.Tr,{children:[jsx76(Table.Td,{children:row.name}),jsx76(Table.Td,{className:ResourceDiffTable_default.removed,children:row.originalValue&&jsx76(ResourcePropertyDisplay,{path:row.path,property:row.property,propertyType:row.originalValue.type,value:row.originalValue.value,ignoreMissingValues:!0})}),jsx76(Table.Td,{className:ResourceDiffTable_default.added,children:row.revisedValue&&jsx76(ResourcePropertyDisplay,{path:row.path,property:row.property,propertyType:row.revisedValue.type,value:row.revisedValue.value,ignoreMissingValues:!0})})]},row.key))})]}):null}function mergePatchOperations(patch){let result=[];for(let patchOperation of patch){let{op,path}=patchOperation;if(path.startsWith("/meta/author")||path.startsWith("/meta/compartment")||path.startsWith("/meta/lastUpdated")||path.startsWith("/meta/versionId"))continue;let count=patch.filter(el=>el.op===op&&el.path===path).length,resultOperation={op,path};count>1&&(op==="add"||op==="remove")&&/\/[0-9-]+$/.test(path)&&(resultOperation.op="replace",resultOperation.path=path.replace(/\/[^/]+$/,"")),result.some(el=>el.op===resultOperation.op&&el.path===resultOperation.path)||result.push(resultOperation)}return result}function jsonPathToFhirPath(path){let parts=path.split("/").filter(Boolean),result="";for(let i=0;i<parts.length;i++){let part=parts[i];part==="-"?result+=".last()":/^\d+$/.test(part)?result+=`[${part}]`:(i>0&&(result+="."),result+=part)}return result.endsWith(".url")&&(result=result.replace(/\.url$/,"")),result}function tryGetElementDefinition(resourceType,fhirPath){return getSearchParameterDetails(resourceType,{resourceType:"SearchParameter",base:[resourceType],code:resourceType+"."+fhirPath,expression:resourceType+"."+fhirPath})?.elementDefinitions?.[0]}function touchUpValue(property,input){return input&&{type:Array.isArray(input)?input[0].type:input.type,value:fixArray(input,!!property?.isArray)}}function fixArray(input,isArray){let inputValue=arrayify(input).flatMap(v2=>v2.value);return isArray?inputValue:inputValue[0]}import{AccessPolicyInteraction,satisfiedAccessPolicy,tryGetProfile as tryGetProfile4}from"@medplum/core";import{useEffect as useEffect10,useMemo as useMemo25,useState as useState38}from"react";import{jsx as jsx77}from"react/jsx-runtime";function ResourceTable(props){let{profileUrl}=props,medplum=R(),accessPolicy=medplum.getAccessPolicy(),value=Me(props.value),[schemaLoaded,setSchemaLoaded]=useState38(!1);useEffect10(()=>{if(value)if(profileUrl)medplum.requestProfileSchema(profileUrl,{expandProfile:!0}).then(()=>{tryGetProfile4(profileUrl)?setSchemaLoaded(!0):console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)});else{let schemaName=value.resourceType;medplum.requestSchema(schemaName).then(()=>{setSchemaLoaded(!0)}).catch(console.error)}},[medplum,profileUrl,value]);let accessPolicyResource=useMemo25(()=>value&&satisfiedAccessPolicy(value,AccessPolicyInteraction.READ,accessPolicy),[accessPolicy,value]);return!schemaLoaded||!value?null:jsx77(BackboneElementDisplay,{path:value.resourceType,value:{type:value.resourceType,value:props.forceUseInput?props.value:value},profileUrl,ignoreMissingValues:props.ignoreMissingValues,accessPolicyResource})}import{ActionIcon as ActionIcon6,Group as Group26,Menu as Menu3,Text as Text11}from"@mantine/core";import{formatDateTime as formatDateTime3,getReferenceString as getReferenceString4}from"@medplum/core";var Timeline_default={item:"Timeline_item",itemPadding:"Timeline_itemPadding"};import{jsx as jsx78,jsxs as jsxs42}from"react/jsx-runtime";function Timeline(props){return jsx78(Container,{children:props.children})}function TimelineItem(props){let{resource,profile,padding,popupMenuItems,...others}=props,author=profile??resource.meta?.author,dateTime=props.dateTime??resource.meta?.lastUpdated;return jsxs42(Panel,{"data-testid":"timeline-item",fill:!0,...others,children:[jsxs42(Group26,{justify:"space-between",gap:8,mx:"xs",my:"sm",children:[jsx78(ResourceAvatar,{value:author,link:!0,size:"md"}),jsxs42("div",{style:{flex:1},children:[jsx78(Text11,{size:"sm",children:jsx78(ResourceName,{c:"dark",fw:500,value:author,link:!0})}),jsxs42(Text11,{size:"xs",children:[jsx78(MedplumLink,{c:"dimmed",to:props.resource,children:formatDateTime3(dateTime)}),jsx78(Text11,{component:"span",c:"dimmed",mx:8,children:"\xB7"}),jsx78(MedplumLink,{c:"dimmed",to:props.resource,children:props.resource.resourceType})]})]}),popupMenuItems&&jsxs42(Menu3,{position:"bottom-end",shadow:"md",width:200,children:[jsx78(Menu3.Target,{children:jsx78(ActionIcon6,{color:"gray",variant:"subtle",radius:"xl","aria-label":`Actions for ${getReferenceString4(props.resource)}`,children:jsx78(IconDots,{})})}),popupMenuItems]})]}),jsx78(ErrorBoundary,{children:jsx78("div",{className:clsx_default(Timeline_default.item,{[Timeline_default.itemPadding]:padding}),children:props.children})})]})}function sortByDateAndPriority(resources,timelineResource){resources.sort((a2,b)=>{let priority1=getPriorityScore(a2,timelineResource),priority2=getPriorityScore(b,timelineResource);return priority1>priority2?1:priority1<priority2?-1:getTime(a2,timelineResource)-getTime(b,timelineResource)})}function getPriorityScore(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){let priority=resource.priority;if(typeof priority=="string")return{stat:4,asap:3,urgent:2}[priority]??0}return 0}function getTime(resource,timelineResource){if(!isSameResourceType(resource,timelineResource)){if(resource.resourceType==="Communication"&&resource.sent)return new Date(resource.sent).getTime();if((resource.resourceType==="DiagnosticReport"||resource.resourceType==="Media"||resource.resourceType==="Observation")&&resource.issued)return new Date(resource.issued).getTime();if(resource.resourceType==="DocumentReference"&&resource.date)return new Date(resource.date).getTime()}let dateTime=resource.meta?.lastUpdated;return dateTime?new Date(dateTime).getTime():0}function isSameResourceType(a2,b){return!!b&&a2.resourceType===b.resourceType&&a2.id===b.id}var ResourceTimeline_default={pinnedComment:"ResourceTimeline_pinnedComment"};import{jsx as jsx79,jsxs as jsxs43}from"react/jsx-runtime";function ResourceTimeline(props){let medplum=R(),sender=medplum.getProfile(),inputRef=useRef10(null),resource=Me(props.value),[history,setHistory]=useState39(),[items,setItems]=useState39([]),loadTimelineResources=props.loadTimelineResources,itemsRef=useRef10(items);itemsRef.current=items;let sortAndSetItems=useCallback8(newItems=>{sortByDateAndPriority(newItems,resource),newItems.reverse(),setItems(newItems)},[resource]),handleBatchResponse=useCallback8(batchResponse=>{let newItems=[];for(let settledResult of batchResponse){if(settledResult.status!=="fulfilled")continue;let bundle=settledResult.value;if(bundle.type==="history"&&setHistory(bundle),bundle.entry)for(let entry of bundle.entry)newItems.push(entry.resource)}sortAndSetItems(newItems)},[sortAndSetItems]),addResource=useCallback8(resource2=>sortAndSetItems([...itemsRef.current,resource2]),[sortAndSetItems]),loadTimeline=useCallback8(()=>{let resourceType,id;"resourceType"in props.value?(resourceType=props.value.resourceType,id=props.value.id):[resourceType,id]=props.value.reference?.split("/"),loadTimelineResources(medplum,resourceType,id).then(handleBatchResponse).catch(console.error)},[medplum,props.value,loadTimelineResources,handleBatchResponse]);useEffect11(()=>loadTimeline(),[loadTimeline]);function createComment(contentString){!resource||!props.createCommunication||medplum.createResource(props.createCommunication(resource,sender,contentString)).then(result=>addResource(result)).catch(console.error)}function createMedia(attachment){!resource||!props.createMedia||medplum.createResource(props.createMedia(resource,sender,attachment)).then(result=>addResource(result)).then(()=>updateNotification({id:"upload-notification",color:"teal",title:"Upload complete",message:"",icon:jsx79(IconCheck,{size:16}),autoClose:2e3})).catch(reason=>updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString5(reason),icon:jsx79(IconFileAlert,{size:16}),autoClose:2e3}))}function onUploadStart(){showNotification5({id:"upload-notification",loading:!0,title:"Initializing upload...",message:"Please wait...",autoClose:!1,withCloseButton:!1})}function onUploadProgress(e){updateNotification({id:"upload-notification",loading:!0,title:"Uploading...",message:getProgressMessage(e),autoClose:!1,withCloseButton:!1})}function onUploadError(outcome){updateNotification({id:"upload-notification",color:"red",title:"Upload error",message:normalizeErrorString5(outcome),icon:jsx79(IconFileAlert,{size:16}),autoClose:2e3})}return resource?jsxs43(Timeline,{children:[props.createCommunication&&jsx79(Panel,{children:jsx79(Form,{testid:"timeline-form",onSubmit:formData=>{createComment(formData.text);let input=inputRef.current;input&&(input.value="",input.focus())},children:jsxs43(Group27,{gap:"xs",wrap:"nowrap",style:{width:"100%"},children:[jsx79(ResourceAvatar,{value:sender}),jsx79(TextInput13,{name:"text",ref:inputRef,placeholder:"Add comment",style:{width:"100%",maxWidth:300}}),jsx79(ActionIcon7,{type:"submit",radius:"xl",color:"blue",variant:"filled",children:jsx79(IconMessage,{size:16})}),jsx79(AttachmentButton,{securityContext:createReference3(resource),onUpload:createMedia,onUploadStart,onUploadProgress,onUploadError,children:props2=>jsx79(ActionIcon7,{...props2,radius:"xl",color:"blue",variant:"filled",children:jsx79(IconCloudUpload,{size:16})})})]})})}),items.map(item=>{if(!item)return null;let key=`${item.resourceType}/${item.id}/${item.meta?.versionId}`,menu=props.getMenu?props.getMenu({primaryResource:resource,currentResource:item,reloadTimeline:loadTimeline}):void 0;if(item.resourceType===resource.resourceType&&item.id===resource.id)return jsx79(HistoryTimelineItem,{history,resource:item,popupMenuItems:menu},key);switch(item.resourceType){case"AuditEvent":return jsx79(AuditEventTimelineItem,{resource:item,popupMenuItems:menu},key);case"Communication":return jsx79(CommunicationTimelineItem,{resource:item,popupMenuItems:menu},key);case"DiagnosticReport":return jsx79(DiagnosticReportTimelineItem,{resource:item,popupMenuItems:menu},key);case"Media":return jsx79(MediaTimelineItem,{resource:item,popupMenuItems:menu},key);default:return jsx79(TimelineItem,{resource:item,padding:!0,children:jsx79(ResourceTable,{value:item,ignoreMissingValues:!0})},key)}})]}):jsx79(Center2,{style:{width:"100%",height:"100%"},children:jsx79(Loader3,{})})}function HistoryTimelineItem(props){let{history,resource,...rest}=props,previous=getPrevious(history,resource);return previous?jsx79(TimelineItem,{resource,padding:!0,...rest,children:jsx79(ResourceDiffTable,{original:previous,revised:props.resource})}):jsxs43(TimelineItem,{resource,padding:!0,...rest,children:[jsx79("h3",{children:"Created"}),jsx79(ResourceTable,{value:resource,ignoreMissingValues:!0,forceUseInput:!0})]})}function getPrevious(history,version){let entries=history.entry,index=entries.findIndex(entry=>entry.resource?.meta?.versionId===version.meta?.versionId);if(!(index>=entries.length-1))return entries[index+1].resource}function CommunicationTimelineItem(props){let className=!props.resource.priority||props.resource.priority==="routine"?void 0:ResourceTimeline_default.pinnedComment;return jsx79(TimelineItem,{resource:props.resource,profile:props.resource.sender,dateTime:props.resource.sent,padding:!0,className,popupMenuItems:props.popupMenuItems,children:jsx79("p",{children:props.resource.payload?.[0]?.contentString})})}function MediaTimelineItem(props){let contentType=props.resource.content?.contentType,padding=contentType&&!contentType.startsWith("image/")&&!contentType.startsWith("video/")&&contentType!=="application/pdf";return jsx79(TimelineItem,{resource:props.resource,padding:!!padding,popupMenuItems:props.popupMenuItems,children:jsx79(AttachmentDisplay,{value:props.resource.content})})}function AuditEventTimelineItem(props){return jsx79(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx79(ScrollArea2,{children:jsx79("pre",{children:props.resource.outcomeDesc})})})}function DiagnosticReportTimelineItem(props){return jsx79(TimelineItem,{resource:props.resource,padding:!0,popupMenuItems:props.popupMenuItems,children:jsx79(DiagnosticReportDisplay,{value:props.resource})})}function getProgressMessage(e){if(e.lengthComputable){let percent=100*e.loaded/e.total;return`Uploaded: ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)} ${percent.toFixed(2)}%`}return`Uploaded: ${formatFileSize(e.loaded)}`}function formatFileSize(bytes){if(bytes===0)return"0.00 B";let e=Math.floor(Math.log(bytes)/Math.log(1024));return(bytes/Math.pow(1024,e)).toFixed(2)+" "+" KMGTP".charAt(e)+"B"}import{jsx as jsx80}from"react/jsx-runtime";function DefaultResourceTimeline(props){let{resource,...rest}=props;return jsx80(ResourceTimeline,{value:resource,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`;return Promise.allSettled([medplum.readHistory(resourceType,id),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count:100})])},...rest})}import{jsx as jsx81}from"react/jsx-runtime";function Document(props){let{children,...others}=props;return jsx81(Container,{children:jsx81(Panel,{...others,children})})}import{createReference as createReference4}from"@medplum/core";import{jsx as jsx82}from"react/jsx-runtime";function EncounterTimeline(props){let{encounter,...rest}=props;return jsx82(ResourceTimeline,{value:encounter,loadTimelineResources:async(medplum,_resourceType,id)=>Promise.allSettled([medplum.readHistory("Encounter",id),medplum.search("Communication","encounter=Encounter/"+id),medplum.search("Media","encounter=Encounter/"+id)]),createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",encounter:createReference4(resource),subject:resource.subject,sender:createReference4(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",encounter:createReference4(resource),subject:resource.subject,operator:createReference4(operator),issued:new Date().toISOString(),content}),...rest})}import{Button as Button12,Loader as Loader5,Table as Table3}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome3}from"@medplum/core";import{memo,useEffect as useEffect15,useRef as useRef14,useState as useState44}from"react";import{evalFhirPath}from"@medplum/core";import{jsx as jsx83}from"react/jsx-runtime";function FhirPathDisplay(props){let value;try{value=evalFhirPath(props.path,props.resource)}catch(err){return console.warn("FhirPathDisplay:",err),null}if(value.length>1)throw new Error(`Component "path" for "FhirPathDisplay" must resolve to a single element. Received ${value.length} elements [${JSON.stringify(value,null,2)}]`);return jsx83(ResourcePropertyDisplay,{value:value[0]||"",propertyType:props.propertyType})}import{ActionIcon as ActionIcon8,Button as Button11,Center as Center3,Group as Group30,Loader as Loader4,Menu as Menu5,Pagination,Table as Table2,Text as Text13,UnstyledButton as UnstyledButton2}from"@mantine/core";import{DEFAULT_SEARCH_COUNT as DEFAULT_SEARCH_COUNT2,deepEquals,formatSearchQuery,isDataTypeLoaded,normalizeOperationOutcome as normalizeOperationOutcome2}from"@medplum/core";import{useCallback as useCallback9,useEffect as useEffect14,useRef as useRef13,useState as useState43}from"react";import{Alert as Alert2}from"@mantine/core";import{operationOutcomeIssueToString}from"@medplum/core";import{jsx as jsx84}from"react/jsx-runtime";function OperationOutcomeAlert(props){let issues=props.outcome?.issue||props.issues;return!issues||issues.length===0?null:jsx84(Alert2,{icon:jsx84(IconAlertCircle,{size:16}),color:"red",children:issues.map(issue=>jsx84("div",{"data-testid":"text-field-error",children:operationOutcomeIssueToString(issue)},issue.details?.text))})}import{Box as Box2,Button as Button7,Modal as Modal3,Text as Text12}from"@mantine/core";import{jsx as jsx85,jsxs as jsxs44}from"react/jsx-runtime";function SearchExportDialog(props){return jsxs44(Modal3,{title:"Export",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:props.onCancel,children:[jsxs44(Box2,{display:"flex",style:{justifyContent:"space-between"},children:[props.exportCsv&&jsx85(ExportButton,{text:"CSV",exportLogic:props.exportCsv,onCancel:props.onCancel}),props.exportTransactionBundle&&jsx85(ExportButton,{text:"Transaction Bundle",exportLogic:props.exportTransactionBundle,onCancel:props.onCancel})]}),jsx85(Text12,{style:{marginTop:"10px",marginLeft:"2px"},children:"Limited to 1000 records"})]})}function ExportButton(props){return jsx85(Button7,{onClick:()=>{props.exportLogic(),props.onCancel()},children:`Export as ${props.text}`})}import{Button as Button8,Group as Group28,Modal as Modal4,MultiSelect,Stack as Stack9}from"@mantine/core";import{getDataType as getDataType2,getSearchParameters,sortStringArray,stringify as stringify2}from"@medplum/core";import{useEffect as useEffect12,useMemo as useMemo26,useRef as useRef11,useState as useState40}from"react";import{capitalize as capitalize5,DEFAULT_SEARCH_COUNT,evalFhirPathTyped as evalFhirPathTyped2,formatDateTime as formatDateTime4,Operator}from"@medplum/core";import{Fragment as Fragment24,jsx as jsx86}from"react/jsx-runtime";var searchParamToOperators={string:[Operator.EQUALS,Operator.NOT,Operator.CONTAINS,Operator.EXACT],fulltext:[Operator.EQUALS,Operator.NOT,Operator.CONTAINS,Operator.EXACT],token:[Operator.EQUALS,Operator.NOT],reference:[Operator.EQUALS,Operator.NOT],numeric:[Operator.EQUALS,Operator.NOT_EQUALS,Operator.GREATER_THAN,Operator.LESS_THAN,Operator.GREATER_THAN_OR_EQUALS,Operator.LESS_THAN_OR_EQUALS],quantity:[Operator.EQUALS,Operator.NOT_EQUALS,Operator.GREATER_THAN,Operator.LESS_THAN,Operator.GREATER_THAN_OR_EQUALS,Operator.LESS_THAN_OR_EQUALS],date:[Operator.EQUALS,Operator.NOT_EQUALS,Operator.GREATER_THAN,Operator.LESS_THAN,Operator.GREATER_THAN_OR_EQUALS,Operator.LESS_THAN_OR_EQUALS,Operator.STARTS_AFTER,Operator.ENDS_BEFORE,Operator.APPROXIMATELY],datetime:[Operator.EQUALS,Operator.NOT_EQUALS,Operator.GREATER_THAN,Operator.LESS_THAN,Operator.GREATER_THAN_OR_EQUALS,Operator.LESS_THAN_OR_EQUALS,Operator.STARTS_AFTER,Operator.ENDS_BEFORE,Operator.APPROXIMATELY]},operatorNames={eq:"equals",ne:"not equals",gt:"greater than",lt:"less than",ge:"greater than or equals",le:"less than or equals",sa:"starts after",eb:"ends before",ap:"approximately",contains:"contains",exact:"exact",text:"text",not:"not",above:"above",below:"below",in:"in","not-in":"not in","of-type":"of type",missing:"missing",present:"present",identifier:"identifier",iterate:"iterate"};function setFilters(definition,filters){return{...definition,filters,offset:0,name:void 0}}function clearFilters(definition){return setFilters(definition,[])}function clearFiltersOnField(definition,code){return setFilters(definition,(definition.filters??[]).filter(f=>f.code!==code))}function addFilter(definition,field,op,value,opt_clear){opt_clear&&(definition=clearFiltersOnField(definition,field));let nextFilters=[];return definition.filters&&nextFilters.push(...definition.filters),nextFilters.push({code:field,operator:op,value:value??""}),setFilters(definition,nextFilters)}function addField(definition,field){if(definition.fields?.includes(field))return definition;let newFields=[];return definition.fields&&newFields.push(...definition.fields),newFields.push(field),{...definition,fields:newFields,name:void 0}}function deleteFilter(definition,index){if(!definition.filters)return definition;let newFilters=[...definition.filters];return newFilters.splice(index,1),{...definition,filters:newFilters,name:void 0}}function addYesterdayFilter(definition,field){return addDayFilter(definition,field,-1)}function addTodayFilter(definition,field){return addDayFilter(definition,field,0)}function addTomorrowFilter(definition,field){return addDayFilter(definition,field,1)}function addDayFilter(definition,field,delta){let startTime=new Date;startTime.setDate(startTime.getDate()+delta),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setDate(endTime.getDate()+1),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addLastMonthFilter(definition,field){return addMonthFilter(definition,field,-1)}function addThisMonthFilter(definition,field){return addMonthFilter(definition,field,0)}function addNextMonthFilter(definition,field){return addMonthFilter(definition,field,1)}function addMonthFilter(definition,field,delta){let startTime=new Date;startTime.setMonth(startTime.getMonth()+delta),startTime.setDate(1),startTime.setHours(0,0,0,0);let endTime=new Date(startTime.getTime());return endTime.setMonth(endTime.getMonth()+1),endTime.setDate(1),endTime.setHours(0,0,0,0),endTime.setTime(endTime.getTime()-1),addDateFilterBetween(definition,field,startTime,endTime)}function addYearToDateFilter(definition,field){let startTime=new Date;return startTime.setMonth(0),startTime.setDate(1),startTime.setHours(0,0,0,0),addDateFilterBetween(definition,field,startTime,new Date)}function addDateFilterBetween(definition,field,d1,d2){return definition=clearFiltersOnField(definition,field),definition=addDateFilterImpl(definition,field,Operator.GREATER_THAN_OR_EQUALS,d1),definition=addDateFilterImpl(definition,field,Operator.LESS_THAN_OR_EQUALS,d2),definition}function addDateFilterImpl(definition,field,op,value){return addFilter(definition,field,op,value.toISOString())}function addMissingFilter(definition,field,value=!0){return addFilter(definition,field,Operator.MISSING,value.toString())}function setOffset(definition,offset){return definition.offset===offset?definition:{...definition,offset,name:void 0}}function setPage(definition,page){let count=definition.count??DEFAULT_SEARCH_COUNT,newOffset=(page-1)*count;return setOffset(definition,newOffset)}function setSort(definition,sort,desc){return sort===getSortField(definition)&&desc!==void 0&&desc===isSortDescending(definition)?definition:{...definition,sortRules:[{code:sort,descending:!!desc}],name:void 0}}function toggleSort(definition,key){let desc=!1;return getSortField(definition)===key&&(desc=!isSortDescending(definition)),setSort(definition,key,desc)}function getSortField(definition){let sortRules=definition.sortRules;if(!sortRules||sortRules.length===0)return;let field=sortRules[0].code;return field.startsWith("-")?field.substr(1):field}function isSortDescending(definition){let sortRules=definition.sortRules;return!sortRules||sortRules.length===0?!1:!!sortRules[0].descending}function getSearchOperators(searchParam){return searchParamToOperators[searchParam.type]}function getOpString(op){return operatorNames[op]??""}function buildFieldNameString(key){let tmp=key;return tmp.includes(".")&&(tmp=tmp.split(".").pop()),tmp==="versionId"?"Version ID":(tmp=tmp.replace("[x]",""),tmp=tmp.replace(/([A-Z])/g," $1"),tmp=tmp.replace(/[-_]/g," "),tmp=tmp.replace(/\s+/g," "),tmp=tmp.trim(),tmp.toLowerCase()==="id"?"ID":tmp.split(/\s/).map(capitalize5).join(" "))}function renderValue(resource,field){let key=field.name;return key==="id"?resource.id:key==="meta.versionId"?resource.meta?.versionId:key==="_lastUpdated"?formatDateTime4(resource.meta?.lastUpdated):field.elementDefinition&&`${resource.resourceType}.${field.name}`===field.elementDefinition.path?renderPropertyValue(resource,field.elementDefinition):field.searchParams&&field.searchParams.length===1&&field.name===field.searchParams[0].code?renderSearchParameterValue(resource,field.searchParams[0]):null}function renderPropertyValue(resource,elementDefinition){let path=elementDefinition.path?.split(".")?.pop()?.replaceAll("[x]","")??"",[value,propertyType]=getValueAndType({type:resource.resourceType,value:resource},path);return value?jsx86(ResourcePropertyDisplay,{path:elementDefinition.path,property:elementDefinition,propertyType,value,maxWidth:200,ignoreMissingValues:!0,link:!1}):null}function renderSearchParameterValue(resource,searchParam){let value=evalFhirPathTyped2(searchParam.expression,[{type:resource.resourceType,value:resource}]);return!value||value.length===0?null:jsx86(Fragment24,{children:value.map((v2,index)=>jsx86(ResourcePropertyDisplay,{propertyType:v2.type,value:v2.value,maxWidth:200,ignoreMissingValues:!0,link:!1},`${index}-${value.length}`))})}import{jsx as jsx87,jsxs as jsxs45}from"react/jsx-runtime";function SearchFieldEditor(props){let wasDropdownOpen=useRef11(!1),[state,setState]=useState40({search:JSON.parse(stringify2(props.search))}),[isDropdownOpen,setIsDropdownOpen]=useState40(!1);useEffect12(()=>{setState({search:props.search})},[props.search]);let allFields=useMemo26(()=>{if(!props.visible)return[];let resourceType=props.search.resourceType,typeSchema=getDataType2(resourceType),searchParams=getSearchParameters(resourceType);return sortStringArray(getFieldsList(typeSchema,searchParams)).map(field=>({value:field,label:buildFieldNameString(field)}))},[props.visible,props.search.resourceType]);if(!props.visible)return null;function handleChange(newFields){setState({search:{...state.search,fields:newFields}})}return jsx87(Modal4,{title:"Fields",closeButtonProps:{"aria-label":"Close"},opened:props.visible,onClose:()=>{props.onCancel()},size:"auto",withOverlay:!0,closeOnClickOutside:!1,overlayProps:{onMouseDownCapture:()=>{wasDropdownOpen.current=isDropdownOpen},onClick:()=>{wasDropdownOpen.current||props.onCancel(),wasDropdownOpen.current=!1},children:jsx87("div",{"data-testid":"overlay-child"})},children:jsxs45(Stack9,{children:[jsx87(MultiSelect,{style:{width:550},placeholder:"Select fields to display",data:allFields,value:state.search.fields??[],onChange:handleChange,onDropdownOpen:()=>setIsDropdownOpen(!0),onDropdownClose:()=>setIsDropdownOpen(!1),maxDropdownHeight:"250px",clearButtonProps:{"aria-label":"Clear selection"},clearable:!0,searchable:!0}),jsx87(Group28,{justify:"flex-end",children:jsx87(Button8,{onClick:()=>props.onOk(state.search),children:"OK"})})]})})}function getFieldsList(typeSchema,searchParams){let result=[],keys=new Set,names=new Set;for(let key of Object.keys(typeSchema.elements))result.push(key),keys.add(key.toLowerCase()),names.add(buildFieldNameString(key));if(searchParams)for(let code of Object.keys(searchParams)){let name=buildFieldNameString(code);!keys.has(code)&&!names.has(name)&&(result.push(code),keys.add(code),names.add(name))}return result}import{Button as Button9,Group as Group29,Modal as Modal5,NativeSelect as NativeSelect10}from"@mantine/core";import{getSearchParameters as getSearchParameters2,stringify as stringify3}from"@medplum/core";import{useEffect as useEffect13,useRef as useRef12,useState as useState41}from"react";import{formatDateTime as formatDateTime5,getSearchParameterDetails as getSearchParameterDetails2,globalSchema,Operator as Operator2,SearchParameterType}from"@medplum/core";import{Fragment as Fragment25,jsx as jsx88}from"react/jsx-runtime";function SearchFilterValueDisplay(props){let{resourceType,filter}=props,searchParam=globalSchema.types[resourceType].searchParams?.[filter.code];if(searchParam){if(searchParam.type==="reference"&&(filter.operator===Operator2.EQUALS||filter.operator===Operator2.NOT_EQUALS))return jsx88(ResourceName,{value:{reference:filter.value}});let searchParamDetails=getSearchParameterDetails2(resourceType,searchParam);if(filter.code==="_lastUpdated"||searchParamDetails.type===SearchParameterType.DATETIME)return jsx88(Fragment25,{children:formatDateTime5(filter.value)})}return jsx88(Fragment25,{children:filter.value})}import{Checkbox as Checkbox2,TextInput as TextInput14}from"@mantine/core";import{getSearchParameterDetails as getSearchParameterDetails3,SearchParameterType as SearchParameterType2}from"@medplum/core";import{jsx as jsx89}from"react/jsx-runtime";function SearchFilterValueInput(props){let details=getSearchParameterDetails3(props.resourceType,props.searchParam),name="filter-value";switch(details.type){case SearchParameterType2.REFERENCE:return jsx89(ReferenceInput,{name,defaultValue:props.defaultValue?{reference:props.defaultValue}:void 0,targetTypes:props.searchParam.target,autoFocus:props.autoFocus,onChange:newReference=>{newReference?props.onChange(newReference.reference):props.onChange("")}});case SearchParameterType2.BOOLEAN:return jsx89(Checkbox2,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultChecked:props.defaultValue==="true",autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.checked.toString())});case SearchParameterType2.DATE:return jsx89(TextInput14,{type:"date",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType2.DATETIME:return jsx89(DateTimeInput,{name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:props.onChange});case SearchParameterType2.NUMBER:return jsx89(TextInput14,{type:"number",name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value)});case SearchParameterType2.QUANTITY:return jsx89(QuantityInput,{name,path:"",defaultValue:tryParseQuantity(props.defaultValue),autoFocus:props.autoFocus,onChange:newQuantity=>{newQuantity?props.onChange(`${newQuantity.value}`):props.onChange("")}});default:return jsx89(TextInput14,{name,"data-autofocus":props.autoFocus,"data-testid":name,defaultValue:props.defaultValue,autoFocus:props.autoFocus,onChange:e=>props.onChange(e.currentTarget.value),placeholder:"Search value"})}}function tryParseQuantity(value){if(value){let[valueString,systemString,unitString]=value.split("|");if(valueString)return{value:parseFloat(valueString),system:systemString,unit:unitString}}}import{jsx as jsx90,jsxs as jsxs46}from"react/jsx-runtime";function SearchFilterEditor(props){let[search,setSearch]=useState41(JSON.parse(stringify3(props.search))),[editingIndex,setEditingIndex]=useState41(-1),searchRef=useRef12(search);searchRef.current=search,useEffect13(()=>{setSearch(JSON.parse(stringify3(props.search)))},[props.search]);function onAddFilter(filter){setSearch(addFilter(searchRef.current,filter.code,filter.operator,filter.value))}if(!props.visible)return null;let resourceType=props.search.resourceType,searchParams=getSearchParameters2(resourceType)??{},filters=search.filters||[];return jsxs46(Modal5,{title:"Filters",closeButtonProps:{"aria-label":"Close"},size:900,opened:props.visible,onClose:props.onCancel,children:[jsx90("div",{children:jsxs46("table",{children:[jsxs46("colgroup",{children:[jsx90("col",{style:{width:200}}),jsx90("col",{style:{width:200}}),jsx90("col",{style:{width:380}}),jsx90("col",{style:{width:120}})]}),jsx90("thead",{children:jsxs46("tr",{children:[jsx90("th",{children:"Field"}),jsx90("th",{children:"Operation"}),jsx90("th",{children:"Value"}),jsx90("th",{children:"Actions"})]})}),jsxs46("tbody",{children:[filters.map((filter,index)=>index===editingIndex?jsx90(FilterRowInput,{resourceType,searchParams,defaultValue:filter,okText:"Save",onOk:newFilter=>{let newFilters=[...filters];newFilters[index]=newFilter,setSearch(setFilters(searchRef.current,newFilters)),setEditingIndex(-1)},onCancel:()=>setEditingIndex(-1)},`filter-${filter.code}-${filter.operator}-${filter.value}-input`):jsx90(FilterRowDisplay,{resourceType,filter,onEdit:()=>setEditingIndex(index),onDelete:()=>setSearch(deleteFilter(searchRef.current,index))},`filter-${filter.code}-${filter.operator}-${filter.value}-display`)),jsx90(FilterRowInput,{resourceType,searchParams,okText:"Add",onOk:onAddFilter})]})]})}),jsx90(Group29,{justify:"flex-end",mt:"xl",children:jsx90(Button9,{onClick:()=>props.onOk(searchRef.current),children:"OK"})})]})}function FilterRowDisplay(props){let{filter}=props;return jsxs46("tr",{children:[jsx90("td",{children:buildFieldNameString(filter.code)}),jsx90("td",{children:getOpString(filter.operator)}),jsx90("td",{children:jsx90(SearchFilterValueDisplay,{resourceType:props.resourceType,filter})}),jsxs46("td",{children:[jsx90(Button9,{size:"compact-md",variant:"outline",onClick:props.onEdit,children:"Edit"}),jsx90(Button9,{size:"compact-md",variant:"outline",onClick:props.onDelete,children:"Delete"})]})]})}function FilterRowInput(props){let[value,setValue]=useState41(props.defaultValue??{}),valueRef=useRef12(value);valueRef.current=value;function setFilterCode(newCode){setValue({...valueRef.current,code:newCode})}function setFilterOperator(newOperator){setValue({...valueRef.current,operator:newOperator})}function setFilterValue(newFilterValue){setValue({...valueRef.current,value:newFilterValue})}let searchParam=props.searchParams[value.code],operators=searchParam&&getSearchOperators(searchParam);return jsxs46("tr",{children:[jsx90("td",{children:jsx90(NativeSelect10,{"data-testid":"filter-field",defaultValue:valueRef.current.code,onChange:e=>setFilterCode(e.currentTarget.value),data:["",...Object.keys(props.searchParams).map(param=>({value:param,label:buildFieldNameString(param)}))]})}),jsx90("td",{children:operators&&jsx90(NativeSelect10,{"data-testid":"filter-operation",defaultValue:value.operator,onChange:e=>setFilterOperator(e.currentTarget.value),data:["",...operators.map(op=>({value:op,label:getOpString(op)}))]})}),jsx90("td",{children:searchParam&&value.operator&&jsx90(SearchFilterValueInput,{resourceType:props.resourceType,searchParam,defaultValue:value.value,onChange:setFilterValue})}),jsxs46("td",{children:[value.code&&value.operator&&jsx90(Button9,{size:"compact-md",variant:"outline",onClick:()=>{props.onOk(valueRef.current),setValue({})},children:props.okText}),props.onCancel&&jsx90(Button9,{size:"compact-md",variant:"outline",onClick:props.onCancel,children:"Cancel"})]})]})}import{Button as Button10,Grid,Modal as Modal6}from"@mantine/core";import{useState as useState42}from"react";import{jsx as jsx91,jsxs as jsxs47}from"react/jsx-runtime";function SearchFilterValueDialog(props){let[value,setValue]=useState42(props.defaultValue??"");if(!props.visible||!props.searchParam||!props.filter)return null;function onOk(){props.onOk({...props.filter,value})}return jsx91(Modal6,{title:props.title,size:"xl",opened:props.visible,onClose:props.onCancel,children:jsx91(Form,{onSubmit:onOk,children:jsxs47(Grid,{children:[jsx91(Grid.Col,{span:10,children:jsx91(SearchFilterValueInput,{resourceType:props.resourceType,searchParam:props.searchParam,defaultValue:value,autoFocus:!0,onChange:setValue})}),jsx91(Grid.Col,{span:2,children:jsx91(Button10,{onClick:onOk,fullWidth:!0,children:"OK"})})]})})})}import{Menu as Menu4}from"@mantine/core";import{Operator as Operator4}from"@medplum/core";import{Fragment as Fragment26,jsx as jsx92,jsxs as jsxs48}from"react/jsx-runtime";function SearchPopupMenu(props){if(!props.searchParams)return null;function onSort(searchParam,desc){onChange(setSort(props.search,searchParam.code,desc))}function onClear(searchParam){onChange(clearFiltersOnField(props.search,searchParam.code))}function onPrompt(searchParam,operator){props.onPrompt(searchParam,{code:searchParam.code,operator,value:""})}function onChange(definition){props.onChange(definition)}return props.searchParams.length===1?jsx92(SearchParameterSubMenu,{search:props.search,searchParam:props.searchParams[0],onSort,onPrompt,onChange,onClear}):jsx92(Menu4.Dropdown,{children:props.searchParams.map(searchParam=>jsx92(Menu4.Item,{children:buildFieldNameString(searchParam.code)},searchParam.code))})}function SearchParameterSubMenu(props){switch(props.searchParam.type){case"date":return jsx92(DateFilterSubMenu,{...props});case"number":case"quantity":return jsx92(NumericFilterSubMenu,{...props});case"reference":return jsx92(ReferenceFilterSubMenu,{...props});case"string":return jsx92(TextFilterSubMenu,{...props});case"token":case"uri":return jsx92(TokenFilterSubMenu,{...props});default:return jsxs48(Fragment26,{children:["Unknown search param type: ",props.searchParam.type]})}}function DateFilterSubMenu(props){let{searchParam}=props,code=searchParam.code;return jsxs48(Menu4.Dropdown,{children:[jsx92(Menu4.Item,{leftSection:jsx92(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Oldest to Newest"}),jsx92(Menu4.Item,{leftSection:jsx92(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Newest to Oldest"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Equals..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.NOT_EQUALS),children:"Does not equal..."}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.ENDS_BEFORE),children:"Before..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.STARTS_AFTER),children:"After..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconBracketsContain,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Between..."}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addTomorrowFilter(props.search,code)),children:"Tomorrow"}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addTodayFilter(props.search,code)),children:"Today"}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addYesterdayFilter(props.search,code)),children:"Yesterday"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addNextMonthFilter(props.search,code)),children:"Next Month"}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addThisMonthFilter(props.search,code)),children:"This Month"}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addLastMonthFilter(props.search,code)),children:"Last Month"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconCalendar,{size:14}),onClick:()=>props.onChange(addYearToDateFilter(props.search,code)),children:"Year to date"}),jsx92(CommonMenuItems,{...props})]})}function NumericFilterSubMenu(props){let{searchParam}=props;return jsxs48(Menu4.Dropdown,{children:[jsx92(Menu4.Item,{leftSection:jsx92(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort Smallest to Largest"}),jsx92(Menu4.Item,{leftSection:jsx92(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Largest to Smallest"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Equals..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.NOT_EQUALS),children:"Does not equal..."}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconMathGreater,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.GREATER_THAN),children:"Greater than..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.GREATER_THAN_OR_EQUALS),children:"Greater than or equal to..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconMathLower,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.LESS_THAN),children:"Less than..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconSettings,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.LESS_THAN_OR_EQUALS),children:"Less than or equal to..."}),jsx92(CommonMenuItems,{...props})]})}function ReferenceFilterSubMenu(props){let{searchParam}=props;return jsxs48(Menu4.Dropdown,{children:[jsx92(Menu4.Item,{leftSection:jsx92(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Equals..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.NOT),children:"Does not equal..."}),jsx92(CommonMenuItems,{...props})]})}function TextFilterSubMenu(props){let{searchParam}=props;return jsxs48(Menu4.Dropdown,{children:[jsx92(Menu4.Item,{leftSection:jsx92(IconSortAscending,{size:14}),onClick:()=>props.onSort(searchParam,!1),children:"Sort A to Z"}),jsx92(Menu4.Item,{leftSection:jsx92(IconSortDescending,{size:14}),onClick:()=>props.onSort(searchParam,!0),children:"Sort Z to A"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Equals..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.NOT),children:"Does not equal..."}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconBucket,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.CONTAINS),children:"Contains..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconBucketOff,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Does not contain..."}),jsx92(CommonMenuItems,{...props})]})}function TokenFilterSubMenu(props){let{searchParam}=props;return jsxs48(Menu4.Dropdown,{children:[jsx92(Menu4.Item,{leftSection:jsx92(IconEqual,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.EQUALS),children:"Equals..."}),jsx92(Menu4.Item,{leftSection:jsx92(IconEqualNot,{size:14}),onClick:()=>props.onPrompt(searchParam,Operator4.NOT),children:"Does not equal..."}),jsx92(CommonMenuItems,{...props})]})}function CommonMenuItems(props){let{searchParam}=props,code=searchParam.code;return jsxs48(Fragment26,{children:[jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconBleach,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code)),children:"Missing"}),jsx92(Menu4.Item,{leftSection:jsx92(IconBleachOff,{size:14}),onClick:()=>props.onChange(addMissingFilter(props.search,code,!1)),children:"Not missing"}),jsx92(Menu4.Divider,{}),jsx92(Menu4.Item,{leftSection:jsx92(IconX,{size:14}),onClick:()=>props.onClear(searchParam),children:"Clear filters"})]})}var SearchControl_default={root:"SearchControl_root",table:"SearchControl_table",tr:"SearchControl_tr",th:"SearchControl_th",control:"SearchControl_control",icon:"SearchControl_icon"};import{getElementDefinition,getSearchParameter,getSearchParameterDetails as getSearchParameterDetails4,getSearchParameters as getSearchParameters3}from"@medplum/core";function getFieldDefinitions(search){let resourceType=search.resourceType,fields=[];for(let name of search.fields||["id","_lastUpdated"])fields.push(getFieldDefinition(resourceType,name));return fields}function getFieldDefinition(resourceType,name){if(name==="_lastUpdated")return{name:"_lastUpdated",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_lastUpdated",name:"_lastUpdated",type:"date",expression:"Resource.meta.lastUpdated"}]};if(name==="meta.versionId")return{name:"meta.versionId",searchParams:[{resourceType:"SearchParameter",base:["Resource"],code:"_versionId",name:"_versionId",type:"token",expression:"Resource.meta.versionId"}]};let exactElementDefinition=getElementDefinition(resourceType,name),exactSearchParam=getSearchParameter(resourceType,name.toLowerCase());if(exactElementDefinition&&exactSearchParam)return{name,elementDefinition:exactElementDefinition,searchParams:[exactSearchParam]};if(exactElementDefinition){let allSearchParams=getSearchParameters3(resourceType),searchParams;if(allSearchParams){let pathRegex=new RegExp(`${resourceType}\\.${name.replaceAll("[x]","")}([^\\w-]|$)`);searchParams=Object.values(allSearchParams).filter(p=>!!p.expression&&pathRegex.test(p?.expression)),searchParams.length===0&&(searchParams=void 0)}return{name,elementDefinition:exactElementDefinition,searchParams}}if(exactSearchParam){let details=getSearchParameterDetails4(resourceType,exactSearchParam);return{name,elementDefinition:details.elementDefinitions?.[0],searchParams:[exactSearchParam]}}return{name}}import{Fragment as Fragment27,jsx as jsx93,jsxs as jsxs49}from"react/jsx-runtime";var SearchChangeEvent=class extends Event{constructor(definition){super("change"),this.definition=definition}},SearchLoadEvent=class extends Event{constructor(response){super("load"),this.response=response}},SearchClickEvent=class extends Event{constructor(resource,browserEvent){super("click"),this.resource=resource,this.browserEvent=browserEvent}};function SearchControl(props){let medplum=R(),[outcome,setOutcome]=useState43(),{search,onLoad}=props,[memoizedSearch,setMemoizedSearch]=useState43(search);deepEquals(search,memoizedSearch)||setMemoizedSearch(search);let[state,setState]=useState43({selected:{},fieldEditorVisible:!1,filterEditorVisible:!1,exportDialogVisible:!1,filterDialogVisible:!1}),stateRef=useRef13(state);stateRef.current=state;let total=memoizedSearch.total??"accurate",loadResults=useCallback9(options=>{setOutcome(void 0),medplum.requestSchema(memoizedSearch.resourceType).then(()=>medplum.search(memoizedSearch.resourceType,formatSearchQuery({...memoizedSearch,total,fields:void 0}),options)).then(response=>{setState({...stateRef.current,searchResponse:response}),onLoad&&onLoad(new SearchLoadEvent(response))}).catch(reason=>{setState({...stateRef.current,searchResponse:void 0}),setOutcome(normalizeOperationOutcome2(reason))})},[medplum,memoizedSearch,total,onLoad]),refreshResults=useCallback9(()=>{setState({...stateRef.current,searchResponse:void 0}),loadResults({cache:"reload"})},[loadResults]);useEffect14(()=>{loadResults()},[loadResults]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...stateRef.current.selected};checked?newSelected[id]=!0:delete newSelected[id],setState({...stateRef.current,selected:newSelected})}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},searchResponse=stateRef.current.searchResponse;checked&&searchResponse?.entry&&searchResponse.entry.forEach(entry=>{entry.resource?.id&&(newSelected[entry.resource.id]=!0)}),setState({...stateRef.current,selected:newSelected})}function isAllSelected(){let state2=stateRef.current;if(!state2.searchResponse?.entry||state2.searchResponse.entry.length===0)return!1;for(let e of state2.searchResponse.entry)if(e.resource?.id&&!state2.selected[e.resource.id])return!1;return!0}function emitSearchChange(newSearch){props.onChange&&props.onChange(new SearchChangeEvent(newSearch))}function handleRowClick(e,resource){if(isCheckboxCell(e.target)||e.button===2)return;killEvent(e);let isAux=e.button===1||e.ctrlKey||e.metaKey;!isAux&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),isAux&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e))}function isExportPassed(){return!!(props.onExport??props.onExportCsv??props.onExportTransactionBundle)}if(outcome)return jsx93(OperationOutcomeAlert,{outcome});if(!isDataTypeLoaded(memoizedSearch.resourceType))return jsx93(Center3,{style:{width:"100%",height:"100%"},children:jsx93(Loader4,{})});let checkboxColumn=props.checkboxesEnabled,fields=getFieldDefinitions(memoizedSearch),resourceType=memoizedSearch.resourceType,lastResult=state.searchResponse,resources=lastResult?.entry?.map(e=>e.resource),buttonVariant="subtle",buttonColor="gray",iconSize=16,isMobile=window.innerWidth<768;return jsxs49("div",{className:SearchControl_default.root,"data-testid":"search-control",children:[!props.hideToolbar&&jsxs49(Group30,{justify:"space-between",mb:"xl",children:[jsxs49(Group30,{gap:2,children:[jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconColumns,{size:iconSize}),onClick:()=>setState({...stateRef.current,fieldEditorVisible:!0}),children:"Fields"}),jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconFilter,{size:iconSize}),onClick:()=>setState({...stateRef.current,filterEditorVisible:!0}),children:"Filters"}),props.onNew&&jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconFilePlus,{size:iconSize}),onClick:props.onNew,children:"New..."}),!isMobile&&isExportPassed()&&jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconTableExport,{size:iconSize}),onClick:props.onExport?props.onExport:()=>setState({...stateRef.current,exportDialogVisible:!0}),children:"Export..."}),!isMobile&&props.onDelete&&jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconTrash,{size:iconSize}),onClick:()=>props.onDelete(Object.keys(state.selected)),children:"Delete..."}),!isMobile&&props.onBulk&&jsx93(Button11,{size:"compact-md",variant:buttonVariant,color:buttonColor,leftSection:jsx93(IconBoxMultiple,{size:iconSize}),onClick:()=>props.onBulk(Object.keys(state.selected)),children:"Bulk..."})]}),jsxs49(Group30,{gap:2,children:[lastResult&&jsxs49(Text13,{size:"xs",c:"dimmed","data-testid":"count-display",children:[getStart(memoizedSearch,lastResult).toLocaleString(),"-",getEnd(memoizedSearch,lastResult).toLocaleString(),lastResult.total!==void 0&&` of ${memoizedSearch.total==="estimate"?"~":""}${lastResult.total?.toLocaleString()}`]}),jsx93(ActionIcon8,{variant:buttonVariant,color:buttonColor,title:"Refresh",onClick:refreshResults,children:jsx93(IconRefresh,{size:iconSize})})]})]}),jsxs49(Table2,{className:SearchControl_default.table,children:[jsxs49(Table2.Thead,{children:[jsxs49(Table2.Tr,{children:[checkboxColumn&&jsx93(Table2.Th,{children:jsx93("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx93(Table2.Th,{children:jsxs49(Menu5,{shadow:"md",width:240,position:"bottom-end",children:[jsx93(Menu5.Target,{children:jsx93(UnstyledButton2,{className:SearchControl_default.control,p:2,children:jsxs49(Group30,{justify:"space-between",wrap:"nowrap",children:[jsx93(Text13,{fw:500,children:buildFieldNameString(field.name)}),jsx93(Center3,{className:SearchControl_default.icon,children:jsx93(IconAdjustmentsHorizontal,{size:14,stroke:1.5})})]})})}),jsx93(SearchPopupMenu,{search:memoizedSearch,searchParams:field.searchParams,onPrompt:(searchParam,filter)=>{setState({...stateRef.current,filterDialogVisible:!0,filterDialogSearchParam:searchParam,filterDialogFilter:filter})},onChange:result=>{emitSearchChange(result)}})]})},field.name))]}),!props.hideFilters&&jsxs49(Table2.Tr,{children:[checkboxColumn&&jsx93(Table2.Th,{}),fields.map(field=>jsx93(Table2.Th,{children:field.searchParams&&jsx93(FilterDescription,{resourceType,searchParams:field.searchParams,filters:memoizedSearch.filters})},field.name))]})]}),jsx93(Table2.Tbody,{children:resources?.map(resource=>resource&&jsxs49(Table2.Tr,{className:SearchControl_default.tr,"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx93(Table2.Td,{children:jsx93("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!state.selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx93(Table2.Td,{children:renderValue(resource,field)},field.name))]},resource.id))})]}),resources?.length===0&&jsx93(Container,{children:jsx93(Center3,{style:{height:150},children:jsx93(Text13,{size:"xl",c:"dimmed",children:"No results"})})}),lastResult&&jsx93(Center3,{m:"md",p:"md",children:jsx93(Pagination,{value:getPage(memoizedSearch),total:getTotalPages(memoizedSearch,lastResult),onChange:newPage=>emitSearchChange(setPage(memoizedSearch,newPage)),getControlProps:control=>{switch(control){case"previous":return{"aria-label":"Previous page"};case"next":return{"aria-label":"Next page"};default:return{}}}})}),jsx93(SearchFieldEditor,{search:memoizedSearch,visible:stateRef.current.fieldEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,fieldEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,fieldEditorVisible:!1})}}),jsx93(SearchFilterEditor,{search:memoizedSearch,visible:stateRef.current.filterEditorVisible,onOk:result=>{emitSearchChange(result),setState({...stateRef.current,filterEditorVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterEditorVisible:!1})}}),jsx93(SearchExportDialog,{visible:stateRef.current.exportDialogVisible,exportCsv:props.onExportCsv,exportTransactionBundle:props.onExportTransactionBundle,onCancel:()=>{setState({...stateRef.current,exportDialogVisible:!1})}}),jsx93(SearchFilterValueDialog,{visible:stateRef.current.filterDialogVisible,title:state.filterDialogSearchParam?.code?buildFieldNameString(state.filterDialogSearchParam.code):"",resourceType,searchParam:state.filterDialogSearchParam,filter:state.filterDialogFilter,defaultValue:"",onOk:filter=>{emitSearchChange(addFilter(memoizedSearch,filter.code,filter.operator,filter.value)),setState({...stateRef.current,filterDialogVisible:!1})},onCancel:()=>{setState({...stateRef.current,filterDialogVisible:!1})}},state.filterDialogSearchParam?.code)]})}var MemoizedSearchControl=SearchControl;function FilterDescription(props){let filters=(props.filters??[]).filter(f=>props.searchParams.find(p=>p.code===f.code));return filters.length===0?jsx93("span",{children:"no filters"}):jsx93(Fragment27,{children:filters.map(filter=>jsxs49("div",{children:[getOpString(filter.operator),"\xA0",jsx93(SearchFilterValueDisplay,{resourceType:props.resourceType,filter})]},`filter-${filter.code}-${filter.operator}-${filter.value}`))})}function getPage(search){return Math.floor((search.offset??0)/(search.count??DEFAULT_SEARCH_COUNT2))+1}function getTotalPages(search,lastResult){let pageSize=search.count??DEFAULT_SEARCH_COUNT2,total=getTotal(search,lastResult);return Math.ceil(total/pageSize)}function getStart(search,lastResult){return Math.min(getTotal(search,lastResult),(search.offset??0)+1)}function getEnd(search,lastResult){return Math.max(getStart(search,lastResult)+(lastResult.entry?.length??0)-1,0)}function getTotal(search,lastResult){let total=lastResult.total;return total===void 0&&(total=(search.offset??0)+(lastResult.entry?.length??0)+(lastResult.link?.some(l=>l.relation==="next")?1:0)),total}import{jsx as jsx94,jsxs as jsxs50}from"react/jsx-runtime";function FhirPathTable(props){let medplum=R(),[schemaLoaded,setSchemaLoaded]=useState44(!1),[outcome,setOutcome]=useState44(),{query,fields}=props,[response,setResponse]=useState44(),[selected,setSelected]=useState44({}),responseRef=useRef14();responseRef.current=response;let selectedRef=useRef14({});selectedRef.current=selected,useEffect15(()=>{setOutcome(void 0),medplum.graphql(query).then(setResponse).catch(err=>setOutcome(normalizeOperationOutcome3(err)))},[medplum,query]);function handleSingleCheckboxClick(e,id){e.stopPropagation();let checked=e.target.checked,newSelected={...selectedRef.current};checked?newSelected[id]=!0:delete newSelected[id],setSelected(newSelected)}function handleAllCheckboxClick(e){e.stopPropagation();let checked=e.target.checked,newSelected={},resources=responseRef.current?.data.ResourceList;checked&&resources&&resources.forEach(resource=>{resource.id&&(newSelected[resource.id]=!0)}),setSelected(newSelected)}function isAllSelected(){let resources=responseRef.current?.data.ResourceList;if(!resources||resources.length===0)return!1;for(let resource of resources)if(resource.id&&!selectedRef.current[resource.id])return!1;return!0}function handleRowClick(e,resource){isCheckboxCell(e.target)||(killEvent(e),e.button!==1&&props.onClick&&props.onClick(new SearchClickEvent(resource,e)),e.button===1&&props.onAuxClick&&props.onAuxClick(new SearchClickEvent(resource,e)))}if(useEffect15(()=>{medplum.requestSchema(props.resourceType).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum,props.resourceType]),!schemaLoaded)return jsx94(Loader5,{});let checkboxColumn=props.checkboxesEnabled;return jsxs50("div",{onContextMenu:e=>killEvent(e),"data-testid":"search-control",children:[jsxs50(Table3,{children:[jsx94(Table3.Thead,{children:jsxs50(Table3.Tr,{children:[checkboxColumn&&jsx94(Table3.Th,{children:jsx94("input",{type:"checkbox",value:"checked","aria-label":"all-checkbox","data-testid":"all-checkbox",checked:isAllSelected(),onChange:e=>handleAllCheckboxClick(e)})}),fields.map(field=>jsx94(Table3.Th,{children:field.name},field.name))]})}),jsx94(Table3.Tbody,{children:response?.data.ResourceList.map(resource=>resource&&jsxs50(Table3.Tr,{"data-testid":"search-control-row",onClick:e=>handleRowClick(e,resource),onAuxClick:e=>handleRowClick(e,resource),children:[checkboxColumn&&jsx94(Table3.Td,{children:jsx94("input",{type:"checkbox",value:"checked","data-testid":"row-checkbox","aria-label":`Checkbox for ${resource.id}`,checked:!!selected[resource.id],onChange:e=>handleSingleCheckboxClick(e,resource.id)})}),fields.map(field=>jsx94(Table3.Td,{children:jsx94(FhirPathDisplay,{propertyType:field.propertyType,path:field.fhirPath,resource})},field.name))]},resource.id))})]}),response?.data.ResourceList.length===0&&jsx94("div",{"data-testid":"empty-search",children:"No results"}),outcome&&jsx94("div",{"data-testid":"search-error",children:jsx94("pre",{style:{textAlign:"left"},children:JSON.stringify(outcome,void 0,2)})}),props.onBulk&&jsx94(Button12,{onClick:()=>props.onBulk(Object.keys(selectedRef.current)),children:"Bulk..."})]})}var MemoizedFhirPathTable=memo(FhirPathTable);import{jsx as jsx95,jsxs as jsxs51}from"react/jsx-runtime";function Logo(props){return jsxs51("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 491 491",style:{width:props.size,height:props.size},children:[jsx95("title",{children:"Medplum Logo"}),jsx95("path",{fill:props.fill??"#ad7136",d:"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z"}),jsx95("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"}),jsx95("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"}),jsx95("path",{fill:props.fill??"#40bc26",d:"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z"}),jsx95("path",{fill:props.fill??"#33961e",d:"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z"})]})}import{Box as Box4,SimpleGrid}from"@mantine/core";import{Box as Box3,Flex as Flex2,Group as Group31,Paper as Paper2,RingProgress,Text as Text14,Title as Title2}from"@mantine/core";import{formatCodeableConcept as formatCodeableConcept3}from"@medplum/core";import{Fragment as Fragment28,jsx as jsx96,jsxs as jsxs52}from"react/jsx-runtime";function MeasureReportGroupDisplay(props){let{group}=props;return jsx96(Paper2,{withBorder:!0,radius:"md",p:"xs",display:"flex",style:{alignItems:"center",justifyContent:"center"},children:jsxs52(Group31,{children:[group.measureScore&&jsx96(MeasureScore,{group}),!group.measureScore&&jsx96(MeasureReportPopulation,{group})]})})}function MeasureTitle(props){let{measure}=props;return jsxs52(Fragment28,{children:[jsx96(Text14,{fz:"md",fw:500,mb:8,children:measure.title}),jsx96(Text14,{fz:"xs",c:"dimmed",mb:8,children:measure.subtitle})]})}function MeasureReportPopulation(props){let{group}=props,populations=group.population,numerator=populations?.find(p=>formatCodeableConcept3(p.code)==="numerator"),denominator=populations?.find(p=>formatCodeableConcept3(p.code)==="denominator"),numeratorCount=numerator?.count,denominatorCount=denominator?.count;if(denominatorCount===0)return jsxs52(Box3,{children:[jsx96(Title2,{order:3,children:"Not Applicable"}),jsx96(Text14,{children:`Denominator: ${denominatorCount}`})]});if(numeratorCount===void 0||denominatorCount===void 0)return jsxs52(Box3,{children:[jsx96(Title2,{order:3,children:"Insufficient Data"}),jsx96(Text14,{children:`Numerator: ${numeratorCount}`}),jsx96(Text14,{children:`Denominator: ${denominatorCount}`})]});let value=numeratorCount/denominatorCount*100;return jsx96(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value,color:groupColor(value)}],label:jsx96(Flex2,{justify:"center",children:jsxs52(Text14,{fw:700,fz:18,children:[numeratorCount," / ",denominatorCount]})})})}function MeasureScore(props){let{group}=props,unit=group.measureScore?.unit??group.measureScore?.code;return jsx96(Fragment28,{children:unit==="%"?jsx96(RingProgress,{size:120,thickness:12,roundCaps:!0,sections:[{value:groupValue(group),color:groupColor(group?.measureScore?.value??0)}],label:jsx96(Flex2,{justify:"center",children:jsx96(Text14,{fw:700,fz:18,children:jsx96(QuantityDisplay,{value:group.measureScore})})})}):jsx96(Flex2,{h:120,align:"center",children:jsx96(Title2,{order:3,children:jsx96(QuantityDisplay,{value:group.measureScore})})})})}function groupValue(group){let score=group.measureScore?.value,unit=group.measureScore?.unit;return score?score<=1&&unit==="%"?score*100:score:0}function groupColor(score){return score<=33?"red":score<=67?"yellow":"green"}import{jsx as jsx97,jsxs as jsxs53}from"react/jsx-runtime";function MeasureReportDisplay(props){let report=Me(props.measureReport),[measure]=Ie("Measure",{url:report?.measure});return report?jsxs53(Box4,{children:[measure&&jsx97(MeasureTitle,{measure}),jsx97(SimpleGrid,{cols:{base:3,sm:1},spacing:{base:"md",sm:"sm"},children:report.group?.map((group,idx)=>jsx97(MeasureReportGroupDisplay,{group},group.id??idx))})]}):null}import{ActionIcon as ActionIcon9,Indicator,Tooltip as Tooltip3}from"@mantine/core";import{useCallback as useCallback10,useEffect as useEffect16,useState as useState45}from"react";import{jsx as jsx98}from"react/jsx-runtime";function NotificationIcon(props){let medplum=R(),{label,resourceType,countCriteria,subscriptionCriteria,onClick}=props,[unreadCount,setUnreadCount]=useState45(0),updateCount=useCallback10(cache=>{medplum.search(resourceType,countCriteria,{cache}).then(result=>setUnreadCount(result.total)).catch(console.error)},[medplum,resourceType,countCriteria]);useEffect16(()=>{updateCount("default")},[updateCount]),ze(subscriptionCriteria,()=>{updateCount("reload")});let icon=jsx98(Tooltip3,{label,children:jsx98(ActionIcon9,{variant:"subtle",color:"gray",size:"lg","aria-label":label,onClick,children:props.iconComponent})});return unreadCount>0?jsx98(Indicator,{inline:!0,label:unreadCount.toLocaleString(),size:16,offset:2,position:"bottom-end",color:"red",children:icon}):icon}import{Card,Divider,Flex as Flex3,Group as Group41,Paper as Paper3,Stack as Stack16,Text as Text21}from"@mantine/core";import{calculateAgeString,formatHumanName as formatHumanName4,resolveId}from"@medplum/core";import{useEffect as useEffect17,useMemo as useMemo27,useState as useState55}from"react";import{Anchor as Anchor3,Box as Box5,Group as Group33,Modal as Modal7,Text as Text15}from"@mantine/core";import{useDisclosure}from"@mantine/hooks";import{useCallback as useCallback12,useState as useState47}from"react";import{Button as Button13,Group as Group32,Stack as Stack10,TextInput as TextInput15}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG2,addProfileToResource,createReference as createReference5}from"@medplum/core";import{useCallback as useCallback11,useState as useState46}from"react";import{jsx as jsx99,jsxs as jsxs54}from"react/jsx-runtime";var HTTP="http://",PATIENT_ALLERGY_PROFILE=HTTP_HL7_ORG2+"/fhir/us/core/StructureDefinition/us-core-allergyintolerance";function AllergyDialog(props){let{patient,encounter,allergy,onSubmit}=props,[code,setCode]=useState46(allergy?.code),[clinicalStatus,setClinicalStatus]=useState46(allergy?.clinicalStatus),handleSubmit=useCallback11(formData=>{onSubmit(addProfileToResource({...allergy,resourceType:"AllergyIntolerance",patient:createReference5(patient),encounter:encounter?createReference5(encounter):void 0,code,clinicalStatus,onsetDateTime:formData.onsetDateTime?formData.onsetDateTime:void 0,reaction:formData.reaction?[{manifestation:[{text:formData.reaction}]}]:void 0},PATIENT_ALLERGY_PROFILE))},[patient,encounter,allergy,code,clinicalStatus,onSubmit]);return jsx99(Form,{onSubmit:handleSubmit,children:jsxs54(Stack10,{children:[jsx99(CodeableConceptInput,{name:"allergy",label:"Code",path:"AllergyIntolerance.code","data-autofocus":!0,binding:HTTP+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1186.8",maxValues:1,defaultValue:allergy?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx99(TextInput15,{name:"reaction",label:"Reaction",defaultValue:allergy?.reaction?.[0]?.manifestation?.[0]?.text}),jsx99(CodeableConceptInput,{name:"clinicalStatus",label:"Clinical Status",path:"AllergyIntolerance.clinicalStatus",binding:HTTP_HL7_ORG2+"/fhir/ValueSet/allergyintolerance-clinical",maxValues:1,defaultValue:allergy?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx99(DateTimeInput,{name:"onsetDateTime",label:"Onset",defaultValue:allergy?.recordedDate}),jsx99(Group32,{justify:"flex-end",gap:4,mt:"md",children:jsx99(Button13,{type:"submit",children:"Save"})})]})},allergy?.id)}import{Badge as Badge2}from"@mantine/core";import{getDisplayString as getDisplayString5}from"@medplum/core";import{jsx as jsx100}from"react/jsx-runtime";function ConceptBadge(props){let{resource,onEdit}=props,rightSection;return onEdit&&(rightSection=jsx100(IconEdit,{"aria-label":`Edit ${getDisplayString5(resource)}`,size:12,onClick:e=>{killEvent(e),onEdit(resource)}})),jsx100(MedplumLink,{to:resource,children:jsx100(Badge2,{variant:"light",maw:"100%",rightSection,children:getDisplayString5(resource)})},resource.id)}import{Fragment as Fragment29,jsx as jsx101,jsxs as jsxs55}from"react/jsx-runtime";function Allergies(props){let medplum=R(),{patient,encounter}=props,[allergies,setAllergies]=useState47(props.allergies),[opened,{open,close}]=useDisclosure(!1),[editAllergy,setEditAllergy]=useState47(),handleSubmit=useCallback12(async allergy=>{if(allergy.id){let updatedAllergy=await medplum.updateResource(allergy);setAllergies(allergies.map(a2=>a2.id===updatedAllergy.id?updatedAllergy:a2))}else{let newAllergy=await medplum.createResource(allergy);setAllergies([...allergies,newAllergy])}setEditAllergy(void 0),close()},[medplum,allergies,close]);return jsxs55(Fragment29,{children:[jsxs55(Group33,{justify:"space-between",children:[jsx101(Text15,{fz:"md",fw:700,children:"Allergies"}),jsx101(Anchor3,{component:"button",onClick:e=>{killEvent(e),setEditAllergy(void 0),open()},children:"+ Add"})]}),allergies.length>0?jsx101(Box5,{children:allergies.map(allergy=>jsx101(ConceptBadge,{resource:allergy,onEdit:a2=>{setEditAllergy(a2),open()}},allergy.id))}):jsx101(Text15,{children:"(none)"}),jsx101(Modal7,{opened,onClose:close,title:editAllergy?"Edit Allergy":"Add Allergy",children:jsx101(AllergyDialog,{patient,encounter,allergy:editAllergy,onSubmit:handleSubmit})})]})}import{Anchor as Anchor4,Box as Box6,Group as Group35,Modal as Modal8,Text as Text16}from"@mantine/core";import{useDisclosure as useDisclosure2}from"@mantine/hooks";import{useCallback as useCallback14,useState as useState49}from"react";import{Alert as Alert3,Button as Button14,Group as Group34,Radio,Stack as Stack11}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG3,addProfileToResource as addProfileToResource2,createReference as createReference6}from"@medplum/core";import{useCallback as useCallback13,useState as useState48}from"react";import{jsx as jsx102,jsxs as jsxs56}from"react/jsx-runtime";var HTTP2="http://",statusValues=["active","stopped","on-hold","cancelled","completed","entered-in-error","draft","unknown"];function MedicationDialog(props){let me=ie(),{patient,encounter,medication,onSubmit}=props,[code,setCode]=useState48(medication?.medicationCodeableConcept),handleSubmit=useCallback13(formData=>{if(!me)throw new Error("Not signed in");onSubmit(addProfileToResource2({...medication,resourceType:"MedicationRequest",status:formData.status,intent:medication?.intent??"order",encounter:medication?.encounter??(encounter&&createReference6(encounter)),requester:medication?.requester??createReference6(me),medicationCodeableConcept:code,subject:createReference6(patient)},HTTP_HL7_ORG3+"/fhir/us/core/StructureDefinition/us-core-medicationrequest"))},[me,onSubmit,medication,encounter,code,patient]);return me?jsx102(Form,{onSubmit:handleSubmit,children:jsxs56(Stack11,{children:[jsx102(CodeableConceptInput,{name:"request",path:"MedicationRequest.medication[x]","data-autofocus":!0,binding:HTTP2+"cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1010.4",maxValues:1,defaultValue:medication?.medicationCodeableConcept,onChange:request=>setCode(request),outcome:void 0}),jsx102(Radio.Group,{name:"status",label:"Request Status",required:!0,defaultValue:medication?.status,children:statusValues.map(sv=>jsx102(Radio,{value:sv,label:sv,my:"xs",required:!0},sv))}),jsx102(Group34,{justify:"flex-end",gap:4,children:jsx102(Button14,{type:"submit",children:"Save"})})]})}):jsx102(Alert3,{color:"red",children:"Not signed in"})}import{Fragment as Fragment30,jsx as jsx103,jsxs as jsxs57}from"react/jsx-runtime";function Medications(props){let medplum=R(),[medicationRequests,setMedicationRequests]=useState49(props.medicationRequests),[editMedication,setEditMedication]=useState49(),[opened,{open,close}]=useDisclosure2(!1),handleSubmit=useCallback14(async medication=>{if(medication.id){let updatedMedication=await medplum.updateResource(medication);setMedicationRequests(medicationRequests.map(m=>m.id===updatedMedication.id?updatedMedication:m))}else{let newMedication=await medplum.createResource(medication);setMedicationRequests([newMedication,...medicationRequests])}setEditMedication(void 0),close()},[medplum,medicationRequests,close]);return jsxs57(Fragment30,{children:[jsxs57(Group35,{justify:"space-between",children:[jsx103(Text16,{fz:"md",fw:700,children:"Medications"}),jsx103(Anchor4,{component:"button",onClick:e=>{killEvent(e),setEditMedication(void 0),open()},children:"+ Add"})]}),medicationRequests.length>0?jsx103(Box6,{children:medicationRequests.map(request=>jsx103(ConceptBadge,{resource:request,onEdit:mr=>{setEditMedication(mr),open()}},request.id))}):jsx103(Text16,{children:"(none)"}),jsx103(Modal8,{opened,onClose:close,title:editMedication?"Edit Medication":"Add Medication",children:jsx103(MedicationDialog,{patient:props.patient,encounter:props.encounter,medication:editMedication,onSubmit:handleSubmit})})]})}import{Anchor as Anchor5,Grid as Grid2,Group as Group37,Modal as Modal9,Text as Text17}from"@mantine/core";import{useDisclosure as useDisclosure3}from"@mantine/hooks";import{Fragment as Fragment31,useCallback as useCallback16,useState as useState51}from"react";import{Button as Button15,Group as Group36,Stack as Stack12}from"@mantine/core";import{HTTP_HL7_ORG as HTTP_HL7_ORG4,HTTP_TERMINOLOGY_HL7_ORG,addProfileToResource as addProfileToResource3,createReference as createReference7}from"@medplum/core";import{useCallback as useCallback15,useState as useState50}from"react";import{jsx as jsx104,jsxs as jsxs58}from"react/jsx-runtime";function ConditionDialog(props){let{patient,encounter,condition,onSubmit}=props,[code,setCode]=useState50(condition?.code),[clinicalStatus,setClinicalStatus]=useState50(condition?.clinicalStatus),handleSubmit=useCallback15(formData=>{let updatedCondition=addProfileToResource3({...condition,resourceType:"Condition",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG+"/CodeSystem/condition-category",code:"problem-list-item",display:"Problem List Item"}],text:"Problem List Item"}],subject:createReference7(patient),encounter:encounter&&createReference7(encounter),code,clinicalStatus,onsetDateTime:formData.onsetDateTime?convertLocalToIso(formData.onsetDateTime):void 0},HTTP_HL7_ORG4+"/fhir/us/core/StructureDefinition/us-core-condition-problems-health-concerns");onSubmit(updatedCondition)},[patient,encounter,condition,code,clinicalStatus,onSubmit]);return jsx104(Form,{onSubmit:handleSubmit,children:jsxs58(Stack12,{children:[jsx104(CodeableConceptInput,{name:"code",label:"Problem",path:"Condition.code","data-autofocus":!0,binding:HTTP_HL7_ORG4+"/fhir/us/core/ValueSet/us-core-condition-code",defaultValue:condition?.code,onChange:code2=>setCode(code2),outcome:void 0}),jsx104(CodeableConceptInput,{name:"clinicalStatus",label:"Status",path:"Condition.clinicalStatus",binding:HTTP_HL7_ORG4+"/fhir/ValueSet/condition-clinical",defaultValue:condition?.clinicalStatus,onChange:clinicalStatus2=>setClinicalStatus(clinicalStatus2),outcome:void 0}),jsx104(DateTimeInput,{name:"onsetDateTime",label:"Dx Date",defaultValue:condition?.onsetDateTime,required:!0}),jsx104(Group36,{justify:"flex-end",gap:4,mt:"md",children:jsx104(Button15,{type:"submit",children:"Save"})})]})},condition?.id)}import{Fragment as Fragment32,jsx as jsx105,jsxs as jsxs59}from"react/jsx-runtime";function ProblemList(props){let medplum=R(),{patient,encounter}=props,[problems,setProblems]=useState51(props.problems),[editCondition,setEditCondition]=useState51(),[opened,{open,close}]=useDisclosure3(!1),handleSubmit=useCallback16(async condition=>{if(condition.id){let updatedCondition=await medplum.updateResource(condition);setProblems(problems.map(p=>p.id===updatedCondition.id?updatedCondition:p))}else{let newCondition=await medplum.createResource(condition);setProblems([...problems,newCondition])}setEditCondition(void 0),close()},[medplum,problems,close]);return jsxs59(Fragment32,{children:[jsxs59(Group37,{justify:"space-between",children:[jsx105(Text17,{fz:"md",fw:700,children:"Problem List"}),jsx105(Anchor5,{component:"button",onClick:e=>{killEvent(e),setEditCondition(void 0),open()},children:"+ Add"})]}),problems.length>0?jsx105(Grid2,{gutter:"xs",children:problems.map(problem=>jsxs59(Fragment31,{children:[jsx105(Grid2.Col,{span:2,children:problem.onsetDateTime?.substring(0,4)}),jsx105(Grid2.Col,{span:10,children:jsx105(ConceptBadge,{resource:problem,onEdit:c=>{setEditCondition(c),open()}},problem.id)})]},problem.id))}):jsx105(Text17,{children:"(none)"}),jsx105(Modal9,{opened,onClose:close,title:editCondition?"Edit Problem":"Add Problem",children:jsx105(ConditionDialog,{patient,encounter,condition:editCondition,onSubmit:handleSubmit})})]})}import{Anchor as Anchor6,Badge as Badge3,Box as Box7,Button as Button16,Group as Group38,Modal as Modal10,Radio as Radio2,Stack as Stack13,Text as Text18}from"@mantine/core";import{useDisclosure as useDisclosure4}from"@mantine/hooks";import{HTTP_HL7_ORG as HTTP_HL7_ORG5,HTTP_TERMINOLOGY_HL7_ORG as HTTP_TERMINOLOGY_HL7_ORG2,LOINC,SNOMED,createReference as createReference8}from"@medplum/core";import{useCallback as useCallback17,useState as useState52}from"react";import{Fragment as Fragment33,jsx as jsx106,jsxs as jsxs60}from"react/jsx-runtime";var NULLFLAVOR=HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/v3-NullFlavor",CodesToText={38628009:"Homosexual",20430005:"Heterosexual",42035005:"Bisexual",OTH:"Other",UNK:"Unknown",ASKU:"Asked but no answer"},CodesToSystem={38628009:SNOMED,20430005:SNOMED,42035005:SNOMED,OTH:NULLFLAVOR,UNK:NULLFLAVOR,ASKU:NULLFLAVOR};function SexualOrientation(props){let medplum=R(),{patient,encounter}=props,[sexualOrientation,setSexualOrientation]=useState52(props.sexualOrientation),[opened,{open,close}]=useDisclosure4(!1),handleSubmit=useCallback17(formData=>{let code=formData.sexualOrientation;medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG5+"/fhir/us/core/ValueSet/us-core-sexual-orientation"]},status:"final",category:[{coding:[{system:HTTP_TERMINOLOGY_HL7_ORG2+"/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC,code:"76690-7",display:"Sexual orientation"}],text:"Sexual orientation"},subject:createReference8(patient),encounter:encounter?createReference8(encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:CodesToSystem[code],code:formData.sexualOrientation}],text:CodesToText[code]}}).then(newSexualOrientation=>{setSexualOrientation(newSexualOrientation),close()}).catch(console.error)},[medplum,patient,encounter,close]);return jsxs60(Fragment33,{children:[jsxs60(Group38,{justify:"space-between",children:[jsx106(Text18,{fz:"md",fw:700,children:"Sexual Orientation"}),jsx106(Anchor6,{href:"#",onClick:e=>{killEvent(e),open()},children:"+ Edit"})]}),sexualOrientation?.valueCodeableConcept?jsx106(Box7,{children:jsx106(Badge3,{variant:"light",children:jsx106(CodeableConceptDisplay,{value:sexualOrientation.valueCodeableConcept})})}):jsx106(Text18,{children:"(none)"}),jsx106(Modal10,{opened,onClose:close,title:"Set Sexual Orientation",children:jsx106(Form,{onSubmit:handleSubmit,children:jsxs60(Stack13,{children:[jsx106(Radio2.Group,{name:"sexualOrientation",label:"Sexual Orientation",required:!0,children:Object.entries(CodesToText).map(([code,text])=>jsx106(Radio2,{value:code,label:text,my:"xs"},code))}),jsx106(Group38,{justify:"flex-end",gap:4,mt:"md",children:jsx106(Button16,{type:"submit",children:"Save"})})]})})})]})}import{Anchor as Anchor7,Badge as Badge4,Box as Box8,Button as Button17,Group as Group39,Modal as Modal11,Radio as Radio3,Stack as Stack14,Text as Text19}from"@mantine/core";import{useDisclosure as useDisclosure5}from"@mantine/hooks";import{HTTP_HL7_ORG as HTTP_HL7_ORG6,LOINC as LOINC2,SNOMED as SNOMED2,createReference as createReference9}from"@medplum/core";import{useCallback as useCallback18,useState as useState53}from"react";import{Fragment as Fragment34,jsx as jsx107,jsxs as jsxs61}from"react/jsx-runtime";var smokingStatusOptions={266919005:"Never smoked tobacco",266927001:"Tobacco smoking consumption unknown","428041000124106":"Occasional tobacco smoker","428061000124105":"Light tobacco smoker","428071000124103":"Heavy tobacco smoker",449868002:"Smokes tobacco daily",77176002:"Smoker",8517006:"Ex-smoker"};function SmokingStatus(props){let medplum=R(),{patient,encounter}=props,[smokingStatus,setSmokingStatus]=useState53(props.smokingStatus),[opened,{open,close}]=useDisclosure5(!1),handleSubmit=useCallback18(formData=>{medplum.createResource({resourceType:"Observation",meta:{profile:[HTTP_HL7_ORG6+"/fhir/us/core/StructureDefinition/us-core-smokingstatus"]},status:"final",category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"social-history",display:"Social History"}],text:"Social History"}],code:{coding:[{system:LOINC2,code:"72166-2",display:"Tobacco smoking status"}],text:"Tobacco smoking status"},subject:createReference9(patient),encounter:encounter?createReference9(encounter):void 0,effectiveDateTime:new Date().toISOString(),valueCodeableConcept:{coding:[{system:SNOMED2,version:SNOMED2+"/731000124108",code:formData.smokingStatus}],text:smokingStatusOptions[formData.smokingStatus]}}).then(newSmokingStatus=>{setSmokingStatus(newSmokingStatus),close()}).catch(console.error)},[medplum,patient,encounter,close]);return jsxs61(Fragment34,{children:[jsxs61(Group39,{justify:"space-between",children:[jsx107(Text19,{fz:"md",fw:700,children:"Smoking Status"}),jsx107(Anchor7,{href:"#",onClick:e=>{killEvent(e),open()},children:"+ Edit"})]}),smokingStatus?.valueCodeableConcept?jsx107(Box8,{children:jsx107(Badge4,{variant:"light",children:jsx107(CodeableConceptDisplay,{value:smokingStatus.valueCodeableConcept})})}):jsx107(Text19,{children:"(none)"}),jsx107(Modal11,{opened,onClose:close,title:"Set Smoking Status",children:jsx107(Form,{onSubmit:handleSubmit,children:jsxs61(Stack14,{children:[jsx107(Radio3.Group,{name:"smokingStatus",label:"Smoking Status",required:!0,children:Object.entries(smokingStatusOptions).map(([code,text])=>jsx107(Radio3,{value:code,label:text,my:"xs"},code))}),jsx107(Group39,{justify:"flex-end",gap:4,mt:"md",children:jsx107(Button17,{type:"submit",children:"Save"})})]})})})]})}import{Anchor as Anchor8,Button as Button18,Grid as Grid3,Group as Group40,Modal as Modal12,Stack as Stack15,Text as Text20,Textarea as Textarea3,TextInput as TextInput16}from"@mantine/core";import{useDisclosure as useDisclosure6}from"@mantine/hooks";import{useCallback as useCallback19,useState as useState54}from"react";import{LOINC as LOINC3,UCUM,createReference as createReference10}from"@medplum/core";function getObservationValue(observations,code){return observations.find(o=>o.code?.coding?.[0].code===code)?.valueQuantity}function getCompoundObservationValue(observations,code,innerCode){return observations.find(o=>o.code?.coding?.[0].code===code)?.component?.find(c=>c.code?.coding?.[0].code===innerCode)?.valueQuantity}function createObservation(patient,encounter,code,title,valueQuantity){if(isValidNumber(valueQuantity.value))return{...createBaseObservation(patient,encounter,code,title),valueQuantity}}function createCompoundObservation(patient,encounter,code,title,components){let component=components.filter(c=>isValidNumber(c.valueQuantity?.value));if(component.length!==0)return{...createBaseObservation(patient,encounter,code,title),component}}function createBaseObservation(patient,encounter,code,title){return{resourceType:"Observation",status:"preliminary",subject:createReference10(patient),encounter:encounter?createReference10(encounter):void 0,effectiveDateTime:new Date().toISOString(),category:[{coding:[{system:"http://terminology.hl7.org/CodeSystem/observation-category",code:"vital-signs",display:"Vital Signs"}]}],code:createLoincCode(code,title)}}function createLoincCode(code,display){return{coding:[{code,display,system:LOINC3}],text:display}}function createQuantity(value,unit){return{value,system:UCUM,unit,code:unit}}function isValidNumber(value){return value!==void 0&&!isNaN(value)&&isFinite(value)}import{Fragment as Fragment35,jsx as jsx108,jsxs as jsxs62}from"react/jsx-runtime";var LOINC_CODES={bloodPressure:{code:"85354-9",title:"Blood Pressure",unit:"mm[Hg]"},heartRate:{code:"8867-4",title:"Heart Rate",unit:"/min"},bodyTemperature:{code:"8310-5",title:"Body Temperature",unit:"Cel"},respiratoryRate:{code:"9279-1",title:"Respiratory Rate",unit:"/min"},height:{code:"8302-2",title:"height",unit:"cm"},weight:{code:"29463-7",title:"weight",unit:"kg"},bmi:{code:"39156-5",title:"BMI",unit:"kg/m2"},oxygen:{code:"2708-6",title:"Oxygen",unit:"%"},headCircumference:{code:"9843-4",title:"Head Circumference",unit:"cm"}},SYSTOLIC="8480-6",DIASTOLIC="8462-4";function Vitals(props){let medplum=R(),{patient,encounter}=props,[vitals,setVitals]=useState54(props.vitals),[opened,{open,close}]=useDisclosure6(!1),handleSubmit=useCallback19(formData=>{let newObservations=Object.entries(LOINC_CODES).map(([name,meta])=>name==="bloodPressure"?createCompoundObservation(patient,encounter,meta.code,meta.title,[{code:createLoincCode(SYSTOLIC,"Systolic blood pressure"),valueQuantity:createQuantity(parseFloat(formData.systolic),"mm[Hg]")},{code:createLoincCode(DIASTOLIC,"Diastolic blood pressure"),valueQuantity:createQuantity(parseFloat(formData.diastolic),"mm[Hg]")}]):createObservation(patient,encounter,meta.code,meta.title,createQuantity(parseFloat(formData[name]),meta.unit))).filter(Boolean);Promise.all(newObservations.map(obs=>medplum.createResource(obs))).then(newVitals=>setVitals([...newVitals,...vitals])).catch(console.error),close()},[medplum,patient,encounter,vitals,close]);return jsxs62(Fragment35,{children:[jsxs62(Group40,{justify:"space-between",children:[jsx108(Text20,{fz:"md",fw:700,children:"Vitals"}),jsx108(Anchor8,{href:"#",onClick:e=>{killEvent(e),open()},children:"+ Add"})]}),jsxs62(Grid3,{children:[jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"BP Sys"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getCompoundObservationValue(vitals,LOINC_CODES.bloodPressure.code,SYSTOLIC)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"BP Dias"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getCompoundObservationValue(vitals,LOINC_CODES.bloodPressure.code,DIASTOLIC)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"HR"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.heartRate.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"Temp"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.bodyTemperature.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"RR"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.respiratoryRate.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"Height"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.height.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"Weight"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.weight.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"BMI"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.bmi.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"O2"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.oxygen.code)})}),jsx108(Grid3.Col,{span:3,ta:"right",c:"dimmed",children:"HC"}),jsx108(Grid3.Col,{span:3,children:jsx108(QuantityDisplay,{value:getObservationValue(vitals,LOINC_CODES.headCircumference.code)})})]}),jsx108(Modal12,{opened,onClose:close,title:"Add Vitals",children:jsxs62(Form,{onSubmit:handleSubmit,children:[jsxs62(Stack15,{children:[jsxs62(Group40,{grow:!0,children:[jsx108(TextInput16,{name:"systolic",label:"BP Sys","data-autofocus":!0,autoFocus:!0}),jsx108(TextInput16,{name:"diastolic",label:"BP Dias"})]}),jsxs62(Group40,{grow:!0,children:[jsx108(TextInput16,{name:"heartRate",label:"HR"}),jsx108(TextInput16,{name:"bodyTemperature",label:"Temp"})]}),jsxs62(Group40,{grow:!0,children:[jsx108(TextInput16,{name:"respiratoryRate",label:"RR"}),jsx108(TextInput16,{name:"height",label:"height"})]}),jsxs62(Group40,{grow:!0,children:[jsx108(TextInput16,{name:"weight",label:"Wt"}),jsx108(TextInput16,{name:"bmi",label:"BMI"})]}),jsxs62(Group40,{grow:!0,children:[jsx108(TextInput16,{name:"oxygen",label:"O2"}),jsx108(TextInput16,{name:"headCircumference",label:"HC"})]}),jsx108(Textarea3,{name:"notes",label:"Notes"})]}),jsx108(Group40,{justify:"flex-end",gap:4,mt:"md",children:jsx108(Button18,{type:"submit",children:"Save"})})]})})]})}import{Fragment as Fragment36,jsx as jsx109,jsxs as jsxs63}from"react/jsx-runtime";function getGenderIcon(patient){switch(patient?.gender){case"female":return IconGenderFemale;case"male":return IconGenderMale;default:return}}function pluralize(count,singular,plural){return count===0?`No ${plural}`:count===1?`1 ${singular}`:`${count} ${plural}`}function PatientSummary(props){let medplum=R(),{patient:propsPatient,background,appointmentsUrl:propsAppointmentsUrl,encountersUrl:propsEncountersUrl,...cardProps}=props,patient=Me(propsPatient),[medicalData,setMedicalData]=useState55(),appointmentsUrl="appointmentsUrl"in props?propsAppointmentsUrl:"#",encountersUrl="encountersUrl"in props?propsEncountersUrl:"#";useEffect17(()=>{let ref=`Patient/${resolveId(propsPatient)}`,searchMeta={_count:100,_sort:"-_lastUpdated"},today=new Date().toISOString().substring(0,10);Promise.all([medplum.searchResources("AllergyIntolerance",{patient:ref,...searchMeta}),medplum.searchResources("Condition",{patient:ref,...searchMeta}),medplum.searchResources("MedicationRequest",{subject:ref,...searchMeta}),medplum.searchResources("Observation",{subject:ref,...searchMeta}),medplum.searchResources("Appointment",{patient:ref,date:`ge${today}`,status:"proposed,pending,booked",...searchMeta}),medplum.searchResources("Encounter",{subject:ref,date:`le${today}`,status:"finished",...searchMeta})]).then(results=>{let observations=results[3];setMedicalData({allergies:results[0],problems:results[1],medicationRequests:results[2],sexualOrientation:observations.find(obs=>obs.code?.coding?.[0].code==="76690-7"),smokingStatus:observations.find(obs=>obs.code?.coding?.[0].code==="72166-2"),vitals:observations.filter(obs=>obs.category?.[0]?.coding?.[0].code==="vital-signs"),appointments:results[4],encounters:results[5]})}).catch(console.error)},[medplum,propsPatient]);let links=useMemo27(()=>{let appointmentsLink=appointmentsUrl===void 0?void 0:jsx109(MedplumLink,{to:appointmentsUrl,children:pluralize(medicalData?.appointments?.length,"upcoming appointment","upcoming appointments")},"appt"),encountersLink=encountersUrl===void 0?void 0:jsx109(MedplumLink,{to:encountersUrl,children:pluralize(medicalData?.encounters?.length,"documented visit","documented visits")},"enc");return[appointmentsLink,encountersLink].filter(Boolean)},[appointmentsUrl,medicalData?.appointments?.length,medicalData?.encounters?.length,encountersUrl]);if(!patient)return null;let GenderIconComponent=getGenderIcon(patient);return jsxs63(Card,{...cardProps,children:[jsx109(Card.Section,{h:100,style:{background}}),jsx109(ResourceAvatar,{value:patient,size:80,radius:80,mx:"auto",mt:-50,style:{border:"2px solid white"}}),jsx109(Text21,{ta:"center",fz:"lg",fw:500,children:formatHumanName4(patient.name?.[0])}),patient.birthDate&&jsxs63(Text21,{ta:"center",fz:"xs",c:"dimmed",children:[patient.birthDate," (",calculateAgeString(patient.birthDate),")"]}),jsx109(Paper3,{withBorder:!0,p:"md",my:"md",children:jsxs63(Group41,{wrap:"nowrap",justify:"space-evenly",children:[jsxs63(Flex3,{justify:"center",align:"center",direction:"column",gap:0,children:[jsx109(IconUserSquare,{size:24,color:"gray"}),jsx109(Text21,{fz:"xs",ta:"center",style:{whiteSpace:"nowrap"},children:"Self"})]}),jsxs63(Flex3,{justify:"center",align:"center",direction:"column",gap:0,children:[jsx109(IconStethoscope,{size:24,color:"gray"}),jsx109(Text21,{fz:"xs",style:{whiteSpace:"nowrap"},children:patient?.generalPractitioner?.[0]?.display??"No provider"})]}),GenderIconComponent&&jsxs63(Flex3,{justify:"center",align:"center",direction:"column",gap:0,children:[jsx109(GenderIconComponent,{size:24,color:"gray"}),jsx109(Text21,{fz:"xs",style:{whiteSpace:"nowrap"},children:patient.gender})]})]})}),jsxs63(Stack16,{gap:"xs",children:[links.length>0&&jsxs63(Fragment36,{children:[links,jsx109(Divider,{})]}),medicalData&&jsxs63(Fragment36,{children:[jsx109(Allergies,{patient,allergies:medicalData.allergies}),jsx109(Divider,{}),jsx109(ProblemList,{patient,problems:medicalData.problems}),jsx109(Divider,{}),jsx109(Medications,{patient,medicationRequests:medicalData.medicationRequests}),jsx109(Divider,{}),jsx109(SexualOrientation,{patient,sexualOrientation:medicalData.sexualOrientation}),jsx109(Divider,{}),jsx109(SmokingStatus,{patient,smokingStatus:medicalData.smokingStatus}),jsx109(Divider,{}),jsx109(Vitals,{patient,vitals:medicalData.vitals})]})]})]})}import{createReference as createReference11}from"@medplum/core";import{useCallback as useCallback20}from"react";import{jsx as jsx110}from"react/jsx-runtime";function PatientTimeline(props){let{patient,...rest}=props,loadTimelineResources=useCallback20((medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("Patient",id),medplum.search("Communication",{subject:ref,_count}),medplum.search("Device",{patient:ref,_count}),medplum.search("DeviceRequest",{patient:ref,_count}),medplum.search("DiagnosticReport",{subject:ref,_count}),medplum.search("Media",{subject:ref,_count}),medplum.search("ServiceRequest",{subject:ref,_count}),medplum.search("Task",{subject:ref,_count})])},[]);return jsx110(ResourceTimeline,{value:patient,loadTimelineResources,createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",subject:createReference11(resource),sender:createReference11(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",subject:createReference11(resource),operator:createReference11(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor9,Button as Button19,NativeSelect as NativeSelect11,Stack as Stack17,TextInput as TextInput17}from"@mantine/core";import{getReferenceString as getReferenceString5}from"@medplum/core";import{useEffect as useEffect18,useRef as useRef15,useState as useState56}from"react";var PlanDefinitionBuilder_default={section:"PlanDefinitionBuilder_section",hovering:"PlanDefinitionBuilder_hovering",editing:"PlanDefinitionBuilder_editing",bottomActions:"PlanDefinitionBuilder_bottomActions"};import{jsx as jsx111,jsxs as jsxs64}from"react/jsx-runtime";function PlanDefinitionBuilder(props){let medplum=R(),defaultValue2=Me(props.value),[schemaLoaded,setSchemaLoaded]=useState56(!1),[selectedKey,setSelectedKey]=useState56(),[hoverKey,setHoverKey]=useState56(),[value,setValue]=useState56();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}let valueRef=useRef15();if(valueRef.current=value,useEffect18(()=>{medplum.requestSchema("PlanDefinition").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect18(()=>(setValue(ensurePlanDefinitionKeys(defaultValue2??{resourceType:"PlanDefinition",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]),!schemaLoaded||!value)return null;function changeProperty(property,newValue){setValue({...valueRef.current,[property]:newValue})}return jsx111("div",{children:jsxs64(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx111(TextInput17,{label:"Plan Title",defaultValue:value.title,onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx111(ActionArrayBuilder,{actions:value.action||[],selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:x=>changeProperty("action",x)}),jsx111(Button19,{type:"submit",children:"Save"})]})})}function ActionArrayBuilder(props){let actionsRef=useRef15();actionsRef.current=props.actions;function changeAction(changedAction){props.onChange(actionsRef.current.map(i=>i.id===changedAction.id?changedAction:i))}function addAction(addedAction){props.onChange([...actionsRef.current,addedAction]),props.setSelectedKey(addedAction.id)}function removeAction(removedAction){props.onChange(actionsRef.current.filter(i=>i!==removedAction))}return jsxs64("div",{className:PlanDefinitionBuilder_default.section,children:[props.actions.map(action=>jsx111("div",{children:jsx111(ActionBuilder,{action,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,setHoverKey:props.setHoverKey,onChange:changeAction,onRemove:()=>removeAction(action)})},action.id)),jsx111("div",{className:PlanDefinitionBuilder_default.bottomActions,children:jsx111(Anchor9,{href:"#",onClick:e=>{killEvent(e),addAction({id:generateId()})},children:"Add action"})})]})}function ActionBuilder(props){let{action}=props,actionType=getInitialActionType(action),editing=props.selectedKey===props.action.id,hovering=props.hoverKey===props.action.id;function onClick(e){e.stopPropagation(),props.setSelectedKey(props.action.id)}function onHover(e){killEvent(e),props.setHoverKey(props.action.id)}let className=clsx_default(PlanDefinitionBuilder_default.section,{[PlanDefinitionBuilder_default.editing]:editing,[PlanDefinitionBuilder_default.hovering]:hovering&&!editing});return jsxs64("div",{"data-testid":action.id,className,onClick,onMouseOver:onHover,onFocus:onHover,children:[editing?jsx111(ActionEditor,{action,actionType,onChange:props.onChange,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,setHoverKey:props.setHoverKey,onRemove:props.onRemove}):jsx111(ActionDisplay,{action,actionType}),jsx111("div",{className:PlanDefinitionBuilder_default.bottomActions,children:jsx111(Anchor9,{href:"#",onClick:e=>{e.preventDefault(),props.onRemove()},children:"Remove"})})]})}var timingProperty={path:"PlanDefinition.action.timing[x]",min:0,max:1,description:"",isArray:!1,constraints:[],type:["dateTime","Period","Range","Timing"].map(t=>({code:t}))};function ActionDisplay(props){let{action,actionType}=props,[propertyValue,propertyType]=getActionTiming(action);return jsxs64("div",{children:[jsxs64("div",{children:[action.title||"Untitled"," ",actionType&&`(${actionType})`]}),action.definitionCanonical&&jsx111("div",{children:jsx111(ReferenceDisplay,{value:{reference:action.definitionCanonical}})}),propertyValue&&jsx111("div",{children:jsx111(ResourcePropertyDisplay,{property:timingProperty,propertyType,value:propertyValue})})]})}function ActionEditor(props){let{action}=props,[actionType,setActionType]=useState56(props.actionType);function changeProperty(property,value){props.onChange({...action,[property]:value})}return jsxs64(Stack17,{gap:"xl",children:[jsx111(TextInput17,{name:`actionTitle-${action.id}`,label:"Title",defaultValue:action.title,onChange:e=>changeProperty("title",e.currentTarget.value)}),jsx111(TextInput17,{name:`actionDescription-${action.id}`,label:"Description",defaultValue:action.description,onChange:e=>changeProperty("description",e.currentTarget.value)}),jsx111(NativeSelect11,{label:"Type of Action",description:"The type of the action to be performed.",name:`actionType-${action.id}`,defaultValue:actionType,onChange:e=>setActionType(e.currentTarget.value),data:["","appointment","lab","questionnaire","task"]}),action.action&&action.action.length>0&&jsx111(ActionArrayBuilder,{actions:action.action,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,setHoverKey:props.setHoverKey,onChange:x=>changeProperty("action",x)}),(()=>{switch(actionType){case"appointment":return jsx111(ActionResourceTypeBuilder,{title:"Appointment",description:"The subject must schedule an appointment from the schedule.",resourceType:"Schedule",action,onChange:props.onChange});case"lab":return jsx111(ActionResourceTypeBuilder,{title:"Lab",description:"The subject must complete the following lab panel.",resourceType:"ActivityDefinition",action,onChange:props.onChange});case"questionnaire":return jsx111(ActionResourceTypeBuilder,{title:"Questionnaire",description:"The subject must complete the selected questionnaire.",resourceType:"Questionnaire",action,onChange:props.onChange});case"task":return jsx111(ActionResourceTypeBuilder,{title:"Task",description:"The subject must complete the following task.",resourceType:"ActivityDefinition",action,onChange:props.onChange});default:return null}})(),jsx111(FormSection,{title:"Timing",description:"When the action should take place.",children:jsx111(ActionTimingInput,{name:"timing-"+action.id,action,onChange:props.onChange})})]})}function ActionResourceTypeBuilder(props){let{id,definitionCanonical}=props.action,reference=definitionCanonical?.startsWith(props.resourceType+"/")?{reference:definitionCanonical}:void 0;return jsx111(ResourceInput,{name:id,resourceType:props.resourceType,defaultValue:reference,loadOnFocus:!0,onChange:newValue=>{newValue?props.onChange({...props.action,definitionCanonical:getReferenceString5(newValue)}):props.onChange({...props.action,definitionCanonical:void 0})}})}function ActionTimingInput(props){let value=props.action,key="timing",[propertyValue,propertyType]=getActionTiming(value);return jsx111(ResourcePropertyInput,{property:timingProperty,name:"timing[x]",path:"PlanDefinition.timing[x]",defaultValue:propertyValue,defaultPropertyType:propertyType,onChange:(newValue,propName)=>{props.onChange(setPropertyValue(value,key,propName??key,timingProperty,newValue))},outcome:void 0})}function getInitialActionType(action){if(action.definitionCanonical?.startsWith("Schedule"))return"appointment";if(action.definitionCanonical?.startsWith("Questionnaire/"))return"questionnaire";if(action.definitionCanonical?.startsWith("ActivityDefinition/"))return"task"}function getActionTiming(action){return getValueAndType({type:"PlanDefinitionAction",value:action},"timing")}var nextId=1;function generateId(existing){if(existing){if(existing.startsWith("id-")){let existingNum=parseInt(existing.substring(3),10);isNaN(existingNum)||(nextId=Math.max(nextId,existingNum+1))}return existing}return"id-"+nextId++}function ensurePlanDefinitionKeys(planDefinition){return{...planDefinition,action:ensurePlanDefinitionActionKeys(planDefinition.action)}}function ensurePlanDefinitionActionKeys(actions){if(actions)return actions.map(action=>({...action,id:generateId(action.id),action:ensurePlanDefinitionActionKeys(action.action)}))}import{Anchor as Anchor10,Box as Box9,Button as Button20,Group as Group43,NativeSelect as NativeSelect13,Space as Space2,Textarea as Textarea5,TextInput as TextInput19,Title as Title3}from"@mantine/core";import{getElementDefinition as getElementDefinition3,isResource as isResourceType}from"@medplum/core";import{useEffect as useEffect19,useRef as useRef16,useState as useState57}from"react";import{Checkbox as Checkbox3,Group as Group42,MultiSelect as MultiSelect2,NativeSelect as NativeSelect12,Radio as Radio4,Textarea as Textarea4,TextInput as TextInput18}from"@mantine/core";import{capitalize as capitalize6,deepEquals as deepEquals2,formatCodeableConcept as formatCodeableConcept4,formatCoding as formatCoding3,getElementDefinition as getElementDefinition2,getTypedPropertyValue as getTypedPropertyValue3,stringify as stringify5}from"@medplum/core";import{useContext as useContext23}from"react";import{deepClone as deepClone2,evalFhirPathTyped as evalFhirPathTyped3,formatCoding as formatCoding2,getExtension,getReferenceString as getReferenceString6,getTypedPropertyValue as getTypedPropertyValue2,splitN,stringify as stringify4}from"@medplum/core";var QuestionnaireItemType=(QuestionnaireItemType2=>(QuestionnaireItemType2.group="group",QuestionnaireItemType2.display="display",QuestionnaireItemType2.question="question",QuestionnaireItemType2.boolean="boolean",QuestionnaireItemType2.decimal="decimal",QuestionnaireItemType2.integer="integer",QuestionnaireItemType2.date="date",QuestionnaireItemType2.dateTime="dateTime",QuestionnaireItemType2.time="time",QuestionnaireItemType2.string="string",QuestionnaireItemType2.text="text",QuestionnaireItemType2.url="url",QuestionnaireItemType2.choice="choice",QuestionnaireItemType2.openChoice="open-choice",QuestionnaireItemType2.attachment="attachment",QuestionnaireItemType2.reference="reference",QuestionnaireItemType2.quantity="quantity",QuestionnaireItemType2))(QuestionnaireItemType||{});function isChoiceQuestion(item){return item.type==="choice"||item.type==="open-choice"}function isQuestionEnabled(item,responseItems){if(!item.enableWhen)return!0;let enableBehavior=item.enableBehavior??"any";for(let enableWhen of item.enableWhen){let actualAnswers=getByLinkId(responseItems,enableWhen.question);if(enableWhen.operator==="exists"&&!enableWhen.answerBoolean&&!actualAnswers?.length){if(enableBehavior==="any")return!0;continue}let{anyMatch,allMatch}=checkAnswers(enableWhen,actualAnswers,enableBehavior);if(enableBehavior==="any"&&anyMatch)return!0;if(enableBehavior==="all"&&!allMatch)return!1}return enableBehavior!=="any"}function getNewMultiSelectValues(selected,propertyName,item){return selected.map(o=>{let option=item.answerOption?.find(option2=>formatCoding2(option2.valueCoding)===o||option2[propertyName]===o),optionValue=getTypedPropertyValue2({type:"QuestionnaireItemAnswerOption",value:option},"value");return{[propertyName]:optionValue?.value}})}function getByLinkId(responseItems,linkId){if(responseItems)for(let response of responseItems){if(response.linkId===linkId)return response.answer;if(response.item){let nestedAnswer=getByLinkId(response.item,linkId);if(nestedAnswer)return nestedAnswer}}}function evaluateMatch(actualAnswer,expectedAnswer,operator){if(operator==="exists")return!!actualAnswer===expectedAnswer.value;if(actualAnswer){let fhirPathOperator=operator==="="||operator==="!="?operator?.replace("=","~"):operator,[{value}]=evalFhirPathTyped3(`%actualAnswer ${fhirPathOperator} %expectedAnswer`,[actualAnswer],{"%actualAnswer":actualAnswer,"%expectedAnswer":expectedAnswer});return value}else return!1}function checkAnswers(enableWhen,answers,enableBehavior){let actualAnswers=answers||[],expectedAnswer=getTypedPropertyValue2({type:"QuestionnaireItemEnableWhen",value:enableWhen},"answer[x]"),anyMatch=!1,allMatch=!0;for(let actualAnswerValue of actualAnswers){let actualAnswer=getTypedPropertyValue2({type:"QuestionnaireResponseItemAnswer",value:actualAnswerValue},"value[x]"),{operator}=enableWhen;if(evaluateMatch(actualAnswer,expectedAnswer,operator)?anyMatch=!0:allMatch=!1,enableBehavior==="any"&&anyMatch)break}return{anyMatch,allMatch}}function getQuestionnaireItemReferenceTargetTypes(item){let extension=getExtension(item,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");if(extension){if(extension.valueCode!==void 0)return[extension.valueCode];if(extension.valueCodeableConcept)return extension.valueCodeableConcept?.coding?.map(c=>c.code)}}function setQuestionnaireItemReferenceTargetTypes(item,targetTypes){let result=deepClone2(item),extension=getExtension(result,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource");return!targetTypes||targetTypes.length===0?(extension&&(result.extension=result.extension?.filter(e=>e!==extension)),result):(extension||(result.extension||(result.extension=[]),extension={url:"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource"},result.extension.push(extension)),targetTypes.length===1?(extension.valueCode=targetTypes[0],delete extension.valueCodeableConcept):(extension.valueCodeableConcept={coding:targetTypes.map(t=>({code:t}))},delete extension.valueCode),result)}function getQuestionnaireItemReferenceFilter(item,subject,encounter){let extension=getExtension(item,"http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter");if(!extension?.valueString)return;let filter=extension.valueString;subject?.reference&&(filter=filter.replaceAll("$subj",subject.reference)),encounter?.reference&&(filter=filter.replaceAll("$encounter",encounter.reference));let result={},parts=filter.split("&");for(let part of parts){let[key,value]=splitN(part,"=",2);result[key]=value}return result}function buildInitialResponse(questionnaire){return{resourceType:"QuestionnaireResponse",questionnaire:getReferenceString6(questionnaire),item:buildInitialResponseItems(questionnaire.item),status:"in-progress"}}function buildInitialResponseItems(items){return items?.map(buildInitialResponseItem)??[]}function buildInitialResponseItem(item){return{id:generateId2(),linkId:item.linkId,text:item.text,item:buildInitialResponseItems(item.item),answer:item.initial?.map(buildInitialResponseAnswer)??[]}}var nextId2=1;function generateId2(){return"id-"+nextId2++}function buildInitialResponseAnswer(answer){return{...answer}}function formatReferenceString(typedValue){return typedValue.value.display||typedValue.value.reference||stringify4(typedValue.value)}function getNumberOfPages(questionnaire){let firstItem=questionnaire?.item?.[0];return firstItem&&getExtension(firstItem,"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl")?.valueCodeableConcept?.coding?.[0]?.code==="page"?questionnaire.item.length:1}import{createContext as createContext2}from"react";var QuestionnaireFormContext=createContext2({});import{jsx as jsx112}from"react/jsx-runtime";function QuestionnaireFormItem(props){let context=useContext23(QuestionnaireFormContext),item=props.item,response=props.response;function onChangeAnswer(newResponseAnswer){let updatedAnswers;Array.isArray(newResponseAnswer)?updatedAnswers=newResponseAnswer:props.index>=(props.response?.answer?.length??0)?updatedAnswers=(props.response?.answer??[]).concat([newResponseAnswer]):updatedAnswers=(props.response?.answer??[]).map((a2,idx)=>idx===props.index?newResponseAnswer:a2)??[],props.onChange({id:response?.id,linkId:response?.linkId,text:item.text,answer:updatedAnswers})}let type=item.type;if(!type)return null;let name=item.linkId;if(!name)return null;let initial=item.initial&&item.initial.length>0?item.initial[0]:void 0,defaultValue2=getCurrentAnswer(response,props.index)??getTypedPropertyValue3({type:"QuestionnaireItemInitial",value:initial},"value");switch(type){case"display":return jsx112("p",{children:props.item.text},props.item.linkId);case"boolean":return jsx112(CheckboxFormSection,{title:props.item.text,htmlFor:props.item.linkId,children:jsx112(Checkbox3,{id:props.item.linkId,name:props.item.linkId,defaultChecked:defaultValue2?.value,onChange:e=>onChangeAnswer({valueBoolean:e.currentTarget.checked})})},props.item.linkId);case"decimal":return jsx112(TextInput18,{type:"number",step:"any",id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueDecimal:e.currentTarget.valueAsNumber})});case"integer":return jsx112(TextInput18,{type:"number",step:1,id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueInteger:e.currentTarget.valueAsNumber})});case"date":return jsx112(TextInput18,{type:"date",id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueDate:e.currentTarget.value})});case"dateTime":return jsx112(DateTimeInput,{name,required:item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer({valueDateTime:newValue})});case"time":return jsx112(TextInput18,{type:"time",id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueTime:e.currentTarget.value})});case"string":case"url":return jsx112(TextInput18,{id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueString:e.currentTarget.value})});case"text":return jsx112(Textarea4,{id:name,name,required:item.required,defaultValue:defaultValue2?.value,onChange:e=>onChangeAnswer({valueString:e.currentTarget.value})});case"attachment":return jsx112(Group42,{py:4,children:jsx112(AttachmentInput,{path:"",name,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer({valueAttachment:newValue})})});case"reference":return jsx112(ReferenceInput,{name,required:item.required,targetTypes:getQuestionnaireItemReferenceTargetTypes(item),searchCriteria:getQuestionnaireItemReferenceFilter(item,context.subject,context.encounter),defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer({valueReference:newValue})});case"quantity":return jsx112(QuantityInput,{path:"",name,required:item.required,defaultValue:defaultValue2?.value,onChange:newValue=>onChangeAnswer({valueQuantity:newValue}),disableWheel:!0});case"choice":case"open-choice":return isDropDownChoice(item)&&!item.answerValueSet?jsx112(QuestionnaireChoiceDropDownInput,{name,item,initial,response,onChangeAnswer:e=>onChangeAnswer(e)}):jsx112(QuestionnaireChoiceSetInput,{name,item,initial,response,onChangeAnswer:e=>onChangeAnswer(e)});default:return null}}function QuestionnaireChoiceDropDownInput(props){let{name,item,initial,response}=props;if(!item.answerOption?.length)return jsx112(NoAnswerDisplay,{});let initialValue=getTypedPropertyValue3({type:"QuestionnaireItemInitial",value:initial},"value"),data2=[""];for(let option of item.answerOption){let optionValue=getTypedPropertyValue3({type:"QuestionnaireItemAnswerOption",value:option},"value");data2.push(typedValueToString(optionValue))}let defaultValue2=getCurrentAnswer(response)??initialValue;if(item.repeats){let{propertyName,data:data3}=formatSelectData(props.item),currentAnswer=getCurrentMultiSelectAnswer(response);return jsx112(MultiSelect2,{data:data3,placeholder:"Select items",searchable:!0,defaultValue:currentAnswer||[typedValueToString(initialValue)],onChange:selected=>{let values=getNewMultiSelectValues(selected,propertyName,item);props.onChangeAnswer(values)}})}return jsx112(NativeSelect12,{id:name,name,onChange:e=>{let index=e.currentTarget.selectedIndex;if(index===0){props.onChangeAnswer({});return}let option=item.answerOption[index-1],optionValue=getTypedPropertyValue3({type:"QuestionnaireItemAnswerOption",value:option},"value"),propertyName="value"+capitalize6(optionValue.type);props.onChangeAnswer({[propertyName]:optionValue.value})},defaultValue:formatCoding3(defaultValue2?.value)||defaultValue2?.value,data:data2})}function QuestionnaireChoiceSetInput(props){let{name,item,initial,onChangeAnswer,response}=props;return!item.answerOption?.length&&!item.answerValueSet?jsx112(NoAnswerDisplay,{}):item.answerValueSet?jsx112(CodingInput,{path:"",name,binding:item.answerValueSet,onChange:code=>onChangeAnswer({valueCoding:code}),creatable:item.type==="open-choice"}):jsx112(QuestionnaireChoiceRadioInput,{name:response?.id??name,item,initial,response,onChangeAnswer})}function QuestionnaireChoiceRadioInput(props){let{name,item,initial,onChangeAnswer,response}=props,valueElementDefinition=getElementDefinition2("QuestionnaireItemAnswerOption","value[x]"),initialValue=getTypedPropertyValue3({type:"QuestionnaireItemInitial",value:initial},"value"),options=[],defaultValue2;if(item.answerOption)for(let i=0;i<item.answerOption.length;i++){let option=item.answerOption[i],optionName=`${name}-option-${i}`,optionValue=getTypedPropertyValue3({type:"QuestionnaireItemAnswerOption",value:option},"value");optionValue?.value&&(initialValue&&stringify5(optionValue)===stringify5(initialValue)&&(defaultValue2=optionName),options.push([optionName,optionValue]))}let defaultAnswer=getCurrentAnswer(response),answerLinkId=getCurrentRadioAnswer(options,defaultAnswer);return jsx112(Radio4.Group,{name,value:answerLinkId??defaultValue2,onChange:newValue=>{let option=options.find(option2=>option2[0]===newValue);if(option){let optionValue=option[1],propertyName="value"+capitalize6(optionValue.type);onChangeAnswer({[propertyName]:optionValue.value})}},children:options.map(([optionName,optionValue])=>jsx112(Radio4,{id:optionName,value:optionName,py:4,label:jsx112(ResourcePropertyDisplay,{property:valueElementDefinition,propertyType:optionValue.type,value:optionValue.value})},optionName))})}function NoAnswerDisplay(){return jsx112(TextInput18,{disabled:!0,placeholder:"No Answers Defined"})}function getItemValue(answer){return getTypedPropertyValue3({type:"QuestionnaireItemAnswer",value:answer},"value")}function getCurrentAnswer(response,index=0){let results=response.answer;return getItemValue(results?.[index]??{})}function getCurrentMultiSelectAnswer(response){let results=response.answer;return results?results.map(a2=>getItemValue(a2)).map(type=>formatCoding3(type?.value)||type?.value):[]}function getCurrentRadioAnswer(options,defaultAnswer){return options.find(option=>deepEquals2(option[1].value,defaultAnswer?.value))?.[0]}function typedValueToString(typedValue){if(typedValue)return typedValue.type==="CodeableConcept"?formatCodeableConcept4(typedValue.value):typedValue.type==="Coding"?formatCoding3(typedValue.value):typedValue.type==="Reference"?formatReferenceString(typedValue):typedValue.value.toString()}function isDropDownChoice(item){return!!item.extension?.some(e=>e.url==="http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl"&&e.valueCodeableConcept?.coding?.[0]?.code==="drop-down")}function formatSelectData(item){if(item.answerOption?.length===0)return{propertyName:"",data:[]};let option=item.answerOption[0],optionValue=getTypedPropertyValue3({type:"QuestionnaireItemAnswerOption",value:option},"value"),propertyName="value"+capitalize6(optionValue.type),data2=(item.answerOption??[]).map(a2=>({value:getValueAndLabel(a2,propertyName),label:getValueAndLabel(a2,propertyName)}));return{propertyName,data:data2}}function getValueAndLabel(option,propertyName){return formatCoding3(option.valueCoding)||option[propertyName]?.toString()}var QuestionnaireBuilder_default={section:"QuestionnaireBuilder_section",hovering:"QuestionnaireBuilder_hovering",editing:"QuestionnaireBuilder_editing",questionBody:"QuestionnaireBuilder_questionBody",topActions:"QuestionnaireBuilder_topActions",bottomActions:"QuestionnaireBuilder_bottomActions",movementActions:"QuestionnaireBuilder_movementActions",movementIcons:"QuestionnaireBuilder_movementIcons",columnAlignment:"QuestionnaireBuilder_columnAlignment",linkIdInput:"QuestionnaireBuilder_linkIdInput",typeSelect:"QuestionnaireBuilder_typeSelect"};import{Fragment as Fragment37,jsx as jsx113,jsxs as jsxs65}from"react/jsx-runtime";function QuestionnaireBuilder(props){let medplum=R(),defaultValue2=Me(props.questionnaire),[schemaLoaded,setSchemaLoaded]=useState57(!1),[value,setValue]=useState57(),[selectedKey,setSelectedKey]=useState57(),[hoverKey,setHoverKey]=useState57();function handleDocumentMouseOver(){setHoverKey(void 0)}function handleDocumentClick(){setSelectedKey(void 0)}useEffect19(()=>{medplum.requestSchema("Questionnaire").then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect19(()=>(setValue(ensureQuestionnaireKeys(defaultValue2??{resourceType:"Questionnaire",status:"active"})),document.addEventListener("mouseover",handleDocumentMouseOver),document.addEventListener("click",handleDocumentClick),()=>{document.removeEventListener("mouseover",handleDocumentMouseOver),document.removeEventListener("click",handleDocumentClick)}),[defaultValue2]);let handleChange=(questionnaire,disableSubmit)=>{setValue(questionnaire),props.autoSave&&!disableSubmit&&props.onSubmit&&props.onSubmit(questionnaire)};return!schemaLoaded||!value?null:jsx113("div",{children:jsxs65(Form,{testid:"questionnaire-form",onSubmit:()=>props.onSubmit(value),children:[jsx113(ItemBuilder,{item:value,selectedKey,setSelectedKey,hoverKey,setHoverKey,onChange:handleChange}),jsx113(Button20,{type:"submit",children:"Save"})]})})}function ItemBuilder(props){let resource=props.item,item=props.item,isResource2=isResourceType(props.item),isContainer=isResource2||item.type==="group",linkId=item.linkId??"[untitled]",editing=props.selectedKey===props.item.id,hovering=props.hoverKey===props.item.id,itemRef=useRef16();itemRef.current=props.item;function onClick(e){killEvent(e),props.setSelectedKey(props.item.id)}function onHover(e){killEvent(e),props.setHoverKey(props.item.id)}function changeItem(changedItem){let curr=itemRef.current;props.onChange({...curr,item:curr.item?.map(i=>i.id===changedItem.id?changedItem:i)})}function addItem(addedItem,disableSubmit){props.onChange({...props.item,item:[...props.item.item??[],addedItem]},disableSubmit)}function removeItem(removedItem){props.onChange({...props.item,item:props.item.item?.filter(i=>i!==removedItem)})}function changeProperty(property,value){props.onChange({...itemRef.current,[property]:value})}function updateItem(updatedItem){props.onChange({...props.item,...updatedItem})}function toggleRepeatable(item2){props.onChange({...props.item,item:props.item.item?.map(i=>i===item2?{...i,repeats:!i.repeats}:i)})}function moveItem(itemIndex,delta){let updatedItems=reorderItems(props.item.item,itemIndex,delta);props.onChange({...props.item,item:updatedItems})}let className=clsx_default(QuestionnaireBuilder_default.section,{[QuestionnaireBuilder_default.editing]:editing,[QuestionnaireBuilder_default.hovering]:hovering&&!editing});return jsxs65("div",{"data-testid":item.linkId,className,onClick,onMouseOver:onHover,onFocus:onHover,children:[jsx113("div",{className:QuestionnaireBuilder_default.questionBody,children:editing?jsxs65(Fragment37,{children:[isResource2&&jsx113(TextInput19,{size:"xl",defaultValue:resource.title,onBlur:e=>changeProperty("title",e.currentTarget.value)}),!isResource2&&jsx113(Textarea5,{autosize:!0,minRows:2,defaultValue:item.text,onBlur:e=>changeProperty("text",e.currentTarget.value)}),item.type==="reference"&&jsx113(ReferenceProfiles,{item,onChange:updateItem}),isChoiceQuestion(item)&&jsx113(AnswerBuilder,{item,onChange:item2=>updateItem(item2)})]}):jsxs65(Fragment37,{children:[resource.title&&jsx113(Title3,{children:resource.title}),item.text&&jsx113("div",{children:item.text}),!isContainer&&jsx113(QuestionnaireFormItem,{item,index:0,onChange:()=>{},response:{linkId:item.linkId}})]})}),item.item?.map((item2,i)=>jsx113("div",{children:jsx113(ItemBuilder,{item:item2,selectedKey:props.selectedKey,setSelectedKey:props.setSelectedKey,hoverKey:props.hoverKey,isFirst:i===0,isLast:i===(props.item.item??[]).length-1,setHoverKey:props.setHoverKey,onChange:changeItem,onRemove:()=>removeItem(item2),onRepeatable:toggleRepeatable,onMoveUp:()=>moveItem(i,-1),onMoveDown:()=>moveItem(i,1)})},item2.id)),!isContainer&&jsx113("div",{className:QuestionnaireBuilder_default.topActions,children:editing?jsxs65(Fragment37,{children:[jsx113(TextInput19,{size:"xs",className:QuestionnaireBuilder_default.linkIdInput,defaultValue:item.linkId,onBlur:e=>changeProperty("linkId",e.currentTarget.value)}),!isContainer&&jsx113(NativeSelect13,{size:"xs",className:QuestionnaireBuilder_default.typeSelect,defaultValue:item.type,onChange:e=>changeProperty("type",e.currentTarget.value),data:[{value:"display",label:"Display"},{value:"boolean",label:"Boolean"},{value:"decimal",label:"Decimal"},{value:"integer",label:"Integer"},{value:"date",label:"Date"},{value:"dateTime",label:"Date/Time"},{value:"time",label:"Time"},{value:"string",label:"String"},{value:"text",label:"Text"},{value:"url",label:"URL"},{value:"choice",label:"Choice"},{value:"open-choice",label:"Open Choice"},{value:"attachment",label:"Attachment"},{value:"reference",label:"Reference"},{value:"quantity",label:"Quantity"}]})]}):jsx113("div",{children:linkId})}),!isResource2&&jsx113(Box9,{className:QuestionnaireBuilder_default.movementActions,children:jsxs65(Box9,{className:QuestionnaireBuilder_default.columnAlignment,children:[!props.isFirst&&jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveUp&&props.onMoveUp()},children:jsx113(IconArrowUp,{"data-testid":"up-button",size:15,className:QuestionnaireBuilder_default.movementIcons})}),!props.isLast&&jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),props.onMoveDown&&props.onMoveDown()},children:jsx113(IconArrowDown,{"data-testid":"down-button",size:15,className:QuestionnaireBuilder_default.movementIcons})})]})}),jsxs65("div",{className:QuestionnaireBuilder_default.bottomActions,children:[isContainer&&jsxs65(Fragment37,{children:[jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId3(),linkId:generateLinkId("q"),type:"string",text:"Question"})},children:"Add item"}),jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),addItem({id:generateId3(),linkId:generateLinkId("g"),type:"group",text:"Group"},!0)},children:"Add group"})]}),isResource2&&jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),addItem(createPage(),!0)},children:"Add Page"}),editing&&!isResource2&&jsxs65(Fragment37,{children:[jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),props.onRepeatable&&props.onRepeatable(item)},children:item.repeats?"Remove Repeatable":"Make Repeatable"}),jsx113(Anchor10,{href:"#",onClick:e=>{e.preventDefault(),props.onRemove&&props.onRemove()},children:"Remove"})]})]})]})}function AnswerBuilder(props){let property=getElementDefinition3("QuestionnaireItemAnswerOption","value[x]"),options=props.item.answerOption??[];return jsxs65("div",{children:[props.item.answerValueSet!==void 0?jsx113(TextInput19,{placeholder:"Enter Value Set",defaultValue:props.item.answerValueSet,onChange:e=>props.onChange({...props.item,answerValueSet:e.target.value})}):jsx113(AnswerOptionsInput,{options,property,item:props.item,onChange:props.onChange}),jsxs65(Box9,{display:"flex",children:[jsx113(Anchor10,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerValueSet:void 0,answerOption:[...options,{id:generateId3()}]})},children:"Add choice"}),jsx113(Space2,{w:"lg"}),jsx113(Anchor10,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:[],answerValueSet:""})},children:"Add value set"})]})]})}function AnswerOptionsInput(props){return jsx113("div",{children:props.options.map(option=>{let[propertyValue,propertyType]=getValueAndType({type:"QuestionnaireItemAnswerOption",value:option},"value");return jsxs65("div",{style:{display:"flex",flexDirection:"row",justifyContent:"space-between",alignItems:"center",width:"80%"},children:[jsx113("div",{children:jsx113(ResourcePropertyInput,{name:"value[x]",path:"Questionnaire.answerOption.value[x]",property:props.property,defaultPropertyType:propertyType,defaultValue:propertyValue,onChange:(newValue,propName)=>{let newOptions=[...props.options],index=newOptions.findIndex(o=>o.id===option.id);newOptions[index]={id:option.id,[propName]:newValue},props.onChange({...props.item,answerOption:newOptions})},outcome:void 0},option.id)}),jsx113("div",{children:jsx113(Anchor10,{href:"#",onClick:e=>{killEvent(e),props.onChange({...props.item,answerOption:props.options.filter(o=>o.id!==option.id)})},children:"Remove"})})]},option.id)})})}function ReferenceProfiles(props){let targetTypes=getQuestionnaireItemReferenceTargetTypes(props.item)??[];return jsxs65(Fragment37,{children:[targetTypes.map((targetType,index)=>jsxs65(Group43,{children:[jsx113(ResourceTypeInput,{name:"resourceType",placeholder:"Resource Type",defaultValue:targetType,onChange:newValue=>{props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.map(t=>t===targetType?newValue:t)))}}),jsx113(Anchor10,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,targetTypes.filter(t=>t!==targetType)))},children:"Remove"})]},`${targetType}-${index}`)),jsx113(Anchor10,{href:"#",onClick:e=>{killEvent(e),props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item,[...targetTypes,""]))},children:"Add Resource Type"})]})}var nextLinkId=1,nextId3=1;function generateLinkId(prefix){return prefix+nextLinkId++}function generateId3(){return"id-"+nextId3++}function ensureQuestionnaireKeys(questionnaire){return{...questionnaire,id:questionnaire.id||generateId3(),item:ensureQuestionnaireItemKeys(questionnaire.item)}}function ensureQuestionnaireItemKeys(items){if(items)return items.forEach(item=>{item.id?.match(/^id-\d+$/)&&(nextId3=Math.max(nextId3,parseInt(item.id.substring(3),10)+1)),item.linkId?.match(/^q\d+$/)&&(nextLinkId=Math.max(nextLinkId,parseInt(item.linkId.substring(1),10)+1))}),items.map(item=>({...item,id:item.id||generateId3(),item:ensureQuestionnaireItemKeys(item.item),answerOption:ensureQuestionnaireOptionKeys(item.answerOption)}))}function ensureQuestionnaireOptionKeys(options){if(options)return options.map(option=>({...option,id:option.id||generateId3()}))}function createPage(){return{id:generateId3(),linkId:generateLinkId("s"),type:"group",text:"New Page",extension:[{url:"http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl",valueCodeableConcept:{coding:[{system:"http://hl7.org/fhir/questionnaire-item-control",code:"page"}]}}]}}function reorderItems(items,itemIndex,delta){let currentItems=items??[],newIndex=itemIndex+delta;if(newIndex<0||newIndex>=currentItems.length)return currentItems;let updatedItems=[...currentItems];return[updatedItems[itemIndex],updatedItems[newIndex]]=[updatedItems[newIndex],updatedItems[itemIndex]],updatedItems}import{Title as Title5}from"@mantine/core";import{createReference as createReference12,getReferenceString as getReferenceString7}from"@medplum/core";import{useCallback as useCallback21,useEffect as useEffect20,useState as useState60}from"react";import{Button as Button21,Group as Group44,Stack as Stack19,Stepper}from"@mantine/core";import{Anchor as Anchor11}from"@mantine/core";import{useState as useState58}from"react";import{jsx as jsx114,jsxs as jsxs66}from"react/jsx-runtime";function QuestionnaireRepeatableItem(props){let{item,response,onChange}=props,[number,setNumber]=useState58(getNumberOfRepeats(item,response??{linkId:item.linkId}));if(!props.checkForQuestionEnabled(item)||!response)return null;if(item.type==="display")return jsx114("p",{children:item.text},item.linkId);let showAddButton=item?.repeats&&item.type!=="choice"&&item.type!=="open-choice";return item.type==="boolean"?jsx114(QuestionnaireFormItem,{item,response,onChange:r2=>onChange([r2]),index:0},item.linkId):jsxs66(FormSection,{htmlFor:props.item.linkId,title:props.item.text,withAsterisk:props.item.required,children:[[...Array(number)].map((_2,index)=>jsx114(QuestionnaireFormItem,{item,response,onChange:r2=>onChange([r2]),index},`${item.linkId}-${index}`)),showAddButton&&jsx114(Anchor11,{onClick:()=>setNumber(n=>n+1),children:"Add Item"})]},props.item.linkId)}function getNumberOfRepeats(item,response){if(item.type==="choice"||item.type==="open-choice")return 1;let answers=response.answer;return answers?.length?answers.length:1}import{Anchor as Anchor12,Stack as Stack18,Title as Title4}from"@mantine/core";import{useState as useState59}from"react";import{Fragment as Fragment38,jsx as jsx115,jsxs as jsxs67}from"react/jsx-runtime";function QuestionnaireRepeatedGroup(props){let[responses,setResponses]=useState59(props.response);if(responses.length===0)return null;function handleRepeatableGroup(newResponseItems,index){let newResponses=responses.map((responses2,idx)=>idx===index?newResponseItems[0]:responses2);setResponses(newResponses),props.onChange(newResponses)}function insertNewGroup(){let newResponse=buildInitialResponseItem(props.item);setResponses([...responses,newResponse])}return jsxs67(Fragment38,{children:[responses.map((response,idx)=>jsx115(QuestionnaireGroup,{item:props.item,response,checkForQuestionEnabled:props.checkForQuestionEnabled,onChange:r2=>handleRepeatableGroup(r2,idx)},response.id)),props.item.repeats&&jsx115(Anchor12,{onClick:insertNewGroup,children:`Add Group: ${props.item.text}`})]})}function QuestionnaireGroup(props){let{response,checkForQuestionEnabled,onChange}=props;function onSetGroup(newResponseItem){let mergedResponse=response.item?.map(current=>newResponseItem.find(newResponse2=>newResponse2.id===current.id)??current)?.concat(newResponseItem.slice(1)),groupResponse={...response,item:mergedResponse};onChange([groupResponse])}return props.checkForQuestionEnabled(props.item)?jsxs67("div",{children:[props.item.text&&jsx115(Title4,{order:3,mb:"md",children:props.item.text}),jsx115(Stack18,{children:props.item.item?.map(item=>item.type==="group"?item.repeats?jsx115(QuestionnaireRepeatedGroup,{item,response:response.item?.filter(i=>i.linkId===item.linkId)??[],checkForQuestionEnabled,onChange:onSetGroup},item.linkId):jsx115(QuestionnaireGroup,{item,checkForQuestionEnabled,response:response.item?.find(i=>i.linkId===item.linkId)??{linkId:item.linkId},onChange:onSetGroup},item.linkId):jsx115(QuestionnaireRepeatableItem,{item,response:response.item?.find(i=>i.linkId===item.linkId),onChange:onSetGroup,checkForQuestionEnabled},item.linkId))})]},props.item.linkId):null}import{Fragment as Fragment39,jsx as jsx116,jsxs as jsxs68}from"react/jsx-runtime";function QuestionnairePageSequence(props){let{items,response,activePage,onChange,nextStep,prevStep,numberOfPages,renderPages,submitButtonText,excludeButtons,checkForQuestionEnabled}=props,form=items.map(item=>{let itemResponse=response?.item?.filter(i=>i.linkId===item.linkId)??[],repeatedItem=item.type==="group"?jsx116(QuestionnaireRepeatedGroup,{item,response:itemResponse,onChange,checkForQuestionEnabled},item.linkId):jsx116(QuestionnaireRepeatableItem,{item,response:itemResponse?.[0],onChange,checkForQuestionEnabled},item.linkId);return renderPages?jsx116(Stepper.Step,{label:item.text,children:repeatedItem},item.linkId):repeatedItem});return jsxs68(Fragment39,{children:[renderPages&&jsx116(Stepper,{active:activePage??0,allowNextStepsSelect:!1,p:6,children:form}),!renderPages&&jsx116(Stack19,{children:form}),!excludeButtons&&jsx116(ButtonGroup,{activePage:activePage??0,numberOfPages,nextStep:renderPages?nextStep:void 0,prevStep:renderPages?prevStep:void 0,renderPages,submitButtonText})]})}function ButtonGroup(props){let showBackButton=props.renderPages&&props.activePage>0,showNextButton=props.renderPages&&props.activePage<props.numberOfPages-1,showSubmitButton=!props.renderPages||props.activePage===props.numberOfPages-1;return jsxs68(Group44,{justify:"flex-end",mt:"xl",gap:"xs",children:[showBackButton&&jsx116(Button21,{onClick:props.prevStep,children:"Back"}),showNextButton&&jsx116(Button21,{onClick:e=>{let form=e.currentTarget.closest("form");props.nextStep&&form.reportValidity()&&props.nextStep()},children:"Next"}),showSubmitButton&&jsx116(Button21,{type:"submit",children:props.submitButtonText??"Submit"})]})}import{jsx as jsx117,jsxs as jsxs69}from"react/jsx-runtime";function QuestionnaireForm(props){let medplum=R(),source=medplum.getProfile(),[schemaLoaded,setSchemaLoaded]=useState60(!1),questionnaire=Me(props.questionnaire),[response,setResponse]=useState60(),[activePage,setActivePage]=useState60(0),{onChange}=props;useEffect20(()=>{medplum.requestSchema("Questionnaire").then(()=>medplum.requestSchema("QuestionnaireResponse")).then(()=>setSchemaLoaded(!0)).catch(console.log)},[medplum]),useEffect20(()=>{setResponse(questionnaire?buildInitialResponse(questionnaire):void 0)},[questionnaire]);let setItems=useCallback21(newResponseItems=>{setResponse(prevResponse=>{let currentItems=prevResponse?.item??[],newResponse={resourceType:"QuestionnaireResponse",status:"in-progress",item:mergeItems(currentItems,Array.isArray(newResponseItems)?newResponseItems:[newResponseItems])};if(onChange)try{onChange(newResponse)}catch(e){console.error("Error invoking QuestionnaireForm.onChange callback",e)}return newResponse})},[onChange]);function checkForQuestionEnabled(item){return isQuestionEnabled(item,response?.item??[])}if(!schemaLoaded||!questionnaire||!response)return null;let numberOfPages=getNumberOfPages(questionnaire),nextStep=()=>setActivePage(current=>current+1),prevStep=()=>setActivePage(current=>current-1);return jsx117(QuestionnaireFormContext.Provider,{value:{subject:props.subject,encounter:props.encounter},children:jsxs69(Form,{testid:"questionnaire-form",onSubmit:()=>{props.onSubmit&&response&&props.onSubmit({...response,questionnaire:getReferenceString7(questionnaire),subject:props.subject,source:createReference12(source),authored:new Date().toISOString(),status:"completed"})},children:[questionnaire.title&&jsx117(Title5,{children:questionnaire.title}),jsx117(QuestionnairePageSequence,{items:questionnaire.item??[],response,onChange:setItems,renderPages:!props.disablePagination&&numberOfPages>1,activePage,numberOfPages,excludeButtons:props.excludeButtons,submitButtonText:props.submitButtonText,checkForQuestionEnabled,nextStep,prevStep})]})})}function mergeIndividualItems(prevItem,newItem){let mergedNestedItems=mergeItems(prevItem.item??[],newItem.item??[]);return{...newItem,item:mergedNestedItems.length>0?mergedNestedItems:void 0,answer:newItem.answer&&newItem.answer.length>0?newItem.answer:prevItem.answer}}function mergeItems(prevItems,newItems){let result=[],usedIds=new Set;for(let prevItem of prevItems){let itemId=prevItem.id,newItem=newItems.find(item=>item.id===itemId);newItem?(result.push(mergeIndividualItems(prevItem,newItem)),usedIds.add(newItem.id)):result.push(prevItem)}for(let newItem of newItems)usedIds.has(newItem.id)||result.push(newItem);return result}import{ActionIcon as ActionIcon10,Button as Button22,Divider as Divider2,Group as Group45,NativeSelect as NativeSelect14,Stack as Stack20,Text as Text22,TextInput as TextInput20}from"@mantine/core";import{formatRange as formatRange2,getCodeBySystem}from"@medplum/core";import{useEffect as useEffect21,useState as useState61}from"react";var ReferenceRangeEditor_default={section:"ReferenceRangeEditor_section"};import{jsx as jsx118,jsxs as jsxs70}from"react/jsx-runtime";var intervalFilters=["gender","age","gestationalAge","context","appliesTo","category"],defaultProps={definition:{resourceType:"ObservationDefinition",code:{text:""}},onSubmit:()=>{}};function ReferenceRangeEditor(props){props=Object.assign(defaultProps,props);let defaultDefinition=props.definition,[intervalGroups,setIntervalGroups]=useState61([]),[groupId,setGroupId]=useState61(1),[intervalId,setIntervalId]=useState61(1);return useEffect21(()=>{let definition=ensureQualifiedIntervalKeys(defaultDefinition,setIntervalId);setIntervalGroups(groupQualifiedIntervals(definition.qualifiedInterval||[],setGroupId))},[defaultDefinition]),jsxs70(Form,{testid:"reference-range-editor",onSubmit:submitDefinition,children:[jsx118(Stack20,{children:intervalGroups.map(intervalGroup=>jsx118(ReferenceRangeGroupEditor,{unit:getUnitString(defaultDefinition.quantitativeDetails?.unit),onChange:changeInterval,onAdd:addInterval,onRemove:removeInterval,onRemoveGroup:removeGroup,intervalGroup},`group-${intervalGroup.id}`))}),jsx118(ActionIcon10,{title:"Add Group",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),addGroup({id:`group-id-${groupId}`,filters:{},intervals:[]}),setGroupId(id=>id+1)},children:jsx118(IconCirclePlus,{})}),jsx118(Group45,{justify:"flex-end",children:jsx118(Button22,{type:"submit",children:"Save"})})]});function submitDefinition(){let qualifiedInterval=intervalGroups.flatMap(group=>group.intervals).filter(interval=>!isEmptyInterval(interval));props.onSubmit({...defaultDefinition,qualifiedInterval})}function addGroup(addedGroup){setIntervalGroups(currentGroups=>[...currentGroups,addedGroup])}function removeGroup(removedGroup){setIntervalGroups(currentGroups=>currentGroups.filter(group=>group.id!==removedGroup.id))}function changeInterval(groupId2,changedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2),index=currentGroup?.intervals.findIndex(interval=>interval.id===changedInterval.id);return index!==void 0&¤tGroup?.intervals[index]&&(currentGroup.intervals[index]=changedInterval),groups})}function addInterval(groupId2,addedInterval){addedInterval.id===void 0&&(addedInterval.id=`id-${intervalId}`,setIntervalId(id=>id+1)),setIntervalGroups(groups=>{groups=[...groups];let currentGroupIndex=groups.findIndex(g=>g.id===groupId2);if(currentGroupIndex!==-1){let currentGroup={...groups[currentGroupIndex]};addedInterval={...addedInterval,...currentGroup.filters},currentGroup.intervals=[...currentGroup.intervals,addedInterval],groups[currentGroupIndex]=currentGroup}return groups})}function removeInterval(groupId2,removedInterval){setIntervalGroups(groups=>{groups=[...groups];let currentGroup=groups.find(g=>g.id===groupId2);return currentGroup&&(currentGroup.intervals=currentGroup.intervals.filter(interval=>interval.id!==removedInterval.id)),groups})}}function ReferenceRangeGroupEditor(props){let{intervalGroup,unit}=props;return jsx118(Container,{"data-testid":intervalGroup.id,className:ReferenceRangeEditor_default.section,children:jsxs70(Stack20,{gap:"lg",children:[jsx118(Group45,{justify:"flex-end",children:jsx118(ActionIcon10,{title:"Remove Group",variant:"subtle","data-testid":`remove-group-button-${intervalGroup.id}`,size:"sm",onClick:e=>{killEvent(e),props.onRemoveGroup(intervalGroup)},children:jsx118(IconCircleMinus,{})},`remove-group-button-${intervalGroup.id}`)}),jsx118(ReferenceRangeGroupFilters,{intervalGroup,onChange:props.onChange}),jsx118(Divider2,{}),intervalGroup.intervals.map(interval=>jsxs70(Stack20,{gap:"xs",children:[jsxs70(Group45,{children:[jsx118(TextInput20,{"data-testid":`condition-${interval.id}`,defaultValue:interval.condition,label:"Condition: ",size:"sm",onChange:e=>{killEvent(e),props.onChange(intervalGroup.id,{...interval,condition:e.currentTarget.value.trim()})}},`condition-${interval.id}`),jsx118(ActionIcon10,{title:"Remove Interval",variant:"subtle",size:"sm","data-testid":`remove-interval-${interval.id}`,onClick:e=>{killEvent(e),props.onRemove(intervalGroup.id,interval)},children:jsx118(IconCircleMinus,{})},`remove-interval-${interval.id}`)]}),jsx118(RangeInput,{path:"",onChange:range=>{props.onChange(intervalGroup.id,{...interval,range})},name:`range-${interval.id}`,defaultValue:interval.range},`range-${interval.id}`)]},`interval-${interval.id}`)),jsx118(ActionIcon10,{title:"Add Interval",variant:"subtle",size:"sm",onClick:e=>{killEvent(e),props.onAdd(intervalGroup.id,{range:{low:{unit},high:{unit}}})},children:jsx118(IconCirclePlus,{})})]})})}function ReferenceRangeGroupFilters(props){let{intervalGroup,onChange}=props;intervalGroup.filters.age||(intervalGroup.filters.age={});for(let key of["low","high"])intervalGroup.filters.age[key]?.unit||(intervalGroup.filters.age[key]={...intervalGroup.filters.age[key],unit:"years",system:"http://unitsofmeasure.org"});return jsxs70(Stack20,{style:{maxWidth:"50%"},children:[jsx118(Group45,{children:jsx118(NativeSelect14,{data:["","male","female"],label:"Gender:",defaultValue:intervalGroup.filters.gender||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newGender=e.currentTarget.value;newGender===""&&(newGender=void 0),onChange(intervalGroup.id,{...interval,gender:newGender})}}})}),jsxs70(Group45,{gap:"xs",children:[jsx118(Text22,{component:"label",htmlFor:`div-age-${intervalGroup.id}`,children:"Age:"}),jsx118("div",{id:`div-age-${intervalGroup.id}`,children:jsx118(RangeInput,{path:"",name:`age-${intervalGroup.id}`,defaultValue:intervalGroup.filters.age,onChange:ageRange=>{for(let interval of intervalGroup.intervals)onChange(intervalGroup.id,{...interval,age:ageRange})}},`age-${intervalGroup.id}`)})]}),jsx118(NativeSelect14,{data:["","pre-puberty","follicular","midcycle","luteal","postmenopausal"],label:"Endocrine:",defaultValue:intervalGroup.filters.context?.text||"",onChange:e=>{for(let interval of intervalGroup.intervals){let newEndocrine=e.currentTarget.value;newEndocrine===""?(newEndocrine=void 0,onChange(intervalGroup.id,{...interval,context:void 0})):onChange(intervalGroup.id,{...interval,context:{text:newEndocrine,coding:[{code:newEndocrine,system:"http://terminology.hl7.org/CodeSystem/referencerange-meaning"}]}})}}}),jsx118(NativeSelect14,{data:["","reference","critical","absolute"],label:"Category: ",defaultValue:intervalGroup.filters.category,onChange:e=>{for(let interval of intervalGroup.intervals){let newCategory=e.currentTarget.value;newCategory===""?onChange(intervalGroup.id,{...interval,category:void 0}):onChange(intervalGroup.id,{...interval,category:newCategory})}}})]})}function ensureQualifiedIntervalKeys(definition,setIntervalId){let intervals=definition.qualifiedInterval||[],nextId4=Math.max(...intervals.map(interval=>{let existingNum=parseInt(interval.id?.substring(3)||"",10);return isNaN(existingNum)?Number.NEGATIVE_INFINITY:existingNum}))+1;return Number.isFinite(nextId4)||(nextId4=1),definition={...definition,qualifiedInterval:intervals.map(interval=>({...interval,id:interval.id||`id-${nextId4++}`}))},setIntervalId(nextId4),definition}function groupQualifiedIntervals(intervals,setGroupId){let groupId=1,groups={};for(let interval of intervals){let groupKey=generateGroupKey(interval);groupKey in groups||(groups[groupKey]={id:`group-id-${groupId++}`,filters:Object.fromEntries(intervalFilters.map(f=>[f,interval[f]])),intervals:[]}),groups[groupKey].intervals.push(interval)}return setGroupId(groupId),Object.values(groups)}function generateGroupKey(interval){return[`gender=${interval.gender}`,`age=${formatRange2(interval.age)}`,`gestationalAge=${formatRange2(interval.gestationalAge)}`,`context=${interval.context?.text}`,`appliesTo=${interval.appliesTo?.map(c=>c.text).join("+")}`,`category=${interval.category}`].join(":")}function getUnitString(unit){return unit&&(getCodeBySystem(unit,"http://unitsofmeasure.org")||unit.text)}function isEmptyInterval(interval){return interval.range?.low?.value===void 0&&interval.range?.high?.value===void 0}import{Button as Button23,Grid as Grid4,Text as Text23}from"@mantine/core";import{formatDateTime as formatDateTime6,getReferenceString as getReferenceString8}from"@medplum/core";import{Fragment as Fragment40,useEffect as useEffect22,useState as useState62}from"react";import{jsx as jsx119,jsxs as jsxs71}from"react/jsx-runtime";function RequestGroupDisplay(props){let medplum=R(),requestGroup=Me(props.value),[startedLoading,setStartedLoading]=useState62(!1),[responseBundle,setResponseBundle]=useState62();if(useEffect22(()=>{requestGroup&&!startedLoading&&(medplum.executeBatch(buildBatchRequest(requestGroup)).then(setResponseBundle).catch(console.log),setStartedLoading(!0))},[medplum,requestGroup,startedLoading]),!requestGroup||!responseBundle)return null;return jsx119(Grid4,{children:requestGroup.action?.map((action,index)=>{let task=action.resource&&findBundleEntry(action.resource),taskInput=task?.input?.[0]?.valueReference,taskOutput=task?.output?.[0]?.valueReference;return jsxs71(Fragment40,{children:[jsx119(Grid4.Col,{span:1,p:"md",children:task?.status==="completed"?jsx119(IconCheckbox,{}):jsx119(IconSquare,{color:"gray"})}),jsxs71(Grid4.Col,{span:9,p:"xs",children:[jsx119(Text23,{fw:500,children:action.title}),action.description&&jsx119("div",{children:action.description}),jsxs71("div",{children:["Last edited by\xA0",jsx119(ResourceName,{value:task?.meta?.author}),"\xA0on\xA0",formatDateTime6(task?.meta?.lastUpdated)]}),jsxs71("div",{children:["Status: ",jsx119(StatusBadge,{status:task?.status||"unknown"})]})]}),jsxs71(Grid4.Col,{span:2,p:"md",children:[taskInput&&!taskOutput&&jsx119(Button23,{onClick:()=>props.onStart(task,taskInput),children:"Start"}),taskInput&&taskOutput&&jsx119(Button23,{onClick:()=>props.onEdit(task,taskInput,taskOutput),children:"Edit"})]})]},`action-${index}`)})});function buildBatchRequest(request){let batchEntries=[];if(request.action)for(let action of request.action)action.resource?.reference&&batchEntries.push({request:{method:"GET",url:action.resource.reference}});return{resourceType:"Bundle",type:"batch",entry:batchEntries}}function findBundleEntry(reference){for(let entry of responseBundle?.entry)if(entry.resource&&reference.reference===getReferenceString8(entry.resource))return entry.resource}}import{useEffect as useEffect23,useState as useState63}from"react";import{stringify as stringify6}from"@medplum/core";function diff(original,revised){let path=buildPath(original,revised);return buildRevisions(path,original,revised)}function buildPath(orig,rev){let N2=orig.length,M2=rev.length,MAX=N2+M2+1,size=1+2*MAX,middle=size/2|0,diagonal=new Array(size);diagonal[middle+1]={i:0,j:-1,prev:void 0,snake:!0};for(let d=0;d<MAX;d++){for(let k2=-d;k2<=d;k2+=2){let kmiddle=middle+k2,kplus=kmiddle+1,kminus=kmiddle-1,kplusNode=diagonal[kplus],kminusNode=diagonal[kminus],prev,i=0;k2===-d||k2!==d&&kminusNode.i<kplusNode.i?(i=kplusNode.i,prev=kplusNode):(i=kminusNode.i+1,prev=kminusNode),diagonal[kminus]=void 0;let j2=i-k2,node={i,j:j2,prev:previousSnake(prev),snake:!1};for(;i<N2&&j2<M2&&orig[i]===rev[j2];)i++,j2++;if(i>node.i&&(node={i,j:j2,prev:node,snake:!0}),diagonal[kmiddle]=node,i>=N2&&j2>=M2)return diagonal[kmiddle]}diagonal[middle+d-1]=void 0}}function buildRevisions(startNode,orig,rev){let deltas=[],path=startNode;for(path.snake&&(path=path.prev);path?.prev&&path.prev.j>=0;){let i=path.i,j2=path.j;path=path.prev;let ianchor=path.i,janchor=path.j,original={position:ianchor,lines:orig.slice(ianchor,i)},revised={position:janchor,lines:rev.slice(janchor,j2)},type;original.lines.length===0&&revised.lines.length>0?type="insert":original.lines.length>0&&revised.lines.length===0?type="delete":type="change",deltas.push({original,revised,type}),path.snake&&(path=path.prev)}return deltas}function previousSnake(node){return node&&!node.snake&&node.prev?node.prev:node}function blame(history){let versions=history.entry.filter(entry=>!!entry.resource).map(entry=>({meta:entry.resource?.meta,lines:stringify6(entry.resource,!0).match(/[^\r\n]+/g)})).sort((a2,b)=>a2.meta.lastUpdated.localeCompare(b.meta.lastUpdated)),table=versions[0].lines.map(line=>({id:versions[0].meta.versionId,meta:versions[0].meta,value:line,span:1}));return compareVersions(table,versions),combineSpans(table),table}function compareVersions(table,versions){for(let i=1;i<versions.length;i++){let revisions=diff(versions[i-1].lines,versions[i].lines);for(let revision of revisions){let position=revision.original.position,oldLines=revision.original.lines,newLines=revision.revised.lines;if((revision.type==="delete"||revision.type==="change")&&table.splice(position,oldLines.length),revision.type==="insert"||revision.type==="change")for(let k2=0;k2<revision.revised.lines.length;k2++)table.splice(position+k2,0,{id:versions[i].meta.versionId,meta:versions[i].meta,value:newLines[k2],span:1})}}}function combineSpans(table){let start=0;for(;start<table.length;){let curr=start;for(;curr<table.length&&table[curr].id===table[start].id;)table[curr].span=-1,curr++;table[start].span=curr-start,start=curr}}var ResourceBlame_default={container:"ResourceBlame_container",root:"ResourceBlame_root",startRow:"ResourceBlame_startRow",normalRow:"ResourceBlame_normalRow",author:"ResourceBlame_author",dateTime:"ResourceBlame_dateTime",lineNumber:"ResourceBlame_lineNumber",line:"ResourceBlame_line",pre:"ResourceBlame_pre"};function getVersionUrl(resource,versionId){return`/${resource.resourceType}/${resource.id}/_history/${versionId}`}function getTimeString(lastUpdated){let seconds=Math.floor((Date.now()-Date.parse(lastUpdated))/1e3),years=Math.floor(seconds/31536e3);if(years>0)return pluralizeTime(years,"year");let months=Math.floor(seconds/2592e3);if(months>0)return pluralizeTime(months,"month");let days=Math.floor(seconds/86400);if(days>0)return pluralizeTime(days,"day");let hours=Math.floor(seconds/3600);if(hours>0)return pluralizeTime(hours,"hour");let minutes=Math.floor(seconds/60);return minutes>0?pluralizeTime(minutes,"minute"):pluralizeTime(seconds,"second")}function pluralizeTime(count,noun){return`${count} ${count===1?noun:noun+"s"} ago`}import{Fragment as Fragment41,jsx as jsx120,jsxs as jsxs72}from"react/jsx-runtime";function ResourceBlame(props){let medplum=R(),[value,setValue]=useState63(props.history);if(useEffect23(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),!value)return jsx120("div",{children:"Loading..."});let resource=value.entry?.[0]?.resource;if(!resource)return null;let table=blame(value);return jsx120("div",{className:ResourceBlame_default.container,children:jsx120("table",{className:ResourceBlame_default.root,children:jsx120("tbody",{children:table.map((row,index)=>jsxs72("tr",{className:row.span>0?ResourceBlame_default.startRow:ResourceBlame_default.normalRow,children:[row.span>0&&jsxs72(Fragment41,{children:[jsx120("td",{className:ResourceBlame_default.author,rowSpan:row.span,children:jsx120(ResourceBadge,{value:row.meta.author,link:!0})}),jsx120("td",{className:ResourceBlame_default.dateTime,rowSpan:row.span,children:jsx120(MedplumLink,{to:getVersionUrl(resource,row.meta.versionId),children:getTimeString(row.meta.lastUpdated)})})]}),jsx120("td",{className:ResourceBlame_default.lineNumber,children:index+1}),jsx120("td",{className:ResourceBlame_default.line,children:jsx120("pre",{className:ResourceBlame_default.pre,children:row.value})})]},"row-"+index))})})})}import{stringify as stringify7}from"@medplum/core";var ResourceDiff_default={removed:"ResourceDiff_removed",added:"ResourceDiff_added"};import{Fragment as Fragment42,jsx as jsx121,jsxs as jsxs73}from"react/jsx-runtime";function ResourceDiff(props){let originalResource=props.original,revisedResource=props.revised;props.ignoreMeta&&(originalResource={...originalResource,meta:void 0},revisedResource={...revisedResource,meta:void 0});let original=stringify7(originalResource,!0).match(/[^\r\n]+/g),revised=stringify7(revisedResource,!0).match(/[^\r\n]+/g),deltas=diff(original,revised);return jsx121("pre",{style:{color:"gray"},children:deltas.map((delta,index)=>jsx121(ChangeDiff,{delta},"delta"+index))})}function ChangeDiff(props){return jsxs73(Fragment42,{children:["...",jsx121("br",{}),props.delta.original.lines.length>0&&jsx121("div",{className:ResourceDiff_default.removed,children:props.delta.original.lines.join(`
|
|
72
72
|
`)}),props.delta.revised.lines.length>0&&jsx121("div",{className:ResourceDiff_default.added,children:props.delta.revised.lines.join(`
|
|
73
|
-
`)}),"...",jsx121("br",{})]})}import{ActionIcon as ActionIcon11,Alert as Alert4,Button as Button24,Group as Group46,Menu as Menu6,Stack as Stack21,TextInput as TextInput21,useMantineTheme}from"@mantine/core";import{AccessPolicyInteraction as AccessPolicyInteraction2,applyDefaultValuesToResource,canWriteResourceType,isPopulated as isPopulated12,satisfiedAccessPolicy as satisfiedAccessPolicy2,tryGetProfile as tryGetProfile5}from"@medplum/core";import{useEffect as useEffect24,useMemo as useMemo28,useState as useState64}from"react";var ResourceForm_default={splitButton:"ResourceForm_splitButton",menuControl:"ResourceForm_menuControl"};import{jsx as jsx122,jsxs as jsxs74}from"react/jsx-runtime";function ResourceForm(props){let{outcome}=props,medplum=R(),defaultValue2=Me(props.defaultValue),resourceType=defaultValue2?.resourceType,[schemaLoaded,setSchemaLoaded]=useState64(!1),[value,setValue]=useState64(),accessPolicy=medplum.getAccessPolicy(),theme=useMantineTheme();useEffect24(()=>{if(defaultValue2)if(props.profileUrl){let profileUrl=props.profileUrl;medplum.requestProfileSchema(props.profileUrl,{expandProfile:!0}).then(()=>{let profile=tryGetProfile5(profileUrl);if(profile){setSchemaLoaded(!0);let modifiedDefaultValue=applyDefaultValuesToResource(defaultValue2,profile);setValue(modifiedDefaultValue)}else console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)})}else medplum.requestSchema(resourceType).then(()=>{setValue(defaultValue2),setSchemaLoaded(!0)}).catch(console.log)},[medplum,defaultValue2,resourceType,props.profileUrl]);let accessPolicyResource=useMemo28(()=>defaultValue2&&satisfiedAccessPolicy2(defaultValue2,AccessPolicyInteraction2.READ,accessPolicy),[accessPolicy,defaultValue2]),canWrite=useMemo28(()=>medplum.isSuperAdmin()||!accessPolicy||!isPopulated12(value?.resourceType)?!0:canWriteResourceType(accessPolicy,value?.resourceType),[medplum,accessPolicy,value?.resourceType]);return!schemaLoaded||!value?jsx122("div",{children:"Loading..."}):canWrite?jsxs74("form",{noValidate:!0,autoComplete:"off",onSubmit:e=>{e.preventDefault(),props.onSubmit&&props.onSubmit(value)},children:[jsxs74(Stack21,{mb:"xl",children:[jsx122(FormSection,{title:"Resource Type",htmlFor:"resourceType",outcome,children:jsx122(TextInput21,{name:"resourceType",defaultValue:value.resourceType,disabled:!0})}),jsx122(FormSection,{title:"ID",htmlFor:"id",outcome,children:jsx122(TextInput21,{name:"id",defaultValue:value.id,disabled:!0})})]}),jsx122(BackboneElementInput,{path:value.resourceType,valuePath:value.resourceType,typeName:resourceType,defaultValue:value,outcome,onChange:setValue,profileUrl:props.profileUrl,accessPolicyResource}),jsxs74(Group46,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[jsx122(Button24,{type:"submit",className:clsx_default((props.onPatch||props.onDelete)&&ResourceForm_default.splitButton),children:defaultValue2?.id?"Update":"Create"}),(props.onPatch||props.onDelete)&&jsxs74(Menu6,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[jsx122(Menu6.Target,{children:jsx122(ActionIcon11,{variant:"filled",color:theme.primaryColor,size:36,className:ResourceForm_default.menuControl,"aria-label":"More actions",children:jsx122(IconChevronDown,{size:14,stroke:1.5})})}),jsxs74(Menu6.Dropdown,{children:[props.onPatch&&jsx122(Menu6.Item,{leftSection:jsx122(IconEdit,{size:14,stroke:1.5}),onClick:()=>{props.onPatch(value)},children:"Patch"}),props.onDelete&&jsx122(Menu6.Item,{color:"red",leftSection:jsx122(IconTrash,{size:14,stroke:1.5,color:"red"}),onClick:()=>{props.onDelete(value)},children:"Delete"})]})]})]})]}):jsxs74(Alert4,{color:"red",title:"Permission denied",icon:jsx122(IconAlertCircle,{}),children:["Your access level prevents you from editing and creating ",value.resourceType," resources."]})}import{Table as Table4}from"@mantine/core";import{formatDateTime as formatDateTime7,normalizeErrorString as normalizeErrorString6}from"@medplum/core";import{useEffect as useEffect25,useState as useState65}from"react";import{jsx as jsx123,jsxs as jsxs75}from"react/jsx-runtime";function ResourceHistoryTable(props){let medplum=R(),[value,setValue]=useState65(props.history);return useEffect25(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),value?jsxs75(Table4,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[jsx123(Table4.Thead,{children:jsxs75(Table4.Tr,{children:[jsx123(Table4.Th,{children:"Author"}),jsx123(Table4.Th,{children:"Date"}),jsx123(Table4.Th,{children:"Version"})]})}),jsx123(Table4.Tbody,{children:value.entry?.map((entry,index)=>jsx123(HistoryRow,{entry},"entry-"+index))})]}):jsx123("div",{children:"Loading..."})}function HistoryRow(props){let{response,resource}=props.entry;return resource?jsxs75(Table4.Tr,{children:[jsx123(Table4.Td,{children:jsx123(ResourceBadge,{value:resource.meta?.author,link:!0})}),jsx123(Table4.Td,{children:formatDateTime7(resource.meta?.lastUpdated)}),jsx123(Table4.Td,{children:jsx123(MedplumLink,{to:getVersionUrl2(resource),children:resource.meta?.versionId})})]}):jsx123(Table4.Tr,{children:jsx123(Table4.Td,{colSpan:3,children:normalizeErrorString6(response?.outcome)})})}function getVersionUrl2(resource){return`/${resource.resourceType}/${resource.id}/_history/${resource.meta?.versionId}`}import{Button as Button25,Stack as Stack22,Text as Text24}from"@mantine/core";import{getReferenceString as getReferenceString9,isReference as isReference3}from"@medplum/core";import{useState as useState66}from"react";var Scheduler_default={container:"Scheduler_container",info:"Scheduler_info",selection:"Scheduler_selection"};import{jsx as jsx124,jsxs as jsxs76}from"react/jsx-runtime";function Scheduler(props){let schedule=Me(props.schedule),questionnaire=Me(props.questionnaire),[month,setMonth]=useState66(getStartMonth()),[date,setDate]=useState66(),[slot,setSlot]=useState66(),[response,setResponse]=useState66(),[slots]=Ne("Slot",new URLSearchParams([["_count",(30*24).toString()],["schedule",isReference3(props.schedule)?props.schedule.reference:getReferenceString9(props.schedule)],["start","gt"+getStart2(month)],["start","lt"+getEnd2(month)]]));if(!schedule||!slots||!questionnaire)return null;let actor=schedule.actor?.[0];return jsxs76("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:[jsxs76("div",{className:Scheduler_default.info,children:[actor&&jsx124(ResourceAvatar,{value:actor,size:"xl"}),actor&&jsx124(Text24,{size:"xl",fw:500,children:jsx124(ResourceName,{value:actor})}),jsx124("p",{children:"1 hour"}),date&&jsx124("p",{children:date.toLocaleDateString()}),slot&&jsx124("p",{children:formatTime(new Date(slot.start))})]}),jsxs76("div",{className:Scheduler_default.selection,children:[!date&&jsxs76("div",{children:[jsx124("h3",{children:"Select date"}),jsx124(CalendarInput,{slots,onChangeMonth:setMonth,onClick:setDate})]}),date&&!slot&&jsxs76("div",{children:[jsx124("h3",{children:"Select time"}),jsx124(Stack22,{children:slots.map(s=>{let slotStart=new Date(s.start);return slotStart.getTime()>date.getTime()&&slotStart.getTime()<date.getTime()+24*3600*1e3&&jsx124("div",{children:jsx124(Button25,{variant:"outline",style:{width:150},onClick:()=>setSlot(s),children:formatTime(slotStart)})},s.id)})})]}),date&&slot&&!response&&jsx124(QuestionnaireForm,{questionnaire,submitButtonText:"Next",onSubmit:setResponse}),date&&slot&&response&&jsxs76("div",{children:[jsx124("h3",{children:"You're all set!"}),jsx124("p",{children:"Check your email for a calendar invite."})]})]})]})}function getStart2(month){return formatSlotInstant(month.getTime())}function getEnd2(month){return formatSlotInstant(month.getTime()+31*24*60*60*1e3)}function formatSlotInstant(time){let date=new Date(Math.max(Date.now(),time));return date.setHours(0,0,0,0),date.toISOString()}function formatTime(date){return date.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}import{createReference as createReference13}from"@medplum/core";import{jsx as jsx125}from"react/jsx-runtime";function ServiceRequestTimeline(props){let{serviceRequest,...rest}=props;return jsx125(ResourceTimeline,{value:serviceRequest,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("ServiceRequest",id),medplum.search("Communication",{"based-on":ref,_count}),medplum.search("DiagnosticReport",{"based-on":ref,_count}),medplum.search("Media",{"based-on":ref,_count}),medplum.search("DocumentReference",{related:ref,_count}),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count})])},createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",basedOn:[createReference13(resource)],subject:resource.subject,sender:createReference13(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",basedOn:[createReference13(resource)],subject:resource.subject,operator:createReference13(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor13}from"@mantine/core";import{showNotification as showNotification6}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString7}from"@medplum/core";import{jsx as jsx126}from"react/jsx-runtime";function SmartAppLaunchLink(props){let medplum=R(),{client,patient,encounter,children,...rest}=props;function launchApp(){medplum.createResource({resourceType:"SmartAppLaunch",patient,encounter}).then(result=>{let url=new URL(client.launchUri);url.searchParams.set("iss",medplum.getBaseUrl()+"fhir/R4"),url.searchParams.set("launch",result.id),window.location.assign(url.toString())}).catch(err=>showNotification6({color:"red",message:normalizeErrorString7(err),autoClose:!1}))}return jsx126(Anchor13,{onClick:()=>launchApp(),...rest,children})}import{normalizeOperationOutcome as normalizeOperationOutcome6}from"@medplum/core";import{useEffect as useEffect28,useState as useState70}from"react";import{Anchor as Anchor14,Button as Button26,Center as Center4,Group as Group47,Stack as Stack23,Text as Text25,TextInput as TextInput22,Title as Title6}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useState as useState67}from"react";import{jsx as jsx127,jsxs as jsxs77}from"react/jsx-runtime";function NewProjectForm(props){let medplum=R(),[outcome,setOutcome]=useState67();return jsxs77(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}},children:[jsxs77(Center4,{style:{flexDirection:"column"},children:[jsx127(Logo,{size:32}),jsx127(Title6,{children:"Create project"})]}),jsxs77(Stack23,{gap:"xl",children:[jsx127(TextInput22,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")}),jsxs77(Text25,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx127(Anchor14,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx127(Anchor14,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]}),jsx127(Group47,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:jsx127(Button26,{type:"submit",children:"Create project"})})]})}import{Anchor as Anchor15,Button as Button27,Center as Center5,Checkbox as Checkbox4,Divider as Divider3,Group as Group48,PasswordInput,Stack as Stack24,Text as Text26,TextInput as TextInput23}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome5}from"@medplum/core";import{useEffect as useEffect27,useState as useState69}from"react";import{useEffect as useEffect26,useRef as useRef17,useState as useState68}from"react";function createScriptTag(src,onload){let head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.async=!0,script.src=src,script.onload=onload??null,head.appendChild(script)}import{jsx as jsx128}from"react/jsx-runtime";function GoogleButton(props){let medplum=R(),{googleClientId,handleGoogleCredential}=props,parentRef=useRef17(null),[scriptLoaded,setScriptLoaded]=useState68(typeof google<"u"),[initialized,setInitialized]=useState68(!1),[buttonRendered,setButtonRendered]=useState68(!1);return useEffect26(()=>{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?jsx128("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__"}}function initRecaptcha(siteKey){typeof grecaptcha>"u"&&createScriptTag("https://www.google.com/recaptcha/api.js?render="+siteKey)}function getRecaptcha(siteKey){return new Promise((resolve,reject)=>{grecaptcha.ready(async()=>{try{resolve(await grecaptcha.execute(siteKey,{action:"submit"}))}catch(err){reject(err)}})})}import{Fragment as Fragment43,jsx as jsx129,jsxs as jsxs78}from"react/jsx-runtime";function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=R(),[outcome,setOutcome]=useState69(),issues=getIssuesForExpression(outcome,void 0);return useEffect27(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsxs78(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(normalizeOperationOutcome5(err))}},children:[jsx129(Center5,{style:{flexDirection:"column"},children:props.children}),jsx129(OperationOutcomeAlert,{issues}),googleClientId&&jsxs78(Fragment43,{children:[jsx129(Group48,{justify:"center",p:"xl",style:{height:70},children:jsx129(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(normalizeOperationOutcome5(err))}}})}),jsx129(Divider3,{label:"or",labelPosition:"center",my:"lg"})]}),jsxs78(Stack24,{gap:"xl",children:[jsx129(TextInput23,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),jsx129(TextInput23,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),jsx129(TextInput23,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),jsx129(PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")}),jsxs78(Text26,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx129(Anchor15,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx129(Anchor15,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),jsxs78(Text26,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",jsx129(Anchor15,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx129(Anchor15,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]}),jsxs78(Group48,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[jsx129(Checkbox4,{name:"remember",label:"Remember me",size:"xs"}),jsx129(Button27,{type:"submit",children:"Create account"})]})]})}import{jsx as jsx130,jsxs as jsxs79}from"react/jsx-runtime";function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=R(),[login,setLogin]=useState70(),[outcome,setOutcome]=useState70();useEffect28(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome6(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 jsxs79(Document,{width:450,children:[outcome&&jsx130("pre",{children:JSON.stringify(outcome,null,2)}),!login&&jsx130(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&jsx130(NewProjectForm,{login,handleAuthResponse})]})}import{showNotification as showNotification7}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString9}from"@medplum/core";import{useCallback as useCallback23,useEffect as useEffect29,useRef as useRef18,useState as useState74}from"react";import{Anchor as Anchor16,Button as Button28,Center as Center6,Checkbox as Checkbox5,Divider as Divider4,Group as Group49,PasswordInput as PasswordInput2,Stack as Stack25,TextInput as TextInput24}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome7}from"@medplum/core";import{useCallback as useCallback22,useState as useState71}from"react";import{Fragment as Fragment44,jsx as jsx131,jsxs as jsxs80}from"react/jsx-runtime";function AuthenticationForm(props){let[email,setEmail]=useState71();return email?jsx131(PasswordForm,{email,...props}):jsx131(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=R(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=useState71(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=useCallback22(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=useCallback22(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=useCallback22(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome(normalizeOperationOutcome7(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return jsxs80(Form,{onSubmit:handleSubmit,children:[jsx131(Center6,{style:{flexDirection:"column"},children}),jsx131(OperationOutcomeAlert,{issues}),googleClientId&&jsxs80(Fragment44,{children:[jsx131(Group49,{justify:"center",p:"xl",style:{height:70},children:jsx131(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&jsx131(Divider4,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&jsx131(TextInput24,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")}),jsxs80(Group49,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[jsx131("div",{children:onRegister&&jsx131(Anchor16,{component:"button",type:"button",color:"dimmed",onClick:onRegister,size:"xs",children:"Register"})}),!disableEmailAuth&&jsx131(Button28,{type:"submit",children:"Next"})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=R(),[outcome,setOutcome]=useState71(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=useCallback22(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome7(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return jsxs80(Form,{onSubmit:handleSubmit,children:[jsx131(Center6,{style:{flexDirection:"column"},children}),jsx131(OperationOutcomeAlert,{issues}),jsx131(Stack25,{gap:"xl",children:jsx131(PasswordInput2,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password")})}),jsxs80(Group49,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[onForgotPassword&&jsx131(Anchor16,{component:"button",type:"button",c:"dimmed",onClick:onForgotPassword,size:"xs",children:"Forgot password"}),jsx131(Checkbox5,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),jsx131(Button28,{type:"submit",children:"Sign in"})]})]})}import{Avatar as Avatar3,Combobox as Combobox2,Flex as Flex4,Group as Group50,Stack as Stack26,Text as Text27,TextInput as TextInput25,Title as Title7,useCombobox as useCombobox2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome8}from"@medplum/core";import{useState as useState72}from"react";import{jsx as jsx132,jsxs as jsxs81}from"react/jsx-runtime";function ChooseProfileForm(props){let medplum=R(),combobox=useCombobox2(),[search,setSearch]=useState72(""),[outcome,setOutcome]=useState72();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(normalizeOperationOutcome8(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>jsx132(Combobox2.Option,{value:item.id,children:jsx132(SelectOption,{...item})},item.id));return jsxs81(Stack26,{children:[jsxs81(Flex4,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[jsx132(Logo,{size:32}),jsx132(Title7,{order:3,children:"Choose profile"})]}),jsx132(OperationOutcomeAlert,{outcome}),jsxs81(Combobox2,{store:combobox,onOptionSubmit:handleValueSelect,children:[jsx132(Combobox2.EventsTarget,{children:jsx132(TextInput25,{placeholder:"Search",value:search,onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),jsx132("div",{children:jsx132(Combobox2.Options,{children:options.length>0?options:jsx132(Combobox2.Empty,{children:"Nothing found..."})})})]})]})}function SelectOption(membership){return jsxs81(Group50,{children:[jsx132(Avatar3,{radius:"xl"}),jsxs81("div",{children:[jsx132(Text27,{fz:"sm",fw:500,children:membership.profile?.display}),jsx132(Text27,{fz:"xs",opacity:.6,children:membership.project?.display})]})]})}import{Button as Button29,Center as Center7,Checkbox as Checkbox6,Group as Group51,Stack as Stack27,Title as Title8}from"@mantine/core";import{jsx as jsx133,jsxs as jsxs82}from"react/jsx-runtime";function ChooseScopeForm(props){let medplum=R();return jsx133(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:jsxs82(Stack27,{children:[jsxs82(Center7,{style:{flexDirection:"column"},children:[jsx133(Logo,{size:32}),jsx133(Title8,{children:"Choose scope"})]}),jsx133(Stack27,{children:(props.scope??"openid").split(" ").map(scopeName=>jsx133(Checkbox6,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName))}),jsx133(Group51,{justify:"flex-end",mt:"xl",children:jsx133(Button29,{type:"submit",children:"Set scope"})})]})})}import{Alert as Alert5,Button as Button30,Center as Center8,Group as Group52,Stack as Stack28,TextInput as TextInput26,Title as Title9}from"@mantine/core";import{normalizeErrorString as normalizeErrorString8}from"@medplum/core";import{useState as useState73}from"react";import{jsx as jsx134,jsxs as jsxs83}from"react/jsx-runtime";function MfaForm(props){let medplum=R(),[errorMessage,setErrorMessage]=useState73();return jsx134(Form,{onSubmit:formData=>{setErrorMessage(void 0),medplum.post("auth/mfa/verify",{login:props.login,token:formData.token}).then(props.handleAuthResponse).catch(err=>setErrorMessage(normalizeErrorString8(err)))},children:jsxs83(Stack28,{children:[jsxs83(Center8,{style:{flexDirection:"column"},children:[jsx134(Logo,{size:32}),jsx134(Title9,{children:"Enter MFA code"})]}),errorMessage&&jsx134(Alert5,{icon:jsx134(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),jsx134(Stack28,{children:jsx134(TextInput26,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),jsx134(Group52,{justify:"flex-end",mt:"xl",children:jsx134(Button30,{type:"submit",children:"Submit code"})})]})})}import{jsx as jsx135}from"react/jsx-runtime";function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=R(),[login,setLogin]=useState74(),loginRequested=useRef18(!1),[mfaRequired,setAuthenticatorRequired]=useState74(!1),[memberships,setMemberships]=useState74(),handleCode=useCallback23(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>showNotification7({color:"red",message:normalizeErrorString9(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=useCallback23(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=useCallback23(response=>{handleCode(response.code)},[handleCode]);return useEffect29(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>showNotification7({color:"red",message:normalizeErrorString9(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),jsx135(Document,{width:450,px:"sm",py:"md",children:login?mfaRequired?jsx135(MfaForm,{login,handleAuthResponse}):memberships?jsx135(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.projectId==="new"?jsx135(NewProjectForm,{login,handleAuthResponse}):props.chooseScopes?jsx135(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):jsx135("div",{children:"Success"}):jsx135(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}import{ActionIcon as ActionIcon12,Group as Group53,LoadingOverlay,Paper as Paper4,ScrollArea as ScrollArea3,Skeleton,Stack as Stack29,TextInput as TextInput27,Title as Title10}from"@mantine/core";import{useResizeObserver}from"@mantine/hooks";import{showNotification as showNotification8}from"@mantine/notifications";import{getDisplayString as getDisplayString6,getReferenceString as getReferenceString10,normalizeErrorString as normalizeErrorString10}from"@medplum/core";import{useCallback as useCallback24,useEffect as useEffect30,useMemo as useMemo29,useRef as useRef19,useState as useState75}from"react";var BaseChat_default={chatPaper:"BaseChat_chatPaper",chatTitle:"BaseChat_chatTitle",chatBody:"BaseChat_chatBody",chatScrollArea:"BaseChat_chatScrollArea",chatInputContainer:"BaseChat_chatInputContainer",chatBubbleOuterWrap:"BaseChat_chatBubbleOuterWrap",chatBubbleRightAlignedInnerWrap:"BaseChat_chatBubbleRightAlignedInnerWrap",chatBubbleLeftAlignedInnerWrap:"BaseChat_chatBubbleLeftAlignedInnerWrap",chatBubble:"BaseChat_chatBubble",chatBubbleName:"BaseChat_chatBubbleName",chatBubbleNameRight:"BaseChat_chatBubbleNameRight"};import{jsx as jsx136,jsxs as jsxs84}from"react/jsx-runtime";function parseSentTime(communication){let sentTime=new Date(communication.sent??0),sentTimeMins=sentTime.getMinutes().toString();return`${sentTime.getHours()}:${sentTimeMins.length===1?"0":""}${sentTimeMins}`}function upsertCommunications(communications,received,setCommunications){let newCommunications=[...communications],foundNew=!1;for(let comm of received){let existingIdx=newCommunications.findIndex(c=>c.id===comm.id);existingIdx!==-1?newCommunications[existingIdx]=comm:(newCommunications.push(comm),foundNew=!0)}foundNew&&newCommunications.sort((a2,b)=>a2.sent.localeCompare(b.sent)),setCommunications(newCommunications)}function BaseChat(props){let{title,communications,setCommunications,query,sendMessage,onMessageReceived,inputDisabled,...paperProps}=props,medplum=R(),inputRef=useRef19(null),scrollAreaRef=useRef19(null),firstScrollRef=useRef19(!0),initialLoadRef=useRef19(!0),[profile,setProfile]=useState75(medplum.getProfile()),[reconnecting,setReconnecting]=useState75(!1),[loading,setLoading]=useState75(!0);loading||(initialLoadRef.current=!1);let profileRefStr=useMemo29(()=>profile?getReferenceString10(medplum.getProfile()):"",[profile,medplum]),searchMessages=useCallback24(async()=>{setLoading(!0);let searchParams=new URLSearchParams(query);searchParams.append("_sort","-sent");let searchResult=await medplum.searchResources("Communication",searchParams,{cache:"no-cache"});upsertCommunications(communicationsRef.current,searchResult,setCommunications),setLoading(!1)},[medplum,setCommunications,query]);useEffect30(()=>{searchMessages().catch(err=>showNotification8({color:"red",message:normalizeErrorString10(err)}))},[searchMessages]),ze(`Communication?${query}`,bundle=>{let communication=bundle.entry?.[1]?.resource;upsertCommunications(communicationsRef.current,[communication],setCommunications),onMessageReceived&&getReferenceString10(communication.sender)!==profileRefStr&&onMessageReceived(communication)},{onWebSocketClose:useCallback24(()=>{reconnecting||setReconnecting(!0),showNotification8({color:"red",message:"Live chat disconnected. Attempting to reconnect..."})},[setReconnecting,reconnecting]),onWebSocketOpen:useCallback24(()=>{reconnecting&&showNotification8({color:"green",message:"Live chat reconnected."})},[reconnecting]),onSubscriptionConnect:useCallback24(()=>{reconnecting&&(searchMessages().catch(err=>showNotification8({color:"red",message:normalizeErrorString10(err)})),setReconnecting(!1))},[reconnecting,setReconnecting,searchMessages])});let sendMessageInternal=useCallback24(formData=>{inputDisabled||(inputRef.current&&(inputRef.current.value=""),sendMessage(formData.message),scrollToBottomRef.current=!0)},[inputDisabled,sendMessage]);useEffect30(()=>{let latestProfile=medplum.getProfile();profile?.id!==latestProfile?.id&&(setProfile(latestProfile),setCommunications([]))});let[parentRef,parentRect]=useResizeObserver(),communicationsRef=useRef19(communications);communicationsRef.current=communications;let prevCommunicationsRef=useRef19(communications),scrollToBottomRef=useRef19(!0);useEffect30(()=>{communications!==prevCommunicationsRef.current&&(scrollToBottomRef.current=!0),prevCommunicationsRef.current=communications},[communications]),useEffect30(()=>{scrollToBottomRef.current&&scrollAreaRef.current?.scrollTo&&(scrollAreaRef.current.scrollTo({top:scrollAreaRef.current.scrollHeight,...firstScrollRef.current?{duration:0}:{behavior:"smooth"}}),firstScrollRef.current=!1,scrollToBottomRef.current=!1)});let myLastDeliveredId=useMemo29(()=>{let i=communications.length;for(;i--;){let comm=communications[i];if(comm.sender?.reference===profileRefStr&&comm.received)return comm.id}return""},[communications,profileRefStr]);return profile?jsxs84(Paper4,{className:BaseChat_default.chatPaper,p:0,radius:"md",...paperProps,children:[jsx136(Title10,{order:2,className:BaseChat_default.chatTitle,children:title}),jsx136("div",{className:BaseChat_default.chatBody,ref:parentRef,children:initialLoadRef.current?jsxs84(Stack29,{align:"stretch",mt:"lg",children:[jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(Skeleton,{height:38,circle:!0,ml:"md"}),jsx136(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]}),jsxs84(Group53,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ChatBubbleSkeleton,{alignment:"right",parentWidth:parentRect.width}),jsx136(Skeleton,{height:38,circle:!0,mr:"md"})]}),jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(Skeleton,{height:38,circle:!0,ml:"md"}),jsx136(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]})]},"skeleton-chat-messages"):jsxs84(ScrollArea3,{viewportRef:scrollAreaRef,className:BaseChat_default.chatScrollArea,h:parentRect.height,children:[jsx136(LoadingOverlay,{visible:loading||reconnecting,style:{width:parentRect.width,height:parentRect.height,position:"absolute",zIndex:1}}),communications.map((c,i)=>{let prevCommunication=i>0?communications[i-1]:void 0,prevCommTime=prevCommunication?parseSentTime(prevCommunication):void 0,currCommTime=parseSentTime(c);return jsxs84(Stack29,{align:"stretch",children:[(!prevCommTime||currCommTime!==prevCommTime)&&jsx136("div",{style:{textAlign:"center"},children:currCommTime}),c.sender?.reference===profileRefStr?jsxs84(Group53,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ChatBubble,{alignment:"right",communication:c,showDelivered:!!c.received&&c.id===myLastDeliveredId}),jsx136(ResourceAvatar,{radius:"xl",color:"orange",value:c.sender})]}):jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ResourceAvatar,{radius:"xl",value:c.sender}),jsx136(ChatBubble,{alignment:"left",communication:c})]})]},`${c.id}--${c.meta?.versionId??"no-version"}`)})]})}),jsx136("div",{className:BaseChat_default.chatInputContainer,children:jsx136(Form,{onSubmit:sendMessageInternal,children:jsx136(TextInput27,{ref:inputRef,name:"message",placeholder:inputDisabled?"Replies are disabled":"Type a message...",radius:"xl",rightSectionWidth:42,disabled:inputDisabled,rightSection:inputDisabled?void 0:jsx136(ActionIcon12,{type:"submit",size:"1.5rem",radius:"xl",color:"blue",variant:"filled","aria-label":"Send message",children:jsx136(IconArrowRight,{size:"1rem",stroke:1.5})})})})})]}):null}function ChatBubble(props){let{communication,alignment,showDelivered}=props,content=communication.payload?.[0]?.contentString||"",seenTime=new Date(communication.received??-1),senderResource=Me(communication.sender);return jsxs84("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx136("div",{className:clsx_default(BaseChat_default.chatBubbleName,alignment==="right"&&BaseChat_default.chatBubbleNameRight),"aria-label":"Sender name",children:senderResource?getDisplayString6(senderResource):"[Unknown sender]"}),jsx136("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx136("div",{className:BaseChat_default.chatBubble,children:content})}),showDelivered&&jsxs84("div",{style:{textAlign:"right"},children:["Delivered ",seenTime.getHours(),":",seenTime.getMinutes().toString().length===1?"0":"",seenTime.getMinutes()]})]})}function ChatBubbleSkeleton(props){let{alignment,parentWidth}=props;return jsxs84("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx136("div",{className:BaseChat_default.chatBubbleName,"aria-label":"Placeholder sender name",children:jsx136("div",{style:{position:"relative"},children:jsx136(Skeleton,{height:14,width:"100px",radius:"l",ml:alignment==="left"?"sm":void 0,style:alignment==="right"?{position:"absolute",right:5,top:-15}:void 0})})}),jsx136("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx136("div",{className:BaseChat_default.chatBubble,children:jsx136(Skeleton,{height:14,width:parentWidth*.5,radius:"l"})})})]})}import{ActionIcon as ActionIcon13}from"@mantine/core";import{useEffect as useEffect31,useState as useState76}from"react";var ChatModal_default={iconContainer:"ChatModal_iconContainer",icon:"ChatModal_icon",chatModalContainer:"ChatModal_chatModalContainer"};import{Fragment as Fragment45,jsx as jsx137,jsxs as jsxs85}from"react/jsx-runtime";function ChatModal(props){let{open,children}=props,profile=ie(),[opened,setOpened]=useState76(open??!1);return useEffect31(()=>{setOpened(prevVal=>open??prevVal)},[open]),profile?jsxs85(Fragment45,{children:[opened&&jsx137("div",{className:ChatModal_default.chatModalContainer,children}),opened?jsx137("div",{className:ChatModal_default.iconContainer,children:jsx137(ActionIcon13,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!1),"aria-label":"Close chat",children:jsx137(IconChevronDown,{size:"1.625rem"})})}):jsx137("div",{className:ChatModal_default.iconContainer,children:jsx137(ActionIcon13,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!0),"aria-label":"Open chat",children:jsx137(IconChevronUp,{size:"1.625rem"})})})]}):null}import{createReference as createReference14,formatCodeableConcept as formatCodeableConcept5,getReferenceString as getReferenceString11}from"@medplum/core";import{useCallback as useCallback25,useEffect as useEffect32,useMemo as useMemo30,useState as useState77}from"react";import{jsx as jsx138}from"react/jsx-runtime";function ThreadChat(props){let{thread,title,onMessageSent,inputDisabled}=props,medplum=R(),profile=ie(),prevThreadId=ve(thread?.id),[communications,setCommunications]=useState77([]),profileRef=useMemo30(()=>profile?createReference14(profile):void 0,[profile]),threadRef=useMemo30(()=>createReference14(thread),[thread]);useEffect32(()=>{thread?.id!==prevThreadId&&setCommunications([])},[thread?.id,prevThreadId]);let sendMessage=useCallback25(message=>{let profileRefStr=profileRef?getReferenceString11(profileRef):void 0;profileRefStr&&medplum.createResource({resourceType:"Communication",status:"in-progress",sender:profileRef,recipient:thread.recipient?.filter(ref=>getReferenceString11(ref)!==profileRefStr)??[],sent:new Date().toISOString(),payload:[{contentString:message}],partOf:[threadRef]}).then(communication=>{setCommunications([...communications,communication]),onMessageSent?.(communication)}).catch(console.error)},[medplum,profileRef,thread,threadRef,communications,onMessageSent]),onMessageReceived=useMemo30(()=>thread.recipient?.length===2?message=>{message.received&&message.status==="completed"||medplum.updateResource({...message,received:message.received??new Date().toISOString(),status:"completed"}).catch(console.error)}:void 0,[medplum,thread.recipient?.length]);return profile?jsx138(BaseChat,{title:title??(thread?.topic?formatCodeableConcept5(thread.topic):"[No thread title]"),communications,setCommunications,query:`part-of=Communication/${thread.id}`,sendMessage,onMessageReceived,inputDisabled}):null}export{AddressDisplay,AddressInput,AnnotationInput,AppShell,AsyncAutocomplete,AttachmentArrayDisplay,AttachmentArrayInput,AttachmentButton,AttachmentDisplay,AttachmentInput,BackboneElementDisplay,BackboneElementInput,BaseChat,CalendarInput,ChatModal,CheckboxFormSection,CodeInput,CodeableConceptDisplay,CodeableConceptInput,CodingDisplay,CodingInput,ContactDetailDisplay,ContactDetailInput,ContactPointDisplay,ContactPointInput,Container,DateTimeInput,DefaultResourceTimeline,DescriptionList,DescriptionListEntry,DiagnosticReportDisplay,Document,ElementDefinitionInputSelector,ElementDefinitionTypeInput,EncounterTimeline,ErrorBoundary,FhirPathTable,Form,FormSection,Header,HumanNameDisplay,HumanNameInput,IdentifierDisplay,IdentifierInput,Loading,Logo,MeasureReportDisplay,MedplumLink,de as MedplumProvider,MemoizedFhirPathTable,MemoizedSearchControl,MoneyDisplay,MoneyInput,Navbar,NoteDisplay,NotificationIcon,ObservationTable,OperationOutcomeAlert,Panel,PatientSummary,PatientTimeline,PlanDefinitionBuilder,QuantityDisplay,QuantityInput,QuestionnaireBuilder,QuestionnaireForm,QuestionnaireFormContext,QuestionnaireItemType,RangeDisplay,RangeInput,ReferenceDisplay,ReferenceInput,ReferenceRangeEditor,ReferenceRangeGroupEditor,RegisterForm,RequestGroupDisplay,ResourceArrayDisplay,ResourceArrayInput,ResourceAvatar,ResourceBadge,ResourceBlame,ResourceDiff,ResourceForm,ResourceHistoryTable,ResourceInput,ResourceName,ResourcePropertyDisplay,ResourcePropertyInput,ResourceTable,ResourceTimeline,Scheduler,SearchChangeEvent,SearchClickEvent,SearchControl,SearchFieldEditor,SearchFilterEditor,SearchLoadEvent,ServiceRequestTimeline,SignInForm,SmartAppLaunchLink,StatusBadge,ThreadChat,Timeline,TimelineItem,TimingInput,ValueSetAutocomplete,addDateFilterBetween,addField,addFilter,addLastMonthFilter,addMissingFilter,addNextMonthFilter,addThisMonthFilter,addTodayFilter,addTomorrowFilter,addYearToDateFilter,addYesterdayFilter,buildFieldNameString,buildInitialResponse,buildInitialResponseItem,clearFilters,clearFiltersOnField,convertIsoToLocal,convertLocalToIso,createScriptTag,deleteFilter,formatReferenceString,getErrorsForInput,getFieldDefinitions,getIssuesForExpression,getNewMultiSelectValues,getNumberOfPages,getOpString,getQuestionnaireItemReferenceFilter,getQuestionnaireItemReferenceTargetTypes,getRecaptcha,getSearchOperators,getSortField,getValuePath,initRecaptcha,isChoiceQuestion,isQuestionEnabled,isSortDescending,isSupportedProfileStructureDefinition,parseForm,M as reactContext,renderValue,setFilters,setOffset,setPage,setPropertyValue,setQuestionnaireItemReferenceTargetTypes,setSort,sortByDateAndPriority,toggleSort,Re as useCachedBinaryUrl,R as useMedplum,T as useMedplumContext,oe as useMedplumNavigate,ie as useMedplumProfile,ve as usePrevious,Me as useResource,ke as useSearch,Ie as useSearchOne,Ne as useSearchResources,ze as useSubscription};
|
|
73
|
+
`)}),"...",jsx121("br",{})]})}import{ActionIcon as ActionIcon11,Alert as Alert4,Button as Button24,Group as Group46,Menu as Menu6,Stack as Stack21,TextInput as TextInput21,useMantineTheme}from"@mantine/core";import{AccessPolicyInteraction as AccessPolicyInteraction2,applyDefaultValuesToResource,canWriteResourceType,isPopulated as isPopulated12,satisfiedAccessPolicy as satisfiedAccessPolicy2,tryGetProfile as tryGetProfile5}from"@medplum/core";import{useEffect as useEffect24,useMemo as useMemo28,useState as useState64}from"react";var ResourceForm_default={splitButton:"ResourceForm_splitButton",menuControl:"ResourceForm_menuControl"};import{jsx as jsx122,jsxs as jsxs74}from"react/jsx-runtime";function ResourceForm(props){let{outcome}=props,medplum=R(),defaultValue2=Me(props.defaultValue),resourceType=defaultValue2?.resourceType,[schemaLoaded,setSchemaLoaded]=useState64(!1),[value,setValue]=useState64(),accessPolicy=medplum.getAccessPolicy(),theme=useMantineTheme();useEffect24(()=>{if(defaultValue2)if(props.profileUrl){let profileUrl=props.profileUrl;medplum.requestProfileSchema(props.profileUrl,{expandProfile:!0}).then(()=>{let profile=tryGetProfile5(profileUrl);if(profile){setSchemaLoaded(!0);let modifiedDefaultValue=applyDefaultValuesToResource(defaultValue2,profile);setValue(modifiedDefaultValue)}else console.error(`Schema not found for ${profileUrl}`)}).catch(reason=>{console.error("Error in requestProfileSchema",reason)})}else medplum.requestSchema(resourceType).then(()=>{setValue(defaultValue2),setSchemaLoaded(!0)}).catch(console.log)},[medplum,defaultValue2,resourceType,props.profileUrl]);let accessPolicyResource=useMemo28(()=>defaultValue2&&satisfiedAccessPolicy2(defaultValue2,AccessPolicyInteraction2.READ,accessPolicy),[accessPolicy,defaultValue2]),canWrite=useMemo28(()=>medplum.isSuperAdmin()||!accessPolicy||!isPopulated12(value?.resourceType)?!0:canWriteResourceType(accessPolicy,value?.resourceType),[medplum,accessPolicy,value?.resourceType]);return!schemaLoaded||!value?jsx122("div",{children:"Loading..."}):canWrite?jsxs74("form",{noValidate:!0,autoComplete:"off",onSubmit:e=>{e.preventDefault(),props.onSubmit&&props.onSubmit(value)},children:[jsxs74(Stack21,{mb:"xl",children:[jsx122(FormSection,{title:"Resource Type",htmlFor:"resourceType",outcome,children:jsx122(TextInput21,{name:"resourceType",defaultValue:value.resourceType,disabled:!0})}),jsx122(FormSection,{title:"ID",htmlFor:"id",outcome,children:jsx122(TextInput21,{name:"id",defaultValue:value.id,disabled:!0})})]}),jsx122(BackboneElementInput,{path:value.resourceType,valuePath:value.resourceType,typeName:resourceType,defaultValue:value,outcome,onChange:setValue,profileUrl:props.profileUrl,accessPolicyResource}),jsxs74(Group46,{justify:"flex-end",mt:"xl",wrap:"nowrap",gap:0,children:[jsx122(Button24,{type:"submit",className:clsx_default((props.onPatch||props.onDelete)&&ResourceForm_default.splitButton),children:defaultValue2?.id?"Update":"Create"}),(props.onPatch||props.onDelete)&&jsxs74(Menu6,{transitionProps:{transition:"pop"},position:"bottom-end",withinPortal:!0,children:[jsx122(Menu6.Target,{children:jsx122(ActionIcon11,{variant:"filled",color:theme.primaryColor,size:36,className:ResourceForm_default.menuControl,"aria-label":"More actions",children:jsx122(IconChevronDown,{size:14,stroke:1.5})})}),jsxs74(Menu6.Dropdown,{children:[props.onPatch&&jsx122(Menu6.Item,{leftSection:jsx122(IconEdit,{size:14,stroke:1.5}),onClick:()=>{props.onPatch(value)},children:"Patch"}),props.onDelete&&jsx122(Menu6.Item,{color:"red",leftSection:jsx122(IconTrash,{size:14,stroke:1.5,color:"red"}),onClick:()=>{props.onDelete(value)},children:"Delete"})]})]})]})]}):jsxs74(Alert4,{color:"red",title:"Permission denied",icon:jsx122(IconAlertCircle,{}),children:["Your access level prevents you from editing and creating ",value.resourceType," resources."]})}import{Table as Table4}from"@mantine/core";import{formatDateTime as formatDateTime7,normalizeErrorString as normalizeErrorString6}from"@medplum/core";import{useEffect as useEffect25,useState as useState65}from"react";import{jsx as jsx123,jsxs as jsxs75}from"react/jsx-runtime";function ResourceHistoryTable(props){let medplum=R(),[value,setValue]=useState65(props.history);return useEffect25(()=>{!props.history&&props.resourceType&&props.id&&medplum.readHistory(props.resourceType,props.id).then(setValue).catch(console.log)},[medplum,props.history,props.resourceType,props.id]),value?jsxs75(Table4,{withTableBorder:!0,withRowBorders:!0,withColumnBorders:!0,children:[jsx123(Table4.Thead,{children:jsxs75(Table4.Tr,{children:[jsx123(Table4.Th,{children:"Author"}),jsx123(Table4.Th,{children:"Date"}),jsx123(Table4.Th,{children:"Version"})]})}),jsx123(Table4.Tbody,{children:value.entry?.map((entry,index)=>jsx123(HistoryRow,{entry},"entry-"+index))})]}):jsx123("div",{children:"Loading..."})}function HistoryRow(props){let{response,resource}=props.entry;return resource?jsxs75(Table4.Tr,{children:[jsx123(Table4.Td,{children:jsx123(ResourceBadge,{value:resource.meta?.author,link:!0})}),jsx123(Table4.Td,{children:formatDateTime7(resource.meta?.lastUpdated)}),jsx123(Table4.Td,{children:jsx123(MedplumLink,{to:getVersionUrl2(resource),children:resource.meta?.versionId})})]}):jsx123(Table4.Tr,{children:jsx123(Table4.Td,{colSpan:3,children:normalizeErrorString6(response?.outcome)})})}function getVersionUrl2(resource){return`/${resource.resourceType}/${resource.id}/_history/${resource.meta?.versionId}`}import{Button as Button25,Stack as Stack22,Text as Text24}from"@mantine/core";import{getReferenceString as getReferenceString9,isReference as isReference3}from"@medplum/core";import{useState as useState66}from"react";var Scheduler_default={container:"Scheduler_container",info:"Scheduler_info",selection:"Scheduler_selection"};import{jsx as jsx124,jsxs as jsxs76}from"react/jsx-runtime";function Scheduler(props){let schedule=Me(props.schedule),questionnaire=Me(props.questionnaire),[month,setMonth]=useState66(getStartMonth()),[date,setDate]=useState66(),[slot,setSlot]=useState66(),[response,setResponse]=useState66(),[slots]=Ne("Slot",new URLSearchParams([["_count",(30*24).toString()],["schedule",isReference3(props.schedule)?props.schedule.reference:getReferenceString9(props.schedule)],["start","gt"+getStart2(month)],["start","lt"+getEnd2(month)]]));if(!schedule||!slots||!questionnaire)return null;let actor=schedule.actor?.[0];return jsxs76("div",{className:Scheduler_default.container,"data-testid":"scheduler",children:[jsxs76("div",{className:Scheduler_default.info,children:[actor&&jsx124(ResourceAvatar,{value:actor,size:"xl"}),actor&&jsx124(Text24,{size:"xl",fw:500,children:jsx124(ResourceName,{value:actor})}),jsx124("p",{children:"1 hour"}),date&&jsx124("p",{children:date.toLocaleDateString()}),slot&&jsx124("p",{children:formatTime(new Date(slot.start))})]}),jsxs76("div",{className:Scheduler_default.selection,children:[!date&&jsxs76("div",{children:[jsx124("h3",{children:"Select date"}),jsx124(CalendarInput,{slots,onChangeMonth:setMonth,onClick:setDate})]}),date&&!slot&&jsxs76("div",{children:[jsx124("h3",{children:"Select time"}),jsx124(Stack22,{children:slots.map(s=>{let slotStart=new Date(s.start);return slotStart.getTime()>date.getTime()&&slotStart.getTime()<date.getTime()+24*3600*1e3&&jsx124("div",{children:jsx124(Button25,{variant:"outline",style:{width:150},onClick:()=>setSlot(s),children:formatTime(slotStart)})},s.id)})})]}),date&&slot&&!response&&jsx124(QuestionnaireForm,{questionnaire,submitButtonText:"Next",onSubmit:setResponse}),date&&slot&&response&&jsxs76("div",{children:[jsx124("h3",{children:"You're all set!"}),jsx124("p",{children:"Check your email for a calendar invite."})]})]})]})}function getStart2(month){return formatSlotInstant(month.getTime())}function getEnd2(month){return formatSlotInstant(month.getTime()+31*24*60*60*1e3)}function formatSlotInstant(time){let date=new Date(Math.max(Date.now(),time));return date.setHours(0,0,0,0),date.toISOString()}function formatTime(date){return date.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}import{createReference as createReference13}from"@medplum/core";import{jsx as jsx125}from"react/jsx-runtime";function ServiceRequestTimeline(props){let{serviceRequest,...rest}=props;return jsx125(ResourceTimeline,{value:serviceRequest,loadTimelineResources:async(medplum,resourceType,id)=>{let ref=`${resourceType}/${id}`,_count=100;return Promise.allSettled([medplum.readHistory("ServiceRequest",id),medplum.search("Communication",{"based-on":ref,_count}),medplum.search("DiagnosticReport",{"based-on":ref,_count}),medplum.search("Media",{"based-on":ref,_count}),medplum.search("DocumentReference",{related:ref,_count}),medplum.search("Task",{_filter:`based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`,_count})])},createCommunication:(resource,sender,text)=>({resourceType:"Communication",status:"completed",basedOn:[createReference13(resource)],subject:resource.subject,sender:createReference13(sender),sent:new Date().toISOString(),payload:[{contentString:text}]}),createMedia:(resource,operator,content)=>({resourceType:"Media",status:"completed",basedOn:[createReference13(resource)],subject:resource.subject,operator:createReference13(operator),issued:new Date().toISOString(),content}),...rest})}import{Anchor as Anchor13}from"@mantine/core";import{showNotification as showNotification6}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString7}from"@medplum/core";import{jsx as jsx126}from"react/jsx-runtime";function SmartAppLaunchLink(props){let medplum=R(),{client,patient,encounter,children,...rest}=props;function launchApp(){medplum.createResource({resourceType:"SmartAppLaunch",patient,encounter}).then(result=>{let url=new URL(client.launchUri);url.searchParams.set("iss",medplum.getBaseUrl()+"fhir/R4"),url.searchParams.set("launch",result.id),window.location.assign(url.toString())}).catch(err=>showNotification6({color:"red",message:normalizeErrorString7(err),autoClose:!1}))}return jsx126(Anchor13,{onClick:()=>launchApp(),...rest,children})}import{normalizeOperationOutcome as normalizeOperationOutcome6}from"@medplum/core";import{useEffect as useEffect28,useState as useState70}from"react";import{Anchor as Anchor14,Button as Button26,Center as Center4,Group as Group47,Stack as Stack23,Text as Text25,TextInput as TextInput22,Title as Title6}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome4}from"@medplum/core";import{useState as useState67}from"react";import{jsx as jsx127,jsxs as jsxs77}from"react/jsx-runtime";function NewProjectForm(props){let medplum=R(),[outcome,setOutcome]=useState67();return jsxs77(Form,{onSubmit:async formData=>{try{props.handleAuthResponse(await medplum.startNewProject({login:props.login,projectName:formData.projectName}))}catch(err){setOutcome(normalizeOperationOutcome4(err))}},children:[jsxs77(Center4,{style:{flexDirection:"column"},children:[jsx127(Logo,{size:32}),jsx127(Title6,{children:"Create project"})]}),jsxs77(Stack23,{gap:"xl",children:[jsx127(TextInput22,{name:"projectName",label:"Project Name",placeholder:"My Project",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"projectName")}),jsxs77(Text25,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx127(Anchor14,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx127(Anchor14,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]})]}),jsx127(Group47,{justify:"flex-end",mt:"xl",wrap:"nowrap",children:jsx127(Button26,{type:"submit",children:"Create project"})})]})}import{Anchor as Anchor15,Button as Button27,Center as Center5,Checkbox as Checkbox4,Divider as Divider3,Group as Group48,PasswordInput,Stack as Stack24,Text as Text26,TextInput as TextInput23}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome5}from"@medplum/core";import{useEffect as useEffect27,useState as useState69}from"react";import{useEffect as useEffect26,useRef as useRef17,useState as useState68}from"react";function createScriptTag(src,onload){let head=document.getElementsByTagName("head")[0],script=document.createElement("script");script.async=!0,script.src=src,script.onload=onload??null,head.appendChild(script)}import{jsx as jsx128}from"react/jsx-runtime";function GoogleButton(props){let medplum=R(),{googleClientId,handleGoogleCredential}=props,parentRef=useRef17(null),[scriptLoaded,setScriptLoaded]=useState68(typeof google<"u"),[initialized,setInitialized]=useState68(!1),[buttonRendered,setButtonRendered]=useState68(!1);return useEffect26(()=>{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?jsx128("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__"}}function initRecaptcha(siteKey){typeof grecaptcha>"u"&&createScriptTag("https://www.google.com/recaptcha/api.js?render="+siteKey)}function getRecaptcha(siteKey){return new Promise((resolve,reject)=>{grecaptcha.ready(async()=>{try{resolve(await grecaptcha.execute(siteKey,{action:"submit"}))}catch(err){reject(err)}})})}import{Fragment as Fragment43,jsx as jsx129,jsxs as jsxs78}from"react/jsx-runtime";function NewUserForm(props){let googleClientId=getGoogleClientId(props.googleClientId),recaptchaSiteKey=props.recaptchaSiteKey,medplum=R(),[outcome,setOutcome]=useState69(),issues=getIssuesForExpression(outcome,void 0);return useEffect27(()=>{recaptchaSiteKey&&initRecaptcha(recaptchaSiteKey)},[recaptchaSiteKey]),jsxs78(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(normalizeOperationOutcome5(err))}},children:[jsx129(Center5,{style:{flexDirection:"column"},children:props.children}),jsx129(OperationOutcomeAlert,{issues}),googleClientId&&jsxs78(Fragment43,{children:[jsx129(Group48,{justify:"center",p:"xl",style:{height:70},children:jsx129(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(normalizeOperationOutcome5(err))}}})}),jsx129(Divider3,{label:"or",labelPosition:"center",my:"lg"})]}),jsxs78(Stack24,{gap:"xl",children:[jsx129(TextInput23,{name:"firstName",type:"text",label:"First name",placeholder:"First name",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"firstName")}),jsx129(TextInput23,{name:"lastName",type:"text",label:"Last name",placeholder:"Last name",required:!0,error:getErrorsForInput(outcome,"lastName")}),jsx129(TextInput23,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,error:getErrorsForInput(outcome,"email")}),jsx129(PasswordInput,{name:"password",label:"Password",autoComplete:"off",required:!0,error:getErrorsForInput(outcome,"password")}),jsxs78(Text26,{c:"dimmed",size:"xs",children:["By clicking submit you agree to the Medplum"," ",jsx129(Anchor15,{href:"https://www.medplum.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx129(Anchor15,{href:"https://www.medplum.com/terms",children:"Terms\xA0of\xA0Service"}),"."]}),jsxs78(Text26,{c:"dimmed",size:"xs",children:["This site is protected by reCAPTCHA and the Google"," ",jsx129(Anchor15,{href:"https://policies.google.com/privacy",children:"Privacy\xA0Policy"})," and ",jsx129(Anchor15,{href:"https://policies.google.com/terms",children:"Terms\xA0of\xA0Service"})," apply."]})]}),jsxs78(Group48,{justify:"space-between",mt:"xl",wrap:"nowrap",children:[jsx129(Checkbox4,{name:"remember",label:"Remember me",size:"xs"}),jsx129(Button27,{type:"submit",children:"Create account"})]})]})}import{jsx as jsx130,jsxs as jsxs79}from"react/jsx-runtime";function RegisterForm(props){let{type,projectId,clientId,googleClientId,recaptchaSiteKey,onSuccess}=props,medplum=R(),[login,setLogin]=useState70(),[outcome,setOutcome]=useState70();useEffect28(()=>{type==="patient"&&login&&medplum.startNewPatient({login,projectId}).then(response=>medplum.processCode(response.code)).then(()=>onSuccess()).catch(err=>setOutcome(normalizeOperationOutcome6(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 jsxs79(Document,{width:450,children:[outcome&&jsx130("pre",{children:JSON.stringify(outcome,null,2)}),!login&&jsx130(NewUserForm,{projectId,clientId,googleClientId,recaptchaSiteKey,handleAuthResponse,children:props.children}),login&&type==="project"&&jsx130(NewProjectForm,{login,handleAuthResponse})]})}import{showNotification as showNotification7}from"@mantine/notifications";import{normalizeErrorString as normalizeErrorString9}from"@medplum/core";import{useCallback as useCallback23,useEffect as useEffect29,useRef as useRef18,useState as useState74}from"react";import{Anchor as Anchor16,Button as Button28,Center as Center6,Checkbox as Checkbox5,Divider as Divider4,Group as Group49,PasswordInput as PasswordInput2,Stack as Stack25,TextInput as TextInput24}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome7}from"@medplum/core";import{useCallback as useCallback22,useState as useState71}from"react";import{Fragment as Fragment44,jsx as jsx131,jsxs as jsxs80}from"react/jsx-runtime";function AuthenticationForm(props){let[email,setEmail]=useState71();return email?jsx131(PasswordForm,{email,...props}):jsx131(EmailForm,{setEmail,...props})}function EmailForm(props){let{setEmail,onRegister,handleAuthResponse,children,disableEmailAuth,...baseLoginRequest}=props,medplum=R(),googleClientId=!props.disableGoogleAuth&&getGoogleClientId(props.googleClientId),[outcome,setOutcome]=useState71(),issues=getIssuesForExpression(outcome,void 0),isExternalAuth=useCallback22(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=useCallback22(async formData=>{let authMethod=await medplum.post("auth/method",{email:formData.email});await isExternalAuth(authMethod)||setEmail(formData.email)},[medplum,isExternalAuth,setEmail]),handleGoogleCredential=useCallback22(async response=>{try{let authResponse=await medplum.startGoogleLogin({...baseLoginRequest,googleCredential:response.credential});await isExternalAuth(authResponse)||handleAuthResponse(authResponse)}catch(err){setOutcome(normalizeOperationOutcome7(err))}},[medplum,baseLoginRequest,isExternalAuth,handleAuthResponse]);return jsxs80(Form,{onSubmit:handleSubmit,children:[jsx131(Center6,{style:{flexDirection:"column"},children}),jsx131(OperationOutcomeAlert,{issues}),googleClientId&&jsxs80(Fragment44,{children:[jsx131(Group49,{justify:"center",p:"xl",style:{height:70},children:jsx131(GoogleButton,{googleClientId,handleGoogleCredential})}),!disableEmailAuth&&jsx131(Divider4,{label:"or",labelPosition:"center",my:"lg"})]}),!disableEmailAuth&&jsx131(TextInput24,{name:"email",type:"email",label:"Email",placeholder:"name@domain.com",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"email")}),jsxs80(Group49,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[jsx131("div",{children:onRegister&&jsx131(Anchor16,{component:"button",type:"button",color:"dimmed",onClick:onRegister,size:"xs",children:"Register"})}),!disableEmailAuth&&jsx131(Button28,{type:"submit",children:"Next"})]})]})}function PasswordForm(props){let{onForgotPassword,handleAuthResponse,children,...baseLoginRequest}=props,medplum=R(),[outcome,setOutcome]=useState71(),issues=getIssuesForExpression(outcome,void 0),handleSubmit=useCallback22(formData=>{medplum.startLogin({...baseLoginRequest,password:formData.password,remember:formData.remember==="on"}).then(handleAuthResponse).catch(err=>setOutcome(normalizeOperationOutcome7(err)))},[medplum,baseLoginRequest,handleAuthResponse]);return jsxs80(Form,{onSubmit:handleSubmit,children:[jsx131(Center6,{style:{flexDirection:"column"},children}),jsx131(OperationOutcomeAlert,{issues}),jsx131(Stack25,{gap:"xl",children:jsx131(PasswordInput2,{name:"password",label:"Password",autoComplete:"off",required:!0,autoFocus:!0,error:getErrorsForInput(outcome,"password")})}),jsxs80(Group49,{justify:"space-between",mt:"xl",gap:0,wrap:"nowrap",children:[onForgotPassword&&jsx131(Anchor16,{component:"button",type:"button",c:"dimmed",onClick:onForgotPassword,size:"xs",children:"Forgot password"}),jsx131(Checkbox5,{id:"remember",name:"remember",label:"Remember me",size:"xs",style:{lineHeight:1}}),jsx131(Button28,{type:"submit",children:"Sign in"})]})]})}import{Avatar as Avatar3,Combobox as Combobox2,Flex as Flex4,Group as Group50,Stack as Stack26,Text as Text27,TextInput as TextInput25,Title as Title7,useCombobox as useCombobox2}from"@mantine/core";import{normalizeOperationOutcome as normalizeOperationOutcome8}from"@medplum/core";import{useState as useState72}from"react";import{jsx as jsx132,jsxs as jsxs81}from"react/jsx-runtime";function ChooseProfileForm(props){let medplum=R(),combobox=useCombobox2(),[search,setSearch]=useState72(""),[outcome,setOutcome]=useState72();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(normalizeOperationOutcome8(err)))}let options=props.memberships.filter(filterMembership).slice(0,10).map(item=>jsx132(Combobox2.Option,{value:item.id,children:jsx132(SelectOption,{...item})},item.id));return jsxs81(Stack26,{children:[jsxs81(Flex4,{gap:"md",mb:"md",justify:"center",align:"center",direction:"column",wrap:"nowrap",children:[jsx132(Logo,{size:32}),jsx132(Title7,{order:3,children:"Choose profile"})]}),jsx132(OperationOutcomeAlert,{outcome}),jsxs81(Combobox2,{store:combobox,onOptionSubmit:handleValueSelect,children:[jsx132(Combobox2.EventsTarget,{children:jsx132(TextInput25,{placeholder:"Search",value:search,onChange:event=>{setSearch(event.currentTarget.value),combobox.updateSelectedOptionIndex()}})}),jsx132("div",{children:jsx132(Combobox2.Options,{children:options.length>0?options:jsx132(Combobox2.Empty,{children:"Nothing found..."})})})]})]})}function SelectOption(membership){return jsxs81(Group50,{children:[jsx132(Avatar3,{radius:"xl"}),jsxs81("div",{children:[jsx132(Text27,{fz:"sm",fw:500,children:membership.profile?.display}),jsx132(Text27,{fz:"xs",opacity:.6,children:membership.project?.display})]})]})}import{Button as Button29,Center as Center7,Checkbox as Checkbox6,Group as Group51,Stack as Stack27,Title as Title8}from"@mantine/core";import{jsx as jsx133,jsxs as jsxs82}from"react/jsx-runtime";function ChooseScopeForm(props){let medplum=R();return jsx133(Form,{onSubmit:formData=>{medplum.post("auth/scope",{login:props.login,scope:Object.keys(formData).join(" ")}).then(props.handleAuthResponse).catch(console.log)},children:jsxs82(Stack27,{children:[jsxs82(Center7,{style:{flexDirection:"column"},children:[jsx133(Logo,{size:32}),jsx133(Title8,{children:"Choose scope"})]}),jsx133(Stack27,{children:(props.scope??"openid").split(" ").map(scopeName=>jsx133(Checkbox6,{id:scopeName,name:scopeName,label:scopeName,defaultChecked:!0},scopeName))}),jsx133(Group51,{justify:"flex-end",mt:"xl",children:jsx133(Button29,{type:"submit",children:"Set scope"})})]})})}import{Alert as Alert5,Button as Button30,Center as Center8,Group as Group52,Stack as Stack28,TextInput as TextInput26,Title as Title9}from"@mantine/core";import{normalizeErrorString as normalizeErrorString8}from"@medplum/core";import{useState as useState73}from"react";import{jsx as jsx134,jsxs as jsxs83}from"react/jsx-runtime";function MfaForm(props){let medplum=R(),[errorMessage,setErrorMessage]=useState73();return jsx134(Form,{onSubmit:formData=>{setErrorMessage(void 0),medplum.post("auth/mfa/verify",{login:props.login,token:formData.token}).then(props.handleAuthResponse).catch(err=>setErrorMessage(normalizeErrorString8(err)))},children:jsxs83(Stack28,{children:[jsxs83(Center8,{style:{flexDirection:"column"},children:[jsx134(Logo,{size:32}),jsx134(Title9,{children:"Enter MFA code"})]}),errorMessage&&jsx134(Alert5,{icon:jsx134(IconAlertCircle,{size:16}),title:"Error",color:"red",children:errorMessage}),jsx134(Stack28,{children:jsx134(TextInput26,{name:"token",label:"MFA code",required:!0,autoFocus:!0})}),jsx134(Group52,{justify:"flex-end",mt:"xl",children:jsx134(Button30,{type:"submit",children:"Submit code"})})]})})}import{jsx as jsx135}from"react/jsx-runtime";function SignInForm(props){let{login:loginCode,chooseScopes,onSuccess,onForgotPassword,onRegister,onCode,...baseLoginRequest}=props,medplum=R(),[login,setLogin]=useState74(),loginRequested=useRef18(!1),[mfaRequired,setAuthenticatorRequired]=useState74(!1),[memberships,setMemberships]=useState74(),handleCode=useCallback23(code=>{onCode?onCode(code):medplum.processCode(code).then(()=>{onSuccess&&onSuccess()}).catch(err=>showNotification7({color:"red",message:normalizeErrorString9(err)}))},[medplum,onCode,onSuccess]),handleAuthResponse=useCallback23(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=useCallback23(response=>{handleCode(response.code)},[handleCode]);return useEffect29(()=>{loginCode&&!loginRequested.current&&!login&&(loginRequested.current=!0,medplum.get("auth/login/"+loginCode).then(handleAuthResponse).catch(err=>showNotification7({color:"red",message:normalizeErrorString9(err)})))},[medplum,loginCode,loginRequested,login,handleAuthResponse]),jsx135(Document,{width:450,px:"sm",py:"md",children:login?mfaRequired?jsx135(MfaForm,{login,handleAuthResponse}):memberships?jsx135(ChooseProfileForm,{login,memberships,handleAuthResponse}):props.projectId==="new"?jsx135(NewProjectForm,{login,handleAuthResponse}):props.chooseScopes?jsx135(ChooseScopeForm,{login,scope:props.scope,handleAuthResponse:handleScopeResponse}):jsx135("div",{children:"Success"}):jsx135(AuthenticationForm,{onForgotPassword,onRegister,handleAuthResponse,disableGoogleAuth:props.disableGoogleAuth,disableEmailAuth:props.disableEmailAuth,...baseLoginRequest,children:props.children})})}import{ActionIcon as ActionIcon12,Group as Group53,LoadingOverlay,Paper as Paper4,ScrollArea as ScrollArea3,Skeleton,Stack as Stack29,TextInput as TextInput27,Title as Title10}from"@mantine/core";import{useResizeObserver}from"@mantine/hooks";import{showNotification as showNotification8}from"@mantine/notifications";import{getDisplayString as getDisplayString6,getReferenceString as getReferenceString10,normalizeErrorString as normalizeErrorString10}from"@medplum/core";import{useCallback as useCallback24,useEffect as useEffect30,useMemo as useMemo29,useRef as useRef19,useState as useState75}from"react";var BaseChat_default={chatPaper:"BaseChat_chatPaper",chatTitle:"BaseChat_chatTitle",chatBody:"BaseChat_chatBody",chatScrollArea:"BaseChat_chatScrollArea",chatInputContainer:"BaseChat_chatInputContainer",chatBubbleOuterWrap:"BaseChat_chatBubbleOuterWrap",chatBubbleRightAlignedInnerWrap:"BaseChat_chatBubbleRightAlignedInnerWrap",chatBubbleLeftAlignedInnerWrap:"BaseChat_chatBubbleLeftAlignedInnerWrap",chatBubble:"BaseChat_chatBubble",chatBubbleName:"BaseChat_chatBubbleName",chatBubbleNameRight:"BaseChat_chatBubbleNameRight"};import{jsx as jsx136,jsxs as jsxs84}from"react/jsx-runtime";function parseSentTime(communication){let sentTime=new Date(communication.sent??0),sentTimeMins=sentTime.getMinutes().toString();return`${sentTime.getHours()}:${sentTimeMins.length===1?"0":""}${sentTimeMins}`}function upsertCommunications(communications,received,setCommunications){let newCommunications=[...communications],foundNew=!1;for(let comm of received){let existingIdx=newCommunications.findIndex(c=>c.id===comm.id);existingIdx!==-1?newCommunications[existingIdx]=comm:(newCommunications.push(comm),foundNew=!0)}foundNew&&newCommunications.sort((a2,b)=>a2.sent.localeCompare(b.sent)),setCommunications(newCommunications)}function BaseChat(props){let{title,communications,setCommunications,query,sendMessage,onMessageReceived,inputDisabled,...paperProps}=props,medplum=R(),inputRef=useRef19(null),scrollAreaRef=useRef19(null),firstScrollRef=useRef19(!0),initialLoadRef=useRef19(!0),[profile,setProfile]=useState75(medplum.getProfile()),[reconnecting,setReconnecting]=useState75(!1),[loading,setLoading]=useState75(!0);loading||(initialLoadRef.current=!1);let profileRefStr=useMemo29(()=>profile?getReferenceString10(medplum.getProfile()):"",[profile,medplum]),searchMessages=useCallback24(async()=>{setLoading(!0);let searchParams=new URLSearchParams(query);searchParams.append("_sort","-sent");let searchResult=await medplum.searchResources("Communication",searchParams,{cache:"no-cache"});upsertCommunications(communicationsRef.current,searchResult,setCommunications),setLoading(!1)},[medplum,setCommunications,query]);useEffect30(()=>{searchMessages().catch(err=>showNotification8({color:"red",message:normalizeErrorString10(err)}))},[searchMessages]),ze(`Communication?${query}`,bundle=>{let communication=bundle.entry?.[1]?.resource;upsertCommunications(communicationsRef.current,[communication],setCommunications),onMessageReceived&&getReferenceString10(communication.sender)!==profileRefStr&&onMessageReceived(communication)},{onWebSocketClose:useCallback24(()=>{reconnecting||setReconnecting(!0),showNotification8({color:"red",message:"Live chat disconnected. Attempting to reconnect..."})},[setReconnecting,reconnecting]),onWebSocketOpen:useCallback24(()=>{reconnecting&&showNotification8({color:"green",message:"Live chat reconnected."})},[reconnecting]),onSubscriptionConnect:useCallback24(()=>{reconnecting&&(searchMessages().catch(err=>showNotification8({color:"red",message:normalizeErrorString10(err)})),setReconnecting(!1))},[reconnecting,setReconnecting,searchMessages])});let sendMessageInternal=useCallback24(formData=>{inputDisabled||(inputRef.current&&(inputRef.current.value=""),sendMessage(formData.message),scrollToBottomRef.current=!0)},[inputDisabled,sendMessage]);useEffect30(()=>{let latestProfile=medplum.getProfile();profile?.id!==latestProfile?.id&&(setProfile(latestProfile),setCommunications([]))});let[parentRef,parentRect]=useResizeObserver(),communicationsRef=useRef19(communications);communicationsRef.current=communications;let prevCommunicationsRef=useRef19(communications),scrollToBottomRef=useRef19(!0);useEffect30(()=>{communications!==prevCommunicationsRef.current&&(scrollToBottomRef.current=!0),prevCommunicationsRef.current=communications},[communications]),useEffect30(()=>{scrollToBottomRef.current&&scrollAreaRef.current?.scrollTo&&(scrollAreaRef.current.scrollTo({top:scrollAreaRef.current.scrollHeight,...firstScrollRef.current?{duration:0}:{behavior:"smooth"}}),firstScrollRef.current=!1,scrollToBottomRef.current=!1)});let myLastDeliveredId=useMemo29(()=>{let i=communications.length;for(;i--;){let comm=communications[i];if(comm.sender?.reference===profileRefStr&&comm.received)return comm.id}return""},[communications,profileRefStr]);return profile?jsxs84(Paper4,{className:BaseChat_default.chatPaper,p:0,radius:"md",...paperProps,children:[jsx136(Title10,{order:2,className:BaseChat_default.chatTitle,children:title}),jsx136("div",{className:BaseChat_default.chatBody,ref:parentRef,children:initialLoadRef.current?jsxs84(Stack29,{align:"stretch",mt:"lg",children:[jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(Skeleton,{height:38,circle:!0,ml:"md"}),jsx136(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]}),jsxs84(Group53,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ChatBubbleSkeleton,{alignment:"right",parentWidth:parentRect.width}),jsx136(Skeleton,{height:38,circle:!0,mr:"md"})]}),jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(Skeleton,{height:38,circle:!0,ml:"md"}),jsx136(ChatBubbleSkeleton,{alignment:"left",parentWidth:parentRect.width})]})]},"skeleton-chat-messages"):jsxs84(ScrollArea3,{viewportRef:scrollAreaRef,className:BaseChat_default.chatScrollArea,h:parentRect.height,children:[jsx136(LoadingOverlay,{visible:loading||reconnecting,style:{width:parentRect.width,height:parentRect.height,position:"absolute",zIndex:1}}),communications.map((c,i)=>{let prevCommunication=i>0?communications[i-1]:void 0,prevCommTime=prevCommunication?parseSentTime(prevCommunication):void 0,currCommTime=parseSentTime(c);return jsxs84(Stack29,{align:"stretch",children:[(!prevCommTime||currCommTime!==prevCommTime)&&jsx136("div",{style:{textAlign:"center"},children:currCommTime}),c.sender?.reference===profileRefStr?jsxs84(Group53,{justify:"flex-end",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ChatBubble,{alignment:"right",communication:c,showDelivered:!!c.received&&c.id===myLastDeliveredId}),jsx136(ResourceAvatar,{radius:"xl",color:"orange",value:c.sender})]}):jsxs84(Group53,{justify:"flex-start",align:"flex-end",gap:"xs",mb:"sm",children:[jsx136(ResourceAvatar,{radius:"xl",value:c.sender}),jsx136(ChatBubble,{alignment:"left",communication:c})]})]},`${c.id}--${c.meta?.versionId??"no-version"}`)})]})}),jsx136("div",{className:BaseChat_default.chatInputContainer,children:jsx136(Form,{onSubmit:sendMessageInternal,children:jsx136(TextInput27,{ref:inputRef,name:"message",placeholder:inputDisabled?"Replies are disabled":"Type a message...",radius:"xl",rightSectionWidth:42,disabled:inputDisabled,rightSection:inputDisabled?void 0:jsx136(ActionIcon12,{type:"submit",size:"1.5rem",radius:"xl",color:"blue",variant:"filled","aria-label":"Send message",children:jsx136(IconArrowRight,{size:"1rem",stroke:1.5})})})})})]}):null}function ChatBubble(props){let{communication,alignment,showDelivered}=props,content=communication.payload?.[0]?.contentString||"",seenTime=new Date(communication.received??-1),senderResource=Me(communication.sender);return jsxs84("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx136("div",{className:clsx_default(BaseChat_default.chatBubbleName,alignment==="right"&&BaseChat_default.chatBubbleNameRight),"aria-label":"Sender name",children:senderResource?getDisplayString6(senderResource):"[Unknown sender]"}),jsx136("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx136("div",{className:BaseChat_default.chatBubble,children:content})}),showDelivered&&jsxs84("div",{style:{textAlign:"right"},children:["Delivered ",seenTime.getHours(),":",seenTime.getMinutes().toString().length===1?"0":"",seenTime.getMinutes()]})]})}function ChatBubbleSkeleton(props){let{alignment,parentWidth}=props;return jsxs84("div",{className:BaseChat_default.chatBubbleOuterWrap,children:[jsx136("div",{className:BaseChat_default.chatBubbleName,"aria-label":"Placeholder sender name",children:jsx136("div",{style:{position:"relative"},children:jsx136(Skeleton,{height:14,width:"100px",radius:"l",ml:alignment==="left"?"sm":void 0,style:alignment==="right"?{position:"absolute",right:5,top:-15}:void 0})})}),jsx136("div",{className:alignment==="left"?BaseChat_default.chatBubbleLeftAlignedInnerWrap:BaseChat_default.chatBubbleRightAlignedInnerWrap,children:jsx136("div",{className:BaseChat_default.chatBubble,children:jsx136(Skeleton,{height:14,width:parentWidth*.5,radius:"l"})})})]})}import{ActionIcon as ActionIcon13}from"@mantine/core";import{useEffect as useEffect31,useState as useState76}from"react";var ChatModal_default={iconContainer:"ChatModal_iconContainer",icon:"ChatModal_icon",chatModalContainer:"ChatModal_chatModalContainer"};import{Fragment as Fragment45,jsx as jsx137,jsxs as jsxs85}from"react/jsx-runtime";function ChatModal(props){let{open,children}=props,profile=ie(),[opened,setOpened]=useState76(open??!1);return useEffect31(()=>{setOpened(prevVal=>open??prevVal)},[open]),profile?jsxs85(Fragment45,{children:[opened&&jsx137("div",{className:ChatModal_default.chatModalContainer,children}),opened?jsx137("div",{className:ChatModal_default.iconContainer,children:jsx137(ActionIcon13,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!1),"aria-label":"Close chat",children:jsx137(IconChevronDown,{size:"1.625rem"})})}):jsx137("div",{className:ChatModal_default.iconContainer,children:jsx137(ActionIcon13,{className:ChatModal_default.icon,color:"blue",size:"lg",radius:"xl",variant:"outline",onClick:()=>setOpened(!0),"aria-label":"Open chat",children:jsx137(IconChevronUp,{size:"1.625rem"})})})]}):null}import{createReference as createReference14,formatCodeableConcept as formatCodeableConcept5,getReferenceString as getReferenceString11}from"@medplum/core";import{useCallback as useCallback25,useEffect as useEffect32,useMemo as useMemo30,useState as useState77}from"react";import{jsx as jsx138}from"react/jsx-runtime";function ThreadChat(props){let{thread,title,onMessageSent,inputDisabled}=props,medplum=R(),profile=ie(),prevThreadId=ve(thread?.id),[communications,setCommunications]=useState77([]),profileRef=useMemo30(()=>profile?createReference14(profile):void 0,[profile]),threadRef=useMemo30(()=>createReference14(thread),[thread]);useEffect32(()=>{thread?.id!==prevThreadId&&setCommunications([])},[thread?.id,prevThreadId]);let sendMessage=useCallback25(message=>{let profileRefStr=profileRef?getReferenceString11(profileRef):void 0;profileRefStr&&medplum.createResource({resourceType:"Communication",status:"in-progress",sender:profileRef,recipient:thread.recipient?.filter(ref=>getReferenceString11(ref)!==profileRefStr)??[],sent:new Date().toISOString(),payload:[{contentString:message}],partOf:[threadRef]}).then(communication=>{setCommunications([...communications,communication]),onMessageSent?.(communication)}).catch(console.error)},[medplum,profileRef,thread,threadRef,communications,onMessageSent]),onMessageReceived=useMemo30(()=>thread.recipient?.length===2?message=>{message.received&&message.status==="completed"||medplum.updateResource({...message,received:message.received??new Date().toISOString(),status:"completed"}).catch(console.error)}:void 0,[medplum,thread.recipient?.length]);return profile?jsx138(BaseChat,{title:title??(thread?.topic?formatCodeableConcept5(thread.topic):"[No thread title]"),communications,setCommunications,query:`part-of=Communication/${thread.id}`,sendMessage,onMessageReceived,inputDisabled}):null}export{AddressDisplay,AddressInput,AnnotationInput,AppShell,AsyncAutocomplete,AttachmentArrayDisplay,AttachmentArrayInput,AttachmentButton,AttachmentDisplay,AttachmentInput,BackboneElementDisplay,BackboneElementInput,BaseChat,CalendarInput,ChatModal,CheckboxFormSection,CodeInput,CodeableConceptDisplay,CodeableConceptInput,CodingDisplay,CodingInput,ContactDetailDisplay,ContactDetailInput,ContactPointDisplay,ContactPointInput,Container,DateTimeInput,DefaultResourceTimeline,DescriptionList,DescriptionListEntry,DiagnosticReportDisplay,Document,ElementDefinitionInputSelector,ElementDefinitionTypeInput,EncounterTimeline,ErrorBoundary,FhirPathTable,Form,FormSection,Header,HumanNameDisplay,HumanNameInput,IdentifierDisplay,IdentifierInput,Loading,Logo,MeasureReportDisplay,MedplumLink,de as MedplumProvider,MemoizedFhirPathTable,MemoizedSearchControl,MoneyDisplay,MoneyInput,Navbar,NoteDisplay,NotificationIcon,ObservationTable,OperationOutcomeAlert,Panel,PatientSummary,PatientTimeline,PlanDefinitionBuilder,QuantityDisplay,QuantityInput,QuestionnaireBuilder,QuestionnaireForm,QuestionnaireFormContext,QuestionnaireItemType,RangeDisplay,RangeInput,RatioInput,ReferenceDisplay,ReferenceInput,ReferenceRangeEditor,ReferenceRangeGroupEditor,RegisterForm,RequestGroupDisplay,ResourceArrayDisplay,ResourceArrayInput,ResourceAvatar,ResourceBadge,ResourceBlame,ResourceDiff,ResourceForm,ResourceHistoryTable,ResourceInput,ResourceName,ResourcePropertyDisplay,ResourcePropertyInput,ResourceTable,ResourceTimeline,Scheduler,SearchChangeEvent,SearchClickEvent,SearchControl,SearchFieldEditor,SearchFilterEditor,SearchLoadEvent,ServiceRequestTimeline,SignInForm,SmartAppLaunchLink,StatusBadge,ThreadChat,Timeline,TimelineItem,TimingInput,ValueSetAutocomplete,addDateFilterBetween,addField,addFilter,addLastMonthFilter,addMissingFilter,addNextMonthFilter,addThisMonthFilter,addTodayFilter,addTomorrowFilter,addYearToDateFilter,addYesterdayFilter,buildFieldNameString,buildInitialResponse,buildInitialResponseItem,clearFilters,clearFiltersOnField,convertIsoToLocal,convertLocalToIso,createScriptTag,deleteFilter,formatReferenceString,getErrorsForInput,getFieldDefinitions,getIssuesForExpression,getNewMultiSelectValues,getNumberOfPages,getOpString,getQuestionnaireItemReferenceFilter,getQuestionnaireItemReferenceTargetTypes,getRecaptcha,getSearchOperators,getSortField,getValuePath,initRecaptcha,isChoiceQuestion,isQuestionEnabled,isSortDescending,isSupportedProfileStructureDefinition,parseForm,M as reactContext,renderValue,setFilters,setOffset,setPage,setPropertyValue,setQuestionnaireItemReferenceTargetTypes,setSort,sortByDateAndPriority,toggleSort,Re as useCachedBinaryUrl,R as useMedplum,T as useMedplumContext,oe as useMedplumNavigate,ie as useMedplumProfile,ve as usePrevious,Me as useResource,ke as useSearch,Ie as useSearchOne,Ne as useSearchResources,ze as useSubscription};
|
|
74
74
|
/*! Bundled license information:
|
|
75
75
|
|
|
76
76
|
@tabler/icons-react/dist/esm/defaultAttributes.mjs:
|
|
77
77
|
(**
|
|
78
|
-
* @license @tabler/icons-react v3.
|
|
78
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
79
79
|
*
|
|
80
80
|
* This source code is licensed under the MIT license.
|
|
81
81
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -83,7 +83,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
83
83
|
|
|
84
84
|
@tabler/icons-react/dist/esm/createReactComponent.mjs:
|
|
85
85
|
(**
|
|
86
|
-
* @license @tabler/icons-react v3.
|
|
86
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
87
87
|
*
|
|
88
88
|
* This source code is licensed under the MIT license.
|
|
89
89
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -91,7 +91,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
91
91
|
|
|
92
92
|
@tabler/icons-react/dist/esm/icons/IconAdjustmentsHorizontal.mjs:
|
|
93
93
|
(**
|
|
94
|
-
* @license @tabler/icons-react v3.
|
|
94
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
95
95
|
*
|
|
96
96
|
* This source code is licensed under the MIT license.
|
|
97
97
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -99,7 +99,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
99
99
|
|
|
100
100
|
@tabler/icons-react/dist/esm/icons/IconAlertCircle.mjs:
|
|
101
101
|
(**
|
|
102
|
-
* @license @tabler/icons-react v3.
|
|
102
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
103
103
|
*
|
|
104
104
|
* This source code is licensed under the MIT license.
|
|
105
105
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -107,7 +107,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
107
107
|
|
|
108
108
|
@tabler/icons-react/dist/esm/icons/IconArrowDown.mjs:
|
|
109
109
|
(**
|
|
110
|
-
* @license @tabler/icons-react v3.
|
|
110
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
111
111
|
*
|
|
112
112
|
* This source code is licensed under the MIT license.
|
|
113
113
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -115,7 +115,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
115
115
|
|
|
116
116
|
@tabler/icons-react/dist/esm/icons/IconArrowRight.mjs:
|
|
117
117
|
(**
|
|
118
|
-
* @license @tabler/icons-react v3.
|
|
118
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
119
119
|
*
|
|
120
120
|
* This source code is licensed under the MIT license.
|
|
121
121
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -123,7 +123,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
123
123
|
|
|
124
124
|
@tabler/icons-react/dist/esm/icons/IconArrowUp.mjs:
|
|
125
125
|
(**
|
|
126
|
-
* @license @tabler/icons-react v3.
|
|
126
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
127
127
|
*
|
|
128
128
|
* This source code is licensed under the MIT license.
|
|
129
129
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -131,7 +131,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
131
131
|
|
|
132
132
|
@tabler/icons-react/dist/esm/icons/IconBleachOff.mjs:
|
|
133
133
|
(**
|
|
134
|
-
* @license @tabler/icons-react v3.
|
|
134
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
135
135
|
*
|
|
136
136
|
* This source code is licensed under the MIT license.
|
|
137
137
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -139,7 +139,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
139
139
|
|
|
140
140
|
@tabler/icons-react/dist/esm/icons/IconBleach.mjs:
|
|
141
141
|
(**
|
|
142
|
-
* @license @tabler/icons-react v3.
|
|
142
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
143
143
|
*
|
|
144
144
|
* This source code is licensed under the MIT license.
|
|
145
145
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -147,7 +147,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
147
147
|
|
|
148
148
|
@tabler/icons-react/dist/esm/icons/IconBoxMultiple.mjs:
|
|
149
149
|
(**
|
|
150
|
-
* @license @tabler/icons-react v3.
|
|
150
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
151
151
|
*
|
|
152
152
|
* This source code is licensed under the MIT license.
|
|
153
153
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -155,7 +155,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
155
155
|
|
|
156
156
|
@tabler/icons-react/dist/esm/icons/IconBracketsContain.mjs:
|
|
157
157
|
(**
|
|
158
|
-
* @license @tabler/icons-react v3.
|
|
158
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
159
159
|
*
|
|
160
160
|
* This source code is licensed under the MIT license.
|
|
161
161
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -163,7 +163,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
163
163
|
|
|
164
164
|
@tabler/icons-react/dist/esm/icons/IconBucketOff.mjs:
|
|
165
165
|
(**
|
|
166
|
-
* @license @tabler/icons-react v3.
|
|
166
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
167
167
|
*
|
|
168
168
|
* This source code is licensed under the MIT license.
|
|
169
169
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -171,7 +171,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
171
171
|
|
|
172
172
|
@tabler/icons-react/dist/esm/icons/IconBucket.mjs:
|
|
173
173
|
(**
|
|
174
|
-
* @license @tabler/icons-react v3.
|
|
174
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
175
175
|
*
|
|
176
176
|
* This source code is licensed under the MIT license.
|
|
177
177
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -179,7 +179,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
179
179
|
|
|
180
180
|
@tabler/icons-react/dist/esm/icons/IconCalendar.mjs:
|
|
181
181
|
(**
|
|
182
|
-
* @license @tabler/icons-react v3.
|
|
182
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
183
183
|
*
|
|
184
184
|
* This source code is licensed under the MIT license.
|
|
185
185
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -187,7 +187,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
187
187
|
|
|
188
188
|
@tabler/icons-react/dist/esm/icons/IconCheck.mjs:
|
|
189
189
|
(**
|
|
190
|
-
* @license @tabler/icons-react v3.
|
|
190
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
191
191
|
*
|
|
192
192
|
* This source code is licensed under the MIT license.
|
|
193
193
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -195,7 +195,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
195
195
|
|
|
196
196
|
@tabler/icons-react/dist/esm/icons/IconCheckbox.mjs:
|
|
197
197
|
(**
|
|
198
|
-
* @license @tabler/icons-react v3.
|
|
198
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
199
199
|
*
|
|
200
200
|
* This source code is licensed under the MIT license.
|
|
201
201
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -203,7 +203,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
203
203
|
|
|
204
204
|
@tabler/icons-react/dist/esm/icons/IconChevronDown.mjs:
|
|
205
205
|
(**
|
|
206
|
-
* @license @tabler/icons-react v3.
|
|
206
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
207
207
|
*
|
|
208
208
|
* This source code is licensed under the MIT license.
|
|
209
209
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -211,7 +211,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
211
211
|
|
|
212
212
|
@tabler/icons-react/dist/esm/icons/IconChevronUp.mjs:
|
|
213
213
|
(**
|
|
214
|
-
* @license @tabler/icons-react v3.
|
|
214
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
215
215
|
*
|
|
216
216
|
* This source code is licensed under the MIT license.
|
|
217
217
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -219,7 +219,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
219
219
|
|
|
220
220
|
@tabler/icons-react/dist/esm/icons/IconCircleMinus.mjs:
|
|
221
221
|
(**
|
|
222
|
-
* @license @tabler/icons-react v3.
|
|
222
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
223
223
|
*
|
|
224
224
|
* This source code is licensed under the MIT license.
|
|
225
225
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -227,7 +227,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
227
227
|
|
|
228
228
|
@tabler/icons-react/dist/esm/icons/IconCirclePlus.mjs:
|
|
229
229
|
(**
|
|
230
|
-
* @license @tabler/icons-react v3.
|
|
230
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
231
231
|
*
|
|
232
232
|
* This source code is licensed under the MIT license.
|
|
233
233
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -235,7 +235,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
235
235
|
|
|
236
236
|
@tabler/icons-react/dist/esm/icons/IconCloudUpload.mjs:
|
|
237
237
|
(**
|
|
238
|
-
* @license @tabler/icons-react v3.
|
|
238
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
239
239
|
*
|
|
240
240
|
* This source code is licensed under the MIT license.
|
|
241
241
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -243,7 +243,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
243
243
|
|
|
244
244
|
@tabler/icons-react/dist/esm/icons/IconColumns.mjs:
|
|
245
245
|
(**
|
|
246
|
-
* @license @tabler/icons-react v3.
|
|
246
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
247
247
|
*
|
|
248
248
|
* This source code is licensed under the MIT license.
|
|
249
249
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -251,7 +251,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
251
251
|
|
|
252
252
|
@tabler/icons-react/dist/esm/icons/IconCopy.mjs:
|
|
253
253
|
(**
|
|
254
|
-
* @license @tabler/icons-react v3.
|
|
254
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
255
255
|
*
|
|
256
256
|
* This source code is licensed under the MIT license.
|
|
257
257
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -259,7 +259,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
259
259
|
|
|
260
260
|
@tabler/icons-react/dist/esm/icons/IconCurrencyDollar.mjs:
|
|
261
261
|
(**
|
|
262
|
-
* @license @tabler/icons-react v3.
|
|
262
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
263
263
|
*
|
|
264
264
|
* This source code is licensed under the MIT license.
|
|
265
265
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -267,7 +267,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
267
267
|
|
|
268
268
|
@tabler/icons-react/dist/esm/icons/IconDots.mjs:
|
|
269
269
|
(**
|
|
270
|
-
* @license @tabler/icons-react v3.
|
|
270
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
271
271
|
*
|
|
272
272
|
* This source code is licensed under the MIT license.
|
|
273
273
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -275,7 +275,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
275
275
|
|
|
276
276
|
@tabler/icons-react/dist/esm/icons/IconEdit.mjs:
|
|
277
277
|
(**
|
|
278
|
-
* @license @tabler/icons-react v3.
|
|
278
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
279
279
|
*
|
|
280
280
|
* This source code is licensed under the MIT license.
|
|
281
281
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -283,7 +283,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
283
283
|
|
|
284
284
|
@tabler/icons-react/dist/esm/icons/IconEqualNot.mjs:
|
|
285
285
|
(**
|
|
286
|
-
* @license @tabler/icons-react v3.
|
|
286
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
287
287
|
*
|
|
288
288
|
* This source code is licensed under the MIT license.
|
|
289
289
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -291,7 +291,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
291
291
|
|
|
292
292
|
@tabler/icons-react/dist/esm/icons/IconEqual.mjs:
|
|
293
293
|
(**
|
|
294
|
-
* @license @tabler/icons-react v3.
|
|
294
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
295
295
|
*
|
|
296
296
|
* This source code is licensed under the MIT license.
|
|
297
297
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -299,7 +299,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
299
299
|
|
|
300
300
|
@tabler/icons-react/dist/esm/icons/IconFileAlert.mjs:
|
|
301
301
|
(**
|
|
302
|
-
* @license @tabler/icons-react v3.
|
|
302
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
303
303
|
*
|
|
304
304
|
* This source code is licensed under the MIT license.
|
|
305
305
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -307,7 +307,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
307
307
|
|
|
308
308
|
@tabler/icons-react/dist/esm/icons/IconFilePlus.mjs:
|
|
309
309
|
(**
|
|
310
|
-
* @license @tabler/icons-react v3.
|
|
310
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
311
311
|
*
|
|
312
312
|
* This source code is licensed under the MIT license.
|
|
313
313
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -315,7 +315,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
315
315
|
|
|
316
316
|
@tabler/icons-react/dist/esm/icons/IconFilter.mjs:
|
|
317
317
|
(**
|
|
318
|
-
* @license @tabler/icons-react v3.
|
|
318
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
319
319
|
*
|
|
320
320
|
* This source code is licensed under the MIT license.
|
|
321
321
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -323,7 +323,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
323
323
|
|
|
324
324
|
@tabler/icons-react/dist/esm/icons/IconGenderFemale.mjs:
|
|
325
325
|
(**
|
|
326
|
-
* @license @tabler/icons-react v3.
|
|
326
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
327
327
|
*
|
|
328
328
|
* This source code is licensed under the MIT license.
|
|
329
329
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -331,7 +331,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
331
331
|
|
|
332
332
|
@tabler/icons-react/dist/esm/icons/IconGenderMale.mjs:
|
|
333
333
|
(**
|
|
334
|
-
* @license @tabler/icons-react v3.
|
|
334
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
335
335
|
*
|
|
336
336
|
* This source code is licensed under the MIT license.
|
|
337
337
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -339,7 +339,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
339
339
|
|
|
340
340
|
@tabler/icons-react/dist/esm/icons/IconLogout.mjs:
|
|
341
341
|
(**
|
|
342
|
-
* @license @tabler/icons-react v3.
|
|
342
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
343
343
|
*
|
|
344
344
|
* This source code is licensed under the MIT license.
|
|
345
345
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -347,7 +347,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
347
347
|
|
|
348
348
|
@tabler/icons-react/dist/esm/icons/IconMathGreater.mjs:
|
|
349
349
|
(**
|
|
350
|
-
* @license @tabler/icons-react v3.
|
|
350
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
351
351
|
*
|
|
352
352
|
* This source code is licensed under the MIT license.
|
|
353
353
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -355,7 +355,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
355
355
|
|
|
356
356
|
@tabler/icons-react/dist/esm/icons/IconMathLower.mjs:
|
|
357
357
|
(**
|
|
358
|
-
* @license @tabler/icons-react v3.
|
|
358
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
359
359
|
*
|
|
360
360
|
* This source code is licensed under the MIT license.
|
|
361
361
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -363,7 +363,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
363
363
|
|
|
364
364
|
@tabler/icons-react/dist/esm/icons/IconMessage.mjs:
|
|
365
365
|
(**
|
|
366
|
-
* @license @tabler/icons-react v3.
|
|
366
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
367
367
|
*
|
|
368
368
|
* This source code is licensed under the MIT license.
|
|
369
369
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -371,7 +371,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
371
371
|
|
|
372
372
|
@tabler/icons-react/dist/esm/icons/IconPlus.mjs:
|
|
373
373
|
(**
|
|
374
|
-
* @license @tabler/icons-react v3.
|
|
374
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
375
375
|
*
|
|
376
376
|
* This source code is licensed under the MIT license.
|
|
377
377
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -379,7 +379,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
379
379
|
|
|
380
380
|
@tabler/icons-react/dist/esm/icons/IconRefresh.mjs:
|
|
381
381
|
(**
|
|
382
|
-
* @license @tabler/icons-react v3.
|
|
382
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
383
383
|
*
|
|
384
384
|
* This source code is licensed under the MIT license.
|
|
385
385
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -387,7 +387,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
387
387
|
|
|
388
388
|
@tabler/icons-react/dist/esm/icons/IconSearch.mjs:
|
|
389
389
|
(**
|
|
390
|
-
* @license @tabler/icons-react v3.
|
|
390
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
391
391
|
*
|
|
392
392
|
* This source code is licensed under the MIT license.
|
|
393
393
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -395,7 +395,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
395
395
|
|
|
396
396
|
@tabler/icons-react/dist/esm/icons/IconSettings.mjs:
|
|
397
397
|
(**
|
|
398
|
-
* @license @tabler/icons-react v3.
|
|
398
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
399
399
|
*
|
|
400
400
|
* This source code is licensed under the MIT license.
|
|
401
401
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -403,7 +403,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
403
403
|
|
|
404
404
|
@tabler/icons-react/dist/esm/icons/IconSortAscending.mjs:
|
|
405
405
|
(**
|
|
406
|
-
* @license @tabler/icons-react v3.
|
|
406
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
407
407
|
*
|
|
408
408
|
* This source code is licensed under the MIT license.
|
|
409
409
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -411,7 +411,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
411
411
|
|
|
412
412
|
@tabler/icons-react/dist/esm/icons/IconSortDescending.mjs:
|
|
413
413
|
(**
|
|
414
|
-
* @license @tabler/icons-react v3.
|
|
414
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
415
415
|
*
|
|
416
416
|
* This source code is licensed under the MIT license.
|
|
417
417
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -419,7 +419,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
419
419
|
|
|
420
420
|
@tabler/icons-react/dist/esm/icons/IconSquare.mjs:
|
|
421
421
|
(**
|
|
422
|
-
* @license @tabler/icons-react v3.
|
|
422
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
423
423
|
*
|
|
424
424
|
* This source code is licensed under the MIT license.
|
|
425
425
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -427,7 +427,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
427
427
|
|
|
428
428
|
@tabler/icons-react/dist/esm/icons/IconStethoscope.mjs:
|
|
429
429
|
(**
|
|
430
|
-
* @license @tabler/icons-react v3.
|
|
430
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
431
431
|
*
|
|
432
432
|
* This source code is licensed under the MIT license.
|
|
433
433
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -435,7 +435,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
435
435
|
|
|
436
436
|
@tabler/icons-react/dist/esm/icons/IconSwitchHorizontal.mjs:
|
|
437
437
|
(**
|
|
438
|
-
* @license @tabler/icons-react v3.
|
|
438
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
439
439
|
*
|
|
440
440
|
* This source code is licensed under the MIT license.
|
|
441
441
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -443,7 +443,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
443
443
|
|
|
444
444
|
@tabler/icons-react/dist/esm/icons/IconTableExport.mjs:
|
|
445
445
|
(**
|
|
446
|
-
* @license @tabler/icons-react v3.
|
|
446
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
447
447
|
*
|
|
448
448
|
* This source code is licensed under the MIT license.
|
|
449
449
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -451,7 +451,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
451
451
|
|
|
452
452
|
@tabler/icons-react/dist/esm/icons/IconTrash.mjs:
|
|
453
453
|
(**
|
|
454
|
-
* @license @tabler/icons-react v3.
|
|
454
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
455
455
|
*
|
|
456
456
|
* This source code is licensed under the MIT license.
|
|
457
457
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -459,7 +459,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
459
459
|
|
|
460
460
|
@tabler/icons-react/dist/esm/icons/IconUserSquare.mjs:
|
|
461
461
|
(**
|
|
462
|
-
* @license @tabler/icons-react v3.
|
|
462
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
463
463
|
*
|
|
464
464
|
* This source code is licensed under the MIT license.
|
|
465
465
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -467,7 +467,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
467
467
|
|
|
468
468
|
@tabler/icons-react/dist/esm/icons/IconX.mjs:
|
|
469
469
|
(**
|
|
470
|
-
* @license @tabler/icons-react v3.
|
|
470
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
471
471
|
*
|
|
472
472
|
* This source code is licensed under the MIT license.
|
|
473
473
|
* See the LICENSE file in the root directory of this source tree.
|
|
@@ -475,7 +475,7 @@ var __create=Object.create;var __defProp=Object.defineProperty;var __getOwnPropD
|
|
|
475
475
|
|
|
476
476
|
@tabler/icons-react/dist/esm/tabler-icons-react.mjs:
|
|
477
477
|
(**
|
|
478
|
-
* @license @tabler/icons-react v3.
|
|
478
|
+
* @license @tabler/icons-react v3.12.0 - MIT
|
|
479
479
|
*
|
|
480
480
|
* This source code is licensed under the MIT license.
|
|
481
481
|
* See the LICENSE file in the root directory of this source tree.
|