{
  "version": 3,
  "sources": ["../../src/index.ts", "../../src/AddressDisplay/AddressDisplay.tsx", "../../src/AddressInput/AddressInput.tsx", "../../src/ElementsInput/ElementsInput.utils.ts", "../../src/constants.ts", "../../src/AnnotationInput/AnnotationInput.tsx", "../../src/AppShell/AppShell.tsx", "../../src/ErrorBoundary/ErrorBoundary.tsx", "../../../../node_modules/@tabler/icons-react/dist/esm/createReactComponent.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/defaultAttributes.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconAlertCircle.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowDown.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowRight.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowUp.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconArrowsSort.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBinaryTree.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBleachOff.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBleach.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBookmark.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBracketsContain.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBriefcase.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBucketOff.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconBucket.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCake.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarDue.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarEvent.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarMonth.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCalendarTime.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCheck.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCheckbox.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconChevronDown.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconChevronLeft.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconChevronRight.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconChevronUp.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCircleMinus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCirclePlus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconClipboardCheck.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCloudUpload.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconColumns.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCopy.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCurrencyDollar.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconDeviceDesktop.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconDots.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconDownload.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEdit.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEmpathize.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEqualNot.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEqual.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEyeOff.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconEye.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconFileAlert.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconFileExport.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconFileText.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconFilter2Plus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconFlask.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconInfoCircle.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconLanguage.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconLayoutSidebar.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconLibraryPlus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconLogout.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMapPin.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMathGreater.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMathLower.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMessageCircle.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMessage.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMicrophone.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMinus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconMoon.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPalette.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPaperclip.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPencil.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconPlus.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconReload.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSearch.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSend.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSettings.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSortAscending.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSortDescending.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSquare.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconStethoscope.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSunHigh.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconSwitchHorizontal.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconTableExport.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconTable.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconTrash.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconUsers.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconX.mjs", "../../../../node_modules/@tabler/icons-react/dist/esm/icons/IconCircleFilled.mjs", "../../src/Loading/Loading.tsx", "../../src/AppShell/AnnouncementBanners.tsx", "../../src/AppShell/AppShell.module.css", "../../src/AppShell/Header.tsx", "../../src/ResourceAvatar/ResourceAvatar.tsx", "../../src/MedplumLink/MedplumLink.tsx", "../../src/utils/dom.ts", "../../src/ResourceAvatar/ResourceAvatar.utils.ts", "../../src/AppShell/Header.module.css", "../../src/AppShell/HeaderDropdown.tsx", "../../../../node_modules/clsx/dist/clsx.mjs", "../../src/auth/ProjectLoginOption.tsx", "../../src/auth/ProjectLoginOption.module.css", "../../src/utils/app.ts", "../../src/AppShell/HeaderDropdown.module.css", "../../src/AppShell/HeaderSearchInput.tsx", "../../src/AsyncAutocomplete/AsyncAutocomplete.tsx", "../../src/AsyncAutocomplete/AsyncAutocomplete.utils.ts", "../../src/AppShell/HeaderSearchInput.module.css", "../../src/AppShell/userMenuMiddlewares.ts", "../../src/AppShell/Navbar.tsx", "../../src/BookmarkDialog/BookmarkDialog.tsx", "../../src/Form/Form.tsx", "../../src/Form/Form.context.ts", "../../src/Form/FormUtils.ts", "../../src/Form/SubmitButton.tsx", "../../src/ResourceTypeInput/ResourceTypeInput.tsx", "../../src/CodeInput/CodeInput.tsx", "../../src/ValueSetAutocomplete/ValueSetAutocomplete.tsx", "../../src/UnavailableNote/UnavailableNote.tsx", "../../src/AppShell/Navbar.module.css", "../../src/AppShell/Spotlight.tsx", "../../src/AppShell/Spotlight.module.css", "../../src/AttachmentArrayDisplay/AttachmentArrayDisplay.tsx", "../../src/AttachmentDisplay/AttachmentDisplay.tsx", "../../src/CcdaDisplay/CcdaDisplay.tsx", "../../src/AttachmentDisplay/ScannedImage.tsx", "../../src/DescriptionList/DescriptionList.module.css", "../../src/DescriptionList/DescriptionList.tsx", "../../src/AttachmentArrayInput/AttachmentArrayInput.tsx", "../../src/AttachmentButton/AttachmentButton.tsx", "../../src/AttachmentInput/AttachmentInput.tsx", "../../src/auth/ChangePasswordForm.tsx", "../../src/Container/Container.tsx", "../../src/Container/Container.module.css", "../../src/Panel/Panel.tsx", "../../src/Panel/Panel.module.css", "../../src/Document/Document.tsx", "../../src/Logo/Logo.tsx", "../../src/PasswordInput/PasswordInput.tsx", "../../src/utils/outcomes.ts", "../../src/auth/ChooseScopeForm.tsx", "../../src/auth/MfaEnrollForm.tsx", "../../src/auth/MfaForm.tsx", "../../src/auth/MfaVerificationForm.tsx", "../../src/auth/RegisterForm.tsx", "../../src/OperationOutcomeAlert/OperationOutcomeAlert.tsx", "../../src/auth/NewProjectForm.tsx", "../../src/auth/NewUserForm.tsx", "../../src/GoogleButton/GoogleButton.tsx", "../../src/utils/script.ts", "../../src/GoogleButton/GoogleButton.utils.ts", "../../src/utils/recaptcha.ts", "../../src/auth/ResetPasswordForm.tsx", "../../src/auth/SetPasswordForm.tsx", "../../src/auth/SignInForm.tsx", "../../src/auth/AuthenticationForm.tsx", "../../src/auth/ChooseProfileForm.tsx", "../../src/BackboneElementDisplay/BackboneElementDisplay.tsx", "../../src/ResourcePropertyDisplay/ResourcePropertyDisplay.tsx", "../../src/CodeableConceptDisplay/CodeableConceptDisplay.tsx", "../../src/CodingDisplay/CodingDisplay.tsx", "../../src/ContactPointDisplay/ContactPointDisplay.tsx", "../../src/ContactDetailDisplay/ContactDetailDisplay.tsx", "../../src/ExtensionDisplay/ExtensionDisplay.tsx", "../../src/ResourcePropertyDisplay/ResourcePropertyDisplay.utils.ts", "../../src/HumanNameDisplay/HumanNameDisplay.tsx", "../../src/IdentifierDisplay/IdentifierDisplay.tsx", "../../src/MoneyDisplay/MoneyDisplay.tsx", "../../src/QuantityDisplay/QuantityDisplay.tsx", "../../src/RangeDisplay/RangeDisplay.tsx", "../../src/RatioDisplay/RatioDisplay.tsx", "../../src/ReferenceDisplay/ReferenceDisplay.tsx", "../../src/ResourceArrayDisplay/ResourceArrayDisplay.tsx", "../../src/ResourceArrayInput/ResourceArrayInput.utils.ts", "../../src/SliceDisplay/SliceDisplay.tsx", "../../src/utils/maybeWrapWithContext.tsx", "../../src/BackboneElementInput/BackboneElementInput.tsx", "../../src/ElementsInput/ElementsInput.tsx", "../../src/CheckboxFormSection/CheckboxFormSection.tsx", "../../src/FormSection/FormSection.module.css", "../../src/utils/maybeWrapWithTooltip.tsx", "../../src/FormSection/FormSection.tsx", "../../src/ResourceForm/ResourceForm.utils.ts", "../../src/ResourcePropertyInput/ResourcePropertyInput.tsx", "../../src/CodeableConceptInput/CodeableConceptInput.tsx", "../../src/CodingInput/CodingInput.tsx", "../../src/ContactDetailInput/ContactDetailInput.tsx", "../../src/ContactPointInput/ContactPointInput.tsx", "../../src/DateTimeInput/DateTimeInput.tsx", "../../src/DateTimeInput/DateTimeInput.module.css", "../../src/DateTimeInput/DateTimeInput.utils.ts", "../../src/ExtensionInput/ExtensionInput.tsx", "../../src/HumanNameInput/HumanNameInput.tsx", "../../src/IdentifierInput/IdentifierInput.tsx", "../../src/MoneyInput/MoneyInput.tsx", "../../src/PeriodInput/PeriodInput.tsx", "../../src/QuantityInput/QuantityInput.tsx", "../../src/RangeInput/RangeInput.tsx", "../../src/RatioInput/RatioInput.tsx", "../../src/ReferenceInput/ReferenceInput.tsx", "../../src/ResourceInput/ResourceInput.tsx", "../../src/ResourceInput/MultiResourceInput.tsx", "../../src/ResourceArrayInput/ResourceArrayInput.tsx", "../../src/ResourcePropertyInput/ResourcePropertyInput.utils.ts", "../../src/SliceInput/SliceInput.tsx", "../../src/ResourceArrayInput/ResourceArrayInput.module.css", "../../src/buttons/ArrayAddButton.tsx", "../../src/buttons/ArrayRemoveButton.tsx", "../../src/SensitiveTextarea/SensitiveTextarea.tsx", "../../src/TimingInput/TimingInput.tsx", "../../src/BackboneElementInput/BackboneElementInput.module.css", "../../src/CalendarDateInput/CalendarDateInput.tsx", "../../src/CalendarDateInput/CalendarDateInput.module.css", "../../src/CalendarDateInput/CalendarDateInput.utils.ts", "../../src/CalendarDateInput/useDayRangeDrag.ts", "../../src/CalendarInput/CalendarInput.tsx", "../../src/chat/BaseChat/BaseChat.tsx", "../../src/chat/BaseChat/BaseChat.module.css", "../../src/chat/BaseChat/DocumentPicker.tsx", "../../src/chat/ChatModal/ChatModal.tsx", "../../src/chat/ChatModal/ChatModal.module.css", "../../src/chat/ThreadChat/ThreadChat.tsx", "../../src/chat/ThreadInbox/NewTopicDialog.tsx", "../../src/Modal/Modal.tsx", "../../src/Modal/Modal.module.css", "../../src/chat/ThreadInbox/ThreadMessageForm.tsx", "../../src/chat/ThreadInbox/ParticipantFilter.tsx", "../../src/chat/ThreadInbox/ParticipantFilter.module.css", "../../src/chat/ThreadInbox/ThreadInbox.tsx", "../../src/ListWithDetailPane/ListWithDetailPane.tsx", "../../src/ListWithDetailPane/ListWithDetailPane.module.css", "../../src/ListWithDetailPane/ListWithDetailPaneSkeleton.tsx", "../../src/chat/ThreadInbox/EditThreadDialog.tsx", "../../src/chat/ThreadInbox/ThreadDetail.tsx", "../../src/PatientSummary/PatientSummary.tsx", "../../src/PatientSummary/PatientSummary.module.css", "../../src/PatientSummary/sectionConfigs.tsx", "../../src/PatientSummary/Allergies.tsx", "../../src/StatusBadge/StatusBadge.tsx", "../../src/PatientSummary/AllergyDialog.tsx", "../../src/PatientSummary/CollapsibleSection.tsx", "../../src/PatientSummary/CollapsibleSection.module.css", "../../src/PatientSummary/SummaryItem.tsx", "../../src/PatientSummary/SummaryItem.module.css", "../../src/PatientSummary/Goals.tsx", "../../src/PatientSummary/GoalDialog.tsx", "../../src/PatientSummary/PatientSummary.utils.ts", "../../src/PatientSummary/Immunizations.tsx", "../../src/PatientSummary/ImmunizationDialog.tsx", "../../src/PatientSummary/Insurance.tsx", "../../src/PatientSummary/Labs.tsx", "../../src/DiagnosticReportDisplay/DiagnosticReportDisplay.tsx", "../../src/NoteDisplay/NoteDisplay.tsx", "../../src/NoteDisplay/NoteDisplay.module.css", "../../src/ResourceBadge/ResourceBadge.tsx", "../../src/ResourceName/ResourceName.tsx", "../../src/DiagnosticReportDisplay/DiagnosticReportDisplay.module.css", "../../src/PatientSummary/Medications.tsx", "../../src/utils/date.ts", "../../src/PatientSummary/MedicationDialog.tsx", "../../src/PatientSummary/PatientInfoItem.tsx", "../../src/PatientSummary/Pharmacies.tsx", "../../src/PatientSummary/pharmacy-utils.ts", "../../src/PatientSummary/ProblemList.tsx", "../../src/PatientSummary/ConditionDialog.tsx", "../../src/PatientSummary/SexualOrientation.tsx", "../../src/PatientSummary/SmokingStatus.tsx", "../../src/PatientSummary/Vitals.tsx", "../../src/PatientSummary/Vitals.utils.ts", "../../src/chat/ThreadInbox/ThreadDetail.module.css", "../../src/chat/ThreadInbox/ThreadInbox.module.css", "../../src/chat/ThreadInbox/ThreadListItem.tsx", "../../src/chat/ThreadInbox/ThreadListItem.module.css", "../../src/ResourceTimeline/ResourceTimeline.tsx", "../../src/ResourceDiffTable/ResourceDiffTable.tsx", "../../src/ResourceDiffRow/ResourceDiffRow.tsx", "../../src/ResourceDiffRow/ResourceDiffRow.module.css", "../../src/ResourceDiffTable/ResourceDiffTable.module.css", "../../src/ResourceTable/ResourceTable.tsx", "../../src/Timeline/Timeline.tsx", "../../src/Timeline/Timeline.module.css", "../../src/ResourceTimeline/ResourceTimeline.module.css", "../../src/DefaultResourceTimeline/DefaultResourceTimeline.tsx", "../../src/EncounterTimeline/EncounterTimeline.tsx", "../../src/FhirPathTable/FhirPathTable.tsx", "../../src/FhirPathDisplay/FhirPathDisplay.tsx", "../../src/SearchControl/SearchControl.tsx", "../../src/SearchExportDialog/SearchExportDialog.tsx", "../../src/SearchFieldEditor/SearchFieldEditor.tsx", "../../src/SearchControl/SearchUtils.tsx", "../../src/SearchControl/SearchControl.module.css", "../../src/SearchFilterEditor/SearchFilterPopover.tsx", "../../src/SearchControl/SearchToolbarPopover.tsx", "../../src/SearchControl/SearchToolbarPopover.module.css", "../../src/SearchControl/useEditableRows.ts", "../../src/SearchFilterValueInput/SearchFilterValueInput.tsx", "../../src/SearchFilterEditor/SearchFilterPopover.module.css", "../../src/SearchFilterValueDialog/SearchFilterValueDialog.tsx", "../../src/SearchFilterValueDisplay/SearchFilterValueDisplay.tsx", "../../src/SearchPopupMenu/SearchPopupMenu.tsx", "../../src/SearchSortEditor/SearchSortEditor.tsx", "../../src/utils/pagination.ts", "../../src/SearchControl/SearchControlField.ts", "../../src/InfoBar/InfoBar.tsx", "../../src/InfoBar/InfoBar.module.css", "../../src/LabOrdersPanel/LabOrderDetails.tsx", "../../src/LabOrdersPanel/documentReference.ts", "../../src/LabOrdersPanel/LabDetailLayout.tsx", "../../src/LabOrdersPanel/LabDocumentSection.tsx", "../../src/LabOrdersPanel/LabDocumentSection.module.css", "../../src/LabOrdersPanel/labOrder.ts", "../../src/LabOrdersPanel/LabReportContent.tsx", "../../src/LabOrdersPanel/LabReportContent.module.css", "../../src/LabOrdersPanel/LabOrdersPanel.tsx", "../../src/LabOrdersPanel/LabDetailPane.tsx", "../../src/LabOrdersPanel/LabResultDetails.tsx", "../../src/LabOrdersPanel/LabListItem.tsx", "../../src/LabOrdersPanel/LabListItem.module.css", "../../src/LabOrdersPanel/LabResultListItem.tsx", "../../src/LabOrdersPanel/LabSelectEmpty.tsx", "../../src/LinkTabs/LinkTabs.tsx", "../../src/LinkTabs/LinkTabs.module.css", "../../src/MeasureReportDisplay/MeasureReportDisplay.tsx", "../../src/MeasureReportDisplay/MeasureReportGroupDisplay/MeasureReportGroupDisplay.tsx", "../../src/NotificationIcon/NotificationIcon.tsx", "../../src/PatientAccountsForm/PatientAccountsForm.tsx", "../../src/PatientExportForm/PatientExportForm.tsx", "../../src/PatientHeader/PatientHeader.tsx", "../../src/PatientHeader/PatientHeader.utils.ts", "../../src/PatientSummary/PharmacyDialog.tsx", "../../src/PatientSummary/PharmacyDialog.module.css", "../../src/PatientSummary/SummaryResourceListSection.tsx", "../../src/PatientTimeline/PatientTimeline.tsx", "../../src/PlanDefinitionBuilder/PlanDefinitionBuilder.tsx", "../../src/PlanDefinitionBuilder/PlanDefinitionBuilder.module.css", "../../src/QrCodeScanner/QrCodeScanner.tsx", "../../src/QuestionnaireBuilder/QuestionnaireBuilder.tsx", "../../src/QuestionnaireForm/QuestionnaireFormItem.tsx", "../../src/QuestionnaireBuilder/QuestionnaireBuilder.module.css", "../../src/QuestionnaireForm/AIRealTimeQuestionnaireForm.tsx", "../../src/QuestionnaireForm/AIRealTimeQuestionnaireForm.module.css", "../../src/QuestionnaireForm/QuestionnaireForm.tsx", "../../src/SignatureInput/SignatureInput.tsx", "../../../../node_modules/signature_pad/src/point.ts", "../../../../node_modules/signature_pad/src/bezier.ts", "../../../../node_modules/signature_pad/src/signature_event_target.ts", "../../../../node_modules/signature_pad/src/throttle.ts", "../../../../node_modules/signature_pad/src/signature_pad.ts", "../../src/QuestionnaireForm/QuestionnaireFormItemArray.tsx", "../../src/QuestionnaireForm/QuestionnaireFormGroup.tsx", "../../src/QuestionnaireForm/QuestionnaireFormRepeatableGroup.tsx", "../../src/QuestionnaireForm/QuestionnaireFormRepeatableItem.tsx", "../../src/QuestionnaireForm/QuestionnaireFormStepper.tsx", "../../src/QuestionnaireResponseDisplay/QuestionnaireResponseDisplay.tsx", "../../src/QuestionnaireResponseDisplay/QuestionnaireResponseItemDisplay.tsx", "../../src/ReferenceRangeEditor/ReferenceRangeEditor.tsx", "../../src/ReferenceRangeEditor/ReferenceRangeEditor.module.css", "../../src/RequestGroupDisplay/RequestGroupDisplay.tsx", "../../src/ResourceBlame/ResourceBlame.tsx", "../../src/utils/blame.ts", "../../src/utils/diff.ts", "../../src/ResourceBlame/ResourceBlame.module.css", "../../src/ResourceBlame/ResourceBlame.utils.ts", "../../src/ResourceBoard/ResourceBoard.tsx", "../../src/ResourceDiff/ResourceDiff.tsx", "../../src/ResourceDiff/ResourceDiff.module.css", "../../src/ResourceForm/ResourceForm.tsx", "../../src/ResourceForm/ResourceForm.module.css", "../../src/ResourceHistoryTable/ResourceHistoryTable.tsx", "../../src/Scheduler/Scheduler.tsx", "../../src/Scheduler/Scheduler.module.css", "../../src/ScrollToTop/ScrollToTop.tsx", "../../src/SearchFilterEditor/SearchFilterEditor.tsx", "../../src/ServiceRequestTimeline/ServiceRequestTimeline.tsx", "../../src/SmartAppLaunchLink/SmartAppLaunchLink.tsx"],
  "sourcesContent": ["// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// Re-export all hooks from @medplum/react-hooks\nexport * from '@medplum/react-hooks';\n\n// Export all components\nexport * from './AddressDisplay/AddressDisplay';\nexport * from './AddressInput/AddressInput';\nexport * from './AnnotationInput/AnnotationInput';\nexport * from './AppShell/AppShell';\nexport * from './AppShell/Header';\nexport * from './AppShell/Navbar';\nexport * from './AppShell/Spotlight';\nexport * from './AsyncAutocomplete/AsyncAutocomplete';\nexport * from './AttachmentArrayDisplay/AttachmentArrayDisplay';\nexport * from './AttachmentArrayInput/AttachmentArrayInput';\nexport * from './AttachmentButton/AttachmentButton';\nexport * from './AttachmentDisplay/AttachmentDisplay';\nexport * from './AttachmentInput/AttachmentInput';\nexport * from './auth/ChangePasswordForm';\nexport * from './auth/ChooseScopeForm';\nexport * from './auth/MfaEnrollForm';\nexport * from './auth/MfaForm';\nexport * from './auth/MfaVerificationForm';\nexport * from './auth/RegisterForm';\nexport * from './auth/ResetPasswordForm';\nexport * from './auth/SetPasswordForm';\nexport * from './auth/SignInForm';\nexport * from './BackboneElementDisplay/BackboneElementDisplay';\nexport * from './BackboneElementInput/BackboneElementInput';\nexport * from './CalendarDateInput/CalendarDateInput';\nexport * from './CalendarInput/CalendarInput';\nexport * from './chat/BaseChat/BaseChat';\nexport * from './chat/ChatModal/ChatModal';\nexport * from './chat/ThreadChat/ThreadChat';\nexport * from './chat/ThreadInbox/NewTopicDialog';\nexport * from './chat/ThreadInbox/ParticipantFilter';\nexport * from './chat/ThreadInbox/ThreadInbox';\nexport * from './CheckboxFormSection/CheckboxFormSection';\nexport * from './CodeableConceptDisplay/CodeableConceptDisplay';\nexport * from './CodeableConceptInput/CodeableConceptInput';\nexport * from './CodeInput/CodeInput';\nexport * from './CodingDisplay/CodingDisplay';\nexport * from './CodingInput/CodingInput';\nexport * from './ContactDetailDisplay/ContactDetailDisplay';\nexport * from './ContactDetailInput/ContactDetailInput';\nexport * from './ContactPointDisplay/ContactPointDisplay';\nexport * from './ContactPointInput/ContactPointInput';\nexport * from './Container/Container';\nexport * from './DateTimeInput/DateTimeInput';\nexport * from './DateTimeInput/DateTimeInput.utils';\nexport * from './DefaultResourceTimeline/DefaultResourceTimeline';\nexport * from './DescriptionList/DescriptionList';\nexport * from './DiagnosticReportDisplay/DiagnosticReportDisplay';\nexport * from './Document/Document';\nexport * from './EncounterTimeline/EncounterTimeline';\nexport * from './ErrorBoundary/ErrorBoundary';\nexport * from './FhirPathTable/FhirPathTable';\nexport * from './Form/Form';\nexport * from './Form/FormUtils';\nexport * from './Form/SubmitButton';\nexport * from './FormSection/FormSection';\nexport * from './HumanNameDisplay/HumanNameDisplay';\nexport * from './HumanNameInput/HumanNameInput';\nexport * from './IdentifierDisplay/IdentifierDisplay';\nexport * from './IdentifierInput/IdentifierInput';\nexport * from './InfoBar/InfoBar';\nexport * from './LabOrdersPanel/LabOrderDetails';\nexport * from './LabOrdersPanel/LabOrdersPanel';\nexport * from './LabOrdersPanel/LabResultDetails';\nexport * from './LinkTabs/LinkTabs';\nexport * from './ListWithDetailPane/ListWithDetailPane';\nexport * from './Loading/Loading';\nexport * from './Logo/Logo';\nexport * from './MeasureReportDisplay/MeasureReportDisplay';\nexport * from './MedplumLink/MedplumLink';\nexport * from './Modal/Modal';\nexport * from './MoneyDisplay/MoneyDisplay';\nexport * from './MoneyInput/MoneyInput';\nexport * from './NoteDisplay/NoteDisplay';\nexport * from './NotificationIcon/NotificationIcon';\nexport * from './OperationOutcomeAlert/OperationOutcomeAlert';\nexport * from './Panel/Panel';\nexport * from './PasswordInput/PasswordInput';\nexport * from './PatientAccountsForm/PatientAccountsForm';\nexport * from './PatientExportForm/PatientExportForm';\nexport * from './PatientHeader/PatientHeader';\nexport * from './PatientSummary/PatientSummary';\nexport type * from './PatientSummary/PatientSummary.types';\nexport * from './PatientSummary/Pharmacies';\nexport * from './PatientSummary/pharmacy-utils';\nexport * from './PatientSummary/PharmacyDialog';\nexport {\n  AllergiesSection,\n  DemographicsSection,\n  GoalsSection,\n  ImmunizationsSection,\n  InsuranceSection,\n  LabsSection,\n  MedicationsSection,\n  PharmaciesSection,\n  ProblemListSection,\n  SexualOrientationSection,\n  SmokingStatusSection,\n  VitalsSection,\n  createLabsSection,\n  createPharmaciesSection,\n  getDefaultSections,\n} from './PatientSummary/sectionConfigs';\nexport { summaryResourceListSection } from './PatientSummary/SummaryResourceListSection';\nexport type { SummaryResourceListOptions } from './PatientSummary/SummaryResourceListSection';\nexport * from './PatientTimeline/PatientTimeline';\nexport * from './PlanDefinitionBuilder/PlanDefinitionBuilder';\nexport * from './QrCodeScanner/QrCodeScanner';\nexport * from './QuantityDisplay/QuantityDisplay';\nexport * from './QuantityInput/QuantityInput';\nexport * from './QuestionnaireBuilder/QuestionnaireBuilder';\nexport * from './QuestionnaireForm/AIRealTimeQuestionnaireForm';\nexport * from './QuestionnaireForm/QuestionnaireForm';\nexport * from './QuestionnaireResponseDisplay/QuestionnaireResponseDisplay';\nexport * from './RangeDisplay/RangeDisplay';\nexport * from './RangeInput/RangeInput';\nexport * from './RatioInput/RatioInput';\nexport * from './ReferenceDisplay/ReferenceDisplay';\nexport * from './ReferenceInput/ReferenceInput';\nexport * from './ReferenceRangeEditor/ReferenceRangeEditor';\nexport * from './RequestGroupDisplay/RequestGroupDisplay';\nexport * from './ResourceArrayDisplay/ResourceArrayDisplay';\nexport * from './ResourceArrayInput/ResourceArrayInput';\nexport * from './ResourceAvatar/ResourceAvatar';\nexport * from './ResourceBadge/ResourceBadge';\nexport * from './ResourceBlame/ResourceBlame';\nexport * from './ResourceBoard/ResourceBoard';\nexport * from './ResourceDiff/ResourceDiff';\nexport * from './ResourceDiffTable/ResourceDiffTable';\nexport * from './ResourceForm/ResourceForm';\nexport * from './ResourceForm/ResourceForm.utils';\nexport * from './ResourceHistoryTable/ResourceHistoryTable';\nexport * from './ResourceInput/MultiResourceInput';\nexport * from './ResourceInput/ResourceInput';\nexport * from './ResourceName/ResourceName';\nexport * from './ResourcePropertyDisplay/ResourcePropertyDisplay';\nexport * from './ResourcePropertyInput/ResourcePropertyInput';\nexport * from './ResourcePropertyInput/ResourcePropertyInput.utils';\nexport * from './ResourceTable/ResourceTable';\nexport * from './ResourceTimeline/ResourceTimeline';\nexport * from './Scheduler/Scheduler';\nexport * from './ScrollToTop/ScrollToTop';\nexport * from './SearchControl/SearchControl';\nexport * from './SearchControl/SearchControlField';\nexport * from './SearchControl/SearchUtils';\nexport * from './SearchFieldEditor/SearchFieldEditor';\nexport * from './SearchFilterEditor/SearchFilterEditor';\nexport * from './ServiceRequestTimeline/ServiceRequestTimeline';\nexport * from './SignatureInput/SignatureInput';\nexport * from './SmartAppLaunchLink/SmartAppLaunchLink';\nexport * from './StatusBadge/StatusBadge';\nexport * from './Timeline/Timeline';\nexport * from './TimingInput/TimingInput';\nexport * from './UnavailableNote/UnavailableNote';\nexport * from './utils/app';\nexport * from './utils/date';\nexport * from './utils/dom';\nexport * from './utils/outcomes';\nexport * from './utils/pagination';\nexport * from './utils/recaptcha';\nexport * from './utils/script';\nexport * from './ValueSetAutocomplete/ValueSetAutocomplete';\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AddressFormatOptions } from '@medplum/core';\nimport { formatAddress } from '@medplum/core';\nimport type { Address } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface AddressDisplayProps {\n  readonly value?: Address;\n  readonly options?: AddressFormatOptions;\n}\n\nexport function AddressDisplay(props: AddressDisplayProps): JSX.Element | null {\n  const address = props.value;\n  if (!address) {\n    return null;\n  }\n\n  return <>{formatAddress(address, props.options)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { trimTrailingEmptyElements } from '@medplum/core';\nimport type { Address } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nfunction getLine(address: Address, index: number): string {\n  return address.line && address.line.length > index ? address.line[index] : '';\n}\n\nfunction setLine(address: Address, index: number, str: string): Address {\n  const line: string[] = address.line || [];\n  while (line.length <= index) {\n    line.push('');\n  }\n  line[index] = str;\n  return { ...address, line: trimTrailingEmptyElements(line) };\n}\n\nexport type AddressInputProps = ComplexTypeInputProps<Address>;\n\nexport function AddressInput(props: AddressInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue || {});\n\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [useProps, typeProps, line1Props, line2Props, cityProps, stateProps, postalCodeProps] = useMemo(\n    () =>\n      ['use', 'type', 'line1', 'line2', 'city', 'state', 'postalCode'].map((field) =>\n        getExtendedProps(props.path + '.' + field)\n      ),\n    [getExtendedProps, props.path]\n  );\n\n  // TODO{profiles} is it worth the complexity of subbing in an autocomplete input when\n  // a binding is defined in a profile? If so, it should go in a new wrapper around TextInput\n  // e.g. US Core Patient Profile\n\n  function setValueWrapper(newValue: Partial<Address>): void {\n    setValue((prevValue) => ({ ...prevValue, ...newValue }));\n    if (props.onChange) {\n      props.onChange({ ...value, ...newValue });\n    }\n  }\n\n  function setUse(use: 'home' | 'work' | 'temp' | 'old' | 'billing'): void {\n    setValueWrapper({ use });\n  }\n\n  function setType(type: 'postal' | 'physical' | 'both'): void {\n    setValueWrapper({ type });\n  }\n\n  function setLine1(line1: string): void {\n    setValueWrapper(setLine(value, 0, line1));\n  }\n\n  function setLine2(line2: string): void {\n    setValueWrapper(setLine(value, 1, line2));\n  }\n\n  function setCity(city: string): void {\n    setValueWrapper({ city });\n  }\n\n  function setState(state: string): void {\n    setValueWrapper({ state });\n  }\n\n  function setPostalCode(postalCode: string): void {\n    setValueWrapper({ postalCode });\n  }\n\n  return (\n    <Group gap=\"xs\" wrap=\"nowrap\" grow>\n      <NativeSelect\n        disabled={props.disabled || useProps?.readonly}\n        data-testid=\"address-use\"\n        defaultValue={value.use}\n        onChange={(e) => setUse(e.currentTarget.value as 'home' | 'work' | 'temp' | 'old' | 'billing')}\n        data={['', 'home', 'work', 'temp', 'old', 'billing']}\n      />\n      <NativeSelect\n        disabled={props.disabled || typeProps?.readonly}\n        data-testid=\"address-type\"\n        defaultValue={value.type}\n        onChange={(e) => setType(e.currentTarget.value as 'postal' | 'physical' | 'both')}\n        data={['', 'postal', 'physical', 'both']}\n      />\n      <TextInput\n        disabled={props.disabled || line1Props?.readonly}\n        placeholder=\"Line 1\"\n        defaultValue={getLine(value, 0)}\n        onChange={(e) => setLine1(e.currentTarget.value)}\n      />\n      <TextInput\n        disabled={props.disabled || line2Props?.readonly}\n        placeholder=\"Line 2\"\n        defaultValue={getLine(value, 1)}\n        onChange={(e) => setLine2(e.currentTarget.value)}\n      />\n      <TextInput\n        disabled={props.disabled || cityProps?.readonly}\n        placeholder=\"City\"\n        defaultValue={value.city}\n        onChange={(e) => setCity(e.currentTarget.value)}\n      />\n      <TextInput\n        disabled={props.disabled || stateProps?.readonly}\n        placeholder=\"State\"\n        defaultValue={value.state}\n        onChange={(e) => setState(e.currentTarget.value)}\n      />\n      <TextInput\n        disabled={props.disabled || postalCodeProps?.readonly}\n        placeholder=\"Postal Code\"\n        defaultValue={value.postalCode}\n        onChange={(e) => setPostalCode(e.currentTarget.value)}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ElementsContextType, ExtendedInternalSchemaElement } from '@medplum/core';\nimport { isPopulated } from '@medplum/core';\nimport { createContext } from 'react';\nimport { DEFAULT_IGNORED_NON_NESTED_PROPERTIES, DEFAULT_IGNORED_PROPERTIES } from '../constants';\n\nexport const ElementsContext = createContext<ElementsContextType>({\n  path: '',\n  profileUrl: undefined,\n  elements: Object.create(null),\n  elementsByPath: Object.create(null),\n  getExtendedProps: () => {\n    return { readonly: false, hidden: false };\n  },\n  accessPolicyResource: undefined,\n  debugMode: false,\n  isDefaultContext: true,\n});\nElementsContext.displayName = 'ElementsContext';\n\nexport const EXTENSION_KEYS = ['extension', 'modifierExtension'];\nexport const IGNORED_PROPERTIES = ['id', ...DEFAULT_IGNORED_PROPERTIES].filter(\n  (prop) => !EXTENSION_KEYS.includes(prop)\n);\n\nexport function getElementsToRender(\n  inputElements: Record<string, ExtendedInternalSchemaElement>\n): [string, ExtendedInternalSchemaElement][] {\n  const result = Object.entries(inputElements).filter(([key, element]) => {\n    if (!isPopulated(element.type)) {\n      return false;\n    }\n\n    if (element.max === 0) {\n      return false;\n    }\n\n    // toLowerCase to handle Extension.url as well as Extension.extension.url, etc.\n    if (element.path.toLowerCase().endsWith('extension.url') && element.fixed) {\n      return false;\n    }\n\n    if (EXTENSION_KEYS.includes(key) && !isPopulated(element.slicing?.slices)) {\n      // an extension property without slices has no nested extensions\n      return false;\n    } else if (IGNORED_PROPERTIES.includes(key)) {\n      return false;\n    } else if (DEFAULT_IGNORED_NON_NESTED_PROPERTIES.includes(key) && element.path.split('.').length === 2) {\n      return false;\n    }\n\n    // Profiles can include nested elements in addition to their containing element, e.g.:\n    // identifier, identifier.use, identifier.system\n    // Skip nested elements, e.g. identifier.use, since they are handled by the containing element\n    if (key.includes('.')) {\n      return false;\n    }\n\n    return true;\n  });\n\n  return result;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nexport const DEFAULT_IGNORED_PROPERTIES = ['meta', 'implicitRules', 'contained', 'extension', 'modifierExtension'];\n\n// Ignored only when they are top-level properties\n// e.g. Patient.language is ignored, but Patient.communication.language is not ignored\nexport const DEFAULT_IGNORED_NON_NESTED_PROPERTIES = ['language', 'text'];\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { TextInput } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport type { Annotation } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface AnnotationInputProps extends ComplexTypeInputProps<Annotation> {}\n\nexport function AnnotationInput(props: AnnotationInputProps): JSX.Element {\n  const author = useMedplumProfile();\n  const [value, setValue] = useState(props.defaultValue || ({} as Annotation));\n\n  function setText(text: string): void {\n    const newValue: Annotation = text\n      ? {\n          text,\n          authorReference: author && createReference(author),\n          time: new Date().toISOString(),\n        }\n      : ({} as Annotation);\n\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  return (\n    <TextInput\n      disabled={props.disabled}\n      name={props.name}\n      placeholder=\"Annotation text\"\n      defaultValue={value.text}\n      onChange={(e) => setText(e.currentTarget.value)}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AppShellHeaderConfiguration, AppShellNavbarConfiguration } from '@mantine/core';\nimport { AppShell as MantineAppShell } from '@mantine/core';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { Suspense, useState } from 'react';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { Loading } from '../Loading/Loading';\nimport type { AppShellAnnouncement } from './AnnouncementBanners';\nimport { AnnouncementBanners } from './AnnouncementBanners';\nimport classes from './AppShell.module.css';\nimport { Header } from './Header';\nimport type { NavbarMenu } from './Navbar';\nimport { Navbar } from './Navbar';\nimport type { SpotlightLinkAction } from './Spotlight';\n\nconst OPEN_WIDTH = 250;\nconst CLOSED_WIDTH = 59;\nconst HEADER_HEIGHT = 60;\nconst ANNOUNCEMENT_HEIGHT = 36;\n\nexport type { AppShellAnnouncement } from './AnnouncementBanners';\n\nexport interface AppShellProps {\n  readonly logo: ReactNode;\n  readonly pathname?: string;\n  readonly searchParams?: URLSearchParams;\n  readonly headerSearchDisabled?: boolean;\n  readonly version?: string;\n  readonly menus?: NavbarMenu[];\n  readonly children: ReactNode;\n  readonly displayAddBookmark?: boolean;\n  readonly resourceTypeSearchDisabled?: boolean;\n  readonly notifications?: ReactNode;\n  readonly announcements?: AppShellAnnouncement[];\n  readonly layoutVersion?: 'v1' | 'v2';\n  readonly showLayoutVersionToggle?: boolean;\n  readonly spotlightPatientsOnly?: boolean;\n  readonly spotlightActions?: SpotlightLinkAction[];\n}\n\nexport function AppShell(props: AppShellProps): JSX.Element {\n  const [navbarOpen, setNavbarOpen] = useState(localStorage['navbarOpen'] === 'true');\n  const [layoutVersion] = useState(\n    props.layoutVersion ?? (localStorage['appShellLayoutVersion'] as 'v1' | 'v2' | undefined) ?? 'v1'\n  );\n  const medplum = useMedplum();\n  const profile = useMedplumProfile();\n  const [dismissedAnnouncementIds, setDismissedAnnouncementIds] = useState<ReadonlySet<string>>(() => {\n    try {\n      const dismissed = localStorage['appShellDismissedAnnouncements'];\n      return new Set(dismissed ? JSON.parse(dismissed) : []);\n    } catch (_err) {\n      return new Set();\n    }\n  });\n\n  const visibleAnnouncements = props.announcements?.filter(\n    (announcement) => !announcement.id || !dismissedAnnouncementIds.has(announcement.id)\n  );\n  const announcementHeight = visibleAnnouncements?.length ? visibleAnnouncements.length * ANNOUNCEMENT_HEIGHT : 0;\n\n  function setNavbarOpenWrapper(open: boolean): void {\n    localStorage['navbarOpen'] = open.toString();\n    setNavbarOpen(open);\n  }\n\n  function dismissAnnouncement(announcement: AppShellAnnouncement): void {\n    if (announcement.id) {\n      setDismissedAnnouncementIds((dismissedIds) => {\n        const updated = new Set(dismissedIds);\n        updated.add(announcement.id as string);\n        localStorage['appShellDismissedAnnouncements'] = JSON.stringify([...updated]);\n        return updated;\n      });\n    }\n    announcement.onDismiss?.(announcement);\n  }\n\n  function closeNavbar(): void {\n    setNavbarOpenWrapper(false);\n  }\n\n  function toggleNavbar(): void {\n    setNavbarOpenWrapper(!navbarOpen);\n  }\n\n  if (medplum.isLoading()) {\n    return <Loading />;\n  }\n\n  let headerProp: AppShellHeaderConfiguration | undefined;\n  let navbarProp: AppShellNavbarConfiguration | undefined;\n  let headerComponent: ReactNode | undefined;\n  let navbarComponent: ReactNode | undefined;\n\n  if (layoutVersion === 'v2') {\n    // Layout version v2:\n    // - No header\n    // - Navbar is either open or closed based on state\n    headerProp = { height: announcementHeight };\n    navbarProp = {\n      width: navbarOpen ? OPEN_WIDTH : CLOSED_WIDTH,\n      breakpoint: 0,\n      collapsed: {\n        desktop: !profile,\n        mobile: !profile,\n      },\n    };\n    headerComponent = visibleAnnouncements?.length ? (\n      <MantineAppShell.Header style={{ zIndex: 101 }}>\n        <AnnouncementBanners announcements={visibleAnnouncements} onDismiss={dismissAnnouncement} />\n      </MantineAppShell.Header>\n    ) : undefined;\n    navbarComponent = profile ? (\n      <Navbar\n        logo={props.logo}\n        pathname={props.pathname}\n        searchParams={props.searchParams}\n        menus={props.menus}\n        navbarToggle={toggleNavbar}\n        closeNavbar={closeNavbar}\n        displayAddBookmark={props.displayAddBookmark}\n        resourceTypeSearchDisabled={true}\n        opened={navbarOpen}\n        spotlightEnabled={true}\n        patientsOnly={props.spotlightPatientsOnly}\n        spotlightActions={props.spotlightActions}\n        userMenuEnabled={true}\n        version={props.version}\n        showLayoutVersionToggle={props.showLayoutVersionToggle}\n      />\n    ) : undefined;\n  } else {\n    // Default to layout version v1\n    headerProp = { height: HEADER_HEIGHT + announcementHeight };\n    navbarProp = {\n      width: OPEN_WIDTH,\n      breakpoint: 'sm',\n      collapsed: {\n        desktop: !profile || !navbarOpen,\n        mobile: !profile || !navbarOpen,\n      },\n    };\n    headerComponent = profile && (\n      <Header\n        pathname={props.pathname}\n        searchParams={props.searchParams}\n        headerSearchDisabled={props.headerSearchDisabled}\n        logo={props.logo}\n        version={props.version}\n        navbarOpen={navbarOpen}\n        navbarToggle={toggleNavbar}\n        notifications={props.notifications}\n        announcements={visibleAnnouncements}\n        onDismissAnnouncement={dismissAnnouncement}\n      />\n    );\n    navbarComponent =\n      profile && navbarOpen ? (\n        <Navbar\n          pathname={props.pathname}\n          searchParams={props.searchParams}\n          menus={props.menus}\n          navbarToggle={toggleNavbar}\n          closeNavbar={closeNavbar}\n          displayAddBookmark={props.displayAddBookmark}\n          resourceTypeSearchDisabled={props.resourceTypeSearchDisabled}\n          patientsOnly={props.spotlightPatientsOnly}\n          spotlightActions={props.spotlightActions}\n        />\n      ) : undefined;\n  }\n\n  return (\n    <MantineAppShell header={headerProp} navbar={navbarProp} padding={0}>\n      {headerComponent}\n      {navbarComponent}\n      <MantineAppShell.Main className={classes.main}>\n        <ErrorBoundary>\n          <Suspense fallback={<Loading />}>{props.children}</Suspense>\n        </ErrorBoundary>\n      </MantineAppShell.Main>\n    </MantineAppShell>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Alert } from '@mantine/core';\nimport { locationUtils, normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport type { ErrorInfo, ReactNode } from 'react';\nimport { Component } from 'react';\n\nexport interface ErrorBoundaryProps {\n  readonly children: ReactNode;\n}\n\nexport interface ErrorBoundaryState {\n  readonly error?: Error;\n  readonly lastLocation: string;\n}\n\n/**\n * ErrorBoundary is a React component that handles errors in its child components.\n * See: https://reactjs.org/docs/error-boundaries.html\n */\nexport class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {\n  readonly state: ErrorBoundaryState;\n\n  constructor(props: ErrorBoundaryProps) {\n    super(props);\n    this.state = { lastLocation: locationUtils.getLocation() };\n  }\n\n  static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n    return { error, lastLocation: locationUtils.getLocation() };\n  }\n\n  componentDidUpdate(_prevProps: ErrorBoundaryProps, _prevState: ErrorBoundaryState): void {\n    if (locationUtils.getLocation() !== this.state.lastLocation) {\n      this.setState({\n        lastLocation: locationUtils.getLocation(),\n        error: undefined,\n      });\n    }\n  }\n\n  shouldComponentUpdate(nextProps: ErrorBoundaryProps, nextState: ErrorBoundaryState): boolean {\n    if (this.props.children !== nextProps.children) {\n      return true;\n    }\n    if (nextState.error && !this.state.error) {\n      return true;\n    }\n    if (this.state.lastLocation !== locationUtils.getLocation()) {\n      return true;\n    }\n    return false;\n  }\n\n  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {\n    console.error('Uncaught error:', error, errorInfo);\n  }\n\n  render(): ReactNode {\n    if (this.state.error) {\n      return (\n        <Alert icon={<IconAlertCircle size={16} />} title=\"Something went wrong\" color=\"red\">\n          {normalizeErrorString(this.state.error)}\n        </Alert>\n      );\n    }\n\n    return this.props.children;\n  }\n}\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes.mjs';\n\nconst createReactComponent = (type, iconName, iconNamePascal, iconNode) => {\n  const Component = forwardRef(\n    ({\n      color = \"currentColor\",\n      size = 24,\n      stroke = 2,\n      title,\n      className,\n      children,\n      ...rest\n    }, ref) => createElement(\n      \"svg\",\n      {\n        ref,\n        ...defaultAttributes[type],\n        width: size,\n        height: size,\n        className: [`tabler-icon`, `tabler-icon-${iconName}`, className].filter(Boolean).join(\" \"),\n        ...type === \"filled\" ? {\n          fill: color\n        } : {\n          strokeWidth: stroke,\n          stroke: color\n        },\n        ...rest\n      },\n      [\n        title && createElement(\"title\", { key: \"svg-title\" }, title),\n        ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),\n        ...Array.isArray(children) ? children : [children]\n      ]\n    )\n  );\n  Component.displayName = `${iconNamePascal}`;\n  return Component;\n};\n\nexport { createReactComponent as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nvar defaultAttributes = {\n  outline: {\n    xmlns: \"http://www.w3.org/2000/svg\",\n    width: 24,\n    height: 24,\n    viewBox: \"0 0 24 24\",\n    fill: \"none\",\n    stroke: \"currentColor\",\n    strokeWidth: 2,\n    strokeLinecap: \"round\",\n    strokeLinejoin: \"round\"\n  },\n  filled: {\n    xmlns: \"http://www.w3.org/2000/svg\",\n    width: 24,\n    height: 24,\n    viewBox: \"0 0 24 24\",\n    fill: \"currentColor\",\n    stroke: \"none\"\n  }\n};\n\nexport { defaultAttributes as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 8v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 16h.01\", \"key\": \"svg-2\" }]];\nconst IconAlertCircle = createReactComponent(\"outline\", \"alert-circle\", \"AlertCircle\", __iconNode);\n\nexport { __iconNode, IconAlertCircle as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12 5l0 14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M18 13l-6 6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M6 13l6 6\", \"key\": \"svg-2\" }]];\nconst IconArrowDown = createReactComponent(\"outline\", \"arrow-down\", \"ArrowDown\", __iconNode);\n\nexport { __iconNode, IconArrowDown as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 12l14 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M13 18l6 -6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M13 6l6 6\", \"key\": \"svg-2\" }]];\nconst IconArrowRight = createReactComponent(\"outline\", \"arrow-right\", \"ArrowRight\", __iconNode);\n\nexport { __iconNode, IconArrowRight as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12 5l0 14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M18 11l-6 -6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M6 11l6 -6\", \"key\": \"svg-2\" }]];\nconst IconArrowUp = createReactComponent(\"outline\", \"arrow-up\", \"ArrowUp\", __iconNode);\n\nexport { __iconNode, IconArrowUp as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 9l4 -4l4 4m-4 -4v14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21 15l-4 4l-4 -4m4 4v-14\", \"key\": \"svg-1\" }]];\nconst IconArrowsSort = createReactComponent(\"outline\", \"arrows-sort\", \"ArrowsSort\", __iconNode);\n\nexport { __iconNode, IconArrowsSort as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M6 20a2 2 0 1 0 -4 0a2 2 0 0 0 4 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 4a2 2 0 1 0 -4 0a2 2 0 0 0 4 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M16 20a2 2 0 1 0 -4 0a2 2 0 0 0 4 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M11 12a2 2 0 1 0 -4 0a2 2 0 0 0 4 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M21 12a2 2 0 1 0 -4 0a2 2 0 0 0 4 0\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M5.058 18.306l2.88 -4.606\", \"key\": \"svg-5\" }], [\"path\", { \"d\": \"M10.061 10.303l2.877 -4.604\", \"key\": \"svg-6\" }], [\"path\", { \"d\": \"M10.065 13.705l2.876 4.6\", \"key\": \"svg-7\" }], [\"path\", { \"d\": \"M15.063 5.7l2.881 4.61\", \"key\": \"svg-8\" }]];\nconst IconBinaryTree = createReactComponent(\"outline\", \"binary-tree\", \"BinaryTree\", __iconNode);\n\nexport { __iconNode, IconBinaryTree as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 19h14m1.986 -1.977a2 2 0 0 0 -.146 -.773l-7.1 -12.25a2 2 0 0 0 -3.5 0l-.815 1.405m-1.488 2.568l-4.797 8.277a2 2 0 0 0 1.75 2.75\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 3l18 18\", \"key\": \"svg-1\" }]];\nconst IconBleachOff = createReactComponent(\"outline\", \"bleach-off\", \"BleachOff\", __iconNode);\n\nexport { __iconNode, IconBleachOff as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 19h14a2 2 0 0 0 1.84 -2.75l-7.1 -12.25a2 2 0 0 0 -3.5 0l-7.1 12.25a2 2 0 0 0 1.75 2.75\", \"key\": \"svg-0\" }]];\nconst IconBleach = createReactComponent(\"outline\", \"bleach\", \"Bleach\", __iconNode);\n\nexport { __iconNode, IconBleach as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M18 7v14l-6 -4l-6 4v-14a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4\", \"key\": \"svg-0\" }]];\nconst IconBookmark = createReactComponent(\"outline\", \"bookmark\", \"Bookmark\", __iconNode);\n\nexport { __iconNode, IconBookmark as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 4h-4v16h4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M17 4h4v16h-4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 16h.01\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M12 16h.01\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M16 16h.01\", \"key\": \"svg-4\" }]];\nconst IconBracketsContain = createReactComponent(\"outline\", \"brackets-contain\", \"BracketsContain\", __iconNode);\n\nexport { __iconNode, IconBracketsContain as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 9a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2l0 -9\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M8 7v-2a2 2 0 0 1 2 -2h4a2 2 0 0 1 2 2v2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 12l0 .01\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M3 13a20 20 0 0 0 18 0\", \"key\": \"svg-3\" }]];\nconst IconBriefcase = createReactComponent(\"outline\", \"briefcase\", \"Briefcase\", __iconNode);\n\nexport { __iconNode, IconBriefcase as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5.029 5.036c-.655 .58 -1.029 1.25 -1.029 1.964c0 2.033 3.033 3.712 6.96 3.967m3.788 -.21c3.064 -.559 5.252 -2.029 5.252 -3.757c0 -2.21 -3.582 -4 -8 -4c-1.605 0 -3.1 .236 -4.352 .643\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.1 -.3 .252 -.812 .457 -1.535m.862 -3.146c.262 -.975 .735 -2.76 1.418 -5.354a7.45 7.45 0 0 0 .263 -1.965\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M3 3l18 18\", \"key\": \"svg-2\" }]];\nconst IconBucketOff = createReactComponent(\"outline\", \"bucket-off\", \"BucketOff\", __iconNode);\n\nexport { __iconNode, IconBucketOff as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 7a8 4 0 1 0 16 0a8 4 0 1 0 -16 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 7c0 .664 .088 1.324 .263 1.965l2.737 10.035c.5 1.5 2.239 2 5 2s4.5 -.5 5 -2c.333 -1 1.246 -4.345 2.737 -10.035a7.45 7.45 0 0 0 .263 -1.965\", \"key\": \"svg-1\" }]];\nconst IconBucket = createReactComponent(\"outline\", \"bucket\", \"Bucket\", __iconNode);\n\nexport { __iconNode, IconBucket as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 20h18v-8a3 3 0 0 0 -3 -3h-12a3 3 0 0 0 -3 3v8\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 14.803c.312 .135 .654 .204 1 .197a2.4 2.4 0 0 0 2 -1a2.4 2.4 0 0 1 2 -1a2.4 2.4 0 0 1 2 1a2.4 2.4 0 0 0 2 1a2.4 2.4 0 0 0 2 -1a2.4 2.4 0 0 1 2 -1a2.4 2.4 0 0 1 2 1a2.4 2.4 0 0 0 2 1c.35 .007 .692 -.062 1 -.197\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 4l1.465 1.638a2 2 0 1 1 -3.015 .099l1.55 -1.737\", \"key\": \"svg-2\" }]];\nconst IconCake = createReactComponent(\"outline\", \"cake\", \"Cake\", __iconNode);\n\nexport { __iconNode, IconCake as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -12\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M11 16a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-4\" }]];\nconst IconCalendarDue = createReactComponent(\"outline\", \"calendar-due\", \"CalendarDue\", __iconNode);\n\nexport { __iconNode, IconCalendarDue as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -12\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3l0 4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3l0 4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11l16 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M8 15h2v2h-2l0 -2\", \"key\": \"svg-4\" }]];\nconst IconCalendarEvent = createReactComponent(\"outline\", \"calendar-event\", \"CalendarEvent\", __iconNode);\n\nexport { __iconNode, IconCalendarEvent as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 7a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16 3v4\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 11h16\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M8 14v4\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M12 14v4\", \"key\": \"svg-5\" }], [\"path\", { \"d\": \"M16 14v4\", \"key\": \"svg-6\" }]];\nconst IconCalendarMonth = createReactComponent(\"outline\", \"calendar-month\", \"CalendarMonth\", __iconNode);\n\nexport { __iconNode, IconCalendarMonth as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M11.795 21h-6.795a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M14 18a4 4 0 1 0 8 0a4 4 0 1 0 -8 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M15 3v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M7 3v4\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M3 11h16\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M18 16.496v1.504l1 1\", \"key\": \"svg-5\" }]];\nconst IconCalendarTime = createReactComponent(\"outline\", \"calendar-time\", \"CalendarTime\", __iconNode);\n\nexport { __iconNode, IconCalendarTime as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 12l5 5l10 -10\", \"key\": \"svg-0\" }]];\nconst IconCheck = createReactComponent(\"outline\", \"check\", \"Check\", __iconNode);\n\nexport { __iconNode, IconCheck as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 11l3 3l8 -8\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M20 12v6a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2h9\", \"key\": \"svg-1\" }]];\nconst IconCheckbox = createReactComponent(\"outline\", \"checkbox\", \"Checkbox\", __iconNode);\n\nexport { __iconNode, IconCheckbox as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M6 9l6 6l6 -6\", \"key\": \"svg-0\" }]];\nconst IconChevronDown = createReactComponent(\"outline\", \"chevron-down\", \"ChevronDown\", __iconNode);\n\nexport { __iconNode, IconChevronDown as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M15 6l-6 6l6 6\", \"key\": \"svg-0\" }]];\nconst IconChevronLeft = createReactComponent(\"outline\", \"chevron-left\", \"ChevronLeft\", __iconNode);\n\nexport { __iconNode, IconChevronLeft as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 6l6 6l-6 6\", \"key\": \"svg-0\" }]];\nconst IconChevronRight = createReactComponent(\"outline\", \"chevron-right\", \"ChevronRight\", __iconNode);\n\nexport { __iconNode, IconChevronRight as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M6 15l6 -6l6 6\", \"key\": \"svg-0\" }]];\nconst IconChevronUp = createReactComponent(\"outline\", \"chevron-up\", \"ChevronUp\", __iconNode);\n\nexport { __iconNode, IconChevronUp as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 1 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 12l6 0\", \"key\": \"svg-1\" }]];\nconst IconCircleMinus = createReactComponent(\"outline\", \"circle-minus\", \"CircleMinus\", __iconNode);\n\nexport { __iconNode, IconCircleMinus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 12h6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 9v6\", \"key\": \"svg-2\" }]];\nconst IconCirclePlus = createReactComponent(\"outline\", \"circle-plus\", \"CirclePlus\", __iconNode);\n\nexport { __iconNode, IconCirclePlus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 5a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 14l2 2l4 -4\", \"key\": \"svg-2\" }]];\nconst IconClipboardCheck = createReactComponent(\"outline\", \"clipboard-check\", \"ClipboardCheck\", __iconNode);\n\nexport { __iconNode, IconClipboardCheck as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 18a4.6 4.4 0 0 1 0 -9a5 4.5 0 0 1 11 2h1a3.5 3.5 0 0 1 0 7h-1\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 15l3 -3l3 3\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 12l0 9\", \"key\": \"svg-2\" }]];\nconst IconCloudUpload = createReactComponent(\"outline\", \"cloud-upload\", \"CloudUpload\", __iconNode);\n\nexport { __iconNode, IconCloudUpload as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 6l5.5 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 10l5.5 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M4 14l5.5 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 18l5.5 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M14.5 6l5.5 0\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M14.5 10l5.5 0\", \"key\": \"svg-5\" }], [\"path\", { \"d\": \"M14.5 14l5.5 0\", \"key\": \"svg-6\" }], [\"path\", { \"d\": \"M14.5 18l5.5 0\", \"key\": \"svg-7\" }]];\nconst IconColumns = createReactComponent(\"outline\", \"columns\", \"Columns\", __iconNode);\n\nexport { __iconNode, IconColumns as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 9.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667l0 -8.666\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1\", \"key\": \"svg-1\" }]];\nconst IconCopy = createReactComponent(\"outline\", \"copy\", \"Copy\", __iconNode);\n\nexport { __iconNode, IconCopy as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M16.7 8a3 3 0 0 0 -2.7 -2h-4a3 3 0 0 0 0 6h4a3 3 0 0 1 0 6h-4a3 3 0 0 1 -2.7 -2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 3v3m0 12v3\", \"key\": \"svg-1\" }]];\nconst IconCurrencyDollar = createReactComponent(\"outline\", \"currency-dollar\", \"CurrencyDollar\", __iconNode);\n\nexport { __iconNode, IconCurrencyDollar as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 5a1 1 0 0 1 1 -1h16a1 1 0 0 1 1 1v10a1 1 0 0 1 -1 1h-16a1 1 0 0 1 -1 -1v-10\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M7 20h10\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 16v4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M15 16v4\", \"key\": \"svg-3\" }]];\nconst IconDeviceDesktop = createReactComponent(\"outline\", \"device-desktop\", \"DeviceDesktop\", __iconNode);\n\nexport { __iconNode, IconDeviceDesktop as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M11 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M18 12a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-2\" }]];\nconst IconDots = createReactComponent(\"outline\", \"dots\", \"Dots\", __iconNode);\n\nexport { __iconNode, IconDots as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M7 11l5 5l5 -5\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 4l0 12\", \"key\": \"svg-2\" }]];\nconst IconDownload = createReactComponent(\"outline\", \"download\", \"Download\", __iconNode);\n\nexport { __iconNode, IconDownload as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 7h-1a2 2 0 0 0 -2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2 -2v-1\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M20.385 6.585a2.1 2.1 0 0 0 -2.97 -2.97l-8.415 8.385v3h3l8.385 -8.415\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M16 5l3 3\", \"key\": \"svg-2\" }]];\nconst IconEdit = createReactComponent(\"outline\", \"edit\", \"Edit\", __iconNode);\n\nexport { __iconNode, IconEdit as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9.5 5.5a2.5 2.5 0 1 0 5 0a2.5 2.5 0 1 0 -5 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 21.368l5.095 -5.096a3.088 3.088 0 1 0 -4.367 -4.367l-.728 .727l-.728 -.727a3.088 3.088 0 1 0 -4.367 4.367l5.095 5.096\", \"key\": \"svg-1\" }]];\nconst IconEmpathize = createReactComponent(\"outline\", \"empathize\", \"Empathize\", __iconNode);\n\nexport { __iconNode, IconEmpathize as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 10h14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 14h14\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M5 19l14 -14\", \"key\": \"svg-2\" }]];\nconst IconEqualNot = createReactComponent(\"outline\", \"equal-not\", \"EqualNot\", __iconNode);\n\nexport { __iconNode, IconEqualNot as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 10h14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 14h14\", \"key\": \"svg-1\" }]];\nconst IconEqual = createReactComponent(\"outline\", \"equal\", \"Equal\", __iconNode);\n\nexport { __iconNode, IconEqual as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M10.585 10.587a2 2 0 0 0 2.829 2.828\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M3 3l18 18\", \"key\": \"svg-2\" }]];\nconst IconEyeOff = createReactComponent(\"outline\", \"eye-off\", \"EyeOff\", __iconNode);\n\nexport { __iconNode, IconEyeOff as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6\", \"key\": \"svg-1\" }]];\nconst IconEye = createReactComponent(\"outline\", \"eye\", \"Eye\", __iconNode);\n\nexport { __iconNode, IconEye as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M14 3v4a1 1 0 0 0 1 1h4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M12 17l.01 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M12 11l0 3\", \"key\": \"svg-3\" }]];\nconst IconFileAlert = createReactComponent(\"outline\", \"file-alert\", \"FileAlert\", __iconNode);\n\nexport { __iconNode, IconFileAlert as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M14 3v4a1 1 0 0 0 1 1h4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M11.5 21h-4.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v5m-5 6h7m-3 -3l3 3l-3 3\", \"key\": \"svg-1\" }]];\nconst IconFileExport = createReactComponent(\"outline\", \"file-export\", \"FileExport\", __iconNode);\n\nexport { __iconNode, IconFileExport as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M14 3v4a1 1 0 0 0 1 1h4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 9l1 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M9 13l6 0\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M9 17l6 0\", \"key\": \"svg-4\" }]];\nconst IconFileText = createReactComponent(\"outline\", \"file-text\", \"FileText\", __iconNode);\n\nexport { __iconNode, IconFileText as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 6h16\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M6 12h10\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M9 18h3\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M19 15v6\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M16 18h6\", \"key\": \"svg-4\" }]];\nconst IconFilter2Plus = createReactComponent(\"outline\", \"filter-2-plus\", \"Filter2Plus\", __iconNode);\n\nexport { __iconNode, IconFilter2Plus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 3l6 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M10 9l4 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M10 3v6l-4 11a.7 .7 0 0 0 .5 1h11a.7 .7 0 0 0 .5 -1l-4 -11v-6\", \"key\": \"svg-2\" }]];\nconst IconFlask = createReactComponent(\"outline\", \"flask\", \"Flask\", __iconNode);\n\nexport { __iconNode, IconFlask as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 12a9 9 0 1 0 18 0a9 9 0 0 0 -18 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M12 9h.01\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M11 12h1v4h1\", \"key\": \"svg-2\" }]];\nconst IconInfoCircle = createReactComponent(\"outline\", \"info-circle\", \"InfoCircle\", __iconNode);\n\nexport { __iconNode, IconInfoCircle as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 6.371c0 4.418 -2.239 6.629 -5 6.629\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 6.371h7\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M5 9c0 2.144 2.252 3.908 6 4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M12 20l4 -9l4 9\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M19.1 18h-6.2\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M6.694 3l.793 .582\", \"key\": \"svg-5\" }]];\nconst IconLanguage = createReactComponent(\"outline\", \"language\", \"Language\", __iconNode);\n\nexport { __iconNode, IconLanguage as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 6a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2l0 -12\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 4l0 16\", \"key\": \"svg-1\" }]];\nconst IconLayoutSidebar = createReactComponent(\"outline\", \"layout-sidebar\", \"LayoutSidebar\", __iconNode);\n\nexport { __iconNode, IconLayoutSidebar as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 5.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667l0 -8.666\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4.012 7.26a2.005 2.005 0 0 0 -1.012 1.737v10c0 1.1 .9 2 2 2h10c.75 0 1.158 -.385 1.5 -1\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M11 10h6\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M14 7v6\", \"key\": \"svg-3\" }]];\nconst IconLibraryPlus = createReactComponent(\"outline\", \"library-plus\", \"LibraryPlus\", __iconNode);\n\nexport { __iconNode, IconLibraryPlus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M14 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 12h12l-3 -3\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M18 15l3 -3\", \"key\": \"svg-2\" }]];\nconst IconLogout = createReactComponent(\"outline\", \"logout\", \"Logout\", __iconNode);\n\nexport { __iconNode, IconLogout as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0\", \"key\": \"svg-1\" }]];\nconst IconMapPin = createReactComponent(\"outline\", \"map-pin\", \"MapPin\", __iconNode);\n\nexport { __iconNode, IconMapPin as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 18l14 -6l-14 -6\", \"key\": \"svg-0\" }]];\nconst IconMathGreater = createReactComponent(\"outline\", \"math-greater\", \"MathGreater\", __iconNode);\n\nexport { __iconNode, IconMathGreater as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M19 18l-14 -6l14 -6\", \"key\": \"svg-0\" }]];\nconst IconMathLower = createReactComponent(\"outline\", \"math-lower\", \"MathLower\", __iconNode);\n\nexport { __iconNode, IconMathLower as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1\", \"key\": \"svg-0\" }]];\nconst IconMessageCircle = createReactComponent(\"outline\", \"message-circle\", \"MessageCircle\", __iconNode);\n\nexport { __iconNode, IconMessageCircle as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M8 9h8\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M8 13h6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M18 4a3 3 0 0 1 3 3v8a3 3 0 0 1 -3 3h-5l-5 3v-3h-2a3 3 0 0 1 -3 -3v-8a3 3 0 0 1 3 -3h12\", \"key\": \"svg-2\" }]];\nconst IconMessage = createReactComponent(\"outline\", \"message\", \"Message\", __iconNode);\n\nexport { __iconNode, IconMessage as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M9 5a3 3 0 0 1 3 -3a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3a3 3 0 0 1 -3 -3l0 -5\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 10a7 7 0 0 0 14 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 21l8 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M12 17l0 4\", \"key\": \"svg-3\" }]];\nconst IconMicrophone = createReactComponent(\"outline\", \"microphone\", \"Microphone\", __iconNode);\n\nexport { __iconNode, IconMicrophone as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 12l14 0\", \"key\": \"svg-0\" }]];\nconst IconMinus = createReactComponent(\"outline\", \"minus\", \"Minus\", __iconNode);\n\nexport { __iconNode, IconMinus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12 3c.132 0 .263 0 .393 0a7.5 7.5 0 0 0 7.92 12.446a9 9 0 1 1 -8.313 -12.454l0 .008\", \"key\": \"svg-0\" }]];\nconst IconMoon = createReactComponent(\"outline\", \"moon\", \"Moon\", __iconNode);\n\nexport { __iconNode, IconMoon as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12 21a9 9 0 0 1 0 -18c4.97 0 9 3.582 9 8c0 1.06 -.474 2.078 -1.318 2.828c-.844 .75 -1.989 1.172 -3.182 1.172h-2.5a2 2 0 0 0 -1 3.75a1.3 1.3 0 0 1 -1 2.25\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M7.5 10.5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M11.5 7.5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M15.5 10.5a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\", \"key\": \"svg-3\" }]];\nconst IconPalette = createReactComponent(\"outline\", \"palette\", \"Palette\", __iconNode);\n\nexport { __iconNode, IconPalette as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M15 7l-6.5 6.5a1.5 1.5 0 0 0 3 3l6.5 -6.5a3 3 0 0 0 -6 -6l-6.5 6.5a4.5 4.5 0 0 0 9 9l6.5 -6.5\", \"key\": \"svg-0\" }]];\nconst IconPaperclip = createReactComponent(\"outline\", \"paperclip\", \"Paperclip\", __iconNode);\n\nexport { __iconNode, IconPaperclip as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M13.5 6.5l4 4\", \"key\": \"svg-1\" }]];\nconst IconPencil = createReactComponent(\"outline\", \"pencil\", \"Pencil\", __iconNode);\n\nexport { __iconNode, IconPencil as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12 5l0 14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M5 12l14 0\", \"key\": \"svg-1\" }]];\nconst IconPlus = createReactComponent(\"outline\", \"plus\", \"Plus\", __iconNode);\n\nexport { __iconNode, IconPlus as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M19.933 13.041a8 8 0 1 1 -9.925 -8.788c3.899 -1 7.935 1.007 9.425 4.747\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M20 4v5h-5\", \"key\": \"svg-1\" }]];\nconst IconReload = createReactComponent(\"outline\", \"reload\", \"Reload\", __iconNode);\n\nexport { __iconNode, IconReload as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 10a7 7 0 1 0 14 0a7 7 0 1 0 -14 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21 21l-6 -6\", \"key\": \"svg-1\" }]];\nconst IconSearch = createReactComponent(\"outline\", \"search\", \"Search\", __iconNode);\n\nexport { __iconNode, IconSearch as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M10 14l11 -11\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M21 3l-6.5 18a.55 .55 0 0 1 -1 0l-3.5 -7l-7 -3.5a.55 .55 0 0 1 0 -1l18 -6.5\", \"key\": \"svg-1\" }]];\nconst IconSend = createReactComponent(\"outline\", \"send\", \"Send\", __iconNode);\n\nexport { __iconNode, IconSend as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M10.325 4.317c.426 -1.756 2.924 -1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543 -.94 3.31 .826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756 .426 1.756 2.924 0 3.35a1.724 1.724 0 0 0 -1.066 2.573c.94 1.543 -.826 3.31 -2.37 2.37a1.724 1.724 0 0 0 -2.572 1.065c-.426 1.756 -2.924 1.756 -3.35 0a1.724 1.724 0 0 0 -2.573 -1.066c-1.543 .94 -3.31 -.826 -2.37 -2.37a1.724 1.724 0 0 0 -1.065 -2.572c-1.756 -.426 -1.756 -2.924 0 -3.35a1.724 1.724 0 0 0 1.066 -2.573c-.94 -1.543 .826 -3.31 2.37 -2.37c1 .608 2.296 .07 2.572 -1.065\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\", \"key\": \"svg-1\" }]];\nconst IconSettings = createReactComponent(\"outline\", \"settings\", \"Settings\", __iconNode);\n\nexport { __iconNode, IconSettings as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 6l7 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 12l7 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M4 18l9 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M15 9l3 -3l3 3\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M18 6l0 12\", \"key\": \"svg-4\" }]];\nconst IconSortAscending = createReactComponent(\"outline\", \"sort-ascending\", \"SortAscending\", __iconNode);\n\nexport { __iconNode, IconSortAscending as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 6l9 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M4 12l7 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M4 18l7 0\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M15 15l3 3l3 -3\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M18 6l0 12\", \"key\": \"svg-4\" }]];\nconst IconSortDescending = createReactComponent(\"outline\", \"sort-descending\", \"SortDescending\", __iconNode);\n\nexport { __iconNode, IconSortDescending as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 5a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14\", \"key\": \"svg-0\" }]];\nconst IconSquare = createReactComponent(\"outline\", \"square\", \"Square\", __iconNode);\n\nexport { __iconNode, IconSquare as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M6 4h-1a2 2 0 0 0 -2 2v3.5a5.5 5.5 0 0 0 11 0v-3.5a2 2 0 0 0 -2 -2h-1\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M8 15a6 6 0 1 0 12 0v-3\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M11 3v2\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M6 3v2\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M18 10a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\", \"key\": \"svg-4\" }]];\nconst IconStethoscope = createReactComponent(\"outline\", \"stethoscope\", \"Stethoscope\", __iconNode);\n\nexport { __iconNode, IconStethoscope as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M14.828 14.828a4 4 0 1 0 -5.656 -5.656a4 4 0 0 0 5.656 5.656\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M6.343 17.657l-1.414 1.414\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M6.343 6.343l-1.414 -1.414\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M17.657 6.343l1.414 -1.414\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M17.657 17.657l1.414 1.414\", \"key\": \"svg-4\" }], [\"path\", { \"d\": \"M4 12h-2\", \"key\": \"svg-5\" }], [\"path\", { \"d\": \"M12 4v-2\", \"key\": \"svg-6\" }], [\"path\", { \"d\": \"M20 12h2\", \"key\": \"svg-7\" }], [\"path\", { \"d\": \"M12 20v2\", \"key\": \"svg-8\" }]];\nconst IconSunHigh = createReactComponent(\"outline\", \"sun-high\", \"SunHigh\", __iconNode);\n\nexport { __iconNode, IconSunHigh as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M16 3l4 4l-4 4\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M10 7l10 0\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M8 13l-4 4l4 4\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M4 17l9 0\", \"key\": \"svg-3\" }]];\nconst IconSwitchHorizontal = createReactComponent(\"outline\", \"switch-horizontal\", \"SwitchHorizontal\", __iconNode);\n\nexport { __iconNode, IconSwitchHorizontal as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M12.5 21h-7.5a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v7.5\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 10h18\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M10 3v18\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M16 19h6\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M19 16l3 3l-3 3\", \"key\": \"svg-4\" }]];\nconst IconTableExport = createReactComponent(\"outline\", \"table-export\", \"TableExport\", __iconNode);\n\nexport { __iconNode, IconTableExport as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M3 5a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-14\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 10h18\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M10 3v18\", \"key\": \"svg-2\" }]];\nconst IconTable = createReactComponent(\"outline\", \"table\", \"Table\", __iconNode);\n\nexport { __iconNode, IconTable as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M4 7l16 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M10 11l0 6\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M14 11l0 6\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12\", \"key\": \"svg-3\" }], [\"path\", { \"d\": \"M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3\", \"key\": \"svg-4\" }]];\nconst IconTrash = createReactComponent(\"outline\", \"trash\", \"Trash\", __iconNode);\n\nexport { __iconNode, IconTrash as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M5 7a4 4 0 1 0 8 0a4 4 0 1 0 -8 0\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2\", \"key\": \"svg-1\" }], [\"path\", { \"d\": \"M16 3.13a4 4 0 0 1 0 7.75\", \"key\": \"svg-2\" }], [\"path\", { \"d\": \"M21 21v-2a4 4 0 0 0 -3 -3.85\", \"key\": \"svg-3\" }]];\nconst IconUsers = createReactComponent(\"outline\", \"users\", \"Users\", __iconNode);\n\nexport { __iconNode, IconUsers as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M18 6l-12 12\", \"key\": \"svg-0\" }], [\"path\", { \"d\": \"M6 6l12 12\", \"key\": \"svg-1\" }]];\nconst IconX = createReactComponent(\"outline\", \"x\", \"X\", __iconNode);\n\nexport { __iconNode, IconX as default };\n", "/**\n * @license @tabler/icons-react v3.51.0 - MIT\n *\n * This source code is licensed under the MIT license.\n * See the LICENSE file in the root directory of this source tree.\n */\n\nimport createReactComponent from '../createReactComponent.mjs';\n\nconst __iconNode = [[\"path\", { \"d\": \"M7 3.34a10 10 0 1 1 -4.995 8.984l-.005 -.324l.005 -.324a10 10 0 0 1 4.995 -8.336z\", \"key\": \"svg-0\" }]];\nconst IconCircleFilled = createReactComponent(\"filled\", \"circle-filled\", \"CircleFilled\", __iconNode);\n\nexport { __iconNode, IconCircleFilled as default };\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Center, Loader } from '@mantine/core';\nimport type { JSX } from 'react';\n\nexport function Loading(): JSX.Element {\n  return (\n    <Center style={{ width: '100%', height: '100vh' }}>\n      <Loader />\n    </Center>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MantineColor } from '@mantine/core';\nimport { Box, CloseButton, Group, Text } from '@mantine/core';\nimport type { AriaRole, JSX, ReactNode } from 'react';\nimport classes from './AppShell.module.css';\n\nexport interface AppShellAnnouncement {\n  readonly id?: string;\n  readonly message: ReactNode;\n  readonly color?: MantineColor;\n  readonly icon?: ReactNode;\n  readonly dismissible?: boolean;\n  readonly onDismiss?: (announcement: AppShellAnnouncement) => void;\n  readonly role?: AriaRole;\n}\n\ninterface AnnouncementBannersProps {\n  readonly announcements: AppShellAnnouncement[];\n  readonly onDismiss: (announcement: AppShellAnnouncement) => void;\n}\n\nexport function AnnouncementBanners(props: AnnouncementBannersProps): JSX.Element {\n  return (\n    <>\n      {props.announcements.map((announcement, index) => (\n        <Box\n          key={announcement.id ?? index}\n          className={classes.announcement}\n          style={{\n            backgroundColor: `var(--mantine-color-${announcement.color ?? 'yellow'}-light)`,\n            color: `var(--mantine-color-${announcement.color ?? 'yellow'}-light-color)`,\n          }}\n          role={announcement.role ?? 'status'}\n        >\n          <Group gap=\"xs\" wrap=\"nowrap\" h=\"100%\" px=\"md\">\n            {announcement.icon}\n            <Text size=\"sm\" fw={500} truncate>\n              {announcement.message}\n            </Text>\n            {announcement.dismissible && (\n              <CloseButton\n                size=\"sm\"\n                variant=\"subtle\"\n                aria-label=\"Dismiss announcement\"\n                onClick={() => props.onDismiss(announcement)}\n                ml=\"auto\"\n              />\n            )}\n          </Group>\n        </Box>\n      ))}\n    </>\n  );\n}\n", ".main {\n  flex: 1;\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n  overflow-x: auto;\n}\n\n.announcement {\n  height: 36px;\n  border-top: 1px solid var(--mantine-color-default-border);\n  overflow: hidden;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Group, AppShell as MantineAppShell, Menu, Stack, Text, UnstyledButton } from '@mantine/core';\nimport { formatHumanName } from '@medplum/core';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport type { AppShellAnnouncement } from './AnnouncementBanners';\nimport { AnnouncementBanners } from './AnnouncementBanners';\nimport classes from './Header.module.css';\nimport { HeaderDropdown } from './HeaderDropdown';\nimport headerDropdownClasses from './HeaderDropdown.module.css';\nimport { HeaderSearchInput } from './HeaderSearchInput';\nimport { userMenuMiddlewares } from './userMenuMiddlewares';\n\nexport interface HeaderProps {\n  readonly pathname?: string;\n  readonly searchParams?: URLSearchParams;\n  readonly headerSearchDisabled?: boolean;\n  readonly logo: ReactNode;\n  readonly version?: string;\n  readonly navbarOpen?: boolean;\n  readonly navbarToggle: () => void;\n  readonly notifications?: ReactNode;\n  readonly announcements?: AppShellAnnouncement[];\n  readonly onDismissAnnouncement?: (announcement: AppShellAnnouncement) => void;\n}\n\nexport function Header(props: HeaderProps): JSX.Element {\n  const medplum = useMedplum();\n  const profile = useMedplumProfile();\n  const [userMenuOpened, setUserMenuOpened] = useState(false);\n  const projectDisplay = medplum.getProject()?.name ?? medplum.getActiveLogin()?.project.display;\n\n  return (\n    <MantineAppShell.Header p={0} style={{ zIndex: 101 }}>\n      <Box p={8} h={60}>\n        <Group justify=\"space-between\">\n          <Group gap=\"xs\">\n            <UnstyledButton\n              className={classes.logoButton}\n              aria-expanded={props.navbarOpen}\n              aria-controls=\"navbar\"\n              onClick={() => props.navbarToggle()}\n            >\n              {props.logo}\n            </UnstyledButton>\n            {!props.headerSearchDisabled && (\n              <HeaderSearchInput pathname={props.pathname} searchParams={props.searchParams} />\n            )}\n          </Group>\n          <Group gap=\"lg\" pr=\"sm\">\n            {props.notifications}\n            <Menu\n              width={260}\n              shadow=\"md\"\n              radius=\"md\"\n              position=\"bottom-end\"\n              middlewares={userMenuMiddlewares}\n              transitionProps={{ transition: 'fade-down' }}\n              opened={userMenuOpened}\n              onClose={() => setUserMenuOpened(false)}\n            >\n              <Menu.Target>\n                <UnstyledButton\n                  className={classes.user}\n                  aria-label=\"User menu\"\n                  data-active={userMenuOpened || undefined}\n                  onClick={() => setUserMenuOpened((o) => !o)}\n                >\n                  <Group gap={7}>\n                    <ResourceAvatar value={profile} radius=\"xl\" size={24} />\n                    <Stack gap={0} className={classes.userInfo}>\n                      <Text size=\"sm\" className={classes.userName} truncate>\n                        {formatHumanName(profile?.name?.[0])}\n                      </Text>\n                      {projectDisplay && (\n                        <Text size=\"xs\" c=\"dimmed\" className={classes.userProject} title={projectDisplay} truncate>\n                          {projectDisplay}\n                        </Text>\n                      )}\n                    </Stack>\n                    <IconChevronDown size={12} stroke={1.5} />\n                  </Group>\n                </UnstyledButton>\n              </Menu.Target>\n              <Menu.Dropdown className={headerDropdownClasses.dropdown}>\n                <HeaderDropdown version={props.version} />\n              </Menu.Dropdown>\n            </Menu>\n          </Group>\n        </Group>\n      </Box>\n      {!!props.announcements?.length && props.onDismissAnnouncement && (\n        <AnnouncementBanners announcements={props.announcements} onDismiss={props.onDismissAnnouncement} />\n      )}\n    </MantineAppShell.Header>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AvatarProps } from '@mantine/core';\nimport { Avatar } from '@mantine/core';\nimport { getDisplayString, getImageSrc } from '@medplum/core';\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl, useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { getInitials } from './ResourceAvatar.utils';\n\nexport interface ResourceAvatarProps extends AvatarProps {\n  readonly value?: Reference | Resource;\n  readonly link?: boolean;\n}\n\nexport function ResourceAvatar(props: ResourceAvatarProps): JSX.Element {\n  const resource = useResource(props.value);\n  const text = resource ? getDisplayString(resource) : (props.alt ?? '');\n  const initials = getInitials(text);\n  const uncachedImageUrl = (resource && getImageSrc(resource)) ?? props.src;\n  const imageUrl = useCachedBinaryUrl(uncachedImageUrl ?? undefined);\n  const radius = props.radius ?? 'xl';\n\n  const avatarProps = { ...props, value: undefined, link: undefined };\n\n  if (props.link) {\n    return (\n      <MedplumLink to={resource}>\n        <Avatar src={imageUrl} alt={text} radius={radius} {...avatarProps}>\n          {initials}\n        </Avatar>\n      </MedplumLink>\n    );\n  }\n\n  return (\n    <Avatar src={imageUrl} alt={text} radius={radius} {...avatarProps}>\n      {initials}\n    </Avatar>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AnchorProps, ElementProps } from '@mantine/core';\nimport { Anchor } from '@mantine/core';\nimport { isReference, isResource } from '@medplum/core';\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport type { JSX, MouseEvent, MouseEventHandler, ReactNode } from 'react';\nimport { isAuxClick } from '../utils/dom';\n\nexport interface MedplumLinkProps extends AnchorProps, ElementProps<'a', keyof AnchorProps> {\n  readonly to?: Resource | Reference | string;\n  readonly suffix?: string;\n  readonly label?: string;\n  readonly onClick?: MouseEventHandler;\n  readonly children: ReactNode;\n}\n\nexport function MedplumLink(props: MedplumLinkProps): JSX.Element {\n  const navigate = useMedplumNavigate();\n  const { to, suffix, label, onClick, children, ...rest } = props;\n\n  let href = getHref(to);\n  if (suffix) {\n    href += '/' + suffix;\n  }\n\n  return (\n    <Anchor\n      href={href}\n      aria-label={label}\n      onAuxClick={(e: MouseEvent) => {\n        // allow default browser behavior for anchor aux clicks\n        e.stopPropagation();\n      }}\n      onClick={(e: MouseEvent) => {\n        e.stopPropagation();\n        if (onClick) {\n          // onClick() takes the place of default anchor click behavior\n          e.preventDefault();\n          onClick(e);\n        } else if (to) {\n          // allow default browser behavior for anchor aux clicks\n          if (!isAuxClick(e)) {\n            // navigate() takes the place of default anchor click behavior\n            e.preventDefault();\n            navigate(href);\n          }\n        }\n      }}\n      {...rest}\n    >\n      {children}\n    </Anchor>\n  );\n}\n\nfunction getHref(to: Resource | Reference | string | undefined): string {\n  if (to) {\n    if (typeof to === 'string') {\n      return getStringHref(to);\n    } else if (isResource(to)) {\n      return getResourceHref(to);\n    } else if (isReference(to)) {\n      return getReferenceHref(to);\n    }\n  }\n  return '#';\n}\n\nfunction getStringHref(to: string): string {\n  if (to.startsWith('http://') || to.startsWith('https://') || to.startsWith('/')) {\n    return to;\n  }\n  return '/' + to;\n}\n\nfunction getResourceHref(to: Resource): string {\n  return `/${to.resourceType}/${to.id}`;\n}\n\nfunction getReferenceHref(to: Reference): string {\n  return `/${to.reference}`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ContentType } from '@medplum/core';\nimport type { MouseEvent, SyntheticEvent } from 'react';\n\n/**\n * Kills a browser event.\n * Prevents default behavior.\n * Stops event propagation.\n * @param e - The event.\n */\nexport function killEvent(e: Event | SyntheticEvent): void {\n  e.preventDefault();\n  e.stopPropagation();\n}\n\n/**\n * Returns true if the event is an auxiliary click.\n * @param e - The event.\n * @returns True if the event is an auxiliary click.\n */\nexport function isAuxClick(e: MouseEvent): boolean {\n  return e.button === 1 || e.ctrlKey || e.metaKey;\n}\n\n/**\n * Returns true if the element is a checkbox or a table cell containing a checkbox.\n * Table cells containing checkboxes are commonly accidentally clicked.\n * @param el - The HTML DOM element.\n * @returns True if the element is a checkbox or a table cell containing a checkbox.\n */\nexport function isCheckboxCell(el: Element): boolean {\n  if (isCheckboxElement(el)) {\n    return true;\n  }\n\n  if (el instanceof HTMLTableCellElement) {\n    const children = el.children;\n    if (children.length === 1 && isCheckboxElement(children[0])) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction isCheckboxElement(el: Element): boolean {\n  return el instanceof HTMLInputElement && el.type === 'checkbox';\n}\n\nexport type Command<T = string> = {\n  command: string;\n  value?: T;\n};\n\n/**\n * Sends a structured command to the iframe using postMessage.\n *\n * Normally postMessage implies global event listeners. This method uses\n * MessageChannel to create a message channel between the iframe and the parent.\n * @param frame - The receiving IFrame.\n * @param command - The command to send.\n * @returns Promise to the response from the IFrame.\n * @see https://advancedweb.hu/how-to-use-async-await-with-postmessage/\n */\nexport async function sendCommand<T = string, R = unknown>(frame: HTMLIFrameElement, command: Command<T>): Promise<R> {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel();\n\n    channel.port1.onmessage = ({ data }) => {\n      channel.port1.close();\n      if (data.error) {\n        reject(data.error);\n      } else {\n        resolve(data.result);\n      }\n    };\n\n    frame.contentWindow?.postMessage(command, new URL(frame.src).origin, [channel.port2]);\n  });\n}\n\n/**\n * Creates a Blob object from the JSON object given and downloads the object.\n * @param jsonString - The JSON string.\n * @param fileName - Optional file name. Default is based on current timestamp.\n */\nexport function exportJsonFile(jsonString: string, fileName?: string): void {\n  const blobForExport = new Blob([jsonString], { type: ContentType.JSON });\n  const url = URL.createObjectURL(blobForExport);\n\n  const link = document.createElement('a');\n  link.href = url;\n\n  const linkName = fileName ?? new Date().toISOString().replaceAll(/\\D/g, '');\n  link.download = `${linkName}.json`;\n\n  document.body.appendChild(link);\n  link.click();\n\n  // Clean up the URL object\n  URL.revokeObjectURL(url);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nexport function getInitials(input: string): string {\n  const words = input.split(' ').filter(Boolean);\n  if (words.length > 1) {\n    return words[0][0] + words.at(-1)?.at(0);\n  }\n  if (words.length === 1) {\n    return words[0][0];\n  }\n  return '';\n}\n", ".logoButton {\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n  border-radius: var(--mantine-radius-sm);\n  transition: background-color 100ms ease;\n\n  &:hover {\n    background-color: var(--mantine-primary-color-light-hover);\n  }\n}\n\n.user {\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n  border-radius: var(--mantine-radius-sm);\n  transition: background-color 100ms ease;\n\n  &:hover {\n    background-color: var(--mantine-primary-color-light-hover);\n  }\n\n  &[data-active] {\n    background-color: var(--mantine-primary-color-light-hover);\n  }\n}\n\n.userInfo {\n  margin-right: 3px;\n  min-width: 0;\n  max-width: 160px;\n\n  @media (max-width: $mantine-breakpoint-xs) {\n    display: none;\n  }\n}\n\n.userName {\n  font-weight: 500;\n  line-height: 1.2;\n}\n\n.userProject {\n  line-height: 1.2;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MantineColorScheme } from '@mantine/core';\nimport { Box, Divider, Flex, Menu, SegmentedControl, Text, useMantineColorScheme } from '@mantine/core';\nimport type { LoginState, ProfileResource } from '@medplum/core';\nimport { formatHumanName, getReferenceString, locationUtils } from '@medplum/core';\nimport { useMedplumContext } from '@medplum/react-hooks';\nimport type { TablerIcon } from '@tabler/icons-react';\nimport {\n  IconDeviceDesktop,\n  IconLogout,\n  IconMoon,\n  IconPalette,\n  IconSettings,\n  IconSunHigh,\n  IconSwitchHorizontal,\n  IconTable,\n} from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { ProjectLoginOption } from '../auth/ProjectLoginOption';\nimport { getAppName } from '../utils/app';\nimport classes from './HeaderDropdown.module.css';\n\ntype AppShellLayoutVersion = 'v1' | 'v2';\n\nconst MENU_ICON_COLOR = 'var(--mantine-color-dimmed)';\n\nconst THEME_OPTIONS: { value: string; label: JSX.Element }[] = [\n  { value: 'light', label: <ThemeOptionLabel Icon={IconSunHigh} label=\"Light\" /> },\n  { value: 'auto', label: <ThemeOptionLabel Icon={IconDeviceDesktop} label=\"System\" /> },\n  { value: 'dark', label: <ThemeOptionLabel Icon={IconMoon} label=\"Dark\" /> },\n];\n\nconst LAYOUT_OPTIONS: { label: string; value: AppShellLayoutVersion }[] = [\n  { label: 'v1', value: 'v1' },\n  { label: 'v2', value: 'v2' },\n];\n\nfunction ThemeOptionLabel({ Icon, label }: { readonly Icon: TablerIcon; readonly label: string }): JSX.Element {\n  return (\n    <span aria-label={label} style={{ display: 'flex' }}>\n      <Icon size={16} color={MENU_ICON_COLOR} aria-hidden />\n    </span>\n  );\n}\n\nfunction HeaderDropdownDivider(): JSX.Element {\n  return <Divider my={4} mx={4} className={classes.divider} />;\n}\n\nfunction isSameLogin(a: LoginState, b: LoginState | undefined): boolean {\n  if (!b) {\n    return false;\n  }\n  return a.project.reference === b.project.reference && a.profile.reference === b.profile.reference;\n}\n\nfunction getLoginKey(login: LoginState): string {\n  return `${login.project.reference}-${login.profile.reference}`;\n}\n\nexport interface HeaderDropdownProps {\n  readonly version?: string;\n  readonly showLayoutVersionToggle?: boolean;\n}\n\nexport function HeaderDropdown(props: HeaderDropdownProps): JSX.Element {\n  const context = useMedplumContext();\n  const { medplum, profile, navigate } = context;\n  const activeLogin = medplum.getActiveLogin();\n  const logins = medplum.getLogins();\n  const recentLogins = logins.filter((login) => !isSameLogin(login, activeLogin));\n  const project = medplum.getProject();\n  const { colorScheme, setColorScheme } = useMantineColorScheme();\n  const [layoutVersion] = useState(\n    () => (localStorage['appShellLayoutVersion'] as AppShellLayoutVersion | undefined) ?? 'v1'\n  );\n  const showLayoutToggle = props.showLayoutVersionToggle ?? true;\n\n  const projectDisplay = project?.name ?? medplum.getActiveLogin()?.project.display;\n  const profileDisplay = activeLogin?.profile.display ?? (profile ? formatHumanName(profile.name?.[0]) : undefined);\n\n  function switchLogin(login: LoginState): void {\n    medplum\n      .setActiveLogin(login)\n      .then(() => locationUtils.reload())\n      .catch(console.error);\n  }\n\n  return (\n    <>\n      <Box className={classes.accountSection}>\n        <Box className={classes.projectOption}>\n          <ProjectLoginOption projectDisplay={projectDisplay} profileDisplay={profileDisplay} selected />\n        </Box>\n      </Box>\n      {recentLogins.length > 0 && (\n        <>\n          <HeaderDropdownDivider />\n          <Box className={classes.projectList} role=\"group\" aria-label=\"Projects\">\n            {recentLogins.map((login) => (\n              <Menu.Item\n                key={getLoginKey(login)}\n                className={classes.recentProjectItem}\n                onClick={() => switchLogin(login)}\n              >\n                <Box className={classes.projectOption}>\n                  <ProjectLoginOption projectDisplay={login.project.display} profileDisplay={login.profile.display} />\n                </Box>\n              </Menu.Item>\n            ))}\n          </Box>\n        </>\n      )}\n      <Box className={classes.menuFooter}>\n        <HeaderDropdownDivider />\n        <Menu.Item\n          leftSection={<IconSwitchHorizontal size={16} color={MENU_ICON_COLOR} />}\n          onClick={() => navigate('/signin')}\n        >\n          <Text size=\"sm\">Switch to another project</Text>\n        </Menu.Item>\n        <Menu.Item\n          leftSection={<IconSettings size={16} color={MENU_ICON_COLOR} />}\n          onClick={() => navigate(`/${getReferenceString(profile as ProfileResource)}`)}\n        >\n          <Text size=\"sm\">Account settings</Text>\n        </Menu.Item>\n\n        <Flex className={classes.settingsRow} align=\"center\" pl=\"sm\" pr=\"xs\" py=\"xs\">\n          <Flex align=\"center\" gap=\"xs\">\n            <IconPalette size={16} color={MENU_ICON_COLOR} />\n            <Text size=\"sm\">Appearance</Text>\n          </Flex>\n          <Box className={classes.settingsControlWrapper}>\n            <SegmentedControl\n              classNames={{ root: cx(classes.segmentedControl, classes.appearanceControl) }}\n              size=\"xs\"\n              radius=\"xl\"\n              withItemsBorders={false}\n              value={colorScheme}\n              onChange={(newValue) => setColorScheme(newValue as MantineColorScheme)}\n              data={THEME_OPTIONS}\n              aria-label=\"Color scheme\"\n            />\n          </Box>\n        </Flex>\n        {showLayoutToggle && (\n          <Flex className={classes.settingsRow} align=\"center\" pl=\"sm\" pr=\"xs\" py=\"xs\">\n            <Flex align=\"center\" gap=\"xs\">\n              <IconTable size={16} color={MENU_ICON_COLOR} />\n              <Text size=\"sm\">Layout</Text>\n            </Flex>\n            <Box className={classes.settingsControlWrapper}>\n              <SegmentedControl\n                classNames={{ root: cx(classes.segmentedControl, classes.layoutControl) }}\n                size=\"xs\"\n                radius=\"xl\"\n                withItemsBorders={false}\n                value={layoutVersion}\n                onChange={(newValue) => {\n                  localStorage['appShellLayoutVersion'] = newValue;\n                  locationUtils.reload();\n                }}\n                data={LAYOUT_OPTIONS}\n                aria-label=\"App shell layout version\"\n              />\n            </Box>\n          </Flex>\n        )}\n        <Menu.Item\n          leftSection={<IconLogout size={16} color={MENU_ICON_COLOR} />}\n          onClick={async () => {\n            await medplum.signOut();\n            navigate('/signin');\n          }}\n        >\n          <Text size=\"sm\">Sign out</Text>\n        </Menu.Item>\n        <HeaderDropdownDivider />\n        <Text size=\"xs\" c=\"dimmed\" fw={500} my=\"sm\" ta=\"center\">\n          {getAppName()} {props.version}\n        </Text>\n      </Box>\n    </>\n  );\n}\n", "function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(f=r(e[t]))&&(n&&(n+=\" \"),n+=f)}else for(f in e)e[f]&&(n&&(n+=\" \"),n+=f);return n}export function clsx(){for(var e,t,f=0,n=\"\",o=arguments.length;f<o;f++)(e=arguments[f])&&(t=r(e))&&(n&&(n+=\" \"),n+=t);return n}export default clsx;", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Group, Text } from '@mantine/core';\nimport type { ProjectMembership } from '@medplum/fhirtypes';\nimport { IconBriefcase, IconCheck } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport classes from './ProjectLoginOption.module.css';\n\nexport interface ProjectLoginOptionProps {\n  readonly projectDisplay?: string;\n  readonly profileDisplay?: string;\n  readonly label?: string;\n  readonly selected?: boolean;\n}\n\nexport function ProjectLoginOption(props: ProjectLoginOptionProps): JSX.Element {\n  const { projectDisplay, profileDisplay, label, selected } = props;\n  const projectTitle = label ? `${projectDisplay} - ${label}` : projectDisplay;\n\n  return (\n    <Group gap=\"xs\" align=\"center\" wrap=\"nowrap\" style={{ width: '100%', minWidth: 0 }}>\n      <Box className={classes.iconBox}>\n        <IconBriefcase size={16} stroke={2} />\n      </Box>\n      <div style={{ flex: 1, minWidth: 0 }}>\n        <Text size=\"sm\" fw={500} truncate>\n          {projectTitle}\n        </Text>\n        <Text size=\"xs\" className={classes.subtitle} truncate>\n          {profileDisplay}\n        </Text>\n      </div>\n      {selected && <IconCheck size={16} stroke={2} color=\"var(--mantine-color-blue-6)\" />}\n    </Group>\n  );\n}\n\nexport interface ProjectMembershipLoginOptionProps {\n  readonly membership: ProjectMembership;\n  readonly label?: string;\n}\n\nexport function ProjectMembershipLoginOption(props: ProjectMembershipLoginOptionProps): JSX.Element {\n  const { membership, label } = props;\n  return (\n    <ProjectLoginOption\n      projectDisplay={membership.project?.display}\n      profileDisplay={membership.profile?.display}\n      label={label}\n    />\n  );\n}\n", ".iconBox {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 32px;\n  height: 32px;\n  border-radius: var(--mantine-radius-sm);\n  background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n  color: var(--project-login-icon-color, light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2)));\n}\n\n.subtitle {\n  color: var(--mantine-color-dimmed);\n}\n\n.interactive {\n  border-radius: var(--mantine-radius-sm);\n  padding: 8px 12px;\n  cursor: pointer;\n\n  /* Keyboard-highlighted option gets the same treatment as hover (background + icon\n     color), overriding Mantine's default filled/white-text combo, plus an outline so\n     it's still distinguishable from a plain hover. Text colors never invert, so there's\n     no selected+hover contrast conflict to guard against. */\n  &:hover,\n  &[data-hovered],\n  &[data-combobox-selected] {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n    color: var(--mantine-color-text);\n\n    & .iconBox {\n      color: var(--mantine-color-text);\n    }\n  }\n\n  &[data-combobox-selected] {\n    outline: 2px solid var(--mantine-color-blue-6);\n    outline-offset: -2px;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Returns the application name from environment variables or a default value.\n * @returns The application name.\n */\nexport function getAppName(): string {\n  return import.meta.env.MEDPLUM_APP_NAME || 'Medplum';\n}\n", ".divider {\n  border-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n.accountSection {\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n}\n\n.projectOption {\n  padding: 0 8px 0 0;\n  border-radius: 8px;\n  width: 100%;\n  min-width: 0;\n  overflow: hidden;\n}\n\n/* Allow the Menu item's label to shrink so the project name can truncate */\n.recentProjectItem :global(.mantine-Menu-itemLabel) {\n  min-width: 0;\n}\n\n.dropdown :global(.mantine-Menu-item).recentProjectItem:hover,\n.dropdown :global(.mantine-Menu-item).recentProjectItem[data-hovered] {\n  --project-login-icon-color: var(--mantine-color-text);\n}\n\n.dropdown {\n  display: flex;\n  flex-direction: column;\n  /* Fallback until floating-ui measures the space beside the menu button. */\n  max-height: calc(100dvh - 80px);\n  /* Scroll the menu when the pinned footer is taller than that space, so Sign out stays reachable. */\n  overflow-y: auto;\n  overscroll-behavior: contain;\n}\n\n.accountSection,\n.divider,\n.menuFooter {\n  flex-shrink: 0;\n}\n\n.projectList {\n  flex: 0 1 auto;\n  min-height: 0;\n  overflow-y: auto;\n  scrollbar-width: thin;\n  /* Room for the 2px focus outline and its 2px offset. */\n  padding: 4px;\n}\n\n/* scrollIntoView aligns the border box, so the outline needs its own margin. */\n.projectList :global(.mantine-Menu-item) {\n  scroll-margin: 4px;\n}\n\n/* Two ProjectLoginOption rows (~56px each), plus the focus padding above. */\n.projectList:has(> :nth-child(2)) {\n  min-height: calc(7rem + 8px);\n}\n\n/* A single row does not shrink; the menu scrolls instead. */\n.projectList:has(> :only-child) {\n  flex-shrink: 0;\n}\n\n.dropdown :global(.mantine-Menu-item) {\n  border-radius: var(--mantine-radius-sm);\n  padding-top: var(--mantine-spacing-xs);\n  padding-bottom: var(--mantine-spacing-xs);\n}\n\n.dropdown :global(.mantine-Menu-item:hover),\n.dropdown :global(.mantine-Menu-item[data-hovered]) {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n/* Row height follows label; switcher is positioned out of flow */\n.settingsRow {\n  position: relative;\n  min-height: 20px;\n  padding-right: 76px;\n  width: 100%;\n}\n\n.settingsControlWrapper {\n  position: absolute;\n  top: 50%;\n  right: var(--mantine-spacing-xs);\n  transform: translateY(-50%);\n}\n\n.segmentedControl {\n  --sc-padding: 0;\n  flex-shrink: 0;\n  padding: 2px;\n}\n\n.segmentedControl :global(.mantine-SegmentedControl-label) {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  line-height: 1;\n  color: var(--mantine-color-dimmed);\n}\n\n.segmentedControl :global(.mantine-SegmentedControl-label[data-active]) {\n  color: var(--mantine-color-dimmed);\n}\n\n/* Square segments so the FloatingIndicator renders as a circle */\n.appearanceControl :global(.mantine-SegmentedControl-control) {\n  flex: 0 0 24px;\n  width: 24px;\n}\n\n.appearanceControl :global(.mantine-SegmentedControl-label) {\n  width: 24px;\n  height: 24px;\n  min-width: 24px;\n  min-height: 24px;\n  padding: 0;\n}\n\n.appearanceControl :global(.mantine-SegmentedControl-indicator) {\n  border-radius: 50%;\n}\n\n.layoutControl :global(.mantine-SegmentedControl-control) {\n  flex: 0 0 auto;\n}\n\n.layoutControl :global(.mantine-SegmentedControl-label) {\n  min-width: 28px;\n  height: 24px;\n  min-height: 24px;\n  padding: 0 6px;\n  font-size: var(--mantine-font-size-xs);\n}\n\n.layoutControl :global(.mantine-SegmentedControl-indicator) {\n  border-radius: var(--mantine-radius-xl);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Text } from '@mantine/core';\nimport { formatHumanName, getDisplayString, getReferenceString, isUUID } from '@medplum/core';\nimport type { Patient, ServiceRequest } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { forwardRef, useCallback } from 'react';\nimport type { AsyncAutocompleteOption } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { AsyncAutocomplete } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport classes from './HeaderSearchInput.module.css';\n\nexport type HeaderSearchTypes = Patient | ServiceRequest;\n\ninterface SearchGraphQLResponse {\n  readonly data: {\n    readonly Patients1: Patient[] | undefined;\n    readonly Patients2: Patient[] | undefined;\n    readonly ServiceRequestList: ServiceRequest[] | undefined;\n  };\n}\n\nfunction toOption(resource: HeaderSearchTypes): AsyncAutocompleteOption<HeaderSearchTypes> {\n  return {\n    value: resource.id as string,\n    label: getDisplayString(resource),\n    resource,\n  };\n}\n\nexport interface HeaderSearchInputProps {\n  readonly pathname?: string;\n  readonly searchParams?: URLSearchParams;\n}\n\nexport function HeaderSearchInput(props: HeaderSearchInputProps): JSX.Element {\n  const navigate = useMedplumNavigate();\n  const medplum = useMedplum();\n\n  const loadData = useCallback(\n    async (input: string, signal: AbortSignal): Promise<HeaderSearchTypes[]> => {\n      const query = buildGraphQLQuery(input);\n      const options = { signal };\n      const response = (await medplum.graphql(query, undefined, undefined, options)) as SearchGraphQLResponse;\n      return getResourcesFromResponse(response, input);\n    },\n    [medplum]\n  );\n\n  const handleSelect = useCallback(\n    (item: HeaderSearchTypes[]): void => {\n      if (item.length > 0) {\n        navigate(`/${getReferenceString(item[0])}`);\n      }\n    },\n    [navigate]\n  );\n\n  return (\n    <AsyncAutocomplete\n      key={`${props.pathname}?${props.searchParams}`}\n      size=\"sm\"\n      radius=\"md\"\n      className={classes.searchInput}\n      leftSection={<IconSearch size={16} />}\n      placeholder=\"Search\"\n      itemComponent={ItemComponent}\n      toOption={toOption}\n      onChange={handleSelect}\n      loadOptions={loadData}\n      maxValues={0}\n      clearable={false}\n    />\n  );\n}\n\nconst ItemComponent = forwardRef<HTMLDivElement, AsyncAutocompleteOption<HeaderSearchTypes>>(\n  ({ resource, active: _active, ...others }: AsyncAutocompleteOption<HeaderSearchTypes>, ref) => {\n    let helpText: string | undefined = undefined;\n\n    if (resource.resourceType === 'Patient') {\n      helpText = resource.birthDate;\n    } else if (resource.resourceType === 'ServiceRequest') {\n      helpText = resource.subject?.display;\n    }\n\n    return (\n      <div ref={ref} {...others}>\n        <Group wrap=\"nowrap\">\n          <ResourceAvatar value={resource} />\n          <div>\n            <Text>{getDisplayString(resource)}</Text>\n            <Text size=\"xs\" c=\"dimmed\">\n              {helpText}\n            </Text>\n          </div>\n        </Group>\n      </div>\n    );\n  }\n);\n\nfunction buildGraphQLQuery(input: string): string {\n  const escaped = JSON.stringify(input);\n  if (isUUID(input)) {\n    return `{\n      Patients1: PatientList(_id: ${escaped}, _count: 1) {\n        resourceType\n        id\n        identifier {\n          system\n          value\n        }\n        name {\n          given\n          family\n        }\n        birthDate\n      }\n      ServiceRequestList(_id: ${escaped}, _count: 1) {\n        resourceType\n        id\n        identifier {\n          system\n          value\n        }\n        subject {\n          display\n        }\n      }\n    }`.replaceAll(/\\s+/g, ' ');\n  }\n  return `{\n    Patients1: PatientList(name: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier {\n        system\n        value\n      }\n      name {\n        given\n        family\n      }\n      birthDate\n    }\n    Patients2: PatientList(identifier: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier {\n        system\n        value\n      }\n      name {\n        given\n        family\n      }\n      birthDate\n    }\n    ServiceRequestList(identifier: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier {\n        system\n        value\n      }\n      subject {\n        display\n      }\n    }\n  }`.replaceAll(/\\s+/g, ' ');\n}\n\n/**\n * Returns a de-duped and sorted list of resources from the search response.\n * The search request is actually 3+ separate searches, which can include duplicates.\n * This function combines the results, de-dupes, and sorts by relevance.\n * @param response - The response from a search query.\n * @param query - The user entered search query.\n * @returns The resources to display in the autocomplete.\n */\nfunction getResourcesFromResponse(response: SearchGraphQLResponse, query: string): HeaderSearchTypes[] {\n  const resources = [];\n  if (response.data.Patients1) {\n    resources.push(...response.data.Patients1);\n  }\n  if (response.data.Patients2) {\n    resources.push(...response.data.Patients2);\n  }\n  if (response.data.ServiceRequestList) {\n    resources.push(...response.data.ServiceRequestList);\n  }\n  return sortByRelevance(dedupeResources(resources), query).slice(0, 5);\n}\n\n/**\n * Removes duplicate resources from an array by ID.\n * @param resources - The array of resources with possible duplicates.\n * @returns The array of resources with no duplicates.\n */\nfunction dedupeResources(resources: HeaderSearchTypes[]): HeaderSearchTypes[] {\n  const ids = new Set<string>();\n  const result = [];\n\n  for (const resource of resources) {\n    if (!ids.has(resource.id as string)) {\n      ids.add(resource.id as string);\n      result.push(resource);\n    }\n  }\n\n  return result;\n}\n\n/**\n * Sorts an array of resources by relevance.\n * @param resources - The candidate resources.\n * @param query - The user entered search string.\n * @returns The sorted array of resources.\n */\nfunction sortByRelevance(resources: HeaderSearchTypes[], query: string): HeaderSearchTypes[] {\n  return resources.sort((a: HeaderSearchTypes, b: HeaderSearchTypes) => {\n    return getResourceScore(b, query) - getResourceScore(a, query);\n  });\n}\n\n/**\n * Calculates a relevance score of a candidate resource.\n * Higher scores are better.\n * @param resource - The candidate resource.\n * @param query - The user entered search string.\n * @returns The relevance score of the candidate resource.\n */\nfunction getResourceScore(resource: HeaderSearchTypes, query: string): number {\n  let bestScore = 0;\n\n  if (resource.identifier) {\n    for (const identifier of resource.identifier) {\n      bestScore = Math.max(bestScore, getStringScore(identifier.value, query));\n    }\n  }\n\n  if (resource.resourceType === 'Patient' && resource.name) {\n    for (const name of resource.name) {\n      bestScore = Math.max(bestScore, getStringScore(formatHumanName(name), query));\n    }\n  }\n\n  return bestScore;\n}\n\n/**\n * Calculates a relevance score of a candidate display string.\n * Higher scores are better.\n * @param str - The candidate display string.\n * @param query - The user entered search string.\n * @returns The relevance score of the candidate string.\n */\nfunction getStringScore(str: string | undefined, query: string): number {\n  if (!str) {\n    return 0;\n  }\n  const index = str.toLowerCase().indexOf(query.toLowerCase());\n  if (index < 0) {\n    return 0;\n  }\n  return 100 - index;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ComboboxItem, ComboboxProps } from '@mantine/core';\nimport { Combobox, Group, Loader, Pill, PillsInput, ScrollAreaAutosize, useCombobox } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconCheck } from '@tabler/icons-react';\nimport type { JSX, KeyboardEvent, ReactNode, SyntheticEvent } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { AsyncAutocompleteTestIds } from './AsyncAutocomplete.utils';\n\nexport interface AsyncAutocompleteOption<T> extends ComboboxItem {\n  readonly active?: boolean;\n  readonly resource: T;\n}\n\nexport interface AsyncAutocompleteProps<T> extends Omit<\n  ComboboxProps,\n  'data' | 'defaultValue' | 'loadOptions' | 'onChange' | 'onCreate' | 'searchable'\n> {\n  readonly name?: string;\n  readonly label?: ReactNode;\n  /**\n   * Names the field for assistive technology, for use instead of a visible `label` (don't pass both). The name\n   * goes on the search box and on a group around the whole field, which keeps the selected values (and, at\n   * `maxValues`, the clear button) named while the search box is hidden (disabled or at `maxValues`).\n   */\n  readonly 'aria-label'?: string;\n  readonly description?: ReactNode;\n  readonly error?: ReactNode;\n  readonly defaultValue?: T | T[];\n  readonly toOption: (item: T) => AsyncAutocompleteOption<T>;\n  readonly loadOptions: (input: string, signal: AbortSignal) => Promise<T[]>;\n  readonly itemComponent?: (props: AsyncAutocompleteOption<T>) => JSX.Element | ReactNode;\n  readonly pillComponent?: (props: {\n    item: AsyncAutocompleteOption<T>;\n    disabled?: boolean;\n    onRemove: () => void;\n  }) => JSX.Element;\n  readonly emptyComponent?: (props: { search: string }) => JSX.Element | ReactNode;\n  readonly onChange: (item: T[]) => void;\n  readonly onCreate?: (input: string) => T;\n  readonly creatable?: boolean;\n  readonly clearable?: boolean;\n  readonly required?: boolean;\n  readonly withAsterisk?: boolean;\n  readonly className?: string;\n  readonly placeholder?: string;\n  readonly leftSection?: ReactNode;\n  readonly maxValues?: number;\n  readonly optionsDropdownMaxHeight?: number;\n  readonly minInputLength?: number; // minimum number of input characters required before executing loadOptions\n}\n\nexport function AsyncAutocomplete<T>(props: AsyncAutocompleteProps<T>): JSX.Element {\n  const combobox = useCombobox({\n    onDropdownClose: () => combobox.resetSelectedOption(),\n    onDropdownOpen: () => combobox.updateSelectedOptionIndex('active'),\n  });\n  const {\n    name,\n    label,\n    'aria-label': ariaLabel,\n    description,\n    error,\n    defaultValue,\n    toOption,\n    loadOptions,\n    itemComponent,\n    pillComponent,\n    emptyComponent,\n    onChange,\n    onCreate,\n    creatable,\n    clearable,\n    required,\n    withAsterisk,\n    placeholder,\n    leftSection,\n    maxValues,\n    optionsDropdownMaxHeight = 320,\n    minInputLength = 0,\n    ...rest\n  } = props;\n  const disabled = rest.disabled; // leave in rest so it also propagates to ComboBox\n  const defaultItems = toDefaultItems(defaultValue);\n  const [search, setSearch] = useState('');\n  const [timer, setTimer] = useState<number>();\n  const [abortController, setAbortController] = useState<AbortController>();\n  const [selected, setSelected] = useState(defaultItems.map(toOption));\n  const [options, setOptions] = useState<AsyncAutocompleteOption<T>[]>([]);\n  const ItemComponent = itemComponent ?? DefaultItemComponent;\n  const PillComponent = pillComponent ?? DefaultPillComponent;\n  const EmptyComponent = emptyComponent ?? DefaultEmptyComponent;\n\n  const searchRef = useRef(search);\n  const lastLoadOptionsRef = useRef<AsyncAutocompleteProps<T>['loadOptions']>(undefined);\n  const lastValueRef = useRef<string>(undefined);\n  const timerRef = useRef<number>(timer);\n  const abortControllerRef = useRef<AbortController>(abortController);\n  const autoSubmitRef = useRef<boolean>(false);\n  const selectedRef = useRef(selected);\n  useLayoutEffect(() => {\n    searchRef.current = search;\n    timerRef.current = timer;\n    abortControllerRef.current = abortController;\n    selectedRef.current = selected;\n  });\n\n  const handleValueAdd = useCallback(\n    (item: AsyncAutocompleteOption<T>): void => {\n      const selected = selectedRef.current;\n      if (selected.some((v) => v.value === item.value)) {\n        return;\n      }\n\n      // when maxValues is 0, still fire the onChange when an item is selected\n      if (maxValues === 0) {\n        onChange([item.resource]);\n        setSelected([]);\n        return;\n      }\n\n      const newSelected = [...selected, item];\n\n      if (maxValues !== undefined) {\n        while (newSelected.length > maxValues) {\n          // Remove from the front\n          newSelected.shift();\n        }\n\n        if (newSelected.length >= maxValues) {\n          // The search input is about to be hidden now that the cap is reached; reset the dropdown\n          // state so it doesn't linger with stale options and no input left to dismiss it.\n          setSearch('');\n          setOptions([]);\n          combobox.closeDropdown();\n        }\n      }\n\n      onChange(newSelected.map((v) => v.resource));\n      setSelected(newSelected);\n    },\n    [maxValues, onChange, combobox, setSearch, setOptions]\n  );\n\n  const handleTimer = useCallback((): void => {\n    setTimer(undefined);\n\n    if (searchRef.current === lastValueRef.current && loadOptions === lastLoadOptionsRef.current) {\n      // Same search input and loadOptions function, move on\n      return;\n    }\n    if ((searchRef.current?.length ?? 0) < minInputLength) {\n      return;\n    }\n\n    lastValueRef.current = searchRef.current;\n    lastLoadOptionsRef.current = loadOptions;\n\n    const newAbortController = new AbortController();\n    setAbortController(newAbortController);\n\n    loadOptions(searchRef.current ?? '', newAbortController.signal)\n      .then((newValues: T[]) => {\n        if (!newAbortController.signal.aborted) {\n          const newOptions = newValues.map(toOption);\n          setOptions(newOptions);\n          if (autoSubmitRef.current) {\n            if (newOptions.length > 0) {\n              handleValueAdd(newOptions[0]);\n            }\n            autoSubmitRef.current = false;\n          } else if (newValues.length > 0) {\n            combobox.openDropdown();\n          }\n        }\n      })\n      .catch((err) => {\n        if (!(newAbortController.signal.aborted || err.message.includes('aborted'))) {\n          showNotification({ color: 'red', message: normalizeErrorString(err) });\n        }\n      })\n      .finally(() => {\n        if (!newAbortController.signal.aborted) {\n          setAbortController(undefined);\n        }\n      });\n  }, [combobox, loadOptions, handleValueAdd, toOption, minInputLength, setTimer, setAbortController]);\n\n  const handleSearchChange = useCallback(\n    (e: SyntheticEvent): void => {\n      if ((options && options.length > 0) || creatable) {\n        combobox.openDropdown();\n      }\n\n      combobox.updateSelectedOptionIndex();\n      setSearch((e.currentTarget as HTMLInputElement).value);\n\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort();\n        setAbortController(undefined);\n      }\n\n      if (timerRef.current !== undefined) {\n        window.clearTimeout(timerRef.current);\n      }\n\n      const newTimer = window.setTimeout(() => handleTimer(), 100);\n      setTimer(newTimer);\n    },\n    [combobox, options, creatable, handleTimer, setTimer, setSearch, setAbortController]\n  );\n\n  const toggleSelected = useCallback(\n    (newValue: string): void => {\n      const alreadySelected = selected.some((v) => v.value === newValue);\n      if (alreadySelected) {\n        const newSelected = selected.filter((v) => v.value !== newValue);\n        onChange(newSelected.map((v) => v.resource));\n        setSelected(newSelected);\n      } else {\n        let option = options?.find((option) => option.value === newValue);\n        if (!option && creatable !== false && onCreate) {\n          const createdResource = onCreate(newValue);\n          option = toOption(createdResource);\n        }\n        if (option) {\n          handleValueAdd(option);\n        }\n      }\n    },\n    [selected, onChange, handleValueAdd, onCreate, toOption, options, creatable]\n  );\n\n  const handleValueSelect = useMemo(() => {\n    if (disabled) {\n      return undefined;\n    }\n\n    return (val: string): void => {\n      if (disabled) {\n        return;\n      }\n      lastValueRef.current = undefined;\n      if (val === '$create') {\n        setSearch('');\n        toggleSelected(search);\n      } else {\n        toggleSelected(val);\n      }\n    };\n  }, [toggleSelected, disabled, search, setSearch]);\n\n  const handleValueRemove = useCallback(\n    (item: AsyncAutocompleteOption<T>): void => {\n      const newSelected = selected.filter((v) => v.value !== item.value);\n      onChange(newSelected.map((v) => v.resource));\n      setSelected(newSelected);\n    },\n    [selected, onChange]\n  );\n\n  const handleKeyDown = useCallback(\n    (e: KeyboardEvent): void => {\n      if (e.key === 'Enter') {\n        if (timer || abortController) {\n          // The user pressed enter, but we don't have results yet.\n          // We need to wait for the results to come in.\n          autoSubmitRef.current = true;\n        }\n      } else if (e.key === 'Backspace' && search.length === 0) {\n        killEvent(e);\n        handleValueRemove(selected[selected.length - 1]);\n      }\n    },\n    [abortController, handleValueRemove, search.length, selected, timer]\n  );\n\n  useEffect(() => {\n    return () => {\n      if (abortControllerRef.current) {\n        abortControllerRef.current.abort();\n      }\n    };\n  }, []);\n\n  // Based on Mantine MultiSelect:\n  // https://github.com/mantinedev/mantine/blob/master/packages/%40mantine/core/src/components/MultiSelect/MultiSelect.tsx\n  const clearButton = !disabled && clearable && selected.length > 0 && (\n    <Combobox.ClearButton\n      title=\"Clear all\"\n      size=\"sm\"\n      onClear={() => {\n        setSearch('');\n        setSelected([]);\n        onChange([]);\n        combobox.closeDropdown();\n      }}\n    />\n  );\n\n  const createVisible = creatable && search.trim().length > 0;\n  const comboboxVisible = options.length > 0 || createVisible;\n\n  return (\n    <Combobox store={combobox} onOptionSubmit={handleValueSelect} withinPortal={true} shadow=\"xl\" {...rest}>\n      <Combobox.DropdownTarget>\n        <PillsInput\n          label={label}\n          description={description}\n          error={error}\n          className={props.className}\n          leftSection={leftSection}\n          rightSection={abortController ? <Loader size={16} /> : clearButton}\n          required={required}\n          withAsterisk={withAsterisk}\n          disabled={disabled}\n          wrapperProps={ariaLabel ? { role: 'group', 'aria-label': ariaLabel } : undefined}\n        >\n          <Pill.Group data-testid={AsyncAutocompleteTestIds.selectedItems}>\n            {selected.map((item) => (\n              <PillComponent\n                key={item.value}\n                item={item}\n                disabled={disabled}\n                onRemove={() => handleValueRemove(item)}\n              />\n            ))}\n            {!disabled && (maxValues === undefined || maxValues === 0 || selected.length < maxValues) && (\n              <Combobox.EventsTarget>\n                <PillsInput.Field\n                  role=\"searchbox\"\n                  name={name}\n                  aria-label={ariaLabel}\n                  value={search}\n                  placeholder={placeholder}\n                  onFocus={handleSearchChange}\n                  onBlur={() => {\n                    combobox.closeDropdown();\n                    setSearch('');\n                  }}\n                  onKeyDown={handleKeyDown}\n                  onChange={handleSearchChange}\n                />\n              </Combobox.EventsTarget>\n            )}\n          </Pill.Group>\n        </PillsInput>\n      </Combobox.DropdownTarget>\n\n      <Combobox.Dropdown hidden={!comboboxVisible} data-testid={AsyncAutocompleteTestIds.options}>\n        <Combobox.Options>\n          <ScrollAreaAutosize type=\"scroll\" mah={optionsDropdownMaxHeight}>\n            {options.map((item) => {\n              const active = selected.some((v) => v.value === item.value);\n              return (\n                <Combobox.Option value={item.value} key={item.value} active={active}>\n                  <ItemComponent {...item} active={active} />\n                </Combobox.Option>\n              );\n            })}\n\n            {createVisible && <Combobox.Option value=\"$create\">+ Create {search}</Combobox.Option>}\n\n            {!creatable && search.trim().length > 0 && options.length === 0 && <EmptyComponent search={search} />}\n          </ScrollAreaAutosize>\n        </Combobox.Options>\n      </Combobox.Dropdown>\n    </Combobox>\n  );\n}\n\nfunction toDefaultItems<T>(defaultValue: T | T[] | undefined): T[] {\n  if (!defaultValue) {\n    return [];\n  }\n  if (Array.isArray(defaultValue)) {\n    return defaultValue;\n  }\n  return [defaultValue];\n}\n\nfunction DefaultItemComponent<T>(props: AsyncAutocompleteOption<T>): JSX.Element {\n  return (\n    <Group gap=\"xs\">\n      {props.active && <IconCheck size={12} />}\n      <span>{props.label}</span>\n    </Group>\n  );\n}\n\nfunction DefaultPillComponent<T>({\n  item,\n  disabled,\n  onRemove,\n}: {\n  readonly item: AsyncAutocompleteOption<T>;\n  readonly disabled?: boolean;\n  readonly onRemove: () => void;\n}): JSX.Element {\n  return (\n    <Pill withRemoveButton={!disabled} onRemove={onRemove}>\n      {item.label}\n    </Pill>\n  );\n}\n\nfunction DefaultEmptyComponent(): JSX.Element {\n  return <Combobox.Empty>Nothing found</Combobox.Empty>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nexport const AsyncAutocompleteTestIds = { selectedItems: 'selected-items', options: 'options' };\n", ".searchInput {\n  input {\n    width: 220px;\n    transition: width 0.1s ease-in-out;\n  }\n\n  input:focus {\n    width: 400px;\n  }\n\n  @media (max-width: 800px) {\n    input {\n      width: 150px;\n    }\n    input:focus {\n      width: 150px;\n    }\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MenuProps } from '@mantine/core';\n\n/** Limits menu height to the space beside the button. Width stays on the Menu `width` prop. */\nexport const userMenuMiddlewares: NonNullable<MenuProps['middlewares']> = {\n  flip: true,\n  shift: true,\n  size: {\n    padding: 8,\n    apply({ availableHeight, elements }) {\n      if (availableHeight > 0 && Number.isFinite(availableHeight)) {\n        elements.floating.style.maxHeight = `${Math.floor(availableHeight)}px`;\n      } else {\n        elements.floating.style.maxHeight = '';\n      }\n    },\n  },\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport {\n  Box,\n  Divider,\n  AppShell as MantineAppShell,\n  Menu,\n  ScrollArea,\n  Stack,\n  Text,\n  Tooltip,\n  UnstyledButton,\n} from '@mantine/core';\nimport { spotlight } from '@mantine/spotlight';\nimport { formatHumanName } from '@medplum/core';\nimport type { ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumNavigate, useMedplumProfile, useNotificationCount } from '@medplum/react-hooks';\nimport { IconBookmark, IconCirclePlus, IconLayoutSidebar, IconSearch, IconX } from '@tabler/icons-react';\nimport type { JSX, MouseEvent, MouseEventHandler, ReactNode, SyntheticEvent } from 'react';\nimport { Fragment, useState } from 'react';\nimport { BookmarkDialog } from '../BookmarkDialog/BookmarkDialog';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport { HeaderDropdown } from './HeaderDropdown';\nimport headerDropdownClasses from './HeaderDropdown.module.css';\nimport classes from './Navbar.module.css';\nimport type { SpotlightLinkAction } from './Spotlight';\nimport { Spotlight } from './Spotlight';\nimport { userMenuMiddlewares } from './userMenuMiddlewares';\n\nexport interface NavbarLink {\n  readonly icon?: JSX.Element;\n  readonly label?: string;\n  readonly href: string;\n  /** Static count to display. Ignored if notificationCount is provided. */\n  readonly count?: number;\n  /** If true, shows red alert styling (red dot on collapsed icon, red count text when expanded). */\n  readonly alert?: boolean;\n  /** Live subscription-based count. Overrides static `count` when provided. */\n  readonly notificationCount?: {\n    readonly resourceType: ResourceType;\n    readonly countCriteria: string;\n    readonly subscriptionCriteria: string;\n  };\n  /** Callback fired when the dismiss button is clicked. When provided, a dismiss (X) button appears on hover. */\n  readonly onDismiss?: () => void;\n}\n\nexport interface NavbarMenu {\n  readonly title?: string;\n  readonly links?: NavbarLink[];\n}\n\nexport interface NavbarProps {\n  readonly pathname?: string;\n  readonly searchParams?: URLSearchParams;\n  readonly logo?: ReactNode;\n  readonly menus?: NavbarMenu[];\n  readonly navbarToggle: () => void;\n  readonly closeNavbar: () => void;\n  readonly spotlightEnabled?: boolean;\n  readonly patientsOnly?: boolean;\n  readonly spotlightActions?: SpotlightLinkAction[];\n  readonly userMenuEnabled?: boolean;\n  readonly displayAddBookmark?: boolean;\n  readonly resourceTypeSearchDisabled?: boolean;\n  readonly opened?: boolean;\n  readonly version?: string;\n  readonly showLayoutVersionToggle?: boolean;\n}\n\nexport function Navbar(props: NavbarProps): JSX.Element {\n  const medplum = useMedplum();\n  const navigate = useMedplumNavigate();\n  const profile = useMedplumProfile();\n  const activeLink = getActiveLink(props.pathname, props.searchParams, props.menus);\n  const [userMenuOpened, setUserMenuOpened] = useState(false);\n  const [bookmarkDialogVisible, setBookmarkDialogVisible] = useState(false);\n  const projectDisplay = medplum.getProject()?.name ?? medplum.getActiveLogin()?.project.display;\n\n  function onLinkClick(e: SyntheticEvent, to: string): void {\n    e.stopPropagation();\n    e.preventDefault();\n    navigate(to);\n    if (window.innerWidth < 768) {\n      props.closeNavbar();\n    }\n  }\n\n  function navigateResourceType(resourceType: string | undefined): void {\n    if (resourceType) {\n      navigate(`/${resourceType}`);\n    }\n  }\n\n  const opened = props.opened ?? true;\n\n  return (\n    <>\n      <MantineAppShell.Navbar id=\"navbar\" className={classes.navbar}>\n        {props.logo && (\n          <MantineAppShell.Section px=\"xs\" pt=\"xs\" pb=\"4px\">\n            <UnstyledButton\n              className={classes.logoButton}\n              onClick={props.navbarToggle}\n              aria-expanded={opened}\n              aria-controls=\"navbar\"\n              aria-label=\"Medplum Logo\"\n            >\n              {props.logo}\n            </UnstyledButton>\n          </MantineAppShell.Section>\n        )}\n        <ScrollArea px=\"xs\" pb=\"xs\" pt=\"sm\" h=\"100%\">\n          <MantineAppShell.Section grow>\n            {props.spotlightEnabled && (\n              <Box mb={2}>\n                <Tooltip label=\"Search\" position=\"right\" transitionProps={{ duration: 0 }} disabled={opened}>\n                  <UnstyledButton className={classes.link} onClick={() => spotlight.open()} aria-label=\"Search\">\n                    <IconSearch size=\"1.2rem\" />\n                    <span className={classes.linkLabel} data-opened={opened || undefined}>\n                      Search\n                    </span>\n                  </UnstyledButton>\n                </Tooltip>\n              </Box>\n            )}\n            {props.spotlightEnabled && (\n              <Spotlight patientsOnly={props.patientsOnly} staticActions={props.spotlightActions} />\n            )}\n            {!props.resourceTypeSearchDisabled && (\n              <MantineAppShell.Section mb=\"sm\">\n                <ResourceTypeInput\n                  key={window.location.pathname}\n                  name=\"resourceType\"\n                  placeholder=\"Resource Type\"\n                  maxValues={0}\n                  onChange={(newValue) => navigateResourceType(newValue)}\n                />\n              </MantineAppShell.Section>\n            )}\n            {props.menus?.map((menu, index) => (\n              <Fragment key={`menu-${menu.title ?? index}`}>\n                {menu.title && (\n                  <Text className={classes.menuTitle} data-opened={opened || undefined}>\n                    {menu.title}\n                  </Text>\n                )}\n                <Stack gap=\"2\">\n                  {menu.links?.map((link) =>\n                    link.notificationCount ? (\n                      <NavbarLinkWithSubscription\n                        key={link.href}\n                        to={link.href}\n                        active={link.href === activeLink?.href}\n                        onClick={(e) => onLinkClick(e, link.href)}\n                        icon={link.icon}\n                        label={link.label ?? ''}\n                        opened={opened}\n                        alert={link.alert}\n                        notificationCount={link.notificationCount}\n                        onDismiss={link.onDismiss}\n                      />\n                    ) : (\n                      <NavbarLinkContent\n                        key={link.href}\n                        to={link.href}\n                        active={link.href === activeLink?.href}\n                        onClick={(e) => onLinkClick(e, link.href)}\n                        icon={link.icon}\n                        label={link.label ?? ''}\n                        opened={opened}\n                        alert={link.alert}\n                        count={link.count}\n                        onDismiss={link.onDismiss}\n                      />\n                    )\n                  )}\n                </Stack>\n              </Fragment>\n            ))}\n            {props.displayAddBookmark && (\n              <Tooltip label=\"Add Bookmark\" position=\"right\" transitionProps={{ duration: 0 }} disabled={opened}>\n                <UnstyledButton\n                  className={`${classes.link} ${classes.addBookmarkLink}`}\n                  onClick={() => setBookmarkDialogVisible(true)}\n                >\n                  <IconCirclePlus />\n                  <span className={classes.linkLabel} data-opened={opened || undefined}>\n                    Add Bookmark\n                  </span>\n                </UnstyledButton>\n              </Tooltip>\n            )}\n          </MantineAppShell.Section>\n        </ScrollArea>\n        {props.userMenuEnabled && (\n          <MantineAppShell.Section px=\"xs\" py=\"xs\">\n            <Tooltip\n              label={opened ? 'Close Sidebar' : 'Open Sidebar'}\n              position=\"right\"\n              transitionProps={{ duration: 0 }}\n            >\n              <UnstyledButton\n                className={classes.toggleButton}\n                data-opened={opened || undefined}\n                aria-label={opened ? 'Close Sidebar' : 'Open Sidebar'}\n                onClick={props.navbarToggle}\n                aria-expanded={opened}\n                aria-controls=\"navbar\"\n              >\n                <IconLayoutSidebar />\n              </UnstyledButton>\n            </Tooltip>\n            <Divider my=\"xs\" className={classes.divider} />\n            <Menu\n              width={260}\n              shadow=\"md\"\n              radius=\"md\"\n              position=\"top-start\"\n              middlewares={userMenuMiddlewares}\n              transitionProps={{ transition: 'fade-up' }}\n              opened={userMenuOpened}\n              onClose={() => setUserMenuOpened(false)}\n            >\n              <Menu.Target>\n                <UnstyledButton\n                  className={`${classes.link} ${classes.userLink}`}\n                  pl=\"7\"\n                  aria-label=\"User menu\"\n                  data-active={userMenuOpened || undefined}\n                  onClick={() => setUserMenuOpened((o) => !o)}\n                  bd=\"1px 0 0 0 solid var(--mantine-color-gray-200)\"\n                >\n                  <ResourceAvatar value={profile} radius=\"xl\" size={24} />\n                  <span className={classes.userLinkLabel} data-opened={opened || undefined}>\n                    <Text span inherit truncate>\n                      {formatHumanName(profile?.name?.[0])}\n                    </Text>\n                    {projectDisplay && (\n                      <Text span inherit fz=\"xs\" c=\"dimmed\" truncate title={projectDisplay}>\n                        {projectDisplay}\n                      </Text>\n                    )}\n                  </span>\n                </UnstyledButton>\n              </Menu.Target>\n              <Menu.Dropdown className={headerDropdownClasses.dropdown}>\n                <HeaderDropdown version={props.version} showLayoutVersionToggle={props.showLayoutVersionToggle} />\n              </Menu.Dropdown>\n            </Menu>\n          </MantineAppShell.Section>\n        )}\n      </MantineAppShell.Navbar>\n      {props.pathname && props.searchParams && (\n        <BookmarkDialog\n          pathname={props.pathname}\n          searchParams={props.searchParams}\n          visible={bookmarkDialogVisible}\n          onOk={() => setBookmarkDialogVisible(false)}\n          onCancel={() => setBookmarkDialogVisible(false)}\n        />\n      )}\n    </>\n  );\n}\n\ninterface NavbarLinkContentProps {\n  readonly to: string;\n  readonly active: boolean;\n  readonly onClick: MouseEventHandler;\n  readonly icon?: JSX.Element;\n  readonly label: string;\n  readonly opened?: boolean;\n  readonly count?: number;\n  readonly alert?: boolean;\n  readonly onDismiss?: () => void;\n}\n\nfunction NavbarLinkContent(props: NavbarLinkContentProps): JSX.Element {\n  const { to, icon, label, onClick, active, count, alert, opened, onDismiss } = props;\n  const showCount = count !== undefined && count > 0;\n\n  const iconElement = icon ?? <IconBookmark />;\n  const showDot = showCount && alert && !opened;\n\n  function handleDismiss(e: MouseEvent): void {\n    e.preventDefault();\n    e.stopPropagation();\n    onDismiss?.();\n  }\n\n  return (\n    <Tooltip label={label} position=\"right\" transitionProps={{ duration: 0 }} disabled={opened}>\n      <MedplumLink to={to} onClick={onClick} className={classes.link} data-active={active || undefined}>\n        <span className={classes.iconWrapper}>\n          {iconElement}\n          {showDot && <span className={classes.alertDot} />}\n        </span>\n        <span className={classes.linkLabel} data-opened={opened || undefined}>\n          {label}\n        </span>\n        {showCount && (\n          <span className={classes.linkCount} data-opened={opened || undefined} data-alert={alert || undefined}>\n            {count.toLocaleString()}\n          </span>\n        )}\n        {onDismiss && opened && (\n          <Tooltip label=\"Dismiss\" openDelay={500}>\n            <UnstyledButton aria-label=\"Dismiss\" className={classes.dismissButton} onClick={handleDismiss}>\n              <IconX size={14} />\n            </UnstyledButton>\n          </Tooltip>\n        )}\n      </MedplumLink>\n    </Tooltip>\n  );\n}\n\ninterface NavbarLinkWithSubscriptionProps {\n  readonly to: string;\n  readonly active: boolean;\n  readonly onClick: MouseEventHandler;\n  readonly icon?: JSX.Element;\n  readonly label: string;\n  readonly opened?: boolean;\n  readonly alert?: boolean;\n  readonly notificationCount: {\n    readonly resourceType: ResourceType;\n    readonly countCriteria: string;\n    readonly subscriptionCriteria: string;\n  };\n  readonly onDismiss?: () => void;\n}\n\nfunction NavbarLinkWithSubscription(props: NavbarLinkWithSubscriptionProps): JSX.Element {\n  const count = useNotificationCount(props.notificationCount);\n  return (\n    <NavbarLinkContent\n      to={props.to}\n      active={props.active}\n      onClick={props.onClick}\n      icon={props.icon}\n      label={props.label}\n      opened={props.opened}\n      alert={props.alert}\n      count={count}\n      onDismiss={props.onDismiss}\n    />\n  );\n}\n\n/**\n * Returns the best \"active\" link for the menu.\n * In most cases, the navbar links are simple, and an exact match can determine which link is active.\n * However, we ignore some search parameters to support pagination.\n * But we cannot ignore all search parameters, to support separate links based on search filters.\n * So in the end, we use a simple scoring system based on the number of matching query search params.\n * @param currentPathname - The web browser current pathname.\n * @param currentSearchParams - The web browser current search parameters.\n * @param menus - Collection of navbar menus and links.\n * @returns The active link if one is found.\n */\nfunction getActiveLink(\n  currentPathname: string | undefined,\n  currentSearchParams: URLSearchParams | undefined,\n  menus: NavbarMenu[] | undefined\n): NavbarLink | undefined {\n  if (!currentPathname || !currentSearchParams || !menus) {\n    return undefined;\n  }\n\n  let bestLink = undefined;\n  let bestScore = 0;\n\n  for (const menu of menus) {\n    if (menu.links) {\n      for (const link of menu.links) {\n        const score = getLinkScore(currentPathname, currentSearchParams, link.href);\n        if (score > bestScore) {\n          bestScore = score;\n          bestLink = link;\n        }\n      }\n    }\n  }\n\n  return bestLink;\n}\n\n/**\n * Calculates a score for a link.\n * Zero means \"does not match at all\".\n * One means \"matches the pathname only\".\n * Additional increases for each matching search parameter.\n * Ignores pagination parameters \"_count\" and \"_offset\".\n * @param currentPathname - The web browser current pathname.\n * @param currentSearchParams - The web browser current search parameters.\n * @param linkHref - A candidate link href.\n * @returns The link score.\n */\nfunction getLinkScore(currentPathname: string, currentSearchParams: URLSearchParams, linkHref: string): number {\n  const linkUrl = new URL(linkHref, 'https://example.com');\n  if (currentPathname !== linkUrl.pathname) {\n    return 0;\n  }\n  const ignoredParams = ['_count', '_offset'];\n  for (const [key, value] of linkUrl.searchParams.entries()) {\n    if (ignoredParams.includes(key)) {\n      continue;\n    }\n    if (currentSearchParams.get(key) !== value) {\n      return 0;\n    }\n  }\n  let count = 1;\n  for (const [key, value] of currentSearchParams.entries()) {\n    if (ignoredParams.includes(key)) {\n      continue;\n    }\n    if (linkUrl.searchParams.get(key) === value) {\n      count++;\n    }\n  }\n  return count;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Modal, NativeSelect, Stack, TextInput } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { WithId } from '@medplum/core';\nimport { deepClone, normalizeErrorString } from '@medplum/core';\nimport type { UserConfiguration } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\n\ninterface BookmarkDialogProps {\n  readonly pathname: string;\n  readonly searchParams: URLSearchParams;\n  readonly visible: boolean;\n  readonly onOk: () => void;\n  readonly onCancel: () => void;\n}\nexport function BookmarkDialog(props: BookmarkDialogProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const config = medplum.getUserConfiguration() as WithId<UserConfiguration>;\n\n  function submitHandler(formData: Record<string, string>): void {\n    const { menuname, bookmarkname: name } = formData;\n    const target = `${props.pathname}?${props.searchParams.toString()}`;\n    const newConfig = deepClone(config);\n    const menu = newConfig.menu?.find(({ title }) => title === menuname);\n\n    menu?.link?.push({ name, target });\n    medplum\n      .updateResource(newConfig)\n      .then((res) => {\n        // refresh current config menu\n        config.menu = res.menu;\n        medplum.dispatchEvent({ type: 'change' });\n        showNotification({ color: 'green', message: 'Success' });\n        props.onOk();\n      })\n      .catch((err: any) => {\n        showNotification({ color: 'red', message: normalizeErrorString(err) });\n      });\n  }\n\n  return (\n    <Modal\n      title=\"Add Bookmark\"\n      closeButtonProps={{ 'aria-label': 'Close' }}\n      opened={props.visible}\n      onClose={props.onCancel}\n    >\n      <Form onSubmit={submitHandler}>\n        <Stack>\n          <SelectMenu config={config}></SelectMenu>\n          <TextInput\n            label=\"Bookmark Name\"\n            type=\"text\"\n            name=\"bookmarkname\"\n            placeholder=\"Bookmark Name\"\n            defaultValue={props.pathname.split('/')[1] || ''}\n            withAsterisk\n          />\n          <Group justify=\"flex-end\">\n            <SubmitButton mt=\"sm\">OK</SubmitButton>\n          </Group>\n        </Stack>\n      </Form>\n    </Modal>\n  );\n}\n\ninterface SelectMenuProps {\n  readonly config: UserConfiguration | undefined;\n}\n\nfunction SelectMenu(props: SelectMenuProps): JSX.Element {\n  function userConfigToMenu(config: UserConfiguration | undefined): string[] {\n    return config?.menu?.map((menu) => menu.title) as [];\n  }\n  const menus = userConfigToMenu(props.config);\n\n  return <NativeSelect name=\"menuname\" defaultValue={menus[0]} label=\"Select Menu Option\" data={menus} withAsterisk />;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { CSSProperties, JSX, ReactNode, SyntheticEvent } from 'react';\nimport { useState } from 'react';\nimport { FormContext } from './Form.context';\nimport { parseForm } from './FormUtils';\n\nexport interface FormProps {\n  readonly onSubmit?: (formData: Record<string, string>) => Promise<void> | void;\n  readonly style?: CSSProperties;\n  readonly children?: ReactNode;\n  readonly testid?: string;\n}\n\nexport function Form(props: FormProps): JSX.Element {\n  const [submitting, setSubmitting] = useState(false);\n  return (\n    <FormContext.Provider value={{ submitting }}>\n      <form\n        style={props.style}\n        data-testid={props.testid}\n        onSubmit={(e: SyntheticEvent) => {\n          e.preventDefault();\n          const formData = parseForm(e.target as HTMLFormElement);\n          if (props.onSubmit) {\n            setSubmitting(true);\n            const result = props.onSubmit(formData);\n            if (result?.then) {\n              result.catch(console.error).finally(() => {\n                setSubmitting(false);\n              });\n            } else {\n              setSubmitting(false);\n            }\n          }\n        }}\n      >\n        {props.children}\n      </form>\n    </FormContext.Provider>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createContext } from 'react';\n\nexport const FormContext = createContext<{ submitting: boolean }>({\n  submitting: false,\n});\nFormContext.displayName = 'FormContext';\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Parses an HTML form and returns the result as a JavaScript object.\n * @param form - The HTML form element.\n * @returns Form values in key value pairs.\n */\nexport function parseForm(form: HTMLFormElement): Record<string, string> {\n  const result: Record<string, string> = {};\n\n  for (const element of Array.from(form.elements)) {\n    if (element instanceof HTMLInputElement) {\n      parseInputElement(result, element);\n    } else if (element instanceof HTMLTextAreaElement) {\n      result[element.name] = element.value;\n    } else if (element instanceof HTMLSelectElement) {\n      parseSelectElement(result, element);\n    }\n  }\n\n  return result;\n}\n\n/**\n * Parses an HTML input element.\n * Sets the name/value pair in the result,\n * but only if the element is enabled and checked.\n * @param result - The result builder.\n * @param el - The input element.\n */\nfunction parseInputElement(result: Record<string, string>, el: HTMLInputElement): void {\n  if (el.disabled) {\n    // Ignore disabled elements\n    return;\n  }\n\n  if ((el.type === 'checkbox' || el.type === 'radio') && !el.checked) {\n    // Ignore unchecked radio or checkbox elements\n    return;\n  }\n\n  result[el.name] = el.value;\n}\n\n/**\n * Parses an HTML select element.\n * Sets the name/value pair if one is selected.\n * @param result - The result builder.\n * @param el - The select element.\n */\nfunction parseSelectElement(result: Record<string, string>, el: HTMLSelectElement): void {\n  result[el.name] = el.value;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ButtonProps } from '@mantine/core';\nimport { Button } from '@mantine/core';\nimport type { JSX } from 'react';\nimport { useContext } from 'react';\nimport { FormContext } from './Form.context';\n\nexport type SubmitButtonProps = Omit<ButtonProps, 'type' | 'loading'>;\n\nexport function SubmitButton(props: ButtonProps): JSX.Element {\n  const { children, ...buttonProps } = props;\n  const { submitting } = useContext(FormContext);\n  return (\n    <Button type=\"submit\" loading={submitting} {...buttonProps}>\n      {children}\n    </Button>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ResourceType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeInput } from '../CodeInput/CodeInput';\n\nexport interface ResourceTypeInputProps {\n  readonly name: string;\n  readonly placeholder?: string;\n  readonly defaultValue?: ResourceType;\n  readonly autoFocus?: boolean;\n  readonly testId?: string;\n  readonly maxValues?: number;\n  readonly onChange?: (value: ResourceType | undefined) => void;\n  readonly disabled?: boolean;\n  /** Render the options dropdown inside the DOM tree (not a portal); defaults to portalled. */\n  readonly withinPortal?: boolean;\n}\n\nexport function ResourceTypeInput(props: ResourceTypeInputProps): JSX.Element {\n  const [resourceType, setResourceType] = useState(props.defaultValue);\n  const onChange = props.onChange;\n\n  const setResourceTypeWrapper = useCallback(\n    (newResourceType: string | undefined) => {\n      setResourceType(newResourceType as ResourceType);\n      if (onChange) {\n        onChange(newResourceType as ResourceType);\n      }\n    },\n    [onChange]\n  );\n\n  return (\n    <CodeInput\n      disabled={props.disabled}\n      data-autofocus={props.autoFocus}\n      data-testid={props.testId}\n      defaultValue={resourceType}\n      onChange={setResourceTypeWrapper}\n      name={props.name}\n      placeholder={props.placeholder}\n      binding=\"https://medplum.com/fhir/ValueSet/resource-types\"\n      creatable={false}\n      maxValues={props.maxValues ?? 1}\n      clearable={false}\n      withHelpText={false}\n      withinPortal={props.withinPortal}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport type { ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\nimport { ValueSetAutocomplete } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nexport interface CodeInputProps extends Omit<ValueSetAutocompleteProps, 'defaultValue' | 'onChange'> {\n  readonly defaultValue?: string;\n  readonly onChange: ((value: string | undefined) => void) | undefined;\n}\n\nexport function CodeInput(props: CodeInputProps): JSX.Element {\n  const { defaultValue, onChange, withHelpText, ...rest } = props;\n  const [value, setValue] = useState(defaultValue);\n\n  function handleChange(newValues: ValueSetExpansionContains[]): void {\n    const newValue = newValues[0];\n    const newCode = valueSetElementToCode(newValue);\n    setValue(newCode);\n    if (onChange) {\n      onChange(newCode);\n    }\n  }\n\n  return (\n    <ValueSetAutocomplete\n      defaultValue={codeToValueSetElement(value)}\n      onChange={handleChange}\n      withHelpText={withHelpText ?? true}\n      {...rest}\n    />\n  );\n}\n\nfunction codeToValueSetElement(code: string | undefined): ValueSetExpansionContains | undefined {\n  return code ? { code } : undefined;\n}\n\nfunction valueSetElementToCode(element: ValueSetExpansionContains | undefined): string | undefined {\n  return element?.code;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Group, Text } from '@mantine/core';\nimport type { ValueSetExpandParams } from '@medplum/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport type { ValueSet, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useMedplum, useValueSetAvailability } from '@medplum/react-hooks';\nimport { IconCheck } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { forwardRef, useCallback, useState } from 'react';\nimport type { AsyncAutocompleteOption, AsyncAutocompleteProps } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { AsyncAutocomplete } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { UnavailableNote } from '../UnavailableNote/UnavailableNote';\n\nexport interface ValueSetAutocompleteProps extends Omit<\n  AsyncAutocompleteProps<ValueSetExpansionContains>,\n  'loadOptions' | 'toKey' | 'toOption'\n> {\n  readonly binding: string | undefined;\n  readonly creatable?: boolean;\n  readonly clearable?: boolean;\n  readonly expandParams?: Partial<ValueSetExpandParams>;\n  readonly withHelpText?: boolean;\n}\n\nfunction toKey(element: ValueSetExpansionContains): string {\n  if (typeof element.code === 'string') {\n    return element.code;\n  }\n  return JSON.stringify(element);\n}\n\nfunction getDisplay(item: ValueSetExpansionContains): string {\n  if (typeof item.display === 'string') {\n    return item.display;\n  }\n  return toKey(item);\n}\n\nfunction toOption(element: ValueSetExpansionContains): AsyncAutocompleteOption<ValueSetExpansionContains> {\n  return {\n    value: toKey(element),\n    label: getDisplay(element),\n    resource: element,\n  };\n}\n\nfunction createValue(input: string): ValueSetExpansionContains {\n  return {\n    code: input,\n    display: input,\n  };\n}\n\n/**\n * A low-level component to autocomplete based on a FHIR Valueset.\n * This is the base component for CodeableConceptInput, CodingInput, and CodeInput.\n * @param props - The ValueSetAutocomplete React props.\n * @returns The ValueSetAutocomplete React node.\n */\nexport function ValueSetAutocomplete(props: ValueSetAutocompleteProps): JSX.Element {\n  const medplum = useMedplum();\n  const { binding, creatable, clearable, expandParams, withHelpText, itemComponent, error, description, ...rest } =\n    props;\n  const isCreatable = creatable ?? true;\n  const isUnavailable = useValueSetAvailability(binding) === false;\n  const [searchError, setSearchError] = useState<string>();\n\n  const loadValues = useCallback(\n    async (input: string, signal: AbortSignal): Promise<ValueSetExpansionContains[]> => {\n      if (!binding || isUnavailable) {\n        return [];\n      }\n      try {\n        const valueSet: ValueSet = await medplum.valueSetExpand(\n          {\n            count: 10,\n            ...expandParams,\n            url: binding,\n            filter: input,\n          },\n          { signal }\n        );\n        setSearchError(undefined);\n        const valueSetElements = valueSet.expansion?.contains ?? [];\n        const newData: ValueSetExpansionContains[] = [];\n        for (const valueSetElement of valueSetElements) {\n          if (valueSetElement.code && !newData.some((item) => item.code === valueSetElement.code)) {\n            newData.push(valueSetElement);\n          }\n        }\n        return newData;\n      } catch (err) {\n        // Surface the failure inline (below) and swallow it, so the shared AsyncAutocomplete does\n        // not also raise a toast. A search 400 is never treated as \"value set missing\" - that\n        // verdict comes only from the filter-free mount probe in useValueSetAvailability.\n        const message = normalizeErrorString(err);\n        if (!(signal.aborted || message.includes('aborted'))) {\n          setSearchError(message);\n        }\n        return [];\n      }\n    },\n    [medplum, expandParams, binding, isUnavailable]\n  );\n\n  // An unavailable value set degrades the field by severity: if manual entry is allowed the field\n  // stays usable with a quiet helper note, otherwise it is truly unusable and gets disabled.\n  let inputDescription: ReactNode = description;\n  let inputError: ReactNode = error;\n  let inputDisabled = rest.disabled;\n  if (isUnavailable) {\n    const unavailableMessage = `Value set ${binding} is unavailable`;\n    if (isCreatable) {\n      // The field is still usable, so show a non-error helper note (in the description slot)\n      const unavailableNote = (\n        <UnavailableNote text=\"Suggestions unavailable\" severity=\"warning\" message={unavailableMessage} />\n      );\n      inputDescription = combineNodes(description, unavailableNote);\n    } else {\n      // The field is unusable: disable it and explain why alongside any consumer validation error\n      const unavailableNote = (\n        <UnavailableNote text=\"This field is unavailable.\" severity=\"error\" message={unavailableMessage} />\n      );\n      inputError = combineNodes(error, unavailableNote);\n      inputDisabled = true;\n    }\n  } else if (searchError) {\n    // A transient search failure shows inline, below the input, alongside any validation error\n    inputError = combineNodes(error, searchError);\n  }\n\n  return (\n    <AsyncAutocomplete\n      {...rest}\n      description={inputDescription}\n      error={inputError}\n      disabled={inputDisabled}\n      creatable={isCreatable}\n      clearable={clearable ?? true}\n      toOption={toOption}\n      loadOptions={loadValues}\n      onCreate={createValue}\n      // A caller's own row wins: `withHelpText` is the built-in one, not the only one allowed.\n      itemComponent={itemComponent ?? (withHelpText ? ItemComponent : undefined)}\n    />\n  );\n}\n\n/**\n * Stacks two pieces of field text, dropping either if absent. The second node is a block-level\n * `span` with a top margin so it always starts on its own line and stays visually separated even\n * when the first node's text wraps \u2014 with no extra spacing when only one node is present. A `span`\n * (rather than a `div`/`Stack`) keeps this valid inside Mantine's description/error slots, which\n * render as a `<p>` and cannot legally contain block elements.\n * @param first - The first node (e.g. a consumer-supplied error or description).\n * @param second - The second node (e.g. the unavailable/search-error note).\n * @returns Both nodes stacked with spacing, or whichever one is present.\n */\nfunction combineNodes(first: ReactNode, second: ReactNode): ReactNode {\n  if (first && second) {\n    return (\n      <>\n        {first}\n        <Box component=\"span\" display=\"block\" mt=\"xs\">\n          {second}\n        </Box>\n      </>\n    );\n  }\n  return first || second;\n}\n\nconst ItemComponent = forwardRef<HTMLDivElement, AsyncAutocompleteOption<ValueSetExpansionContains>>(\n  ({ label, resource, active, ...others }: AsyncAutocompleteOption<ValueSetExpansionContains>, ref) => {\n    return (\n      <div ref={ref} {...others}>\n        <Group wrap=\"nowrap\" gap=\"xs\">\n          {active && <IconCheck size={12} />}\n          <div>\n            <Text>{label}</Text>\n            <Text size=\"xs\" c=\"dimmed\">\n              {`${resource.system}#${resource.code}`}\n            </Text>\n          </div>\n        </Group>\n      </div>\n    );\n  }\n);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Text, Tooltip } from '@mantine/core';\nimport { IconInfoCircle } from '@tabler/icons-react';\nimport type { JSX } from 'react';\n\n/**\n * How badly the missing dependency degrades the field: `warning` when the field is still usable\n * (e.g. it accepts free text and has only lost its suggestions), `error` when it is not.\n */\nexport type UnavailableNoteSeverity = 'warning' | 'error';\n\nconst SEVERITY_COLORS: Record<UnavailableNoteSeverity, string> = {\n  warning: 'yellow.9',\n  error: 'red',\n};\n\nexport interface UnavailableNoteProps {\n  readonly text: string;\n  /** Defaults to `warning`. */\n  readonly severity?: UnavailableNoteSeverity;\n  /** When set, overrides the color `severity` would pick. */\n  readonly color?: string;\n  readonly message: string;\n}\n\nexport function UnavailableNote({ text, severity = 'warning', color, message }: UnavailableNoteProps): JSX.Element {\n  const noteColor = color ?? SEVERITY_COLORS[severity];\n  return (\n    <Text span size=\"xs\" c={noteColor}>\n      {text}\n      <Tooltip label={message} position=\"top-start\" withArrow events={{ hover: true, focus: true, touch: true }}>\n        <ActionIcon\n          variant=\"subtle\"\n          color={noteColor}\n          size={16}\n          ml={4}\n          aria-label={`Why is this unavailable? ${message}`}\n          style={{ verticalAlign: 'text-bottom' }}\n        >\n          <IconInfoCircle size={14} />\n        </ActionIcon>\n      </Tooltip>\n    </Text>\n  );\n}\n", ".navbar {\n  padding: 0;\n  transition-property: width;\n}\n\n.logoButton {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: fit-content;\n  height: fit-content;\n  padding: 8px 7px;\n  border-radius: var(--mantine-radius-md);\n  transition: background-color 100ms ease;\n\n  &:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n  }\n\n  & > * {\n    display: block;\n  }\n}\n\n.menuTitle {\n  height: 40px;\n  margin: 0;\n  padding-left: 10px;\n  display: flex;\n  align-items: flex-end;\n  padding-bottom: 8px;\n  box-sizing: border-box;\n  font-size: var(--mantine-font-size-xs);\n  font-weight: 500;\n  line-height: 1;\n  white-space: nowrap;\n  overflow: hidden;\n  color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-gray-6));\n  opacity: 0;\n  transition: opacity 150ms ease;\n\n  &[data-opened] {\n    opacity: 1;\n  }\n}\n\n.menuTitle:empty,\n.menuTitle:blank {\n  display: none;\n}\n\n.link {\n  width: 100%;\n  height: 36px;\n  border-radius: var(--mantine-radius-md);\n  font-weight: 450;\n  display: flex;\n  align-items: center;\n  justify-content: start;\n  padding: 0 var(--mantine-spacing-xs);\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));\n  outline: none;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  text-decoration: none;\n\n  &:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n    text-decoration: none;\n  }\n\n  & svg:global(.tabler-icon) {\n    color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));\n    stroke-width: 2;\n    width: 18px;\n    height: 18px;\n    min-width: 18px;\n    max-width: 18px;\n  }\n\n  &[data-active] {\n    &,\n    &:hover {\n      background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n      color: light-dark(var(--mantine-primary-color-light-color), var(--mantine-primary-color-5));\n\n      & svg:global(.tabler-icon) {\n        color: light-dark(var(--mantine-primary-color-light-color), var(--mantine-primary-color-6));\n      }\n    }\n\n    & .dismissButton {\n      color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));\n\n      & svg:global(.tabler-icon) {\n        color: inherit;\n      }\n\n      &:hover {\n        color: light-dark(var(--mantine-color-gray-9), var(--mantine-color-gray-0));\n      }\n    }\n  }\n}\n\n.link:focus-visible {\n  outline: none;\n}\n\n.linkLabel {\n  margin-left: 8px;\n  white-space: nowrap;\n  opacity: 0;\n  transition: opacity 150ms ease;\n\n  &[data-opened] {\n    opacity: 1;\n  }\n}\n\n.userLink {\n  height: auto;\n  min-height: 36px;\n  padding-top: 4px;\n  padding-bottom: 4px;\n}\n\n.userLinkLabel {\n  display: flex;\n  flex-direction: column;\n  margin-left: 8px;\n  min-width: 0;\n  opacity: 0;\n  transition: opacity 150ms ease;\n\n  &[data-opened] {\n    opacity: 1;\n  }\n}\n\n.iconWrapper {\n  position: relative;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.alertDot {\n  position: absolute;\n  bottom: -2px;\n  left: 13px;\n  width: 8px;\n  height: 8px;\n  border-radius: 50%;\n  background-color: var(--mantine-color-red-6);\n  pointer-events: none;\n}\n\n.linkCount {\n  margin-left: auto;\n  font-size: var(--mantine-font-size-xs);\n  font-weight: 500;\n  color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-3));\n  white-space: nowrap;\n  opacity: 0;\n  transition: opacity 150ms ease;\n\n  &[data-opened] {\n    opacity: 1;\n  }\n\n  &[data-alert] {\n    color: var(--mantine-color-white);\n    background-color: var(--mantine-color-red-6);\n    font-weight: 600;\n    font-size: 10px;\n    min-width: 18px;\n    height: 18px;\n    line-height: 18px;\n    text-align: center;\n    border-radius: 9px;\n    padding: 0 5px;\n  }\n}\n\n.dismissButton {\n  display: none;\n  margin-left: auto;\n  align-items: center;\n  justify-content: center;\n  padding: 4px;\n  border-radius: 4px;\n  cursor: pointer;\n}\n\n.link:hover .dismissButton {\n  display: flex;\n}\n\n.link .dismissButton {\n  color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-3));\n\n  & svg:global(.tabler-icon) {\n    color: inherit;\n  }\n\n  &:hover {\n    color: light-dark(var(--mantine-color-gray-9), var(--mantine-color-gray-0));\n  }\n}\n\n.addBookmarkLink {\n  margin-top: 40px;\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));\n\n\n  & svg:global(.tabler-icon) {\n    color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));\n  }\n}\n\n.toggleButton {\n  width: 38px;\n  height: 36px;\n  border-radius: var(--mantine-radius-md);\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 0;\n  transition: background-color 100ms ease;\n  cursor: e-resize;\n\n  &[data-opened] {\n    cursor: w-resize;\n  }\n\n  & svg:global(.tabler-icon) {\n    color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-0));\n    stroke-width: 2;\n    width: 18px;\n    height: 18px;\n    min-width: 18px;\n    max-width: 18px;\n  }\n\n  &:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n  }\n}\n\n.divider {\n  border-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Kbd, Stack, Text } from '@mantine/core';\nimport { useDebouncedCallback } from '@mantine/hooks';\nimport type { SpotlightActionData } from '@mantine/spotlight';\nimport { Spotlight as MantineSpotlight, spotlight } from '@mantine/spotlight';\nimport { formatHumanName, isUUID } from '@medplum/core';\nimport type { Patient, ServiceRequest, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport classes from './Spotlight.module.css';\n\nconst DEBOUNCE_MS = 200;\n\nexport type HeaderSearchTypes = Patient | ServiceRequest;\n\n/**\n * A Spotlight entry. Setting `href` renders it as an anchor rather than a button, so the browser's\n * \"Open link in new tab\" context menu and Cmd/Ctrl+click both work. A plain click is handed to the\n * SPA router instead of triggering a full page load; pass `onClick` to do something other than\n * navigate to `href`.\n */\nexport interface SpotlightLinkAction extends SpotlightActionData {\n  readonly href?: string;\n}\n\ninterface SpotlightLinkActionGroup {\n  readonly group: string;\n  readonly actions: SpotlightLinkAction[];\n}\n\nexport interface SpotlightProps {\n  readonly patientsOnly?: boolean;\n  readonly staticActions?: SpotlightLinkAction[];\n}\n\nfunction ShortcutHints(): JSX.Element {\n  return (\n    <Group gap=\"lg\" justify=\"flex-start\" align=\"center\" wrap=\"wrap\" className={classes.shortcutHints}>\n      <Group gap={6} align=\"center\" wrap=\"nowrap\">\n        <span className={classes.groupLabel}>Open search</span>\n        <Kbd>\u2318</Kbd>\n        <Kbd>K</Kbd>\n      </Group>\n      <Group gap={6} align=\"center\" wrap=\"nowrap\">\n        <span className={classes.groupLabel}>Select</span>\n        <Kbd>\u2191</Kbd>\n        <Kbd>\u2193</Kbd>\n      </Group>\n      <Group gap={6} align=\"center\" wrap=\"nowrap\">\n        <span className={classes.groupLabel}>Open / Go</span>\n        <Kbd>\u21B5</Kbd>\n      </Group>\n    </Group>\n  );\n}\n\ninterface SpotlightActionItemProps {\n  readonly action: SpotlightLinkAction;\n  readonly group?: string;\n  readonly highlightQuery?: boolean;\n}\n\n/**\n * Renders one Spotlight entry, as an anchor when the action has an `href`.\n * @param props - The Spotlight action item props.\n * @param props.action - The action to render.\n * @param props.group - The name of the group the action belongs to.\n * @param props.highlightQuery - Whether to highlight the search query within the label.\n * @returns The rendered Spotlight action.\n */\nfunction SpotlightActionItem({ action, group, highlightQuery }: SpotlightActionItemProps): JSX.Element {\n  const navigate = useMedplumNavigate();\n  const { href, onClick } = action;\n\n  // Typed as HTMLElement because the action renders as an anchor whenever `href` is set.\n  const handleClick: React.MouseEventHandler<HTMLElement> = (event) => {\n    // Let the browser take modified clicks on a real link (new tab / new window / download)\n    // and leave the palette open, since the current page isn't going anywhere.\n    if (href && (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)) {\n      return;\n    }\n    event.preventDefault();\n    if (onClick) {\n      // Same button-only typing as `component`/`href` below; the event is an anchor's when `href` is set.\n      onClick(event as React.MouseEvent<HTMLButtonElement>);\n    } else if (href) {\n      navigate(href);\n    }\n    spotlight.close();\n  };\n\n  return (\n    <MantineSpotlight.Action\n      label={action.label}\n      description={action.description}\n      leftSection={action.leftSection}\n      highlightQuery={highlightQuery}\n      // Closing is handled in `handleClick` so modified clicks can keep the palette open.\n      closeSpotlightOnTrigger={false}\n      onClick={handleClick}\n      // `component`/`href` pass through to the polymorphic UnstyledButton underneath, which\n      // `SpotlightActionProps` types as button-only. `group` is a grouping/testing selector hook.\n      {...({ ...(href && { component: 'a', href }), group } as Record<string, unknown>)}\n    />\n  );\n}\n\n/**\n * Filters action groups by query (matching label or description), dropping empty groups.\n * Mantine's `defaultSpotlightFilter` is internal to `@mantine/spotlight` and the composable API\n * has no `filter` prop, so the same label/description matching is applied here.\n * @param query - The search query.\n * @param groups - The action groups to filter.\n * @returns The filtered action groups.\n */\nfunction filterActionGroups(query: string, groups: SpotlightLinkActionGroup[]): SpotlightLinkActionGroup[] {\n  const q = query.trim().toLowerCase();\n  const result: SpotlightLinkActionGroup[] = [];\n  for (const { group, actions } of groups) {\n    const matches = actions.filter(\n      (a) => a.label?.toLowerCase().includes(q) || a.description?.toLowerCase().includes(q)\n    );\n    if (matches.length > 0) {\n      result.push({ group, actions: matches });\n    }\n  }\n  return result;\n}\n\ninterface SearchGraphQLResponse {\n  readonly data: {\n    readonly Patients1: Patient[] | undefined;\n    readonly Patients2: Patient[] | undefined;\n    readonly ServiceRequestList: ServiceRequest[] | undefined;\n  };\n}\n\nfunction KeyboardHint(): JSX.Element {\n  return (\n    <Stack gap=\"xs\" py=\"lg\">\n      <Text size=\"sm\" c=\"dimmed\">\n        Press <Kbd>\u2318</Kbd> + <Kbd>K</Kbd> to open Search next time.\n      </Text>\n      <Text size=\"sm\" c=\"dimmed\">\n        (<Kbd>Ctrl</Kbd> + <Kbd>K</Kbd> on Windows)\n      </Text>\n    </Stack>\n  );\n}\n\nexport function Spotlight({ patientsOnly, staticActions }: SpotlightProps): JSX.Element {\n  const medplum = useMedplum();\n  const [query, setQuery] = useState('');\n  const [searching, setSearching] = useState(false);\n  const [actions, setActions] = useState<SpotlightLinkActionGroup[]>([]);\n\n  const debouncedSearch = useDebouncedCallback((searchQuery: string) => {\n    const graphqlQuery = buildGraphQLQuery(searchQuery);\n\n    if (patientsOnly) {\n      // Only search patients\n      medplum\n        .graphql(graphqlQuery)\n        .then((response: SearchGraphQLResponse) => {\n          const resources = getResourcesFromResponse(response);\n          const patients = resources.filter((r): r is Patient => r.resourceType === 'Patient');\n          setActions(patientsToActions(patients));\n        })\n        .catch(console.error)\n        .finally(() => setSearching(false));\n    } else {\n      // Search patients, service requests, and resource types\n      Promise.all([\n        medplum.graphql(graphqlQuery),\n        medplum.valueSetExpand({\n          url: 'https://medplum.com/fhir/ValueSet/resource-types',\n          filter: searchQuery,\n          count: 5,\n        }),\n      ])\n        .then(([graphqlResponse, valueSetResult]) => {\n          const resources = getResourcesFromResponse(graphqlResponse as SearchGraphQLResponse);\n          const resourceTypes = valueSetResult.expansion?.contains ?? [];\n          setActions(resourcesToActions(resources, resourceTypes));\n        })\n        .catch(console.error)\n        .finally(() => setSearching(false));\n    }\n  }, DEBOUNCE_MS);\n\n  const handleQueryChange = (newQuery: string): void => {\n    setQuery(newQuery);\n    if (!newQuery) {\n      debouncedSearch.cancel();\n      setSearching(false);\n      setActions([]);\n      return;\n    }\n    setSearching(true);\n    debouncedSearch(newQuery);\n  };\n\n  const showStaticActions = !query && !!staticActions?.length;\n  const filteredActions = query ? filterActionGroups(query, actions) : [];\n\n  // Empty-state content, shown (via Spotlight.Empty) only when no actions are listed.\n  let emptyContent: ReactNode;\n  if (!showStaticActions && filteredActions.length === 0) {\n    if (searching) {\n      emptyContent = 'Searching...';\n    } else if (query) {\n      emptyContent = 'No results found';\n    } else {\n      emptyContent = <KeyboardHint />;\n    }\n  }\n\n  return (\n    <MantineSpotlight.Root\n      query={query}\n      onQueryChange={handleQueryChange}\n      radius=\"md\"\n      classNames={{\n        body: classes.body,\n        content: classes.content,\n        search: classes.search,\n        actionsList: classes.actionsList,\n        action: classes.action,\n        actionSection: classes.actionSection,\n        actionDescription: classes.actionDescription,\n        actionsGroup: classes.actionsGroup,\n        empty: classes.emptyState,\n        footer: classes.footer,\n      }}\n    >\n      <MantineSpotlight.Search\n        leftSection={<IconSearch size=\"1.2rem\" stroke={2} color=\"var(--mantine-color-gray-5)\" />}\n        placeholder=\"Start typing to search\u2026\"\n        type=\"search\"\n        autoComplete=\"off\"\n        autoCorrect=\"off\"\n        spellCheck={false}\n        name={patientsOnly ? 'provider-spotlight-search' : 'spotlight-search'}\n        // Tell common password managers to ignore this field\n        {...({ 'data-1p-ignore': 'true', 'data-lpignore': 'true' } as any)}\n        leftSectionProps={{ style: { marginLeft: 'calc(var(--mantine-spacing-md) - 12px)' } }}\n      />\n\n      <MantineSpotlight.ActionsList>\n        {showStaticActions && (\n          <MantineSpotlight.ActionsGroup label=\"Actions\">\n            {staticActions?.map((action) => (\n              <SpotlightActionItem key={action.id} action={action} group=\"Actions\" />\n            ))}\n          </MantineSpotlight.ActionsGroup>\n        )}\n\n        {!!query &&\n          filteredActions.map((group) => (\n            <MantineSpotlight.ActionsGroup key={group.group} label={group.group}>\n              {group.actions.map((action) => (\n                <SpotlightActionItem key={action.id} action={action} group={group.group} highlightQuery />\n              ))}\n            </MantineSpotlight.ActionsGroup>\n          ))}\n\n        {emptyContent && <MantineSpotlight.Empty>{emptyContent}</MantineSpotlight.Empty>}\n      </MantineSpotlight.ActionsList>\n\n      <MantineSpotlight.Footer>\n        <ShortcutHints />\n      </MantineSpotlight.Footer>\n    </MantineSpotlight.Root>\n  );\n}\n\nfunction buildGraphQLQuery(input: string): string {\n  const escaped = JSON.stringify(input);\n  if (isUUID(input)) {\n    return `{\n      Patients1: PatientList(_id: ${escaped}, _count: 1) {\n        resourceType\n        id\n        identifier { system value }\n        name { given family }\n        birthDate\n        photo { url contentType }\n      }\n      ServiceRequestList(_id: ${escaped}, _count: 1) {\n        resourceType\n        id\n        identifier { system value }\n        subject { display }\n      }\n    }`.replaceAll(/\\s+/g, ' ');\n  }\n  return `{\n    Patients1: PatientList(name: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier { system value }\n      name { given family }\n      birthDate\n      photo { url contentType }\n    }\n    Patients2: PatientList(identifier: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier { system value }\n      name { given family }\n      birthDate\n      photo { url contentType }\n    }\n    ServiceRequestList(identifier: ${escaped}, _count: 5) {\n      resourceType\n      id\n      identifier { system value }\n      subject { display }\n    }\n  }`.replaceAll(/\\s+/g, ' ');\n}\n\nfunction getResourcesFromResponse(response: SearchGraphQLResponse): HeaderSearchTypes[] {\n  const resources: HeaderSearchTypes[] = [];\n  if (response.data.Patients1) {\n    resources.push(...response.data.Patients1);\n  }\n  if (response.data.Patients2) {\n    resources.push(...response.data.Patients2);\n  }\n  if (response.data.ServiceRequestList) {\n    resources.push(...response.data.ServiceRequestList);\n  }\n  return dedupeResources(resources);\n}\n\nfunction dedupeResources(resources: HeaderSearchTypes[]): HeaderSearchTypes[] {\n  const ids = new Set<string>();\n  const result: HeaderSearchTypes[] = [];\n  for (const resource of resources) {\n    if (resource.id && !ids.has(resource.id)) {\n      ids.add(resource.id);\n      result.push(resource);\n    }\n  }\n  return result;\n}\n\nfunction patientToAction(patient: Patient & { id: string }): SpotlightLinkAction {\n  return {\n    id: patient.id,\n    href: `/Patient/${patient.id}`,\n    label: patient.name ? formatHumanName(patient.name[0]) : patient.id,\n    description: patient.birthDate,\n    leftSection: <ResourceAvatar value={patient} radius=\"xl\" size={24} />,\n  };\n}\n\nfunction patientsToActions(patients: Patient[]): SpotlightLinkActionGroup[] {\n  const patientActions: SpotlightLinkAction[] = patients\n    .filter((p): p is Patient & { id: string } => Boolean(p.id))\n    .map(patientToAction);\n\n  return patientActions.length > 0 ? [{ group: 'Patients', actions: patientActions }] : [];\n}\n\nfunction resourcesToActions(\n  resources: HeaderSearchTypes[],\n  resourceTypes: ValueSetExpansionContains[]\n): SpotlightLinkActionGroup[] {\n  const result: SpotlightLinkActionGroup[] = [];\n\n  // Resource types\n  const resourceTypeActions: SpotlightLinkAction[] = resourceTypes.map((rt) => ({\n    id: `resource-type-${rt.code}`,\n    href: `/${rt.code}`,\n    label: rt.display ?? rt.code ?? '',\n    description: 'Resource Type',\n  }));\n  if (resourceTypeActions.length > 0) {\n    result.push({ group: 'Resource Types', actions: resourceTypeActions });\n  }\n\n  const patientActions: SpotlightLinkAction[] = [];\n  const serviceRequestActions: SpotlightLinkAction[] = [];\n\n  for (const resource of resources) {\n    if (resource.resourceType === 'Patient' && resource.id) {\n      patientActions.push(patientToAction(resource as Patient & { id: string }));\n    } else if (resource.resourceType === 'ServiceRequest' && resource.id) {\n      serviceRequestActions.push({\n        id: resource.id,\n        href: `/ServiceRequest/${resource.id}`,\n        label: resource.id,\n        description: resource.subject?.display,\n      });\n    }\n  }\n\n  if (patientActions.length > 0) {\n    result.push({ group: 'Patients', actions: patientActions });\n  }\n  if (serviceRequestActions.length > 0) {\n    result.push({ group: 'Service Requests', actions: serviceRequestActions });\n  }\n\n  return result;\n}\n", "/*\n * Spotlight component style overrides.\n * Uses Mantine's classNames API for maintainability across Mantine upgrades.\n * See: https://mantine.dev/styles/styles-api/\n */\n\n/* Action section (avatar/icon) margins */\n.actionSection[data-position='left'] {\n  margin-inline-end: var(--mantine-spacing-xs);\n}\n\n.actionSection[data-position='right'] {\n  margin-inline-start: var(--mantine-spacing-xs);\n}\n\n/* Action item styling - matches navbar link colors */\n.action:where(:not([data-selected])):hover,\n.action:where(:not([data-selected])):active {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n.action:where([data-selected]) {\n  background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n  color: light-dark(var(--mantine-primary-color-light-color), var(--mantine-primary-color-5));\n}\n\n.action:where([data-selected]) .actionDescription {\n  color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-gray-5));\n}\n\n/* Action group styling */\n.actionsGroup {\n  gap: 4px;\n  margin-top: 4px;\n  padding-top: var(--mantine-spacing-md);\n}\n\n/* First group: compensate for container padding */\n.actionsGroup:first-child {\n  margin-top: 0;\n  padding-top: calc(var(--mantine-spacing-md) - 2px);\n}\n\n/* Add divider between action groups */\n.actionsGroup:not(:first-child) {\n  border-top: calc(0.0625rem * var(--mantine-scale)) solid\n    light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n/* Actions list container */\n.actionsList {\n  padding-top: 2px;\n}\n\n/* Modal content wrapper */\n.content {\n  box-shadow: 0 0.5rem 2rem light-dark(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.5));\n}\n\n/* Group label \u2014 match Menu.Label (title case, not Mantine's default uppercase). */\n.groupLabel,\n.actionsGroup::before {\n  font-size: var(--mantine-font-size-xs);\n  font-weight: 500;\n  color: var(--mantine-color-dimmed);\n  text-transform: none;\n}\n\n.actionsGroup::before {\n  padding-inline: var(--mantine-spacing-md);\n  padding-bottom: 2px;\n}\n\n/* Searching / empty hint \u2014 same top as first Actions group */\n.emptyState {\n  padding-top: calc(var(--mantine-spacing-md) - 2px);\n  padding-inline: var(--mantine-spacing-md);\n  padding-bottom: var(--mantine-spacing-md);\n}\n\n/* Footer with keyboard shortcut hints \u2014 match Actions title inset */\n.footer {\n  border-top: calc(0.0625rem * var(--mantine-scale)) solid\n    light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n  padding: var(--mantine-spacing-md) calc(var(--mantine-spacing-md) + calc(0.25rem * var(--mantine-scale)));\n}\n\n.shortcutHints {\n  width: 100%;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InternalSchemaElement } from '@medplum/core';\nimport { getPathDisplayName, isPopulated } from '@medplum/core';\nimport type { Attachment } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\n\nexport interface AttachmentArrayDisplayProps {\n  readonly path?: string;\n  readonly values?: Attachment[];\n  readonly maxWidth?: number;\n  readonly includeDescriptionListEntry?: boolean;\n  readonly property?: InternalSchemaElement;\n}\n\nexport function AttachmentArrayDisplay(props: AttachmentArrayDisplayProps): JSX.Element {\n  const attachmentElements = props.values?.map((v, index) => (\n    <div key={'attatchment-' + index}>\n      <AttachmentDisplay value={v} maxWidth={props.maxWidth} />\n    </div>\n  ));\n\n  let content: JSX.Element;\n  if (props.includeDescriptionListEntry) {\n    if (props.property === undefined) {\n      throw new Error('props.property is required when includeDescriptionListEntry is true');\n    }\n\n    if (!isPopulated(props.path)) {\n      throw new Error('props.path is required when includeDescriptionListEntry is true');\n    }\n\n    // Since arrays are responsible for rendering their own DescriptionListEntry, we must find the key\n    const key = props.path.split('.').pop() as string;\n    content = <DescriptionListEntry term={getPathDisplayName(key)}>{attachmentElements}</DescriptionListEntry>;\n  } else {\n    content = <>{attachmentElements}</>;\n  }\n  return content;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor } from '@mantine/core';\nimport { ContentType } from '@medplum/core';\nimport type { Attachment } from '@medplum/fhirtypes';\nimport type { MedplumContext } from '@medplum/react-hooks';\nimport { useCachedBinaryUrl, useMedplumContext } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { CcdaDisplay } from '../CcdaDisplay/CcdaDisplay';\nimport { ScannedImage } from './ScannedImage';\n\nexport interface AttachmentDisplayProps {\n  readonly value?: Attachment;\n  readonly maxWidth?: number;\n}\n\nexport function AttachmentDisplay(props: AttachmentDisplayProps): JSX.Element | null {\n  // Optional context: AttachmentDisplay does not require a MedplumProvider\n  const baseUrl = (useMedplumContext() as MedplumContext | undefined)?.medplum.getBaseUrl();\n  const { contentType, data, url: storedUrl, title } = props.value ?? {};\n  const uncachedUrl = toSafeUrl(storedUrl, baseUrl);\n  const cachedUrl = useCachedBinaryUrl(uncachedUrl);\n\n  if (!cachedUrl && !data) {\n    return null;\n  }\n\n  const url = cachedUrl ?? `data:${contentType};base64,${data}`;\n\n  return (\n    <div data-testid=\"attachment-display\">\n      {contentType?.startsWith('image/') && (\n        <ScannedImage data-testid=\"attachment-image\" style={{ maxWidth: props.maxWidth }} src={url} alt={title} />\n      )}\n      {contentType?.startsWith('video/') && (\n        <video data-testid=\"attachment-video\" style={{ maxWidth: props.maxWidth }} controls={true}>\n          <source type={contentType} src={url} />\n        </video>\n      )}\n      {contentType?.startsWith('audio/') && (\n        <audio data-testid=\"attachment-audio\" style={{ maxWidth: props.maxWidth }} controls={true}>\n          <source type={contentType} src={url} />\n        </audio>\n      )}\n      {(contentType?.startsWith('text/') ||\n        contentType === 'application/json' ||\n        contentType === 'application/pdf') && (\n        <div data-testid=\"attachment-iframe\" style={{ maxWidth: props.maxWidth, minHeight: 400 }}>\n          <iframe\n            title=\"Attachment\"\n            width=\"100%\"\n            height=\"400\"\n            src={url + '#navpanes=0'}\n            allowFullScreen={true}\n            frameBorder={0}\n            seamless={true}\n          />\n        </div>\n      )}\n      {contentType === ContentType.CDA_XML && <CcdaDisplay url={url} />}\n      <div data-testid=\"download-link\" style={{ padding: '2px 16px 16px 16px' }}>\n        <Anchor\n          // use the `uncachedUrl` to download the file as the cached URL may expire by the time the user clicks the download link\n          href={uncachedUrl}\n          data-testid=\"attachment-details\"\n          target=\"_blank\"\n          rel=\"noopener noreferrer\"\n          download={getDownloadName(title)}\n        >\n          {title || 'Download'}\n        </Anchor>\n      </div>\n    </div>\n  );\n}\n\n/**\n * Returns the URL only when it cannot load a page of the current app.\n * Same-origin URLs are rejected unless they are Medplum storage URLs (single-origin deployments),\n * because the URL is rendered into an iframe and a link. Other server paths can redirect to app pages.\n * @param url - The attachment URL.\n * @param baseUrl - The Medplum server base URL, if available.\n * @returns The URL if it is a data, blob, other-origin http(s), or Medplum storage URL; otherwise undefined.\n */\nfunction toSafeUrl(url: string | undefined, baseUrl: string | undefined): string | undefined {\n  if (!url) {\n    return undefined;\n  }\n  try {\n    const parsed = new URL(url, window.location.href);\n    if (parsed.protocol === 'data:' || parsed.protocol === 'blob:') {\n      return url;\n    }\n    if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {\n      return undefined;\n    }\n    if (parsed.origin !== window.location.origin) {\n      return parsed.href;\n    }\n    if (!baseUrl) {\n      return undefined;\n    }\n    // Return the parsed href so the browser loads exactly the path that was checked\n    const storage = new URL('storage/', new URL(baseUrl, window.location.href));\n    const isStorageUrl = storage.origin === parsed.origin && parsed.pathname.startsWith(storage.pathname);\n    return isStorageUrl ? parsed.href : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction getDownloadName(title: string | undefined): string | undefined {\n  // Title often contains the filename by convention\n  return title?.includes('.') ? title : undefined;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button } from '@mantine/core';\nimport type { JSX } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { exportJsonFile, sendCommand } from '../utils/dom';\n\nconst CCDA_VIEWER_URL = 'https://ccda.medplum.com';\nconst BASE_VALIDATION_URL = 'https://ccda-validator.medplum.com/';\n\nexport interface CcdaDisplayProps {\n  readonly url?: string;\n  readonly maxWidth?: number;\n}\n\ninterface ValidationResult {\n  resultsMetaData: {\n    ccdaDocumentType: string;\n    ccdaVersion: string;\n    objectiveProvided: string;\n    serviceError: boolean;\n    serviceErrorMessage: string | null;\n    ccdaFileName: string;\n    ccdaFileContents: string;\n    resultMetaData: {\n      type: string;\n      count: number;\n    }[];\n    severityLevel: string;\n    totalConformanceErrorChecks: number;\n  };\n}\n\nexport function CcdaDisplay(props: CcdaDisplayProps): JSX.Element | null {\n  const { url } = props;\n  const [shouldSend, setShouldSend] = useState(false);\n  const iframeRef = useRef(null);\n  const [validationResult, setValidationResult] = useState<ValidationResult>();\n  const [validating, setValidating] = useState(false);\n\n  useEffect(() => {\n    if (!url) {\n      return;\n    }\n    if (shouldSend && iframeRef.current) {\n      sendCommand(iframeRef.current, { command: 'loadCcdaXml', value: url }).catch(console.error);\n      setShouldSend(false);\n    }\n  }, [url, shouldSend]);\n\n  const validateCcda = async (): Promise<void> => {\n    if (!url) {\n      return;\n    }\n\n    try {\n      setValidating(true);\n\n      // Download the CCDA from the URL using plain fetch to avoid CORS issues\n      const response = await fetch(url);\n      const ccdaContent = await response.text();\n\n      // Prepare form data for submission\n      const formData = new FormData();\n      formData.append('ccdaFile', new Blob([ccdaContent], { type: 'text/xml' }), 'ccda.xml');\n\n      // Submit to validation API using direct fetch to avoid CORS issues\n      const validationUrl = `${BASE_VALIDATION_URL}referenceccdaservice/?validationObjective=C-CDA_IG_Plus_Vocab&referenceFileName=No%20scenario%20File&curesUpdate=true&severityLevel=WARNING`;\n      const validationResponse = await fetch(validationUrl, {\n        method: 'POST',\n        body: formData,\n        // Don't send credentials for cross-origin requests\n        credentials: 'omit',\n        // Don't follow redirects automatically\n        redirect: 'manual',\n      });\n\n      if (!validationResponse.ok) {\n        throw new Error(`Validation failed: ${validationResponse.status} ${validationResponse.statusText}`);\n      }\n\n      // Parse the JSON response\n      const validationResult = await validationResponse.json();\n      setValidationResult(validationResult as ValidationResult);\n    } catch (error) {\n      setValidationResult(undefined);\n      console.error('CCDA validation error:', error);\n    } finally {\n      setValidating(false);\n    }\n  };\n\n  const downloadResults = (): void => {\n    if (!validationResult) {\n      return;\n    }\n\n    const resultsJson = JSON.stringify(validationResult, null, 2);\n    exportJsonFile(resultsJson, 'ccda-validation-results');\n  };\n\n  const getErrorCount = (): number => {\n    if (!validationResult) {\n      return 0;\n    }\n    return validationResult.resultsMetaData.resultMetaData\n      .filter((item) => item?.type.includes('Error'))\n      .reduce((sum, item) => sum + (item.count || 0), 0);\n  };\n\n  if (!url) {\n    return null;\n  }\n\n  return (\n    <div data-testid=\"ccda-iframe\" style={{ maxWidth: props.maxWidth }}>\n      <div style={{ minHeight: 400 }}>\n        <iframe\n          title=\"C-CDA Viewer\"\n          width=\"100%\"\n          height=\"400\"\n          ref={iframeRef}\n          src={CCDA_VIEWER_URL}\n          allowFullScreen={true}\n          frameBorder={0}\n          seamless={true}\n          onLoad={() => setShouldSend(true)}\n        />\n      </div>\n\n      <div style={{ marginTop: '10px', marginBottom: '10px', display: 'flex', alignItems: 'center' }}>\n        <Button type=\"button\" onClick={validateCcda} disabled={validating}>\n          {validating ? 'Validating...' : 'Validate'}\n        </Button>\n\n        {validationResult && (\n          <>\n            <div style={{ marginLeft: '15px' }}>\n              <strong>Validation Results:</strong> {getErrorCount()} errors found\n            </div>\n\n            <Button\n              type=\"button\"\n              onClick={downloadResults}\n              color=\"green\"\n              style={{\n                marginLeft: 'auto',\n              }}\n            >\n              Download Full Results\n            </Button>\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Loader } from '@mantine/core';\nimport type { DetailedHTMLProps, ImgHTMLAttributes, JSX } from 'react';\nimport { useEffect, useRef, useState } from 'react';\n\nexport interface ScannedImageProps extends DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement> {\n  readonly maxRetries?: number;\n}\n\nexport function ScannedImage(props: ScannedImageProps): JSX.Element {\n  const { maxRetries = 5, ...rest } = props;\n  const [attempt, setAttempt] = useState(0);\n  const [status, setStatus] = useState<'fetching' | 'backoff' | 'loaded' | 'failed'>('fetching');\n  const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n\n  useEffect(() => {\n    return () => {\n      if (timeoutRef.current !== undefined) {\n        clearTimeout(timeoutRef.current);\n      }\n    };\n  }, []);\n\n  const handleError = (): void => {\n    if (attempt >= maxRetries) {\n      setStatus('failed');\n      return;\n    }\n\n    setStatus('backoff');\n\n    // Exponential backoff: 1s, 2s, 4s, 8s, 16s\n    const delay = Math.min(1000 * 2 ** attempt, 16000);\n    timeoutRef.current = setTimeout(() => {\n      setAttempt((a) => a + 1);\n      setStatus('fetching');\n      timeoutRef.current = undefined;\n    }, delay);\n  };\n\n  if (status === 'failed') {\n    return <div className=\"image-placeholder\">Image unavailable</div>;\n  }\n\n  if (status === 'backoff') {\n    return <Loader />;\n  }\n\n  return <img onLoad={() => setStatus('loaded')} onError={handleError} {...rest} />;\n}\n", ".root {\n  display: grid;\n  grid-template-columns: 30% 70%;\n  margin: 0;\n\n  & > dt,\n  & > dd {\n    padding: var(--mantine-spacing-xs);\n    border-top: 0.1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));\n    margin: 0;\n  }\n\n  & > dt:first-of-type,\n  & > dd:first-of-type {\n    border-top: 0;\n  }\n}\n\n.compact {\n  grid-template-columns: auto 1fr;\n\n  & > dt,\n  & > dd {\n    border: 0;\n    padding: 0;\n  }\n\n  & > dt {\n    padding-right: var(--mantine-spacing-xs);\n  }\n\n  & > dd {\n    padding-left: var(--mantine-spacing-xs);\n  }\n\n  & > dt:last-of-type,\n  & > dd:last-of-type {\n    padding-bottom: var(--mantine-spacing-xs);\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport classes from './DescriptionList.module.css';\n\nexport interface DescriptionListProps {\n  readonly children: ReactNode;\n  readonly compact?: boolean;\n}\n\nexport function DescriptionList(props: DescriptionListProps): JSX.Element {\n  const { children, compact } = props;\n  return <dl className={cx(classes.root, { [classes.compact]: compact })}>{children}</dl>;\n}\n\nexport interface DescriptionListEntryProps {\n  readonly term: string;\n  readonly children: ReactNode;\n}\n\nexport function DescriptionListEntry(props: DescriptionListEntryProps): JSX.Element {\n  return (\n    <>\n      <dt>{props.term}</dt>\n      <dd>{props.children}</dd>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon } from '@mantine/core';\nimport type { Attachment } from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCloudUpload } from '@tabler/icons-react';\nimport type { JSX, MouseEvent } from 'react';\nimport { useState } from 'react';\nimport { AttachmentButton } from '../AttachmentButton/AttachmentButton';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { killEvent } from '../utils/dom';\n\nexport interface AttachmentArrayInputProps {\n  readonly name: string;\n  readonly defaultValue?: Attachment[];\n  readonly arrayElement?: boolean;\n  readonly onChange?: (value: Attachment[]) => void;\n  readonly disabled?: boolean;\n}\n\nexport function AttachmentArrayInput(props: AttachmentArrayInputProps): JSX.Element {\n  const [values, setValues] = useState(props.defaultValue ?? []);\n\n  function setValuesWrapper(newValues: Attachment[]): void {\n    setValues(newValues);\n    if (props.onChange) {\n      props.onChange(newValues);\n    }\n  }\n\n  return (\n    <table style={{ width: '100%' }}>\n      <colgroup>\n        <col width=\"97%\" />\n        <col width=\"3%\" />\n      </colgroup>\n      <tbody>\n        {values.map((v: Attachment, index: number) => (\n          <tr key={`${index}-${values.length}`}>\n            <td>\n              <AttachmentDisplay value={v} maxWidth={200} />\n            </td>\n            <td>\n              <ActionIcon\n                disabled={props.disabled}\n                title=\"Remove\"\n                variant=\"subtle\"\n                size=\"sm\"\n                color=\"gray\"\n                onClick={(e: MouseEvent) => {\n                  killEvent(e);\n                  const copy = values.slice();\n                  copy.splice(index, 1);\n                  setValuesWrapper(copy);\n                }}\n              >\n                <IconCircleMinus />\n              </ActionIcon>\n            </td>\n          </tr>\n        ))}\n        <tr>\n          <td></td>\n          <td>\n            <AttachmentButton\n              disabled={props.disabled}\n              onUpload={(attachment: Attachment) => {\n                setValuesWrapper([...values, attachment]);\n              }}\n            >\n              {(props) => (\n                <ActionIcon {...props} title=\"Add\" variant=\"subtle\" size=\"sm\" color={props.disabled ? 'gray' : 'green'}>\n                  <IconCloudUpload />\n                </ActionIcon>\n              )}\n            </AttachmentButton>\n          </td>\n        </tr>\n      </tbody>\n    </table>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { Attachment, OperationOutcome, Reference } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { ChangeEvent, JSX, MouseEvent, ReactNode } from 'react';\nimport { useRef } from 'react';\nimport { killEvent } from '../utils/dom';\n\nexport interface AttachmentButtonProps {\n  readonly securityContext?: Reference;\n  readonly onUpload: (attachment: Attachment) => void;\n  readonly onUploadStart?: () => void;\n  readonly onUploadProgress?: (e: ProgressEvent) => void;\n  readonly onUploadError?: (outcome: OperationOutcome) => void;\n  children(props: { disabled?: boolean; onClick(e: MouseEvent): void }): ReactNode;\n  readonly disabled?: boolean;\n}\n\nexport function AttachmentButton(props: AttachmentButtonProps): JSX.Element {\n  const medplum = useMedplum();\n  const fileInputRef = useRef<HTMLInputElement>(null);\n\n  function onClick(e: MouseEvent): void {\n    killEvent(e);\n    fileInputRef.current?.click();\n  }\n\n  function onFileChange(e: ChangeEvent): void {\n    killEvent(e);\n    const files = (e.target as HTMLInputElement).files;\n    if (files) {\n      Array.from(files).forEach(processFile);\n    }\n  }\n\n  /**\n   * Processes a single file.\n   * @param file - The file descriptor.\n   */\n  function processFile(file: File): void {\n    if (!file) {\n      return;\n    }\n\n    const fileName = file.name;\n    if (!fileName) {\n      return;\n    }\n\n    if (props.onUploadStart) {\n      props.onUploadStart();\n    }\n\n    medplum\n      .createAttachment({\n        data: file,\n        contentType: file.type || 'application/octet-stream',\n        filename: file.name,\n        securityContext: props.securityContext,\n        onProgress: props.onUploadProgress,\n      })\n      .then((attachment: Attachment) => props.onUpload(attachment))\n      .catch((err) => {\n        if (props.onUploadError) {\n          props.onUploadError(normalizeOperationOutcome(err));\n        }\n      });\n  }\n\n  return (\n    <>\n      <input\n        disabled={props.disabled}\n        type=\"file\"\n        data-testid=\"upload-file-input\"\n        style={{ display: 'none' }}\n        ref={fileInputRef}\n        onChange={(e) => onFileChange(e)}\n      />\n      {/* eslint-disable-next-line react-hooks/refs */}\n      {props.children({ onClick, disabled: props.disabled })}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button } from '@mantine/core';\nimport type { Attachment, Reference } from '@medplum/fhirtypes';\nimport type { JSX, MouseEvent } from 'react';\nimport { useState } from 'react';\nimport { AttachmentButton } from '../AttachmentButton/AttachmentButton';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { killEvent } from '../utils/dom';\n\nexport interface AttachmentInputProps extends ComplexTypeInputProps<Attachment> {\n  readonly arrayElement?: boolean;\n  readonly securityContext?: Reference;\n  readonly onChange?: (value: Attachment | undefined) => void;\n}\n\nexport function AttachmentInput(props: AttachmentInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n\n  function setValueWrapper(newValue: Attachment | undefined): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  if (value) {\n    return (\n      <>\n        <AttachmentDisplay value={value} maxWidth={200} />\n        <Button\n          disabled={props.disabled}\n          onClick={(e: MouseEvent) => {\n            killEvent(e);\n            setValueWrapper(undefined);\n          }}\n        >\n          Remove\n        </Button>\n      </>\n    );\n  }\n\n  return (\n    <AttachmentButton disabled={props.disabled} securityContext={props.securityContext} onUpload={setValueWrapper}>\n      {(props) => <Button {...props}>Upload...</Button>}\n    </AttachmentButton>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Flex, Group, Stack, Title } from '@mantine/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\nimport { PasswordInput } from '../PasswordInput/PasswordInput';\nimport { getErrorsForInput } from '../utils/outcomes';\n\nexport interface ChangePasswordFormProps {\n  readonly onSuccess?: () => void;\n}\n\nexport function ChangePasswordForm(props: ChangePasswordFormProps): JSX.Element {\n  const { onSuccess } = props;\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const [success, setSuccess] = useState(false);\n\n  return (\n    <Document width={450}>\n      <Form\n        onSubmit={(formData: Record<string, string>) => {\n          setOutcome(undefined);\n          medplum\n            .post('auth/changepassword', formData)\n            .then(() => {\n              setSuccess(true);\n              onSuccess?.();\n            })\n            .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n        }}\n      >\n        <Flex direction=\"column\" align=\"center\" justify=\"center\">\n          <Logo size={32} />\n          <Title>Change password</Title>\n        </Flex>\n        {!success && (\n          <Stack gap=\"xl\" mt=\"xl\">\n            <PasswordInput\n              name=\"oldPassword\"\n              label=\"Old password\"\n              required={true}\n              autoFocus={true}\n              error={getErrorsForInput(outcome, 'oldPassword')}\n            />\n            <PasswordInput\n              name=\"newPassword\"\n              label=\"New password\"\n              required={true}\n              error={getErrorsForInput(outcome, 'newPassword')}\n            />\n            <PasswordInput\n              name=\"confirmPassword\"\n              label=\"Confirm new password\"\n              required={true}\n              error={getErrorsForInput(outcome, 'confirmPassword')}\n            />\n            <Group justify=\"flex-end\" mt=\"xl\" wrap=\"nowrap\">\n              <Button type=\"submit\">Change password</Button>\n            </Group>\n          </Stack>\n        )}\n        {success && <div data-testid=\"success\">Password changed successfully</div>}\n      </Form>\n    </Document>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ContainerProps } from '@mantine/core';\nimport { Container as MantineContainer } from '@mantine/core';\nimport type { JSX } from 'react';\nimport classes from './Container.module.css';\n\nexport function Container(props: ContainerProps): JSX.Element {\n  const { children, ...others } = props;\n\n  return (\n    <MantineContainer className={classes.root} {...others}>\n      {children}\n    </MantineContainer>\n  );\n}\n", ".root {\n  @media (max-width: 800px) {\n    padding-left: 4px;\n    padding-right: 4px;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { PaperProps } from '@mantine/core';\nimport { Paper } from '@mantine/core';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport classes from './Panel.module.css';\n\nexport interface PanelProps extends PaperProps {\n  readonly width?: number;\n  readonly fill?: boolean;\n  readonly children?: ReactNode;\n}\n\nexport function Panel(props: PanelProps): JSX.Element {\n  const { width, fill, className, children, ...rest } = props;\n  const style = width ? { maxWidth: width } : undefined;\n  return (\n    <Paper\n      className={cx(classes.paper, fill && classes.fill, className)}\n      style={style}\n      shadow=\"sm\"\n      radius=\"sm\"\n      withBorder\n      {...rest}\n    >\n      {children}\n    </Paper>\n  );\n}\n", ".paper {\n  margin: var(--mantine-spacing-xl) auto;\n  padding: var(--mantine-spacing-md);\n\n  @media (max-width: 800px) {\n    padding: 8px;\n  }\n\n  & img {\n    width: 100%;\n    max-width: 100%;\n  }\n\n  & video {\n    width: 100%;\n    max-width: 100%;\n  }\n}\n\n.fill {\n  padding: 0;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { JSX } from 'react';\nimport { Container } from '../Container/Container';\nimport type { PanelProps } from '../Panel/Panel';\nimport { Panel } from '../Panel/Panel';\n\nexport function Document(props: PanelProps): JSX.Element {\n  const { children, ...others } = props;\n  return (\n    <Container>\n      <Panel {...others}>{children}</Panel>\n    </Container>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { JSX } from 'react';\n\nexport interface LogoProps {\n  readonly size: number;\n  readonly fill?: string;\n}\n\nexport function Logo(props: LogoProps): JSX.Element {\n  const overrideUrl = import.meta.env.MEDPLUM_LOGO_URL;\n  if (overrideUrl) {\n    return <img src={overrideUrl} alt=\"Logo\" style={{ maxHeight: props.size }} />;\n  }\n  return (\n    <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 180 180\" style={{ width: props.size, height: props.size }}>\n      <title>Medplum Logo</title>\n      <path\n        fill={props.fill ?? '#9c36b5'}\n        d=\"M84 56c-3-15-15-24-23-28l5-10c8 2 14 8 20 14 0-12 1-16 5-21 8-9 13-9 41-9 0 7 1 18-3 24-7 9-16 7-41 8 5 8 7 14 8 22 36-24 74-7 74 39 0 42-40 83-80 83s-80-41-80-83c0-46 38-63 74-39Zm-3 43H65c-4 0-7 3-7 7v4c0 4 3 7 7 7h16v16c0 4 3 7 7 7h4c4 0 7-3 7-7v-16h16c4 0 7-3 7-7v-4c0-4-3-7-7-7H99V83c0-4-3-7-7-7h-4c-4 0-7 3-7 7z\"\n      />\n    </svg>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { PasswordInputProps } from '@mantine/core';\nimport { PasswordInput as MantinePasswordInput } from '@mantine/core';\nimport type { JSX } from 'react';\n\n/**\n * Mantine's `PasswordInput` sets `tabIndex={-1}` and `aria-hidden` on the visibility toggle button\n * unless `visibilityToggleButtonProps` is provided, which removes it from the keyboard tab order and\n * hides it from assistive technology. This wrapper defaults the toggle to be keyboard accessible.\n * @param props - The password input props.\n * @returns The password input component.\n */\nexport function PasswordInput(props: PasswordInputProps): JSX.Element {\n  const { visibilityToggleButtonProps, ...rest } = props;\n  return (\n    <MantinePasswordInput\n      {...rest}\n      visibilityToggleButtonProps={{\n        'aria-label': 'Toggle password visibility',\n        tabIndex: 0,\n        ...visibilityToggleButtonProps,\n      }}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { OperationOutcome, OperationOutcomeIssue } from '@medplum/fhirtypes';\n\nexport function getErrorsForInput(\n  outcome: OperationOutcome | undefined,\n  expression: string | undefined\n): string | undefined {\n  return outcome?.issue\n    ?.filter((issue) => isExpressionMatch(issue.expression?.[0], expression))\n    ?.map((issue) => issue.details?.text)\n    ?.join('\\n');\n}\n\nexport function getIssuesForExpression(\n  outcome: OperationOutcome | undefined,\n  expression: string | undefined\n): OperationOutcomeIssue[] | undefined {\n  return outcome?.issue?.filter((issue) => isExpressionMatch(issue.expression?.[0], expression));\n}\n\nconst ARRAY_INDEX_REGEX = /\\[\\d+\\]/;\nfunction isExpressionMatch(expr1: string | undefined, expr2: string | undefined): boolean {\n  // to make this behavior backwards compatible, if only one expression specifies array indexes, ignore all indexes\n  const isExpr1Indexed = typeof expr1 === 'string' && ARRAY_INDEX_REGEX.test(expr1);\n  const isExpr2Indexed = typeof expr2 === 'string' && ARRAY_INDEX_REGEX.test(expr2);\n  if (isExpr1Indexed !== isExpr2Indexed) {\n    expr1 = expr1?.replace(ARRAY_INDEX_REGEX, '');\n    expr2 = expr2?.replace(ARRAY_INDEX_REGEX, '');\n  }\n\n  // Expression can be either \"fieldName\" or \"resourceType.fieldName\"\n  if (expr1 === expr2) {\n    return true;\n  }\n  if (!expr1 || !expr2) {\n    return false;\n  }\n  const dot1 = expr1.indexOf('.');\n  if (dot1 >= 0 && expr1.substring(dot1 + 1) === expr2) {\n    return true;\n  }\n  const dot2 = expr2.indexOf('.');\n  if (dot2 >= 0 && expr2.substring(dot2 + 1) === expr1) {\n    return true;\n  }\n  return false;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Checkbox, Flex, Group, Stack, Title } from '@mantine/core';\nimport type { LoginAuthenticationResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { Fragment } from 'react/jsx-runtime';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Logo } from '../Logo/Logo';\n\nexport interface ChooseScopeFormProps {\n  readonly login: string;\n  readonly scope: string | undefined;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n  readonly title?: string;\n  readonly submitLabel?: string;\n  readonly logo?: ReactNode;\n  readonly children?: ReactNode;\n}\n\nconst openConditionScope = /^patient\\/Condition\\.(?:\\*|c?r?u?d?s?)$/;\nconst encounterDiagnosis = '?category=http://terminology.hl7.org/CodeSystem/condition-category|encounter-diagnosis';\nconst problemListItem = '?category=http://terminology.hl7.org/CodeSystem/condition-category|problem-list-item';\nconst healthConcern = '?category=http://hl7.org/fhir/us/core/CodeSystem/condition-category|health-concern';\n\nconst openObservationScope = /^patient\\/Observation\\.(?:\\*|c?r?u?d?s?)$/;\nconst clinicalTest = '?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-observation-category|clinical-test';\nconst laboratory = '?category=http://terminology.hl7.org/CodeSystem/observation-category|laboratory';\nconst socialHistory = '?category=http://terminology.hl7.org/CodeSystem/observation-category|social-history';\nconst sdoh = '?category=http://hl7.org/fhir/us/core/CodeSystem/us-core-category|sdoh';\nconst survey = '?category=http://terminology.hl7.org/CodeSystem/observation-category|survey';\nconst vitalSigns = '?category=http://terminology.hl7.org/CodeSystem/observation-category|vital-signs';\n\nexport function ChooseScopeForm(props: ChooseScopeFormProps): JSX.Element {\n  const medplum = useMedplum();\n  return (\n    <Form\n      onSubmit={(formData: Record<string, string>) => {\n        medplum\n          .post<LoginAuthenticationResponse>('auth/scope', {\n            login: props.login,\n            scope: Object.keys(formData).join(' '),\n          })\n          .then(props.handleAuthResponse)\n          .catch(console.log);\n      }}\n    >\n      <Stack>\n        <Flex direction=\"column\" align=\"center\" justify=\"center\">\n          {props.logo ?? <Logo size={32} />}\n          <Title order={3} py=\"lg\">\n            {props.title ?? 'Choose scope'}\n          </Title>\n          {props.children}\n        </Flex>\n        <Stack>\n          {(props.scope ?? 'openid').split(' ').map((scopeName: string) => {\n            let additionalScopes: string[] | undefined;\n            if (openConditionScope.test(scopeName)) {\n              additionalScopes = [\n                scopeName + encounterDiagnosis,\n                scopeName + problemListItem,\n                scopeName + healthConcern,\n              ];\n            } else if (openObservationScope.test(scopeName)) {\n              additionalScopes = [\n                scopeName + clinicalTest,\n                scopeName + laboratory,\n                scopeName + socialHistory,\n                scopeName + sdoh,\n                scopeName + survey,\n                scopeName + vitalSigns,\n              ];\n            }\n            return (\n              <Fragment key={scopeName + '_group'}>\n                <Checkbox key={scopeName} id={scopeName} name={scopeName} label={scopeName} defaultChecked />\n                {additionalScopes?.map((scope) => (\n                  <Checkbox key={scope} id={scope} name={scope} label={scope} />\n                ))}\n              </Fragment>\n            );\n          })}\n        </Stack>\n        <Group justify=\"flex-end\" mt=\"xl\">\n          <SubmitButton fullWidth>{props.submitLabel ?? 'Set Scope'}</SubmitButton>\n        </Group>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Center, Stack, Text, Title } from '@mantine/core';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport { Logo } from '../Logo/Logo';\nimport type { MfaMethod } from './MfaForm';\nimport { MfaForm } from './MfaForm';\n\nexport interface MfaEnrollFormProps {\n  /** The MFA methods the user is allowed to enroll in. */\n  readonly allowedMethods: MfaMethod[];\n  /** The TOTP QR code data URL, shown when enrolling an authenticator app. */\n  readonly qrCodeUrl?: string;\n  /** Enroll the email factor (the server emails a code on subsequent sign-ins). */\n  readonly onEnrollEmail: () => void;\n  /** Enroll the TOTP factor with the code from the user's authenticator app. */\n  readonly onEnrollTotp: (token: string) => void | Promise<void>;\n  /** Title for the authenticator (TOTP) QR enrollment step. */\n  readonly totpTitle: string;\n  /** Optional description shown alongside the TOTP QR code. */\n  readonly totpDescription?: ReactNode;\n  /** Submit button label for the TOTP step. */\n  readonly totpButtonText?: string;\n}\n\n/**\n * Shared MFA enrollment UI used during sign-in and on the MFA settings page.\n * When the user is allowed to enroll in more than one method it leads with a\n * chooser; an email-only project shows a single \"enable\" prompt; otherwise it\n * shows the authenticator (TOTP) QR code. The chooser and email-only screens\n * are identical across contexts, while the TOTP step's wording is supplied by\n * the caller.\n * @param props - The MfaEnrollForm React props.\n * @returns The MfaEnrollForm React node.\n */\nexport function MfaEnrollForm(props: MfaEnrollFormProps): JSX.Element {\n  const { allowedMethods, qrCodeUrl, onEnrollEmail, onEnrollTotp } = props;\n  const [selected, setSelected] = useState<MfaMethod>();\n\n  const emailAllowed = allowedMethods.includes('email');\n  const totpAllowed = allowedMethods.includes('totp');\n\n  // When both methods are offered, let the user choose first.\n  if (emailAllowed && totpAllowed && !selected) {\n    return (\n      <Center style={{ flexDirection: 'column' }}>\n        <Logo size={32} />\n        <Title order={3} py=\"lg\" ta=\"center\">\n          Set up multi-factor authentication\n        </Title>\n        <Stack w=\"100%\">\n          <Text c=\"dimmed\" ta=\"center\">\n            Choose how you want to verify your identity when you sign in.\n          </Text>\n          <Button fullWidth onClick={() => setSelected('totp')}>\n            Use an authenticator app (recommended)\n          </Button>\n          <Button fullWidth variant=\"default\" onClick={onEnrollEmail}>\n            Continue with email-based MFA\n          </Button>\n        </Stack>\n      </Center>\n    );\n  }\n\n  // Email-only project setting.\n  if (emailAllowed && !totpAllowed) {\n    return (\n      <Center style={{ flexDirection: 'column' }}>\n        <Logo size={32} />\n        <Title order={3} py=\"lg\">\n          Set up email-based MFA\n        </Title>\n        <Stack w=\"100%\">\n          <Text c=\"dimmed\" ta=\"center\">\n            When you sign in, we&apos;ll email you a verification code to confirm your identity.\n          </Text>\n          <Button fullWidth onClick={onEnrollEmail}>\n            Enable email-based MFA\n          </Button>\n        </Stack>\n      </Center>\n    );\n  }\n\n  // Default: authenticator (TOTP) enrollment via QR code.\n  return (\n    <MfaForm\n      title={props.totpTitle}\n      description={props.totpDescription}\n      buttonText={props.totpButtonText ?? 'Enroll'}\n      qrCodeUrl={qrCodeUrl}\n      onSubmit={(fields) => onEnrollTotp(fields.token)}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Alert, Center, Image, Stack, Text, TextInput, Title } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Logo } from '../Logo/Logo';\nexport type MfaFormFields = 'token';\n\n/** An MFA factor a user can enroll in or verify with. */\nexport type MfaMethod = 'totp' | 'email';\n\nexport interface MfaFormProps {\n  readonly title: string;\n  readonly buttonText: string;\n  readonly description?: ReactNode;\n  readonly qrCodeUrl?: string;\n  readonly onSubmit: (formData: Record<MfaFormFields, string>) => void | Promise<void>;\n  /** Optional content rendered below the submit button (e.g. an alternate MFA method action). */\n  readonly footer?: ReactNode;\n}\n\nexport function MfaForm(props: MfaFormProps): JSX.Element {\n  const [errorMessage, setErrorMessage] = useState<string>();\n  return (\n    <Form\n      onSubmit={(formData: Record<MfaFormFields, string>) => {\n        setErrorMessage(undefined);\n        props.onSubmit(formData)?.catch((err) => setErrorMessage(normalizeErrorString(err)));\n      }}\n    >\n      <Center style={{ flexDirection: 'column' }}>\n        <Logo size={32} />\n        <Title order={3} py=\"lg\">\n          {props.title}\n        </Title>\n        {!props.qrCodeUrl && props.description && (\n          <Text c=\"dimmed\" mb=\"lg\" mt=\"-lg\" ta=\"center\">\n            {props.description}\n          </Text>\n        )}\n      </Center>\n      {errorMessage && (\n        <Alert icon={<IconAlertCircle size={16} />} title=\"Error\" color=\"red\" mb=\"lg\">\n          {errorMessage}\n        </Alert>\n      )}\n      {props.qrCodeUrl && (\n        <Center>\n          <Stack mb=\"xl\" justify=\"center\">\n            {props.description && (\n              <Text c=\"dimmed\" mb=\"md\" mt=\"-lg\" ta=\"center\">\n                {props.description}\n              </Text>\n            )}\n            <Image\n              src={props.qrCodeUrl}\n              alt=\"Multi Factor Auth QR Code\"\n              w=\"60%\"\n              mx=\"auto\"\n              radius=\"md\"\n              p=\"xs\"\n              bg=\"var(--mantine-color-white)\"\n              style={{ border: '1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4))' }}\n            />\n          </Stack>\n        </Center>\n      )}\n      <Stack gap=\"sm\">\n        <TextInput name=\"token\" label=\"MFA code\" autoComplete=\"one-time-code\" required autoFocus />\n      </Stack>\n      <Stack gap=\"xs\" pt=\"md\">\n        <SubmitButton fullWidth>{props.buttonText}</SubmitButton>\n        {props.footer}\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { normalizeErrorString } from '@medplum/core';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport type { MfaMethod } from './MfaForm';\nimport { MfaForm } from './MfaForm';\n\nexport interface MfaVerificationFormProps {\n  /** The MFA methods the user can verify with. */\n  readonly methods: MfaMethod[];\n  /** The user's email, shown when entering an emailed code. */\n  readonly email?: string;\n  /**\n   * Whether to start in email-code-entry mode. Use when email is the only\n   * method (and a code has already been sent), so the user goes straight to\n   * entering the code instead of an authenticator code.\n   */\n  readonly initialEmailMode?: boolean;\n  /** Sends (or resends) a verification code to the user's email. */\n  readonly onRequestEmailCode: () => void | Promise<void>;\n  /** Called with the entered token (an authenticator code or an emailed code). */\n  readonly onSubmit: (token: string) => void | Promise<void>;\n  /** Optional override for the submit button label. */\n  readonly buttonText?: string;\n}\n\n/**\n * Shared MFA verification UI used during sign-in and when changing MFA\n * settings. It leads with the authenticator code and, when email is also an\n * available method, offers a \"Get a code by email instead\" action. Once in\n * email mode it shows the emailed-code entry with a \"Resend code\" action.\n * @param props - The MfaVerificationForm React props.\n * @returns The MfaVerificationForm React node.\n */\nexport function MfaVerificationForm(props: MfaVerificationFormProps): JSX.Element {\n  const { methods, email, onRequestEmailCode, onSubmit } = props;\n  const [emailMode, setEmailMode] = useState(Boolean(props.initialEmailMode));\n\n  const requestEmailCode = (): void => {\n    Promise.resolve(onRequestEmailCode())\n      .then(() => setEmailMode(true))\n      .catch((err: unknown) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  };\n\n  let footer: ReactNode;\n  if (emailMode) {\n    footer = (\n      <Anchor component=\"button\" type=\"button\" size=\"sm\" ta=\"center\" onClick={requestEmailCode}>\n        Resend code\n      </Anchor>\n    );\n  } else if (methods.includes('email')) {\n    footer = (\n      <Anchor component=\"button\" type=\"button\" size=\"sm\" ta=\"center\" onClick={requestEmailCode}>\n        Get a code by email instead\n      </Anchor>\n    );\n  }\n\n  return (\n    <MfaForm\n      title={emailMode ? 'Enter verification code' : 'Enter MFA code'}\n      description={\n        emailMode ? (\n          <>\n            Enter the 6-digit code we emailed{email ? ' to ' : ''}\n            {email && <strong>{email}</strong>}\n          </>\n        ) : (\n          'Enter the code from your authenticator app.'\n        )\n      }\n      buttonText={props.buttonText ?? 'Submit code'}\n      onSubmit={(fields) => onSubmit(fields.token)}\n      footer={footer}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { LoginAuthenticationResponse } from '@medplum/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { getIssuesForExpression } from '../utils/outcomes';\nimport { NewProjectForm } from './NewProjectForm';\nimport { NewUserForm } from './NewUserForm';\n\nexport interface RegisterFormProps {\n  readonly type: 'patient' | 'project';\n  readonly login?: string;\n  readonly projectId?: string;\n  readonly clientId?: string;\n  readonly googleClientId?: string;\n  readonly recaptchaSiteKey?: string;\n  readonly children?: ReactNode;\n  readonly onSuccess: () => void;\n  readonly onSignIn?: () => void;\n}\n\nexport function RegisterForm(props: RegisterFormProps): JSX.Element {\n  const { type, projectId, clientId, googleClientId, recaptchaSiteKey, onSuccess, onSignIn } = props;\n  const medplum = useMedplum();\n  const [login, setLogin] = useState<string | undefined>(props.login);\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const [emailVerificationRequired, setEmailVerificationRequired] = useState<boolean>(false);\n\n  useEffect(() => {\n    if (type === 'patient' && login) {\n      medplum\n        .startNewPatient({ login, projectId: projectId as string })\n        .then((response) => medplum.processCode(response.code as string))\n        .then(() => onSuccess())\n        .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n    }\n  }, [medplum, type, projectId, login, onSuccess]);\n\n  function handleAuthResponse(response: LoginAuthenticationResponse): void {\n    if (response.code) {\n      medplum\n        .processCode(response.code)\n        .then(() => onSuccess())\n        .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n    }\n    if (response.login) {\n      setLogin(response.login);\n    }\n    if (response.emailVerificationRequired) {\n      setEmailVerificationRequired(true);\n    }\n  }\n\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  return (\n    <Document width={400} px=\"xl\" py=\"xl\" bdrs=\"md\">\n      <OperationOutcomeAlert issues={issues} mb=\"lg\" />\n      {!login && (\n        <NewUserForm\n          projectId={projectId as string}\n          clientId={clientId}\n          googleClientId={googleClientId}\n          recaptchaSiteKey={recaptchaSiteKey}\n          onSignIn={onSignIn}\n          handleAuthResponse={handleAuthResponse}\n        >\n          {props.children}\n        </NewUserForm>\n      )}\n      {emailVerificationRequired && (\n        <div>Please check your email for a verification link. Click the link to continue setting up your account.</div>\n      )}\n      {login && !emailVerificationRequired && type === 'project' && (\n        <NewProjectForm login={login} handleAuthResponse={handleAuthResponse} />\n      )}\n    </Document>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AlertProps } from '@mantine/core';\nimport { Alert } from '@mantine/core';\nimport { isOk, operationOutcomeIssueToString } from '@medplum/core';\nimport type { OperationOutcome, OperationOutcomeIssue } from '@medplum/fhirtypes';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport type { JSX } from 'react';\n\nexport interface OperationOutcomeAlertProps extends AlertProps {\n  readonly outcome?: OperationOutcome;\n  readonly issues?: OperationOutcomeIssue[];\n  readonly displayOkOutcomes?: boolean;\n}\n\nexport function OperationOutcomeAlert(props: OperationOutcomeAlertProps): JSX.Element | null {\n  const { outcome, issues: issuesProp, displayOkOutcomes, ...spacingProps } = props;\n\n  const issues = outcome?.issue || issuesProp;\n  if (!issues || issues.length === 0) {\n    return null;\n  }\n\n  if (outcome && isOk(outcome) && !displayOkOutcomes) {\n    return null;\n  }\n\n  return (\n    <Alert icon={<IconAlertCircle size={16} />} color=\"red\" {...spacingProps}>\n      {issues.map((issue) => (\n        <div data-testid=\"text-field-error\" key={issue.details?.text}>\n          {operationOutcomeIssueToString(issue)}\n        </div>\n      ))}\n    </Alert>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Flex, Stack, Text, TextInput, Title } from '@mantine/core';\nimport type { LoginAuthenticationResponse } from '@medplum/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { getErrorsForInput, getIssuesForExpression } from '../utils/outcomes';\n\nexport interface NewProjectFormProps {\n  readonly login: string;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n}\n\nexport function NewProjectForm(props: NewProjectFormProps): JSX.Element {\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome | undefined>();\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  return (\n    <Form\n      onSubmit={async (formData: Record<string, string>) => {\n        try {\n          props.handleAuthResponse(\n            await medplum.startNewProject({\n              login: props.login,\n              projectName: formData.projectName,\n            })\n          );\n        } catch (err) {\n          setOutcome(normalizeOperationOutcome(err));\n        }\n      }}\n    >\n      <Flex direction=\"column\" align=\"center\" justify=\"center\">\n        <Logo size={32} />\n        <Title order={3} py=\"lg\">\n          Create a new project\n        </Title>\n      </Flex>\n      <OperationOutcomeAlert issues={issues} mb=\"lg\" />\n      <Stack gap=\"sm\">\n        <TextInput\n          name=\"projectName\"\n          label=\"Project Name\"\n          placeholder=\"My Project\"\n          required={true}\n          autoFocus={true}\n          error={getErrorsForInput(outcome, 'projectName')}\n        />\n      </Stack>\n      <Stack gap=\"xs\" mt=\"md\">\n        <SubmitButton fullWidth>Create Project</SubmitButton>\n        <Text c=\"dimmed\" size=\"xs\" pt=\"lg\" ta=\"center\">\n          By clicking \"Create Project\" you agree to the Medplum{' '}\n          <Anchor href=\"https://www.medplum.com/privacy\">Privacy&nbsp;Policy</Anchor>\n          {' and '}\n          <Anchor href=\"https://www.medplum.com/terms\">Terms&nbsp;of&nbsp;Service</Anchor>.\n        </Text>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Box, Checkbox, Divider, Flex, Stack, Text, TextInput } from '@mantine/core';\nimport type { GoogleCredentialResponse, LoginAuthenticationResponse } from '@medplum/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { GoogleButton } from '../GoogleButton/GoogleButton';\nimport { getGoogleClientId } from '../GoogleButton/GoogleButton.utils';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { PasswordInput } from '../PasswordInput/PasswordInput';\nimport { getErrorsForInput, getIssuesForExpression } from '../utils/outcomes';\nimport { getRecaptcha, initRecaptcha } from '../utils/recaptcha';\n\nexport interface NewUserFormProps {\n  readonly projectId: string;\n  readonly clientId?: string;\n  readonly googleClientId?: string;\n  readonly recaptchaSiteKey?: string;\n  readonly children?: ReactNode;\n  readonly onSignIn?: () => void;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n}\n\nexport function NewUserForm(props: NewUserFormProps): JSX.Element {\n  const googleClientId = getGoogleClientId(props.googleClientId);\n  const recaptchaSiteKey = props.recaptchaSiteKey;\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  useEffect(() => {\n    if (recaptchaSiteKey) {\n      initRecaptcha(recaptchaSiteKey);\n    }\n  }, [recaptchaSiteKey]);\n\n  return (\n    <Form\n      onSubmit={async (formData: Record<string, string>) => {\n        setOutcome(undefined);\n        try {\n          let recaptchaToken = '';\n          if (recaptchaSiteKey) {\n            recaptchaToken = await getRecaptcha(recaptchaSiteKey);\n          }\n          props.handleAuthResponse(\n            await medplum.startNewUser({\n              projectId: props.projectId,\n              clientId: props.clientId,\n              firstName: formData.firstName,\n              lastName: formData.lastName,\n              email: formData.email,\n              password: formData.password,\n              remember: formData.remember === 'true',\n              recaptchaSiteKey,\n              recaptchaToken,\n            })\n          );\n        } catch (err) {\n          setOutcome(normalizeOperationOutcome(err));\n        }\n      }}\n    >\n      <Flex direction=\"column\" align=\"center\" justify=\"center\">\n        {props.children}\n      </Flex>\n      <OperationOutcomeAlert issues={issues} mb=\"lg\" />\n      {googleClientId && (\n        <>\n          <Box style={{ minHeight: 40 }}>\n            <GoogleButton\n              googleClientId={googleClientId}\n              handleGoogleCredential={async (response: GoogleCredentialResponse) => {\n                try {\n                  props.handleAuthResponse(\n                    await medplum.startGoogleLogin({\n                      googleClientId: response.clientId,\n                      googleCredential: response.credential,\n                      projectId: props.projectId,\n                      createUser: true,\n                    })\n                  );\n                } catch (err) {\n                  setOutcome(normalizeOperationOutcome(err));\n                }\n              }}\n            />\n          </Box>\n          <Divider label=\"or\" labelPosition=\"center\" my=\"lg\" />\n        </>\n      )}\n      <Stack gap=\"sm\">\n        <TextInput\n          name=\"firstName\"\n          type=\"text\"\n          label=\"First name\"\n          placeholder=\"First name\"\n          required={true}\n          autoFocus={true}\n          error={getErrorsForInput(outcome, 'firstName')}\n        />\n        <TextInput\n          name=\"lastName\"\n          type=\"text\"\n          label=\"Last name\"\n          placeholder=\"Last name\"\n          required={true}\n          error={getErrorsForInput(outcome, 'lastName')}\n        />\n        <TextInput\n          name=\"email\"\n          type=\"email\"\n          label=\"Email\"\n          placeholder=\"name@domain.com\"\n          required={true}\n          error={getErrorsForInput(outcome, 'email')}\n        />\n        <PasswordInput\n          name=\"password\"\n          label=\"Password\"\n          autoComplete=\"off\"\n          required={true}\n          error={getErrorsForInput(outcome, 'password')}\n        />\n      </Stack>\n      <Stack gap=\"xs\">\n        <Checkbox\n          id=\"remember\"\n          name=\"remember\"\n          label=\"Remember me\"\n          size=\"xs\"\n          style={{ lineHeight: 1 }}\n          pt=\"md\"\n          pb=\"xs\"\n        />\n        <SubmitButton fullWidth>Register Account</SubmitButton>\n        {props.onSignIn && (\n          <Text\n            size=\"sm\"\n            mt=\"lg\"\n            c=\"dimmed\"\n            ta=\"center\"\n            data-dashlane-ignore=\"true\"\n            data-lp-ignore=\"true\"\n            data-no-autofill=\"true\"\n            data-form-type=\"navigation\"\n          >\n            Already have an account?{' '}\n            <Anchor component=\"button\" type=\"button\" onClick={props.onSignIn}>\n              Sign In\n            </Anchor>\n          </Text>\n        )}\n        <Text c=\"dimmed\" size=\"xs\" pt=\"lg\" ta=\"center\">\n          By clicking \"Register Account\" you agree to the Medplum{' '}\n          <Anchor href=\"https://www.medplum.com/privacy\">Privacy&nbsp;Policy</Anchor>\n          {' and '}\n          <Anchor href=\"https://www.medplum.com/terms\">Terms&nbsp;of&nbsp;Service</Anchor>.\n        </Text>\n        <Text c=\"dimmed\" size=\"xs\" ta=\"center\">\n          This site is protected by reCAPTCHA and the Google{' '}\n          <Anchor href=\"https://policies.google.com/privacy\">Privacy&nbsp;Policy</Anchor>\n          {' and '}\n          <Anchor href=\"https://policies.google.com/terms\">Terms&nbsp;of&nbsp;Service</Anchor> apply.\n        </Text>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box } from '@mantine/core';\nimport type { GoogleCredentialResponse } from '@medplum/core';\nimport type { JSX } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport { createScriptTag } from '../utils/script';\n\ninterface GoogleApi {\n  readonly accounts: {\n    id: {\n      initialize: (args: any) => void;\n      renderButton: (parent: HTMLElement, args: any) => void;\n    };\n  };\n}\n\ndeclare const google: GoogleApi;\n\nexport interface GoogleButtonProps {\n  readonly googleClientId?: string;\n  readonly handleGoogleCredential: (response: GoogleCredentialResponse) => void;\n}\n\nexport function GoogleButton(props: GoogleButtonProps): JSX.Element | null {\n  const { googleClientId, handleGoogleCredential } = props;\n  const parentRef = useRef<HTMLDivElement>(null);\n  const [scriptLoaded, setScriptLoaded] = useState(typeof google !== 'undefined');\n  const initializedRef = useRef(false);\n  const buttonRenderedRef = useRef(false);\n\n  useEffect(() => {\n    if (typeof google === 'undefined') {\n      createScriptTag('https://accounts.google.com/gsi/client', () => setScriptLoaded(true));\n      return;\n    }\n\n    if (!initializedRef.current) {\n      google.accounts.id.initialize({\n        client_id: googleClientId,\n        callback: handleGoogleCredential,\n      });\n      initializedRef.current = true;\n    }\n\n    if (parentRef.current && !buttonRenderedRef.current) {\n      google.accounts.id.renderButton(parentRef.current, {\n        type: 'standard',\n        logo_alignment: 'center',\n        width: parentRef.current.clientWidth,\n      });\n      buttonRenderedRef.current = true;\n    }\n  }, [googleClientId, scriptLoaded, handleGoogleCredential]);\n\n  if (!googleClientId) {\n    return null;\n  }\n\n  return <Box ref={parentRef} w=\"100%\" h={40} display=\"flex\" style={{ justifyContent: 'center' }} />;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Dynamically creates a script tag for the specified JavaScript file.\n * @param src - The JavaScript file URL.\n * @param onload - Optional callback for the onload event.\n */\nexport function createScriptTag(src: string, onload?: () => void): void {\n  const head = document.getElementsByTagName('head')[0];\n  const script = document.createElement('script');\n  script.async = true;\n  script.src = src;\n  script.onload = onload ?? null;\n  head.appendChild(script);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { locationUtils } from '@medplum/core';\n\nexport function getGoogleClientId(clientId: string | undefined): string | undefined {\n  if (clientId) {\n    return clientId;\n  }\n\n  const origin = locationUtils.getOrigin();\n  if (origin) {\n    const authorizedOrigins = import.meta.env.GOOGLE_AUTH_ORIGINS?.split(',') ?? [];\n    if (authorizedOrigins.includes(origin)) {\n      return import.meta.env.GOOGLE_CLIENT_ID;\n    }\n  }\n\n  return undefined;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createScriptTag } from './script';\n\n// reCAPTCHA type definitions do not work with Vite project aliasing.\n// Project aliasing is more valuable than type definitions,\n// so cheating and using `any` here.\ndeclare let grecaptcha: any;\n\n/**\n * Dynamically loads the recaptcha script.\n * We do not want to load the script on page load unless the user needs it.\n * @param siteKey - The reCAPTCHA site key, available from the reCAPTCHA admin page.\n */\nexport function initRecaptcha(siteKey: string): void {\n  if (typeof grecaptcha === 'undefined') {\n    createScriptTag('https://www.google.com/recaptcha/api.js?render=' + siteKey);\n  }\n}\n\n/**\n * Starts a request to generate a recapcha token.\n * @param siteKey - The reCAPTCHA site key, available from the reCAPTCHA admin page.\n * @returns Promise to a recaptcha token for the current user.\n */\nexport function getRecaptcha(siteKey: string): Promise<string> {\n  return new Promise((resolve, reject) => {\n    grecaptcha.ready(async () => {\n      try {\n        resolve(await grecaptcha.execute(siteKey, { action: 'submit' }));\n      } catch (err) {\n        reject(err);\n      }\n    });\n  });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Flex, Stack, Text, TextInput, Title } from '@mantine/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { getErrorsForInput, getIssuesForExpression } from '../utils/outcomes';\nimport { getRecaptcha, initRecaptcha } from '../utils/recaptcha';\n\nexport interface ResetPasswordFormProps {\n  readonly projectId?: string;\n  readonly recaptchaSiteKey?: string;\n  readonly onSuccess?: () => void;\n  readonly onSignIn?: () => void;\n  readonly onRegister?: () => void;\n}\n\nexport function ResetPasswordForm(props: ResetPasswordFormProps): JSX.Element {\n  const { projectId, recaptchaSiteKey, onSuccess, onSignIn, onRegister } = props;\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const [success, setSuccess] = useState(false);\n\n  useEffect(() => {\n    if (recaptchaSiteKey) {\n      initRecaptcha(recaptchaSiteKey);\n    }\n  }, [recaptchaSiteKey]);\n\n  return (\n    <Document width={400} px=\"xl\" py=\"xl\" bdrs=\"md\">\n      <Form\n        onSubmit={async (formData: Record<string, string>) => {\n          setOutcome(undefined);\n          try {\n            let recaptchaToken = '';\n            if (recaptchaSiteKey) {\n              recaptchaToken = await getRecaptcha(recaptchaSiteKey);\n            }\n\n            await medplum.post('auth/resetpassword', {\n              ...formData,\n              projectId,\n              recaptchaToken,\n            });\n            setSuccess(true);\n            onSuccess?.();\n          } catch (err) {\n            setOutcome(normalizeOperationOutcome(err));\n          }\n        }}\n      >\n        <Flex direction=\"column\" align=\"center\" justify=\"center\">\n          <Logo size={32} />\n          <Title order={3} py=\"lg\">\n            Reset your password\n          </Title>\n        </Flex>\n        <OperationOutcomeAlert issues={getIssuesForExpression(outcome, undefined)} mb=\"lg\" />\n        {!success && (\n          <>\n            <Stack gap=\"sm\" mb=\"md\">\n              <TextInput\n                name=\"email\"\n                type=\"email\"\n                label=\"Email\"\n                placeholder=\"name@domain.com\"\n                required={true}\n                autoFocus={true}\n                error={getErrorsForInput(outcome, 'email')}\n              />\n            </Stack>\n            <Stack gap=\"xs\">\n              <SubmitButton fullWidth>Reset Password</SubmitButton>\n              {onSignIn && (\n                <Text\n                  size=\"sm\"\n                  mt=\"lg\"\n                  c=\"dimmed\"\n                  style={{ textAlign: 'center' }}\n                  data-dashlane-ignore=\"true\"\n                  data-lp-ignore=\"true\"\n                  data-no-autofill=\"true\"\n                  data-form-type=\"navigation\"\n                >\n                  <Anchor onClick={onSignIn}>Back to Sign In</Anchor>\n                </Text>\n              )}\n              {onRegister && (\n                <Text\n                  size=\"sm\"\n                  mt=\"none\"\n                  c=\"dimmed\"\n                  style={{ textAlign: 'center' }}\n                  data-dashlane-ignore=\"true\"\n                  data-lp-ignore=\"true\"\n                  data-no-autofill=\"true\"\n                  data-form-type=\"navigation\"\n                >\n                  Don't have an account? <Anchor onClick={onRegister}>Sign Up</Anchor>\n                </Text>\n              )}\n            </Stack>\n          </>\n        )}\n        {success && (\n          <Text c=\"dimmed\" size=\"sm\" ta=\"center\" mt=\"md\">\n            If the account exists on our system, a password reset email will be sent.\n          </Text>\n        )}\n      </Form>\n    </Document>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Button, Flex, Group, Stack, Title } from '@mantine/core';\nimport { badRequest, normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { PasswordInput } from '../PasswordInput/PasswordInput';\nimport { getErrorsForInput, getIssuesForExpression } from '../utils/outcomes';\n\nexport interface SetPasswordFormProps {\n  readonly id: string;\n  readonly secret: string;\n  readonly onSuccess?: () => void;\n  readonly onSignIn?: () => void;\n}\n\nexport function SetPasswordForm(props: SetPasswordFormProps): JSX.Element {\n  const { id, secret, onSuccess, onSignIn } = props;\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const [success, setSuccess] = useState(false);\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  return (\n    <Document width={450}>\n      <OperationOutcomeAlert issues={issues} />\n      <Form\n        onSubmit={(formData: Record<string, string>) => {\n          if (formData.password !== formData.confirmPassword) {\n            setOutcome(badRequest('Passwords do not match', 'confirmPassword'));\n            return;\n          }\n          setOutcome(undefined);\n          medplum\n            .post('auth/setpassword', { id, secret, password: formData.password })\n            .then(() => {\n              setSuccess(true);\n              onSuccess?.();\n            })\n            .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n        }}\n      >\n        <Flex direction=\"column\" align=\"center\" justify=\"center\">\n          <Logo size={32} />\n          <Title>Set password</Title>\n        </Flex>\n        {!success && (\n          <Stack>\n            <PasswordInput\n              name=\"password\"\n              label=\"New password\"\n              required={true}\n              error={getErrorsForInput(outcome, 'password')}\n            />\n            <PasswordInput\n              name=\"confirmPassword\"\n              label=\"Confirm new password\"\n              required={true}\n              error={getErrorsForInput(outcome, 'confirmPassword')}\n            />\n            <Group justify=\"flex-end\" mt=\"xl\">\n              <Button type=\"submit\">Set password</Button>\n            </Group>\n          </Stack>\n        )}\n        {success && (\n          <div data-testid=\"success\">\n            Password set. You can now&nbsp;\n            {onSignIn ? (\n              <Anchor component=\"button\" type=\"button\" onClick={onSignIn}>\n                sign in\n              </Anchor>\n            ) : (\n              'sign in'\n            )}\n            .\n          </div>\n        )}\n      </Form>\n    </Document>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { showNotification } from '@mantine/notifications';\nimport type { BaseLoginRequest, LoginAuthenticationResponse, MedplumClient } from '@medplum/core';\nimport { isUUID, normalizeErrorString, parseJWTPayload } from '@medplum/core';\nimport type { ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { AuthenticationForm } from './AuthenticationForm';\nimport { ChooseProfileForm } from './ChooseProfileForm';\nimport type { ChooseScopeFormProps } from './ChooseScopeForm';\nimport { ChooseScopeForm } from './ChooseScopeForm';\nimport { MfaEnrollForm } from './MfaEnrollForm';\nimport type { MfaMethod } from './MfaForm';\nimport { MfaVerificationForm } from './MfaVerificationForm';\nimport { NewProjectForm } from './NewProjectForm';\n\nexport interface SignInFormProps extends BaseLoginRequest {\n  readonly login?: string;\n  readonly chooseScopes?: boolean;\n  readonly disableEmailAuth?: boolean;\n  readonly disableGoogleAuth?: boolean;\n  readonly onSuccess?: () => void;\n  readonly onForgotPassword?: () => void;\n  readonly onRegister?: () => void;\n  readonly onCode?: (code: string) => void;\n  readonly children?: ReactNode;\n  readonly chooseScopeFormProps?: Omit<ChooseScopeFormProps, 'login' | 'scope' | 'handleAuthResponse'>;\n}\n\n/**\n * The SignInForm component allows users to sign in to Medplum.\n *\n * \"Signing in\" is a multi-step process:\n * 1) Authentication - identify the user\n * 2) MFA - If MFA is enabled, prompt for MFA code\n * 3) Choose profile - If the user has multiple profiles, prompt to choose one\n * 4) Choose scope - If the user has multiple scopes, prompt to choose one\n * 5) Success - Return to the caller with either a code or a redirect\n * @param props - The SignInForm React props.\n * @returns The SignInForm React node.\n */\nexport function SignInForm(props: SignInFormProps): JSX.Element {\n  const {\n    login: loginCode,\n    chooseScopes,\n    chooseScopeFormProps,\n    onSuccess,\n    onForgotPassword,\n    onRegister,\n    onCode,\n    ...baseLoginRequest\n  } = props;\n  const medplum = useMedplum();\n  const [login, setLogin] = useState<string>();\n  const loginRequested = useRef(false);\n  const [mfaEnrollRequired, setMfaEnrollRequired] = useState(false);\n  const [enrollQrCode, setEnrollQrCode] = useState<string>();\n  const [enrollMethods, setEnrollMethods] = useState<MfaMethod[]>();\n  const [mfaRequired, setMfaRequired] = useState(false);\n  const [mfaMethods, setMfaMethods] = useState<MfaMethod[]>();\n  const [mfaEmail, setMfaEmail] = useState<string>();\n  const [mfaEmailMode, setMfaEmailMode] = useState(false);\n  const [memberships, setMemberships] = useState<ProjectMembership[]>();\n\n  const handleCode = useCallback(\n    (code: string): void => {\n      if (onCode) {\n        onCode(code);\n      } else {\n        medplum\n          .processCode(code)\n          .then(() => {\n            if (onSuccess) {\n              onSuccess();\n            }\n          })\n          .catch((err: unknown) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n      }\n    },\n    [medplum, onCode, onSuccess]\n  );\n\n  const handleAuthResponse = useCallback(\n    (response: LoginAuthenticationResponse): void => {\n      setMfaEnrollRequired(!!response.mfaEnrollRequired);\n      setEnrollQrCode(response.enrollQrCode);\n      setEnrollMethods(response.allowedMfaMethods);\n      setMfaRequired(!!response.mfaRequired);\n\n      if (response.mfaRequired) {\n        const methods = response.mfaMethods;\n        setMfaMethods(methods);\n        setMfaEmail(response.email);\n        // When email is the only enrolled method, the server has already sent\n        // the verification code, so show the code entry form directly.\n        if (methods?.length === 1 && methods[0] === 'email') {\n          setMfaEmailMode(true);\n        }\n      } else {\n        setMfaMethods(undefined);\n        setMfaEmail(undefined);\n        setMfaEmailMode(false);\n      }\n\n      if (response.login) {\n        setLogin(response.login);\n      }\n\n      if (response.memberships) {\n        setMemberships(response.memberships);\n      }\n\n      if (response.code) {\n        if (chooseScopes) {\n          setMemberships(undefined);\n        } else {\n          handleCode(response.code);\n        }\n      }\n    },\n    [chooseScopes, handleCode]\n  );\n\n  const requestEmailCode = useCallback(async (): Promise<void> => {\n    if (!login) {\n      return;\n    }\n    await medplum.post('auth/mfa/send-email', { login });\n  }, [medplum, login]);\n\n  const enrollEmail = useCallback((): void => {\n    if (!login) {\n      return;\n    }\n    medplum\n      .post<LoginAuthenticationResponse>('auth/mfa/login-enroll', { login, method: 'email' })\n      .then(handleAuthResponse)\n      .catch((err: unknown) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [medplum, login, handleAuthResponse]);\n\n  const handleScopeResponse = useCallback(\n    (response: LoginAuthenticationResponse): void => {\n      handleCode(response.code as string);\n    },\n    [handleCode]\n  );\n\n  useEffect(() => {\n    // Beware the race condition here\n    // The `useMedplum` hook will return a new instance of the MedplumClient on login\n    // We do not want to request the login status again in that case\n    // Only request login status once\n    // Login IDs are UUIDs, and anything else would change the request path\n    // Hosts like the Medplum app swap in a loading screen while the new profile loads, which remounts\n    // this form with the same `loginCode`; by then that login is granted, and the server rejects it\n    if (loginCode && isUUID(loginCode) && !loginRequested.current && !login && !isSignedInWith(medplum, loginCode)) {\n      loginRequested.current = true;\n      medplum\n        .get('auth/login/' + encodeURIComponent(loginCode))\n        .then(handleAuthResponse)\n        .catch((err: unknown) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n    }\n  }, [medplum, loginCode, loginRequested, login, handleAuthResponse]);\n\n  return (\n    <Document width={400} px=\"xl\" py=\"xl\" bdrs=\"md\">\n      {(() => {\n        if (!login) {\n          return (\n            <AuthenticationForm\n              onForgotPassword={onForgotPassword}\n              onRegister={onRegister}\n              handleAuthResponse={handleAuthResponse}\n              disableGoogleAuth={props.disableGoogleAuth}\n              disableEmailAuth={props.disableEmailAuth}\n              {...baseLoginRequest}\n            >\n              {props.children}\n            </AuthenticationForm>\n          );\n        } else if (mfaEnrollRequired) {\n          return (\n            <MfaEnrollForm\n              allowedMethods={enrollMethods ?? ['totp']}\n              qrCodeUrl={enrollQrCode}\n              onEnrollEmail={enrollEmail}\n              totpTitle=\"Enroll in MFA\"\n              totpDescription=\"Scan this QR code with your authenticator app.\"\n              onEnrollTotp={async (token) => {\n                const res = await medplum.post<LoginAuthenticationResponse>('auth/mfa/login-enroll', {\n                  login: login,\n                  method: 'totp',\n                  token,\n                });\n                handleAuthResponse(res);\n              }}\n            />\n          );\n        } else if (mfaRequired) {\n          return (\n            <MfaVerificationForm\n              methods={mfaMethods ?? []}\n              email={mfaEmail}\n              initialEmailMode={mfaEmailMode}\n              onRequestEmailCode={requestEmailCode}\n              onSubmit={async (token) => {\n                const res = await medplum.post<LoginAuthenticationResponse>('auth/mfa/verify', {\n                  login: login,\n                  token,\n                });\n                handleAuthResponse(res);\n              }}\n            />\n          );\n        } else if (props.projectId === 'new') {\n          return <NewProjectForm login={login} handleAuthResponse={handleAuthResponse} />;\n        } else if (memberships) {\n          return <ChooseProfileForm login={login} memberships={memberships} handleAuthResponse={handleAuthResponse} />;\n        } else if (props.chooseScopes) {\n          return (\n            <ChooseScopeForm\n              login={login}\n              scope={props.scope}\n              handleAuthResponse={handleScopeResponse}\n              {...chooseScopeFormProps}\n            />\n          );\n        } else {\n          return <div>Success</div>;\n        }\n      })()}\n    </Document>\n  );\n}\n\nfunction isSignedInWith(medplum: MedplumClient, loginId: string): boolean {\n  const accessToken = medplum.getAccessToken();\n  if (!accessToken) {\n    return false;\n  }\n  try {\n    return parseJWTPayload(accessToken).login_id === loginId;\n  } catch (_err) {\n    return false;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Anchor, Box, Checkbox, Divider, Flex, Stack, Text, TextInput } from '@mantine/core';\nimport type {\n  BaseLoginRequest,\n  GoogleCredentialResponse,\n  GoogleLoginRequest,\n  LoginAuthenticationResponse,\n} from '@medplum/core';\nimport { locationUtils, normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconPencil } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { GoogleButton } from '../GoogleButton/GoogleButton';\nimport { getGoogleClientId } from '../GoogleButton/GoogleButton.utils';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { PasswordInput } from '../PasswordInput/PasswordInput';\nimport { getErrorsForInput, getIssuesForExpression } from '../utils/outcomes';\n\nexport interface AuthenticationFormProps extends BaseLoginRequest {\n  readonly disableEmailAuth?: boolean;\n  readonly disableGoogleAuth?: boolean;\n  readonly onForgotPassword?: () => void;\n  readonly onRegister?: () => void;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n  readonly children?: ReactNode;\n}\n\nexport function AuthenticationForm(props: AuthenticationFormProps): JSX.Element {\n  const [email, setEmail] = useState<string>();\n\n  if (!email) {\n    return <EmailForm setEmail={setEmail} {...props} />;\n  } else {\n    return <PasswordForm email={email} resetEmail={() => setEmail(undefined)} {...props} />;\n  }\n}\n\nexport interface EmailFormProps extends BaseLoginRequest {\n  readonly disableEmailAuth?: boolean;\n  readonly disableGoogleAuth?: boolean;\n  readonly onRegister?: () => void;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n  readonly setEmail: (email: string) => void;\n  readonly children?: ReactNode;\n}\n\nexport function EmailForm(props: EmailFormProps): JSX.Element {\n  const { setEmail, onRegister, handleAuthResponse, children, disableEmailAuth, ...baseLoginRequest } = props;\n  const medplum = useMedplum();\n  const googleClientId = !props.disableGoogleAuth && getGoogleClientId(props.googleClientId);\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  const isExternalAuth = useCallback(\n    async (authMethod: any): Promise<boolean> => {\n      if (!authMethod.authorizeUrl) {\n        return false;\n      }\n\n      const state = JSON.stringify({\n        ...(await medplum.ensureCodeChallenge(baseLoginRequest)),\n        domain: authMethod.domain,\n        returnTo: locationUtils.getLocation(),\n      });\n      const url = new URL(authMethod.authorizeUrl);\n      url.searchParams.set('state', state);\n      locationUtils.assign(url.toString());\n      return true;\n    },\n    [medplum, baseLoginRequest]\n  );\n\n  const handleSubmit = useCallback(\n    async (formData: Record<string, string>) => {\n      const authMethod = await medplum.post('auth/method', { email: formData.email });\n      if (!(await isExternalAuth(authMethod))) {\n        setEmail(formData.email);\n      }\n    },\n    [medplum, isExternalAuth, setEmail]\n  );\n\n  const handleGoogleCredential = useCallback(\n    async (response: GoogleCredentialResponse) => {\n      try {\n        const authResponse = await medplum.startGoogleLogin({\n          ...baseLoginRequest,\n          googleCredential: response.credential,\n        } as GoogleLoginRequest);\n        if (!(await isExternalAuth(authResponse))) {\n          handleAuthResponse(authResponse);\n        }\n      } catch (err) {\n        setOutcome(normalizeOperationOutcome(err));\n      }\n    },\n    [medplum, baseLoginRequest, isExternalAuth, handleAuthResponse]\n  );\n\n  return (\n    <Form onSubmit={handleSubmit}>\n      <Flex direction=\"column\" align=\"center\" justify=\"center\">\n        {children}\n      </Flex>\n      <OperationOutcomeAlert issues={issues} mb=\"lg\" />\n      {googleClientId && (\n        <>\n          <Box style={{ minHeight: 40 }}>\n            <GoogleButton googleClientId={googleClientId} handleGoogleCredential={handleGoogleCredential} />\n          </Box>\n          {!disableEmailAuth && <Divider label=\"or\" labelPosition=\"center\" my=\"lg\" />}\n        </>\n      )}\n      {!disableEmailAuth && (\n        <TextInput\n          name=\"email\"\n          type=\"email\"\n          label=\"Email\"\n          mb=\"md\"\n          placeholder=\"name@domain.com\"\n          required={true}\n          autoFocus={true}\n          error={getErrorsForInput(outcome, 'email')}\n          data-testid=\"auth.email\"\n        />\n      )}\n      <Stack gap=\"xs\">\n        {!disableEmailAuth && <SubmitButton fullWidth>Continue</SubmitButton>}\n        {onRegister && (\n          <Text\n            size=\"sm\"\n            mt=\"lg\"\n            c=\"dimmed\"\n            style={{ textAlign: 'center' }}\n            data-dashlane-ignore=\"true\"\n            data-lp-ignore=\"true\"\n            data-no-autofill=\"true\"\n            data-form-type=\"navigation\"\n          >\n            Don\u2019t have an account? <Anchor onClick={onRegister}>Register</Anchor>\n          </Text>\n        )}\n      </Stack>\n    </Form>\n  );\n}\n\nexport interface PasswordFormProps extends BaseLoginRequest {\n  readonly email: string;\n  readonly onForgotPassword?: () => void;\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n  readonly resetEmail: () => void;\n  readonly children?: ReactNode;\n}\n\nexport function PasswordForm(props: PasswordFormProps): JSX.Element {\n  const { onForgotPassword, handleAuthResponse, children, ...baseLoginRequest } = props;\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const issues = getIssuesForExpression(outcome, undefined);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) =>\n      medplum\n        .startLogin({\n          ...baseLoginRequest,\n          password: formData.password,\n          remember: formData.remember === 'on',\n        })\n        .then(handleAuthResponse)\n        .catch((err: unknown) => setOutcome(normalizeOperationOutcome(err))),\n    [medplum, baseLoginRequest, handleAuthResponse]\n  );\n\n  return (\n    <Form onSubmit={handleSubmit}>\n      <Flex direction=\"column\" align=\"center\" justify=\"center\">\n        {children}\n      </Flex>\n      <OperationOutcomeAlert issues={issues} mb=\"lg\" />\n      <Stack gap=\"sm\">\n        <TextInput\n          label=\"Email\"\n          value={props.email}\n          disabled\n          rightSectionWidth={36}\n          rightSection={\n            <ActionIcon variant=\"subtle\" color=\"gray\" onClick={props.resetEmail} aria-label=\"Change email\">\n              <IconPencil size=\"1rem\" stroke={1.5} />\n            </ActionIcon>\n          }\n        />\n        <PasswordInput\n          name=\"password\"\n          label=\"Password\"\n          autoComplete=\"off\"\n          required={true}\n          autoFocus={true}\n          error={getErrorsForInput(outcome, 'password')}\n          data-testid=\"auth.password\"\n        />\n      </Stack>\n      <Stack gap=\"xs\">\n        <Checkbox\n          id=\"remember\"\n          name=\"remember\"\n          label=\"Remember me\"\n          size=\"xs\"\n          style={{ lineHeight: 1 }}\n          pt=\"md\"\n          pb=\"xs\"\n        />\n        <SubmitButton>Sign In</SubmitButton>\n        {onForgotPassword && (\n          <Text\n            size=\"sm\"\n            mt=\"lg\"\n            c=\"dimmed\"\n            style={{ textAlign: 'center' }}\n            data-dashlane-ignore=\"true\"\n            data-lp-ignore=\"true\"\n            data-no-autofill=\"true\"\n            data-form-type=\"navigation\"\n          >\n            <Anchor onClick={onForgotPassword}>Reset Password</Anchor>\n          </Text>\n        )}\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Combobox, Flex, Stack, Text, TextInput, Title, useCombobox } from '@mantine/core';\nimport { useLocalStorage } from '@mantine/hooks';\nimport type { LoginAuthenticationResponse } from '@medplum/core';\nimport { getIdentifier, normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome, ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { ProjectMembershipLoginOption } from './ProjectLoginOption';\nimport projectLoginClasses from './ProjectLoginOption.module.css';\n\nexport interface ChooseProfileFormProps {\n  readonly login: string;\n  readonly memberships: ProjectMembership[];\n  readonly handleAuthResponse: (response: LoginAuthenticationResponse) => void;\n}\n\nconst RECENT_PROJECTS_KEY = 'medplum.recentProjects';\nconst MAX_RECENT_PROJECTS = 10;\n\nexport function ChooseProfileForm(props: ChooseProfileFormProps): JSX.Element {\n  const medplum = useMedplum();\n  const combobox = useCombobox();\n  const [search, setSearch] = useState('');\n  const [outcome, setOutcome] = useState<OperationOutcome>();\n  const [recentProjects, setRecentProjects] = useLocalStorage<Record<string, number>>({\n    key: RECENT_PROJECTS_KEY,\n    defaultValue: {},\n    getInitialValueInEffect: false,\n  });\n\n  function filterDisplay(display: string | undefined): boolean {\n    return !!display?.toLowerCase()?.includes(search.toLowerCase());\n  }\n\n  function filterMembership(membership: ProjectMembership): boolean {\n    return (\n      filterDisplay(membership.profile?.display) ||\n      filterDisplay(membership.project?.display) ||\n      filterDisplay(getMembershipLabel(membership))\n    );\n  }\n\n  function compareMembershipRecency(m1: ProjectMembership, m2: ProjectMembership): number {\n    const t1 = (m1.id && recentProjects[m1.id]) || 0;\n    const t2 = (m2.id && recentProjects[m2.id]) || 0;\n    return t2 - t1;\n  }\n\n  function handleValueSelect(membershipId: string): void {\n    medplum\n      .post<LoginAuthenticationResponse>('auth/profile', {\n        login: props.login,\n        profile: membershipId,\n      })\n      .then((response) => {\n        setRecentProjects((prev) => {\n          const next = { ...prev, [membershipId]: Date.now() };\n          const entries = Object.entries(next).sort((a, b) => b[1] - a[1]);\n          return Object.fromEntries(entries.slice(0, MAX_RECENT_PROJECTS));\n        });\n        props.handleAuthResponse(response);\n      })\n      .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n  }\n\n  const options = props.memberships\n    .filter(filterMembership)\n    .sort(compareMembershipRecency)\n    .slice(0, 10)\n    .map((item) => (\n      <Combobox.Option value={item.id as string} key={item.id} className={projectLoginClasses.interactive}>\n        <ProjectMembershipLoginOption membership={item} label={getMembershipLabel(item)} />\n      </Combobox.Option>\n    ));\n\n  return (\n    <Stack gap=\"0\">\n      <Flex justify=\"center\" align=\"center\" direction=\"column\" wrap=\"nowrap\">\n        <Logo size={32} />\n        <Title order={3} py=\"lg\">\n          Choose a Project\n        </Title>\n      </Flex>\n      <OperationOutcomeAlert outcome={outcome} mb=\"lg\" />\n      <Combobox store={combobox} onOptionSubmit={handleValueSelect}>\n        <Combobox.EventsTarget>\n          <TextInput\n            placeholder=\"Search\"\n            value={search}\n            mb=\"md\"\n            autoFocus\n            leftSection={<IconSearch size={16} />}\n            onChange={(event) => {\n              setSearch(event.currentTarget.value);\n              combobox.updateSelectedOptionIndex();\n            }}\n          />\n        </Combobox.EventsTarget>\n\n        <div>\n          <Combobox.Options style={{ marginLeft: '-10px', marginRight: '-10px', marginBottom: '-10px' }}>\n            {options.length > 0 ? options : <Combobox.Empty>Nothing found...</Combobox.Empty>}\n          </Combobox.Options>\n        </div>\n      </Combobox>\n      <Text size=\"sm\" ta=\"center\" mt=\"md\">\n        <Anchor\n          component=\"button\"\n          type=\"button\"\n          onClick={() => {\n            window.location.href = `/signin?project=new&login=${props.login}`;\n          }}\n        >\n          Create a new project\n        </Anchor>\n      </Text>\n    </Stack>\n  );\n}\n\nfunction getMembershipLabel(membership: ProjectMembership): string | undefined {\n  return getIdentifier(membership, 'https://medplum.com/identifier/label');\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ElementsContextType, TypedValue } from '@medplum/core';\nimport { buildElementsContext, getPathDisplayName, isEmpty, tryGetDataType } from '@medplum/core';\nimport type { AccessPolicyResource } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo } from 'react';\nimport { DEFAULT_IGNORED_NON_NESTED_PROPERTIES, DEFAULT_IGNORED_PROPERTIES } from '../constants';\nimport { DescriptionList, DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\n\nconst EXTENSION_KEYS = ['extension', 'modifierExtension'];\nconst IGNORED_PROPERTIES = DEFAULT_IGNORED_PROPERTIES.filter((prop) => !EXTENSION_KEYS.includes(prop));\n\nexport interface BackboneElementDisplayProps {\n  readonly value: TypedValue;\n  /** The path identifies the element and is expressed as a \".\"-separated list of ancestor elements, beginning with the name of the resource or extension. */\n  readonly path: string;\n  readonly compact?: boolean;\n  readonly ignoreMissingValues?: boolean;\n  readonly link?: boolean;\n  /** (optional) Profile URL of the structure definition represented by the backbone element */\n  readonly profileUrl?: string;\n  /**\n   * (optional) If provided, inputs specified in `accessPolicyResource.hiddenFields` are not shown.\n   */\n  readonly accessPolicyResource?: AccessPolicyResource;\n}\n\nexport function BackboneElementDisplay(props: BackboneElementDisplayProps): JSX.Element | null {\n  const typedValue = props.value;\n  const { value, type: typeName } = typedValue;\n  const parentElementsContext = useContext(ElementsContext);\n  const profileUrl = props.profileUrl ?? parentElementsContext?.profileUrl;\n  const typeSchema = useMemo(() => tryGetDataType(typeName, profileUrl), [profileUrl, typeName]);\n\n  const newElementsContext: ElementsContextType | undefined = useMemo(() => {\n    if (!typeSchema) {\n      return undefined;\n    }\n    return buildElementsContext({\n      parentContext: parentElementsContext,\n      elements: typeSchema.elements,\n      path: props.path,\n      profileUrl: typeSchema.url,\n      accessPolicyResource: props.accessPolicyResource,\n    });\n  }, [typeSchema, parentElementsContext, props.path, props.accessPolicyResource]);\n\n  if (isEmpty(value)) {\n    return null;\n  }\n\n  if (!typeSchema) {\n    return <div>{typeName}&nbsp;not implemented</div>;\n  }\n\n  if (\n    typeof value === 'object' &&\n    'name' in value &&\n    Object.keys(value).length === 1 &&\n    typeof value.name === 'string'\n  ) {\n    // Special case for common BackboneElement pattern\n    // Where there is an object with a single property 'name'\n    // Just display the name value.\n    return <div>{value.name}</div>;\n  }\n\n  // Since this component may create a new ElementsContext, compute the effective context for use in this component\n  const elementsContext = newElementsContext ?? parentElementsContext;\n\n  return maybeWrapWithContext(\n    ElementsContext.Provider,\n    newElementsContext,\n    <DescriptionList compact={props.compact}>\n      {Object.entries(elementsContext.elements).map(([key, property]) => {\n        if (EXTENSION_KEYS.includes(key) && isEmpty(property.slicing?.slices)) {\n          // an extension property without slices has no nested extensions\n          return null;\n        } else if (IGNORED_PROPERTIES.includes(key)) {\n          return null;\n        } else if (DEFAULT_IGNORED_NON_NESTED_PROPERTIES.includes(key) && property.path.split('.').length === 2) {\n          return null;\n        }\n\n        // Profiles can include nested elements in addition to their containing element, e.g.:\n        // identifier, identifier.use, identifier.system\n        // Skip nested elements, e.g. identifier.use, since they are handled by the containing element\n        if (key.includes('.')) {\n          return null;\n        }\n\n        const [propertyValue, propertyType] = getValueAndType(typedValue, key, elementsContext.profileUrl);\n        if ((props.ignoreMissingValues || property.max === 0) && isEmpty(propertyValue)) {\n          return null;\n        }\n\n        if (props.path.endsWith('.extension') && (key === 'url' || key === 'id')) {\n          return null;\n        }\n\n        // Array values provide their own DescriptionListEntry wrapper(s)\n        const isArrayProperty = property.max > 1 || property.isArray;\n        const resourcePropertyDisplay = (\n          <ResourcePropertyDisplay\n            key={key}\n            property={property}\n            propertyType={propertyType}\n            path={props.path + '.' + key}\n            value={propertyValue}\n            ignoreMissingValues={props.ignoreMissingValues}\n            includeArrayDescriptionListEntry={isArrayProperty}\n            link={props.link}\n          />\n        );\n\n        if (isArrayProperty) {\n          return resourcePropertyDisplay;\n        }\n\n        return (\n          <DescriptionListEntry key={key} term={getPathDisplayName(key)}>\n            {resourcePropertyDisplay}\n          </DescriptionListEntry>\n        );\n      })}\n    </DescriptionList>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, CopyButton, Flex, Tooltip } from '@mantine/core';\nimport type { InternalSchemaElement } from '@medplum/core';\nimport {\n  formatDateTime,\n  formatPeriod,\n  formatTiming,\n  formatWallTime,\n  isEmpty,\n  isObject,\n  isString,\n  PropertyType,\n} from '@medplum/core';\nimport type { ElementDefinitionType } from '@medplum/fhirtypes';\nimport { IconCheck, IconCopy, IconEye, IconEyeOff } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { AddressDisplay } from '../AddressDisplay/AddressDisplay';\nimport { AttachmentArrayDisplay } from '../AttachmentArrayDisplay/AttachmentArrayDisplay';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { BackboneElementDisplay } from '../BackboneElementDisplay/BackboneElementDisplay';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { CodingDisplay } from '../CodingDisplay/CodingDisplay';\nimport { ContactDetailDisplay } from '../ContactDetailDisplay/ContactDetailDisplay';\nimport { ContactPointDisplay } from '../ContactPointDisplay/ContactPointDisplay';\nimport { ExtensionDisplay } from '../ExtensionDisplay/ExtensionDisplay';\nimport { HumanNameDisplay } from '../HumanNameDisplay/HumanNameDisplay';\nimport { IdentifierDisplay } from '../IdentifierDisplay/IdentifierDisplay';\nimport { MoneyDisplay } from '../MoneyDisplay/MoneyDisplay';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\nimport { RangeDisplay } from '../RangeDisplay/RangeDisplay';\nimport { RatioDisplay } from '../RatioDisplay/RatioDisplay';\nimport { ReferenceDisplay } from '../ReferenceDisplay/ReferenceDisplay';\nimport { ResourceArrayDisplay } from '../ResourceArrayDisplay/ResourceArrayDisplay';\n\nexport interface ResourcePropertyDisplayProps {\n  readonly property?: InternalSchemaElement;\n  /** The path identifies the element and is expressed as a \".\"-separated list of ancestor elements, beginning with the name of the resource or extension. */\n  readonly path?: string;\n  readonly propertyType: string;\n  readonly value: any;\n  readonly arrayElement?: boolean;\n  readonly maxWidth?: number;\n  readonly ignoreMissingValues?: boolean;\n  readonly link?: boolean;\n  /** (Optional) The `ElemendDefinitionType` to display the property against. Used when displaying extensions.  */\n  readonly elementDefinitionType?: ElementDefinitionType;\n  /** (Optional) If true and `property` is an array, output is wrapped with a DescriptionListEntry */\n  readonly includeArrayDescriptionListEntry?: boolean;\n}\n\n/**\n * Low-level component that renders a property from a given resource, given type information.\n * @param props - The ResourcePropertyDisplay React props.\n * @returns The ResourcePropertyDisplay React node.\n */\nexport function ResourcePropertyDisplay(props: ResourcePropertyDisplayProps): JSX.Element | null {\n  const { property, propertyType, value } = props;\n\n  const isIdProperty = property?.path?.endsWith('.id');\n  if (isIdProperty) {\n    return (\n      <Flex gap={3} align=\"center\">\n        {value}\n        {!isEmpty(value) && (\n          <CopyButton value={value} timeout={2000}>\n            {({ copied, copy }) => (\n              <Tooltip label={copied ? 'Copied' : 'Copy'} withArrow position=\"right\">\n                <ActionIcon variant=\"subtle\" color={copied ? 'teal' : 'gray'} onClick={copy}>\n                  {copied ? <IconCheck size=\"1rem\" /> : <IconCopy size=\"1rem\" />}\n                </ActionIcon>\n              </Tooltip>\n            )}\n          </CopyButton>\n        )}\n      </Flex>\n    );\n  }\n\n  if (property && (property.isArray || property.max > 1) && !props.arrayElement) {\n    if (propertyType === PropertyType.Attachment) {\n      return (\n        <AttachmentArrayDisplay\n          values={value}\n          maxWidth={props.maxWidth}\n          includeDescriptionListEntry={props.includeArrayDescriptionListEntry}\n          property={property}\n          path={props.path}\n        />\n      );\n    }\n    return (\n      <ResourceArrayDisplay\n        path={props.path}\n        property={property}\n        propertyType={propertyType}\n        values={value}\n        includeDescriptionListEntry={props.includeArrayDescriptionListEntry}\n        ignoreMissingValues={props.ignoreMissingValues}\n        link={props.link}\n      />\n    );\n  }\n\n  switch (propertyType) {\n    case PropertyType.boolean:\n      return <>{value === undefined ? '' : Boolean(value).toString()}</>;\n    case PropertyType.SystemString:\n    case PropertyType.string:\n      // Check if this is a secret field that should be masked\n      if (props.property?.path?.toLowerCase().includes('secret')) {\n        return <SecretFieldDisplay value={value} />;\n      }\n      return <div style={{ whiteSpace: 'pre-wrap' }}>{value}</div>;\n    case PropertyType.code:\n    case PropertyType.date:\n    case PropertyType.decimal:\n    case PropertyType.id:\n    case PropertyType.integer:\n    case PropertyType.positiveInt:\n    case PropertyType.unsignedInt:\n    case PropertyType.uri:\n    case PropertyType.url:\n    case PropertyType.xhtml:\n      if (isObject(value) && !isString(value)) {\n        console.warn('Non-standard FHIR data or missing primitive value with extension', {\n          path: props.path,\n          propertyType,\n          value,\n        });\n        return null;\n      }\n      return <>{value?.toString()}</>;\n    case PropertyType.canonical:\n      return <ReferenceDisplay value={{ reference: value }} link={props.link} />;\n    case PropertyType.dateTime:\n    case PropertyType.instant:\n      return <>{formatDateTime(value)}</>;\n    case PropertyType.time:\n      return <>{formatWallTime(value)}</>;\n    case PropertyType.markdown:\n      return <pre>{value}</pre>;\n    case PropertyType.Address:\n      return <AddressDisplay value={value} />;\n    case PropertyType.Annotation:\n      return <>{value?.text}</>;\n    case PropertyType.Attachment:\n      return <AttachmentDisplay value={value} maxWidth={props.maxWidth} />;\n    case PropertyType.CodeableConcept:\n      return <CodeableConceptDisplay value={value} />;\n    case PropertyType.Coding:\n      return <CodingDisplay value={value} />;\n    case PropertyType.ContactDetail:\n      return <ContactDetailDisplay value={value} />;\n    case PropertyType.ContactPoint:\n      return <ContactPointDisplay value={value} />;\n    case PropertyType.HumanName:\n      return <HumanNameDisplay value={value} />;\n    case PropertyType.Identifier:\n      return <IdentifierDisplay value={value} />;\n    case PropertyType.Money:\n      return <MoneyDisplay value={value} />;\n    case PropertyType.Period:\n      return <>{formatPeriod(value)}</>;\n    case PropertyType.Quantity:\n    case PropertyType.Duration:\n      return <QuantityDisplay value={value} />;\n    case PropertyType.Range:\n      return <RangeDisplay value={value} />;\n    case PropertyType.Ratio:\n      return <RatioDisplay value={value} />;\n    case PropertyType.Reference:\n      return <ReferenceDisplay value={value} link={props.link} />;\n    case PropertyType.Timing:\n      return <>{formatTiming(value)}</>;\n    case PropertyType.Dosage:\n    case PropertyType.UsageContext:\n      if (!props.path) {\n        throw new Error(`Displaying property of type ${props.propertyType} requires path`);\n      }\n      return (\n        <BackboneElementDisplay\n          path={props.path}\n          value={{ type: propertyType, value }}\n          compact={true}\n          ignoreMissingValues={props.ignoreMissingValues}\n        />\n      );\n    case PropertyType.Extension:\n      if (!props.path) {\n        throw new Error(`Displaying property of type ${props.propertyType} requires path`);\n      }\n      return (\n        <ExtensionDisplay\n          path={props.path}\n          value={value}\n          compact={true}\n          ignoreMissingValues={props.ignoreMissingValues}\n          elementDefinitionType={props.elementDefinitionType}\n        />\n      );\n    default:\n      if (!property) {\n        throw new Error(`Displaying property of type ${props.propertyType} requires element schema`);\n      }\n      if (!props.path) {\n        throw new Error(`Displaying property of type ${props.propertyType} requires path`);\n      }\n      return (\n        <BackboneElementDisplay\n          path={props.path}\n          value={{ type: property.type[0].code, value }}\n          compact={true}\n          ignoreMissingValues={props.ignoreMissingValues}\n        />\n      );\n  }\n}\n\ninterface SecretFieldDisplayProps {\n  readonly value: string;\n}\n\nfunction SecretFieldDisplay(props: SecretFieldDisplayProps): JSX.Element {\n  const [isVisible, setIsVisible] = useState(false);\n  const secretValue = props.value ?? '';\n  const hasValue = !isEmpty(secretValue);\n  const MASK = '\u2022'.repeat(8);\n\n  return (\n    <Flex gap={3} align=\"center\">\n      {isVisible ? (\n        <div style={{ whiteSpace: 'pre-wrap' }}>{secretValue}</div>\n      ) : (\n        <div style={{ whiteSpace: 'pre-wrap' }} aria-hidden=\"true\">\n          {hasValue ? MASK : ''}\n        </div>\n      )}\n      {hasValue && (\n        <>\n          <CopyButton value={props.value} timeout={2000}>\n            {({ copied, copy }) => (\n              <Tooltip label={copied ? 'Copied' : 'Copy secret'} withArrow position=\"right\">\n                <ActionIcon\n                  variant=\"subtle\"\n                  color={copied ? 'teal' : 'gray'}\n                  onClick={copy}\n                  aria-label={copied ? 'Copied' : 'Copy secret'}\n                >\n                  {copied ? <IconCheck size=\"1rem\" /> : <IconCopy size=\"1rem\" />}\n                </ActionIcon>\n              </Tooltip>\n            )}\n          </CopyButton>\n          <Tooltip label={isVisible ? 'Hide secret' : 'Show secret'} withArrow position=\"right\">\n            <ActionIcon\n              variant=\"subtle\"\n              color=\"gray\"\n              onClick={() => setIsVisible(!isVisible)}\n              aria-label={isVisible ? 'Hide secret' : 'Show secret'}\n            >\n              {isVisible ? <IconEyeOff size=\"1rem\" /> : <IconEye size=\"1rem\" />}\n            </ActionIcon>\n          </Tooltip>\n        </>\n      )}\n    </Flex>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatCodeableConcept } from '@medplum/core';\nimport type { CodeableConcept } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface CodeableConceptDisplayProps {\n  readonly value?: CodeableConcept;\n}\n\nexport function CodeableConceptDisplay(props: CodeableConceptDisplayProps): JSX.Element {\n  return <>{formatCodeableConcept(props.value)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatCoding } from '@medplum/core';\nimport type { Coding } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface CodingDisplayProps {\n  readonly value?: Coding;\n  readonly includeCode?: boolean;\n}\n\nexport function CodingDisplay(props: CodingDisplayProps): JSX.Element {\n  return <>{formatCoding(props.value, props.includeCode)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ContactPoint } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface ContactPointDisplayProps {\n  readonly value?: ContactPoint;\n}\n\nexport function ContactPointDisplay(props: ContactPointDisplayProps): JSX.Element | null {\n  const contactPoint = props.value;\n  if (!contactPoint) {\n    return null;\n  }\n\n  const builder = [];\n\n  if (contactPoint.value) {\n    builder.push(contactPoint.value);\n  }\n\n  if (contactPoint.use || contactPoint.system) {\n    builder.push(' [');\n\n    if (contactPoint.use) {\n      builder.push(contactPoint.use);\n    }\n\n    if (contactPoint.use && contactPoint.system) {\n      builder.push(' ');\n    }\n\n    if (contactPoint.system) {\n      builder.push(contactPoint.system);\n    }\n\n    builder.push(']');\n  }\n\n  return <>{builder.join('').trim()}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ContactDetail } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { ContactPointDisplay } from '../ContactPointDisplay/ContactPointDisplay';\n\nexport interface ContactDetailDisplayProps {\n  readonly value?: ContactDetail;\n}\n\nexport function ContactDetailDisplay(props: ContactDetailDisplayProps): JSX.Element | null {\n  const contactDetail = props.value;\n  if (!contactDetail) {\n    return null;\n  }\n\n  return (\n    <>\n      {contactDetail.name}\n      {contactDetail.name && ': '}\n      {contactDetail.telecom?.map((telecom) => (\n        <ContactPointDisplay key={`telecom-${contactDetail.name}-${telecom.value}`} value={telecom} />\n      ))}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ElementType } from '@medplum/core';\nimport { getDataType, isPopulated, isProfileLoaded, tryGetProfile } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useContext, useEffect, useMemo, useState } from 'react';\nimport { BackboneElementDisplay } from '../BackboneElementDisplay/BackboneElementDisplay';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\n\nexport type ExtensionDisplayProps = {\n  /** The path identifies the element and is expressed as a \".\"-separated list of ancestor elements, beginning with the name of the resource or extension. */\n  readonly path: string;\n  readonly elementDefinitionType?: ElementType;\n  readonly value: any;\n  readonly ignoreMissingValues?: boolean;\n  readonly link?: boolean;\n  readonly compact?: boolean;\n};\n\nexport function ExtensionDisplay(props: ExtensionDisplayProps): JSX.Element | null {\n  const { elementDefinitionType } = props;\n\n  const medplum = useMedplum();\n  const ctx = useContext(ElementsContext);\n  const [typeSchema, setTypeSchema] = useState(getDataType('Extension'));\n  const profileUrl: string | undefined = useMemo(() => {\n    if (!isPopulated(elementDefinitionType?.profile)) {\n      return undefined;\n    }\n\n    return elementDefinitionType.profile[0] satisfies string;\n  }, [elementDefinitionType]);\n  const [loadingProfile, setLoadingProfile] = useState(profileUrl !== undefined);\n\n  useEffect(() => {\n    if (profileUrl) {\n      setLoadingProfile(true);\n      medplum\n        .requestProfileSchema(profileUrl)\n        .then(() => {\n          const profile = tryGetProfile(profileUrl);\n          setLoadingProfile(false);\n          if (profile) {\n            setTypeSchema(profile);\n          }\n        })\n        .catch((reason) => {\n          setLoadingProfile(false);\n          console.warn(reason);\n        });\n    }\n  }, [medplum, profileUrl]);\n\n  if (profileUrl && (loadingProfile || !isProfileLoaded(profileUrl))) {\n    return <div>Loading...</div>;\n  }\n\n  const valueElement = typeSchema.elements['value[x]'];\n  const extensionHasValue = valueElement?.max !== 0;\n  if (extensionHasValue) {\n    const [propertyValue, propertyType] = getValueAndType(\n      { type: 'Extension', value: props.value },\n      'value[x]',\n      profileUrl ?? ctx.profileUrl\n    );\n    return <ResourcePropertyDisplay propertyType={propertyType} value={propertyValue} />;\n  }\n\n  return (\n    <BackboneElementDisplay\n      path={props.path}\n      value={{ type: typeSchema.type, value: props.value }}\n      compact={props.compact}\n      ignoreMissingValues={props.ignoreMissingValues}\n      link={props.link}\n      profileUrl={profileUrl}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InternalSchemaElement, TypedValue } from '@medplum/core';\nimport { getTypedPropertyValue, getTypedPropertyValueWithSchema } from '@medplum/core';\n\n/**\n * Returns the value of the property and the property type.\n * Some property definitions support multiple types.\n * For example, \"Observation.value[x]\" can be \"valueString\", \"valueInteger\", \"valueQuantity\", etc.\n * According to the spec, there can only be one property for a given element definition.\n * This function returns the value and the type.\n * @param context - The base context (usually a FHIR resource).\n * @param path - The property path.\n * @param profileUrl - The property path.\n * @returns The value of the property and the property type.\n */\nexport function getValueAndType(context: TypedValue, path: string, profileUrl?: string): [any, string] {\n  const typedResult = getTypedPropertyValue(context, path, { profileUrl });\n  if (!typedResult) {\n    return [undefined, 'undefined'];\n  }\n\n  if (Array.isArray(typedResult)) {\n    return [typedResult.map((e) => e.value), typedResult[0].type];\n  }\n\n  return [typedResult.value, typedResult.type];\n}\n\n/**\n * Returns the value of the property and the property type.\n * Some property definitions support multiple types.\n * For example, \"Observation.value[x]\" can be \"valueString\", \"valueInteger\", \"valueQuantity\", etc.\n * According to the spec, there can only be one property for a given element definition.\n * This function returns the value and the type.\n * @param typedValue - The base context (usually a FHIR resource).\n * @param path - The property path.\n * @param element - The property element definition.\n * @returns The value of the property and the property type.\n */\nexport function getValueAndTypeFromElement(\n  typedValue: TypedValue,\n  path: string,\n  element: InternalSchemaElement\n): [any, string] {\n  const typedResult = getTypedPropertyValueWithSchema(typedValue, path, element);\n  if (!typedResult) {\n    return [undefined, 'undefined'];\n  }\n\n  if (Array.isArray(typedResult)) {\n    return [typedResult.map((e) => e.value), typedResult[0].type];\n  }\n\n  return [typedResult.value, typedResult.type];\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { HumanNameFormatOptions } from '@medplum/core';\nimport { formatHumanName } from '@medplum/core';\nimport type { HumanName } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface HumanNameDisplayProps {\n  readonly value?: HumanName;\n  readonly options?: HumanNameFormatOptions;\n}\n\nexport function HumanNameDisplay(props: HumanNameDisplayProps): JSX.Element | null {\n  const name = props.value;\n  if (!name) {\n    return null;\n  }\n\n  return <>{formatHumanName(name, props.options)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Identifier } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface IdentifierDisplayProps {\n  readonly value?: Identifier;\n}\n\nexport function IdentifierDisplay(props: IdentifierDisplayProps): JSX.Element {\n  return (\n    <div>\n      {props.value?.system}: {props.value?.value}\n    </div>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatMoney } from '@medplum/core';\nimport type { Money } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface MoneyDisplayProps {\n  readonly value?: Money;\n}\n\nexport function MoneyDisplay(props: MoneyDisplayProps): JSX.Element | null {\n  return <>{formatMoney(props.value)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatQuantity } from '@medplum/core';\nimport type { Quantity } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface QuantityDisplayProps {\n  readonly value?: Quantity;\n  readonly precision?: number;\n}\n\nexport function QuantityDisplay(props: QuantityDisplayProps): JSX.Element | null {\n  return <>{formatQuantity(props.value, props.precision)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { formatRange } from '@medplum/core';\nimport type { Range } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\n\nexport interface RangeDisplayProps {\n  readonly value?: Range;\n  readonly precision?: number;\n  readonly exclusive?: boolean;\n}\n\nexport function RangeDisplay(props: RangeDisplayProps): JSX.Element | null {\n  return <>{formatRange(props.value, props.precision, props.exclusive)}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Ratio } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\n\nexport interface RatioDisplayProps {\n  readonly value?: Ratio;\n  readonly precision?: number;\n}\n\nexport function RatioDisplay(props: RatioDisplayProps): JSX.Element | null {\n  const value = props.value;\n  if (!value) {\n    return null;\n  }\n\n  return (\n    <>\n      <QuantityDisplay value={value.numerator} precision={props.precision} />\n      &nbsp;/&nbsp;\n      <QuantityDisplay value={value.denominator} precision={props.precision} />\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { stringify } from '@medplum/core';\nimport type { Reference } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\n\nexport interface ReferenceDisplayProps {\n  readonly value?: Reference;\n  readonly link?: boolean;\n}\n\nexport function ReferenceDisplay(props: ReferenceDisplayProps): JSX.Element | null {\n  if (!props.value) {\n    return null;\n  }\n\n  const displayString = props.value.display || props.value.reference || stringify(props.value);\n\n  // The \"link\" prop defaults to \"true\"; undefined is treated as \"true\"\n  // To disable the link, it must be explicitly \"false\"\n  if (props.link !== false && props.value.reference) {\n    return <MedplumLink to={props.value}>{displayString}</MedplumLink>;\n  } else {\n    return <>{displayString}</>;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Text } from '@mantine/core';\nimport type { InternalSchemaElement, SliceDefinitionWithTypes } from '@medplum/core';\nimport { getPathDisplayName, isPopulated } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useContext, useEffect, useMemo, useState } from 'react';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { assignValuesIntoSlices, prepareSlices } from '../ResourceArrayInput/ResourceArrayInput.utils';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { SliceDisplay } from '../SliceDisplay/SliceDisplay';\n\nconst MAX_ARRAY_SIZE = 50;\n\nexport interface ResourceArrayDisplayProps {\n  /** The path identifies the element and is expressed as a \".\"-separated list of ancestor elements, beginning with the name of the resource or extension. */\n  readonly path?: string;\n  readonly property: InternalSchemaElement;\n  readonly propertyType: string;\n  readonly values: any[];\n  readonly ignoreMissingValues?: boolean;\n  readonly link?: boolean;\n  readonly includeDescriptionListEntry?: boolean;\n}\n\nexport function ResourceArrayDisplay(props: ResourceArrayDisplayProps): JSX.Element | null {\n  const { property, propertyType } = props;\n  const medplum = useMedplum();\n  const values = useMemo<any[]>(() => (Array.isArray(props.values) ? props.values : []), [props.values]);\n  const [loading, setLoading] = useState(true);\n  const [slices, setSlices] = useState<SliceDefinitionWithTypes[]>([]);\n  const [slicedValues, setSlicedValues] = useState<any[][]>(() => [values]);\n  const [valuesLength, setValuesLength] = useState(0);\n  const ctx = useContext(ElementsContext);\n\n  useEffect(() => {\n    prepareSlices({\n      medplum,\n      property,\n    })\n      .then((slices) => {\n        setValuesLength(values.length);\n        setSlices(slices);\n        const limitedValues = values.slice(0, MAX_ARRAY_SIZE);\n        const slicedValues = assignValuesIntoSlices(limitedValues, slices, property.slicing, ctx.profileUrl);\n        setSlicedValues(slicedValues);\n        setLoading(false);\n      })\n      .catch((reason) => {\n        console.error(reason);\n        setLoading(false);\n      });\n  }, [medplum, property, ctx.profileUrl, setSlicedValues, values]);\n\n  if (loading) {\n    return <div>Loading...</div>;\n  }\n\n  let nonSliceContent: JSX.Element | undefined;\n  const showNonSliceValues = property.type[0]?.code !== 'Extension';\n  if (showNonSliceValues) {\n    const nonSliceValues = slicedValues[slices.length];\n    const nonSliceElements = nonSliceValues.map((value, valueIndex) => (\n      <div key={`${valueIndex}-${nonSliceValues.length}`}>\n        <ResourcePropertyDisplay\n          path={props.path}\n          arrayElement={true}\n          property={property}\n          propertyType={propertyType}\n          value={value}\n          ignoreMissingValues={props.ignoreMissingValues}\n          link={props.link}\n        />\n      </div>\n    ));\n\n    if (props.includeDescriptionListEntry) {\n      // Since arrays are responsible for rendering their own DescriptionListEntry, we must find the key\n      if (!isPopulated(props.path)) {\n        throw new Error('props.path is required when includeDescriptionListEntry is true');\n      }\n      const key = props.path.split('.').pop() as string;\n      nonSliceContent = <DescriptionListEntry term={getPathDisplayName(key)}>{nonSliceElements}</DescriptionListEntry>;\n    } else {\n      nonSliceContent = <>{nonSliceElements}</>;\n    }\n  }\n\n  return (\n    <>\n      {slices.map((slice, sliceIndex) => {\n        if (!props.path) {\n          throw new Error(`Displaying a resource property with slices of type ${props.propertyType} requires path`);\n        }\n        let sliceDisplay = (\n          <SliceDisplay\n            key={slice.name}\n            path={props.path}\n            slice={slice}\n            property={property}\n            value={slicedValues[sliceIndex]}\n            ignoreMissingValues={props.ignoreMissingValues}\n            link={props.link}\n          />\n        );\n\n        if (props.includeDescriptionListEntry) {\n          sliceDisplay = (\n            <DescriptionListEntry key={slice.name} term={getPathDisplayName(slice.name)}>\n              {sliceDisplay}\n            </DescriptionListEntry>\n          );\n        }\n        return sliceDisplay;\n      })}\n\n      {nonSliceContent}\n      {valuesLength > MAX_ARRAY_SIZE && (\n        <Group justify=\"right\">\n          <Text>... {valuesLength} total values</Text>\n        </Group>\n      )}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InternalSchemaElement, MedplumClient, SliceDefinitionWithTypes, SlicingRules } from '@medplum/core';\nimport { getValueSliceName, isPopulated, isSliceDefinitionWithTypes, tryGetProfile } from '@medplum/core';\n\nexport function assignValuesIntoSlices<T>(\n  values: T[],\n  slices: SliceDefinitionWithTypes[],\n  slicing: SlicingRules | undefined,\n  profileUrl: string | undefined\n): T[][] {\n  if (!isPopulated(slicing?.slices)) {\n    return [values];\n  }\n\n  // store values in an array of arrays: one for each slice plus another for non-sliced values\n  const slicedValues: T[][] = new Array(slices.length + 1);\n  for (let i = 0; i < slicedValues.length; i++) {\n    slicedValues[i] = [];\n  }\n\n  for (const value of values) {\n    const sliceName = getValueSliceName(value, slices, slicing.discriminator, profileUrl);\n\n    let sliceIndex = sliceName ? slices.findIndex((slice) => slice.name === sliceName) : -1;\n    // -1 can come from either findIndex or the ternary else\n    if (sliceIndex === -1) {\n      sliceIndex = slices.length;\n    }\n    slicedValues[sliceIndex].push(value);\n  }\n\n  return slicedValues;\n}\n\nexport async function prepareSlices({\n  medplum,\n  property,\n}: {\n  medplum: MedplumClient;\n  property: InternalSchemaElement;\n}): Promise<SliceDefinitionWithTypes[]> {\n  return new Promise((resolve, reject) => {\n    if (!property.slicing) {\n      resolve([]);\n      return;\n    }\n\n    const supportedSlices: SliceDefinitionWithTypes[] = [];\n    const profileUrls: (string | undefined)[] = [];\n    const promises: Promise<void>[] = [];\n    for (const slice of property.slicing.slices) {\n      if (!isSliceDefinitionWithTypes(slice)) {\n        console.debug('Unsupported slice definition', slice);\n        continue;\n      }\n\n      let profileUrl: string | undefined;\n      // If elements are not defined for the slice, look for a profile\n      if (!isPopulated(slice.elements)) {\n        profileUrl = slice.type[0]?.profile?.[0];\n      }\n\n      // important to keep these three arrays the same length;\n      supportedSlices.push(slice);\n      profileUrls.push(profileUrl);\n      if (profileUrl) {\n        promises.push(medplum.requestProfileSchema(profileUrl));\n      }\n    }\n\n    Promise.all(promises)\n      .then(() => {\n        for (let i = 0; i < supportedSlices.length; i++) {\n          const slice = supportedSlices[i];\n          const profileUrl = profileUrls[i];\n          if (profileUrl) {\n            const typeSchema = tryGetProfile(profileUrl);\n            slice.typeSchema = typeSchema;\n          }\n        }\n        resolve(supportedSlices);\n      })\n      .catch(reject);\n  });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ElementsContextType, InternalSchemaElement, SliceDefinitionWithTypes } from '@medplum/core';\nimport { buildElementsContext, isPopulated } from '@medplum/core';\nimport type { JSX } from 'react';\nimport { useContext, useMemo } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\n\nexport interface SliceDisplayProps {\n  readonly path: string;\n  readonly slice: SliceDefinitionWithTypes;\n  readonly property: InternalSchemaElement;\n  readonly value: any[];\n  readonly ignoreMissingValues?: boolean;\n  readonly link?: boolean;\n}\n\nexport function SliceDisplay(props: SliceDisplayProps): JSX.Element {\n  const { slice, property } = props;\n\n  const sliceElements = slice.typeSchema?.elements ?? slice.elements;\n\n  const parentContext = useContext(ElementsContext);\n\n  const contextValue: ElementsContextType | undefined = useMemo(() => {\n    if (isPopulated(sliceElements)) {\n      return buildElementsContext({\n        parentContext: parentContext,\n        elements: sliceElements,\n        path: props.path,\n        profileUrl: slice.typeSchema?.url,\n      });\n    }\n    return undefined;\n  }, [parentContext, props.path, slice.typeSchema?.url, sliceElements]);\n\n  return maybeWrapWithContext(\n    ElementsContext.Provider,\n    contextValue,\n    <>\n      {props.value.map((value, valueIndex) => {\n        return (\n          <div key={`${valueIndex}-${props.value.length}`}>\n            <ResourcePropertyDisplay\n              property={property}\n              path={props.path}\n              arrayElement={true}\n              elementDefinitionType={slice.type[0]}\n              propertyType={slice.type[0].code}\n              value={value}\n              ignoreMissingValues={props.ignoreMissingValues}\n              link={props.link}\n            />\n          </div>\n        );\n      })}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Context, JSX } from 'react';\n\nexport function maybeWrapWithContext<T>(\n  ContextProvider: Context<T>['Provider'],\n  contextValue: T | undefined,\n  contents: JSX.Element\n): JSX.Element {\n  if (contextValue !== undefined) {\n    return <ContextProvider value={contextValue}>{contents}</ContextProvider>;\n  }\n\n  return contents;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box } from '@mantine/core';\nimport type { ElementsContextType } from '@medplum/core';\nimport { buildElementsContext, tryGetDataType } from '@medplum/core';\nimport type { AccessPolicyResource } from '@medplum/fhirtypes';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsInput } from '../ElementsInput/ElementsInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\nimport classes from './BackboneElementInput.module.css';\n\nexport interface BackboneElementInputProps extends BaseInputProps {\n  /** Type name the backbone element represents */\n  readonly typeName: string;\n  /** (optional) The contents of the resource represented by the backbone element */\n  readonly defaultValue?: any;\n  /** (optional) callback function that is called when the value of the backbone element changes */\n  readonly onChange?: (value: any) => void;\n  /** (optional) Profile URL of the structure definition represented by the backbone element */\n  readonly profileUrl?: string;\n  /**\n   * (optional) If provided, inputs specified in `accessPolicyResource.readonlyFields` are not editable\n   * and inputs specified in `accessPolicyResource.hiddenFields` are not shown.\n   */\n  readonly accessPolicyResource?: AccessPolicyResource;\n}\n\nexport function BackboneElementInput(props: BackboneElementInputProps): JSX.Element {\n  const [defaultValue] = useState(() => props.defaultValue ?? {});\n  const parentElementsContext = useContext(ElementsContext);\n  const profileUrl = props.profileUrl ?? parentElementsContext?.profileUrl;\n  const typeSchema = useMemo(() => tryGetDataType(props.typeName, profileUrl), [props.typeName, profileUrl]);\n  const type = typeSchema?.type ?? props.typeName;\n\n  const contextValue: ElementsContextType | undefined = useMemo(() => {\n    if (!typeSchema) {\n      return undefined;\n    }\n    return buildElementsContext({\n      parentContext: parentElementsContext,\n      elements: typeSchema.elements,\n      path: props.path,\n      profileUrl: typeSchema.url,\n      accessPolicyResource: props.accessPolicyResource,\n    });\n  }, [typeSchema, parentElementsContext, props.path, props.accessPolicyResource]);\n\n  if (!typeSchema) {\n    return <div>{type}&nbsp;not implemented</div>;\n  }\n\n  const isNested = parentElementsContext.path !== '';\n\n  return maybeWrapWithContext(\n    ElementsContext.Provider,\n    contextValue,\n    <Box className={cx({ [classes.nested]: isNested })}>\n      <ElementsInput\n        path={props.path}\n        valuePath={props.valuePath}\n        type={type}\n        defaultValue={defaultValue}\n        onChange={props.onChange}\n        outcome={props.outcome}\n      />\n    </Box>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Stack } from '@mantine/core';\nimport type { TypedValue } from '@medplum/core';\nimport { getPathDisplayName } from '@medplum/core';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { CheckboxFormSection } from '../CheckboxFormSection/CheckboxFormSection';\nimport { FormSection } from '../FormSection/FormSection';\nimport { setPropertyValue } from '../ResourceForm/ResourceForm.utils';\nimport { getValueAndTypeFromElement } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport type { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { EXTENSION_KEYS, ElementsContext, getElementsToRender } from './ElementsInput.utils';\n\nexport interface ElementsInputProps extends BaseInputProps {\n  readonly type: string;\n  readonly defaultValue: any;\n  readonly onChange: ((value: any) => void) | undefined;\n  readonly testId?: string;\n}\n\nexport function ElementsInput(props: ElementsInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue ?? {});\n  const elementsContext = useContext(ElementsContext);\n  const elementsToRender = useMemo(() => {\n    return getElementsToRender(elementsContext.elements);\n  }, [elementsContext.elements]);\n\n  function setValueWrapper(newValue: any): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  const typedValue: TypedValue = { type: props.type, value };\n\n  return (\n    <Stack style={{ flexGrow: 1 }} data-testid={props.testId}>\n      {elementsToRender.map(([key, element]) => {\n        const [propertyValue, propertyType] = getValueAndTypeFromElement(typedValue, key, element);\n        const required = element.min !== undefined && element.min > 0;\n        const valuePath = props.valuePath ? props.valuePath + '.' + key : undefined;\n        const resourcePropertyInput = (\n          <ResourcePropertyInput\n            key={key}\n            property={element}\n            name={key}\n            path={props.path + '.' + key}\n            valuePath={valuePath}\n            defaultValue={propertyValue}\n            defaultPropertyType={propertyType}\n            onChange={(newValue: any, propName?: string) => {\n              setValueWrapper(setPropertyValue({ ...value }, key, propName ?? key, element, newValue));\n            }}\n            outcome={props.outcome}\n          />\n        );\n\n        // no FormSection wrapper for extensions\n        if (props.type === 'Extension' || EXTENSION_KEYS.includes(key)) {\n          return resourcePropertyInput;\n        }\n\n        if (element.type.length === 1 && element.type[0].code === 'boolean') {\n          return (\n            <CheckboxFormSection\n              key={key}\n              title={getPathDisplayName(key)}\n              description={element.description}\n              htmlFor={key}\n              fhirPath={element.path}\n              withAsterisk={required}\n              readonly={element.readonly}\n            >\n              {resourcePropertyInput}\n            </CheckboxFormSection>\n          );\n        }\n\n        return (\n          <FormSection\n            key={key}\n            title={getPathDisplayName(key)}\n            description={element.description}\n            withAsterisk={required}\n            htmlFor={key}\n            outcome={props.outcome}\n            fhirPath={element.path}\n            errorExpression={valuePath}\n            readonly={element.readonly}\n          >\n            {resourcePropertyInput}\n          </FormSection>\n        );\n      })}\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Input } from '@mantine/core';\nimport type { JSX, ReactNode } from 'react';\nimport { useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport classes from '../FormSection/FormSection.module.css';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\n\nexport interface CheckboxFormSectionProps {\n  readonly htmlFor?: string;\n  readonly title?: string;\n  readonly description?: string;\n  readonly withAsterisk?: boolean;\n  readonly children?: ReactNode;\n  readonly testId?: string;\n  readonly fhirPath?: string;\n  readonly readonly?: boolean;\n}\n\nexport function CheckboxFormSection(props: CheckboxFormSectionProps): JSX.Element {\n  const { debugMode } = useContext(ElementsContext);\n\n  let label: ReactNode;\n  if (debugMode && props.fhirPath) {\n    label = `${props.title} - ${props.fhirPath}`;\n  } else {\n    label = props.title;\n  }\n  return maybeWrapWithTooltip(\n    props?.readonly ? READ_ONLY_TOOLTIP_TEXT : undefined,\n    <Group wrap=\"nowrap\" data-testid={props.testId}>\n      <div>{props.children}</div>\n      <div>\n        <Input.Wrapper\n          id={props.htmlFor}\n          label={label}\n          classNames={{ label: props?.readonly ? classes.dimmed : undefined }}\n          description={props.description}\n          withAsterisk={props.withAsterisk}\n        >\n          {(() => null)()}\n        </Input.Wrapper>\n      </div>\n    </Group>\n  );\n}\n", ".dimmed {\n  color: var(--mantine-color-dimmed);\n}\n\n.preserveBreaks {\n  white-space: pre-wrap;\n}\n\n.description:not(:has(+ :global(.mantine-Input-wrapper))) {\n  margin-bottom: calc(var(--mantine-spacing-xs) / 2);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Tooltip } from '@mantine/core';\nimport type { JSX } from 'react';\n\nexport const READ_ONLY_TOOLTIP_TEXT = 'Read Only';\n\nexport function maybeWrapWithTooltip(tooltipText: string | undefined, children: JSX.Element): JSX.Element {\n  return tooltipText ? <Tooltip.Floating label={tooltipText}>{children}</Tooltip.Floating> : children;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Input } from '@mantine/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport classes from './FormSection.module.css';\n\nexport interface FormSectionProps {\n  readonly title?: string;\n  readonly htmlFor?: string;\n  readonly description?: string;\n  readonly withAsterisk?: boolean;\n  readonly outcome?: OperationOutcome;\n  readonly children?: ReactNode;\n  readonly testId?: string;\n  readonly fhirPath?: string;\n  readonly errorExpression?: string;\n  readonly readonly?: boolean;\n}\n\nexport function FormSection(props: FormSectionProps): JSX.Element {\n  const { debugMode } = useContext(ElementsContext);\n\n  let label: ReactNode;\n  if (debugMode && props.fhirPath) {\n    label = `${props.title} - ${props.fhirPath}`;\n  } else {\n    label = props.title;\n  }\n  return maybeWrapWithTooltip(\n    props?.readonly ? READ_ONLY_TOOLTIP_TEXT : undefined,\n    <Input.Wrapper\n      id={props.htmlFor}\n      label={label}\n      classNames={{\n        label: cx({ [classes.dimmed]: props?.readonly }, classes.preserveBreaks),\n        description: classes.description,\n      }}\n      description={props.description}\n      withAsterisk={props.withAsterisk}\n      error={getErrorsForInput(props.outcome, props.errorExpression ?? props.htmlFor)}\n      data-testid={props.testId}\n    >\n      {props.children}\n    </Input.Wrapper>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InternalSchemaElement } from '@medplum/core';\nimport { capitalize, isEmpty } from '@medplum/core';\nimport type { StructureDefinition } from '@medplum/fhirtypes';\n\nexport function setPropertyValue(\n  obj: any,\n  key: string,\n  propName: string,\n  elementDefinition: InternalSchemaElement,\n  value: any\n): any {\n  const types = elementDefinition.type;\n  if (types.length > 1) {\n    for (const type of types) {\n      const compoundKey = key.replace('[x]', capitalize(type.code));\n      if (compoundKey in obj) {\n        delete obj[compoundKey];\n      }\n    }\n  }\n  if (isEmpty(value)) {\n    obj[propName] = undefined;\n  } else {\n    obj[propName] = value;\n  }\n  return obj;\n}\n\nexport type SupportedProfileStructureDefinition = StructureDefinition & {\n  url: NonNullable<StructureDefinition['url']>;\n  name: NonNullable<StructureDefinition['name']>;\n};\n\nexport function isSupportedProfileStructureDefinition(\n  profile?: StructureDefinition\n): profile is SupportedProfileStructureDefinition {\n  return !!profile && !isEmpty(profile.url) && !isEmpty(profile.name);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Checkbox, Group, NativeSelect, Textarea, TextInput } from '@mantine/core';\nimport type { ExtendedInternalSchemaElement } from '@medplum/core';\nimport {\n  applyDefaultValuesToElement,\n  capitalize,\n  getPathDifference,\n  HTTP_HL7_ORG,\n  isComplexTypeCode,\n  isEmpty,\n  isPopulated,\n  PropertyType,\n} from '@medplum/core';\nimport type { ElementDefinitionBinding, ElementDefinitionType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { AddressInput } from '../AddressInput/AddressInput';\nimport { AnnotationInput } from '../AnnotationInput/AnnotationInput';\nimport { AttachmentArrayInput } from '../AttachmentArrayInput/AttachmentArrayInput';\nimport { AttachmentInput } from '../AttachmentInput/AttachmentInput';\nimport { BackboneElementInput } from '../BackboneElementInput/BackboneElementInput';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { CodeInput } from '../CodeInput/CodeInput';\nimport { CodingInput } from '../CodingInput/CodingInput';\nimport { ContactDetailInput } from '../ContactDetailInput/ContactDetailInput';\nimport { ContactPointInput } from '../ContactPointInput/ContactPointInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ExtensionInput } from '../ExtensionInput/ExtensionInput';\nimport { HumanNameInput } from '../HumanNameInput/HumanNameInput';\nimport { IdentifierInput } from '../IdentifierInput/IdentifierInput';\nimport { MoneyInput } from '../MoneyInput/MoneyInput';\nimport { PeriodInput } from '../PeriodInput/PeriodInput';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { RangeInput } from '../RangeInput/RangeInput';\nimport { RatioInput } from '../RatioInput/RatioInput';\nimport { ReferenceInput } from '../ReferenceInput/ReferenceInput';\nimport { ResourceArrayInput } from '../ResourceArrayInput/ResourceArrayInput';\nimport { SensitiveTextarea } from '../SensitiveTextarea/SensitiveTextarea';\nimport { TimingInput } from '../TimingInput/TimingInput';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport type { BaseInputProps, ComplexTypeInputProps, PrimitiveTypeInputProps } from './ResourcePropertyInput.utils';\n\nexport interface ResourcePropertyInputProps extends BaseInputProps {\n  readonly property: ExtendedInternalSchemaElement;\n  readonly name: string;\n  readonly defaultPropertyType?: string;\n  readonly defaultValue: any;\n  readonly arrayElement?: boolean;\n  readonly onChange?: (value: any, propName?: string) => void;\n}\n\nexport function ResourcePropertyInput(props: ResourcePropertyInputProps): JSX.Element {\n  const { property, name, onChange, defaultValue } = props;\n  const defaultPropertyType =\n    props.defaultPropertyType && props.defaultPropertyType !== 'undefined'\n      ? props.defaultPropertyType\n      : property.type[0].code;\n  const propertyTypes = property.type as ElementDefinitionType[];\n\n  if ((property.isArray || property.max > 1) && !props.arrayElement) {\n    if (defaultPropertyType === PropertyType.Attachment) {\n      return (\n        <AttachmentArrayInput\n          name={name}\n          defaultValue={defaultValue}\n          onChange={onChange}\n          disabled={property.readonly}\n        />\n      );\n    }\n\n    // Extensions are a special type of array that shouldn't be indented\n    const indent = propertyTypes[0]?.code !== PropertyType.Extension;\n    return (\n      <ResourceArrayInput\n        property={property}\n        name={name}\n        path={props.path}\n        valuePath={props.valuePath}\n        defaultValue={defaultValue}\n        indent={indent}\n        onChange={onChange}\n        outcome={props.outcome}\n      />\n    );\n  } else if (propertyTypes.length > 1) {\n    return <ElementDefinitionInputSelector elementDefinitionTypes={propertyTypes} {...props} />;\n  } else {\n    return (\n      <ElementDefinitionTypeInput\n        name={name}\n        defaultValue={defaultValue}\n        onChange={(newValue: any) => {\n          if (props.onChange) {\n            const newPropName = props.name.replace('[x]', capitalize(propertyTypes[0].code));\n            props.onChange(newValue, newPropName);\n          }\n        }}\n        outcome={props.outcome}\n        elementDefinitionType={propertyTypes[0]}\n        min={property.min}\n        max={property.min}\n        binding={property.binding}\n        path={props.path}\n        valuePath={props.valuePath}\n        readOnly={property.readonly}\n      />\n    );\n  }\n}\n\nexport interface ElementDefinitionSelectorProps extends ResourcePropertyInputProps {\n  readonly elementDefinitionTypes: ElementDefinitionType[];\n}\n\nexport function ElementDefinitionInputSelector(props: ElementDefinitionSelectorProps): JSX.Element {\n  const propertyTypes = props.elementDefinitionTypes;\n  let initialPropertyType: ElementDefinitionType | undefined = undefined;\n  if (props.defaultPropertyType) {\n    initialPropertyType = propertyTypes.find((t) => t.code === props.defaultPropertyType);\n  }\n  if (!initialPropertyType) {\n    initialPropertyType = propertyTypes[0];\n  }\n  const [selectedType, setSelectedType] = useState(initialPropertyType);\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\" align=\"flex-start\">\n      <NativeSelect\n        disabled={props.property.readonly}\n        style={{ width: '200px' }}\n        defaultValue={selectedType.code}\n        data-testid={props.name && props.name + '-selector'}\n        onChange={(e) => {\n          setSelectedType(\n            propertyTypes.find(\n              (type: ElementDefinitionType) => type.code === e.currentTarget.value\n            ) as ElementDefinitionType\n          );\n        }}\n        data={propertyTypes.map((type: ElementDefinitionType) => ({\n          value: type.code,\n          label: type.code,\n        }))}\n      />\n      <ElementDefinitionTypeInput\n        name={props.name}\n        defaultValue={props.defaultValue}\n        outcome={props.outcome}\n        elementDefinitionType={selectedType}\n        onChange={(newValue: any) => {\n          if (props.onChange) {\n            props.onChange(newValue, props.name.replace('[x]', capitalize(selectedType.code)));\n          }\n        }}\n        min={props.property.min}\n        max={props.property.max}\n        binding={props.property.binding}\n        path={props.property.path}\n        valuePath={props.valuePath}\n        readOnly={props.property.readonly}\n      />\n    </Group>\n  );\n}\n\n// Avoiding optional props on lower-level components like to make it more difficult to misuse\nexport interface ElementDefinitionTypeInputProps extends Pick<\n  ResourcePropertyInputProps,\n  'name' | 'path' | 'valuePath' | 'defaultValue' | 'onChange' | 'outcome'\n> {\n  readonly elementDefinitionType: ElementDefinitionType;\n  readonly min: number;\n  readonly max: number;\n  readonly binding: ElementDefinitionBinding | undefined;\n  readonly readOnly?: boolean;\n}\n\nexport function ElementDefinitionTypeInput(props: ElementDefinitionTypeInputProps): JSX.Element {\n  const { name, onChange, outcome, binding, path, valuePath, readOnly } = props;\n  const required = props.min !== undefined && props.min > 0;\n\n  const propertyType = props.elementDefinitionType.code;\n\n  const elementsContext = useContext(ElementsContext);\n  const defaultValue = useMemo(() => {\n    if (!isComplexTypeCode(propertyType)) {\n      return props.defaultValue;\n    }\n\n    if (!isEmpty(props.defaultValue)) {\n      return props.defaultValue;\n    }\n\n    const withDefaults = Object.create(null);\n    if (elementsContext.path === props.path) {\n      applyDefaultValuesToElement(withDefaults, elementsContext.elements);\n    } else {\n      const key = getPathDifference(elementsContext.path, props.path);\n      if (key === undefined) {\n        return props.defaultValue;\n      }\n      applyDefaultValuesToElement(withDefaults, elementsContext.elements, key);\n    }\n\n    if (isPopulated(withDefaults)) {\n      return withDefaults;\n    }\n\n    return props.defaultValue;\n  }, [propertyType, elementsContext.path, elementsContext.elements, props.path, props.defaultValue]);\n\n  if (!propertyType) {\n    return <div>Property type not specified </div>;\n  }\n\n  function getComplexInputProps(): ComplexTypeInputProps<any> {\n    return { name, defaultValue, onChange, outcome, path, valuePath, disabled: readOnly };\n  }\n\n  function getPrimitiveInputProps(): PrimitiveTypeInputProps {\n    const error = getErrorsForInput(props.outcome, valuePath ?? path);\n    return {\n      id: name,\n      name,\n      'data-testid': name,\n      defaultValue,\n      required,\n      error,\n      disabled: readOnly,\n    };\n  }\n\n  switch (propertyType) {\n    // 2.24.0.1 Primitive Types\n    // https://www.hl7.org/fhir/datatypes.html#primitive\n\n    case PropertyType.SystemString:\n    case PropertyType.canonical:\n    case PropertyType.id:\n    case PropertyType.string:\n    case PropertyType.uri:\n    case PropertyType.url:\n      if (props.path === 'Project.secret.value[x]' || props.path === 'ClientApplication.certificateTrustStore') {\n        return (\n          <SensitiveTextarea\n            {...getPrimitiveInputProps()}\n            onChange={(e) => {\n              if (props.onChange) {\n                props.onChange(e.currentTarget.value);\n              }\n            }}\n          />\n        );\n      }\n\n      return (\n        <TextInput\n          {...getPrimitiveInputProps()}\n          onChange={(e) => {\n            if (onChange) {\n              onChange(e.currentTarget.value);\n            }\n          }}\n        />\n      );\n    case PropertyType.date:\n      return (\n        <TextInput\n          {...getPrimitiveInputProps()}\n          type=\"date\"\n          onChange={(e) => {\n            if (onChange) {\n              onChange(e.currentTarget.value);\n            }\n          }}\n        />\n      );\n    case PropertyType.time:\n      return (\n        <TextInput\n          {...getPrimitiveInputProps()}\n          type=\"time\"\n          step={1}\n          onChange={(e) => {\n            if (onChange) {\n              onChange(e.currentTarget.value);\n            }\n          }}\n        />\n      );\n    case PropertyType.dateTime:\n    case PropertyType.instant:\n      return <DateTimeInput {...getPrimitiveInputProps()} onChange={onChange} outcome={outcome} />;\n    case PropertyType.decimal:\n    case PropertyType.integer:\n    case PropertyType.positiveInt:\n    case PropertyType.unsignedInt:\n      return (\n        <TextInput\n          {...getPrimitiveInputProps()}\n          type=\"number\"\n          step={propertyType === PropertyType.decimal ? 'any' : '1'}\n          onChange={(e) => {\n            if (onChange) {\n              const num = e.currentTarget.valueAsNumber;\n              onChange(Number.isNaN(num) ? undefined : num);\n            }\n          }}\n        />\n      );\n    case PropertyType.code:\n      // overwrite getPrimitiveInputProps().error since FormSection already shows errors\n      return (\n        <CodeInput\n          {...getPrimitiveInputProps()}\n          error={undefined}\n          onChange={onChange}\n          binding={binding?.valueSet}\n          creatable\n          maxValues={1}\n        />\n      );\n    case PropertyType.boolean:\n      return (\n        <Checkbox\n          {...getPrimitiveInputProps()}\n          defaultChecked={Boolean(defaultValue)}\n          onChange={(e) => {\n            if (onChange) {\n              onChange(e.currentTarget.checked);\n            }\n          }}\n        />\n      );\n    case PropertyType.base64Binary:\n    case PropertyType.markdown:\n    case PropertyType.xhtml:\n      return (\n        <Textarea\n          {...getPrimitiveInputProps()}\n          spellCheck={propertyType !== PropertyType.base64Binary}\n          onChange={(e) => {\n            if (onChange) {\n              onChange(e.currentTarget.value);\n            }\n          }}\n        />\n      );\n\n    // 2.24.0.2 Complex Types\n    // https://www.hl7.org/fhir/datatypes.html#complex\n\n    case PropertyType.Address:\n      return <AddressInput {...getComplexInputProps()} />;\n    case PropertyType.Annotation:\n      return <AnnotationInput {...getComplexInputProps()} />;\n    case PropertyType.Attachment:\n      return <AttachmentInput {...getComplexInputProps()} />;\n    case PropertyType.CodeableConcept:\n      return <CodeableConceptInput binding={binding?.valueSet} {...getComplexInputProps()} />;\n    case PropertyType.Coding:\n      return <CodingInput binding={binding?.valueSet} {...getComplexInputProps()} />;\n    case PropertyType.ContactDetail:\n      return <ContactDetailInput {...getComplexInputProps()} />;\n    case PropertyType.ContactPoint:\n      return <ContactPointInput {...getComplexInputProps()} />;\n    case PropertyType.Extension:\n      return <ExtensionInput {...getComplexInputProps()} propertyType={props.elementDefinitionType} />;\n    case PropertyType.HumanName:\n      return <HumanNameInput {...getComplexInputProps()} />;\n    case PropertyType.Identifier:\n      return <IdentifierInput {...getComplexInputProps()} />;\n    case PropertyType.Money:\n      return <MoneyInput {...getComplexInputProps()} />;\n    case PropertyType.Period:\n      return <PeriodInput {...getComplexInputProps()} />;\n    case PropertyType.Duration:\n    case PropertyType.Quantity:\n      return <QuantityInput {...getComplexInputProps()} />;\n    case PropertyType.Range:\n      return <RangeInput {...getComplexInputProps()} />;\n    case PropertyType.Ratio:\n      return <RatioInput {...getComplexInputProps()} />;\n    case PropertyType.Reference:\n      return <ReferenceInput {...getComplexInputProps()} targetTypes={getTargetTypes(props.elementDefinitionType)} />;\n    case PropertyType.Timing:\n      return <TimingInput {...getComplexInputProps()} />;\n    case PropertyType.Dosage:\n    case PropertyType.UsageContext:\n    default:\n      return <BackboneElementInput {...getComplexInputProps()} typeName={propertyType} />;\n  }\n}\n\nconst RESOURCE_TYPE_URL_PREFIXES = [\n  `${HTTP_HL7_ORG}/fhir/StructureDefinition/`,\n  'https://medplum.com/fhir/StructureDefinition/',\n];\nfunction getTargetTypes(elementDefinitionType?: ElementDefinitionType): string[] | undefined {\n  return elementDefinitionType?.targetProfile?.map((p) => {\n    const resourceTypePrefix = RESOURCE_TYPE_URL_PREFIXES.find((prefix) => p.startsWith(prefix));\n    if (resourceTypePrefix) {\n      return p.slice(resourceTypePrefix.length);\n    } else {\n      return p;\n    }\n  });\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { CodeableConcept, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport type { ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\nimport { ValueSetAutocomplete } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nexport interface CodeableConceptInputProps\n  extends\n    Omit<ValueSetAutocompleteProps, 'name' | 'defaultValue' | 'onChange' | 'disabled'>,\n    ComplexTypeInputProps<CodeableConcept> {\n  readonly onChange?: (value: CodeableConcept | undefined) => void;\n}\n\nexport function CodeableConceptInput(props: CodeableConceptInputProps): JSX.Element {\n  const {\n    defaultValue,\n    onChange,\n    withHelpText,\n    // spread these unused props so they don't get passed to ValueSetAutocomplete in `rest`\n    outcome: _outcome,\n    path: _path,\n    valuePath: _valuePath,\n    ...rest\n  } = props;\n  const [value, setValue] = useState(defaultValue);\n\n  function handleChange(newValues: ValueSetExpansionContains[]): void {\n    const newConcept = valueSetElementToCodeableConcept(newValues);\n    setValue(newConcept);\n    if (onChange) {\n      onChange(newConcept);\n    }\n  }\n\n  return (\n    <ValueSetAutocomplete\n      defaultValue={value && codeableConceptToValueSetElement(value)}\n      onChange={handleChange}\n      withHelpText={withHelpText ?? true}\n      {...rest}\n    />\n  );\n}\n\nfunction codeableConceptToValueSetElement(concept: CodeableConcept): ValueSetExpansionContains[] | undefined {\n  return concept.coding?.map((c) => ({\n    system: c.system,\n    code: c.code,\n    display: c.display,\n  }));\n}\n\nfunction valueSetElementToCodeableConcept(elements: ValueSetExpansionContains[]): CodeableConcept | undefined {\n  if (elements.length === 0) {\n    return undefined;\n  }\n  return {\n    coding: elements.map((e) => ({\n      system: e.system,\n      code: e.code,\n      display: e.display,\n    })),\n  };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Coding, QuestionnaireResponseItem, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport type { ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\nimport { ValueSetAutocomplete } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nexport interface CodingInputProps\n  extends\n    Omit<ValueSetAutocompleteProps, 'defaultValue' | 'onChange' | 'disabled' | 'name'>,\n    ComplexTypeInputProps<Coding> {\n  readonly response?: QuestionnaireResponseItem;\n}\n\nexport function CodingInput(props: CodingInputProps): JSX.Element {\n  const { defaultValue, onChange, withHelpText, response, ...rest } = props;\n  const [value, setValue] = useState(response?.answer?.[0]?.valueCoding ?? defaultValue);\n\n  function handleChange(newValues: ValueSetExpansionContains[]): void {\n    const newValue = newValues[0];\n    const newConcept = newValue && valueSetElementToCoding(newValue);\n    setValue(newConcept);\n    if (onChange) {\n      onChange(newConcept);\n    }\n  }\n\n  return (\n    <ValueSetAutocomplete\n      defaultValue={value ? codingToValueSetElement(value) : undefined}\n      maxValues={1}\n      onChange={handleChange}\n      withHelpText={withHelpText ?? true}\n      {...rest}\n    />\n  );\n}\n\nexport function codingToValueSetElement(coding: Coding): ValueSetExpansionContains {\n  return {\n    system: coding.system,\n    code: coding.code,\n    display: coding.display,\n  };\n}\n\nexport function valueSetElementToCoding(element: ValueSetExpansionContains): Coding {\n  return {\n    system: element.system,\n    code: element.code,\n    display: element.display,\n  };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, TextInput } from '@mantine/core';\nimport type { ContactDetail, ContactPoint } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ContactPointInput } from '../ContactPointInput/ContactPointInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport type ContactDetailInputProps = ComplexTypeInputProps<ContactDetail>;\n\nexport function ContactDetailInput(props: ContactDetailInputProps): JSX.Element {\n  const [contactDetail, setContactDetail] = useState(props.defaultValue);\n\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [nameProps, telecomProps] = useMemo(\n    () => ['name', 'telecom'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setContactDetailWrapper(newValue: ContactDetail): void {\n    setContactDetail(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  function setName(name: string): void {\n    const newValue: ContactDetail = { ...contactDetail, name };\n    if (!name) {\n      delete newValue.name;\n    }\n    setContactDetailWrapper(newValue);\n  }\n\n  function setTelecom(telecom: ContactPoint | undefined): void {\n    const newValue: ContactDetail = { ...contactDetail, telecom: telecom && [telecom] };\n    if (!telecom) {\n      delete newValue.telecom;\n    }\n    setContactDetailWrapper(newValue);\n  }\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <TextInput\n        disabled={props.disabled || nameProps?.readonly}\n        data-testid={props.name + '-name'}\n        name={props.name + '-name'}\n        placeholder=\"Name\"\n        style={{ width: 180 }}\n        defaultValue={contactDetail?.name}\n        onChange={(e) => setName(e.currentTarget.value)}\n      />\n      <ContactPointInput\n        disabled={props.disabled || telecomProps?.readonly}\n        name={props.name + '-telecom'}\n        path={props.path + '.telecom'}\n        defaultValue={contactDetail?.telecom?.[0]}\n        onChange={setTelecom}\n        outcome={props.outcome}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, NativeSelect, TextInput } from '@mantine/core';\nimport type { ContactPoint } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\n\nexport type ContactPointInputProps = ComplexTypeInputProps<ContactPoint> & {\n  readonly onChange?: (value: ContactPoint | undefined) => void;\n};\n\nexport function ContactPointInput(props: ContactPointInputProps): JSX.Element {\n  const { path, outcome } = props;\n  const { elementsByPath, getExtendedProps } = useContext(ElementsContext);\n  const [contactPoint, setContactPoint] = useState(props.defaultValue);\n\n  const [systemElement, useElement, valueElement] = useMemo(\n    () => ['system', 'use', 'value'].map((field) => elementsByPath[path + '.' + field]),\n    [elementsByPath, path]\n  );\n  const [systemProps, useProps, valueProps] = useMemo(\n    () => ['system', 'use', 'value'].map((field) => getExtendedProps(path + '.' + field)),\n    [getExtendedProps, path]\n  );\n\n  function setContactPointWrapper(newValue: ContactPoint | undefined): void {\n    if (newValue && Object.keys(newValue).length === 0) {\n      newValue = undefined;\n    }\n    setContactPoint(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  function setSystem(system: 'url' | 'phone' | 'fax' | 'email' | 'pager' | 'sms' | 'other'): void {\n    const newValue: ContactPoint = { ...contactPoint, system };\n    if (!system) {\n      delete newValue.system;\n    }\n    setContactPointWrapper(newValue);\n  }\n\n  function setUse(use: 'home' | 'work' | 'temp' | 'old' | 'mobile'): void {\n    const newValue: ContactPoint = { ...contactPoint, use };\n    if (!use) {\n      delete newValue.use;\n    }\n    setContactPointWrapper(newValue);\n  }\n\n  function setValue(value: string): void {\n    const newValue: ContactPoint = { ...contactPoint, value };\n    if (!value) {\n      delete newValue.value;\n    }\n    setContactPointWrapper(newValue);\n  }\n\n  const errorPath = props.valuePath ?? path;\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\" align=\"flex-start\">\n      <NativeSelect\n        disabled={props.disabled || systemProps?.readonly}\n        data-testid=\"system\"\n        defaultValue={contactPoint?.system}\n        required={(systemElement?.min ?? 0) > 0}\n        onChange={(e) =>\n          setSystem(e.currentTarget.value as 'url' | 'phone' | 'fax' | 'email' | 'pager' | 'sms' | 'other')\n        }\n        data={['', 'email', 'phone', 'fax', 'pager', 'sms', 'url', 'other']}\n        error={getErrorsForInput(outcome, errorPath + '.system')}\n      />\n      <NativeSelect\n        disabled={props.disabled || useProps?.readonly}\n        data-testid=\"use\"\n        defaultValue={contactPoint?.use}\n        required={(useElement?.min ?? 0) > 0}\n        onChange={(e) => setUse(e.currentTarget.value as 'home' | 'work' | 'temp' | 'old' | 'mobile')}\n        data={['', 'home', 'work', 'temp', 'old', 'mobile']}\n        error={getErrorsForInput(outcome, errorPath + '.use')}\n      />\n      <TextInput\n        disabled={props.disabled || valueProps?.readonly}\n        placeholder=\"Value\"\n        defaultValue={contactPoint?.value}\n        required={(valueElement?.min ?? 0) > 0}\n        onChange={(e) => setValue(e.currentTarget.value)}\n        error={getErrorsForInput(outcome, errorPath + '.value')}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, TextInput } from '@mantine/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport { IconCalendarEvent } from '@tabler/icons-react';\nimport type { ChangeEvent, FocusEvent, JSX } from 'react';\nimport { useEffect, useRef, useState } from 'react';\nimport type { PrimitiveTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport classes from './DateTimeInput.module.css';\nimport { convertIsoToLocal, convertLocalToIso } from './DateTimeInput.utils';\n\nexport interface DateTimeInputProps extends PrimitiveTypeInputProps {\n  readonly label?: string;\n  readonly placeholder?: string;\n  readonly defaultValue?: string;\n  readonly autoFocus?: boolean;\n  readonly outcome?: OperationOutcome;\n  readonly onChange?: (value: string) => void;\n}\n\n/**\n * The DateTimeInput component is a wrapper around the HTML5 input type=\"datetime-local\".\n * The main purpose is to reconcile time zones.\n * Most of our date/time values are in ISO-8601, which includes a time zone offset.\n * The datetime-local input does not support the time zone offset.\n * @param props - The Input props.\n * @returns The JSX element to render.\n */\nexport function DateTimeInput(props: DateTimeInputProps): JSX.Element {\n  const defaultValue = convertIsoToLocal(props.defaultValue);\n  const [empty, setEmpty] = useState(!defaultValue);\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  useEffect(() => {\n    if (inputRef.current) {\n      setEmpty(isEmpty(inputRef.current));\n    }\n  }, [defaultValue]);\n\n  return (\n    <TextInput\n      ref={inputRef}\n      id={props.name}\n      name={props.name}\n      label={props.label}\n      data-autofocus={props.autoFocus}\n      data-testid={props['data-testid'] ?? props.name}\n      placeholder={props.placeholder}\n      required={props.required}\n      disabled={props.disabled}\n      type={getInputType()}\n      step={1}\n      defaultValue={defaultValue}\n      classNames={{ input: classes.input }}\n      data-empty={empty || undefined}\n      autoFocus={props.autoFocus}\n      error={getErrorsForInput(props.outcome, props.name)}\n      rightSection={\n        <ActionIcon\n          variant=\"transparent\"\n          color=\"gray\"\n          className={classes.pickerButton}\n          aria-label=\"Open date picker\"\n          disabled={props.disabled}\n          onClick={() => openPicker(inputRef.current)}\n        >\n          <IconCalendarEvent size={16} stroke={2} className={classes.pickerIcon} />\n        </ActionIcon>\n      }\n      rightSectionPointerEvents=\"all\"\n      onBlur={(e: FocusEvent<HTMLInputElement>) => setEmpty(isEmpty(e.currentTarget))}\n      onChange={(e: ChangeEvent<HTMLInputElement>) => {\n        setEmpty(isEmpty(e.currentTarget));\n        if (props.onChange) {\n          const newValue = e.currentTarget.value;\n          props.onChange(convertLocalToIso(newValue));\n        }\n      }}\n    />\n  );\n}\n\nfunction isEmpty(input: HTMLInputElement): boolean {\n  return !input.value && !input.validity.badInput;\n}\n\nfunction openPicker(input: HTMLInputElement | null): void {\n  try {\n    input?.showPicker?.();\n  } catch {\n    // showPicker throws in cross-origin iframes\n  }\n}\n\n/**\n * Returns the input type for the requested type.\n * JSDOM does not support many of the valid <input> type attributes.\n * For example, it won't fire change events for <input type=\"datetime-local\">.\n * @returns The input type for the current environment.\n */\nfunction getInputType(): string {\n  return import.meta.env.NODE_ENV === 'test' ? 'text' : 'datetime-local';\n}\n", ".input[data-empty]:not(:focus)::-webkit-datetime-edit {\n  color: var(--input-placeholder-color);\n}\n\n.input::-webkit-date-and-time-value,\n.input::-webkit-datetime-edit,\n.input::-webkit-datetime-edit-fields-wrapper,\n.input::-webkit-datetime-edit-month-field,\n.input::-webkit-datetime-edit-day-field,\n.input::-webkit-datetime-edit-year-field,\n.input::-webkit-datetime-edit-hour-field,\n.input::-webkit-datetime-edit-minute-field,\n.input::-webkit-datetime-edit-second-field,\n.input::-webkit-datetime-edit-meridiem-field,\n.input::-webkit-datetime-edit-ampm-field,\n.input::-webkit-datetime-edit-text {\n  margin-inline: 0;\n  padding: 0;\n}\n\n.input::-webkit-calendar-picker-indicator {\n  display: none;\n}\n\n.pickerIcon {\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n}\n\n.pickerButton:disabled {\n  background-color: transparent;\n}\n\n.pickerButton:disabled .pickerIcon {\n  color: light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-3));\n}\n\n@supports (-moz-appearance: none) {\n  .input {\n    --input-padding-inline-end: calc(var(--input-right-section-size) / 2 - 8px);\n  }\n\n  .pickerButton {\n    display: none;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { isValidDate } from '@medplum/core';\n\n/**\n * Converts an ISO-8601 date/time string to a local date/time string.\n * @param isoString - The ISO-8601 date/time string to convert.\n * @returns The local date/time string.\n */\nexport function convertIsoToLocal(isoString: string | undefined): string {\n  if (!isoString) {\n    return '';\n  }\n\n  // Convert the ISO-8601 date to a local datetime-local value.\n  // See: https://developer.mozilla.org/en-US/docs/Web/HTML/Date_and_time_formats#local_date_and_time_strings\n  // See: https://stackoverflow.com/a/60368477\n  const date = new Date(isoString);\n  if (!isValidDate(date)) {\n    // If the input string was malformed, return an empty string.\n    return '';\n  }\n\n  return date.toLocaleDateString('sv') + 'T' + date.toLocaleTimeString('sv');\n}\n\n/**\n * Converts a local date/time string to an ISO-8601 date/time string.\n * @param localString - The local date/time string to convert.\n * @returns The ISO-8601 date/time string.\n */\nexport function convertLocalToIso(localString: string | undefined): string {\n  if (!localString) {\n    return '';\n  }\n\n  // Try to parse the local string as a Date\n  // JavaScript's Date() constructor defaults to the local time zone.\n  // The Date() constructor will throw if the value is malformed.\n  const date = new Date(localString);\n  if (!isValidDate(date)) {\n    // If the input string was malformed, return an empty string.\n    return '';\n  }\n\n  return date.toISOString();\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { isPopulated, isProfileLoaded } from '@medplum/core';\nimport type { ElementDefinitionType, Extension } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { BackboneElementInput } from '../BackboneElementInput/BackboneElementInput';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport type ExtensionInputProps = ComplexTypeInputProps<Extension> & {\n  readonly propertyType: ElementDefinitionType;\n};\n\nexport function ExtensionInput(props: ExtensionInputProps): JSX.Element | null {\n  const { propertyType } = props;\n\n  const medplum = useMedplum();\n  const profileUrl: string | undefined = useMemo(() => {\n    if (!isPopulated(propertyType.profile)) {\n      return undefined;\n    }\n\n    return propertyType.profile[0] satisfies string;\n  }, [propertyType]);\n  const [loadingProfile, setLoadingProfile] = useState(profileUrl !== undefined);\n\n  useEffect(() => {\n    if (profileUrl) {\n      setLoadingProfile(true);\n      medplum\n        .requestProfileSchema(profileUrl)\n        .then(() => setLoadingProfile(false))\n        .catch((reason) => {\n          setLoadingProfile(false);\n          console.warn(reason);\n        });\n    }\n  }, [medplum, profileUrl]);\n\n  if (profileUrl && (loadingProfile || !isProfileLoaded(profileUrl))) {\n    return <div>Loading...</div>;\n  }\n\n  /*\n    From the spec:\n    An extension SHALL have either a value (i.e. a value[x] element) or sub-extensions, but not both.\n    If present, the value[x] element SHALL have content (value attribute or other elements)\n  */\n\n  // const valueElement = typeSchema.elements['value[x]'];\n  // const extensionHasValue = valueElement.max !== 0;\n  // console.debug(typeSchema.name, { extensionHasValue });\n  // It seems like the behavior of ExtensionInput should differ based on extensionHasValue. It likely\n  // isn't strictly necessary to do so given the recursive use of BackboneElementInput\n\n  return (\n    <BackboneElementInput\n      profileUrl={profileUrl}\n      path={props.path}\n      typeName=\"Extension\"\n      defaultValue={props.defaultValue}\n      onChange={props.onChange}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, NativeSelect, TextInput } from '@mantine/core';\nimport type { HumanName } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\n\nexport type HumanNameInputProps = ComplexTypeInputProps<HumanName>;\n\nexport function HumanNameInput(props: HumanNameInputProps): JSX.Element {\n  const { outcome, path } = props;\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [useProps, prefixProps, givenProps, familyProps, suffixProps] = useMemo(\n    () => ['use', 'prefix', 'given', 'family', 'suffix'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: HumanName): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  function setUse(use: 'temp' | 'old' | 'usual' | 'official' | 'nickname' | 'anonymous' | 'maiden' | undefined): void {\n    // || instead of ?? to handle empty strings\n    setValueWrapper({ ...value, use: use || undefined });\n  }\n\n  function setPrefix(prefix: string): void {\n    setValueWrapper({\n      ...value,\n      prefix: prefix ? prefix.split(' ') : undefined,\n    });\n  }\n\n  function setGiven(given: string): void {\n    setValueWrapper({\n      ...value,\n      given: given ? given.split(' ') : undefined,\n    });\n  }\n\n  function setFamily(family: string): void {\n    setValueWrapper({\n      ...value,\n      // || instead of ?? to handle empty strings\n      family: family || undefined,\n    });\n  }\n\n  function setSuffix(suffix: string): void {\n    setValueWrapper({\n      ...value,\n      suffix: suffix ? suffix.split(' ') : undefined,\n    });\n  }\n\n  const errorPath = props.valuePath ?? path;\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <NativeSelect\n        disabled={props.disabled || useProps?.readonly}\n        defaultValue={value?.use}\n        name={props.name + '-use'}\n        data-testid=\"use\"\n        onChange={(e) =>\n          setUse(e.currentTarget.value as 'temp' | 'old' | 'usual' | 'official' | 'nickname' | 'anonymous' | 'maiden')\n        }\n        data={['', 'temp', 'old', 'usual', 'official', 'nickname', 'anonymous', 'maiden']}\n        error={getErrorsForInput(outcome, errorPath + '.use')}\n      />\n      <TextInput\n        disabled={props.disabled || prefixProps?.readonly}\n        placeholder=\"Prefix\"\n        name={props.name + '-prefix'}\n        defaultValue={value?.prefix?.join(' ')}\n        onChange={(e) => setPrefix(e.currentTarget.value)}\n        error={getErrorsForInput(outcome, errorPath + '.prefix')}\n      />\n      <TextInput\n        disabled={props.disabled || givenProps?.readonly}\n        placeholder=\"Given\"\n        name={props.name + '-given'}\n        defaultValue={value?.given?.join(' ')}\n        onChange={(e) => setGiven(e.currentTarget.value)}\n        error={getErrorsForInput(outcome, errorPath + '.given')}\n      />\n      <TextInput\n        disabled={props.disabled || familyProps?.readonly}\n        name={props.name + '-family'}\n        placeholder=\"Family\"\n        defaultValue={value?.family}\n        onChange={(e) => setFamily(e.currentTarget.value)}\n        error={getErrorsForInput(outcome, errorPath + '.family')}\n      />\n      <TextInput\n        disabled={props.disabled || suffixProps?.readonly}\n        placeholder=\"Suffix\"\n        name={props.name + '-suffix'}\n        defaultValue={value?.suffix?.join(' ')}\n        onChange={(e) => setSuffix(e.currentTarget.value)}\n        error={getErrorsForInput(outcome, errorPath + '.suffix')}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, TextInput } from '@mantine/core';\nimport type { Identifier } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\n\nexport type IdentifierInputProps = ComplexTypeInputProps<Identifier>;\n\nexport function IdentifierInput(props: IdentifierInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const { elementsByPath, getExtendedProps } = useContext(ElementsContext);\n\n  const [systemElement, valueElement] = useMemo(\n    () => ['system', 'value'].map((field) => elementsByPath[props.path + '.' + field]),\n    [elementsByPath, props.path]\n  );\n\n  const [systemProps, valueProps] = useMemo(\n    () => ['system', 'value'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: Identifier): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n  const errorPath: string = props.valuePath ?? props.path;\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\" align=\"flex-start\">\n      <TextInput\n        disabled={props.disabled || systemProps?.readonly}\n        placeholder=\"System\"\n        required={(systemElement?.min ?? 0) > 0}\n        defaultValue={value?.system}\n        onChange={(e) => setValueWrapper({ ...value, system: e.currentTarget.value })}\n        error={getErrorsForInput(props.outcome, errorPath + '.system')}\n      />\n      <TextInput\n        disabled={props.disabled || valueProps?.readonly}\n        placeholder=\"Value\"\n        required={(valueElement?.min ?? 0) > 0}\n        defaultValue={value?.value}\n        onChange={(e) => setValueWrapper({ ...value, value: e.currentTarget.value })}\n        error={getErrorsForInput(props.outcome, errorPath + '.value')}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { NativeSelect, TextInput } from '@mantine/core';\nimport type { Money } from '@medplum/fhirtypes';\nimport { IconCurrencyDollar } from '@tabler/icons-react';\nimport type { ChangeEvent, JSX } from 'react';\nimport { useCallback, useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\n/*\n * Based on: https://github.com/mantinedev/ui.mantine.dev/blob/master/components/CurrencyInput/CurrencyInput.tsx\n */\n\n/**\n * List of currencies.\n *\n * Full list of currencies:\n * https://www.hl7.org/fhir/valueset-currencies.html\n *\n * Latest browsers can report list of supported currencies, but it's not widely supported:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf\n *\n * Using a short list for simplicity for now.\n */\nconst data = ['USD', 'EUR', 'CAD', 'GBP', 'AUD'];\n\nexport interface MoneyInputProps extends ComplexTypeInputProps<Money> {\n  readonly label?: string;\n  readonly placeholder?: string;\n}\n\nexport function MoneyInput(props: MoneyInputProps): JSX.Element {\n  const { onChange } = props;\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [currencyProps, valueProps] = useMemo(\n    () => ['currency', 'value'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  const setValueWrapper = useCallback(\n    (newValue: Money): void => {\n      setValue(newValue);\n      if (onChange) {\n        onChange(newValue);\n      }\n    },\n    [onChange]\n  );\n\n  const handleCurrencyChange = useCallback(\n    (e: ChangeEvent<HTMLSelectElement>) => {\n      setValueWrapper({\n        ...value,\n        currency: e.currentTarget.value as Money['currency'],\n      });\n    },\n    [value, setValueWrapper]\n  );\n\n  const handleValueChange = useCallback(\n    (e: ChangeEvent<HTMLInputElement>) => {\n      setValueWrapper({\n        ...value,\n        value: e.currentTarget.valueAsNumber,\n      });\n    },\n    [value, setValueWrapper]\n  );\n\n  const select = (\n    <NativeSelect\n      disabled={props.disabled || currencyProps?.readonly}\n      defaultValue={value?.currency}\n      data={data}\n      styles={{\n        input: {\n          fontWeight: 500,\n          borderTopLeftRadius: 0,\n          borderBottomLeftRadius: 0,\n          width: 92,\n        },\n      }}\n      onChange={handleCurrencyChange}\n    />\n  );\n\n  return (\n    <TextInput\n      disabled={props.disabled || valueProps?.readonly}\n      type=\"number\"\n      name={props.name}\n      label={props.label}\n      placeholder={props.placeholder ?? 'Value'}\n      defaultValue={value?.value?.toString() ?? 'USD'}\n      leftSection={<IconCurrencyDollar size={14} />}\n      rightSection={select}\n      rightSectionWidth={92}\n      onChange={handleValueChange}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group } from '@mantine/core';\nimport type { Period } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface PeriodInputProps extends ComplexTypeInputProps<Period> {}\n\nexport function PeriodInput(props: PeriodInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [startProps, endProps] = useMemo(\n    () => ['start', 'end'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: Period): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <DateTimeInput\n        disabled={props.disabled || startProps?.readonly}\n        name={props.name + '.start'}\n        placeholder=\"Start\"\n        defaultValue={value?.start}\n        onChange={(newValue) => setValueWrapper({ ...value, start: newValue })}\n      />\n      <DateTimeInput\n        disabled={props.disabled || endProps?.readonly}\n        name={props.name + '.end'}\n        placeholder=\"End\"\n        defaultValue={value?.end}\n        onChange={(newValue) => setValueWrapper({ ...value, end: newValue })}\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, NativeSelect, TextInput } from '@mantine/core';\nimport type { Quantity } from '@medplum/fhirtypes';\nimport type { JSX, WheelEvent } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface QuantityInputProps extends ComplexTypeInputProps<Quantity> {\n  readonly autoFocus?: boolean;\n  readonly required?: boolean;\n  readonly disableWheel?: boolean;\n}\n\nexport function QuantityInput(props: QuantityInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [comparatorProps, valueProps, unitProps] = useMemo(\n    () => ['comparator', 'value', 'unit'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: Quantity): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <NativeSelect\n        disabled={props.disabled || comparatorProps?.readonly}\n        style={{ width: 80 }}\n        data-testid={props.name + '-comparator'}\n        defaultValue={value?.comparator}\n        data={['', '<', '<=', '>=', '>']}\n        onChange={(e) =>\n          setValueWrapper({\n            ...value,\n            comparator: e.currentTarget.value as '<' | '<=' | '>=' | '>',\n          })\n        }\n      />\n      <TextInput\n        disabled={props.disabled || valueProps?.readonly}\n        id={props.name}\n        name={props.name}\n        required={props.required}\n        data-autofocus={props.autoFocus}\n        data-testid={props.name + '-value'}\n        type=\"number\"\n        placeholder=\"Value\"\n        defaultValue={value?.value}\n        autoFocus={props.autoFocus}\n        step=\"any\"\n        onWheel={(e: WheelEvent<HTMLInputElement>) => {\n          if (props.disableWheel) {\n            e.currentTarget.blur();\n          }\n        }}\n        onChange={(e) => {\n          setValueWrapper({\n            ...value,\n            value: tryParseNumber(e.currentTarget.value),\n          });\n        }}\n      />\n      <TextInput\n        disabled={props.disabled || unitProps?.readonly}\n        placeholder=\"Unit\"\n        data-testid={props.name + '-unit'}\n        defaultValue={value?.unit}\n        onChange={(e) =>\n          setValueWrapper({\n            ...value,\n            unit: e.currentTarget.value,\n          })\n        }\n      />\n    </Group>\n  );\n}\n\nfunction tryParseNumber(str: string): number | undefined {\n  if (!str) {\n    return undefined;\n  }\n  return Number.parseFloat(str);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group } from '@mantine/core';\nimport type { Range } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface RangeInputProps extends ComplexTypeInputProps<Range> {}\n\n/**\n * Renders a Range input.\n * See: https://www.hl7.org/fhir/datatypes.html#Range\n * @param props - Range input properties.\n * @returns Range input element.\n */\nexport function RangeInput(props: RangeInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [lowProps, highProps] = useMemo(\n    () => ['low', 'high'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: Range): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <QuantityInput\n        path={props.path + '.low'}\n        disabled={props.disabled || lowProps?.readonly}\n        name={props.name + '-low'}\n        defaultValue={value?.low}\n        onChange={(v) =>\n          setValueWrapper({\n            ...value,\n            low: v,\n          })\n        }\n      />\n\n      <QuantityInput\n        path={props.path + '.high'}\n        disabled={props.disabled || highProps?.readonly}\n        name={props.name + '-high'}\n        defaultValue={value?.high}\n        onChange={(v) =>\n          setValueWrapper({\n            ...value,\n            high: v,\n          })\n        }\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group } from '@mantine/core';\nimport type { Ratio } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface RatioInputProps extends ComplexTypeInputProps<Ratio> {}\n\n/**\n * Renders a Ratio input.\n * See: https://www.hl7.org/fhir/datatypes.html#Ratio\n * @param props - Ratio input properties.\n * @returns Ratio input element.\n */\nexport function RatioInput(props: RatioInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [numeratorProps, denominatorProps] = useMemo(\n    () => ['numerator', 'denominator'].map((field) => getExtendedProps(props.path + '.' + field)),\n    [getExtendedProps, props.path]\n  );\n\n  function setValueWrapper(newValue: Ratio): void {\n    setValue(newValue);\n    if (props.onChange) {\n      props.onChange(newValue);\n    }\n  }\n\n  return (\n    <Group gap=\"xs\" grow wrap=\"nowrap\">\n      <QuantityInput\n        path={props.path + '.numerator'}\n        disabled={props.disabled || numeratorProps?.readonly}\n        name={props.name + '-numerator'}\n        defaultValue={value?.numerator}\n        onChange={(v) =>\n          setValueWrapper({\n            ...value,\n            numerator: v,\n          })\n        }\n      />\n      <QuantityInput\n        path={props.path + '.denominator'}\n        disabled={props.disabled || denominatorProps?.readonly}\n        name={props.name + '-denominator'}\n        defaultValue={value?.denominator}\n        onChange={(v) =>\n          setValueWrapper({\n            ...value,\n            denominator: v,\n          })\n        }\n      />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, NativeSelect } from '@mantine/core';\nimport type { MedplumClient } from '@medplum/core';\nimport { LRUCache, ReadablePromise, createReference, isEmpty, isPopulated, tryGetProfile } from '@medplum/core';\nimport type { Reference, Resource, ResourceType, StructureDefinition } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\n\nexport interface ReferenceInputProps<T extends Resource = Resource> {\n  readonly name: string;\n  readonly placeholder?: string;\n  readonly defaultValue?: Reference<T>;\n  readonly targetTypes?: string[];\n  readonly searchCriteria?: Record<string, string>;\n  readonly autoFocus?: boolean;\n  readonly required?: boolean;\n  readonly onChange?: (value: Reference<T> | undefined) => void;\n  readonly disabled?: boolean;\n  /** Render the dropdowns inside the DOM tree (not a portal); defaults to portalled. */\n  readonly withinPortal?: boolean;\n}\n\ninterface BaseTargetType {\n  readonly value: string;\n}\n\ntype ProfileTargetType = BaseTargetType & {\n  readonly type: 'profile';\n  readonly name?: string;\n  readonly title?: string;\n  readonly resourceType?: string;\n  readonly error?: any;\n};\n\ntype ResourceTypeTargetType = BaseTargetType & {\n  readonly type: 'resourceType';\n  readonly resourceType: string;\n};\ntype TargetType = ResourceTypeTargetType | ProfileTargetType;\n\nexport function ReferenceInput<T extends Resource = Resource>(props: ReferenceInputProps<T>): JSX.Element {\n  const { onChange } = props;\n  const medplum = useMedplum();\n  const [value, setValue] = useState(props.defaultValue);\n  const [targetTypes, setTargetTypes] = useState<TargetType[] | undefined>(() => createTargetTypes(props.targetTypes));\n  const [targetType, setTargetType] = useState<TargetType | undefined>(() =>\n    getInitialTargetType(props.defaultValue, targetTypes)\n  );\n\n  const promiseCache = useRef(new LRUCache<ReadablePromise<TargetType>>());\n\n  const searchCriteria = useMemo<ReferenceInputProps['searchCriteria']>(() => {\n    if (targetType?.type === 'profile') {\n      return { ...props.searchCriteria, _profile: targetType.value };\n    }\n    return props.searchCriteria;\n  }, [props.searchCriteria, targetType]);\n\n  useEffect(() => {\n    let anyToFetch = false;\n    const newTargetTypePromises: Promise<TargetType>[] | undefined = targetTypes?.map((tt) => {\n      if (!shouldFetchResourceType(tt)) {\n        return Promise.resolve(tt);\n      }\n\n      anyToFetch = true;\n      const cacheKey = tt.value;\n      const cached = promiseCache.current.get(cacheKey);\n      if (cached) {\n        return cached;\n      }\n\n      const promise = fetchResourceTypeOfProfile(medplum, tt.value)\n        .then((profile) => {\n          const newTargetType = { ...tt };\n\n          if (!profile) {\n            console.error(`StructureDefinition not found for ${tt.value}`);\n            newTargetType.error = 'StructureDefinition not found';\n          } else if (!isPopulated(profile.type)) {\n            console.error(`StructureDefinition.type missing for ${tt.value}`);\n            newTargetType.error = 'StructureDefinition.type missing';\n          } else {\n            newTargetType.resourceType = profile.type;\n            newTargetType.name = profile.name;\n            newTargetType.title = profile.title;\n          }\n\n          return newTargetType;\n        })\n        .catch((reason) => {\n          console.error(reason);\n          return { ...tt, error: reason };\n        });\n\n      const readablePromise = new ReadablePromise(promise);\n      promiseCache.current.set(cacheKey, readablePromise);\n\n      return readablePromise;\n    });\n\n    if (!newTargetTypePromises || !anyToFetch) {\n      return;\n    }\n\n    Promise.all(newTargetTypePromises)\n      .then((newTargetTypes) => {\n        setTargetTypes(newTargetTypes);\n        if (!targetType) {\n          return;\n        }\n\n        const index = newTargetTypes.findIndex(\n          (tt) => tt.value === targetType.value || tt.resourceType === targetType.resourceType\n        );\n        if (index === -1) {\n          console.debug(`defaultValue had unexpected resourceType: ${targetType.resourceType}`);\n          return;\n        }\n        // orphaned targetType has been resolved\n        setTargetType(newTargetTypes[index]);\n      })\n      .catch(console.error);\n  }, [medplum, targetType, targetTypes]);\n\n  const setValueHelper = useCallback(\n    (item: T | undefined) => {\n      const newValue = item ? createReference(item) : undefined;\n      setValue(newValue);\n      if (onChange) {\n        onChange(newValue);\n      }\n    },\n    [onChange]\n  );\n\n  const typeSelectOptions = useMemo(() => {\n    if (targetTypes) {\n      return targetTypes.map((tt) => {\n        return {\n          value: tt.value,\n          label: tt.type === 'profile' ? (tt.title ?? tt.name ?? tt.resourceType ?? tt.value) : tt.value,\n        };\n      });\n    }\n    return [];\n  }, [targetTypes]);\n\n  return (\n    <>\n      {props.name && <input type=\"hidden\" name={props.name} value={value?.reference ?? ''} />}\n      <Group gap=\"xs\" grow wrap=\"nowrap\">\n        {targetTypes && targetTypes.length > 1 && (\n          <NativeSelect\n            name={props.name + '-resourceType'}\n            disabled={props.disabled}\n            data-autofocus={props.autoFocus}\n            data-testid=\"reference-input-resource-type-select\"\n            defaultValue={targetType?.resourceType}\n            autoFocus={props.autoFocus}\n            onChange={(e) => {\n              const newValue = e.currentTarget.value;\n              const newTargetType = targetTypes.find((tt) => tt.value === newValue);\n              setTargetType(newTargetType);\n            }}\n            data={typeSelectOptions}\n          />\n        )}\n        {!targetTypes && (\n          <ResourceTypeInput\n            disabled={props.disabled}\n            autoFocus={props.autoFocus}\n            testId=\"reference-input-resource-type-input\"\n            defaultValue={targetType?.resourceType as ResourceType}\n            onChange={(newResourceType) => {\n              if (newResourceType) {\n                setTargetType({ type: 'resourceType', value: newResourceType, resourceType: newResourceType });\n              } else {\n                setTargetType(undefined);\n              }\n            }}\n            name={props.name + '-resourceType'}\n            placeholder=\"Resource Type\"\n            withinPortal={props.withinPortal}\n          />\n        )}\n        <ResourceInput\n          resourceType={targetType?.resourceType as ResourceType}\n          name={props.name + '-id'}\n          required={props.required}\n          placeholder={props.placeholder}\n          defaultValue={value}\n          searchCriteria={searchCriteria}\n          onChange={setValueHelper}\n          disabled={props.disabled}\n          withinPortal={props.withinPortal}\n        />\n      </Group>\n    </>\n  );\n}\n\nfunction createTargetTypes(resourceTypesAndProfileUrls: string[] | undefined): TargetType[] | undefined {\n  if (\n    !resourceTypesAndProfileUrls ||\n    resourceTypesAndProfileUrls.length === 0 ||\n    (resourceTypesAndProfileUrls.length === 1 && resourceTypesAndProfileUrls[0] === 'Resource')\n  ) {\n    return undefined;\n  }\n\n  const results: TargetType[] = [];\n  for (const value of resourceTypesAndProfileUrls) {\n    // is there a less hacky way to distinguish resourceType from profile URLs?\n    if (value.includes('/')) {\n      results.push({ type: 'profile', value });\n    } else {\n      results.push({ type: 'resourceType', value, resourceType: value });\n    }\n  }\n  return results;\n}\n\nfunction getInitialTargetType(\n  defaultValue: Reference | undefined,\n  targetTypes: TargetType[] | undefined\n): TargetType | undefined {\n  const defaultValueResourceType = defaultValue?.reference?.split('/')[0];\n  if (defaultValueResourceType) {\n    const targetType = targetTypes?.find((tt) => tt.resourceType === defaultValueResourceType);\n    if (targetType) {\n      return targetType;\n    }\n\n    // An \"orphaned\" TargetType is created when defaultValue references a resourceType\n    // that is not yet represented in targetTypes due to profile URL resolution to resource type\n    // that has yet to occur. An orphan can also occur if a defaultValue is provided\n    // but targetTypes is not.\n    return {\n      type: 'resourceType',\n      value: defaultValueResourceType,\n      resourceType: defaultValueResourceType,\n    };\n  }\n\n  if (targetTypes && targetTypes.length > 0) {\n    return targetTypes[0];\n  }\n\n  return undefined;\n}\n\ninterface ResourceTypeGraphQLResponse {\n  readonly data: {\n    readonly StructureDefinitionList: Partial<StructureDefinition>[];\n  };\n}\n\nasync function fetchResourceTypeOfProfile(\n  medplum: MedplumClient,\n  profileUrl: string\n): Promise<Partial<StructureDefinition> | undefined> {\n  const profile = tryGetProfile(profileUrl);\n  if (profile) {\n    return { type: profile.type, name: profile.name, title: profile.title };\n  }\n\n  const query = `{\n      StructureDefinitionList(url: \"${profileUrl}\", _sort: \"_lastUpdated\", _count: 1) {\n        type,\n        name,\n        title,\n      }\n    }`.replaceAll(/\\s+/g, ' ');\n\n  const response = (await medplum.graphql(query)) as ResourceTypeGraphQLResponse;\n\n  return response.data.StructureDefinitionList[0];\n}\n\nfunction shouldFetchResourceType(targetType: TargetType): targetType is ProfileTargetType {\n  return targetType.type === 'profile' && !targetType?.error && isEmpty(targetType.resourceType);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback } from 'react';\nimport type { AsyncAutocompleteOption, AsyncAutocompleteProps } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { MultiResourceInput } from './MultiResourceInput';\n\nexport interface ResourceInputProps<T extends Resource = Resource> {\n  readonly resourceType: T['resourceType'];\n  readonly name: string;\n  readonly defaultValue?: T | Reference<T>;\n  readonly searchCriteria?: Record<string, string>;\n  /** The search parameter, with any modifier, that the typed text is sent as (e.g. `name:contains`). Defaults to one chosen by resource type. */\n  readonly searchParam?: string;\n  readonly placeholder?: string;\n  readonly required?: boolean;\n  readonly itemComponent?: (props: AsyncAutocompleteOption<T>) => JSX.Element | ReactNode;\n  readonly onChange?: (value: T | undefined) => void;\n  readonly disabled?: boolean;\n  readonly label?: AsyncAutocompleteProps<T>['label'];\n  /**\n   * Names the field for assistive technology, for use instead of a visible `label` (don't pass both). The name\n   * goes on the search box and on a group around the whole field, which keeps the chosen resource named while the\n   * search box is hidden (disabled or once a resource is chosen).\n   */\n  readonly 'aria-label'?: AsyncAutocompleteProps<T>['aria-label'];\n  readonly error?: AsyncAutocompleteProps<T>['error'];\n  /** Render the options dropdown inside the DOM tree (not a portal); defaults to portalled. */\n  readonly withinPortal?: boolean;\n  /** Whether to show a button that clears the whole selection. Defaults to true. */\n  readonly clearable?: boolean;\n}\n\n/**\n * @param props - The props for the ResourceInput component.\n * @returns The ResourceInput component.\n */\nexport function ResourceInput<T extends Resource = Resource>(props: ResourceInputProps<T>): JSX.Element | null {\n  const onChange = props.onChange;\n\n  const handleChange = useCallback(\n    (newResources: T[]) => {\n      if (onChange) {\n        onChange(newResources[0]);\n      }\n    },\n    [onChange]\n  );\n\n  return (\n    <MultiResourceInput<T>\n      resourceType={props.resourceType}\n      name={props.name}\n      defaultValue={props.defaultValue ? [props.defaultValue] : undefined}\n      searchCriteria={props.searchCriteria}\n      searchParam={props.searchParam}\n      placeholder={props.placeholder}\n      required={props.required}\n      itemComponent={props.itemComponent}\n      onChange={handleChange}\n      disabled={props.disabled}\n      label={props.label}\n      aria-label={props['aria-label']}\n      error={props.error}\n      withinPortal={props.withinPortal}\n      maxValues={1}\n      clearable={props.clearable}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Text } from '@mantine/core';\nimport { getDisplayString, getReferenceString, isReference, isResource } from '@medplum/core';\nimport type { Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { forwardRef, useCallback, useEffect, useRef, useState } from 'react';\nimport type { AsyncAutocompleteOption, AsyncAutocompleteProps } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { AsyncAutocomplete } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\n\n/**\n * Search parameter overrides for specific resource types.\n * Use this to specify the search parameter to use for a given resource type.\n * Otherwise it will fallback to \"name\" if the resource type is in NAME_RESOURCE_TYPES.\n * Otherwise it will fallback to \"_id\".\n */\nconst SEARCH_CODES: Record<string, string> = {\n  Device: 'device-name',\n  Observation: 'code',\n  Subscription: 'criteria',\n  User: 'email:contains',\n};\n\n/**\n * Resource types that should use the \"name\" search parameter.\n * This is the full list of resource types that have a \"name\" search parameter.\n * Otherwise it will fallback to \"_id\".\n */\nconst NAME_RESOURCE_TYPES = [\n  'AccessPolicy',\n  'Account',\n  'ActivityDefinition',\n  'Bot',\n  'CapabilityStatement',\n  'CareTeam',\n  'ClientApplication',\n  'CodeSystem',\n  'CompartmentDefinition',\n  'ConceptMap',\n  'EffectEvidenceSynthesis',\n  'Endpoint',\n  'EventDefinition',\n  'Evidence',\n  'EvidenceVariable',\n  'ExampleScenario',\n  'GraphDefinition',\n  'Group',\n  'HealthcareService',\n  'ImplementationGuide',\n  'InsurancePlan',\n  'Library',\n  'Location',\n  'Measure',\n  'MedicinalProduct',\n  'MessageDefinition',\n  'NamingSystem',\n  'OperationDefinition',\n  'Organization',\n  'Patient',\n  'Person',\n  'PlanDefinition',\n  'Practitioner',\n  'Project',\n  'Questionnaire',\n  'RelatedPerson',\n  'ResearchDefinition',\n  'ResearchElementDefinition',\n  'ResearchStudy',\n  'RiskEvidenceSynthesis',\n  'SearchParameter',\n  'StructureDefinition',\n  'StructureMap',\n  'TerminologyCapabilities',\n  'TestScript',\n  'UserConfiguration',\n  'ValueSet',\n];\n\n/**\n * Converts a FHIR resource to an AsyncAutocomplete option.\n * @param resource - The FHIR resource.\n * @returns An AsyncAutocompleteOption for the resource.\n */\nfunction toOption<T extends Resource>(resource: T): AsyncAutocompleteOption<T> {\n  return {\n    value: getReferenceString(resource) ?? '',\n    label: getDisplayString(resource),\n    resource,\n  };\n}\n\n/**\n * Returns the search parameter to use for the given resource type.\n * If the resource type is in SEARCH_CODES, then that value is used.\n * Otherwise, if the resource type is in NAME_RESOURCE_TYPES, then \"name\" is used.\n * Otherwise, \"_id\" is used.\n * @param resourceType - The FHIR resource type.\n * @returns The search parameter to use for the autocomplete input.\n */\nfunction getSearchParamForResourceType(resourceType: string): string {\n  return SEARCH_CODES[resourceType] ?? (NAME_RESOURCE_TYPES.includes(resourceType) ? 'name' : '_id');\n}\n\n/**\n * Default item component for resource autocomplete inputs.\n * Displays the resource avatar, display name, and birth date or ID.\n */\nexport const DefaultResourceItemComponent = forwardRef<HTMLDivElement, AsyncAutocompleteOption<Resource>>(\n  ({ label, resource, active: _active, ...others }: AsyncAutocompleteOption<Resource>, ref) => {\n    return (\n      <div ref={ref} {...others}>\n        <Group wrap=\"nowrap\">\n          <ResourceAvatar value={resource} />\n          <div>\n            <Text>{label}</Text>\n            <Text size=\"xs\" c=\"dimmed\">\n              {(resource as Patient).birthDate || resource.id}\n            </Text>\n          </div>\n        </Group>\n      </div>\n    );\n  }\n);\n\nDefaultResourceItemComponent.displayName = 'DefaultResourceItemComponent';\n\nexport interface MultiResourceInputProps<T extends Resource = Resource> {\n  readonly resourceType: T['resourceType'];\n  readonly name: string;\n  /**\n   * Initial selected values. Each entry may be a full resource or a reference that will be\n   * resolved on mount. Treated as uncontrolled \u2014 changes after mount are ignored.\n   */\n  readonly defaultValue?: (T | Reference<T>)[];\n  readonly searchCriteria?: Record<string, string>;\n  /** The search parameter, with any modifier, that the typed text is sent as (e.g. `name:contains`). Defaults to one chosen by resource type. */\n  readonly searchParam?: string;\n  readonly placeholder?: string;\n  readonly required?: boolean;\n  readonly itemComponent?: (props: AsyncAutocompleteOption<T>) => JSX.Element | ReactNode;\n  /** Called whenever the selection changes. Receives the full array of selected resources. */\n  readonly onChange?: (value: T[]) => void;\n  readonly disabled?: boolean;\n  readonly label?: AsyncAutocompleteProps<T>['label'];\n  /**\n   * Names the field for assistive technology, for use instead of a visible `label` (don't pass both). The name\n   * goes on the search box and on a group around the whole field, which keeps the chosen resources named while the\n   * search box is hidden (disabled or at `maxValues`).\n   */\n  readonly 'aria-label'?: AsyncAutocompleteProps<T>['aria-label'];\n  readonly error?: AsyncAutocompleteProps<T>['error'];\n  /** Maximum number of resources that can be selected. Defaults to uncapped. */\n  readonly maxValues?: number;\n  /** Render the options dropdown inside the DOM tree (not a portal); defaults to portalled. */\n  readonly withinPortal?: boolean;\n  /** Whether to show a button that clears the whole selection. Defaults to true. */\n  readonly clearable?: boolean;\n}\n\nexport function MultiResourceInput<T extends Resource = Resource>(\n  props: MultiResourceInputProps<T>\n): JSX.Element | null {\n  const medplum = useMedplum();\n  const { resourceType, searchCriteria, searchParam } = props;\n  const ItemComponent = props.itemComponent ?? DefaultResourceItemComponent;\n  const onChange = props.onChange;\n\n  // Capture initial defaultValue at mount \u2014 treated as uncontrolled (initial-only).\n  // The Mantine MultiSelect component does not reliably handle changes to defaultValue after mount.\n  const initialDefaultValue = useRef(props.defaultValue);\n\n  // undefined = still resolving references, [] = ready with no defaults, T[] = ready with resolved resources\n  const [defaultResources, setDefaultResources] = useState<T[] | undefined>(\n    !props.defaultValue || props.defaultValue.length === 0 ? [] : undefined\n  );\n\n  useEffect(() => {\n    let cancelled = false;\n    const items = initialDefaultValue.current;\n\n    if (items && items.length > 0) {\n      Promise.allSettled(\n        items.map((item): Promise<T> => {\n          if (isResource(item)) {\n            return Promise.resolve(item);\n          }\n          if (isReference(item)) {\n            const ref: Reference<T> = item;\n            return medplum.readReference(ref);\n          }\n          return Promise.reject(new Error('Not a resolvable item'));\n        })\n      )\n        .then((settled) => {\n          if (!cancelled) {\n            setDefaultResources(settled.filter((r) => r.status === 'fulfilled').map((r) => r.value));\n          }\n        })\n        .catch(() => {});\n    }\n\n    return () => {\n      cancelled = true;\n    };\n  }, [medplum]);\n\n  const loadValues = useCallback(\n    async (input: string, signal: AbortSignal): Promise<T[]> => {\n      const searchParams = new URLSearchParams({\n        [searchParam ?? getSearchParamForResourceType(resourceType)]: input ?? '',\n        _count: '10',\n        ...searchCriteria,\n      });\n\n      const resources = await medplum.searchResources(resourceType, searchParams, { signal });\n      return resources as unknown as T[];\n    },\n    [medplum, resourceType, searchCriteria, searchParam]\n  );\n\n  const handleChange = useCallback(\n    (newResources: T[]) => {\n      if (onChange) {\n        onChange(newResources);\n      }\n    },\n    [onChange]\n  );\n\n  if (defaultResources === undefined) {\n    // Default references are still resolving \u2014 defer render to avoid\n    // Mantine MultiSelect issues with defaultValue changing after mount.\n    return null;\n  }\n\n  return (\n    <AsyncAutocomplete<T>\n      disabled={props.disabled}\n      name={props.name}\n      label={props.label}\n      aria-label={props['aria-label']}\n      error={props.error}\n      required={props.required}\n      itemComponent={ItemComponent}\n      defaultValue={defaultResources}\n      placeholder={props.placeholder}\n      maxValues={props.maxValues}\n      toOption={toOption}\n      loadOptions={loadValues}\n      onChange={handleChange}\n      withinPortal={props.withinPortal}\n      clearable={props.clearable ?? true}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Stack, Text } from '@mantine/core';\nimport type { ExtendedInternalSchemaElement, SliceDefinitionWithTypes } from '@medplum/core';\nimport { getPathDisplayName } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX, MouseEvent } from 'react';\nimport { useContext, useEffect, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport type { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getValuePath } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { SliceInput } from '../SliceInput/SliceInput';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { ArrayRemoveButton } from '../buttons/ArrayRemoveButton';\nimport { killEvent } from '../utils/dom';\nimport classes from './ResourceArrayInput.module.css';\nimport { assignValuesIntoSlices, prepareSlices } from './ResourceArrayInput.utils';\n\nexport interface ResourceArrayInputProps extends BaseInputProps {\n  readonly property: ExtendedInternalSchemaElement;\n  readonly name: string;\n  readonly defaultValue?: any[];\n  readonly indent?: boolean;\n  readonly onChange?: (value: any[]) => void;\n  readonly hideNonSliceValues?: boolean;\n}\n\nexport function ResourceArrayInput(props: ResourceArrayInputProps): JSX.Element | null {\n  const { property } = props;\n  const medplum = useMedplum();\n  const [loading, setLoading] = useState(true);\n  const [slices, setSlices] = useState<SliceDefinitionWithTypes[]>([]);\n  // props.defaultValue should NOT be used after this; prefer the defaultValue state\n  const [defaultValue] = useState<any[]>(() => (Array.isArray(props.defaultValue) ? props.defaultValue : []));\n  const [slicedValues, setSlicedValues] = useState<any[][]>(() => [defaultValue]);\n  const ctx = useContext(ElementsContext);\n\n  const propertyTypeCode = property.type[0]?.code;\n  useEffect(() => {\n    prepareSlices({\n      medplum,\n      property,\n    })\n      .then((slices) => {\n        setSlices(slices);\n        const slicedValues = assignValuesIntoSlices(defaultValue, slices, property.slicing, ctx.profileUrl);\n        addPlaceholderValues(slicedValues, slices);\n        setSlicedValues(slicedValues);\n        setLoading(false);\n      })\n      .catch((reason) => {\n        console.error(reason);\n        setLoading(false);\n      });\n  }, [medplum, property, defaultValue, ctx.profileUrl, setSlicedValues]);\n\n  function setValuesWrapper(newValues: any[], sliceIndex: number): void {\n    const newSlicedValues = [...slicedValues];\n    newSlicedValues[sliceIndex] = newValues;\n    setSlicedValues(newSlicedValues);\n    if (props.onChange) {\n      // Remove any placeholder (i.e. undefined) values before propagating\n      const cleaned = newSlicedValues.flat().filter((val) => val !== undefined);\n      props.onChange(cleaned);\n    }\n  }\n\n  if (loading) {\n    return <div>Loading...</div>;\n  }\n\n  const nonSliceIndex = slices.length;\n  const nonSliceValues = slicedValues[nonSliceIndex];\n\n  // Hide non-sliced values when handling sliced extensions\n  const showNonSliceValues = !(props.hideNonSliceValues ?? (propertyTypeCode === 'Extension' && slices.length > 0));\n  const propertyDisplayName = getPathDisplayName(property.path);\n  const showEmptyMessage = props.property.readonly && slices.length === 0 && defaultValue.length === 0;\n\n  return (\n    <Stack className={props.indent ? classes.indented : undefined}>\n      {showEmptyMessage && <Text c=\"dimmed\">(empty)</Text>}\n      {slices.map((slice, sliceIndex) => {\n        return (\n          <SliceInput\n            slice={slice}\n            key={slice.name}\n            path={props.path}\n            valuePath={props.valuePath}\n            property={property}\n            defaultValue={slicedValues[sliceIndex]}\n            onChange={(newValue: any[]) => {\n              setValuesWrapper(newValue, sliceIndex);\n            }}\n            testId={`slice-${slice.name}`}\n          />\n        );\n      })}\n\n      {showNonSliceValues &&\n        nonSliceValues.map((value, valueIndex) => (\n          <Group key={`${valueIndex}-${nonSliceValues.length}`} wrap=\"nowrap\" style={{ flexGrow: 1 }}>\n            <div style={{ flexGrow: 1 }}>\n              <ResourcePropertyInput\n                arrayElement={true}\n                property={props.property}\n                name={props.name + '.' + valueIndex}\n                path={props.path}\n                valuePath={getValuePath(props.path, props.valuePath, valueIndex)}\n                defaultValue={value}\n                onChange={(newValue: any) => {\n                  const newNonSliceValues = [...nonSliceValues];\n                  newNonSliceValues[valueIndex] = newValue;\n                  setValuesWrapper(newNonSliceValues, nonSliceIndex);\n                }}\n                defaultPropertyType={undefined}\n                outcome={props.outcome}\n              />\n            </div>\n            {!props.property.readonly && (\n              <ArrayRemoveButton\n                propertyDisplayName={propertyDisplayName}\n                testId={`nonsliced-remove-${valueIndex}`}\n                onClick={(e: MouseEvent) => {\n                  killEvent(e);\n                  const newNonSliceValues = [...nonSliceValues];\n                  newNonSliceValues.splice(valueIndex, 1);\n                  setValuesWrapper(newNonSliceValues, nonSliceIndex);\n                }}\n              />\n            )}\n          </Group>\n        ))}\n      {!props.property.readonly && showNonSliceValues && slicedValues.flat().length < property.max && (\n        <Group wrap=\"nowrap\" style={{ justifyContent: 'flex-start' }}>\n          <ArrayAddButton\n            propertyDisplayName={propertyDisplayName}\n            onClick={(e: MouseEvent) => {\n              killEvent(e);\n              const newNonSliceValues = [...nonSliceValues];\n              newNonSliceValues.push(undefined);\n              setValuesWrapper(newNonSliceValues, nonSliceIndex);\n            }}\n            testId=\"nonsliced-add\"\n          />\n        </Group>\n      )}\n    </Stack>\n  );\n}\n\nfunction addPlaceholderValues(slicedValues: any[][], slices: SliceDefinitionWithTypes[]): void {\n  for (let sliceIndex = 0; sliceIndex < slices.length; sliceIndex++) {\n    const slice = slices[sliceIndex];\n    const sliceValues = slicedValues[sliceIndex];\n\n    while (sliceValues.length < slice.min) {\n      sliceValues.push(undefined);\n    }\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { OperationOutcome } from '@medplum/fhirtypes';\n\nexport interface BaseInputProps {\n  /** The path identifying the related element definition and is expressed as a \".\"-separated list of ancestor elements, beginning with the name of the resource or extension. */\n  readonly path: string;\n  /** (optional) A FHIRPath expression that identifies the input more precisely than `path`, e.g. `Patient.identifier[0].system` versus `Patient.identifier.system` */\n  readonly valuePath?: string;\n  /** (optional) OperationOutcome from the last attempted system action*/\n  readonly outcome?: OperationOutcome;\n}\n\nexport interface ComplexTypeInputProps<ValueType> extends BaseInputProps {\n  readonly name: string;\n  readonly defaultValue?: ValueType;\n  readonly onChange?: (value: ValueType, propName?: string) => void;\n  readonly disabled?: boolean;\n}\n\nexport interface PrimitiveTypeInputProps {\n  readonly id?: string;\n  readonly name: string;\n  readonly 'data-testid'?: string;\n  readonly defaultValue?: any;\n  readonly required?: boolean;\n  readonly error?: string;\n  readonly disabled?: boolean;\n}\n\nexport function getValuePath(elementPath: string, valuePath: string | undefined, arrayIndex?: number): string {\n  if (valuePath === undefined) {\n    return elementPath;\n  }\n\n  return arrayIndex === undefined ? valuePath : `${valuePath}[${arrayIndex}]`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Stack, Text } from '@mantine/core';\nimport type { ElementsContextType, ExtendedInternalSchemaElement, SliceDefinitionWithTypes } from '@medplum/core';\nimport { buildElementsContext, getPropertyDisplayName, isEmpty, isPopulated } from '@medplum/core';\nimport type { JSX, MouseEvent } from 'react';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { FormSection } from '../FormSection/FormSection';\nimport classes from '../ResourceArrayInput/ResourceArrayInput.module.css';\nimport { ElementDefinitionTypeInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport type { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { ArrayRemoveButton } from '../buttons/ArrayRemoveButton';\nimport { killEvent } from '../utils/dom';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\n\nexport interface SliceInputProps extends BaseInputProps {\n  readonly slice: SliceDefinitionWithTypes;\n  readonly property: ExtendedInternalSchemaElement;\n  readonly defaultValue: any[];\n  readonly onChange: (newValue: any[]) => void;\n  readonly testId?: string;\n}\n\nexport function SliceInput(props: SliceInputProps): JSX.Element | null {\n  const { slice, property } = props;\n  const [values, setValues] = useState(props.defaultValue);\n\n  const sliceElements = slice.typeSchema?.elements ?? slice.elements;\n\n  const parentElementsContextValue = useContext(ElementsContext);\n\n  const contextValue: ElementsContextType | undefined = useMemo(() => {\n    if (isPopulated(sliceElements)) {\n      return buildElementsContext({\n        parentContext: parentElementsContextValue,\n        elements: sliceElements,\n        path: props.path,\n        profileUrl: slice.typeSchema?.url,\n      });\n    }\n    return undefined;\n  }, [parentElementsContextValue, props.path, slice.typeSchema?.url, sliceElements]);\n\n  function setValuesWrapper(newValues: any[]): void {\n    setValues(newValues);\n    if (props.onChange) {\n      props.onChange(newValues);\n    }\n  }\n\n  const required = slice.min > 0;\n\n  // this is a bit of a hack targeted at nested extensions; indentation would ideally be controlled elsewhere\n  // e.g. USCorePatientProfile -> USCoreEthnicityExtension -> {ombCategory, detailed, text}\n  const indentedStack = isEmpty(slice.elements);\n  const propertyDisplayName = getPropertyDisplayName(slice.name);\n  const showEmptyMessage = props.property.readonly && values.length === 0;\n  return maybeWrapWithContext(\n    ElementsContext.Provider,\n    contextValue,\n    <FormSection\n      title={propertyDisplayName}\n      description={slice.definition}\n      withAsterisk={required}\n      fhirPath={`${property.path}:${slice.name}`}\n      testId={props.testId}\n      readonly={props.property.readonly}\n    >\n      {showEmptyMessage ? (\n        <Text c=\"dimmed\">(empty)</Text>\n      ) : (\n        <Stack className={indentedStack ? classes.indented : undefined}>\n          {values.map((value, valueIndex) => {\n            return (\n              <Group key={`${valueIndex}-${values.length}`} wrap=\"nowrap\">\n                <div style={{ flexGrow: 1 }} data-testid={props.testId && `${props.testId}-elements-${valueIndex}`}>\n                  <ElementDefinitionTypeInput\n                    elementDefinitionType={slice.type[0]}\n                    name={slice.name}\n                    defaultValue={value}\n                    onChange={(newValue) => {\n                      const newValues = [...values];\n                      newValues[valueIndex] = newValue;\n                      setValuesWrapper(newValues);\n                    }}\n                    outcome={props.outcome}\n                    min={slice.min}\n                    max={slice.max}\n                    binding={slice.binding}\n                    path={props.path}\n                    valuePath={undefined /* `valuePath` not supported in slices */}\n                    readOnly={props.property.readonly}\n                  />\n                </div>\n                {!props.property.readonly && values.length > slice.min && (\n                  <ArrayRemoveButton\n                    propertyDisplayName={propertyDisplayName}\n                    testId={props.testId && `${props.testId}-remove-${valueIndex}`}\n                    onClick={(e: MouseEvent) => {\n                      killEvent(e);\n                      const newValues = [...values];\n                      newValues.splice(valueIndex, 1);\n                      setValuesWrapper(newValues);\n                    }}\n                  />\n                )}\n              </Group>\n            );\n          })}\n          {!props.property.readonly && values.length < slice.max && (\n            <Group wrap=\"nowrap\" style={{ justifyContent: 'flex-start' }}>\n              <ArrayAddButton\n                propertyDisplayName={propertyDisplayName}\n                onClick={(e: MouseEvent) => {\n                  killEvent(e);\n                  const newValues = [...values, undefined];\n                  setValuesWrapper(newValues);\n                }}\n                testId={props.testId && `${props.testId}-add`}\n              />\n            </Group>\n          )}\n        </Stack>\n      )}\n    </FormSection>\n  );\n}\n", ".indented {\n  margin-top: 0.5rem;\n  border-left: 3px solid var(--mantine-color-gray-4);\n  padding: 0.5rem 0 0.5rem 0.5rem;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Button } from '@mantine/core';\nimport { IconCirclePlus } from '@tabler/icons-react';\nimport type { JSX, MouseEventHandler } from 'react';\n\nexport interface ArrayAddButtonProps {\n  readonly propertyDisplayName?: string;\n  readonly onClick: MouseEventHandler;\n  readonly testId?: string;\n}\n\nexport function ArrayAddButton({ propertyDisplayName, onClick, testId }: ArrayAddButtonProps): JSX.Element {\n  const text = propertyDisplayName ? `Add ${propertyDisplayName}` : 'Add';\n\n  return propertyDisplayName ? (\n    <Button\n      title={text}\n      size=\"sm\"\n      color=\"green.6\"\n      variant=\"subtle\"\n      data-testid={testId}\n      leftSection={<IconCirclePlus size=\"1.25rem\" />}\n      onClick={onClick}\n    >\n      {text}\n    </Button>\n  ) : (\n    <ActionIcon title={text} color=\"green.6\" data-testid={testId} onClick={onClick}>\n      <IconCirclePlus size=\"1.25rem\" />\n    </ActionIcon>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon } from '@mantine/core';\nimport { IconCircleMinus } from '@tabler/icons-react';\nimport type { JSX, MouseEventHandler } from 'react';\n\nexport interface ArrayRemoveButtonProps {\n  readonly propertyDisplayName?: string;\n  readonly onClick: MouseEventHandler;\n  readonly testId?: string;\n}\n\nexport function ArrayRemoveButton({ propertyDisplayName, onClick, testId }: ArrayRemoveButtonProps): JSX.Element {\n  return (\n    <ActionIcon\n      title={propertyDisplayName ? `Remove ${propertyDisplayName}` : 'Remove'}\n      color=\"red.5\"\n      data-testid={testId}\n      variant=\"subtle\"\n      onClick={onClick}\n    >\n      <IconCircleMinus size=\"1.25rem\" />\n    </ActionIcon>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { TextareaProps } from '@mantine/core';\nimport { ActionIcon, Flex, Textarea } from '@mantine/core';\nimport { useClipboard } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { IconCopy } from '@tabler/icons-react';\nimport type { JSX, RefAttributes } from 'react';\nimport { useRef, useState } from 'react';\n\nexport interface SensitiveTextareaProps extends TextareaProps, RefAttributes<HTMLTextAreaElement> {}\n\nexport function SensitiveTextarea(props: Omit<SensitiveTextareaProps, 'ref'>): JSX.Element {\n  const [revealed, setRevealed] = useState(false);\n  const clipboard = useClipboard();\n  const ref = useRef<HTMLTextAreaElement | null>(null);\n\n  const styles: SensitiveTextareaProps['styles'] = {\n    ...props.styles,\n  };\n  if (!revealed) {\n    if (!styles.input) {\n      styles.input = {};\n    }\n\n    (styles.input as Record<string, string>)['WebkitTextSecurity'] = 'disc';\n  }\n\n  return (\n    <Flex gap=\"xs\">\n      <Textarea\n        {...props}\n        styles={{\n          ...styles,\n          root: {\n            ...(styles.root ?? {}),\n            flexGrow: 1,\n          },\n        }}\n        ref={ref}\n        autosize\n        minRows={1}\n        onFocus={() => setRevealed(true)}\n        onBlur={() => setRevealed(false)}\n      />\n      <ActionIcon\n        title=\"Copy secret\"\n        onClick={() => {\n          clipboard.copy(ref.current?.value);\n          showNotification({ color: 'green', message: 'Copied' });\n        }}\n      >\n        <IconCopy />\n      </ActionIcon>\n    </Flex>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Button, Chip, Group, Modal, NativeSelect, Stack, Switch, TextInput } from '@mantine/core';\nimport type { DayOfWeek } from '@medplum/core';\nimport { formatTiming } from '@medplum/core';\nimport type { Timing, TimingRepeat } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useContext, useMemo, useRef, useState } from 'react';\n\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { FormSection } from '../FormSection/FormSection';\nimport type { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { ArrayRemoveButton } from '../buttons/ArrayRemoveButton';\n\n// Sunday-first, unlike the Monday-first `DAYS_OF_WEEK` in core, because this\n// drives the order the day chips are rendered in.\nconst daysOfWeek: DayOfWeek[] = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\n\ntype PeriodUnit = 'a' | 's' | 'min' | 'h' | 'd' | 'wk' | 'mo';\n\n// Internal state wrapper for `repeat.timeOfDay` array entries; used to provide\n// a stable ID to each raw string.\ntype TimeOfDayItem = { id: number; value: string };\n\nexport interface TimingInputProps extends ComplexTypeInputProps<Timing> {\n  readonly defaultModalOpen?: boolean;\n}\n\nexport function TimingInput(props: TimingInputProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue);\n  const [open, setOpen] = useState(!props.disabled && (props.defaultModalOpen ?? false));\n\n  return (\n    <>\n      <Group gap=\"xs\" grow wrap=\"nowrap\">\n        <span data-testid=\"timinginput-display\">{formatTiming(value) || 'No repeat'}</span>\n        <Button disabled={props.disabled} onClick={() => setOpen(true)}>\n          Edit\n        </Button>\n      </Group>\n      {!props.disabled && (\n        <TimingEditorDialog\n          path={props.path}\n          visible={open}\n          defaultValue={value}\n          onOk={(newValue) => {\n            if (props.onChange) {\n              props.onChange(newValue);\n            }\n            setValue(newValue);\n            setOpen(false);\n          }}\n          onCancel={() => setOpen(false)}\n        />\n      )}\n    </>\n  );\n}\n\ninterface TimingEditorDialogProps {\n  readonly path: string;\n  readonly visible: boolean;\n  readonly defaultValue?: Timing;\n  readonly onOk: (newValue: Timing) => void;\n  readonly onCancel: () => void;\n}\n\nconst defaultValue: Timing = {\n  repeat: {\n    period: 1,\n    periodUnit: 'd',\n  },\n};\n\nfunction TimingEditorDialog(props: TimingEditorDialogProps): JSX.Element {\n  const [value, setValue] = useState(props.defaultValue || defaultValue);\n  const [timeOfDayItems, setTimeOfDayItems] = useState<TimeOfDayItem[]>(() =>\n    (props.defaultValue?.repeat?.timeOfDay ?? []).map((v, i) => ({ id: i, value: v }))\n  );\n  const nextTimeOfDayId = useRef(timeOfDayItems.length);\n  const { getExtendedProps } = useContext(ElementsContext);\n  const [\n    eventProps,\n    repeatProps,\n    repeatPeriodProps,\n    repeatPeriodUnitProps,\n    repeatDayOfWeekProps,\n    repeatTimeOfDayProps,\n  ] = useMemo(\n    () =>\n      ['event', 'repeat', 'repeat.period', 'repeat.periodUnit', 'repeat.dayOfWeek', 'repeat.timeOfDay'].map((field) =>\n        getExtendedProps(props.path + '.' + field)\n      ),\n    [getExtendedProps, props.path]\n  );\n\n  function setStart(newStart: string): void {\n    setValue((value) => ({ ...value, event: [newStart] }));\n  }\n\n  function setRepeat(repeat: TimingRepeat | undefined): void {\n    setValue((value) => ({ ...value, repeat }));\n  }\n\n  function setPeriod(period: number | undefined): void {\n    setValue((value) => ({ ...value, repeat: { ...value.repeat, period } }));\n  }\n\n  function setPeriodUnit(periodUnit: PeriodUnit | undefined): void {\n    setValue((value) => ({ ...value, repeat: { ...value.repeat, periodUnit } }));\n  }\n\n  function setDaysOfWeek(dayOfWeek: DayOfWeek[] | undefined): void {\n    setValue((value) => ({ ...value, repeat: { ...value.repeat, dayOfWeek } }));\n  }\n\n  function setTimeOfDay(updater: (items: TimeOfDayItem[]) => TimeOfDayItem[]): void {\n    setTimeOfDayItems((items) => {\n      const newItems = updater(items);\n      const timeOfDay = newItems.map((item) => item.value);\n      setValue((value) => ({\n        ...value,\n        repeat: {\n          ...value.repeat,\n          timeOfDay,\n        },\n      }));\n      return newItems;\n    });\n  }\n\n  return (\n    <Modal\n      title=\"Timing\"\n      closeButtonProps={{ 'aria-label': 'Close' }}\n      opened={props.visible}\n      onClose={() => props.onCancel()}\n    >\n      <Stack gap=\"md\">\n        <FormSection title=\"Starts on\" htmlFor=\"timing-dialog-start\">\n          <DateTimeInput\n            disabled={eventProps?.readonly}\n            name=\"timing-dialog-start\"\n            onChange={(newValue) => setStart(newValue)}\n          />\n        </FormSection>\n        <Switch\n          disabled={repeatProps?.readonly}\n          label=\"Repeat\"\n          checked={!!value.repeat}\n          onChange={(e) => setRepeat(e.currentTarget.checked ? defaultValue.repeat : undefined)}\n        />\n        {value.repeat && (\n          <>\n            <FormSection title=\"Repeat every\" htmlFor=\"timing-dialog-period\">\n              <Group gap=\"xs\" grow wrap=\"nowrap\">\n                <TextInput\n                  disabled={repeatPeriodProps?.readonly}\n                  type=\"number\"\n                  step={1}\n                  id=\"timing-dialog-period\"\n                  name=\"timing-dialog-period\"\n                  defaultValue={value.repeat.period || 1}\n                  onChange={(e) => setPeriod(Number.parseInt(e.currentTarget.value, 10) || 1)}\n                />\n                <NativeSelect\n                  disabled={repeatPeriodUnitProps?.readonly}\n                  id=\"timing-dialog-periodUnit\"\n                  name=\"timing-dialog-periodUnit\"\n                  defaultValue={value.repeat.periodUnit}\n                  onChange={(e) => setPeriodUnit(e.currentTarget.value as PeriodUnit | undefined)}\n                  data={[\n                    { label: 'minute', value: 'min' },\n                    { label: 'hour', value: 'h' },\n                    { label: 'day', value: 'd' },\n                    { label: 'week', value: 'wk' },\n                    { label: 'month', value: 'mo' },\n                    { label: 'year', value: 'a' },\n                  ]}\n                />\n              </Group>\n            </FormSection>\n            {value.repeat.periodUnit === 'wk' && (\n              <FormSection title=\"Repeat on\">\n                <Chip.Group\n                  multiple\n                  onChange={setDaysOfWeek as (v: string[] | undefined) => void}\n                  value={value.repeat?.dayOfWeek}\n                >\n                  <Group justify=\"space-between\" mt=\"xs\" gap=\"xs\">\n                    {daysOfWeek.map((day) => (\n                      <Chip\n                        key={day}\n                        value={day}\n                        size=\"xs\"\n                        radius=\"xl\"\n                        disabled={repeatDayOfWeekProps?.readonly}\n                        checked={(value.repeat?.dayOfWeek ?? []).includes(day)}\n                      >\n                        {day.charAt(0).toUpperCase()}\n                      </Chip>\n                    ))}\n                  </Group>\n                </Chip.Group>\n              </FormSection>\n            )}\n            <FormSection title=\"At times\">\n              <Stack mt=\"xs\">\n                {timeOfDayItems.map((item, idx) => (\n                  <Group key={item.id}>\n                    <TextInput\n                      disabled={repeatTimeOfDayProps?.readonly}\n                      type=\"time\"\n                      id={`timing-dialog-repeat-timeOfDay[${idx}]`}\n                      name={`timing-dialog-repeat-timeOfDay[${idx}]`}\n                      data-testid={`timing-repeat-timeOfDay-input-${idx}`}\n                      defaultValue={item.value.slice(0, 5) /* truncate to HH:mm */}\n                      onChange={(e) => {\n                        const newValue = `${e.currentTarget.value}:00`;\n                        setTimeOfDay((items) => items.with(idx, { ...item, value: newValue }));\n                      }}\n                      style={{ flexGrow: 1 }}\n                    />\n                    <ArrayRemoveButton\n                      testId={`timing-repeat-timeOfDay-remove-${idx}`}\n                      onClick={() => setTimeOfDay((items) => items.toSpliced(idx, 1))}\n                    />\n                  </Group>\n                ))}\n                <Box>\n                  <ArrayAddButton\n                    propertyDisplayName=\"Time of Day\"\n                    onClick={() =>\n                      setTimeOfDay((items) => {\n                        const id = nextTimeOfDayId.current++;\n                        return items.concat({ id, value: '00:00:00' });\n                      })\n                    }\n                  />\n                </Box>\n              </Stack>\n            </FormSection>\n          </>\n        )}\n        <Group justify=\"flex-end\">\n          <Button onClick={() => props.onOk(value)}>OK</Button>\n        </Group>\n      </Stack>\n    </Modal>\n  );\n}\n", ".nested {\n  padding-left: var(--mantine-spacing-md);\n  padding-top: var(--mantine-spacing-md);\n  padding-bottom: var(--mantine-spacing-sm);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Button, Group } from '@mantine/core';\nimport { IconChevronLeft, IconChevronRight } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { useMemo, useState } from 'react';\nimport classes from './CalendarDateInput.module.css';\nimport {\n  dayNumber,\n  getMonthString,\n  getStartMonth,\n  isBeforeDay,\n  isSameDay,\n  sortEnds,\n  startOfDay,\n  startOfMonth,\n} from './CalendarDateInput.utils';\nimport { useDayRangeDrag } from './useDayRangeDrag';\n\nexport interface CalendarDateInputProps {\n  readonly availableDates: Date[];\n  readonly onChangeMonth: (date: Date) => void;\n  /** Called with the day picked. */\n  readonly onClick: (date: Date) => void;\n  readonly month?: Date;\n  /** An extra day to mark as picked, alongside any `range`. Ignored while a drag is under way. */\n  readonly selected?: Date;\n  readonly allowUnavailableDates?: boolean;\n  readonly earliestDate?: Date;\n  /**\n   * The stretch of days on show, banded across the weeks it spans. The ends may carry a time of\n   * day; only the days they fall on are used.\n   */\n  readonly range?: { readonly start: Date; readonly end: Date };\n  /**\n   * Called with the stretch of days a drag or a shift-click asked for, earlier end first.\n   *\n   * A shift-click moves the nearer end of the range to the day clicked and leaves the other where\n   * it is, so clicking beyond either end widens the range and clicking within it draws that end in.\n   * A day exactly between the two holds the start. The nearer end is measured on the range itself,\n   * which may begin in a month that has been paged away from.\n   */\n  readonly onSelectRange?: (start: Date, end: Date) => void;\n  /**\n   * Shown in place of the month and year above the grid, such as a button for jumping to a month.\n   * Rendered inside a `<p>`, so it must be inline content.\n   */\n  readonly monthLabel?: ReactNode;\n}\n\ninterface CalendarCell {\n  readonly date: Date;\n  readonly available: boolean;\n}\n\ntype OptionalCalendarCell = CalendarCell | undefined;\n\nexport function CalendarDateInput(props: CalendarDateInputProps): JSX.Element {\n  const { onChangeMonth, onClick, onSelectRange, allowUnavailableDates, earliestDate } = props;\n  const [uncontrolledMonth, setUncontrolledMonth] = useState<Date>(getStartMonth);\n  const shownMonth = props.month ?? uncontrolledMonth;\n  const year = shownMonth.getFullYear();\n  const monthIndex = shownMonth.getMonth();\n  const month = useMemo(() => new Date(year, monthIndex, 1), [year, monthIndex]);\n  const atEarliestMonth = !!earliestDate && month <= startOfMonth(earliestDate);\n\n  const drag = useDayRangeDrag(onSelectRange);\n\n  function moveMonth(delta: number): void {\n    const newMonth = new Date(month.getFullYear(), month.getMonth() + delta, 1);\n    if (props.month === undefined) {\n      setUncontrolledMonth(newMonth);\n    }\n    onChangeMonth(newMonth);\n  }\n\n  function isDayDisabled(day: CalendarCell): boolean {\n    return (!day.available && !allowUnavailableDates) || (!!earliestDate && isBeforeDay(day.date, earliestDate));\n  }\n\n  // A drag that has not yet crossed a day would otherwise blot out the range on show, so the band\n  // blinks down to the day pressed on the way to every click.\n  const dragging = drag.range && !isSameDay(drag.range.start, drag.range.end) ? drag.range : undefined;\n  const range = toDays(dragging ?? props.range);\n  // Suppressed only while actively dragging, so a static range still shows its picked day.\n  const selected = dragging ? undefined : props.selected;\n\n  const grid = useMemo(() => buildGrid(month, props.availableDates), [month, props.availableDates]);\n\n  return (\n    <div className={classes.root}>\n      <Group justify=\"space-between\" gap=\"xs\" grow wrap=\"nowrap\">\n        <p style={{ flex: 1 }}>{props.monthLabel ?? getMonthString(month)}</p>\n        <Group justify=\"flex-end\" gap={4}>\n          <ActionIcon\n            className={classes.monthButton}\n            variant=\"subtle\"\n            color=\"gray\"\n            radius=\"xl\"\n            size=\"lg\"\n            aria-label=\"Previous month\"\n            disabled={atEarliestMonth}\n            onClick={() => moveMonth(-1)}\n          >\n            <IconChevronLeft size={18} stroke={1.8} />\n          </ActionIcon>\n          <ActionIcon\n            className={classes.monthButton}\n            variant=\"subtle\"\n            color=\"gray\"\n            radius=\"xl\"\n            size=\"lg\"\n            aria-label=\"Next month\"\n            onClick={() => moveMonth(1)}\n          >\n            <IconChevronRight size={18} stroke={1.8} />\n          </ActionIcon>\n        </Group>\n      </Group>\n      <table className={cx(classes.table, onSelectRange && classes.selectsRanges)}>\n        <thead>\n          <tr>\n            <th>SUN</th>\n            <th>MON</th>\n            <th>TUE</th>\n            <th>WED</th>\n            <th>THU</th>\n            <th>FRI</th>\n            <th>SAT</th>\n          </tr>\n        </thead>\n        <tbody>\n          {grid.map((week, weekIndex) => (\n            <tr key={'week-' + weekIndex}>\n              {week.map((day, dayIndex) => (\n                <td\n                  key={'day-' + dayIndex}\n                  className={cx(\n                    day &&\n                      range &&\n                      day.date >= range.start &&\n                      day.date <= range.end && [\n                        classes.inRange,\n                        (isSameDay(day.date, range.start) || dayIndex === 0) && classes.rangeOpens,\n                        (isSameDay(day.date, range.end) || dayIndex === week.length - 1) && classes.rangeCloses,\n                      ]\n                  )}\n                >\n                  {day && (\n                    <Button\n                      variant=\"light\"\n                      className={cx(\n                        day.available && classes.available,\n                        isAnchor(day.date, range, selected) && classes.selected\n                      )}\n                      aria-pressed={selected || range ? isChosen(day.date, range, selected) : undefined}\n                      disabled={isDayDisabled(day)}\n                      onPointerDown={(event) => {\n                        if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {\n                          event.currentTarget.releasePointerCapture(event.pointerId);\n                        }\n                        drag.begin(day.date);\n                      }}\n                      onPointerOver={() => drag.extend(day.date)}\n                      onClick={(event) => {\n                        // A drag that crossed days has already asked for them, and\n                        // the browser reports the release as a click as well.\n                        if (drag.consumeClick()) {\n                          return;\n                        }\n                        if (event.shiftKey && onSelectRange) {\n                          const reached = moveNearerEnd(day.date, range, selected);\n                          if (reached && !isSameDay(reached.start, reached.end)) {\n                            // Shift-clicking an end asks for the range already on show.\n                            if (\n                              !range ||\n                              !isSameDay(reached.start, range.start) ||\n                              !isSameDay(reached.end, range.end)\n                            ) {\n                              onSelectRange(reached.start, reached.end);\n                            }\n                            return;\n                          }\n                        }\n                        onClick(day.date);\n                      }}\n                    >\n                      {day.date.getDate()}\n                    </Button>\n                  )}\n                </td>\n              ))}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n\ntype DayRange = CalendarDateInputProps['range'];\n\n/**\n * Pulls the ends of a range back to the days they fall on.\n * @param range - The stretch of days asked for, if there is one.\n * @returns The same range at day granularity.\n */\nfunction toDays(range: DayRange): DayRange {\n  return range && { start: startOfDay(range.start), end: startOfDay(range.end) };\n}\n\n/**\n * Returns whether a day is one the calendar is anchored on, and so marked as picked.\n * @param date - Local midnight of the day in question.\n * @param range - The stretch of days on show, if there is one.\n * @param selected - The single day chosen, if there is one.\n * @returns True when the day is an end of the range on show, or the day named as picked.\n */\nfunction isAnchor(date: Date, range: DayRange, selected: Date | undefined): boolean {\n  return isSameDay(date, selected) || (!!range && (isSameDay(date, range.start) || isSameDay(date, range.end)));\n}\n\n/**\n * Returns whether a day is part of what has been chosen.\n * @param date - Local midnight of the day in question.\n * @param range - The stretch of days on show, if there is one.\n * @param selected - The single day chosen, if there is one.\n * @returns True when the day falls within what is chosen.\n */\nfunction isChosen(date: Date, range: DayRange, selected: Date | undefined): boolean {\n  return isAnchor(date, range, selected) || (!!range && date > range.start && date < range.end);\n}\n\n/**\n * Works out the range a shift-click asks for: the nearer end moves to the day clicked, and the\n * other end is held where it is.\n * @param date - Local midnight of the day shift-clicked.\n * @param range - The stretch of days on show, if there is one.\n * @param selected - The single day on show, if there is one.\n * @returns The range reached, or undefined when there is no end to hold.\n */\nfunction moveNearerEnd(date: Date, range: DayRange, selected: Date | undefined): DayRange {\n  if (range) {\n    const start = startOfDay(range.start);\n    const end = startOfDay(range.end);\n    // Exactly one of these is negative unless the day falls within the range, so the nearer end\n    // comes out without measuring either distance. A day dead centre holds the start, leaving the\n    // end to come back to it.\n    const held = dayNumber(date) - dayNumber(start) < dayNumber(end) - dayNumber(date) ? end : start;\n    return sortEnds(held, date);\n  }\n  if (selected) {\n    return sortEnds(startOfDay(selected), date);\n  }\n  return undefined;\n}\n\nfunction buildGrid(startDate: Date, availableDates: Date[]): OptionalCalendarCell[][] {\n  const d = new Date(startDate.getFullYear(), startDate.getMonth());\n  const grid: OptionalCalendarCell[][] = [];\n  let row: OptionalCalendarCell[] = [];\n\n  // Fill leading empty days\n  for (let i = 0; i < d.getDay(); i++) {\n    row.push(undefined);\n  }\n\n  while (d.getMonth() === startDate.getMonth()) {\n    row.push({\n      date: new Date(d),\n      available: isDayAvailable(d, availableDates),\n    });\n\n    if (d.getDay() === 6) {\n      grid.push(row);\n      row = [];\n    }\n\n    d.setDate(d.getDate() + 1);\n  }\n\n  // Fill trailing empty days\n  if (d.getDay() !== 0) {\n    for (let i = d.getDay(); i < 7; i++) {\n      row.push(undefined);\n    }\n    grid.push(row);\n  }\n\n  return grid;\n}\n\n/**\n * Returns true if the given date is available for booking.\n * @param day - The day to check.\n * @param availableDates - The list of available dates.\n * @returns True if there are any available slots for the day.\n */\nfunction isDayAvailable(day: Date, availableDates: Date[]): boolean {\n  // Note that slot start and end time may or may not be in UTC.\n  return availableDates.some((availableDate) => isSameDay(availableDate, day));\n}\n", "/* Sizes the calendar as a whole, so the month row and the grid under it stay the same\n   width and the month buttons sit over the last column. */\n.root {\n  min-width: 260px;\n  max-width: 350px;\n}\n\n/* Mantine fills a disabled ActionIcon, which a subtle one has no fill to fall back from. */\n.monthButton:disabled {\n  background-color: transparent;\n}\n\n.table {\n  width: 100%;\n  table-layout: fixed;\n  border-collapse: collapse;\n  user-select: none;\n\n  & th {\n    font-weight: normal;\n    font-size: 11px;\n    padding: 8px 2px;\n    text-align: center;\n  }\n\n  & td {\n    padding: 2px;\n    text-align: center;\n  }\n\n  & td button {\n    width: 100%;\n    max-width: 44px;\n    height: auto;\n    aspect-ratio: 1;\n    margin: 0 auto;\n    color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));\n    font-size: 16px;\n    font-weight: normal;\n    text-align: center;\n    padding: 0;\n    background-color: transparent;\n    border: 0;\n    border-radius: 50%;\n    cursor: pointer;\n  }\n\n  & td button:hover {\n    background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));\n  }\n\n  & td button.available {\n    background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n    color: var(--mantine-color-text);\n    font-weight: 500;\n  }\n\n  & td button.available:hover {\n    background-color: light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-3));\n  }\n\n  & td button:disabled,\n  & td button:disabled:hover {\n    background-color: transparent;\n    cursor: default;\n    color: light-dark(var(--mantine-color-gray-4), var(--mantine-color-dark-4));\n    font-weight: normal;\n  }\n\n  & td button.selected:not(:disabled),\n  & td button.selected:not(:disabled):hover {\n    background-color: var(--mantine-primary-color-filled);\n    color: var(--mantine-color-white);\n    font-weight: 500;\n  }\n\n  & td.inRange {\n    background-color: var(--mantine-primary-color-light);\n  }\n\n  & td.rangeOpens {\n    border-top-left-radius: 999px;\n    border-bottom-left-radius: 999px;\n  }\n\n  & td.rangeCloses {\n    border-top-right-radius: 999px;\n    border-bottom-right-radius: 999px;\n  }\n}\n\n/* A finger dragging out a range must not scroll the page out from under it.\n   Only calendars that take ranges give up the scroll. */\n.table.selectsRanges td button {\n  touch-action: none;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Returns a month display string (e.g. \"January 2020\").\n * @param date - Any date within the month.\n * @returns The month display string (e.g. \"January 2020\")\n */\nexport function getMonthString(date: Date): string {\n  return date.toLocaleString('default', { month: 'long' }) + ' ' + date.getFullYear();\n}\n\nexport function getStartMonth(): Date {\n  return startOfMonth(new Date());\n}\n\n/**\n * Returns local midnight on the first of a date's month.\n * @param date - Any date within the month.\n * @returns The first day of that month.\n */\nexport function startOfMonth(date: Date): Date {\n  return new Date(date.getFullYear(), date.getMonth(), 1);\n}\n\n/**\n * Returns local midnight of the day a date falls on.\n * @param date - Any instant within the day.\n * @returns The day it falls on, at midnight.\n */\nexport function startOfDay(date: Date): Date {\n  return new Date(date.getFullYear(), date.getMonth(), date.getDate());\n}\n\n/**\n * Numbers the day a date falls on, so two days can be counted apart.\n *\n * Local midnights are 23 or 25 hours apart across a daylight-saving change \u2014 enough to make a day\n * exactly between two others look nearer to one of them \u2014 so the day is numbered rather than\n * measured. Taking the local day as though it were UTC lands on an exact multiple of a day.\n * @param date - Any instant within the day.\n * @returns A number that steps by exactly one day per day.\n */\nexport function dayNumber(date: Date): number {\n  return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());\n}\n\n/**\n * Returns whether a day falls before another, ignoring the time of day.\n * @param day - Local midnight of the day in question.\n * @param limit - The instant the day is measured against.\n * @returns True when the day ends before the limit.\n */\nexport function isBeforeDay(day: Date, limit: Date): boolean {\n  return day.getTime() < startOfDay(limit).getTime();\n}\n\n/**\n * Puts the ends of a range in order.\n * @param from - The day the range began on.\n * @param to - The day it has reached.\n * @returns The earlier day as the start.\n */\nexport function sortEnds(from: Date, to: Date): { start: Date; end: Date } {\n  return from <= to ? { start: from, end: to } : { start: to, end: from };\n}\n\n/**\n * Returns whether two dates fall on the same day in the local timezone.\n * @param left - The first date.\n * @param right - The second date, which may be absent.\n * @returns True when both dates are present and share a calendar day.\n */\nexport function isSameDay(left: Date, right: Date | undefined): boolean {\n  return (\n    !!right &&\n    left.getFullYear() === right.getFullYear() &&\n    left.getMonth() === right.getMonth() &&\n    left.getDate() === right.getDate()\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useEffect, useRef, useState } from 'react';\nimport { isSameDay, sortEnds } from './CalendarDateInput.utils';\n\nexport interface DayRangeDrag {\n  /** The range being dragged out, if a drag is under way. */\n  readonly range: { readonly start: Date; readonly end: Date } | undefined;\n  /** Begins a drag on a day. */\n  readonly begin: (date: Date) => void;\n  /** Carries the drag under way, if any, out to a day. */\n  readonly extend: (date: Date) => void;\n  /** Whether the click now arriving is the tail of a drag, and so is spent. */\n  readonly consumeClick: () => boolean;\n}\n\n/**\n * Tracks a drag across calendar days, asking for the range it covers on release.\n * @param onSelectRange - Called with the range a finished drag covered. A drag\n * is only tracked when this is given.\n * @returns The drag under way and the handlers that drive it.\n */\nexport function useDayRangeDrag(onSelectRange?: (start: Date, end: Date) => void): DayRangeDrag {\n  const [from, setFrom] = useState<Date>();\n  const [to, setTo] = useState<Date>();\n  // Set when a drag has just ended, to swallow the click that follows it.\n  const dragged = useRef(false);\n\n  useEffect(() => {\n    if (!from) {\n      return undefined;\n    }\n    function finish(): void {\n      if (from && to && !isSameDay(from, to)) {\n        dragged.current = true;\n        const { start, end } = sortEnds(from, to);\n        onSelectRange?.(start, end);\n      }\n      setFrom(undefined);\n      setTo(undefined);\n    }\n    // A drag the browser takes over, to scroll or to hand to another gesture,\n    // never reaches a day to ask for.\n    function abandon(): void {\n      setFrom(undefined);\n      setTo(undefined);\n    }\n    window.addEventListener('pointerup', finish);\n    window.addEventListener('pointercancel', abandon);\n    return () => {\n      window.removeEventListener('pointerup', finish);\n      window.removeEventListener('pointercancel', abandon);\n    };\n  }, [from, to, onSelectRange]);\n\n  return {\n    range: from && to ? sortEnds(from, to) : undefined,\n    begin(date: Date): void {\n      dragged.current = false;\n      if (onSelectRange) {\n        setFrom(date);\n        setTo(date);\n      }\n    },\n    extend(date: Date): void {\n      if (from) {\n        setTo(date);\n      }\n    },\n    consumeClick(): boolean {\n      const wasDrag = dragged.current;\n      dragged.current = false;\n      return wasDrag;\n    },\n  };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Slot } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useMemo } from 'react';\nimport { CalendarDateInput } from '../CalendarDateInput/CalendarDateInput';\n\n/** @deprecated Use CalendarDateInputProps instead. */\nexport interface CalendarInputProps {\n  readonly slots: Slot[];\n  readonly onChangeMonth: (date: Date) => void;\n  readonly onClick: (date: Date) => void;\n}\n\n/**\n * A calendar that marks the days with slots as available.\n * @deprecated Use CalendarDateInput instead, which takes the available dates directly\n * and supports month navigation, a controlled selection, and date ranges.\n * @param props - The Input props.\n * @returns The JSX element to render.\n */\nexport function CalendarInput(props: CalendarInputProps): JSX.Element {\n  const { slots, ...rest } = props;\n  const availableDates = useMemo(() => slots.map((slot) => new Date(slot.start)), [slots]);\n  return <CalendarDateInput {...rest} availableDates={availableDates} />;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { PaperProps } from '@mantine/core';\nimport {\n  ActionIcon,\n  Group,\n  LoadingOverlay,\n  Menu,\n  Paper,\n  Popover,\n  ScrollArea,\n  Skeleton,\n  Stack,\n  Text,\n  TextInput,\n  Title,\n} from '@mantine/core';\nimport { useResizeObserver } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport type { ProfileResource, WithId } from '@medplum/core';\nimport { getDisplayString, getReferenceString, normalizeErrorString } from '@medplum/core';\nimport type { Attachment, Bundle, Communication, DocumentReference, Reference } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl, useMedplum, useResource, useSubscription } from '@medplum/react-hooks';\nimport {\n  IconArrowRight,\n  IconDots,\n  IconDownload,\n  IconFileExport,\n  IconFileText,\n  IconPaperclip,\n  IconX,\n} from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Form } from '../../Form/Form';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './BaseChat.module.css';\nimport { DocumentPicker } from './DocumentPicker';\n\n/**\n * Returns the URL only when its scheme is http or https, blocking javascript: / data: XSS vectors.\n * @param url - The URL to validate.\n * @returns The URL if safe, otherwise undefined.\n */\nfunction toSafeUrl(url: string | undefined): string | undefined {\n  if (!url) {\n    return undefined;\n  }\n  try {\n    const { protocol } = new URL(url);\n    return protocol === 'https:' || protocol === 'http:' || protocol === 'blob:' ? url : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction showError(message: string): void {\n  showNotification({\n    color: 'red',\n    title: 'Error',\n    message,\n    autoClose: false,\n  });\n}\n\nfunction parseSentTime(communication: Communication): string {\n  return new Date(communication.sent ?? 0).toLocaleDateString(undefined, {\n    year: 'numeric',\n    month: 'short',\n    day: 'numeric',\n  });\n}\n\nfunction upsertCommunications(\n  communications: Communication[],\n  received: Communication[],\n  setCommunications: (communications: Communication[]) => void\n): void {\n  const newCommunications = [...communications];\n  let foundNew = false;\n  for (const comm of received) {\n    const existingIdx = newCommunications.findIndex((c) => c.id === comm.id);\n    if (existingIdx !== -1) {\n      newCommunications[existingIdx] = comm;\n    } else {\n      newCommunications.push(comm);\n      foundNew = true;\n    }\n  }\n\n  if (foundNew) {\n    newCommunications.sort((a, b) => {\n      if (!a.sent && !b.sent) {\n        return 0;\n      }\n      if (!a.sent) {\n        return -1;\n      }\n      if (!b.sent) {\n        return 1;\n      }\n      return a.sent.localeCompare(b.sent);\n    });\n  }\n\n  setCommunications(newCommunications);\n}\n\nexport interface BaseChatProps extends PaperProps {\n  readonly title: string;\n  readonly communications: Communication[];\n  readonly setCommunications: (communications: Communication[]) => void;\n  readonly query: string;\n  readonly sendMessage: (content: string, file?: File, existingDocRef?: DocumentReference) => void;\n  readonly onMessageReceived?: (message: Communication) => void;\n  readonly onMessageUpdated?: (message: Communication) => void;\n  readonly inputDisabled?: boolean;\n  readonly excludeHeader?: boolean;\n  readonly onError?: (err: Error) => void;\n  readonly uploadEnabled?: boolean;\n  readonly attachmentSubjectRef?: Reference;\n  readonly onViewInDocuments?: (reference: Reference<DocumentReference>) => void;\n}\n\n/**\n * BaseChat component for displaying and managing communications.\n *\n * **NOTE: The component automatically filters `Communication` resources where the `sent` property is `undefined`.**\n *\n * @param props - The BaseChat React props.\n * @returns The BaseChat React node.\n */\nexport function BaseChat(props: BaseChatProps): JSX.Element | null {\n  const {\n    title,\n    communications,\n    setCommunications,\n    query,\n    sendMessage,\n    onMessageReceived,\n    onMessageUpdated,\n    inputDisabled,\n    onError,\n    excludeHeader = false,\n    uploadEnabled = false,\n    attachmentSubjectRef,\n    onViewInDocuments,\n    ...paperProps\n  } = props;\n  const medplum = useMedplum();\n\n  const inputRef = useRef<HTMLInputElement>(null);\n  const scrollAreaRef = useRef<HTMLDivElement>(null);\n  const firstScrollRef = useRef(true);\n  const initialLoadRef = useRef(true);\n\n  const [profile, setProfile] = useState(medplum.getProfile());\n  const [reconnecting, setReconnecting] = useState(false);\n  const [loading, setLoading] = useState(true);\n  const [pendingFile, setPendingFile] = useState<File | undefined>(undefined);\n  const [pendingDocRef, setPendingDocRef] = useState<DocumentReference | undefined>(undefined);\n  const [pickerOpen, setPickerOpen] = useState(false);\n  const fileInputRef = useRef<HTMLInputElement>(null);\n\n  if (!loading) {\n    initialLoadRef.current = false;\n  }\n\n  const profileRefStr = useMemo<string>(\n    () => (profile ? getReferenceString(medplum.getProfile() as WithId<ProfileResource>) : ''),\n    [profile, medplum]\n  );\n\n  const searchMessages = useCallback(async (): Promise<void> => {\n    setLoading(true);\n    const searchParams = new URLSearchParams(query);\n    searchParams.append('_sort', '-sent');\n    searchParams.append('sent:missing', 'false');\n    const searchResult = await medplum.searchResources('Communication', searchParams, { cache: 'no-cache' });\n    upsertCommunications(communicationsRef.current, searchResult, setCommunications);\n    setLoading(false);\n  }, [medplum, setCommunications, query]);\n\n  useEffect(() => {\n    searchMessages().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [searchMessages]);\n\n  useSubscription(\n    `Communication?${query}`,\n    (bundle: Bundle) => {\n      const communication = bundle.entry?.[1]?.resource as Communication;\n      upsertCommunications(communicationsRef.current, [communication], setCommunications);\n      // If we are the sender of this message, then we want to skip calling `onMessageUpdated` or `onMessageReceived`\n      if (getReferenceString(communication.sender as Reference) === profileRefStr) {\n        return;\n      }\n      // If this communication already exists, call `onMessageUpdated`\n      if (communicationsRef.current.find((c) => c.id === communication.id)) {\n        onMessageUpdated?.(communication);\n      } else {\n        // Else a new message was created\n        // Call `onMessageReceived` when we are not the sender of a chat message that came in\n        onMessageReceived?.(communication);\n      }\n    },\n    {\n      onWebSocketClose: useCallback(() => {\n        if (!reconnecting) {\n          setReconnecting(true);\n        }\n        showNotification({ color: 'red', message: 'Live chat disconnected. Attempting to reconnect...' });\n      }, [reconnecting]),\n      onWebSocketOpen: useCallback(() => {\n        if (reconnecting) {\n          showNotification({ color: 'green', message: 'Live chat reconnected.' });\n        }\n      }, [reconnecting]),\n      onSubscriptionConnect: useCallback(() => {\n        if (reconnecting) {\n          searchMessages().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n          setReconnecting(false);\n        }\n      }, [reconnecting, searchMessages]),\n      onError: useCallback(\n        (err: Error) => {\n          if (onError) {\n            onError(err);\n          } else {\n            showError(normalizeErrorString(err));\n          }\n        },\n        [onError]\n      ),\n    }\n  );\n\n  const sendMessageInternal = useCallback(\n    (formData: Record<string, string>) => {\n      if (inputDisabled) {\n        return;\n      }\n      const message = formData.message?.trim() ?? '';\n      if (!message && !pendingFile && !pendingDocRef) {\n        return;\n      }\n      if (inputRef.current) {\n        inputRef.current.value = '';\n      }\n      if (fileInputRef.current) {\n        fileInputRef.current.value = '';\n      }\n      sendMessage(message, pendingFile, pendingDocRef);\n      setPendingFile(undefined);\n      setPendingDocRef(undefined);\n      scrollToBottomRef.current = true;\n    },\n    [inputDisabled, sendMessage, pendingFile, pendingDocRef]\n  );\n\n  // Disabled because we can make sure this will trigger an update when local profile !== medplum.getProfile()\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  useEffect(() => {\n    const latestProfile = medplum.getProfile();\n    if (profile?.id !== latestProfile?.id) {\n      setProfile(latestProfile);\n      setCommunications([]);\n    }\n  });\n\n  const [parentRef, parentRect] = useResizeObserver<HTMLDivElement>();\n\n  const communicationsRef = useRef(communications);\n  communicationsRef.current = communications;\n  const prevCommunicationsRef = useRef(communications);\n\n  const scrollToBottomRef = useRef(true);\n\n  useEffect(() => {\n    if (communications !== prevCommunicationsRef.current) {\n      scrollToBottomRef.current = true;\n    }\n    prevCommunicationsRef.current = communications;\n  }, [communications]);\n\n  useEffect(() => {\n    if (scrollToBottomRef.current) {\n      if (scrollAreaRef.current?.scrollTo) {\n        scrollAreaRef.current.scrollTo({\n          top: scrollAreaRef.current.scrollHeight,\n          // We want to skip scrolling through the whole chat on initial load,\n          // Then every time after we will do the \"smooth scroll\"\n          ...(firstScrollRef.current ? { duration: 0 } : { behavior: 'smooth' }),\n        });\n        firstScrollRef.current = false;\n        scrollToBottomRef.current = false;\n      }\n    }\n  });\n\n  const myLastDeliveredId = useMemo<string>(() => {\n    let i = communications.length;\n\n    while (i--) {\n      const comm = communications[i];\n      if (comm.sender?.reference === profileRefStr && comm.received) {\n        return comm.id as string;\n      }\n    }\n\n    return '';\n  }, [communications, profileRefStr]);\n\n  if (!profile) {\n    return null;\n  }\n\n  return (\n    <Paper className={classes.chatPaper} p={0} radius=\"md\" {...paperProps}>\n      {!excludeHeader && (\n        <Title order={2} className={classes.chatTitle}>\n          {title}\n        </Title>\n      )}\n      <div className={classes.chatBody} ref={parentRef}>\n        {initialLoadRef.current ? (\n          <Stack key=\"skeleton-chat-messages\" align=\"stretch\" mt=\"lg\">\n            <Group justify=\"flex-start\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n              <Skeleton height={38} circle ml=\"md\" />\n              <ChatBubbleSkeleton alignment=\"left\" parentWidth={parentRect.width} />\n            </Group>\n            <Group justify=\"flex-end\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n              <ChatBubbleSkeleton alignment=\"right\" parentWidth={parentRect.width} />\n              <Skeleton height={38} circle mr=\"md\" />\n            </Group>\n            <Group justify=\"flex-start\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n              <Skeleton height={38} circle ml=\"md\" />\n              <ChatBubbleSkeleton alignment=\"left\" parentWidth={parentRect.width} />\n            </Group>\n          </Stack>\n        ) : (\n          <ScrollArea viewportRef={scrollAreaRef} className={classes.chatScrollArea} h={parentRect.height}>\n            {/* We don't wrap our scrollarea or scrollarea children with this overlay since it seems to break the rendering of the virtual scroll element */}\n            {/* Instead we manually set the width and height to match the parent and use absolute positioning */}\n            <LoadingOverlay\n              visible={loading || reconnecting}\n              style={{ width: parentRect.width, height: parentRect.height, position: 'absolute', zIndex: 1 }}\n            />\n            {communications.map((c, i) => {\n              const prevCommunication = i > 0 ? communications[i - 1] : undefined;\n              const prevCommTime = prevCommunication ? parseSentTime(prevCommunication) : undefined;\n              const currCommTime = parseSentTime(c);\n              const showDelivered = !!c.received && c.id === myLastDeliveredId;\n              const payloads = c.payload ?? [];\n              const contentRef = payloads.find((p) => p.contentReference)?.contentReference;\n              const contentAttachment = payloads.find((p) => p.contentAttachment)?.contentAttachment;\n              const hasAttachment = !!(contentRef || contentAttachment);\n              const isSender = c.sender?.reference === profileRefStr;\n              const menu = hasAttachment ? (\n                <ChatBubbleMenu\n                  contentRef={contentRef}\n                  contentAttachment={contentAttachment}\n                  onViewInDocuments={onViewInDocuments}\n                />\n              ) : null;\n              return (\n                <Stack key={`${c.id}--${c.meta?.versionId ?? 'no-version'}`} align=\"stretch\">\n                  {(!prevCommTime || currCommTime !== prevCommTime) && (\n                    <Text fz=\"xs\" ta=\"center\">\n                      {currCommTime}\n                    </Text>\n                  )}\n                  {isSender ? (\n                    <Group justify=\"flex-end\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n                      <div className={classes.chatBubbleMenu}>{menu}</div>\n                      <ChatBubble alignment=\"right\" communication={c} showDelivered={showDelivered} />\n                      <ResourceAvatar\n                        radius=\"xl\"\n                        color=\"orange\"\n                        value={c.sender}\n                        mb={!showDelivered ? 'sm' : undefined}\n                      />\n                    </Group>\n                  ) : (\n                    <Group justify=\"flex-start\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n                      <ResourceAvatar radius=\"xl\" value={c.sender} mb=\"sm\" />\n                      <ChatBubble alignment=\"left\" communication={c} />\n                      <div className={classes.chatBubbleMenu}>{menu}</div>\n                    </Group>\n                  )}\n                </Stack>\n              );\n            })}\n          </ScrollArea>\n        )}\n      </div>\n      <div className={classes.chatInputContainer}>\n        {(pendingFile || pendingDocRef) && (\n          <Group className={classes.chatPendingFile} gap={4} align=\"center\" wrap=\"nowrap\">\n            {pendingDocRef ? <IconFileText size=\"0.75rem\" /> : <IconPaperclip size=\"0.75rem\" />}\n            <Text fz=\"xs\" c=\"dimmed\" flex={1} truncate>\n              {pendingDocRef\n                ? (pendingDocRef.description ?? pendingDocRef.content?.[0]?.attachment?.title ?? 'Document')\n                : pendingFile?.name}\n            </Text>\n            <ActionIcon\n              size=\"xs\"\n              variant=\"subtle\"\n              color=\"red\"\n              onClick={() => {\n                setPendingDocRef(undefined);\n                setPendingFile(undefined);\n                if (fileInputRef.current) {\n                  fileInputRef.current.value = '';\n                }\n              }}\n              aria-label=\"Remove attachment\"\n            >\n              <IconX size=\"0.75rem\" />\n            </ActionIcon>\n          </Group>\n        )}\n        <input\n          ref={fileInputRef}\n          type=\"file\"\n          style={{ display: 'none' }}\n          disabled={inputDisabled}\n          onChange={(e) => {\n            const file = e.target.files?.[0];\n            if (file) {\n              setPendingFile(file);\n              setPendingDocRef(undefined);\n            }\n          }}\n        />\n        <Form onSubmit={sendMessageInternal}>\n          <TextInput\n            ref={inputRef}\n            name=\"message\"\n            placeholder={!inputDisabled ? 'Type a message...' : 'Replies are disabled'}\n            radius=\"xl\"\n            leftSectionWidth={42}\n            rightSectionWidth={42}\n            disabled={inputDisabled}\n            leftSection={\n              !inputDisabled && uploadEnabled ? (\n                <Popover\n                  opened={pickerOpen}\n                  onChange={setPickerOpen}\n                  position=\"top-start\"\n                  withArrow\n                  shadow=\"md\"\n                  withinPortal\n                >\n                  <Popover.Target>\n                    <ActionIcon\n                      onClick={() => setPickerOpen((o) => !o)}\n                      size=\"1.5rem\"\n                      radius=\"xl\"\n                      color={pendingFile || pendingDocRef ? 'blue' : 'gray'}\n                      variant={pendingFile || pendingDocRef ? 'filled' : 'subtle'}\n                      aria-label=\"Attach file\"\n                    >\n                      <IconPaperclip size=\"1rem\" stroke={1.5} />\n                    </ActionIcon>\n                  </Popover.Target>\n                  <Popover.Dropdown p={0}>\n                    <DocumentPicker\n                      subjectRef={attachmentSubjectRef}\n                      onSelect={(doc) => {\n                        setPendingDocRef(doc);\n                        setPendingFile(undefined);\n                        setPickerOpen(false);\n                      }}\n                      onUpload={() => {\n                        setPickerOpen(false);\n                        fileInputRef.current?.click();\n                      }}\n                    />\n                  </Popover.Dropdown>\n                </Popover>\n              ) : undefined\n            }\n            rightSection={\n              !inputDisabled ? (\n                <ActionIcon\n                  type=\"submit\"\n                  size=\"1.5rem\"\n                  radius=\"xl\"\n                  color=\"blue\"\n                  variant=\"filled\"\n                  aria-label=\"Send message\"\n                >\n                  <IconArrowRight size=\"1rem\" stroke={1.5} />\n                </ActionIcon>\n              ) : undefined\n            }\n          />\n        </Form>\n      </div>\n    </Paper>\n  );\n}\n\ninterface ChatBubbleProps {\n  readonly communication: Communication;\n  readonly alignment: 'left' | 'right';\n  readonly showDelivered?: boolean;\n}\n\nfunction ChatBubble(props: ChatBubbleProps): JSX.Element {\n  const { communication, alignment, showDelivered } = props;\n  const payloads = communication.payload ?? [];\n  const textContent = payloads.find((p) => p.contentString)?.contentString ?? '';\n  const contentRef = payloads.find((p) => p.contentReference)?.contentReference;\n  const attachment = payloads.find((p) => p.contentAttachment)?.contentAttachment;\n  const sentTime = new Date(communication.sent ?? -1);\n  const seenTime = new Date(communication.received ?? -1);\n  const senderResource = useResource(communication.sender);\n  return (\n    <div className={classes.chatBubbleOuterWrap}>\n      <Text\n        fz=\"xs\"\n        mb=\"xs\"\n        fw={500}\n        className={alignment === 'right' ? classes.chatBubbleNameRight : undefined}\n        aria-label=\"Sender name\"\n      >\n        {senderResource ? getDisplayString(senderResource) : '[Unknown sender]'}\n        &nbsp;&middot;&nbsp;\n        <Text span c=\"dimmed\" fz=\"xs\">\n          {Number.isNaN(sentTime.getTime())\n            ? ''\n            : sentTime.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' })}\n        </Text>\n      </Text>\n      <div\n        className={\n          alignment === 'left' ? classes.chatBubbleLeftAlignedInnerWrap : classes.chatBubbleRightAlignedInnerWrap\n        }\n      >\n        <div className={classes.chatBubble}>\n          {textContent && <span>{textContent}</span>}\n          {contentRef && <ChatBubbleDocumentReference reference={contentRef} hasText={!!textContent} />}\n          {attachment && <ChatBubbleAttachment attachment={attachment} hasText={!!textContent} />}\n        </div>\n      </div>\n      {showDelivered && (\n        <div style={{ textAlign: 'right' }}>\n          Delivered {seenTime.getHours()}:{seenTime.getMinutes().toString().length === 1 ? '0' : ''}\n          {seenTime.getMinutes()}\n        </div>\n      )}\n    </div>\n  );\n}\n\ninterface ChatBubbleAttachmentProps {\n  readonly attachment: Attachment;\n  readonly hasText: boolean;\n}\n\nfunction ChatBubbleAttachment({ attachment, hasText }: ChatBubbleAttachmentProps): JSX.Element {\n  return (\n    <div className={hasText ? classes.chatBubbleAttachmentWithText : undefined}>\n      <Group gap={4} wrap=\"nowrap\">\n        <span className={classes.chatBubbleAttachmentIcon}>\n          <IconPaperclip size=\"0.75rem\" />\n        </span>\n        <Text fz=\"xs\" truncate>\n          {attachment.title ?? 'File attached'}\n        </Text>\n      </Group>\n    </div>\n  );\n}\n\ninterface ChatBubbleDocumentReferenceProps {\n  readonly reference: Reference;\n  readonly hasText: boolean;\n}\n\nfunction ChatBubbleDocumentReference({ reference, hasText }: ChatBubbleDocumentReferenceProps): JSX.Element | null {\n  const docRef = useResource<DocumentReference>(reference as Reference<DocumentReference>);\n  const attachment = docRef?.content?.[0]?.attachment;\n  if (!attachment) {\n    return null;\n  }\n  return <ChatBubbleAttachment attachment={attachment} hasText={hasText} />;\n}\n\ninterface ChatBubbleMenuProps {\n  readonly contentRef?: Reference;\n  readonly contentAttachment?: Attachment;\n  readonly onViewInDocuments?: (reference: Reference<DocumentReference>) => void;\n}\n\nfunction ChatBubbleMenu({ contentRef, contentAttachment, onViewInDocuments }: ChatBubbleMenuProps): JSX.Element {\n  const docRef = useResource<DocumentReference>(contentRef as Reference<DocumentReference> | undefined);\n  const attachment = contentRef ? docRef?.content?.[0]?.attachment : contentAttachment;\n  const cachedUrl = useCachedBinaryUrl(attachment?.url);\n\n  const handleDownload = (): void => {\n    // Navigation requests don't include an Origin header so CORS never applies.\n    // fetch() / medplum.download() both send Origin which CloudFront rejects.\n    const href = toSafeUrl(cachedUrl ?? attachment?.url);\n    if (!href) {\n      return;\n    }\n    window.open(href, '_blank', 'noopener,noreferrer');\n  };\n\n  return (\n    <Menu withinPortal position=\"bottom-start\" shadow=\"md\">\n      <Menu.Target>\n        <ActionIcon variant=\"outline\" color=\"gray\" radius=\"xl\" size=\"sm\" aria-label=\"Attachment options\">\n          <IconDots size=\"0.75rem\" />\n        </ActionIcon>\n      </Menu.Target>\n      <Menu.Dropdown>\n        {contentRef && onViewInDocuments && (\n          <Menu.Item\n            leftSection={<IconFileExport size=\"0.9rem\" />}\n            onClick={() => onViewInDocuments(contentRef as Reference<DocumentReference>)}\n          >\n            View in Documents\n          </Menu.Item>\n        )}\n        <Menu.Item leftSection={<IconDownload size=\"0.9rem\" />} onClick={handleDownload}>\n          Download\n        </Menu.Item>\n      </Menu.Dropdown>\n    </Menu>\n  );\n}\n\nexport interface ChatBubbleSkeletonProps {\n  readonly alignment: 'left' | 'right';\n  readonly parentWidth: number;\n}\n\nfunction ChatBubbleSkeleton(props: ChatBubbleSkeletonProps): JSX.Element {\n  const { alignment, parentWidth } = props;\n  return (\n    <div className={classes.chatBubbleOuterWrap}>\n      <div className={classes.chatBubbleName} aria-label=\"Placeholder sender name\">\n        <div style={{ position: 'relative' }}>\n          <Skeleton\n            height={14}\n            width=\"100px\"\n            radius=\"l\"\n            ml={alignment === 'left' ? 'sm' : undefined}\n            style={alignment === 'right' ? { position: 'absolute', right: 5, top: -15 } : undefined}\n          />\n        </div>\n      </div>\n      <div\n        className={\n          alignment === 'left' ? classes.chatBubbleLeftAlignedInnerWrap : classes.chatBubbleRightAlignedInnerWrap\n        }\n      >\n        <div className={classes.chatBubble}>\n          <Skeleton height={14} width={parentWidth * 0.5} radius=\"l\" />\n        </div>\n      </div>\n    </div>\n  );\n}\n", ".chatPaper {\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.chatTitle {\n  background-color: light-dark(var(--mantine-color-blue-7), var(--mantine-color-blue-8));\n  color: light-dark(var(--mantine-color-white), var(--mantine-color-gray-3));\n  font-size: var(--mantine-font-size-sm);\n  font-weight: 500;\n  padding: var(--mantine-spacing-sm);\n  user-select: none;\n}\n\n.chatBody {\n  background-color: var(--mantine-color-body);\n  flex: 1;\n  min-height: 0;\n  position: relative;\n}\n\n.chatScrollArea {\n  padding: var(--mantine-spacing-xs);\n}\n\n.chatInputContainer {\n  background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n  flex-shrink: 0;\n  padding: 6px 8px;\n  position: relative;\n}\n\n.chatPendingFile {\n  position: absolute;\n  bottom: 100%;\n  left: 0;\n  right: 0;\n  background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n  border-top: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-3));\n  padding: 4px 8px;\n}\n\n.chatBubbleOuterWrap {\n  max-width: 75%;\n  padding-bottom: 10px;\n}\n\n.chatBubbleRightAlignedInnerWrap {\n  display: flex;\n  flex-direction: row-reverse;\n}\n\n.chatBubbleLeftAlignedInnerWrap {\n  display: flex;\n  flex-direction: row;\n}\n\n.chatBubble {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-blue-7));\n  border-radius: var(--mantine-radius-lg);\n  padding: var(--mantine-spacing-sm);\n  min-width: 40px;\n  color: light-dark(var(--mantine-color-black), var(--mantine-color-gray-2));\n\n  & p {\n    margin-top: 0.25rem;\n    margin-bottom: 0.25rem;\n  }\n\n  & pre {\n    max-width: 280px;\n    overflow: auto;\n  }\n}\n\n.chatBubbleNameRight {\n  text-align: right;\n}\n\n.chatPendingFile {\n  position: absolute;\n  bottom: 100%;\n  left: 0;\n  right: 0;\n  background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n  border-top: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-3));\n  padding: 4px 8px;\n}\n\n.chatBubbleAttachmentWithText {\n  margin-top: 6px;\n}\n\n.chatBubbleAttachmentIcon {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n}\n\n.chatBubbleMenu {\n  align-self: center;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Divider, Loader, Stack, Text, TextInput, UnstyledButton } from '@mantine/core';\nimport { useDebouncedCallback } from '@mantine/hooks';\nimport { getReferenceString } from '@medplum/core';\nimport type { DocumentReference, Reference } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconFileText, IconPaperclip } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\n\nexport interface DocumentPickerProps {\n  readonly subjectRef?: Reference;\n  readonly onSelect: (doc: DocumentReference) => void;\n  readonly onUpload: () => void;\n}\n\nexport function DocumentPicker({ subjectRef, onSelect, onUpload }: DocumentPickerProps): JSX.Element {\n  const medplum = useMedplum();\n  const [search, setSearch] = useState('');\n  const [docs, setDocs] = useState<DocumentReference[]>([]);\n  const [loading, setLoading] = useState(true);\n  const subjectRefStr = subjectRef ? getReferenceString(subjectRef) : undefined;\n\n  const fetchDocs = useDebouncedCallback(async (query: string) => {\n    setLoading(true);\n    try {\n      const params = new URLSearchParams();\n      if (subjectRefStr) {\n        params.set('subject', subjectRefStr);\n      }\n      if (query.trim()) {\n        params.set('description:contains', query.trim());\n      }\n      params.set('_sort', '-date');\n      params.set('_count', '5');\n      const results = await medplum.searchResources('DocumentReference', params);\n      setDocs([...results]);\n    } catch (err) {\n      console.error(err);\n    } finally {\n      setLoading(false);\n    }\n  }, 300);\n\n  useEffect(() => {\n    fetchDocs(search);\n  }, [fetchDocs, search]);\n\n  const getDocName = (doc: DocumentReference): string =>\n    doc.description ?? doc.content?.[0]?.attachment?.title ?? 'Untitled';\n\n  return (\n    <Stack gap={0} w={280}>\n      <Text fw={500} fz=\"sm\" px=\"sm\" pt=\"sm\" pb=\"xs\">\n        Attachments\n      </Text>\n      <Box px=\"sm\" pb=\"xs\">\n        <TextInput\n          placeholder=\"Search for a Document...\"\n          size=\"xs\"\n          value={search}\n          onChange={(e) => setSearch(e.currentTarget.value)}\n        />\n      </Box>\n      <Divider />\n      {loading ? (\n        <Box py=\"sm\" style={{ display: 'flex', justifyContent: 'center' }}>\n          <Loader size=\"xs\" />\n        </Box>\n      ) : (\n        <Stack gap={0}>\n          {docs.map((doc) => (\n            <UnstyledButton\n              key={doc.id}\n              px=\"sm\"\n              py=\"xs\"\n              onClick={() => onSelect(doc)}\n              style={{ display: 'flex', alignItems: 'center', gap: 8 }}\n            >\n              <IconFileText size=\"1rem\" style={{ flexShrink: 0, color: 'var(--mantine-color-blue-6)' }} />\n              <Text fz=\"sm\" truncate>\n                {getDocName(doc)}\n              </Text>\n            </UnstyledButton>\n          ))}\n          {docs.length === 0 && (\n            <Text fz=\"xs\" c=\"dimmed\" px=\"sm\" py=\"xs\">\n              No documents found\n            </Text>\n          )}\n        </Stack>\n      )}\n      <Divider />\n      <UnstyledButton px=\"sm\" py=\"xs\" onClick={onUpload} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>\n        <IconPaperclip size=\"1rem\" style={{ flexShrink: 0, color: 'var(--mantine-color-gray-6)' }} />\n        <Text fz=\"sm\" c=\"dimmed\">\n          Upload an image, pdf, etc.\n        </Text>\n      </UnstyledButton>\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon } from '@mantine/core';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown, IconChevronUp } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport classes from './ChatModal.module.css';\n\nexport interface ChatModalProps {\n  readonly open?: boolean;\n  readonly children: ReactNode;\n}\n\nexport function ChatModal(props: ChatModalProps): JSX.Element | null {\n  const { open, children } = props;\n  const profile = useMedplumProfile();\n  const [opened, setOpened] = useState(open ?? false);\n\n  useEffect(() => {\n    setOpened((prevVal) => open ?? prevVal);\n  }, [open]);\n\n  if (!profile) {\n    return null;\n  }\n\n  return (\n    <>\n      {opened && <div className={classes.chatModalContainer}>{children}</div>}\n      {opened ? (\n        <div className={classes.iconContainer}>\n          <ActionIcon\n            className={classes.icon}\n            color=\"blue\"\n            size=\"lg\"\n            radius=\"xl\"\n            variant=\"outline\"\n            onClick={() => setOpened(false)}\n            aria-label=\"Close chat\"\n          >\n            <IconChevronDown size=\"1.625rem\" />\n          </ActionIcon>\n        </div>\n      ) : (\n        <div className={classes.iconContainer}>\n          <ActionIcon\n            className={classes.icon}\n            color=\"blue\"\n            size=\"lg\"\n            radius=\"xl\"\n            variant=\"outline\"\n            onClick={() => setOpened(true)}\n            aria-label=\"Open chat\"\n          >\n            <IconChevronUp size=\"1.625rem\" />\n          </ActionIcon>\n        </div>\n      )}\n    </>\n  );\n}\n", ".iconContainer {\n  position: fixed;\n  bottom: 0.5rem;\n  right: 0.5rem;\n  z-index: 100px;\n}\n\n.icon {\n  background-color: light-dark(var(--mantine-color-white), var(--mantine-color-dark-7));\n  box-shadow:\n    0 0.2rem 0.4rem rgba(0, 0, 0, 0.05),\n    0 0.2rem 0.4rem rgba(0, 0, 0, 0.1);\n}\n\n.chatModalContainer {\n  position: fixed;\n  bottom: 3rem;\n  right: 0.5rem;\n  z-index: 100px;\n  width: 400px;\n  height: 450px;\n  max-height: 450px;\n  overflow: hidden;\n  border-radius: var(--mantine-radius-md);\n  box-shadow:\n    0 0.2rem 0.4rem rgba(0, 0, 0, 0.05),\n    0 0.2rem 0.4rem rgba(0, 0, 0, 0.1);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { createReference, formatCodeableConcept, getReferenceString } from '@medplum/core';\nimport type { Communication, CommunicationPayload, DocumentReference, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile, usePrevious } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { BaseChat } from '../BaseChat/BaseChat';\n\nexport interface ThreadChatProps {\n  readonly thread: Communication;\n  readonly title?: string;\n  readonly onMessageSent?: (message: Communication) => void;\n  readonly inputDisabled?: boolean;\n  readonly excludeHeader?: boolean;\n  readonly uploadEnabled?: boolean;\n  readonly onError?: (err: Error) => void;\n  readonly onViewInDocuments?: (reference: Reference<DocumentReference>) => void;\n}\n\nexport function ThreadChat(props: ThreadChatProps): JSX.Element | null {\n  const { thread, title, onMessageSent, inputDisabled, excludeHeader, uploadEnabled, onError, onViewInDocuments } =\n    props;\n  const medplum = useMedplum();\n  const profile = useMedplumProfile();\n  const prevThreadId = usePrevious(thread?.id);\n  const [communications, setCommunications] = useState<Communication[]>([]);\n\n  const profileRef = useMemo(() => (profile ? createReference(profile) : undefined), [profile]);\n  const threadRef = useMemo(() => createReference(thread), [thread]);\n\n  useEffect(() => {\n    if (thread?.id !== prevThreadId) {\n      setCommunications([]);\n    }\n  }, [thread?.id, prevThreadId]);\n\n  const sendMessage = useCallback(\n    (message: string, file?: File, existingDocRef?: DocumentReference) => {\n      const profileRefStr = profileRef ? getReferenceString(profileRef) : undefined;\n      if (!profileRefStr) {\n        return;\n      }\n\n      const buildAndSend = async (): Promise<void> => {\n        const payload: CommunicationPayload[] = [];\n        if (message) {\n          payload.push({ contentString: message });\n        }\n        if (existingDocRef) {\n          payload.push({ contentReference: createReference(existingDocRef) });\n        } else if (file) {\n          const docRef = await medplum.createDocumentReference({\n            data: file,\n            contentType: file.type || 'application/octet-stream',\n            filename: file.name,\n            additionalFields: {\n              ...(thread.subject ? { subject: thread.subject } : {}),\n              description: file.name,\n            },\n          });\n          payload.push({ contentReference: createReference(docRef) });\n        }\n        const communication = await medplum.createResource<Communication>({\n          resourceType: 'Communication',\n          status: 'in-progress',\n          sender: profileRef,\n          recipient: thread.recipient?.filter((ref) => getReferenceString(ref) !== profileRefStr) ?? [],\n          sent: new Date().toISOString(),\n          payload,\n          partOf: [threadRef],\n          subject: thread.subject,\n        });\n        setCommunications([...communications, communication]);\n        // Touch the thread header so its meta.lastUpdated tracks message activity\n        if (thread.id) {\n          try {\n            await medplum.patchResource('Communication', thread.id, [\n              { op: 'add', path: '/sent', value: communication.sent },\n            ]);\n          } catch (err) {\n            onError?.(err as Error);\n          }\n        }\n        onMessageSent?.(communication);\n      };\n\n      buildAndSend().catch(console.error);\n    },\n    [medplum, profileRef, thread, threadRef, communications, onMessageSent, onError]\n  );\n\n  // Currently we only support `delivered` on chats with 2 participants\n  // Normally we would use `useCallback` to memoize a function\n  // But in this case we only want to conditionally pass a function if the thread has 2 participants...\n  // If the thread has 3 or more participants, we do not pass this function; instead we pass undefined\n  const onMessageReceived = useMemo(\n    () =>\n      thread.recipient?.length === 2\n        ? (message: Communication): void => {\n            if (!(message.received && message.status === 'completed')) {\n              medplum\n                .updateResource({\n                  ...message,\n                  received: message.received ?? new Date().toISOString(), // Mark as received if needed\n                  status: 'completed', // Mark as 'read'\n                  // See: https://www.medplum.com/docs/communications/messaging-data-model#communication-lifecycle\n                  // for more info about recommended `Communication` lifecycle\n                })\n                .catch(console.error);\n            }\n          }\n        : undefined,\n    [medplum, thread.recipient?.length]\n  );\n\n  if (!profile) {\n    return null;\n  }\n\n  return (\n    <BaseChat\n      title={title ?? (thread?.topic ? formatCodeableConcept(thread.topic) : '[No thread title]')}\n      communications={communications}\n      setCommunications={setCommunications}\n      query={`part-of=Communication/${thread.id as string}`}\n      sendMessage={sendMessage}\n      onMessageReceived={onMessageReceived}\n      inputDisabled={inputDisabled}\n      excludeHeader={excludeHeader}\n      uploadEnabled={uploadEnabled}\n      onError={onError}\n      attachmentSubjectRef={thread.subject}\n      onViewInDocuments={onViewInDocuments}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { createReference, normalizeErrorString } from '@medplum/core';\nimport type { Communication, Patient, Practitioner, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport { Modal } from '../../Modal/Modal';\nimport { ThreadMessageForm } from './ThreadMessageForm';\n\n/**\n * Props for the NewTopicDialog component.\n * @param subject - The patient to associate with the new thread. When provided and `allowPatientSelection` is false, the patient field is pre-filled and disabled.\n * @param opened - Whether the dialog is open.\n * @param onClose - Callback fired when the dialog is closed.\n * @param onSubmit - Callback fired with the created Communication resource after successful submission.\n * @param allowPatientSelection - When true, the patient field is an editable search input. When false (default), the field is pre-filled from `subject` and disabled. Use true for provider-facing contexts, false for patient-facing apps.\n */\nexport interface NewTopicDialogProps {\n  subject: Reference<Patient> | Patient | undefined;\n  opened: boolean;\n  onClose: () => void;\n  onSubmit?: (communication: Communication) => void;\n  allowPatientSelection?: boolean;\n}\n\nexport const NewTopicDialog = (props: NewTopicDialogProps): JSX.Element => {\n  const { subject, opened, onClose, onSubmit, allowPatientSelection = false } = props;\n  const medplum = useMedplum();\n  const profile = useMedplumProfile();\n  const profileRef = useMemo(() => (profile ? createReference(profile) : undefined), [profile]);\n\n  // Default the signed-in provider as the first practitioner recipient.\n  const initialPractitioners = useMemo<Reference<Practitioner>[]>(\n    () => (profile?.resourceType === 'Practitioner' ? [createReference(profile)] : []),\n    [profile]\n  );\n\n  const [topic, setTopic] = useState('');\n  const [practitioners, setPractitioners] = useState<Reference<Practitioner>[]>(initialPractitioners);\n  const [patient, setPatient] = useState<Reference<Patient> | undefined>(\n    subject ? createReference(subject as Patient) : undefined\n  );\n\n  const handleSubmit = async (): Promise<void> => {\n    // The Next button is disabled until both are set; this guard also narrows `patient`.\n    if (!patient || practitioners.length === 0) {\n      return;\n    }\n\n    const communication: Communication = {\n      resourceType: 'Communication',\n      status: 'in-progress',\n      subject: patient,\n      sender: profileRef,\n      recipient: [patient, ...practitioners],\n      topic: topic ? { text: topic } : undefined,\n    };\n\n    try {\n      const createdCommunication = await medplum.createResource(communication);\n\n      onClose();\n      onSubmit?.(createdCommunication);\n    } catch (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n    }\n  };\n\n  return (\n    <Modal\n      opened={opened}\n      onClose={onClose}\n      title=\"New Message\"\n      size=\"md\"\n      actions={\n        <Button onClick={handleSubmit} disabled={!patient || practitioners.length === 0}>\n          Next\n        </Button>\n      }\n    >\n      <ThreadMessageForm\n        defaultPractitioners={initialPractitioners}\n        onPractitionersChange={setPractitioners}\n        topic={topic}\n        onTopicChange={setTopic}\n        defaultPatient={patient}\n        onPatientChange={setPatient}\n        allowPatientSelection={allowPatientSelection}\n      />\n    </Modal>\n  );\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ModalProps as MantineModalProps } from '@mantine/core';\nimport { Modal as MantineModal } from '@mantine/core';\nimport { IconX } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { CSSProperties, JSX, ReactNode } from 'react';\nimport { Form } from '../Form/Form';\nimport classes from './Modal.module.css';\n\n/**\n * Keeps the flex chain intact across the form element, so the footer stays pinned. Inline rather\n * than in the CSS module because `Form` takes a style but not a className.\n */\nconst formStyle: CSSProperties = {\n  display: 'flex',\n  flexDirection: 'column',\n  flex: '1 1 auto',\n  minHeight: 0,\n};\n\n/**\n * Props for {@link Modal}.\n */\nexport interface ModalProps extends Omit<MantineModalProps, 'children' | 'onSubmit' | 'scrollAreaComponent'> {\n  /** Modal body, rendered in the scrolling region between the header and the footer. */\n  readonly children: ReactNode;\n  /**\n   * Buttons pinned to the bottom edge of the modal above a full-bleed border.\n   * They stretch to the full width with the primary action first; wrap them in a\n   * `Group justify=\"flex-end\"` for a right-aligned row instead. Omit for modals that only display\n   * content - the footer and its border are then not rendered.\n   */\n  readonly actions?: ReactNode;\n  /**\n   * Wraps the body and the footer in a {@link Form}, so a `SubmitButton` in\n   * `actions` submits the named inputs in `children`. A `SubmitButton` without this has no form to\n   * submit and does nothing.\n   */\n  readonly onSubmit?: (formData: Record<string, string>) => Promise<void> | void;\n  /**\n   * Fixed body height as a CSS length, e.g. `'60vh'`, for modals whose content\n   * is a fixed layout rather than a form that should size to its fields. Omit to size to the content.\n   */\n  readonly bodyHeight?: string;\n}\n\n/**\n * A modal with the standard Medplum chrome: a bold title above a border, one scrolling body, and\n * action buttons pinned to the bottom edge. Owns the layout so call sites pass content and actions\n * rather than assembling a shell out of `Stack`, `Divider` and `styles` overrides.\n *\n * All other Mantine `Modal` props pass through. `scrollAreaComponent` does not, because it inserts\n * an element between the content and the body that breaks the flex chain the pinned footer needs.\n * @param props - The Modal React props.\n * @returns The Modal React node.\n */\nexport function Modal(props: ModalProps): JSX.Element {\n  const {\n    children,\n    actions,\n    onSubmit,\n    bodyHeight,\n    classNames,\n    style,\n    closeButtonProps,\n    centered = true,\n    padding = 'lg',\n    radius = 'md',\n    ...modalProps\n  } = props;\n\n  const contents = (\n    <>\n      <div className={classes.scroll}>{children}</div>\n      {actions && <div className={classes.footer}>{actions}</div>}\n    </>\n  );\n\n  return (\n    <MantineModal\n      {...modalProps}\n      centered={centered}\n      padding={padding}\n      radius={radius}\n      closeButtonProps={{\n        'aria-label': 'Close',\n        radius: 'xl',\n        icon: <IconX size={16} stroke={2} />,\n        ...closeButtonProps,\n      }}\n      classNames={{\n        ...classNames,\n        // The slot rules are scoped under `.modal` in the CSS module, so the root class has to\n        // land for any of them to apply.\n        root: cx(classes.modal, classNames?.root),\n        content: cx(classes.content, classNames?.content),\n        header: cx(classes.header, classNames?.header),\n        title: cx(classes.title, classNames?.title),\n        close: cx(classes.close, classNames?.close),\n        body: cx(classes.body, classNames?.body),\n      }}\n      style={bodyHeight ? [style, { '--medplum-modal-body-height': bodyHeight }] : style}\n    >\n      {onSubmit ? (\n        <Form onSubmit={onSubmit} style={formStyle}>\n          {contents}\n        </Form>\n      ) : (\n        contents\n      )}\n    </MantineModal>\n  );\n}\n", "/*\n * The `.modal` ancestor is load-bearing, not redundant scoping: these rules override Mantine's own\n * slot styles, which are a single class each, so they need two classes to win. Removing the\n * ancestor drops the specificity to a tie and Mantine's values apply instead.\n *\n * `.modal` is the root slot, an ancestor of every other slot. The classes below are the slot\n * classes themselves, so each selector matches exactly one element.\n */\n.modal .content {\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n.modal .header {\n  flex: 0 0 auto;\n  position: static;\n  padding-block: var(--mantine-spacing-sm);\n  padding-inline-start: var(--mantine-spacing-lg);\n  padding-inline-end: var(--mantine-spacing-sm);\n  border-bottom: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n.modal .title {\n  font-size: var(--mantine-font-size-md);\n  font-weight: 800;\n}\n\n@media (hover: hover) {\n  .modal .close:hover:where(:not(:disabled, [data-disabled])) {\n    background-color: var(--mantine-color-gray-light-hover);\n  }\n}\n\n@media (hover: none) {\n  .modal .close:active:where(:not(:disabled, [data-disabled])) {\n    background-color: var(--mantine-color-gray-light-hover);\n  }\n}\n\n.modal .body {\n  display: flex;\n  flex-direction: column;\n  flex: 1 1 auto;\n  min-height: 0;\n  height: var(--medplum-modal-body-height, auto);\n  padding: 0;\n}\n\n.scroll {\n  flex: 1 1 auto;\n  min-height: 0;\n  min-width: 0;\n  overflow-y: auto;\n  overscroll-behavior: contain;\n  padding: var(--mb-padding, var(--mantine-spacing-lg));\n}\n\n.footer {\n  flex: 0 0 auto;\n  display: flex;\n  flex-direction: column;\n  gap: var(--mantine-spacing-sm);\n  padding: var(--mb-padding, var(--mantine-spacing-lg));\n  border-top: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Stack, Text, TextInput } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport type { Patient, Practitioner, Reference } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { MultiResourceInput } from '../../ResourceInput/MultiResourceInput';\nimport { ResourceInput } from '../../ResourceInput/ResourceInput';\n\n/**\n * Props for the ThreadMessageForm component \u2014 the shared Patient + Practitioner + Topic fields\n * used by the New Message and Message Settings dialogs. The form owns the spacing between its\n * own sections, so call sites drop it in without a wrapping layout element.\n * The patient and practitioner inputs are uncontrolled: the `default*` props seed them on\n * mount only, and later edits are reported through the `on*Change` callbacks. Mount the form\n * only once the defaults are known (both dialogs mount it after the thread is resolved).\n * @param defaultPractitioners - The initial practitioner recipients (init-only, uncontrolled input).\n * @param onPractitionersChange - Called with the new practitioner reference list when the selection changes.\n * @param topic - The current topic text (controlled).\n * @param onTopicChange - Called with the new topic text on every edit.\n * @param defaultPatient - The initial patient (init-only, uncontrolled input).\n * @param onPatientChange - Called with the new patient reference when the selection changes. When omitted, the patient field is read-only.\n * @param allowPatientSelection - When true, the patient field is an editable search input. When false (default), the field is pre-filled from `defaultPatient` and disabled.\n */\nexport interface ThreadMessageFormProps {\n  defaultPractitioners: Reference<Practitioner>[];\n  onPractitionersChange: (practitioners: Reference<Practitioner>[]) => void;\n  topic: string;\n  onTopicChange: (topic: string) => void;\n  defaultPatient?: Reference<Patient>;\n  onPatientChange?: (patient: Reference<Patient> | undefined) => void;\n  allowPatientSelection?: boolean;\n}\n\nexport const ThreadMessageForm = (props: ThreadMessageFormProps): JSX.Element => {\n  const { defaultPractitioners, onPractitionersChange, topic, onTopicChange, defaultPatient, onPatientChange } = props;\n  const allowPatientSelection = props.allowPatientSelection ?? false;\n  return (\n    <Stack gap=\"lg\">\n      <Stack gap={0}>\n        <Text fw={500}>Patient</Text>\n\n        {allowPatientSelection && <Text c=\"dimmed\">Select a patient</Text>}\n\n        <ResourceInput\n          resourceType=\"Patient\"\n          name=\"patient\"\n          required={!!onPatientChange}\n          defaultValue={defaultPatient}\n          disabled={!allowPatientSelection && !!defaultPatient}\n          onChange={(value) => {\n            onPatientChange?.(value ? createReference(value) : undefined);\n          }}\n        />\n      </Stack>\n\n      <Stack gap={0}>\n        <Text fw={500}>Practitioner</Text>\n        <Text c=\"dimmed\">Select one or more practitioners</Text>\n\n        <MultiResourceInput<Practitioner>\n          resourceType=\"Practitioner\"\n          name=\"practitioners\"\n          defaultValue={defaultPractitioners}\n          onChange={(resources) =>\n            onPractitionersChange(resources.map((practitioner) => createReference(practitioner)))\n          }\n        />\n      </Stack>\n\n      <Stack gap={0}>\n        <Text fw={500}>Topic (optional)</Text>\n        <Text c=\"dimmed\">Enter a topic for the message</Text>\n\n        <TextInput placeholder=\"Enter your topic\" value={topic} onChange={(e) => onTopicChange(e.target.value)} />\n      </Stack>\n    </Stack>\n  );\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n  ActionIcon,\n  Checkbox,\n  CloseButton,\n  Group,\n  Indicator,\n  Popover,\n  Stack,\n  Text,\n  TextInput,\n  Tooltip,\n} from '@mantine/core';\nimport { useDebouncedCallback, useDisclosure } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { createReference, formatHumanName, getReferenceString, normalizeErrorString } from '@medplum/core';\nimport type { Patient, Practitioner, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile, useResource } from '@medplum/react-hooks';\nimport { IconUsers } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './ParticipantFilter.module.css';\n\nexport interface ParticipantFilterProps {\n  readonly selectedParticipants: Reference<Patient | Practitioner>[];\n  readonly onFilterChange: (participants: Reference<Patient | Practitioner>[]) => void;\n}\n\nexport function ParticipantFilter(props: ParticipantFilterProps): JSX.Element {\n  const { selectedParticipants, onFilterChange } = props;\n  const [opened, { open, close }] = useDisclosure(false);\n  const [searchQuery, setSearchQuery] = useState('');\n  const [searchResults, setSearchResults] = useState<Reference<Patient | Practitioner>[]>([]);\n  const [isSearching, setIsSearching] = useState(false);\n  const medplum = useMedplum();\n  const profile = useMedplumProfile();\n\n  const currentUserParticipant = useMemo((): Reference<Patient | Practitioner> | undefined => {\n    if (!profile) {\n      return undefined;\n    }\n    return createReference(profile) as Reference<Patient | Practitioner>;\n  }, [profile]);\n\n  const additionalParticipants = useMemo(() => {\n    const currentUserRef = currentUserParticipant?.reference;\n    return selectedParticipants.filter((p) => p.reference !== currentUserRef);\n  }, [selectedParticipants, currentUserParticipant]);\n\n  const debouncedSearch = useDebouncedCallback(async (query: string): Promise<void> => {\n    if (!query.trim()) {\n      setSearchResults([]);\n      return;\n    }\n\n    setIsSearching(true);\n    try {\n      const bundle = await medplum.search('Patient', {\n        _type: 'Patient,Practitioner',\n        name: query,\n        _count: '10',\n      });\n\n      const currentUserRef = currentUserParticipant?.reference;\n\n      const results = (bundle.entry ?? [])\n        .map((entry) => entry.resource as Patient | Practitioner)\n        .filter((resource): resource is Patient | Practitioner => {\n          if (!resource) {\n            return false;\n          }\n          const refString = getReferenceString(resource);\n          return !!refString && refString !== currentUserRef;\n        })\n        .map((resource) => createReference(resource));\n\n      setSearchResults(results);\n    } catch (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n      setSearchResults([]);\n    } finally {\n      setIsSearching(false);\n    }\n  }, 300);\n\n  useEffect(() => {\n    debouncedSearch(searchQuery);\n    return debouncedSearch.cancel;\n  }, [searchQuery, debouncedSearch]);\n\n  const isSelected = (participant: Reference<Patient | Practitioner>): boolean => {\n    return selectedParticipants.some((p) => p.reference === participant.reference);\n  };\n\n  const toggleParticipant = (participant: Reference<Patient | Practitioner>): void => {\n    const newParticipants = isSelected(participant)\n      ? selectedParticipants.filter((p) => p.reference !== participant.reference)\n      : [...selectedParticipants, participant];\n\n    onFilterChange(newParticipants);\n  };\n\n  const removeParticipant = (participant: Reference<Patient | Practitioner>): void => {\n    const newParticipants = selectedParticipants.filter((p) => p.reference !== participant.reference);\n    onFilterChange(newParticipants);\n  };\n\n  // Build display list: current user first, then additional selected, then search results\n  const displayParticipants = useMemo(() => {\n    const result: Reference<Patient | Practitioner>[] = [];\n\n    for (const p of additionalParticipants) {\n      if (!result.some((r) => r.reference === p.reference)) {\n        result.push(p);\n      }\n    }\n\n    if (searchQuery.trim() && searchResults.length > 0) {\n      for (const p of searchResults) {\n        if (currentUserParticipant?.reference === p.reference) {\n          continue;\n        }\n        if (!result.some((r) => r.reference === p.reference)) {\n          result.push(p);\n        }\n      }\n    }\n\n    return result;\n  }, [additionalParticipants, searchQuery, searchResults, currentUserParticipant]);\n\n  const hasActiveFilter = selectedParticipants.length > 0;\n\n  return (\n    <Popover\n      opened={opened}\n      onChange={(o) => !o && close()}\n      position=\"bottom-start\"\n      width={360}\n      shadow=\"md\"\n      radius=\"md\"\n      withinPortal\n    >\n      <Popover.Target>\n        <Tooltip label=\"Message Participants\" position=\"bottom\" openDelay={500} disabled={opened}>\n          <Indicator disabled={!hasActiveFilter} color=\"blue\" size={8} offset={4}>\n            <ActionIcon\n              variant=\"transparent\"\n              onClick={opened ? close : open}\n              radius=\"xl\"\n              size={32}\n              className=\"outline-icon-button\"\n              data-opened={opened || undefined}\n            >\n              <IconUsers size={16} />\n            </ActionIcon>\n          </Indicator>\n        </Tooltip>\n      </Popover.Target>\n\n      <Popover.Dropdown p=\"md\">\n        <Stack gap=\"md\">\n          <Text size=\"xs\" c=\"dimmed\" fw={500}>\n            Message Participants\n          </Text>\n\n          <TextInput\n            placeholder=\"Search for a Patient or Practitioner...\"\n            value={searchQuery}\n            autoFocus\n            onChange={(e) => setSearchQuery(e.target.value)}\n            rightSection={searchQuery ? <CloseButton size=\"sm\" onClick={() => setSearchQuery('')} /> : null}\n          />\n\n          <Stack gap=\"xs\" mah={250} style={{ overflowY: 'auto' }}>\n            {currentUserParticipant && (\n              <ParticipantItem\n                participant={currentUserParticipant}\n                isSelected={isSelected(currentUserParticipant)}\n                isCurrentUser={true}\n                onToggle={() => toggleParticipant(currentUserParticipant)}\n              />\n            )}\n\n            {displayParticipants.map((participant) => (\n              <ParticipantItem\n                key={participant.reference}\n                participant={participant}\n                isSelected={isSelected(participant)}\n                isCurrentUser={false}\n                onToggle={() => toggleParticipant(participant)}\n                onRemove={isSelected(participant) ? () => removeParticipant(participant) : undefined}\n              />\n            ))}\n\n            {isSearching && (\n              <Text size=\"sm\" c=\"dimmed\" ta=\"center\">\n                Searching...\n              </Text>\n            )}\n            {searchQuery.trim() && !isSearching && searchResults.length === 0 && (\n              <Text size=\"sm\" c=\"dimmed\" ta=\"center\">\n                No results found\n              </Text>\n            )}\n          </Stack>\n        </Stack>\n      </Popover.Dropdown>\n    </Popover>\n  );\n}\n\ninterface ParticipantItemProps {\n  readonly participant: Reference<Patient | Practitioner>;\n  readonly isSelected: boolean;\n  readonly isCurrentUser: boolean;\n  readonly onToggle: () => void;\n  readonly onRemove?: () => void;\n}\n\nfunction ParticipantItem(props: ParticipantItemProps): JSX.Element | null {\n  const { participant, isSelected, isCurrentUser, onToggle, onRemove } = props;\n  const patientResource = useResource(participant);\n\n  if (!patientResource) {\n    return null;\n  }\n\n  return (\n    <Group justify=\"space-between\" wrap=\"nowrap\" className={classes.participantItem}>\n      <Group gap=\"sm\" wrap=\"nowrap\" style={{ flex: 1, minWidth: 0 }}>\n        <Checkbox checked={isSelected} onChange={onToggle} />\n        <ResourceAvatar value={participant} radius=\"xl\" size={32} />\n        <Text size=\"sm\" truncate style={{ flex: 1 }}>\n          {formatHumanName(patientResource?.name?.[0] ?? {})}\n          {isCurrentUser && (\n            <Text component=\"span\" c=\"dimmed\" size=\"sm\">\n              {' '}\n              (you)\n            </Text>\n          )}\n        </Text>\n      </Group>\n      {onRemove && <CloseButton size=\"sm\" onClick={onRemove} />}\n    </Group>\n  );\n}\n", ".participantItem {\n  padding: 4px 0;\n}\n\n.participantItem:hover {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-gray-9));\n  border-radius: var(--mantine-radius-sm);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { ActionIcon, Box, Center, Flex, Skeleton, Stack, Text, ThemeIcon, Tooltip } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport type { SearchRequest } from '@medplum/core';\nimport { isReference, normalizeErrorString, Operator, parseSearchRequest } from '@medplum/core';\nimport type { Communication, DocumentReference, Patient, Practitioner, Reference, Resource } from '@medplum/fhirtypes';\nimport { useThreadInbox } from '@medplum/react-hooks';\nimport { IconMessageCircle, IconPlus } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo } from 'react';\nimport type { ListWithDetailPaneTab } from '../../ListWithDetailPane/ListWithDetailPane';\nimport { ListWithDetailPane } from '../../ListWithDetailPane/ListWithDetailPane';\nimport type { PatientSummarySectionConfig } from '../../PatientSummary/PatientSummary.types';\nimport { EditThreadDialog } from './EditThreadDialog';\nimport { NewTopicDialog } from './NewTopicDialog';\nimport { ParticipantFilter } from './ParticipantFilter';\nimport { ThreadDetail } from './ThreadDetail';\nimport classes from './ThreadInbox.module.css';\nimport { ThreadListItem } from './ThreadListItem';\n\n/**\n * ThreadInbox is a component that displays a list of threads and allows the user to select a thread to view.\n * @param query - The query to fetch all communications.\n * @param threadId - The id of the thread to select.\n * @param subject - The default subject when creating a new thread.\n * @param showPatientSummary - Whether to show the patient summary.\n * @param sections - Optional sections configuration for the patient summary.\n * @param patientHeaderLink - Where the patient summary header navigates when clicked. Omit for a static header.\n * @param onNew - A function to handle a new thread.\n * @param onSelectFirst - Fired with the first thread when the list loads with nothing selected; use it to navigate to that thread (with replace) so the inbox auto-selects it.\n * @param getThreadUri - A function to build thread URIs.\n * @param onChange - A function to handle search changes.\n * @param inProgressUri - The URI for in-progress threads.\n * @param completedUri - The URI for completed threads.\n * @param newTopicOpened - Controlled open state for the new topic dialog. When provided, use `onNewTopicOpen` and `onNewTopicClose` to update it.\n * @param onNewTopicOpen - Called when the user clicks the new message button. Required when `newTopicOpened` is provided.\n * @param onNewTopicClose - Called when the new topic dialog is closed. Required when `newTopicOpened` is provided.\n */\n\nexport interface ThreadInboxProps {\n  readonly query: string;\n  readonly threadId: string | undefined;\n  readonly subject?: Reference<Patient> | Patient;\n  readonly showPatientSummary?: boolean;\n  readonly sections?: PatientSummarySectionConfig[];\n  readonly patientHeaderMenuItems?: ReactNode;\n  readonly patientHeaderLink?: Resource | Reference | string;\n  readonly onEditPatient?: () => void;\n  readonly onPatientChange?: (patient: Reference<Patient> | undefined) => void;\n  readonly onNew: (message: Communication) => void;\n  readonly onSelectFirst?: (thread: Communication) => void;\n  readonly getThreadUri: (topic: Communication) => string;\n  readonly onChange: (search: SearchRequest) => void;\n  readonly inProgressUri: string;\n  readonly completedUri: string;\n  readonly uploadEnabled?: boolean;\n  readonly onViewInDocuments?: (reference: Reference<DocumentReference>) => void;\n  readonly allowPatientSelection?: boolean;\n  readonly newTopicOpened?: boolean;\n  readonly onNewTopicOpen?: () => void;\n  readonly onNewTopicClose?: () => void;\n}\n\nexport function ThreadInbox(props: ThreadInboxProps): JSX.Element {\n  const {\n    query,\n    threadId,\n    subject,\n    showPatientSummary = false,\n    sections,\n    patientHeaderMenuItems,\n    patientHeaderLink,\n    onEditPatient,\n    onPatientChange,\n    onNew,\n    onSelectFirst,\n    getThreadUri,\n    uploadEnabled,\n    onViewInDocuments,\n    onChange,\n    inProgressUri,\n    completedUri,\n    allowPatientSelection = false,\n    onNewTopicOpen,\n    onNewTopicClose,\n  } = props;\n\n  const [internalModalOpened, { open: openInternalModal, close: closeInternalModal }] = useDisclosure(false);\n  const modalOpened = props.newTopicOpened ?? internalModalOpened;\n  const openModal = onNewTopicOpen ?? openInternalModal;\n  const closeModal = onNewTopicClose ?? closeInternalModal;\n  const [editModalOpened, { open: openEditModal, close: closeEditModal }] = useDisclosure(false);\n\n  const currentSearch = useMemo(() => parseSearchRequest(`Communication?${query}`), [query]);\n\n  const searchParams = useMemo(() => new URLSearchParams(query), [query]);\n  const itemsPerPage = Number.parseInt(searchParams.get('_count') || '20', 10);\n  const currentOffset = Number.parseInt(searchParams.get('_offset') || '0', 10);\n  const currentPage = Math.floor(currentOffset / itemsPerPage) + 1;\n  const status = (searchParams.get('status') as Communication['status']) || 'in-progress';\n\n  // Extract participants from parsed search request filters (comma-separated)\n  const selectedParticipants = useMemo((): Reference<Patient | Practitioner>[] => {\n    const recipientFilters = currentSearch.filters?.filter((f) => f.code === 'recipient') ?? [];\n    // Split comma-separated values and flatten\n    return recipientFilters.flatMap((f) =>\n      f.value\n        .split(',')\n        .filter(Boolean)\n        .map((ref) => ({ reference: ref }))\n    );\n  }, [currentSearch]);\n\n  const {\n    loading,\n    error,\n    threadMessages,\n    selectedThread,\n    total,\n    handleThreadStatusChange,\n    addThreadMessage,\n    refreshThreadMessages,\n  } = useThreadInbox({\n    query,\n    threadId,\n  });\n\n  const threadSubject = selectedThread?.subject;\n  const patientReference = isReference<Patient>(threadSubject, 'Patient') ? threadSubject.reference : undefined;\n  useEffect(() => {\n    onPatientChange?.(patientReference ? { reference: patientReference } : undefined);\n  }, [patientReference, onPatientChange]);\n\n  const handleParticipantsChange = useCallback(\n    (participants: Reference<Patient | Practitioner>[]) => {\n      // Remove existing recipient filters\n      const otherFilters = currentSearch.filters?.filter((f) => f.code !== 'recipient') ?? [];\n\n      // Add recipient filter with comma-separated values (OR logic in FHIR)\n      const participantRefs = participants.map((p) => p.reference).filter(Boolean) as string[];\n      const newFilters =\n        participantRefs.length > 0\n          ? [...otherFilters, { code: 'recipient', operator: Operator.EQUALS, value: participantRefs.join(',') }]\n          : otherFilters;\n\n      onChange({\n        ...currentSearch,\n        filters: newFilters,\n        offset: 0, // Reset to first page when filter changes\n      });\n    },\n    [currentSearch, onChange]\n  );\n\n  useEffect(() => {\n    if (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n    }\n  }, [error]);\n\n  const handleTopicStatusChangeWithErrorHandling = async (newStatus: Communication['status']): Promise<void> => {\n    handleThreadStatusChange(newStatus);\n    try {\n      await refreshThreadMessages();\n    } catch (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n    }\n  };\n\n  const handleNewTopicCompletion = (message: Communication): void => {\n    addThreadMessage(message);\n    onNew(message);\n  };\n\n  // The list renders the parent thread (topic) of each tuple; the last message is\n  // looked up by thread id when rendering each row.\n  const items = useMemo(() => threadMessages.map(([topic]) => topic), [threadMessages]);\n  const lastMessageByThreadId = useMemo(() => {\n    const map = new Map<string, Communication | undefined>();\n    for (const [topic, last] of threadMessages) {\n      if (topic.id) {\n        map.set(topic.id, last);\n      }\n    }\n    return map;\n  }, [threadMessages]);\n\n  const isDraft = useCallback(\n    (thread: Communication): boolean =>\n      !!thread.id && lastMessageByThreadId.has(thread.id) && !lastMessageByThreadId.get(thread.id),\n    [lastMessageByThreadId]\n  );\n\n  const handleMessageSent = useCallback(() => {\n    refreshThreadMessages().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [refreshThreadMessages]);\n\n  const tabs = useMemo<ListWithDetailPaneTab[]>(\n    () => [\n      { value: 'in-progress', label: 'In Progress', uri: inProgressUri },\n      { value: 'completed', label: 'Completed', uri: completedUri },\n    ],\n    [inProgressUri, completedUri]\n  );\n\n  const pageCount = total !== undefined ? Math.ceil(total / itemsPerPage) : 0;\n\n  const headerActions = (\n    <>\n      <ParticipantFilter selectedParticipants={selectedParticipants} onFilterChange={handleParticipantsChange} />\n      <Tooltip label=\"New Message\" position=\"bottom\" openDelay={500}>\n        <ActionIcon radius=\"xl\" variant=\"filled\" color=\"blue\" size={32} onClick={openModal}>\n          <IconPlus size={16} />\n        </ActionIcon>\n      </Tooltip>\n    </>\n  );\n\n  return (\n    <>\n      <div className={classes.container}>\n        <ListWithDetailPane<Communication>\n          items={items}\n          loading={loading}\n          selectedKey={selectedThread?.id ?? threadId}\n          selected={selectedThread}\n          // Suppress auto-select while the new-topic dialog is open (e.g. a URL-driven\n          // /new route with no selection) \u2014 selecting would navigate away and close it.\n          onSelectFirst={modalOpened ? undefined : onSelectFirst}\n          listWidth={380}\n          tabs={tabs}\n          activeTab={status}\n          headerActions={headerActions}\n          skeleton={<ThreadListSkeleton />}\n          emptyList={<EmptyMessagesState />}\n          emptyDetail={<NoMessages />}\n          refresh={refreshThreadMessages}\n          page={currentPage}\n          pageCount={pageCount}\n          onPageChange={(page) => onChange({ ...currentSearch, offset: (page - 1) * itemsPerPage })}\n          renderItem={(item) => (\n            <ThreadListItem\n              topic={item}\n              lastCommunication={item.id ? lastMessageByThreadId.get(item.id) : undefined}\n              getThreadUri={getThreadUri}\n            />\n          )}\n          renderDetail={(thread) => (\n            <ThreadDetail\n              thread={thread}\n              showPatientSummary={showPatientSummary}\n              sections={sections}\n              patientHeaderMenuItems={patientHeaderMenuItems}\n              patientHeaderLink={patientHeaderLink}\n              onEditPatient={onEditPatient}\n              uploadEnabled={uploadEnabled}\n              onViewInDocuments={onViewInDocuments}\n              onStatusChange={handleTopicStatusChangeWithErrorHandling}\n              onOpenSettings={isDraft(thread) ? undefined : openEditModal}\n              onMessageSent={handleMessageSent}\n            />\n          )}\n        />\n      </div>\n      {/* Both dialogs are mounted only while open so every open is a fresh instance \u2014 any\n          entries dismissed without saving are abandoned, with no leftover form state. */}\n      {modalOpened && (\n        <NewTopicDialog\n          subject={subject}\n          opened={modalOpened}\n          onClose={closeModal}\n          onSubmit={handleNewTopicCompletion}\n          allowPatientSelection={allowPatientSelection}\n        />\n      )}\n      {selectedThread && editModalOpened && (\n        <EditThreadDialog\n          thread={selectedThread}\n          opened={editModalOpened}\n          onClose={closeEditModal}\n          onSaved={() => {\n            refreshThreadMessages().catch((err) =>\n              showNotification({ color: 'red', message: normalizeErrorString(err) })\n            );\n          }}\n        />\n      )}\n    </>\n  );\n}\n\nfunction NoMessages(): JSX.Element {\n  return (\n    <Center h=\"100%\" w=\"100%\">\n      <Stack align=\"center\" gap=\"md\">\n        <ThemeIcon size={64} variant=\"light\" color=\"gray\">\n          <IconMessageCircle size={32} />\n        </ThemeIcon>\n        <Stack align=\"center\" gap=\"xs\">\n          <Text size=\"sm\" c=\"dimmed\" ta=\"center\">\n            Select a message from the list to view details\n          </Text>\n        </Stack>\n      </Stack>\n    </Center>\n  );\n}\n\nfunction EmptyMessagesState(): JSX.Element {\n  return (\n    <Flex direction=\"column\" h=\"100%\" justify=\"center\" align=\"center\">\n      <Stack align=\"center\" gap=\"md\" pt=\"xl\">\n        <IconMessageCircle size={64} color=\"var(--mantine-color-gray-4)\" />\n        <Text size=\"lg\" c=\"dimmed\" fw={500}>\n          No messages found\n        </Text>\n      </Stack>\n    </Flex>\n  );\n}\n\nfunction ThreadListSkeleton(): JSX.Element {\n  const titleWidths = [80, 72, 68, 64];\n  const subtitleWidths = [85, 78, 70, 60];\n  return (\n    <Stack gap=\"md\" p=\"md\">\n      {Array.from({ length: 10 }).map((_, index) => {\n        const titleWidth = titleWidths[index % titleWidths.length];\n        const subtitleWidth = subtitleWidths[index % subtitleWidths.length];\n        return (\n          <Flex key={index} gap=\"sm\" align=\"flex-start\">\n            <Skeleton height={40} width={40} radius=\"50%\" />\n            <Box style={{ flex: 1 }}>\n              <Flex direction=\"column\" gap=\"xs\">\n                <Skeleton height={16} width={`${titleWidth}%`} />\n                <Skeleton height={14} width={`${subtitleWidth}%`} />\n              </Flex>\n            </Box>\n          </Flex>\n        );\n      })}\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Center, Divider, Flex, Group, Pagination, ScrollArea, Stack, Tabs, Text } from '@mantine/core';\nimport type { Resource } from '@medplum/fhirtypes';\nimport { useStabilizedCallback } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { useEffect } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport classes from './ListWithDetailPane.module.css';\nimport { ListWithDetailPaneSkeleton } from './ListWithDetailPaneSkeleton';\n\nexport interface ListWithDetailPaneTab {\n  readonly value: string;\n  readonly label: ReactNode;\n  readonly uri: string;\n}\n\nexport interface ListWithDetailPaneItemContext<T extends { id?: string } = Resource> {\n  readonly selected: boolean;\n  readonly index: number;\n  readonly items: T[];\n}\n\nexport interface ListWithDetailPaneDetailContext {\n  readonly refresh?: () => Promise<void>;\n}\n\n/**\n * Props shared by every ListWithDetailPane, independent of the header style.\n * @param items - The current page of items to render in the list.\n * @param loading - When true, the list area shows the skeleton instead of items.\n * @param selectedKey - Id of the highlighted row.\n * @param renderItem - Renders one row of the list sidebar.\n * @param emptyList - Shown when the list is empty. Default: dimmed \"No items found\".\n * @param skeleton - Shown while loading. Default: built-in skeleton rows.\n * @param listWidth - Sidebar width in pixels. Default 350.\n * @param listVisible - Whether the list sidebar is shown. Default true. When false the sidebar collapses\n * (animated) and is removed from the accessibility tree. Controlled \u2014 consumers render their own toggle\n * buttons (typically a collapse icon in `headerActions` and an expand icon somewhere in the detail pane).\n * @param headerActions - Right-aligned slot in the sidebar header row: action buttons, filter popovers.\n * @param selected - The resolved selected item, or undefined when nothing is selected.\n * @param renderDetail - Renders the detail pane for the selected item.\n * @param emptyDetail - Shown when nothing is selected. Default: dimmed prompt.\n * @param listFooter - Pinned below the scrolling list and above the pagination row, e.g. bulk actions\n * for the current list. Rendered only when the list has finished loading.\n * @param refresh - Optional. Passed through to the detail render context so the detail pane can refetch the list.\n * @param onSelectFirst - Auto-select escape hatch. Fired with the first item when the list has finished loading\n * (`loading` false) with items while nothing is selected (`selectedKey` undefined). The consumer decides how to\n * navigate (typically with history replace). Pass an id-driven `selectedKey` (e.g. the URL route param) so a\n * selection that is still resolving does not read as \"nothing selected\", and keep `loading` true from the render a\n * new search starts on, so this never fires against a stale list.\n * @param page - Current 1-based page. Pagination is hidden unless this, `pageCount`, and `onPageChange` are set.\n * @param pageCount - Total number of pages. Pagination is hidden when this is less than or equal to 1.\n * @param onPageChange - Fired by the built-in pagination with the new 1-based page.\n */\nexport interface ListWithDetailPanePropsBase<T extends { id?: string } = Resource> {\n  readonly items: T[];\n  readonly loading: boolean;\n  readonly selectedKey?: string;\n  readonly renderItem: (item: T, ctx: ListWithDetailPaneItemContext<T>) => ReactNode;\n  readonly emptyList?: ReactNode;\n  readonly skeleton?: ReactNode;\n  readonly listWidth?: number;\n  readonly listVisible?: boolean;\n  readonly headerActions?: ReactNode;\n  readonly selected: T | undefined;\n  readonly renderDetail: (selected: T, ctx: ListWithDetailPaneDetailContext) => ReactNode;\n  readonly emptyDetail?: ReactNode;\n  readonly listFooter?: ReactNode;\n  readonly refresh?: () => Promise<void>;\n  readonly onSelectFirst?: (item: T) => void;\n  readonly page?: number;\n  readonly pageCount?: number;\n  readonly onPageChange?: (page: number) => void;\n}\n\n/**\n * Plain-text header (or no header at all). Declares the tab fields as `never` so a title\n * can't be mixed with tabs.\n * @param headerText - Plain title shown at the left of the header.\n */\nexport interface ListWithDetailPaneTextHeaderProps {\n  readonly headerText?: ReactNode;\n  readonly tabs?: never;\n  readonly activeTab?: never;\n}\n\n/**\n * Pill-tab header. Declares `headerText` as `never` so tabs can't be mixed with a title.\n * Each tab renders as a link to its `uri`, so tab switching needs no change callback.\n * @param tabs - Sidebar header tabs. Selecting a tab navigates to its URI.\n * @param activeTab - Controlled active tab value; consumers derive it from the URL.\n */\nexport interface ListWithDetailPaneTabsHeaderProps {\n  readonly tabs: ListWithDetailPaneTab[];\n  readonly activeTab?: string;\n  readonly headerText?: never;\n}\n\n/** The sidebar header is plain text or pill tabs, never both. */\nexport type ListWithDetailPaneHeaderProps = ListWithDetailPaneTextHeaderProps | ListWithDetailPaneTabsHeaderProps;\n\nexport type ListWithDetailPaneProps<T extends { id?: string } = Resource> = ListWithDetailPanePropsBase<T> &\n  ListWithDetailPaneHeaderProps;\n\n// Configs\nconst DEFAULT_LIST_WIDTH = 350;\nconst HEADER_HEIGHT = 64;\n\n/**\n * ListWithDetailPane is a generic, presentational master-detail shell: a left sidebar\n * with optional pill tabs, header actions, a scrollable list, and pagination, plus a\n * detail area for the selected item. It does no data fetching \u2014 it renders what it is\n * given, navigates via links, and emits `onPageChange` / `onSelectFirst` callbacks.\n * @param props - The ListWithDetailPane React props.\n * @returns The ListWithDetailPane React node.\n */\nexport function ListWithDetailPane<T extends { id?: string } = Resource>(\n  props: ListWithDetailPaneProps<T>\n): JSX.Element {\n  const {\n    items,\n    loading,\n    selectedKey,\n    renderItem,\n    emptyList,\n    skeleton,\n    listWidth = DEFAULT_LIST_WIDTH,\n    listVisible = true,\n    headerText,\n    tabs,\n    activeTab,\n    headerActions,\n    selected,\n    renderDetail,\n    emptyDetail,\n    listFooter,\n    refresh,\n    onSelectFirst,\n    page,\n    pageCount,\n    onPageChange,\n  } = props;\n\n  // Consumers routinely pass onSelectFirst as an inline arrow, and a changing identity must not\n  // refire the auto-select effect (firing on every render would loop with consumers that\n  // navigate on select).\n  const selectFirst = useStabilizedCallback(onSelectFirst);\n\n  // Auto-select the first item when a load settles with items and no selection intended.\n  useEffect(() => {\n    if (!loading && selectedKey === undefined && items.length > 0) {\n      selectFirst(items[0]);\n    }\n  }, [loading, selectedKey, items, selectFirst]);\n\n  let headerLeft: ReactNode = <span />;\n  if (tabs) {\n    headerLeft = (\n      <Tabs value={activeTab ?? null} variant=\"unstyled\" className={classes.pillTabs}>\n        <Tabs.List>\n          {tabs.map((tab) => (\n            <Tabs.Tab\n              key={tab.value}\n              value={tab.value}\n              // Render the pill itself as the link. Nesting an anchor inside the tab\n              // button would leave the pill's padding dead (the anchor stops the click\n              // from reaching the button) and is invalid interactive nesting. Mantine's\n              // own onClick is dropped: navigation is the link's job, so there is one\n              // code path and no tab-change callback to wire up.\n              renderRoot={({ onClick: _onClick, className, children, ...rootProps }) => (\n                <MedplumLink to={tab.uri} className={cx(classes.tabLink, className)} {...rootProps}>\n                  {children}\n                </MedplumLink>\n              )}\n            >\n              {tab.label}\n            </Tabs.Tab>\n          ))}\n        </Tabs.List>\n      </Tabs>\n    );\n  } else if (headerText !== undefined) {\n    headerLeft = <Text className={classes.headerText}>{headerText}</Text>;\n  }\n\n  return (\n    <Flex direction=\"row\" h=\"100%\" w=\"100%\" className={classes.container}>\n      <Flex\n        direction=\"column\"\n        w={listVisible ? listWidth : 0}\n        h=\"100%\"\n        className={cx(classes.shell, !listVisible && classes.shellHidden)}\n        aria-hidden={!listVisible || undefined}\n      >\n        {(tabs || headerActions || headerText) && (\n          <>\n            <Flex h={HEADER_HEIGHT} align=\"center\" justify=\"space-between\" p=\"md\">\n              {headerLeft}\n              {headerActions && <Group gap=\"xs\">{headerActions}</Group>}\n            </Flex>\n            <Divider />\n          </>\n        )}\n        <ScrollArea flex={1} scrollbarSize={10} type=\"hover\" scrollHideDelay={250}>\n          {loading && (skeleton ?? <ListWithDetailPaneSkeleton />)}\n          {!loading && items.length === 0 && (emptyList ?? <DefaultEmptyList />)}\n          {!loading && items.length > 0 && (\n            <div className={classes.list}>\n              {items.map((item, index) => {\n                const isSelected = item.id !== undefined && item.id === selectedKey;\n                return (\n                  <div key={item.id ?? index} className={cx(classes.item, isSelected && classes.selected)}>\n                    {renderItem(item, { selected: isSelected, index, items })}\n                  </div>\n                );\n              })}\n            </div>\n          )}\n        </ScrollArea>\n        {!loading && listFooter}\n        {onPageChange !== undefined && page !== undefined && pageCount !== undefined && pageCount > 1 && (\n          <div className={classes.footer}>\n            <Pagination value={page} total={pageCount} onChange={onPageChange} size=\"sm\" siblings={1} boundaries={1} />\n          </div>\n        )}\n      </Flex>\n      {selected === undefined ? (\n        <Box flex={1} h=\"100%\">\n          {emptyDetail ?? <DefaultEmptyDetail />}\n        </Box>\n      ) : (\n        renderDetail(selected, { refresh })\n      )}\n    </Flex>\n  );\n}\n\nfunction DefaultEmptyList(): JSX.Element {\n  return (\n    <Flex direction=\"column\" h=\"100%\" justify=\"center\" align=\"center\" pt=\"xl\">\n      <Text c=\"dimmed\" fw={500}>\n        No items found\n      </Text>\n    </Flex>\n  );\n}\n\nfunction DefaultEmptyDetail(): JSX.Element {\n  return (\n    <Center h=\"100%\" w=\"100%\">\n      <Stack align=\"center\" gap=\"xs\">\n        <Text size=\"sm\" c=\"dimmed\" ta=\"center\">\n          Select an item from the list to view details\n        </Text>\n      </Stack>\n    </Center>\n  );\n}\n", ".container {\n  height: 100%;\n  width: 100%;\n  overflow: hidden;\n}\n\n.shell {\n  display: flex;\n  flex-direction: column;\n  /* The list keeps its width; a wide detail pane scrolls instead of squeezing it. */\n  flex-shrink: 0;\n  height: 100%;\n  background: var(--mantine-color-body);\n  /* Clips the list while its width animates between open and collapsed. */\n  overflow: hidden;\n  transition:\n    width 200ms ease,\n    opacity 200ms ease;\n}\n\n.shell,\n.detailBorder {\n  border-right: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));\n}\n\n/* Collapsed sidebar (`listVisible` false). `visibility` flips only after the\n   width/opacity animation ends (via its 200ms transition delay), which also\n   drops the hidden list's links and buttons out of the tab order. On expand the\n   base `.shell` transition applies, so visibility returns immediately. */\n.shellHidden {\n  opacity: 0;\n  visibility: hidden;\n  border-right: none;\n  transition:\n    width 200ms ease,\n    opacity 200ms ease,\n    visibility 0s 200ms;\n}\n\n/* Inset the rows from the sidebar edges. Each item's rounded hover/selected\n   highlight (`.item`) would otherwise bleed to the pane border and lose its\n   corners; this padding gives the highlight breathing room on all sides. */\n.list {\n  padding: var(--mantine-spacing-xs);\n}\n\n/* Per-item chrome wrapper. The list renders this `<div>` around each item's\n   content (from `renderItem`), so it owns the hover/selected backgrounds. It\n   deliberately has no padding: the item's content provides its own padding so a\n   navigational item (a link) can fill this wrapper and keep the whole row clickable. */\n.item {\n  transition: background 0.2s;\n  cursor: pointer;\n  border-radius: 0.5rem;\n}\n\n/* Normalize the line-height of every text child so a mix of `<Text size=\"md\">`\n   (e.g. the bold first line) and `<Text size=\"sm\">` (secondary/tertiary lines)\n   share the same vertical rhythm. Without this, default Mantine line-heights\n   (1.55 vs 1.45) cause uneven gaps between lines in a list item. */\n.item :global(.mantine-Text-root) {\n  line-height: var(--mantine-line-height-sm);\n}\n\n.item:hover {\n  background: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n.item.selected {\n  background: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n}\n\n.footer {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n  padding-inline: var(--mantine-spacing-md);\n  padding-block: 15px;\n}\n\n/* Header text style for headers that show a plain title (no pill tabs). Reads as\n   the section title of the list, so it is a step larger and heavier than the row\n   text below it.\n\n   `padding-inline-start` lines the title up with the text of the rows: the header\n   bar has `p=\"md\"`, while a row's text sits at `.list` padding (xs) plus the\n   item's own 0.5rem content padding. */\n.headerText {\n  font-size: var(--mantine-font-size-md);\n  font-weight: 600;\n  color: light-dark(var(--mantine-color-gray-9), var(--mantine-color-white));\n  line-height: 1.2;\n  padding-inline-start: calc(var(--mantine-spacing-xs) + 0.5rem - var(--mantine-spacing-md));\n}\n\n/* Pill-style Tabs used in list headers. CSS-module-scoped \u2014 the `:global()`\n   wrappers keep Mantine's `.mantine-Tabs-*` class names global so the\n   descendant selectors continue to target them. */\n.pillTabs :global(.mantine-Tabs-list) {\n  display: flex;\n  gap: 2px;\n}\n\n.pillTabs :global(.mantine-Tabs-tab) {\n  height: 32px;\n  padding-inline: calc(0.875rem * var(--mantine-scale));\n  padding-block: 0;\n  border-radius: var(--mantine-radius-xl);\n  font-size: var(--mantine-font-size-sm);\n  font-weight: 450;\n  background-color: transparent;\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-gray-4));\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  transition:\n    background-color 150ms ease,\n    color 150ms ease;\n}\n\n.pillTabs :global(.mantine-Tabs-tab):hover {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n.pillTabs :global(.mantine-Tabs-tab[data-active]) {\n  background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n  color: light-dark(var(--mantine-color-gray-9), var(--mantine-color-white));\n}\n\n.pillTabs :global(.mantine-Tabs-tab[data-active]):hover {\n  background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n  color: light-dark(var(--mantine-color-gray-9), var(--mantine-color-white));\n}\n\n.tabLink {\n  color: inherit;\n  line-height: 1;\n  text-decoration: none;\n\n  &:hover {\n    text-decoration: none;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Flex, Skeleton, Stack } from '@mantine/core';\nimport type { JSX } from 'react';\n\n// Configs\nconst SKELETON_WIDTHS = [\n  ['85%', '60%', '72%'],\n  ['70%', '80%', '55%'],\n  ['92%', '50%', '65%'],\n  ['78%', '68%', '58%'],\n  ['88%', '45%', '75%'],\n  ['74%', '70%', '62%'],\n];\n\n/**\n * ListWithDetailPaneSkeleton is the default loading placeholder for the list sidebar.\n * It renders a few rows of varied-width skeleton lines separated by dividers.\n * @returns The ListWithDetailPaneSkeleton React node.\n */\nexport function ListWithDetailPaneSkeleton(): JSX.Element {\n  return (\n    <Stack gap=\"md\" p=\"md\">\n      {SKELETON_WIDTHS.map((widths, index) => (\n        <Stack key={index}>\n          <Flex direction=\"column\" gap=\"xs\" align=\"flex-start\">\n            <Skeleton height={16} width={widths[0]} />\n            <Skeleton height={14} width={widths[1]} />\n            <Skeleton height={14} width={widths[2]} />\n          </Flex>\n          <Divider />\n        </Stack>\n      ))}\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { isReference, normalizeErrorString } from '@medplum/core';\nimport type { Communication, Patient, Practitioner, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport { Modal } from '../../Modal/Modal';\nimport { ThreadMessageForm } from './ThreadMessageForm';\n\n/**\n * Props for the EditThreadDialog component.\n * @param thread - The thread (root Communication) to edit, as a resource or a reference to resolve.\n * @param opened - Whether the dialog is open.\n * @param onClose - Callback fired when the dialog is closed.\n * @param onSaved - Callback fired with the updated Communication resource after a successful save.\n */\nexport interface EditThreadDialogProps {\n  thread: Communication | Reference<Communication>;\n  opened: boolean;\n  onClose: () => void;\n  onSaved?: (communication: Communication) => void;\n}\n\nexport const EditThreadDialog = (props: EditThreadDialogProps): JSX.Element => {\n  const { opened, onClose, onSaved } = props;\n  const medplum = useMedplum();\n  const thread = useResource(props.thread);\n\n  const patientRef = thread?.subject as Reference<Patient> | undefined;\n  const initialPractitioners = useMemo(() => {\n    const fromRecipients = (thread?.recipient ?? []).filter((r) => isReference<Practitioner>(r, 'Practitioner'));\n    if (fromRecipients.length > 0) {\n      return fromRecipients;\n    }\n    // Fallback for threads with no practitioner recipient (e.g. legacy/patient-only threads):\n    // surface the sender when it is a Practitioner, so the field isn't empty. Saving then\n    // migrates this practitioner into the recipient list.\n    const sender = thread?.sender;\n    if (isReference<Practitioner>(sender, 'Practitioner')) {\n      return [sender];\n    }\n    return [];\n  }, [thread?.recipient, thread?.sender]);\n\n  // The dialog is mounted only while open (see ThreadInbox), so this state initializes fresh on\n  // each open \u2014 edits dismissed without saving are abandoned with no leftover form state.\n  const [topic, setTopic] = useState(thread?.topic?.text ?? '');\n  const [practitioners, setPractitioners] = useState<Reference<Practitioner>[]>(initialPractitioners);\n\n  // When the thread is passed as a reference it resolves after mount, so re-initialize\n  // the form state when it arrives (React's \"adjusting state when a prop changes\" pattern).\n  const [initializedThread, setInitializedThread] = useState(thread);\n  if (thread !== initializedThread) {\n    setInitializedThread(thread);\n    setTopic(thread?.topic?.text ?? '');\n    setPractitioners(initialPractitioners);\n  }\n\n  const handleSave = async (): Promise<void> => {\n    if (!thread) {\n      return;\n    }\n    // Preserve all non-Practitioner recipients (the patient subject, RelatedPerson,\n    // CareTeam, etc.) and replace only the Practitioner entries with the edited set,\n    // so editing the topic/practitioners never silently drops other participants.\n    const preservedRecipients = (thread.recipient ?? []).filter((r) => !isReference<Practitioner>(r, 'Practitioner'));\n    const updated: Communication = {\n      ...thread,\n      recipient: [...preservedRecipients, ...practitioners],\n      topic: topic ? { text: topic } : undefined,\n    };\n\n    try {\n      const saved = await medplum.updateResource(updated);\n      onSaved?.(saved);\n      onClose();\n    } catch (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n    }\n  };\n\n  return (\n    <Modal\n      opened={opened}\n      onClose={onClose}\n      title=\"Message Settings\"\n      size=\"md\"\n      // Falsy actions render no footer, so the modal is title-only while the thread resolves.\n      actions={\n        thread && (\n          <Button onClick={handleSave} disabled={practitioners.length === 0}>\n            Save\n          </Button>\n        )\n      }\n    >\n      {thread && (\n        <ThreadMessageForm\n          defaultPractitioners={initialPractitioners}\n          onPractitionersChange={setPractitioners}\n          topic={topic}\n          onTopicChange={setTopic}\n          defaultPatient={patientRef}\n        />\n      )}\n    </Modal>\n  );\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport {\n  ActionIcon,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Group,\n  Menu,\n  Paper,\n  ScrollArea,\n  Stack,\n  Text,\n  Tooltip,\n} from '@mantine/core';\nimport { getReferenceString } from '@medplum/core';\nimport type { Communication, DocumentReference, Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { IconChevronDown, IconInfoCircle } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { PatientSummary } from '../../PatientSummary/PatientSummary';\nimport type { PatientSummarySectionConfig } from '../../PatientSummary/PatientSummary.types';\nimport { ThreadChat } from '../ThreadChat/ThreadChat';\nimport classes from './ThreadDetail.module.css';\n\n/**\n * Props for the ThreadDetail component.\n * @param thread - The selected thread (parent Communication) to display.\n * @param showPatientSummary - Whether to show the patient summary sidebar.\n * @param sections - Optional sections configuration for the patient summary.\n * @param patientHeaderLink - Where the patient summary header navigates when clicked. Omit for a static header.\n * @param uploadEnabled - Whether to show the attachment upload button in the chat input.\n * @param onViewInDocuments - When provided, shows a \"View in Documents\" action on attachment messages that invokes this callback with the attachment's DocumentReference.\n * @param onStatusChange - Fired when the user changes the thread status from the header menu.\n * @param onOpenSettings - When provided, shows a Message Settings button in the header that invokes this callback.\n * @param onMessageSent - Fired with the created Communication after the user sends a message in the chat.\n */\nexport interface ThreadDetailProps {\n  readonly thread: Communication;\n  readonly showPatientSummary?: boolean;\n  readonly sections?: PatientSummarySectionConfig[];\n  readonly patientHeaderMenuItems?: ReactNode;\n  readonly patientHeaderLink?: Resource | Reference | string;\n  readonly onEditPatient?: () => void;\n  readonly uploadEnabled?: boolean;\n  readonly onViewInDocuments?: (reference: Reference<DocumentReference>) => void;\n  readonly onStatusChange: (status: Communication['status']) => void;\n  readonly onOpenSettings?: () => void;\n  readonly onMessageSent?: (message: Communication) => void;\n}\n\n/**\n * ThreadDetail renders the detail pane of the ThreadInbox: the thread header with a\n * status menu, the chat thread, and an optional patient summary sidebar.\n * @param props - The ThreadDetail React props.\n * @returns The ThreadDetail React node.\n */\nexport function ThreadDetail(props: ThreadDetailProps): JSX.Element {\n  const {\n    thread,\n    showPatientSummary = false,\n    sections,\n    patientHeaderMenuItems,\n    patientHeaderLink,\n    onEditPatient,\n    uploadEnabled,\n    onViewInDocuments,\n    onStatusChange,\n    onOpenSettings,\n    onMessageSent,\n  } = props;\n\n  return (\n    <>\n      {/* Main chat area */}\n      <Flex direction=\"column\" style={{ flex: 1 }} h=\"100%\" className={classes.rightBorder}>\n        <Paper h=\"100%\">\n          <Stack h=\"100%\" gap={0}>\n            <Flex h={64} align=\"center\" justify=\"space-between\" p=\"md\">\n              <Text fw={800} truncate fz=\"lg\">\n                {thread.topic?.text ?? 'Messages'}\n              </Text>\n\n              <Group gap=\"xs\">\n                {onOpenSettings && (\n                  <Tooltip label=\"Message Settings\" position=\"bottom\" openDelay={500}>\n                    <ActionIcon\n                      aria-label=\"Message settings\"\n                      variant=\"transparent\"\n                      radius=\"xl\"\n                      size={32}\n                      className=\"outline-icon-button\"\n                      onClick={onOpenSettings}\n                    >\n                      <IconInfoCircle size={16} />\n                    </ActionIcon>\n                  </Tooltip>\n                )}\n\n                <Menu position=\"bottom-end\" shadow=\"md\">\n                  <Menu.Target>\n                    <Button\n                      variant=\"light\"\n                      color={getStatusColor(thread.status)}\n                      rightSection={thread.status === 'completed' ? undefined : <IconChevronDown size={16} />}\n                      radius=\"xl\"\n                      size=\"sm\"\n                    >\n                      {thread.status\n                        .split('-')\n                        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n                        .join(' ')}\n                    </Button>\n                  </Menu.Target>\n\n                  {thread.status !== 'completed' && (\n                    <Menu.Dropdown>\n                      <Menu.Item onClick={() => onStatusChange('completed')}>Completed</Menu.Item>\n                    </Menu.Dropdown>\n                  )}\n                </Menu>\n              </Group>\n            </Flex>\n            <Divider />\n            <Box flex={1} h=\"100%\">\n              <ThreadChat\n                key={`${getReferenceString(thread)}`}\n                title={'Messages'}\n                thread={thread}\n                excludeHeader={true}\n                uploadEnabled={uploadEnabled}\n                onViewInDocuments={onViewInDocuments}\n                onMessageSent={onMessageSent}\n              />\n            </Box>\n          </Stack>\n        </Paper>\n      </Flex>\n\n      {/* Right sidebar - Patient summary */}\n      {thread.subject && showPatientSummary && (\n        <Box w={300} h=\"100%\" bg=\"light-dark(var(--mantine-color-white), var(--mantine-color-body))\">\n          <ScrollArea p={0} h=\"100%\" scrollbarSize={10} type=\"hover\" scrollHideDelay={250}>\n            <PatientSummary\n              key={thread.id}\n              patient={thread.subject as Reference<Patient>}\n              sections={sections}\n              headerMenuItems={patientHeaderMenuItems}\n              headerLink={patientHeaderLink}\n              onEditPatient={onEditPatient}\n            />\n          </ScrollArea>\n        </Box>\n      )}\n    </>\n  );\n}\n\nfunction getStatusColor(status: Communication['status']): string {\n  if (status === 'completed') {\n    return 'green';\n  }\n  if (status === 'stopped') {\n    return 'red';\n  }\n  return 'blue';\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Box, Divider, Flex, Group, Menu, Skeleton, Stack, Text } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { MedplumClient, WithId } from '@medplum/core';\nimport { formatDate, formatHumanName, normalizeErrorString, resolveId } from '@medplum/core';\nimport type { OperationOutcome, Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, usePatientSummaryData, useResource, useResourceModified } from '@medplum/react-hooks';\nimport { IconDots, IconReload } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport styles from './PatientSummary.module.css';\nimport type { PatientSummarySectionConfig } from './PatientSummary.types';\nimport { getDefaultSections } from './sectionConfigs';\n\nexport interface PatientSummaryProps {\n  readonly patient: Patient | Reference<Patient>;\n  readonly onClickResource?: (resource: Resource) => void;\n  readonly onRequestLabs?: () => void;\n  readonly sections?: PatientSummarySectionConfig[];\n  readonly headerMenuItems?: ReactNode;\n  readonly headerLink?: Resource | Reference | string;\n  readonly onEditPatient?: () => void;\n}\n\nexport function PatientSummary(props: PatientSummaryProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const { patient: propsPatient, onClickResource, onRequestLabs, headerMenuItems, headerLink, onEditPatient } = props;\n  const [patientOutcome, setPatientOutcome] = useState<OperationOutcome | undefined>();\n  const resolvedPatient = useResource(propsPatient, setPatientOutcome);\n  const [modifiedPatient, setModifiedPatient] = useState<WithId<Patient> | undefined>();\n  const [createdDate, setCreatedDate] = useState<string | undefined>();\n\n  useResourceModified('Patient', (event) => {\n    if (event.resource && event.resource.id === resolvedPatient?.id) {\n      setModifiedPatient(event.resource);\n    }\n  });\n\n  const patient = modifiedPatient?.id === resolvedPatient?.id ? modifiedPatient : resolvedPatient;\n\n  // Determine sections: custom or default\n  const defaultSections = useMemo(() => getDefaultSections(onRequestLabs), [onRequestLabs]);\n  const sections = props.sections ?? defaultSections;\n\n  // Fetch all data for all sections (with search deduplication)\n  const { sectionData, loading, error, refresh } = usePatientSummaryData(propsPatient, sections);\n\n  const handleRefresh = useCallback(() => {\n    refresh();\n    const id = resolveId(propsPatient);\n    if (!id) {\n      return;\n    }\n    medplum\n      .readResource('Patient', id, { cache: 'reload' })\n      .then(setModifiedPatient)\n      .catch((err) => showNotification({ color: 'red', title: 'Error', message: normalizeErrorString(err) }));\n  }, [medplum, propsPatient, refresh]);\n\n  useEffect(() => {\n    const id = resolveId(propsPatient);\n    if (id) {\n      readCreatedDate(medplum, id)\n        .then((lastUpdated) => setCreatedDate(lastUpdated ?? ''))\n        .catch(() => {});\n    }\n  }, [propsPatient, medplum]);\n\n  if (!patient) {\n    return patientOutcome ? null : <PatientSummarySkeleton sections={Math.max(sections.length - 1, 1)} />;\n  }\n\n  const headerContent = (\n    <Group align=\"center\" gap=\"sm\" wrap=\"nowrap\" className={styles.headerContent}>\n      <ResourceAvatar value={patient} size={48} radius={48} />\n      <Stack gap={0} style={{ flex: 1, minWidth: 0 }}>\n        <Text fz=\"h4\" fw={800} truncate style={{ minWidth: 0 }}>\n          {formatHumanName(patient.name?.[0])}\n        </Text>\n        {createdDate && (\n          <Text fz=\"xs\" mt={-2} fw={500} c=\"gray.6\" truncate style={{ minWidth: 0 }}>\n            Patient since {formatDate(createdDate)}\n          </Text>\n        )}\n      </Stack>\n    </Group>\n  );\n\n  return (\n    <Flex direction=\"column\" gap={0} w=\"100%\" h=\"100%\" className={styles.panel}>\n      <Box>\n        <Group align=\"center\" gap=\"sm\" wrap=\"nowrap\" py=\"md\" pl=\"sm\" pr=\"xs\">\n          {headerLink ? (\n            <MedplumLink to={headerLink} className={styles.headerLink} underline=\"never\">\n              {headerContent}\n            </MedplumLink>\n          ) : (\n            headerContent\n          )}\n          <Menu shadow=\"md\" radius=\"md\" width={240} position=\"bottom-end\">\n            <Menu.Target>\n              <ActionIcon\n                variant=\"subtle\"\n                size=\"md\"\n                radius=\"xl\"\n                aria-label=\"Patient actions\"\n                className={styles.actionsButton}\n              >\n                <IconDots size={18} />\n              </ActionIcon>\n            </Menu.Target>\n            <Menu.Dropdown>\n              {headerMenuItems && (\n                <>\n                  {headerMenuItems}\n                  <Menu.Divider />\n                </>\n              )}\n              <Menu.Item\n                leftSection={<IconReload size={16} color=\"var(--mantine-color-dimmed)\" />}\n                onClick={handleRefresh}\n              >\n                <Text size=\"sm\">Refresh</Text>\n              </Menu.Item>\n            </Menu.Dropdown>\n          </Menu>\n        </Group>\n        <Divider />\n      </Box>\n\n      <Stack gap={0} px=\"xs\" pb={16} style={{ flex: 2, overflowY: 'auto', minHeight: 0 }}>\n        {error && (\n          <Text c=\"red\" fz=\"sm\">\n            Error loading patient summary: {error.message}\n          </Text>\n        )}\n        {loading && sections.length > 0 && (\n          <PatientSummarySectionsSkeleton sections={Math.max(sections.length - 1, 1)} />\n        )}\n        {!loading && sections.length > 0 && (\n          <>\n            {sections.map((section, index) => {\n              const SectionComponent = section.component;\n              return (\n                <div key={section.key}>\n                  <SectionComponent\n                    patient={patient}\n                    onClickResource={onClickResource}\n                    onEditPatient={onEditPatient}\n                    results={sectionData[index] ?? {}}\n                  />\n                  <Divider />\n                </div>\n              );\n            })}\n          </>\n        )}\n      </Stack>\n    </Flex>\n  );\n}\n\n/**\n * Reads the creation timestamp of a patient from the oldest entry in its version history.\n * History is returned newest first, so the newest page's `total` is used to page directly to the\n * oldest version instead of downloading every version.\n * @param medplum - The Medplum client.\n * @param id - The patient ID.\n * @returns The `meta.lastUpdated` of the first version, or undefined if unavailable.\n */\nasync function readCreatedDate(medplum: MedplumClient, id: string): Promise<string | undefined> {\n  const newest = await medplum.readHistory('Patient', id, { count: 1 });\n  const total = newest.total;\n  const oldest =\n    total !== undefined && total > 1\n      ? await medplum.readHistory('Patient', id, { count: 1, offset: total - 1 })\n      : newest;\n  const entries = oldest.entry ?? [];\n  return entries[entries.length - 1]?.resource?.meta?.lastUpdated;\n}\n\nexport interface PatientSummarySkeletonProps {\n  readonly sections?: number;\n}\n\n/**\n * Loading placeholder that mirrors the PatientSummary layout: the patient header followed by\n * demographic rows and a set of collapsible sections with their items.\n * @param props - The skeleton props.\n * @returns The PatientSummarySkeleton React node.\n */\nexport function PatientSummarySkeleton(props: PatientSummarySkeletonProps): JSX.Element {\n  return (\n    <Flex direction=\"column\" gap=\"xs\" w=\"100%\" h=\"100%\" className={styles.panel} data-testid=\"patient-summary-skeleton\">\n      <Group align=\"center\" gap=\"sm\" p={16} wrap=\"nowrap\">\n        <Skeleton circle height={48} style={{ flexShrink: 0 }} />\n        <Stack gap={8} style={{ flex: 1, minWidth: 0 }}>\n          <Skeleton height={20} width=\"60%\" />\n          <Skeleton height={10} width=\"45%\" />\n        </Stack>\n      </Group>\n      <Divider />\n      <Stack gap=\"xs\" px={16} pt={12} pb={16} style={{ flex: 2, overflow: 'hidden', minHeight: 0 }}>\n        <PatientSummarySectionsSkeleton sections={props.sections} />\n      </Stack>\n    </Flex>\n  );\n}\n\nconst SKELETON_ROW_WIDTHS = ['55%', '30%', '40%', '75%', '25%', '50%'];\n\n/**\n * Loading placeholder for the scrollable body of the PatientSummary: a block of demographic rows\n * followed by collapsible section headers, each with a few item rows and a status badge.\n * @param props - The skeleton props.\n * @returns The PatientSummarySectionsSkeleton React node.\n */\nfunction PatientSummarySectionsSkeleton(props: PatientSummarySkeletonProps): JSX.Element {\n  const sections = props.sections ?? 3;\n  return (\n    <div data-testid=\"patient-summary-sections-skeleton\">\n      <Stack gap=\"xs\" py={8}>\n        {SKELETON_ROW_WIDTHS.map((width, index) => (\n          <Group key={index} gap=\"sm\" align=\"center\" ml={6} py={2} wrap=\"nowrap\">\n            <Skeleton circle height={16} style={{ flexShrink: 0 }} />\n            <Skeleton height={14} width={width} />\n          </Group>\n        ))}\n      </Stack>\n      <Divider />\n      {Array.from({ length: sections }, (_, index) => (\n        <Box key={index}>\n          <Box py=\"xs\">\n            <Group gap={8} align=\"center\" wrap=\"nowrap\">\n              <Skeleton circle height={28} style={{ flexShrink: 0 }} />\n              <Skeleton height={16} width={SKELETON_ROW_WIDTHS[(index + 1) % SKELETON_ROW_WIDTHS.length]} />\n            </Group>\n            <Stack gap=\"sm\" ml=\"var(--mantine-spacing-xl)\" mt=\"xs\" mb=\"md\" pl={4}>\n              {Array.from({ length: 2 }, (_, item) => (\n                <Stack key={item} gap={6}>\n                  <Skeleton height={14} width={SKELETON_ROW_WIDTHS[(index + item) % SKELETON_ROW_WIDTHS.length]} />\n                  <Skeleton height={18} width={64} radius=\"xl\" />\n                </Stack>\n              ))}\n            </Stack>\n          </Box>\n          <Divider />\n        </Box>\n      ))}\n    </div>\n  );\n}\n", ".panel {\n  height: 100%;\n}\n\n[data-mantine-color-scheme='dark'] .panel {\n  background-color: var(--mantine-color-body);\n}\n\n[data-mantine-color-scheme='light'] .panel {\n  background-color: var(--mantine-color-white);\n}\n\n.headerLink,\n.headerContent {\n  flex: 1;\n  min-width: 0;\n}\n\n.headerLink {\n  display: block;\n  color: inherit;\n  text-decoration: none;\n}\n\n.headerLink:hover {\n  text-decoration: none;\n}\n\n.actionsButton {\n  flex-shrink: 0;\n}\n\n.actionsButton[data-expanded] {\n  background-color: var(--mantine-primary-color-light);\n  color: var(--mantine-primary-color-light-color);\n}\n\n.patientSummaryBadge {\n  cursor: pointer;\n}\n\n.patientSummaryHeader {\n  width: 100%;\n  cursor: default;\n}\n\n.patientSummaryHeader :global(.mantine-ActionIcon-root),\n.patientSummaryHeader :global(.mantine-Text-root) {\n  cursor: pointer;\n  margin: 0;\n}\n\n.patientSummaryCollapseIcon {\n  transition: transform 0.2s;\n}\n\n.patientSummaryCollapseIcon.collapsed {\n  transform: rotate(-90deg);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Stack } from '@mantine/core';\nimport { calculateAgeString, formatAddress } from '@medplum/core';\nimport type {\n  AllergyIntolerance,\n  Condition,\n  Coverage,\n  DiagnosticReport,\n  Goal,\n  Immunization,\n  MedicationRequest,\n  MedicationStatement,\n  Observation,\n  ServiceRequest,\n} from '@medplum/fhirtypes';\nimport {\n  IconBinaryTree,\n  IconCake,\n  IconEmpathize,\n  IconLanguage,\n  IconMapPin,\n  IconStethoscope,\n} from '@tabler/icons-react';\nimport type { ComponentType } from 'react';\nimport { Allergies } from './Allergies';\nimport { Goals } from './Goals';\nimport { Immunizations } from './Immunizations';\nimport { Insurance } from './Insurance';\nimport { Labs } from './Labs';\nimport { Medications } from './Medications';\nimport { PatientInfoItem } from './PatientInfoItem';\nimport type { PatientSummarySectionConfig, SectionRenderContext } from './PatientSummary.types';\nimport {\n  formatPatientGenderDisplay,\n  formatPatientRaceEthnicityDisplay,\n  getEthnicity,\n  getGeneralPractitioner,\n  getPreferredLanguage,\n  getRace,\n} from './PatientSummary.utils';\nimport type { PharmacyDialogBaseProps } from './Pharmacies';\nimport { Pharmacies } from './Pharmacies';\nimport { ProblemList } from './ProblemList';\nimport { SexualOrientation } from './SexualOrientation';\nimport { SmokingStatus } from './SmokingStatus';\nimport { Vitals } from './Vitals';\n\n/** Demographics section \u2014 no FHIR searches, renders patient info items directly. */\nexport const DemographicsSection: PatientSummarySectionConfig = {\n  key: 'demographics',\n  title: 'Demographics',\n  component: ({ patient, onClickResource, onEditPatient }: SectionRenderContext) => {\n    const languageDisplay = getPreferredLanguage(patient);\n    const onClick = onEditPatient ?? (onClickResource ? () => onClickResource(patient) : undefined);\n    return (\n      <Stack gap=\"xs\" py=\"md\">\n        <PatientInfoItem\n          value={patient.birthDate ? `${patient.birthDate} (${calculateAgeString(patient.birthDate)})` : undefined}\n          icon={<IconCake size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Birthdate\"\n          label=\"Birthdate & Age\"\n          onClick={onClick}\n        />\n        <PatientInfoItem\n          value={patient.gender ? formatPatientGenderDisplay(patient) : undefined}\n          icon={<IconEmpathize size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Gender & Identity\"\n          label=\"Gender & Identity\"\n          onClick={onClick}\n        />\n        <PatientInfoItem\n          value={getRace(patient) || getEthnicity(patient) ? formatPatientRaceEthnicityDisplay(patient) : undefined}\n          icon={<IconBinaryTree size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Race & Ethnicity\"\n          label=\"Race & Ethnicity\"\n          onClick={onClick}\n        />\n        <PatientInfoItem\n          value={patient.address?.[0] ? formatAddress(patient.address[0]) : undefined}\n          icon={<IconMapPin size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Location\"\n          label=\"Location\"\n          onClick={onClick}\n        />\n        <PatientInfoItem\n          value={languageDisplay}\n          icon={<IconLanguage size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Language\"\n          label=\"Language\"\n          onClick={onClick}\n        />\n        <PatientInfoItem\n          value={getGeneralPractitioner(patient)}\n          icon={<IconStethoscope size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add General Practitioner\"\n          label=\"General Practitioner\"\n          onClick={onClick}\n        />\n      </Stack>\n    );\n  },\n};\n\n/** Insurance section \u2014 searches for Coverage resources. */\nexport const InsuranceSection: PatientSummarySectionConfig = {\n  key: 'insurance',\n  title: 'Insurance',\n  searches: [{ key: 'coverages', resourceType: 'Coverage', patientParam: 'beneficiary' }],\n  component: ({ results, onClickResource }: SectionRenderContext) => (\n    <Insurance coverages={(results['coverages'] as Coverage[]) || []} onClickResource={onClickResource} />\n  ),\n};\n\n/** Allergies section \u2014 searches for AllergyIntolerance resources. */\nexport const AllergiesSection: PatientSummarySectionConfig = {\n  key: 'allergies',\n  title: 'Allergies',\n  searches: [{ key: 'allergies', resourceType: 'AllergyIntolerance', patientParam: 'patient' }],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => (\n    <Allergies\n      patient={patient}\n      allergies={(results['allergies'] as AllergyIntolerance[]) || []}\n      onClickResource={onClickResource}\n    />\n  ),\n};\n\n/** Problem List section \u2014 searches for Condition resources. */\nexport const ProblemListSection: PatientSummarySectionConfig = {\n  key: 'problemList',\n  title: 'Problems',\n  searches: [{ key: 'conditions', resourceType: 'Condition', patientParam: 'patient' }],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => (\n    <ProblemList\n      patient={patient}\n      problems={(results['conditions'] as Condition[]) || []}\n      onClickResource={onClickResource}\n    />\n  ),\n};\n\n/** Medications section \u2014 searches for MedicationRequest and MedicationStatement resources. */\nexport const MedicationsSection: PatientSummarySectionConfig = {\n  key: 'medications',\n  title: 'Medications',\n  searches: [\n    { key: 'medicationRequests', resourceType: 'MedicationRequest', patientParam: 'subject' },\n    { key: 'medicationStatements', resourceType: 'MedicationStatement', patientParam: 'subject' },\n  ],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => (\n    <Medications\n      patient={patient}\n      medicationRequests={(results['medicationRequests'] as MedicationRequest[]) || []}\n      medicationStatements={(results['medicationStatements'] as MedicationStatement[]) || []}\n      onClickResource={onClickResource}\n    />\n  ),\n};\n\n/** Immunizations section \u2014 searches for Immunization resources. */\nexport const ImmunizationsSection: PatientSummarySectionConfig = {\n  key: 'immunizations',\n  title: 'Immunizations',\n  searches: [{ key: 'immunizations', resourceType: 'Immunization', patientParam: 'patient' }],\n  component: ({ results, patient }: SectionRenderContext) => (\n    <Immunizations patient={patient} immunizations={(results['immunizations'] as Immunization[]) || []} />\n  ),\n};\n\n/** Goals section \u2014 searches for Goal resources. */\nexport const GoalsSection: PatientSummarySectionConfig = {\n  key: 'goals',\n  title: 'Goals',\n  searches: [{ key: 'goals', resourceType: 'Goal', patientParam: 'patient' }],\n  component: ({ results, patient }: SectionRenderContext) => (\n    <Goals patient={patient} goals={(results['goals'] as Goal[]) || []} />\n  ),\n};\n\n/**\n * Labs section \u2014 searches for both ServiceRequest and DiagnosticReport resources.\n * Accepts an optional `onRequestLabs` callback via closure.\n * @param onRequestLabs - Optional callback invoked when the user requests labs.\n * @returns A section config for labs.\n */\nexport function createLabsSection(onRequestLabs?: () => void): PatientSummarySectionConfig {\n  return {\n    key: 'labs',\n    title: 'Labs',\n    searches: [\n      { key: 'serviceRequests', resourceType: 'ServiceRequest', patientParam: 'subject' },\n      { key: 'diagnosticReports', resourceType: 'DiagnosticReport', patientParam: 'subject' },\n    ],\n    component: ({ results, patient, onClickResource }: SectionRenderContext) => (\n      <Labs\n        patient={patient}\n        serviceRequests={(results['serviceRequests'] as ServiceRequest[]) || []}\n        diagnosticReports={(results['diagnosticReports'] as DiagnosticReport[]) || []}\n        onClickResource={onClickResource}\n        onRequestLabs={onRequestLabs}\n      />\n    ),\n  };\n}\n\n/** Default Labs section constant (no onRequestLabs callback). */\nexport const LabsSection: PatientSummarySectionConfig = createLabsSection();\n\n/** Sexual Orientation section \u2014 searches for Observation resources by LOINC 76690-7. */\nexport const SexualOrientationSection: PatientSummarySectionConfig = {\n  key: 'sexualOrientation',\n  title: 'Sexual Orientation',\n  searches: [{ key: 'observations', resourceType: 'Observation', patientParam: 'subject', query: { code: '76690-7' } }],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => {\n    const observations = (results['observations'] as Observation[]) || [];\n    return (\n      <SexualOrientation patient={patient} sexualOrientation={observations[0]} onClickResource={onClickResource} />\n    );\n  },\n};\n\n/** Smoking Status section \u2014 searches for Observation resources by LOINC 72166-2. */\nexport const SmokingStatusSection: PatientSummarySectionConfig = {\n  key: 'smokingStatus',\n  title: 'Smoking Status',\n  searches: [{ key: 'observations', resourceType: 'Observation', patientParam: 'subject', query: { code: '72166-2' } }],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => {\n    const observations = (results['observations'] as Observation[]) || [];\n    return <SmokingStatus patient={patient} smokingStatus={observations[0]} onClickResource={onClickResource} />;\n  },\n};\n\n/** Vitals section \u2014 searches for Observation resources with category vital-signs. */\nexport const VitalsSection: PatientSummarySectionConfig = {\n  key: 'vitals',\n  title: 'Vitals',\n  searches: [\n    { key: 'observations', resourceType: 'Observation', patientParam: 'subject', query: { category: 'vital-signs' } },\n  ],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => {\n    const observations = (results['observations'] as Observation[]) || [];\n    return <Vitals patient={patient} vitals={observations} onClickResource={onClickResource} />;\n  },\n};\n\n/**\n * Pharmacies section \u2014 no FHIR searches; the Pharmacies component resolves its own data\n * from patient extensions.\n * Accepts an optional `pharmacyDialogComponent` via closure.\n * @param pharmacyDialogComponent - Optional component for the pharmacy search dialog.\n * @returns A section config for pharmacies.\n */\nexport function createPharmaciesSection(\n  pharmacyDialogComponent?: ComponentType<PharmacyDialogBaseProps>\n): PatientSummarySectionConfig {\n  return {\n    key: 'pharmacies',\n    title: 'Pharmacies',\n    component: ({ patient, onClickResource }: SectionRenderContext) => (\n      <Pharmacies\n        patient={patient}\n        onClickResource={onClickResource}\n        pharmacyDialogComponent={pharmacyDialogComponent}\n      />\n    ),\n  };\n}\n\n/** Default Pharmacies section constant (no pharmacy dialog component). */\nexport const PharmaciesSection: PatientSummarySectionConfig = createPharmaciesSection();\n\n/**\n * Returns the default set of sections, matching the original hardcoded PatientSummary layout.\n * The `onRequestLabs` callback is threaded through to the Labs section.\n * @param onRequestLabs - Optional callback invoked when the user requests labs.\n * @returns The default array of section configs.\n */\nexport function getDefaultSections(onRequestLabs?: () => void): PatientSummarySectionConfig[] {\n  return [\n    DemographicsSection,\n    InsuranceSection,\n    AllergiesSection,\n    ProblemListSection,\n    MedicationsSection,\n    ImmunizationsSection,\n    createLabsSection(onRequestLabs),\n    SexualOrientationSection,\n    SmokingStatusSection,\n    VitalsSection,\n    GoalsSection,\n    PharmaciesSection,\n  ];\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { getDisplayString } from '@medplum/core';\nimport type { AllergyIntolerance, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useMemo, useState } from 'react';\nimport { Modal } from '../Modal/Modal';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { AllergyDialog } from './AllergyDialog';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface AllergiesProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly allergies: AllergyIntolerance[];\n  readonly onClickResource?: (resource: AllergyIntolerance) => void;\n}\n\nexport function Allergies(props: AllergiesProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient, encounter } = props;\n  const [allergies, setAllergies] = useState(props.allergies);\n  const [opened, { open, close }] = useDisclosure(false);\n  const [editAllergy, setEditAllergy] = useState<AllergyIntolerance>();\n\n  // Sort allergies with active ones first\n  const sortedAllergies = useMemo(() => {\n    return [...allergies].sort((a, b) => {\n      const aStatus = a.clinicalStatus?.coding?.[0]?.code;\n      const bStatus = b.clinicalStatus?.coding?.[0]?.code;\n\n      // Active allergies first\n      if (aStatus === 'active' && bStatus !== 'active') {\n        return -1;\n      }\n      if (aStatus !== 'active' && bStatus === 'active') {\n        return 1;\n      }\n\n      return getDisplayString(a).localeCompare(getDisplayString(b));\n    });\n  }, [allergies]);\n\n  const handleSubmit = useCallback(\n    async (allergy: AllergyIntolerance) => {\n      if (allergy.id) {\n        const updatedAllergy = await medplum.updateResource(allergy);\n        setAllergies(allergies.map((a) => (a.id === updatedAllergy.id ? updatedAllergy : a)));\n      } else {\n        const newAllergy = await medplum.createResource(allergy);\n        setAllergies([...allergies, newAllergy]);\n      }\n      setEditAllergy(undefined);\n      close();\n    },\n    [medplum, allergies, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Allergies\"\n        onAdd={() => {\n          setEditAllergy(undefined);\n          open();\n        }}\n      >\n        {sortedAllergies.length > 0 ? (\n          <Box>\n            <Flex direction=\"column\" gap={8}>\n              {sortedAllergies.map((allergy) => {\n                const status = allergy.clinicalStatus?.coding?.[0]?.code || 'unknown';\n\n                return (\n                  <SummaryItem\n                    key={allergy.id}\n                    onClick={() => {\n                      setEditAllergy(allergy);\n                      open();\n                    }}\n                  >\n                    <Box>\n                      <Text fw={500} className={styles.itemText}>\n                        {getDisplayString(allergy)}\n                      </Text>\n                      <Group mt={2} gap={4}>\n                        {status && (\n                          <StatusBadge color={getClinicalStatusColor(status)} variant=\"light\" status={status} />\n                        )}\n                      </Group>\n                    </Box>\n                  </SummaryItem>\n                );\n              })}\n            </Flex>\n          </Box>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      <Modal opened={opened} onClose={close} title={editAllergy ? 'Edit Allergy' : 'Add Allergy'}>\n        <AllergyDialog patient={patient} encounter={encounter} allergy={editAllergy} onSubmit={handleSubmit} />\n      </Modal>\n    </>\n  );\n}\n\nfunction getClinicalStatusColor(status?: string): string {\n  if (!status) {\n    return 'gray';\n  }\n\n  switch (status) {\n    case 'active':\n      return 'red';\n    case 'inactive':\n      return 'orange';\n    case 'resolved':\n      return 'blue';\n    default:\n      return 'gray';\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { BadgeProps, DefaultMantineColor } from '@mantine/core';\nimport { Badge } from '@mantine/core';\nimport type { JSX } from 'react';\n\n/*\n * Request status: https://hl7.org/fhir/valueset-request-status.html\n * draft, active, on-hold, revoked, completed, entered-in-error, unknown\n *\n * Publication status: https://hl7.org/fhir/valueset-publication-status.html\n * draft, active, retired, unknown\n *\n * Observation status: https://www.hl7.org/fhir/valueset-observation-status.html\n * registered, preliminary, final, amended,  corrected, cancelled, entered-in-error, unknown\n *\n * DiagnosticReport status: https://hl7.org/fhir/valueset-diagnostic-report-status.html\n * registered, preliminary, final, amended, corrected, appended, cancelled, entered-in-error, unknown\n *\n * Task status: https://hl7.org/fhir/valueset-task-status.html\n * draft, requested, received, accepted, rejected, ready, cancelled, in-progress, on-hold, failed, completed, entered-in-error\n *\n * Appointment status: https://www.hl7.org/fhir/valueset-appointmentstatus.html\n * proposed, pending, booked, arrived, fulfilled, cancelled, noshow, entered-in-error, chcked-in, waitlist\n *\n * Immunization status: https://hl7.org/fhir/r4/valueset-immunization-status.html\n * completed, entered-in-error, not-done\n */\n\nconst statusToColor: Record<string, DefaultMantineColor> = {\n  draft: 'blue',\n  active: 'blue',\n  'on-hold': 'yellow',\n  revoked: 'red',\n  completed: 'green',\n  'entered-in-error': 'red',\n  unknown: 'gray',\n  retired: 'gray',\n  registered: 'blue',\n  preliminary: 'blue',\n  final: 'green',\n  amended: 'yellow',\n  corrected: 'yellow',\n  cancelled: 'red',\n  requested: 'blue',\n  received: 'blue',\n  accepted: 'blue',\n  rejected: 'red',\n  ready: 'blue',\n  'in-progress': 'blue',\n  failed: 'red',\n  proposed: 'blue',\n  pending: 'blue',\n  booked: 'blue',\n  arrived: 'blue',\n  fulfilled: 'green',\n  noshow: 'red',\n  'checked-in': 'blue',\n  waitlist: 'gray',\n  routine: 'gray',\n  urgent: 'red',\n  asap: 'red',\n  stat: 'red',\n  'not-done': 'red',\n  connected: 'green',\n  disconnected: 'red',\n  finished: 'green',\n  planned: 'gray',\n};\n\nexport interface StatusBadgeProps extends Omit<BadgeProps, 'children'> {\n  readonly status: string;\n}\n\nexport function StatusBadge(props: StatusBadgeProps): JSX.Element {\n  const { status, ...badgeProps } = props;\n\n  return (\n    <Badge color={props.color || statusToColor[status]} {...badgeProps}>\n      {status.replaceAll('-', ' ')}\n    </Badge>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Stack, TextInput } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport type { AllergyIntolerance, Encounter, Patient } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\n\nexport interface AllergyDialogProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly allergy?: AllergyIntolerance;\n  readonly onSubmit: (allergy: AllergyIntolerance) => void;\n}\n\nconst HTTP = 'http://';\n\nconst PATIENT_ALLERGY_PROFILE = HTTP_HL7_ORG + '/fhir/us/core/StructureDefinition/us-core-allergyintolerance';\n\nexport function AllergyDialog(props: AllergyDialogProps): JSX.Element {\n  const { patient, encounter, allergy, onSubmit } = props;\n  const [code, setCode] = useState(allergy?.code);\n  const [clinicalStatus, setClinicalStatus] = useState(allergy?.clinicalStatus);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      onSubmit(\n        addProfileToResource(\n          {\n            ...allergy,\n            resourceType: 'AllergyIntolerance',\n            patient: createReference(patient),\n            encounter: encounter ? createReference(encounter) : undefined,\n            code,\n            clinicalStatus,\n            onsetDateTime: formData.onsetDateTime ? formData.onsetDateTime : undefined,\n            reaction: formData.reaction ? [{ manifestation: [{ text: formData.reaction }] }] : undefined,\n          },\n          PATIENT_ALLERGY_PROFILE\n        )\n      );\n    },\n    [patient, encounter, allergy, code, clinicalStatus, onSubmit]\n  );\n\n  return (\n    <Form key={allergy?.id} onSubmit={handleSubmit}>\n      <Stack>\n        <CodeableConceptInput\n          name=\"allergy\"\n          label=\"Code\"\n          path=\"AllergyIntolerance.code\"\n          data-autofocus={true}\n          binding={HTTP + 'cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1186.8'}\n          maxValues={1}\n          defaultValue={allergy?.code}\n          onChange={(code) => setCode(code)}\n          outcome={undefined}\n        />\n        <TextInput name=\"reaction\" label=\"Reaction\" defaultValue={allergy?.reaction?.[0]?.manifestation?.[0]?.text} />\n        <CodeableConceptInput\n          name=\"clinicalStatus\"\n          label=\"Clinical Status\"\n          path=\"AllergyIntolerance.clinicalStatus\"\n          binding={HTTP_HL7_ORG + '/fhir/ValueSet/allergyintolerance-clinical'}\n          maxValues={1}\n          defaultValue={allergy?.clinicalStatus}\n          onChange={(clinicalStatus) => setClinicalStatus(clinicalStatus)}\n          outcome={undefined}\n        />\n        <DateTimeInput name=\"onsetDateTime\" label=\"Onset\" defaultValue={allergy?.recordedDate} />\n        <Group justify=\"flex-end\" gap={4} mt=\"md\">\n          <SubmitButton>Save</SubmitButton>\n        </Group>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Box, Collapse, Group, Text } from '@mantine/core';\nimport { IconChevronDown, IconPlus } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport classes from './CollapsibleSection.module.css';\n\nexport interface CollapsibleSectionProps {\n  readonly title: string;\n  readonly children: ReactNode;\n  readonly onAdd?: () => void;\n}\n\nexport function CollapsibleSection(props: CollapsibleSectionProps): JSX.Element {\n  const { title, children, onAdd } = props;\n  const [collapsed, setCollapsed] = useState(false);\n\n  return (\n    <Box className={classes.root} py=\"xs\">\n      <Group justify=\"space-between\" align=\"center\" wrap=\"nowrap\" className={classes.header}>\n        <Group gap={8} wrap=\"nowrap\">\n          <ActionIcon\n            variant=\"subtle\"\n            color=\"gray\"\n            radius=\"xl\"\n            onClick={() => setCollapsed((c) => !c)}\n            aria-label={collapsed ? `Show ${title.toLowerCase()}` : `Hide ${title.toLowerCase()}`}\n            className={classes.chevron}\n            data-collapsed={collapsed || undefined}\n            size=\"md\"\n          >\n            <IconChevronDown size={20} />\n          </ActionIcon>\n          <Text fz=\"md\" fw={800} onClick={() => setCollapsed((c) => !c)} className={classes.title}>\n            {title}\n          </Text>\n        </Group>\n\n        {onAdd && (\n          <ActionIcon\n            role=\"button\"\n            aria-label=\"Add item\"\n            className={classes.addButton}\n            variant=\"subtle\"\n            radius=\"xl\"\n            onClick={(e) => {\n              killEvent(e);\n              onAdd();\n            }}\n            size=\"md\"\n          >\n            <IconPlus size={18} />\n          </ActionIcon>\n        )}\n      </Group>\n\n      <Collapse in={!collapsed}>\n        <Box ml=\"var(--mantine-spacing-xl)\" mt=\"xs\" mb=\"md\" pl={4}>\n          {children}\n        </Box>\n      </Collapse>\n    </Box>\n  );\n}\n", "/* CollapsibleSection.module.css */\n\n.root {\n  position: relative;\n}\n\n.header {\n  width: 100%;\n  cursor: default;\n}\n\n.chevron {\n  transition: transform 0.2s ease;\n  cursor: pointer;\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1)) !important;\n}\n\n.chevron[data-collapsed] {\n  transform: rotate(-90deg);\n}\n\n@media (hover: hover) {\n  .chevron:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6)) !important;\n  }\n}\n\n.title {\n  cursor: pointer;\n}\n\n.addButton {\n  flex-shrink: 0;\n  stroke-width: 1;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Box } from '@mantine/core';\nimport { IconChevronRight } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport styles from './SummaryItem.module.css';\n\ninterface SummaryItemProps {\n  children: ReactNode;\n  onClick?: () => void;\n}\n\nexport default function SummaryItem(props: SummaryItemProps): JSX.Element {\n  const { children, onClick } = props;\n  return (\n    <Box className={cx(styles.item, onClick && styles.clickable)} onClick={onClick}>\n      {children}\n      {onClick && (\n        <>\n          <div className={styles.gradient} />\n          <div className={styles.container}>\n            <ActionIcon className={styles.chevron} size=\"md\" variant=\"transparent\" tabIndex={-1}>\n              <IconChevronRight size={16} stroke={2.5} />\n            </ActionIcon>\n          </div>\n        </>\n      )}\n    </Box>\n  );\n}\n", ".gradient {\n  position: absolute;\n  right: 28px;\n  top: 0;\n  bottom: 0;\n  width: 48px;\n\n  z-index: 1;\n  opacity: 0;\n  pointer-events: none;\n  transition: opacity 0.2s;\n}\n\n[data-mantine-color-scheme='dark'] .gradient {\n  background: linear-gradient(to right, transparent, var(--mantine-color-body));\n}\n\n[data-mantine-color-scheme='light'] .gradient {\n  background: linear-gradient(to right, transparent, var(--mantine-color-white));\n}\n\n.container {\n  position: absolute;\n  right: 0;\n  top: 0;\n  bottom: 0;\n  width: 28px;\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  opacity: 0;\n  pointer-events: none;\n  transition: opacity 0.2s;\n}\n\n[data-mantine-color-scheme='dark'] .container {\n  background: var(--mantine-color-body);\n}\n\n[data-mantine-color-scheme='light'] .container {\n  background: var(--mantine-color-white);\n}\n\n.chevron {\n  position: static;\n  margin: 0;\n  padding: 0;\n  transition: opacity 0.2s;\n  opacity: 1;\n  cursor: pointer;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.clickable:hover .gradient,\n.clickable:hover .container {\n  opacity: 1;\n  pointer-events: auto;\n}\n\n.item {\n  position: relative;\n  max-width: 100%;\n}\n\n.clickable {\n  cursor: pointer;\n}\n\n.itemText {\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatCodeableConcept, formatDate } from '@medplum/core';\nimport type { Goal, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport { GoalDialog } from './GoalDialog';\nimport { isEnteredInError } from './PatientSummary.utils';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface GoalsProps {\n  readonly patient: Patient;\n  readonly goals: Goal[];\n}\n\nexport function Goals(props: GoalsProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient } = props;\n  const [goals, setGoals] = useState(props.goals);\n  const [opened, { open, close }] = useDisclosure(false);\n  const [editGoal, setEditGoal] = useState<Goal>();\n\n  const handleSubmit = useCallback(\n    async (goal: Goal) => {\n      if (goal.id) {\n        const updated = await medplum.updateResource(goal);\n        setGoals(goals.map((g) => (g.id === updated.id ? updated : g)));\n      } else {\n        const created = await medplum.createResource(goal);\n        setGoals([created, ...goals]);\n      }\n      setEditGoal(undefined);\n      close();\n    },\n    [medplum, goals, close]\n  );\n\n  // Hide entered-in-error goals (still reachable by direct URL).\n  const visibleGoals = goals.filter((goal) => !isEnteredInError(goal));\n\n  const handleDelete = useCallback(async () => {\n    if (!editGoal?.id) {\n      return;\n    }\n    await medplum.deleteResource('Goal', editGoal.id);\n    setGoals(goals.filter((g) => g.id !== editGoal.id));\n    setEditGoal(undefined);\n    close();\n  }, [medplum, goals, editGoal, close]);\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Goals\"\n        onAdd={() => {\n          setEditGoal(undefined);\n          open();\n        }}\n      >\n        {visibleGoals.length > 0 ? (\n          <Flex direction=\"column\" gap={8}>\n            {visibleGoals.map((goal) => (\n              <SummaryItem\n                key={goal.id}\n                onClick={() => {\n                  setEditGoal(goal);\n                  open();\n                }}\n              >\n                <Box>\n                  <Text fw={500} className={styles.itemText}>\n                    {getGoalDisplay(goal)}\n                  </Text>\n                  <Group mt={2} gap={4}>\n                    {goal.lifecycleStatus && (\n                      <StatusBadge\n                        color={getGoalStatusColor(goal.lifecycleStatus)}\n                        variant=\"light\"\n                        status={goal.lifecycleStatus}\n                      />\n                    )}\n                    {getGoalDateText(goal) && (\n                      <Text size=\"xs\" fw={500} c=\"dimmed\">\n                        {getGoalDateText(goal)}\n                      </Text>\n                    )}\n                  </Group>\n                </Box>\n              </SummaryItem>\n            ))}\n          </Flex>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      {/* Mounted only while open so every open is a fresh instance, with no leftover form state. */}\n      {opened && (\n        <GoalDialog\n          patient={patient}\n          goal={editGoal}\n          opened={opened}\n          onClose={close}\n          onSubmit={handleSubmit}\n          onDelete={handleDelete}\n        />\n      )}\n    </>\n  );\n}\n\nfunction getGoalDisplay(goal: Goal): string {\n  return (goal.description && formatCodeableConcept(goal.description)) || 'Goal';\n}\n\nfunction getGoalDateText(goal: Goal): string | undefined {\n  const dueDate = goal.target?.find((target) => target.dueDate)?.dueDate;\n  if (dueDate) {\n    return `Target ${formatDate(dueDate)}`;\n  }\n  return goal.startDate ? `Started ${formatDate(goal.startDate)}` : undefined;\n}\n\nfunction getGoalStatusColor(status: string): string {\n  switch (status) {\n    case 'active':\n    case 'accepted':\n    case 'completed':\n      return 'green';\n    case 'on-hold':\n    case 'planned':\n    case 'proposed':\n      return 'yellow';\n    case 'cancelled':\n    case 'rejected':\n    case 'entered-in-error':\n      return 'red';\n    default:\n      return 'gray';\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Stack, TextInput } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport type { Goal, Patient } from '@medplum/fhirtypes';\nimport { IconTrash } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeInput } from '../CodeInput/CodeInput';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\n\nexport interface GoalDialogProps {\n  readonly patient: Patient;\n  readonly goal?: Goal;\n  readonly opened: boolean;\n  readonly onClose: () => void;\n  readonly onSubmit: (goal: Goal) => void;\n  /** When editing an existing goal, called to delete it. */\n  readonly onDelete?: () => void;\n}\n\nconst GOAL_STATUS_VALUESET = 'http://hl7.org/fhir/ValueSet/goal-status';\n\nexport function GoalDialog(props: GoalDialogProps): JSX.Element {\n  const { patient, goal, opened, onClose, onSubmit, onDelete } = props;\n  const [lifecycleStatus, setLifecycleStatus] = useState<Goal['lifecycleStatus']>(goal?.lifecycleStatus ?? 'active');\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      onSubmit({\n        ...goal,\n        resourceType: 'Goal',\n        lifecycleStatus: lifecycleStatus ?? 'active',\n        description: { text: formData.description ?? goal?.description?.text ?? '' },\n        subject: createReference(patient),\n        startDate: formData.startDate || undefined,\n        target: formData.dueDate ? [{ ...goal?.target?.[0], dueDate: formData.dueDate }] : goal?.target,\n      });\n    },\n    [patient, goal, lifecycleStatus, onSubmit]\n  );\n\n  return (\n    <Modal\n      opened={opened}\n      onClose={onClose}\n      title={goal ? 'Edit Goal' : 'Add Goal'}\n      size=\"md\"\n      onSubmit={handleSubmit}\n      actions={\n        <>\n          <SubmitButton>Save</SubmitButton>\n          {goal?.id && onDelete && (\n            <Button variant=\"light\" color=\"red\" leftSection={<IconTrash size={16} />} onClick={onDelete}>\n              Delete\n            </Button>\n          )}\n        </>\n      }\n    >\n      <Stack gap=\"md\">\n        <TextInput\n          name=\"description\"\n          label=\"Goal\"\n          data-autofocus={true}\n          required\n          defaultValue={goal?.description?.text}\n        />\n        <CodeInput\n          name=\"lifecycleStatus\"\n          label=\"Status\"\n          binding={GOAL_STATUS_VALUESET}\n          maxValues={1}\n          defaultValue={goal?.lifecycleStatus ?? 'active'}\n          onChange={(value) => setLifecycleStatus((value as Goal['lifecycleStatus']) ?? undefined)}\n        />\n        <TextInput type=\"date\" name=\"startDate\" label=\"Start Date\" defaultValue={goal?.startDate} />\n        <TextInput type=\"date\" name=\"dueDate\" label=\"Target Date\" defaultValue={goal?.target?.[0]?.dueDate} />\n      </Stack>\n    </Modal>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { capitalize, getExtension, HTTP_HL7_ORG } from '@medplum/core';\nimport type { CodeableConcept, Patient, Resource } from '@medplum/fhirtypes';\n\n/**\n * Returns true when a resource has been marked `entered-in-error`. Such resources are hidden from\n * list/summary views (they remain accessible by direct URL). The error state lives in different\n * fields depending on resource type: `.status` (most), `.lifecycleStatus` (Goal), and\n * `.verificationStatus` (AllergyIntolerance, Condition).\n * @param resource - The resource to check.\n * @returns True if the resource is entered-in-error.\n */\nexport function isEnteredInError(resource: Resource): boolean {\n  const candidate = resource as Resource & {\n    status?: string;\n    lifecycleStatus?: string;\n    verificationStatus?: CodeableConcept;\n  };\n  if (candidate.status === 'entered-in-error' || candidate.lifecycleStatus === 'entered-in-error') {\n    return true;\n  }\n  return !!candidate.verificationStatus?.coding?.some((coding) => coding.code === 'entered-in-error');\n}\n\nexport function getGenderIdentity(patient: Patient): string | undefined {\n  const genderIdentityExt = getExtension(\n    patient,\n    `${HTTP_HL7_ORG}/fhir/us/core/StructureDefinition/us-core-genderIdentity`\n  );\n  return genderIdentityExt?.valueCodeableConcept?.coding?.[0]?.display;\n}\n\nexport function getBirthSex(patient: Patient): string | undefined {\n  const birthSexExt = getExtension(patient, `${HTTP_HL7_ORG}/fhir/us/core/StructureDefinition/us-core-birthsex`);\n  return birthSexExt?.valueCode;\n}\n\nexport function getRace(patient: Patient): string | undefined {\n  const raceExt = getExtension(patient, `${HTTP_HL7_ORG}/fhir/us/core/StructureDefinition/us-core-race`);\n  return raceExt?.extension?.find((subExt) => subExt.url === 'ombCategory')?.valueCoding?.display;\n}\n\nexport function getEthnicity(patient: Patient): string | undefined {\n  const ethnicityExt = getExtension(patient, `${HTTP_HL7_ORG}/fhir/us/core/StructureDefinition/us-core-ethnicity`);\n  return ethnicityExt?.extension?.find((subExt) => subExt.url === 'ombCategory')?.valueCoding?.display;\n}\n\nexport function getGeneralPractitioner(patient: Patient): string | undefined {\n  return patient.generalPractitioner?.[0]?.display;\n}\n\nexport function formatPatientGenderDisplay(patient: Patient): string {\n  const capitalizedGender = patient.gender ? capitalize(patient.gender) : '';\n\n  const genderIdentity = getGenderIdentity(patient);\n  const birthSex = getBirthSex(patient);\n\n  const parts: string[] = [];\n\n  if (capitalizedGender) {\n    parts.push(capitalizedGender);\n  }\n\n  if (genderIdentity) {\n    parts.push(genderIdentity);\n  }\n\n  if (birthSex) {\n    parts.push(`Born as ${birthSex}`);\n  }\n\n  return parts.join(' \u00B7 ');\n}\n\nexport function formatPatientRaceEthnicityDisplay(patient: Patient): string {\n  const race = getRace(patient);\n  const ethnicity = getEthnicity(patient);\n  const parts: string[] = [];\n\n  if (race) {\n    parts.push(race);\n  }\n  if (ethnicity) {\n    parts.push(ethnicity);\n  }\n\n  return parts.join(' \u00B7 ');\n}\n\n/**\n * Formats a FHIR status/lifecycleStatus code for display: removes hyphens and capitalizes each word.\n * e.g. 'on-hold' \u2192 'On Hold', 'not-done' \u2192 'Not Done', 'active' \u2192 'Active'.\n * @param status - The raw status code.\n * @returns The human-friendly, capitalized, hyphen-free label.\n */\nexport function formatStatusLabel(status: string): string {\n  return status\n    .split('-')\n    .map((word) => capitalize(word))\n    .join(' ');\n}\n\nexport const getPreferredLanguage = (patient: Patient): string | undefined => {\n  if (!patient.communication?.length) {\n    return undefined;\n  }\n\n  const preferred = patient.communication?.find((comm) => comm.preferred === true);\n  if (preferred?.language?.coding?.[0]?.display) {\n    return preferred.language.coding[0].display;\n  }\n\n  return patient.communication[0]?.language?.coding?.[0]?.display;\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatCodeableConcept, formatDate } from '@medplum/core';\nimport type { Encounter, Immunization, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport { ImmunizationDialog } from './ImmunizationDialog';\nimport { isEnteredInError } from './PatientSummary.utils';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface ImmunizationsProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly immunizations: Immunization[];\n}\n\nexport function Immunizations(props: ImmunizationsProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient, encounter } = props;\n  const [immunizations, setImmunizations] = useState(props.immunizations);\n  const [opened, { open, close }] = useDisclosure(false);\n  const [editImmunization, setEditImmunization] = useState<Immunization>();\n\n  // Hide entered-in-error immunizations (still reachable by direct URL); most recent first.\n  const sortedImmunizations = [...immunizations]\n    .filter((immunization) => !isEnteredInError(immunization))\n    .sort((a, b) => (b.occurrenceDateTime ?? '').localeCompare(a.occurrenceDateTime ?? ''));\n\n  const handleSubmit = useCallback(\n    async (immunization: Immunization) => {\n      if (immunization.id) {\n        const updated = await medplum.updateResource(immunization);\n        setImmunizations(immunizations.map((i) => (i.id === updated.id ? updated : i)));\n      } else {\n        const created = await medplum.createResource(immunization);\n        setImmunizations([created, ...immunizations]);\n      }\n      setEditImmunization(undefined);\n      close();\n    },\n    [medplum, immunizations, close]\n  );\n\n  const handleDelete = useCallback(async () => {\n    if (!editImmunization?.id) {\n      return;\n    }\n    await medplum.deleteResource('Immunization', editImmunization.id);\n    setImmunizations(immunizations.filter((i) => i.id !== editImmunization.id));\n    setEditImmunization(undefined);\n    close();\n  }, [medplum, immunizations, editImmunization, close]);\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Immunizations\"\n        onAdd={() => {\n          setEditImmunization(undefined);\n          open();\n        }}\n      >\n        {sortedImmunizations.length > 0 ? (\n          <Flex direction=\"column\" gap={8}>\n            {sortedImmunizations.map((immunization) => (\n              <SummaryItem\n                key={immunization.id}\n                onClick={() => {\n                  setEditImmunization(immunization);\n                  open();\n                }}\n              >\n                <Box>\n                  <Text fw={500} className={styles.itemText}>\n                    {getImmunizationDisplay(immunization)}\n                  </Text>\n                  <Group mt={2} gap={4}>\n                    {immunization.status && (\n                      <StatusBadge\n                        color={getImmunizationStatusColor(immunization.status)}\n                        variant=\"light\"\n                        status={immunization.status}\n                      />\n                    )}\n                    {immunization.occurrenceDateTime && (\n                      <Text size=\"xs\" fw={500} c=\"dimmed\">\n                        Given {formatDate(immunization.occurrenceDateTime)}\n                      </Text>\n                    )}\n                  </Group>\n                </Box>\n              </SummaryItem>\n            ))}\n          </Flex>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      {/* Mounted only while open so every open is a fresh instance, with no leftover form state. */}\n      {opened && (\n        <ImmunizationDialog\n          patient={patient}\n          encounter={encounter}\n          immunization={editImmunization}\n          opened={opened}\n          onClose={close}\n          onSubmit={handleSubmit}\n          onDelete={handleDelete}\n        />\n      )}\n    </>\n  );\n}\n\nfunction getImmunizationDisplay(immunization: Immunization): string {\n  return (immunization.vaccineCode && formatCodeableConcept(immunization.vaccineCode)) || 'Immunization';\n}\n\nfunction getImmunizationStatusColor(status: string): string {\n  switch (status) {\n    case 'completed':\n      return 'green';\n    case 'not-done':\n      return 'gray';\n    case 'entered-in-error':\n      return 'red';\n    default:\n      return 'gray';\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Radio, Stack } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport type { Encounter, Immunization, Patient } from '@medplum/fhirtypes';\nimport { IconTrash } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { convertLocalToIso } from '../DateTimeInput/DateTimeInput.utils';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport { formatStatusLabel } from './PatientSummary.utils';\n\nexport interface ImmunizationDialogProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly immunization?: Immunization;\n  readonly opened: boolean;\n  readonly onClose: () => void;\n  readonly onSubmit: (immunization: Immunization) => void;\n  /** When editing an existing immunization, called to delete it. */\n  readonly onDelete?: () => void;\n}\n\nconst statusValues: Immunization['status'][] = ['completed', 'not-done'];\n\nexport function ImmunizationDialog(props: ImmunizationDialogProps): JSX.Element {\n  const { patient, encounter, immunization, opened, onClose, onSubmit, onDelete } = props;\n  const [vaccineCode, setVaccineCode] = useState(immunization?.vaccineCode);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      onSubmit({\n        ...immunization,\n        resourceType: 'Immunization',\n        status: (formData.status as Immunization['status']) ?? 'completed',\n        patient: createReference(patient),\n        encounter: immunization?.encounter ?? (encounter && createReference(encounter)),\n        vaccineCode: vaccineCode ?? { text: '' },\n        occurrenceDateTime: formData.occurrenceDateTime\n          ? convertLocalToIso(formData.occurrenceDateTime)\n          : (immunization?.occurrenceDateTime ?? ''),\n      });\n    },\n    [patient, encounter, immunization, vaccineCode, onSubmit]\n  );\n\n  return (\n    <Modal\n      opened={opened}\n      onClose={onClose}\n      title={immunization ? 'Edit Immunization' : 'Add Immunization'}\n      size=\"md\"\n      onSubmit={handleSubmit}\n      actions={\n        <>\n          <SubmitButton>Save</SubmitButton>\n          {immunization?.id && onDelete && (\n            <Button variant=\"light\" color=\"red\" leftSection={<IconTrash size={16} />} onClick={onDelete}>\n              Delete\n            </Button>\n          )}\n        </>\n      }\n    >\n      <Stack gap=\"md\">\n        <CodeableConceptInput\n          name=\"vaccineCode\"\n          label=\"Vaccine\"\n          path=\"Immunization.vaccineCode\"\n          data-autofocus={true}\n          binding=\"http://hl7.org/fhir/ValueSet/vaccine-code\"\n          maxValues={1}\n          defaultValue={immunization?.vaccineCode}\n          onChange={(value) => setVaccineCode(value)}\n          outcome={undefined}\n        />\n        <DateTimeInput\n          name=\"occurrenceDateTime\"\n          label=\"Date Given\"\n          defaultValue={immunization?.occurrenceDateTime}\n          required\n        />\n        <Radio.Group name=\"status\" label=\"Status\" required defaultValue={immunization?.status ?? 'completed'}>\n          {statusValues.map((sv) => (\n            <Radio key={sv} value={sv} label={formatStatusLabel(sv as string)} my=\"xs\" required />\n          ))}\n        </Radio.Group>\n      </Stack>\n    </Modal>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { formatDate } from '@medplum/core';\nimport type { Coverage, Organization, Reference } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport styles from './PatientSummary.module.css';\nimport SummaryItem from './SummaryItem';\n\nexport interface CoverageItemProps {\n  readonly coverage: Coverage | Reference<Coverage>;\n  readonly organization?: Organization | Reference<Organization>;\n  readonly onClickResource?: (resource: Coverage) => void;\n}\n\nexport function CoverageItem(props: CoverageItemProps): JSX.Element {\n  const { coverage, organization, onClickResource } = props;\n  const coverageResource = useResource(coverage);\n  const organizationResource = useResource(organization);\n  let payorName = 'Unknown Payor';\n  if (organizationResource) {\n    if ('name' in organizationResource && typeof organizationResource.name === 'string') {\n      payorName = organizationResource.name;\n    }\n  }\n\n  const detailsText = `ID: ${coverageResource?.subscriberId ?? 'N/A'}${\n    formatClassInfo(coverageResource) ? ` \u00B7 ${formatClassInfo(coverageResource)}` : ''\n  }`;\n\n  return (\n    <SummaryItem\n      onClick={() => {\n        if (coverageResource) {\n          onClickResource?.(coverageResource);\n        }\n      }}\n    >\n      <Box>\n        <Text fw={500} className={styles.itemText}>\n          {payorName}\n        </Text>\n        <Text fw={500} className={styles.itemText}>\n          {detailsText}\n        </Text>\n        <Group mt={2} gap={4}>\n          <StatusBadge color=\"green\" variant=\"light\" status=\"Active\" />\n          <Text size=\"xs\" fw={500} color=\"gray.6\">\n            Ends {formatDate(coverageResource?.period?.end)}\n          </Text>\n        </Group>\n      </Box>\n    </SummaryItem>\n  );\n}\n\nexport interface InsuranceProps {\n  readonly coverages: Coverage[];\n  readonly onClickResource?: (resource: Coverage) => void;\n}\n\nexport function Insurance(props: InsuranceProps): JSX.Element {\n  const { coverages, onClickResource } = props;\n\n  const activeCoverages = coverages.filter(\n    (coverage) => coverage.status === 'active' && !coverage.type?.coding?.some((coding) => coding.code === 'SELFPAY')\n  );\n\n  return (\n    <CollapsibleSection title=\"Insurance\">\n      {activeCoverages.length > 0 ? (\n        <Flex direction=\"column\" gap={8}>\n          {activeCoverages.map((coverage) => (\n            <CoverageItem\n              key={coverage.id}\n              coverage={coverage}\n              organization={coverage.payor?.[0] as Reference<Organization>}\n              onClickResource={onClickResource}\n            />\n          ))}\n        </Flex>\n      ) : (\n        <Text>(none)</Text>\n      )}\n    </CollapsibleSection>\n  );\n}\n\nfunction capitalizeWords(str: string): string {\n  return str\n    .split(' ')\n    .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n    .join(' ');\n}\n\nfunction formatClassInfo(coverage: Coverage | undefined): string {\n  if (!coverage) {\n    return '';\n  }\n  const classInfo = coverage.class\n    ?.filter((cls) => cls.type?.coding?.[0]?.code !== 'plan')\n    .map((cls) => {\n      const type = cls.type?.coding?.[0]?.code ?? '';\n      return `${capitalizeWords(type)}: ${cls.value}`;\n    })\n    .join(' \u00B7 ');\n  return classInfo ?? '';\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatDate, getDisplayString } from '@medplum/core';\nimport type { CodeableConcept, DiagnosticReport, Patient, Resource, ServiceRequest } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { DiagnosticReportDisplay } from '../DiagnosticReportDisplay/DiagnosticReportDisplay';\nimport { Modal } from '../Modal/Modal';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface LabsProps {\n  readonly patient: Patient;\n  readonly serviceRequests: ServiceRequest[];\n  readonly diagnosticReports: DiagnosticReport[];\n  readonly onClickResource?: (resource: Resource) => void;\n  readonly onRequestLabs?: () => void;\n}\n\nexport function Labs(props: LabsProps): JSX.Element {\n  const { serviceRequests, diagnosticReports, onClickResource, onRequestLabs } = props;\n  const [selectedReport, setSelectedReport] = useState<DiagnosticReport | undefined>();\n  const [reportDialogOpened, { open: openReportDialog, close: closeReportDialog }] = useDisclosure(false);\n\n  // Get all Diagnostic Reports that are code LAB.\n  // Build a set of all Service Requests that are based on these Diagnostic Reports.\n  const diagnosticReportsRequests = new Set<string>();\n  const filteredDiagnosticReports = diagnosticReports.filter((report) => {\n    const flag = isLaboratoryReport(report);\n    if (flag && report.basedOn) {\n      report.basedOn.forEach((basedOn) => {\n        if (basedOn.reference?.startsWith('ServiceRequest/')) {\n          const [, id] = basedOn.reference.split('/');\n          diagnosticReportsRequests.add(id);\n        }\n      });\n    }\n    return flag;\n  });\n\n  // Filter out Service Requests that are based on Diagnostic Reports.\n  // Filter out multiple service requests with the same requisition number.\n  const completedRequisitionNumbers = new Set<string>();\n  const filteredServiceRequests = serviceRequests.filter((request) => {\n    if (request.id && diagnosticReportsRequests.has(request.id)) {\n      return false;\n    }\n\n    // If the ServiceRequest is also based on a parent ServiceRequest, skip it.\n    if (request.basedOn) {\n      const basedOn = request.basedOn.find((basedOn) => {\n        if (basedOn.reference?.startsWith('ServiceRequest/')) {\n          const [, id] = basedOn.reference.split('/');\n          return diagnosticReportsRequests.has(id);\n        }\n        return false;\n      });\n      if (basedOn) {\n        return false;\n      }\n    }\n\n    const shouldFilter = shouldFilterRequest(request, completedRequisitionNumbers);\n    if (!shouldFilter && request.requisition?.value) {\n      completedRequisitionNumbers.add(request.requisition?.value);\n    }\n    return !shouldFilter;\n  });\n\n  const handleDiagnosticReportClick = (report: DiagnosticReport): void => {\n    setSelectedReport(report);\n    openReportDialog();\n  };\n\n  return (\n    <>\n      <CollapsibleSection title=\"Labs\" onAdd={() => onRequestLabs?.()}>\n        <Flex direction=\"column\" gap={8}>\n          {filteredServiceRequests.map((serviceRequest) => (\n            <SummaryItem key={serviceRequest.id} onClick={() => onClickResource?.(serviceRequest)}>\n              <Box>\n                <Text fw={500} className={styles.itemText}>\n                  {getDisplayString(serviceRequest)}\n                </Text>\n                <Group mt={2} gap={4}>\n                  {serviceRequest.status && (\n                    <StatusBadge\n                      color={getStatusColor(serviceRequest.status)}\n                      variant=\"light\"\n                      status={serviceRequest.status}\n                    />\n                  )}\n                  <Text size=\"xs\" fw={500} c=\"dimmed\">\n                    {formatDate(serviceRequest.authoredOn)}\n                  </Text>\n                </Group>\n              </Box>\n            </SummaryItem>\n          ))}\n\n          {filteredDiagnosticReports.map((report) => (\n            <SummaryItem key={report.id} onClick={() => handleDiagnosticReportClick(report)}>\n              <Box>\n                <Text fw={500} className={styles.itemText}>\n                  {getDisplayString(report)}\n                </Text>\n                <Group mt={2} gap={4}>\n                  {report.status && (\n                    <StatusBadge color={getStatusColor(report.status)} variant=\"light\" status={report.status} />\n                  )}\n                  <Text size=\"xs\" fw={500} c=\"dimmed\">\n                    {formatDate(report.issued)}\n                  </Text>\n                </Group>\n              </Box>\n            </SummaryItem>\n          ))}\n\n          {filteredServiceRequests.length === 0 && filteredDiagnosticReports.length === 0 && <Text>(none)</Text>}\n        </Flex>\n      </CollapsibleSection>\n      <Modal opened={reportDialogOpened} onClose={closeReportDialog} title=\"Lab Results\" size=\"80%\">\n        {selectedReport && <DiagnosticReportDisplay value={selectedReport} hideSubject={true} />}\n      </Modal>\n    </>\n  );\n}\n\nconst getStatusColor = (status: string): string => {\n  switch (status) {\n    case 'active':\n      return 'indigo';\n    case 'final':\n      return 'teal';\n    case 'cancelled':\n      return 'red';\n    default:\n      return 'gray';\n  }\n};\n\nfunction hasLaboratoryCategory(category: CodeableConcept): boolean {\n  if (!category.coding || !Array.isArray(category.coding)) {\n    return false;\n  }\n\n  for (const coding of category.coding) {\n    if (coding.code === 'LAB') {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction isLaboratoryReport(report: DiagnosticReport): boolean {\n  if (!report.category || !Array.isArray(report.category)) {\n    return false;\n  }\n  for (const category of report.category) {\n    if (hasLaboratoryCategory(category)) {\n      return true;\n    }\n  }\n\n  return false;\n}\n\nfunction shouldFilterRequest(request: ServiceRequest, completedRequisitionNumbers: Set<string>): boolean {\n  if (['completed', 'draft', 'entered-in-error'].includes(request.status)) {\n    return true;\n  }\n\n  const requisitionNumber = request.requisition?.value;\n  if (requisitionNumber && completedRequisitionNumbers.has(requisitionNumber)) {\n    return true;\n  }\n\n  return false;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Group, List, Stack, Text, Title } from '@mantine/core';\nimport type { MedplumClient } from '@medplum/core';\nimport {\n  formatAddress,\n  formatCodeableConcept,\n  formatDateTime,\n  formatHumanName,\n  formatObservationValue,\n  getDisplayString,\n  isReference,\n} from '@medplum/core';\nimport type {\n  Annotation,\n  CareTeam,\n  DiagnosticReport,\n  Observation,\n  ObservationComponent,\n  ObservationReferenceRange,\n  Organization,\n  OrganizationContact,\n  Patient,\n  Practitioner,\n  PractitionerRole,\n  Reference,\n  RelatedPerson,\n  Specimen,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { useEffect, useState } from 'react';\nimport { AddressDisplay } from '../AddressDisplay/AddressDisplay';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { ContactPointDisplay } from '../ContactPointDisplay/ContactPointDisplay';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { NoteDisplay } from '../NoteDisplay/NoteDisplay';\nimport { RangeDisplay } from '../RangeDisplay/RangeDisplay';\nimport { ReferenceDisplay } from '../ReferenceDisplay/ReferenceDisplay';\nimport { ResourceBadge } from '../ResourceBadge/ResourceBadge';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport classes from './DiagnosticReportDisplay.module.css';\n\nexport interface DiagnosticReportDisplayProps {\n  readonly value?: DiagnosticReport | Reference<DiagnosticReport>;\n  readonly hideObservationNotes?: boolean;\n  readonly hideSpecimenInfo?: boolean;\n  readonly hideSubject?: boolean;\n}\n\nDiagnosticReportDisplay.defaultProps = {\n  hideObservationNotes: false,\n  hideSpecimenInfo: false,\n  hideSubject: false,\n} as DiagnosticReportDisplayProps;\n\nexport function DiagnosticReportDisplay(props: DiagnosticReportDisplayProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const diagnosticReport = useResource(props.value);\n  const [specimens, setSpecimens] = useState<Specimen[]>();\n\n  useEffect(() => {\n    if (diagnosticReport?.specimen) {\n      Promise.allSettled(diagnosticReport.specimen.map((ref) => medplum.readReference(ref)))\n        .then((outcomes) =>\n          outcomes\n            .filter((outcome) => outcome.status === 'fulfilled')\n            .map((outcome) => (outcome as PromiseFulfilledResult<Specimen>).value)\n        )\n        .then(setSpecimens)\n        .catch(console.error);\n    }\n  }, [medplum, diagnosticReport]);\n\n  if (!diagnosticReport) {\n    return null;\n  }\n\n  const specimenNotes: Annotation[] = specimens?.flatMap((spec) => spec.note || []) || [];\n\n  if (diagnosticReport.presentedForm && diagnosticReport.presentedForm.length > 0) {\n    const pf = diagnosticReport.presentedForm[0];\n    if (pf.contentType?.startsWith('text/plain') && pf.data) {\n      specimenNotes.push({ text: window.atob(pf.data) });\n    }\n  }\n\n  return (\n    <Stack>\n      <Title>Diagnostic Report</Title>\n      <DiagnosticReportHeader value={diagnosticReport} hideSubject={props.hideSubject} />\n      {specimens && !props.hideSpecimenInfo && SpecimenInfo(specimens)}\n      {diagnosticReport.result && (\n        <ObservationTable hideObservationNotes={props.hideObservationNotes} value={diagnosticReport.result} />\n      )}\n      {specimenNotes.length > 0 && <NoteDisplay value={specimenNotes} />}\n      {diagnosticReport.conclusion && (\n        <Stack mt=\"md\">\n          <Text fw={500} size=\"sm\" c=\"dimmed\">\n            Conclusion\n          </Text>\n          <Text>{diagnosticReport.conclusion}</Text>\n        </Stack>\n      )}\n      <PerformingLabs value={diagnosticReport} />\n    </Stack>\n  );\n}\n\ninterface DiagnosticReportHeaderProps {\n  readonly value: DiagnosticReport;\n  readonly hideSubject?: boolean;\n}\n\nfunction DiagnosticReportHeader({ value, hideSubject = false }: DiagnosticReportHeaderProps): JSX.Element {\n  const basedOn = useResource(value.basedOn?.[0]);\n  const requester = basedOn?.resourceType === 'ServiceRequest' ? basedOn.requester : undefined;\n  const showSubject = Boolean(value.subject && !hideSubject);\n  const hasLeftColumn = showSubject || Boolean(requester) || Boolean(value.resultsInterpreter?.length);\n  const hasRightColumn = Boolean(value.performer?.length || value.issued || value.status);\n  return (\n    <Group mt=\"md\" gap=\"xl\" align=\"stretch\" wrap=\"nowrap\">\n      {hasLeftColumn && (\n        <Stack gap=\"md\" style={{ flex: 1 }}>\n          {showSubject && (\n            <HeaderField label=\"Subject\">\n              <ResourceBadge value={value.subject} link={true} />\n            </HeaderField>\n          )}\n          {requester && (\n            <HeaderField label=\"Ordering\">\n              <ResourceBadge value={requester} link={true} />\n            </HeaderField>\n          )}\n          {value.resultsInterpreter?.map((interpreter) => (\n            <HeaderField key={interpreter.reference} label=\"Interpreter\">\n              <ResourceBadge value={interpreter} link={true} />\n            </HeaderField>\n          ))}\n        </Stack>\n      )}\n      {hasLeftColumn && hasRightColumn && <Divider orientation=\"vertical\" />}\n      {hasRightColumn && (\n        <Stack gap=\"md\" style={{ flex: 1 }}>\n          {value.performer?.map((performer) => (\n            <HeaderField key={performer.reference} label=\"Performer\">\n              <PerformerDisplay value={performer} />\n            </HeaderField>\n          ))}\n          {value.issued && (\n            <HeaderField label=\"Issued\">\n              <Text>{formatDateTime(value.issued)}</Text>\n            </HeaderField>\n          )}\n          {value.status && (\n            <HeaderField label=\"Status\">\n              <StatusBadge status={value.status} />\n            </HeaderField>\n          )}\n        </Stack>\n      )}\n    </Group>\n  );\n}\n\ninterface HeaderFieldProps {\n  readonly label: string;\n  readonly children: ReactNode;\n}\n\nfunction HeaderField({ label, children }: HeaderFieldProps): JSX.Element {\n  return (\n    <Group gap=\"md\" align=\"flex-start\" wrap=\"nowrap\">\n      <Text c=\"dimmed\" w={110} style={{ flexShrink: 0 }}>\n        {label}\n      </Text>\n      <div>{children}</div>\n    </Group>\n  );\n}\n\ninterface PerformerDisplayProps {\n  readonly value: NonNullable<DiagnosticReport['performer']>[number];\n}\n\nfunction PerformerDisplay({ value }: PerformerDisplayProps): JSX.Element {\n  const performer = useResource(value);\n  const address = performer?.resourceType === 'Organization' ? performer.address?.[0] : undefined;\n  return (\n    <>\n      <ResourceBadge value={value} link={true} />\n      {address && (\n        <Text size=\"sm\" c=\"dimmed\" mt={4} ml={34}>\n          <AddressDisplay value={address} />\n        </Text>\n      )}\n    </>\n  );\n}\n\nfunction SpecimenInfo(specimens: Specimen[] | undefined): JSX.Element {\n  return (\n    <Stack gap=\"xs\">\n      <Title order={2} size=\"h6\">\n        Specimens\n      </Title>\n\n      <List type=\"ordered\">\n        {specimens?.map((specimen) => (\n          <List.Item ml=\"sm\" key={`specimen-${specimen.id}`}>\n            <Group gap={20}>\n              <Group gap={5}>\n                <Text fw={500}>Collected:</Text> {formatDateTime(specimen.collection?.collectedDateTime)}\n              </Group>\n              <Group gap={5}>\n                <Text fw={500}>Received:</Text> {formatDateTime(specimen.receivedTime)}\n              </Group>\n            </Group>\n          </List.Item>\n        ))}\n      </List>\n    </Stack>\n  );\n}\n\nexport interface ObservationTableProps {\n  readonly value?: Observation[] | Reference<Observation>[];\n  readonly ancestorIds?: string[];\n  readonly hideObservationNotes?: boolean;\n}\n\nexport function ObservationTable(props: ObservationTableProps): JSX.Element {\n  return (\n    <table className={classes.table}>\n      <thead>\n        <tr>\n          <th>Test</th>\n          <th>Value</th>\n          <th>Reference Range</th>\n          <th>Interpretation</th>\n          <th>Category</th>\n          <th>Performer</th>\n          <th>Status</th>\n        </tr>\n      </thead>\n      <tbody>\n        <ObservationRowGroup\n          value={props.value}\n          ancestorIds={props.ancestorIds}\n          hideObservationNotes={props.hideObservationNotes}\n        />\n      </tbody>\n    </table>\n  );\n}\n\ninterface ObservationRowGroupProps {\n  readonly value?: Observation[] | Reference<Observation>[];\n  readonly ancestorIds?: string[];\n  readonly hideObservationNotes?: boolean;\n}\n\nfunction ObservationRowGroup(props: ObservationRowGroupProps): JSX.Element {\n  return (\n    <>\n      {props.value?.map((observation) => (\n        <ObservationRow\n          key={`obs-${isReference(observation) ? observation.reference : observation.id}`}\n          value={observation}\n          ancestorIds={props.ancestorIds}\n          hideObservationNotes={props.hideObservationNotes}\n        />\n      ))}\n    </>\n  );\n}\n\ninterface ObservationRowProps {\n  readonly value: Observation | Reference<Observation>;\n  readonly ancestorIds?: string[];\n  readonly hideObservationNotes?: boolean;\n}\n\nfunction ObservationRow(props: ObservationRowProps): JSX.Element | null {\n  const observation = useResource(props.value);\n\n  if (!observation || props.ancestorIds?.includes(observation.id)) {\n    return null;\n  }\n\n  if (isDoNotReportObservation(observation)) {\n    return null;\n  }\n\n  const displayNotes = !props.hideObservationNotes && observation.note;\n\n  const critical = isCritical(observation);\n\n  const depth = props.ancestorIds?.length ?? 0;\n\n  const memberRows = observation.hasMember && (\n    <ObservationRowGroup\n      value={observation.hasMember as Reference<Observation>[]}\n      ancestorIds={props.ancestorIds ? [...props.ancestorIds, observation.id] : [observation.id]}\n      hideObservationNotes={props.hideObservationNotes}\n    />\n  );\n\n  if (isGroupingObservation(observation)) {\n    return (\n      <>\n        <tr className={classes.groupHeaderRow}>\n          <td colSpan={7} style={indentStyle(depth)}>\n            <Group gap=\"sm\">\n              <MedplumLink to={observation}>\n                <CodeableConceptDisplay value={observation.code} />\n              </MedplumLink>\n              {observation.effectiveDateTime && (\n                <Text size=\"sm\" c=\"dimmed\" fw={400}>\n                  Collected: {formatDateTime(observation.effectiveDateTime)}\n                </Text>\n              )}\n            </Group>\n          </td>\n        </tr>\n        {displayNotes && (\n          <tr>\n            <td colSpan={7} style={indentStyle(depth + 1)}>\n              <NoteDisplay value={observation.note} />\n            </td>\n          </tr>\n        )}\n        {memberRows}\n      </>\n    );\n  }\n\n  return (\n    <>\n      <tr className={cx({ [classes.criticalRow]: critical })}>\n        <td rowSpan={displayNotes ? 2 : 1} style={indentStyle(depth)}>\n          <MedplumLink to={observation}>\n            <CodeableConceptDisplay value={observation.code} />\n          </MedplumLink>\n        </td>\n        <td>\n          <ObservationValueDisplay value={observation} />\n        </td>\n        <td>\n          <ReferenceRangeDisplay value={observation.referenceRange} />\n        </td>\n        <td>\n          {observation.interpretation && observation.interpretation.length > 0 && (\n            <CodeableConceptDisplay value={observation.interpretation[0]} />\n          )}\n        </td>\n        <td>\n          {observation.category && observation.category.length > 0 && (\n            <>\n              {observation.category.map((concept) => (\n                <div key={`category-${formatCodeableConcept(concept)}`}>\n                  <CodeableConceptDisplay value={concept} />\n                </div>\n              ))}\n            </>\n          )}\n        </td>\n        <td>\n          {observation.performer?.map((performer) => (\n            <ObservationPerformerDisplay key={performer.reference} value={performer} />\n          ))}\n        </td>\n        <td>{observation.status && <StatusBadge status={observation.status} />}</td>\n      </tr>\n      {memberRows}\n      {displayNotes && (\n        <tr>\n          <td colSpan={6}>\n            <NoteDisplay value={observation.note} />\n          </td>\n        </tr>\n      )}\n    </>\n  );\n}\n\ninterface ObservationPerformerDisplayProps {\n  readonly value: Reference<Practitioner | PractitionerRole | Organization | CareTeam | Patient | RelatedPerson>;\n}\n\nfunction ObservationPerformerDisplay(props: ObservationPerformerDisplayProps): JSX.Element {\n  const performer = useResource(props.value);\n  if (!performer) {\n    return <ReferenceDisplay value={props.value} />;\n  }\n  return <MedplumLink to={props.value}>{getDisplayString(performer)}</MedplumLink>;\n}\n\ninterface ObservationValueDisplayProps {\n  readonly value?: Observation | ObservationComponent;\n}\n\nfunction ObservationValueDisplay(props: ObservationValueDisplayProps): JSX.Element | null {\n  const obs = props.value;\n  return <>{formatObservationValue(obs)}</>;\n}\n\ninterface ReferenceRangeProps {\n  readonly value?: ObservationReferenceRange[];\n}\n\nfunction ReferenceRangeDisplay(props: ReferenceRangeProps): JSX.Element | null {\n  const range = props.value && props.value.length > 0 && props.value[0];\n  if (!range) {\n    return null;\n  }\n  if (range.text) {\n    return <>{range.text}</>;\n  }\n  return <RangeDisplay value={range} />;\n}\n\n/**\n * Indents a table cell by nesting depth, so members read as belonging to the group above them.\n * @param depth - The nesting depth of the observation, where the report's own results are depth 0.\n * @returns Style props for the cell.\n */\nfunction indentStyle(depth: number): { paddingInlineStart: string } | undefined {\n  return depth > 0 ? { paddingInlineStart: `calc(4px + ${depth} * var(--mantine-spacing-md))` } : undefined;\n}\n\n/**\n * Sentinel value Quest Diagnostics uses for a sub-result that was intentionally not reported,\n * such as a skipped reflex microscopy panel. Stands for \"Do Not Report\".\n */\nconst DO_NOT_REPORT_VALUE = 'DNR';\n\n/**\n * Returns true if the observation is a leaf result whose value is the \"Do Not Report\" sentinel.\n * DiagnosticReportDisplay always hides these rows, matching how such not-reported sub-results\n * are conventionally omitted from a printed lab report.\n *\n * Grouping observations (those with `hasMember`) are excluded: `formatObservationValue` already\n * returns an empty string for them (they carry members, not a value of their own), so this check\n * would not match a well-formed group - but excluding them explicitly means a group can never be\n * hidden by this check even if some future or malformed feed puts \"DNR\" on a group's own value,\n * which would otherwise hide every result nested under it.\n * @param observation - The FHIR observation.\n * @returns True if the observation is a non-grouping result reported as \"DNR\".\n */\nfunction isDoNotReportObservation(observation: Observation): boolean {\n  const isLeafResult = !observation.hasMember?.length;\n  return isLeafResult && formatObservationValue(observation) === DO_NOT_REPORT_VALUE;\n}\n\n/**\n * Returns true if the observation exists only to group its members.\n *\n * Panel headers - such as Health Gorilla's `hg-observaton-group` - carry a code and members but no\n * result of their own, so a normal row for them renders with every data column blank. Labs consider\n * such a row misleading, so they are rendered as a section header spanning the table instead.\n * @param observation - The FHIR observation.\n * @returns True if the observation has members and nothing of its own to display.\n */\nfunction isGroupingObservation(observation: Observation): boolean {\n  if (!observation.hasMember?.length) {\n    return false;\n  }\n  return !(\n    formatObservationValue(observation) ||\n    observation.dataAbsentReason ||\n    observation.interpretation?.length ||\n    observation.referenceRange?.length\n  );\n}\n\n/**\n * Returns true if the observation is critical.\n * See: https://www.hl7.org/fhir/valueset-observation-interpretation.html\n * @param observation - The FHIR observation.\n * @returns True if the FHIR observation is a critical value.\n */\nfunction isCritical(observation: Observation): boolean {\n  const code = observation.interpretation?.[0]?.coding?.[0]?.code;\n  if (code !== undefined) {\n    return code === 'AA' || code === 'LL' || code === 'HH' || code === 'A';\n  }\n  const interpretation = observation.interpretation?.[0].text;\n  return (\n    interpretation === 'Critical abnormal' ||\n    interpretation === 'Critical high' ||\n    interpretation === 'Critical low' ||\n    interpretation === 'Critical' ||\n    interpretation === 'Abnormal'\n  );\n}\n\ninterface PerformingLabsProps {\n  readonly value: DiagnosticReport;\n}\n\nfunction PerformingLabs({ value }: PerformingLabsProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const [labs, setLabs] = useState<Organization[]>();\n\n  useEffect(() => {\n    getPerformingLabs(medplum, value).then(setLabs).catch(console.error);\n  }, [medplum, value]);\n\n  if (!labs || labs.length === 0) {\n    return null;\n  }\n\n  return (\n    <Stack gap=\"xs\" mt=\"md\">\n      <Divider />\n      <Text fw={500} size=\"sm\" c=\"dimmed\">\n        Performing Labs\n      </Text>\n      {labs.map((lab) => (\n        <Group key={`lab-${lab.id}-${lab.name}`} justify=\"space-between\" align=\"flex-start\" wrap=\"nowrap\">\n          <div>\n            <Text>{lab.name}</Text>\n            {lab.address?.[0] && (\n              <Text size=\"sm\" c=\"dimmed\">\n                <AddressDisplay value={lab.address[0]} />\n              </Text>\n            )}\n          </div>\n          <LabContactDisplay value={lab.contact?.[0]} />\n        </Group>\n      ))}\n    </Stack>\n  );\n}\n\ninterface LabContactDisplayProps {\n  readonly value?: OrganizationContact;\n}\n\nfunction LabContactDisplay({ value }: LabContactDisplayProps): JSX.Element | null {\n  if (!value) {\n    return null;\n  }\n  return (\n    <div style={{ textAlign: 'right' }}>\n      {value.name && <Text>{value.name.text ?? formatHumanName(value.name)}</Text>}\n      {value.telecom?.[0] && (\n        <Text size=\"sm\" c=\"dimmed\">\n          <ContactPointDisplay value={value.telecom[0]} />\n        </Text>\n      )}\n    </div>\n  );\n}\n\n/**\n * Collects the unique performing lab organizations for a diagnostic report.\n *\n * Walks the report results (including nested observation groups) and resolves\n * each observation performer that is an Organization. References of the form\n * \"#id\" are resolved against the report's contained resources, which is how\n * lab integrations such as Health Gorilla represent the performing labs.\n * @param medplum - The Medplum client.\n * @param report - The diagnostic report.\n * @returns The unique performing lab organizations.\n */\nasync function getPerformingLabs(medplum: MedplumClient, report: DiagnosticReport): Promise<Organization[]> {\n  const observations: Observation[] = [];\n  const visited = new Set<string>();\n\n  async function resolveObservation(ref: Reference<Observation>): Promise<void> {\n    const refString = ref.reference;\n    if (!refString || visited.has(refString)) {\n      return;\n    }\n    visited.add(refString);\n    const observation = refString.startsWith('#')\n      ? findContained<Observation>(report, refString, 'Observation')\n      : await medplum.readReference(ref).catch(() => undefined);\n    if (!observation) {\n      return;\n    }\n    observations.push(observation);\n    for (const member of observation.hasMember ?? []) {\n      await resolveObservation(member as Reference<Observation>);\n    }\n  }\n\n  for (const result of report.result ?? []) {\n    await resolveObservation(result);\n  }\n\n  const labs = new Map<string, Organization>();\n  for (const performer of observations.flatMap((observation) => observation.performer ?? [])) {\n    const refString = performer.reference;\n    let organization: Organization | undefined;\n    if (refString?.startsWith('#')) {\n      organization = findContained<Organization>(report, refString, 'Organization');\n    } else if (refString?.startsWith('Organization/')) {\n      organization = await medplum.readReference(performer as Reference<Organization>).catch(() => undefined);\n    }\n    if (organization && (organization.address || organization.contact)) {\n      const key = `${organization.name}|${formatAddress(organization.address?.[0])}`;\n      if (!labs.has(key)) {\n        labs.set(key, organization);\n      }\n    }\n  }\n\n  return Array.from(labs.values());\n}\n\nfunction findContained<T extends Observation | Organization>(\n  report: DiagnosticReport,\n  refString: string,\n  resourceType: T['resourceType']\n): T | undefined {\n  const id = refString.slice(1);\n  return report.contained?.find((resource) => resource.resourceType === resourceType && resource.id === id) as\n    T | undefined;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Blockquote, Stack } from '@mantine/core';\nimport type { Annotation } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport classes from './NoteDisplay.module.css';\n\nexport interface NoteDisplayProps {\n  readonly value?: Annotation[];\n}\n\nexport function NoteDisplay({ value }: NoteDisplayProps): JSX.Element | null {\n  if (!value) {\n    return null;\n  }\n\n  return (\n    <Stack justify=\"flex-start\" gap=\"xs\">\n      {value.map(\n        (note) =>\n          note.text && (\n            <Blockquote\n              key={`note-${note.text}`}\n              classNames={{ cite: classes.noteCite, root: classes.noteRoot }}\n              cite={note.authorReference?.display || note.authorString}\n              icon={null}\n            >\n              {note.text}\n            </Blockquote>\n          )\n      )}\n    </Stack>\n  );\n}\n", ".noteBody {\n  font-size: var(--mantine-font-size-sm);\n}\n\n.noteCite {\n  font-size: var(--mantine-font-size-xs);\n  margin-block-start: 3;\n}\n\n.noteRoot {\n  padding: 5px;\n  white-space: pre-wrap;\n  font-family: var(--mantine-font-family-monospace);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group } from '@mantine/core';\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\n\nexport interface ResourceBadgeProps {\n  readonly value?: Reference | Resource;\n  readonly link?: boolean;\n}\n\nexport function ResourceBadge(props: ResourceBadgeProps): JSX.Element {\n  return (\n    <Group gap=\"xs\">\n      <ResourceAvatar size={24} radius={12} value={props.value} link={props.link} />\n      <ResourceName value={props.value} link={props.link} />\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { TextProps } from '@mantine/core';\nimport { Text } from '@mantine/core';\nimport { getDisplayString, isOk, normalizeErrorString } from '@medplum/core';\nimport type { OperationOutcome, Reference, Resource } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\n\nexport interface ResourceNameProps extends TextProps {\n  readonly value?: Reference | Resource;\n  readonly link?: boolean;\n}\n\nexport function ResourceName(props: ResourceNameProps): JSX.Element | null {\n  const { value, link, ...rest } = props;\n  const [outcome, setOutcome] = useState<OperationOutcome | undefined>();\n  const resource = useResource(value, setOutcome);\n  let text: string;\n\n  if (outcome && !isOk(outcome)) {\n    text = `[${normalizeErrorString(outcome)}]`;\n  } else if (resource) {\n    text = getDisplayString(resource);\n  } else {\n    return null;\n  }\n\n  return link ? (\n    <MedplumLink to={value} {...rest}>\n      {text}\n    </MedplumLink>\n  ) : (\n    <Text component=\"span\" {...rest}>\n      {text}\n    </Text>\n  );\n}\n", ".table {\n  border: 0.1px solid var(--mantine-color-gray-5);\n  border-collapse: collapse;\n\n  & td,\n  & th {\n    border: 0.1px solid var(--mantine-color-gray-5);\n    padding: 4px;\n  }\n\n  & :global(.mantine-Badge-root) {\n    min-width: max-content;\n  }\n}\n\n.groupHeaderRow {\n  background: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n  font-weight: 600;\n}\n\n.criticalRow {\n  background: light-dark(var(--mantine-color-red-0), oklch(from var(--mantine-color-red-8) l c h / 0.2));\n  border: 0.1px solid var(--mantine-color-red-5);\n  color: light-dark(var(--mantine-color-red-5), var(--mantine-color-red-0));\n  font-weight: 500;\n\n  & td {\n    border: 0.1px solid var(--mantine-color-red-5);\n  }\n}\n\n.noteBody {\n  font-size: var(--mantine-font-size-sm);\n}\n\n.noteCite {\n  font-size: var(--mantine-font-size-xs);\n  margin-block-start: 3;\n}\n\n.noteRoot {\n  padding: 5px;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatCodeableConcept, getDisplayString } from '@medplum/core';\nimport type { Encounter, MedicationRequest, MedicationStatement, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { Modal } from '../Modal/Modal';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { compareByLastUpdatedDescending } from '../utils/date';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport { MedicationDialog } from './MedicationDialog';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport type MedicationSummaryResource = MedicationRequest | MedicationStatement;\n\nexport interface MedicationsProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly medicationRequests: MedicationRequest[];\n  readonly medicationStatements?: MedicationStatement[];\n  readonly onClickResource?: (resource: MedicationSummaryResource) => void;\n}\n\nexport function Medications(props: MedicationsProps): JSX.Element {\n  const medplum = useMedplum();\n  const [medicationRequests, setMedicationRequests] = useState(props.medicationRequests);\n  const [editMedication, setEditMedication] = useState<MedicationRequest>();\n  const [opened, { open, close }] = useDisclosure(false);\n  const medications = [...medicationRequests, ...(props.medicationStatements ?? [])].sort(\n    compareByLastUpdatedDescending\n  );\n\n  const handleSubmit = useCallback(\n    async (medication: MedicationRequest) => {\n      if (medication.id) {\n        const updatedMedication = await medplum.updateResource(medication);\n        setMedicationRequests(medicationRequests.map((m) => (m.id === updatedMedication.id ? updatedMedication : m)));\n      } else {\n        const newMedication = await medplum.createResource(medication);\n        setMedicationRequests([newMedication, ...medicationRequests]);\n      }\n\n      setEditMedication(undefined);\n      close();\n    },\n    [medplum, medicationRequests, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Medications\"\n        onAdd={() => {\n          setEditMedication(undefined);\n          open();\n        }}\n      >\n        {medications.length > 0 ? (\n          <Flex direction=\"column\" gap={8}>\n            {medications.map((medication) => (\n              <SummaryItem\n                key={`${medication.resourceType}/${medication.id}`}\n                onClick={() => {\n                  if (medication.resourceType === 'MedicationRequest') {\n                    setEditMedication(medication);\n                    open();\n                  } else {\n                    props.onClickResource?.(medication);\n                  }\n                }}\n              >\n                <Box>\n                  <Text fw={500} className={styles.itemText}>\n                    {getMedicationDisplayString(medication)}\n                  </Text>\n                  <Group mt={2} gap={4}>\n                    {medication.status && (\n                      <StatusBadge\n                        color={getStatusColor(medication.status)}\n                        variant=\"light\"\n                        status={medication.status}\n                      />\n                    )}\n                  </Group>\n                </Box>\n              </SummaryItem>\n            ))}\n          </Flex>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      <Modal opened={opened} onClose={close} title={editMedication ? 'Edit Medication' : 'Add Medication'}>\n        <MedicationDialog\n          patient={props.patient}\n          encounter={props.encounter}\n          medication={editMedication}\n          onSubmit={handleSubmit}\n        />\n      </Modal>\n    </>\n  );\n}\n\nfunction getStatusColor(status?: string): string {\n  if (!status) {\n    return 'gray';\n  }\n\n  switch (status) {\n    case 'active':\n      return 'green';\n    case 'stopped':\n      return 'red';\n    case 'on-hold':\n      return 'yellow';\n    case 'cancelled':\n      return 'red';\n    case 'completed':\n      return 'blue';\n    case 'entered-in-error':\n      return 'red';\n    case 'draft':\n      return 'gray';\n    default:\n      return 'gray';\n  }\n}\n\nfunction getMedicationDisplayString(medication: MedicationSummaryResource): string {\n  if (medication.medicationCodeableConcept) {\n    return formatCodeableConcept(medication.medicationCodeableConcept);\n  }\n\n  return getDisplayString(medication);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Resource } from '@medplum/fhirtypes';\n\n/**\n * Compares two resources by meta.lastUpdated descending.\n * Resources without meta.lastUpdated sort after resources with meta.lastUpdated.\n * @param a - First resource.\n * @param b - Second resource.\n * @returns Comparator result for Array.sort().\n */\nexport function compareByLastUpdatedDescending(a: Resource, b: Resource): number {\n  const aLastUpdated = a.meta?.lastUpdated;\n  const bLastUpdated = b.meta?.lastUpdated;\n\n  if (!aLastUpdated && !bLastUpdated) {\n    return 0;\n  }\n\n  if (!aLastUpdated) {\n    return 1;\n  }\n\n  if (!bLastUpdated) {\n    return -1;\n  }\n\n  return bLastUpdated.localeCompare(aLastUpdated);\n}\n\n/**\n * Sorts an array of resources in place by meta.lastUpdated ascending.\n * @param resources - Array of resources.\n * @param timelineResource - Optional primary resource of a timeline view. If specified, the primary resource will be sorted by meta.lastUpdated descending.\n */\nexport function sortByDateAndPriority(resources: Resource[], timelineResource?: Resource): void {\n  resources.sort((a: Resource, b: Resource): number => {\n    const priority1 = getPriorityScore(a, timelineResource);\n    const priority2 = getPriorityScore(b, timelineResource);\n    if (priority1 > priority2) {\n      return 1;\n    }\n    if (priority1 < priority2) {\n      return -1;\n    }\n    return getTime(a, timelineResource) - getTime(b, timelineResource);\n  });\n}\n\nfunction getPriorityScore(resource: Resource, timelineResource: Resource | undefined): number {\n  if (!isSameResourceType(resource, timelineResource)) {\n    // Only use priority if not the primary resource of a timeline view.\n\n    const priority = (resource as any).priority;\n    if (typeof priority === 'string') {\n      return { stat: 4, asap: 3, urgent: 2 }[priority] ?? 0;\n    }\n  }\n  return 0;\n}\n\nfunction getTime(resource: Resource, timelineResource: Resource | undefined): number {\n  if (!isSameResourceType(resource, timelineResource)) {\n    // Only use special case timestamps if not the primary resource of a timeline view.\n\n    if (resource.resourceType === 'Communication' && resource.sent) {\n      return new Date(resource.sent).getTime();\n    }\n\n    if (\n      (resource.resourceType === 'DiagnosticReport' ||\n        resource.resourceType === 'Media' ||\n        resource.resourceType === 'Observation') &&\n      resource.issued\n    ) {\n      return new Date(resource.issued).getTime();\n    }\n\n    if (resource.resourceType === 'DocumentReference' && resource.date) {\n      return new Date(resource.date).getTime();\n    }\n  }\n\n  const dateTime = resource.meta?.lastUpdated;\n  if (!dateTime) {\n    return 0;\n  }\n  return new Date(dateTime).getTime();\n}\n\nfunction isSameResourceType(a: Resource, b: Resource | undefined): boolean {\n  return !!b && a.resourceType === b.resourceType && a.id === b.id;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Alert, Group, Radio, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport type { Encounter, MedicationRequest, Patient } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\n\nexport interface MedicationDialogProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly medication?: MedicationRequest;\n  readonly onSubmit: (medication: MedicationRequest) => void;\n}\n\nconst HTTP = 'http://';\n\nconst statusValues: MedicationRequest['status'][] = [\n  'active',\n  'stopped',\n  'on-hold',\n  'cancelled',\n  'completed',\n  'entered-in-error',\n  'draft',\n  'unknown',\n];\n\nexport function MedicationDialog(props: MedicationDialogProps): JSX.Element {\n  const me = useMedplumProfile();\n  const { patient, encounter, medication, onSubmit } = props;\n  const [code, setCode] = useState(medication?.medicationCodeableConcept);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      if (!me) {\n        throw new Error('Not signed in');\n      }\n\n      onSubmit(\n        addProfileToResource(\n          {\n            ...medication,\n            resourceType: 'MedicationRequest',\n            status: formData.status as MedicationRequest['status'],\n            intent: medication?.intent ?? 'order',\n            encounter: medication?.encounter ?? (encounter && createReference(encounter)),\n            requester: medication?.requester ?? createReference(me),\n            medicationCodeableConcept: code,\n            subject: createReference(patient),\n          },\n          HTTP_HL7_ORG + '/fhir/us/core/StructureDefinition/us-core-medicationrequest'\n        )\n      );\n    },\n    [me, onSubmit, medication, encounter, code, patient]\n  );\n\n  if (!me) {\n    return <Alert color=\"red\">Not signed in</Alert>;\n  }\n\n  return (\n    <Form onSubmit={handleSubmit}>\n      <Stack>\n        <CodeableConceptInput\n          name=\"request\"\n          path=\"MedicationRequest.medication[x]\"\n          data-autofocus={true}\n          binding={HTTP + 'cts.nlm.nih.gov/fhir/ValueSet/2.16.840.1.113762.1.4.1010.4'}\n          maxValues={1}\n          defaultValue={medication?.medicationCodeableConcept}\n          onChange={(request) => setCode(request)}\n          outcome={undefined}\n        />\n        <Radio.Group name=\"status\" label=\"Request Status\" required defaultValue={medication?.status}>\n          {statusValues.map((sv) => (\n            <Radio key={sv} value={sv} label={sv} my=\"xs\" required />\n          ))}\n        </Radio.Group>\n        <Group justify=\"flex-end\" gap={4}>\n          <SubmitButton>Save</SubmitButton>\n        </Group>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Group, Text, Tooltip } from '@mantine/core';\nimport type { JSX } from 'react';\nimport styles from './PatientSummary.module.css';\nimport SummaryItem from './SummaryItem';\n\nexport interface PatientInfoItemProps {\n  value: string | undefined;\n  icon: React.ReactNode;\n  placeholder: string;\n  label: string;\n  onClick?: () => void;\n}\n\nexport const PatientInfoItem = (props: PatientInfoItemProps): JSX.Element => {\n  const { value, icon, placeholder, label, onClick } = props;\n  const displayText = value || placeholder;\n\n  return (\n    <SummaryItem onClick={onClick}>\n      <Box className={styles.patientSummaryListItem}>\n        <Tooltip label={label} position=\"top-start\" openDelay={650}>\n          <Group gap=\"sm\" align=\"center\" ml={6} mr={2} style={{ flexWrap: 'nowrap', minWidth: 0 }}>\n            {icon}\n            <Text fz=\"sm\" fw={400} truncate c={value ? 'inherit' : 'var(--mantine-color-gray-6)'}>\n              {displayText}\n            </Text>\n          </Group>\n        </Tooltip>\n      </Box>\n    </SummaryItem>\n  );\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Loader, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatAddress, getReferenceString, OperationOutcomeError } from '@medplum/core';\nimport type { Organization, Patient } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport type { ComponentType, JSX } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { Modal } from '../Modal/Modal';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport type { LoadState } from '../utils/loadState';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport { getPreferredPharmaciesFromPatient } from './pharmacy-utils';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\n/**\n * Base props that any pharmacy dialog component must accept.\n */\nexport interface PharmacyDialogBaseProps {\n  readonly patient: Patient;\n  readonly onSubmit: (pharmacy: Organization) => void;\n  readonly onClose: () => void;\n}\n\nexport interface PharmaciesProps {\n  readonly patient: Patient;\n  readonly pharmacies?: Organization[];\n  readonly onClickResource?: (resource: Organization) => void;\n  readonly pharmacyDialogComponent?: ComponentType<PharmacyDialogBaseProps>;\n}\n\ninterface PharmacyWithPrimary extends Organization {\n  isPrimary?: boolean;\n}\n\nexport function Pharmacies(props: PharmaciesProps): JSX.Element {\n  const { patient: patientProp, onClickResource, pharmacyDialogComponent } = props;\n  const PharmacyDialogComponent = pharmacyDialogComponent;\n  const medplum = useMedplum();\n  const [opened, { open, close }] = useDisclosure(false);\n  const [resolvedPharmacies, setResolvedPharmacies] = useState<PharmacyWithPrimary[]>([]);\n  const [loadState, setLoadState] = useState<LoadState>('loading');\n\n  // Use useResource to get the latest patient data (in case it's updated)\n  const patient = useResource(patientProp);\n\n  // Extract pharmacy references from Patient extensions\n  const pharmacyRefs = useMemo(() => {\n    if (!patient) {\n      return [];\n    }\n    return getPreferredPharmaciesFromPatient(patient);\n  }, [patient]);\n\n  // Resolve Organization references\n  useEffect(() => {\n    let cancelled = false;\n\n    const fetchPharmacies = async (): Promise<void> => {\n      if (props.pharmacies) {\n        // If pharmacies were provided as props, use them directly\n        if (!cancelled) {\n          setResolvedPharmacies(props.pharmacies);\n          setLoadState('loaded');\n        }\n        return;\n      }\n\n      if (pharmacyRefs.length === 0) {\n        if (!cancelled) {\n          setResolvedPharmacies([]);\n          setLoadState('loaded');\n        }\n        return;\n      }\n\n      setLoadState('loading');\n\n      try {\n        const results = await Promise.all(\n          pharmacyRefs.map(async (pharmacyRef) => {\n            try {\n              const org = await medplum.readReference(pharmacyRef.organizationRef);\n              return { ...org, isPrimary: pharmacyRef.isPrimary };\n            } catch (error) {\n              if (!isNotFoundError(error)) {\n                // Error logged by Medplum error handler\n              }\n              return null;\n            }\n          })\n        );\n        if (!cancelled) {\n          const validResults = results.filter((result): result is NonNullable<typeof result> => result !== null);\n          setResolvedPharmacies(validResults);\n          // If all references failed to resolve, show error state\n          // If some resolved successfully, show loaded state with partial results\n          setLoadState(validResults.length === 0 && pharmacyRefs.length > 0 ? 'error' : 'loaded');\n        }\n      } catch (_error) {\n        // Promise.all error indicates a critical failure\n        // Set error state to show failure message to user\n        // The specific error is not critical since UI properly handles all error states\n        if (!cancelled) {\n          setLoadState('error');\n        }\n        // Note: Not re-throwing as error is already handled via UI state\n      }\n    };\n\n    fetchPharmacies().catch(() => {\n      // Error is handled in the component's error state\n    });\n\n    return () => {\n      cancelled = true;\n    };\n  }, [medplum, pharmacyRefs, props.pharmacies]);\n\n  const handleSubmit = useCallback(\n    async (_pharmacy: Organization) => {\n      // After adding a pharmacy, the patient extension is updated by the bot\n      // Invalidate only the patient resource to trigger a refresh\n      if (patient?.id) {\n        medplum.invalidateUrl(getReferenceString(patient));\n      }\n      close();\n    },\n    [medplum, patient, close]\n  );\n\n  if (!patient) {\n    return <></>;\n  }\n\n  const renderPharmacyList = (): JSX.Element => {\n    if (loadState === 'loading') {\n      return <Loader size=\"sm\" />;\n    }\n    if (loadState === 'error') {\n      return (\n        <Text c=\"red\" size=\"sm\">\n          Failed to load pharmacies\n        </Text>\n      );\n    }\n    if (resolvedPharmacies.length === 0) {\n      return <Text>(none)</Text>;\n    }\n    return (\n      <Box>\n        <Flex direction=\"column\" gap={8}>\n          {resolvedPharmacies.map((pharmacy, index) => (\n            <SummaryItem key={pharmacy.id || index} onClick={() => onClickResource?.(pharmacy)}>\n              <Box>\n                <Text fw={500} className={styles.itemText}>\n                  {pharmacy.name}\n                </Text>\n                <Group mt={2} gap={4}>\n                  {pharmacy.isPrimary && <StatusBadge color=\"blue\" variant=\"light\" status=\"primary\" />}\n                  {pharmacy.address?.[0] && (\n                    <Text size=\"xs\" c=\"dimmed\">\n                      {formatAddress(pharmacy.address[0])}\n                    </Text>\n                  )}\n                </Group>\n              </Box>\n            </SummaryItem>\n          ))}\n        </Flex>\n      </Box>\n    );\n  };\n\n  return (\n    <>\n      <CollapsibleSection title=\"Pharmacies\" onAdd={pharmacyDialogComponent ? open : undefined}>\n        {renderPharmacyList()}\n      </CollapsibleSection>\n      {PharmacyDialogComponent ? (\n        <Modal opened={opened} onClose={close} title=\"Add Pharmacy\" size=\"lg\">\n          <PharmacyDialogComponent patient={patient} onSubmit={handleSubmit} onClose={close} />\n        </Modal>\n      ) : null}\n    </>\n  );\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n  if (!(error instanceof OperationOutcomeError)) {\n    return false;\n  }\n\n  return (\n    error.outcome.issue?.some((issue: unknown) => (issue as Record<string, unknown>).code === 'not-found') ?? false\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// Re-export generic pharmacy utilities from @medplum/core\nexport {\n  PATIENT_PREFERRED_PHARMACY_URL,\n  PHARMACY_PREFERENCE_TYPE_SYSTEM,\n  PHARMACY_TYPE_PREFERRED,\n  PHARMACY_TYPE_PRIMARY,\n  addPreferredPharmacyToPatient,\n  createPreferredPharmacyExtension,\n  getPreferredPharmaciesFromPatient,\n  isAddPharmacyResponse,\n  isOrganizationArray,\n  removePreferredPharmacyFromPatient,\n} from '@medplum/core';\nexport type { AddFavoriteParams, AddPharmacyResponse, PharmacySearchParams, PreferredPharmacy } from '@medplum/core';\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Badge, Box, Flex, Group, Text, UnstyledButton } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatDate, getDisplayString } from '@medplum/core';\nimport type { Condition, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useMemo, useState } from 'react';\nimport { Modal } from '../Modal/Modal';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport { ConditionDialog } from './ConditionDialog';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface ProblemListProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly problems: Condition[];\n  readonly onClickResource?: (resource: Condition) => void;\n}\n\nfunction getCodeKey(condition: Condition): string | undefined {\n  const coding = condition.code?.coding?.[0];\n  if (coding?.system && coding?.code) {\n    return `${coding.system}|${coding.code}`;\n  }\n  if (coding?.code) {\n    return coding.code;\n  }\n  return condition.code?.text ?? condition.id;\n}\n\nexport function ProblemList(props: ProblemListProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient, encounter } = props;\n  const [problems, setProblems] = useState(\n    props.problems.filter((c) => c.verificationStatus?.coding?.[0]?.code !== 'entered-in-error')\n  );\n  const [editCondition, setEditCondition] = useState<Condition>();\n  const [opened, { open, close }] = useDisclosure(false);\n  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(() => new Set());\n\n  const groupedProblems = useMemo(() => {\n    const groups = new Map<string, Condition[]>();\n    for (let i = 0; i < problems.length; i++) {\n      const problem = problems[i];\n      const key = getCodeKey(problem) ?? `ungrouped-${i}`;\n      const existing = groups.get(key);\n      if (existing) {\n        existing.push(problem);\n      } else {\n        groups.set(key, [problem]);\n      }\n    }\n    return Array.from(groups.entries());\n  }, [problems]);\n\n  const toggleGroup = useCallback((key: string) => {\n    setExpandedGroups((prev) => {\n      const next = new Set(prev);\n      if (next.has(key)) {\n        next.delete(key);\n      } else {\n        next.add(key);\n      }\n      return next;\n    });\n  }, []);\n\n  const handleSubmit = useCallback(\n    async (condition: Condition) => {\n      if (condition.id) {\n        const updatedCondition = await medplum.updateResource(condition);\n        setProblems(problems.map((p) => (p.id === updatedCondition.id ? updatedCondition : p)));\n      } else {\n        const newCondition = await medplum.createResource(condition);\n        setProblems([newCondition, ...problems]);\n      }\n      setEditCondition(undefined);\n      close();\n    },\n    [medplum, problems, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Problems\"\n        onAdd={() => {\n          setEditCondition(undefined);\n          open();\n        }}\n      >\n        {problems.length > 0 ? (\n          <Flex direction=\"column\" gap={8}>\n            {groupedProblems.map(([key, group], groupIndex) => {\n              const isExpanded = expandedGroups.has(key);\n              const displayProblems = isExpanded ? group : [group[0]];\n              const groupContentId = `problem-group-content-${groupIndex}`;\n              return (\n                <Box key={key}>\n                  <Flex direction=\"column\" gap={4} id={groupContentId}>\n                    {displayProblems.map((problem) => (\n                      <SummaryItem\n                        key={problem.id}\n                        onClick={() => {\n                          setEditCondition(problem);\n                          open();\n                        }}\n                      >\n                        <Box>\n                          <Group gap={6} wrap=\"nowrap\">\n                            <Text fw={500} className={styles.itemText}>\n                              {getDisplayString(problem)}\n                            </Text>\n                            {!isExpanded && group.length > 1 && (\n                              <Badge size=\"xs\" color=\"gray\" variant=\"light\" style={{ flexShrink: 0 }}>\n                                +{group.length - 1}\n                              </Badge>\n                            )}\n                          </Group>\n                          <Group mt={2} gap={4}>\n                            {problem.clinicalStatus?.coding?.[0]?.code && (\n                              <StatusBadge\n                                data-testid=\"status-badge\"\n                                color={getStatusColor(problem.clinicalStatus?.coding?.[0]?.code)}\n                                variant=\"light\"\n                                status={problem.clinicalStatus?.coding?.[0]?.code}\n                              />\n                            )}\n                            <Text size=\"xs\" fw={500} c=\"dimmed\">\n                              {formatDate(problem.onsetDateTime)}\n                            </Text>\n                          </Group>\n                        </Box>\n                      </SummaryItem>\n                    ))}\n                  </Flex>\n                  {group.length > 1 && (\n                    <UnstyledButton\n                      onClick={() => toggleGroup(key)}\n                      aria-expanded={isExpanded}\n                      aria-controls={groupContentId}\n                      pl={4}\n                      pt={2}\n                      style={{ fontSize: 'var(--mantine-font-size-xs)', color: 'var(--mantine-color-dimmed)' }}\n                    >\n                      {isExpanded ? 'Show less' : `Show all ${group.length} entries`}\n                    </UnstyledButton>\n                  )}\n                </Box>\n              );\n            })}\n          </Flex>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      <Modal opened={opened} onClose={close} title={editCondition ? 'Edit Problem' : 'Add Problem'}>\n        <ConditionDialog patient={patient} encounter={encounter} condition={editCondition} onSubmit={handleSubmit} />\n      </Modal>\n    </>\n  );\n}\n\nconst getStatusColor = (status?: string): string => {\n  if (!status) {\n    return 'gray';\n  }\n\n  switch (status) {\n    case 'active':\n    case 'recurrence':\n    case 'relapse':\n      return 'green';\n    case 'inactive':\n      return 'orange';\n    case 'remission':\n      return 'blue';\n    case 'resolved':\n      return 'teal';\n    default:\n      return 'gray';\n  }\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport type { Condition, Encounter, Patient } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { convertLocalToIso } from '../DateTimeInput/DateTimeInput.utils';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\n\nexport interface ConditionDialogProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly condition?: Condition;\n  readonly onSubmit: (condition: Condition) => void;\n}\n\nexport function ConditionDialog(props: ConditionDialogProps): JSX.Element {\n  const { patient, encounter, condition, onSubmit } = props;\n  const [code, setCode] = useState(condition?.code);\n  const [clinicalStatus, setClinicalStatus] = useState(condition?.clinicalStatus);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      const updatedCondition: Condition = addProfileToResource(\n        {\n          ...condition,\n          resourceType: 'Condition',\n          category: [\n            {\n              coding: [\n                {\n                  system: HTTP_TERMINOLOGY_HL7_ORG + '/CodeSystem/condition-category',\n                  code: 'problem-list-item',\n                  display: 'Problem List Item',\n                },\n              ],\n              text: 'Problem List Item',\n            },\n          ],\n          subject: createReference(patient),\n          encounter: encounter && createReference(encounter),\n          code,\n          clinicalStatus,\n          onsetDateTime: formData.onsetDateTime ? convertLocalToIso(formData.onsetDateTime) : undefined,\n        },\n        HTTP_HL7_ORG + '/fhir/us/core/StructureDefinition/us-core-condition-problems-health-concerns'\n      );\n      onSubmit(updatedCondition);\n    },\n    [patient, encounter, condition, code, clinicalStatus, onSubmit]\n  );\n\n  return (\n    <Form key={condition?.id} onSubmit={handleSubmit}>\n      <Stack>\n        <CodeableConceptInput\n          name=\"code\"\n          label=\"Problem\"\n          path=\"Condition.code\"\n          data-autofocus={true}\n          binding={HTTP_HL7_ORG + '/fhir/us/core/ValueSet/us-core-condition-code'}\n          defaultValue={condition?.code}\n          onChange={(code) => setCode(code)}\n          outcome={undefined}\n        />\n        <CodeableConceptInput\n          name=\"clinicalStatus\"\n          label=\"Status\"\n          path=\"Condition.clinicalStatus\"\n          binding={HTTP_HL7_ORG + '/fhir/ValueSet/condition-clinical'}\n          defaultValue={condition?.clinicalStatus}\n          onChange={(clinicalStatus) => setClinicalStatus(clinicalStatus)}\n          outcome={undefined}\n        />\n        <DateTimeInput name=\"onsetDateTime\" label=\"Dx Date\" defaultValue={condition?.onsetDateTime} required />\n        <Group justify=\"flex-end\" gap={4} mt=\"md\">\n          <SubmitButton>Save</SubmitButton>\n        </Group>\n      </Stack>\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Radio, Text, UnstyledButton } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { createReference, HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, LOINC, SNOMED } from '@medplum/core';\nimport type { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport { killEvent } from '../utils/dom';\nimport { CollapsibleSection } from './CollapsibleSection';\n\nconst NULLFLAVOR = HTTP_TERMINOLOGY_HL7_ORG + '/CodeSystem/v3-NullFlavor';\n\ntype SexualOrientationCode = '38628009' | '20430005' | '42035005' | 'OTH' | 'UNK' | 'ASKU';\n// Sexual orientation widget\n// See: https://hl7.org/fhir/us/core/STU5.0.1/StructureDefinition-us-core-observation-sexual-orientation.html\nconst CodesToText: Record<SexualOrientationCode, string> = {\n  '38628009': 'Homosexual',\n  '20430005': 'Heterosexual',\n  '42035005': 'Bisexual',\n  OTH: 'Other',\n  UNK: 'Unknown',\n  ASKU: 'Asked but no answer',\n};\n\nconst CodesToSystem: Record<SexualOrientationCode, string> = {\n  38628009: SNOMED,\n  20430005: SNOMED,\n  42035005: SNOMED,\n  OTH: NULLFLAVOR,\n  UNK: NULLFLAVOR,\n  ASKU: NULLFLAVOR,\n};\n\nexport interface SexualOrientationProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly sexualOrientation?: Observation;\n  readonly onClickResource?: (resource: Observation) => void;\n}\n\nexport function SexualOrientation(props: SexualOrientationProps): JSX.Element {\n  const { patient, encounter } = props;\n  const medplum = useMedplum();\n  const [sexualOrientation, setSexualOrientation] = useState(props.sexualOrientation);\n  const [opened, { open, close }] = useDisclosure(false);\n  const [hoverIndex, setHoverIndex] = useState<number | null>(null);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      const code = formData.sexualOrientation as SexualOrientationCode;\n      medplum\n        .createResource<Observation>({\n          resourceType: 'Observation',\n          meta: {\n            profile: [HTTP_HL7_ORG + '/fhir/us/core/ValueSet/us-core-sexual-orientation'],\n          },\n          status: 'final',\n          category: [\n            {\n              coding: [\n                {\n                  system: HTTP_TERMINOLOGY_HL7_ORG + '/CodeSystem/observation-category',\n                  code: 'social-history',\n                  display: 'Social History',\n                },\n              ],\n              text: 'Social History',\n            },\n          ],\n          code: {\n            coding: [\n              {\n                system: LOINC,\n                code: '76690-7',\n                display: 'Sexual orientation',\n              },\n            ],\n            text: 'Sexual orientation',\n          },\n          subject: createReference(patient),\n          encounter: encounter ? createReference(encounter) : undefined,\n          effectiveDateTime: new Date().toISOString(),\n          valueCodeableConcept: {\n            coding: [\n              {\n                system: CodesToSystem[code],\n                code: formData.sexualOrientation,\n              },\n            ],\n            text: CodesToText[code],\n          },\n        })\n        .then((newSexualOrientation) => {\n          setSexualOrientation(newSexualOrientation);\n          close();\n        })\n        .catch(console.error);\n    },\n    [medplum, patient, encounter, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Sexual Orientation\"\n        onAdd={() => {\n          open();\n        }}\n      >\n        {sexualOrientation ? (\n          <Flex direction=\"column\" gap={8}>\n            <Box onMouseEnter={() => setHoverIndex(0)} onMouseLeave={() => setHoverIndex(null)}>\n              <UnstyledButton\n                data-testid=\"sexual-orientation-button\"\n                onClick={(e) => {\n                  killEvent(e);\n                  if (props.onClickResource) {\n                    props.onClickResource(sexualOrientation);\n                  }\n                }}\n              >\n                <Box pr={hoverIndex === 0 ? 24 : 0}>\n                  <Text size=\"sm\" fw={500}>\n                    {sexualOrientation.valueCodeableConcept?.text ?? 'Unknown'}\n                  </Text>\n                </Box>\n              </UnstyledButton>\n            </Box>\n          </Flex>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      <Modal\n        opened={opened}\n        onClose={close}\n        title=\"Set Sexual Orientation\"\n        size=\"md\"\n        onSubmit={handleSubmit}\n        actions={<SubmitButton>Save</SubmitButton>}\n      >\n        <Radio.Group name=\"sexualOrientation\" label=\"Sexual Orientation\" required>\n          {Object.entries(CodesToText).map(([code, text]) => (\n            <Radio key={code} value={code} label={text} my=\"xs\" />\n          ))}\n        </Radio.Group>\n      </Modal>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Radio, Text, UnstyledButton } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { HTTP_HL7_ORG, LOINC, SNOMED, createReference, formatCodeableConcept } from '@medplum/core';\nimport type { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport { CollapsibleSection } from './CollapsibleSection';\n\n// Smoking Status widget\n// See: https://build.fhir.org/ig/HL7/US-Core/StructureDefinition-us-core-smokingstatus.html\n\nconst smokingStatusOptions: Record<string, string> = {\n  '266919005': 'Never smoked tobacco',\n  '266927001': 'Tobacco smoking consumption unknown',\n  '428041000124106': 'Occasional tobacco smoker',\n  '428061000124105': 'Light tobacco smoker',\n  '428071000124103': 'Heavy tobacco smoker',\n  '449868002': 'Smokes tobacco daily',\n  '77176002': 'Smoker',\n  '8517006': 'Ex-smoker',\n};\n\nexport interface SmokingStatusProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly smokingStatus?: Observation;\n  readonly onClickResource?: (resource: Observation) => void;\n}\n\nexport function SmokingStatus(props: SmokingStatusProps): JSX.Element {\n  const medplum = useMedplum();\n  const [smokingStatus, setSmokingStatus] = useState(props.smokingStatus);\n  const [opened, { open, close }] = useDisclosure(false);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      medplum\n        .createResource<Observation>({\n          resourceType: 'Observation',\n          meta: {\n            profile: [HTTP_HL7_ORG + '/fhir/us/core/StructureDefinition/us-core-smokingstatus'],\n          },\n          status: 'final',\n          category: [\n            {\n              coding: [\n                {\n                  system: 'http://terminology.hl7.org/CodeSystem/observation-category',\n                  code: 'social-history',\n                  display: 'Social History',\n                },\n              ],\n              text: 'Social History',\n            },\n          ],\n          code: {\n            coding: [\n              {\n                system: LOINC,\n                code: '72166-2',\n                display: 'Tobacco smoking status',\n              },\n            ],\n            text: 'Tobacco smoking status',\n          },\n          subject: createReference(props.patient),\n          encounter: props.encounter ? createReference(props.encounter) : undefined,\n          effectiveDateTime: new Date().toISOString(),\n          valueCodeableConcept: {\n            coding: [\n              {\n                system: SNOMED,\n                version: SNOMED + '/731000124108',\n                code: formData.smokingStatus,\n              },\n            ],\n            text: smokingStatusOptions[formData.smokingStatus],\n          },\n        })\n        .then((newSmokingStatus) => {\n          setSmokingStatus(newSmokingStatus);\n          close();\n        })\n        .catch(console.error);\n    },\n    [medplum, props.patient, props.encounter, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Smoking Status\"\n        onAdd={() => {\n          open();\n        }}\n      >\n        {smokingStatus?.valueCodeableConcept ? (\n          <UnstyledButton data-testid=\"smoking-status-button\" onClick={() => props.onClickResource?.(smokingStatus)}>\n            <Text>{formatCodeableConcept(smokingStatus.valueCodeableConcept)}</Text>\n          </UnstyledButton>\n        ) : (\n          <Text>(none)</Text>\n        )}\n      </CollapsibleSection>\n      <Modal\n        opened={opened}\n        onClose={close}\n        title=\"Set Smoking Status\"\n        size=\"md\"\n        onSubmit={handleSubmit}\n        actions={<SubmitButton>Save</SubmitButton>}\n      >\n        <Radio.Group name=\"smokingStatus\" label=\"Smoking Status\" required>\n          {Object.entries(smokingStatusOptions).map(([code, text]) => (\n            <Radio key={code} value={code} label={text} my=\"xs\" />\n          ))}\n        </Radio.Group>\n      </Modal>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, SimpleGrid, Stack, Text, Textarea, TextInput } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { formatQuantity } from '@medplum/core';\nimport type { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport {\n  createCompoundObservation,\n  createLoincCode,\n  createObservation,\n  createQuantity,\n  getObservationValue,\n} from './Vitals.utils';\n\ninterface ObservationMeta {\n  readonly name: string;\n  readonly short: string;\n  readonly code: string;\n  readonly component?: string;\n  readonly title: string;\n  readonly unit: string;\n}\n\nconst BP = '85354-9';\nconst SYSTOLIC = '8480-6';\nconst DIASTOLIC = '8462-4';\n\nconst LOINC_CODES: ObservationMeta[] = [\n  {\n    name: 'systolic',\n    short: 'BP Sys',\n    code: BP,\n    component: SYSTOLIC,\n    title: 'Blood Pressure',\n    unit: 'mm[Hg]',\n  },\n  {\n    name: 'diastolic',\n    short: 'BP Dias',\n    code: BP,\n    component: DIASTOLIC,\n    title: 'Blood Pressure',\n    unit: 'mm[Hg]',\n  },\n  {\n    name: 'heartRate',\n    short: 'HR',\n    code: '8867-4',\n    title: 'Heart Rate',\n    unit: '/min',\n  },\n  {\n    name: 'bodyTemperature',\n    short: 'Temp',\n    code: '8310-5',\n    title: 'Body Temperature',\n    unit: 'Cel',\n  },\n  {\n    name: 'respiratoryRate',\n    short: 'RR',\n    code: '9279-1',\n    title: 'Respiratory Rate',\n    unit: '/min',\n  },\n  {\n    name: 'height',\n    short: 'Ht',\n    code: '8302-2',\n    title: 'Height',\n    unit: 'cm',\n  },\n  {\n    name: 'weight',\n    short: 'Wt',\n    code: '29463-7',\n    title: 'Weight',\n    unit: 'kg',\n  },\n  {\n    name: 'bmi',\n    short: 'BMI',\n    code: '39156-5',\n    title: 'BMI',\n    unit: 'kg/m2',\n  },\n  {\n    name: 'oxygen',\n    short: 'O2',\n    code: '2708-6',\n    title: 'Oxygen',\n    unit: '%',\n  },\n  {\n    name: 'headCircumference',\n    short: 'HC',\n    code: '9843-4',\n    title: 'Head Circumference',\n    unit: 'cm',\n  },\n];\n\nexport interface VitalsProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly vitals: Observation[];\n  readonly onClickResource?: (resource: Observation) => void;\n}\n\nexport function Vitals(props: VitalsProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient, encounter } = props;\n  const [vitals, setVitals] = useState(props.vitals);\n  const [opened, { open, close }] = useDisclosure(false);\n\n  const handleSubmit = useCallback(\n    (formData: Record<string, string>) => {\n      const newObservations = [];\n\n      // Blood pressure is special because it has two components\n      newObservations.push(\n        createCompoundObservation(patient, encounter, BP, 'Blood pressure', [\n          {\n            code: createLoincCode(SYSTOLIC, 'Systolic blood pressure'),\n            valueQuantity: createQuantity(Number.parseFloat(formData['systolic']), 'mm[Hg]'),\n          },\n          {\n            code: createLoincCode(DIASTOLIC, 'Diastolic blood pressure'),\n            valueQuantity: createQuantity(Number.parseFloat(formData['diastolic']), 'mm[Hg]'),\n          },\n        ])\n      );\n\n      for (const meta of LOINC_CODES) {\n        if (meta.component) {\n          continue;\n        }\n        newObservations.push(\n          createObservation(\n            patient,\n            encounter,\n            meta.code,\n            meta.title,\n            createQuantity(Number.parseFloat(formData[meta.name]), meta.unit)\n          )\n        );\n      }\n\n      Promise.all(newObservations.filter(Boolean).map((obs) => medplum.createResource(obs as Observation)))\n        .then((newVitals) => setVitals([...newVitals, ...vitals]))\n        .catch(console.error);\n\n      close();\n    },\n    [medplum, patient, encounter, vitals, close]\n  );\n\n  return (\n    <>\n      <CollapsibleSection\n        title=\"Vitals\"\n        onAdd={() => {\n          open();\n        }}\n      >\n        <Stack>\n          {LOINC_CODES.map((meta) => {\n            const obs = vitals.find((o) => o.code?.coding?.[0].code === meta.code);\n            return (\n              <Group align=\"center\" key={meta.name}>\n                <Text c=\"dimmed\">{meta.short}</Text>\n                {obs && <Text>{formatQuantity(getObservationValue(obs, meta.component))}</Text>}\n              </Group>\n            );\n          })}\n        </Stack>\n      </CollapsibleSection>\n\n      <Modal\n        opened={opened}\n        onClose={close}\n        title=\"Add Vitals\"\n        size=\"md\"\n        onSubmit={handleSubmit}\n        actions={<SubmitButton>Save</SubmitButton>}\n      >\n        <Stack>\n          <SimpleGrid cols={2}>\n            {LOINC_CODES.map((meta, index) => (\n              <TextInput\n                key={meta.name}\n                name={meta.name}\n                label={meta.short}\n                description={`${meta.title} (${meta.unit})`}\n                data-autofocus={index === 0}\n                autoFocus={index === 0}\n              />\n            ))}\n          </SimpleGrid>\n          <Textarea name=\"notes\" label=\"Notes\" />\n        </Stack>\n      </Modal>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { LOINC, UCUM, createReference } from '@medplum/core';\nimport type {\n  CodeableConcept,\n  Encounter,\n  Observation,\n  ObservationComponent,\n  Patient,\n  Quantity,\n} from '@medplum/fhirtypes';\n\n/**\n * Tries to get the observation quantity value.\n * @param obs - The observation to check.\n * @param component - Optional sub-component code to check.\n * @returns The observation quantity value, if available. Otherwise, undefined.\n */\nexport function getObservationValue(obs: Observation, component?: string): Quantity | undefined {\n  if (component) {\n    return obs.component?.find((c) => c.code?.coding?.[0].code === component)?.valueQuantity;\n  }\n  return obs.valueQuantity;\n}\n\nexport function createObservation(\n  patient: Patient,\n  encounter: Encounter | undefined,\n  code: string,\n  title: string,\n  valueQuantity: Quantity\n): Observation | undefined {\n  if (!isValidNumber(valueQuantity.value)) {\n    return undefined;\n  }\n  return {\n    ...createBaseObservation(patient, encounter, code, title),\n    valueQuantity,\n  };\n}\n\nexport function createCompoundObservation(\n  patient: Patient,\n  encounter: Encounter | undefined,\n  code: string,\n  title: string,\n  components: ObservationComponent[]\n): Observation | undefined {\n  const component = components.filter((c) => isValidNumber(c.valueQuantity?.value));\n  if (component.length === 0) {\n    return undefined;\n  }\n  return {\n    ...createBaseObservation(patient, encounter, code, title),\n    component,\n  };\n}\n\nexport function createBaseObservation(\n  patient: Patient,\n  encounter: Encounter | undefined,\n  code: string,\n  title: string\n): Observation {\n  return {\n    resourceType: 'Observation',\n    status: 'preliminary',\n    subject: createReference(patient),\n    encounter: encounter ? createReference(encounter) : undefined,\n    effectiveDateTime: new Date().toISOString(),\n    category: [\n      {\n        coding: [\n          {\n            system: 'http://terminology.hl7.org/CodeSystem/observation-category',\n            code: 'vital-signs',\n            display: 'Vital Signs',\n          },\n        ],\n      },\n    ],\n    code: createLoincCode(code, title),\n  };\n}\n\nexport function createLoincCode(code: string, display: string): CodeableConcept {\n  return {\n    coding: [\n      {\n        code,\n        display,\n        system: LOINC,\n      },\n    ],\n    text: display,\n  };\n}\n\nexport function createQuantity(value: number, unit: string): Quantity {\n  return {\n    value,\n    system: UCUM,\n    unit,\n    code: unit,\n  };\n}\n\nfunction isValidNumber(value: number | undefined): boolean {\n  return value !== undefined && !Number.isNaN(value) && Number.isFinite(value);\n}\n", ".rightBorder {\n  border-right: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-gray-8));\n}\n", ".container {\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n  flex: 1;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Stack, Text } from '@mantine/core';\nimport { formatDateTime, formatHumanName } from '@medplum/core';\nimport type { Communication, Patient, Reference } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './ThreadListItem.module.css';\n\nexport interface ThreadListItemProps {\n  topic: Communication;\n  lastCommunication: Communication | undefined;\n  getThreadUri: (topic: Communication) => string;\n}\n\n// Content-only row: the surrounding ListWithDetailPane `.item` wrapper owns the\n// hover/selected chrome, so this renders just the link and its contents.\nexport const ThreadListItem = (props: ThreadListItemProps): JSX.Element => {\n  const { topic, lastCommunication, getThreadUri } = props;\n  const patientResource = useResource(topic.subject as Reference<Patient>);\n  const patientName = formatHumanName(patientResource?.name?.[0]);\n  const lastMsg = lastCommunication?.payload?.[0]?.contentString;\n  const trimmedMsg = lastMsg?.length && lastMsg.length > 100 ? lastMsg.slice(0, 100) + '...' : lastMsg;\n  const senderName = lastCommunication?.sender?.display ? `${lastCommunication?.sender?.display}: ` : '';\n  const content = trimmedMsg ? `${senderName} ${trimmedMsg}` : `No messages available`;\n  const topicName = topic.topic?.text ?? content;\n\n  return (\n    <MedplumLink to={getThreadUri(topic)} underline=\"never\" display=\"block\" c=\"inherit\">\n      <Group p=\"xs\" align=\"center\" wrap=\"nowrap\">\n        <ResourceAvatar value={topic.subject} radius=\"xl\" size={36} />\n        <Stack gap={0}>\n          <Text size=\"sm\" fw={700} truncate=\"end\">\n            {patientName}\n          </Text>\n          <Text size=\"sm\" fw={400} lineClamp={2} className={classes.content}>\n            {topicName}\n          </Text>\n          <Text size=\"xs\" style={{ marginTop: 2 }}>\n            {lastCommunication ? formatDateTime(lastCommunication.sent) : ''}\n          </Text>\n        </Stack>\n      </Group>\n    </MedplumLink>\n  );\n};\n", ".content {\n  word-wrap: break-word;\n  overflow-wrap: break-word;\n  white-space: normal;\n  word-break: break-word;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Button, Group, ScrollArea, TextInput } from '@mantine/core';\nimport { showNotification, updateNotification } from '@mantine/notifications';\nimport type { MedplumClient, ProfileResource } from '@medplum/core';\nimport { createReference, normalizeErrorString } from '@medplum/core';\nimport type {\n  Attachment,\n  AuditEvent,\n  Bundle,\n  Communication,\n  DiagnosticReport,\n  Media,\n  OperationOutcome,\n  Reference,\n  Resource,\n  ResourceType,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconCheck, IconCloudUpload, IconFileAlert, IconMessage } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { AttachmentButton } from '../AttachmentButton/AttachmentButton';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { DiagnosticReportDisplay } from '../DiagnosticReportDisplay/DiagnosticReportDisplay';\nimport { Form } from '../Form/Form';\nimport { Panel } from '../Panel/Panel';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceDiffTable } from '../ResourceDiffTable/ResourceDiffTable';\nimport { ResourceTable } from '../ResourceTable/ResourceTable';\nimport type { TimelineItemProps } from '../Timeline/Timeline';\nimport { Timeline, TimelineItem, TimelineItemSkeleton } from '../Timeline/Timeline';\nimport { sortByDateAndPriority } from '../utils/date';\nimport classes from './ResourceTimeline.module.css';\n\nexport interface ResourceTimelineMenuItemContext {\n  readonly primaryResource: Resource;\n  readonly currentResource: Resource;\n  readonly reloadTimeline: () => void;\n}\n\nexport interface ResourceTimelineProps<T extends Resource> {\n  readonly value: T | Reference<T>;\n  readonly loadTimelineResources: (\n    medplum: MedplumClient,\n    resourceType: ResourceType,\n    id: string\n  ) => Promise<PromiseSettledResult<Bundle>[]>;\n  readonly createCommunication?: (resource: T, sender: ProfileResource, text: string) => Communication;\n  readonly createMedia?: (resource: T, operator: ProfileResource, attachment: Attachment) => Media;\n  readonly getMenu?: (context: ResourceTimelineMenuItemContext) => ReactNode;\n}\n\nexport function ResourceTimeline<T extends Resource>(props: ResourceTimelineProps<T>): JSX.Element {\n  const medplum = useMedplum();\n  const sender = medplum.getProfile() as ProfileResource;\n  const inputRef = useRef<HTMLInputElement>(null);\n  const resource = useResource(props.value);\n  const [history, setHistory] = useState<Bundle>();\n  const [items, setItems] = useState<Resource[]>([]);\n  const [countToShow, setCountToShow] = useState(10);\n  const [loading, setLoading] = useState(true);\n  const loadTimelineResources = props.loadTimelineResources;\n\n  const itemsRef = useRef(items);\n  useLayoutEffect(() => {\n    itemsRef.current = items;\n  });\n\n  /**\n   * Sorts and sets the items.\n   *\n   * Sorting is primarily a function of meta.lastUpdated, but there are special cases.\n   * When displaying connected resources, for example a Communication in the context of an Encounter,\n   * the Communication.sent time is used rather than Communication.meta.lastUpdated.\n   *\n   * Other examples of special cases:\n   * - DiagnosticReport.issued\n   * - Media.issued\n   * - Observation.issued\n   * - DocumentReference.date\n   *\n   * See \"sortByDateAndPriority()\" for more details.\n   */\n  const sortAndSetItems = useCallback(\n    (newItems: Resource[]): void => {\n      sortByDateAndPriority(newItems, resource);\n      newItems.reverse();\n      setItems(newItems);\n    },\n    [resource]\n  );\n\n  /**\n   * Handles a batch request response.\n   * @param batchResponse - The batch response.\n   */\n  const handleBatchResponse = useCallback(\n    (batchResponse: PromiseSettledResult<Bundle>[]): void => {\n      const newItems: Resource[] = [];\n\n      for (const settledResult of batchResponse) {\n        if (settledResult.status !== 'fulfilled') {\n          // User may not have access to all resource types\n          continue;\n        }\n\n        const bundle = settledResult.value;\n        if (bundle.type === 'history') {\n          setHistory(bundle);\n        }\n\n        if (bundle.entry) {\n          for (const entry of bundle.entry) {\n            newItems.push(entry.resource as Resource);\n          }\n        }\n      }\n\n      sortAndSetItems(newItems);\n      setLoading(false);\n    },\n    [sortAndSetItems]\n  );\n\n  /**\n   * Adds an array of resources to the timeline.\n   * @param resource - Resource to add.\n   */\n  const addResource = useCallback(\n    (resource: Resource): void => sortAndSetItems([...itemsRef.current, resource]),\n    [sortAndSetItems]\n  );\n\n  /**\n   * Loads the timeline.\n   */\n  const loadTimeline = useCallback(() => {\n    let resourceType: ResourceType;\n    let id: string;\n    if ('resourceType' in props.value) {\n      resourceType = props.value.resourceType;\n      id = props.value.id as string;\n    } else {\n      [resourceType, id] = props.value.reference?.split('/') as [ResourceType, string];\n    }\n    loadTimelineResources(medplum, resourceType, id)\n      .then(handleBatchResponse)\n      .catch((err) => {\n        console.error(err);\n        setLoading(false);\n      });\n  }, [medplum, props.value, loadTimelineResources, handleBatchResponse]);\n\n  useEffect(() => loadTimeline(), [loadTimeline]);\n\n  /**\n   * Adds a Communication resource to the timeline.\n   * @param contentString - The comment content.\n   */\n  function createComment(contentString: string): void {\n    if (!resource || !props.createCommunication) {\n      // Encounter not loaded yet\n      return;\n    }\n    medplum\n      .createResource(props.createCommunication(resource, sender, contentString))\n      .then((result) => addResource(result))\n      .catch(console.error);\n  }\n\n  /**\n   * Adds a Media resource to the timeline.\n   * @param attachment - The media attachment.\n   */\n  function createMedia(attachment: Attachment): void {\n    if (!resource || !props.createMedia) {\n      // Encounter not loaded yet\n      return;\n    }\n    medplum\n      .createResource(props.createMedia(resource, sender, attachment))\n      .then((result) => addResource(result))\n      .then(() =>\n        updateNotification({\n          id: 'upload-notification',\n          color: 'teal',\n          title: 'Upload complete',\n          message: '',\n          icon: <IconCheck size={16} />,\n          autoClose: 2000,\n        })\n      )\n      .catch((reason) =>\n        updateNotification({\n          id: 'upload-notification',\n          color: 'red',\n          title: 'Upload error',\n          message: normalizeErrorString(reason),\n          icon: <IconFileAlert size={16} />,\n          autoClose: 2000,\n        })\n      );\n  }\n\n  function onUploadStart(): void {\n    showNotification({\n      id: 'upload-notification',\n      loading: true,\n      title: 'Initializing upload...',\n      message: 'Please wait...',\n      autoClose: false,\n      withCloseButton: false,\n    });\n  }\n\n  function onUploadProgress(e: ProgressEvent): void {\n    updateNotification({\n      id: 'upload-notification',\n      loading: true,\n      title: 'Uploading...',\n      message: getProgressMessage(e),\n      autoClose: false,\n      withCloseButton: false,\n    });\n  }\n\n  function onUploadError(outcome: OperationOutcome): void {\n    updateNotification({\n      id: 'upload-notification',\n      color: 'red',\n      title: 'Upload error',\n      message: normalizeErrorString(outcome),\n      icon: <IconFileAlert size={16} />,\n      autoClose: 2000,\n    });\n  }\n\n  if (!resource) {\n    return (\n      <Timeline>\n        <TimelineSkeletonItems />\n      </Timeline>\n    );\n  }\n\n  // TODO: Handle null history items for deleted versions.\n  const itemsToShow = items.filter((item) => item).slice(0, countToShow);\n\n  return (\n    <Timeline>\n      {props.createCommunication && (\n        <Panel>\n          <Form\n            testid=\"timeline-form\"\n            onSubmit={(formData: Record<string, string>) => {\n              createComment(formData.text);\n\n              const input = inputRef.current;\n              if (input) {\n                input.value = '';\n                input.focus();\n              }\n            }}\n          >\n            <Group gap=\"xs\" wrap=\"nowrap\" style={{ width: '100%' }}>\n              <ResourceAvatar value={sender} />\n              <TextInput\n                name=\"text\"\n                ref={inputRef}\n                placeholder=\"Add comment\"\n                style={{ width: '100%', maxWidth: 300 }}\n              />\n              <ActionIcon type=\"submit\" radius=\"xl\" color=\"blue\" variant=\"filled\">\n                <IconMessage size={16} />\n              </ActionIcon>\n              <AttachmentButton\n                securityContext={createReference(resource)}\n                onUpload={createMedia}\n                onUploadStart={onUploadStart}\n                onUploadProgress={onUploadProgress}\n                onUploadError={onUploadError}\n              >\n                {(props) => (\n                  <ActionIcon {...props} radius=\"xl\" color=\"blue\" variant=\"filled\">\n                    <IconCloudUpload size={16} />\n                  </ActionIcon>\n                )}\n              </AttachmentButton>\n            </Group>\n          </Form>\n        </Panel>\n      )}\n      {loading && items.length === 0 && <TimelineSkeletonItems />}\n      {itemsToShow.map((item) => {\n        const key = `${item.resourceType}/${item.id}/${item.meta?.versionId}`;\n        const menu = props.getMenu\n          ? props.getMenu({\n              primaryResource: resource,\n              currentResource: item,\n              reloadTimeline: loadTimeline,\n            })\n          : undefined;\n        if (item.resourceType === resource.resourceType && item.id === resource.id) {\n          return <HistoryTimelineItem key={key} history={history as Bundle} resource={item} popupMenuItems={menu} />;\n        }\n        switch (item.resourceType) {\n          case 'AuditEvent':\n            return <AuditEventTimelineItem key={key} resource={item} popupMenuItems={menu} />;\n          case 'Communication':\n            return <CommunicationTimelineItem key={key} resource={item} popupMenuItems={menu} />;\n          case 'DiagnosticReport':\n            return <DiagnosticReportTimelineItem key={key} resource={item} popupMenuItems={menu} />;\n          case 'Media':\n            return <MediaTimelineItem key={key} resource={item} popupMenuItems={menu} />;\n          default:\n            return (\n              <TimelineItem key={key} resource={item} padding={true}>\n                <ResourceTable value={item} ignoreMissingValues={true} />\n              </TimelineItem>\n            );\n        }\n      })}\n      {countToShow < items.length && (\n        <Group justify=\"center\" pb=\"lg\">\n          <Button onClick={() => setCountToShow(countToShow + 10)}>Show More</Button>\n        </Group>\n      )}\n    </Timeline>\n  );\n}\n\nfunction TimelineSkeletonItems(): JSX.Element {\n  return (\n    <>\n      <TimelineItemSkeleton lines={3} />\n      <TimelineItemSkeleton lines={6} />\n      <TimelineItemSkeleton lines={4} />\n    </>\n  );\n}\n\ninterface HistoryTimelineItemProps extends TimelineItemProps {\n  readonly history: Bundle;\n}\n\nfunction HistoryTimelineItem(props: HistoryTimelineItemProps): JSX.Element {\n  const { history, resource, ...rest } = props;\n  const previous = getPrevious(history, resource);\n  if (previous) {\n    return (\n      <TimelineItem resource={resource} padding={true} {...rest}>\n        <ResourceDiffTable original={previous} revised={props.resource} />\n      </TimelineItem>\n    );\n  } else {\n    return (\n      <TimelineItem resource={resource} padding={true} {...rest}>\n        <h3>Created</h3>\n        <ResourceTable value={resource} ignoreMissingValues forceUseInput />\n      </TimelineItem>\n    );\n  }\n}\n\nfunction getPrevious(history: Bundle, version: Resource): Resource | undefined {\n  const entries = history.entry ?? [];\n  const index = entries.findIndex((entry) => entry.resource?.meta?.versionId === version.meta?.versionId);\n  // If not found index is -1, -1 === 0 - 1 so this returns undefined\n  if (index >= entries.length - 1) {\n    return undefined;\n  }\n  return entries[index + 1].resource;\n}\n\nfunction CommunicationTimelineItem(props: TimelineItemProps<Communication>): JSX.Element {\n  const routine = !props.resource.priority || props.resource.priority === 'routine';\n  const className = routine ? undefined : classes.pinnedComment;\n  return (\n    <TimelineItem\n      resource={props.resource}\n      profile={props.resource.sender}\n      dateTime={props.resource.sent}\n      padding={true}\n      className={className}\n      popupMenuItems={props.popupMenuItems}\n    >\n      <p>{props.resource.payload?.[0]?.contentString}</p>\n    </TimelineItem>\n  );\n}\n\nfunction MediaTimelineItem(props: TimelineItemProps<Media>): JSX.Element {\n  const contentType = props.resource.content?.contentType;\n  const padding =\n    contentType &&\n    !contentType.startsWith('image/') &&\n    !contentType.startsWith('video/') &&\n    contentType !== 'application/pdf';\n  return (\n    <TimelineItem resource={props.resource} padding={!!padding} popupMenuItems={props.popupMenuItems}>\n      <AttachmentDisplay value={props.resource.content} />\n    </TimelineItem>\n  );\n}\n\nfunction AuditEventTimelineItem(props: TimelineItemProps<AuditEvent>): JSX.Element {\n  return (\n    <TimelineItem resource={props.resource} padding={true} popupMenuItems={props.popupMenuItems}>\n      <ScrollArea>\n        <pre>{props.resource.outcomeDesc}</pre>\n      </ScrollArea>\n    </TimelineItem>\n  );\n}\n\nfunction DiagnosticReportTimelineItem(props: TimelineItemProps<DiagnosticReport>): JSX.Element {\n  return (\n    <TimelineItem resource={props.resource} padding={true} popupMenuItems={props.popupMenuItems}>\n      <DiagnosticReportDisplay value={props.resource} />\n    </TimelineItem>\n  );\n}\n\nfunction getProgressMessage(e: ProgressEvent): string {\n  if (e.lengthComputable) {\n    const percent = (100 * e.loaded) / e.total;\n    return `Uploaded: ${formatFileSize(e.loaded)} / ${formatFileSize(e.total)} ${percent.toFixed(2)}%`;\n  }\n  return `Uploaded: ${formatFileSize(e.loaded)}`;\n}\n\nfunction formatFileSize(bytes: number): string {\n  if (bytes === 0) {\n    return '0.00 B';\n  }\n  const e = Math.floor(Math.log(bytes) / Math.log(1024));\n  return (bytes / Math.pow(1024, e)).toFixed(2) + ' ' + ' KMGTP'.charAt(e) + 'B';\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Table } from '@mantine/core';\nimport type { InternalSchemaElement, Operation, TypedValue } from '@medplum/core';\nimport {\n  arrayify,\n  capitalize,\n  createPatch,\n  evalFhirPathTyped,\n  getSearchParameterDetails,\n  toTypedValue,\n} from '@medplum/core';\nimport type { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { ResourceDiffRow } from '../ResourceDiffRow/ResourceDiffRow';\nimport classes from './ResourceDiffTable.module.css';\n\nexport interface ResourceDiffTableProps {\n  readonly original: Resource;\n  readonly revised: Resource;\n}\n\nexport function ResourceDiffTable(props: ResourceDiffTableProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const { original, revised } = props;\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n\n  useEffect(() => {\n    medplum\n      .requestSchema(props.original.resourceType)\n      .then(() => setSchemaLoaded(true))\n      .catch(console.log);\n  }, [medplum, props.original.resourceType]);\n\n  const diffTable = useMemo(() => {\n    if (!schemaLoaded) {\n      return null;\n    }\n\n    const typedOriginal = [toTypedValue(original)];\n    const typedRevised = [toTypedValue(revised)];\n    const result = [];\n\n    // First, we filter and consolidate the patch operations\n    // We can do this because we do not use the \"value\" field in the patch operations\n    // Remove patch operations on meta elements such as \"meta.lastUpdated\" and \"meta.versionId\"\n    // Consolidate patch operations on arrays\n    const patch = mergePatchOperations(createPatch(original, revised));\n\n    // Next, convert the patch operations to a diff table\n    for (const op of patch) {\n      const path = op.path;\n      const fhirPath = jsonPathToFhirPath(path);\n      const property = tryGetElementDefinition(original.resourceType, fhirPath);\n      const originalValue = op.op === 'add' ? undefined : evalFhirPathTyped(fhirPath, typedOriginal);\n      const revisedValue = op.op === 'remove' ? undefined : evalFhirPathTyped(fhirPath, typedRevised);\n      result.push({\n        key: `op-${op.op}-${op.path}`,\n        name: `${capitalize(op.op)} ${fhirPath}`,\n        path: property?.path ?? original.resourceType + '.' + fhirPath,\n        property: property,\n        originalValue: touchUpValue(property, originalValue),\n        revisedValue: touchUpValue(property, revisedValue),\n      });\n    }\n\n    return result;\n  }, [schemaLoaded, original, revised]);\n\n  if (!diffTable) {\n    return null;\n  }\n\n  return (\n    <Table className={classes.root}>\n      <Table.Thead>\n        <Table.Tr>\n          <Table.Th />\n          <Table.Th>Before</Table.Th>\n          <Table.Th>After</Table.Th>\n        </Table.Tr>\n      </Table.Thead>\n      <Table.Tbody>\n        {diffTable.map((row) => {\n          const { key, ...rest } = row;\n          return <ResourceDiffRow key={key} {...rest} />;\n        })}\n      </Table.Tbody>\n    </Table>\n  );\n}\n\nfunction mergePatchOperations(patch: Operation[]): Operation[] {\n  const result: Operation[] = [];\n  for (const patchOperation of patch) {\n    const { op, path } = patchOperation;\n    if (\n      path.startsWith('/meta/author') ||\n      path.startsWith('/meta/compartment') ||\n      path.startsWith('/meta/lastUpdated') ||\n      path.startsWith('/meta/versionId')\n    ) {\n      continue;\n    }\n    const count = patch.filter((el) => el.op === op && el.path === path).length;\n    const resultOperation = { op, path } as Operation;\n    if (count > 1 && (op === 'add' || op === 'remove') && /\\/[0-9-]+$/.test(path)) {\n      // Remove everything after the last slash\n      resultOperation.op = 'replace';\n      resultOperation.path = path.replace(/\\/[^/]+$/, '');\n    }\n    if (!result.some((el) => el.op === resultOperation.op && el.path === resultOperation.path)) {\n      // Only add the operation if it doesn't already exist\n      result.push(resultOperation);\n    }\n  }\n  return result;\n}\n\nfunction jsonPathToFhirPath(path: string): string {\n  const parts = path.split('/').filter(Boolean);\n  let result = '';\n  for (let i = 0; i < parts.length; i++) {\n    const part = parts[i];\n    if (part === '-') {\n      result += '.last()';\n    } else if (/^\\d+$/.test(part)) {\n      result += `[${part}]`;\n    } else {\n      if (i > 0) {\n        result += '.';\n      }\n      result += part;\n    }\n  }\n\n  // For attachments, remove the .url suffix\n  // Note that not all \".url\" properties are attachments, but it is the common case.\n  // If the property is not an attachment, the diff will simply render the parent element,\n  // which is still fine.\n  if (result.endsWith('.url')) {\n    result = result.replace(/\\.url$/, '');\n  }\n\n  return result;\n}\n\nfunction tryGetElementDefinition(resourceType: string, fhirPath: string): InternalSchemaElement | undefined {\n  try {\n    const details = getSearchParameterDetails(resourceType, {\n      resourceType: 'SearchParameter',\n      base: [resourceType],\n      code: resourceType + '.' + fhirPath,\n      expression: resourceType + '.' + fhirPath,\n    } as SearchParameter);\n    return details?.elementDefinitions?.[0];\n  } catch (err) {\n    console.warn('Failed to get element definition', { resourceType, fhirPath, err });\n    return undefined;\n  }\n}\n\nfunction touchUpValue(\n  property: InternalSchemaElement | undefined,\n  input: TypedValue[] | TypedValue | undefined\n): TypedValue | undefined {\n  if (!input || (Array.isArray(input) && input.length === 0)) {\n    return undefined;\n  }\n  return {\n    type: Array.isArray(input) ? input[0].type : input.type,\n    value: fixArray(input, !!property?.isArray),\n  };\n}\n\nfunction fixArray(input: TypedValue[] | TypedValue, isArray: boolean): any {\n  const inputValue = arrayify(input).flatMap((v) => v.value);\n  return isArray ? inputValue : inputValue[0];\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Table } from '@mantine/core';\nimport type { InternalSchemaElement, TypedValue } from '@medplum/core';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport classes from './ResourceDiffRow.module.css';\n\nexport interface ResourceDiffRowProps {\n  name: string;\n  path: string;\n  property: InternalSchemaElement | undefined;\n  originalValue: TypedValue | undefined;\n  revisedValue: TypedValue | undefined;\n}\n\nexport function ResourceDiffRow(props: ResourceDiffRowProps): JSX.Element {\n  const { name, path, property, originalValue, revisedValue } = props;\n  const isAttachmentType = !!property?.type?.find((t) => t.code === 'Attachment');\n  const [isCollapsed, setIsCollapsed] = useState(isAttachmentType);\n  const toggleCollapse = (): void => setIsCollapsed((prev) => !prev);\n\n  return (\n    <>\n      {(isAttachmentType && !isCollapsed) || !isAttachmentType ? (\n        <>\n          <Table.Tr>\n            <Table.Td>{name}</Table.Td>\n            <Table.Td className={classes.removed}>\n              {originalValue && (\n                <ResourcePropertyDisplay\n                  path={path}\n                  property={property}\n                  propertyType={originalValue.type}\n                  value={originalValue.value}\n                  ignoreMissingValues={true}\n                />\n              )}\n            </Table.Td>\n            <Table.Td className={classes.added}>\n              {revisedValue && (\n                <ResourcePropertyDisplay\n                  path={path}\n                  property={property}\n                  propertyType={revisedValue.type}\n                  value={revisedValue.value}\n                  ignoreMissingValues={true}\n                />\n              )}\n            </Table.Td>\n          </Table.Tr>\n        </>\n      ) : (\n        <Table.Tr>\n          <Table.Td>{name}</Table.Td>\n          <Table.Td colSpan={2} style={{ textAlign: 'right' }}>\n            <Button onClick={toggleCollapse} variant=\"light\">\n              Expand\n            </Button>\n          </Table.Td>\n        </Table.Tr>\n      )}\n    </>\n  );\n}\n", ".removed {\n  color: var(--mantine-color-red-7);\n  text-decoration: line-through;\n}\n\n.added {\n  color: var(--mantine-color-green-7);\n}\n", ".root {\n  border-collapse: collapse;\n  width: 100%;\n\n  & tr {\n    border-top: 0.1px solid var(--mantine-color-gray-3);\n  }\n\n  & th,\n  & td {\n    padding: var(--mantine-spacing-sm) var(--mantine-spacing-sm);\n    vertical-align: top;\n    word-wrap: break-word;\n    overflow-wrap: anywhere;\n    white-space: normal;\n    min-width: 100px;\n  }\n}\n\n.removed {\n  color: var(--mantine-color-red-7);\n  text-decoration: line-through;\n}\n\n.added {\n  color: var(--mantine-color-green-7);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { AccessPolicyInteraction, satisfiedAccessPolicy, tryGetProfile } from '@medplum/core';\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { BackboneElementDisplay } from '../BackboneElementDisplay/BackboneElementDisplay';\n\nexport interface ResourceTableProps {\n  /**\n   * The input value either as a resource or a reference.\n   */\n  readonly value: Resource | Reference;\n\n  /**\n   * Optional flag to ignore missing values.\n   * By default, missing values are displayed as empty strings.\n   */\n  readonly ignoreMissingValues?: boolean;\n\n  /**\n   * Optional flag to force use the input value.\n   * This is useful when you want to display a specific version of the resource,\n   * and not use the latest version.\n   */\n  readonly forceUseInput?: boolean;\n\n  /** (optional) URL of the resource profile used to display the form. */\n  readonly profileUrl?: string;\n}\n\nexport function ResourceTable(props: ResourceTableProps): JSX.Element | null {\n  const { profileUrl } = props;\n  const medplum = useMedplum();\n  const accessPolicy = medplum.getAccessPolicy();\n  const value = useResource(props.value);\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n\n  useEffect(() => {\n    if (!value) {\n      return;\n    }\n\n    if (profileUrl) {\n      medplum\n        .requestProfileSchema(profileUrl, { expandProfile: true })\n        .then(() => {\n          const profile = tryGetProfile(profileUrl);\n          if (profile) {\n            setSchemaLoaded(true);\n          } else {\n            console.error(`Schema not found for ${profileUrl}`);\n          }\n        })\n        .catch((reason) => {\n          console.error('Error in requestProfileSchema', reason);\n        });\n    } else {\n      const schemaName = value.resourceType;\n      medplum\n        .requestSchema(schemaName)\n        .then(() => {\n          setSchemaLoaded(true);\n        })\n        .catch(console.error);\n    }\n  }, [medplum, profileUrl, value]);\n\n  const accessPolicyResource = useMemo(() => {\n    return value && satisfiedAccessPolicy(value, AccessPolicyInteraction.READ, accessPolicy);\n  }, [accessPolicy, value]);\n\n  if (!schemaLoaded || !value) {\n    return null;\n  }\n\n  return (\n    <BackboneElementDisplay\n      path={value.resourceType}\n      value={{\n        type: value.resourceType,\n        value: props.forceUseInput ? props.value : value,\n      }}\n      profileUrl={profileUrl}\n      ignoreMissingValues={props.ignoreMissingValues}\n      accessPolicyResource={accessPolicyResource}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Group, Menu, Skeleton, Stack, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport type { Reference, Resource } from '@medplum/fhirtypes';\nimport { IconDots } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { Container } from '../Container/Container';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport type { PanelProps } from '../Panel/Panel';\nimport { Panel } from '../Panel/Panel';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport classes from './Timeline.module.css';\n\nexport interface TimelineProps {\n  readonly children?: ReactNode;\n}\n\nexport function Timeline(props: TimelineProps): JSX.Element {\n  return <Container w=\"100%\">{props.children}</Container>;\n}\n\nexport interface TimelineItemProps<T extends Resource = Resource> extends PanelProps {\n  readonly resource: T;\n  readonly profile?: Reference;\n  readonly dateTime?: string;\n  readonly padding?: boolean;\n  readonly popupMenuItems?: ReactNode;\n}\n\nexport function TimelineItem(props: TimelineItemProps): JSX.Element {\n  const { resource, profile, padding, popupMenuItems, ...others } = props;\n  const author = profile ?? resource.meta?.author;\n  const onBehalfOf = resource.meta?.onBehalfOf;\n  const dateTime = props.dateTime ?? resource.meta?.lastUpdated;\n\n  return (\n    <Panel data-testid=\"timeline-item\" fill={true} {...others}>\n      <Group justify=\"space-between\" gap={8} mx=\"xs\" my=\"sm\">\n        <ResourceAvatar value={author} link={true} size=\"md\" />\n        <div style={{ flex: 1 }}>\n          <Text size=\"sm\">\n            <ResourceName c=\"inherit\" fw={500} value={author} link={true} />\n            {onBehalfOf && (\n              <Text component=\"span\" size=\"xs\" c=\"dimmed\">\n                {' on behalf of '}\n                <ResourceName c=\"inherit\" value={onBehalfOf} link={true} />\n              </Text>\n            )}\n          </Text>\n          <Text size=\"xs\">\n            <MedplumLink c=\"dimmed\" to={props.resource}>\n              {formatDateTime(dateTime)}\n            </MedplumLink>\n            <Text component=\"span\" c=\"dimmed\" mx={8}>\n              &middot;\n            </Text>\n            <MedplumLink c=\"dimmed\" to={props.resource}>\n              {props.resource.resourceType}\n            </MedplumLink>\n          </Text>\n        </div>\n        {popupMenuItems && (\n          <Menu position=\"bottom-end\" shadow=\"md\" width={200}>\n            <Menu.Target>\n              <ActionIcon\n                color=\"gray\"\n                variant=\"subtle\"\n                radius=\"xl\"\n                aria-label={`Actions for ${getReferenceString(props.resource)}`}\n              >\n                <IconDots />\n              </ActionIcon>\n            </Menu.Target>\n            {popupMenuItems}\n          </Menu>\n        )}\n      </Group>\n      <ErrorBoundary>\n        <div className={cx(classes.item, { [classes.itemPadding]: padding })}>{props.children}</div>\n      </ErrorBoundary>\n    </Panel>\n  );\n}\n\nexport interface TimelineItemSkeletonProps {\n  readonly lines?: number;\n}\n\n/**\n * Loading placeholder that mirrors the TimelineItem layout: an avatar with name and date lines\n * in the header, followed by a title bar and full-width body rows.\n * @param props - The skeleton props.\n * @returns The TimelineItemSkeleton React node.\n */\nexport function TimelineItemSkeleton(props: TimelineItemSkeletonProps): JSX.Element {\n  const lines = props.lines ?? 4;\n  return (\n    <Panel data-testid=\"timeline-item-skeleton\" fill={true}>\n      <Group gap={8} mx=\"xs\" my=\"sm\" wrap=\"nowrap\">\n        <Skeleton circle height={38} />\n        <Stack gap={8} style={{ flex: 1 }}>\n          <Skeleton height={16} width=\"28%\" />\n          <Skeleton height={12} width=\"40%\" />\n        </Stack>\n      </Group>\n      <Stack gap=\"md\" className={classes.itemPadding}>\n        <Skeleton height={24} width=\"35%\" mb=\"xs\" />\n        {Array.from({ length: lines }, (_, index) => (\n          <Skeleton key={index} height={18} />\n        ))}\n      </Stack>\n    </Panel>\n  );\n}\n", ".item {\n  white-space: pre-wrap;\n}\n\n.itemPadding {\n  padding: 0 16px 16px 16px;\n}\n", ".pinnedComment {\n  background-color: var(--mantine-color-blue-0);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport type { Reference, Resource, ResourceType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport type { ResourceTimelineProps } from '../ResourceTimeline/ResourceTimeline';\nimport { ResourceTimeline } from '../ResourceTimeline/ResourceTimeline';\n\nexport interface DefaultResourceTimelineProps extends Pick<ResourceTimelineProps<Resource>, 'getMenu'> {\n  readonly resource: Resource | Reference;\n}\n\nexport function DefaultResourceTimeline(props: DefaultResourceTimelineProps): JSX.Element {\n  const { resource, ...rest } = props;\n  return (\n    <ResourceTimeline\n      value={resource}\n      loadTimelineResources={async (medplum: MedplumClient, resourceType: ResourceType, id: string) => {\n        const ref = `${resourceType}/${id}`;\n        const _count = 100;\n        return Promise.allSettled([\n          medplum.readHistory(resourceType, id),\n          medplum.search('Task', { _filter: `based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`, _count }),\n        ]);\n      }}\n      {...rest}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, ProfileResource } from '@medplum/core';\nimport { createReference } from '@medplum/core';\nimport type { Attachment, Encounter, Reference, ResourceType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport type { ResourceTimelineProps } from '../ResourceTimeline/ResourceTimeline';\nimport { ResourceTimeline } from '../ResourceTimeline/ResourceTimeline';\n\nexport interface EncounterTimelineProps extends Pick<ResourceTimelineProps<Encounter>, 'getMenu'> {\n  readonly encounter: Encounter | Reference<Encounter>;\n}\n\nexport function EncounterTimeline(props: EncounterTimelineProps): JSX.Element {\n  const { encounter, ...rest } = props;\n\n  return (\n    <ResourceTimeline\n      value={encounter}\n      loadTimelineResources={async (medplum: MedplumClient, _resourceType: ResourceType, id: string) => {\n        return Promise.allSettled([\n          medplum.readHistory('Encounter', id),\n          medplum.search('Communication', 'encounter=Encounter/' + id),\n          medplum.search('Media', 'encounter=Encounter/' + id),\n        ]);\n      }}\n      createCommunication={(resource: Encounter, sender: ProfileResource, text: string) => ({\n        resourceType: 'Communication',\n        status: 'completed',\n        encounter: createReference(resource),\n        subject: resource.subject,\n        sender: createReference(sender),\n        sent: new Date().toISOString(),\n        payload: [{ contentString: text }],\n      })}\n      createMedia={(resource: Encounter, operator: ProfileResource, content: Attachment) => ({\n        resourceType: 'Media',\n        status: 'completed',\n        encounter: createReference(resource),\n        subject: resource.subject,\n        operator: createReference(operator),\n        issued: new Date().toISOString(),\n        content,\n      })}\n      {...rest}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Loader, Table } from '@mantine/core';\nimport { badRequest, normalizeOperationOutcome } from '@medplum/core';\nimport type { OperationOutcome, Resource } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { ChangeEvent, JSX, MouseEvent } from 'react';\nimport { memo, useEffect, useState } from 'react';\nimport { FhirPathDisplay } from '../FhirPathDisplay/FhirPathDisplay';\nimport { SearchClickEvent } from '../SearchControl/SearchControl';\nimport { isCheckboxCell, killEvent } from '../utils/dom';\n\nexport interface FhirPathTableField {\n  readonly propertyType: string;\n  readonly name: string;\n  readonly fhirPath: string;\n}\n\nexport interface FhirPathTableProps {\n  readonly resourceType: string;\n  readonly query: string;\n  readonly fields: FhirPathTableField[];\n  readonly checkboxesEnabled?: boolean;\n  readonly onClick?: (e: SearchClickEvent) => void;\n  readonly onAuxClick?: (e: SearchClickEvent) => void;\n  readonly onBulk?: (ids: string[]) => void;\n}\n\nexport interface SmartSearchResponse {\n  readonly data: {\n    ResourceList: Resource[];\n  };\n}\n\n/**\n * The FhirPathTable component represents the embeddable search table control.\n * @param props - FhirPathTable React props.\n * @returns FhirPathTable React node.\n */\nexport function FhirPathTable(props: FhirPathTableProps): JSX.Element {\n  const medplum = useMedplum();\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n  const [outcome, setOutcome] = useState<OperationOutcome | undefined>();\n  const { query, fields } = props;\n  const [response, setResponse] = useState<SmartSearchResponse | undefined>();\n  const [selected, setSelected] = useState<{ [id: string]: boolean }>({});\n\n  useEffect(() => {\n    setOutcome(undefined);\n    // Read-only table; same check as the server's includesMutations()\n    if (query.includes('mutation')) {\n      setResponse(undefined);\n      setOutcome(badRequest('Mutations are not allowed'));\n      return;\n    }\n    medplum\n      .graphql(query)\n      .then(setResponse)\n      .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n  }, [medplum, query]);\n\n  function handleSingleCheckboxClick(e: ChangeEvent, id: string): void {\n    e.stopPropagation();\n\n    const el = e.target as HTMLInputElement;\n    const checked = el.checked;\n    const newSelected = { ...selected };\n    if (checked) {\n      newSelected[id] = true;\n    } else {\n      delete newSelected[id];\n    }\n    setSelected(newSelected);\n  }\n\n  function handleAllCheckboxClick(e: ChangeEvent): void {\n    e.stopPropagation();\n\n    const el = e.target as HTMLInputElement;\n    const checked = el.checked;\n    const newSelected = {} as { [id: string]: boolean };\n    const resources = response?.data.ResourceList;\n    if (checked && resources) {\n      resources.forEach((resource) => {\n        if (resource.id) {\n          newSelected[resource.id] = true;\n        }\n      });\n    }\n    setSelected(newSelected);\n  }\n\n  function isAllSelected(): boolean {\n    const resources = response?.data.ResourceList;\n    if (!resources || resources.length === 0) {\n      return false;\n    }\n    for (const resource of resources) {\n      if (resource.id && !selected[resource.id]) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  function handleRowClick(e: MouseEvent, resource: Resource): void {\n    if (isCheckboxCell(e.target as Element)) {\n      // Ignore clicks on checkboxes\n      return;\n    }\n\n    killEvent(e);\n\n    if (e.button !== 1 && props.onClick) {\n      props.onClick(new SearchClickEvent(resource, e));\n    }\n\n    if (e.button === 1 && props.onAuxClick) {\n      props.onAuxClick(new SearchClickEvent(resource, e));\n    }\n  }\n\n  useEffect(() => {\n    medplum\n      .requestSchema(props.resourceType)\n      .then(() => setSchemaLoaded(true))\n      .catch(console.log);\n  }, [medplum, props.resourceType]);\n\n  if (!schemaLoaded) {\n    return <Loader />;\n  }\n\n  const checkboxColumn = props.checkboxesEnabled;\n\n  return (\n    <div onContextMenu={(e) => killEvent(e)} data-testid=\"search-control\">\n      <Table>\n        <Table.Thead>\n          <Table.Tr>\n            {checkboxColumn && (\n              <Table.Th>\n                <input\n                  type=\"checkbox\"\n                  value=\"checked\"\n                  aria-label=\"all-checkbox\"\n                  data-testid=\"all-checkbox\"\n                  checked={isAllSelected()}\n                  onChange={(e) => handleAllCheckboxClick(e)}\n                />\n              </Table.Th>\n            )}\n            {fields.map((field) => (\n              <Table.Th key={field.name}>{field.name}</Table.Th>\n            ))}\n          </Table.Tr>\n        </Table.Thead>\n        <Table.Tbody>\n          {response?.data.ResourceList.map(\n            (resource) =>\n              resource && (\n                <Table.Tr\n                  key={resource.id}\n                  data-testid=\"search-control-row\"\n                  onClick={(e) => handleRowClick(e, resource)}\n                  onAuxClick={(e) => handleRowClick(e, resource)}\n                >\n                  {checkboxColumn && (\n                    <Table.Td>\n                      <input\n                        type=\"checkbox\"\n                        value=\"checked\"\n                        data-testid=\"row-checkbox\"\n                        aria-label={`Checkbox for ${resource.id}`}\n                        checked={!!selected[resource.id as string]}\n                        onChange={(e) => handleSingleCheckboxClick(e, resource.id as string)}\n                      />\n                    </Table.Td>\n                  )}\n                  {fields.map((field) => {\n                    return (\n                      <Table.Td key={field.name}>\n                        <FhirPathDisplay propertyType={field.propertyType} path={field.fhirPath} resource={resource} />\n                      </Table.Td>\n                    );\n                  })}\n                </Table.Tr>\n              )\n          )}\n        </Table.Tbody>\n      </Table>\n      {response?.data.ResourceList.length === 0 && <div data-testid=\"empty-search\">No results</div>}\n      {outcome && (\n        <div data-testid=\"search-error\">\n          <pre style={{ textAlign: 'left' }}>{JSON.stringify(outcome, undefined, 2)}</pre>\n        </div>\n      )}\n      {props.onBulk && (\n        <Button onClick={() => (props.onBulk as (ids: string[]) => any)(Object.keys(selected))}>Bulk...</Button>\n      )}\n    </div>\n  );\n}\n\nexport const MemoizedFhirPathTable = memo(FhirPathTable);\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { evalFhirPath } from '@medplum/core';\nimport type { Resource } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\n\nexport interface FhirPathDisplayProps {\n  readonly resource: Resource;\n  readonly path: string;\n  readonly propertyType: string;\n}\n\nexport function FhirPathDisplay(props: FhirPathDisplayProps): JSX.Element | null {\n  let value;\n\n  try {\n    value = evalFhirPath(props.path, props.resource);\n  } catch (err) {\n    console.warn('FhirPathDisplay:', err);\n    return null;\n  }\n\n  if (value.length > 1) {\n    throw new Error(\n      `Component \"path\" for \"FhirPathDisplay\" must resolve to a single element. \\\n       Received ${value.length} elements \\\n       [${JSON.stringify(value, null, 2)}]`\n    );\n  }\n  return <ResourcePropertyDisplay value={value[0] || ''} propertyType={props.propertyType} />;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport {\n  ActionIcon,\n  Button,\n  Center,\n  Checkbox,\n  Group,\n  Loader,\n  Menu,\n  Pagination,\n  Table,\n  Text,\n  Tooltip,\n  UnstyledButton,\n} from '@mantine/core';\nimport type { Filter, SearchRequest } from '@medplum/core';\nimport {\n  deepEquals,\n  DEFAULT_SEARCH_COUNT,\n  formatSearchQuery,\n  isDataTypeLoaded,\n  normalizeOperationOutcome,\n} from '@medplum/core';\nimport type { Bundle, OperationOutcome, Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport {\n  IconArrowDown,\n  IconArrowUp,\n  IconColumns,\n  IconDots,\n  IconLibraryPlus,\n  IconPlus,\n  IconReload,\n  IconTableExport,\n  IconTrash,\n} from '@tabler/icons-react';\nimport type { JSX, KeyboardEvent, MouseEvent, ReactNode } from 'react';\nimport { useCallback, useEffect, useState } from 'react';\nimport { Container } from '../Container/Container';\nimport { Modal } from '../Modal/Modal';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { SearchExportDialog } from '../SearchExportDialog/SearchExportDialog';\nimport { SearchFieldEditor } from '../SearchFieldEditor/SearchFieldEditor';\nimport { SearchFilterPopover } from '../SearchFilterEditor/SearchFilterPopover';\nimport { SearchFilterValueDialog } from '../SearchFilterValueDialog/SearchFilterValueDialog';\nimport { SearchFilterValueDisplay } from '../SearchFilterValueDisplay/SearchFilterValueDisplay';\nimport { SearchPopupMenu } from '../SearchPopupMenu/SearchPopupMenu';\nimport { SearchSortEditor } from '../SearchSortEditor/SearchSortEditor';\nimport { isAuxClick, isCheckboxCell, killEvent } from '../utils/dom';\nimport { getPaginationControlProps } from '../utils/pagination';\nimport classes from './SearchControl.module.css';\nimport { getFieldDefinitions } from './SearchControlField';\nimport { addFilter, buildFieldNameString, DEFAULT_SORT_RULES, getOpString, renderValue, setPage } from './SearchUtils';\n\nexport class SearchChangeEvent extends Event {\n  readonly definition: SearchRequest;\n\n  constructor(definition: SearchRequest) {\n    super('change');\n    this.definition = definition;\n  }\n}\n\nexport class SearchLoadEvent extends Event {\n  readonly response: Bundle;\n\n  constructor(response: Bundle) {\n    super('load');\n    this.response = response;\n  }\n}\n\nexport class SearchClickEvent extends Event {\n  readonly resource: Resource;\n  readonly browserEvent: MouseEvent;\n\n  constructor(resource: Resource, browserEvent: MouseEvent) {\n    super('click');\n    this.resource = resource;\n    this.browserEvent = browserEvent;\n  }\n}\n\n/**\n * An additional, computed column appended after the search-result columns. It is not backed by a\n * search parameter, so it has no sort/filter menu and renders arbitrary content per row.\n */\nexport interface SearchControlAdditionalColumn {\n  /** The column header text. */\n  readonly name: string;\n  /** Renders the cell contents for the given row resource. */\n  readonly renderCell: (resource: Resource) => ReactNode;\n}\n\nexport interface SearchControlProps {\n  readonly search: SearchRequest;\n  readonly checkboxesEnabled?: boolean;\n  /** Additional computed columns rendered after the search-result columns. */\n  readonly additionalColumns?: readonly SearchControlAdditionalColumn[];\n  readonly hideToolbar?: boolean;\n  /** Hides the per-column filter description row under the column headers. */\n  readonly hideFilters?: boolean;\n  readonly onLoad?: (e: SearchLoadEvent) => void;\n  readonly onChange?: (e: SearchChangeEvent) => void;\n  readonly onClick?: (e: SearchClickEvent) => void;\n  readonly onAuxClick?: (e: SearchClickEvent) => void;\n  readonly onNew?: () => void;\n  readonly onExport?: () => void;\n  readonly onExportCsv?: () => void;\n  readonly onExportTransactionBundle?: () => void;\n  /**\n   * Deletes the checked rows after confirmation. A returned Promise keeps the modal open with a\n   * loading button until it settles; a rejection leaves the modal open for the caller to report.\n   */\n  readonly onDelete?: (ids: string[]) => void | Promise<void>;\n  readonly onBulk?: (ids: string[]) => void;\n}\n\ninterface SearchControlState {\n  readonly searchResponse?: Bundle;\n  readonly selected: { [id: string]: boolean };\n  readonly exportDialogVisible: boolean;\n  readonly deleteConfirmVisible?: boolean;\n  readonly deleting?: boolean;\n  readonly dialogOpenTime?: number;\n  readonly fieldEditorVisible: boolean;\n  readonly filterDialogVisible: boolean;\n  readonly filterDialogFilter?: Filter;\n  readonly filterDialogSearchParam?: SearchParameter;\n}\n\n/**\n * Embeddable FHIR search table with a toolbar (column, filter and sort popovers, result count,\n * actions menu, New button), sortable/filterable column headers, optional row checkboxes and\n * pagination. Controlled: every change is emitted through `onChange` for the caller to apply.\n * @param props - The SearchControl React props.\n * @returns The SearchControl React node.\n */\nexport function SearchControl(props: SearchControlProps): JSX.Element {\n  const medplum = useMedplum();\n  const [outcome, setOutcome] = useState<OperationOutcome | undefined>();\n  const { search, onLoad } = props;\n  const sortedSearch = search.sortRules?.length ? search : { ...search, sortRules: [...DEFAULT_SORT_RULES] };\n\n  const [memoizedSearch, setMemoizedSearch] = useState(sortedSearch);\n\n  if (!deepEquals(sortedSearch, memoizedSearch)) {\n    setMemoizedSearch(sortedSearch);\n  }\n\n  const [state, setState] = useState<SearchControlState>({\n    selected: {},\n    exportDialogVisible: false,\n    fieldEditorVisible: false,\n    filterDialogVisible: false,\n  });\n  const [activeRowId, setActiveRowId] = useState<string>();\n\n  const total = memoizedSearch.total ?? 'accurate';\n\n  const loadResults = useCallback(\n    (options?: RequestInit) => {\n      setOutcome(undefined);\n      medplum\n        .requestSchema(memoizedSearch.resourceType)\n        .then(() =>\n          medplum.search(\n            memoizedSearch.resourceType,\n            formatSearchQuery({ ...memoizedSearch, total, fields: undefined }),\n            options\n          )\n        )\n        .then((response) => {\n          setState((s) => ({ ...s, searchResponse: response }));\n          if (onLoad) {\n            onLoad(new SearchLoadEvent(response));\n          }\n        })\n        .catch((reason) => {\n          setState((s) => ({ ...s, searchResponse: undefined }));\n          setOutcome(normalizeOperationOutcome(reason));\n        });\n    },\n    [medplum, memoizedSearch, total, onLoad]\n  );\n\n  const refreshResults = useCallback(() => {\n    setState((s) => ({ ...s, searchResponse: undefined }));\n    loadResults({ cache: 'reload' });\n  }, [loadResults]);\n\n  useEffect(() => {\n    loadResults();\n  }, [loadResults]);\n\n  /**\n   * Checks or unchecks a row.\n   * @param id - The row's resource ID.\n   * @param checked - The new checked state; toggles the row when omitted.\n   */\n  function setRowSelected(id: string, checked?: boolean): void {\n    setState((s) => {\n      const newSelected = { ...s.selected };\n      if (checked ?? !s.selected[id]) {\n        newSelected[id] = true;\n      } else {\n        delete newSelected[id];\n      }\n      return { ...s, selected: newSelected };\n    });\n  }\n\n  function setAllSelected(checked: boolean): void {\n    setState((s) => {\n      const newSelected = {} as { [id: string]: boolean };\n      if (checked && s.searchResponse?.entry) {\n        s.searchResponse.entry.forEach((entry) => {\n          if (entry.resource?.id) {\n            newSelected[entry.resource.id] = true;\n          }\n        });\n      }\n      return { ...s, selected: newSelected };\n    });\n  }\n\n  function emitSearchChange(newSearch: SearchRequest): void {\n    if (props.onChange) {\n      props.onChange(new SearchChangeEvent(newSearch));\n    }\n  }\n\n  function handleRowClick(e: MouseEvent, resource: Resource): void {\n    if (isCheckboxCell(e.target as Element) || e.button === 2) {\n      return;\n    }\n\n    killEvent(e);\n\n    const isAux = isAuxClick(e);\n\n    if (!isAux && props.onClick) {\n      props.onClick(new SearchClickEvent(resource, e));\n    }\n\n    if (isAux && props.onAuxClick) {\n      props.onAuxClick(new SearchClickEvent(resource, e));\n    }\n  }\n\n  /**\n   * Keyboard support for a focused row: arrows and Home/End move between rows, Enter clicks the row\n   * (Ctrl/Cmd+Enter as an auxiliary click) and Space toggles its checkbox.\n   * @param e - The keydown event.\n   * @param resource - The row's resource.\n   */\n  function handleRowKeyDown(e: KeyboardEvent<HTMLTableRowElement>, resource: Resource): void {\n    if (e.target !== e.currentTarget) {\n      return;\n    }\n    const row = e.currentTarget;\n    let nextRow: Element | null | undefined;\n    if (e.key === 'ArrowDown') {\n      nextRow = row.nextElementSibling;\n    } else if (e.key === 'ArrowUp') {\n      nextRow = row.previousElementSibling;\n    } else if (e.key === 'Home') {\n      nextRow = row.parentElement?.firstElementChild;\n    } else if (e.key === 'End') {\n      nextRow = row.parentElement?.lastElementChild;\n    } else if (e.key === 'Enter') {\n      killEvent(e);\n      row.dispatchEvent(\n        new window.MouseEvent('click', { bubbles: true, cancelable: true, ctrlKey: e.ctrlKey, metaKey: e.metaKey })\n      );\n      return;\n    } else if (e.key === ' ' && checkboxColumn) {\n      killEvent(e);\n      setRowSelected(resource.id as string);\n      return;\n    } else {\n      return;\n    }\n    killEvent(e);\n    (nextRow as HTMLElement | null | undefined)?.focus();\n  }\n\n  async function runDelete(): Promise<void> {\n    const ids = Object.keys(state.selected);\n    setState((s) => ({ ...s, deleting: true }));\n    try {\n      await props.onDelete?.(ids);\n      setState((s) => ({ ...s, selected: {}, deleting: false, deleteConfirmVisible: false }));\n      loadResults({ cache: 'reload' });\n    } catch {\n      setState((s) => ({ ...s, deleting: false }));\n    }\n  }\n\n  function closeDeleteConfirm(): void {\n    setState((s) => ({ ...s, deleteConfirmVisible: false }));\n  }\n\n  if (outcome) {\n    return <OperationOutcomeAlert outcome={outcome} />;\n  }\n\n  if (!isDataTypeLoaded(memoizedSearch.resourceType)) {\n    return (\n      <Center style={{ width: '100%', height: '100%' }}>\n        <Loader />\n      </Center>\n    );\n  }\n\n  const checkboxColumn = props.checkboxesEnabled;\n  const fields = getFieldDefinitions(memoizedSearch);\n  const resourceType = memoizedSearch.resourceType;\n  const lastResult = state.searchResponse;\n  const entries = lastResult?.entry;\n  const resources = entries?.map((e) => e.resource);\n\n  const selectedIds = Object.keys(state.selected);\n  const allSelected = !!entries?.length && entries.every((e) => !e.resource?.id || state.selected[e.resource.id]);\n  const showExport = !!(props.onExport ?? props.onExportCsv ?? props.onExportTransactionBundle);\n  const showDelete = !!props.onDelete;\n  const showBulk = !!props.onBulk;\n\n  const focusableRowId =\n    activeRowId && resources?.some((r) => r?.id === activeRowId) ? activeRowId : resources?.find(Boolean)?.id;\n\n  return (\n    <div className={classes.root} data-testid=\"search-control\">\n      {!props.hideToolbar && (\n        <Group justify=\"space-between\" pb=\"md\" className={classes.toolbar}>\n          <Group gap=\"xs\">\n            <Button\n              className={classes.toolbarButton}\n              size=\"compact-md\"\n              variant=\"subtle\"\n              color=\"gray\"\n              leftSection={<IconColumns size={16} />}\n              onClick={() => setState((s) => ({ ...s, fieldEditorVisible: true, dialogOpenTime: Date.now() }))}\n            >\n              Fields\n            </Button>\n            <SearchFilterPopover search={memoizedSearch} onChange={emitSearchChange} />\n            <SearchSortEditor search={memoizedSearch} onChange={emitSearchChange} />\n            {lastResult && (\n              <Text size=\"xs\" fw={500} c=\"dimmed\" ml={4} data-testid=\"count-display\">\n                {getStart(memoizedSearch, lastResult).toLocaleString()}-\n                {getEnd(memoizedSearch, lastResult).toLocaleString()}\n                {lastResult.total !== undefined &&\n                  ` of ${memoizedSearch.total === 'estimate' ? '~' : ''}${lastResult.total?.toLocaleString()}`}\n              </Text>\n            )}\n          </Group>\n          <Group gap=\"xs\">\n            <Tooltip label=\"Refresh\" position=\"bottom\" openDelay={500}>\n              <ActionIcon\n                className={classes.actionIcon}\n                variant=\"transparent\"\n                color=\"gray\"\n                size={32}\n                radius=\"xl\"\n                aria-label=\"Refresh\"\n                title=\"Refresh\"\n                onClick={refreshResults}\n              >\n                <IconReload size={16} />\n              </ActionIcon>\n            </Tooltip>\n            {(showExport || showBulk || showDelete) && (\n              <Menu shadow=\"md\" width={200} radius=\"md\" position=\"bottom-end\">\n                <Menu.Target>\n                  <ActionIcon\n                    className={classes.actionIcon}\n                    variant=\"transparent\"\n                    color=\"gray\"\n                    size={32}\n                    radius=\"xl\"\n                    aria-label=\"Actions\"\n                  >\n                    <IconDots size={16} />\n                  </ActionIcon>\n                </Menu.Target>\n                <Menu.Dropdown className={classes.menuDropdown}>\n                  {showExport && (\n                    <Menu.Item\n                      leftSection={<IconTableExport size={16} />}\n                      onClick={\n                        props.onExport ??\n                        (() => setState((s) => ({ ...s, exportDialogVisible: true, dialogOpenTime: Date.now() })))\n                      }\n                    >\n                      Export\n                    </Menu.Item>\n                  )}\n                  {showBulk && (\n                    <Menu.Item leftSection={<IconLibraryPlus size={16} />} onClick={() => props.onBulk?.(selectedIds)}>\n                      Bulk Apply\n                    </Menu.Item>\n                  )}\n                  {showDelete && (\n                    <Menu.Item\n                      leftSection={<IconTrash size={16} />}\n                      disabled={selectedIds.length === 0}\n                      onClick={() => setState((s) => ({ ...s, deleteConfirmVisible: true }))}\n                    >\n                      Delete\n                    </Menu.Item>\n                  )}\n                </Menu.Dropdown>\n              </Menu>\n            )}\n            {props.onNew && (\n              <Tooltip label={`New ${resourceType}`} position=\"bottom\" openDelay={500}>\n                <ActionIcon\n                  variant=\"filled\"\n                  color=\"blue\"\n                  size={32}\n                  radius=\"xl\"\n                  aria-label={`New ${resourceType}`}\n                  onClick={props.onNew}\n                >\n                  <IconPlus size={16} />\n                </ActionIcon>\n              </Tooltip>\n            )}\n          </Group>\n        </Group>\n      )}\n      <div className={classes.tableScroll}>\n        <Table className={classes.table}>\n          <Table.Thead>\n            <Table.Tr>\n              {checkboxColumn && (\n                <Table.Th\n                  className={classes.checkboxCell}\n                  data-checkbox-cell\n                  data-testid=\"all-checkbox-cell\"\n                  onClick={(e) => handleCheckboxCellClick(e, () => setAllSelected(!allSelected))}\n                  onAuxClick={(e) => e.stopPropagation()}\n                >\n                  <div className={classes.checkboxWrap}>\n                    <Checkbox\n                      size=\"xs\"\n                      aria-label=\"Select all rows\"\n                      data-testid=\"all-checkbox\"\n                      checked={allSelected}\n                      onChange={(e) => setAllSelected(e.currentTarget.checked)}\n                    />\n                  </div>\n                </Table.Th>\n              )}\n              {fields.map((field) => {\n                const sortCode = field.searchParams?.[0]?.code;\n                const sortRule = sortCode ? memoizedSearch.sortRules?.find((r) => r.code === sortCode) : undefined;\n                return (\n                  <Table.Th key={field.name} aria-sort={sortRule && (sortRule.descending ? 'descending' : 'ascending')}>\n                    {field.searchParams ? (\n                      <Menu shadow=\"md\" radius=\"md\" position=\"bottom-start\">\n                        <Menu.Target>\n                          <UnstyledButton className={classes.control}>\n                            <Group gap={4} wrap=\"nowrap\">\n                              <ColumnTitle>{buildFieldNameString(field.name)}</ColumnTitle>\n                              {sortRule &&\n                                (sortRule.descending ? (\n                                  <IconArrowDown size={12} stroke={2} aria-hidden />\n                                ) : (\n                                  <IconArrowUp size={12} stroke={2} aria-hidden />\n                                ))}\n                            </Group>\n                          </UnstyledButton>\n                        </Menu.Target>\n                        <SearchPopupMenu\n                          search={memoizedSearch}\n                          searchParams={field.searchParams}\n                          onChange={emitSearchChange}\n                          onPrompt={(searchParam, filter) =>\n                            setState((s) => ({\n                              ...s,\n                              filterDialogVisible: true,\n                              filterDialogSearchParam: searchParam,\n                              filterDialogFilter: filter,\n                              dialogOpenTime: Date.now(),\n                            }))\n                          }\n                        />\n                      </Menu>\n                    ) : (\n                      <ColumnTitle className={classes.staticColumnTitle}>\n                        {buildFieldNameString(field.name)}\n                      </ColumnTitle>\n                    )}\n                  </Table.Th>\n                );\n              })}\n              {props.additionalColumns?.map((col) => (\n                <Table.Th key={col.name}>\n                  <ColumnTitle className={classes.staticColumnTitle}>{col.name}</ColumnTitle>\n                </Table.Th>\n              ))}\n            </Table.Tr>\n            {!props.hideFilters && (\n              <Table.Tr>\n                {checkboxColumn && <Table.Th />}\n                {fields.map((field) => (\n                  <Table.Th key={field.name}>\n                    {field.searchParams && (\n                      <FilterDescription\n                        resourceType={resourceType}\n                        searchParams={field.searchParams}\n                        filters={memoizedSearch.filters}\n                      />\n                    )}\n                  </Table.Th>\n                ))}\n                {props.additionalColumns?.map((col) => (\n                  <Table.Th key={col.name} />\n                ))}\n              </Table.Tr>\n            )}\n          </Table.Thead>\n          <Table.Tbody>\n            {resources?.map(\n              (resource) =>\n                resource && (\n                  <Table.Tr\n                    key={resource.id}\n                    className={classes.tr}\n                    data-testid=\"search-control-row\"\n                    tabIndex={resource.id === focusableRowId ? 0 : -1}\n                    onFocus={(e) => {\n                      if (e.target === e.currentTarget) {\n                        setActiveRowId(resource.id);\n                      }\n                    }}\n                    onKeyDown={(e) => handleRowKeyDown(e, resource)}\n                    onClick={(e) => handleRowClick(e, resource)}\n                    onAuxClick={(e) => handleRowClick(e, resource)}\n                  >\n                    {checkboxColumn && (\n                      <Table.Td\n                        className={classes.checkboxCell}\n                        data-checkbox-cell\n                        data-testid=\"row-checkbox-cell\"\n                        onClick={(e) => handleCheckboxCellClick(e, () => setRowSelected(resource.id as string))}\n                        onAuxClick={(e) => e.stopPropagation()}\n                      >\n                        <div className={classes.checkboxWrap}>\n                          <Checkbox\n                            size=\"xs\"\n                            data-testid=\"row-checkbox\"\n                            aria-label={`Checkbox for ${resource.id}`}\n                            checked={!!state.selected[resource.id as string]}\n                            onChange={(e) => setRowSelected(resource.id as string, e.currentTarget.checked)}\n                          />\n                        </div>\n                      </Table.Td>\n                    )}\n                    {fields.map((field) => (\n                      <Table.Td key={field.name}>{renderValue(resource, field)}</Table.Td>\n                    ))}\n                    {props.additionalColumns?.map((col) => (\n                      <Table.Td key={col.name}>{col.renderCell(resource)}</Table.Td>\n                    ))}\n                  </Table.Tr>\n                )\n            )}\n          </Table.Tbody>\n        </Table>\n      </div>\n      {!resources?.length && (\n        <Container>\n          <Center style={{ height: 150 }}>\n            <Text className={classes.mutedText} size=\"xl\">\n              No results\n            </Text>\n          </Center>\n        </Container>\n      )}\n      {lastResult && (\n        <Center m={0} p=\"md\" pb={0}>\n          <Pagination\n            value={getPage(memoizedSearch)}\n            total={getTotalPages(memoizedSearch, lastResult)}\n            onChange={(newPage) => emitSearchChange(setPage(memoizedSearch, newPage))}\n            getControlProps={getPaginationControlProps}\n          />\n        </Center>\n      )}\n      <SearchFieldEditor\n        key={`search-field-editor-${state.dialogOpenTime}`}\n        search={memoizedSearch}\n        visible={state.fieldEditorVisible}\n        onOk={(result) => {\n          emitSearchChange(result);\n          setState((s) => ({ ...s, fieldEditorVisible: false }));\n        }}\n        onCancel={() => setState((s) => ({ ...s, fieldEditorVisible: false }))}\n      />\n      <SearchExportDialog\n        key={`search-export-dialog-${state.dialogOpenTime}`}\n        visible={state.exportDialogVisible}\n        exportCsv={props.onExportCsv}\n        exportTransactionBundle={props.onExportTransactionBundle}\n        onCancel={() => {\n          setState((s) => ({ ...s, exportDialogVisible: false }));\n        }}\n      />\n      <SearchFilterValueDialog\n        key={`search-filter-dialog-${state.dialogOpenTime}`}\n        visible={state.filterDialogVisible}\n        title={state.filterDialogSearchParam?.code ? buildFieldNameString(state.filterDialogSearchParam.code) : ''}\n        resourceType={resourceType}\n        searchParam={state.filterDialogSearchParam}\n        filter={state.filterDialogFilter}\n        defaultValue=\"\"\n        onOk={(filter) => {\n          emitSearchChange(addFilter(memoizedSearch, filter.code, filter.operator, filter.value));\n          setState((s) => ({ ...s, filterDialogVisible: false }));\n        }}\n        onCancel={() => setState((s) => ({ ...s, filterDialogVisible: false }))}\n      />\n      <Modal\n        opened={!!state.deleteConfirmVisible}\n        onClose={state.deleting ? () => undefined : closeDeleteConfirm}\n        title={`Delete selected ${buildFieldNameString(resourceType)} resources?`}\n        actions={\n          <>\n            <Button color=\"red\" w=\"100%\" loading={!!state.deleting} onClick={runDelete}>\n              Delete\n            </Button>\n            <Button variant=\"outline\" w=\"100%\" disabled={!!state.deleting} onClick={closeDeleteConfirm}>\n              Cancel\n            </Button>\n          </>\n        }\n      >\n        <Text>This action cannot be undone.</Text>\n      </Modal>\n    </div>\n  );\n}\n\nfunction ColumnTitle(props: { readonly children: ReactNode; readonly className?: string }): JSX.Element {\n  return (\n    <Text className={`${classes.mutedText} ${props.className ?? ''}`} size=\"xs\" fw={500} lh=\"sm\">\n      {props.children}\n    </Text>\n  );\n}\n\ninterface FilterDescriptionProps {\n  readonly resourceType: string;\n  readonly searchParams: SearchParameter[];\n  readonly filters?: Filter[];\n}\n\nfunction FilterDescription(props: FilterDescriptionProps): JSX.Element {\n  const filters = (props.filters ?? []).filter((f) => props.searchParams.find((p) => p.code === f.code));\n  if (filters.length === 0) {\n    return (\n      <Text className={classes.mutedText} size=\"xs\" lh=\"sm\">\n        no filters\n      </Text>\n    );\n  }\n\n  return (\n    <>\n      {filters.map((filter: Filter) => (\n        <Text key={`filter-${filter.code}-${filter.operator}-${filter.value}`} size=\"xs\" lh=\"sm\">\n          {getOpString(filter.operator)}\n          &nbsp;\n          <SearchFilterValueDisplay resourceType={props.resourceType} filter={filter} />\n        </Text>\n      ))}\n    </>\n  );\n}\n\n/**\n * Makes the whole checkbox cell a hit target; clicks on the input itself are left to its own handler.\n * @param e - The click event on the cell.\n * @param toggle - Toggles the cell's checkbox.\n */\nfunction handleCheckboxCellClick(e: MouseEvent, toggle: () => void): void {\n  e.stopPropagation();\n  if ((e.target as Element).closest('input, label')) {\n    return;\n  }\n  toggle();\n}\n\nfunction getPage(search: SearchRequest): number {\n  return Math.floor((search.offset ?? 0) / (search.count ?? DEFAULT_SEARCH_COUNT)) + 1;\n}\n\nfunction getTotalPages(search: SearchRequest, lastResult: Bundle): number {\n  const pageSize = search.count ?? DEFAULT_SEARCH_COUNT;\n  const total = getTotal(search, lastResult);\n  return Math.ceil(total / pageSize);\n}\n\nfunction getStart(search: SearchRequest, lastResult: Bundle): number {\n  return Math.min(getTotal(search, lastResult), (search.offset ?? 0) + 1);\n}\n\nfunction getEnd(search: SearchRequest, lastResult: Bundle): number {\n  return Math.max(getStart(search, lastResult) + (lastResult.entry?.length ?? 0) - 1, 0);\n}\n\nfunction getTotal(search: SearchRequest, lastResult: Bundle): number {\n  let total = lastResult.total;\n  if (total === undefined) {\n    // If the total is not specified, then we have to estimate it\n    total =\n      (search.offset ?? 0) +\n      (lastResult.entry?.length ?? 0) +\n      (lastResult.link?.some((l) => l.relation === 'next') ? 1 : 0);\n  }\n  return total;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Text } from '@mantine/core';\nimport type { JSX } from 'react';\nimport { Modal } from '../Modal/Modal';\n\ninterface SearchExportDialogProps {\n  readonly visible: boolean;\n  readonly exportCsv?: () => void;\n  readonly exportTransactionBundle?: () => void;\n  readonly onCancel: () => void;\n}\n\nexport function SearchExportDialog(props: SearchExportDialogProps): JSX.Element | null {\n  // Left undefined when neither format is offered, so the modal renders no footer and no\n  // footer border rather than an empty bordered strip.\n  const actions =\n    props.exportCsv || props.exportTransactionBundle ? (\n      <>\n        {props.exportCsv && <ExportButton text=\"CSV\" exportLogic={props.exportCsv} onCancel={props.onCancel} />}\n        {props.exportTransactionBundle && (\n          <ExportButton\n            text=\"Transaction Bundle\"\n            exportLogic={props.exportTransactionBundle}\n            onCancel={props.onCancel}\n          />\n        )}\n      </>\n    ) : undefined;\n\n  return (\n    <Modal title=\"Export\" opened={props.visible} onClose={props.onCancel} actions={actions}>\n      <Text>Limited to 1000 records</Text>\n    </Modal>\n  );\n}\n\ninterface ExportButtonProps {\n  readonly text: string;\n  readonly exportLogic: () => void;\n  readonly onCancel: () => void;\n}\n\nexport function ExportButton(props: ExportButtonProps): JSX.Element {\n  return (\n    <Button\n      onClick={() => {\n        props.exportLogic();\n        props.onCancel();\n      }}\n    >\n      {`Export as ${props.text}`}\n    </Button>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Group, MultiSelect } from '@mantine/core';\nimport type { InternalTypeSchema, SearchRequest } from '@medplum/core';\nimport { getDataType, getSearchParameters, sortStringArray, stringify } from '@medplum/core';\nimport type { SearchParameter } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { Modal } from '../Modal/Modal';\nimport { buildFieldNameString } from '../SearchControl/SearchUtils';\n\nexport interface SearchFieldEditorProps {\n  readonly visible: boolean;\n  readonly search: SearchRequest;\n  readonly onOk: (search: SearchRequest) => void;\n  readonly onCancel: () => void;\n}\n\nexport function SearchFieldEditor(props: SearchFieldEditorProps): JSX.Element | null {\n  const wasDropdownOpen = useRef(false);\n  const [state, setState] = useState({\n    search: JSON.parse(stringify(props.search)) as SearchRequest,\n  });\n\n  const [isDropdownOpen, setIsDropdownOpen] = useState(false);\n\n  useEffect(() => {\n    setState({ search: props.search });\n  }, [props.search]);\n\n  const allFields = useMemo(() => {\n    if (!props.visible) {\n      return [];\n    }\n\n    const resourceType = props.search.resourceType;\n    const typeSchema = getDataType(resourceType);\n    const searchParams = getSearchParameters(resourceType);\n    return sortStringArray(getFieldsList(typeSchema, searchParams)).map((field) => {\n      return { value: field, label: buildFieldNameString(field) };\n    });\n  }, [props.visible, props.search.resourceType]);\n\n  function handleChange(newFields: string[]): void {\n    setState({ search: { ...state.search, fields: newFields } });\n  }\n\n  return (\n    <Modal\n      title=\"Fields\"\n      opened={props.visible}\n      onClose={() => {\n        props.onCancel();\n      }}\n      size=\"auto\"\n      /*\n      By default, the MultiSelect dropdown does not interact well with Modal's closeOnClickOutside:\n      When the MultiSelect's dropdown is opened and the user clicks outside of the dropdown to close it\n      (and outside the modal, i.e. clicks on the Modal's overlay), the Modal is undesirably also closed\n      from the same click.\n\n      Due to the sequencing of the events fired during a click on the overlay and when React\n      rerenders of various components occur, it is not possible to simply do something such as setting\n      closeOnClickOutside={!isDropdownOpened}:\n\n      * user begins a click on the overlay which triggers\n      * mousedown event on the overlay which triggers\n      * blur event on the MultiSelect's input element which invokes\n      * the MultiSelect.onDropdownClose callback which calls setIsDropdownOpen(false) which causes\n      * rerender of SearchFieldEditor with isDropdownOpen set to false\n      * the user ends the click which triggers\n      * click event on the Modal which activates the closeOnClickOutside logic\n      * since isDropdownOpen is false, closeOnClickOutside is true, so the Modal closes\n\n      Instead, emulate closeOnClickOutside's behavior only when the MultiSelect dropdown\n      was not open at the beginning of the click\n      */\n      withOverlay\n      closeOnClickOutside={false}\n      overlayProps={{\n        onMouseDownCapture: () => {\n          // capture whether the MultiSelect dropdown is open when a click on the overlay begins (i.e. mousedown)\n          wasDropdownOpen.current = isDropdownOpen;\n        },\n        onClick: () => {\n          if (!wasDropdownOpen.current) {\n            // invoke onCancel callback since the dropdown wasn't open at the start of the click on the overlay\n            props.onCancel();\n          }\n\n          // not strictly needed since onMouseDownCapture should always precede onClick, but reset the ref\n          wasDropdownOpen.current = false;\n        },\n        children: <div data-testid=\"overlay-child\" />, // can't specify testid on the overlay itself\n      }}\n      actions={\n        <Group justify=\"flex-end\">\n          <Button onClick={() => props.onOk(state.search)}>OK</Button>\n        </Group>\n      }\n    >\n      <MultiSelect\n        // withinPortal={true}\n        style={{ width: 550 }}\n        placeholder=\"Select fields to display\"\n        data={allFields}\n        value={state.search.fields ?? []}\n        onChange={handleChange}\n        onDropdownOpen={() => setIsDropdownOpen(true)}\n        onDropdownClose={() => setIsDropdownOpen(false)}\n        /* shows at most ~6.5 items; the extra half to provide a hint that there are more entries to scroll through */\n        maxDropdownHeight=\"250px\"\n        // dropdownPosition=\"bottom\"\n        clearButtonProps={{ 'aria-label': 'Clear selection' }}\n        clearable\n        searchable\n      />\n    </Modal>\n  );\n}\n\n/**\n * Returns a list of fields/columns available for a type.\n * The result is the union of properties and search parameters.\n * @param typeSchema - The type definition.\n * @param searchParams - The search parameters.\n * @returns A list of fields/columns available for a resource type.\n */\nfunction getFieldsList(\n  typeSchema: InternalTypeSchema,\n  searchParams: Record<string, SearchParameter> | undefined\n): string[] {\n  const result = [] as string[];\n  const keys = new Set<string>();\n  const names = new Set<string>();\n\n  // Add properties first\n  for (const key of Object.keys(typeSchema.elements)) {\n    result.push(key);\n    keys.add(key.toLowerCase());\n    names.add(buildFieldNameString(key));\n  }\n\n  // Add search parameters if unique\n  if (searchParams) {\n    for (const code of Object.keys(searchParams)) {\n      const name = buildFieldNameString(code);\n      if (!keys.has(code) && !names.has(name)) {\n        result.push(code);\n        keys.add(code);\n        names.add(name);\n      }\n    }\n  }\n\n  return result;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ComboboxData, ComboboxItem } from '@mantine/core';\nimport { Group, Text } from '@mantine/core';\nimport type { Filter, InternalSchemaElement, SearchRequest, SortRule } from '@medplum/core';\nimport {\n  capitalize,\n  DEFAULT_SEARCH_COUNT,\n  evalFhirPathTyped,\n  formatDateTime,\n  getDisplayString,\n  isProfileResource,\n  Operator,\n  PropertyType,\n} from '@medplum/core';\nimport type { Reference, Resource, SearchParameter } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport classes from './SearchControl.module.css';\nimport type { SearchControlField } from './SearchControlField';\n\ntype SearchParamType = SearchParameter['type'] | 'fulltext' | 'datetime';\n\nconst searchParamToOperators: Partial<Record<SearchParamType, Operator[]>> = {\n  string: [Operator.EQUALS, Operator.NOT, Operator.CONTAINS, Operator.EXACT],\n  fulltext: [Operator.EQUALS, Operator.NOT, Operator.CONTAINS, Operator.EXACT],\n  token: [Operator.EQUALS, Operator.NOT, Operator.TEXT],\n  reference: [Operator.EQUALS, Operator.NOT],\n  number: [\n    Operator.EQUALS,\n    Operator.NOT_EQUALS,\n    Operator.GREATER_THAN,\n    Operator.LESS_THAN,\n    Operator.GREATER_THAN_OR_EQUALS,\n    Operator.LESS_THAN_OR_EQUALS,\n  ],\n  quantity: [\n    Operator.EQUALS,\n    Operator.NOT_EQUALS,\n    Operator.GREATER_THAN,\n    Operator.LESS_THAN,\n    Operator.GREATER_THAN_OR_EQUALS,\n    Operator.LESS_THAN_OR_EQUALS,\n  ],\n  date: [\n    Operator.EQUALS,\n    Operator.NOT_EQUALS,\n    Operator.GREATER_THAN,\n    Operator.LESS_THAN,\n    Operator.GREATER_THAN_OR_EQUALS,\n    Operator.LESS_THAN_OR_EQUALS,\n    Operator.STARTS_AFTER,\n    Operator.ENDS_BEFORE,\n    Operator.APPROXIMATELY,\n  ],\n  datetime: [\n    Operator.EQUALS,\n    Operator.NOT_EQUALS,\n    Operator.GREATER_THAN,\n    Operator.LESS_THAN,\n    Operator.GREATER_THAN_OR_EQUALS,\n    Operator.LESS_THAN_OR_EQUALS,\n    Operator.STARTS_AFTER,\n    Operator.ENDS_BEFORE,\n    Operator.APPROXIMATELY,\n  ],\n  uri: [Operator.EQUALS, Operator.NOT, Operator.ABOVE, Operator.BELOW],\n};\n\nconst operatorNames: Record<Operator, string> = {\n  eq: 'equals',\n  ne: 'not equals',\n  gt: 'greater than',\n  lt: 'less than',\n  ge: 'greater than or equals',\n  le: 'less than or equals',\n  sa: 'starts after',\n  eb: 'ends before',\n  ap: 'approximately',\n  sw: 'starts with',\n  contains: 'contains',\n  exact: 'exact',\n  text: 'text',\n  not: 'not',\n  above: 'above',\n  below: 'below',\n  in: 'in',\n  'not-in': 'not in',\n  'of-type': 'of type',\n  missing: 'missing',\n  present: 'present',\n  identifier: 'identifier',\n  iterate: 'iterate',\n};\n\n/**\n * Sets the array of filters.\n * @param definition - The original search request.\n * @param filters - The new filters.\n * @returns The updated search request.\n */\nexport function setFilters(definition: SearchRequest, filters: Filter[]): SearchRequest {\n  return {\n    ...definition,\n    filters: filters,\n    offset: 0,\n    name: undefined,\n  };\n}\n\n/**\n * Clears all of the filters.\n * @param definition - The original search request.\n * @returns The updated search request.\n */\nexport function clearFilters(definition: SearchRequest): SearchRequest {\n  return setFilters(definition, []);\n}\n\n/**\n * Clears all of the filters on a certain field.\n * @param definition - The original search request.\n * @param code - The field key name to clear filters.\n * @returns The updated search request.\n */\nexport function clearFiltersOnField(definition: SearchRequest, code: string): SearchRequest {\n  return setFilters(\n    definition,\n    (definition.filters ?? []).filter((f) => f.code !== code)\n  );\n}\n\n/**\n * Adds a filter.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param op - The operation key name.\n * @param value - The filter value.\n * @param opt_clear - Optional flag to clear filters on the field.\n * @returns The updated search request.\n */\nexport function addFilter(\n  definition: SearchRequest,\n  field: string,\n  op: Operator,\n  value?: string,\n  opt_clear?: boolean\n): SearchRequest {\n  if (opt_clear) {\n    definition = clearFiltersOnField(definition, field);\n  }\n\n  const nextFilters: Filter[] = [];\n  if (definition.filters) {\n    nextFilters.push(...definition.filters);\n  }\n  nextFilters.push({ code: field, operator: op, value: value ?? '' });\n\n  return setFilters(definition, nextFilters);\n}\n\n/**\n * Adds a field.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addField(definition: SearchRequest, field: string): SearchRequest {\n  if (definition.fields?.includes(field)) {\n    return definition;\n  }\n  const newFields = [];\n  if (definition.fields) {\n    newFields.push(...definition.fields);\n  }\n  newFields.push(field);\n  return {\n    ...definition,\n    fields: newFields,\n    name: undefined,\n  };\n}\n\n/**\n * Deletes a filter at the specified index.\n * @param definition - The original search request.\n * @param index - The filter index.\n * @returns The updated search request.\n */\nexport function deleteFilter(definition: SearchRequest, index: number): SearchRequest {\n  if (!definition.filters) {\n    return definition;\n  }\n  const newFilters = [...definition.filters];\n  newFilters.splice(index, 1);\n  return {\n    ...definition,\n    filters: newFilters,\n    name: undefined,\n  };\n}\n\n/**\n * Adds a filter that constrains the specified field to \"yesterday\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addYesterdayFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addDayFilter(definition, field, -1);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"today\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addTodayFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addDayFilter(definition, field, 0);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"tomorrow\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addTomorrowFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addDayFilter(definition, field, 1);\n}\n\n/**\n * Adds a filter that constrains the specified field to a day.\n * The day is specified as a delta from the current day.\n * \"Today\" would be 0.\n * \"Yesterday\" would be -1.\n * \"Tomorrow\" would be 1.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param delta - The number of days from this day.\n * @returns The updated search request.\n */\nfunction addDayFilter(definition: SearchRequest, field: string, delta: number): SearchRequest {\n  const startTime = new Date();\n  startTime.setDate(startTime.getDate() + delta);\n  startTime.setHours(0, 0, 0, 0);\n\n  const endTime = new Date(startTime.getTime());\n  endTime.setDate(endTime.getDate() + 1);\n  endTime.setTime(endTime.getTime() - 1);\n\n  return addDateFilterBetween(definition, field, startTime, endTime);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"next 24 hours\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addNext24HoursFilter(definition: SearchRequest, field: string): SearchRequest {\n  const now = new Date();\n  const endTime = new Date(now.getTime() + 24 * 60 * 60 * 1000);\n  return addDateFilterBetween(definition, field, now, endTime);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"last month\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addLastMonthFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addMonthFilter(definition, field, -1);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"this month\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addThisMonthFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addMonthFilter(definition, field, 0);\n}\n\n/**\n * Adds a filter that constrains the specified field to \"next month\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addNextMonthFilter(definition: SearchRequest, field: string): SearchRequest {\n  return addMonthFilter(definition, field, 1);\n}\n\n/**\n * Adds a filter that constrains the specified field to a month.\n * The month is specified as a delta from the current month.\n * \"This month\" would be 0.\n * \"Last month\" would be -1.\n * \"Next month\" would be 1.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param delta - The number of months from this month.\n * @returns The updated search request.\n */\nfunction addMonthFilter(definition: SearchRequest, field: string, delta: number): SearchRequest {\n  const startTime = new Date();\n  startTime.setMonth(startTime.getMonth() + delta);\n  startTime.setDate(1);\n  startTime.setHours(0, 0, 0, 0);\n\n  const endTime = new Date(startTime.getTime());\n  endTime.setMonth(endTime.getMonth() + 1);\n  endTime.setDate(1);\n  endTime.setHours(0, 0, 0, 0);\n  endTime.setTime(endTime.getTime() - 1);\n\n  return addDateFilterBetween(definition, field, startTime, endTime);\n}\n\n/**\n * Adds a filter that constrains the specified field to the year to date.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @returns The updated search request.\n */\nexport function addYearToDateFilter(definition: SearchRequest, field: string): SearchRequest {\n  const startTime = new Date();\n  startTime.setMonth(0);\n  startTime.setDate(1);\n  startTime.setHours(0, 0, 0, 0);\n\n  const endTime = new Date();\n\n  return addDateFilterBetween(definition, field, startTime, endTime);\n}\n\n/**\n * Adds a filter for a date between two dates (inclusive of both dates).\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param d1 - The start date.\n * @param d2 - The end date.\n * @returns The updated search request.\n */\nexport function addDateFilterBetween(definition: SearchRequest, field: string, d1: Date, d2: Date): SearchRequest {\n  definition = clearFiltersOnField(definition, field);\n  definition = addDateFilterImpl(definition, field, Operator.GREATER_THAN_OR_EQUALS, d1);\n  definition = addDateFilterImpl(definition, field, Operator.LESS_THAN_OR_EQUALS, d2);\n  return definition;\n}\n\n/**\n * Adds a filter for a date before a certain date/time.\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param op - The date/time operation.\n * @param value - The date.\n * @returns The updated search request.\n */\nfunction addDateFilterImpl(definition: SearchRequest, field: string, op: Operator, value: Date): SearchRequest {\n  return addFilter(definition, field, op, value.toISOString());\n}\n\n/**\n * Adds a filter that constrains the specified field to \"missing\".\n * @param definition - The original search request.\n * @param field - The field key name.\n * @param value - Optional boolean value. Default is true.\n * @returns The updated search request.\n */\nexport function addMissingFilter(definition: SearchRequest, field: string, value = true): SearchRequest {\n  return addFilter(definition, field, Operator.MISSING, value.toString());\n}\n\n/**\n * Sets the offset (starting at zero).\n * @param definition - The original search request.\n * @param offset - The offset number.\n * @returns The updated search request.\n */\nexport function setOffset(definition: SearchRequest, offset: number): SearchRequest {\n  if (definition.offset === offset) {\n    return definition;\n  }\n  return {\n    ...definition,\n    offset,\n    name: undefined,\n  };\n}\n\n/**\n * Creates a new search request with the search offset at the specified page.\n * @param definition - The search definition.\n * @param page - The new page number\n * @returns The new search definition.\n */\nexport function setPage(definition: SearchRequest, page: number): SearchRequest {\n  const count = definition.count ?? DEFAULT_SEARCH_COUNT;\n  const newOffset = (page - 1) * count;\n  return setOffset(definition, newOffset);\n}\n\n/**\n * Sorts the search by the specified key, and optional direction.\n * Direction defaults to ascending ('asc') if not specified.\n * @param definition - The original search request.\n * @param sort - The sort key.\n * @param desc - Optional descending flag. Default is false.\n * @returns The updated search request.\n */\nexport function setSort(definition: SearchRequest, sort: string, desc?: boolean): SearchRequest {\n  if (sort === getSortField(definition) && desc !== undefined && desc === isSortDescending(definition)) {\n    return definition;\n  }\n  return {\n    ...definition,\n    sortRules: [\n      {\n        code: sort,\n        descending: !!desc,\n      },\n    ],\n    name: undefined,\n  };\n}\n\n/**\n * Toggles the sort of the search by key.\n * If the search is already sorted by the key, reverses the direction.\n * If the search is not sorted by the key, sort in ascending order.\n * @param definition - The original search request.\n * @param key - The field key name.\n * @returns The updated search request.\n */\nexport function toggleSort(definition: SearchRequest, key: string): SearchRequest {\n  let desc = false;\n  if (getSortField(definition) === key) {\n    desc = !isSortDescending(definition);\n  }\n  return setSort(definition, key, desc);\n}\n\n/** The sort {@link SearchControl} applies when a search has no sort rules: Last Updated, newest first. */\nexport const DEFAULT_SORT_RULES: readonly SortRule[] = [{ code: '_lastUpdated', descending: true }];\n\n/**\n * Returns true when two lists of sort rules sort the same way. A missing `descending` counts as ascending.\n * @param a - The first sort rules.\n * @param b - The second sort rules.\n * @returns True if both lists have the same codes and directions in the same order.\n */\nexport function isSameSort(a: readonly SortRule[], b: readonly SortRule[]): boolean {\n  return (\n    a.length === b.length && a.every((rule, i) => rule.code === b[i].code && !!rule.descending === !!b[i].descending)\n  );\n}\n\nexport function getSortField(definition: SearchRequest): string | undefined {\n  const sortRules = definition.sortRules;\n  if (!sortRules || sortRules.length === 0) {\n    return undefined;\n  }\n  const field = sortRules[0].code;\n  return field.startsWith('-') ? field.substr(1) : field;\n}\n\nexport function isSortDescending(definition: SearchRequest): boolean {\n  const sortRules = definition.sortRules;\n  if (!sortRules || sortRules.length === 0) {\n    return false;\n  }\n  return !!sortRules[0].descending;\n}\n\n/**\n * Returns a list of operators for a search parameter.\n * @param searchParam - The search parameter.\n * @returns The list of operators that can be used for the search parameter.\n */\nexport function getSearchOperators(searchParam: SearchParameter): Operator[] | undefined {\n  return searchParamToOperators[searchParam.type];\n}\n\n/**\n * Returns a string representing the operation.\n * @param op - The operation code.\n * @returns A display string for the operation.\n */\nexport function getOpString(op: Operator): string {\n  return operatorNames[op] ?? '';\n}\n\n/**\n * Returns a field display name.\n * @param key - The field key.\n * @returns The field display name.\n */\nexport function buildFieldNameString(key: string): string {\n  let tmp = key;\n\n  // If dot separated, only the last part\n  if (tmp.includes('.')) {\n    tmp = tmp.split('.').pop() as string;\n  }\n\n  // Special case for Version ID\n  if (tmp === 'versionId') {\n    return 'Version ID';\n  }\n\n  // Remove choice of type\n  tmp = tmp.replace('[x]', '');\n\n  // Convert camel case to space separated\n  tmp = tmp.replaceAll(/([A-Z])/g, ' $1');\n\n  // Convert dashes and underscores to spaces\n  tmp = tmp.replaceAll(/[-_]/g, ' ');\n\n  // Normalize whitespace to single space character\n  tmp = tmp.replaceAll(/\\s+/g, ' ');\n\n  // Trim\n  tmp = tmp.trim();\n\n  // Special case for ID\n  if (tmp.toLowerCase() === 'id') {\n    return 'ID';\n  }\n\n  // Capitalize the first letter of each word\n  return tmp.split(/\\s/).map(capitalize).join(' ');\n}\n\n/**\n * Returns true if the given search parameter code refers to a resource metadata field.\n * @param code - The search parameter code.\n * @returns True if the code is a meta search parameter.\n */\nexport function isMetaSearchParam(code: string): boolean {\n  return code.startsWith('_');\n}\n\n/**\n * Returns a display label for a search parameter code. Metadata codes keep their\n * underscore-prefixed code so they never share a label with a same-named element\n * (e.g. `ProjectMembership.project` vs `_project`).\n * @param code - The search parameter code.\n * @returns The display label for the search parameter.\n */\nexport function buildSearchParamFieldLabel(code: string): string {\n  return isMetaSearchParam(code) ? code : buildFieldNameString(code);\n}\n\n/**\n * Splits search parameter codes into resource fields and `_`-prefixed metadata, each sorted by label.\n * @param codes - The search parameter codes.\n * @returns The field and metadata codes.\n */\nexport function partitionSearchParams(codes: string[]): { fields: string[]; metadata: string[] } {\n  const byLabel = (a: string, b: string): number =>\n    buildSearchParamFieldLabel(a).localeCompare(buildSearchParamFieldLabel(b));\n  return {\n    fields: codes.filter((code) => !isMetaSearchParam(code)).sort(byLabel),\n    metadata: codes.filter((code) => isMetaSearchParam(code)).sort(byLabel),\n  };\n}\n\n/**\n * Builds grouped Select options (Fields, then Metadata) for choosing a search parameter.\n * @param searchParams - The resource type's search parameters, keyed by code.\n * @returns The grouped Select data.\n */\nexport function getSearchParamSelectData(searchParams: Record<string, SearchParameter>): ComboboxData {\n  const { fields, metadata } = partitionSearchParams(Object.keys(searchParams));\n  const toItems = (codes: string[]): ComboboxItem[] =>\n    codes.map((code) => ({ value: code, label: buildSearchParamFieldLabel(code) }));\n  return [\n    ...(fields.length > 0 ? [{ group: 'Fields', items: toItems(fields) }] : []),\n    ...(metadata.length > 0 ? [{ group: 'Metadata', items: toItems(metadata) }] : []),\n  ];\n}\n\n/**\n * Sort direction labels by search parameter type: dates oldest/newest, numbers smallest/largest, else A/Z.\n * @param type - The search parameter type.\n * @returns The ascending and descending labels.\n */\nexport function getSortDirectionLabels(type: string | undefined): { asc: string; desc: string } {\n  switch (type) {\n    case 'date':\n      return { asc: 'Oldest to Newest', desc: 'Newest to Oldest' };\n    case 'number':\n    case 'quantity':\n      return { asc: 'Smallest to Largest', desc: 'Largest to Smallest' };\n    default:\n      return { asc: 'A to Z', desc: 'Z to A' };\n  }\n}\n\n/**\n * Returns a fragment to be displayed in the search table for the value.\n * @param resource - The parent resource.\n * @param field - The search code or FHIRPath expression.\n * @returns The fragment to display.\n */\nexport function renderValue(resource: Resource, field: SearchControlField): string | JSX.Element | null | undefined {\n  const key = field.name;\n  if (key === 'id') {\n    return <MedplumLink to={`/${resource.resourceType}/${resource.id}`}>{resource.id}</MedplumLink>;\n  }\n\n  if (key === 'meta.versionId') {\n    return resource.meta?.versionId;\n  }\n\n  if (key === '_lastUpdated') {\n    return formatDateTime(resource.meta?.lastUpdated);\n  }\n\n  if (key === 'name' && isProfileResource(resource)) {\n    return renderNameWithAvatar(resource);\n  }\n\n  // Priority 1: InternalSchemaElement by exact match\n  if (`${resource.resourceType}.${field.name}` === field.elementDefinition?.path) {\n    return renderPropertyValue(resource, field.elementDefinition);\n  }\n\n  // Priority 2: SearchParameter by exact match\n  if (field.searchParams?.length === 1 && field.name === field.searchParams[0].code) {\n    return renderSearchParameterValue(resource, field.searchParams[0]);\n  }\n\n  // We don't know how to render this field definition\n  return null;\n}\n\n/**\n * Renders a person-like resource's name column as its avatar next to its display name.\n * @param resource - The Patient, Practitioner or RelatedPerson.\n * @returns The avatar + name element.\n */\nfunction renderNameWithAvatar(resource: Resource): JSX.Element {\n  return (\n    <Group gap=\"xs\" wrap=\"nowrap\">\n      <ResourceAvatar value={resource} radius=\"xl\" size={28} />\n      <Text size=\"sm\" truncate>\n        {getDisplayString(resource)}\n      </Text>\n    </Group>\n  );\n}\n\n/**\n * Renders references as an avatar/name link and `status` fields as a colored badge.\n * @param propertyType - The FHIR property type of the value.\n * @param value - The value to render.\n * @param code - The field's element name or search parameter code (used to detect status fields).\n * @returns A rich display element, or undefined to fall back to {@link ResourcePropertyDisplay}.\n */\nfunction renderRichValue(propertyType: string, value: unknown, code: string): JSX.Element | undefined {\n  if (propertyType === PropertyType.Reference && !Array.isArray(value)) {\n    return <ReferenceAvatarLink value={value as Reference} />;\n  }\n  if (code === 'status' && typeof value === 'string') {\n    return (\n      <StatusBadge\n        status={value}\n        variant=\"light\"\n        classNames={{ root: classes.statusBadge, label: classes.statusBadgeLabel }}\n      />\n    );\n  }\n  return undefined;\n}\n\nfunction ReferenceAvatarLink({ value }: { readonly value: Reference }): JSX.Element {\n  const name = value.display || <ResourceName value={value} />;\n  return (\n    <Group gap=\"xs\" wrap=\"nowrap\">\n      <ResourceAvatar value={value} radius=\"xl\" size={28} />\n      {value.reference ? (\n        <MedplumLink to={value} size=\"sm\" className={classes.nameLink}>\n          {name}\n        </MedplumLink>\n      ) : (\n        <Text size=\"sm\">{name}</Text>\n      )}\n    </Group>\n  );\n}\n\n/**\n * Returns a fragment to be displayed in the search table for a resource property.\n * @param resource - The parent resource.\n * @param elementDefinition - The property element definition.\n * @returns A React element or null.\n */\nfunction renderPropertyValue(resource: Resource, elementDefinition: InternalSchemaElement): JSX.Element | null {\n  const path = elementDefinition.path?.split('.')?.pop()?.replaceAll('[x]', '') ?? '';\n  const [value, propertyType] = getValueAndType({ type: resource.resourceType, value: resource }, path);\n  if (!value) {\n    return null;\n  }\n\n  return (\n    renderRichValue(propertyType, value, path) ?? (\n      <ResourcePropertyDisplay\n        path={elementDefinition.path}\n        property={elementDefinition}\n        propertyType={propertyType}\n        value={value}\n        maxWidth={200}\n        ignoreMissingValues={true}\n        link={false}\n      />\n    )\n  );\n}\n\n/**\n * Returns a fragment to be displayed in the search table for a search parameter.\n * @param resource - The parent resource.\n * @param searchParam - The search parameter.\n * @returns A React element or null.\n */\nfunction renderSearchParameterValue(resource: Resource, searchParam: SearchParameter): JSX.Element | null {\n  const value = evalFhirPathTyped(searchParam.expression as string, [{ type: resource.resourceType, value: resource }]);\n  if (!value || value.length === 0) {\n    return null;\n  }\n\n  return (\n    <>\n      {value.map((v, index) => {\n        const key = `${index}-${value.length}`;\n        const rich = renderRichValue(v.type, v.value, searchParam.code);\n        if (rich) {\n          return <span key={key}>{rich}</span>;\n        }\n        return (\n          <ResourcePropertyDisplay\n            key={key}\n            propertyType={v.type}\n            value={v.value}\n            maxWidth={200}\n            ignoreMissingValues={true}\n            link={false}\n          />\n        );\n      })}\n    </>\n  );\n}\n", ".root {\n  max-width: 100%;\n  overflow: hidden;\n  text-align: left;\n}\n\n.tableScroll {\n  overflow-x: auto;\n}\n\n.table {\n  cursor: pointer;\n  --table-border-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n.table tbody tr:last-of-type > td,\n.table tbody tr:last-of-type > th {\n  border-bottom: 1px solid var(--table-border-color);\n}\n\n.table thead th {\n  padding-top: 8px;\n  padding-bottom: 8px;\n}\n\n.table tbody td {\n  height: 43px;\n}\n\n.toolbar {\n  border-bottom: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n.actionIcon {\n  border: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));\n  transition: border-color 150ms ease;\n}\n\n.actionIcon:hover,\n.actionIcon[data-opened],\n.actionIcon[data-expanded],\n.toolbarButton:hover,\n.toolbarButton[data-opened] {\n  border-color: light-dark(var(--mantine-color-gray-5), var(--mantine-color-dark-2));\n}\n\n.toolbar :global(.mantine-ActionIcon-root):active,\n.toolbarButton:active {\n  transform: none !important;\n}\n\n.menuDropdown :global(.mantine-Menu-item) {\n  border-radius: var(--mantine-radius-sm);\n}\n\n.menuDropdown :global(.mantine-Menu-itemLabel) {\n  line-height: var(--mantine-line-height-sm);\n}\n\n.menuDropdown :global(.mantine-Menu-item:hover),\n.menuDropdown :global(.mantine-Menu-item[data-hovered]) {\n  background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n.menuDropdown :global(.mantine-Menu-itemSection[data-position='left']) svg,\n.actionIcon svg,\n.toolbarButton svg {\n  color: var(--mantine-color-dimmed);\n}\n\n.tr {\n  &:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n  }\n}\n\n.tr:focus-visible {\n  outline: 2px solid var(--mantine-primary-color-filled);\n  outline-offset: -2px;\n}\n\n.nameLink {\n  color: var(--mantine-color-text);\n  text-decoration: none;\n}\n\n.nameLink:hover {\n  text-decoration: underline;\n}\n\n.checkboxCell {\n  width: 1px;\n  white-space: nowrap;\n  vertical-align: middle;\n  cursor: pointer;\n}\n\n.checkboxWrap {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n}\n\n.checkboxWrap input {\n  margin: 0;\n}\n\n.control,\n.staticColumnTitle {\n  padding: 5px 7px;\n  margin-left: -7px;\n}\n\n.mutedText,\n.control {\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n}\n\n.control {\n  width: fit-content;\n  border-radius: var(--mantine-radius-sm);\n\n  &:hover,\n  &[data-expanded] {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n  }\n}\n\n.toolbarButton {\n  border: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));\n  border-radius: var(--mantine-radius-xl);\n  transition: border-color 150ms ease;\n\n  padding-left: 10px !important;\n  padding-right: 12px !important;\n  --button-height: 32px !important;\n  font-weight: 450;\n  color: light-dark(var(--mantine-color-gray-8), var(--mantine-color-dark-0));\n}\n\n.toolbarButton:hover,\n.toolbarButton:focus,\n.toolbarButton:active,\n.toolbarButton[data-opened] {\n  background-color: transparent !important;\n  color: light-dark(var(--mantine-color-gray-8), var(--mantine-color-dark-0)) !important;\n}\n\n.toolbarButton :global(.mantine-Button-section[data-position='left']) {\n  margin-inline-end: 6px;\n}\n\n.statusBadge {\n  overflow: visible;\n  max-width: none;\n}\n\n.statusBadgeLabel {\n  overflow: visible;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ComboboxData } from '@mantine/core';\nimport { ActionIcon, Select, Text } from '@mantine/core';\nimport { useDebouncedCallback } from '@mantine/hooks';\nimport type { Filter, SearchRequest } from '@medplum/core';\nimport {\n  Operator,\n  SearchParameterType,\n  deepEquals,\n  getSearchParameterDetails,\n  getSearchParameters,\n} from '@medplum/core';\nimport type { SearchParameter } from '@medplum/fhirtypes';\nimport { IconFilter2Plus, IconX } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport { AddRowButton, SearchToolbarPopover } from '../SearchControl/SearchToolbarPopover';\nimport popoverClasses from '../SearchControl/SearchToolbarPopover.module.css';\nimport { getOpString, getSearchOperators, getSearchParamSelectData, setFilters } from '../SearchControl/SearchUtils';\nimport type { EditableRow } from '../SearchControl/useEditableRows';\nimport { useEditableRows } from '../SearchControl/useEditableRows';\nimport { SearchFilterValueInput } from '../SearchFilterValueInput/SearchFilterValueInput';\nimport classes from './SearchFilterPopover.module.css';\n\nexport interface SearchFilterPopoverProps {\n  readonly search: SearchRequest;\n  readonly onChange: (search: SearchRequest) => void;\n}\n\n/** How long typing in a value input can pause before the filter is applied to the search. */\nconst FILTER_VALUE_DEBOUNCE_MS = 300;\n\n/**\n * Popover-based filter builder for the {@link SearchControl} toolbar: a list of\n * `Where`/`and` + field + operator + value conditions that apply live as the user edits.\n * `SearchRequest.filters` is a flat AND-combined array, so the leading conjunction is a static\n * label rather than an editable and/or toggle. Incomplete rows stay local until they have a value.\n * Field, operator and remove changes apply at once; typed values apply after a short pause, or\n * when the popover closes. Changing the field or operator of an applied condition keeps its value\n * when the new field takes the same kind of input, so the condition is updated rather than dropped.\n * @param props - The filter popover props.\n * @returns The filter popover React node.\n */\nexport function SearchFilterPopover(props: SearchFilterPopoverProps): JSX.Element {\n  const { search, onChange } = props;\n  const [opened, setOpened] = useState(false);\n  const { rows, reset, update, remove, add } = useEditableRows<Partial<Filter>>(() => getInitialFilters(search));\n  const searchParams = useMemo(() => getSearchParameters(search.resourceType) ?? {}, [search.resourceType]);\n  const fieldData = useMemo(() => getSearchParamSelectData(searchParams), [searchParams]);\n\n  function emit(nextRows: EditableRow<Partial<Filter>>[]): void {\n    const complete = nextRows.map((row) => row.value).filter(isCompleteFilter);\n    if (!deepEquals(complete, search.filters ?? [])) {\n      onChange(setFilters(search, complete));\n    }\n  }\n\n  const emitDebounced = useDebouncedCallback(emit, { delay: FILTER_VALUE_DEBOUNCE_MS, flushOnUnmount: true });\n\n  function emitNow(nextRows: EditableRow<Partial<Filter>>[]): void {\n    emitDebounced.cancel();\n    emit(nextRows);\n  }\n\n  function setOpenedFlushing(nextOpened: boolean): void {\n    if (!nextOpened) {\n      emitDebounced.flush();\n    }\n    setOpened(nextOpened);\n  }\n\n  function toggle(): void {\n    if (!opened) {\n      reset(getInitialFilters(search));\n    }\n    setOpenedFlushing(!opened);\n  }\n\n  const activeCount = search.filters?.length ?? 0;\n  const activeLabel =\n    activeCount > 0 ? `${activeCount} ${activeCount === 1 ? 'Filter' : 'Filters'} Applied` : undefined;\n\n  return (\n    <SearchToolbarPopover\n      label=\"Filters\"\n      icon={<IconFilter2Plus size={16} />}\n      width={860}\n      opened={opened}\n      onToggle={toggle}\n      onChange={setOpenedFlushing}\n      activeLabel={activeLabel}\n      footer={<AddRowButton label=\"Add Filter\" onClick={() => add({})} />}\n    >\n      <div className={popoverClasses.body} tabIndex={-1} data-autofocus>\n        {rows.length === 0 && <div className={popoverClasses.empty}>No filters applied</div>}\n        {rows.map(({ id, value }, index) => (\n          <FilterConditionRow\n            key={id}\n            rowId={id}\n            index={index}\n            resourceType={search.resourceType}\n            searchParams={searchParams}\n            fieldData={fieldData}\n            value={value}\n            onChange={(next) => emitNow(update(index, next))}\n            onValueChange={(next) => emitDebounced(update(index, next))}\n            onDelete={() => emitNow(remove(index))}\n          />\n        ))}\n      </div>\n    </SearchToolbarPopover>\n  );\n}\n\n/**\n * Props for one condition row in the filter popover.\n * - `rowId`: stable key for the row, so its value input is not remounted when earlier rows are removed.\n * - `index`: position in the list; drives the `Where`/`and` label and the accessible names.\n * - `resourceType`: the searched resource type, used to render the value input.\n * - `searchParams`: the resource type's search parameters, keyed by code.\n * - `fieldData`: grouped Select options for the field picker.\n * - `value`: the condition being edited; incomplete until it has a code, operator and value.\n * - `onChange`: the field or operator changed; applied immediately.\n * - `onValueChange`: the value input changed; may fire on every keystroke, so it is debounced.\n * - `onDelete`: remove this row.\n */\ninterface FilterConditionRowProps {\n  readonly rowId: number;\n  readonly index: number;\n  readonly resourceType: string;\n  readonly searchParams: Record<string, SearchParameter>;\n  readonly fieldData: ComboboxData;\n  readonly value: Partial<Filter>;\n  readonly onChange: (value: Partial<Filter>) => void;\n  readonly onValueChange: (value: Partial<Filter>) => void;\n  readonly onDelete: () => void;\n}\n\n/**\n * One filter condition on a single line: conjunction, field, operator, value and remove button.\n * @param props - The condition row props.\n * @returns The condition row React node.\n */\nfunction FilterConditionRow(props: FilterConditionRowProps): JSX.Element {\n  const { value, searchParams, resourceType, index } = props;\n  const searchParam = value.code ? searchParams[value.code] : undefined;\n  const operators = searchParam && getSearchOperators(searchParam);\n\n  function changeField(code: string | null): void {\n    const nextParam = code ? searchParams[code] : undefined;\n    const keepOperator = !!value.operator && !!nextParam && !!getSearchOperators(nextParam)?.includes(value.operator);\n    const keepValue = !!searchParam && !!nextParam && canKeepValue(resourceType, searchParam, nextParam);\n    props.onChange({\n      code: code ?? undefined,\n      operator: keepOperator ? value.operator : Operator.EQUALS,\n      value: keepValue ? value.value : '',\n    });\n  }\n\n  function changeOperator(op: string | null): void {\n    props.onChange({ code: value.code, operator: (op as Operator) ?? undefined, value: value.value });\n  }\n\n  const valueInput = (\n    <div className={classes.value}>\n      {searchParam && value.operator && (\n        <SearchFilterValueInput\n          key={`filter-${props.rowId}-value-${value.code}-${value.operator}`}\n          name={`filter-${index}-value`}\n          aria-label={`Filter ${index + 1} value`}\n          resourceType={props.resourceType}\n          searchParam={searchParam}\n          defaultValue={value.value}\n          withinPortal={false}\n          onChange={(newValue) => props.onValueChange({ code: value.code, operator: value.operator, value: newValue })}\n        />\n      )}\n    </div>\n  );\n\n  const deleteButton = (\n    <ActionIcon\n      variant=\"subtle\"\n      color=\"gray\"\n      radius=\"xl\"\n      aria-label={`Remove filter ${index + 1}`}\n      ml={2}\n      onClick={props.onDelete}\n    >\n      <IconX size={16} stroke={2} className={popoverClasses.deleteIcon} />\n    </ActionIcon>\n  );\n\n  return (\n    <div className={classes.row}>\n      <Text className={classes.conjunction}>{index === 0 ? 'Where' : 'and'}</Text>\n      <Select\n        comboboxProps={{ withinPortal: false }}\n        className={classes.field}\n        aria-label={`Filter ${index + 1} field`}\n        placeholder=\"Field\"\n        searchable\n        data={props.fieldData}\n        value={value.code ?? null}\n        onChange={changeField}\n      />\n      <Select\n        comboboxProps={{ withinPortal: false }}\n        className={classes.operator}\n        aria-label={`Filter ${index + 1} operator`}\n        placeholder=\"Operator\"\n        disabled={!operators}\n        data={operators ? operators.map((op) => ({ value: op, label: getOpString(op) })) : []}\n        value={value.operator ?? null}\n        onChange={changeOperator}\n      />\n      {valueInput}\n      {deleteButton}\n    </div>\n  );\n}\n\n/**\n * Whether a condition's value still fits after its field changes: the new field must take the same\n * kind of input. References never carry over, since their value is picked from a search of the\n * field's target types rather than typed.\n * @param resourceType - The searched resource type.\n * @param prevParam - The search parameter the value was entered for.\n * @param nextParam - The newly selected search parameter.\n * @returns True if the value can be carried over to the new field.\n */\nfunction canKeepValue(resourceType: string, prevParam: SearchParameter, nextParam: SearchParameter): boolean {\n  const type = getSearchParameterDetails(resourceType, nextParam).type;\n  return type !== SearchParameterType.REFERENCE && type === getSearchParameterDetails(resourceType, prevParam).type;\n}\n\nfunction getInitialFilters(search: SearchRequest): Partial<Filter>[] {\n  return [...(search.filters ?? [])];\n}\n\nfunction isCompleteFilter(filter: Partial<Filter>): filter is Filter {\n  return !!filter.code && !!filter.operator && filter.value !== undefined && filter.value !== '';\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Indicator, Popover, Tooltip, VisuallyHidden } from '@mantine/core';\nimport { IconCirclePlus } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useId } from 'react';\nimport controlClasses from './SearchControl.module.css';\nimport classes from './SearchToolbarPopover.module.css';\n\nexport interface SearchToolbarPopoverProps {\n  readonly label: string;\n  readonly icon: ReactNode;\n  readonly width: number;\n  readonly opened: boolean;\n  readonly onToggle: () => void;\n  readonly onChange: (opened: boolean) => void;\n  /** Describes the active state (e.g. \"2 Filters Applied\"); shows the indicator dot and tooltip when set. */\n  readonly activeLabel?: string;\n  readonly footer?: ReactNode;\n  readonly children: ReactNode;\n}\n\n/**\n * Shared shell for the {@link SearchControl} toolbar popovers (Columns, Filters, Sort): the toolbar\n * button with its optional active-state indicator, and the dropdown with an optional footer.\n * @param props - The popover props.\n * @returns The popover React node.\n */\nexport function SearchToolbarPopover(props: SearchToolbarPopoverProps): JSX.Element {\n  const { opened, activeLabel } = props;\n  const activeLabelId = useId();\n  return (\n    <Popover\n      opened={opened}\n      onChange={props.onChange}\n      position=\"bottom-start\"\n      shadow=\"md\"\n      radius=\"md\"\n      width={props.width}\n      trapFocus\n      returnFocus\n      closeOnClickOutside\n    >\n      <Indicator className={classes.indicator} disabled={!activeLabel} color=\"blue\" size={8} offset={6}>\n        <Tooltip label={activeLabel ?? ''} position=\"bottom\" openDelay={500} disabled={!activeLabel || opened}>\n          <Popover.Target>\n            <Button\n              className={controlClasses.toolbarButton}\n              data-opened={opened || undefined}\n              size=\"compact-md\"\n              variant=\"subtle\"\n              color=\"gray\"\n              leftSection={props.icon}\n              aria-describedby={activeLabel ? activeLabelId : undefined}\n              onClick={props.onToggle}\n            >\n              {props.label}\n            </Button>\n          </Popover.Target>\n        </Tooltip>\n      </Indicator>\n      {activeLabel && <VisuallyHidden id={activeLabelId}>{activeLabel}</VisuallyHidden>}\n      <Popover.Dropdown className={classes.dropdown}>\n        {props.children}\n        {props.footer && <div className={classes.footer}>{props.footer}</div>}\n      </Popover.Dropdown>\n    </Popover>\n  );\n}\n\nexport function AddRowButton(props: { readonly label: string; readonly onClick: () => void }): JSX.Element {\n  return (\n    <Button\n      className={classes.addButton}\n      size=\"compact-sm\"\n      variant=\"subtle\"\n      color=\"blue\"\n      leftSection={<IconCirclePlus size={16} />}\n      fw={500}\n      onClick={props.onClick}\n    >\n      {props.label}\n    </Button>\n  );\n}\n", "/* SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors */\n/* SPDX-License-Identifier: Apache-2.0 */\n\n.dropdown {\n  max-width: calc(100vw - 32px);\n  padding: 0;\n}\n\n.body {\n  padding: var(--mantine-spacing-md);\n  padding-right: var(--mantine-spacing-xs);\n  display: flex;\n  flex-direction: column;\n  gap: var(--mantine-spacing-md);\n}\n\n.row {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.grow {\n  flex: 1 1 auto;\n  min-width: 0;\n}\n\n.footer {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  padding: var(--mantine-spacing-sm);\n  border-top: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n.deleteIcon {\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n}\n\n.empty {\n  padding-block: 7px;\n  font-size: var(--mantine-font-size-sm);\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n}\n\n.indicator {\n  --indicator-right: calc(0.25rem * var(--mantine-scale)) !important;\n}\n\n.addButton :global(.mantine-Button-section[data-position='left']) {\n  margin-inline-end: calc(var(--mantine-spacing-xs) * 0.5);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useState } from 'react';\n\nexport interface EditableRow<T> {\n  /** Stable React key, so removing a row never re-keys the rows after it. */\n  readonly id: number;\n  readonly value: T;\n}\n\nlet nextRowId = 0;\n\nfunction toRows<T>(values: T[]): EditableRow<T>[] {\n  return values.map((value) => ({ id: nextRowId++, value }));\n}\n\n/**\n * Row state for the list editors (sort rules, filter conditions): values with stable keys plus\n * reset/update/remove/add. `update` and `remove` return the next rows so the caller can emit them.\n * @param initial - Produces the initial row values.\n * @returns The rows and their mutators.\n */\nexport function useEditableRows<T>(initial: () => T[]): {\n  readonly rows: EditableRow<T>[];\n  readonly reset: (values: T[]) => void;\n  readonly update: (index: number, value: T) => EditableRow<T>[];\n  readonly remove: (index: number) => EditableRow<T>[];\n  readonly add: (value: T) => void;\n} {\n  const [rows, setRows] = useState(() => toRows(initial()));\n\n  function update(index: number, value: T): EditableRow<T>[] {\n    const next = rows.map((row, i) => (i === index ? { ...row, value } : row));\n    setRows(next);\n    return next;\n  }\n\n  function remove(index: number): EditableRow<T>[] {\n    const next = rows.filter((_, i) => i !== index);\n    setRows(next);\n    return next;\n  }\n\n  return {\n    rows,\n    reset: (values) => setRows(toRows(values)),\n    update,\n    remove,\n    add: (value) => setRows([...rows, ...toRows([value])]),\n  };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Checkbox, TextInput } from '@mantine/core';\nimport { getSearchParameterDetails, SearchParameterType } from '@medplum/core';\nimport type { Quantity, Reference, SearchParameter } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ReferenceInput } from '../ReferenceInput/ReferenceInput';\n\nexport interface SearchFilterValueInputProps {\n  readonly resourceType: string;\n  readonly searchParam: SearchParameter;\n  readonly name?: string;\n  /** Accessible name for the value input. */\n  readonly 'aria-label'?: string;\n  readonly defaultValue?: string;\n  readonly autoFocus?: boolean;\n  /** Render reference dropdowns inside the DOM tree (not a portal); defaults to portalled. */\n  readonly withinPortal?: boolean;\n  readonly onChange: (value: string) => void;\n}\n\nexport function SearchFilterValueInput(props: SearchFilterValueInputProps): JSX.Element | null {\n  const details = getSearchParameterDetails(props.resourceType, props.searchParam);\n  const name = props.name ?? 'filter-value';\n\n  switch (details.type) {\n    case SearchParameterType.REFERENCE:\n      return (\n        <ReferenceInput\n          name={name}\n          defaultValue={props.defaultValue ? { reference: props.defaultValue } : undefined}\n          targetTypes={props.searchParam.target}\n          withinPortal={props.withinPortal}\n          autoFocus={props.autoFocus}\n          onChange={(newReference: Reference | undefined) => {\n            if (newReference) {\n              props.onChange(newReference.reference as string);\n            } else {\n              props.onChange('');\n            }\n          }}\n        />\n      );\n\n    case SearchParameterType.BOOLEAN:\n      return (\n        <Checkbox\n          name={name}\n          aria-label={props['aria-label']}\n          data-autofocus={props.autoFocus}\n          data-testid={name}\n          defaultChecked={props.defaultValue === 'true'}\n          autoFocus={props.autoFocus}\n          onChange={(e) => props.onChange(e.currentTarget.checked.toString())}\n        />\n      );\n\n    case SearchParameterType.DATE:\n      return (\n        <TextInput\n          type=\"date\"\n          name={name}\n          aria-label={props['aria-label']}\n          data-autofocus={props.autoFocus}\n          data-testid={name}\n          defaultValue={props.defaultValue}\n          autoFocus={props.autoFocus}\n          onChange={(e) => props.onChange(e.currentTarget.value)}\n        />\n      );\n\n    case SearchParameterType.DATETIME:\n      return (\n        <DateTimeInput\n          name={name}\n          defaultValue={props.defaultValue}\n          autoFocus={props.autoFocus}\n          onChange={props.onChange}\n        />\n      );\n\n    case SearchParameterType.NUMBER:\n      return (\n        <TextInput\n          type=\"number\"\n          name={name}\n          aria-label={props['aria-label']}\n          data-autofocus={props.autoFocus}\n          data-testid={name}\n          defaultValue={props.defaultValue}\n          autoFocus={props.autoFocus}\n          onChange={(e) => props.onChange(e.currentTarget.value)}\n        />\n      );\n\n    case SearchParameterType.QUANTITY:\n      return (\n        <QuantityInput\n          name={name}\n          path=\"\"\n          defaultValue={tryParseQuantity(props.defaultValue)}\n          autoFocus={props.autoFocus}\n          onChange={(newQuantity: Quantity | undefined) => {\n            if (newQuantity) {\n              props.onChange(`${newQuantity.value}`);\n            } else {\n              props.onChange('');\n            }\n          }}\n        />\n      );\n\n    default:\n      return (\n        <TextInput\n          name={name}\n          aria-label={props['aria-label']}\n          data-autofocus={props.autoFocus}\n          data-testid={name}\n          defaultValue={props.defaultValue}\n          autoFocus={props.autoFocus}\n          onChange={(e) => props.onChange(e.currentTarget.value)}\n          placeholder=\"Search value\"\n        />\n      );\n  }\n}\n\nfunction tryParseQuantity(value: string | undefined): Quantity | undefined {\n  if (value) {\n    const [valueString, systemString, unitString] = value.split('|');\n    if (valueString) {\n      return {\n        value: Number.parseFloat(valueString),\n        system: systemString,\n        unit: unitString,\n      };\n    }\n  }\n  return undefined;\n}\n", "/* SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors */\n/* SPDX-License-Identifier: Apache-2.0 */\n\n.row {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.conjunction {\n  flex: 0 0 64px;\n  font-size: var(--mantine-font-size-sm);\n  color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n}\n\n.field {\n  flex: 0 0 200px;\n}\n\n.operator {\n  flex: 0 0 170px;\n}\n\n.value {\n  flex: 1 1 auto;\n  min-width: 0;\n}\n\n@media (max-width: 48em) {\n  .row {\n    flex-wrap: wrap;\n  }\n\n  .field,\n  .operator {\n    flex: 1 1 0;\n    min-width: 0;\n  }\n\n  .value {\n    order: 1;\n    flex: 1 1 100%;\n    padding-left: calc(64px + 8px);\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group } from '@mantine/core';\nimport type { Filter } from '@medplum/core';\nimport type { SearchParameter } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useState } from 'react';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport { SearchFilterValueInput } from '../SearchFilterValueInput/SearchFilterValueInput';\n\nexport interface SearchFilterValueDialogProps {\n  readonly title: string;\n  readonly visible: boolean;\n  readonly resourceType: string;\n  readonly searchParam?: SearchParameter;\n  readonly filter?: Filter;\n  readonly defaultValue?: string;\n  readonly onOk: (filter: Filter) => void;\n  readonly onCancel: () => void;\n}\n\nexport function SearchFilterValueDialog(props: SearchFilterValueDialogProps): JSX.Element | null {\n  const [value, setValue] = useState(props.defaultValue ?? '');\n\n  if (!props.searchParam || !props.filter) {\n    return null;\n  }\n\n  function onOk(): void {\n    props.onOk({ ...(props.filter as Filter), value });\n  }\n\n  return (\n    <Modal\n      title={props.title}\n      size=\"xl\"\n      opened={props.visible}\n      onClose={props.onCancel}\n      onSubmit={onOk}\n      actions={\n        <Group justify=\"flex-end\">\n          <SubmitButton>OK</SubmitButton>\n        </Group>\n      }\n    >\n      <SearchFilterValueInput\n        resourceType={props.resourceType}\n        searchParam={props.searchParam}\n        defaultValue={value}\n        autoFocus={true}\n        onChange={setValue}\n      />\n    </Modal>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Filter } from '@medplum/core';\nimport { formatDateTime, getSearchParameterDetails, globalSchema, Operator, SearchParameterType } from '@medplum/core';\nimport type { JSX } from 'react';\nimport { ResourceName } from '../ResourceName/ResourceName';\n\nexport interface SearchFilterValueDisplayProps {\n  readonly resourceType: string;\n  readonly filter: Filter;\n}\n\nexport function SearchFilterValueDisplay(props: SearchFilterValueDisplayProps): JSX.Element {\n  const { resourceType, filter } = props;\n\n  const searchParam = globalSchema.types[resourceType].searchParams?.[filter.code];\n  if (searchParam) {\n    if (\n      searchParam.type === 'reference' &&\n      (filter.operator === Operator.EQUALS || filter.operator === Operator.NOT_EQUALS)\n    ) {\n      return <ResourceName value={{ reference: filter.value }} />;\n    }\n\n    const searchParamDetails = getSearchParameterDetails(resourceType, searchParam);\n    if (filter.code === '_lastUpdated' || searchParamDetails.type === SearchParameterType.DATETIME) {\n      return <>{formatDateTime(filter.value)}</>;\n    }\n  }\n\n  return <>{filter.value}</>;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Menu } from '@mantine/core';\nimport type { Filter, SearchRequest } from '@medplum/core';\nimport { Operator } from '@medplum/core';\nimport type { SearchParameter } from '@medplum/fhirtypes';\nimport {\n  IconBleach,\n  IconBleachOff,\n  IconBracketsContain,\n  IconBucket,\n  IconBucketOff,\n  IconCalendarDue,\n  IconCalendarMonth,\n  IconCalendarTime,\n  IconCheck,\n  IconEqual,\n  IconEqualNot,\n  IconMathGreater,\n  IconMathLower,\n  IconSettings,\n  IconSortAscending,\n  IconSortDescending,\n  IconX,\n} from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { Fragment } from 'react';\nimport classes from '../SearchControl/SearchControl.module.css';\nimport {\n  addLastMonthFilter,\n  addMissingFilter,\n  addNext24HoursFilter,\n  addNextMonthFilter,\n  addThisMonthFilter,\n  addTodayFilter,\n  addTomorrowFilter,\n  addYearToDateFilter,\n  addYesterdayFilter,\n  buildFieldNameString,\n  clearFiltersOnField,\n  setSort,\n} from '../SearchControl/SearchUtils';\n\nexport interface SearchPopupMenuProps {\n  readonly search: SearchRequest;\n  readonly searchParams?: SearchParameter[];\n  readonly onPrompt: (searchParam: SearchParameter, filter: Filter) => void;\n  readonly onChange: (definition: SearchRequest) => void;\n}\n\nconst ICON_SIZE = 16;\nconst ICON_COLOR = 'var(--mantine-color-dimmed)';\nconst CHECK = <IconCheck size={ICON_SIZE} color=\"var(--mantine-color-blue-6)\" />;\n\n/**\n * Column header dropdown: sort directions, filter prompts, relative date shortcuts (for dates),\n * missing / not missing, and clear filters for the column's search parameter.\n * @param props - The popup menu props.\n * @returns The menu dropdown, or null when the column is not backed by a search parameter.\n */\nexport function SearchPopupMenu(props: SearchPopupMenuProps): JSX.Element | null {\n  if (!props.searchParams) {\n    return null;\n  }\n\n  function onSort(searchParam: SearchParameter, desc: boolean): void {\n    onChange(setSort(props.search, searchParam.code, desc));\n  }\n\n  function onClear(searchParam: SearchParameter): void {\n    onChange(clearFiltersOnField(props.search, searchParam.code));\n  }\n\n  function onPrompt(searchParam: SearchParameter, operator: Operator): void {\n    props.onPrompt(searchParam, { code: searchParam.code, operator, value: '' });\n  }\n\n  function onChange(definition: SearchRequest): void {\n    props.onChange(definition);\n  }\n\n  if (props.searchParams.length === 1) {\n    return (\n      <SearchParameterSubMenu\n        search={props.search}\n        searchParam={props.searchParams[0]}\n        onSort={onSort}\n        onPrompt={onPrompt}\n        onChange={onChange}\n        onClear={onClear}\n      />\n    );\n  }\n\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      {props.searchParams.map((searchParam) => (\n        <Menu.Item key={searchParam.code}>{buildFieldNameString(searchParam.code)}</Menu.Item>\n      ))}\n    </Menu.Dropdown>\n  );\n}\n\ninterface SearchPopupSubMenuProps {\n  readonly search: SearchRequest;\n  readonly searchParam: SearchParameter;\n  readonly onSort: (searchParam: SearchParameter, descending: boolean) => void;\n  readonly onPrompt: (searchParam: SearchParameter, operator: Operator) => void;\n  readonly onChange: (search: SearchRequest) => void;\n  readonly onClear: (searchParam: SearchParameter) => void;\n}\n\nfunction SearchParameterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  switch (props.searchParam.type) {\n    case 'date':\n      return <DateFilterSubMenu {...props} />;\n    case 'number':\n    case 'quantity':\n      return <NumericFilterSubMenu {...props} />;\n    case 'reference':\n      return <ReferenceFilterSubMenu {...props} />;\n    case 'string':\n      return <TextFilterSubMenu {...props} />;\n    case 'token':\n      return <TokenFilterSubMenu {...props} />;\n    case 'uri':\n      return <UriFilterSubMenu {...props} />;\n    default:\n      return <>Unknown search param type: {props.searchParam.type}</>;\n  }\n}\n\ninterface MenuEntryProps {\n  readonly icon: ReactNode;\n  readonly checked?: boolean;\n  readonly onClick: () => void;\n  readonly children: ReactNode;\n}\n\nfunction MenuEntry(props: MenuEntryProps): JSX.Element {\n  return (\n    <Menu.Item leftSection={props.icon} rightSection={props.checked ? CHECK : null} onClick={props.onClick}>\n      {props.children}\n    </Menu.Item>\n  );\n}\n\ninterface SortItemsProps extends SearchPopupSubMenuProps {\n  readonly ascLabel: string;\n  readonly descLabel: string;\n}\n\nfunction SortItems(props: SortItemsProps): JSX.Element {\n  const { searchParam } = props;\n  const isSelected = (descending: boolean): boolean =>\n    !!props.search.sortRules?.some((rule) => rule.code === searchParam.code && !!rule.descending === descending);\n  return (\n    <>\n      <MenuEntry\n        icon={<IconSortAscending size={ICON_SIZE} color={ICON_COLOR} />}\n        checked={isSelected(false)}\n        onClick={() => props.onSort(searchParam, false)}\n      >\n        {props.ascLabel}\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconSortDescending size={ICON_SIZE} color={ICON_COLOR} />}\n        checked={isSelected(true)}\n        onClick={() => props.onSort(searchParam, true)}\n      >\n        {props.descLabel}\n      </MenuEntry>\n      <Menu.Divider />\n    </>\n  );\n}\n\ninterface EqualityItemsProps extends SearchPopupSubMenuProps {\n  readonly notOperator: Operator;\n}\n\nfunction EqualityItems(props: EqualityItemsProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <>\n      <MenuEntry\n        icon={<IconEqual size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}\n      >\n        Equals...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconEqualNot size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, props.notOperator)}\n      >\n        Does not equal...\n      </MenuEntry>\n    </>\n  );\n}\n\ntype RelativeDateOption = {\n  readonly label: string;\n  readonly Icon: typeof IconCalendarDue;\n  readonly apply: (search: SearchRequest, code: string) => SearchRequest;\n  /** The end is \"now\" at the time it was picked, so only the start is compared. */\n  readonly openEnded?: boolean;\n};\n\nconst RELATIVE_DATE_GROUPS: RelativeDateOption[][] = [\n  [\n    { label: 'Tomorrow', Icon: IconCalendarDue, apply: addTomorrowFilter },\n    { label: 'Today', Icon: IconCalendarDue, apply: addTodayFilter },\n    { label: 'Yesterday', Icon: IconCalendarDue, apply: addYesterdayFilter },\n    { label: 'Next 24 Hours', Icon: IconCalendarTime, apply: addNext24HoursFilter },\n  ],\n  [\n    { label: 'Next Month', Icon: IconCalendarMonth, apply: addNextMonthFilter },\n    { label: 'This Month', Icon: IconCalendarMonth, apply: addThisMonthFilter },\n    { label: 'Last Month', Icon: IconCalendarMonth, apply: addLastMonthFilter },\n  ],\n  [{ label: 'Year to date', Icon: IconCalendarTime, apply: addYearToDateFilter, openEnded: true }],\n];\n\n/**\n * Returns true when the column's filters are exactly the start/end pair this relative date\n * produces today.\n * @param option - The relative date option.\n * @param search - The current search.\n * @param code - The column's search parameter code.\n * @returns True if the option is the column's current filter.\n */\nfunction isRelativeDateSelected(option: RelativeDateOption, search: SearchRequest, code: string): boolean {\n  const actual = (search.filters ?? []).filter((filter) => filter.code === code);\n  const expected = option.apply({ resourceType: search.resourceType }, code).filters ?? [];\n  if (actual.length !== expected.length) {\n    return false;\n  }\n  return expected.every((filter, i) => {\n    const matchesValue = option.openEnded && i > 0 ? true : actual[i].value === filter.value;\n    return actual[i].operator === filter.operator && matchesValue;\n  });\n}\n\nfunction DateFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  const code = searchParam.code;\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <SortItems {...props} ascLabel=\"Sort Oldest to Newest\" descLabel=\"Sort Newest to Oldest\" />\n      <EqualityItems {...props} notOperator={Operator.NOT_EQUALS} />\n      <Menu.Divider />\n      <MenuEntry\n        icon={<IconMathLower size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.ENDS_BEFORE)}\n      >\n        Before...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconMathGreater size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.STARTS_AFTER)}\n      >\n        After...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconBracketsContain size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}\n      >\n        Between...\n      </MenuEntry>\n      {RELATIVE_DATE_GROUPS.map((group) => (\n        <Fragment key={group[0].label}>\n          <Menu.Divider />\n          {group.map((option) => (\n            <MenuEntry\n              key={option.label}\n              icon={<option.Icon size={ICON_SIZE} color={ICON_COLOR} />}\n              checked={isRelativeDateSelected(option, props.search, code)}\n              onClick={() => props.onChange(option.apply(props.search, code))}\n            >\n              {option.label}\n            </MenuEntry>\n          ))}\n        </Fragment>\n      ))}\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction NumericFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <SortItems {...props} ascLabel=\"Sort Smallest to Largest\" descLabel=\"Sort Largest to Smallest\" />\n      <EqualityItems {...props} notOperator={Operator.NOT_EQUALS} />\n      <Menu.Divider />\n      <MenuEntry\n        icon={<IconMathGreater size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.GREATER_THAN)}\n      >\n        Greater than...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconSettings size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.GREATER_THAN_OR_EQUALS)}\n      >\n        Greater than or equal to...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconMathLower size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.LESS_THAN)}\n      >\n        Less than...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconSettings size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.LESS_THAN_OR_EQUALS)}\n      >\n        Less than or equal to...\n      </MenuEntry>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction ReferenceFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <EqualityItems {...props} notOperator={Operator.NOT} />\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction TextFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <SortItems {...props} ascLabel=\"Sort A to Z\" descLabel=\"Sort Z to A\" />\n      <EqualityItems {...props} notOperator={Operator.NOT} />\n      <Menu.Divider />\n      <MenuEntry\n        icon={<IconBucket size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.CONTAINS)}\n      >\n        Contains...\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconBucketOff size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}\n      >\n        Does not contain...\n      </MenuEntry>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction TokenFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <EqualityItems {...props} notOperator={Operator.NOT} />\n      <Menu.Divider />\n      <MenuEntry\n        icon={<IconEqual size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onPrompt(searchParam, Operator.TEXT)}\n      >\n        Text contains...\n      </MenuEntry>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction UriFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  return (\n    <Menu.Dropdown className={classes.menuDropdown}>\n      <EqualityItems {...props} notOperator={Operator.NOT} />\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction CommonMenuItems(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  const code = searchParam.code;\n  return (\n    <>\n      <Menu.Divider />\n      <MenuEntry\n        icon={<IconBleach size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onChange(addMissingFilter(props.search, code))}\n      >\n        Missing\n      </MenuEntry>\n      <MenuEntry\n        icon={<IconBleachOff size={ICON_SIZE} color={ICON_COLOR} />}\n        onClick={() => props.onChange(addMissingFilter(props.search, code, false))}\n      >\n        Not missing\n      </MenuEntry>\n      <Menu.Divider />\n      <MenuEntry icon={<IconX size={ICON_SIZE} color={ICON_COLOR} />} onClick={() => props.onClear(searchParam)}>\n        Clear filters\n      </MenuEntry>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Select } from '@mantine/core';\nimport type { SearchRequest, SortRule } from '@medplum/core';\nimport { getSearchParameters } from '@medplum/core';\nimport { IconArrowsSort, IconX } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport { AddRowButton, SearchToolbarPopover } from '../SearchControl/SearchToolbarPopover';\nimport classes from '../SearchControl/SearchToolbarPopover.module.css';\nimport {\n  DEFAULT_SORT_RULES,\n  getSearchParamSelectData,\n  getSortDirectionLabels,\n  isSameSort,\n} from '../SearchControl/SearchUtils';\nimport type { EditableRow } from '../SearchControl/useEditableRows';\nimport { useEditableRows } from '../SearchControl/useEditableRows';\n\nexport interface SearchSortEditorProps {\n  readonly search: SearchRequest;\n  readonly onChange: (search: SearchRequest) => void;\n}\n\n/**\n * Popover-based sort builder for the {@link SearchControl} toolbar: an ordered list of\n * `field + direction` rows that apply live as the user edits. Opens showing the default sort when\n * the search has no sort rules.\n * @param props - The sort editor props.\n * @returns The sort editor React node.\n */\nexport function SearchSortEditor(props: SearchSortEditorProps): JSX.Element {\n  const { search, onChange } = props;\n  const [opened, setOpened] = useState(false);\n  const { rows, reset, update, remove, add } = useEditableRows(() => getInitialRules(search));\n  const searchParams = useMemo(() => getSearchParameters(search.resourceType) ?? {}, [search.resourceType]);\n  const fieldData = useMemo(() => getSearchParamSelectData(searchParams), [searchParams]);\n\n  function toggle(): void {\n    if (!opened) {\n      reset(getInitialRules(search));\n    }\n    setOpened((o) => !o);\n  }\n\n  function emit(nextRows: EditableRow<SortRule>[]): void {\n    onChange({ ...search, sortRules: nextRows.map((row) => row.value).filter((rule) => !!rule.code) });\n  }\n\n  const rules = search.sortRules ?? [];\n  const activeLabel =\n    rules.length > 0 && !isSameSort(rules, DEFAULT_SORT_RULES)\n      ? `${rules.length} ${rules.length === 1 ? 'Sort' : 'Sorts'} Applied`\n      : undefined;\n\n  return (\n    <SearchToolbarPopover\n      label=\"Sort\"\n      icon={<IconArrowsSort size={16} />}\n      width={520}\n      opened={opened}\n      onToggle={toggle}\n      onChange={setOpened}\n      activeLabel={activeLabel}\n      footer={<AddRowButton label=\"Add Sort\" onClick={() => add({ code: '', descending: false })} />}\n    >\n      <div className={classes.body} tabIndex={-1} data-autofocus>\n        {rows.length === 0 && <div className={classes.empty}>No sort applied</div>}\n        {rows.map(({ id, value: rule }, index) => {\n          const labels = getSortDirectionLabels(rule.code ? searchParams[rule.code]?.type : undefined);\n          const direction = rule.descending ? 'desc' : 'asc';\n          return (\n            <div className={classes.row} key={id}>\n              <Select\n                comboboxProps={{ withinPortal: false }}\n                className={classes.grow}\n                aria-label={`Sort ${index + 1} field`}\n                placeholder=\"Field\"\n                searchable\n                data={fieldData}\n                value={rule.code || null}\n                onChange={(code) => emit(update(index, { code: code ?? '', descending: rule.descending }))}\n              />\n              <Select\n                comboboxProps={{ withinPortal: false }}\n                className={classes.grow}\n                aria-label={`Sort ${index + 1} direction`}\n                placeholder=\"Order\"\n                disabled={!rule.code}\n                allowDeselect={false}\n                data={[\n                  { value: 'asc', label: labels.asc },\n                  { value: 'desc', label: labels.desc },\n                ]}\n                value={rule.code ? direction : null}\n                onChange={(dir) => emit(update(index, { code: rule.code, descending: dir === 'desc' }))}\n              />\n              <ActionIcon\n                variant=\"subtle\"\n                color=\"gray\"\n                radius=\"xl\"\n                aria-label={`Remove sort ${index + 1}`}\n                ml={2}\n                onClick={() => emit(remove(index))}\n              >\n                <IconX size={16} stroke={2} className={classes.deleteIcon} />\n              </ActionIcon>\n            </div>\n          );\n        })}\n      </div>\n    </SearchToolbarPopover>\n  );\n}\n\nfunction getInitialRules(search: SearchRequest): SortRule[] {\n  return search.sortRules?.length ? [...search.sortRules] : [...DEFAULT_SORT_RULES];\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * Returns control properties for pagination controls.\n * This is specifically for the Mantine Pagination component.\n * See: https://v7.mantine.dev/core/pagination/?t=props\n * @param controlName - The name of the pagination control (e.g., 'previous', 'next').\n * @returns The properties for the pagination control.\n */\nexport function getPaginationControlProps(controlName: string): Record<string, string> {\n  // \"next\" | \"previous\" | \"first\" | \"last\"\n  switch (controlName) {\n    case 'next':\n      return { 'aria-label': 'Next page' };\n    case 'previous':\n      return { 'aria-label': 'Previous page' };\n    case 'first':\n      return { 'aria-label': 'First page' };\n    case 'last':\n      return { 'aria-label': 'Last page' };\n    default:\n      return {};\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { InternalSchemaElement, SearchRequest } from '@medplum/core';\nimport {\n  getElementDefinition,\n  getSearchParameter,\n  getSearchParameterDetails,\n  getSearchParameters,\n} from '@medplum/core';\nimport type { ResourceType, SearchParameter } from '@medplum/fhirtypes';\n\n/**\n * The SearchControlField type describes a field in the search control.\n *\n * In a SearchRequest, a field is a simple string. Strings can be one of the following:\n * 1) Simple property names, which refer to InternalSchemaElement objects\n * 2) Search parameter names, which refer to SearchParameter resources\n *\n * Consider a few examples of how this becomes complicated.\n *\n * \"name\" (easy)\n *  - element definition path=\"Patient.name\"\n *  - search parameter code=\"name\"\n *\n * \"birthDate\" (medium)\n *  - refers to the element definition path=\"Patient.birthDate\"\n *  - refers to the search parameter code=\"birthdate\" (note the capitalization)\n *\n * \"email\" (hard)\n *  - refers to the search parameter code=\"email\"\n *  - refers to the element definition path=\"Patient.telecom\"\n *\n * In the last case, we start with the search parameter, and walk backwards to the\n * element definition in order to get type details for rendering.\n *\n * Overall, we want columns, fields, properties, and search parameters to feel seamless,\n * so we try our darndest to make this work.\n */\nexport interface SearchControlField {\n  readonly name: string;\n  readonly elementDefinition?: InternalSchemaElement;\n  readonly searchParams?: SearchParameter[];\n}\n\n/**\n * Returns the collection of field definitions for the search request.\n * @param search - The search request definition.\n * @returns An array of field definitions.\n */\nexport function getFieldDefinitions(search: SearchRequest): SearchControlField[] {\n  const resourceType = search.resourceType;\n  const fields = [] as SearchControlField[];\n\n  for (const name of search.fields || ['id', '_lastUpdated']) {\n    fields.push(getFieldDefinition(resourceType, name));\n  }\n  return fields;\n}\n\n/**\n * Return the field definition for a given field name.\n * Field names can be either property names or search parameter codes.\n * @param resourceType - The resource type.\n * @param name - The search field name (either property name or search parameter code).\n * @returns The field definition.\n */\nfunction getFieldDefinition(resourceType: string, name: string): SearchControlField {\n  if (name === '_lastUpdated') {\n    return {\n      name: '_lastUpdated',\n      searchParams: [\n        {\n          resourceType: 'SearchParameter',\n          base: ['Resource' as ResourceType],\n          code: '_lastUpdated',\n          name: '_lastUpdated',\n          type: 'date',\n          expression: 'Resource.meta.lastUpdated',\n        } as SearchParameter,\n      ],\n    };\n  }\n\n  if (name === 'meta.versionId') {\n    return {\n      name: 'meta.versionId',\n      searchParams: [\n        {\n          resourceType: 'SearchParameter',\n          base: ['Resource' as ResourceType],\n          code: '_versionId',\n          name: '_versionId',\n          type: 'token',\n          expression: 'Resource.meta.versionId',\n        } as SearchParameter,\n      ],\n    };\n  }\n\n  const exactElementDefinition = getElementDefinition(resourceType, name);\n  const exactSearchParam = getSearchParameter(resourceType, name.toLowerCase());\n\n  // Best case: Exact match of element definition or search parameter.\n  // Examples: ServiceRequest.subject, Patient.name, Patient.birthDate\n  // In this case, we only show the one search parameter.\n  if (exactElementDefinition && exactSearchParam) {\n    return { name, elementDefinition: exactElementDefinition, searchParams: [exactSearchParam] };\n  }\n\n  // Next best case: Exact match of element definition\n  // Examples: Observation.value\n  // In this case, there could be zero or more search parameters that are a function of the element definition.\n  // So search for those search parameters.\n  if (exactElementDefinition) {\n    const allSearchParams = getSearchParameters(resourceType);\n    let searchParams: SearchParameter[] | undefined = undefined;\n    if (allSearchParams) {\n      // To avoid matching names that happen to be prefixes of other names, e.g. id and identifier,\n      // match ${resourceType}.${name} followed by a non-name character OR the end of the string\n      // Name characters include letters, numbers, underscores, and hyphens\n      const pathRegex = new RegExp(`${resourceType}\\\\.${name.replaceAll('[x]', '')}([^\\\\w-]|$)`);\n\n      searchParams = Object.values(allSearchParams).filter((p) => !!p.expression && pathRegex.test(p?.expression));\n      if (searchParams.length === 0) {\n        searchParams = undefined;\n      }\n    }\n    return { name, elementDefinition: exactElementDefinition, searchParams };\n  }\n\n  // Search parameter case: Exact match of search parameter\n  // Examples: Observation.value-quantity, Patient.email\n  // Here we have a search parameter, but no element definition.\n  // Observation.value-quantity is a search parameter for the Observation.value element.\n  // Patient.email is a search parameter for the Patient.telecom element.\n  // So we need to walk backwards to find the element definition.\n  if (exactSearchParam) {\n    const details = getSearchParameterDetails(resourceType, exactSearchParam);\n    return { name, elementDefinition: details.elementDefinitions?.[0], searchParams: [exactSearchParam] };\n  }\n\n  // Worst case: no element definition and no search parameter.\n  // This is probably a malformed URL that includes an unknown field.\n  // We will render the column header, but all cells will be empty.\n  return { name };\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ScrollArea, Skeleton } from '@mantine/core';\nimport type { JSX, ReactNode } from 'react';\nimport classes from './InfoBar.module.css';\n\nexport interface InfoBarProps {\n  readonly children: ReactNode;\n}\n\nexport function InfoBar(props: InfoBarProps): JSX.Element {\n  return (\n    <ScrollArea>\n      <div className={classes.root}>{props.children}</div>\n    </ScrollArea>\n  );\n}\n\nexport interface InfoBarEntryProps {\n  readonly children: ReactNode;\n}\n\nInfoBar.Entry = function InfoBarEntry(props: InfoBarEntryProps): JSX.Element {\n  return <div className={classes.entry}>{props.children}</div>;\n};\n\nexport interface InfoBarKeyProps {\n  readonly children: ReactNode;\n}\n\nInfoBar.Key = function InfoBarEntry(props: InfoBarKeyProps): JSX.Element {\n  return <div className={classes.key}>{props.children}</div>;\n};\n\nexport interface InfoBarValueProps {\n  readonly children: ReactNode;\n}\n\nInfoBar.Value = function InfoBarEntry(props: InfoBarValueProps): JSX.Element {\n  return <div className={classes.value}>{props.children}</div>;\n};\n\nexport interface InfoBarSkeletonProps {\n  readonly withAvatar?: boolean;\n  readonly entries?: number;\n}\n\nconst SKELETON_VALUE_WIDTHS = [120, 90, 50, 60, 40, 110, 220, 90];\n\n/**\n * Loading placeholder that mirrors the InfoBar layout: an optional avatar followed by\n * key/value entries of varying width.\n * @param props - The skeleton props.\n * @returns The InfoBarSkeleton React node.\n */\nexport function InfoBarSkeleton(props: InfoBarSkeletonProps): JSX.Element {\n  const entries = props.entries ?? 6;\n  return (\n    <ScrollArea>\n      <div data-testid=\"info-bar-skeleton\" className={classes.root}>\n        {props.withAvatar && <Skeleton circle height={56} mr={8} style={{ flexShrink: 0 }} />}\n        {Array.from({ length: entries }, (_, index) => (\n          <InfoBar.Entry key={index}>\n            <Skeleton height={10} width={SKELETON_VALUE_WIDTHS[index % SKELETON_VALUE_WIDTHS.length] * 0.6} mb={8} />\n            <Skeleton height={16} width={SKELETON_VALUE_WIDTHS[index % SKELETON_VALUE_WIDTHS.length]} />\n          </InfoBar.Entry>\n        ))}\n      </div>\n    </ScrollArea>\n  );\n}\n", ".root {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  padding: 8px 10px;\n}\n\n.entry {\n  display: inline-block;\n  margin: 5px 20px 5px 5px;\n}\n\n.key {\n  color: var(--mantine-color-gray-6);\n  text-transform: uppercase;\n  font-size: var(--mantine-font-size-xs);\n  white-space: nowrap;\n}\n\n.value {\n  font-size: var(--mantine-font-size-md);\n  font-weight: 600;\n  margin-left: 0;\n  white-space: nowrap;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Badge, Button, Divider, Group, Loader, Menu, Stack, Tabs, Text, ThemeIcon, Timeline } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { WithId } from '@medplum/core';\nimport { formatDate, formatHumanName, normalizeErrorString } from '@medplum/core';\nimport type {\n  CarePlan,\n  DiagnosticReport,\n  DocumentReference,\n  MedicationRequest,\n  QuestionnaireResponse,\n  Reference,\n  ServiceRequest,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconCheck, IconChevronDown, IconClipboardCheck, IconFlask, IconSend } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport classes from '../ListWithDetailPane/ListWithDetailPane.module.css';\nimport { fetchLabOrderRequisitionDocuments, getHealthGorillaRequisitionId } from './documentReference';\nimport { LabDetailLayout } from './LabDetailLayout';\nimport { LabDocumentSection } from './LabDocumentSection';\nimport {\n  getOrderDisplayText,\n  getOrderStatusColor,\n  getOrderStatusDisplayText,\n  getQuestionnaireResponseRef,\n} from './labOrder';\nimport { LabReportContent } from './LabReportContent';\n\nexport interface LabOrderDetailsProps {\n  order: ServiceRequest;\n  onChange?: (order: WithId<ServiceRequest>) => void;\n  onResume?: () => void;\n  selectedReport?: Reference<DiagnosticReport>;\n}\n\ninterface ProgressStep {\n  id: string;\n  title: string;\n  description: string;\n  icon: JSX.Element;\n  status: 'completed' | 'current' | 'pending';\n  timestamp?: string;\n}\n\nexport function LabOrderDetails(props: LabOrderDetailsProps): JSX.Element {\n  const { order, onChange, onResume, selectedReport } = props;\n  const medplum = useMedplum();\n  const patient = useResource(order.subject);\n  const requester = useResource(order.requester);\n  const selectedReportResource = useResource(selectedReport);\n  const [diagnosticReports, setDiagnosticReports] = useState<DiagnosticReport[]>([]);\n  const [reportsFetched, setReportsFetched] = useState(false);\n  const [labOrderRequisitionDocs, setLabOrderRequisitionDocs] = useState<DocumentReference[]>([]);\n  const [loadingDocs, setLoadingDocs] = useState(false);\n  const [specimenLabelDocs, setSpecimenLabelDocs] = useState<DocumentReference[]>([]);\n  const [loadingSpecimenDocs, setLoadingSpecimenDocs] = useState(false);\n  const [questionnaireResponse, setQuestionnaireResponse] = useState<QuestionnaireResponse | null>(null);\n  const [loadingQuestionnaire, setLoadingQuestionnaire] = useState(false);\n  // Default to the Report tab whenever the caller explicitly selected a report (e.g. clicked one\n  // from a results list) or the order is fully completed - in every other case there's nothing\n  // to show there yet, so default to tracking progress instead. This is only the *initial* tab;\n  // availability of the Report tab itself is governed separately, by whether a report exists (see\n  // primaryReport below) rather than by order status, since a report can exist well before the\n  // order it belongs to is marked completed (e.g. a preliminary or partial result).\n  const [activeDetailTab, setActiveDetailTab] = useState<'report' | 'progress' | 'order'>(\n    selectedReport || order.status === 'completed' ? 'report' : 'progress'\n  );\n\n  const canRevoke = order.status === 'draft' || order.status === 'active' || order.status === 'on-hold';\n  const isDraft = order.status === 'draft';\n  const hideProgress = isDraft || order.status === 'revoked';\n\n  const handleRevoke = useCallback(async (): Promise<void> => {\n    try {\n      const updated = await medplum.patchResource('ServiceRequest', order.id as string, [\n        { op: 'replace', path: '/status', value: 'revoked' },\n      ]);\n      onChange?.(updated);\n    } catch (err) {\n      showNotification({ color: 'red', message: normalizeErrorString(err) });\n    }\n  }, [medplum, order.id, onChange]);\n\n  // An order can have more than one DiagnosticReport (e.g. a multi-day culture result resent\n  // with additional findings). When the caller didn't pass a specific selectedReport, fetch just\n  // the most recently updated one to show by default.\n  useEffect(() => {\n    if (selectedReport) {\n      return;\n    }\n\n    const fetchReports = async (): Promise<void> => {\n      const reports = await medplum.searchResources('DiagnosticReport', {\n        'based-on': `ServiceRequest/${order.id}`,\n        _sort: '-_lastUpdated',\n        _count: '1',\n      });\n      setDiagnosticReports(reports);\n      setReportsFetched(true);\n    };\n\n    fetchReports().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [medplum, order.id, selectedReport]);\n\n  // When the caller passed a selectedReport, always show that exact resource - resolved directly\n  // by reference, never substituted with a different report. Otherwise fall back to the most\n  // recently updated report.\n  const latestReport = diagnosticReports.length > 0 ? diagnosticReports[0] : undefined;\n  const primaryReport = selectedReport ? selectedReportResource : latestReport;\n  // While this is true, we don't yet know whether a report exists - keep the Report tab visible\n  // (with a loader) rather than flipping it away only to potentially flip it back once the fetch\n  // resolves, and don't bounce the user off the Report tab just because it isn't resolved yet.\n  const isLoadingPrimaryReport = selectedReport ? selectedReportResource === undefined : !reportsFetched;\n\n  // The tab actually shown, derived from the requested tab plus two corrections:\n  // - once loading finishes with no report found, a request for 'report' has nothing to show, so\n  //   fall back to a tab that does (e.g. a completed order whose report search came back empty);\n  // - 'progress' is requested but genuinely hidden (hideProgress), so fall back to 'order'. This\n  //   never overrides a 'report' request on a draft/revoked order - the report tab's own\n  //   availability is governed separately, by whether a report exists (see primaryReport above),\n  //   so a draft or revoked order with a report (e.g. a preliminary result opened from Completed)\n  //   must still be able to select and view it instead of being stuck on Order Details.\n  let detailTab: 'report' | 'progress' | 'order' = activeDetailTab;\n  if (!isLoadingPrimaryReport && !primaryReport && activeDetailTab === 'report') {\n    detailTab = hideProgress ? 'order' : 'progress';\n  } else if (hideProgress && activeDetailTab === 'progress') {\n    detailTab = 'order';\n  }\n\n  // Progress tracker logic\n  const getProgressSteps = useMemo((): ProgressStep[] => {\n    const steps: ProgressStep[] = [\n      {\n        id: 'order-sent',\n        title: 'Order Sent',\n        description: 'Lab order has been submitted',\n        icon: <IconSend size={16} />,\n        status: 'completed',\n        timestamp:\n          order.authoredOn || order.meta?.lastUpdated\n            ? formatDate(order.authoredOn || order.meta?.lastUpdated)\n            : undefined,\n      },\n      {\n        id: 'lab-acknowledged',\n        title: 'Order Acknowledged',\n        description: 'Lab has received and acknowledged the order',\n        icon: <IconCheck size={16} />,\n        status: 'pending',\n      },\n      {\n        id: 'testing',\n        title: 'Testing',\n        description: 'Lab is processing the sample',\n        icon: <IconFlask size={16} />,\n        status: 'pending',\n      },\n      {\n        id: 'final',\n        title: 'Final',\n        description: 'Results are ready',\n        icon: <IconClipboardCheck size={16} />,\n        status: 'pending',\n      },\n    ];\n\n    // Determine current step based on available data\n    let currentStepIndex = 0;\n\n    // Step 1: Order Sent - always completed if order exists\n    if (order.authoredOn) {\n      currentStepIndex = 1;\n    }\n\n    // Step 2: Lab Acknowledged - presence of accession number or LabOrderRequisition\n    if (order.requisition?.value || labOrderRequisitionDocs.length > 0) {\n      steps[1].status = 'completed';\n      steps[1].timestamp = order.requisition?.value ? 'Acknowledged' : undefined;\n      currentStepIndex = 2;\n    }\n\n    // Step 3: Testing - DiagnosticReport.effectiveDateTime\n    if (primaryReport?.effectiveDateTime) {\n      steps[2].status = 'completed';\n      steps[2].timestamp = formatDate(primaryReport.effectiveDateTime);\n      currentStepIndex = 3;\n    }\n\n    // Step 4: Final - DiagnosticReport.issued timestamp\n    if (primaryReport?.issued && primaryReport.status === 'final') {\n      steps[3].status = 'completed';\n      steps[3].timestamp = formatDate(primaryReport.issued);\n      currentStepIndex = 4;\n    }\n\n    // Set current step\n    if (currentStepIndex < steps.length) {\n      steps[currentStepIndex].status = 'current';\n    }\n\n    return steps;\n  }, [order, primaryReport, labOrderRequisitionDocs]);\n\n  // Helper function to get step color\n  const getStepColor = (status: 'completed' | 'current' | 'pending'): string => {\n    if (status === 'completed') {\n      return 'green';\n    }\n    if (status === 'current') {\n      return 'blue';\n    }\n    return 'gray.2';\n  };\n\n  // Fetch Lab Order Requisition documents when order changes\n  useEffect(() => {\n    const fetchDocuments = async (): Promise<void> => {\n      if (!order.id) {\n        setLabOrderRequisitionDocs([]);\n        return;\n      }\n      setLoadingDocs(true);\n      setLabOrderRequisitionDocs([]); // Clear previous documents immediately\n\n      try {\n        const docs = await fetchLabOrderRequisitionDocuments(medplum, order);\n        setLabOrderRequisitionDocs(docs);\n      } catch (error) {\n        console.error('Error fetching lab order requisition documents:', error);\n        setLabOrderRequisitionDocs([]);\n      } finally {\n        setLoadingDocs(false);\n      }\n    };\n\n    fetchDocuments().catch(console.error);\n\n    // Cleanup function to clear documents when component unmounts or order changes\n    return () => {\n      setLabOrderRequisitionDocs([]);\n      setLoadingDocs(false);\n    };\n  }, [medplum, order]);\n\n  // Fetch Specimen Label documents when order changes\n  useEffect(() => {\n    const fetchSpecimenLabelDocuments = async (): Promise<void> => {\n      if (!order.id) {\n        setSpecimenLabelDocs([]);\n        return;\n      }\n      setLoadingSpecimenDocs(true);\n      setSpecimenLabelDocs([]); // Clear previous documents immediately\n\n      try {\n        // Extract Health Gorilla Requisition ID from ServiceRequest (same as requisition docs)\n        const healthGorillaRequisitionId = getHealthGorillaRequisitionId(order);\n\n        if (!healthGorillaRequisitionId) {\n          setSpecimenLabelDocs([]);\n          return;\n        }\n\n        // Search for DocumentReference with category \"SpecimenLabel\" using the same identifier pattern\n        const searchParams = new URLSearchParams({\n          category: 'SpecimenLabel',\n          identifier: `https://www.healthgorilla.com|${healthGorillaRequisitionId}`,\n          _sort: '-_lastUpdated',\n        });\n\n        const searchResult = await medplum.searchResources('DocumentReference', searchParams, { cache: 'no-cache' });\n        setSpecimenLabelDocs(searchResult);\n      } catch (error) {\n        console.error('Error fetching specimen label documents:', error);\n        setSpecimenLabelDocs([]);\n      } finally {\n        setLoadingSpecimenDocs(false);\n      }\n    };\n\n    fetchSpecimenLabelDocuments().catch(console.error);\n\n    // Cleanup function to clear documents when component unmounts or order changes\n    return () => {\n      setSpecimenLabelDocs([]);\n      setLoadingSpecimenDocs(false);\n    };\n  }, [medplum, order]);\n\n  // Fetch QuestionnaireResponse when order changes\n  useEffect(() => {\n    const fetchQuestionnaireResponse = async (): Promise<void> => {\n      setQuestionnaireResponse(null);\n\n      // First, check if current order has QuestionnaireResponse in supportingInfo\n      const currentRef = getQuestionnaireResponseRef(order);\n      if (currentRef?.reference) {\n        try {\n          setLoadingQuestionnaire(true);\n          setQuestionnaireResponse(await medplum.readReference(currentRef as Reference<QuestionnaireResponse>));\n          return;\n        } catch (error) {\n          console.error('Error fetching questionnaire response from current order:', error);\n        } finally {\n          setLoadingQuestionnaire(false);\n        }\n      }\n\n      // For HealthGorilla case: if no QuestionnaireResponse found in current order,\n      // search for the original ServiceRequest that has this ServiceRequest in its basedOn field\n      // This applies to both open and completed orders\n      if (order.id) {\n        try {\n          setLoadingQuestionnaire(true);\n\n          // Search for ServiceRequests for the same patient with the same code to narrow down results\n          const searchResult = await medplum.searchResources('ServiceRequest', {\n            subject: order.subject?.reference,\n            code: order.code?.coding?.[0]?.code, // Include the same code to narrow down results\n            _count: 50, // Get more results to filter through\n          });\n\n          // Prefer the ServiceRequest that has this order in its basedOn field and a QuestionnaireResponse;\n          // otherwise fall back to any ServiceRequest with a QuestionnaireResponse\n          const withQuestionnaire = searchResult.filter((sr) => getQuestionnaireResponseRef(sr));\n          const sourceOrder =\n            withQuestionnaire.find((sr) =>\n              sr.basedOn?.some(\n                (ref: Reference<CarePlan | ServiceRequest | MedicationRequest>) =>\n                  ref.reference === `ServiceRequest/${order.id}`\n              )\n            ) ?? withQuestionnaire[0];\n          const sourceRef = getQuestionnaireResponseRef(sourceOrder);\n          if (sourceRef?.reference) {\n            setQuestionnaireResponse(await medplum.readReference(sourceRef as Reference<QuestionnaireResponse>));\n          }\n        } catch (error) {\n          console.error('Error fetching questionnaire response from original order:', error);\n        } finally {\n          setLoadingQuestionnaire(false);\n        }\n      }\n    };\n\n    fetchQuestionnaireResponse().catch(console.error);\n\n    // Cleanup function\n    return () => {\n      setQuestionnaireResponse(null);\n      setLoadingQuestionnaire(false);\n    };\n  }, [medplum, order]);\n\n  return (\n    <LabDetailLayout\n      title={getOrderDisplayText(order)}\n      subtitle={\n        order.status === 'completed' && order.meta?.lastUpdated\n          ? `Completed ${formatDate(order.meta.lastUpdated)} \u2022 Ordered ${formatDate(order.authoredOn || order.meta?.lastUpdated)}`\n          : `Ordered ${formatDate(order.authoredOn || order.meta?.lastUpdated)}`\n      }\n      actions={\n        <Group justify=\"space-between\" align=\"center\">\n          <Tabs\n            value={detailTab}\n            onChange={(value) => setActiveDetailTab(value as 'report' | 'progress' | 'order')}\n            variant=\"unstyled\"\n            className={classes.pillTabs}\n          >\n            <Tabs.List>\n              {(isLoadingPrimaryReport || primaryReport) && <Tabs.Tab value=\"report\">Report</Tabs.Tab>}\n              {!hideProgress && <Tabs.Tab value=\"progress\">Progress Tracker</Tabs.Tab>}\n              <Tabs.Tab value=\"order\">Order Details</Tabs.Tab>\n            </Tabs.List>\n          </Tabs>\n          <Menu position=\"bottom-end\" shadow=\"md\">\n            <Menu.Target>\n              <Button\n                variant=\"light\"\n                color={getOrderStatusColor(order.status)}\n                rightSection={canRevoke ? <IconChevronDown size={16} /> : undefined}\n                radius=\"xl\"\n                size=\"sm\"\n              >\n                {getOrderStatusDisplayText(order.status)}\n              </Button>\n            </Menu.Target>\n            {canRevoke && (\n              <Menu.Dropdown>\n                {isDraft && onResume && <Menu.Item onClick={onResume}>Active</Menu.Item>}\n                <Menu.Item onClick={() => handleRevoke().catch(console.error)}>Revoked</Menu.Item>\n              </Menu.Dropdown>\n            )}\n          </Menu>\n        </Group>\n      }\n    >\n      {/* Order Details Tab Content */}\n      {detailTab === 'order' && (\n        <Stack gap=\"md\">\n          <Stack gap=\"sm\" mb=\"xl\">\n            <DetailRow label=\"Order Date\">\n              <Text size=\"sm\">{formatDate(order.authoredOn || order.meta?.lastUpdated)}</Text>\n            </DetailRow>\n\n            {order.code?.coding && (\n              <DetailRow label=\"Test Code\">\n                <Stack gap=\"xs\">\n                  {order.code.coding.map((coding, index) => (\n                    <Text key={index} size=\"sm\">\n                      {coding.display} ({coding.code})\n                    </Text>\n                  ))}\n                </Stack>\n              </DetailRow>\n            )}\n\n            {requester?.resourceType === 'Practitioner' && (\n              <DetailRow label=\"Ordering provider\">\n                <Text size=\"sm\">{formatHumanName(requester.name?.[0])}</Text>\n              </DetailRow>\n            )}\n\n            {order.performer?.[0]?.display && (\n              <DetailRow label=\"Performing lab\">\n                <Text size=\"sm\">{order.performer[0].display}</Text>\n              </DetailRow>\n            )}\n\n            {order.requisition?.value && (\n              <DetailRow label=\"Requisition ID\">\n                <Text size=\"sm\">{order.requisition.value}</Text>\n              </DetailRow>\n            )}\n\n            {patient?.resourceType === 'Patient' && (\n              <DetailRow label=\"Patient\">\n                <Text size=\"sm\">{formatHumanName(patient.name?.[0])}</Text>\n              </DetailRow>\n            )}\n\n            {order.priority && (\n              <DetailRow label=\"Priority\">\n                <Text size=\"sm\">{order.priority}</Text>\n              </DetailRow>\n            )}\n\n            {order.reasonCode && (\n              <DetailRow label=\"Reason\">\n                <Stack gap=\"xs\">\n                  {order.reasonCode.map((reason, index) => (\n                    <Text key={index} size=\"sm\">\n                      {reason.text || reason.coding?.[0]?.display}\n                    </Text>\n                  ))}\n                </Stack>\n              </DetailRow>\n            )}\n\n            {order.note && (\n              <DetailRow label=\"Notes\">\n                <Stack gap=\"xs\">\n                  {order.note.map((note, index) => (\n                    <Text key={index} size=\"sm\">\n                      {note.text}\n                    </Text>\n                  ))}\n                </Stack>\n              </DetailRow>\n            )}\n\n            {order.orderDetail && (\n              <>\n                <Divider />\n                <Stack gap=\"sm\">\n                  <Text fw={800} size=\"lg\">\n                    Order Details\n                  </Text>\n                  {order.orderDetail.map((detail, index) => (\n                    <Group key={index} align=\"flex-start\">\n                      <Text fw={500} size=\"sm\">\n                        Detail {index + 1}:\n                      </Text>\n                      <Text size=\"sm\">{detail.text || detail.coding?.[0]?.display}</Text>\n                    </Group>\n                  ))}\n                </Stack>\n              </>\n            )}\n          </Stack>\n\n          <Divider />\n          <LabDocumentSection\n            title=\"Requisition Document\"\n            loading={loadingDocs}\n            loadingText=\"Loading requisition documents...\"\n            emptyText=\"No lab order requisition documents found.\"\n            docs={labOrderRequisitionDocs}\n          />\n\n          {/* Order Entry Questions - show when QuestionnaireResponse is linked */}\n          {questionnaireResponse && (\n            <>\n              <Divider />\n              <Stack gap=\"md\" mb=\"xl\">\n                <Text fw={800} size=\"md\">\n                  Order Entry Questions\n                </Text>\n\n                {loadingQuestionnaire && (\n                  <Group>\n                    <Loader size=\"sm\" />\n                    <Text size=\"sm\" c=\"dimmed\">\n                      Loading questionnaire response...\n                    </Text>\n                  </Group>\n                )}\n\n                {!loadingQuestionnaire && questionnaireResponse && (\n                  <Stack gap=\"sm\">\n                    {questionnaireResponse.item && questionnaireResponse.item.length > 0 ? (\n                      questionnaireResponse.item.map((item, index) => (\n                        <Group key={index} align=\"flex-start\" style={{ alignItems: 'flex-start' }} gap=\"lg\">\n                          <div style={{ width: '150px', flexShrink: 0 }}>\n                            <Text fw={500} size=\"sm\" c=\"dimmed\">\n                              {item.text || item.linkId || `Question ${index + 1}`}\n                            </Text>\n                          </div>\n                          <div style={{ flex: 1 }}>\n                            {item.answer && item.answer.length > 0 ? (\n                              <Stack gap=\"xs\">\n                                {item.answer.map((answer, answerIndex) => {\n                                  // Extract the answer value based on FHIR QuestionnaireResponse answer types\n                                  let answerText = 'No answer provided';\n\n                                  if (answer.valueString) {\n                                    answerText = answer.valueString;\n                                  } else if (answer.valueCoding?.display) {\n                                    answerText = answer.valueCoding.display;\n                                  } else if (answer.valueCoding?.code) {\n                                    answerText = `${answer.valueCoding.code}${answer.valueCoding.display ? ` - ${answer.valueCoding.display}` : ''}`;\n                                  } else if (answer.valueBoolean !== undefined) {\n                                    answerText = answer.valueBoolean.toString();\n                                  } else if (answer.valueInteger !== undefined) {\n                                    answerText = answer.valueInteger.toString();\n                                  } else if (answer.valueDecimal !== undefined) {\n                                    answerText = answer.valueDecimal.toString();\n                                  } else if (answer.valueDate) {\n                                    answerText = answer.valueDate;\n                                  } else if (answer.valueDateTime) {\n                                    answerText = answer.valueDateTime;\n                                  } else if (answer.valueTime) {\n                                    answerText = answer.valueTime;\n                                  } else if (answer.valueUri) {\n                                    answerText = answer.valueUri;\n                                  } else if (answer.valueQuantity) {\n                                    answerText = `${answer.valueQuantity.value}${answer.valueQuantity.unit ? ` ${answer.valueQuantity.unit}` : ''}`;\n                                  } else if (answer.valueReference?.display) {\n                                    answerText = answer.valueReference.display;\n                                  } else if (answer.valueReference?.reference) {\n                                    answerText = answer.valueReference.reference;\n                                  } else if (answer.valueAttachment?.title) {\n                                    answerText = answer.valueAttachment.title;\n                                  } else if (answer.valueAttachment?.url) {\n                                    answerText = answer.valueAttachment.url;\n                                  }\n\n                                  return (\n                                    <Text key={answerIndex} size=\"sm\">\n                                      {answerText}\n                                    </Text>\n                                  );\n                                })}\n                              </Stack>\n                            ) : (\n                              <Text size=\"sm\" c=\"dimmed\">\n                                No answer provided\n                              </Text>\n                            )}\n                          </div>\n                        </Group>\n                      ))\n                    ) : (\n                      <Text size=\"sm\" c=\"dimmed\">\n                        No questionnaire items found.\n                      </Text>\n                    )}\n                  </Stack>\n                )}\n              </Stack>\n            </>\n          )}\n\n          <Divider />\n          <LabDocumentSection\n            title=\"Specimen Label\"\n            loading={loadingSpecimenDocs}\n            loadingText=\"Loading specimen label documents...\"\n            emptyText=\"No specimen label documents found.\"\n            docs={specimenLabelDocs}\n          />\n        </Stack>\n      )}\n\n      {/* Progress Tracker Tab Content - for open items */}\n      {detailTab === 'progress' && (\n        <Stack gap=\"md\">\n          <Stack p=\"xl\" align=\"center\">\n            <Timeline\n              active={getProgressSteps.findIndex((step) => step.status === 'current')}\n              bulletSize={24}\n              lineWidth={2}\n              color=\"green\"\n              styles={{\n                root: {\n                  maxWidth: '400px',\n                },\n              }}\n            >\n              {getProgressSteps.map((step, index) => {\n                const nextStep = getProgressSteps[index + 1];\n                const isCurrentToNext = step.status === 'current' && nextStep;\n                const isCompletedToCompleted = step.status === 'completed' && nextStep?.status === 'completed';\n                const isCompletedToCurrent = step.status === 'completed' && nextStep?.status === 'current';\n                const isPendingToPending = step.status === 'pending' && nextStep?.status === 'pending';\n\n                return (\n                  <Timeline.Item\n                    key={step.id}\n                    lineVariant={isCurrentToNext || isPendingToPending ? 'dotted' : 'solid'}\n                    bullet={\n                      <ThemeIcon\n                        size={32}\n                        radius=\"xl\"\n                        color={getStepColor(step.status)}\n                        variant=\"filled\"\n                        style={{\n                          color: step.status === 'pending' ? 'var(--mantine-color-gray-8)' : undefined,\n                        }}\n                        data-completed-to-completed={isCompletedToCompleted ? 'true' : undefined}\n                        data-completed-to-current={isCompletedToCurrent ? 'true' : undefined}\n                      >\n                        {step.icon}\n                      </ThemeIcon>\n                    }\n                    title={\n                      <Group gap=\"xs\" align=\"center\">\n                        <Text fw={step.status === 'current' ? 600 : 500} size=\"sm\">\n                          {step.title}\n                        </Text>\n                        {step.timestamp && (\n                          <Badge size=\"xs\" variant=\"light\" color=\"gray\">\n                            {step.timestamp}\n                          </Badge>\n                        )}\n                      </Group>\n                    }\n                  >\n                    <Text size=\"sm\" c=\"dimmed\">\n                      {step.description}\n                    </Text>\n                  </Timeline.Item>\n                );\n              })}\n            </Timeline>\n          </Stack>\n        </Stack>\n      )}\n\n      {/* Report Tab Content - for completed items */}\n      {detailTab === 'report' && isLoadingPrimaryReport && (\n        <Group justify=\"center\" p=\"xl\">\n          <Loader size=\"sm\" />\n        </Group>\n      )}\n      {detailTab === 'report' && !isLoadingPrimaryReport && primaryReport && (\n        <LabReportContent report={primaryReport} />\n      )}\n    </LabDetailLayout>\n  );\n}\n\nfunction DetailRow({ label, children }: { label: string; children: ReactNode }): JSX.Element {\n  return (\n    <Group align=\"flex-start\" gap=\"lg\">\n      <Text fw={500} size=\"sm\" style={{ width: '150px' }} c=\"dimmed\">\n        {label}\n      </Text>\n      {children}\n    </Group>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient } from '@medplum/core';\nimport type { Attachment, DocumentReference, Observation, Reference, ServiceRequest } from '@medplum/fhirtypes';\n\nconst HEALTH_GORILLA_REQUEST_SYSTEM = 'https://www.healthgorilla.com';\n\n/**\n * Fetches DocumentReference resources with LabOrderRequisition category that match a ServiceRequest's Health Gorilla Requisition ID\n * @param medplum - The Medplum client\n * @param serviceRequest - The ServiceRequest to fetch the DocumentReference for\n * @returns The DocumentReference resources\n */\nexport async function fetchLabOrderRequisitionDocuments(\n  medplum: MedplumClient,\n  serviceRequest: ServiceRequest\n): Promise<DocumentReference[]> {\n  const healthGorillaRequisitionId = getHealthGorillaRequisitionId(serviceRequest);\n\n  if (!healthGorillaRequisitionId) {\n    return [];\n  }\n\n  const searchParams = new URLSearchParams({\n    category: 'LabOrderRequisition',\n    identifier: `${HEALTH_GORILLA_REQUEST_SYSTEM}|${healthGorillaRequisitionId}`,\n    _sort: '-_lastUpdated',\n  });\n\n  const results = await medplum.searchResources('DocumentReference', searchParams, { cache: 'no-cache' });\n  return results;\n}\n\n/**\n * Resolves DiagnosticReport.presentedForm attachments into displayable attachments.\n * Some integrations (e.g. HGDX) set Attachment.url to a DocumentReference reference\n * such as \"DocumentReference/123\" instead of a binary URL. For those entries, fetch\n * the DocumentReference and use its content attachment instead, preferring the\n * content whose contentType matches the presentedForm entry.\n * @param medplum - The Medplum client\n * @param presentedForm - The DiagnosticReport.presentedForm attachments\n * @returns The displayable attachments\n */\nexport async function resolvePresentedFormAttachments(\n  medplum: MedplumClient,\n  presentedForm: Attachment[] | undefined\n): Promise<Attachment[]> {\n  const resolved = await Promise.all(\n    (presentedForm ?? []).map(async (form) => {\n      const docRefId = form.url?.startsWith('DocumentReference/') ? form.url.split('/')[1] : undefined;\n      if (!docRefId) {\n        return form;\n      }\n      try {\n        const docRef = await medplum.readResource('DocumentReference', docRefId);\n        const content =\n          docRef.content?.find((c) => c.attachment?.contentType === form.contentType) ?? docRef.content?.[0];\n        if (!content?.attachment) {\n          return undefined;\n        }\n        return { ...content.attachment, title: form.title ?? content.attachment.title };\n      } catch (error) {\n        console.error('Error resolving presented form document reference:', error);\n        return undefined;\n      }\n    })\n  );\n  return resolved.filter((attachment): attachment is Attachment => !!attachment);\n}\n\n/**\n * Resolves lab-branded PDF(s) attached via Observation.derivedFrom on a DiagnosticReport's\n * result Observations (and any of their hasMember descendants).\n *\n * Health Gorilla usually folds the lab-branded PDF into DiagnosticReport.presentedForm\n * alongside its own generated report, but it doesn't always include it there. Medplum\n * separately (and redundantly) stores the lab-branded PDF via a \"Clinical PDF Report\"\n * Observation's derivedFrom reference, so this is a more reliable source for it than\n * presentedForm alone.\n * @param medplum - The Medplum client\n * @param resultRefs - The DiagnosticReport.result references\n * @returns The displayable attachments, in result/hasMember traversal order\n */\nexport async function resolveDerivedFromAttachments(\n  medplum: MedplumClient,\n  resultRefs: Reference<Observation>[] | undefined\n): Promise<Attachment[]> {\n  const attachments: Attachment[] = [];\n  const visited = new Set<string>();\n\n  async function visit(ref: Reference<Observation>): Promise<void> {\n    if (!ref.reference || visited.has(ref.reference)) {\n      return;\n    }\n    visited.add(ref.reference);\n\n    let observation: Observation;\n    try {\n      observation = await medplum.readReference(ref);\n    } catch (error) {\n      console.error('Error resolving Observation for derivedFrom attachment:', error);\n      return;\n    }\n\n    for (const derived of observation.derivedFrom ?? []) {\n      if (!derived.reference?.startsWith('DocumentReference/')) {\n        continue;\n      }\n      try {\n        const docRef = await medplum.readReference(derived as Reference<DocumentReference>);\n        const attachment = docRef.content?.[0]?.attachment;\n        if (attachment?.url) {\n          attachments.push({ ...attachment, title: derived.display ?? attachment.title });\n        }\n      } catch (error) {\n        console.error('Error resolving derivedFrom document reference:', error);\n      }\n    }\n\n    for (const member of observation.hasMember ?? []) {\n      await visit(member as Reference<Observation>);\n    }\n  }\n\n  for (const ref of resultRefs ?? []) {\n    await visit(ref);\n  }\n\n  return attachments;\n}\n\n/**\n * Extracts the Health Gorilla Requisition ID from a ServiceRequest\n * Looks for the requisition identifier with system \"https://www.healthgorilla.com\"\n * @param serviceRequest - The ServiceRequest to extract the Health Gorilla Requisition ID from\n * @returns The Health Gorilla Requisition ID\n */\nexport function getHealthGorillaRequisitionId(serviceRequest: ServiceRequest): string | undefined {\n  // Check if ServiceRequest has a requisition identifier\n  if (serviceRequest.requisition?.system === HEALTH_GORILLA_REQUEST_SYSTEM) {\n    return serviceRequest.requisition.value;\n  }\n\n  // Also check the identifier array for Health Gorilla identifiers\n  if (serviceRequest.identifier) {\n    const healthGorillaIdentifier = serviceRequest.identifier.find((id) => id.system === HEALTH_GORILLA_REQUEST_SYSTEM);\n    if (healthGorillaIdentifier?.value) {\n      return healthGorillaIdentifier.value;\n    }\n  }\n\n  return undefined;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Paper, ScrollArea, Stack, Text } from '@mantine/core';\nimport type { JSX, ReactNode } from 'react';\n\nexport interface LabDetailLayoutProps {\n  readonly title: ReactNode;\n  readonly subtitle: ReactNode;\n  readonly actions: ReactNode;\n  readonly children: ReactNode;\n}\n\nexport function LabDetailLayout(props: LabDetailLayoutProps): JSX.Element {\n  return (\n    <ScrollArea h=\"100%\">\n      <Paper h=\"100%\">\n        <Stack gap=\"0\">\n          <Stack gap=\"md\" p=\"md\">\n            <Stack gap=\"0\">\n              <Text size=\"xl\" fw={800}>\n                {props.title}\n              </Text>\n              <Text size=\"sm\" c=\"gray.7\">\n                {props.subtitle}\n              </Text>\n            </Stack>\n            <Divider />\n            {props.actions}\n          </Stack>\n          <Stack gap=\"xs\" p=\"md\">\n            {props.children}\n          </Stack>\n        </Stack>\n      </Paper>\n    </ScrollArea>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Loader, Stack, Text } from '@mantine/core';\nimport type { DocumentReference } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport classes from './LabDocumentSection.module.css';\n\nexport interface LabDocumentSectionProps {\n  readonly title: string;\n  readonly loading: boolean;\n  readonly loadingText: string;\n  readonly emptyText: string;\n  readonly docs: DocumentReference[];\n}\n\nexport function LabDocumentSection(props: LabDocumentSectionProps): JSX.Element {\n  const { title, loading, loadingText, emptyText, docs } = props;\n  return (\n    <Stack gap=\"lg\" mb=\"xl\">\n      <Text fw={800} size=\"md\" pb=\"0\">\n        {title}\n      </Text>\n      {loading && (\n        <Group>\n          <Loader size=\"sm\" />\n          <Text size=\"sm\" c=\"dimmed\">\n            {loadingText}\n          </Text>\n        </Group>\n      )}\n\n      {!loading && docs.length > 0 && (\n        <Stack gap=\"md\">\n          {docs.map((doc, index) => (\n            <Stack key={doc.id || index} gap=\"xs\">\n              {doc.content?.map((content, contentIndex) => (\n                <div key={contentIndex} className={classes.frame}>\n                  <AttachmentDisplay value={content.attachment} />\n                </div>\n              ))}\n            </Stack>\n          ))}\n        </Stack>\n      )}\n\n      {!loading && docs.length === 0 && (\n        <Text size=\"sm\" c=\"dimmed\">\n          {emptyText}\n        </Text>\n      )}\n    </Stack>\n  );\n}\n", ".frame {\n  height: 600px;\n  border-radius: 4px;\n  overflow: hidden;\n  border: 1px solid #3c3c3c;\n}\n\n.frame :global([data-testid='attachment-iframe']),\n.frame :global([data-testid='attachment-iframe'] iframe) {\n  height: 600px !important;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Reference, ServiceRequest } from '@medplum/fhirtypes';\n\nexport const getOrderDisplayText = (order: ServiceRequest): string => {\n  // If there are multiple codes (2 or more), show them separated by commas\n  if (order.code?.coding && order.code.coding.length >= 2) {\n    return order.code.coding.map((coding) => coding.display).join(', ');\n  }\n\n  // If there's a text field and only one code, use the text field\n  if (order.code?.text) {\n    return order.code.text;\n  }\n\n  // Otherwise, show the first code or fallback\n  return order.code?.coding?.[0]?.display || 'Lab Order';\n};\n\nexport const getOrderStatusColor = (status: string | undefined): string => {\n  switch (status) {\n    case 'active':\n      return 'blue';\n    case 'draft':\n    case 'requested':\n      return 'yellow';\n    case 'on-hold':\n      return 'orange';\n    case 'revoked':\n    case 'cancelled':\n    case 'entered-in-error':\n      return 'red';\n    case 'completed':\n      return 'green';\n    default:\n      return 'gray';\n  }\n};\n\nexport const getOrderStatusDisplayText = (status: string | undefined): string => {\n  switch (status) {\n    case 'active':\n      return 'Active';\n    case 'draft':\n      return 'Draft';\n    case 'requested':\n      return 'Requested';\n    case 'on-hold':\n      return 'On Hold';\n    case 'revoked':\n      return 'Revoked';\n    case 'cancelled':\n      return 'Cancelled';\n    case 'entered-in-error':\n      return 'Error';\n    case 'completed':\n      return 'Completed';\n    case 'unknown':\n      return 'Unknown';\n    default:\n      return status || 'Unknown';\n  }\n};\n\nexport const getQuestionnaireResponseRef = (order: ServiceRequest | undefined): Reference | undefined =>\n  order?.supportingInfo?.find((ref) => ref.reference?.startsWith('QuestionnaireResponse/'));\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Stack, Text } from '@mantine/core';\nimport type { Attachment, DiagnosticReport } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { DiagnosticReportDisplay } from '../DiagnosticReportDisplay/DiagnosticReportDisplay';\nimport { resolveDerivedFromAttachments, resolvePresentedFormAttachments } from './documentReference';\nimport classes from './LabReportContent.module.css';\n\ninterface LabReportContentProps {\n  report: DiagnosticReport;\n}\n\n/**\n * Renders the content of a lab report: the presented form documents (e.g. the\n * lab's PDF) followed by the structured report results. Shared between the\n * standalone result view and the order's Report tab.\n * @param props - The DiagnosticReport to render.\n * @returns The lab report content.\n */\nexport function LabReportContent(props: LabReportContentProps): JSX.Element {\n  const { report } = props;\n  const medplum = useMedplum();\n  const [labDocumentAttachments, setLabDocumentAttachments] = useState<Attachment[]>([]);\n\n  // Resolve both attachment sources together and commit them in a single state update, so the\n  // list doesn't render with just one source and then visibly reorder once the other resolves.\n  // Health Gorilla doesn't always fold the lab-branded PDF into presentedForm; derivedFrom is a\n  // more reliable fallback source for it, so it's placed first. The two sources often resolve the\n  // *same* lab-branded PDF (Health Gorilla usually folds it into presentedForm too), so de-dupe by\n  // URL before rendering.\n  useEffect(() => {\n    let cancelled = false;\n\n    Promise.allSettled([\n      resolveDerivedFromAttachments(medplum, report.result),\n      resolvePresentedFormAttachments(medplum, report.presentedForm),\n    ])\n      .then(([derivedFromResult, presentedFormResult]) => {\n        if (cancelled) {\n          return;\n        }\n        if (derivedFromResult.status === 'rejected') {\n          console.error('Error resolving derivedFrom attachments:', derivedFromResult.reason);\n        }\n        if (presentedFormResult.status === 'rejected') {\n          console.error('Error resolving presentedForm attachments:', presentedFormResult.reason);\n        }\n        const derivedFromAttachments = derivedFromResult.status === 'fulfilled' ? derivedFromResult.value : [];\n        const presentedFormAttachments = presentedFormResult.status === 'fulfilled' ? presentedFormResult.value : [];\n\n        // Only de-dupe attachments that have a URL to key on; attachments without one\n        // (e.g. a bare presentedForm entry with just a title/contentType) always render.\n        const seenUrls = new Set<string>();\n        const deduped = [...derivedFromAttachments, ...presentedFormAttachments].filter((attachment) => {\n          if (!attachment.url) {\n            return true;\n          }\n          if (seenUrls.has(attachment.url)) {\n            return false;\n          }\n          seenUrls.add(attachment.url);\n          return true;\n        });\n        setLabDocumentAttachments(deduped);\n      })\n      .catch(console.error);\n\n    return () => {\n      cancelled = true;\n      setLabDocumentAttachments([]);\n    };\n  }, [medplum, report]);\n\n  return (\n    <Stack gap=\"sm\" mb=\"xl\">\n      {/* Results PDF */}\n      {labDocumentAttachments.length > 0 && (\n        <Stack gap=\"lg\" mb=\"xl\">\n          <Text fw={800} size=\"md\" pb=\"0\">\n            Lab Document\n          </Text>\n          <Stack gap=\"md\">\n            {labDocumentAttachments.map((form, index) => (\n              <Stack key={index} gap=\"xs\">\n                <div className={classes.attachment}>\n                  <AttachmentDisplay value={form} />\n                </div>\n              </Stack>\n            ))}\n          </Stack>\n        </Stack>\n      )}\n\n      {report.result && report.result.length > 0 && (\n        <Stack pt=\"md\">\n          <DiagnosticReportDisplay value={report} />\n        </Stack>\n      )}\n    </Stack>\n  );\n}\n", ".attachment {\n  height: 600px;\n  border-radius: 4px;\n  overflow: hidden;\n  border: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-dark-4));\n}\n\n/* AttachmentDisplay renders PDFs/text in an iframe that defaults to 400px;\n   force it to fill the fixed-height container. Scoped to this container via\n   the parent class so it does not affect other attachment displays. */\n.attachment :global(div[data-testid='attachment-iframe']),\n.attachment :global(div[data-testid='attachment-iframe'] iframe) {\n  height: 600px !important;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Box, Flex, Stack, Text, Tooltip } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { Filter, SearchRequest, WithId } from '@medplum/core';\nimport { formatSearchQuery, getReferenceString, normalizeErrorString, Operator } from '@medplum/core';\nimport type { DiagnosticReport, Patient, Reference, ServiceRequest } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconPlus } from '@tabler/icons-react';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport type { ListWithDetailPaneTab } from '../ListWithDetailPane/ListWithDetailPane';\nimport { ListWithDetailPane } from '../ListWithDetailPane/ListWithDetailPane';\nimport { LabDetailPane } from './LabDetailPane';\nimport { LabListItem } from './LabListItem';\nimport { LabResultListItem } from './LabResultListItem';\nimport { LabSelectEmpty } from './LabSelectEmpty';\n\nexport type LabTab = 'open' | 'completed' | 'revoked';\nexport type LabItem = WithId<ServiceRequest> | WithId<DiagnosticReport>;\n\nconst DEFAULT_COUNT = 20;\n\nexport interface LabOrdersPanelOrderModalProps {\n  readonly opened: boolean;\n  readonly draftOrder: WithId<ServiceRequest> | undefined;\n  readonly onClose: () => void;\n  readonly onSaved: () => void;\n}\n\n/**\n * LabOrdersPanel lists a patient's lab orders and results, and shows the selected one.\n * It does no routing: the caller derives the search and selection from the URL and navigates.\n * @param patient - The patient whose labs are listed.\n * @param search - The normalized search for the active tab (status, sort, count, offset).\n * @param activeTab - The active tab.\n * @param selectedId - The id of the selected order or result.\n * @param getItemUri - A function to build the URI of a list item.\n * @param onChange - Called with the new search when the page changes.\n * @param completedUri - The URI for the completed tab.\n * @param openUri - The URI for the open tab.\n * @param revokedUri - The URI for the revoked tab.\n * @param onNew - Called after an order is submitted or a draft is saved.\n * @param renderOrderModal - Renders the order modal. Without it, ordering and resuming drafts are hidden.\n */\nexport interface LabOrdersPanelProps {\n  readonly patient: Patient | Reference<Patient> | undefined;\n  readonly search: SearchRequest;\n  readonly activeTab: LabTab;\n  readonly selectedId: string | undefined;\n  readonly getItemUri: (item: LabItem) => string;\n  readonly onChange: (search: SearchRequest) => void;\n  readonly completedUri: string;\n  readonly openUri: string;\n  readonly revokedUri: string;\n  readonly onNew?: () => void;\n  readonly renderOrderModal?: (props: LabOrdersPanelOrderModalProps) => ReactNode;\n}\n\nexport function LabOrdersPanel(props: LabOrdersPanelProps): JSX.Element {\n  const {\n    patient,\n    search,\n    activeTab,\n    selectedId,\n    getItemUri,\n    onChange,\n    completedUri,\n    openUri,\n    revokedUri,\n    onNew,\n    renderOrderModal,\n  } = props;\n  const medplum = useMedplum();\n  const patientReference = patient ? getReferenceString(patient) : undefined;\n  const resourceType = activeTab === 'completed' ? 'DiagnosticReport' : 'ServiceRequest';\n\n  const [items, setItems] = useState<LabItem[]>([]);\n  const [total, setTotal] = useState(0);\n  const [selected, setSelected] = useState<LabItem>();\n  const [loading, setLoading] = useState(false);\n  // The order modal is either closed, creating a new order, or resuming a draft.\n  const [orderModal, setOrderModal] = useState<'new' | WithId<ServiceRequest>>();\n\n  const fetchData = useCallback(async (): Promise<void> => {\n    if (!patientReference) {\n      return;\n    }\n    setLoading(true);\n    try {\n      const filters: Filter[] = [\n        ...(search.filters ?? []),\n        { code: 'subject', operator: Operator.EQUALS, value: patientReference },\n      ];\n      if (activeTab !== 'completed') {\n        // A lab order is a top-level ServiceRequest plus one child ServiceRequest\n        // per test (basedOn the parent), all sharing a requisition. Listing only\n        // top-level requests shows each order once, and keeps the server total\n        // (used for pagination) consistent with the rows displayed.\n        filters.push({ code: 'based-on', operator: Operator.MISSING, value: 'true' });\n      }\n      const fetchQuery: SearchRequest = { ...search, filters, total: 'accurate' };\n      const results = await medplum.searchResources(resourceType, formatSearchQuery(fetchQuery), {\n        cache: 'no-cache',\n      });\n      setItems(results);\n      setTotal(results.bundle?.total ?? results.length);\n    } catch (error) {\n      showNotification({ color: 'red', message: normalizeErrorString(error) });\n    } finally {\n      setLoading(false);\n    }\n  }, [medplum, patientReference, resourceType, search, activeTab]);\n\n  useEffect(() => {\n    fetchData().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [fetchData]);\n\n  // Resolve the selected item from the loaded list, falling back to a read.\n  useEffect(() => {\n    const resolveSelected = async (): Promise<void> => {\n      if (!selectedId) {\n        setSelected(undefined);\n        return;\n      }\n      const found = items.find((item) => item.id === selectedId);\n      if (found) {\n        setSelected(found);\n        return;\n      }\n      setSelected(await medplum.readResource(resourceType, selectedId));\n    };\n    resolveSelected().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [selectedId, items, resourceType, medplum]);\n\n  const tabs = useMemo<ListWithDetailPaneTab[]>(\n    () => [\n      { value: 'completed', label: 'Completed', uri: completedUri },\n      { value: 'open', label: 'Open', uri: openUri },\n      { value: 'revoked', label: 'Revoked', uri: revokedUri },\n    ],\n    [completedUri, openUri, revokedUri]\n  );\n\n  const count = search.count ?? DEFAULT_COUNT;\n  const page = Math.floor((search.offset ?? 0) / count) + 1;\n  const pageCount = Math.max(1, Math.ceil(total / count));\n\n  const handleOrderSaved = useCallback((): void => {\n    setOrderModal(undefined);\n    fetchData()\n      .then(() => onNew?.())\n      .catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n  }, [fetchData, onNew]);\n\n  const headerActions = renderOrderModal && (\n    <Tooltip label=\"Order Labs\" position=\"bottom\" openDelay={500}>\n      <ActionIcon\n        radius=\"xl\"\n        variant=\"filled\"\n        color=\"blue\"\n        size={32}\n        aria-label=\"Order Labs\"\n        onClick={() => setOrderModal('new')}\n      >\n        <IconPlus size={16} />\n      </ActionIcon>\n    </Tooltip>\n  );\n\n  return (\n    <Box w=\"100%\" h=\"100%\">\n      <ListWithDetailPane<LabItem>\n        items={items}\n        loading={loading}\n        selectedKey={selectedId}\n        selected={selected}\n        tabs={tabs}\n        activeTab={activeTab}\n        headerActions={headerActions}\n        emptyList={<EmptyLabsState activeTab={activeTab} />}\n        emptyDetail={<LabSelectEmpty />}\n        page={page}\n        pageCount={pageCount}\n        onPageChange={(newPage) => onChange({ ...search, offset: (newPage - 1) * count })}\n        renderItem={(item, ctx) =>\n          item.resourceType === 'DiagnosticReport' ? (\n            <LabResultListItem report={item} selected={ctx.selected} to={getItemUri(item)} />\n          ) : (\n            <LabListItem\n              item={item}\n              selectedItem={ctx.selected ? item : undefined}\n              activeTab=\"open\"\n              onItemSelect={() => getItemUri(item)}\n            />\n          )\n        }\n        renderDetail={(item) => (\n          <LabDetailPane\n            item={item}\n            onOrderChange={() =>\n              fetchData().catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err) }))\n            }\n            onResumeOrder={renderOrderModal ? setOrderModal : undefined}\n          />\n        )}\n      />\n      {renderOrderModal?.({\n        opened: !!orderModal,\n        draftOrder: orderModal === 'new' ? undefined : orderModal,\n        onClose: () => setOrderModal(undefined),\n        onSaved: handleOrderSaved,\n      })}\n    </Box>\n  );\n}\n\nfunction EmptyLabsState({ activeTab }: { activeTab: LabTab }): JSX.Element {\n  return (\n    <Flex direction=\"column\" h=\"100%\" justify=\"center\" align=\"center\">\n      <Stack align=\"center\" gap=\"md\" pt=\"xl\">\n        <Text size=\"md\" c=\"dimmed\" fw={400}>\n          No {activeTab} labs to display.\n        </Text>\n      </Stack>\n    </Flex>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Center, Loader } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { WithId } from '@medplum/core';\nimport { createReference, isReference, normalizeErrorString } from '@medplum/core';\nimport type { DiagnosticReport, Reference, ServiceRequest } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { LabOrderDetails } from './LabOrderDetails';\nimport { LabResultDetails } from './LabResultDetails';\n\ninterface LabDetailPaneProps {\n  item: WithId<ServiceRequest> | WithId<DiagnosticReport>;\n  onOrderChange?: (order: WithId<ServiceRequest>) => void;\n  onResumeOrder?: (order: WithId<ServiceRequest>) => void;\n}\n\n/**\n * Renders the detail pane for a selected lab item. An order (ServiceRequest)\n * shows the order details. A result (DiagnosticReport) that is based on a\n * ServiceRequest also shows the order details for that request; otherwise it\n * falls back to the result details.\n * @param props - The lab item to render.\n * @returns The detail pane for the given lab item.\n */\nexport function LabDetailPane(props: LabDetailPaneProps): JSX.Element {\n  const { item, onOrderChange, onResumeOrder } = props;\n  const medplum = useMedplum();\n\n  const basedOnRef =\n    item.resourceType === 'DiagnosticReport'\n      ? item.basedOn?.find((ref): ref is Reference<ServiceRequest> => isReference(ref, 'ServiceRequest'))\n      : undefined;\n\n  // A ServiceRequest item is its own order; a DiagnosticReport's order is\n  // fetched from its basedOn reference.\n  const [order, setOrder] = useState<WithId<ServiceRequest> | undefined>(\n    item.resourceType === 'ServiceRequest' ? item : undefined\n  );\n  const [loading, setLoading] = useState<boolean>(!!basedOnRef);\n\n  useEffect(() => {\n    let subscribed = true;\n    const fetchOrder = async (): Promise<void> => {\n      if (item.resourceType === 'ServiceRequest') {\n        setOrder(item);\n        setLoading(false);\n        return;\n      }\n      setOrder(undefined);\n      if (!basedOnRef) {\n        setLoading(false);\n        return;\n      }\n      setLoading(true);\n      try {\n        const result = await medplum.readReference(basedOnRef);\n        if (subscribed) {\n          setOrder(result);\n        }\n      } catch (err) {\n        if (subscribed) {\n          showNotification({ color: 'red', message: normalizeErrorString(err) });\n        }\n      } finally {\n        if (subscribed) {\n          setLoading(false);\n        }\n      }\n    };\n    fetchOrder().catch(console.error);\n    return () => {\n      subscribed = false;\n    };\n  }, [medplum, item, basedOnRef]);\n\n  return (\n    <Box h=\"100%\" flex={1} style={{ overflow: 'hidden' }}>\n      {loading ? (\n        <Center h=\"100%\">\n          <Loader />\n        </Center>\n      ) : (\n        <>\n          {order && (\n            <LabOrderDetails\n              key={`${order.id}:${item.resourceType === 'DiagnosticReport' ? item.id : ''}`}\n              order={order}\n              selectedReport={item.resourceType === 'DiagnosticReport' ? createReference(item) : undefined}\n              onChange={(updated) => {\n                setOrder(updated);\n                onOrderChange?.(updated);\n              }}\n              onResume={onResumeOrder ? () => onResumeOrder(order) : undefined}\n            />\n          )}\n          {!order && item.resourceType === 'DiagnosticReport' && <LabResultDetails key={item.id} result={item} />}\n        </>\n      )}\n    </Box>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Badge, Group } from '@mantine/core';\nimport { formatDate } from '@medplum/core';\nimport type { DiagnosticReport } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { LabDetailLayout } from './LabDetailLayout';\nimport { LabReportContent } from './LabReportContent';\n\nexport interface LabResultDetailsProps {\n  result: DiagnosticReport;\n}\n\nexport function LabResultDetails(props: LabResultDetailsProps): JSX.Element {\n  const { result } = props;\n\n  return (\n    <LabDetailLayout\n      title={<CodeableConceptDisplay value={result.code} />}\n      subtitle={\n        <>\n          Issued {formatDate(result.issued)}\n          {result.effectiveDateTime && ` \u2022 Collected ${formatDate(result.effectiveDateTime)}`}\n        </>\n      }\n      actions={\n        <Group justify=\"flex-end\" align=\"center\">\n          <Badge size=\"lg\" color={getStatusColor(result.status)} variant=\"light\">\n            {getStatusDisplayText(result.status)}\n          </Badge>\n        </Group>\n      }\n    >\n      <LabReportContent report={result} />\n    </LabDetailLayout>\n  );\n}\n\nconst getStatusColor = (status: string | undefined): string => {\n  switch (status) {\n    case 'final':\n      return 'green';\n    case 'partial':\n      return 'yellow';\n    case 'preliminary':\n      return 'blue';\n    case 'cancelled':\n    case 'entered-in-error':\n      return 'red';\n    default:\n      return 'gray';\n  }\n};\n\nconst getStatusDisplayText = (status: string | undefined): string => {\n  switch (status) {\n    case 'final':\n      return 'Final';\n    case 'partial':\n      return 'Partial';\n    case 'preliminary':\n      return 'Preliminary';\n    case 'cancelled':\n      return 'Cancelled';\n    case 'entered-in-error':\n      return 'Error';\n    default:\n      return status || 'Unknown';\n  }\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Badge, Group, Stack, Text } from '@mantine/core';\nimport { formatDate, formatHumanName } from '@medplum/core';\nimport type { Practitioner, ServiceRequest } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport classes from './LabListItem.module.css';\nimport { getOrderDisplayText, getOrderStatusColor, getOrderStatusDisplayText } from './labOrder';\n\ntype LabTab = 'open' | 'completed';\n\ninterface LabListItemProps {\n  item: ServiceRequest;\n  selectedItem: ServiceRequest | undefined;\n  activeTab: LabTab;\n  onItemSelect: (item: ServiceRequest) => string;\n}\n\nexport function LabListItem(props: LabListItemProps): JSX.Element {\n  const { item, selectedItem, activeTab, onItemSelect } = props;\n  const isSelected = selectedItem?.id === item.id;\n  const requester = useResource(item.requester) as Practitioner | undefined;\n\n  return (\n    <MedplumLink to={onItemSelect(item)} underline=\"never\">\n      <Group\n        align=\"center\"\n        wrap=\"nowrap\"\n        className={cx(classes.contentContainer, {\n          [classes.selected]: isSelected,\n        })}\n      >\n        <Stack gap={0} flex={1} miw={0}>\n          <Group justify=\"space-between\" align=\"flex-start\">\n            <Text fw={700} className={classes.title} flex={1}>\n              {getOrderDisplayText(item)}\n            </Text>\n            {activeTab !== 'completed' && (\n              <Badge size=\"sm\" color={getOrderStatusColor(item.status)} variant=\"light\">\n                {getOrderStatusDisplayText(item.status)}\n              </Badge>\n            )}\n          </Group>\n          {getAdditionalInfo(item, activeTab).map((info, index) => (\n            <Text key={index} size=\"sm\">\n              {info}\n            </Text>\n          ))}\n          <Text size=\"sm\" c=\"dimmed\">\n            {getSubText(item, requester)}\n          </Text>\n        </Stack>\n      </Group>\n    </MedplumLink>\n  );\n}\n\nconst getSubText = (item: ServiceRequest, requester: Practitioner | undefined): string => {\n  // Use authoredOn if available, otherwise fall back to meta.lastUpdated\n  const date = formatDate(item.authoredOn || item.meta?.lastUpdated);\n  if (requester?.resourceType === 'Practitioner') {\n    return `Ordered ${date} by ${formatHumanName(requester.name?.[0])}`;\n  }\n  return `Ordered ${date}`;\n};\n\nconst getAdditionalInfo = (item: ServiceRequest, activeTab: LabTab): string[] => {\n  const info: string[] = [];\n\n  if (activeTab === 'completed') {\n    // For completed items, show completion date instead of REQ #\n    const completionDate = item.meta?.lastUpdated ? formatDate(item.meta.lastUpdated) : 'Unknown date';\n    info.push(`Completed ${completionDate}`);\n  } else if (item.requisition?.value) {\n    // For open items, show REQ # as before\n    info.push(`REQ #${item.requisition.value}`);\n  }\n\n  return info;\n};\n", ".content {\n  word-wrap: break-word;\n  overflow-wrap: break-word;\n  white-space: normal;\n  word-break: break-word;\n}\n\n.title {\n  white-space: nowrap !important;\n  overflow: hidden !important;\n  text-overflow: ellipsis !important;\n  width: 100% !important;\n  max-width: 100% !important;\n}\n\n.contentContainer {\n  transition: background 0.2s;\n  cursor: pointer;\n  padding: 0.5rem;\n  border-radius: 0.5rem;\n  color: light-dark(var(--mantine-color-black), var(--mantine-color-gray-2));\n  width: 100%;\n  max-width: 100%;\n  min-width: 0;\n  overflow: hidden;\n}\n\n.contentContainer:hover {\n  background: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-8));\n}\n\n.contentContainer.selected {\n  background: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-8));\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Badge, Group, Stack, Text } from '@mantine/core';\nimport { formatDate, formatHumanName } from '@medplum/core';\nimport type { DiagnosticReport } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport classes from './LabListItem.module.css';\n\ninterface LabResultListItemProps {\n  report: DiagnosticReport;\n  selected: boolean;\n  to: string;\n}\n\nexport function LabResultListItem(props: LabResultListItemProps): JSX.Element {\n  const { report, selected, to } = props;\n  const performer = useResource(report.performer?.[0]);\n  const subText = getSubText(report, performer);\n  const isFinalized = FINALIZED_REPORT_STATUSES.has(report.status);\n  const date = formatDate(report.issued || report.effectiveDateTime || report.meta?.lastUpdated);\n\n  return (\n    <MedplumLink to={to} underline=\"never\">\n      <Group\n        align=\"center\"\n        wrap=\"nowrap\"\n        className={cx(classes.contentContainer, {\n          [classes.selected]: selected,\n        })}\n      >\n        <Stack gap={0} flex={1} miw={0}>\n          <Group justify=\"space-between\" align=\"flex-start\" wrap=\"nowrap\">\n            <Text fw={700} className={classes.title} flex={1}>\n              {getDisplayText(report)}\n            </Text>\n            {!isFinalized && (\n              <Badge size=\"sm\" color=\"yellow\" variant=\"light\">\n                {getReportStatusDisplayText(report.status)}\n              </Badge>\n            )}\n          </Group>\n          <Text size=\"sm\">{isFinalized ? `Completed ${date}` : `Received ${date}`}</Text>\n          {subText && (\n            <Text size=\"sm\" c=\"dimmed\">\n              {subText}\n            </Text>\n          )}\n        </Stack>\n      </Group>\n    </MedplumLink>\n  );\n}\n\n// A result can still be useful to a clinician before it's finalized (e.g. an interim value from\n// a multi-day culture), which is why it's listed here at all - but it must stay visually distinct\n// from a final result, or there's no way to tell the two apart without opening it.\nconst FINALIZED_REPORT_STATUSES = new Set<DiagnosticReport['status']>(['final', 'corrected', 'amended']);\n\nconst getReportStatusDisplayText = (status: DiagnosticReport['status']): string => {\n  return status === 'partial' ? 'Partial' : 'Preliminary';\n};\n\nconst getDisplayText = (report: DiagnosticReport): string => {\n  // If there are multiple codes (2 or more), show them separated by commas\n  if (report.code?.coding && report.code.coding.length >= 2) {\n    return report.code.coding.map((coding) => coding.display).join(', ');\n  }\n\n  // If there's a text field and only one code, use the text field\n  if (report.code?.text) {\n    return report.code.text;\n  }\n\n  // Otherwise, show the first code or fallback\n  return report.code?.coding?.[0]?.display || 'Lab Result';\n};\n\nconst getSubText = (report: DiagnosticReport, performer: ReturnType<typeof useResource>): string => {\n  if (performer?.resourceType === 'Practitioner') {\n    return `Performed by ${formatHumanName(performer.name?.[0])}`;\n  }\n  if (performer?.resourceType === 'Organization' && performer.name) {\n    return performer.name;\n  }\n  const collected = formatDate(report.effectiveDateTime);\n  return collected ? `Collected ${collected}` : '';\n};\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Flex, Stack, Text } from '@mantine/core';\nimport type { JSX } from 'react';\n\nexport function LabSelectEmpty(): JSX.Element {\n  return (\n    <Flex direction=\"column\" h=\"100%\" justify=\"center\" align=\"center\">\n      <Stack align=\"center\" gap=\"md\" pt=\"xl\">\n        <Text size=\"md\" c=\"dimmed\" fw={400}>\n          Lab details will appear here when selected.\n        </Text>\n      </Stack>\n    </Flex>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { TabsProps } from '@mantine/core';\nimport { Anchor, Tabs } from '@mantine/core';\nimport { isString, locationUtils } from '@medplum/core';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport type { JSX, MouseEvent } from 'react';\nimport { useState } from 'react';\nimport { isAuxClick } from '../utils/dom';\nimport styles from './LinkTabs.module.css';\n\nexport interface TabDefinition {\n  readonly label: string;\n  readonly value: string;\n}\n\nexport interface LinkTabsProps extends Omit<TabsProps, 'value' | 'onChange'> {\n  readonly baseUrl: string;\n  readonly tabs: string[] | TabDefinition[];\n  readonly children?: React.ReactNode;\n}\n\nexport function LinkTabs(props: LinkTabsProps): JSX.Element {\n  const { baseUrl, tabs: tabDefinitions, children, ...rest } = props;\n  const tabs = normalizeTabDefinitions(tabDefinitions);\n  const navigate = useMedplumNavigate();\n\n  const [currentTab, setCurrentTab] = useState(() => {\n    const segment = locationUtils.getPathname().split('/').pop();\n    if (segment) {\n      const segmentLower = segment.toLowerCase();\n      const matched = tabs.find((t) => t.value.split(/[?#]/)[0].toLowerCase() === segmentLower);\n      if (matched) {\n        return matched.value;\n      }\n    }\n    return tabs[0].value;\n  });\n\n  function onTabChange(newTabName: string | null): void {\n    newTabName = newTabName || tabs[0].value;\n    setCurrentTab(newTabName);\n    navigate(`${baseUrl}/${newTabName}`);\n  }\n\n  return (\n    <Tabs value={currentTab} onChange={onTabChange} {...rest}>\n      <Tabs.List className={styles.list}>\n        {tabs.map((t) => (\n          <Tabs.Tab key={t.value} value={t.value}>\n            <Anchor className={styles.link} href={`${baseUrl}/${t.value}`} onClick={onLinkClick}>\n              {t.label}\n            </Anchor>\n          </Tabs.Tab>\n        ))}\n      </Tabs.List>\n      {children}\n    </Tabs>\n  );\n}\n\nfunction normalizeTabDefinitions(tabs: string[] | TabDefinition[]): TabDefinition[] {\n  return tabs.map((t) => (isString(t) ? { label: t, value: t.toLowerCase() } : t));\n}\n\nfunction onLinkClick(e: MouseEvent): void {\n  if (!isAuxClick(e)) {\n    e.preventDefault();\n  }\n}\n", ".list {\n  white-space: nowrap;\n  flex-wrap: nowrap;\n}\n\n.link {\n  color: var(--mantine-color-text);\n  line-height: 1;\n  text-decoration: none;\n\n  &:hover {\n    text-decoration: none;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, SimpleGrid } from '@mantine/core';\nimport type { MeasureReport, MeasureReportGroup, Reference } from '@medplum/fhirtypes';\nimport { useResource, useSearchOne } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { MeasureReportGroupDisplay, MeasureTitle } from './MeasureReportGroupDisplay/MeasureReportGroupDisplay';\n\nexport interface MeasureReportDisplayProps {\n  readonly measureReport: MeasureReport | Reference<MeasureReport>;\n}\n\nexport function MeasureReportDisplay(props: MeasureReportDisplayProps): JSX.Element | null {\n  const report = useResource(props.measureReport);\n  const [measure] = useSearchOne('Measure', { url: report?.measure });\n\n  if (!report) {\n    return null;\n  }\n\n  return (\n    <Box>\n      {measure && <MeasureTitle measure={measure} />}\n      <SimpleGrid cols={{ base: 3, sm: 1 }} spacing={{ base: 'md', sm: 'sm' }}>\n        {report.group?.map((group: MeasureReportGroup, idx: number) => (\n          <MeasureReportGroupDisplay key={group.id ?? idx} group={group} />\n        ))}\n      </SimpleGrid>\n    </Box>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Paper, RingProgress, Text, Title } from '@mantine/core';\nimport { formatCodeableConcept } from '@medplum/core';\nimport type { Measure, MeasureReportGroup } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { QuantityDisplay } from '../../QuantityDisplay/QuantityDisplay';\n\ninterface MeasureReportGroupDisplayProps {\n  readonly group: MeasureReportGroup;\n}\n\ninterface MeasureProps {\n  readonly measure: Measure;\n}\n\nexport function MeasureReportGroupDisplay(props: MeasureReportGroupDisplayProps): JSX.Element | null {\n  const { group } = props;\n  return (\n    <Paper withBorder radius=\"md\" p=\"xs\" display=\"flex\" style={{ alignItems: 'center', justifyContent: 'center' }}>\n      <Group>\n        {group.measureScore && <MeasureScore group={group} />}\n        {!group.measureScore && <MeasureReportPopulation group={group} />}\n      </Group>\n    </Paper>\n  );\n}\n\nexport function MeasureTitle(props: MeasureProps): JSX.Element {\n  const { measure } = props;\n  return (\n    <>\n      <Text fz=\"md\" fw={500} mb={8}>\n        {measure.title}\n      </Text>\n      <Text fz=\"xs\" c=\"dimmed\" mb={8}>\n        {measure.subtitle}\n      </Text>\n    </>\n  );\n}\n\nfunction MeasureReportPopulation(props: MeasureReportGroupDisplayProps): JSX.Element {\n  const { group } = props;\n  const populations = group.population;\n  const numerator = populations?.find((p: any) => formatCodeableConcept(p.code) === 'numerator');\n  const denominator = populations?.find((p: any) => formatCodeableConcept(p.code) === 'denominator');\n\n  const numeratorCount = numerator?.count;\n  const denominatorCount = denominator?.count;\n\n  if (denominatorCount === 0) {\n    return (\n      <Box>\n        <Title order={3}>Not Applicable</Title>\n        <Text>{`Denominator: ${denominatorCount}`}</Text>\n      </Box>\n    );\n  }\n\n  if (numeratorCount === undefined || denominatorCount === undefined) {\n    return (\n      <Box>\n        <Title order={3}>Insufficient Data</Title>\n        <Text>{`Numerator: ${numeratorCount}`}</Text>\n        <Text>{`Denominator: ${denominatorCount}`}</Text>\n      </Box>\n    );\n  }\n\n  const value = (numeratorCount / denominatorCount) * 100;\n  return (\n    <RingProgress\n      size={120}\n      thickness={12}\n      roundCaps\n      sections={[{ value: value, color: groupColor(value) }]}\n      label={\n        <Flex justify=\"center\">\n          <Text fw={700} fz={18}>\n            {numeratorCount} / {denominatorCount}\n          </Text>\n        </Flex>\n      }\n    />\n  );\n}\n\nfunction MeasureScore(props: MeasureReportGroupDisplayProps): JSX.Element {\n  const { group } = props;\n  const unit = group.measureScore?.unit ?? group.measureScore?.code;\n\n  return (\n    <>\n      {unit === '%' ? (\n        <RingProgress\n          size={120}\n          thickness={12}\n          roundCaps\n          sections={[{ value: groupValue(group), color: groupColor(group?.measureScore?.value ?? 0) }]}\n          label={\n            <Flex justify=\"center\">\n              <Text fw={700} fz={18}>\n                <QuantityDisplay value={group.measureScore} />\n              </Text>\n            </Flex>\n          }\n        />\n      ) : (\n        <Flex h={120} align=\"center\">\n          <Title order={3}>\n            <QuantityDisplay value={group.measureScore} />\n          </Title>\n        </Flex>\n      )}\n    </>\n  );\n}\n\nfunction groupValue(group: MeasureReportGroup): number {\n  const score = group.measureScore?.value;\n  const unit = group.measureScore?.unit;\n  if (!score) {\n    return 0;\n  }\n  if (score <= 1 && unit === '%') {\n    return score * 100;\n  }\n  return score;\n}\n\nfunction groupColor(score: number): string {\n  if (score <= 33) {\n    return 'red';\n  }\n  if (score <= 67) {\n    return 'yellow';\n  }\n  return 'green';\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Indicator, Tooltip } from '@mantine/core';\nimport type { ResourceType } from '@medplum/fhirtypes';\nimport { useNotificationCount } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\n\nexport interface NotificationIconProps {\n  readonly iconComponent: JSX.Element;\n  readonly label?: string;\n  readonly tooltip?: string;\n  readonly resourceType: ResourceType;\n  readonly countCriteria: string;\n  readonly subscriptionCriteria: string;\n  readonly onClick?: () => void;\n}\n\nexport function NotificationIcon(props: NotificationIconProps): JSX.Element {\n  const { resourceType, countCriteria, subscriptionCriteria } = props;\n  const unreadCount = useNotificationCount({ resourceType, countCriteria, subscriptionCriteria });\n\n  // Start with the inner icon component\n  let result: JSX.Element = props.iconComponent;\n\n  // If there is an onClick handler, wrap the icon in an ActionIcon\n  if (props.onClick) {\n    result = (\n      <ActionIcon variant=\"subtle\" color=\"gray\" size=\"lg\" aria-label={props.label} onClick={props.onClick}>\n        {result}\n      </ActionIcon>\n    );\n  }\n\n  // If there is a tooltip, wrap the icon in a Tooltip\n  if (props.tooltip) {\n    result = <Tooltip label={props.tooltip}>{result}</Tooltip>;\n  }\n\n  // If there is an unread count, add an Indicator\n  if (unreadCount > 0) {\n    result = (\n      <Indicator inline label={unreadCount.toLocaleString()} size={16} offset={2} position=\"bottom-end\" color=\"red\">\n        {result}\n      </Indicator>\n    );\n  }\n\n  return result;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport {\n  ActionIcon,\n  Alert,\n  Badge,\n  Box,\n  Button,\n  Checkbox,\n  Divider,\n  Group,\n  Modal,\n  Stack,\n  Table,\n  Text,\n  Title,\n} from '@mantine/core';\nimport { notifications } from '@mantine/notifications';\nimport { extractAccountReferences, normalizeErrorString } from '@medplum/core';\nimport type { Patient, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconCheck, IconMinus, IconPlus, IconX } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useMemo, useState } from 'react';\nimport { ReferenceInput } from '../ReferenceInput/ReferenceInput';\nimport { ResourceBadge } from '../ResourceBadge/ResourceBadge';\n\nexport interface PatientAccountsFormProps {\n  readonly patient: Patient;\n  readonly onSaved?: () => void;\n}\n\nconst NOTIFICATION_ID = 'patient-accounts';\nconst NOTIFICATION_TITLE = 'Patient Accounts';\nconst ACCOUNT_TARGET_TYPES: ResourceType[] = ['Organization', 'HealthcareService', 'CareTeam'];\n\ninterface AccountChange {\n  readonly reference: Reference;\n  readonly type: 'addition' | 'removal';\n}\n\nexport function PatientAccountsForm(props: PatientAccountsFormProps): JSX.Element {\n  const { patient } = props;\n  const medplum = useMedplum();\n  const isAdmin = medplum.isProjectAdmin() || medplum.isSuperAdmin();\n\n  const originalAccounts = useMemo<Reference[]>(() => extractAccountReferences(patient.meta) ?? [], [patient.meta]);\n\n  const [pendingAccounts, setPendingAccounts] = useState(originalAccounts);\n  const [confirmModalOpen, setConfirmModalOpen] = useState(false);\n  const [propagate, setPropagate] = useState(true);\n  const [saving, setSaving] = useState(false);\n\n  const changes = useMemo<AccountChange[]>(() => {\n    const result: AccountChange[] = [];\n\n    // Find additions (in pending but not in original)\n    for (const account of pendingAccounts) {\n      if (!originalAccounts.some((o) => o.reference === account.reference)) {\n        result.push({ reference: account, type: 'addition' });\n      }\n    }\n\n    // Find removals (in original but not in pending)\n    for (const account of originalAccounts) {\n      if (!pendingAccounts.some((p) => p.reference === account.reference)) {\n        result.push({ reference: account, type: 'removal' });\n      }\n    }\n\n    return result;\n  }, [originalAccounts, pendingAccounts]);\n\n  const hasChanges = changes.length > 0;\n\n  const handleAddAccount = useCallback(\n    (value: Reference | undefined) => {\n      if (!value?.reference) {\n        return;\n      }\n      // Don't add duplicates\n      if (pendingAccounts.some((a) => a.reference === value.reference)) {\n        return;\n      }\n      setPendingAccounts((prev) => [...prev, value]);\n    },\n    [pendingAccounts]\n  );\n\n  const handleRemoveAccount = useCallback((referenceString: string) => {\n    setPendingAccounts((prev) => prev.filter((a) => a.reference !== referenceString));\n  }, []);\n\n  const handleSave = useCallback(async () => {\n    const patientId = patient.id;\n    if (!patientId) {\n      notifications.show({\n        id: NOTIFICATION_ID,\n        title: NOTIFICATION_TITLE,\n        color: 'red',\n        message: 'Cannot update accounts: Patient resource has no ID.',\n        icon: <IconX size=\"1rem\" />,\n        autoClose: false,\n        withCloseButton: true,\n      });\n      return;\n    }\n\n    setSaving(true);\n    setConfirmModalOpen(false);\n\n    const url = medplum.fhirUrl('Patient', patientId, '$set-accounts');\n\n    const parameters = {\n      resourceType: 'Parameters' as const,\n      parameter: [\n        ...pendingAccounts.map((account) => ({\n          name: 'accounts' as const,\n          valueReference: { reference: account.reference },\n        })),\n        { name: 'propagate' as const, valueBoolean: propagate },\n      ],\n    };\n\n    notifications.show({\n      id: NOTIFICATION_ID,\n      title: NOTIFICATION_TITLE,\n      loading: true,\n      message: propagate ? 'Saving account changes and propagating to compartment...' : 'Saving account changes...',\n      autoClose: false,\n      withCloseButton: false,\n    });\n\n    try {\n      const headers: Record<string, string> = {};\n      if (propagate) {\n        headers['Prefer'] = 'respond-async';\n      }\n      await medplum.post(url, parameters, undefined, { headers });\n\n      // Invalidate the cached Patient so useResource re-fetches with updated meta.accounts\n      medplum.invalidateUrl(medplum.fhirUrl('Patient', patientId));\n\n      notifications.update({\n        id: NOTIFICATION_ID,\n        title: NOTIFICATION_TITLE,\n        color: 'green',\n        message: propagate ? 'Account changes saved. Compartment updates are being applied.' : 'Account changes saved.',\n        icon: <IconCheck size=\"1rem\" />,\n        loading: false,\n        autoClose: true,\n        withCloseButton: true,\n      });\n\n      props.onSaved?.();\n    } catch (err) {\n      notifications.update({\n        id: NOTIFICATION_ID,\n        title: NOTIFICATION_TITLE,\n        color: 'red',\n        message: normalizeErrorString(err),\n        icon: <IconX size=\"1rem\" />,\n        loading: false,\n        autoClose: false,\n        withCloseButton: true,\n      });\n    } finally {\n      setSaving(false);\n    }\n  }, [medplum, patient, pendingAccounts, propagate, props]);\n\n  if (!isAdmin) {\n    return (\n      <Alert color=\"blue\" title=\"Admin access required\">\n        You need project admin access to manage patient account assignments.\n      </Alert>\n    );\n  }\n\n  return (\n    <>\n      <Stack>\n        <Title order={3}>Current Accounts</Title>\n        {pendingAccounts.length === 0 ? (\n          <Text c=\"dimmed\">No accounts assigned to this patient.</Text>\n        ) : (\n          <Table>\n            <Table.Thead>\n              <Table.Tr>\n                <Table.Th>Type</Table.Th>\n                <Table.Th>Account</Table.Th>\n                <Table.Th />\n              </Table.Tr>\n            </Table.Thead>\n            <Table.Tbody>\n              {pendingAccounts.map((account) => (\n                <Table.Tr key={account.reference}>\n                  <Table.Td>\n                    <AccountTypeBadge reference={account} />\n                  </Table.Td>\n                  <Table.Td>\n                    <ResourceBadge value={account} link />\n                  </Table.Td>\n                  <Table.Td>\n                    <ActionIcon\n                      variant=\"subtle\"\n                      color=\"red\"\n                      aria-label={`Remove ${account.reference}`}\n                      onClick={() => handleRemoveAccount(account.reference as string)}\n                    >\n                      <IconX size={16} />\n                    </ActionIcon>\n                  </Table.Td>\n                </Table.Tr>\n              ))}\n            </Table.Tbody>\n          </Table>\n        )}\n\n        <Divider />\n\n        <Title order={4}>Add Account</Title>\n        <ReferenceInput\n          name=\"newAccount\"\n          placeholder=\"Search for Organization, HealthcareService, or CareTeam...\"\n          targetTypes={ACCOUNT_TARGET_TYPES}\n          onChange={(value) => {\n            if (value) {\n              handleAddAccount(value);\n            }\n          }}\n        />\n\n        {hasChanges && (\n          <>\n            <Divider />\n            <Title order={4}>Pending Changes</Title>\n            <Stack gap=\"xs\">\n              {changes.map((change) => (\n                <Group key={`${change.type}-${change.reference.reference}`} gap=\"xs\">\n                  {change.type === 'addition' ? (\n                    <Badge color=\"green\" variant=\"light\" leftSection={<IconPlus size={12} />}>\n                      Add\n                    </Badge>\n                  ) : (\n                    <Badge color=\"red\" variant=\"light\" leftSection={<IconMinus size={12} />}>\n                      Remove\n                    </Badge>\n                  )}\n                  <ResourceBadge value={change.reference} link />\n                </Group>\n              ))}\n            </Stack>\n          </>\n        )}\n\n        <Box>\n          <Button disabled={!hasChanges || saving} onClick={() => setConfirmModalOpen(true)}>\n            Save Changes\n          </Button>\n        </Box>\n      </Stack>\n\n      <Modal\n        opened={confirmModalOpen}\n        onClose={() => setConfirmModalOpen(false)}\n        title=\"Confirm Account Changes\"\n        size=\"md\"\n        keepMounted\n      >\n        <Stack>\n          <Text>\n            The following changes will be applied to Patient{' '}\n            <strong>\n              {patient.name?.[0]?.given?.join(' ')} {patient.name?.[0]?.family}\n            </strong>\n            :\n          </Text>\n\n          {changes.filter((c) => c.type === 'addition').length > 0 && (\n            <Box>\n              <Text fw={600} c=\"green\">\n                Adding:\n              </Text>\n              <Stack gap=\"xs\" mt=\"xs\">\n                {changes\n                  .filter((c) => c.type === 'addition')\n                  .map((c) => (\n                    <Group key={c.reference.reference} gap=\"xs\">\n                      <IconPlus size={14} color=\"green\" />\n                      <ResourceBadge value={c.reference} />\n                    </Group>\n                  ))}\n              </Stack>\n            </Box>\n          )}\n\n          {changes.filter((c) => c.type === 'removal').length > 0 && (\n            <Box>\n              <Text fw={600} c=\"red\">\n                Removing:\n              </Text>\n              <Stack gap=\"xs\" mt=\"xs\">\n                {changes\n                  .filter((c) => c.type === 'removal')\n                  .map((c) => (\n                    <Group key={c.reference.reference} gap=\"xs\">\n                      <IconMinus size={14} color=\"red\" />\n                      <ResourceBadge value={c.reference} />\n                    </Group>\n                  ))}\n              </Stack>\n            </Box>\n          )}\n\n          <Checkbox\n            label=\"Propagate changes to all resources in this patient's compartment\"\n            checked={propagate}\n            onChange={(event) => setPropagate(event.currentTarget.checked)}\n          />\n\n          <Group justify=\"right\" mt=\"md\">\n            <Button variant=\"default\" onClick={() => setConfirmModalOpen(false)}>\n              Cancel\n            </Button>\n            <Button onClick={handleSave} loading={saving}>\n              Confirm\n            </Button>\n          </Group>\n        </Stack>\n      </Modal>\n    </>\n  );\n}\n\nfunction AccountTypeBadge({ reference }: { readonly reference: Reference }): JSX.Element {\n  const type = reference.reference?.split('/')[0] ?? 'Unknown';\n  const colorMap: Record<string, string> = {\n    Organization: 'blue',\n    HealthcareService: 'teal',\n    CareTeam: 'violet',\n  };\n  return (\n    <Badge variant=\"light\" color={colorMap[type] ?? 'gray'} size=\"sm\">\n      {type}\n    </Badge>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Checkbox, Group, SegmentedControl, Stack } from '@mantine/core';\nimport { notifications } from '@mantine/notifications';\nimport { ContentType, normalizeErrorString, resolveId } from '@medplum/core';\nimport type { Patient, Reference } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconCheck, IconX } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { convertLocalToIso } from '../DateTimeInput/DateTimeInput.utils';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { FormSection } from '../FormSection/FormSection';\nimport { ReferenceInput } from '../ReferenceInput/ReferenceInput';\n\nexport interface PatientExportFormProps {\n  readonly patient: Patient | Reference<Patient>;\n}\n\nconst NOTIFICATION_ID = 'patient-export';\nconst NOTIFICATION_TITLE = 'Patient Export';\n\ninterface FormatDefinition {\n  operation: string;\n  type?: string;\n  extension: string;\n  contentType: string;\n}\n\nconst formats: Record<string, FormatDefinition> = {\n  everything: {\n    operation: '$everything',\n    extension: 'json',\n    contentType: ContentType.FHIR_JSON,\n  },\n  summary: {\n    operation: '$summary',\n    extension: 'json',\n    contentType: ContentType.FHIR_JSON,\n  },\n  ccda: {\n    operation: '$ccda-export',\n    extension: 'xml',\n    contentType: ContentType.CDA_XML,\n  },\n  ccdaReferral: {\n    operation: '$ccda-export',\n    type: 'referral',\n    extension: 'xml',\n    contentType: ContentType.CDA_XML,\n  },\n};\n\nexport function PatientExportForm(props: PatientExportFormProps): JSX.Element {\n  const medplum = useMedplum();\n  const { patient } = props;\n  const [format, setFormat] = useState('everything');\n  const [inlineAttachments, setInlineAttachments] = useState(false);\n\n  const handleSubmit = useCallback(\n    async (data: Record<string, string>) => {\n      const patientId = resolveId(patient) as string;\n      const { operation, type, contentType, extension } = formats[format];\n      const url = medplum.fhirUrl('Patient', patientId, operation);\n      const params = {} as Record<string, unknown>;\n\n      if (format === 'everything' && inlineAttachments) {\n        url.searchParams.set('_inlineAttachments', 'true');\n      }\n\n      if (type) {\n        params.type = type;\n      }\n\n      if (data.author) {\n        params.author = { reference: data.author };\n      }\n\n      if (data.authoredOn) {\n        params.authoredOn = convertLocalToIso(data.authoredOn);\n      }\n\n      if (data.startDate) {\n        params.start = data.startDate;\n      }\n\n      if (data.endDate) {\n        params.end = data.endDate;\n      }\n\n      notifications.show({\n        id: NOTIFICATION_ID,\n        title: NOTIFICATION_TITLE,\n        loading: true,\n        message: 'Exporting...',\n        autoClose: false,\n        withCloseButton: false,\n      });\n\n      try {\n        const response = await medplum.post(url, params, undefined, {\n          cache: 'no-cache',\n          headers: { Accept: contentType },\n        });\n\n        const fileName = `Patient-export-${patientId}-${new Date().toISOString().replaceAll(':', '-')}.${extension}`;\n\n        saveData(response, fileName, contentType);\n\n        notifications.update({\n          id: NOTIFICATION_ID,\n          title: NOTIFICATION_TITLE,\n          color: 'green',\n          message: 'Done',\n          icon: <IconCheck size=\"1rem\" />,\n          loading: false,\n          autoClose: true,\n          withCloseButton: true,\n        });\n      } catch (err) {\n        notifications.update({\n          id: NOTIFICATION_ID,\n          title: NOTIFICATION_TITLE,\n          color: 'red',\n          message: normalizeErrorString(err),\n          icon: <IconX size=\"1rem\" />,\n          loading: false,\n          autoClose: false,\n          withCloseButton: true,\n        });\n      }\n    },\n    [medplum, patient, format, inlineAttachments]\n  );\n\n  return (\n    <Form onSubmit={handleSubmit}>\n      <Stack>\n        <FormSection title=\"Export Format\" description=\"Required\" withAsterisk>\n          <SegmentedControl\n            name=\"format\"\n            value={format}\n            onChange={setFormat}\n            data={[\n              { label: 'FHIR Everything', value: 'everything' },\n              { label: 'Patient Summary', value: 'summary' },\n              { label: 'C-CDA', value: 'ccda' },\n              { label: 'C-CDA Referral', value: 'ccdaReferral' },\n            ]}\n            fullWidth\n          />\n        </FormSection>\n        <FormSection title=\"Author\" description=\"Optional author for composition. Default value is current user.\">\n          <ReferenceInput\n            name=\"author\"\n            placeholder=\"Author\"\n            targetTypes={['Organization', 'Practitioner', 'PractitionerRole']}\n          />\n        </FormSection>\n        <FormSection\n          title=\"Authored On\"\n          description=\"Optional date for composition authored on. Default value is current date.\"\n        >\n          <DateTimeInput name=\"authoredOn\" placeholder=\"Authored on\" />\n        </FormSection>\n        <FormSection\n          title=\"Start Date\"\n          description=\"The start date of care. If no start date is provided, all records prior to the end date are in scope.\"\n        >\n          <DateTimeInput name=\"startDate\" placeholder=\"Start date\" />\n        </FormSection>\n        <FormSection\n          title=\"End Date\"\n          description=\"The end date of care. If no end date is provided, all records subsequent to the start date are in scope.\"\n        >\n          <DateTimeInput name=\"endDate\" placeholder=\"End date\" />\n        </FormSection>\n        {format === 'everything' && (\n          <FormSection\n            title=\"Inline Attachments\"\n            description=\"Embed DocumentReference file attachments as base64-encoded data instead of storage URLs.\"\n          >\n            <Stack gap=\"xs\">\n              <Checkbox\n                label=\"Inline attachments\"\n                checked={inlineAttachments}\n                onChange={(e) => setInlineAttachments(e.currentTarget.checked)}\n              />\n            </Stack>\n          </FormSection>\n        )}\n        <Group justify=\"right\">\n          <SubmitButton>Request Export</SubmitButton>\n        </Group>\n      </Stack>\n    </Form>\n  );\n}\n\n/**\n * Tricks the browser into downloading a file.\n *\n * This function creates a temporary anchor (<a>) element, converts the provided data to a Blob,\n * and then simulates a click on the link to trigger a file download in the browser.\n *\n * See: https://stackoverflow.com/a/19328891\n *\n * @param data - The data to save.\n * @param fileName - The name of the file.\n * @param contentType - The content type of the file.\n */\nfunction saveData(data: unknown, fileName: string, contentType: string): void {\n  const content = typeof data === 'string' ? data : JSON.stringify(data, null, 2);\n  const blob = new Blob([content], { type: contentType });\n  const url = window.URL.createObjectURL(blob);\n  const a = document.createElement('a');\n  document.body.appendChild(a);\n  a.style.display = 'none';\n  a.href = url;\n  a.download = fileName;\n  a.click();\n  window.URL.revokeObjectURL(url);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { calculateAgeString } from '@medplum/core';\nimport type { Patient, Reference } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { HumanNameDisplay } from '../HumanNameDisplay/HumanNameDisplay';\nimport { InfoBar } from '../InfoBar/InfoBar';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { getDefaultColor } from './PatientHeader.utils';\n\nexport interface PatientHeaderProps {\n  readonly patient: Patient | Reference<Patient>;\n}\n\nexport function PatientHeader(props: PatientHeaderProps): JSX.Element | null {\n  const patient = useResource(props.patient);\n  if (!patient) {\n    return null;\n  }\n  return (\n    <InfoBar>\n      <ResourceAvatar value={patient} size=\"lg\" color={getDefaultColor(patient)} />\n      <InfoBar.Entry>\n        <InfoBar.Key>Name</InfoBar.Key>\n        <InfoBar.Value>\n          <MedplumLink to={patient} fw={500}>\n            {patient.name ? <HumanNameDisplay value={patient.name[0]} options={{ use: false }} /> : '[blank]'}\n          </MedplumLink>\n        </InfoBar.Value>\n      </InfoBar.Entry>\n      {patient.birthDate && (\n        <>\n          <InfoBar.Entry>\n            <InfoBar.Key>DoB</InfoBar.Key>\n            <InfoBar.Value>{patient.birthDate}</InfoBar.Value>\n          </InfoBar.Entry>\n          <InfoBar.Entry>\n            <InfoBar.Key>Age</InfoBar.Key>\n            <InfoBar.Value>{calculateAgeString(patient.birthDate)}</InfoBar.Value>\n          </InfoBar.Entry>\n        </>\n      )}\n      {patient.gender && (\n        <InfoBar.Entry>\n          <InfoBar.Key>Gender</InfoBar.Key>\n          <InfoBar.Value>{patient.gender}</InfoBar.Value>\n        </InfoBar.Entry>\n      )}\n      {patient.address && (\n        <InfoBar.Entry>\n          <InfoBar.Key>State</InfoBar.Key>\n          <InfoBar.Value>{patient.address[0]?.state}</InfoBar.Value>\n        </InfoBar.Entry>\n      )}\n      {patient.identifier?.map((identifier) => (\n        <InfoBar.Entry key={`${identifier?.system}-${identifier?.value}`}>\n          <InfoBar.Key>{identifier?.system}</InfoBar.Key>\n          <InfoBar.Value>{identifier?.value}</InfoBar.Value>\n        </InfoBar.Entry>\n      ))}\n    </InfoBar>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Patient } from '@medplum/fhirtypes';\n\nexport function getDefaultColor(patient: Patient): string | undefined {\n  if (patient.gender === 'male') {\n    return 'blue';\n  }\n  if (patient.gender === 'female') {\n    return 'pink';\n  }\n  return undefined;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Button, Checkbox, Flex, Group, Loader, Radio, Stack, Text, TextInput } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport type { AddFavoriteParams, AddPharmacyResponse, PharmacySearchParams } from '@medplum/core';\nimport { formatAddress, normalizeErrorString } from '@medplum/core';\nimport type { Organization, Patient } from '@medplum/fhirtypes';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useMemo, useState } from 'react';\nimport styles from './PharmacyDialog.module.css';\n\n/**\n * Placeholder text for each pharmacy search field. Vendors can override these to\n * reflect their own API constraints (e.g. DoseSpot requires a 3-character minimum\n * on text searches, whereas ScriptSure expects a 2-letter state and 5-digit ZIP).\n */\nexport interface PharmacySearchFieldPlaceholders {\n  readonly name?: string;\n  readonly city?: string;\n  readonly state?: string;\n  readonly zip?: string;\n  readonly phoneOrFax?: string;\n  readonly address?: string;\n  readonly ncpdpID?: string;\n}\n\nconst DEFAULT_SEARCH_PLACEHOLDERS: Required<PharmacySearchFieldPlaceholders> = {\n  name: 'Enter pharmacy name (min 3 chars)',\n  city: 'City (min 3 chars)',\n  state: 'State (min 3 chars)',\n  zip: 'Zip code (min 3 chars)',\n  phoneOrFax: 'Phone or fax number',\n  address: 'Street address (min 3 chars)',\n  ncpdpID: 'National Council for Prescription Drug Programs ID',\n};\n\nexport interface PharmacyDialogProps {\n  readonly patient: Patient;\n  readonly onSubmit: (pharmacy: Organization) => void;\n  readonly onClose: () => void;\n  readonly onSearch: (params: PharmacySearchParams & Record<string, unknown>) => Promise<Organization[]>;\n  readonly onAddToFavorites: (params: AddFavoriteParams) => Promise<AddPharmacyResponse>;\n  /** Optional fields rendered inside the search form above the submit button. */\n  readonly renderBeforeSearchButton?: ReactNode;\n  /**\n   * Extra search parameters merged into the bot request (e.g. vendor-specific filters).\n   * `handleSearch` depends on this callback, so callers should memoize it (e.g. `useCallback`)\n   * to avoid re-creating the search handler on every render.\n   */\n  readonly getExtraSearchParams?: () => Record<string, unknown>;\n  /** Optional per-field placeholder overrides for the search form. */\n  readonly searchPlaceholders?: PharmacySearchFieldPlaceholders;\n}\n\n/**\n * Gets a unique key for a pharmacy based on its identifier or index.\n * @param pharmacy - The pharmacy Organization resource.\n * @param index - The index of the pharmacy in the list.\n * @returns A unique key string for the pharmacy.\n */\nfunction getPharmacyKey(pharmacy: Organization, index: number): string {\n  return pharmacy.identifier?.[0]?.value || `pharmacy-${index}`;\n}\n\n/**\n * Search form component for finding pharmacies\n */\ninterface SearchFormProps {\n  readonly onSearch: (formData: FormData) => void;\n  readonly searching: boolean;\n  readonly renderBeforeSearchButton?: ReactNode;\n  readonly placeholders: Required<PharmacySearchFieldPlaceholders>;\n}\n\nfunction SearchForm({ onSearch, searching, renderBeforeSearchButton, placeholders }: SearchFormProps): JSX.Element {\n  return (\n    <form\n      onSubmit={(e) => {\n        e.preventDefault();\n        const formData = new FormData(e.currentTarget);\n        onSearch(formData);\n      }}\n    >\n      <Stack gap=\"md\">\n        <TextInput name=\"name\" label=\"Pharmacy Name\" placeholder={placeholders.name} />\n        <Group grow>\n          <TextInput name=\"city\" label=\"City\" placeholder={placeholders.city} />\n          <TextInput name=\"state\" label=\"State\" placeholder={placeholders.state} />\n        </Group>\n        <Group grow>\n          <TextInput name=\"zip\" label=\"Zip Code\" placeholder={placeholders.zip} />\n          <TextInput name=\"phoneOrFax\" label=\"Phone or Fax\" placeholder={placeholders.phoneOrFax} />\n        </Group>\n        <TextInput name=\"address\" label=\"Address\" placeholder={placeholders.address} />\n        <TextInput name=\"ncpdpID\" label=\"NCPDP ID\" placeholder={placeholders.ncpdpID} />\n\n        {renderBeforeSearchButton}\n\n        <Button type=\"submit\" loading={searching}>\n          Search\n        </Button>\n      </Stack>\n    </form>\n  );\n}\n\n/**\n * Individual pharmacy item in search results\n */\ninterface PharmacyItemProps {\n  readonly pharmacy: Organization;\n  readonly pharmacyKey: string;\n  readonly isSelected: boolean;\n  readonly onSelect: () => void;\n}\n\nfunction PharmacyItem({ pharmacy, pharmacyKey, isSelected, onSelect }: PharmacyItemProps): JSX.Element {\n  return (\n    <Box\n      key={pharmacyKey}\n      p=\"sm\"\n      className={isSelected ? styles.pharmacyItemSelected : styles.pharmacyItem}\n      onClick={onSelect}\n    >\n      <Radio\n        value={pharmacyKey}\n        label={\n          <Box>\n            <Text fw={500} size=\"sm\">\n              {pharmacy.name}\n            </Text>\n            {pharmacy.address?.[0] && (\n              <Text size=\"xs\" c=\"dimmed\">\n                {formatAddress(pharmacy.address[0])}\n              </Text>\n            )}\n            {pharmacy.telecom?.find((t) => t.system === 'phone') && (\n              <Text size=\"xs\" c=\"dimmed\">\n                Phone: {pharmacy.telecom.find((t) => t.system === 'phone')?.value}\n              </Text>\n            )}\n            {pharmacy.telecom?.find((t) => t.system === 'fax') && (\n              <Text size=\"xs\" c=\"dimmed\">\n                Fax: {pharmacy.telecom.find((t) => t.system === 'fax')?.value}\n              </Text>\n            )}\n          </Box>\n        }\n      />\n    </Box>\n  );\n}\n\n/**\n * Search results section with pharmacy list and action buttons\n */\ninterface SearchResultsProps {\n  readonly searchResults: Organization[];\n  readonly selectedPharmacy: Organization | undefined;\n  readonly onSelectPharmacy: (pharmacy: Organization) => void;\n  readonly setAsPrimary: boolean;\n  readonly onSetAsPrimary: (value: boolean) => void;\n  readonly onAddFavorite: () => void;\n  readonly onClose: () => void;\n  readonly adding: boolean;\n}\n\nfunction SearchResults({\n  searchResults,\n  selectedPharmacy,\n  onSelectPharmacy,\n  setAsPrimary,\n  onSetAsPrimary,\n  onAddFavorite,\n  onClose,\n  adding,\n}: SearchResultsProps): JSX.Element {\n  return (\n    <Box mt=\"xl\">\n      <Text fw={600} mb=\"md\">\n        Search Results ({searchResults.length})\n      </Text>\n      <Radio.Group\n        value={selectedPharmacy ? getPharmacyKey(selectedPharmacy, searchResults.indexOf(selectedPharmacy)) : ''}\n        onChange={(value) => {\n          const selected = searchResults.find((p, i) => getPharmacyKey(p, i) === value);\n          if (selected) {\n            onSelectPharmacy(selected);\n          }\n        }}\n      >\n        <Stack gap=\"sm\">\n          {searchResults.map((pharmacy, index) => {\n            const pharmacyKey = getPharmacyKey(pharmacy, index);\n            const isSelected = selectedPharmacy\n              ? getPharmacyKey(selectedPharmacy, searchResults.indexOf(selectedPharmacy)) === pharmacyKey\n              : false;\n\n            return (\n              <PharmacyItem\n                key={pharmacyKey}\n                pharmacy={pharmacy}\n                pharmacyKey={pharmacyKey}\n                isSelected={isSelected}\n                onSelect={() => onSelectPharmacy(pharmacy)}\n              />\n            );\n          })}\n        </Stack>\n      </Radio.Group>\n\n      <Flex mt=\"lg\" gap=\"md\" align=\"center\" justify=\"space-between\">\n        <Checkbox\n          label=\"Set as primary pharmacy\"\n          checked={setAsPrimary}\n          onChange={(e) => onSetAsPrimary(e.currentTarget.checked)}\n        />\n        <Group>\n          <Button variant=\"subtle\" onClick={onClose}>\n            Cancel\n          </Button>\n          <Button onClick={onAddFavorite} disabled={!selectedPharmacy} loading={adding}>\n            Add to Favorites\n          </Button>\n        </Group>\n      </Flex>\n    </Box>\n  );\n}\n\n/**\n * Renders a dialog for searching and adding pharmacies to a patient's favorites.\n * This is a generic component that accepts search and add callbacks.\n * @param props - The dialog props.\n * @returns The pharmacy dialog component.\n */\nexport function PharmacyDialog(props: PharmacyDialogProps): JSX.Element {\n  const {\n    patient,\n    onSubmit,\n    onClose,\n    onSearch,\n    onAddToFavorites,\n    renderBeforeSearchButton,\n    getExtraSearchParams,\n    searchPlaceholders,\n  } = props;\n\n  const placeholders = useMemo<Required<PharmacySearchFieldPlaceholders>>(\n    () => ({ ...DEFAULT_SEARCH_PLACEHOLDERS, ...searchPlaceholders }),\n    [searchPlaceholders]\n  );\n\n  const [searchResults, setSearchResults] = useState<Organization[]>([]);\n  const [searching, setSearching] = useState(false);\n  const [selectedPharmacy, setSelectedPharmacy] = useState<Organization | undefined>();\n  const [setAsPrimary, setSetAsPrimary] = useState(false);\n  const [adding, setAdding] = useState(false);\n\n  const handleSearch = useCallback(\n    async (formData: FormData) => {\n      const searchParams: PharmacySearchParams = {\n        name: (formData.get('name') as string) || undefined,\n        city: (formData.get('city') as string) || undefined,\n        state: (formData.get('state') as string) || undefined,\n        zip: (formData.get('zip') as string) || undefined,\n        address: (formData.get('address') as string) || undefined,\n        phoneOrFax: (formData.get('phoneOrFax') as string) || undefined,\n        ncpdpID: (formData.get('ncpdpID') as string) || undefined,\n      };\n\n      // Remove empty values\n      const cleanParams = Object.fromEntries(\n        Object.entries(searchParams).filter(([_, v]) => typeof v === 'string' && v.trim() !== '')\n      ) as PharmacySearchParams;\n\n      const extraParams = getExtraSearchParams?.() ?? {};\n      const mergedParams = { ...cleanParams, ...extraParams };\n\n      const hasTextCriteria = Object.keys(cleanParams).length > 0;\n      const hasExtraCriteria = Object.entries(extraParams).some(([, value]) => {\n        if (Array.isArray(value)) {\n          return value.length > 0;\n        }\n        return value !== undefined && value !== null && value !== '';\n      });\n\n      if (!hasTextCriteria && !hasExtraCriteria) {\n        showNotification({\n          color: 'yellow',\n          title: 'Search Required',\n          message: 'Please enter at least one search criterion',\n        });\n        return;\n      }\n\n      setSearching(true);\n      setSelectedPharmacy(undefined);\n      try {\n        const results = await onSearch(mergedParams);\n        setSearchResults(results);\n        if (results.length === 0) {\n          showNotification({\n            color: 'blue',\n            title: 'No Results',\n            message: 'No pharmacies found matching your search criteria',\n          });\n        }\n      } catch (error) {\n        showNotification({\n          color: 'red',\n          title: 'Search Error',\n          message: normalizeErrorString(error),\n        });\n      } finally {\n        setSearching(false);\n      }\n    },\n    [getExtraSearchParams, onSearch]\n  );\n\n  const handleAddFavorite = useCallback(async () => {\n    if (!selectedPharmacy || !patient.id) {\n      return;\n    }\n\n    setAdding(true);\n    try {\n      const response = await onAddToFavorites({\n        patientId: patient.id,\n        pharmacy: selectedPharmacy,\n        setAsPrimary,\n      });\n\n      if (response.success) {\n        showNotification({\n          color: 'green',\n          title: 'Success',\n          message: response.message,\n        });\n        // Return the persisted Organization if available, otherwise the selected one\n        onSubmit(response.organization || selectedPharmacy);\n      } else {\n        showNotification({\n          color: 'red',\n          title: 'Error',\n          message: response.message,\n        });\n      }\n    } catch (error) {\n      showNotification({\n        color: 'red',\n        title: 'Error',\n        message: normalizeErrorString(error),\n      });\n    } finally {\n      setAdding(false);\n    }\n  }, [selectedPharmacy, patient.id, setAsPrimary, onAddToFavorites, onSubmit]);\n\n  return (\n    <Box>\n      <SearchForm\n        onSearch={(formData) => handleSearch(formData).catch(console.error)}\n        searching={searching}\n        renderBeforeSearchButton={renderBeforeSearchButton}\n        placeholders={placeholders}\n      />\n\n      {searching && (\n        <Flex justify=\"center\" mt=\"xl\">\n          <Loader />\n        </Flex>\n      )}\n\n      {searchResults.length > 0 && !searching && (\n        <SearchResults\n          searchResults={searchResults}\n          selectedPharmacy={selectedPharmacy}\n          onSelectPharmacy={setSelectedPharmacy}\n          setAsPrimary={setAsPrimary}\n          onSetAsPrimary={setSetAsPrimary}\n          onAddFavorite={handleAddFavorite}\n          onClose={onClose}\n          adding={adding}\n        />\n      )}\n    </Box>\n  );\n}\n", ".pharmacyItem {\n  border: 1px solid var(--mantine-color-gray-3);\n  border-radius: var(--mantine-radius-sm);\n  cursor: pointer;\n  transition:\n    border-color 0.2s,\n    box-shadow 0.2s;\n}\n\n.pharmacyItem:hover {\n  border-color: var(--mantine-color-blue-4);\n}\n\n.pharmacyItemSelected {\n  border: 2px solid var(--mantine-color-blue-6);\n  border-radius: var(--mantine-radius-sm);\n  cursor: pointer;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n/* eslint-disable react-refresh/only-export-components */\nimport { Box, Flex, Group, Text } from '@mantine/core';\nimport { getDisplayString as coreGetDisplayString } from '@medplum/core';\nimport type { Resource, ResourceType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\nimport { CollapsibleSection } from './CollapsibleSection';\nimport type { PatientSummarySectionConfig, SectionRenderContext } from './PatientSummary.types';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface SummaryResourceListOptions {\n  /** Unique key for React reconciliation. */\n  readonly key: string;\n  /** Section title displayed in the collapsible header. */\n  readonly title: string;\n  /** FHIR search configuration. */\n  readonly search: {\n    readonly resourceType: ResourceType;\n    /** Which search param references the patient. Defaults to 'subject'. */\n    readonly patientParam?: string;\n    /** Additional search params. */\n    readonly query?: Record<string, string | number | boolean | undefined>;\n  };\n  /** Override the default display string for each resource. */\n  readonly getDisplayString?: (resource: Resource) => string;\n  /** Return a status badge config, or undefined to show no badge. */\n  readonly getStatus?: (resource: Resource) => { label: string; color: string } | undefined;\n  /** Return secondary text (shown dimmed below the primary text). */\n  readonly getSecondaryText?: (resource: Resource) => string | undefined;\n  /** Filter resources before display. */\n  readonly filter?: (resource: Resource) => boolean;\n  /** Sort resources before display. */\n  readonly sort?: (a: Resource, b: Resource) => number;\n  /** Callback for the \"+\" add button. If omitted, no add button is shown. */\n  readonly onAdd?: () => void;\n}\n\n/**\n * Creates a `PatientSummarySectionConfig` that renders a list of resources\n * using the same visual pattern as built-in sections (CollapsibleSection + SummaryItem + StatusBadge).\n * @param options - Configuration for the resource list section.\n * @returns A section config that renders a generic resource list.\n */\nexport function summaryResourceListSection(options: SummaryResourceListOptions): PatientSummarySectionConfig {\n  return {\n    key: options.key,\n    title: options.title,\n    searches: [\n      {\n        key: options.key,\n        resourceType: options.search.resourceType,\n        patientParam: options.search.patientParam,\n        query: options.search.query,\n      },\n    ],\n    component: (context: SectionRenderContext) => (\n      <ResourceListDisplay options={options} resources={context.results[options.key] ?? []} context={context} />\n    ),\n  };\n}\n\ninterface ResourceListDisplayProps {\n  readonly options: SummaryResourceListOptions;\n  readonly resources: Resource[];\n  readonly context: SectionRenderContext;\n}\n\nfunction ResourceListDisplay(props: ResourceListDisplayProps): JSX.Element {\n  const { options, context } = props;\n  let resources = [...props.resources];\n\n  if (options.filter) {\n    resources = resources.filter(options.filter);\n  }\n\n  if (options.sort) {\n    resources.sort(options.sort);\n  }\n\n  return (\n    <CollapsibleSection title={options.title} onAdd={options.onAdd}>\n      {resources.length > 0 ? (\n        <Flex direction=\"column\" gap={8}>\n          {resources.map((resource) => {\n            const displayString = options.getDisplayString\n              ? options.getDisplayString(resource)\n              : coreGetDisplayString(resource);\n            const status = options.getStatus?.(resource);\n            const secondaryText = options.getSecondaryText?.(resource);\n\n            return (\n              <SummaryItem key={resource.id} onClick={() => context.onClickResource?.(resource)}>\n                <Box>\n                  <Text fw={500} className={styles.itemText}>\n                    {displayString}\n                  </Text>\n                  {(status || secondaryText) && (\n                    <Group mt={2} gap={4}>\n                      {status && <StatusBadge color={status.color} variant=\"light\" status={status.label} />}\n                      {secondaryText && (\n                        <Text size=\"xs\" fw={500} c=\"dimmed\">\n                          {secondaryText}\n                        </Text>\n                      )}\n                    </Group>\n                  )}\n                </Box>\n              </SummaryItem>\n            );\n          })}\n        </Flex>\n      ) : (\n        <Text>(none)</Text>\n      )}\n    </CollapsibleSection>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, ProfileResource } from '@medplum/core';\nimport { createReference } from '@medplum/core';\nimport type { Attachment, Patient, Reference, ResourceType } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useCallback } from 'react';\nimport type { ResourceTimelineProps } from '../ResourceTimeline/ResourceTimeline';\nimport { ResourceTimeline } from '../ResourceTimeline/ResourceTimeline';\n\nexport interface PatientTimelineProps extends Pick<ResourceTimelineProps<Patient>, 'getMenu'> {\n  readonly patient: Patient | Reference<Patient>;\n}\n\nexport function PatientTimeline(props: PatientTimelineProps): JSX.Element {\n  const { patient, ...rest } = props;\n\n  const loadTimelineResources = useCallback((medplum: MedplumClient, resourceType: ResourceType, id: string) => {\n    const ref = `${resourceType}/${id}`;\n    const _count = 100;\n    return Promise.allSettled([\n      medplum.readHistory('Patient', id),\n      medplum.search('ClinicalImpression', { subject: ref, _count }),\n      medplum.search('Communication', { subject: ref, _count }),\n      medplum.search('Device', { patient: ref, _count }),\n      medplum.search('DeviceRequest', { patient: ref, _count }),\n      medplum.search('DiagnosticReport', { subject: ref, _count }),\n      medplum.search('Media', { subject: ref, _count }),\n      medplum.search('ServiceRequest', { subject: ref, _count }),\n      medplum.search('Task', { subject: ref, _count }),\n    ]);\n  }, []);\n\n  return (\n    <ResourceTimeline\n      value={patient}\n      loadTimelineResources={loadTimelineResources}\n      createCommunication={(resource: Patient, sender: ProfileResource, text: string) => ({\n        resourceType: 'Communication',\n        status: 'completed',\n        subject: createReference(resource),\n        sender: createReference(sender),\n        sent: new Date().toISOString(),\n        payload: [{ contentString: text }],\n      })}\n      createMedia={(resource: Patient, operator: ProfileResource, content: Attachment) => ({\n        resourceType: 'Media',\n        status: 'completed',\n        subject: createReference(resource),\n        operator: createReference(operator),\n        issued: new Date().toISOString(),\n        content,\n      })}\n      {...rest}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport {\n  Anchor,\n  Box,\n  Button,\n  CloseButton,\n  Flex,\n  Group,\n  Loader,\n  NativeSelect,\n  Paper,\n  Stack,\n  Text,\n  TextInput,\n} from '@mantine/core';\nimport { getReferenceString } from '@medplum/core';\nimport type {\n  ActivityDefinition,\n  PlanDefinition,\n  PlanDefinitionAction,\n  Questionnaire,\n  Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX, MouseEvent, SyntheticEvent } from 'react';\nimport { useEffect, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { killEvent } from '../utils/dom';\nimport classes from './PlanDefinitionBuilder.module.css';\n\nexport interface PlanDefinitionBuilderProps {\n  readonly value: Partial<PlanDefinition> | Reference<PlanDefinition>;\n  readonly onSubmit: (result: PlanDefinition) => void;\n}\n\nexport function PlanDefinitionBuilder(props: PlanDefinitionBuilderProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const defaultValue = useResource(props.value);\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n  const [selectedKey, setSelectedKey] = useState<string>();\n  const [hoverKey, setHoverKey] = useState<string>();\n  const [value, setValue] = useState<PlanDefinition>();\n\n  function handleDocumentMouseOver(): void {\n    setHoverKey(undefined);\n  }\n\n  function handleDocumentClick(): void {\n    setSelectedKey(undefined);\n  }\n\n  useEffect(() => {\n    medplum\n      .requestSchema('PlanDefinition')\n      .then(() => setSchemaLoaded(true))\n      .catch(console.log);\n  }, [medplum]);\n\n  useEffect(() => {\n    setValue(ensurePlanDefinitionKeys(defaultValue ?? { resourceType: 'PlanDefinition', status: 'active' }));\n    document.addEventListener('mouseover', handleDocumentMouseOver);\n    document.addEventListener('click', handleDocumentClick);\n    return () => {\n      document.removeEventListener('mouseover', handleDocumentMouseOver);\n      document.removeEventListener('click', handleDocumentClick);\n    };\n  }, [defaultValue]);\n\n  if (!schemaLoaded || !value) {\n    return null;\n  }\n\n  function changeProperty(property: string, newValue: any): void {\n    setValue((prevValue) => ({ ...prevValue, [property]: newValue }) as PlanDefinition);\n  }\n\n  return (\n    <div>\n      <Form testid=\"questionnaire-form\" onSubmit={() => props.onSubmit(value)}>\n        <TextInput\n          label=\"Plan Title\"\n          py=\"md\"\n          defaultValue={value.title}\n          onChange={(e) => changeProperty('title', e.currentTarget.value)}\n        />\n        <ActionArrayBuilder\n          actions={value.action || []}\n          selectedKey={selectedKey}\n          setSelectedKey={setSelectedKey}\n          hoverKey={hoverKey}\n          setHoverKey={setHoverKey}\n          onChange={(x) => changeProperty('action', x)}\n        />\n        <SubmitButton>Save</SubmitButton>\n      </Form>\n    </div>\n  );\n}\n\ninterface ActionArrayBuilderProps {\n  readonly actions: PlanDefinitionAction[];\n  readonly selectedKey: string | undefined;\n  readonly setSelectedKey: (key: string | undefined) => void;\n  readonly hoverKey: string | undefined;\n  readonly setHoverKey: (key: string | undefined) => void;\n  readonly onChange: (actions: PlanDefinitionAction[]) => void;\n}\n\nfunction ActionArrayBuilder(props: ActionArrayBuilderProps): JSX.Element {\n  function changeAction(changedAction: PlanDefinitionAction): void {\n    props.onChange(props.actions.map((i) => (i.id === changedAction.id ? changedAction : i)));\n  }\n\n  function addAction(addedAction: PlanDefinitionAction): void {\n    props.onChange([...props.actions, addedAction]);\n    props.setSelectedKey(addedAction.id);\n  }\n\n  function removeAction(removedAction: PlanDefinitionAction): void {\n    props.onChange(props.actions.filter((i) => i !== removedAction));\n  }\n\n  return (\n    <Stack gap=\"md\" className={classes.section}>\n      {props.actions.map((action) => (\n        <ActionBuilder\n          key={action.id}\n          action={action}\n          selectedKey={props.selectedKey}\n          setSelectedKey={props.setSelectedKey}\n          hoverKey={props.hoverKey}\n          setHoverKey={props.setHoverKey}\n          onChange={changeAction}\n          onRemove={() => removeAction(action)}\n        />\n      ))}\n      <div>\n        <Button\n          variant=\"outline\"\n          onClick={(e: MouseEvent) => {\n            killEvent(e);\n            addAction({ id: generateId() });\n          }}\n        >\n          Add action\n        </Button>\n      </div>\n    </Stack>\n  );\n}\n\ninterface ActionBuilderProps {\n  readonly action: PlanDefinitionAction;\n  readonly selectedKey: string | undefined;\n  readonly setSelectedKey: (key: string | undefined) => void;\n  readonly hoverKey: string | undefined;\n  readonly setHoverKey: (key: string | undefined) => void;\n  readonly onChange: (action: PlanDefinitionAction) => void;\n  readonly onRemove: () => void;\n}\n\nfunction ActionBuilder(props: ActionBuilderProps): JSX.Element {\n  const { action } = props;\n\n  function onClick(e: SyntheticEvent): void {\n    e.stopPropagation();\n    props.setSelectedKey(props.action.id);\n  }\n\n  function onHover(e: SyntheticEvent): void {\n    killEvent(e);\n    props.setHoverKey(props.action.id);\n  }\n\n  return (\n    <div onClick={onClick} onMouseOver={onHover} onFocus={onHover}>\n      <ActionEditor\n        action={action}\n        onChange={props.onChange}\n        selectedKey={props.selectedKey}\n        hoverKey={props.hoverKey}\n        onRemove={props.onRemove}\n      />\n    </div>\n  );\n}\n\ninterface ActionEditorProps {\n  readonly action: PlanDefinitionAction;\n  readonly selectedKey: string | undefined;\n  readonly hoverKey: string | undefined;\n  readonly onChange: (action: PlanDefinitionAction) => void;\n  readonly onRemove: () => void;\n}\n\nfunction ActionEditor(props: ActionEditorProps): JSX.Element {\n  const { action } = props;\n  const [actionType, setActionType] = useState<string | undefined>();\n  const medplum = useMedplum();\n  const [loading, setLoading] = useState(false);\n  const [resource, setResource] = useState<Questionnaire | ActivityDefinition | undefined>();\n  const editing = props.selectedKey === props.action.id;\n  const hovering = props.hoverKey === props.action.id;\n\n  function changeProperty(property: string, value: any): void {\n    props.onChange({\n      ...action,\n      [property]: value,\n    });\n  }\n\n  const className = cx(classes.section, {\n    [classes.hovering]: hovering && !editing,\n  });\n\n  useEffect(() => {\n    const readResource = async (): Promise<void> => {\n      if (!action.definitionCanonical) {\n        return;\n      }\n      setLoading(true);\n      const resource = await medplum.readCanonical(['Questionnaire', 'ActivityDefinition'], action.definitionCanonical);\n      setActionType(getInitialActionType(resource));\n      setResource(resource);\n      setLoading(false);\n    };\n    readResource().catch(console.error);\n  }, [action.definitionCanonical, medplum]);\n\n  if (loading) {\n    return <Loader />;\n  }\n\n  return (\n    <Paper data-testid={action.id} className={className} p={0} radius=\"sm\" withBorder>\n      <Flex w=\"100%\" p=\"xs\" bg=\"gray.0\" gap=\"md\" align=\"center\" justify=\"space-between\">\n        <TextInput\n          w=\"100%\"\n          name={`actionTitle-${action.id}`}\n          defaultValue={action.title}\n          placeholder=\"Title\"\n          onChange={(e) => changeProperty('title', e.currentTarget.value)}\n        />\n        <CloseButton data-testid=\"close-button\" onClick={props.onRemove} />\n      </Flex>\n\n      {editing && (\n        <Stack gap=\"xl\" p=\"md\">\n          <Box>\n            <TextInput\n              label=\"Task Description\"\n              placeholder=\"Enter task description\"\n              name={`actionDescription-${action.id}`}\n              defaultValue={action.description}\n              onChange={(e) => changeProperty('description', e.currentTarget.value)}\n            />\n          </Box>\n\n          <Box>\n            <NativeSelect\n              label=\"Type of Action\"\n              value={actionType}\n              onChange={(e) => {\n                const value = e.currentTarget.value === 'standard' ? undefined : e.currentTarget.value;\n                setActionType(value);\n                props.onChange({\n                  ...props.action,\n                  definitionCanonical: value === 'standard' ? undefined : props.action.definitionCanonical,\n                });\n              }}\n              data={[\n                { value: 'standard', label: 'Standard task' },\n                { value: 'questionnaire', label: 'Task with Questionnaire' },\n                { value: 'activitydefinition', label: 'Task with Activity Definition' },\n              ]}\n            />\n          </Box>\n\n          {actionType === 'questionnaire' && (\n            <Stack gap={0}>\n              <Group gap={0} mb=\"xs\">\n                <Text fw={600}>Select questionnaire</Text>\n                <Text c=\"red\">*</Text>\n              </Group>\n              <Text size=\"sm\" c=\"dimmed\" mb=\"sm\">\n                Questionnaire to be shown in the task in Encounter view. You can create new one from{' '}\n                <Anchor href=\"/Questionnaire\" target=\"_blank\" c=\"blue\">\n                  questionnaires list\n                </Anchor>\n              </Text>\n              <ActionResourceTypeBuilder\n                resource={resource}\n                resourceType=\"Questionnaire\"\n                action={action}\n                onChange={props.onChange}\n                placeholder=\"Search for questionnaire\"\n              />\n            </Stack>\n          )}\n\n          {actionType === 'activitydefinition' && (\n            <Stack gap={0}>\n              <Group gap={0} mb=\"xs\">\n                <Text fw={600}>Select activity definition</Text>\n                <Text c=\"red\">*</Text>\n              </Group>\n              <Text size=\"sm\" c=\"dimmed\" mb=\"sm\">\n                ActivityDefinition.kind resource to be shown in the task in Encounter view. You can create new one from{' '}\n                <Anchor href=\"/ActivityDefinition\" target=\"_blank\" c=\"blue\">\n                  activity definitions list\n                </Anchor>\n              </Text>\n              <ActionResourceTypeBuilder\n                resource={resource}\n                resourceType=\"ActivityDefinition\"\n                action={action}\n                onChange={props.onChange}\n                placeholder=\"Search for activity definition\"\n              />\n            </Stack>\n          )}\n        </Stack>\n      )}\n    </Paper>\n  );\n}\n\ninterface ActionResourceTypeBuilderProps {\n  readonly action: PlanDefinitionAction;\n  readonly resource: Questionnaire | ActivityDefinition | undefined;\n  readonly resourceType: 'Questionnaire' | 'ActivityDefinition';\n  readonly placeholder?: string;\n  readonly onChange: (action: PlanDefinitionAction) => void;\n}\n\nfunction ActionResourceTypeBuilder(props: ActionResourceTypeBuilderProps): JSX.Element {\n  const { id } = props.action;\n  const { resource } = props as { resource: Questionnaire | ActivityDefinition };\n\n  return (\n    <ResourceInput\n      name={id as string}\n      placeholder={props.placeholder}\n      resourceType={props.resourceType}\n      defaultValue={resource}\n      onChange={(newValue) => {\n        if (newValue) {\n          props.onChange({\n            ...props.action,\n            definitionCanonical: 'url' in newValue ? newValue.url : undefined,\n            definitionUri: !('url' in newValue) ? getReferenceString(newValue) : undefined,\n          });\n        } else {\n          props.onChange({ ...props.action, definitionCanonical: undefined });\n        }\n      }}\n    />\n  );\n}\n\nfunction getInitialActionType(resource: Questionnaire | ActivityDefinition | undefined): string | undefined {\n  return resource === undefined ? 'standard' : resource.resourceType.toLowerCase();\n}\n\nlet nextId = 1;\n\n/**\n * Generates a unique ID.\n * React needs unique IDs for components for rendering performance.\n * All of the important components in the questionnaire builder have id properties for this:\n * Questionnaire, QuestionnaireItem, and QuestionnaireItemAnswerOption.\n * @param existing - Optional existing id which will update nextId.\n * @returns A unique key.\n */\nfunction generateId(existing?: string): string {\n  if (existing) {\n    if (existing.startsWith('id-')) {\n      const existingNum = Number.parseInt(existing.substring(3), 10);\n      if (!Number.isNaN(existingNum)) {\n        nextId = Math.max(nextId, existingNum + 1);\n      }\n    }\n    return existing;\n  }\n  return 'id-' + nextId++;\n}\n\nfunction ensurePlanDefinitionKeys(planDefinition: PlanDefinition): PlanDefinition {\n  return {\n    ...planDefinition,\n    action: ensurePlanDefinitionActionKeys(planDefinition.action),\n  };\n}\n\nfunction ensurePlanDefinitionActionKeys(\n  actions: PlanDefinitionAction[] | undefined\n): PlanDefinitionAction[] | undefined {\n  if (!actions) {\n    return undefined;\n  }\n  return actions.map((action) => ({\n    ...action,\n    id: generateId(action.id),\n    action: ensurePlanDefinitionActionKeys(action.action),\n  }));\n}\n", ".section {\n  position: relative;\n  padding: 6px 0 16px 0;\n  transition: all 0.1;\n}\n\n.hovering {\n  border: 1.5px solid var(--mantine-color-blue-5);\n}\n\n.editing {\n  border: 1.5px solid var(--mantine-color-gray-1);\n  border-left: 4px solid var(--mantine-color-blue-5);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Alert, Box, Center, Loader, Stack, Text } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { useStabilizedCallback } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useRef, useState } from 'react';\n\nconst SCAN_INTERVAL_MS = 150;\n\ntype JsQr = (\n  data: Uint8ClampedArray,\n  width: number,\n  height: number,\n  options?: { inversionAttempts?: 'dontInvert' | 'onlyInvert' | 'attemptBoth' | 'invertFirst' }\n) => { data: string } | null;\n\nlet jsQrPromise: Promise<JsQr> | undefined;\n\nexport interface QrCodeScannerProps {\n  readonly onScan: (data: string) => void;\n  readonly onError?: (error: Error) => void;\n  readonly scanOnce?: boolean;\n}\n\nexport function QrCodeScanner({ onScan, onError, scanOnce = true }: QrCodeScannerProps): JSX.Element {\n  const videoRef = useRef<HTMLVideoElement>(null);\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const emitScan = useStabilizedCallback(onScan);\n  const emitError = useStabilizedCallback(onError);\n  const [loading, setLoading] = useState(true);\n  const [error, setError] = useState<string>();\n\n  useEffect(() => {\n    const video = videoRef.current;\n    const canvasElement = canvasRef.current;\n    const ctx = canvasElement?.getContext('2d', { willReadFrequently: true });\n    if (!video || !canvasElement || !ctx) {\n      return undefined;\n    }\n    const videoElement = video;\n    const scanCanvas = canvasElement;\n    const scanCtx = ctx;\n\n    let rafId = 0;\n    let stream: MediaStream | undefined;\n    let cancelled = false;\n    let scanned = false;\n    let lastScanTime = 0;\n    let jsQr: JsQr | undefined;\n\n    function stopStream(): void {\n      stream?.getTracks().forEach((t) => t.stop());\n    }\n\n    function fail(err: unknown): void {\n      const normalized = err instanceof Error ? err : new Error(String(err));\n      if (!cancelled) {\n        setLoading(false);\n        setError(normalizeErrorString(normalized));\n        emitError(normalized);\n      }\n    }\n\n    function tick(timestamp: number): void {\n      if (cancelled || scanned || !jsQr) {\n        return;\n      }\n      if (videoElement.readyState === videoElement.HAVE_ENOUGH_DATA) {\n        setLoading(false);\n        if (timestamp - lastScanTime >= SCAN_INTERVAL_MS) {\n          lastScanTime = timestamp;\n          scanCanvas.height = videoElement.videoHeight;\n          scanCanvas.width = videoElement.videoWidth;\n          scanCtx.drawImage(videoElement, 0, 0, scanCanvas.width, scanCanvas.height);\n          const imageData = scanCtx.getImageData(0, 0, scanCanvas.width, scanCanvas.height);\n          const code = jsQr(imageData.data, imageData.width, imageData.height, { inversionAttempts: 'attemptBoth' });\n          if (code?.data) {\n            scanned = scanOnce;\n            emitScan(code.data);\n            if (scanOnce) {\n              stopStream();\n              return;\n            }\n          }\n        }\n      }\n      rafId = requestAnimationFrame(tick);\n    }\n\n    async function start(): Promise<void> {\n      try {\n        jsQr = await loadJsQr();\n        if (cancelled) {\n          return;\n        }\n        if (!navigator.mediaDevices?.getUserMedia) {\n          throw new Error('Camera access is not available in this browser.');\n        }\n        const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });\n        if (cancelled) {\n          mediaStream.getTracks().forEach((t) => t.stop());\n          return;\n        }\n        stream = mediaStream;\n        videoElement.srcObject = mediaStream;\n        videoElement.setAttribute('playsinline', 'true');\n        await videoElement.play();\n        if (!cancelled) {\n          rafId = requestAnimationFrame(tick);\n        }\n      } catch (err) {\n        fail(err);\n      }\n    }\n\n    start().catch(fail);\n\n    return () => {\n      cancelled = true;\n      cancelAnimationFrame(rafId);\n      stopStream();\n    };\n  }, [scanOnce, emitScan, emitError]);\n\n  return (\n    <Stack gap=\"sm\">\n      {error && <Alert color=\"red\">{error}</Alert>}\n      <Box\n        pos=\"relative\"\n        style={{\n          aspectRatio: '4 / 3',\n          display: error ? 'none' : 'block',\n          width: '100%',\n          maxHeight: '70vh',\n          overflow: 'hidden',\n          borderRadius: 'var(--mantine-radius-default)',\n          background: 'black',\n        }}\n      >\n        <video\n          ref={videoRef}\n          width={640}\n          height={480}\n          muted\n          style={{\n            display: 'block',\n            width: '100%',\n            height: '100%',\n            objectFit: 'cover',\n          }}\n        />\n        {loading && !error && (\n          <Center pos=\"absolute\" top={0} left={0} right={0} bottom={0} style={{ pointerEvents: 'none' }}>\n            <Stack gap=\"xs\" align=\"center\">\n              <Loader size=\"sm\" color=\"gray.3\" />\n              <Text c=\"gray.3\" size=\"sm\">\n                Loading camera...\n              </Text>\n            </Stack>\n          </Center>\n        )}\n      </Box>\n      <canvas ref={canvasRef} hidden />\n    </Stack>\n  );\n}\n\nasync function loadJsQr(): Promise<JsQr> {\n  if (!jsQrPromise) {\n    jsQrPromise = import('jsqr')\n      .then((module) => module.default as JsQr)\n      .catch((err) => {\n        jsQrPromise = undefined;\n        throw new Error(\n          `QR code scanning requires the optional \"jsqr\" dependency. Install jsqr to use QrCodeScanner. ${normalizeErrorString(\n            err\n          )}`\n        );\n      });\n  }\n  return jsQrPromise;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Box, Group, NativeSelect, Space, Textarea, TextInput, Title } from '@mantine/core';\nimport { getElementDefinition, isResource as isResourceType } from '@medplum/core';\nimport type {\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireItemAnswerOption,\n  Reference,\n  ResourceType,\n} from '@medplum/fhirtypes';\nimport {\n  getQuestionnaireItemReferenceTargetTypes,\n  isChoiceQuestion,\n  QUESTIONNAIRE_ITEM_CONTROL_URL,\n  QuestionnaireItemType,\n  setQuestionnaireItemReferenceTargetTypes,\n  useMedplum,\n  useResource,\n} from '@medplum/react-hooks';\nimport { IconArrowDown, IconArrowUp } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX, MouseEvent, SyntheticEvent } from 'react';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { QuestionnaireFormItem } from '../QuestionnaireForm/QuestionnaireFormItem';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport { killEvent } from '../utils/dom';\nimport classes from './QuestionnaireBuilder.module.css';\n\nexport interface QuestionnaireBuilderProps {\n  readonly questionnaire: Partial<Questionnaire> | Reference<Questionnaire>;\n  readonly onSubmit: (result: Questionnaire) => void;\n  readonly autoSave?: boolean;\n}\n\nexport function QuestionnaireBuilder(props: QuestionnaireBuilderProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const defaultValue = useResource(props.questionnaire);\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n  const [value, setValue] = useState<Questionnaire>();\n  const [selectedKey, setSelectedKey] = useState<string>();\n  const [hoverKey, setHoverKey] = useState<string>();\n\n  function handleDocumentMouseOver(): void {\n    setHoverKey(undefined);\n  }\n\n  function handleDocumentClick(): void {\n    setSelectedKey(undefined);\n  }\n\n  useEffect(() => {\n    medplum\n      .requestSchema('Questionnaire')\n      .then(() => setSchemaLoaded(true))\n      .catch(console.log);\n  }, [medplum]);\n\n  useEffect(() => {\n    setValue(ensureQuestionnaireKeys(defaultValue ?? { resourceType: 'Questionnaire', status: 'active' }));\n    document.addEventListener('mouseover', handleDocumentMouseOver);\n    document.addEventListener('click', handleDocumentClick);\n    return () => {\n      document.removeEventListener('mouseover', handleDocumentMouseOver);\n      document.removeEventListener('click', handleDocumentClick);\n    };\n  }, [defaultValue]);\n\n  const handleChange = (questionnaire: Questionnaire, disableSubmit?: boolean): void => {\n    setValue(questionnaire);\n    if (props.autoSave && !disableSubmit && props.onSubmit) {\n      props.onSubmit(questionnaire);\n    }\n  };\n\n  if (!schemaLoaded || !value) {\n    return null;\n  }\n\n  return (\n    <div>\n      <Form testid=\"questionnaire-form\" onSubmit={() => props.onSubmit(value)}>\n        <ItemBuilder\n          item={value}\n          selectedKey={selectedKey}\n          setSelectedKey={setSelectedKey}\n          hoverKey={hoverKey}\n          setHoverKey={setHoverKey}\n          onChange={handleChange}\n        />\n        <SubmitButton>Save</SubmitButton>\n      </Form>\n    </div>\n  );\n}\n\ninterface ItemBuilderProps<T extends Questionnaire | QuestionnaireItem> {\n  readonly item: T;\n  readonly selectedKey: string | undefined;\n  readonly setSelectedKey: (key: string | undefined) => void;\n  readonly hoverKey: string | undefined;\n  readonly isFirst?: boolean;\n  readonly isLast?: boolean;\n  readonly setHoverKey: (key: string | undefined) => void;\n  readonly onChange: (item: T, disableSubmit?: boolean) => void;\n  readonly onRemove?: () => void;\n  readonly onRepeatable?: (item: QuestionnaireItem) => void;\n  onMoveUp?(): void;\n  onMoveDown?(): void;\n}\n\nfunction ItemBuilder<T extends Questionnaire | QuestionnaireItem>(props: ItemBuilderProps<T>): JSX.Element {\n  const resource = props.item as Questionnaire;\n  const item = props.item as QuestionnaireItem;\n  const isResource = isResourceType(props.item);\n  const isContainer = isResource || item.type === QuestionnaireItemType.group;\n  const linkId = item.linkId ?? '[untitled]';\n  const editing = props.selectedKey === props.item.id;\n  const hovering = props.hoverKey === props.item.id;\n\n  const itemRef = useRef(props.item);\n  useLayoutEffect(() => {\n    itemRef.current = props.item;\n  });\n\n  function onClick(e: SyntheticEvent): void {\n    killEvent(e);\n    props.setSelectedKey(props.item.id);\n  }\n\n  function onHover(e: SyntheticEvent): void {\n    killEvent(e);\n    props.setHoverKey(props.item.id);\n  }\n\n  function changeItem(changedItem: QuestionnaireItem): void {\n    const curr = itemRef.current;\n    props.onChange({\n      ...curr,\n      item: curr.item?.map((i) => (i.id === changedItem.id ? changedItem : i)),\n    });\n  }\n\n  function addItem(addedItem: QuestionnaireItem, disableSubmit?: boolean): void {\n    props.onChange(\n      {\n        ...props.item,\n        item: [...(props.item.item ?? []), addedItem],\n      },\n      disableSubmit\n    );\n  }\n\n  function removeItem(removedItem: QuestionnaireItem): void {\n    props.onChange({\n      ...props.item,\n      item: props.item.item?.filter((i) => i !== removedItem),\n    });\n  }\n\n  function changeProperty(property: string, value: any): void {\n    props.onChange({\n      ...itemRef.current,\n      [property]: value,\n    });\n  }\n\n  function updateItem(updatedItem: QuestionnaireItem): void {\n    props.onChange({\n      ...props.item,\n      ...updatedItem,\n    });\n  }\n\n  function toggleRepeatable(item: QuestionnaireItem): void {\n    props.onChange({\n      ...props.item,\n      item: props.item.item?.map((i) => (i === item ? { ...i, repeats: !i.repeats } : i)),\n    });\n  }\n\n  function moveItem(itemIndex: number, delta: number): void {\n    const updatedItems = reorderItems(props.item.item, itemIndex, delta);\n\n    props.onChange({\n      ...props.item,\n      item: updatedItems,\n    });\n  }\n\n  const className = cx(classes.section, {\n    [classes.editing]: editing,\n    [classes.hovering]: hovering && !editing,\n  });\n\n  return (\n    <div data-testid={item.linkId} className={className} onClick={onClick} onMouseOver={onHover} onFocus={onHover}>\n      <div className={classes.questionBody}>\n        {editing ? (\n          <>\n            {isResource && (\n              <TextInput\n                size=\"xl\"\n                defaultValue={resource.title}\n                onBlur={(e) => changeProperty('title', e.currentTarget.value)}\n              />\n            )}\n            {!isResource && (\n              <Textarea\n                autosize\n                minRows={2}\n                defaultValue={item.text}\n                onBlur={(e) => changeProperty('text', e.currentTarget.value)}\n              />\n            )}\n            {item.type === 'reference' && <ReferenceProfiles item={item} onChange={updateItem} />}\n            {isChoiceQuestion(item) && <AnswerBuilder item={item} onChange={(item) => updateItem(item)} />}\n          </>\n        ) : (\n          <>\n            {resource.title && <Title>{resource.title}</Title>}\n            {item.text && <div className={classes.preserveBreaks}>{item.text}</div>}\n            {!isContainer && (\n              <QuestionnaireFormItem item={item} index={0} required={false} responseItem={{ linkId: item.linkId }} />\n            )}\n          </>\n        )}\n      </div>\n      {item.item?.map((item, i) => (\n        <div key={item.id}>\n          <ItemBuilder\n            item={item}\n            selectedKey={props.selectedKey}\n            setSelectedKey={props.setSelectedKey}\n            hoverKey={props.hoverKey}\n            isFirst={i === 0}\n            isLast={i === (props.item.item ?? []).length - 1}\n            setHoverKey={props.setHoverKey}\n            onChange={changeItem}\n            onRemove={() => removeItem(item)}\n            onRepeatable={toggleRepeatable}\n            onMoveUp={() => moveItem(i, -1)}\n            onMoveDown={() => moveItem(i, 1)}\n          />\n        </div>\n      ))}\n      {!isContainer && (\n        <div className={classes.topActions}>\n          {editing ? (\n            <>\n              <TextInput\n                size=\"xs\"\n                className={classes.linkIdInput}\n                defaultValue={item.linkId}\n                onBlur={(e) => changeProperty('linkId', e.currentTarget.value)}\n              />\n              {!isContainer && (\n                <NativeSelect\n                  size=\"xs\"\n                  className={classes.typeSelect}\n                  defaultValue={item.type}\n                  onChange={(e) => changeProperty('type', e.currentTarget.value)}\n                  data={[\n                    { value: 'display', label: 'Display' },\n                    { value: 'boolean', label: 'Boolean' },\n                    { value: 'decimal', label: 'Decimal' },\n                    { value: 'integer', label: 'Integer' },\n                    { value: 'date', label: 'Date' },\n                    { value: 'dateTime', label: 'Date/Time' },\n                    { value: 'time', label: 'Time' },\n                    { value: 'string', label: 'String' },\n                    { value: 'text', label: 'Text' },\n                    { value: 'url', label: 'URL' },\n                    { value: 'choice', label: 'Choice' },\n                    { value: 'open-choice', label: 'Open Choice' },\n                    { value: 'attachment', label: 'Attachment' },\n                    { value: 'reference', label: 'Reference' },\n                    { value: 'quantity', label: 'Quantity' },\n                  ]}\n                />\n              )}\n            </>\n          ) : (\n            <div>{linkId}</div>\n          )}\n        </div>\n      )}\n      {!isResource && (\n        <Box className={classes.movementActions}>\n          <Box className={classes.columnAlignment}>\n            {!props.isFirst && (\n              <Anchor\n                href=\"#\"\n                onClick={(e: MouseEvent) => {\n                  e.preventDefault();\n                  if (props.onMoveUp) {\n                    props.onMoveUp();\n                  }\n                }}\n              >\n                <IconArrowUp data-testid=\"up-button\" size={15} className={classes.movementIcons} />\n              </Anchor>\n            )}\n            {!props.isLast && (\n              <Anchor\n                href=\"#\"\n                onClick={(e: MouseEvent) => {\n                  e.preventDefault();\n                  if (props.onMoveDown) {\n                    props.onMoveDown();\n                  }\n                }}\n              >\n                <IconArrowDown data-testid=\"down-button\" size={15} className={classes.movementIcons} />\n              </Anchor>\n            )}\n          </Box>\n        </Box>\n      )}\n      <div className={classes.bottomActions}>\n        {isContainer && (\n          <>\n            <Anchor\n              href=\"#\"\n              onClick={(e: MouseEvent) => {\n                e.preventDefault();\n                addItem({\n                  id: generateId(),\n                  linkId: generateLinkId('q'),\n                  type: 'string',\n                  text: 'Question',\n                });\n              }}\n            >\n              Add item\n            </Anchor>\n            <Anchor\n              href=\"#\"\n              onClick={(e: MouseEvent) => {\n                e.preventDefault();\n                addItem(\n                  {\n                    id: generateId(),\n                    linkId: generateLinkId('g'),\n                    type: 'group',\n                    text: 'Group',\n                  },\n                  true\n                );\n              }}\n            >\n              Add group\n            </Anchor>\n          </>\n        )}\n        {isResource && (\n          <Anchor\n            href=\"#\"\n            onClick={(e: MouseEvent) => {\n              e.preventDefault();\n              addItem(createPage(), true);\n            }}\n          >\n            Add Page\n          </Anchor>\n        )}\n        {editing && !isResource && (\n          <>\n            <Anchor\n              href=\"#\"\n              onClick={(e: MouseEvent) => {\n                e.preventDefault();\n                if (props.onRepeatable) {\n                  props.onRepeatable(item);\n                }\n              }}\n            >\n              {item.repeats ? 'Remove Repeatable' : 'Make Repeatable'}\n            </Anchor>\n            <Anchor\n              href=\"#\"\n              onClick={(e: MouseEvent) => {\n                e.preventDefault();\n                if (props.onRemove) {\n                  props.onRemove();\n                }\n              }}\n            >\n              Remove\n            </Anchor>\n          </>\n        )}\n      </div>\n    </div>\n  );\n}\n\ninterface AnswerBuilderProps {\n  readonly item: QuestionnaireItem;\n  readonly onChange: (item: QuestionnaireItem) => void;\n}\n\nfunction AnswerBuilder(props: AnswerBuilderProps): JSX.Element {\n  const property = getElementDefinition('QuestionnaireItemAnswerOption', 'value[x]');\n  const options = props.item.answerOption ?? [];\n  return (\n    <div>\n      {props.item.answerValueSet !== undefined ? (\n        <TextInput\n          placeholder=\"Enter Value Set\"\n          defaultValue={props.item.answerValueSet}\n          onChange={(e) => props.onChange({ ...props.item, answerValueSet: e.target.value })}\n        />\n      ) : (\n        <AnswerOptionsInput options={options} property={property} item={props.item} onChange={props.onChange} />\n      )}\n      <Box display=\"flex\">\n        <Anchor\n          href=\"#\"\n          onClick={(e: SyntheticEvent) => {\n            killEvent(e);\n            props.onChange({\n              ...props.item,\n              answerValueSet: undefined,\n              answerOption: [\n                ...options,\n                {\n                  id: generateId(),\n                },\n              ],\n            });\n          }}\n        >\n          Add choice\n        </Anchor>\n        <Space w=\"lg\" />\n        <Anchor\n          href=\"#\"\n          onClick={(e: SyntheticEvent) => {\n            killEvent(e);\n            props.onChange({\n              ...props.item,\n              answerOption: [],\n              answerValueSet: '',\n            });\n          }}\n        >\n          Add value set\n        </Anchor>\n      </Box>\n    </div>\n  );\n}\n\ninterface AnswerOptionsInputProps {\n  readonly options: QuestionnaireItemAnswerOption[];\n  readonly property: any;\n  readonly item: QuestionnaireItem;\n  readonly onChange: (item: QuestionnaireItem) => void;\n}\n\nfunction AnswerOptionsInput(props: AnswerOptionsInputProps): JSX.Element {\n  return (\n    <div>\n      {props.options.map((option: QuestionnaireItemAnswerOption) => {\n        const [propertyValue, propertyType] = getValueAndType(\n          { type: 'QuestionnaireItemAnswerOption', value: option },\n          'value'\n        );\n        return (\n          <div\n            key={option.id}\n            style={{\n              display: 'flex',\n              flexDirection: 'row',\n              justifyContent: 'space-between',\n              alignItems: 'center',\n              width: '80%',\n            }}\n          >\n            <div>\n              <ResourcePropertyInput\n                key={option.id}\n                name=\"value[x]\"\n                path=\"Questionnaire.answerOption.value[x]\"\n                property={props.property}\n                defaultPropertyType={propertyType}\n                defaultValue={propertyValue}\n                onChange={(newValue: any, propName?: string) => {\n                  const newOptions = [...props.options];\n                  const index = newOptions.findIndex((o) => o.id === option.id);\n                  newOptions[index] = { id: option.id, [propName as string]: newValue };\n                  props.onChange({\n                    ...props.item,\n                    answerOption: newOptions,\n                  });\n                }}\n                outcome={undefined}\n              />\n            </div>\n\n            <div>\n              <Anchor\n                href=\"#\"\n                onClick={(e: SyntheticEvent) => {\n                  killEvent(e);\n                  props.onChange({\n                    ...props.item,\n                    answerOption: props.options.filter((o) => o.id !== option.id),\n                  });\n                }}\n              >\n                Remove\n              </Anchor>\n            </div>\n          </div>\n        );\n      })}\n    </div>\n  );\n}\n\ninterface ReferenceTypeProps {\n  readonly item: QuestionnaireItem;\n  readonly onChange: (updatedItem: QuestionnaireItem) => void;\n}\n\nfunction ReferenceProfiles(props: ReferenceTypeProps): JSX.Element {\n  const targetTypes = getQuestionnaireItemReferenceTargetTypes(props.item) ?? [];\n  return (\n    <>\n      {targetTypes.map((targetType: ResourceType, index: number) => {\n        return (\n          <Group key={`${targetType}-${index}`}>\n            <ResourceTypeInput\n              name=\"resourceType\"\n              placeholder=\"Resource Type\"\n              defaultValue={targetType}\n              onChange={(newValue) => {\n                props.onChange(\n                  setQuestionnaireItemReferenceTargetTypes(\n                    props.item,\n                    targetTypes.map((t) => (t === targetType ? (newValue as ResourceType) : t))\n                  )\n                );\n              }}\n            />\n            <Anchor\n              href=\"#\"\n              onClick={(e: SyntheticEvent) => {\n                killEvent(e);\n                props.onChange(\n                  setQuestionnaireItemReferenceTargetTypes(\n                    props.item,\n                    targetTypes.filter((t) => t !== targetType)\n                  )\n                );\n              }}\n            >\n              Remove\n            </Anchor>\n          </Group>\n        );\n      })}\n      <Anchor\n        href=\"#\"\n        onClick={(e: SyntheticEvent) => {\n          killEvent(e);\n          props.onChange(setQuestionnaireItemReferenceTargetTypes(props.item, [...targetTypes, '' as ResourceType]));\n        }}\n      >\n        Add Resource Type\n      </Anchor>\n    </>\n  );\n}\n\nlet nextLinkId = 1;\nlet nextId = 1;\n\n/**\n * Generates a link ID for an item.\n * Link IDs are required properties on QuestionnaireItem objects.\n * @param prefix - The link ID prefix string.\n * @returns A unique link ID.\n */\nfunction generateLinkId(prefix: string): string {\n  return prefix + nextLinkId++;\n}\n\n/**\n * Generates a unique ID.\n * React needs unique IDs for components for rendering performance.\n * All of the important components in the questionnaire builder have id properties for this:\n * Questionnaire, QuestionnaireItem, and QuestionnaireItemAnswerOption.\n * @returns A unique key.\n */\nfunction generateId(): string {\n  return 'id-' + nextId++;\n}\n\nfunction ensureQuestionnaireKeys(questionnaire: Questionnaire): Questionnaire {\n  return {\n    ...questionnaire,\n    id: questionnaire.id || generateId(),\n    item: ensureQuestionnaireItemKeys(questionnaire.item),\n  };\n}\n\nfunction ensureQuestionnaireItemKeys(items: QuestionnaireItem[] | undefined): QuestionnaireItem[] | undefined {\n  if (!items) {\n    return undefined;\n  }\n  items.forEach((item) => {\n    if (item.id?.match(/^id-\\d+$/)) {\n      nextId = Math.max(nextId, Number.parseInt(item.id.substring(3), 10) + 1);\n    }\n    if (item.linkId?.match(/^q\\d+$/)) {\n      nextLinkId = Math.max(nextLinkId, Number.parseInt(item.linkId.substring(1), 10) + 1);\n    }\n  });\n  return items.map((item) => ({\n    ...item,\n    id: item.id || generateId(),\n    item: ensureQuestionnaireItemKeys(item.item),\n    answerOption: ensureQuestionnaireOptionKeys(item.answerOption),\n  }));\n}\n\nfunction ensureQuestionnaireOptionKeys(\n  options: QuestionnaireItemAnswerOption[] | undefined\n): QuestionnaireItemAnswerOption[] | undefined {\n  if (!options) {\n    return undefined;\n  }\n  return options.map((option) => ({\n    ...option,\n    id: option.id || generateId(),\n  }));\n}\n\nfunction createPage(): QuestionnaireItem {\n  return {\n    id: generateId(),\n    linkId: generateLinkId('s'),\n    type: 'group',\n    text: `New Page`,\n    extension: [\n      {\n        url: QUESTIONNAIRE_ITEM_CONTROL_URL,\n        valueCodeableConcept: {\n          coding: [\n            {\n              system: 'http://hl7.org/fhir/questionnaire-item-control',\n              code: 'page',\n            },\n          ],\n        },\n      },\n    ],\n  };\n}\n\nfunction reorderItems(items: QuestionnaireItem[] | undefined, itemIndex: number, delta: number): QuestionnaireItem[] {\n  const currentItems = items ?? [];\n  const newIndex = itemIndex + delta;\n  if (newIndex < 0 || newIndex >= currentItems.length) {\n    return currentItems;\n  }\n\n  const updatedItems = [...currentItems];\n  [updatedItems[itemIndex], updatedItems[newIndex]] = [updatedItems[newIndex], updatedItems[itemIndex]];\n\n  return updatedItems;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { ComboboxItem } from '@mantine/core';\nimport { Box, Checkbox, Group, MultiSelect, NativeSelect, Radio, Text, Textarea, TextInput } from '@mantine/core';\nimport type { TypedValue } from '@medplum/core';\nimport {\n  capitalize,\n  deepEquals,\n  formatCoding,\n  getElementDefinition,\n  getExtension,\n  HTTP_HL7_ORG,\n  stringify,\n  typedValueToString,\n} from '@medplum/core';\nimport type {\n  Coding,\n  QuestionnaireItem,\n  QuestionnaireItemAnswerOption,\n  QuestionnaireItemInitial,\n  QuestionnaireResponseItem,\n  QuestionnaireResponseItemAnswer,\n  ValueSet,\n  ValueSetExpansionContains,\n} from '@medplum/fhirtypes';\nimport type { QuestionnaireFormLoadedState } from '@medplum/react-hooks';\nimport {\n  getItemAnswerOptionValue,\n  getItemInitialValue,\n  getNewMultiSelectValues,\n  getQuestionnaireItemReferenceFilter,\n  getQuestionnaireItemReferenceTargetTypes,\n  isValueSetUnavailableError,\n  QUESTIONNAIRE_ITEM_CONTROL_URL,\n  QuestionnaireItemType,\n  useMedplum,\n} from '@medplum/react-hooks';\nimport type { ChangeEvent, JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { AttachmentInput } from '../AttachmentInput/AttachmentInput';\nimport { CheckboxFormSection } from '../CheckboxFormSection/CheckboxFormSection';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ReferenceInput } from '../ReferenceInput/ReferenceInput';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { UnavailableNote } from '../UnavailableNote/UnavailableNote';\nimport { ValueSetAutocomplete } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nconst MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS = 30;\nconst MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS = 50;\n\nexport interface QuestionnaireFormItemProps {\n  readonly formState?: QuestionnaireFormLoadedState;\n  readonly context?: QuestionnaireResponseItem[];\n  readonly item: QuestionnaireItem;\n  readonly index: number;\n  readonly required?: boolean;\n  readonly responseItem: QuestionnaireResponseItem;\n}\n\nexport function QuestionnaireFormItem(props: QuestionnaireFormItemProps): JSX.Element | null {\n  const formState = props.formState;\n  const item = props.item;\n  const response = props.responseItem;\n\n  function onChangeAnswer(newResponseAnswer: QuestionnaireResponseItemAnswer[]): void {\n    if (formState && props.context) {\n      // For repeating non-choice items, we need to update only the specific index\n      // Choice items (checkboxes, dropdowns) manage multiple answers internally\n      const isNonChoiceRepeating =\n        item.repeats &&\n        props.index !== undefined &&\n        item.type !== QuestionnaireItemType.choice &&\n        item.type !== QuestionnaireItemType.openChoice;\n\n      if (isNonChoiceRepeating) {\n        const currentAnswers = response.answer || [];\n        const updatedAnswers = [...currentAnswers];\n\n        if (newResponseAnswer.length === 0) {\n          // Remove the answer at this index\n          updatedAnswers.splice(props.index, 1);\n        } else {\n          // Update the answer at this index\n          updatedAnswers[props.index] = newResponseAnswer[0];\n        }\n\n        formState.onChangeAnswer(props.context, props.item, updatedAnswers);\n      } else {\n        formState.onChangeAnswer(props.context, props.item, newResponseAnswer);\n      }\n    }\n  }\n\n  const type = item.type;\n  if (!type) {\n    return null;\n  }\n\n  const name = item.linkId;\n  if (!name) {\n    return null;\n  }\n\n  // For repeating non-choice items, generate a unique id by including the index\n  // Choice items render once and manage multiple answers internally, so they keep the same id\n  const isNonChoiceRepeating =\n    item.repeats &&\n    props.index !== undefined &&\n    item.type !== QuestionnaireItemType.choice &&\n    item.type !== QuestionnaireItemType.openChoice;\n  const inputId = isNonChoiceRepeating ? `${name}-${props.index}` : name;\n\n  let initial: QuestionnaireItemInitial | undefined = undefined;\n  if (item.initial && item.initial.length > 0) {\n    initial = item.initial[0];\n  } else if (item.answerOption && item.answerOption.length > 0) {\n    initial = item.answerOption.find((option) => option.initialSelected);\n  }\n\n  const defaultValue = getCurrentAnswer(response, props.index) ?? getItemInitialValue(initial);\n  const validationError = getExtension(\n    response,\n    `${HTTP_HL7_ORG}/fhir/StructureDefinition/questionnaire-validationError`\n  );\n\n  let formComponent: JSX.Element | null = null;\n\n  switch (type) {\n    case QuestionnaireItemType.display:\n      formComponent = <p key={props.item.linkId}>{props.item.text}</p>;\n      break;\n    case QuestionnaireItemType.boolean:\n      formComponent = (\n        <CheckboxFormSection key={props.item.linkId} title={props.item.text} htmlFor={inputId}>\n          <Checkbox\n            id={inputId}\n            name={name}\n            required={props.required ?? item.required}\n            defaultChecked={defaultValue?.value}\n            onChange={(e) => onChangeAnswer([{ valueBoolean: e.currentTarget.checked }])}\n          />\n        </CheckboxFormSection>\n      );\n      break;\n    case QuestionnaireItemType.decimal:\n      formComponent = (\n        <TextInput\n          type=\"number\"\n          step=\"any\"\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) =>\n            onChangeAnswer(e.currentTarget.value === '' ? [] : [{ valueDecimal: e.currentTarget.valueAsNumber }])\n          }\n        />\n      );\n      break;\n    case QuestionnaireItemType.integer:\n      formComponent = (\n        <TextInput\n          type=\"number\"\n          step={1}\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) =>\n            onChangeAnswer(e.currentTarget.value === '' ? [] : [{ valueInteger: e.currentTarget.valueAsNumber }])\n          }\n        />\n      );\n      break;\n    case QuestionnaireItemType.date:\n      formComponent = (\n        <TextInput\n          type=\"date\"\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) => onChangeAnswer([{ valueDate: e.currentTarget.value }])}\n        />\n      );\n      break;\n    case QuestionnaireItemType.dateTime:\n      formComponent = (\n        <DateTimeInput\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(newValue: string) => onChangeAnswer([{ valueDateTime: newValue }])}\n        />\n      );\n      break;\n    case QuestionnaireItemType.time:\n      formComponent = (\n        <TextInput\n          type=\"time\"\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) => onChangeAnswer([{ valueTime: e.currentTarget.value }])}\n        />\n      );\n      break;\n    case QuestionnaireItemType.string:\n    case QuestionnaireItemType.url:\n      formComponent = (\n        <TextInput\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) => {\n            const value = e.currentTarget.value;\n            onChangeAnswer(value === '' ? [] : [{ valueString: value }]);\n          }}\n        />\n      );\n      break;\n    case QuestionnaireItemType.text:\n      formComponent = (\n        <Textarea\n          id={inputId}\n          name={name}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(e) => {\n            const value = e.currentTarget.value;\n            onChangeAnswer(value === '' ? [] : [{ valueString: value }]);\n          }}\n        />\n      );\n      break;\n    case QuestionnaireItemType.attachment:\n      formComponent = (\n        <Group py={4}>\n          <AttachmentInput\n            path=\"\"\n            name={inputId}\n            defaultValue={defaultValue?.value}\n            onChange={(newValue) => onChangeAnswer([{ valueAttachment: newValue }])}\n          />\n        </Group>\n      );\n      break;\n    case QuestionnaireItemType.reference:\n      formComponent = (\n        <ReferenceInput\n          name={inputId}\n          required={props.required ?? item.required}\n          targetTypes={getQuestionnaireItemReferenceTargetTypes(item)}\n          searchCriteria={getQuestionnaireItemReferenceFilter(item, formState?.subject, formState?.encounter)}\n          defaultValue={defaultValue?.value}\n          onChange={(newValue) => onChangeAnswer([{ valueReference: newValue }])}\n        />\n      );\n      break;\n    case QuestionnaireItemType.quantity:\n      formComponent = (\n        <QuantityInput\n          path=\"\"\n          name={inputId}\n          required={props.required ?? item.required}\n          defaultValue={defaultValue?.value}\n          onChange={(newValue) => onChangeAnswer([{ valueQuantity: newValue }])}\n          disableWheel\n        />\n      );\n      break;\n    case QuestionnaireItemType.choice:\n    case QuestionnaireItemType.openChoice:\n      {\n        const { widget, multiselect } = resolveChoiceControl(item);\n        const sharedProps = {\n          name: inputId,\n          item,\n          required: props.required ?? item.required,\n          initial,\n          response,\n          multiselect,\n          onChangeAnswer,\n        };\n        if (widget === 'check-box') {\n          formComponent = <QuestionnaireCheckboxInput {...sharedProps} />;\n        } else if (widget === 'drop-down') {\n          formComponent = <QuestionnaireDropdownInput {...sharedProps} />;\n        } else {\n          formComponent = <QuestionnaireRadioButtonInput {...sharedProps} />;\n        }\n      }\n      break;\n    default:\n      return null;\n  }\n\n  return (\n    <>\n      {formComponent}\n      {validationError?.valueString && (\n        <Text c=\"red\" size=\"lg\" mt={4}>\n          {validationError.valueString}\n        </Text>\n      )}\n    </>\n  );\n}\n\ninterface QuestionnaireChoiceInputProps {\n  readonly name: string;\n  readonly item: QuestionnaireItem;\n  readonly initial: QuestionnaireItemInitial | undefined;\n  readonly multiselect?: boolean;\n  readonly required: boolean | undefined;\n  readonly response?: QuestionnaireResponseItem;\n  readonly onChangeAnswer: (newResponseAnswer: QuestionnaireResponseItemAnswer[]) => void;\n}\n\nfunction QuestionnaireDropdownInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n  const { name, item, required, initial, onChangeAnswer, response, multiselect } = props;\n\n  if (!item.answerOption?.length && !item.answerValueSet) {\n    return <NoAnswerDisplay />;\n  }\n\n  const initialValue = getItemInitialValue(initial);\n  const defaultValue = getCurrentAnswer(response) ?? initialValue;\n  const currentAnswer = getCurrentMultiSelectAnswer(response);\n  const isMultiSelect = item.repeats || multiselect;\n\n  if (item.answerValueSet) {\n    return (\n      <ValueSetAutocomplete\n        name={name}\n        placeholder=\"Select items\"\n        binding={item.answerValueSet}\n        maxValues={isMultiSelect ? undefined : 1}\n        required={required}\n        onChange={(values) => {\n          if (isMultiSelect) {\n            if (values.length === 0) {\n              onChangeAnswer([{}]);\n            } else {\n              onChangeAnswer(values.map((coding) => ({ valueCoding: coding })));\n            }\n          } else {\n            onChangeAnswer([{ valueCoding: values[0] }]);\n          }\n        }}\n        defaultValue={defaultValue?.value}\n      />\n    );\n  }\n\n  if (isMultiSelect) {\n    const { propertyName, data } = formatSelectData(item);\n    return (\n      <MultiSelect\n        data={data}\n        placeholder=\"Select items\"\n        searchable\n        value={currentAnswer}\n        required={required}\n        onChange={(selected) => {\n          if (selected.length === 0) {\n            onChangeAnswer([{}]);\n          } else {\n            const values = getNewMultiSelectValues(selected, propertyName, item);\n            onChangeAnswer(values);\n          }\n        }}\n      />\n    );\n  } else {\n    const data = [''];\n    if (item.answerOption) {\n      for (const option of item.answerOption) {\n        const optionValue = getItemAnswerOptionValue(option);\n        data.push(typedValueToString(optionValue));\n      }\n    }\n    return (\n      <NativeSelect\n        id={name}\n        name={name}\n        required={required}\n        onChange={(e: ChangeEvent<HTMLSelectElement>) => {\n          const index = e.currentTarget.selectedIndex;\n          if (index === 0) {\n            onChangeAnswer([{}]);\n            return;\n          }\n          const option = (item.answerOption as QuestionnaireItemAnswerOption[])[index - 1];\n          const optionValue = getItemAnswerOptionValue(option);\n          const propertyName = 'value' + capitalize(optionValue.type);\n          onChangeAnswer([{ [propertyName]: optionValue.value }]);\n        }}\n        defaultValue={formatCoding(defaultValue?.value) || defaultValue?.value}\n        data={data}\n      />\n    );\n  }\n}\n\nfunction getValueSetOptions(\n  valueSetUrl: string | undefined,\n  medplum: ReturnType<typeof useMedplum>\n): Promise<ValueSetExpansionContains[]> {\n  if (!valueSetUrl) {\n    return Promise.resolve([]);\n  }\n\n  return medplum\n    .valueSetExpand({\n      url: valueSetUrl,\n      count: MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS + 1,\n    })\n    .then((valueSet: ValueSet) => valueSet.expansion?.contains ?? []);\n}\n\ninterface ValueSetOptionsState {\n  readonly options: ValueSetExpansionContains[];\n  readonly loading: boolean;\n  readonly available: boolean | undefined;\n}\n\nfunction useValueSetOptions(valueSetUrl: string | undefined): ValueSetOptionsState {\n  const medplum = useMedplum();\n  const [valueSetOptions, setValueSetOptions] = useState<ValueSetExpansionContains[]>([]);\n  const [isLoading, setIsLoading] = useState(false);\n  const [isAvailable, setIsAvailable] = useState<boolean | undefined>(() => (valueSetUrl ? undefined : true));\n\n  useEffect(() => {\n    async function loadValueSet(): Promise<void> {\n      if (!valueSetUrl) {\n        setIsAvailable(true);\n        return;\n      }\n\n      setIsLoading(true);\n      setIsAvailable(undefined);\n      try {\n        const options = await getValueSetOptions(valueSetUrl, medplum);\n        setValueSetOptions(options);\n        setIsAvailable(true);\n      } catch (err) {\n        // A permanent 400/404 marks it unavailable; a transient failure keeps the field usable\n        const unavailable = isValueSetUnavailableError(err);\n        setIsAvailable(!unavailable);\n        if (!unavailable) {\n          console.error('Error loading value set:', err);\n        }\n      } finally {\n        setIsLoading(false);\n      }\n    }\n\n    loadValueSet().catch(console.error);\n  }, [valueSetUrl, medplum]);\n\n  return { options: valueSetOptions, loading: isLoading, available: isAvailable };\n}\n\n// Radio and checkbox items can only offer the answers their value set provides, so an unavailable\n// value set leaves nothing to pick and the question cannot be answered at all.\nfunction ValueSetUnavailableDisplay({ valueSetUrl }: { readonly valueSetUrl: string | undefined }): JSX.Element {\n  return (\n    <Box>\n      <UnavailableNote\n        text=\"This question is unavailable.\"\n        severity=\"error\"\n        message={`Value set ${valueSetUrl} is unavailable`}\n      />\n    </Box>\n  );\n}\n\nfunction getOptionsFromValueSet(valueSetOptions: ValueSetExpansionContains[], name: string): [string, TypedValue][] {\n  return valueSetOptions.map((option, i) => {\n    const optionName = `${name}-valueset-${i}`;\n    const optionValue = {\n      type: 'Coding',\n      value: {\n        system: option.system,\n        code: option.code,\n        display: option.display,\n      },\n    };\n    return [optionName, optionValue];\n  });\n}\n\nfunction QuestionnaireRadioButtonInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n  const { name, item, required, initial, onChangeAnswer, response } = props;\n  const valueElementDefinition = getElementDefinition('QuestionnaireItemAnswerOption', 'value[x]');\n  const initialValue = getItemInitialValue(initial);\n  const {\n    options: valueSetOptions,\n    loading: isLoading,\n    available: isValueSetAvailable,\n  } = useValueSetOptions(item.answerValueSet);\n\n  const options: [string, TypedValue][] = [];\n  let defaultValue = undefined;\n\n  if (item.answerValueSet) {\n    options.push(...getOptionsFromValueSet(valueSetOptions, name));\n  } else if (item.answerOption) {\n    const mappedOptions = item.answerOption\n      .slice(0, MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)\n      .map((option, i) => {\n        const optionName = `${name}-option-${i}`;\n        const optionValue = getItemAnswerOptionValue(option);\n        if (!optionValue?.value) {\n          return null;\n        }\n        if (initialValue && stringify(optionValue) === stringify(initialValue)) {\n          defaultValue = optionName;\n        }\n        return [optionName, optionValue] as [string, TypedValue];\n      })\n      .filter((option): option is [string, TypedValue] => option !== null);\n\n    options.push(...mappedOptions);\n  }\n\n  const defaultAnswer = getCurrentAnswer(response);\n  const answerLinkId = getCurrentRadioAnswer(options, defaultAnswer);\n\n  if (isLoading) {\n    return <Text>Loading options...</Text>;\n  }\n\n  if (options.length === 0) {\n    return isValueSetAvailable === false ? (\n      <ValueSetUnavailableDisplay valueSetUrl={item.answerValueSet} />\n    ) : (\n      <NoAnswerDisplay />\n    );\n  }\n\n  const limitedOptions = options.slice(0, MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS);\n\n  return (\n    <>\n      <Radio.Group\n        name={name}\n        value={answerLinkId ?? defaultValue}\n        required={required}\n        onChange={(newValue) => {\n          const option = options.find((option) => option[0] === newValue);\n          if (option) {\n            const optionValue = option[1];\n            const propertyName = 'value' + capitalize(optionValue.type);\n            onChangeAnswer([{ [propertyName]: optionValue.value }]);\n          }\n        }}\n      >\n        {limitedOptions.map(([optionName, optionValue]) => (\n          <Radio\n            key={optionName}\n            id={optionName}\n            value={optionName}\n            py={4}\n            required={required}\n            label={\n              <ResourcePropertyDisplay\n                property={valueElementDefinition}\n                propertyType={optionValue.type}\n                value={optionValue.value}\n              />\n            }\n          />\n        ))}\n      </Radio.Group>\n      {((item.answerValueSet && options.length > MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS) ||\n        (item.answerOption && options.length > MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)) && (\n        <Text size=\"sm\" c=\"dimmed\" mt=\"xs\">\n          Showing first {MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS} options\n        </Text>\n      )}\n    </>\n  );\n}\n\nfunction QuestionnaireCheckboxInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n  const { name, item, onChangeAnswer, response } = props;\n  const valueElementDefinition = getElementDefinition('QuestionnaireItemAnswerOption', 'value[x]');\n  const {\n    options: valueSetOptions,\n    loading: isLoading,\n    available: isValueSetAvailable,\n  } = useValueSetOptions(item.answerValueSet);\n\n  // Derive the selected values from the response rather than local state, so that answers\n  // rewritten by the form state (e.g. optionExclusive) are reflected in the checkboxes.\n  const selectedValues = item.answerValueSet\n    ? (response?.answer?.map((a) => a.valueCoding) || []).filter((c): c is Coding => c !== undefined)\n    : getCurrentMultiSelectAnswer(response);\n\n  const options: [string, TypedValue][] = [];\n\n  if (item.answerValueSet) {\n    options.push(...getOptionsFromValueSet(valueSetOptions, name));\n  } else if (item.answerOption) {\n    const mappedOptions = item.answerOption\n      .slice(0, MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)\n      .map((option, i) => {\n        const optionName = `${name}-option-${i}`;\n        const optionValue = getItemAnswerOptionValue(option);\n        return optionValue?.value ? ([optionName, optionValue] as [string, TypedValue]) : null;\n      })\n      .filter((option): option is [string, TypedValue] => option !== null);\n\n    options.push(...mappedOptions);\n  }\n\n  if (isLoading) {\n    return <Text>Loading options...</Text>;\n  }\n\n  if (options.length === 0) {\n    return isValueSetAvailable === false ? (\n      <ValueSetUnavailableDisplay valueSetUrl={item.answerValueSet} />\n    ) : (\n      <NoAnswerDisplay />\n    );\n  }\n\n  const limitedOptions = options.slice(0, MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS);\n\n  const handleCheckboxChange = (optionValue: TypedValue, selected: boolean): void => {\n    if (item.answerValueSet) {\n      const currentCodings = selectedValues as Coding[];\n      let newCodings: Coding[];\n\n      if (selected) {\n        newCodings = [...currentCodings, optionValue.value as Coding];\n      } else {\n        newCodings = currentCodings.filter((c) => !deepEquals(c, optionValue.value));\n      }\n\n      if (newCodings.length === 0) {\n        onChangeAnswer([{}]);\n      } else {\n        onChangeAnswer(newCodings.map((coding) => ({ valueCoding: coding })));\n      }\n    } else {\n      const currentValues = selectedValues as string[];\n      const optionValueStr = typedValueToString(optionValue);\n      let newValues: string[];\n\n      if (selected) {\n        newValues = [...currentValues, optionValueStr];\n      } else {\n        newValues = currentValues.filter((v) => v !== optionValueStr);\n      }\n\n      if (newValues.length === 0) {\n        onChangeAnswer([{}]);\n      } else {\n        const values = getNewMultiSelectValues(newValues, 'value' + capitalize(optionValue.type), item);\n        onChangeAnswer(values);\n      }\n    }\n  };\n\n  return (\n    <Group style={{ flexDirection: 'column', alignItems: 'flex-start' }}>\n      {limitedOptions.map(([optionName, optionValue]) => {\n        const optionValueStr = typedValueToString(optionValue);\n        const isChecked = item.answerValueSet\n          ? (selectedValues as Coding[]).some((coding) => deepEquals(coding, optionValue.value))\n          : (selectedValues as string[]).includes(optionValueStr);\n\n        return (\n          <Checkbox\n            key={optionName}\n            id={optionName}\n            label={\n              <ResourcePropertyDisplay\n                property={valueElementDefinition}\n                propertyType={optionValue.type}\n                value={optionValue.value}\n              />\n            }\n            checked={isChecked}\n            onChange={(event) => handleCheckboxChange(optionValue, event.currentTarget.checked)}\n          />\n        );\n      })}\n      {((item.answerValueSet && options.length > MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS) ||\n        (item.answerOption && options.length > MAX_DISPLAYED_CHECKBOX_RADIO_EXPLICITOPTION_OPTIONS)) && (\n        <Text size=\"sm\" c=\"dimmed\">\n          Showing first {MAX_DISPLAYED_CHECKBOX_RADIO_VALUE_SET_OPTIONS} options\n        </Text>\n      )}\n    </Group>\n  );\n}\n\nfunction NoAnswerDisplay(): JSX.Element {\n  return <TextInput disabled placeholder=\"No Answers Defined\" />;\n}\n\nfunction getCurrentAnswer(response: QuestionnaireResponseItem | undefined, index: number = 0): TypedValue {\n  return getItemAnswerOptionValue(response?.answer?.[index] ?? {});\n}\n\nfunction getCurrentMultiSelectAnswer(response: QuestionnaireResponseItem | undefined): string[] {\n  const results = response?.answer;\n  if (!results) {\n    return [];\n  }\n  const typedValues = results.map((a) => getItemAnswerOptionValue(a));\n  return typedValues.map((type) => formatCoding(type?.value) || type?.value).filter(Boolean);\n}\n\nfunction getCurrentRadioAnswer(options: [string, TypedValue][], defaultAnswer: TypedValue): string | undefined {\n  return options.find((option) => deepEquals(option[1].value, defaultAnswer?.value))?.[0];\n}\n\ntype ChoiceControl = {\n  widget: 'drop-down' | 'radio-button' | 'check-box';\n  multiselect: boolean;\n};\n\nconst choiceTypes: ChoiceControl['widget'][] = ['drop-down', 'radio-button', 'check-box'];\n\n/**\n * Determines the choice control type (dropdown, radio button, or checkbox) based on the questionnaire item properties and extensions.\n * @param item - The questionnaire item to evaluate.\n * @returns The resolved choice control type and whether it is multi-select.\n */\nfunction resolveChoiceControl(item: QuestionnaireItem): ChoiceControl {\n  let widget: ChoiceControl['widget'] = 'radio-button';\n  let multiselect = false;\n\n  if (item.answerValueSet) {\n    // Preserve existing behavior of using dropdown for answerValueSet,\n    // since it can contain many options and radio buttons don't work well in that case\n    widget = 'drop-down';\n  }\n\n  for (const ext of item.extension ?? []) {\n    if (ext.url !== QUESTIONNAIRE_ITEM_CONTROL_URL) {\n      continue;\n    }\n    const code = ext.valueCodeableConcept?.coding?.[0]?.code;\n    if (choiceTypes.includes(code as ChoiceControl['widget'])) {\n      widget = code as ChoiceControl['widget'];\n    }\n    if (code === 'multi-select') {\n      multiselect = true;\n    }\n  }\n\n  if (widget === 'radio-button' && multiselect) {\n    widget = 'check-box';\n  }\n\n  return { widget, multiselect };\n}\n\ninterface FormattedData {\n  readonly propertyName: string;\n  readonly data: ComboboxItem[];\n}\n\nfunction formatSelectData(item: QuestionnaireItem): FormattedData {\n  if (item.answerOption?.length === 0) {\n    return { propertyName: '', data: [] };\n  }\n  const option = (item.answerOption as QuestionnaireItemAnswerOption[])[0];\n  const optionValue = getItemAnswerOptionValue(option);\n  const propertyName = 'value' + capitalize(optionValue.type);\n\n  const data = (item.answerOption ?? []).map((answerOption) => {\n    const answerOptionValue = getItemAnswerOptionValue(answerOption);\n    const answerOptionValueStr = typedValueToString(answerOptionValue);\n    return {\n      value: answerOptionValueStr,\n      label: answerOptionValueStr,\n    };\n  });\n  return { propertyName, data };\n}\n", ".section {\n  position: relative;\n  margin: 4px 4px 8px;\n  padding: 6px 12px 16px 6px;\n  border: 1.5px solid var(--mantine-color-gray-1);\n  border-radius: var(--mantine-radius-sm);\n  transition: all 0.1;\n}\n\n.hovering {\n  border: 1.5px solid var(--mantine-color-blue-5);\n}\n\n.editing {\n  border: 1.5px solid var(--mantine-color-gray-1);\n  border-left: 4px solid var(--mantine-color-blue-5);\n  min-height: 100px;\n}\n\n.questionBody {\n  max-width: 600px;\n}\n\n.topActions {\n  position: absolute;\n  right: 32px;\n  top: 1px;\n  padding: 4px;\n  color: var(--mantine-color-gray-5);\n  font-size: var(--mantine-font-size-xs);\n}\n\n.bottomActions {\n  position: absolute;\n  right: 4px;\n  bottom: 0;\n  --text-fz: var(--mantine-font-size-xs);\n\n  & a {\n    margin-left: 8px;\n  }\n}\n\n.movementActions {\n  position: absolute;\n  right: 8px;\n  top: 0;\n  padding-top: 8px;\n  font-size: var(--mantine-font-size-xs);\n\n  & a {\n    margin-left: 8px;\n  }\n}\n\n.movementIcons {\n  color: var(--mantine-color-gray-5);\n}\n\n.columnAlignment {\n  display: flex;\n  flex-direction: column;\n}\n\n.linkIdInput {\n  width: 100px;\n  margin-bottom: 4px;\n}\n\n.typeSelect {\n  width: 100px;\n}\n\n.preserveBreaks {\n  white-space: pre-wrap;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Box, Button, Collapse, Divider, Flex, Loader, Stack, Text } from '@mantine/core';\nimport { useDebouncedCallback } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { normalizeErrorString } from '@medplum/core';\nimport type { Identifier, Parameters, Questionnaire, QuestionnaireResponse } from '@medplum/fhirtypes';\nimport { useMedplum, useWhisper } from '@medplum/react-hooks';\nimport { IconChevronDown, IconChevronUp, IconCircleFilled, IconMicrophone, IconTrash } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport classes from './AIRealTimeQuestionnaireForm.module.css';\nimport type { QuestionnaireFormProps } from './QuestionnaireForm';\nimport { QuestionnaireForm } from './QuestionnaireForm';\n\nconst DEFAULT_SILENCE_DEBOUNCE_MS = 500;\nconst DEFAULT_IDLE_LABEL = 'Start Dictation to complete this form with your voice';\nconst TRANSCRIPT_PLACEHOLDER = 'Start speaking to see your transcribed words...';\nconst VOICE_TRANSCRIPT_EXTENSION_URL = 'https://medplum.com/ai-voice-transcript';\n\nconst botIdentifier: Identifier = {\n  system: 'https://www.medplum.com/bots',\n  value: 'ai-realtime-questionnaire',\n};\n\nfunction getStoredTranscript(response: QuestionnaireResponse | undefined): string {\n  return response?.extension?.find((e) => e.url === VOICE_TRANSCRIPT_EXTENSION_URL)?.valueString ?? '';\n}\n\nconst DEFAULT_INSTRUCTIONS = (\n  <Stack gap=\"xs\">\n    <Text>\n      To fill out the form, just speak naturally and the dictation tool will map your spoken answers to the form fields.\n    </Text>\n    <Text>Pause briefly between thoughts to start processing.</Text>\n  </Stack>\n);\n\nexport interface AIRealTimeQuestionnaireFormProps extends QuestionnaireFormProps {\n  readonly aiModel?: string;\n  readonly onTranscript?: (fullTranscript: string, chunk: string) => void;\n  readonly voiceInstructions?: ReactNode;\n  readonly silenceDebounceMs?: number;\n}\n\nexport function AIRealTimeQuestionnaireForm(props: AIRealTimeQuestionnaireFormProps): JSX.Element {\n  const { aiModel, onTranscript, voiceInstructions, silenceDebounceMs, ...questionnaireFormProps } = props;\n  const medplum = useMedplum();\n  const [questionnaireResponse, setQuestionnaireResponse] = useState<QuestionnaireResponse | undefined>(\n    props.questionnaireResponse as QuestionnaireResponse | undefined\n  );\n  const [isProcessing, setIsProcessing] = useState(false);\n  const [transcript, setTranscript] = useState('');\n  const [displayTranscript, setDisplayTranscript] = useState(() =>\n    getStoredTranscript(props.questionnaireResponse as QuestionnaireResponse | undefined)\n  );\n  const [expanded, setExpanded] = useState(false);\n  const [isStopping, setIsStopping] = useState(false);\n  // Bumped only when the AI replaces the response, so QuestionnaireForm remounts\n  // and picks up the new defaultValue (the inner hook ignores later prop changes).\n  const [responseVersion, setResponseVersion] = useState(0);\n\n  const questionnaireRef = useRef<Questionnaire | null>(null);\n  const inputRef = useRef('');\n  const inFlightRef = useRef(false);\n  const responseRef = useRef<QuestionnaireResponse | undefined>(questionnaireResponse);\n  const flushTranscriptRef = useRef<() => Promise<void>>(async () => {});\n  const transcriptViewportRef = useRef<HTMLDivElement>(null);\n  // Cumulative transcript across all flushes in this session, written to the\n  // QuestionnaireResponse as a custom extension each time the bot returns.\n  // Seeded from the incoming response so a previously captured transcript is\n  // preserved and appended to rather than overwritten.\n  const fullTranscriptRef = useRef(getStoredTranscript(questionnaireResponse));\n\n  useEffect(() => {\n    responseRef.current = questionnaireResponse;\n  }, [questionnaireResponse]);\n\n  const [botAvailability, setBotAvailability] = useState<'loading' | 'available' | 'unavailable'>('loading');\n  useEffect(() => {\n    let cancelled = false;\n    async function checkBotAvailability(): Promise<void> {\n      try {\n        const bot = await medplum.searchOne('Bot', {\n          identifier: `${botIdentifier.system ?? ''}|${botIdentifier.value ?? ''}`,\n        });\n        if (!cancelled) {\n          setBotAvailability(bot ? 'available' : 'unavailable');\n        }\n      } catch (err) {\n        console.error('Error checking bot availability:', err);\n        if (!cancelled) {\n          setBotAvailability('unavailable');\n        }\n      }\n    }\n    checkBotAvailability().catch(console.error);\n    return () => {\n      cancelled = true;\n    };\n  }, [medplum]);\n\n  const isProjectVoiceEnabled = medplum.getProject()?.features?.includes('ai-realtime') ?? false;\n  const isVoiceEnabled = isProjectVoiceEnabled && botAvailability === 'available';\n  let idleLabel: ReactNode = DEFAULT_IDLE_LABEL;\n  if (!isProjectVoiceEnabled) {\n    idleLabel = (\n      <>\n        Voice dictation is not enabled for this project\n        <br />\n        Please contact support\n      </>\n    );\n  } else if (botAvailability === 'unavailable') {\n    idleLabel = (\n      <>\n        Voice dictation unavailable: bot '{botIdentifier.value ?? ''}' is not deployed\n        <br />\n        Please contact support\n      </>\n    );\n  }\n\n  const { start, stop, status } = useWhisper({\n    model: 'gpt-4o-transcribe',\n    onTranscript: (text) => {\n      const trimmed = text.trim();\n      if (!trimmed) {\n        return;\n      }\n      const previous = inputRef.current.trim();\n      const next = previous ? `${previous} ${trimmed}` : trimmed;\n      inputRef.current = next;\n      setTranscript(next);\n      onTranscript?.(next, trimmed);\n    },\n  });\n\n  const statusRef = useRef(status);\n  useEffect(() => {\n    statusRef.current = status;\n  }, [status]);\n\n  const processTranscript = useCallback(\n    async (transcript: string) => {\n      if (!questionnaireRef.current || !transcript.trim()) {\n        return;\n      }\n\n      setIsProcessing(true);\n      try {\n        const existingResponse = responseRef.current;\n        const parameter: Parameters['parameter'] = [\n          { name: 'questionnaire', valueString: JSON.stringify(questionnaireRef.current) },\n          { name: 'transcript', valueString: transcript },\n        ];\n        if (existingResponse?.item && existingResponse.item.length > 0) {\n          parameter.push({ name: 'questionnaireResponse', valueString: JSON.stringify(existingResponse) });\n        }\n        if (aiModel) {\n          parameter.push({ name: 'model', valueString: aiModel });\n        }\n\n        const response = await medplum.executeBot(botIdentifier, {\n          resourceType: 'Parameters',\n          parameter,\n        });\n\n        const responseParam = response.parameter?.find((p: { name: string }) => p.name === 'questionnaireResponse');\n        if (responseParam?.valueString) {\n          try {\n            const aiQuestionnaireResponse = JSON.parse(responseParam.valueString) as QuestionnaireResponse;\n            const preservedExtensions = (aiQuestionnaireResponse.extension ?? []).filter(\n              (e) => e.url !== VOICE_TRANSCRIPT_EXTENSION_URL\n            );\n            aiQuestionnaireResponse.extension = [\n              ...preservedExtensions,\n              { url: VOICE_TRANSCRIPT_EXTENSION_URL, valueString: fullTranscriptRef.current },\n            ];\n            responseRef.current = aiQuestionnaireResponse;\n            setQuestionnaireResponse(aiQuestionnaireResponse);\n            setResponseVersion((v) => v + 1);\n          } catch (parseError) {\n            console.error('Failed to parse bot response as QuestionnaireResponse:', parseError);\n            showNotification({\n              color: 'red',\n              message: `Failed to parse bot response as QuestionnaireResponse: ${normalizeErrorString(parseError)}`,\n            });\n          }\n        }\n      } catch (error) {\n        console.error('Error processing transcript with AI:', error);\n      } finally {\n        setIsProcessing(false);\n      }\n    },\n    [medplum, aiModel]\n  );\n\n  useEffect(() => {\n    flushTranscriptRef.current = async (): Promise<void> => {\n      if (inFlightRef.current) {\n        return;\n      }\n      const pending = inputRef.current.trim();\n      if (!pending) {\n        return;\n      }\n      inputRef.current = '';\n      setTranscript('');\n      onTranscript?.('', '');\n      fullTranscriptRef.current = fullTranscriptRef.current ? `${fullTranscriptRef.current} ${pending}` : pending;\n      setDisplayTranscript(fullTranscriptRef.current);\n      inFlightRef.current = true;\n      try {\n        await processTranscript(pending);\n      } finally {\n        inFlightRef.current = false;\n      }\n      // Auto-drain: if speech accumulated while we were processing and the user\n      // isn't actively mid-utterance, fire the next $ai immediately.\n      if (inputRef.current.trim() && statusRef.current !== 'speech_started') {\n        flushTranscriptRef.current().catch((err) => console.error('Error draining transcript:', err));\n      }\n    };\n  }, [processTranscript, onTranscript]);\n\n  const debouncedFlush = useDebouncedCallback(() => {\n    if (statusRef.current === 'speech_started') {\n      return;\n    }\n    flushTranscriptRef\n      .current()\n      .catch((err) =>\n        showNotification({ color: 'red', message: `Error flushing transcript: ${normalizeErrorString(err)}` })\n      );\n  }, silenceDebounceMs ?? DEFAULT_SILENCE_DEBOUNCE_MS);\n\n  useEffect(() => {\n    if (status === 'speech_stopped') {\n      debouncedFlush();\n    }\n  }, [status, debouncedFlush]);\n\n  // Auto-scroll the transcript area to the latest text as it streams in.\n  useEffect(() => {\n    const viewport = transcriptViewportRef.current;\n    if (viewport) {\n      viewport.scrollTo({ top: viewport.scrollHeight, behavior: 'smooth' });\n    }\n  }, [transcript, displayTranscript]);\n\n  const isConnecting = status === 'requesting_microphone' || status === 'connecting' || status === 'connected';\n  const isRecording = status === 'listening' || status === 'speech_started' || status === 'speech_stopped';\n\n  const handleStartDictation = useCallback((): void => {\n    setExpanded(true);\n    start().catch((err) => console.error('Error starting voice input:', err));\n  }, [start]);\n\n  const handleStopDictation = useCallback((): void => {\n    setIsStopping(true);\n    stop();\n\n    debouncedFlush.cancel();\n    flushTranscriptRef\n      .current()\n      .catch((err) =>\n        showNotification({ color: 'red', message: `Error flushing transcript: ${normalizeErrorString(err)}` })\n      );\n  }, [stop, debouncedFlush]);\n\n  const handleToggleExpanded = useCallback((): void => {\n    setExpanded((prev) => !prev);\n  }, []);\n\n  const handleClearTranscript = useCallback((): void => {\n    inputRef.current = '';\n    fullTranscriptRef.current = '';\n    setTranscript('');\n    setDisplayTranscript('');\n    onTranscript?.('', '');\n    const existing = responseRef.current;\n    if (existing?.extension?.some((e) => e.url === VOICE_TRANSCRIPT_EXTENSION_URL)) {\n      const next: QuestionnaireResponse = {\n        ...existing,\n        extension: existing.extension.filter((e) => e.url !== VOICE_TRANSCRIPT_EXTENSION_URL),\n      };\n      responseRef.current = next;\n      setQuestionnaireResponse(next);\n    }\n  }, [onTranscript]);\n\n  useEffect(() => {\n    if (isStopping && !isConnecting && !isRecording) {\n      setIsStopping(false);\n    }\n  }, [isStopping, isProcessing, isConnecting, isRecording]);\n\n  // Track the questionnaire prop\n  useEffect(() => {\n    if (typeof props.questionnaire === 'object' && 'resourceType' in props.questionnaire) {\n      questionnaireRef.current = props.questionnaire;\n    }\n  }, [props.questionnaire]);\n\n  const isActive = isRecording && !isStopping;\n  const isButtonLoading = isConnecting || isStopping;\n  const showStopButton = isActive && !isButtonLoading;\n  const showButtonLoader = isButtonLoading;\n\n  let dictationLabel = 'Start Dictation';\n  if (isStopping) {\n    dictationLabel = 'Stopping\u2026';\n  } else if (isConnecting) {\n    dictationLabel = 'Starting\u2026';\n  } else if (showStopButton) {\n    dictationLabel = 'Stop Dictation';\n  }\n\n  // Show \"Processing\u2026\" whenever a bot call is in flight OR a Stop is in progress.\n  // The stop case covers the window where we're draining pending transcript chunks\n  // before the bot call kicks off \u2014 without this, the label snaps back to the idle\n  // copy mid-action and the user thinks the click did nothing.\n  const isFinishing = (isProcessing || isStopping) && !isRecording && !isConnecting;\n  let activeStatusLabel: string | undefined;\n  if (isProcessing || isStopping) {\n    activeStatusLabel = 'Processing\u2026';\n  } else if (isRecording) {\n    activeStatusLabel = 'Listening\u2026';\n  }\n\n  let statusState: 'finishing' | 'recording' | 'idle' = 'idle';\n  let statusIcon: JSX.Element = <IconMicrophone size={20} />;\n  if (isFinishing) {\n    statusState = 'finishing';\n    statusIcon = <Loader size={16} color=\"blue\" />;\n  } else if (activeStatusLabel) {\n    statusState = 'recording';\n    statusIcon = <IconCircleFilled size={16} />;\n  }\n\n  const afterHeader = (\n    <Box className={classes.banner}>\n      <Flex align=\"center\" justify=\"space-between\" gap=\"sm\" p=\"md\" className={classes.headerRow}>\n        <div className={classes.statusRow} data-state={statusState}>\n          <span className={classes.iconWrapper} aria-hidden>\n            {statusIcon}\n          </span>\n          <span className={classes.statusLabel} aria-live=\"polite\">\n            {activeStatusLabel ? (\n              <span className={isFinishing ? classes.statusLabelFinishing : classes.statusLabelPrimary}>\n                {activeStatusLabel}\n              </span>\n            ) : (\n              idleLabel\n            )}\n          </span>\n        </div>\n        <Flex align=\"center\" gap=\"xs\">\n          <Button\n            className={cx(classes.dictationButton, showButtonLoader && classes.dictationButtonLoading)}\n            variant={showStopButton ? 'light' : 'filled'}\n            color={showStopButton ? 'red' : 'blue'}\n            size=\"sm\"\n            leftSection={showButtonLoader ? <Loader size={14} color=\"dimmed\" /> : undefined}\n            disabled={showButtonLoader || (!isVoiceEnabled && !showStopButton)}\n            onClick={showStopButton ? handleStopDictation : handleStartDictation}\n          >\n            {dictationLabel}\n          </Button>\n          <ActionIcon\n            variant=\"subtle\"\n            color=\"gray\"\n            size=\"lg\"\n            radius=\"xl\"\n            aria-label={expanded ? 'Collapse transcript' : 'Expand transcript'}\n            aria-expanded={expanded}\n            onClick={handleToggleExpanded}\n          >\n            {expanded ? <IconChevronUp size={18} /> : <IconChevronDown size={18} />}\n          </ActionIcon>\n        </Flex>\n      </Flex>\n      <Collapse in={expanded}>\n        <Box px=\"md\">\n          <Divider color=\"var(--mantine-color-gray-2)\" />\n        </Box>\n        <Box p=\"md\">\n          <div className={classes.panelGrid}>\n            <div className={classes.panelColumn}>\n              <Text size=\"sm\" fw={700}>\n                How to Use\n              </Text>\n              <div className={classes.instructions}>{voiceInstructions ?? DEFAULT_INSTRUCTIONS}</div>\n            </div>\n            <div className={classes.panelColumn}>\n              <Flex align=\"center\" justify=\"space-between\" gap=\"xs\">\n                <Text size=\"sm\" fw={700}>\n                  Transcript\n                </Text>\n                <Button\n                  variant=\"subtle\"\n                  color=\"red\"\n                  size=\"compact-xs\"\n                  leftSection={<IconTrash size={14} />}\n                  disabled={!displayTranscript && !transcript}\n                  onClick={handleClearTranscript}\n                >\n                  Clear\n                </Button>\n              </Flex>\n              <div className={classes.transcriptWrapper}>\n                <div ref={transcriptViewportRef} className={classes.transcriptArea}>\n                  <Text component=\"pre\" className={classes.transcriptText}>\n                    {(displayTranscript && transcript\n                      ? `${displayTranscript} ${transcript}`\n                      : displayTranscript || transcript) || TRANSCRIPT_PLACEHOLDER}\n                  </Text>\n                </div>\n              </div>\n            </div>\n          </div>\n        </Box>\n      </Collapse>\n    </Box>\n  );\n\n  return (\n    <QuestionnaireForm\n      key={responseVersion}\n      {...questionnaireFormProps}\n      questionnaireResponse={questionnaireResponse}\n      afterHeader={afterHeader}\n      onChange={(response) => {\n        setQuestionnaireResponse(response);\n        props.onChange?.(response);\n      }}\n    />\n  );\n}\n", ".banner {\n  background-color: var(--mantine-color-white);\n  border: 1px solid var(--mantine-color-gray-2);\n  border-radius: var(--mantine-radius-md);\n}\n\n.headerRow {\n  min-height: 56px;\n}\n\n.statusRow {\n  display: flex;\n  align-items: center;\n  flex: 1;\n  min-width: 0;\n}\n\n.iconWrapper {\n  position: relative;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n  width: 20px;\n  height: 20px;\n}\n\n.statusRow :global(.tabler-icon) {\n  width: 20px;\n  height: 20px;\n  stroke-width: 2;\n  color: var(--mantine-color-gray-6);\n}\n\n.statusRow[data-state='recording'] :global(.tabler-icon) {\n  width: 16px;\n  height: 16px;\n  color: var(--mantine-color-red-6);\n  fill: var(--mantine-color-red-6);\n}\n\n.statusRow[data-state='recording'] .iconWrapper {\n  animation: recordingPulse 2.5s ease-in-out infinite;\n}\n\n@keyframes recordingPulse {\n  0%,\n  100% {\n    opacity: 1;\n    transform: scale(1);\n  }\n\n  50% {\n    opacity: 0.5;\n    transform: scale(0.8);\n  }\n}\n\n.statusLabel {\n  margin-left: var(--mantine-spacing-xs);\n  font-size: 14px;\n  font-weight: 450;\n  color: var(--mantine-color-gray-7);\n  white-space: nowrap;\n  overflow: hidden;\n  text-overflow: ellipsis;\n}\n\n.statusLabelPrimary {\n  font-size: 14px;\n  font-weight: 450;\n  color: var(--mantine-color-red-6);\n}\n\n.statusLabelFinishing {\n  font-size: 14px;\n  font-weight: 450;\n  color: var(--mantine-color-gray-6);\n}\n\n.dictationButton {\n  width: 10rem;\n  flex-shrink: 0;\n}\n\n.dictationButton :global(.mantine-Button-label) {\n  overflow: visible;\n  text-overflow: clip;\n}\n\n.dictationButtonLoading:global(.mantine-Button-root),\n.dictationButtonLoading:global(.mantine-Button-root):hover {\n  background-color: var(--mantine-color-gray-2);\n  border-color: var(--mantine-color-gray-2);\n  color: var(--mantine-color-dimmed);\n}\n\n.dictationButtonLoading :global(.mantine-Button-label) {\n  color: var(--mantine-color-dimmed);\n}\n\n.instructions {\n  font-size: 14px;\n  font-weight: 400;\n  line-height: 22px;\n  color: var(--mantine-color-gray-7);\n}\n\n.instructions :global(.mantine-Text-root) {\n  font-size: inherit;\n  font-weight: inherit;\n  line-height: inherit;\n  color: inherit;\n}\n\n.instructions ul {\n  margin: 0;\n  padding-left: 1.25rem;\n}\n\n.instructions > ul > li + li {\n  margin-top: var(--mantine-spacing-sm);\n}\n\n.panelGrid {\n  display: flex;\n  flex-direction: column;\n  gap: var(--mantine-spacing-xl);\n}\n\n@media (min-width: 48em) {\n  .panelGrid {\n    flex-direction: row;\n    align-items: stretch;\n  }\n}\n\n.panelColumn {\n  display: flex;\n  flex: 1;\n  flex-direction: column;\n  gap: var(--mantine-spacing-xs);\n  min-width: 0;\n}\n\n/*\n * On desktop, the transcript box is sized to match the \"How to Use\" column via\n * align-items: stretch on .panelGrid. To prevent the transcript text from\n * pushing the column taller, the scrollable area is absolutely positioned\n * inside a flex-grow wrapper so its content does not contribute to the\n * column's intrinsic height. On mobile (stacked columns), we fall back to a\n * fixed height since there's no sibling column to match.\n */\n.transcriptWrapper {\n  flex: 1;\n  min-height: 12rem;\n}\n\n.transcriptArea {\n  height: 100%;\n  overflow-x: hidden;\n  overflow-y: auto;\n  padding: var(--mantine-spacing-sm);\n  background-color: var(--mantine-color-gray-0);\n  border-radius: var(--mantine-radius-sm);\n}\n\n@media (min-width: 48em) {\n  .transcriptWrapper {\n    position: relative;\n    min-height: 0;\n  }\n\n  .transcriptArea {\n    position: absolute;\n    inset: 0;\n    height: auto;\n  }\n}\n\n.transcriptText {\n  display: block;\n  margin: 0;\n  padding: 0;\n  font-family: var(--mantine-font-family-monospace);\n  font-size: var(--mantine-font-size-xs);\n  line-height: var(--mantine-line-height-sm);\n  white-space: pre-wrap;\n  word-break: break-word;\n  color: var(--mantine-color-text);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Group, Stack, Text, Title } from '@mantine/core';\nimport { createReference, getExtension, getReferenceString } from '@medplum/core';\nimport type { Encounter, Questionnaire, QuestionnaireResponse, Reference } from '@medplum/fhirtypes';\nimport {\n  QUESTIONNAIRE_SIGNATURE_REQUIRED_URL,\n  QUESTIONNAIRE_SIGNATURE_RESPONSE_URL,\n  useMedplum,\n  useQuestionnaireForm,\n} from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { SignatureInput } from '../SignatureInput/SignatureInput';\nimport { QuestionnaireFormItemArray } from './QuestionnaireFormItemArray';\nimport { QuestionnaireFormStepper } from './QuestionnaireFormStepper';\n\nexport interface QuestionnaireFormProps {\n  readonly questionnaire: Questionnaire | Reference<Questionnaire>;\n  readonly questionnaireResponse?: QuestionnaireResponse | Reference<QuestionnaireResponse>;\n  readonly subject?: Reference;\n  readonly encounter?: Reference<Encounter>;\n  readonly source?: QuestionnaireResponse['source'];\n  readonly disablePagination?: boolean;\n  readonly excludeButtons?: boolean;\n  readonly submitButtonText?: string;\n  /** Optional content rendered immediately below the header row, before the form items. */\n  readonly afterHeader?: ReactNode;\n  readonly onChange?: (response: QuestionnaireResponse) => void;\n  readonly onSubmit?: (response: QuestionnaireResponse) => void;\n}\n\nexport function QuestionnaireForm(props: QuestionnaireFormProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const [signatureRequiredSubmitted, setSignatureRequiredSubmitted] = useState(false);\n  const propsRef = useRef(props);\n  const pendingChangeRef = useRef<QuestionnaireResponse | undefined>(undefined);\n  useLayoutEffect(() => {\n    propsRef.current = props;\n  });\n\n  const onFormChange = useCallback((response: QuestionnaireResponse) => {\n    pendingChangeRef.current = response;\n  }, []);\n\n  const formState = useQuestionnaireForm({\n    questionnaire: props.questionnaire,\n    defaultValue: props.questionnaireResponse,\n    subject: props.subject,\n    encounter: props.encounter,\n    source: props.source,\n    disablePagination: props.disablePagination,\n    onChange: onFormChange,\n  });\n  const formStateRef = useRef(formState);\n  useLayoutEffect(() => {\n    formStateRef.current = formState;\n  });\n\n  // Intentionally run after every commit.\n  //\n  // `useQuestionnaireForm` currently invokes its `onChange` callback while the form\n  // is rendering/initializing. Calling `setState` directly from that callback caused\n  // React to warn that `QuestionnaireForm` was updating a parent during render.\n  //\n  // To avoid that render-phase update, `onFormChange` stages the latest response in\n  // `pendingChangeRef`, and this effect flushes it after commit. The effect clears\n  // the ref before calling `setSignatureRequiredSubmitted(false)`, so the state\n  // update does not create an infinite loop: the rerender triggered by `setState`\n  // immediately exits because there is no longer a pending change to flush.\n  //\n  // A more complete fix would be to move `useQuestionnaireForm`'s `onChange`\n  // emission out of render entirely. Until then, this effect must run on every\n  // commit so it can detect newly staged ref-based changes that do not participate\n  // in React's dependency tracking.\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  useEffect(() => {\n    const pendingChange = pendingChangeRef.current;\n    if (!pendingChange) {\n      return;\n    }\n\n    pendingChangeRef.current = undefined;\n    setSignatureRequiredSubmitted(false);\n    propsRef.current.onChange?.(pendingChange);\n  });\n\n  const isSignatureRequired = useMemo(() => {\n    if (formState.loading) {\n      return false;\n    }\n    return !!getExtension(formState.questionnaire, QUESTIONNAIRE_SIGNATURE_REQUIRED_URL);\n  }, [formState]);\n\n  const hasSignature = useMemo(() => {\n    if (formState.loading) {\n      return false;\n    }\n    return !!formState.questionnaireResponse.extension?.find((ext) => ext.url === QUESTIONNAIRE_SIGNATURE_RESPONSE_URL);\n  }, [formState]);\n\n  const handleSubmit = useCallback(() => {\n    const formState = formStateRef.current;\n    if (formState.loading) {\n      return;\n    }\n\n    const onSubmit = propsRef.current.onSubmit;\n    if (!onSubmit) {\n      return;\n    }\n\n    if (isSignatureRequired && !hasSignature) {\n      setSignatureRequiredSubmitted(true);\n      return;\n    }\n\n    const questionnaire = formState.questionnaire;\n    const response = formState.questionnaireResponse;\n    const subject = propsRef.current.subject;\n    let source = propsRef.current.source;\n    if (!source) {\n      const profile = medplum.getProfile();\n      if (profile) {\n        source = createReference(profile);\n      }\n    }\n\n    onSubmit({\n      ...response,\n      questionnaire: questionnaire.url ?? getReferenceString(questionnaire),\n      subject,\n      source,\n      authored: new Date().toISOString(),\n      status: 'completed',\n    });\n  }, [medplum, isSignatureRequired, hasSignature]);\n\n  if (formState.loading) {\n    return null;\n  }\n\n  return (\n    <Form testid=\"questionnaire-form\" onSubmit={handleSubmit}>\n      {formState.questionnaire.title && (\n        <Title order={1} fz=\"1.625rem\" fw={700} lh={1.3} mb=\"xl\">\n          {formState.questionnaire.title}\n        </Title>\n      )}\n      {props.afterHeader && (\n        <Stack gap=\"xl\" mb=\"xl\">\n          {props.afterHeader}\n          <Divider color=\"var(--mantine-color-gray-2)\" />\n        </Stack>\n      )}\n      {formState.pagination ? (\n        <QuestionnaireFormStepper\n          formState={formState}\n          submitButtonText={props.submitButtonText}\n          excludeButtons={props.excludeButtons}\n        >\n          <QuestionnaireFormItemArray\n            formState={formState}\n            context={[]}\n            items={formState.items}\n            responseItems={formState.responseItems}\n          />\n        </QuestionnaireFormStepper>\n      ) : (\n        <>\n          <QuestionnaireFormItemArray\n            formState={formState}\n            context={[]}\n            items={formState.items}\n            responseItems={formState.responseItems}\n          />\n          {isSignatureRequired && (\n            <Stack mt=\"md\" gap={0}>\n              <Text size=\"sm\" fw={500}>\n                Signature\n              </Text>\n              <SignatureInput onChange={formState.onChangeSignature} />\n              {!hasSignature && signatureRequiredSubmitted && (\n                <Text c=\"red\" size=\"sm\">\n                  Signature is required.\n                </Text>\n              )}\n            </Stack>\n          )}\n\n          {!props.excludeButtons && (\n            <Group justify=\"flex-end\" mt=\"xl\" gap=\"xs\">\n              <SubmitButton>{props.submitButtonText ?? 'Submit'}</SubmitButton>\n            </Group>\n          )}\n        </>\n      )}\n    </Form>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { PaperProps } from '@mantine/core';\nimport { Button, Paper } from '@mantine/core';\nimport type { ProfileResource } from '@medplum/core';\nimport { createReference, HTTP_HL7_ORG } from '@medplum/core';\nimport type { Reference, Signature } from '@medplum/fhirtypes';\nimport { useMedplum, useStabilizedCallback } from '@medplum/react-hooks';\nimport { IconTrash } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useEffect, useRef } from 'react';\nimport SignaturePad from 'signature_pad';\n\nexport interface SignatureInputProps extends PaperProps {\n  readonly width?: number;\n  readonly height?: number;\n  readonly defaultValue?: Signature;\n  readonly who?: Reference<ProfileResource>;\n  readonly onChange: ((value: Signature | undefined) => void) | undefined;\n}\n\nexport function SignatureInput(props: SignatureInputProps): JSX.Element {\n  const medplum = useMedplum();\n  const { width = 500, height = 200, defaultValue, who, onChange, ...rest } = props;\n  const canvasRef = useRef<HTMLCanvasElement>(null);\n  const signaturePadRef = useRef<SignaturePad>(null);\n\n  const emitChange = useStabilizedCallback(onChange);\n\n  useEffect(() => {\n    function handleEndStroke(): void {\n      emitChange({\n        type: [\n          {\n            system: HTTP_HL7_ORG + '/fhir/signature-type',\n            code: 'ProofOfOrigin',\n            display: 'Proof of Origin',\n          },\n        ],\n        when: new Date().toISOString(),\n        who: who ?? createReference(medplum.getProfile() as ProfileResource),\n        data: signaturePadRef.current?.toDataURL().split(',')[1],\n      });\n    }\n\n    if (canvasRef.current) {\n      const signaturePad = new SignaturePad(canvasRef.current);\n      if (defaultValue?.data) {\n        signaturePad.fromDataURL(defaultValue.data).catch(console.error);\n      }\n      signaturePad.addEventListener('endStroke', handleEndStroke);\n      signaturePadRef.current = signaturePad;\n    }\n\n    return () => {\n      if (signaturePadRef.current) {\n        signaturePadRef.current.removeEventListener('endStroke', handleEndStroke);\n      }\n    };\n  }, [medplum, defaultValue, who, emitChange]);\n\n  const clearSignature = (): void => {\n    if (signaturePadRef.current) {\n      signaturePadRef.current.clear();\n    }\n    emitChange(undefined);\n  };\n\n  return (\n    <Paper withBorder p={0} w={width} h={height} pos=\"relative\" {...rest}>\n      <canvas ref={canvasRef} width={width} height={height} aria-label=\"Signature input area\"></canvas>\n      <Button\n        onClick={clearSignature}\n        aria-label=\"Clear signature\"\n        pos=\"absolute\"\n        top={0}\n        right={0}\n        size=\"xs\"\n        leftSection={<IconTrash size={16} />}\n        variant=\"subtle\"\n        color=\"gray\"\n      >\n        Clear\n      </Button>\n    </Paper>\n  );\n}\n", "// Interface for point data structure used e.g. in SignaturePad#fromData method\nexport interface BasicPoint {\n  x: number;\n  y: number;\n  pressure: number;\n  time: number;\n}\n\nexport class Point implements BasicPoint {\n  public x: number;\n  public y: number;\n  public pressure: number;\n  public time: number;\n\n  constructor(x: number, y: number, pressure?: number, time?: number) {\n    if (isNaN(x) || isNaN(y)) {\n      throw new Error(`Point is invalid: (${x}, ${y})`);\n    }\n    this.x = +x;\n    this.y = +y;\n    this.pressure = pressure || 0;\n    this.time = time || Date.now();\n  }\n\n  public distanceTo(start: BasicPoint): number {\n    return Math.sqrt(\n      Math.pow(this.x - start.x, 2) + Math.pow(this.y - start.y, 2),\n    );\n  }\n\n  public equals(other: BasicPoint): boolean {\n    return (\n      this.x === other.x &&\n      this.y === other.y &&\n      this.pressure === other.pressure &&\n      this.time === other.time\n    );\n  }\n\n  public velocityFrom(start: BasicPoint): number {\n    return this.time !== start.time\n      ? this.distanceTo(start) / (this.time - start.time)\n      : 0;\n  }\n}\n", "import { BasicPoint, Point } from './point.js';\n\nexport class Bezier {\n  public static fromPoints(\n    points: Point[],\n    widths: { start: number; end: number },\n  ): Bezier {\n    const c2 = this.calculateControlPoints(points[0], points[1], points[2]).c2;\n    const c3 = this.calculateControlPoints(points[1], points[2], points[3]).c1;\n\n    return new Bezier(points[1], c2, c3, points[2], widths.start, widths.end);\n  }\n\n  private static calculateControlPoints(\n    s1: BasicPoint,\n    s2: BasicPoint,\n    s3: BasicPoint,\n  ): {\n    c1: BasicPoint;\n    c2: BasicPoint;\n  } {\n    const dx1 = s1.x - s2.x;\n    const dy1 = s1.y - s2.y;\n    const dx2 = s2.x - s3.x;\n    const dy2 = s2.y - s3.y;\n\n    const m1 = { x: (s1.x + s2.x) / 2.0, y: (s1.y + s2.y) / 2.0 };\n    const m2 = { x: (s2.x + s3.x) / 2.0, y: (s2.y + s3.y) / 2.0 };\n\n    const l1 = Math.sqrt(dx1 * dx1 + dy1 * dy1);\n    const l2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);\n\n    const dxm = m1.x - m2.x;\n    const dym = m1.y - m2.y;\n\n    const k = l1 + l2 == 0 ? 0 : l2 / (l1 + l2);\n    const cm = { x: m2.x + dxm * k, y: m2.y + dym * k };\n\n    const tx = s2.x - cm.x;\n    const ty = s2.y - cm.y;\n\n    return {\n      c1: new Point(m1.x + tx, m1.y + ty),\n      c2: new Point(m2.x + tx, m2.y + ty),\n    };\n  }\n\n  constructor(\n    public startPoint: Point,\n    public control2: BasicPoint,\n    public control1: BasicPoint,\n    public endPoint: Point,\n    public startWidth: number,\n    public endWidth: number,\n  ) {}\n\n  // Returns approximated length. Code taken from https://www.lemoda.net/maths/bezier-length/index.html.\n  public length(): number {\n    const steps = 10;\n    let length = 0;\n    let px;\n    let py;\n\n    for (let i = 0; i <= steps; i += 1) {\n      const t = i / steps;\n      const cx = this.point(\n        t,\n        this.startPoint.x,\n        this.control1.x,\n        this.control2.x,\n        this.endPoint.x,\n      );\n      const cy = this.point(\n        t,\n        this.startPoint.y,\n        this.control1.y,\n        this.control2.y,\n        this.endPoint.y,\n      );\n\n      if (i > 0) {\n        const xdiff = cx - (px as number);\n        const ydiff = cy - (py as number);\n\n        length += Math.sqrt(xdiff * xdiff + ydiff * ydiff);\n      }\n\n      px = cx;\n      py = cy;\n    }\n\n    return length;\n  }\n\n  // Calculate parametric value of x or y given t and the four point coordinates of a cubic bezier curve.\n  private point(\n    t: number,\n    start: number,\n    c1: number,\n    c2: number,\n    end: number,\n  ): number {\n    // prettier-ignore\n    return (       start * (1.0 - t) * (1.0 - t)  * (1.0 - t))\n         + (3.0 *  c1    * (1.0 - t) * (1.0 - t)  * t)\n         + (3.0 *  c2    * (1.0 - t) * t          * t)\n         + (       end   * t         * t          * t);\n  }\n}\n", "export class SignatureEventTarget {\n  /* tslint:disable: variable-name */\n  private _et: EventTarget;\n  /* tslint:enable: variable-name */\n\n  constructor() {\n    try {\n      this._et = new EventTarget();\n    } catch {\n      // Using document as EventTarget to support iOS 13 and older.\n      // Because EventTarget constructor just exists at iOS 14 and later.\n      this._et = document;\n    }\n  }\n\n  addEventListener(\n    type: string,\n    listener: EventListenerOrEventListenerObject | null,\n    options?: boolean | AddEventListenerOptions,\n  ): void {\n    this._et.addEventListener(type, listener, options);\n  }\n\n  dispatchEvent(event: Event): boolean {\n    return this._et.dispatchEvent(event);\n  }\n\n  removeEventListener(\n    type: string,\n    callback: EventListenerOrEventListenerObject | null,\n    options?: boolean | EventListenerOptions,\n  ): void {\n    this._et.removeEventListener(type, callback, options);\n  }\n}\n", "/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-this-alias */\n// Slightly simplified version of http://stackoverflow.com/a/27078401/815507\n\nexport function throttle(\n  fn: (...args: any[]) => any,\n  wait = 250,\n): (this: any, ...args: any[]) => any {\n  let previous = 0;\n  let timeout: number | null = null;\n  let result: any;\n  let storedContext: any;\n  let storedArgs: any[];\n\n  const later = (): void => {\n    previous = Date.now();\n    timeout = null;\n    result = fn.apply(storedContext, storedArgs);\n\n    if (!timeout) {\n      storedContext = null;\n      storedArgs = [];\n    }\n  };\n\n  return function wrapper(this: any, ...args: any[]): any {\n    const now = Date.now();\n    const remaining = wait - (now - previous);\n\n    storedContext = this;\n    storedArgs = args;\n\n    if (remaining <= 0 || remaining > wait) {\n      if (timeout) {\n        clearTimeout(timeout);\n        timeout = null;\n      }\n\n      previous = now;\n      result = fn.apply(storedContext, storedArgs);\n\n      if (!timeout) {\n        storedContext = null;\n        storedArgs = [];\n      }\n    } else if (!timeout) {\n      timeout = window.setTimeout(later, remaining);\n    }\n\n    return result;\n  };\n}\n", "/**\n * The main idea and some parts of the code (e.g. drawing variable width B\u00E9zier curve) are taken from:\n * http://corner.squareup.com/2012/07/smoother-signatures.html\n *\n * Implementation of interpolation using cubic B\u00E9zier curves is taken from:\n * https://web.archive.org/web/20160323213433/http://www.benknowscode.com/2012/09/path-interpolation-using-cubic-bezier_9742.html\n *\n * Algorithm for approximated length of a B\u00E9zier curve is taken from:\n * http://www.lemoda.net/maths/bezier-length/index.html\n */\n\nimport { Bezier } from './bezier.js';\nimport { BasicPoint, Point } from './point.js';\nimport { SignatureEventTarget } from './signature_event_target.js';\nimport { throttle } from './throttle.js';\n\nexport { BasicPoint } from './point.js';\n\nexport interface SignatureEvent {\n  event: MouseEvent | TouchEvent | PointerEvent;\n  type: string;\n  x: number;\n  y: number;\n  pressure: number;\n}\n\nexport interface FromDataOptions {\n  clear?: boolean;\n}\n\nexport interface FromDataUrlOptions {\n  ratio?: number;\n  width?: number;\n  height?: number;\n  xOffset?: number;\n  yOffset?: number;\n}\n\nexport interface ToSVGOptions {\n  includeBackgroundColor?: boolean;\n  includeDataUrl?: boolean;\n}\n\nexport interface PointGroupOptions {\n  dotSize: number;\n  minWidth: number;\n  maxWidth: number;\n  penColor: string;\n  velocityFilterWeight: number;\n  /**\n   * This is the globalCompositeOperation for the line.\n   * *default: 'source-over'*\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation\n   */\n  compositeOperation: GlobalCompositeOperation;\n}\n\nexport interface Options extends Partial<PointGroupOptions> {\n  minDistance?: number;\n  backgroundColor?: string;\n  throttle?: number;\n  canvasContextOptions?: CanvasRenderingContext2DSettings;\n}\n\nexport interface PointGroup extends PointGroupOptions {\n  points: BasicPoint[];\n}\n\nexport default class SignaturePad extends SignatureEventTarget {\n  // Public stuff\n  public dotSize: number;\n  public minWidth: number;\n  public maxWidth: number;\n  public penColor: string;\n  public minDistance: number;\n  public velocityFilterWeight: number;\n  public compositeOperation: GlobalCompositeOperation;\n  public backgroundColor: string;\n  public throttle: number;\n  public canvasContextOptions: CanvasRenderingContext2DSettings;\n\n  // Private stuff\n  /* tslint:disable: variable-name */\n  private _ctx: CanvasRenderingContext2D;\n  private _drawingStroke = false;\n  private _isEmpty = true;\n  private _dataUrl: string | undefined;\n  private _dataUrlOptions: FromDataUrlOptions | undefined;\n  private _lastPoints: Point[] = []; // Stores up to 4 most recent points; used to generate a new curve\n  private _data: PointGroup[] = []; // Stores all points in groups (one group per line or dot)\n  private _lastVelocity = 0;\n  private _lastWidth = 0;\n  private _strokeMoveUpdate: (event: SignatureEvent) => void;\n  private _strokePointerId: number | undefined;\n  /* tslint:enable: variable-name */\n\n  constructor(\n    private canvas: HTMLCanvasElement,\n    options: Options = {},\n  ) {\n    super();\n    this.velocityFilterWeight = options.velocityFilterWeight || 0.7;\n    this.minWidth = options.minWidth || 0.5;\n    this.maxWidth = options.maxWidth || 2.5;\n\n    // We need to handle 0 value, so use `??` instead of `||`\n    this.throttle = options.throttle ?? 16; // in milliseconds\n    this.minDistance = options.minDistance ?? 5; // in pixels\n    this.dotSize = options.dotSize || 0;\n    this.penColor = options.penColor || 'black';\n    this.backgroundColor = options.backgroundColor || 'rgba(0,0,0,0)';\n    this.compositeOperation = options.compositeOperation || 'source-over';\n    this.canvasContextOptions = options.canvasContextOptions ?? {};\n\n    this._strokeMoveUpdate = this.throttle\n      ? throttle(SignaturePad.prototype._strokeUpdate, this.throttle)\n      : SignaturePad.prototype._strokeUpdate;\n\n    this._handleMouseDown = this._handleMouseDown.bind(this);\n    this._handleMouseMove = this._handleMouseMove.bind(this);\n    this._handleMouseUp = this._handleMouseUp.bind(this);\n    this._handleTouchStart = this._handleTouchStart.bind(this);\n    this._handleTouchMove = this._handleTouchMove.bind(this);\n    this._handleTouchEnd = this._handleTouchEnd.bind(this);\n    this._handlePointerDown = this._handlePointerDown.bind(this);\n    this._handlePointerMove = this._handlePointerMove.bind(this);\n    this._handlePointerUp = this._handlePointerUp.bind(this);\n    this._handlePointerCancel = this._handlePointerCancel.bind(this);\n    this._handleTouchCancel = this._handleTouchCancel.bind(this);\n\n    this._ctx = canvas.getContext(\n      '2d',\n      this.canvasContextOptions,\n    ) as CanvasRenderingContext2D;\n\n    this.clear();\n\n    // Enable mouse and touch event handlers\n    this.on();\n  }\n\n  public clear(): void {\n    const { _ctx: ctx, canvas } = this;\n\n    // Clear canvas using background color\n    ctx.fillStyle = this.backgroundColor;\n    ctx.clearRect(0, 0, canvas.width, canvas.height);\n    ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n    this._data = [];\n    this._reset(this._getPointGroupOptions());\n    this._isEmpty = true;\n    this._dataUrl = undefined;\n    this._dataUrlOptions = undefined;\n    this._strokePointerId = undefined;\n  }\n\n  public redraw(): void {\n    const data = this._data;\n    const dataUrl = this._dataUrl;\n    const dataUrlOptions = this._dataUrlOptions;\n\n    this.clear();\n    if (dataUrl) {\n      this.fromDataURL(dataUrl, dataUrlOptions);\n    }\n    this.fromData(data, { clear: false });\n  }\n\n  public fromDataURL(\n    dataUrl: string,\n    options: FromDataUrlOptions = {},\n  ): Promise<void> {\n    return new Promise((resolve, reject) => {\n      const image = new Image();\n      const ratio = options.ratio || window.devicePixelRatio || 1;\n      const width = options.width || this.canvas.width / ratio;\n      const height = options.height || this.canvas.height / ratio;\n      const xOffset = options.xOffset || 0;\n      const yOffset = options.yOffset || 0;\n\n      this._reset(this._getPointGroupOptions());\n\n      image.onload = (): void => {\n        this._ctx.drawImage(image, xOffset, yOffset, width, height);\n        resolve();\n      };\n      image.onerror = (error): void => {\n        reject(error);\n      };\n      image.crossOrigin = 'anonymous';\n      image.src = dataUrl;\n\n      this._isEmpty = false;\n      this._dataUrl = dataUrl;\n      this._dataUrlOptions = { ...options };\n    });\n  }\n\n  public toDataURL(\n    type: 'image/svg+xml',\n    encoderOptions?: ToSVGOptions,\n  ): string;\n  public toDataURL(type?: string, encoderOptions?: number): string;\n  public toDataURL(\n    type = 'image/png',\n    encoderOptions?: number | ToSVGOptions | undefined,\n  ): string {\n    switch (type) {\n      case 'image/svg+xml':\n        if (typeof encoderOptions !== 'object') {\n          encoderOptions = undefined;\n        }\n        return `data:image/svg+xml;base64,${btoa(\n          this.toSVG(encoderOptions as ToSVGOptions),\n        )}`;\n      default:\n        if (typeof encoderOptions !== 'number') {\n          encoderOptions = undefined;\n        }\n        return this.canvas.toDataURL(type, encoderOptions as number);\n    }\n  }\n\n  public on(): void {\n    // Disable panning/zooming when touching canvas element\n    this.canvas.style.touchAction = 'none';\n    (\n      this.canvas.style as CSSStyleDeclaration & {\n        msTouchAction: string | null;\n      }\n    ).msTouchAction = 'none';\n    this.canvas.style.userSelect = 'none';\n    // Safari does not support userSelect property without a prefix even as of iOS 26\n    // https://caniuse.com/?search=user-select\n    this.canvas.style.webkitUserSelect = 'none';\n\n    const isIOS =\n      /Macintosh/.test(navigator.userAgent) && 'ontouchstart' in document;\n\n    // The \"Scribble\" feature of iOS intercepts point events. So that we can\n    // lose some of them when tapping rapidly. Use touch events for iOS\n    // platforms to prevent it. See\n    // https://developer.apple.com/forums/thread/664108 for more information.\n    if (window.PointerEvent && !isIOS) {\n      this._handlePointerEvents();\n    } else {\n      this._handleMouseEvents();\n\n      if ('ontouchstart' in window) {\n        this._handleTouchEvents();\n      }\n    }\n  }\n\n  public off(): void {\n    // Enable panning/zooming when touching canvas element\n    this.canvas.style.touchAction = 'auto';\n    (\n      this.canvas.style as CSSStyleDeclaration & {\n        msTouchAction: string | null;\n      }\n    ).msTouchAction = 'auto';\n    this.canvas.style.userSelect = 'auto';\n    this.canvas.style.webkitUserSelect = 'auto';\n\n    this.canvas.removeEventListener('pointerdown', this._handlePointerDown);\n    this.canvas.removeEventListener('mousedown', this._handleMouseDown);\n    this.canvas.removeEventListener('touchstart', this._handleTouchStart);\n\n    this._removeMoveUpEventListeners();\n  }\n\n  private _getListenerFunctions() {\n    const canvasWindow =\n      window.document === this.canvas.ownerDocument\n        ? window\n        : (this.canvas.ownerDocument.defaultView ?? this.canvas.ownerDocument);\n\n    return {\n      addEventListener: canvasWindow.addEventListener.bind(\n        canvasWindow,\n      ) as typeof window.addEventListener,\n      removeEventListener: canvasWindow.removeEventListener.bind(\n        canvasWindow,\n      ) as typeof window.removeEventListener,\n    };\n  }\n\n  private _removeMoveUpEventListeners(): void {\n    const { removeEventListener } = this._getListenerFunctions();\n    removeEventListener('pointermove', this._handlePointerMove);\n    removeEventListener('pointerup', this._handlePointerUp);\n    removeEventListener('pointercancel', this._handlePointerCancel);\n\n    removeEventListener('mousemove', this._handleMouseMove);\n    removeEventListener('mouseup', this._handleMouseUp);\n\n    removeEventListener('touchmove', this._handleTouchMove);\n    removeEventListener('touchend', this._handleTouchEnd);\n    removeEventListener('touchcancel', this._handleTouchCancel);\n  }\n\n  public isEmpty(): boolean {\n    return this._isEmpty;\n  }\n\n  public fromData(\n    pointGroups: PointGroup[],\n    { clear = true }: FromDataOptions = {},\n  ): void {\n    if (clear) {\n      this.clear();\n    }\n\n    this._fromData(\n      pointGroups,\n      this._drawCurve.bind(this),\n      this._drawDot.bind(this),\n      this._drawLine.bind(this),\n    );\n\n    this._data = this._data.concat(pointGroups);\n  }\n\n  public toData(): PointGroup[] {\n    return this._data;\n  }\n\n  private _isLeftButtonPressed(event: MouseEvent, only?: boolean): boolean {\n    if (only) {\n      return event.buttons === 1;\n    }\n\n    return (event.buttons & 1) === 1;\n  }\n  private _pointerEventToSignatureEvent(\n    event: MouseEvent | PointerEvent,\n  ): SignatureEvent {\n    return {\n      event: event,\n      type: event.type,\n      x: event.clientX,\n      y: event.clientY,\n      pressure: 'pressure' in event ? event.pressure : 0,\n    };\n  }\n\n  private _touchEventToSignatureEvent(event: TouchEvent): SignatureEvent {\n    const touch = event.changedTouches[0];\n    return {\n      event: event,\n      type: event.type,\n      x: touch.clientX,\n      y: touch.clientY,\n      pressure: touch.force,\n    };\n  }\n\n  // Event handlers\n  private _handleMouseDown(event: MouseEvent): void {\n    if (!this._isLeftButtonPressed(event, true) || this._drawingStroke) {\n      return;\n    }\n    this._strokeBegin(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _handleMouseMove(event: MouseEvent): void {\n    if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n      // Stop when not pressing primary button or pressing multiple buttons\n      this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n      return;\n    }\n\n    this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _handleMouseUp(event: MouseEvent): void {\n    if (this._isLeftButtonPressed(event)) {\n      return;\n    }\n\n    this._strokeEnd(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _handleTouchStart(event: TouchEvent): void {\n    if (event.targetTouches.length !== 1 || this._drawingStroke) {\n      return;\n    }\n\n    // Prevent scrolling.\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n\n    this._strokeBegin(this._touchEventToSignatureEvent(event));\n  }\n\n  private _handleTouchMove(event: TouchEvent): void {\n    if (event.targetTouches.length !== 1) {\n      return;\n    }\n\n    // Prevent scrolling.\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n\n    if (!this._drawingStroke) {\n      this._strokeEnd(this._touchEventToSignatureEvent(event), false);\n      return;\n    }\n\n    this._strokeMoveUpdate(this._touchEventToSignatureEvent(event));\n  }\n\n  private _handleTouchEnd(event: TouchEvent): void {\n    if (event.targetTouches.length !== 0) {\n      return;\n    }\n\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n\n    this._strokeEnd(this._touchEventToSignatureEvent(event));\n  }\n\n  private _handlePointerCancel(event: PointerEvent): void {\n    if (!this._allowPointerId(event)) {\n      return;\n    }\n\n    event.preventDefault();\n    this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n  }\n\n  private _handleTouchCancel(event: TouchEvent): void {\n    if (event.cancelable) {\n      event.preventDefault();\n    }\n\n    this._strokeEnd(this._touchEventToSignatureEvent(event), false);\n  }\n\n  private _getPointerId(event: PointerEvent) {\n    // @ts-expect-error persistentDeviceId is not available yet but we want to use it when it is available\n    return event.persistentDeviceId || event.pointerId;\n  }\n\n  private _allowPointerId(\n    event: PointerEvent,\n    allowUndefined = false,\n  ): boolean {\n    if (typeof this._strokePointerId === 'undefined') {\n      return allowUndefined;\n    }\n\n    return this._getPointerId(event) === this._strokePointerId;\n  }\n\n  private _handlePointerDown(event: PointerEvent): void {\n    if (\n      this._drawingStroke ||\n      !this._isLeftButtonPressed(event) ||\n      !this._allowPointerId(event, true)\n    ) {\n      return;\n    }\n\n    this._strokePointerId = this._getPointerId(event);\n\n    event.preventDefault();\n\n    this._strokeBegin(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _handlePointerMove(event: PointerEvent): void {\n    if (!this._allowPointerId(event)) {\n      return;\n    }\n    if (!this._isLeftButtonPressed(event, true) || !this._drawingStroke) {\n      // Stop when primary button not pressed or multiple buttons pressed\n      this._strokeEnd(this._pointerEventToSignatureEvent(event), false);\n      return;\n    }\n\n    event.preventDefault();\n    this._strokeMoveUpdate(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _handlePointerUp(event: PointerEvent): void {\n    if (this._isLeftButtonPressed(event) || !this._allowPointerId(event)) {\n      return;\n    }\n\n    event.preventDefault();\n    this._strokeEnd(this._pointerEventToSignatureEvent(event));\n  }\n\n  private _getPointGroupOptions(group?: PointGroup): PointGroupOptions {\n    return {\n      penColor: group && 'penColor' in group ? group.penColor : this.penColor,\n      dotSize: group && 'dotSize' in group ? group.dotSize : this.dotSize,\n      minWidth: group && 'minWidth' in group ? group.minWidth : this.minWidth,\n      maxWidth: group && 'maxWidth' in group ? group.maxWidth : this.maxWidth,\n      velocityFilterWeight:\n        group && 'velocityFilterWeight' in group\n          ? group.velocityFilterWeight\n          : this.velocityFilterWeight,\n      compositeOperation:\n        group && 'compositeOperation' in group\n          ? group.compositeOperation\n          : this.compositeOperation,\n    };\n  }\n\n  // Private methods\n  private _strokeBegin(event: SignatureEvent): void {\n    const cancelled = !this.dispatchEvent(\n      new CustomEvent('beginStroke', { detail: event, cancelable: true }),\n    );\n    if (cancelled) {\n      return;\n    }\n\n    const { addEventListener } = this._getListenerFunctions();\n    switch (event.event.type) {\n      case 'mousedown':\n        addEventListener('mousemove', this._handleMouseMove, {\n          passive: false,\n        });\n        addEventListener('mouseup', this._handleMouseUp, { passive: false });\n        break;\n      case 'touchstart':\n        addEventListener('touchmove', this._handleTouchMove, {\n          passive: false,\n        });\n        addEventListener('touchend', this._handleTouchEnd, { passive: false });\n        addEventListener('touchcancel', this._handleTouchCancel, {\n          passive: false,\n        });\n        break;\n      case 'pointerdown':\n        addEventListener('pointermove', this._handlePointerMove, {\n          passive: false,\n        });\n        addEventListener('pointerup', this._handlePointerUp, {\n          passive: false,\n        });\n        addEventListener('pointercancel', this._handlePointerCancel, {\n          passive: false,\n        });\n        break;\n      default:\n      // do nothing\n    }\n\n    this._drawingStroke = true;\n\n    const pointGroupOptions = this._getPointGroupOptions();\n\n    const newPointGroup: PointGroup = {\n      ...pointGroupOptions,\n      points: [],\n    };\n\n    this._data.push(newPointGroup);\n    this._reset(pointGroupOptions);\n    this._strokeUpdate(event);\n  }\n\n  private _strokeUpdate(event: SignatureEvent): void {\n    if (!this._drawingStroke) {\n      return;\n    }\n\n    if (this._data.length === 0) {\n      // This can happen if clear() was called while a signature is still in progress,\n      // or if there is a race condition between start/update events.\n      this._strokeBegin(event);\n      return;\n    }\n\n    this.dispatchEvent(\n      new CustomEvent('beforeUpdateStroke', { detail: event }),\n    );\n\n    const point = this._createPoint(event.x, event.y, event.pressure);\n    const lastPointGroup = this._data[this._data.length - 1];\n    const lastPoints = lastPointGroup.points;\n    const lastPoint =\n      lastPoints.length > 0 && lastPoints[lastPoints.length - 1];\n    const isLastPointTooClose = lastPoint\n      ? point.distanceTo(lastPoint) <= this.minDistance\n      : false;\n    const pointGroupOptions = this._getPointGroupOptions(lastPointGroup);\n\n    // Skip this point if it's too close to the previous one\n    if (!lastPoint || !(lastPoint && isLastPointTooClose)) {\n      const curve = this._addPoint(point, pointGroupOptions);\n\n      if (!lastPoint) {\n        this._drawDot(point, pointGroupOptions);\n      } else if (curve) {\n        this._drawCurve(curve, pointGroupOptions);\n      }\n\n      lastPoints.push({\n        time: point.time,\n        x: point.x,\n        y: point.y,\n        pressure: point.pressure,\n      });\n    }\n\n    this.dispatchEvent(new CustomEvent('afterUpdateStroke', { detail: event }));\n  }\n\n  private _strokeEnd(event: SignatureEvent, shouldUpdate = true): void {\n    this._removeMoveUpEventListeners();\n\n    if (!this._drawingStroke) {\n      return;\n    }\n\n    if (shouldUpdate) {\n      this._strokeUpdate(event);\n    }\n\n    this._drawingStroke = false;\n    this._strokePointerId = undefined;\n    this.dispatchEvent(new CustomEvent('endStroke', { detail: event }));\n  }\n\n  private _handlePointerEvents(): void {\n    this._drawingStroke = false;\n\n    this.canvas.addEventListener('pointerdown', this._handlePointerDown, {\n      passive: false,\n    });\n  }\n\n  private _handleMouseEvents(): void {\n    this._drawingStroke = false;\n\n    this.canvas.addEventListener('mousedown', this._handleMouseDown, {\n      passive: false,\n    });\n  }\n\n  private _handleTouchEvents(): void {\n    this.canvas.addEventListener('touchstart', this._handleTouchStart, {\n      passive: false,\n    });\n  }\n\n  // Called when a new line is started\n  private _reset(options: PointGroupOptions): void {\n    this._lastPoints = [];\n    this._lastVelocity = 0;\n    this._lastWidth = (options.minWidth + options.maxWidth) / 2;\n    this._ctx.fillStyle = options.penColor;\n    this._ctx.globalCompositeOperation = options.compositeOperation;\n  }\n\n  private _createPoint(x: number, y: number, pressure: number): Point {\n    const rect = this.canvas.getBoundingClientRect();\n\n    return new Point(\n      x - rect.left,\n      y - rect.top,\n      pressure,\n      new Date().getTime(),\n    );\n  }\n\n  // Add point to _lastPoints array and generate a new curve if there are enough points (i.e. 3)\n  private _addPoint(point: Point, options: PointGroupOptions): Bezier | null {\n    const { _lastPoints } = this;\n\n    _lastPoints.push(point);\n\n    if (_lastPoints.length > 2) {\n      // To reduce the initial lag make it work with 3 points\n      // by copying the first point to the beginning.\n      if (_lastPoints.length === 3) {\n        _lastPoints.unshift(_lastPoints[0]);\n      }\n\n      // _points array will always have 4 points here.\n      const widths = this._calculateCurveWidths(\n        _lastPoints[1],\n        _lastPoints[2],\n        options,\n      );\n      const curve = Bezier.fromPoints(_lastPoints, widths);\n\n      // Remove the first element from the list, so that there are no more than 4 points at any time.\n      _lastPoints.shift();\n\n      return curve;\n    }\n\n    return null;\n  }\n\n  private _calculateCurveWidths(\n    startPoint: Point,\n    endPoint: Point,\n    options: PointGroupOptions,\n  ): { start: number; end: number } {\n    const velocity =\n      options.velocityFilterWeight * endPoint.velocityFrom(startPoint) +\n      (1 - options.velocityFilterWeight) * this._lastVelocity;\n\n    const newWidth = this._strokeWidth(velocity, options);\n\n    const widths = {\n      end: newWidth,\n      start: this._lastWidth,\n    };\n\n    this._lastVelocity = velocity;\n    this._lastWidth = newWidth;\n\n    return widths;\n  }\n\n  private _strokeWidth(velocity: number, options: PointGroupOptions): number {\n    return Math.max(options.maxWidth / (velocity + 1), options.minWidth);\n  }\n\n  private _drawCurveSegment(x: number, y: number, width: number): void {\n    const ctx = this._ctx;\n\n    ctx.moveTo(x, y);\n    ctx.arc(x, y, width, 0, 2 * Math.PI, false);\n    this._isEmpty = false;\n  }\n\n  private _drawCurve(curve: Bezier, options: PointGroupOptions): void {\n    const ctx = this._ctx;\n    const widthDelta = curve.endWidth - curve.startWidth;\n    // '2' is just an arbitrary number here. If only length is used, then\n    // there are gaps between curve segments :/\n    const drawSteps = Math.ceil(curve.length()) * 2;\n\n    ctx.beginPath();\n    ctx.fillStyle = options.penColor;\n\n    for (let i = 0; i < drawSteps; i += 1) {\n      // Calculate the Bezier (x, y) coordinate for this step.\n      const t = i / drawSteps;\n      const tt = t * t;\n      const ttt = tt * t;\n      const u = 1 - t;\n      const uu = u * u;\n      const uuu = uu * u;\n\n      let x = uuu * curve.startPoint.x;\n      x += 3 * uu * t * curve.control1.x;\n      x += 3 * u * tt * curve.control2.x;\n      x += ttt * curve.endPoint.x;\n\n      let y = uuu * curve.startPoint.y;\n      y += 3 * uu * t * curve.control1.y;\n      y += 3 * u * tt * curve.control2.y;\n      y += ttt * curve.endPoint.y;\n\n      const width = Math.min(\n        curve.startWidth + ttt * widthDelta,\n        options.maxWidth,\n      );\n      this._drawCurveSegment(x, y, width);\n    }\n\n    ctx.closePath();\n    ctx.fill();\n  }\n\n  private _getDotSize(options: PointGroupOptions): number {\n    return options.dotSize > 0\n      ? options.dotSize\n      : (options.minWidth + options.maxWidth) / 2;\n  }\n\n  private _drawDot(point: BasicPoint, options: PointGroupOptions): void {\n    const ctx = this._ctx;\n    const width = this._getDotSize(options);\n\n    ctx.beginPath();\n    this._drawCurveSegment(point.x, point.y, width);\n    ctx.closePath();\n    ctx.fillStyle = options.penColor;\n    ctx.fill();\n  }\n\n  private _drawLine(\n    startPoint: BasicPoint,\n    endPoint: BasicPoint,\n    options: PointGroupOptions,\n  ): void {\n    const ctx = this._ctx;\n\n    ctx.save();\n    ctx.beginPath();\n    ctx.moveTo(startPoint.x, startPoint.y);\n    ctx.lineTo(endPoint.x, endPoint.y);\n    ctx.lineWidth = this._getDotSize(options) * 2;\n    ctx.lineCap = 'round';\n    ctx.strokeStyle = options.penColor;\n    ctx.stroke();\n    ctx.restore();\n\n    this._isEmpty = false;\n  }\n\n  private _fromData(\n    pointGroups: PointGroup[],\n    drawCurve: SignaturePad['_drawCurve'],\n    drawDot: SignaturePad['_drawDot'],\n    drawLine: SignaturePad['_drawLine'],\n  ): void {\n    for (const group of pointGroups) {\n      const { points } = group;\n      const pointGroupOptions = this._getPointGroupOptions(group);\n\n      if (points.length > 2) {\n        for (let j = 0; j < points.length; j += 1) {\n          const basicPoint = points[j];\n          const point = new Point(\n            basicPoint.x,\n            basicPoint.y,\n            basicPoint.pressure,\n            basicPoint.time,\n          );\n\n          if (j === 0) {\n            this._reset(pointGroupOptions);\n          }\n\n          const curve = this._addPoint(point, pointGroupOptions);\n\n          if (curve) {\n            drawCurve(curve, pointGroupOptions);\n          }\n        }\n      } else if (points.length === 2) {\n        this._reset(pointGroupOptions);\n\n        drawLine(points[0], points[1], pointGroupOptions);\n      } else {\n        this._reset(pointGroupOptions);\n\n        drawDot(points[0], pointGroupOptions);\n      }\n    }\n  }\n\n  public toSVG({\n    includeBackgroundColor = false,\n    includeDataUrl = false,\n  }: ToSVGOptions = {}): string {\n    const pointGroups = this._data;\n    const ratio = Math.max(window.devicePixelRatio || 1, 1);\n    const minX = 0;\n    const minY = 0;\n    const maxX = this.canvas.width / ratio;\n    const maxY = this.canvas.height / ratio;\n    const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');\n\n    svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n    svg.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');\n    svg.setAttribute('viewBox', `${minX} ${minY} ${maxX} ${maxY}`);\n    svg.setAttribute('width', maxX.toString());\n    svg.setAttribute('height', maxY.toString());\n\n    if (includeBackgroundColor && this.backgroundColor) {\n      const rect = document.createElement('rect');\n      rect.setAttribute('width', '100%');\n      rect.setAttribute('height', '100%');\n      rect.setAttribute('fill', this.backgroundColor);\n\n      svg.appendChild(rect);\n    }\n\n    if (includeDataUrl && this._dataUrl) {\n      const ratio = this._dataUrlOptions?.ratio || window.devicePixelRatio || 1;\n      const width = this._dataUrlOptions?.width || this.canvas.width / ratio;\n      const height = this._dataUrlOptions?.height || this.canvas.height / ratio;\n      const xOffset = this._dataUrlOptions?.xOffset || 0;\n      const yOffset = this._dataUrlOptions?.yOffset || 0;\n\n      const image = document.createElement('image');\n      image.setAttribute('x', xOffset.toString());\n      image.setAttribute('y', yOffset.toString());\n      image.setAttribute('width', width.toString());\n      image.setAttribute('height', height.toString());\n      image.setAttribute('preserveAspectRatio', 'none');\n      image.setAttribute('href', this._dataUrl);\n\n      svg.appendChild(image);\n    }\n\n    this._fromData(\n      pointGroups,\n\n      (curve, { penColor }) => {\n        const path = document.createElement('path');\n\n        // Need to check curve for NaN values, these pop up when drawing\n        // lines on the canvas that are not continuous. E.g. Sharp corners\n        // or stopping mid-stroke and than continuing without lifting mouse.\n        if (\n          !isNaN(curve.control1.x) &&\n          !isNaN(curve.control1.y) &&\n          !isNaN(curve.control2.x) &&\n          !isNaN(curve.control2.y)\n        ) {\n          const attr =\n            `M ${curve.startPoint.x.toFixed(3)},${curve.startPoint.y.toFixed(\n              3,\n            )} ` +\n            `C ${curve.control1.x.toFixed(3)},${curve.control1.y.toFixed(3)} ` +\n            `${curve.control2.x.toFixed(3)},${curve.control2.y.toFixed(3)} ` +\n            `${curve.endPoint.x.toFixed(3)},${curve.endPoint.y.toFixed(3)}`;\n          path.setAttribute('d', attr);\n          path.setAttribute('stroke-width', (curve.endWidth * 2.25).toFixed(3));\n          path.setAttribute('stroke', penColor);\n          path.setAttribute('fill', 'none');\n          path.setAttribute('stroke-linecap', 'round');\n\n          svg.appendChild(path);\n        }\n      },\n\n      (point, { penColor, dotSize, minWidth, maxWidth }) => {\n        const circle = document.createElement('circle');\n        const size = dotSize > 0 ? dotSize : (minWidth + maxWidth) / 2;\n        circle.setAttribute('r', size.toString());\n        circle.setAttribute('cx', point.x.toString());\n        circle.setAttribute('cy', point.y.toString());\n        circle.setAttribute('fill', penColor);\n\n        svg.appendChild(circle);\n      },\n\n      (startPoint, endPoint, options) => {\n        const line = document.createElement('line');\n\n        line.setAttribute('x1', startPoint.x.toString());\n        line.setAttribute('y1', startPoint.y.toString());\n        line.setAttribute('x2', endPoint.x.toString());\n        line.setAttribute('y2', endPoint.y.toString());\n        line.setAttribute('stroke', options.penColor);\n        line.setAttribute(\n          'stroke-width',\n          (this._getDotSize(options) * 2).toString(),\n        );\n        line.setAttribute('stroke-linecap', 'round');\n\n        svg.appendChild(line);\n      },\n    );\n\n    return svg.outerHTML;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Stack } from '@mantine/core';\nimport type { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport type { QuestionnaireFormLoadedState } from '@medplum/react-hooks';\nimport { isQuestionEnabled, QuestionnaireItemType } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { Fragment } from 'react';\nimport { FormSection } from '../FormSection/FormSection';\nimport { QuestionnaireFormGroup } from './QuestionnaireFormGroup';\nimport { QuestionnaireFormItem } from './QuestionnaireFormItem';\nimport { QuestionnaireFormRepeatableGroup } from './QuestionnaireFormRepeatableGroup';\nimport { QuestionnaireFormRepeatableItem } from './QuestionnaireFormRepeatableItem';\n\nexport interface QuestionnaireFormItemArrayProps {\n  readonly formState: QuestionnaireFormLoadedState;\n  readonly context: QuestionnaireResponseItem[];\n  readonly items: QuestionnaireItem[];\n  readonly responseItems: QuestionnaireResponseItem[];\n}\n\nexport function QuestionnaireFormItemArray(props: QuestionnaireFormItemArrayProps): JSX.Element {\n  const { formState, context, items, responseItems } = props;\n  const isTopLevel = context.length === 0;\n  // Tracks whether a top-level group has already been rendered so we can\n  // insert a divider before each subsequent group section.\n  let hasRenderedSection = false;\n\n  return (\n    <Stack gap=\"xl\">\n      {items.map((item, index) => {\n        if (!isQuestionEnabled(item, formState.questionnaireResponse)) {\n          return null;\n        }\n        const isGroup = item.type === QuestionnaireItemType.group;\n        const showSectionDivider = isTopLevel && isGroup && hasRenderedSection;\n        if (isGroup) {\n          hasRenderedSection = true;\n        }\n\n        if (item.type === QuestionnaireItemType.display) {\n          return <p key={`display-${item.id}-${index}`}>{item.text}</p>;\n        }\n\n        const filteredResponseItems = responseItems.filter((responseItem) => responseItem.linkId === item.linkId);\n\n        if (item.type === QuestionnaireItemType.group && item.repeats) {\n          return (\n            <Fragment key={`repeating-group-${item.id}-${index}`}>\n              {showSectionDivider && <Divider color=\"var(--mantine-color-gray-2)\" />}\n              <QuestionnaireFormRepeatableGroup\n                formState={formState}\n                context={context}\n                item={item}\n                responseItems={filteredResponseItems}\n              />\n            </Fragment>\n          );\n        }\n\n        if (item.type === QuestionnaireItemType.group) {\n          return (\n            <Fragment key={`group-${item.id}-${index}`}>\n              {showSectionDivider && <Divider color=\"var(--mantine-color-gray-2)\" />}\n              <QuestionnaireFormGroup\n                formState={formState}\n                context={context}\n                item={item}\n                responseItem={filteredResponseItems[0]}\n              />\n            </Fragment>\n          );\n        }\n\n        if (item.type === QuestionnaireItemType.boolean) {\n          // Special case for boolean items to avoid duplicate text\n          return (\n            <QuestionnaireFormItem\n              key={`boolean-item-${item.id}-${index}`}\n              formState={formState}\n              context={context}\n              item={item}\n              responseItem={filteredResponseItems[0]}\n              index={0}\n            />\n          );\n        }\n\n        if (item.repeats) {\n          return (\n            <QuestionnaireFormRepeatableItem\n              key={`repeating-item-${item.id}-${index}`}\n              formState={formState}\n              context={context}\n              item={item}\n              responseItem={filteredResponseItems[0]}\n            />\n          );\n        }\n\n        return (\n          <FormSection\n            key={`repeating-item-${item.id}-${index}`}\n            htmlFor={item.linkId}\n            title={item.text}\n            withAsterisk={item.required}\n          >\n            <QuestionnaireFormItem\n              formState={formState}\n              context={context}\n              item={item}\n              responseItem={filteredResponseItems[0]}\n              index={0}\n            />\n          </FormSection>\n        );\n      })}\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Title } from '@mantine/core';\nimport type { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport type { QuestionnaireFormLoadedState } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { QuestionnaireFormItemArray } from './QuestionnaireFormItemArray';\n\nexport interface QuestionnaireFormGroupProps {\n  readonly formState: QuestionnaireFormLoadedState;\n  readonly context: QuestionnaireResponseItem[];\n  readonly item: QuestionnaireItem;\n  readonly responseItem: QuestionnaireResponseItem;\n}\n\nexport function QuestionnaireFormGroup(props: QuestionnaireFormGroupProps): JSX.Element | null {\n  const newContext = [...props.context, props.responseItem];\n  return (\n    <div key={props.item.linkId}>\n      {props.item.text && (\n        <Title order={4} mb=\"md\">\n          {props.item.text}\n        </Title>\n      )}\n      <QuestionnaireFormItemArray\n        formState={props.formState}\n        context={newContext}\n        items={props.item.item ?? []}\n        responseItems={props.responseItem.item ?? []}\n      />\n    </div>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor } from '@mantine/core';\nimport type { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport type { QuestionnaireFormLoadedState } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { QuestionnaireFormGroup } from './QuestionnaireFormGroup';\n\nexport interface QuestionnaireFormRepeatableGroupProps {\n  readonly formState: QuestionnaireFormLoadedState;\n  readonly context: QuestionnaireResponseItem[];\n  readonly item: QuestionnaireItem;\n  readonly responseItems: QuestionnaireResponseItem[];\n}\n\nexport function QuestionnaireFormRepeatableGroup(props: QuestionnaireFormRepeatableGroupProps): JSX.Element | null {\n  return (\n    <>\n      {props.responseItems.map((response) => (\n        <QuestionnaireFormGroup\n          key={`group-${response.id}`}\n          formState={props.formState}\n          context={props.context}\n          item={props.item}\n          responseItem={response}\n        />\n      ))}\n      <Anchor\n        onClick={() => props.formState.onAddGroup(props.context, props.item)}\n      >{`Add Group: ${props.item.text}`}</Anchor>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Anchor, Stack } from '@mantine/core';\nimport type { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport type { QuestionnaireFormLoadedState } from '@medplum/react-hooks';\nimport { QuestionnaireItemType } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { FormSection } from '../FormSection/FormSection';\nimport { QuestionnaireFormItem } from './QuestionnaireFormItem';\n\nexport interface QuestionnaireFormRepeatableItemProps {\n  readonly formState: QuestionnaireFormLoadedState;\n  readonly context: QuestionnaireResponseItem[];\n  readonly item: QuestionnaireItem;\n  readonly responseItem: QuestionnaireResponseItem;\n}\n\nexport function QuestionnaireFormRepeatableItem(props: QuestionnaireFormRepeatableItemProps): JSX.Element | null {\n  const { formState, context, item, responseItem } = props;\n  const isChoiceType = item.type === QuestionnaireItemType.choice || item.type === QuestionnaireItemType.openChoice;\n  const showAddButton = !isChoiceType;\n\n  const answers = !isChoiceType && responseItem.answer && responseItem.answer.length > 0 ? responseItem.answer : [{}];\n  return (\n    <FormSection key={props.item.linkId} title={props.item.text} withAsterisk={props.item.required}>\n      <Stack gap=\"xs\">\n        {answers?.map((_, index) => (\n          <QuestionnaireFormItem\n            key={`${item.linkId}-${index}`}\n            formState={formState}\n            context={context}\n            item={item}\n            responseItem={responseItem}\n            index={index}\n          />\n        ))}\n      </Stack>\n      {showAddButton && <Anchor onClick={() => formState.onAddAnswer(context, item)}>Add Item</Anchor>}\n    </FormSection>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Group, Stepper } from '@mantine/core';\nimport type { QuestionnaireFormPaginationState } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { SubmitButton } from '../Form/SubmitButton';\n\nexport interface QuestionnaireFormStepperProps {\n  readonly formState: QuestionnaireFormPaginationState;\n  readonly submitButtonText?: string;\n  readonly excludeButtons?: boolean;\n  readonly children?: React.ReactNode;\n}\n\nexport function QuestionnaireFormStepper(props: QuestionnaireFormStepperProps): JSX.Element {\n  const { formState, submitButtonText, excludeButtons, children } = props;\n  const pages = formState.pages;\n  const activePage = formState.activePage;\n  const showBackButton = activePage > 0;\n  const showNextButton = activePage < pages.length - 1;\n  const showSubmitButton = activePage === pages.length - 1;\n\n  return (\n    <>\n      <Stepper active={activePage} allowNextStepsSelect={false} p={6}>\n        {pages.map((page, index) => (\n          <Stepper.Step key={page.linkId} label={page.title}>\n            {index === activePage && children}\n          </Stepper.Step>\n        ))}\n      </Stepper>\n      {!excludeButtons && (\n        <Group justify=\"flex-end\" mt=\"xl\" gap=\"xs\">\n          {showBackButton && <Button onClick={formState.onPrevPage}>Back</Button>}\n          {showNextButton && (\n            <Button\n              onClick={(e) => {\n                const form = e.currentTarget.closest('form') as HTMLFormElement;\n                if (form.reportValidity()) {\n                  formState.onNextPage();\n                }\n              }}\n            >\n              Next\n            </Button>\n          )}\n          {showSubmitButton && <SubmitButton>{submitButtonText ?? 'Submit'}</SubmitButton>}\n        </Group>\n      )}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Stack } from '@mantine/core';\nimport type { QuestionnaireResponse, Reference } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { QuestionnaireResponseItemDisplay } from './QuestionnaireResponseItemDisplay';\n\nexport interface QuestionnaireResponseDisplayProps {\n  readonly questionnaireResponse: QuestionnaireResponse | Reference<QuestionnaireResponse>;\n}\n\nexport function QuestionnaireResponseDisplay(props: QuestionnaireResponseDisplayProps): JSX.Element {\n  const questionnaireResponse = useResource(props.questionnaireResponse);\n\n  return (\n    <Stack gap={0}>\n      {questionnaireResponse?.item?.map((item, index) => (\n        <QuestionnaireResponseItemDisplay key={`item-${item.id ?? index}`} item={item} />\n      ))}\n    </Stack>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Stack, Text } from '@mantine/core';\nimport { formatDate } from '@medplum/core';\nimport type { QuestionnaireResponseItem, QuestionnaireResponseItemAnswer } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { useMemo } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\nimport { RangeDisplay } from '../RangeDisplay/RangeDisplay';\n\nexport interface QuestionnaireResponseItemDisplayProps {\n  readonly item: QuestionnaireResponseItem;\n}\n\nexport function QuestionnaireResponseItemDisplay(props: QuestionnaireResponseItemDisplayProps): JSX.Element {\n  const { item } = props;\n  const { text: title, answer, item: nestedAnswers } = item;\n\n  const renderContent = useMemo((): JSX.Element => {\n    if (answer && answer.length > 0) {\n      return (\n        <>\n          {answer.map((ans, index) => (\n            <AnswerDisplay key={`answer-${index}`} answer={ans} />\n          ))}\n        </>\n      );\n    } else if (nestedAnswers && nestedAnswers.length > 0) {\n      return (\n        <>\n          {nestedAnswers.map((nestedAnswer, index) => (\n            <QuestionnaireResponseItemDisplay key={`nested-${nestedAnswer.id ?? index}`} item={nestedAnswer} />\n          ))}\n        </>\n      );\n    } else {\n      return <Text c=\"dimmed\">No answer</Text>;\n    }\n  }, [answer, nestedAnswers]);\n\n  return (\n    <Stack gap={0} pb=\"xs\">\n      <Text size=\"lg\" fw={600} id={item.id ? `question-${item.id}` : undefined} component=\"h3\">\n        {title}\n      </Text>\n      {renderContent}\n    </Stack>\n  );\n}\n\ninterface AnswerDisplayProps {\n  readonly answer: QuestionnaireResponseItemAnswer;\n}\n\nfunction AnswerDisplay({ answer }: AnswerDisplayProps): JSX.Element {\n  if (!answer) {\n    return <Text c=\"dimmed\">Invalid answer</Text>;\n  }\n\n  const validEntries = Object.entries(answer).filter(([, value]) => value !== undefined && value !== null);\n\n  if (validEntries.length === 0) {\n    return <Text c=\"dimmed\">No valid answer data</Text>;\n  }\n\n  const [key, value] = validEntries[0];\n\n  switch (key) {\n    case 'valueInteger':\n      return <Text>{value}</Text>;\n    case 'valueQuantity':\n      return <QuantityDisplay value={value} />;\n    case 'valueString':\n      return <Text>{value}</Text>;\n    case 'valueCoding':\n      return <CodeableConceptDisplay value={{ coding: [value] }} />;\n    case 'valueRange':\n      return <RangeDisplay value={value} />;\n    case 'valueDateTime':\n      return <Text>{formatDate(value)}</Text>;\n    case 'valueBoolean':\n      return <Text>{value ? 'True' : 'False'}</Text>;\n    case 'valueReference':\n      return <Text>{value.display ?? value.reference}</Text>;\n    default:\n      return <Text>{value.toString()}</Text>;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Divider, Group, NativeSelect, Stack, Text, TextInput } from '@mantine/core';\nimport { formatRange, getCodeBySystem } from '@medplum/core';\nimport type {\n  CodeableConcept,\n  ObservationDefinition,\n  ObservationDefinitionQualifiedInterval,\n} from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCirclePlus } from '@tabler/icons-react';\nimport type { JSX, MouseEvent } from 'react';\nimport { useEffect, useState } from 'react';\nimport { Container } from '../Container/Container';\nimport { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { RangeInput } from '../RangeInput/RangeInput';\nimport { killEvent } from '../utils/dom';\nimport classes from './ReferenceRangeEditor.module.css';\n\n// Properties of qualified intervals used for grouping\nconst intervalFilters = ['gender', 'age', 'gestationalAge', 'context', 'appliesTo', 'category'] as const;\n\nexport interface ReferenceRangeEditorProps {\n  readonly definition: ObservationDefinition;\n  readonly onSubmit: (result: ObservationDefinition) => void;\n}\n\n// Helper type that groups of qualified intervals by equal filter criteria\nexport type IntervalGroup = {\n  id: string;\n  filters: Record<string, any>;\n  intervals: ObservationDefinitionQualifiedInterval[];\n};\n\nconst defaultProps: ReferenceRangeEditorProps = {\n  definition: {\n    resourceType: 'ObservationDefinition',\n    code: { text: '' },\n  },\n  onSubmit: () => {\n    return undefined;\n  },\n};\n\nexport function ReferenceRangeEditor(props: ReferenceRangeEditorProps): JSX.Element {\n  props = Object.assign(defaultProps, props);\n  const defaultDefinition = props.definition;\n\n  const [intervalGroups, setIntervalGroups] = useState<IntervalGroup[]>([]);\n  const [groupId, setGroupId] = useState(1);\n  const [intervalId, setIntervalId] = useState(1);\n\n  useEffect(() => {\n    const definition = ensureQualifiedIntervalKeys(defaultDefinition, setIntervalId);\n    setIntervalGroups(groupQualifiedIntervals(definition.qualifiedInterval || [], setGroupId));\n  }, [defaultDefinition]);\n\n  return (\n    <Form testid=\"reference-range-editor\" onSubmit={submitDefinition}>\n      <Stack>\n        {intervalGroups.map((intervalGroup) => (\n          <ReferenceRangeGroupEditor\n            unit={getUnitString(defaultDefinition.quantitativeDetails?.unit)}\n            onChange={changeInterval}\n            onAdd={addInterval}\n            onRemove={removeInterval}\n            onRemoveGroup={removeGroup}\n            key={`group-${intervalGroup.id}`}\n            intervalGroup={intervalGroup}\n          />\n        ))}\n      </Stack>\n      <ActionIcon\n        title=\"Add Group\"\n        variant=\"subtle\"\n        size=\"sm\"\n        onClick={(e: MouseEvent) => {\n          killEvent(e);\n          addGroup({ id: `group-id-${groupId}`, filters: {}, intervals: [] });\n          setGroupId((id) => id + 1);\n        }}\n      >\n        <IconCirclePlus />\n      </ActionIcon>\n\n      <Group justify=\"flex-end\">\n        <SubmitButton>Save</SubmitButton>\n      </Group>\n    </Form>\n  );\n\n  /**\n   * Submit qualified intervals\n   */\n\n  function submitDefinition(): void {\n    const qualifiedInterval = intervalGroups\n      .flatMap((group) => group.intervals)\n      .filter((interval) => !isEmptyInterval(interval));\n    props.onSubmit({ ...defaultDefinition, qualifiedInterval });\n  }\n\n  /**\n   * Add Remove Interval Groups\n   */\n\n  function addGroup(addedGroup: IntervalGroup): void {\n    setIntervalGroups((currentGroups) => [...currentGroups, addedGroup]);\n  }\n\n  function removeGroup(removedGroup: IntervalGroup): void {\n    setIntervalGroups((currentGroups) => currentGroups.filter((group) => group.id !== removedGroup.id));\n  }\n\n  /**\n   * Add/Remove/Update specific Qualified Intervals\n   * @param groupId - The reference range group ID.\n   * @param changedInterval - The updated reference range interval.\n   */\n  function changeInterval(groupId: string, changedInterval: ObservationDefinitionQualifiedInterval): void {\n    setIntervalGroups((groups) => {\n      groups = [...groups];\n      const currentGroup = groups.find((g) => g.id === groupId);\n\n      const index = currentGroup?.intervals.findIndex((interval) => interval.id === changedInterval.id);\n      if (index !== undefined && currentGroup?.intervals[index]) {\n        currentGroup.intervals[index] = changedInterval;\n      }\n      return groups;\n    });\n  }\n\n  function addInterval(groupId: string, addedInterval: ObservationDefinitionQualifiedInterval): void {\n    if (addedInterval.id === undefined) {\n      addedInterval.id = `id-${intervalId}`;\n      setIntervalId((id) => id + 1);\n    }\n    setIntervalGroups((groups) => {\n      groups = [...groups];\n      const currentGroupIndex = groups.findIndex((g) => g.id === groupId);\n\n      if (currentGroupIndex !== -1) {\n        const currentGroup = { ...groups[currentGroupIndex] };\n        addedInterval = { ...addedInterval, ...currentGroup.filters };\n        currentGroup.intervals = [...currentGroup.intervals, addedInterval];\n        groups[currentGroupIndex] = currentGroup;\n      }\n\n      return groups;\n    });\n  }\n\n  function removeInterval(groupId: string, removedInterval: ObservationDefinitionQualifiedInterval): void {\n    setIntervalGroups((groups) => {\n      groups = [...groups];\n      const currentGroup = groups.find((g) => g.id === groupId);\n      if (currentGroup) {\n        currentGroup.intervals = currentGroup.intervals.filter((interval) => interval.id !== removedInterval.id);\n      }\n      return groups;\n    });\n  }\n}\n\n/**\n * Helper component that renders an \"interval group\", which is a set of ObservationDefinitionQualifiedIntervals\n * that have the same filter values\n */\nexport interface ReferenceRangeGroupEditorProps {\n  readonly intervalGroup: IntervalGroup;\n  readonly unit: string | undefined;\n  readonly onChange: (groupId: string, changed: ObservationDefinitionQualifiedInterval) => void;\n  readonly onAdd: (groupId: string, added: ObservationDefinitionQualifiedInterval) => void;\n  readonly onRemove: (groupId: string, removed: ObservationDefinitionQualifiedInterval) => void;\n  readonly onRemoveGroup: (removedGroup: IntervalGroup) => void;\n}\n\nexport function ReferenceRangeGroupEditor(props: ReferenceRangeGroupEditorProps): JSX.Element {\n  const { intervalGroup, unit } = props;\n  return (\n    <Container data-testid={intervalGroup.id} className={classes.section}>\n      <Stack gap=\"lg\">\n        <Group justify=\"flex-end\">\n          <ActionIcon\n            title=\"Remove Group\"\n            variant=\"subtle\"\n            data-testid={`remove-group-button-${intervalGroup.id}`}\n            key={`remove-group-button-${intervalGroup.id}`}\n            size=\"sm\"\n            onClick={(e: MouseEvent) => {\n              killEvent(e);\n              props.onRemoveGroup(intervalGroup);\n            }}\n          >\n            <IconCircleMinus />\n          </ActionIcon>\n        </Group>\n        <ReferenceRangeGroupFilters intervalGroup={intervalGroup} onChange={props.onChange} />\n        <Divider />\n        {intervalGroup.intervals.map((interval) => (\n          <Stack key={`interval-${interval.id}`} gap=\"xs\">\n            <Group>\n              <TextInput\n                key={`condition-${interval.id}`}\n                data-testid={`condition-${interval.id}`}\n                defaultValue={interval.condition}\n                label=\"Condition: \"\n                size=\"sm\"\n                onChange={(e) => {\n                  killEvent(e);\n                  props.onChange(intervalGroup.id, { ...interval, condition: e.currentTarget.value.trim() });\n                }}\n              />\n              <ActionIcon\n                title=\"Remove Interval\"\n                variant=\"subtle\"\n                size=\"sm\"\n                key={`remove-interval-${interval.id}`}\n                data-testid={`remove-interval-${interval.id}`}\n                onClick={(e: MouseEvent) => {\n                  killEvent(e);\n                  props.onRemove(intervalGroup.id, interval);\n                }}\n              >\n                <IconCircleMinus />\n              </ActionIcon>\n            </Group>\n\n            <RangeInput\n              path=\"\"\n              onChange={(range) => {\n                props.onChange(intervalGroup.id, { ...interval, range });\n              }}\n              key={`range-${interval.id}`}\n              name={`range-${interval.id}`}\n              defaultValue={interval.range}\n            />\n          </Stack>\n        ))}\n        <ActionIcon\n          title=\"Add Interval\"\n          variant=\"subtle\"\n          size=\"sm\"\n          onClick={(e: MouseEvent) => {\n            killEvent(e);\n            props.onAdd(intervalGroup.id, {\n              range: {\n                low: { unit },\n                high: { unit },\n              },\n            });\n          }}\n        >\n          <IconCirclePlus />\n        </ActionIcon>\n      </Stack>\n    </Container>\n  );\n}\n\ninterface ReferenceRangeGroupFiltersProps {\n  readonly intervalGroup: IntervalGroup;\n  readonly onChange: ReferenceRangeGroupEditorProps['onChange'];\n}\n\n/**\n * Render the \"filters\" section of the IntervalGroup.\n * @param props - The ReferenceRangeGroupFilter React props.\n * @returns The ReferenceRangeGroupFilter React node.\n */\nfunction ReferenceRangeGroupFilters(props: ReferenceRangeGroupFiltersProps): JSX.Element {\n  const { intervalGroup, onChange } = props;\n\n  // Pre-populate the units of the age filter (computed locally, not mutating props)\n  const age = intervalGroup.filters.age ?? {};\n  const ageWithDefaults = {\n    low: age.low?.unit ? age.low : { ...age.low, unit: 'years', system: 'http://unitsofmeasure.org' },\n    high: age.high?.unit ? age.high : { ...age.high, unit: 'years', system: 'http://unitsofmeasure.org' },\n  };\n\n  return (\n    <Stack style={{ maxWidth: '50%' }}>\n      <Group>\n        <NativeSelect\n          data={['', 'male', 'female']}\n          label=\"Gender:\"\n          defaultValue={intervalGroup.filters.gender || ''}\n          onChange={(e) => {\n            for (const interval of intervalGroup.intervals) {\n              let newGender: string | undefined = e.currentTarget.value;\n              if (newGender === '') {\n                newGender = undefined;\n              }\n              onChange(intervalGroup.id, {\n                ...interval,\n                gender: newGender as ObservationDefinitionQualifiedInterval['gender'],\n              });\n            }\n          }}\n        />\n      </Group>\n      <Group gap=\"xs\">\n        <Text component=\"label\" htmlFor={`div-age-${intervalGroup.id}`}>\n          Age:\n        </Text>\n        <div id={`div-age-${intervalGroup.id}`}>\n          <RangeInput\n            path=\"\"\n            key={`age-${intervalGroup.id}`}\n            name={`age-${intervalGroup.id}`}\n            defaultValue={ageWithDefaults}\n            onChange={(ageRange) => {\n              for (const interval of intervalGroup.intervals) {\n                onChange(intervalGroup.id, { ...interval, age: ageRange });\n              }\n            }}\n          />\n        </div>\n      </Group>\n      <NativeSelect\n        data={['', 'pre-puberty', 'follicular', 'midcycle', 'luteal', 'postmenopausal']}\n        label=\"Endocrine:\"\n        defaultValue={intervalGroup.filters.context?.text || ''}\n        onChange={(e) => {\n          for (const interval of intervalGroup.intervals) {\n            let newEndocrine: string | undefined = e.currentTarget.value;\n            if (newEndocrine === '') {\n              newEndocrine = undefined;\n              onChange(intervalGroup.id, { ...interval, context: undefined });\n            } else {\n              onChange(intervalGroup.id, {\n                ...interval,\n                context: {\n                  text: newEndocrine,\n                  coding: [\n                    { code: newEndocrine, system: 'http://terminology.hl7.org/CodeSystem/referencerange-meaning' },\n                  ],\n                },\n              });\n            }\n          }\n        }}\n      />\n      <NativeSelect\n        data={['', 'reference', 'critical', 'absolute']}\n        label=\"Category: \"\n        defaultValue={intervalGroup.filters.category}\n        onChange={(e) => {\n          for (const interval of intervalGroup.intervals) {\n            const newCategory: string | undefined = e.currentTarget.value;\n            if (newCategory === '') {\n              onChange(intervalGroup.id, { ...interval, category: undefined });\n            } else {\n              onChange(intervalGroup.id, {\n                ...interval,\n                category: newCategory as 'reference' | 'critical' | 'absolute',\n              });\n            }\n          }\n        }}\n      />\n    </Stack>\n  );\n}\n\n/**\n * Helper function that assigns ids to each qualifiedInterval of an ObservationDefinition\n * @param definition - An ObservationDefinition\n * @param setIntervalId - React setState function for the intervalId\n * @returns The updated observation definition.\n */\nfunction ensureQualifiedIntervalKeys(\n  definition: ObservationDefinition,\n  setIntervalId: (id: number) => void\n): ObservationDefinition {\n  const intervals = definition.qualifiedInterval || [];\n  // Set the nextId to the max of any existing numeric id\n  let nextId =\n    Math.max(\n      ...intervals.map((interval) => {\n        const existingNum = Number.parseInt(interval.id?.substring(3) || '', 10);\n        return !Number.isNaN(existingNum) ? existingNum : Number.NEGATIVE_INFINITY;\n      })\n    ) + 1;\n\n  if (!Number.isFinite(nextId)) {\n    nextId = 1;\n  }\n\n  // If an interval doesn't have an id, set it to the nextId\n  definition = {\n    ...definition,\n    qualifiedInterval: intervals.map((interval) => ({\n      ...interval,\n      id: interval.id || `id-${nextId++}`,\n    })),\n  };\n  setIntervalId(nextId);\n  return definition;\n}\n\n/**\n * Group all ObservationDefinitionQualifiedIntervals based on the values of their \"filter\" properties,\n * so that similar ranges can be grouped together.\n * @param intervals - Array of reference range intervals.\n * @param setGroupId - Callback to set the group ID.\n * @returns The grouped intervals.\n */\nfunction groupQualifiedIntervals(\n  intervals: ObservationDefinitionQualifiedInterval[],\n  setGroupId: (id: number) => void\n): IntervalGroup[] {\n  let groupId = 1;\n  const groups: Record<string, IntervalGroup> = {};\n  for (const interval of intervals) {\n    const groupKey = generateGroupKey(interval);\n    if (!(groupKey in groups)) {\n      groups[groupKey] = {\n        id: `group-id-${groupId++}`,\n        filters: Object.fromEntries(intervalFilters.map((f) => [f, interval[f]])),\n        intervals: [],\n      };\n    }\n    groups[groupKey].intervals.push(interval);\n  }\n  setGroupId(groupId);\n  return Object.values(groups);\n}\n\n/**\n * Generates a unique string for each set of filter values, so that similarly filtered intervals can be grouped together.\n * @param interval - The reference range interval.\n * @returns A \"group key\" that corresponds to the value of the interval filter properties.\n */\nfunction generateGroupKey(interval: ObservationDefinitionQualifiedInterval): string {\n  const results = [\n    `gender=${interval.gender}`,\n    `age=${formatRange(interval.age)}`,\n    `gestationalAge=${formatRange(interval.gestationalAge)}`,\n    `context=${interval.context?.text}`,\n    `appliesTo=${interval.appliesTo?.map((c) => c.text).join('+')}`,\n    `category=${interval.category}`,\n  ];\n\n  return results.join(':');\n}\n\nfunction getUnitString(unit: CodeableConcept | undefined): string | undefined {\n  return unit && (getCodeBySystem(unit, 'http://unitsofmeasure.org') || unit.text);\n}\n\nfunction isEmptyInterval(interval: ObservationDefinitionQualifiedInterval): boolean {\n  return interval.range?.low?.value === undefined && interval.range?.high?.value === undefined;\n}\n", ".section {\n  position: relative;\n  margin: 4px 4px 8px;\n  padding: 6px 12px 16px 6px;\n  border: 1.5px solid var(--mantine-color-gray-3);\n  border-radius: var(--mantine-radius-sm);\n  transition: all 0.1;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Grid, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport type { Bundle, BundleEntry, Reference, RequestGroup, Resource, Task } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconCheckbox, IconSquare } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { Fragment, useEffect, useState } from 'react';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport { StatusBadge } from '../StatusBadge/StatusBadge';\n\nexport interface RequestGroupDisplayProps {\n  readonly value?: RequestGroup | Reference<RequestGroup>;\n  readonly onStart: (task: Task, input: Reference) => void;\n  readonly onEdit: (task: Task, input: Reference, output: Reference) => void;\n}\n\nexport function RequestGroupDisplay(props: RequestGroupDisplayProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const requestGroup = useResource(props.value);\n  const [startedLoading, setStartedLoading] = useState(false);\n  const [responseBundle, setResponseBundle] = useState<Bundle>();\n\n  useEffect(() => {\n    if (requestGroup && !startedLoading) {\n      medplum.executeBatch(buildBatchRequest(requestGroup)).then(setResponseBundle).catch(console.log);\n      setStartedLoading(true);\n    }\n  }, [medplum, requestGroup, startedLoading]);\n\n  if (!requestGroup || !responseBundle) {\n    return null;\n  }\n\n  return (\n    <Grid>\n      {requestGroup.action?.map((action, index) => {\n        const task = action.resource && findBundleEntry(action.resource as Reference<Task>);\n        const taskInput = task?.input?.[0]?.valueReference;\n        const taskOutput = task?.output?.[0]?.valueReference;\n        return (\n          <Fragment key={`action-${index}`}>\n            <Grid.Col span={1} p=\"md\">\n              {task?.status === 'completed' ? <IconCheckbox /> : <IconSquare color=\"gray\" />}\n            </Grid.Col>\n            <Grid.Col span={9} p=\"xs\">\n              <Text fw={500}>{action.title}</Text>\n              {action.description && <div>{action.description}</div>}\n              <div>\n                Last edited by&nbsp;\n                <ResourceName value={task?.meta?.author} />\n                &nbsp;on&nbsp;\n                {formatDateTime(task?.meta?.lastUpdated)}\n              </div>\n              <div>\n                Status: <StatusBadge status={task?.status || 'unknown'} />\n              </div>\n            </Grid.Col>\n            <Grid.Col span={2} p=\"md\">\n              {taskInput && !taskOutput && <Button onClick={() => props.onStart(task, taskInput)}>Start</Button>}\n              {taskInput && taskOutput && (\n                <Button onClick={() => props.onEdit(task, taskInput, taskOutput)}>Edit</Button>\n              )}\n            </Grid.Col>\n          </Fragment>\n        );\n      })}\n    </Grid>\n  );\n\n  function buildBatchRequest(request: RequestGroup): Bundle {\n    const batchEntries: BundleEntry[] = [];\n    if (request.action) {\n      for (const action of request.action) {\n        if (action.resource?.reference) {\n          batchEntries.push({ request: { method: 'GET', url: action.resource.reference } });\n        }\n      }\n    }\n\n    return {\n      resourceType: 'Bundle',\n      type: 'batch',\n      entry: batchEntries,\n    };\n  }\n\n  function findBundleEntry<T extends Resource>(reference: Reference<T>): T | undefined {\n    for (const entry of responseBundle?.entry ?? []) {\n      if (entry.resource && reference.reference === getReferenceString(entry.resource)) {\n        return entry.resource as T;\n      }\n    }\n    return undefined;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Bundle, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport { blame } from '../utils/blame';\nimport classes from './ResourceBlame.module.css';\nimport { getTimeString, getVersionUrl } from './ResourceBlame.utils';\n\nexport interface ResourceBlameProps {\n  readonly history?: Bundle;\n  readonly resourceType?: ResourceType;\n  readonly id?: string;\n}\n\nexport function ResourceBlame(props: ResourceBlameProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const [value, setValue] = useState(props.history);\n\n  useEffect(() => {\n    if (!props.history && props.resourceType && props.id) {\n      medplum.readHistory(props.resourceType, props.id).then(setValue).catch(console.log);\n    }\n  }, [medplum, props.history, props.resourceType, props.id]);\n\n  if (!value) {\n    return <div>Loading...</div>;\n  }\n\n  const resource = value.entry?.[0]?.resource as Resource;\n\n  if (!resource) {\n    return null;\n  }\n\n  const table = blame(value);\n\n  return (\n    <div className={classes.container}>\n      <table className={classes.root}>\n        <tbody>\n          {table.map((row, index) => (\n            <tr key={'row-' + index} className={row.span > 0 ? classes.startRow : classes.normalRow}>\n              {row.span > 0 && (\n                <>\n                  <td className={classes.author} rowSpan={row.span}>\n                    <ResourceName value={row.meta.author} link={true} fz=\"xs\" />\n                    {row.meta.onBehalfOf && (\n                      <div className={classes.onBehalfOf}>\n                        {'on behalf of '}\n                        <ResourceName value={row.meta.onBehalfOf} link={true} fz=\"xs\" c=\"dimmed\" />\n                      </div>\n                    )}\n                  </td>\n                  <td className={classes.dateTime} rowSpan={row.span}>\n                    <MedplumLink to={getVersionUrl(resource, row.meta.versionId as string)} fz=\"xs\">\n                      {getTimeString(row.meta.lastUpdated as string)}\n                    </MedplumLink>\n                  </td>\n                </>\n              )}\n              <td className={classes.lineNumber}>{index + 1}</td>\n              <td className={classes.line}>\n                <pre className={classes.pre}>{row.value}</pre>\n              </td>\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { stringify } from '@medplum/core';\nimport type { Bundle, Meta } from '@medplum/fhirtypes';\nimport { diff } from './diff';\n\nexport interface BlameRow {\n  id: string;\n  meta: Meta;\n  value: string;\n  span: number;\n}\n\nexport function blame(history: Bundle): BlameRow[] {\n  // Convert to array of array of lines\n  const versions = (history.entry ?? [])\n    .filter((entry) => !!entry.resource)\n    .map((entry) => ({\n      meta: entry.resource?.meta as Meta,\n      lines: stringify(entry.resource, true).match(/[^\\r\\n]+/g) as string[],\n    }))\n    .sort((a, b) => (a.meta.lastUpdated as string).localeCompare(b.meta.lastUpdated as string));\n\n  if (!versions.length) {\n    return [];\n  }\n\n  // Start with array of lines from the first version\n  const table: BlameRow[] = versions[0].lines.map((line) => ({\n    id: versions[0].meta.versionId as string,\n    meta: versions[0].meta,\n    value: line,\n    span: 1,\n  }));\n\n  compareVersions(table, versions);\n  combineSpans(table);\n  return table;\n}\n\n/**\n * For each version, update the blame table with revisions.\n * @param table - The output blame table.\n * @param versions - The array of versions.\n */\nfunction compareVersions(table: BlameRow[], versions: { meta: Meta; lines: string[] }[]): void {\n  for (let i = 1; i < versions.length; i++) {\n    const revisions = diff(versions[i - 1].lines, versions[i].lines);\n\n    for (const revision of revisions) {\n      const position = revision.original.position;\n      const oldLines = revision.original.lines;\n      const newLines = revision.revised.lines;\n\n      if (revision.type === 'delete' || revision.type === 'change') {\n        // Remove the old rows\n        table.splice(position, oldLines.length);\n      }\n\n      if (revision.type === 'insert' || revision.type === 'change') {\n        // Add the new lines\n        for (let k = 0; k < revision.revised.lines.length; k++) {\n          table.splice(position + k, 0, {\n            id: versions[i].meta.versionId as string,\n            meta: versions[i].meta,\n            value: newLines[k],\n            span: 1,\n          });\n        }\n      }\n    }\n  }\n}\n\n/**\n * Combine adjacent rows into spans.\n * @param table - The output blame table.\n */\nfunction combineSpans(table: BlameRow[]): void {\n  let start = 0;\n  while (start < table.length) {\n    let curr = start;\n    while (curr < table.length && table[curr].id === table[start].id) {\n      table[curr].span = -1;\n      curr++;\n    }\n    table[start].span = curr - start;\n    start = curr;\n  }\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\n\n/*\n * Myers Diff algorithm\n * Based on: https://github.com/KengoTODA/java-diff-utils/blob/master/src/main/java/difflib/myers/MyersDiff.java\n * Apache Software License, Version 1.1\n */\nexport function diff(original: string[], revised: string[]): Delta[] {\n  const path = buildPath(original, revised) as PathNode;\n  return buildRevisions(path, original, revised);\n}\n\nexport interface PathNode {\n  readonly i: number;\n  readonly j: number;\n  readonly prev: PathNode | undefined;\n  readonly snake: boolean;\n}\n\nexport interface Delta {\n  readonly original: Chunk;\n  readonly revised: Chunk;\n  readonly type: 'change' | 'delete' | 'insert';\n}\n\nexport interface Chunk {\n  readonly position: number;\n  readonly lines: string[];\n}\n\nfunction buildPath(orig: string[], rev: string[]): PathNode | undefined {\n  const N = orig.length;\n  const M = rev.length;\n  const MAX = N + M + 1;\n  const size = 1 + 2 * MAX;\n  const middle = Math.trunc(size / 2);\n  const diagonal: (PathNode | undefined)[] = new Array(size);\n\n  diagonal[middle + 1] = {\n    i: 0,\n    j: -1,\n    prev: undefined,\n    snake: true,\n  };\n\n  for (let d = 0; d < MAX; d++) {\n    for (let k = -d; k <= d; k += 2) {\n      const kmiddle = middle + k;\n      const kplus = kmiddle + 1;\n      const kminus = kmiddle - 1;\n      const kplusNode = diagonal[kplus] as PathNode;\n      const kminusNode = diagonal[kminus] as PathNode;\n      let prev: PathNode | undefined = undefined;\n      let i = 0;\n\n      if (k === -d || (k !== d && kminusNode.i < kplusNode.i)) {\n        i = kplusNode.i;\n        prev = kplusNode;\n      } else {\n        i = kminusNode.i + 1;\n        prev = kminusNode;\n      }\n\n      diagonal[kminus] = undefined; // no longer used\n\n      let j = i - k;\n      let node = {\n        i,\n        j,\n        prev: previousSnake(prev),\n        snake: false,\n      };\n\n      // orig and rev are zero-based\n      // but the algorithm is one-based\n      // that's why there's no +1 when indexing the sequences\n      while (i < N && j < M && orig[i] === rev[j]) {\n        i++;\n        j++;\n      }\n\n      if (i > node.i) {\n        node = {\n          i,\n          j,\n          prev: node,\n          snake: true,\n        };\n      }\n\n      diagonal[kmiddle] = node;\n\n      if (i >= N && j >= M) {\n        return diagonal[kmiddle];\n      }\n    }\n    diagonal[middle + d - 1] = undefined;\n  }\n\n  // According to Myers, this cannot happen\n  return undefined;\n}\n\nfunction buildRevisions(startNode: PathNode, orig: string[], rev: string[]): Delta[] {\n  const deltas: Delta[] = [];\n  let path: PathNode | undefined = startNode;\n\n  if (path.snake) {\n    path = path.prev;\n  }\n\n  while (path?.prev && path.prev.j >= 0) {\n    const i = path.i;\n    const j = path.j;\n\n    path = path.prev;\n    const ianchor = path.i;\n    const janchor = path.j;\n\n    const original = {\n      position: ianchor,\n      lines: orig.slice(ianchor, i),\n    };\n\n    const revised = {\n      position: janchor,\n      lines: rev.slice(janchor, j),\n    };\n\n    let type: 'insert' | 'delete' | 'change';\n\n    if (original.lines.length === 0 && revised.lines.length > 0) {\n      type = 'insert';\n    } else if (original.lines.length > 0 && revised.lines.length === 0) {\n      type = 'delete';\n    } else {\n      type = 'change';\n    }\n\n    deltas.push({ original, revised, type });\n\n    if (path.snake) {\n      path = path.prev;\n    }\n  }\n\n  return deltas;\n}\n\nfunction previousSnake(node: PathNode): PathNode {\n  if (node && !node.snake && node.prev) {\n    return node.prev;\n  }\n  return node;\n}\n", ".container {\n  overflow-x: auto;\n}\n\n.root {\n  border: 0.1px solid var(--mantine-color-gray-3);\n  border-collapse: collapse;\n  border-radius: var(--mantine-radius-sm);\n  border-spacing: 0;\n  font-size: var(--mantine-font-size-xs);\n  width: 100%;\n\n  & td {\n    padding: 2px 4px 0 4px;\n    vertical-align: top;\n    white-space: nowrap;\n  }\n}\n\n.startRow {\n  border-top: 0.1px solid var(--mantine-color-gray-3);\n  white-space: nowrap;\n}\n\n.normalRow {\n  border-top: 0;\n  white-space: nowrap;\n}\n\n.author {\n  line-height: 10px;\n}\n\n.onBehalfOf {\n  color: var(--mantine-color-dimmed);\n  font-size: var(--mantine-font-size-xs);\n  line-height: 10px;\n}\n\n.dateTime {\n  border-right: 0.1px solid var(--mantine-color-gray-3);\n  line-height: 10px;\n  text-align: right;\n}\n\n.lineNumber {\n  background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-6));\n  border: 0;\n  color: var(--mantine-color-gray-5);\n  font-family: var(--mantine-font-family-monospace);\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n  text-align: right;\n}\n\n.line {\n  font-family: var(--mantine-font-family-monospace);\n  font-size: var(--mantine-font-size-xs);\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n}\n\n.pre {\n  margin: 0;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { Resource } from '@medplum/fhirtypes';\n\nexport function getVersionUrl(resource: Resource, versionId: string): string {\n  return `/${resource.resourceType}/${resource.id}/_history/${versionId}`;\n}\n\nexport function getTimeString(lastUpdated: string): string {\n  const seconds = Math.floor((Date.now() - Date.parse(lastUpdated)) / 1000);\n\n  const years = Math.floor(seconds / 31536000);\n  if (years > 0) {\n    return pluralizeTime(years, 'year');\n  }\n\n  const months = Math.floor(seconds / 2592000);\n  if (months > 0) {\n    return pluralizeTime(months, 'month');\n  }\n\n  const days = Math.floor(seconds / 86400);\n  if (days > 0) {\n    return pluralizeTime(days, 'day');\n  }\n\n  const hours = Math.floor(seconds / 3600);\n  if (hours > 0) {\n    return pluralizeTime(hours, 'hour');\n  }\n\n  const minutes = Math.floor(seconds / 60);\n  if (minutes > 0) {\n    return pluralizeTime(minutes, 'minute');\n  }\n\n  return pluralizeTime(seconds, 'second');\n}\n\nfunction pluralizeTime(count: number, noun: string): string {\n  return `${count} ${count === 1 ? noun : noun + 's'} ago`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, SearchRequest, WithId } from '@medplum/core';\nimport { DEFAULT_SEARCH_COUNT } from '@medplum/core';\nimport type { Resource } from '@medplum/fhirtypes';\nimport type { ResourceBoardLoadResult } from '@medplum/react-hooks';\nimport { useResourceBoard } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\nimport type {\n  ListWithDetailPaneDetailContext,\n  ListWithDetailPaneHeaderProps,\n  ListWithDetailPaneItemContext,\n  ListWithDetailPaneTab,\n} from '../ListWithDetailPane/ListWithDetailPane';\nimport { ListWithDetailPane } from '../ListWithDetailPane/ListWithDetailPane';\n\n// The list/detail shell now lives in ListWithDetailPane; these aliases keep the\n// ResourceBoard public API stable for existing consumers.\nexport type ResourceBoardTab = ListWithDetailPaneTab;\nexport type ResourceBoardItemContext<T extends Resource = Resource> = ListWithDetailPaneItemContext<WithId<T>>;\nexport type ResourceBoardDetailContext = ListWithDetailPaneDetailContext;\n\n/**\n * Props for the ResourceBoard component.\n * @param search - The search definition (resourceType + filters + count/offset), like SearchControl. Default\n * fetching searches with `_total=accurate` and `cache: 'no-cache'`. Deep-equality memoized internally, so parents\n * may pass object literals.\n * @param selectedId - Selected resource id, typically driven by the URL route param.\n * @param loadItems - Custom fetcher replacing the default search (e.g. GraphQL batching, client-side filtering).\n * Re-runs whenever its identity or the search changes \u2014 wrap in useCallback.\n * @param resolveSelected - Selected-resource resolution. Default: find in items by id, else\n * `medplum.readResource(search.resourceType, id)`.\n * @param reloadKey - Manual refresh trigger: change this value (e.g. a counter) to re-run the load without changing\n * the search. Reloads in place \u2014 no skeleton.\n * @param headerText - Plain title shown at the left of the header when no `tabs` are provided.\n * @param tabs - Sidebar header tabs. Selecting a tab navigates to its URI.\n * @param activeTab - Controlled active tab value; consumers derive it from the URL.\n * @param headerActions - Right-aligned slot in the sidebar header row: action buttons, filter popovers.\n * @param renderItem - Renders one row of the list sidebar.\n * @param emptyList - Shown when the list loads empty. Default: dimmed \"No items found\".\n * @param skeleton - Shown while the initial or search-change load is in flight. Default: built-in skeleton rows.\n * @param listWidth - Sidebar width in pixels. Default 350.\n * @param renderDetail - Renders the detail pane for the resolved selection.\n * @param emptyDetail - Shown when nothing is selected or the selection cannot be resolved.\n * @param listFooter - Pinned below the list and above the pagination row, e.g. bulk actions for the current list.\n * @param onChange - Fired by the built-in pagination with the updated offset.\n * @param onSelectFirst - Auto-select escape hatch. Fired with the first item when a load for the current search\n * settles with items while nothing is selected (owned by ListWithDetailPane). The consumer decides how to navigate\n * (e.g. with history replace).\n * @param onLoad - Fired after every successful load.\n * @param onError - List-load and selection-resolution errors. Default: console.error.\n */\nexport interface ResourceBoardProps<T extends Resource = Resource> {\n  readonly search: SearchRequest;\n  readonly selectedId?: string;\n  readonly loadItems?: (search: SearchRequest, medplum: MedplumClient) => Promise<ResourceBoardLoadResult<T>>;\n  readonly resolveSelected?: (id: string, items: WithId<T>[], medplum: MedplumClient) => Promise<WithId<T> | undefined>;\n  readonly reloadKey?: unknown;\n  readonly headerText?: ReactNode;\n  readonly tabs?: ResourceBoardTab[];\n  readonly activeTab?: string;\n  readonly headerActions?: ReactNode;\n  readonly renderItem: (item: WithId<T>, ctx: ResourceBoardItemContext<T>) => ReactNode;\n  readonly emptyList?: ReactNode;\n  readonly skeleton?: ReactNode;\n  readonly listWidth?: number;\n  readonly renderDetail: (selected: WithId<T>, ctx: ResourceBoardDetailContext) => ReactNode;\n  readonly emptyDetail?: ReactNode;\n  readonly listFooter?: ReactNode;\n  readonly onChange?: (search: SearchRequest) => void;\n  readonly onSelectFirst?: (item: WithId<T>) => void;\n  readonly onLoad?: (items: WithId<T>[], total: number | undefined) => void;\n  readonly onError?: (error: unknown) => void;\n}\n\n/**\n * ResourceBoard is a generic master-detail board: it owns data fetching (list search,\n * selection resolution, background refresh via useResourceBoard) and renders the\n * presentational shell with ListWithDetailPane. Escape hatches allow custom loading\n * and selection resolution.\n * @param props - The ResourceBoard React props.\n * @returns The ResourceBoard React node.\n */\nexport function ResourceBoard<T extends Resource = Resource>(props: ResourceBoardProps<T>): JSX.Element {\n  const {\n    search,\n    selectedId,\n    loadItems,\n    resolveSelected,\n    reloadKey,\n    headerText,\n    tabs,\n    activeTab,\n    headerActions,\n    renderItem,\n    emptyList,\n    skeleton,\n    listWidth,\n    renderDetail,\n    emptyDetail,\n    listFooter,\n    onChange,\n    onSelectFirst,\n    onLoad,\n    onError,\n  } = props;\n\n  // Hooks\n  // The hook returns the effective (deep-equality stable) search; alias it locally to\n  // avoid colliding with the `search` prop, which is the raw input.\n  const {\n    items,\n    total,\n    loading,\n    selected,\n    search: memoizedSearch,\n    refresh,\n  } = useResourceBoard<T>({\n    search,\n    selectedId,\n    loadItems,\n    resolveSelected,\n    reloadKey,\n    onLoad,\n    onError,\n  });\n\n  // Derived variables\n  const count = memoizedSearch.count ?? DEFAULT_SEARCH_COUNT;\n  const offset = memoizedSearch.offset ?? 0;\n  const currentPage = Math.floor(offset / count) + 1;\n  const pageCount = total !== undefined ? Math.ceil(total / count) : 0;\n  const selectedKey = selected?.id ?? selectedId;\n\n  // Methods\n  const handlePageChange = (page: number): void => {\n    onChange?.({ ...memoizedSearch, offset: (page - 1) * count });\n  };\n\n  // ListWithDetailPane treats text and tabs as mutually exclusive; tabs take precedence.\n  const headerProps: ListWithDetailPaneHeaderProps = tabs ? { tabs, activeTab } : { headerText };\n\n  return (\n    <ListWithDetailPane<WithId<T>>\n      items={items}\n      loading={loading}\n      selectedKey={selectedKey}\n      renderItem={renderItem}\n      emptyList={emptyList}\n      skeleton={skeleton}\n      listWidth={listWidth}\n      {...headerProps}\n      headerActions={headerActions}\n      selected={selected}\n      renderDetail={renderDetail}\n      emptyDetail={emptyDetail}\n      listFooter={listFooter}\n      refresh={refresh}\n      onSelectFirst={onSelectFirst}\n      page={currentPage}\n      pageCount={pageCount}\n      onPageChange={onChange ? handlePageChange : undefined}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { stringify } from '@medplum/core';\nimport type { Resource } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport type { Delta } from '../utils/diff';\nimport { diff } from '../utils/diff';\nimport classes from './ResourceDiff.module.css';\n\nexport interface ResourceDiffProps {\n  readonly original: Resource;\n  readonly revised: Resource;\n  readonly ignoreMeta?: boolean;\n}\n\nexport function ResourceDiff(props: ResourceDiffProps): JSX.Element {\n  let originalResource = props.original;\n  let revisedResource = props.revised;\n\n  if (props.ignoreMeta) {\n    originalResource = { ...originalResource, meta: undefined };\n    revisedResource = { ...revisedResource, meta: undefined };\n  }\n\n  const original = stringify(originalResource, true).match(/[^\\r\\n]+/g) ?? ['{', '}'];\n  const revised = stringify(revisedResource, true).match(/[^\\r\\n]+/g) ?? ['{', '}'];\n  const deltas = diff(original, revised);\n  return (\n    <pre style={{ color: 'gray' }}>\n      {deltas.map((delta, index) => (\n        <ChangeDiff key={'delta' + index} delta={delta} />\n      ))}\n    </pre>\n  );\n}\n\nfunction ChangeDiff(props: { delta: Delta }): JSX.Element {\n  return (\n    <>\n      ...\n      <br />\n      {props.delta.original.lines.length > 0 && (\n        <div className={classes.removed}>{props.delta.original.lines.join('\\n')}</div>\n      )}\n      {props.delta.revised.lines.length > 0 && (\n        <div className={classes.added}>{props.delta.revised.lines.join('\\n')}</div>\n      )}\n      ...\n      <br />\n    </>\n  );\n}\n", ".removed {\n  color: var(--mantine-color-red-7);\n  text-decoration: line-through;\n}\n\n.added {\n  color: var(--mantine-color-green-7);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Alert, Button, Group, Menu, Stack, TextInput, useMantineTheme } from '@mantine/core';\nimport {\n  AccessPolicyInteraction,\n  applyDefaultValuesToResource,\n  canWriteResourceType,\n  isPopulated,\n  satisfiedAccessPolicy,\n  tryGetProfile,\n} from '@medplum/core';\nimport type { OperationOutcome, Reference, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconAlertCircle, IconChevronDown, IconEdit, IconTrash } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport type { FormEvent, JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { BackboneElementInput } from '../BackboneElementInput/BackboneElementInput';\nimport { FormSection } from '../FormSection/FormSection';\nimport classes from './ResourceForm.module.css';\n\nexport interface ResourceFormProps {\n  readonly defaultValue: Partial<Resource> | Reference;\n  readonly outcome?: OperationOutcome;\n  readonly onSubmit: (resource: Resource) => void;\n  readonly onPatch?: (resource: Resource) => void;\n  readonly onDelete?: (resource: Resource) => void;\n  /** (optional) URL of the resource profile used to display the form. Takes priority over schemaName. */\n  readonly profileUrl?: string;\n  /** (optional) `id` for the form element, so a submit button rendered outside the form can target it via `form={formId}`. */\n  readonly formId?: string;\n  /** (optional) Hide the built-in submit row; pair with `formId` to supply your own submit control. */\n  readonly hideSubmitButton?: boolean;\n}\n\nexport function ResourceForm(props: ResourceFormProps): JSX.Element {\n  const { outcome } = props;\n  const medplum = useMedplum();\n  const defaultValue = useResource(props.defaultValue);\n  const resourceType = defaultValue?.resourceType as ResourceType;\n  const [schemaLoaded, setSchemaLoaded] = useState(false);\n  const [value, setValue] = useState<Resource>();\n  const accessPolicy = medplum.getAccessPolicy();\n  const theme = useMantineTheme();\n\n  useEffect(() => {\n    if (defaultValue) {\n      if (props.profileUrl) {\n        const profileUrl: string = props.profileUrl;\n        medplum\n          .requestProfileSchema(props.profileUrl, { expandProfile: true })\n          .then(() => {\n            const profile = tryGetProfile(profileUrl);\n            if (profile) {\n              setSchemaLoaded(true);\n              const modifiedDefaultValue = applyDefaultValuesToResource(defaultValue, profile);\n              setValue(modifiedDefaultValue);\n            } else {\n              console.error(`Schema not found for ${profileUrl}`);\n            }\n          })\n          .catch((reason) => {\n            console.error('Error in requestProfileSchema', reason);\n          });\n      } else {\n        medplum\n          .requestSchema(resourceType)\n          .then(() => {\n            setValue(defaultValue);\n            setSchemaLoaded(true);\n          })\n          .catch(console.log);\n      }\n    }\n  }, [medplum, defaultValue, resourceType, props.profileUrl]);\n\n  const accessPolicyResource = useMemo(() => {\n    return defaultValue && satisfiedAccessPolicy(defaultValue, AccessPolicyInteraction.READ, accessPolicy);\n  }, [accessPolicy, defaultValue]);\n\n  const canWrite = useMemo<boolean>(() => {\n    if (medplum.isSuperAdmin()) {\n      return true;\n    }\n\n    if (!accessPolicy) {\n      return true;\n    }\n\n    if (!isPopulated(value?.resourceType)) {\n      return true;\n    }\n\n    return canWriteResourceType(accessPolicy, value?.resourceType);\n  }, [medplum, accessPolicy, value?.resourceType]);\n\n  if (!schemaLoaded || !value) {\n    return <div>Loading...</div>;\n  }\n\n  if (!canWrite) {\n    return (\n      <Alert color=\"red\" title=\"Permission denied\" icon={<IconAlertCircle />}>\n        Your access level prevents you from editing and creating {value.resourceType} resources.\n      </Alert>\n    );\n  }\n\n  return (\n    <form\n      id={props.formId}\n      noValidate\n      autoComplete=\"off\"\n      onSubmit={(e: FormEvent) => {\n        e.preventDefault();\n        if (props.onSubmit) {\n          props.onSubmit(value);\n        }\n      }}\n    >\n      <Stack mb=\"xl\">\n        <FormSection title=\"Resource Type\" htmlFor=\"resourceType\" outcome={outcome}>\n          <TextInput name=\"resourceType\" defaultValue={value.resourceType} disabled={true} />\n        </FormSection>\n        <FormSection title=\"ID\" htmlFor=\"id\" outcome={outcome}>\n          <TextInput name=\"id\" defaultValue={value.id} disabled={true} />\n        </FormSection>\n      </Stack>\n      <BackboneElementInput\n        path={value.resourceType}\n        valuePath={value.resourceType}\n        typeName={resourceType}\n        defaultValue={value}\n        outcome={outcome}\n        onChange={setValue}\n        profileUrl={props.profileUrl}\n        accessPolicyResource={accessPolicyResource}\n      />\n      {!props.hideSubmitButton && (\n        <Group justify=\"flex-end\" mt=\"xl\" wrap=\"nowrap\" gap={0}>\n          <Button type=\"submit\" className={cx((props.onPatch || props.onDelete) && classes.splitButton)}>\n            {defaultValue?.id ? 'Update' : 'Create'}\n          </Button>\n          {(props.onPatch || props.onDelete) && (\n            <Menu transitionProps={{ transition: 'pop' }} position=\"bottom-end\" withinPortal>\n              <Menu.Target>\n                <ActionIcon\n                  variant=\"filled\"\n                  color={theme.primaryColor}\n                  size={36}\n                  className={classes.menuControl}\n                  aria-label=\"More actions\"\n                >\n                  <IconChevronDown size={14} stroke={1.5} />\n                </ActionIcon>\n              </Menu.Target>\n              <Menu.Dropdown>\n                {props.onPatch && (\n                  <Menu.Item\n                    leftSection={<IconEdit size={14} stroke={1.5} />}\n                    onClick={() => {\n                      (props.onPatch as (resource: Resource) => void)(value);\n                    }}\n                  >\n                    Patch\n                  </Menu.Item>\n                )}\n                {props.onDelete && (\n                  <Menu.Item\n                    color=\"red\"\n                    leftSection={<IconTrash size={14} stroke={1.5} color=\"red\" />}\n                    onClick={() => {\n                      (props.onDelete as (resource: Resource) => void)(value);\n                    }}\n                  >\n                    Delete\n                  </Menu.Item>\n                )}\n              </Menu.Dropdown>\n            </Menu>\n          )}\n        </Group>\n      )}\n    </form>\n  );\n}\n", ".splitButton {\n  border-top-right-radius: 0;\n  border-bottom-right-radius: 0;\n}\n\n.menuControl {\n  border-top-left-radius: 0;\n  border-bottom-left-radius: 0;\n  border: 0;\n  border-left: rem(1px) solid var(--mantine-color-body);\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Table } from '@mantine/core';\nimport { formatDateTime, normalizeErrorString } from '@medplum/core';\nimport type { Bundle, BundleEntry, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceBadge } from '../ResourceBadge/ResourceBadge';\n\nexport interface ResourceHistoryTableProps {\n  readonly history?: Bundle;\n  readonly resourceType?: string;\n  readonly id?: string;\n}\n\nexport function ResourceHistoryTable(props: ResourceHistoryTableProps): JSX.Element {\n  const medplum = useMedplum();\n  const [value, setValue] = useState(props.history);\n\n  useEffect(() => {\n    if (!props.history && props.resourceType && props.id) {\n      medplum\n        .readHistory(props.resourceType as ResourceType, props.id)\n        .then(setValue)\n        .catch(console.log);\n    }\n  }, [medplum, props.history, props.resourceType, props.id]);\n\n  if (!value) {\n    return <div>Loading...</div>;\n  }\n\n  return (\n    <Table withTableBorder withRowBorders withColumnBorders>\n      <Table.Thead>\n        <Table.Tr>\n          <Table.Th>Author</Table.Th>\n          <Table.Th>On Behalf Of</Table.Th>\n          <Table.Th>Date</Table.Th>\n          <Table.Th>Version</Table.Th>\n        </Table.Tr>\n      </Table.Thead>\n      <Table.Tbody>\n        {value.entry?.map((entry, index) => (\n          <HistoryRow key={'entry-' + index} entry={entry} />\n        ))}\n      </Table.Tbody>\n    </Table>\n  );\n}\n\ninterface HistoryRowProps {\n  readonly entry: BundleEntry;\n}\n\nfunction HistoryRow(props: HistoryRowProps): JSX.Element {\n  const { response, resource } = props.entry;\n  if (resource) {\n    return (\n      <Table.Tr>\n        <Table.Td>\n          <ResourceBadge value={resource.meta?.author} link={true} />\n        </Table.Td>\n        <Table.Td>\n          {resource.meta?.onBehalfOf && <ResourceBadge value={resource.meta.onBehalfOf} link={true} />}\n        </Table.Td>\n        <Table.Td>{formatDateTime(resource.meta?.lastUpdated)}</Table.Td>\n        <Table.Td>\n          <MedplumLink to={getVersionUrl(resource)}>{resource.meta?.versionId}</MedplumLink>\n        </Table.Td>\n      </Table.Tr>\n    );\n  } else {\n    return (\n      <Table.Tr>\n        <Table.Td colSpan={4}>{normalizeErrorString(response?.outcome)}</Table.Td>\n      </Table.Tr>\n    );\n  }\n}\n\nfunction getVersionUrl(resource: Resource): string {\n  return `/${resource.resourceType}/${resource.id}/_history/${resource.meta?.versionId}`;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Loader, Stack, Text } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { arrayify, getReferenceString, isDefined, isReference, isResource, normalizeErrorString } from '@medplum/core';\nimport type { Period, Practitioner, Reference, Resource, Schedule, Slot } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { CalendarDateInput } from '../CalendarDateInput/CalendarDateInput';\nimport { getStartMonth } from '../CalendarDateInput/CalendarDateInput.utils';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport classes from './Scheduler.module.css';\n\nexport type SchedulingOption<T> = [T, Date];\nexport type FetchOptionsFunction<T> = (period: Period) => Promise<SchedulingOption<T>[]>;\n\nexport interface BaseSchedulerProps<T> {\n  /** A Reference or Resource to the actor being scheduled against (typically a Practitioner) */\n  readonly actor?: Reference | Resource;\n  /** A function that fetches SchedulingOption pairs. If this is not a stable function it can cause duplicate queries. */\n  readonly fetchOptions: FetchOptionsFunction<T>;\n  /** React nodes to render inside the scheduler container */\n  readonly children?: React.ReactNode;\n  /** A callback invoked when a specific option is selected */\n  readonly onSelectOption?: (el: T, date: Date) => void;\n}\n\n/**\n * A generic widget to choose an option by date/time. Renders a monthly\n * calendar UI and lets the viewer drill down into options on a given day.\n *\n * @param props - The React props\n * @returns the JSX Element\n */\nexport function BaseScheduler<T>(props: BaseSchedulerProps<T>): JSX.Element | null {\n  const [month, setMonth] = useState(getStartMonth);\n  const [date, setDate] = useState<Date>();\n  const [options, setOptions] = useState<SchedulingOption<T>[]>();\n  const [selectedOption, setSelectedOption] = useState<SchedulingOption<T>>();\n\n  const { fetchOptions, onSelectOption } = props;\n\n  useEffect(() => {\n    let active = true;\n\n    async function doSearch(): Promise<void> {\n      const start = getStart(month);\n      const end = getEnd(month);\n      const options = await fetchOptions({ start, end });\n      if (active) {\n        setOptions(options);\n      }\n    }\n\n    doSearch().catch(console.error);\n\n    return () => {\n      active = false;\n    };\n  }, [fetchOptions, month]);\n\n  const handleSelectOption = useCallback(\n    (option: SchedulingOption<T>) => {\n      setSelectedOption(option);\n      onSelectOption?.(...option);\n    },\n    [onSelectOption]\n  );\n\n  // Restrict to options with unique start times inside the selected day\n  const filteredOptions = useMemo(() => {\n    if (!date || !options) {\n      return [];\n    }\n    const start = date.getTime();\n    const end = start + 24 * 60 * 60 * 1000;\n    const seen = new Set<number>();\n    return options.filter(([_, optionDate]) => {\n      const optionTime = optionDate.getTime();\n      if (seen.has(optionTime)) {\n        return false;\n      }\n      seen.add(optionTime);\n      return start <= optionTime && optionTime < end;\n    });\n  }, [date, options]);\n\n  if (!options) {\n    return (\n      <div className={classes.container} data-testid=\"scheduler\">\n        <Loader />\n      </div>\n    );\n  }\n\n  return (\n    <div className={classes.container} data-testid=\"scheduler\">\n      <div className={classes.info}>\n        {props.actor && <ResourceAvatar value={props.actor} size=\"xl\" />}\n        {props.actor && (\n          <Text size=\"xl\" fw={500}>\n            <ResourceName value={props.actor} />\n          </Text>\n        )}\n        <p>1 hour</p>\n        {date && <p>{date.toLocaleDateString()}</p>}\n        {selectedOption && <p>{formatTime(selectedOption[1])}</p>}\n      </div>\n      <div className={classes.selection}>\n        {!date && (\n          <div>\n            <h3>Select date</h3>\n            <CalendarDateInput\n              availableDates={options.map((opt) => opt[1])}\n              onChangeMonth={setMonth}\n              onClick={setDate}\n            />\n          </div>\n        )}\n        {date && !selectedOption && (\n          <div>\n            <h3>Select time</h3>\n            <Stack>\n              {filteredOptions.map((option) => (\n                <div key={option[1].toISOString()}>\n                  <Button variant=\"outline\" style={{ width: 150 }} onClick={() => handleSelectOption(option)}>\n                    {formatTime(option[1])}\n                  </Button>\n                </div>\n              ))}\n            </Stack>\n          </div>\n        )}\n        {props.children}\n      </div>\n    </div>\n  );\n}\n\n/**\n * Custom function to search for available slots within a given time period\n * @param period - The time period to search within\n * @returns Promise resolving to an array of available slots\n */\nexport type SlotSearchFunction = (period: Period) => Promise<Slot[]>;\nexport interface SchedulerProps {\n  readonly schedule?: Schedule | Reference<Schedule> | Schedule[] | Reference<Schedule>[];\n  fetchSlots?: SlotSearchFunction;\n  onSelectSlot?: (slot: Slot) => void;\n  children?: React.ReactNode;\n}\n\n// Finds the first entry in Schedule.actor of type Reference<Practitioner>\nfunction onlyPractitioner(schedule: Schedule): Reference<Practitioner> | undefined {\n  const refs = schedule.actor.filter((ref) => isReference<Practitioner>(ref, 'Practitioner'));\n  if (refs.length === 1) {\n    return refs[0];\n  }\n  return undefined;\n}\n\nexport function Scheduler(props: SchedulerProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const { fetchSlots, schedule } = props;\n  const [actor, setActor] = useState<Reference<Practitioner> | undefined>();\n\n  const fetchOptions = useCallback(\n    async (period: Period): Promise<SchedulingOption<Slot>[]> => {\n      // use custom slot fetching function when provided\n      if (fetchSlots) {\n        const slots = await fetchSlots(period);\n        return slots.map((slot) => [slot, new Date(slot.start)]);\n      }\n\n      // default search: find slots on the schedules passed in\n      const scheduleRefs = arrayify(schedule ?? [])\n        .map(getReferenceString)\n        .filter(isDefined);\n\n      const slotSearchParams = new URLSearchParams([\n        ['_count', (30 * 24).toString()],\n        ['schedule', scheduleRefs.join(',')],\n        ['start', 'gt' + period.start],\n        ['start', 'lt' + period.end],\n      ]);\n      const slots = await medplum.searchResources('Slot', slotSearchParams);\n      return slots.map((slot) => [slot, new Date(slot.start)]);\n    },\n    [medplum, fetchSlots, schedule]\n  );\n\n  useEffect(() => {\n    const schedules = arrayify(props.schedule);\n    if (schedules?.length !== 1) {\n      return;\n    }\n    const schedule = schedules[0];\n    if (isResource(schedule)) {\n      setActor(onlyPractitioner(schedule));\n    } else {\n      medplum\n        .readReference(schedule)\n        .then((schedule) => {\n          setActor(onlyPractitioner(schedule));\n        })\n        .catch((error: unknown) => {\n          showNotification({\n            color: 'red',\n            title: 'Error',\n            message: normalizeErrorString(error),\n          });\n        });\n    }\n  }, [medplum, props.schedule]);\n\n  return (\n    <BaseScheduler fetchOptions={fetchOptions} onSelectOption={props.onSelectSlot} actor={actor}>\n      {props.children}\n    </BaseScheduler>\n  );\n}\n\nfunction getStart(month: Date): string {\n  return formatSlotInstant(month.getTime());\n}\n\nfunction getEnd(month: Date): string {\n  return formatSlotInstant(month.getTime() + 31 * 24 * 60 * 60 * 1000);\n}\n\nfunction formatSlotInstant(time: number): string {\n  const date = new Date(Math.max(Date.now(), time));\n  date.setHours(0, 0, 0, 0);\n  return date.toISOString();\n}\n\nfunction formatTime(date: Date): string {\n  return date.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });\n}\n", ".container {\n  display: flex;\n  min-height: 400px;\n}\n\n.info {\n  min-width: 300px;\n  padding: 20px;\n  border-right: 1px solid var(--mantine-color-gray-3);\n}\n\n.selection {\n  min-width: 300px;\n  padding: 20px;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { useEffect } from 'react';\nimport { useLocation } from 'react-router';\n\n/**\n * Component that scrolls the window to the top when the route changes.\n * This is useful for maintaining a good user experience when navigating between pages.\n * @returns Empty JSX fragment as this is a utility component with no visual representation\n */\nexport function ScrollToTop(): null {\n  const { pathname } = useLocation();\n\n  useEffect(() => {\n    window.scrollTo(0, 0);\n  }, [pathname]);\n\n  return null;\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Group, NativeSelect } from '@mantine/core';\nimport type { Filter, SearchRequest } from '@medplum/core';\nimport { Operator, deepClone, getSearchParameters } from '@medplum/core';\nimport type { SearchParameter } from '@medplum/fhirtypes';\nimport { IconX } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport { Modal } from '../Modal/Modal';\nimport {\n  addFilter,\n  buildSearchParamFieldLabel,\n  deleteFilter,\n  getOpString,\n  getSearchOperators,\n  isMetaSearchParam,\n  setFilters,\n} from '../SearchControl/SearchUtils';\nimport { SearchFilterValueInput } from '../SearchFilterValueInput/SearchFilterValueInput';\n\nexport interface SearchFilterEditorProps {\n  readonly visible: boolean;\n  readonly search: SearchRequest;\n  readonly onOk: (search: SearchRequest) => void;\n  readonly onCancel: () => void;\n}\n\nexport function SearchFilterEditor(props: SearchFilterEditorProps): JSX.Element | null {\n  const [search, setSearch] = useState(deepClone(props.search));\n\n  const searchRef = useRef(search);\n  useLayoutEffect(() => {\n    searchRef.current = search;\n  });\n\n  useEffect(() => {\n    setSearch(deepClone(props.search));\n  }, [props.search]);\n\n  function onAddFilter(filter: Filter): void {\n    setSearch(addFilter(searchRef.current, filter.code, filter.operator, filter.value));\n  }\n\n  const resourceType = props.search.resourceType;\n  const searchParams = getSearchParameters(resourceType) ?? {};\n  const filters = search.filters || [];\n\n  return (\n    <Modal\n      title=\"Filters\"\n      size={900}\n      opened={props.visible}\n      onClose={props.onCancel}\n      onSubmit={() => props.onOk(searchRef.current)}\n      actions={\n        <Group justify=\"flex-end\">\n          <SubmitButton>OK</SubmitButton>\n        </Group>\n      }\n    >\n      <table>\n        <colgroup>\n          <col style={{ width: 200 }} />\n          <col style={{ width: 200 }} />\n          <col style={{ width: 380 }} />\n          <col style={{ width: 40 }} />\n        </colgroup>\n        <thead>\n          <tr>\n            <th>Field</th>\n            <th>Operation</th>\n            <th>Value</th>\n            <th></th>\n          </tr>\n        </thead>\n        <tbody>\n          {filters.map((filter: Filter, index: number) => (\n            <FilterRowInput\n              id={`filter-${index}-row`}\n              key={`filter-${index}-row`}\n              resourceType={resourceType}\n              searchParams={searchParams}\n              value={filter}\n              onChange={(newFilter: Filter) => {\n                const newFilters = [...filters];\n                newFilters[index] = newFilter;\n                setSearch(setFilters(searchRef.current, newFilters));\n              }}\n              onDelete={() => setSearch(deleteFilter(searchRef.current, index))}\n            />\n          ))}\n        </tbody>\n      </table>\n      <ArrayAddButton propertyDisplayName=\"Filter\" onClick={() => onAddFilter({} as Filter)} />\n    </Modal>\n  );\n}\n\ninterface FilterRowInputProps {\n  readonly id: string;\n  readonly resourceType: string;\n  readonly searchParams: Record<string, SearchParameter>;\n  readonly value: Filter;\n  readonly onChange: (value: Filter) => void;\n  readonly onDelete?: () => void;\n}\n\nfunction FilterRowInput(props: FilterRowInputProps): JSX.Element {\n  const value: Filter = props.value;\n\n  function setFilterCode(newCode: string): void {\n    props.onChange({ code: newCode, operator: Operator.EQUALS, value: '' });\n  }\n\n  function setFilterOperator(newOperator: Operator): void {\n    props.onChange({ code: value.code, operator: newOperator, value: '' });\n  }\n\n  function setFilterValue(newFilterValue: string): void {\n    props.onChange({ code: value.code, operator: value.operator, value: newFilterValue });\n  }\n\n  const searchParam = props.searchParams[value.code];\n  const operators = searchParam && getSearchOperators(searchParam);\n\n  const fieldOptions = [];\n  const metaOptions = [];\n  for (const param of Object.keys(props.searchParams)) {\n    const option = { value: param, label: buildSearchParamFieldLabel(param) };\n    if (isMetaSearchParam(param)) {\n      metaOptions.push(option);\n    } else {\n      fieldOptions.push(option);\n    }\n  }\n\n  return (\n    <tr>\n      <td>\n        <NativeSelect\n          data-testid={`${props.id}-filter-field`}\n          defaultValue={props.value.code}\n          onChange={(e) => setFilterCode(e.currentTarget.value)}\n          data={[\n            '',\n            ...(fieldOptions.length > 0 ? [{ group: 'Fields', items: fieldOptions }] : []),\n            ...(metaOptions.length > 0 ? [{ group: 'Metadata', items: metaOptions }] : []),\n          ]}\n        />\n      </td>\n      <td>\n        {operators && (\n          <NativeSelect\n            key={`${props.id}-filter-value-${props.value.code}`}\n            data-testid={`${props.id}-filter-operation`}\n            defaultValue={value.operator}\n            onChange={(e) => setFilterOperator(e.currentTarget.value as Operator)}\n            data={['', ...operators.map((op) => ({ value: op, label: getOpString(op) }))]}\n          />\n        )}\n      </td>\n      <td>\n        {searchParam && value.operator && (\n          <SearchFilterValueInput\n            key={`${props.id}-filter-value-${props.value.code}-${props.value.operator}`}\n            name={`${props.id}-filter-value`}\n            resourceType={props.resourceType}\n            searchParam={searchParam}\n            defaultValue={value.value}\n            onChange={setFilterValue}\n          />\n        )}\n      </td>\n      <td>\n        {props.onDelete && (\n          <ActionIcon variant=\"outline\" color=\"red\" radius=\"xl\" aria-label=\"Delete filter\" onClick={props.onDelete}>\n            <IconX style={{ width: '70%', height: '70%' }} stroke={1.5} />\n          </ActionIcon>\n        )}\n      </td>\n    </tr>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { MedplumClient, ProfileResource } from '@medplum/core';\nimport { createReference } from '@medplum/core';\nimport type { Attachment, Group, Patient, Reference, ResourceType, ServiceRequest } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport type { ResourceTimelineProps } from '../ResourceTimeline/ResourceTimeline';\nimport { ResourceTimeline } from '../ResourceTimeline/ResourceTimeline';\n\nexport interface ServiceRequestTimelineProps extends Pick<ResourceTimelineProps<ServiceRequest>, 'getMenu'> {\n  readonly serviceRequest: ServiceRequest | Reference<ServiceRequest>;\n}\n\nexport function ServiceRequestTimeline(props: ServiceRequestTimelineProps): JSX.Element {\n  const { serviceRequest, ...rest } = props;\n  return (\n    <ResourceTimeline\n      value={serviceRequest}\n      loadTimelineResources={async (medplum: MedplumClient, resourceType: ResourceType, id: string) => {\n        const ref = `${resourceType}/${id}`;\n        const _count = 100;\n        return Promise.allSettled([\n          medplum.readHistory('ServiceRequest', id),\n          medplum.search('Communication', { 'based-on': ref, _count }),\n          medplum.search('DiagnosticReport', { 'based-on': ref, _count }),\n          medplum.search('Media', { 'based-on': ref, _count }),\n          medplum.search('DocumentReference', { related: ref, _count }),\n          medplum.search('Task', { _filter: `based-on eq ${ref} or focus eq ${ref} or subject eq ${ref}`, _count }),\n        ]);\n      }}\n      createCommunication={(resource: ServiceRequest, sender: ProfileResource, text: string) => ({\n        resourceType: 'Communication',\n        status: 'completed',\n        basedOn: [createReference(resource)],\n        subject: resource.subject as Reference<Group | Patient>,\n        sender: createReference(sender),\n        sent: new Date().toISOString(),\n        payload: [{ contentString: text }],\n      })}\n      createMedia={(resource: ServiceRequest, operator: ProfileResource, content: Attachment) => ({\n        resourceType: 'Media',\n        status: 'completed',\n        basedOn: [createReference(resource)],\n        subject: resource.subject,\n        operator: createReference(operator),\n        issued: new Date().toISOString(),\n        content,\n      })}\n      {...rest}\n    />\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport type { AnchorProps } from '@mantine/core';\nimport { Anchor } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { ensureTrailingSlash, normalizeErrorString } from '@medplum/core';\nimport type { ClientApplication, Encounter, Patient, Reference, SmartAppLaunch } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport type { JSX, ReactNode } from 'react';\n\nexport interface SmartAppLaunchLinkProps extends AnchorProps {\n  readonly client: ClientApplication;\n  readonly patient?: Reference<Patient>;\n  readonly encounter?: Reference<Encounter>;\n  readonly fhirContext?: Reference[];\n  readonly children?: ReactNode;\n}\n\nexport function SmartAppLaunchLink(props: Readonly<SmartAppLaunchLinkProps>): JSX.Element | null {\n  const medplum = useMedplum();\n  const { client, patient, encounter, children, ...rest } = props;\n  const patientResource = useResource(patient);\n  const encounterResource = useResource(encounter);\n\n  function launchApp(): void {\n    const launchUrl = parseLaunchUrl(client.launchUri);\n    if (!launchUrl) {\n      showNotification({ color: 'red', message: 'Invalid launch URI', autoClose: false });\n      return;\n    }\n\n    // Build the patient reference, potentially including an identifier\n    let patientRef: Reference<Patient> | undefined = patient;\n    let encounterRef: Reference<Encounter> | undefined = encounter;\n\n    if (client.launchIdentifierSystems?.length) {\n      // Find patient identifier system configuration\n      const patientIdentifierConfig = client.launchIdentifierSystems.find(\n        (config) => config.resourceType === 'Patient'\n      );\n      if (patientRef && patientResource && patientIdentifierConfig?.system) {\n        const identifier = patientResource.identifier?.find((i) => i.system === patientIdentifierConfig.system);\n        if (identifier) {\n          // Include both the reference and the identifier in the patient reference\n          patientRef = {\n            ...patient,\n            identifier: identifier,\n          };\n        }\n      }\n\n      // Find encounter identifier system configuration\n      const encounterIdentifierConfig = client.launchIdentifierSystems.find(\n        (config) => config.resourceType === 'Encounter'\n      );\n      if (encounterRef && encounterResource && encounterIdentifierConfig?.system) {\n        const identifier = encounterResource.identifier?.find((i) => i.system === encounterIdentifierConfig.system);\n        if (identifier) {\n          encounterRef = {\n            ...encounter,\n            identifier: identifier,\n          };\n        }\n      }\n    }\n\n    medplum\n      .createResource<SmartAppLaunch>({\n        resourceType: 'SmartAppLaunch',\n        patient: patientRef,\n        encounter: encounterRef,\n        fhirContext: props.fhirContext,\n      })\n      .then((result) => {\n        launchUrl.searchParams.set('iss', ensureTrailingSlash(medplum.fhirUrl().toString()));\n        launchUrl.searchParams.set('launch', result.id);\n        window.open(launchUrl.toString(), '_blank');\n      })\n      .catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err), autoClose: false }));\n  }\n\n  return (\n    <Anchor onClick={() => launchApp()} {...rest}>\n      {children}\n    </Anchor>\n  );\n}\n\nfunction parseLaunchUrl(launchUri: string | undefined): URL | undefined {\n  if (!launchUri || !URL.canParse(launchUri)) {\n    return undefined;\n  }\n  const url = new URL(launchUri);\n  return url.protocol === 'https:' || url.protocol === 'http:' ? url : undefined;\n}\n"],
  "mappings": "uvCAAA,qsFAAAA,OAAA,m7LAIA,yBAAc,gCAJd,gBCGA,gBAA8B,yBAerB,gDANF,SAAS,eAAe,MAAgD,CAC7E,IAAM,QAAU,MAAM,MACtB,OAAK,WAIE,qDAAG,uCAAc,QAAS,MAAM,OAAO,EAAE,EAHvC,IAIX,CCjBA,IAAAC,aAA+C,yBAC/CA,aAA0C,yBAG1CC,cAA8C,iBCH9C,IAAAC,aAA4B,yBAC5B,aAA8B,iBCFvB,IAAM,2BAA6B,CAAC,OAAQ,gBAAiB,YAAa,YAAa,mBAAmB,EAIpG,sCAAwC,CAAC,WAAY,MAAM,EDCjE,IAAM,mBAAkB,4BAAmC,CAChE,KAAM,GACN,WAAY,OACZ,SAAU,OAAO,OAAO,IAAI,EAC5B,eAAgB,OAAO,OAAO,IAAI,EAClC,iBAAkB,KACT,CAAE,SAAU,GAAO,OAAQ,EAAM,GAE1C,qBAAsB,OACtB,UAAW,GACX,iBAAkB,EACpB,CAAC,EACD,gBAAgB,YAAc,kBAEvB,IAAM,eAAiB,CAAC,YAAa,mBAAmB,EAClD,mBAAqB,CAAC,KAAM,GAAG,0BAA0B,EAAE,OACrE,MAAS,CAAC,eAAe,SAAS,IAAI,CACzC,EAEO,SAAS,oBACd,cAC2C,CAkC3C,OAjCe,OAAO,QAAQ,aAAa,EAAE,OAAO,CAAC,CAAC,IAAK,OAAO,IAC5D,IAAC,0BAAY,QAAQ,IAAI,GAIzB,QAAQ,MAAQ,GAKhB,QAAQ,KAAK,YAAY,EAAE,SAAS,eAAe,GAAK,QAAQ,OAIhE,eAAe,SAAS,GAA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,yCAAiB,CAAE,MAAO,MAAO,WAAS,qCAAqB,GAAG,EAAG,UAAW,EAAM,CAAC,CAAC,CAC5G,CAEA,SACE,2BAAC,uBAAO,QAAS,IAAM,UAAU,EAAI,GAAG,KACrC,SACH,CAEJ,CAEA,SAAS,eAAe,UAAgD,CACtE,GAAI,CAAC,WAAa,CAAC,IAAI,SAAS,SAAS,EACvC,OAEF,IAAM,IAAM,IAAI,IAAI,SAAS,EAC7B,OAAO,IAAI,WAAa,UAAY,IAAI,WAAa,QAAU,IAAM,MACvE",
  "names": ["Modal", "import_core", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "Component", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "__iconNode", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "main", "announcement", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_core", "import_react_hooks", "import_core", "data", "import_jsx_runtime", "import_jsx_runtime", "logoButton", "user", "userInfo", "userName", "userProject", "import_core", "import_react_hooks", "import_react", "import_core", "iconBox", "subtitle", "interactive", "import_jsx_runtime", "divider", "accountSection", "projectOption", "recentProjectItem", "dropdown", "menuFooter", "projectList", "settingsRow", "settingsControlWrapper", "segmentedControl", "appearanceControl", "layoutControl", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "defaultValue", "toOption", "ItemComponent", "selected", "option", "searchInput", "import_jsx_runtime", "import_jsx_runtime", "MantineAppShell", "import_core", "import_spotlight", "import_react_hooks", "import_react", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_react", "import_react", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_jsx_runtime", "toOption", "ItemComponent", "import_jsx_runtime", "defaultValue", "import_jsx_runtime", "navbar", "logoButton", "menuTitle", "link", "dismissButton", "linkLabel", "userLink", "userLinkLabel", "iconWrapper", "alertDot", "linkCount", "addBookmarkLink", "toggleButton", "divider", "import_core", "import_react_hooks", "import_react", "actionSection", "action", "actionDescription", "actionsGroup", "actionsList", "content", "groupLabel", "emptyState", "footer", "shortcutHints", "import_jsx_runtime", "MantineSpotlight", "buildGraphQLQuery", "getResourcesFromResponse", "r", "dedupeResources", "import_jsx_runtime", "onLinkClick", "MantineAppShell", "import_jsx_runtime", "MantineAppShell", "import_core", "import_core", "import_react_hooks", "import_core", "import_react", "import_jsx_runtime", "validationResult", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "data", "root", "compact", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "props", "import_core", "import_react", "import_jsx_runtime", "props", "import_core", "import_react_hooks", "import_react", "import_core", "root", "import_jsx_runtime", "MantineContainer", "import_core", "paper", "fill", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "MantinePasswordInput", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_notifications", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_notifications", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "slices", "slicedValues", "import_jsx_runtime", "import_jsx_runtime", "EXTENSION_KEYS", "IGNORED_PROPERTIES", "import_core", "import_react", "import_core", "import_react", "import_core", "import_react", "dimmed", "preserveBreaks", "description", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_core", "import_react", "import_react", "import_jsx_runtime", "defaultValue", "import_react", "import_jsx_runtime", "defaultValue", "import_core", "import_react", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "input", "pickerIcon", "pickerButton", "import_core", "import_jsx_runtime", "defaultValue", "isEmpty", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "toOption", "ItemComponent", "r", "import_jsx_runtime", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "indented", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "defaultValue", "slices", "slicedValues", "import_core", "import_hooks", "import_notifications", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "value", "import_jsx_runtime", "defaultValue", "import_jsx_runtime", "nested", "import_jsx_runtime", "defaultValue", "import_core", "import_react", "root", "monthButton", "table", "available", "selected", "inRange", "rangeOpens", "rangeCloses", "selectsRanges", "import_react", "import_jsx_runtime", "import_react", "import_jsx_runtime", "import_core", "import_hooks", "import_notifications", "import_react_hooks", "import_react", "chatPaper", "chatTitle", "chatBody", "chatScrollArea", "chatInputContainer", "chatPendingFile", "chatBubbleOuterWrap", "chatBubbleRightAlignedInnerWrap", "chatBubbleLeftAlignedInnerWrap", "chatBubble", "chatBubbleNameRight", "chatBubbleAttachmentWithText", "chatBubbleAttachmentIcon", "chatBubbleMenu", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "toSafeUrl", "import_core", "import_react_hooks", "import_react", "iconContainer", "icon", "chatModalContainer", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "modal", "content", "header", "title", "close", "body", "scroll", "footer", "import_jsx_runtime", "Modal", "MantineModal", "import_core", "import_jsx_runtime", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_notifications", "import_react_hooks", "import_react", "participantItem", "import_jsx_runtime", "r", "import_core", "import_hooks", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "container", "shell", "detailBorder", "shellHidden", "list", "item", "selected", "footer", "headerText", "pillTabs", "tabLink", "import_core", "import_jsx_runtime", "import_jsx_runtime", "HEADER_HEIGHT", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_jsx_runtime", "r", "Modal", "import_core", "import_core", "import_notifications", "import_react_hooks", "import_react", "panel", "headerLink", "headerContent", "actionsButton", "patientSummaryBadge", "patientSummaryHeader", "patientSummaryCollapseIcon", "collapsed", "import_core", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "code", "clinicalStatus", "import_core", "import_react", "root", "header", "chevron", "title", "addButton", "import_jsx_runtime", "import_core", "gradient", "container", "chevron", "clickable", "item", "itemText", "import_jsx_runtime", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "Modal", "import_core", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "Modal", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_core", "import_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_core", "noteBody", "noteCite", "noteRoot", "import_jsx_runtime", "import_core", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "table", "groupHeaderRow", "criticalRow", "noteBody", "noteCite", "noteRoot", "import_jsx_runtime", "import_jsx_runtime", "basedOn", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "HTTP", "statusValues", "import_jsx_runtime", "getStatusColor", "Modal", "import_core", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "code", "clinicalStatus", "import_jsx_runtime", "getStatusColor", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "Modal", "import_jsx_runtime", "import_jsx_runtime", "_", "rightBorder", "import_jsx_runtime", "getStatusColor", "container", "import_core", "import_react_hooks", "content", "import_jsx_runtime", "import_jsx_runtime", "error", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "removed", "added", "import_jsx_runtime", "root", "removed", "added", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "item", "itemPadding", "import_jsx_runtime", "pinnedComment", "import_jsx_runtime", "resource", "props", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "Modal", "import_core", "import_react", "import_core", "root", "tableScroll", "table", "toolbar", "actionIcon", "toolbarButton", "menuDropdown", "tr", "nameLink", "checkboxCell", "checkboxWrap", "control", "staticColumnTitle", "mutedText", "statusBadge", "statusBadgeLabel", "import_jsx_runtime", "import_jsx_runtime", "Modal", "import_core", "import_hooks", "import_react", "import_core", "import_react", "dropdown", "body", "row", "grow", "footer", "deleteIcon", "empty", "indicator", "addButton", "import_jsx_runtime", "import_react", "import_core", "import_jsx_runtime", "row", "conjunction", "field", "operator", "value", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "Modal", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "r", "Modal", "import_jsx_runtime", "import_core", "root", "entry", "key", "value", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "frame", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "attachment", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "getStatusColor", "import_jsx_runtime", "import_core", "import_react_hooks", "content", "title", "contentContainer", "selected", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "getSubText", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "list", "link", "import_jsx_runtime", "import_core", "import_react_hooks", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_jsx_runtime", "NOTIFICATION_ID", "NOTIFICATION_TITLE", "data", "import_core", "import_react_hooks", "import_jsx_runtime", "import_core", "import_notifications", "import_react", "pharmacyItem", "pharmacyItemSelected", "import_jsx_runtime", "import_core", "import_jsx_runtime", "coreGetDisplayString", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "section", "hovering", "editing", "import_jsx_runtime", "defaultValue", "resource", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "module", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "defaultValue", "data", "option", "section", "hovering", "editing", "questionBody", "topActions", "bottomActions", "movementActions", "movementIcons", "columnAlignment", "linkIdInput", "typeSelect", "preserveBreaks", "import_jsx_runtime", "defaultValue", "isResource", "isResourceType", "item", "generateId", "nextId", "import_core", "import_hooks", "import_notifications", "import_react_hooks", "import_react", "banner", "headerRow", "statusRow", "iconWrapper", "recordingPulse", "statusLabel", "statusLabelPrimary", "statusLabelFinishing", "dictationButton", "dictationButtonLoading", "instructions", "panelGrid", "panelColumn", "transcriptWrapper", "transcriptArea", "transcriptText", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "data", "ratio", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "formState", "import_jsx_runtime", "transcript", "import_core", "import_react_hooks", "import_core", "import_react", "import_jsx_runtime", "value", "import_jsx_runtime", "import_core", "import_react", "section", "import_jsx_runtime", "groupId", "nextId", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_react_hooks", "import_react", "import_core", "container", "root", "startRow", "normalRow", "author", "onBehalfOf", "dateTime", "lineNumber", "line", "pre", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_core", "removed", "added", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "splitButton", "menuControl", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "getVersionUrl", "import_core", "import_notifications", "import_react_hooks", "import_react", "container", "info", "selection", "import_jsx_runtime", "getStart", "getEnd", "options", "schedule", "import_react", "import_core", "import_react", "import_jsx_runtime", "Modal", "import_core", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_jsx_runtime"]
}
