{
  "version": 3,
  "sources": ["../../../../node_modules/rfc6902/pointer.js", "../../../../node_modules/rfc6902/util.js", "../../../../node_modules/rfc6902/diff.js", "../../../../node_modules/rfc6902/patch.js", "../../../../node_modules/rfc6902/index.js", "../../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/src/defaultAttributes.ts", "../../../../node_modules/@tabler/icons-react/src/createReactComponent.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconAdjustmentsHorizontal.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconAlertCircle.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconArrowDown.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconArrowRight.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconArrowUp.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBinaryTree.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBleachOff.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBleach.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBookmark.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBoxMultiple.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBracketsContain.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBriefcase.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBucketOff.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBucket.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCake.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCalendar.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCheck.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCheckbox.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconChevronDown.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconChevronRight.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconChevronUp.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCircleMinus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCirclePlus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCloudUpload.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconColumns.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCopy.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCurrencyDollar.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconDeviceDesktop.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconDots.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconDownload.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEdit.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEmpathize.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEqualNot.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEqual.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEyeOff.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEye.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFileAlert.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFileExport.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFilePlus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFileText.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFilter.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconLanguage.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconLayoutSidebar.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconLogout.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMapPin.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMathGreater.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMathLower.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMessageCircle.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMessage.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMicrophone.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMinus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconMoon.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconPalette.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconPaperclip.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconPencil.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconPlus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconRefresh.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSearch.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSettings.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSortAscending.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSortDescending.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSquare.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconStethoscope.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSunHigh.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconSwitchHorizontal.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconTableExport.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconTable.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconTrash.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconUsers.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconX.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconCircleFilled.ts", "../../src/Loading/Loading.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/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/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/utils/outcomes.ts", "../../src/auth/MfaForm.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/auth/ChooseScopeForm.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.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/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/ChatList.tsx", "../../src/chat/ThreadInbox/ChatListItem.tsx", "../../src/chat/ThreadInbox/ChatListItem.module.css", "../../src/chat/ThreadInbox/NewTopicDialog.tsx", "../../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/QuestionnaireFormItem.tsx", "../../src/QuestionnaireForm/QuestionnaireFormRepeatableGroup.tsx", "../../src/QuestionnaireForm/QuestionnaireFormRepeatableItem.tsx", "../../src/QuestionnaireForm/QuestionnaireFormStepper.tsx", "../../src/chat/ThreadInbox/ParticipantFilter.tsx", "../../src/chat/ThreadInbox/ParticipantFilter.module.css", "../../src/chat/ThreadInbox/ThreadInbox.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/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/PatientSummary/MedicationDialog.tsx", "../../src/PatientSummary/PatientInfoItem.tsx", "../../src/PatientSummary/PatientSummary.utils.ts", "../../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/ThreadInbox.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/utils/date.ts", "../../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/SearchFilterEditor/SearchFilterEditor.tsx", "../../src/SearchFilterValueInput/SearchFilterValueInput.tsx", "../../src/SearchFilterValueDialog/SearchFilterValueDialog.tsx", "../../src/SearchFilterValueDisplay/SearchFilterValueDisplay.tsx", "../../src/SearchPopupMenu/SearchPopupMenu.tsx", "../../src/utils/pagination.ts", "../../src/SearchControl/SearchControl.module.css", "../../src/SearchControl/SearchControlField.ts", "../../src/InfoBar/InfoBar.tsx", "../../src/InfoBar/InfoBar.module.css", "../../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/QuestionnaireBuilder/QuestionnaireBuilder.tsx", "../../src/QuestionnaireBuilder/QuestionnaireBuilder.module.css", "../../src/QuestionnaireForm/AIRealTimeQuestionnaireForm.tsx", "../../src/QuestionnaireForm/AIRealTimeQuestionnaireForm.module.css", "../../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/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", "../../../../node_modules/react-router-dom/dist/index.mjs", "../../src/ServiceRequestTimeline/ServiceRequestTimeline.tsx", "../../src/SmartAppLaunchLink/SmartAppLaunchLink.tsx"],
  "sourcesContent": ["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Pointer = void 0;\nexports.unescapeToken = unescapeToken;\nexports.escapeToken = escapeToken;\n/**\nUnescape token part of a JSON Pointer string\n\n`token` should *not* contain any '/' characters.\n\n> Evaluation of each reference token begins by decoding any escaped\n> character sequence.  This is performed by first transforming any\n> occurrence of the sequence '~1' to '/', and then transforming any\n> occurrence of the sequence '~0' to '~'.  By performing the\n> substitutions in this order, an implementation avoids the error of\n> turning '~01' first into '~1' and then into '/', which would be\n> incorrect (the string '~01' correctly becomes '~1' after\n> transformation).\n\nHere's my take:\n\n~1 is unescaped with higher priority than ~0 because it is a lower-order escape character.\nI say \"lower order\" because '/' needs escaping due to the JSON Pointer serialization technique.\nWhereas, '~' is escaped because escaping '/' uses the '~' character.\n*/\nfunction unescapeToken(token) {\n    return token.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n/** Escape token part of a JSON Pointer string\n\n> '~' needs to be encoded as '~0' and '/'\n> needs to be encoded as '~1' when these characters appear in a\n> reference token.\n\nThis is the exact inverse of `unescapeToken()`, so the reverse replacements must take place in reverse order.\n*/\nfunction escapeToken(token) {\n    return token.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n/**\nJSON Pointer representation\n*/\nvar Pointer = /** @class */ (function () {\n    function Pointer(tokens) {\n        if (tokens === void 0) { tokens = ['']; }\n        this.tokens = tokens;\n    }\n    /**\n    `path` *must* be a properly escaped string.\n    */\n    Pointer.fromJSON = function (path) {\n        var tokens = path.split('/').map(unescapeToken);\n        if (tokens[0] !== '')\n            throw new Error(\"Invalid JSON Pointer: \".concat(path));\n        return new Pointer(tokens);\n    };\n    Pointer.prototype.toString = function () {\n        return this.tokens.map(escapeToken).join('/');\n    };\n    /**\n    Returns an object with 'parent', 'key', and 'value' properties.\n    In the special case that this Pointer's path == \"\",\n    this object will be {parent: null, key: '', value: object}.\n    Otherwise, parent and key will have the property such that parent[key] == value.\n    */\n    Pointer.prototype.evaluate = function (object) {\n        var parent = null;\n        var key = '';\n        var value = object;\n        for (var i = 1, l = this.tokens.length; i < l; i++) {\n            parent = value;\n            key = this.tokens[i];\n            if (key == '__proto__' || key == 'constructor' || key == 'prototype') {\n                continue;\n            }\n            // not sure if this the best way to handle non-existant paths...\n            value = (parent || {})[key];\n        }\n        return { parent: parent, key: key, value: value };\n    };\n    Pointer.prototype.get = function (object) {\n        return this.evaluate(object).value;\n    };\n    Pointer.prototype.set = function (object, value) {\n        var endpoint = this.evaluate(object);\n        if (endpoint.parent) {\n            endpoint.parent[endpoint.key] = value;\n        }\n    };\n    Pointer.prototype.push = function (token) {\n        // mutable\n        this.tokens.push(token);\n    };\n    /**\n    `token` should be a String. It'll be coerced to one anyway.\n  \n    immutable (shallowly)\n    */\n    Pointer.prototype.add = function (token) {\n        var tokens = this.tokens.concat(String(token));\n        return new Pointer(tokens);\n    };\n    /**\n    Create a new Pointer representing the parent of this one.\n  \n    The parent of the empty pointer is the empty pointer.\n  \n    immutable (shallowly)\n    */\n    Pointer.prototype.parent = function () {\n        var tokens = this.tokens.length > 1 ? this.tokens.slice(0, -1) : [''];\n        return new Pointer(tokens);\n    };\n    return Pointer;\n}());\nexports.Pointer = Pointer;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.hasOwnProperty = void 0;\nexports.objectType = objectType;\nexports.clone = clone;\nexports.hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction objectType(object) {\n    if (object === undefined) {\n        return 'undefined';\n    }\n    if (object === null) {\n        return 'null';\n    }\n    if (Array.isArray(object)) {\n        return 'array';\n    }\n    return typeof object;\n}\nfunction isNonPrimitive(value) {\n    // loose-equality checking for null is faster than strict checking for each of null/undefined/true/false\n    // checking null first, then calling typeof, is faster than vice-versa\n    return value != null && typeof value == 'object';\n}\n/**\nRecursively copy a value.\n\n@param source - should be a JavaScript primitive, Array, Date, or (plain old) Object.\n@returns copy of source where every Array and Object have been recursively\n         reconstructed from their constituent elements\n*/\nfunction clone(source) {\n    if (!isNonPrimitive(source)) {\n        // short-circuiting is faster than a single return\n        return source;\n    }\n    // x.constructor == Array is the fastest way to check if x is an Array\n    if (source.constructor == Array) {\n        // construction via imperative for-loop is faster than source.map(arrayVsObject)\n        var length = source.length;\n        // setting the Array length during construction is faster than just `[]` or `new Array()`\n        var arrayTarget = new Array(length);\n        for (var i = 0; i < length; i++) {\n            arrayTarget[i] = clone(source[i]);\n        }\n        return arrayTarget;\n    }\n    // Date\n    if (source.constructor == Date) {\n        var dateTarget = new Date(+source);\n        return dateTarget;\n    }\n    // Object\n    var objectTarget = {};\n    // declaring the variable (with const) inside the loop is faster\n    for (var key in source) {\n        // hasOwnProperty costs a bit of performance, but it's semantically necessary\n        // using a global helper is MUCH faster than calling source.hasOwnProperty(key)\n        if (exports.hasOwnProperty.call(source, key)) {\n            objectTarget[key] = clone(source[key]);\n        }\n    }\n    return objectTarget;\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isDestructive = isDestructive;\nexports.subtract = subtract;\nexports.intersection = intersection;\nexports.diffArrays = diffArrays;\nexports.diffObjects = diffObjects;\nexports.diffAny = diffAny;\nvar util_1 = require(\"./util\");\nfunction isDestructive(_a) {\n    var op = _a.op;\n    return op === 'remove' || op === 'replace' || op === 'copy' || op === 'move';\n}\n/**\nList the keys in `minuend` that are not in `subtrahend`.\n\nA key is only considered if it is both 1) an own-property (o.hasOwnProperty(k))\nof the object, and 2) has a value that is not undefined. This is to match JSON\nsemantics, where JSON object serialization drops keys with undefined values.\n\n@param minuend Object of interest\n@param subtrahend Object of comparison\n@returns Array of keys that are in `minuend` but not in `subtrahend`.\n*/\nfunction subtract(minuend, subtrahend) {\n    var keys = [];\n    for (var key in minuend) {\n        if (util_1.hasOwnProperty.call(minuend, key) &&\n            minuend[key] !== undefined &&\n            !(util_1.hasOwnProperty.call(subtrahend, key) && subtrahend[key] !== undefined)) {\n            keys.push(key);\n        }\n    }\n    return keys;\n}\n/**\nList the keys that shared by all `objects`.\n\nThe semantics of what constitutes a \"key\" is described in {@link subtract}.\n\n@param objects Array of objects to compare\n@returns Array of keys that are in (\"own-properties\" of) every object in `objects`.\n*/\nfunction intersection(objects) {\n    var length = objects.length;\n    // prepare empty counter to keep track of how many objects each key occurred in\n    var counter = {};\n    // go through each object and increment the counter for each key in that object\n    for (var i = 0; i < length; i++) {\n        var object = objects[i];\n        for (var key in object) {\n            if (util_1.hasOwnProperty.call(object, key) && object[key] !== undefined) {\n                counter[key] = (counter[key] || 0) + 1;\n            }\n        }\n    }\n    // now delete all keys from the counter that were not seen in every object\n    for (var key in counter) {\n        if (counter[key] < length) {\n            delete counter[key];\n        }\n    }\n    // finally, extract whatever keys remain in the counter\n    return Object.keys(counter);\n}\n/**\nList the keys that shared by all `a` and `b`.\n\nThe semantics of what constitutes a \"key\" is described in {@link subtract}.\n\n@param a First object to compare\n@param b Second object to compare\n@returns Array of keys that are in (\"own-properties\" of) `a` and `b`.\n*/\nfunction intersection2(a, b) {\n    var keys = [];\n    for (var key in a) {\n        if (util_1.hasOwnProperty.call(a, key) &&\n            a[key] !== undefined &&\n            util_1.hasOwnProperty.call(b, key) &&\n            b[key] !== undefined) {\n            keys.push(key);\n        }\n    }\n    return keys;\n}\nfunction isArrayAdd(array_operation) {\n    return array_operation.op === 'add';\n}\nfunction isArrayRemove(array_operation) {\n    return array_operation.op === 'remove';\n}\nfunction appendArrayOperation(base, operation) {\n    return {\n        // the new operation must be pushed on the end\n        operations: base.operations.concat(operation),\n        cost: base.cost + 1,\n    };\n}\n/**\nCalculate the shortest sequence of operations to get from `input` to `output`,\nusing a dynamic programming implementation of the Levenshtein distance algorithm.\n\nTo get from the input ABC to the output AZ we could just delete all the input\nand say \"insert A, insert Z\" and be done with it. That's what we do if the\ninput is empty. But we can be smarter.\n\n          output\n               A   Z\n               -   -\n          [0]  1   2\ninput A |  1  [0]  1\n      B |  2  [1]  1\n      C |  3   2  [2]\n\n1) start at 0,0 (+0)\n2) keep A (+0)\n3) remove B (+1)\n4) replace C with Z (+1)\n\nIf the `input` (source) is empty, they'll all be in the top row, resulting in an\narray of 'add' operations.\nIf the `output` (target) is empty, everything will be in the left column,\nresulting in an array of 'remove' operations.\n\n@returns A list of add/remove/replace operations.\n*/\nfunction diffArrays(input, output, ptr, diff) {\n    if (diff === void 0) { diff = diffAny; }\n    // set up cost matrix (very simple initialization: just a map)\n    var max_length = Math.max(input.length, output.length);\n    var memo = new Map([[0, { operations: [], cost: 0 }]]);\n    /**\n    Calculate the cheapest sequence of operations required to get from\n    input.slice(0, i) to output.slice(0, j).\n    There may be other valid sequences with the same cost, but none cheaper.\n  \n    @param i The row in the layout above\n    @param j The column in the layout above\n    @returns An object containing a list of operations, along with the total cost\n             of applying them (+1 for each add/remove/replace operation)\n    */\n    function dist(i, j) {\n        // memoized\n        var memo_key = i * max_length + j;\n        var memoized = memo.get(memo_key);\n        if (memoized === undefined) {\n            // TODO: this !diff(...).length usage could/should be lazy\n            if (i > 0 && j > 0 && !diff(input[i - 1], output[j - 1], ptr.add(String(i - 1))).length) {\n                // equal (no operations => no cost)\n                memoized = dist(i - 1, j - 1);\n            }\n            else {\n                var alternatives = [];\n                if (i > 0) {\n                    // NOT topmost row\n                    var remove_base = dist(i - 1, j);\n                    var remove_operation = {\n                        op: 'remove',\n                        index: i - 1,\n                    };\n                    alternatives.push(appendArrayOperation(remove_base, remove_operation));\n                }\n                if (j > 0) {\n                    // NOT leftmost column\n                    var add_base = dist(i, j - 1);\n                    var add_operation = {\n                        op: 'add',\n                        index: i - 1,\n                        value: output[j - 1],\n                    };\n                    alternatives.push(appendArrayOperation(add_base, add_operation));\n                }\n                if (i > 0 && j > 0) {\n                    // TABLE MIDDLE\n                    // supposing we replaced it, compute the rest of the costs:\n                    var replace_base = dist(i - 1, j - 1);\n                    // okay, the general plan is to replace it, but we can be smarter,\n                    // recursing into the structure and replacing only part of it if\n                    // possible, but to do so we'll need the original value\n                    var replace_operation = {\n                        op: 'replace',\n                        index: i - 1,\n                        original: input[i - 1],\n                        value: output[j - 1],\n                    };\n                    alternatives.push(appendArrayOperation(replace_base, replace_operation));\n                }\n                // the only other case, i === 0 && j === 0, has already been memoized\n                // the meat of the algorithm:\n                // sort by cost to find the lowest one (might be several ties for lowest)\n                // [4, 6, 7, 1, 2].sort((a, b) => a - b) -> [ 1, 2, 4, 6, 7 ]\n                var best = alternatives.sort(function (a, b) { return a.cost - b.cost; })[0];\n                memoized = best;\n            }\n            memo.set(memo_key, memoized);\n        }\n        return memoized;\n    }\n    // handle weird objects masquerading as Arrays that don't have proper length\n    // properties by using 0 for everything but positive numbers\n    var input_length = (isNaN(input.length) || input.length <= 0) ? 0 : input.length;\n    var output_length = (isNaN(output.length) || output.length <= 0) ? 0 : output.length;\n    var array_operations = dist(input_length, output_length).operations;\n    var padded_operations = array_operations.reduce(function (_a, array_operation) {\n        var operations = _a[0], padding = _a[1];\n        if (isArrayAdd(array_operation)) {\n            var padded_index = array_operation.index + 1 + padding;\n            var index_token = padded_index < (input_length + padding) ? String(padded_index) : '-';\n            var operation = {\n                op: array_operation.op,\n                path: ptr.add(index_token).toString(),\n                value: array_operation.value,\n            };\n            // padding++ // maybe only if array_operation.index > -1 ?\n            return [operations.concat(operation), padding + 1];\n        }\n        else if (isArrayRemove(array_operation)) {\n            var operation = {\n                op: array_operation.op,\n                path: ptr.add(String(array_operation.index + padding)).toString(),\n            };\n            // padding--\n            return [operations.concat(operation), padding - 1];\n        }\n        else { // replace\n            var replace_ptr = ptr.add(String(array_operation.index + padding));\n            var replace_operations = diff(array_operation.original, array_operation.value, replace_ptr);\n            return [operations.concat.apply(operations, replace_operations), padding];\n        }\n    }, [[], 0])[0];\n    return padded_operations;\n}\nfunction diffObjects(input, output, ptr, diff) {\n    if (diff === void 0) { diff = diffAny; }\n    // if a key is in input but not output -> remove it\n    var operations = [];\n    subtract(input, output).forEach(function (key) {\n        operations.push({ op: 'remove', path: ptr.add(key).toString() });\n    });\n    // if a key is in output but not input -> add it\n    subtract(output, input).forEach(function (key) {\n        operations.push({ op: 'add', path: ptr.add(key).toString(), value: output[key] });\n    });\n    // if a key is in both, diff it recursively\n    intersection2(input, output).forEach(function (key) {\n        operations.push.apply(operations, diff(input[key], output[key], ptr.add(key)));\n    });\n    return operations;\n}\n/**\n`diffAny()` returns an empty array if `input` and `output` are materially equal\n(i.e., would produce equivalent JSON); otherwise it produces an array of patches\nthat would transform `input` into `output`.\n\n> Here, \"equal\" means that the value at the target location and the\n> value conveyed by \"value\" are of the same JSON type, and that they\n> are considered equal by the following rules for that type:\n> o  strings: are considered equal if they contain the same number of\n>    Unicode characters and their code points are byte-by-byte equal.\n> o  numbers: are considered equal if their values are numerically\n>    equal.\n> o  arrays: are considered equal if they contain the same number of\n>    values, and if each value can be considered equal to the value at\n>    the corresponding position in the other array, using this list of\n>    type-specific rules.\n> o  objects: are considered equal if they contain the same number of\n>    members, and if each member can be considered equal to a member in\n>    the other object, by comparing their keys (as strings) and their\n>    values (using this list of type-specific rules).\n> o  literals (false, true, and null): are considered equal if they are\n>    the same.\n*/\nfunction diffAny(input, output, ptr, diff) {\n    if (diff === void 0) { diff = diffAny; }\n    // strict equality handles literals, numbers, and strings (a sufficient but not necessary cause)\n    if (input === output) {\n        return [];\n    }\n    var input_type = (0, util_1.objectType)(input);\n    var output_type = (0, util_1.objectType)(output);\n    if (input_type == 'array' && output_type == 'array') {\n        return diffArrays(input, output, ptr, diff);\n    }\n    if (input_type == 'object' && output_type == 'object') {\n        return diffObjects(input, output, ptr, diff);\n    }\n    // at this point we know that input and output are materially different;\n    // could be array -> object, object -> array, boolean -> undefined,\n    // number -> string, or some other combination, but nothing that can be split\n    // up into multiple patches: so `output` must replace `input` wholesale.\n    return [{ op: 'replace', path: ptr.toString(), value: output }];\n}\n", "\"use strict\";\nvar __extends = (this && this.__extends) || (function () {\n    var extendStatics = function (d, b) {\n        extendStatics = Object.setPrototypeOf ||\n            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n        return extendStatics(d, b);\n    };\n    return function (d, b) {\n        if (typeof b !== \"function\" && b !== null)\n            throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n        extendStatics(d, b);\n        function __() { this.constructor = d; }\n        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n    };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.InvalidOperationError = exports.TestError = exports.MissingError = void 0;\nexports.add = add;\nexports.remove = remove;\nexports.replace = replace;\nexports.move = move;\nexports.copy = copy;\nexports.test = test;\nexports.apply = apply;\nvar pointer_1 = require(\"./pointer\");\nvar util_1 = require(\"./util\");\nvar diff_1 = require(\"./diff\");\nvar MissingError = /** @class */ (function (_super) {\n    __extends(MissingError, _super);\n    function MissingError(path) {\n        var _this = _super.call(this, \"Value required at path: \".concat(path)) || this;\n        _this.path = path;\n        _this.name = 'MissingError';\n        return _this;\n    }\n    return MissingError;\n}(Error));\nexports.MissingError = MissingError;\nvar TestError = /** @class */ (function (_super) {\n    __extends(TestError, _super);\n    function TestError(actual, expected) {\n        var _this = _super.call(this, \"Test failed: \".concat(actual, \" != \").concat(expected)) || this;\n        _this.actual = actual;\n        _this.expected = expected;\n        _this.name = 'TestError';\n        return _this;\n    }\n    return TestError;\n}(Error));\nexports.TestError = TestError;\nfunction _add(object, key, value) {\n    if (Array.isArray(object)) {\n        // `key` must be an index\n        if (key == '-') {\n            object.push(value);\n        }\n        else {\n            var index = parseInt(key, 10);\n            object.splice(index, 0, value);\n        }\n    }\n    else {\n        object[key] = value;\n    }\n}\nfunction _remove(object, key) {\n    if (Array.isArray(object)) {\n        // '-' syntax doesn't make sense when removing\n        var index = parseInt(key, 10);\n        object.splice(index, 1);\n    }\n    else {\n        // not sure what the proper behavior is when path = ''\n        delete object[key];\n    }\n}\n/**\n>  o  If the target location specifies an array index, a new value is\n>     inserted into the array at the specified index.\n>  o  If the target location specifies an object member that does not\n>     already exist, a new member is added to the object.\n>  o  If the target location specifies an object member that does exist,\n>     that member's value is replaced.\n*/\nfunction add(object, operation, options) {\n    var pointer = pointer_1.Pointer.fromJSON(operation.path);\n    // Handle implicit array creation for terminal \"/-\" paths\n    if ((options === null || options === void 0 ? void 0 : options.implicitArrayCreation) && pointer.tokens[pointer.tokens.length - 1] === '-') {\n        // Try to evaluate the parent (the array itself)\n        var parentEndpoint = pointer.parent().evaluate(object);\n        // If the array property doesn't exist but its parent does,\n        // and this parent is a plain object (not an array),\n        // create an (empty) array that we will add to below.\n        if (parentEndpoint.value === undefined && (0, util_1.objectType)(parentEndpoint.parent) === 'object') {\n            parentEndpoint.parent[parentEndpoint.key] = [];\n        }\n    }\n    var endpoint = pointer.evaluate(object);\n    // it's not exactly a \"MissingError\" in the same way that `remove` is -- more like a MissingParent, or something\n    if (endpoint.parent === undefined) {\n        return new MissingError(operation.path);\n    }\n    // When using implicitArrayCreation, validate that \"/-\" targets are actually arrays\n    if ((options === null || options === void 0 ? void 0 : options.implicitArrayCreation) && endpoint.key === '-' && !Array.isArray(endpoint.parent)) {\n        return new MissingError(operation.path);\n    }\n    _add(endpoint.parent, endpoint.key, (0, util_1.clone)(operation.value));\n    return null;\n}\n/**\n> The \"remove\" operation removes the value at the target location.\n> The target location MUST exist for the operation to be successful.\n*/\nfunction remove(object, operation, options) {\n    // endpoint has parent, key, and value properties\n    var endpoint = pointer_1.Pointer.fromJSON(operation.path).evaluate(object);\n    if (endpoint.value === undefined) {\n        return new MissingError(operation.path);\n    }\n    // not sure what the proper behavior is when path = ''\n    _remove(endpoint.parent, endpoint.key);\n    return null;\n}\n/**\n> The \"replace\" operation replaces the value at the target location\n> with a new value.  The operation object MUST contain a \"value\" member\n> whose content specifies the replacement value.\n> The target location MUST exist for the operation to be successful.\n\n> This operation is functionally identical to a \"remove\" operation for\n> a value, followed immediately by an \"add\" operation at the same\n> location with the replacement value.\n\nEven more simply, it's like the add operation with an existence check.\n*/\nfunction replace(object, operation, options) {\n    var endpoint = pointer_1.Pointer.fromJSON(operation.path).evaluate(object);\n    if (endpoint.parent === null) {\n        return new MissingError(operation.path);\n    }\n    // this existence check treats arrays as a special case\n    if (Array.isArray(endpoint.parent)) {\n        if (parseInt(endpoint.key, 10) >= endpoint.parent.length) {\n            return new MissingError(operation.path);\n        }\n    }\n    else if (endpoint.value === undefined) {\n        return new MissingError(operation.path);\n    }\n    endpoint.parent[endpoint.key] = (0, util_1.clone)(operation.value);\n    return null;\n}\n/**\n> The \"move\" operation removes the value at a specified location and\n> adds it to the target location.\n> The operation object MUST contain a \"from\" member, which is a string\n> containing a JSON Pointer value that references the location in the\n> target document to move the value from.\n> This operation is functionally identical to a \"remove\" operation on\n> the \"from\" location, followed immediately by an \"add\" operation at\n> the target location with the value that was just removed.\n\n> The \"from\" location MUST NOT be a proper prefix of the \"path\"\n> location; i.e., a location cannot be moved into one of its children.\n\nTODO: throw if the check described in the previous paragraph fails.\n*/\nfunction move(object, operation, options) {\n    var from_endpoint = pointer_1.Pointer.fromJSON(operation.from).evaluate(object);\n    if (from_endpoint.value === undefined) {\n        return new MissingError(operation.from);\n    }\n    var endpoint = pointer_1.Pointer.fromJSON(operation.path).evaluate(object);\n    if (endpoint.parent === undefined) {\n        return new MissingError(operation.path);\n    }\n    _remove(from_endpoint.parent, from_endpoint.key);\n    _add(endpoint.parent, endpoint.key, from_endpoint.value);\n    return null;\n}\n/**\n> The \"copy\" operation copies the value at a specified location to the\n> target location.\n> The operation object MUST contain a \"from\" member, which is a string\n> containing a JSON Pointer value that references the location in the\n> target document to copy the value from.\n> The \"from\" location MUST exist for the operation to be successful.\n\n> This operation is functionally identical to an \"add\" operation at the\n> target location using the value specified in the \"from\" member.\n\nAlternatively, it's like 'move' without the 'remove'.\n*/\nfunction copy(object, operation, options) {\n    var from_endpoint = pointer_1.Pointer.fromJSON(operation.from).evaluate(object);\n    if (from_endpoint.value === undefined) {\n        return new MissingError(operation.from);\n    }\n    var endpoint = pointer_1.Pointer.fromJSON(operation.path).evaluate(object);\n    if (endpoint.parent === undefined) {\n        return new MissingError(operation.path);\n    }\n    _add(endpoint.parent, endpoint.key, (0, util_1.clone)(from_endpoint.value));\n    return null;\n}\n/**\n> The \"test\" operation tests that a value at the target location is\n> equal to a specified value.\n> The operation object MUST contain a \"value\" member that conveys the\n> value to be compared to the target location's value.\n> The target location MUST be equal to the \"value\" value for the\n> operation to be considered successful.\n*/\nfunction test(object, operation, options) {\n    var endpoint = pointer_1.Pointer.fromJSON(operation.path).evaluate(object);\n    // TODO: this diffAny(...).length usage could/should be lazy\n    if ((0, diff_1.diffAny)(endpoint.value, operation.value, new pointer_1.Pointer()).length) {\n        return new TestError(endpoint.value, operation.value);\n    }\n    return null;\n}\nvar InvalidOperationError = /** @class */ (function (_super) {\n    __extends(InvalidOperationError, _super);\n    function InvalidOperationError(operation) {\n        var _this = _super.call(this, \"Invalid operation: \".concat(operation.op)) || this;\n        _this.operation = operation;\n        _this.name = 'InvalidOperationError';\n        return _this;\n    }\n    return InvalidOperationError;\n}(Error));\nexports.InvalidOperationError = InvalidOperationError;\n/**\nSwitch on `operation.op`, applying the corresponding patch function for each\ncase to `object`.\n*/\nfunction apply(object, operation, options) {\n    // not sure why TypeScript can't infer typesafety of:\n    //   {add, remove, replace, move, copy, test}[operation.op](object, operation)\n    // (seems like a bug)\n    switch (operation.op) {\n        case 'add': return add(object, operation, options);\n        case 'remove': return remove(object, operation, options);\n        case 'replace': return replace(object, operation, options);\n        case 'move': return move(object, operation, options);\n        case 'copy': return copy(object, operation, options);\n        case 'test': return test(object, operation, options);\n    }\n    return new InvalidOperationError(operation);\n}\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Pointer = void 0;\nexports.applyPatch = applyPatch;\nexports.createPatch = createPatch;\nexports.createTests = createTests;\nvar pointer_1 = require(\"./pointer\");\nObject.defineProperty(exports, \"Pointer\", { enumerable: true, get: function () { return pointer_1.Pointer; } });\nvar patch_1 = require(\"./patch\");\nvar diff_1 = require(\"./diff\");\n/**\nApply a 'application/json-patch+json'-type patch to an object.\n\n`patch` *must* be an array of operations.\n\n> Operation objects MUST have exactly one \"op\" member, whose value\n> indicates the operation to perform.  Its value MUST be one of \"add\",\n> \"remove\", \"replace\", \"move\", \"copy\", or \"test\"; other values are\n> errors.\n\nThis method mutates the target object in-place.\n\n@param object The object to apply the patch to\n@param patch Array of operations to apply\n@param options Optional customization of patch application behavior\n@returns list of results, one for each operation: `null` indicated success,\n         otherwise, the result will be an instance of one of the Error classes:\n         MissingError, InvalidOperationError, or TestError.\n*/\nfunction applyPatch(object, patch, options) {\n    return patch.map(function (operation) { return (0, patch_1.apply)(object, operation, options); });\n}\nfunction wrapVoidableDiff(diff) {\n    function wrappedDiff(input, output, ptr) {\n        var custom_patch = diff(input, output, ptr);\n        // ensure an array is always returned\n        return Array.isArray(custom_patch) ? custom_patch : (0, diff_1.diffAny)(input, output, ptr, wrappedDiff);\n    }\n    return wrappedDiff;\n}\n/**\nProduce a 'application/json-patch+json'-type patch to get from one object to\nanother.\n\nThis does not alter `input` or `output` unless they have a property getter with\nside-effects (which is not a good idea anyway).\n\n`diff` is called on each pair of comparable non-primitive nodes in the\n`input`/`output` object trees, producing nested patches. Return `undefined`\nto fall back to default behaviour.\n\nReturns list of operations to perform on `input` to produce `output`.\n*/\nfunction createPatch(input, output, diff) {\n    var ptr = new pointer_1.Pointer();\n    // a new Pointer gets a default path of [''] if not specified\n    return (diff ? wrapVoidableDiff(diff) : diff_1.diffAny)(input, output, ptr);\n}\n/**\nCreate a test operation based on `input`'s current evaluation of the JSON\nPointer `path`; if such a pointer cannot be resolved, returns undefined.\n*/\nfunction createTest(input, path) {\n    var endpoint = pointer_1.Pointer.fromJSON(path).evaluate(input);\n    if (endpoint !== undefined) {\n        return { op: 'test', path: path, value: endpoint.value };\n    }\n}\n/**\nProduce an 'application/json-patch+json'-type list of tests, to verify that\nexisting values in an object are identical to the those captured at some\ncheckpoint (whenever this function is called).\n\nThis does not alter `input` or `output` unless they have a property getter with\nside-effects (which is not a good idea anyway).\n\nReturns list of test operations.\n*/\nfunction createTests(input, patch) {\n    var tests = new Array();\n    patch.filter(diff_1.isDestructive).forEach(function (operation) {\n        var pathTest = createTest(input, operation.path);\n        if (pathTest)\n            tests.push(pathTest);\n        if ('from' in operation) {\n            var fromTest = createTest(input, operation.from);\n            if (fromTest)\n                tests.push(fromTest);\n        }\n    });\n    return tests;\n}\n", "// 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/MfaForm';\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/ChatList';\nexport * from './chat/ThreadInbox/ChatListItem';\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 './LinkTabs/LinkTabs';\nexport * from './Loading/Loading';\nexport * from './Logo/Logo';\nexport * from './MeasureReportDisplay/MeasureReportDisplay';\nexport * from './MedplumLink/MedplumLink';\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 './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  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 './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 './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 './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 classes from './AppShell.module.css';\nimport { Header } from './Header';\nimport type { NavbarMenu } from './Navbar';\nimport { Navbar } from './Navbar';\n\nconst OPEN_WIDTH = 250;\nconst CLOSED_WIDTH = 59;\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 layoutVersion?: 'v1' | 'v2';\n  readonly showLayoutVersionToggle?: boolean;\n  readonly spotlightPatientsOnly?: boolean;\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\n  function setNavbarOpenWrapper(open: boolean): void {\n    localStorage['navbarOpen'] = open.toString();\n    setNavbarOpen(open);\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: 0 };\n    navbarProp = {\n      width: navbarOpen ? OPEN_WIDTH : CLOSED_WIDTH,\n      breakpoint: 0,\n      collapsed: {\n        desktop: !profile,\n        mobile: !profile,\n      },\n    };\n    headerComponent = 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        userMenuEnabled={true}\n        version={props.version}\n        showLayoutVersionToggle={props.showLayoutVersionToggle}\n      />\n    ) : undefined;\n  } else {\n    // Default to layout version v1\n    headerProp = { height: 60 };\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      />\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        />\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", "export default {\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", "import { forwardRef, createElement } from 'react';\nimport defaultAttributes from './defaultAttributes';\nimport type { IconNode, IconProps, Icon } from './types';\n\nconst createReactComponent = (\n  type: 'outline' | 'filled',\n  iconName: string,\n  iconNamePascal: string,\n  iconNode: IconNode,\n) => {\n  const Component = forwardRef<SVGSVGElement, IconProps>(\n    (\n      { color = 'currentColor', size = 24, stroke = 2, title, className, children, ...rest }: IconProps,\n      ref,\n    ) =>\n      createElement(\n        'svg',\n        {\n          ref,\n          ...defaultAttributes[type],\n          width: size,\n          height: size,\n          className: [`tabler-icon`, `tabler-icon-${iconName}`, className].join(' '),\n          ...(type === 'filled'\n            ? {\n                fill: color,\n              }\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\n  Component.displayName = `${iconNamePascal}`;\n\n  return Component;\n};\n\nexport default createReactComponent;\n", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M12 6a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M4 6l8 0\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M16 6l4 0\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M6 12a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\",\"key\":\"svg-3\"}],[\"path\",{\"d\":\"M4 12l2 0\",\"key\":\"svg-4\"}],[\"path\",{\"d\":\"M10 12l10 0\",\"key\":\"svg-5\"}],[\"path\",{\"d\":\"M15 18a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\",\"key\":\"svg-6\"}],[\"path\",{\"d\":\"M4 18l11 0\",\"key\":\"svg-7\"}],[\"path\",{\"d\":\"M19 18l1 0\",\"key\":\"svg-8\"}]]\n\n/**\n * IconAdjustmentsHorizontal\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYWRqdXN0bWVudHMtaG9yaXpvbnRhbCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTIgNmEyIDIgMCAxIDAgNCAwYTIgMiAwIDEgMCAtNCAwIiAvPgogIDxwYXRoIGQ9Ik00IDZsOCAwIiAvPgogIDxwYXRoIGQ9Ik0xNiA2bDQgMCIgLz4KICA8cGF0aCBkPSJNNiAxMmEyIDIgMCAxIDAgNCAwYTIgMiAwIDEgMCAtNCAwIiAvPgogIDxwYXRoIGQ9Ik00IDEybDIgMCIgLz4KICA8cGF0aCBkPSJNMTAgMTJsMTAgMCIgLz4KICA8cGF0aCBkPSJNMTUgMThhMiAyIDAgMSAwIDQgMGEyIDIgMCAxIDAgLTQgMCIgLz4KICA8cGF0aCBkPSJNNCAxOGwxMSAwIiAvPgogIDxwYXRoIGQ9Ik0xOSAxOGwxIDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/adjustments-horizontal\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconAdjustmentsHorizontal = createReactComponent('outline', 'adjustments-horizontal', 'AdjustmentsHorizontal', __iconNode);\n\nexport default IconAdjustmentsHorizontal;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconAlertCircle\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYWxlcnQtY2lyY2xlIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0zIDEyYTkgOSAwIDEgMCAxOCAwYTkgOSAwIDAgMCAtMTggMCIgLz4KICA8cGF0aCBkPSJNMTIgOHY0IiAvPgogIDxwYXRoIGQ9Ik0xMiAxNmguMDEiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/alert-circle\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconAlertCircle = createReactComponent('outline', 'alert-circle', 'AlertCircle', __iconNode);\n\nexport default IconAlertCircle;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconArrowDown\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYXJyb3ctZG93biIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTIgNWwwIDE0IiAvPgogIDxwYXRoIGQ9Ik0xOCAxM2wtNiA2IiAvPgogIDxwYXRoIGQ9Ik02IDEzbDYgNiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/arrow-down\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconArrowDown = createReactComponent('outline', 'arrow-down', 'ArrowDown', __iconNode);\n\nexport default IconArrowDown;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconArrowRight\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYXJyb3ctcmlnaHQiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTUgMTJsMTQgMCIgLz4KICA8cGF0aCBkPSJNMTMgMThsNiAtNiIgLz4KICA8cGF0aCBkPSJNMTMgNmw2IDYiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/arrow-right\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconArrowRight = createReactComponent('outline', 'arrow-right', 'ArrowRight', __iconNode);\n\nexport default IconArrowRight;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconArrowUp\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYXJyb3ctdXAiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTEyIDVsMCAxNCIgLz4KICA8cGF0aCBkPSJNMTggMTFsLTYgLTYiIC8+CiAgPHBhdGggZD0iTTYgMTFsNiAtNiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/arrow-up\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconArrowUp = createReactComponent('outline', 'arrow-up', 'ArrowUp', __iconNode);\n\nexport default IconArrowUp;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBinaryTree\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYmluYXJ5LXRyZWUiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTYgMjBhMiAyIDAgMSAwIC00IDBhMiAyIDAgMCAwIDQgMCIgLz4KICA8cGF0aCBkPSJNMTYgNGEyIDIgMCAxIDAgLTQgMGEyIDIgMCAwIDAgNCAwIiAvPgogIDxwYXRoIGQ9Ik0xNiAyMGEyIDIgMCAxIDAgLTQgMGEyIDIgMCAwIDAgNCAwIiAvPgogIDxwYXRoIGQ9Ik0xMSAxMmEyIDIgMCAxIDAgLTQgMGEyIDIgMCAwIDAgNCAwIiAvPgogIDxwYXRoIGQ9Ik0yMSAxMmEyIDIgMCAxIDAgLTQgMGEyIDIgMCAwIDAgNCAwIiAvPgogIDxwYXRoIGQ9Ik01LjA1OCAxOC4zMDZsMi44OCAtNC42MDYiIC8+CiAgPHBhdGggZD0iTTEwLjA2MSAxMC4zMDNsMi44NzcgLTQuNjA0IiAvPgogIDxwYXRoIGQ9Ik0xMC4wNjUgMTMuNzA1bDIuODc2IDQuNiIgLz4KICA8cGF0aCBkPSJNMTUuMDYzIDUuN2wyLjg4MSA0LjYxIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/binary-tree\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBinaryTree = createReactComponent('outline', 'binary-tree', 'BinaryTree', __iconNode);\n\nexport default IconBinaryTree;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBleachOff\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYmxlYWNoLW9mZiIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNSAxOWgxNG0xLjk4NiAtMS45NzdhMiAyIDAgMCAwIC0uMTQ2IC0uNzczbC03LjEgLTEyLjI1YTIgMiAwIDAgMCAtMy41IDBsLS44MTUgMS40MDVtLTEuNDg4IDIuNTY4bC00Ljc5NyA4LjI3N2EyIDIgMCAwIDAgMS43NSAyLjc1IiAvPgogIDxwYXRoIGQ9Ik0zIDNsMTggMTgiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/bleach-off\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBleachOff = createReactComponent('outline', 'bleach-off', 'BleachOff', __iconNode);\n\nexport default IconBleachOff;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBleach\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYmxlYWNoIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik01IDE5aDE0YTIgMiAwIDAgMCAxLjg0IC0yLjc1bC03LjEgLTEyLjI1YTIgMiAwIDAgMCAtMy41IDBsLTcuMSAxMi4yNWEyIDIgMCAwIDAgMS43NSAyLjc1IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/bleach\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBleach = createReactComponent('outline', 'bleach', 'Bleach', __iconNode);\n\nexport default IconBleach;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBookmark\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYm9va21hcmsiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTE4IDd2MTRsLTYgLTRsLTYgNHYtMTRhNCA0IDAgMCAxIDQgLTRoNGE0IDQgMCAwIDEgNCA0IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/bookmark\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBookmark = createReactComponent('outline', 'bookmark', 'Bookmark', __iconNode);\n\nexport default IconBookmark;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M7 5a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2l0 -10\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M17 17v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-10a2 2 0 0 1 2 -2h2\",\"key\":\"svg-1\"}]]\n\n/**\n * IconBoxMultiple\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYm94LW11bHRpcGxlIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik03IDVhMiAyIDAgMCAxIDIgLTJoMTBhMiAyIDAgMCAxIDIgMnYxMGEyIDIgMCAwIDEgLTIgMmgtMTBhMiAyIDAgMCAxIC0yIC0ybDAgLTEwIiAvPgogIDxwYXRoIGQ9Ik0xNyAxN3YyYTIgMiAwIDAgMSAtMiAyaC0xMGEyIDIgMCAwIDEgLTIgLTJ2LTEwYTIgMiAwIDAgMSAyIC0yaDIiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/box-multiple\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBoxMultiple = createReactComponent('outline', 'box-multiple', 'BoxMultiple', __iconNode);\n\nexport default IconBoxMultiple;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBracketsContain\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYnJhY2tldHMtY29udGFpbiIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNyA0aC00djE2aDQiIC8+CiAgPHBhdGggZD0iTTE3IDRoNHYxNmgtNCIgLz4KICA8cGF0aCBkPSJNOCAxNmguMDEiIC8+CiAgPHBhdGggZD0iTTEyIDE2aC4wMSIgLz4KICA8cGF0aCBkPSJNMTYgMTZoLjAxIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/brackets-contain\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBracketsContain = createReactComponent('outline', 'brackets-contain', 'BracketsContain', __iconNode);\n\nexport default IconBracketsContain;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBriefcase\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYnJpZWZjYXNlIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0zIDlhMiAyIDAgMCAxIDIgLTJoMTRhMiAyIDAgMCAxIDIgMnY5YTIgMiAwIDAgMSAtMiAyaC0xNGEyIDIgMCAwIDEgLTIgLTJsMCAtOSIgLz4KICA8cGF0aCBkPSJNOCA3di0yYTIgMiAwIDAgMSAyIC0yaDRhMiAyIDAgMCAxIDIgMnYyIiAvPgogIDxwYXRoIGQ9Ik0xMiAxMmwwIC4wMSIgLz4KICA8cGF0aCBkPSJNMyAxM2EyMCAyMCAwIDAgMCAxOCAwIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/briefcase\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBriefcase = createReactComponent('outline', 'briefcase', 'Briefcase', __iconNode);\n\nexport default IconBriefcase;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * I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* @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBucketOff = createReactComponent('outline', 'bucket-off', 'BucketOff', __iconNode);\n\nexport default IconBucketOff;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconBucket\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItYnVja2V0Igo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik00IDdhOCA0IDAgMSAwIDE2IDBhOCA0IDAgMSAwIC0xNiAwIiAvPgogIDxwYXRoIGQ9Ik00IDdjMCAuNjY0IC4wODggMS4zMjQgLjI2MyAxLjk2NWwyLjczNyAxMC4wMzVjLjUgMS41IDIuMjM5IDIgNSAyczQuNSAtLjUgNSAtMmMuMzMzIC0xIDEuMjQ2IC00LjM0NSAyLjczNyAtMTAuMDM1YTcuNDUgNy40NSAwIDAgMCAuMjYzIC0xLjk2NSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/bucket\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconBucket = createReactComponent('outline', 'bucket', 'Bucket', __iconNode);\n\nexport default IconBucket;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCake\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2FrZSIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMyAyMGgxOHYtOGEzIDMgMCAwIDAgLTMgLTNoLTEyYTMgMyAwIDAgMCAtMyAzdjgiIC8+CiAgPHBhdGggZD0iTTMgMTQuODAzYy4zMTIgLjEzNSAuNjU0IC4yMDQgMSAuMTk3YTIuNCAyLjQgMCAwIDAgMiAtMWEyLjQgMi40IDAgMCAxIDIgLTFhMi40IDIuNCAwIDAgMSAyIDFhMi40IDIuNCAwIDAgMCAyIDFhMi40IDIuNCAwIDAgMCAyIC0xYTIuNCAyLjQgMCAwIDEgMiAtMWEyLjQgMi40IDAgMCAxIDIgMWEyLjQgMi40IDAgMCAwIDIgMWMuMzUgLjAwNyAuNjkyIC0uMDYyIDEgLS4xOTciIC8+CiAgPHBhdGggZD0iTTEyIDRsMS40NjUgMS42MzhhMiAyIDAgMSAxIC0zLjAxNSAuMDk5bDEuNTUgLTEuNzM3IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/cake\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCake = createReactComponent('outline', 'cake', 'Cake', __iconNode);\n\nexport default IconCake;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\":\"M11 15h1\",\"key\":\"svg-4\"}],[\"path\",{\"d\":\"M12 15v3\",\"key\":\"svg-5\"}]]\n\n/**\n * IconCalendar\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2FsZW5kYXIiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTQgN2EyIDIgMCAwIDEgMiAtMmgxMmEyIDIgMCAwIDEgMiAydjEyYTIgMiAwIDAgMSAtMiAyaC0xMmEyIDIgMCAwIDEgLTIgLTJ2LTEyIiAvPgogIDxwYXRoIGQ9Ik0xNiAzdjQiIC8+CiAgPHBhdGggZD0iTTggM3Y0IiAvPgogIDxwYXRoIGQ9Ik00IDExaDE2IiAvPgogIDxwYXRoIGQ9Ik0xMSAxNWgxIiAvPgogIDxwYXRoIGQ9Ik0xMiAxNXYzIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/calendar\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCalendar = createReactComponent('outline', 'calendar', 'Calendar', __iconNode);\n\nexport default IconCalendar;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M5 12l5 5l10 -10\",\"key\":\"svg-0\"}]]\n\n/**\n * IconCheck\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2hlY2siCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTUgMTJsNSA1bDEwIC0xMCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/check\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCheck = createReactComponent('outline', 'check', 'Check', __iconNode);\n\nexport default IconCheck;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCheckbox\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2hlY2tib3giCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTkgMTFsMyAzbDggLTgiIC8+CiAgPHBhdGggZD0iTTIwIDEydjZhMiAyIDAgMCAxIC0yIDJoLTEyYTIgMiAwIDAgMSAtMiAtMnYtMTJhMiAyIDAgMCAxIDIgLTJoOSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/checkbox\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCheckbox = createReactComponent('outline', 'checkbox', 'Checkbox', __iconNode);\n\nexport default IconCheckbox;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M6 9l6 6l6 -6\",\"key\":\"svg-0\"}]]\n\n/**\n * IconChevronDown\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2hldnJvbi1kb3duIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik02IDlsNiA2bDYgLTYiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/chevron-down\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconChevronDown = createReactComponent('outline', 'chevron-down', 'ChevronDown', __iconNode);\n\nexport default IconChevronDown;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M9 6l6 6l-6 6\",\"key\":\"svg-0\"}]]\n\n/**\n * IconChevronRight\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2hldnJvbi1yaWdodCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNOSA2bDYgNmwtNiA2IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/chevron-right\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconChevronRight = createReactComponent('outline', 'chevron-right', 'ChevronRight', __iconNode);\n\nexport default IconChevronRight;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M6 15l6 -6l6 6\",\"key\":\"svg-0\"}]]\n\n/**\n * IconChevronUp\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2hldnJvbi11cCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNiAxNWw2IC02bDYgNiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/chevron-up\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconChevronUp = createReactComponent('outline', 'chevron-up', 'ChevronUp', __iconNode);\n\nexport default IconChevronUp;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCircleMinus\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2lyY2xlLW1pbnVzIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0zIDEyYTkgOSAwIDEgMCAxOCAwYTkgOSAwIDEgMCAtMTggMCIgLz4KICA8cGF0aCBkPSJNOSAxMmw2IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/circle-minus\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCircleMinus = createReactComponent('outline', 'circle-minus', 'CircleMinus', __iconNode);\n\nexport default IconCircleMinus;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCirclePlus\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2lyY2xlLXBsdXMiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTMgMTJhOSA5IDAgMSAwIDE4IDBhOSA5IDAgMCAwIC0xOCAwIiAvPgogIDxwYXRoIGQ9Ik05IDEyaDYiIC8+CiAgPHBhdGggZD0iTTEyIDl2NiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/circle-plus\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCirclePlus = createReactComponent('outline', 'circle-plus', 'CirclePlus', __iconNode);\n\nexport default IconCirclePlus;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCloudUpload\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY2xvdWQtdXBsb2FkIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik03IDE4YTQuNiA0LjQgMCAwIDEgMCAtOWE1IDQuNSAwIDAgMSAxMSAyaDFhMy41IDMuNSAwIDAgMSAwIDdoLTEiIC8+CiAgPHBhdGggZD0iTTkgMTVsMyAtM2wzIDMiIC8+CiAgPHBhdGggZD0iTTEyIDEybDAgOSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/cloud-upload\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCloudUpload = createReactComponent('outline', 'cloud-upload', 'CloudUpload', __iconNode);\n\nexport default IconCloudUpload;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconColumns\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY29sdW1ucyIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNCA2bDUuNSAwIiAvPgogIDxwYXRoIGQ9Ik00IDEwbDUuNSAwIiAvPgogIDxwYXRoIGQ9Ik00IDE0bDUuNSAwIiAvPgogIDxwYXRoIGQ9Ik00IDE4bDUuNSAwIiAvPgogIDxwYXRoIGQ9Ik0xNC41IDZsNS41IDAiIC8+CiAgPHBhdGggZD0iTTE0LjUgMTBsNS41IDAiIC8+CiAgPHBhdGggZD0iTTE0LjUgMTRsNS41IDAiIC8+CiAgPHBhdGggZD0iTTE0LjUgMThsNS41IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/columns\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconColumns = createReactComponent('outline', 'columns', 'Columns', __iconNode);\n\nexport default IconColumns;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCopy\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY29weSIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNyA5LjY2N2EyLjY2NyAyLjY2NyAwIDAgMSAyLjY2NyAtMi42NjdoOC42NjZhMi42NjcgMi42NjcgMCAwIDEgMi42NjcgMi42Njd2OC42NjZhMi42NjcgMi42NjcgMCAwIDEgLTIuNjY3IDIuNjY3aC04LjY2NmEyLjY2NyAyLjY2NyAwIDAgMSAtMi42NjcgLTIuNjY3bDAgLTguNjY2IiAvPgogIDxwYXRoIGQ9Ik00LjAxMiAxNi43MzdhMi4wMDUgMi4wMDUgMCAwIDEgLTEuMDEyIC0xLjczN3YtMTBjMCAtMS4xIC45IC0yIDIgLTJoMTBjLjc1IDAgMS4xNTggLjM4NSAxLjUgMSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/copy\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCopy = createReactComponent('outline', 'copy', 'Copy', __iconNode);\n\nexport default IconCopy;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCurrencyDollar\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItY3VycmVuY3ktZG9sbGFyIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xNi43IDhhMyAzIDAgMCAwIC0yLjcgLTJoLTRhMyAzIDAgMCAwIDAgNmg0YTMgMyAwIDAgMSAwIDZoLTRhMyAzIDAgMCAxIC0yLjcgLTIiIC8+CiAgPHBhdGggZD0iTTEyIDN2M20wIDEydjMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/currency-dollar\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCurrencyDollar = createReactComponent('outline', 'currency-dollar', 'CurrencyDollar', __iconNode);\n\nexport default IconCurrencyDollar;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconDeviceDesktop\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZGV2aWNlLWRlc2t0b3AiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTMgNWExIDEgMCAwIDEgMSAtMWgxNmExIDEgMCAwIDEgMSAxdjEwYTEgMSAwIDAgMSAtMSAxaC0xNmExIDEgMCAwIDEgLTEgLTF2LTEwIiAvPgogIDxwYXRoIGQ9Ik03IDIwaDEwIiAvPgogIDxwYXRoIGQ9Ik05IDE2djQiIC8+CiAgPHBhdGggZD0iTTE1IDE2djQiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/device-desktop\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconDeviceDesktop = createReactComponent('outline', 'device-desktop', 'DeviceDesktop', __iconNode);\n\nexport default IconDeviceDesktop;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconDots\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZG90cyIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNCAxMmExIDEgMCAxIDAgMiAwYTEgMSAwIDEgMCAtMiAwIiAvPgogIDxwYXRoIGQ9Ik0xMSAxMmExIDEgMCAxIDAgMiAwYTEgMSAwIDEgMCAtMiAwIiAvPgogIDxwYXRoIGQ9Ik0xOCAxMmExIDEgMCAxIDAgMiAwYTEgMSAwIDEgMCAtMiAwIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/dots\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconDots = createReactComponent('outline', 'dots', 'Dots', __iconNode);\n\nexport default IconDots;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconDownload\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZG93bmxvYWQiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTQgMTd2MmEyIDIgMCAwIDAgMiAyaDEyYTIgMiAwIDAgMCAyIC0ydi0yIiAvPgogIDxwYXRoIGQ9Ik03IDExbDUgNWw1IC01IiAvPgogIDxwYXRoIGQ9Ik0xMiA0bDAgMTIiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/download\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconDownload = createReactComponent('outline', 'download', 'Download', __iconNode);\n\nexport default IconDownload;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconEdit\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZWRpdCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNNyA3aC0xYTIgMiAwIDAgMCAtMiAydjlhMiAyIDAgMCAwIDIgMmg5YTIgMiAwIDAgMCAyIC0ydi0xIiAvPgogIDxwYXRoIGQ9Ik0yMC4zODUgNi41ODVhMi4xIDIuMSAwIDAgMCAtMi45NyAtMi45N2wtOC40MTUgOC4zODV2M2gzbDguMzg1IC04LjQxNSIgLz4KICA8cGF0aCBkPSJNMTYgNWwzIDMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/edit\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEdit = createReactComponent('outline', 'edit', 'Edit', __iconNode);\n\nexport default IconEdit;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconEmpathize\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZW1wYXRoaXplIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik05LjUgNS41YTIuNSAyLjUgMCAxIDAgNSAwYTIuNSAyLjUgMCAxIDAgLTUgMCIgLz4KICA8cGF0aCBkPSJNMTIgMjEuMzY4bDUuMDk1IC01LjA5NmEzLjA4OCAzLjA4OCAwIDEgMCAtNC4zNjcgLTQuMzY3bC0uNzI4IC43MjdsLS43MjggLS43MjdhMy4wODggMy4wODggMCAxIDAgLTQuMzY3IDQuMzY3bDUuMDk1IDUuMDk2IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/empathize\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEmpathize = createReactComponent('outline', 'empathize', 'Empathize', __iconNode);\n\nexport default IconEmpathize;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M5 19l14 -14\",\"key\":\"svg-2\"}]]\n\n/**\n * IconEqualNot\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZXF1YWwtbm90Igo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik01IDEwaDE0IiAvPgogIDxwYXRoIGQ9Ik01IDE0aDE0IiAvPgogIDxwYXRoIGQ9Ik01IDE5bDE0IC0xNCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/equal-not\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEqualNot = createReactComponent('outline', 'equal-not', 'EqualNot', __iconNode);\n\nexport default IconEqualNot;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}]]\n\n/**\n * IconEqual\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZXF1YWwiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTUgMTBoMTQiIC8+CiAgPHBhdGggZD0iTTUgMTRoMTQiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/equal\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEqual = createReactComponent('outline', 'equal', 'Equal', __iconNode);\n\nexport default IconEqual;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconEyeOff\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZXllLW9mZiIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTAuNTg1IDEwLjU4N2EyIDIgMCAwIDAgMi44MjkgMi44MjgiIC8+CiAgPHBhdGggZD0iTTE2LjY4MSAxNi42NzNhOC43MTcgOC43MTcgMCAwIDEgLTQuNjgxIDEuMzI3Yy0zLjYgMCAtNi42IC0yIC05IC02YzEuMjcyIC0yLjEyIDIuNzEyIC0zLjY3OCA0LjMyIC00LjY3NG0yLjg2IC0xLjE0NmE5LjA1NSA5LjA1NSAwIDAgMSAxLjgyIC0uMThjMy42IDAgNi42IDIgOSA2Yy0uNjY2IDEuMTEgLTEuMzc5IDIuMDY3IC0yLjEzOCAyLjg3IiAvPgogIDxwYXRoIGQ9Ik0zIDNsMTggMTgiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/eye-off\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEyeOff = createReactComponent('outline', 'eye-off', 'EyeOff', __iconNode);\n\nexport default IconEyeOff;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconEye\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZXllIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xMCAxMmEyIDIgMCAxIDAgNCAwYTIgMiAwIDAgMCAtNCAwIiAvPgogIDxwYXRoIGQ9Ik0yMSAxMmMtMi40IDQgLTUuNCA2IC05IDZjLTMuNiAwIC02LjYgLTIgLTkgLTZjMi40IC00IDUuNCAtNiA5IC02YzMuNiAwIDYuNiAyIDkgNiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/eye\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconEye = createReactComponent('outline', 'eye', 'Eye', __iconNode);\n\nexport default IconEye;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconFileAlert\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZmlsZS1hbGVydCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTQgM3Y0YTEgMSAwIDAgMCAxIDFoNCIgLz4KICA8cGF0aCBkPSJNMTcgMjFoLTEwYTIgMiAwIDAgMSAtMiAtMnYtMTRhMiAyIDAgMCAxIDIgLTJoN2w1IDV2MTFhMiAyIDAgMCAxIC0yIDIiIC8+CiAgPHBhdGggZD0iTTEyIDE3bC4wMSAwIiAvPgogIDxwYXRoIGQ9Ik0xMiAxMWwwIDMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/file-alert\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconFileAlert = createReactComponent('outline', 'file-alert', 'FileAlert', __iconNode);\n\nexport default IconFileAlert;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconFileExport\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZmlsZS1leHBvcnQiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTE0IDN2NGExIDEgMCAwIDAgMSAxaDQiIC8+CiAgPHBhdGggZD0iTTExLjUgMjFoLTQuNWEyIDIgMCAwIDEgLTIgLTJ2LTE0YTIgMiAwIDAgMSAyIC0yaDdsNSA1djVtLTUgNmg3bS0zIC0zbDMgM2wtMyAzIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/file-export\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconFileExport = createReactComponent('outline', 'file-export', 'FileExport', __iconNode);\n\nexport default IconFileExport;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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 11l0 6\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M9 14l6 0\",\"key\":\"svg-3\"}]]\n\n/**\n * IconFilePlus\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZmlsZS1wbHVzIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xNCAzdjRhMSAxIDAgMCAwIDEgMWg0IiAvPgogIDxwYXRoIGQ9Ik0xNyAyMWgtMTBhMiAyIDAgMCAxIC0yIC0ydi0xNGEyIDIgMCAwIDEgMiAtMmg3bDUgNXYxMWEyIDIgMCAwIDEgLTIgMiIgLz4KICA8cGF0aCBkPSJNMTIgMTFsMCA2IiAvPgogIDxwYXRoIGQ9Ik05IDE0bDYgMCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/file-plus\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconFilePlus = createReactComponent('outline', 'file-plus', 'FilePlus', __iconNode);\n\nexport default IconFilePlus;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconFileText\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZmlsZS10ZXh0Igo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xNCAzdjRhMSAxIDAgMCAwIDEgMWg0IiAvPgogIDxwYXRoIGQ9Ik0xNyAyMWgtMTBhMiAyIDAgMCAxIC0yIC0ydi0xNGEyIDIgMCAwIDEgMiAtMmg3bDUgNXYxMWEyIDIgMCAwIDEgLTIgMiIgLz4KICA8cGF0aCBkPSJNOSA5bDEgMCIgLz4KICA8cGF0aCBkPSJNOSAxM2w2IDAiIC8+CiAgPHBhdGggZD0iTTkgMTdsNiAwIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/file-text\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconFileText = createReactComponent('outline', 'file-text', 'FileText', __iconNode);\n\nexport default IconFileText;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M4 4h16v2.172a2 2 0 0 1 -.586 1.414l-4.414 4.414v7l-6 2v-8.5l-4.48 -4.928a2 2 0 0 1 -.52 -1.345v-2.227\",\"key\":\"svg-0\"}]]\n\n/**\n * IconFilter\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItZmlsdGVyIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik00IDRoMTZ2Mi4xNzJhMiAyIDAgMCAxIC0uNTg2IDEuNDE0bC00LjQxNCA0LjQxNHY3bC02IDJ2LTguNWwtNC40OCAtNC45MjhhMiAyIDAgMCAxIC0uNTIgLTEuMzQ1di0yLjIyNyIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/filter\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconFilter = createReactComponent('outline', 'filter', 'Filter', __iconNode);\n\nexport default IconFilter;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconLanguage\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbGFuZ3VhZ2UiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTkgNi4zNzFjMCA0LjQxOCAtMi4yMzkgNi42MjkgLTUgNi42MjkiIC8+CiAgPHBhdGggZD0iTTQgNi4zNzFoNyIgLz4KICA8cGF0aCBkPSJNNSA5YzAgMi4xNDQgMi4yNTIgMy45MDggNiA0IiAvPgogIDxwYXRoIGQ9Ik0xMiAyMGw0IC05bDQgOSIgLz4KICA8cGF0aCBkPSJNMTkuMSAxOGgtNi4yIiAvPgogIDxwYXRoIGQ9Ik02LjY5NCAzbC43OTMgLjU4MiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/language\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconLanguage = createReactComponent('outline', 'language', 'Language', __iconNode);\n\nexport default IconLanguage;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconLayoutSidebar\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbGF5b3V0LXNpZGViYXIiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTQgNmEyIDIgMCAwIDEgMiAtMmgxMmEyIDIgMCAwIDEgMiAydjEyYTIgMiAwIDAgMSAtMiAyaC0xMmEyIDIgMCAwIDEgLTIgLTJsMCAtMTIiIC8+CiAgPHBhdGggZD0iTTkgNGwwIDE2IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/layout-sidebar\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconLayoutSidebar = createReactComponent('outline', 'layout-sidebar', 'LayoutSidebar', __iconNode);\n\nexport default IconLayoutSidebar;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconLogout\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbG9nb3V0Igo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xNCA4di0yYTIgMiAwIDAgMCAtMiAtMmgtN2EyIDIgMCAwIDAgLTIgMnYxMmEyIDIgMCAwIDAgMiAyaDdhMiAyIDAgMCAwIDIgLTJ2LTIiIC8+CiAgPHBhdGggZD0iTTkgMTJoMTJsLTMgLTMiIC8+CiAgPHBhdGggZD0iTTE4IDE1bDMgLTMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/logout\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconLogout = createReactComponent('outline', 'logout', 'Logout', __iconNode);\n\nexport default IconLogout;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconMapPin\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWFwLXBpbiIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNOSAxMWEzIDMgMCAxIDAgNiAwYTMgMyAwIDAgMCAtNiAwIiAvPgogIDxwYXRoIGQ9Ik0xNy42NTcgMTYuNjU3bC00LjI0MyA0LjI0M2EyIDIgMCAwIDEgLTIuODI3IDBsLTQuMjQ0IC00LjI0M2E4IDggMCAxIDEgMTEuMzE0IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/map-pin\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMapPin = createReactComponent('outline', 'map-pin', 'MapPin', __iconNode);\n\nexport default IconMapPin;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M5 18l14 -6l-14 -6\",\"key\":\"svg-0\"}]]\n\n/**\n * IconMathGreater\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWF0aC1ncmVhdGVyIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik01IDE4bDE0IC02bC0xNCAtNiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/math-greater\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMathGreater = createReactComponent('outline', 'math-greater', 'MathGreater', __iconNode);\n\nexport default IconMathGreater;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M19 18l-14 -6l14 -6\",\"key\":\"svg-0\"}]]\n\n/**\n * IconMathLower\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWF0aC1sb3dlciIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTkgMThsLTE0IC02bDE0IC02IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/math-lower\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMathLower = createReactComponent('outline', 'math-lower', 'MathLower', __iconNode);\n\nexport default IconMathLower;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconMessageCircle\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWVzc2FnZS1jaXJjbGUiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTMgMjBsMS4zIC0zLjljLTIuMzI0IC0zLjQzNyAtMS40MjYgLTcuODcyIDIuMSAtMTAuMzc0YzMuNTI2IC0yLjUwMSA4LjU5IC0yLjI5NiAxMS44NDUgLjQ4YzMuMjU1IDIuNzc3IDMuNjk1IDcuMjY2IDEuMDI5IDEwLjUwMWMtMi42NjYgMy4yMzUgLTcuNjE1IDQuMjE1IC0xMS41NzQgMi4yOTNsLTQuNyAxIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/message-circle\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMessageCircle = createReactComponent('outline', 'message-circle', 'MessageCircle', __iconNode);\n\nexport default IconMessageCircle;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconMessage\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWVzc2FnZSIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNOCA5aDgiIC8+CiAgPHBhdGggZD0iTTggMTNoNiIgLz4KICA8cGF0aCBkPSJNMTggNGEzIDMgMCAwIDEgMyAzdjhhMyAzIDAgMCAxIC0zIDNoLTVsLTUgM3YtM2gtMmEzIDMgMCAwIDEgLTMgLTN2LThhMyAzIDAgMCAxIDMgLTNoMTIiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/message\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMessage = createReactComponent('outline', 'message', 'Message', __iconNode);\n\nexport default IconMessage;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconMicrophone\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWljcm9waG9uZSIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNOSA1YTMgMyAwIDAgMSAzIC0zYTMgMyAwIDAgMSAzIDN2NWEzIDMgMCAwIDEgLTMgM2EzIDMgMCAwIDEgLTMgLTNsMCAtNSIgLz4KICA8cGF0aCBkPSJNNSAxMGE3IDcgMCAwIDAgMTQgMCIgLz4KICA8cGF0aCBkPSJNOCAyMWw4IDAiIC8+CiAgPHBhdGggZD0iTTEyIDE3bDAgNCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/microphone\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMicrophone = createReactComponent('outline', 'microphone', 'Microphone', __iconNode);\n\nexport default IconMicrophone;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-0\"}]]\n\n/**\n * IconMinus\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbWludXMiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTUgMTJsMTQgMCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/minus\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMinus = createReactComponent('outline', 'minus', 'Minus', __iconNode);\n\nexport default IconMinus;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconMoon\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItbW9vbiIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTIgM2MuMTMyIDAgLjI2MyAwIC4zOTMgMGE3LjUgNy41IDAgMCAwIDcuOTIgMTIuNDQ2YTkgOSAwIDEgMSAtOC4zMTMgLTEyLjQ1NGwwIC4wMDgiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/moon\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconMoon = createReactComponent('outline', 'moon', 'Moon', __iconNode);\n\nexport default IconMoon;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconPalette\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItcGFsZXR0ZSIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTIgMjFhOSA5IDAgMCAxIDAgLTE4YzQuOTcgMCA5IDMuNTgyIDkgOGMwIDEuMDYgLS40NzQgMi4wNzggLTEuMzE4IDIuODI4Yy0uODQ0IC43NSAtMS45ODkgMS4xNzIgLTMuMTgyIDEuMTcyaC0yLjVhMiAyIDAgMCAwIC0xIDMuNzVhMS4zIDEuMyAwIDAgMSAtMSAyLjI1IiAvPgogIDxwYXRoIGQ9Ik03LjUgMTAuNWExIDEgMCAxIDAgMiAwYTEgMSAwIDEgMCAtMiAwIiAvPgogIDxwYXRoIGQ9Ik0xMS41IDcuNWExIDEgMCAxIDAgMiAwYTEgMSAwIDEgMCAtMiAwIiAvPgogIDxwYXRoIGQ9Ik0xNS41IDEwLjVhMSAxIDAgMSAwIDIgMGExIDEgMCAxIDAgLTIgMCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/palette\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconPalette = createReactComponent('outline', 'palette', 'Palette', __iconNode);\n\nexport default IconPalette;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconPaperclip\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItcGFwZXJjbGlwIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xNSA3bC02LjUgNi41YTEuNSAxLjUgMCAwIDAgMyAzbDYuNSAtNi41YTMgMyAwIDAgMCAtNiAtNmwtNi41IDYuNWE0LjUgNC41IDAgMCAwIDkgOWw2LjUgLTYuNSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/paperclip\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconPaperclip = createReactComponent('outline', 'paperclip', 'Paperclip', __iconNode);\n\nexport default IconPaperclip;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconPencil\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItcGVuY2lsIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik00IDIwaDRsMTAuNSAtMTAuNWEyLjgyOCAyLjgyOCAwIDEgMCAtNCAtNGwtMTAuNSAxMC41djQiIC8+CiAgPHBhdGggZD0iTTEzLjUgNi41bDQgNCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/pencil\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconPencil = createReactComponent('outline', 'pencil', 'Pencil', __iconNode);\n\nexport default IconPencil;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M12 5l0 14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-1\"}]]\n\n/**\n * IconPlus\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItcGx1cyIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTIgNWwwIDE0IiAvPgogIDxwYXRoIGQ9Ik01IDEybDE0IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/plus\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconPlus = createReactComponent('outline', 'plus', 'Plus', __iconNode);\n\nexport default IconPlus;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4\",\"key\":\"svg-1\"}]]\n\n/**\n * IconRefresh\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItcmVmcmVzaCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMjAgMTFhOC4xIDguMSAwIDAgMCAtMTUuNSAtMm0tLjUgLTR2NGg0IiAvPgogIDxwYXRoIGQ9Ik00IDEzYTguMSA4LjEgMCAwIDAgMTUuNSAybS41IDR2LTRoLTQiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/refresh\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconRefresh = createReactComponent('outline', 'refresh', 'Refresh', __iconNode);\n\nexport default IconRefresh;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSearch\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc2VhcmNoIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0zIDEwYTcgNyAwIDEgMCAxNCAwYTcgNyAwIDEgMCAtMTQgMCIgLz4KICA8cGF0aCBkPSJNMjEgMjFsLTYgLTYiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/search\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSearch = createReactComponent('outline', 'search', 'Search', __iconNode);\n\nexport default IconSearch;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSettings\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc2V0dGluZ3MiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTEwLjMyNSA0LjMxN2MuNDI2IC0xLjc1NiAyLjkyNCAtMS43NTYgMy4zNSAwYTEuNzI0IDEuNzI0IDAgMCAwIDIuNTczIDEuMDY2YzEuNTQzIC0uOTQgMy4zMSAuODI2IDIuMzcgMi4zN2ExLjcyNCAxLjcyNCAwIDAgMCAxLjA2NSAyLjU3MmMxLjc1NiAuNDI2IDEuNzU2IDIuOTI0IDAgMy4zNWExLjcyNCAxLjcyNCAwIDAgMCAtMS4wNjYgMi41NzNjLjk0IDEuNTQzIC0uODI2IDMuMzEgLTIuMzcgMi4zN2ExLjcyNCAxLjcyNCAwIDAgMCAtMi41NzIgMS4wNjVjLS40MjYgMS43NTYgLTIuOTI0IDEuNzU2IC0zLjM1IDBhMS43MjQgMS43MjQgMCAwIDAgLTIuNTczIC0xLjA2NmMtMS41NDMgLjk0IC0zLjMxIC0uODI2IC0yLjM3IC0yLjM3YTEuNzI0IDEuNzI0IDAgMCAwIC0xLjA2NSAtMi41NzJjLTEuNzU2IC0uNDI2IC0xLjc1NiAtMi45MjQgMCAtMy4zNWExLjcyNCAxLjcyNCAwIDAgMCAxLjA2NiAtMi41NzNjLS45NCAtMS41NDMgLjgyNiAtMy4zMSAyLjM3IC0yLjM3YzEgLjYwOCAyLjI5NiAuMDcgMi41NzIgLTEuMDY1IiAvPgogIDxwYXRoIGQ9Ik05IDEyYTMgMyAwIDEgMCA2IDBhMyAzIDAgMCAwIC02IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/settings\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSettings = createReactComponent('outline', 'settings', 'Settings', __iconNode);\n\nexport default IconSettings;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSortAscending\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc29ydC1hc2NlbmRpbmciCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTQgNmw3IDAiIC8+CiAgPHBhdGggZD0iTTQgMTJsNyAwIiAvPgogIDxwYXRoIGQ9Ik00IDE4bDkgMCIgLz4KICA8cGF0aCBkPSJNMTUgOWwzIC0zbDMgMyIgLz4KICA8cGF0aCBkPSJNMTggNmwwIDEyIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/sort-ascending\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSortAscending = createReactComponent('outline', 'sort-ascending', 'SortAscending', __iconNode);\n\nexport default IconSortAscending;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSortDescending\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc29ydC1kZXNjZW5kaW5nIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik00IDZsOSAwIiAvPgogIDxwYXRoIGQ9Ik00IDEybDcgMCIgLz4KICA8cGF0aCBkPSJNNCAxOGw3IDAiIC8+CiAgPHBhdGggZD0iTTE1IDE1bDMgM2wzIC0zIiAvPgogIDxwYXRoIGQ9Ik0xOCA2bDAgMTIiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/sort-descending\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSortDescending = createReactComponent('outline', 'sort-descending', 'SortDescending', __iconNode);\n\nexport default IconSortDescending;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSquare\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc3F1YXJlIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0zIDVhMiAyIDAgMCAxIDIgLTJoMTRhMiAyIDAgMCAxIDIgMnYxNGEyIDIgMCAwIDEgLTIgMmgtMTRhMiAyIDAgMCAxIC0yIC0ydi0xNCIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/square\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSquare = createReactComponent('outline', 'square', 'Square', __iconNode);\n\nexport default IconSquare;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconStethoscope\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc3RldGhvc2NvcGUiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTYgNGgtMWEyIDIgMCAwIDAgLTIgMnYzLjVhNS41IDUuNSAwIDAgMCAxMSAwdi0zLjVhMiAyIDAgMCAwIC0yIC0yaC0xIiAvPgogIDxwYXRoIGQ9Ik04IDE1YTYgNiAwIDEgMCAxMiAwdi0zIiAvPgogIDxwYXRoIGQ9Ik0xMSAzdjIiIC8+CiAgPHBhdGggZD0iTTYgM3YyIiAvPgogIDxwYXRoIGQ9Ik0xOCAxMGEyIDIgMCAxIDAgNCAwYTIgMiAwIDEgMCAtNCAwIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/stethoscope\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconStethoscope = createReactComponent('outline', 'stethoscope', 'Stethoscope', __iconNode);\n\nexport default IconStethoscope;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSunHigh\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc3VuLWhpZ2giCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTE0LjgyOCAxNC44MjhhNCA0IDAgMSAwIC01LjY1NiAtNS42NTZhNCA0IDAgMCAwIDUuNjU2IDUuNjU2IiAvPgogIDxwYXRoIGQ9Ik02LjM0MyAxNy42NTdsLTEuNDE0IDEuNDE0IiAvPgogIDxwYXRoIGQ9Ik02LjM0MyA2LjM0M2wtMS40MTQgLTEuNDE0IiAvPgogIDxwYXRoIGQ9Ik0xNy42NTcgNi4zNDNsMS40MTQgLTEuNDE0IiAvPgogIDxwYXRoIGQ9Ik0xNy42NTcgMTcuNjU3bDEuNDE0IDEuNDE0IiAvPgogIDxwYXRoIGQ9Ik00IDEyaC0yIiAvPgogIDxwYXRoIGQ9Ik0xMiA0di0yIiAvPgogIDxwYXRoIGQ9Ik0yMCAxMmgyIiAvPgogIDxwYXRoIGQ9Ik0xMiAyMHYyIiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/sun-high\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSunHigh = createReactComponent('outline', 'sun-high', 'SunHigh', __iconNode);\n\nexport default IconSunHigh;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconSwitchHorizontal\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItc3dpdGNoLWhvcml6b250YWwiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTE2IDNsNCA0bC00IDQiIC8+CiAgPHBhdGggZD0iTTEwIDdsMTAgMCIgLz4KICA8cGF0aCBkPSJNOCAxM2wtNCA0bDQgNCIgLz4KICA8cGF0aCBkPSJNNCAxN2w5IDAiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/switch-horizontal\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconSwitchHorizontal = createReactComponent('outline', 'switch-horizontal', 'SwitchHorizontal', __iconNode);\n\nexport default IconSwitchHorizontal;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconTableExport\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItdGFibGUtZXhwb3J0Igo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik0xMi41IDIxaC03LjVhMiAyIDAgMCAxIC0yIC0ydi0xNGEyIDIgMCAwIDEgMiAtMmgxNGEyIDIgMCAwIDEgMiAydjcuNSIgLz4KICA8cGF0aCBkPSJNMyAxMGgxOCIgLz4KICA8cGF0aCBkPSJNMTAgM3YxOCIgLz4KICA8cGF0aCBkPSJNMTYgMTloNiIgLz4KICA8cGF0aCBkPSJNMTkgMTZsMyAzbC0zIDMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/table-export\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconTableExport = createReactComponent('outline', 'table-export', 'TableExport', __iconNode);\n\nexport default IconTableExport;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconTable\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItdGFibGUiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTMgNWEyIDIgMCAwIDEgMiAtMmgxNGEyIDIgMCAwIDEgMiAydjE0YTIgMiAwIDAgMSAtMiAyaC0xNGEyIDIgMCAwIDEgLTIgLTJ2LTE0IiAvPgogIDxwYXRoIGQ9Ik0zIDEwaDE4IiAvPgogIDxwYXRoIGQ9Ik0xMCAzdjE4IiAvPgo8L3N2Zz4=) - https://tabler.io/icons/icon/table\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconTable = createReactComponent('outline', 'table', 'Table', __iconNode);\n\nexport default IconTable;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconTrash\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItdHJhc2giCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTQgN2wxNiAwIiAvPgogIDxwYXRoIGQ9Ik0xMCAxMWwwIDYiIC8+CiAgPHBhdGggZD0iTTE0IDExbDAgNiIgLz4KICA8cGF0aCBkPSJNNSA3bDEgMTJhMiAyIDAgMCAwIDIgMmg4YTIgMiAwIDAgMCAyIC0ybDEgLTEyIiAvPgogIDxwYXRoIGQ9Ik05IDd2LTNhMSAxIDAgMCAxIDEgLTFoNGExIDEgMCAwIDEgMSAxdjMiIC8+Cjwvc3ZnPg==) - https://tabler.io/icons/icon/trash\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconTrash = createReactComponent('outline', 'trash', 'Trash', __iconNode);\n\nexport default IconTrash;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconUsers\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXItdXNlcnMiCj4KICA8cGF0aCBzdHJva2U9Im5vbmUiIGQ9Ik0wIDBoMjR2MjRIMHoiIGZpbGw9Im5vbmUiIC8+CiAgPHBhdGggZD0iTTUgN2E0IDQgMCAxIDAgOCAwYTQgNCAwIDEgMCAtOCAwIiAvPgogIDxwYXRoIGQ9Ik0zIDIxdi0yYTQgNCAwIDAgMSA0IC00aDRhNCA0IDAgMCAxIDQgNHYyIiAvPgogIDxwYXRoIGQ9Ik0xNiAzLjEzYTQgNCAwIDAgMSAwIDcuNzUiIC8+CiAgPHBhdGggZD0iTTIxIDIxdi0yYTQgNCAwIDAgMCAtMyAtMy44NSIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/users\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconUsers = createReactComponent('outline', 'users', 'Users', __iconNode);\n\nexport default IconUsers;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: IconNode = [[\"path\",{\"d\":\"M18 6l-12 12\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M6 6l12 12\",\"key\":\"svg-1\"}]]\n\n/**\n * IconX\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0ibm9uZSIKICBzdHJva2U9ImN1cnJlbnRDb2xvciIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCiAgY2xhc3M9Imljb24gaWNvbi10YWJsZXIgaWNvbnMtdGFibGVyLW91dGxpbmUgaWNvbi10YWJsZXIteCIKPgogIDxwYXRoIHN0cm9rZT0ibm9uZSIgZD0iTTAgMGgyNHYyNEgweiIgZmlsbD0ibm9uZSIgLz4KICA8cGF0aCBkPSJNMTggNmwtMTIgMTIiIC8+CiAgPHBhdGggZD0iTTYgNmwxMiAxMiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/x\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconX = createReactComponent('outline', 'x', 'X', __iconNode);\n\nexport default IconX;", "import createReactComponent from '../createReactComponent';\nimport { IconNode } from '../types';\n\nexport const __iconNode: 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\"}]]\n\n/**\n * IconCircleFilled\n * @preview ![img](data:image/svg+xml;base64,PHN2ZwogIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICB3aWR0aD0iMjQiCiAgaGVpZ2h0PSIyNCIKICB2aWV3Qm94PSIwIDAgMjQgMjQiCiAgZmlsbD0iY3VycmVudENvbG9yIgogIGNsYXNzPSJpY29uIGljb24tdGFibGVyIGljb25zLXRhYmxlci1maWxsZWQgaWNvbi10YWJsZXItY2lyY2xlIgo+CiAgPHBhdGggc3Ryb2tlPSJub25lIiBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIiAvPgogIDxwYXRoIGQ9Ik03IDMuMzRhMTAgMTAgMCAxIDEgLTQuOTk1IDguOTg0bC0uMDA1IC0uMzI0bC4wMDUgLS4zMjRhMTAgMTAgMCAwIDEgNC45OTUgLTguMzM2eiIgLz4KPC9zdmc+) - https://tabler.io/icons/icon/circle-filled\n * @see https://docs.tabler.io/icons/libraries/react - Documentation\n *\n */\nconst IconCircleFilled = createReactComponent('filled', 'circle-filled', 'CircleFilled', __iconNode);\n\nexport default IconCircleFilled;", "// 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", ".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", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, AppShell as MantineAppShell, Menu, Text, UnstyledButton } from '@mantine/core';\nimport { formatHumanName } from '@medplum/core';\nimport { 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 classes from './Header.module.css';\nimport { HeaderDropdown } from './HeaderDropdown';\nimport headerDropdownClasses from './HeaderDropdown.module.css';\nimport { HeaderSearchInput } from './HeaderSearchInput';\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}\n\nexport function Header(props: HeaderProps): JSX.Element {\n  const profile = useMedplumProfile();\n  const [userMenuOpened, setUserMenuOpened] = useState(false);\n\n  return (\n    <MantineAppShell.Header p={8} style={{ zIndex: 101 }}>\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            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                  <Text size=\"sm\" className={classes.userName}>\n                    {formatHumanName(profile?.name?.[0])}\n                  </Text>\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    </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 } 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 {\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.userName {\n  font-weight: 500;\n  line-height: 1px;\n  margin-right: 3px;\n\n  @media (max-width: $mantine-breakpoint-xs) {\n    display: none;\n  }\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          {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        </>\n      )}\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    </>\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\" c=\"dimmed\" 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.interactive {\n  border-radius: var(--mantine-radius-sm);\n  padding: 8px 12px;\n  cursor: pointer;\n\n  &:hover,\n  &[data-hovered] {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n\n    & .iconBox {\n      color: var(--mantine-color-text);\n    }\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  overflow: visible;\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  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 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    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    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 [autoSubmit, setAutoSubmit] = useState<boolean>();\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>(autoSubmit);\n  useLayoutEffect(() => {\n    searchRef.current = search;\n    timerRef.current = timer;\n    abortControllerRef.current = abortController;\n    autoSubmitRef.current = autoSubmit;\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          setOptions(newValues.map(toOption));\n          if (autoSubmitRef.current) {\n            if (newValues.length > 0) {\n              onChange(newValues.slice(0, 1));\n            }\n            setAutoSubmit(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, onChange, toOption, minInputLength]);\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]\n  );\n\n  const addSelected = useCallback(\n    (newValue: string): void => {\n      const alreadySelected = selected.some((v) => v.value === newValue);\n      const newSelected = alreadySelected ? selected.filter((v) => v.value !== newValue) : [...selected];\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\n      if (option) {\n        // when maxValues is 0, still fire the onChange when an item is selected\n        if (maxValues === 0) {\n          onChange([option.resource]);\n\n          // and clear selected if necessary\n          if (selected.length > 0) {\n            setSelected([]);\n          }\n          return;\n        }\n\n        if (!alreadySelected) {\n          newSelected.push(option);\n        }\n      }\n\n      if (maxValues !== undefined) {\n        while (newSelected.length > maxValues) {\n          // Remove from the front\n          newSelected.shift();\n        }\n      }\n\n      onChange(newSelected.map((v) => v.resource));\n      setSelected(newSelected);\n    },\n    [creatable, options, selected, maxValues, onChange, onCreate, toOption]\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      if (maxValues === 1) {\n        setSearch('');\n        setOptions([]);\n        combobox.closeDropdown();\n      }\n      lastValueRef.current = undefined;\n      if (val === '$create') {\n        setSearch('');\n        addSelected(search);\n      } else {\n        addSelected(val);\n      }\n    };\n  }, [addSelected, combobox, disabled, maxValues, search]);\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          setAutoSubmit(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          disabled={disabled}\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                  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 {\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 { 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 { Spotlight } from './Spotlight';\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 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 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\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 && <Spotlight patientsOnly={props.patientsOnly} />}\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              transitionProps={{ transition: 'fade-up' }}\n              opened={userMenuOpened}\n              onClose={() => setUserMenuOpened(false)}\n            >\n              <Menu.Target>\n                <UnstyledButton\n                  className={classes.link}\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.linkLabel} data-opened={opened || undefined}>\n                    {formatHumanName(profile?.name?.[0])}\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}\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    />\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 { Group, Text } from '@mantine/core';\nimport type { ValueSetExpandParams } from '@medplum/core';\nimport type { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { IconCheck } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { forwardRef, useCallback } from 'react';\nimport type { AsyncAutocompleteOption, AsyncAutocompleteProps } from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { AsyncAutocomplete } from '../AsyncAutocomplete/AsyncAutocomplete';\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, ...rest } = props;\n\n  const loadValues = useCallback(\n    async (input: string, signal: AbortSignal): Promise<ValueSetExpansionContains[]> => {\n      if (!binding) {\n        return [];\n      }\n      const valueSet = await medplum.valueSetExpand(\n        {\n          count: 10,\n          ...expandParams,\n          url: binding,\n          filter: input,\n        },\n        { signal }\n      );\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\n      return newData;\n    },\n    [medplum, expandParams, binding]\n  );\n\n  return (\n    <AsyncAutocomplete\n      {...rest}\n      creatable={creatable ?? true}\n      clearable={clearable ?? true}\n      toOption={toOption}\n      loadOptions={loadValues}\n      onCreate={createValue}\n      itemComponent={withHelpText ? ItemComponent : undefined}\n    />\n  );\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", ".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.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 { Kbd, Stack, Text } from '@mantine/core';\nimport { useDebouncedCallback } from '@mantine/hooks';\nimport type { SpotlightActionData, SpotlightActionGroupData } from '@mantine/spotlight';\nimport { Spotlight as MantineSpotlight } from '@mantine/spotlight';\nimport { formatHumanName, isUUID } from '@medplum/core';\nimport type { Patient, ServiceRequest, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport type { MedplumNavigateFunction } from '@medplum/react-hooks';\nimport { useMedplum, useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport type { JSX } 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\nexport interface SpotlightProps {\n  readonly patientsOnly?: boolean;\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 }: SpotlightProps): JSX.Element {\n  const medplum = useMedplum();\n  const navigate = useMedplumNavigate();\n  const [nothingFoundMessage, setNothingFoundMessage] = useState<React.ReactNode>(<KeyboardHint />);\n  const [actions, setActions] = useState<SpotlightActionGroupData[]>([]);\n\n  const debouncedSearch = useDebouncedCallback((query: string) => {\n    const graphqlQuery = buildGraphQLQuery(query);\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, navigate));\n        })\n        .catch(console.error)\n        .finally(() => setNothingFoundMessage('No results found'));\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: query,\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, navigate));\n        })\n        .catch(console.error)\n        .finally(() => setNothingFoundMessage('No results found'));\n    }\n  }, DEBOUNCE_MS);\n\n  const handleQueryChange = (query: string): void => {\n    if (!query) {\n      debouncedSearch.cancel();\n      setNothingFoundMessage(<KeyboardHint />);\n      setActions([]);\n      return;\n    }\n\n    setNothingFoundMessage('Searching...');\n    debouncedSearch(query);\n  };\n\n  return (\n    <MantineSpotlight\n      actions={actions}\n      nothingFound={nothingFoundMessage}\n      radius=\"md\"\n      highlightQuery\n      searchProps={\n        {\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',\n          'data-lpignore': 'true',\n          leftSectionProps: {\n            style: { marginLeft: 'calc(var(--mantine-spacing-md) - 12px)' },\n          },\n        } as any\n      }\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      }}\n      onQueryChange={handleQueryChange}\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 { 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 patientsToActions(patients: Patient[], navigate: MedplumNavigateFunction): SpotlightActionGroupData[] {\n  const patientActions: SpotlightActionData[] = patients\n    .filter((p): p is Patient & { id: string } => Boolean(p.id))\n    .map((patient) => ({\n      id: 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      onClick: () => navigate(`/Patient/${patient.id}`),\n    }));\n\n  return patientActions.length > 0 ? [{ group: 'Patients', actions: patientActions }] : [];\n}\n\nfunction resourcesToActions(\n  resources: HeaderSearchTypes[],\n  resourceTypes: ValueSetExpansionContains[],\n  navigate: MedplumNavigateFunction\n): SpotlightActionGroupData[] {\n  const result: SpotlightActionGroupData[] = [];\n\n  // Resource types\n  const resourceTypeActions: SpotlightActionData[] = resourceTypes.map((rt) => ({\n    id: `resource-type-${rt.code}`,\n    label: rt.display ?? rt.code ?? '',\n    description: 'Resource Type',\n    onClick: () => navigate(`/${rt.code}`),\n  }));\n  if (resourceTypeActions.length > 0) {\n    result.push({ group: 'Resource Types', actions: resourceTypeActions });\n  }\n\n  const patientActions: SpotlightActionData[] = [];\n  const serviceRequestActions: SpotlightActionData[] = [];\n\n  for (const resource of resources) {\n    if (resource.resourceType === 'Patient' && resource.id) {\n      patientActions.push({\n        id: resource.id,\n        label: resource.name ? formatHumanName(resource.name[0]) : resource.id,\n        description: resource.birthDate,\n        leftSection: <ResourceAvatar value={resource} radius=\"xl\" size={24} />,\n        onClick: () => navigate(`/Patient/${resource.id}`),\n      });\n    } else if (resource.resourceType === 'ServiceRequest' && resource.id) {\n      serviceRequestActions.push({\n        id: resource.id,\n        label: resource.id,\n        description: resource.subject?.display,\n        onClick: () => navigate(`/ServiceRequest/${resource.id}`),\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 light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));\n}\n\n/* Group label spacing */\n.actionsGroup::before {\n  padding-bottom: 2px;\n}\n\n/* Actions list container */\n.actionsList {\n  padding-top: 2px;\n}\n\n/* Modal content wrapper */\n.content {\n  box-shadow: light-dark(\n    0 0.5rem 2rem rgba(0, 0, 0, 0.15),\n    0 0.5rem 2rem rgba(0, 0, 0, 0.5)\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 { 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 { useCachedBinaryUrl } 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  const { contentType, url: uncachedUrl, title } = props.value ?? {};\n  const url = useCachedBinaryUrl(uncachedUrl);\n\n  if (!url) {\n    return null;\n  }\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('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\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, PasswordInput, 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 { 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 { 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 { Alert, Center, Image, Stack, Text, TextInput, Title } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport type { JSX } 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\nexport interface MfaFormProps {\n  readonly title: string;\n  readonly buttonText: string;\n  readonly description?: string;\n  readonly qrCodeUrl?: string;\n  readonly onSubmit: (formData: Record<MfaFormFields, string>) => void | Promise<void>;\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\">\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\">\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      </Stack>\n    </Form>\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}\n\nexport function RegisterForm(props: RegisterFormProps): JSX.Element {\n  const { type, projectId, clientId, googleClientId, recaptchaSiteKey, onSuccess } = 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          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 { 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}\n\nexport function OperationOutcomeAlert(props: OperationOutcomeAlertProps): JSX.Element | null {\n  const { outcome, issues: issuesProp, ...spacingProps } = props;\n  const issues = outcome?.issue || issuesProp;\n  if (!issues || issues.length === 0) {\n    return null;\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, PasswordInput, 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 { 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 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        <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, PasswordInput, 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 { 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 } from '@medplum/core';\nimport { normalizeErrorString } 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 { ChooseScopeForm } from './ChooseScopeForm';\nimport { MfaForm } from './MfaForm';\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}\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    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 [mfaRequired, setMfaRequired] = 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      setMfaRequired(!!response.mfaRequired);\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 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    if (loginCode && !loginRequested.current && !login) {\n      loginRequested.current = true;\n      medplum\n        .get('auth/login/' + 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 && enrollQrCode) {\n          return (\n            <MfaForm\n              title=\"Enroll in MFA\"\n              description=\"Scan this QR code with your authenticator app.\"\n              buttonText=\"Enroll\"\n              qrCodeUrl={enrollQrCode}\n              onSubmit={async (fields) => {\n                const res = await medplum.post<LoginAuthenticationResponse>('auth/mfa/login-enroll', {\n                  login: login,\n                  token: fields.token,\n                });\n                handleAuthResponse(res);\n              }}\n            />\n          );\n        } else if (mfaRequired) {\n          return (\n            <MfaForm\n              title=\"Enter MFA code\"\n              description=\"Enter the code from your authenticator app.\"\n              buttonText=\"Submit Code\"\n              onSubmit={async (fields) => {\n                const res = await medplum.post<LoginAuthenticationResponse>('auth/mfa/verify', {\n                  login: login,\n                  token: fields.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 <ChooseScopeForm login={login} scope={props.scope} handleAuthResponse={handleScopeResponse} />;\n        } else {\n          return <div>Success</div>;\n        }\n      })()}\n    </Document>\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, PasswordInput, 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 { 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 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\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\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 handleValueSelect(membershipId: string): void {\n    medplum\n      .post<LoginAuthenticationResponse>('auth/profile', {\n        login: props.login,\n        profile: membershipId,\n      })\n      .then(props.handleAuthResponse)\n      .catch((err) => setOutcome(normalizeOperationOutcome(err)));\n  }\n\n  const options = props.memberships\n    .filter(filterMembership)\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 { Checkbox, Flex, Group, Stack, Title } from '@mantine/core';\nimport type { LoginAuthenticationResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport type { JSX } 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}\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          <Logo size={32} />\n          <Title order={3} py=\"lg\">\n            Choose scope\n          </Title>\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>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 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", "// 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      }}\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.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 { TextInput } from '@mantine/core';\nimport type { OperationOutcome } from '@medplum/fhirtypes';\nimport type { ChangeEvent, JSX } from 'react';\nimport type { PrimitiveTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\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  return (\n    <TextInput\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={convertIsoToLocal(props.defaultValue)}\n      autoFocus={props.autoFocus}\n      error={getErrorsForInput(props.outcome, props.name)}\n      onChange={(e: ChangeEvent<HTMLInputElement>) => {\n        if (props.onChange) {\n          const newValue = e.currentTarget.value;\n          props.onChange(convertLocalToIso(newValue));\n        }\n      }}\n    />\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", "// 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}\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          />\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        />\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\n/**\n * @deprecated Use MultiResourceInput instead, which supports multiple default and selected values.\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  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  readonly error?: AsyncAutocompleteProps<T>['error'];\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      placeholder={props.placeholder}\n      required={props.required}\n      itemComponent={props.itemComponent}\n      onChange={handleChange}\n      disabled={props.disabled}\n      label={props.label}\n      error={props.error}\n      maxValues={1}\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  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  readonly error?: AsyncAutocompleteProps<T>['error'];\n  /** Maximum number of resources that can be selected. Defaults to uncapped. */\n  readonly maxValues?: number;\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 } = 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 searchCode = getSearchParamForResourceType(resourceType);\n      const searchParams = new URLSearchParams({\n        [searchCode]: 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]\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      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      clearable\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 { 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\nconst daysOfWeek: DayOfWeek[] = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];\n\ntype 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 { Button, Group } from '@mantine/core';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport classes from './CalendarDateInput.module.css';\nimport { getMonthString, getStartMonth } from './CalendarDateInput.utils';\n\nexport interface CalendarDateInputProps {\n  readonly availableDates: Date[];\n  readonly onChangeMonth: (date: Date) => void;\n  readonly onClick: (date: Date) => void;\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 } = props;\n  const [month, setMonth] = useState<Date>(getStartMonth);\n\n  function moveMonth(delta: number): void {\n    setMonth((currMonth) => {\n      const newMonth = new Date(currMonth);\n      newMonth.setMonth(currMonth.getMonth() + delta);\n      onChangeMonth(newMonth);\n      return newMonth;\n    });\n  }\n\n  const grid = useMemo(() => buildGrid(month, props.availableDates), [month, props.availableDates]);\n\n  return (\n    <div>\n      <Group justify=\"space-between\" gap=\"xs\" grow wrap=\"nowrap\">\n        <p style={{ flex: 1 }}>{getMonthString(month)}</p>\n        <Group justify=\"flex-end\" gap=\"xs\">\n          <Button variant=\"outline\" aria-label=\"Previous month\" onClick={() => moveMonth(-1)}>\n            &lt;\n          </Button>\n          <Button variant=\"outline\" aria-label=\"Next month\" onClick={() => moveMonth(1)}>\n            &gt;\n          </Button>\n        </Group>\n      </Group>\n      <table className={classes.table}>\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 key={'day-' + dayIndex}>\n                  {day && (\n                    <Button variant=\"light\" disabled={!day.available} onClick={() => onClick(day.date)}>\n                      {day.date.getDate()}\n                    </Button>\n                  )}\n                </td>\n              ))}\n            </tr>\n          ))}\n        </tbody>\n      </table>\n    </div>\n  );\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  for (const availableDate of availableDates) {\n    if (\n      availableDate.getFullYear() === day.getFullYear() &&\n      availableDate.getMonth() === day.getMonth() &&\n      availableDate.getDate() === day.getDate()\n    ) {\n      return true;\n    }\n  }\n\n  return false;\n}\n", ".table {\n  width: 350px;\n\n  & th {\n    font-weight: normal;\n    font-size: 11px;\n    padding: 8px;\n    text-align: center;\n  }\n\n  & td {\n    padding: 2px 4px;\n  }\n\n  & td button {\n    width: 44px;\n    height: 44px;\n    color: theme.colors[theme.primaryColor][5];\n    font-size: 16px;\n    font-weight: 500;\n    text-align: center;\n    padding: 0;\n    background-color: theme.colors[theme.primaryColor][0];\n    border: 0;\n    border-radius: 50px;\n    cursor: pointer;\n  }\n\n  & td button:hover {\n    background-color: theme.colors[theme.primaryColor][1];\n  }\n\n  & td button:disabled {\n    background-color: transparen;\n    cursor: defaul;\n    color: var(--mantine-color-gray-4);\n    font-weight: normal;\n  }\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  const result = new Date();\n  result.setDate(1);\n  result.setHours(0, 0, 0, 0);\n  return result;\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\nexport interface CalendarInputProps {\n  readonly slots: Slot[];\n  readonly onChangeMonth: (date: Date) => void;\n  readonly onClick: (date: Date) => void;\n}\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-dark), 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        onMessageSent?.(communication);\n      };\n\n      buildAndSend().catch(console.error);\n    },\n    [medplum, profileRef, thread, threadRef, communications, onMessageSent]\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 { Divider, Stack } from '@mantine/core';\nimport type { Communication } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { Fragment } from 'react';\nimport { ChatListItem } from './ChatListItem';\n\nexport interface ChatListProps {\n  threads: [Communication, Communication | undefined][];\n  selectedCommunication: Communication | undefined;\n  getThreadUri: (topic: Communication) => string;\n}\n\nexport const ChatList = (props: ChatListProps): JSX.Element => {\n  const { threads, selectedCommunication, getThreadUri } = props;\n\n  return (\n    <Stack gap={0}>\n      {threads.map((thread: [Communication, Communication | undefined]) => {\n        const topicCommunication = thread[0];\n        const lastCommunication = thread[1];\n        const _isSelected = selectedCommunication?.id === topicCommunication.id;\n        return (\n          <Fragment key={topicCommunication.id}>\n            <ChatListItem\n              topic={topicCommunication}\n              lastCommunication={lastCommunication}\n              isSelected={_isSelected}\n              getThreadUri={getThreadUri}\n            />\n            <Divider />\n          </Fragment>\n        );\n      })}\n    </Stack>\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 { formatDateTime, formatHumanName } from '@medplum/core';\nimport type { Communication, Patient, Reference } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../../MedplumLink/MedplumLink';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './ChatListItem.module.css';\n\nexport interface ChatListItemProps {\n  topic: Communication;\n  lastCommunication: Communication | undefined;\n  isSelected: boolean;\n  getThreadUri: (topic: Communication) => string;\n}\n\nexport const ChatListItem = (props: ChatListItemProps): JSX.Element => {\n  const { topic, lastCommunication, isSelected, 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\">\n      <Group\n        p=\"xs\"\n        align=\"center\"\n        wrap=\"nowrap\"\n        className={cx(classes.contentContainer, {\n          [classes.selected]: isSelected,\n        })}\n      >\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\n.contentContainer:hover {\n  background-color: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-9));\n}\n\n.contentContainer {\n  transition: all 0.2s ease;\n  cursor: pointer;\n  border: 1px solid transparent;\n  text-decoration: none;\n  color: light-dark(var(--mantine-color-dark-9), var(--mantine-color-gray-0));\n}\n\n.contentContainer.selected {\n  background: light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-9));\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Button, Modal, Stack, Text, TextInput } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { createReference, HTTP_HL7_ORG, normalizeErrorString } from '@medplum/core';\nimport type {\n  Communication,\n  Patient,\n  Practitioner,\n  Questionnaire,\n  QuestionnaireResponse,\n  Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useMemo, useState } from 'react';\nimport { QuestionnaireForm } from '../../QuestionnaireForm/QuestionnaireForm';\nimport { ResourceInput } from '../../ResourceInput/ResourceInput';\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  const [topic, setTopic] = useState('');\n  const [practitioners, setPractitioners] = useState(\n    profile?.resourceType === 'Practitioner' ? [createReference(profile) as Reference<Practitioner>] : []\n  );\n  const [patient, setPatient] = useState<Reference<Patient> | undefined>(\n    subject ? createReference(subject as Patient) : undefined\n  );\n\n  // Create initial QuestionnaireResponse with current practitioner as default\n  const initialResponse: QuestionnaireResponse | undefined = useMemo(() => {\n    if (profile?.resourceType === 'Practitioner') {\n      return {\n        resourceType: 'QuestionnaireResponse',\n        status: 'in-progress',\n        item: [\n          {\n            linkId: 'q1',\n            answer: [{ valueReference: createReference(profile) }],\n          },\n        ],\n      };\n    }\n    return undefined;\n  }, [profile]);\n\n  const handleSubmit = async (): Promise<void> => {\n    if (!patient) {\n      showNotification({\n        title: 'Error',\n        message: 'Please select a patient',\n        color: 'red',\n      });\n      return;\n    }\n\n    const communication: Communication = {\n      resourceType: 'Communication',\n      status: 'in-progress',\n      subject: patient,\n      sender: profileRef,\n      recipient: [\n        patient,\n        ...practitioners.map((practitioner) => ({\n          reference: practitioner.reference,\n        })),\n      ],\n      topic: {\n        text: topic,\n      },\n    };\n\n    try {\n      const createdCommunication = await medplum.createResource(communication);\n      onSubmit?.(createdCommunication);\n      onClose();\n    } catch (error) {\n      showNotification({\n        title: 'Error',\n        message: normalizeErrorString(error),\n        color: 'red',\n      });\n    }\n  };\n\n  return (\n    <Modal opened={opened} onClose={onClose} title=\"New Message\" size=\"md\">\n      <Stack gap=\"xl\">\n        <Stack gap={0}>\n          <Text fw={500}>Patient</Text>\n          {allowPatientSelection && <Text c=\"dimmed\">Select a patient</Text>}\n\n          <ResourceInput\n            resourceType=\"Patient\"\n            name=\"patient\"\n            required={true}\n            defaultValue={patient}\n            disabled={!allowPatientSelection && !!patient}\n            onChange={(value) => {\n              setPatient(value ? createReference(value) : undefined);\n            }}\n          />\n        </Stack>\n\n        <Stack gap={0}>\n          <Text fw={500}>Practitioner (optional)</Text>\n          <Text c=\"dimmed\">Select one or more practitioners</Text>\n\n          <QuestionnaireForm\n            questionnaire={questionnaire}\n            questionnaireResponse={initialResponse}\n            excludeButtons={true}\n            onChange={(value: QuestionnaireResponse) => {\n              const references =\n                value.item?.[0].answer\n                  ?.map((item) => item.valueReference)\n                  .filter((ref): ref is Reference<Practitioner> => ref !== undefined) ?? [];\n              setPractitioners(references);\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) => setTopic(e.target.value)} />\n        </Stack>\n\n        <Button onClick={handleSubmit}>Next</Button>\n      </Stack>\n    </Modal>\n  );\n};\n\nconst questionnaire: Questionnaire = {\n  resourceType: 'Questionnaire',\n  status: 'active',\n  item: [\n    {\n      linkId: 'q1',\n      type: 'reference',\n      repeats: true,\n      extension: [\n        {\n          url: `${HTTP_HL7_ORG}/fhir/StructureDefinition/questionnaire-referenceResource`,\n          valueCodeableConcept: {\n            coding: [\n              {\n                system: `${HTTP_HL7_ORG}/fhir/fhir-types`,\n                display: 'Practitioner',\n                code: 'Practitioner',\n              },\n            ],\n          },\n        },\n      ],\n    },\n  ],\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 } from '@medplum/react-hooks';\nimport { IconTrash } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useEffect, useLayoutEffect, 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 onChangeRef = useRef(onChange);\n  useLayoutEffect(() => {\n    onChangeRef.current = onChange;\n  });\n\n  useEffect(() => {\n    function handleEndStroke(): void {\n      onChangeRef.current?.({\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('beginStroke', handleEndStroke);\n      }\n    };\n  }, [medplum, defaultValue, who]);\n\n  const clearSignature = (): void => {\n    if (signaturePadRef.current) {\n      signaturePadRef.current.clear();\n    }\n    onChangeRef.current?.(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    );\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, { passive: false });\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 _drawDot(point: BasicPoint, options: PointGroupOptions): void {\n    const ctx = this._ctx;\n    const width =\n      options.dotSize > 0\n        ? options.dotSize\n        : (options.minWidth + options.maxWidth) / 2;\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 _fromData(\n    pointGroups: PointGroup[],\n    drawCurve: SignaturePad['_drawCurve'],\n    drawDot: SignaturePad['_drawDot'],\n  ): void {\n    for (const group of pointGroups) {\n      const { points } = group;\n      const pointGroupOptions = this._getPointGroupOptions(group);\n\n      if (points.length > 1) {\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 {\n        this._reset(pointGroupOptions);\n\n        drawDot(points[0], pointGroupOptions);\n      }\n    }\n  }\n\n  public toSVG({ includeBackgroundColor = false, includeDataUrl = false }: 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\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 type { ComboboxItem } from '@mantine/core';\nimport { 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  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 { 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        defaultValue={currentAnswer || [typedValueToString(initialValue)]}\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\nfunction useValueSetOptions(valueSetUrl: string | undefined): [ValueSetExpansionContains[], boolean] {\n  const medplum = useMedplum();\n  const [valueSetOptions, setValueSetOptions] = useState<ValueSetExpansionContains[]>([]);\n  const [isLoading, setIsLoading] = useState(false);\n\n  useEffect(() => {\n    async function loadValueSet(): Promise<void> {\n      if (!valueSetUrl) {\n        return;\n      }\n\n      setIsLoading(true);\n      try {\n        const options = await getValueSetOptions(valueSetUrl, medplum);\n        setValueSetOptions(options);\n      } catch (err) {\n        console.error('Error loading value set:', err);\n      } finally {\n        setIsLoading(false);\n      }\n    }\n\n    loadValueSet().catch(console.error);\n  }, [valueSetUrl, medplum]);\n\n  return [valueSetOptions, isLoading];\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 [valueSetOptions, isLoading] = 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 <NoAnswerDisplay />;\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 [valueSetOptions, isLoading] = useValueSetOptions(item.answerValueSet);\n\n  // Get initial values from response\n  const initialSelectedValues = item.answerValueSet\n    ? (response?.answer?.map((a) => a.valueCoding) || []).filter((c): c is Coding => c !== undefined)\n    : getCurrentMultiSelectAnswer(response);\n\n  const [selectedValues, setSelectedValues] = useState(initialSelectedValues);\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 <NoAnswerDisplay />;\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      setSelectedValues(newCodings);\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      setSelectedValues(newValues);\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", "// 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\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({\n        title: 'Error',\n        message: normalizeErrorString(error),\n        color: 'red',\n      });\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 {\n  ActionIcon,\n  Box,\n  Button,\n  Center,\n  Divider,\n  Flex,\n  Group,\n  Menu,\n  Pagination,\n  Paper,\n  ScrollArea,\n  Skeleton,\n  Stack,\n  Tabs,\n  Text,\n  ThemeIcon,\n  Tooltip,\n} from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport type { SearchRequest } from '@medplum/core';\nimport { getReferenceString, normalizeErrorString, Operator, parseSearchRequest } from '@medplum/core';\nimport type { Communication, DocumentReference, Patient, Practitioner, Reference } from '@medplum/fhirtypes';\nimport { useMedplumNavigate, useThreadInbox } from '@medplum/react-hooks';\nimport { IconChevronDown, IconMessageCircle, IconPlus } from '@tabler/icons-react';\nimport type { JSX } from 'react';\nimport { useCallback, useEffect, useMemo } from 'react';\nimport { PatientSummary } from '../../PatientSummary/PatientSummary';\nimport type { PatientSummarySectionConfig } from '../../PatientSummary/PatientSummary.types';\nimport { ThreadChat } from '../ThreadChat/ThreadChat';\nimport { ChatList } from './ChatList';\nimport { NewTopicDialog } from './NewTopicDialog';\nimport { ParticipantFilter } from './ParticipantFilter';\nimport classes from './ThreadInbox.module.css';\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 onNew - A function to handle a new thread.\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 */\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 onNew: (message: 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}\n\nexport function ThreadInbox(props: ThreadInboxProps): JSX.Element {\n  const {\n    query,\n    threadId,\n    subject,\n    showPatientSummary = false,\n    sections,\n    onNew,\n    getThreadUri,\n    uploadEnabled,\n    onViewInDocuments,\n    onChange,\n    inProgressUri,\n    completedUri,\n    allowPatientSelection = false,\n  } = props;\n\n  const navigate = useMedplumNavigate();\n  const [modalOpened, { open: openModal, close: closeModal }] = 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 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  const skeletonTitleWidths = [80, 72, 68, 64];\n  const skeletonSubtitleWidths = [85, 78, 70, 60];\n\n  useEffect(() => {\n    if (error) {\n      showNotification({\n        title: 'Error',\n        message: normalizeErrorString(error),\n        color: 'red',\n      });\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({\n        title: 'Error',\n        message: normalizeErrorString(error),\n        color: 'red',\n      });\n    }\n  };\n\n  const handleNewTopicCompletion = (message: Communication): void => {\n    addThreadMessage(message);\n    onNew(message);\n  };\n\n  return (\n    <>\n      <div className={classes.container}>\n        <Flex direction=\"row\" h=\"100%\" w=\"100%\">\n          {/* Left sidebar - Messages list */}\n          <Flex direction=\"column\" w={380} h=\"100%\" className={classes.rightBorder}>\n            <Paper h=\"100%\" style={{ display: 'flex', flexDirection: 'column' }}>\n              <ScrollArea style={{ flex: 1 }} scrollbarSize={10} type=\"hover\" scrollHideDelay={250}>\n                <Flex h={64} align=\"center\" justify=\"space-between\" p=\"md\">\n                  <Tabs\n                    value={status}\n                    onChange={(value) => {\n                      navigate(value === 'in-progress' ? inProgressUri : completedUri);\n                    }}\n                    variant=\"unstyled\"\n                    className=\"pill-tabs\"\n                  >\n                    <Tabs.List>\n                      <Tabs.Tab value=\"in-progress\">In Progress</Tabs.Tab>\n                      <Tabs.Tab value=\"completed\">Completed</Tabs.Tab>\n                    </Tabs.List>\n                  </Tabs>\n                  <Group gap=\"xs\">\n                    <ParticipantFilter\n                      selectedParticipants={selectedParticipants}\n                      onFilterChange={handleParticipantsChange}\n                    />\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                  </Group>\n                </Flex>\n                <Divider />\n                {loading ? (\n                  <Stack gap=\"md\" p=\"md\">\n                    {Array.from({ length: 10 }).map((_, index) => {\n                      const titleWidth = skeletonTitleWidths[index % skeletonTitleWidths.length];\n                      const subtitleWidth = skeletonSubtitleWidths[index % skeletonSubtitleWidths.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                  threadMessages.length > 0 && (\n                    <ChatList\n                      threads={threadMessages}\n                      selectedCommunication={selectedThread}\n                      getThreadUri={getThreadUri}\n                    />\n                  )\n                )}\n                {threadMessages.length === 0 && !loading && <EmptyMessagesState />}\n              </ScrollArea>\n              {!loading && total !== undefined && total > itemsPerPage && (\n                <Box p=\"md\">\n                  <Center>\n                    <Pagination\n                      value={currentPage}\n                      total={Math.ceil(total / itemsPerPage)}\n                      onChange={(page) => {\n                        const offset = (page - 1) * itemsPerPage;\n                        onChange({\n                          ...currentSearch,\n                          offset,\n                        });\n                      }}\n                      size=\"sm\"\n                      siblings={1}\n                      boundaries={1}\n                    />\n                  </Center>\n                </Box>\n              )}\n            </Paper>\n          </Flex>\n\n          {selectedThread ? (\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                        {selectedThread.topic?.text ?? 'Messages'}\n                      </Text>\n\n                      <Menu position=\"bottom-end\" shadow=\"md\">\n                        <Menu.Target>\n                          <Button\n                            variant=\"light\"\n                            color={getStatusColor(selectedThread.status)}\n                            rightSection={\n                              selectedThread.status === 'completed' ? undefined : <IconChevronDown size={16} />\n                            }\n                            radius=\"xl\"\n                            size=\"sm\"\n                          >\n                            {selectedThread.status\n                              .split('-')\n                              .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n                              .join(' ')}\n                          </Button>\n                        </Menu.Target>\n\n                        {selectedThread.status !== 'completed' && (\n                          <Menu.Dropdown>\n                            <Menu.Item onClick={() => handleTopicStatusChangeWithErrorHandling('completed')}>\n                              Completed\n                            </Menu.Item>\n                          </Menu.Dropdown>\n                        )}\n                      </Menu>\n                    </Flex>\n                    <Divider />\n                    <Flex direction=\"column\" style={{ flex: 1 }} h=\"100%\">\n                      <ThreadChat\n                        key={`${getReferenceString(selectedThread)}`}\n                        title={'Messages'}\n                        thread={selectedThread}\n                        excludeHeader={true}\n                        uploadEnabled={uploadEnabled}\n                        onViewInDocuments={onViewInDocuments}\n                      />\n                    </Flex>\n                  </Stack>\n                </Paper>\n              </Flex>\n\n              {/* Right sidebar - Patient summary */}\n              {selectedThread.subject && showPatientSummary && (\n                <Flex direction=\"column\" w={300} h=\"100%\">\n                  <ScrollArea p={0} h=\"100%\" scrollbarSize={10} type=\"hover\" scrollHideDelay={250}>\n                    <PatientSummary\n                      key={selectedThread.id}\n                      patient={selectedThread.subject as Reference<Patient>}\n                      sections={sections}\n                    />\n                  </ScrollArea>\n                </Flex>\n              )}\n            </>\n          ) : (\n            <Flex direction=\"column\" style={{ flex: 1 }} h=\"100%\">\n              <NoMessages />\n            </Flex>\n          )}\n        </Flex>\n      </div>\n      <NewTopicDialog\n        subject={subject}\n        opened={modalOpened}\n        onClose={closeModal}\n        onSubmit={handleNewTopicCompletion}\n        allowPatientSelection={allowPatientSelection}\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 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\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", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Divider, Flex, Group, Stack, Text, Tooltip } from '@mantine/core';\nimport { formatHumanName, resolveId } from '@medplum/core';\nimport type { Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, usePatientSummaryData, useResource } from '@medplum/react-hooks';\nimport type { JSX } from 'react';\nimport { useEffect, useMemo, useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport styles from './PatientSummary.module.css';\nimport type { PatientSummarySectionConfig } from './PatientSummary.types';\nimport { getDefaultSections } from './sectionConfigs';\nimport SummaryItem from './SummaryItem';\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}\n\nexport function PatientSummary(props: PatientSummaryProps): JSX.Element | null {\n  const medplum = useMedplum();\n  const { patient: propsPatient, onClickResource, onRequestLabs } = props;\n  const patient = useResource(propsPatient);\n  const [createdDate, setCreatedDate] = useState<string | undefined>();\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 } = usePatientSummaryData(propsPatient, sections);\n\n  useEffect(() => {\n    const id = resolveId(propsPatient);\n    if (id) {\n      medplum\n        .readHistory('Patient', id)\n        .then((history) => {\n          const firstEntry = history.entry?.[history.entry.length - 1];\n          const lastUpdated = firstEntry?.resource?.meta?.lastUpdated;\n          setCreatedDate(typeof lastUpdated === 'string' ? lastUpdated : '');\n        })\n        .catch(() => {});\n    }\n  }, [propsPatient, medplum]);\n\n  if (!patient) {\n    return null;\n  }\n\n  return (\n    <Flex direction=\"column\" gap=\"xs\" w=\"100%\" h=\"100%\" className={styles.panel}>\n      <SummaryItem\n        onClick={() => {\n          onClickResource?.(patient);\n        }}\n      >\n        <Group align=\"center\" gap=\"sm\" p={16}>\n          <ResourceAvatar value={patient} size={48} radius={48} style={{ border: '2px solid white' }} />\n          <Stack gap={0} style={{ flex: 1, minWidth: 0 }}>\n            <Tooltip label={formatHumanName(patient.name?.[0])} position=\"top-start\" openDelay={650}>\n              <Text fz=\"h4\" fw={800} truncate style={{ minWidth: 0 }}>\n                {formatHumanName(patient.name?.[0])}\n              </Text>\n            </Tooltip>\n            {(() => {\n              const dateString = typeof createdDate === 'string' && createdDate.length > 0 ? createdDate : undefined;\n              if (!dateString) {\n                return null;\n              }\n              const d = new Date(dateString);\n              return (\n                <Text fz=\"xs\" mt={-2} fw={500} c=\"gray.6\" truncate style={{ minWidth: 0 }}>\n                  Patient since {d.getMonth() + 1}/{d.getDate()}/{d.getFullYear()}\n                </Text>\n              );\n            })()}\n          </Stack>\n        </Group>\n        <Divider />\n      </SummaryItem>\n\n      <Stack gap=\"xs\" px={16} pt={12} 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          <>\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                    results={sectionData[index] ?? {}}\n                  />\n                  <Divider />\n                </div>\n              );\n            })}\n          </>\n        )}\n      </Stack>\n    </Flex>\n  );\n}\n", ".panel {\n  height: 100%;\n}\n\n[data-mantine-color-scheme='dark'] .panel {\n  background-color: var(--mantine-color-dark-8);\n}\n\n[data-mantine-color-scheme='light'] .panel {\n  background-color: var(--mantine-color-white);\n}\n\n.patientSummaryBadge {\n  cursor: pointer;\n}\n\n.patientSummaryAddButton {\n  opacity: 0;\n  transition: opacity 0.2s;\n  position: absolute;\n  right: 0;\n  top: 0;\n  transform: none;\n  stroke-width: 1;\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  MedicationRequest,\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 { 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 }: SectionRenderContext) => {\n    const languageDisplay = getPreferredLanguage(patient);\n    return (\n      <Stack gap=\"xs\" py={8}>\n        <PatientInfoItem\n          patient={patient}\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          onClickResource={onClickResource}\n        />\n        <PatientInfoItem\n          patient={patient}\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          onClickResource={onClickResource}\n        />\n        <PatientInfoItem\n          patient={patient}\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          onClickResource={onClickResource}\n        />\n        <PatientInfoItem\n          patient={patient}\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          onClickResource={onClickResource}\n        />\n        <PatientInfoItem\n          patient={patient}\n          value={languageDisplay}\n          icon={<IconLanguage size={16} stroke={2} color=\"var(--mantine-color-gray-6)\" />}\n          placeholder=\"Add Language\"\n          label=\"Language\"\n          onClickResource={onClickResource}\n        />\n        <PatientInfoItem\n          patient={patient}\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          onClickResource={onClickResource}\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 resources. */\nexport const MedicationsSection: PatientSummarySectionConfig = {\n  key: 'medications',\n  title: 'Medications',\n  searches: [{ key: 'medications', resourceType: 'MedicationRequest', patientParam: 'subject' }],\n  component: ({ results, patient, onClickResource }: SectionRenderContext) => (\n    <Medications\n      patient={patient}\n      medicationRequests={(results['medications'] as MedicationRequest[]) || []}\n      onClickResource={onClickResource}\n    />\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    createLabsSection(onRequestLabs),\n    SexualOrientationSection,\n    SmokingStatusSection,\n    VitalsSection,\n    PharmaciesSection,\n  ];\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Box, Flex, Group, Modal, 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 { 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}>\n      <Group justify=\"space-between\" className={classes.header}>\n        <Group gap={8}>\n          <ActionIcon\n            variant=\"subtle\"\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            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}\n\n.chevron[data-collapsed] {\n  transform: rotate(-90deg);\n}\n\n.title {\n  cursor: pointer;\n}\n\n.addButton {\n  position: absolute;\n  right: 0;\n  top: 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 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={styles.item} onClick={onClick}>\n      {children}\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    </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-dark-8));\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-dark-8);\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.item:hover .gradient,\n.item:hover .container {\n  opacity: 1;\n  pointer-events: auto;\n}\n\n.item {\n  position: relative;\n  max-width: 100%;\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 { 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, Modal, 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 { 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} 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 { Group, List, Stack, Text, Title } from '@mantine/core';\nimport { formatCodeableConcept, formatDateTime, formatObservationValue, isReference } from '@medplum/core';\nimport type {\n  Annotation,\n  DiagnosticReport,\n  Observation,\n  ObservationComponent,\n  ObservationReferenceRange,\n  Reference,\n  Specimen,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport type { JSX } from 'react';\nimport { useEffect, useState } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\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    </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  return (\n    <Group mt=\"md\" gap={30}>\n      {value.subject && !hideSubject && (\n        <div>\n          <Text size=\"xs\" tt=\"uppercase\" c=\"dimmed\">\n            Subject\n          </Text>\n          <ResourceBadge value={value.subject} link={true} />\n        </div>\n      )}\n      {value.resultsInterpreter?.map((interpreter) => (\n        <div key={interpreter.reference}>\n          <Text size=\"xs\" tt=\"uppercase\" c=\"dimmed\">\n            Interpreter\n          </Text>\n          <ResourceBadge value={interpreter} link={true} />\n        </div>\n      ))}\n      {value.performer?.map((performer) => (\n        <div key={performer.reference}>\n          <Text size=\"xs\" tt=\"uppercase\" c=\"dimmed\">\n            Performer\n          </Text>\n          <ResourceBadge value={performer} link={true} />\n        </div>\n      ))}\n      {value.issued && (\n        <div>\n          <Text size=\"xs\" tt=\"uppercase\" c=\"dimmed\">\n            Issued\n          </Text>\n          <Text>{formatDateTime(value.issued)}</Text>\n        </div>\n      )}\n      {value.status && (\n        <div>\n          <Text size=\"xs\" tt=\"uppercase\" c=\"dimmed\">\n            Status\n          </Text>\n          <StatusBadge status={value.status} />\n        </div>\n      )}\n    </Group>\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  const displayNotes = !props.hideObservationNotes && observation.note;\n\n  const critical = isCritical(observation);\n\n  return (\n    <>\n      <tr className={cx({ [classes.criticalRow]: critical })}>\n        <td rowSpan={displayNotes ? 2 : 1}>\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            <ReferenceDisplay key={performer.reference} value={performer} />\n          ))}\n        </td>\n        <td>{observation.status && <StatusBadge status={observation.status} />}</td>\n      </tr>\n      {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      {displayNotes && (\n        <tr>\n          <td colSpan={6}>\n            <NoteDisplay value={observation.note} />\n          </td>\n        </tr>\n      )}\n    </>\n  );\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 * 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  return code === 'AA' || code === 'LL' || code === 'HH' || code === 'A';\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}\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\n.criticalRow {\n  background: light-dark(var(--mantine-color-red-1), var(--mantine-color-red-7));\n  border: 0.1px solid var(--mantine-color-red-5);\n  color: var(--mantine-color-red-5);\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, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { getDisplayString } from '@medplum/core';\nimport type { Encounter, MedicationRequest, 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 { MedicationDialog } from './MedicationDialog';\nimport SummaryItem from './SummaryItem';\nimport styles from './SummaryItem.module.css';\n\nexport interface MedicationsProps {\n  readonly patient: Patient;\n  readonly encounter?: Encounter;\n  readonly medicationRequests: MedicationRequest[];\n  readonly onClickResource?: (resource: MedicationRequest) => 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\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        {medicationRequests.length > 0 ? (\n          <Flex direction=\"column\" gap={8}>\n            {medicationRequests.map((medication) => (\n              <SummaryItem\n                key={medication.id}\n                onClick={() => {\n                  setEditMedication(medication);\n                  open();\n                }}\n              >\n                <Box>\n                  <Text fw={500} className={styles.itemText}>\n                    {getDisplayString(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", "// 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 { Patient } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport styles from './PatientSummary.module.css';\nimport SummaryItem from './SummaryItem';\n\nexport interface PatientInfoItemProps {\n  patient: Patient;\n  value: string | undefined;\n  icon: React.ReactNode;\n  placeholder: string;\n  label: string;\n  onClickResource?: (patient: Patient) => void;\n}\n\nexport const PatientInfoItem = (props: PatientInfoItemProps): JSX.Element => {\n  const { patient, value, icon, placeholder, label, onClickResource } = props;\n  const displayText = value || placeholder;\n\n  return (\n    <SummaryItem\n      onClick={() => {\n        onClickResource?.(patient);\n      }}\n    >\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={{ cursor: 'pointer', 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 { capitalize, getExtension, HTTP_HL7_ORG } from '@medplum/core';\nimport type { Patient } from '@medplum/fhirtypes';\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\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, Loader, Modal, 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 { 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, Modal, 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 { 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, Group, Modal, Radio, Stack, 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 { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\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 opened={opened} onClose={close} title=\"Set Sexual Orientation\">\n        <Form onSubmit={handleSubmit}>\n          <Stack>\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            <Group justify=\"flex-end\" gap={4} mt=\"md\">\n              <SubmitButton>Save</SubmitButton>\n            </Group>\n          </Stack>\n        </Form>\n      </Modal>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Modal, Radio, Stack, 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 { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\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 opened={opened} onClose={close} title=\"Set Smoking Status\">\n        <Form onSubmit={handleSubmit}>\n          <Stack>\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            <Group justify=\"flex-end\" gap={4} mt=\"md\">\n              <SubmitButton>Save</SubmitButton>\n            </Group>\n          </Stack>\n        </Form>\n      </Modal>\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { Group, Modal, 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 { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\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 opened={opened} onClose={close} title=\"Add Vitals\">\n        <Form onSubmit={handleSubmit}>\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          <Group justify=\"flex-end\" gap={4} mt=\"md\">\n            <SubmitButton>Save</SubmitButton>\n          </Group>\n        </Form>\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", ".container {\n  height: 100%;\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n  flex: 1;\n}\n\n.rightBorder {\n  border-right: 1px solid light-dark(var(--mantine-color-gray-3), var(--mantine-color-gray-8));\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Button, Center, Group, Loader, 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 } 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 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    },\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).then(handleBatchResponse).catch(console.error);\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      <Center style={{ width: '100%', height: '100%' }}>\n        <Loader />\n      </Center>\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      {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\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, TypedValue } from '@medplum/core';\nimport { arrayify, capitalize, evalFhirPathTyped, getSearchParameterDetails, toTypedValue } 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 type { Operation } from 'rfc6902';\nimport { createPatch } from 'rfc6902';\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) {\n    return input;\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, 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>{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", ".item {\n  white-space: pre-wrap;\n}\n\n.itemPadding {\n  padding: 0 16px 16px 16px;\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 * 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", ".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 { 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    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  Group,\n  Loader,\n  Menu,\n  Pagination,\n  Table,\n  Text,\n  UnstyledButton,\n} from '@mantine/core';\nimport type { Filter, SearchRequest } from '@medplum/core';\nimport {\n  DEFAULT_SEARCH_COUNT,\n  deepEquals,\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  IconAdjustmentsHorizontal,\n  IconBoxMultiple,\n  IconColumns,\n  IconFilePlus,\n  IconFilter,\n  IconRefresh,\n  IconTableExport,\n  IconTrash,\n} from '@tabler/icons-react';\nimport type { ChangeEvent, JSX, MouseEvent } from 'react';\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport { Container } from '../Container/Container';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\nimport { SearchExportDialog } from '../SearchExportDialog/SearchExportDialog';\nimport { SearchFieldEditor } from '../SearchFieldEditor/SearchFieldEditor';\nimport { SearchFilterEditor } from '../SearchFilterEditor/SearchFilterEditor';\nimport { SearchFilterValueDialog } from '../SearchFilterValueDialog/SearchFilterValueDialog';\nimport { SearchFilterValueDisplay } from '../SearchFilterValueDisplay/SearchFilterValueDisplay';\nimport { SearchPopupMenu } from '../SearchPopupMenu/SearchPopupMenu';\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, 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\nexport interface SearchControlProps {\n  readonly search: SearchRequest;\n  readonly checkboxesEnabled?: boolean;\n  readonly hideToolbar?: boolean;\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  readonly onDelete?: (ids: string[]) => void;\n  readonly onBulk?: (ids: string[]) => void;\n}\n\ninterface SearchControlState {\n  readonly searchResponse?: Bundle;\n  readonly selected: { [id: string]: boolean };\n  readonly fieldEditorVisible: boolean;\n  readonly filterEditorVisible: boolean;\n  readonly filterDialogVisible: boolean;\n  readonly exportDialogVisible: boolean;\n  readonly filterDialogFilter?: Filter;\n  readonly filterDialogSearchParam?: SearchParameter;\n  readonly dialogOpenTime?: number;\n}\n\n/**\n * The SearchControl component represents the embeddable search table control.\n * It includes the table, rows, headers, sorting, etc.\n * It does not include the field editor, filter editor, pagination buttons.\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\n  const [memoizedSearch, setMemoizedSearch] = useState(search);\n\n  if (!deepEquals(search, memoizedSearch)) {\n    setMemoizedSearch(search);\n  }\n\n  const [state, setState] = useState<SearchControlState>({\n    selected: {},\n    fieldEditorVisible: false,\n    filterEditorVisible: false,\n    exportDialogVisible: false,\n    filterDialogVisible: false,\n  });\n\n  const stateRef = useRef(state);\n  useLayoutEffect(() => {\n    stateRef.current = state;\n  });\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({ ...stateRef.current, searchResponse: response });\n          if (onLoad) {\n            onLoad(new SearchLoadEvent(response));\n          }\n        })\n        .catch((reason) => {\n          setState({ ...stateRef.current, searchResponse: undefined });\n          setOutcome(normalizeOperationOutcome(reason));\n        });\n    },\n    [medplum, memoizedSearch, total, onLoad]\n  );\n\n  const refreshResults = useCallback(() => {\n    setState({ ...stateRef.current, searchResponse: undefined });\n    loadResults({ cache: 'reload' });\n  }, [loadResults]);\n\n  useEffect(() => {\n    loadResults();\n  }, [loadResults]);\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 = { ...stateRef.current.selected };\n    if (checked) {\n      newSelected[id] = true;\n    } else {\n      delete newSelected[id];\n    }\n    setState({ ...stateRef.current, selected: 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 searchResponse = stateRef.current.searchResponse;\n    if (checked && searchResponse?.entry) {\n      searchResponse.entry.forEach((entry) => {\n        if (entry.resource?.id) {\n          newSelected[entry.resource.id] = true;\n        }\n      });\n    }\n    setState({ ...stateRef.current, selected: newSelected });\n  }\n\n  function isAllSelected(): boolean {\n    if (!state.searchResponse?.entry || state.searchResponse.entry.length === 0) {\n      return false;\n    }\n    for (const e of state.searchResponse.entry) {\n      if (e.resource?.id && !state.selected[e.resource.id]) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  /**\n   * Emits a change event to the optional change listener.\n   * @param newSearch - The new search definition.\n   */\n  function emitSearchChange(newSearch: SearchRequest): void {\n    if (props.onChange) {\n      props.onChange(new SearchChangeEvent(newSearch));\n    }\n  }\n\n  /**\n   * Handles a click on a order row.\n   * @param e - The click event.\n   * @param resource - The FHIR resource.\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    if (e.button === 2) {\n      // Ignore right clicks\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  function isExportPassed(): boolean {\n    return !!(props.onExport ?? props.onExportCsv ?? props.onExportTransactionBundle);\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 buttonVariant = 'subtle';\n  const buttonColor = 'gray';\n  const iconSize = 16;\n  const isMobile = window.innerWidth < 768;\n\n  return (\n    <div className={classes.root} data-testid=\"search-control\">\n      {!props.hideToolbar && (\n        <Group justify=\"space-between\" mb=\"xl\">\n          <Group gap={2}>\n            <Button\n              size=\"compact-md\"\n              variant={buttonVariant}\n              color={buttonColor}\n              leftSection={<IconColumns size={iconSize} />}\n              onClick={() => setState({ ...stateRef.current, fieldEditorVisible: true, dialogOpenTime: Date.now() })}\n            >\n              Fields\n            </Button>\n            <Button\n              size=\"compact-md\"\n              variant={buttonVariant}\n              color={buttonColor}\n              leftSection={<IconFilter size={iconSize} />}\n              onClick={() => setState({ ...stateRef.current, filterEditorVisible: true, dialogOpenTime: Date.now() })}\n            >\n              Filters\n            </Button>\n            {props.onNew && (\n              <Button\n                size=\"compact-md\"\n                variant={buttonVariant}\n                color={buttonColor}\n                leftSection={<IconFilePlus size={iconSize} />}\n                onClick={props.onNew}\n              >\n                New...\n              </Button>\n            )}\n            {!isMobile && isExportPassed() && (\n              <Button\n                size=\"compact-md\"\n                variant={buttonVariant}\n                color={buttonColor}\n                leftSection={<IconTableExport size={iconSize} />}\n                onClick={\n                  props.onExport\n                    ? props.onExport\n                    : () => setState({ ...stateRef.current, exportDialogVisible: true, dialogOpenTime: Date.now() })\n                }\n              >\n                Export...\n              </Button>\n            )}\n            {!isMobile && props.onDelete && (\n              <Button\n                size=\"compact-md\"\n                variant={buttonVariant}\n                color={buttonColor}\n                leftSection={<IconTrash size={iconSize} />}\n                onClick={() => (props.onDelete as (ids: string[]) => any)(Object.keys(state.selected))}\n              >\n                Delete...\n              </Button>\n            )}\n            {!isMobile && props.onBulk && (\n              <Button\n                size=\"compact-md\"\n                variant={buttonVariant}\n                color={buttonColor}\n                leftSection={<IconBoxMultiple size={iconSize} />}\n                onClick={() => (props.onBulk as (ids: string[]) => any)(Object.keys(state.selected))}\n              >\n                Bulk...\n              </Button>\n            )}\n          </Group>\n          <Group gap={2}>\n            {lastResult && (\n              <Text size=\"xs\" c=\"dimmed\" 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            <ActionIcon variant={buttonVariant} color={buttonColor} title=\"Refresh\" onClick={refreshResults}>\n              <IconRefresh size={iconSize} />\n            </ActionIcon>\n          </Group>\n        </Group>\n      )}\n      <Table className={classes.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}>\n                <Menu shadow=\"md\" width={240} position=\"bottom-end\">\n                  <Menu.Target>\n                    <UnstyledButton className={classes.control} p={2}>\n                      <Group justify=\"space-between\" wrap=\"nowrap\">\n                        <Text fw={500}>{buildFieldNameString(field.name)}</Text>\n                        <Center className={classes.icon}>\n                          <IconAdjustmentsHorizontal size={14} stroke={1.5} />\n                        </Center>\n                      </Group>\n                    </UnstyledButton>\n                  </Menu.Target>\n                  <SearchPopupMenu\n                    search={memoizedSearch}\n                    searchParams={field.searchParams}\n                    onPrompt={(searchParam, filter) => {\n                      setState({\n                        ...stateRef.current,\n                        filterDialogVisible: true,\n                        filterDialogSearchParam: searchParam,\n                        filterDialogFilter: filter,\n                        dialogOpenTime: Date.now(),\n                      });\n                    }}\n                    onChange={(result) => {\n                      emitSearchChange(result);\n                    }}\n                  />\n                </Menu>\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            </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                  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={!!state.selected[resource.id as string]}\n                        onChange={(e) => handleSingleCheckboxClick(e, resource.id as string)}\n                      />\n                    </Table.Td>\n                  )}\n                  {fields.map((field) => (\n                    <Table.Td key={field.name}>{renderValue(resource, field)}</Table.Td>\n                  ))}\n                </Table.Tr>\n              )\n          )}\n        </Table.Tbody>\n      </Table>\n      {!resources?.length && (\n        <Container>\n          <Center style={{ height: 150 }}>\n            <Text size=\"xl\" c=\"dimmed\">\n              No results\n            </Text>\n          </Center>\n        </Container>\n      )}\n      {lastResult && (\n        <Center m=\"md\" p=\"md\">\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({\n            ...stateRef.current,\n            fieldEditorVisible: false,\n          });\n        }}\n        onCancel={() => {\n          setState({\n            ...stateRef.current,\n            fieldEditorVisible: false,\n          });\n        }}\n      />\n      <SearchFilterEditor\n        key={`search-filter-editor-${state.dialogOpenTime}`}\n        search={memoizedSearch}\n        visible={state.filterEditorVisible}\n        onOk={(result) => {\n          emitSearchChange(result);\n          setState({\n            ...stateRef.current,\n            filterEditorVisible: false,\n          });\n        }}\n        onCancel={() => {\n          setState({\n            ...stateRef.current,\n            filterEditorVisible: false,\n          });\n        }}\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({\n            ...stateRef.current,\n            exportDialogVisible: false,\n          });\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({\n            ...stateRef.current,\n            filterDialogVisible: false,\n          });\n        }}\n        onCancel={() => {\n          setState({\n            ...stateRef.current,\n            filterDialogVisible: false,\n          });\n        }}\n      />\n    </div>\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 <span>no filters</span>;\n  }\n\n  return (\n    <>\n      {filters.map((filter: Filter) => (\n        <div key={`filter-${filter.code}-${filter.operator}-${filter.value}`}>\n          {getOpString(filter.operator)}\n          &nbsp;\n          <SearchFilterValueDisplay resourceType={props.resourceType} filter={filter} />\n        </div>\n      ))}\n    </>\n  );\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 { Box, Button, Modal, Text } from '@mantine/core';\nimport type { JSX } from 'react';\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  return (\n    <Modal title=\"Export\" closeButtonProps={{ 'aria-label': 'Close' }} opened={props.visible} onClose={props.onCancel}>\n      <Box display=\"flex\" style={{ justifyContent: 'space-between' }}>\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      </Box>\n      <Text style={{ marginTop: '10px', marginLeft: '2px' }}>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, Modal, MultiSelect, Stack } 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 { 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      closeButtonProps={{ 'aria-label': 'Close' }}\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    >\n      <Stack>\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        <Group justify=\"flex-end\">\n          <Button onClick={() => props.onOk(state.search)}>OK</Button>\n        </Group>\n      </Stack>\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 { Filter, InternalSchemaElement, SearchRequest } from '@medplum/core';\nimport { capitalize, DEFAULT_SEARCH_COUNT, evalFhirPathTyped, formatDateTime, Operator } from '@medplum/core';\nimport type { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport type { JSX } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport type { SearchControlField } from './SearchControlField';\n\nconst searchParamToOperators: Record<string, 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  numeric: [\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\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 as string];\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 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  // 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 * 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    <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 * 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        <ResourcePropertyDisplay\n          key={`${index}-${value.length}`}\n          propertyType={v.type}\n          value={v.value}\n          maxWidth={200}\n          ignoreMissingValues={true}\n          link={false}\n        />\n      ))}\n    </>\n  );\n}\n", "// SPDX-FileCopyrightText: Copyright Orangebot, Inc. and Medplum contributors\n// SPDX-License-Identifier: Apache-2.0\nimport { ActionIcon, Group, Modal, 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 { Form } from '../Form/Form';\nimport { SubmitButton } from '../Form/SubmitButton';\nimport {\n  addFilter,\n  buildFieldNameString,\n  deleteFilter,\n  getOpString,\n  getSearchOperators,\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      closeButtonProps={{ 'aria-label': 'Close' }}\n      size={900}\n      opened={props.visible}\n      onClose={props.onCancel}\n    >\n      <Form onSubmit={() => props.onOk(searchRef.current)}>\n        <div>\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        </div>\n        <Group justify=\"flex-end\" mt=\"xl\">\n          <SubmitButton>OK</SubmitButton>\n        </Group>\n      </Form>\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  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            ...Object.keys(props.searchParams).map((param) => ({ value: param, label: buildFieldNameString(param) })),\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 { 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  readonly defaultValue?: string;\n  readonly autoFocus?: 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          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          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          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          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          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\nimport { Button, Grid, Modal } 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 { Form } from '../Form/Form';\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 title={props.title} size=\"xl\" opened={props.visible} onClose={props.onCancel}>\n      <Form onSubmit={onOk}>\n        <Grid>\n          <Grid.Col span={10}>\n            <SearchFilterValueInput\n              resourceType={props.resourceType}\n              searchParam={props.searchParam}\n              defaultValue={value}\n              autoFocus={true}\n              onChange={setValue}\n            />\n          </Grid.Col>\n          <Grid.Col span={2}>\n            <Button onClick={onOk} fullWidth>\n              OK\n            </Button>\n          </Grid.Col>\n        </Grid>\n      </Form>\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  IconCalendar,\n  IconEqual,\n  IconEqualNot,\n  IconMathGreater,\n  IconMathLower,\n  IconSettings,\n  IconSortAscending,\n  IconSortDescending,\n  IconX,\n} from '@tabler/icons-react';\nimport type { JSX } from 'react';\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\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 there is only one search parameter, then show it directly\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  // Otherwise, show a menu, with each search parameter as a sub menu\n  return (\n    <Menu.Dropdown>\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\nfunction DateFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  const code = searchParam.code;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconSortAscending size={14} />} onClick={() => props.onSort(searchParam, false)}>\n        Sort Oldest to Newest\n      </Menu.Item>\n      <Menu.Item leftSection={<IconSortDescending size={14} />} onClick={() => props.onSort(searchParam, true)}>\n        Sort Newest to Oldest\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconEqualNot size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.NOT_EQUALS)}\n      >\n        Does not equal...\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item\n        leftSection={<IconMathLower size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.ENDS_BEFORE)}\n      >\n        Before...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconMathGreater size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.STARTS_AFTER)}\n      >\n        After...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconBracketsContain size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}\n      >\n        Between...\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addTomorrowFilter(props.search, code))}\n      >\n        Tomorrow\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addTodayFilter(props.search, code))}\n      >\n        Today\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addYesterdayFilter(props.search, code))}\n      >\n        Yesterday\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addNext24HoursFilter(props.search, code))}\n      >\n        Next 24 Hours\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addNextMonthFilter(props.search, code))}\n      >\n        Next Month\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addThisMonthFilter(props.search, code))}\n      >\n        This Month\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addLastMonthFilter(props.search, code))}\n      >\n        Last Month\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item\n        leftSection={<IconCalendar size={14} />}\n        onClick={() => props.onChange(addYearToDateFilter(props.search, code))}\n      >\n        Year to date\n      </Menu.Item>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction NumericFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconSortAscending size={14} />} onClick={() => props.onSort(searchParam, false)}>\n        Sort Smallest to Largest\n      </Menu.Item>\n      <Menu.Item leftSection={<IconSortDescending size={14} />} onClick={() => props.onSort(searchParam, true)}>\n        Sort Largest to Smallest\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconEqualNot size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.NOT_EQUALS)}\n      >\n        Does not equal...\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item\n        leftSection={<IconMathGreater size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.GREATER_THAN)}\n      >\n        Greater than...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconSettings size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.GREATER_THAN_OR_EQUALS)}\n      >\n        Greater than or equal to...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconMathLower size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.LESS_THAN)}\n      >\n        Less than...\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconSettings size={14} />}\n        onClick={() => props.onPrompt(searchParam, Operator.LESS_THAN_OR_EQUALS)}\n      >\n        Less than or equal to...\n      </Menu.Item>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction ReferenceFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item leftSection={<IconEqualNot size={14} />} onClick={() => props.onPrompt(searchParam, Operator.NOT)}>\n        Does not equal...\n      </Menu.Item>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction TextFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconSortAscending size={14} />} onClick={() => props.onSort(searchParam, false)}>\n        Sort A to Z\n      </Menu.Item>\n      <Menu.Item leftSection={<IconSortDescending size={14} />} onClick={() => props.onSort(searchParam, true)}>\n        Sort Z to A\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item leftSection={<IconEqualNot size={14} />} onClick={() => props.onPrompt(searchParam, Operator.NOT)}>\n        Does not equal...\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconBucket size={14} />} onClick={() => props.onPrompt(searchParam, Operator.CONTAINS)}>\n        Contains...\n      </Menu.Item>\n      <Menu.Item leftSection={<IconBucketOff size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Does not contain...\n      </Menu.Item>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction TokenFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item leftSection={<IconEqualNot size={14} />} onClick={() => props.onPrompt(searchParam, Operator.NOT)}>\n        Does not equal...\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.TEXT)}>\n        Text contains...\n      </Menu.Item>\n      <CommonMenuItems {...props} />\n    </Menu.Dropdown>\n  );\n}\n\nfunction UriFilterSubMenu(props: SearchPopupSubMenuProps): JSX.Element {\n  const { searchParam } = props;\n  return (\n    <Menu.Dropdown>\n      <Menu.Item leftSection={<IconEqual size={14} />} onClick={() => props.onPrompt(searchParam, Operator.EQUALS)}>\n        Equals...\n      </Menu.Item>\n      <Menu.Item leftSection={<IconEqualNot size={14} />} onClick={() => props.onPrompt(searchParam, Operator.NOT)}>\n        Does not equal...\n      </Menu.Item>\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      <Menu.Item\n        leftSection={<IconBleach size={14} />}\n        onClick={() => props.onChange(addMissingFilter(props.search, code))}\n      >\n        Missing\n      </Menu.Item>\n      <Menu.Item\n        leftSection={<IconBleachOff size={14} />}\n        onClick={() => props.onChange(addMissingFilter(props.search, code, false))}\n      >\n        Not missing\n      </Menu.Item>\n      <Menu.Divider />\n      <Menu.Item leftSection={<IconX size={14} />} onClick={() => props.onClear(searchParam)}>\n        Clear filters\n      </Menu.Item>\n    </>\n  );\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", ".root {\n  max-width: 100%;\n  overflow: auto;\n  text-align: left;\n  margin-bottom: 20px;\n}\n\n.table {\n  cursor: pointer;\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.th {\n  padding: 0 !important;\n}\n\n.control {\n  width: 100%;\n  padding: var(--mantine-spacing-xs) var(--mantine-spacing-md);\n\n  &:hover {\n    background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n  }\n}\n\n.icon {\n  width: 21px;\n  height: 21px;\n  border-radius: 21px;\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 } 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", ".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\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 { 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 } 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\n  const handleSubmit = useCallback(\n    async (data: Record<string, string>) => {\n      const patientId = resolveId(patient) as string;\n      const format = data.format;\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 (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]\n  );\n\n  return (\n    <Form onSubmit={handleSubmit}>\n      <Stack>\n        <FormSection title=\"Export Format\" description=\"Required\" withAsterisk>\n          <SegmentedControl\n            name=\"format\"\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        <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 } from 'react';\nimport { useCallback, useState } from 'react';\nimport styles from './PharmacyDialog.module.css';\n\nexport interface PharmacyDialogProps {\n  readonly patient: Patient;\n  readonly onSubmit: (pharmacy: Organization) => void;\n  readonly onClose: () => void;\n  readonly onSearch: (params: PharmacySearchParams) => Promise<Organization[]>;\n  readonly onAddToFavorites: (params: AddFavoriteParams) => Promise<AddPharmacyResponse>;\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}\n\nfunction SearchForm({ onSearch, searching }: 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=\"Enter pharmacy name (min 3 chars)\" />\n        <Group grow>\n          <TextInput name=\"city\" label=\"City\" placeholder=\"City (min 3 chars)\" />\n          <TextInput name=\"state\" label=\"State\" placeholder=\"State (min 3 chars)\" />\n        </Group>\n        <Group grow>\n          <TextInput name=\"zip\" label=\"Zip Code\" placeholder=\"Zip code (min 3 chars)\" />\n          <TextInput name=\"phoneOrFax\" label=\"Phone or Fax\" placeholder=\"Phone or fax number\" />\n        </Group>\n        <TextInput name=\"address\" label=\"Address\" placeholder=\"Street address (min 3 chars)\" />\n        <TextInput name=\"ncpdpID\" label=\"NCPDP ID\" placeholder=\"National Council for Prescription Drug Programs ID\" />\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 { patient, onSubmit, onClose, onSearch, onAddToFavorites } = props;\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      if (Object.keys(cleanParams).length === 0) {\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(cleanParams);\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    [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 onSearch={(formData) => handleSearch(formData).catch(console.error)} searching={searching} />\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 { 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", ".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 SILENCE_DEBOUNCE_MS = 3000;\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}\n\nexport function AIRealTimeQuestionnaireForm(props: AIRealTimeQuestionnaireFormProps): JSX.Element {\n  const { aiModel, onTranscript, voiceInstructions, ...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  }, 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 { 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: var(--mantine-color-gray-1);\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 { 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}\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      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      <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    </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-dom';\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", "/**\n * react-router-dom v7.17.0\n *\n * Copyright (c) Remix Software Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE.md file in the root directory of this source tree.\n *\n * @license MIT\n */\n\n// index.ts\nimport { HydratedRouter, RouterProvider } from \"react-router/dom\";\nexport * from \"react-router\";\nexport {\n  HydratedRouter,\n  RouterProvider\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: 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    // 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        const url = new URL(client.launchUri as string);\n        url.searchParams.set('iss', ensureTrailingSlash(medplum.fhirUrl().toString()));\n        url.searchParams.set('launch', result.id);\n        window.open(url.toString(), '_blank');\n      })\n      .catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err), autoClose: false }));\n  }\n\n  return (\n    <Anchor onClick={() => launchApp()} {...rest}>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AA0B,MAAM,EACtG,aACF,aAAe,CACb,GAAG,UACH,UACF,EAEJ,CACF,CAEA,QACG,eAA+B,CAC9B,aAAc,iBACd,QAAS,WACT,UAAW,aACX,YAAa,MAAM,WACrB,CAAC,EACA,KAAM,QAAW,CAChB,IAAM,IAAM,IAAI,IAAI,OAAO,SAAmB,EAC9C,IAAI,aAAa,IAAI,MAAO,oBAAoB,QAAQ,QAAQ,EAAE,SAAS,CAAC,CAAC,EAC7E,IAAI,aAAa,IAAI,SAAU,OAAO,EAAE,EACxC,OAAO,KAAK,IAAI,SAAS,EAAG,QAAQ,CACtC,CAAC,EACA,MAAO,KAAQH,mBAAiB,CAAE,MAAO,MAAO,QAASC,uBAAqB,GAAG,EAAG,UAAW,EAAM,CAAC,CAAC,CAC5G,CAEA,OACEG,OAACL,SAAA,CAAO,QAAS,IAAM,UAAU,EAAI,GAAG,KACrC,SACH,CAEJ",
  "names": ["Pointer", "diff", "memo", "d", "b", "MissingError", "TestError", "InvalidOperationError", "createPatch", "diff", "jsx", "TextInput", "useState", "jsx", "MantineAppShell", "useMedplum", "useMedplumProfile", "useState", "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", "jsx", "jsx", "main", "Group", "Menu", "Text", "formatHumanName", "useMedplumProfile", "useState", "data", "jsx", "jsx", "logoButton", "user", "userName", "Box", "Text", "locationUtils", "useState", "Group", "iconBox", "interactive", "jsx", "jsxs", "Group", "divider", "accountSection", "projectOption", "recentProjectItem", "dropdown", "settingsRow", "settingsControlWrapper", "segmentedControl", "appearanceControl", "layoutControl", "Fragment", "jsx", "jsxs", "useState", "locationUtils", "Box", "Text", "Group", "Text", "formatHumanName", "getDisplayString", "getReferenceString", "useMedplumNavigate", "forwardRef", "useCallback", "Group", "Loader", "normalizeErrorString", "useMemo", "useState", "jsx", "jsxs", "defaultValue", "toOption", "useState", "ItemComponent", "normalizeErrorString", "option", "useMemo", "Loader", "Group", "searchInput", "jsx", "jsxs", "getDisplayString", "useMedplumNavigate", "useCallback", "getReferenceString", "forwardRef", "Group", "Text", "formatHumanName", "jsx", "jsxs", "useMedplumProfile", "useState", "Group", "Menu", "Text", "formatHumanName", "Box", "Divider", "MantineAppShell", "Menu", "Stack", "Text", "UnstyledButton", "formatHumanName", "useMedplumNavigate", "useMedplumProfile", "Fragment", "useState", "Group", "NativeSelect", "TextInput", "showNotification", "normalizeErrorString", "useMedplum", "useState", "createContext", "jsx", "useState", "useContext", "jsx", "useContext", "jsx", "jsxs", "useMedplum", "showNotification", "normalizeErrorString", "TextInput", "Group", "NativeSelect", "useCallback", "useState", "useState", "Group", "Text", "useMedplum", "forwardRef", "useCallback", "jsx", "jsxs", "toOption", "useMedplum", "useCallback", "ItemComponent", "forwardRef", "Group", "Text", "jsx", "defaultValue", "useState", "jsx", "useState", "useCallback", "navbar", "logoButton", "menuTitle", "link", "dismissButton", "linkLabel", "iconWrapper", "alertDot", "linkCount", "addBookmarkLink", "toggleButton", "divider", "Stack", "Text", "formatHumanName", "isUUID", "useMedplum", "useMedplumNavigate", "useState", "actionSection", "action", "actionDescription", "actionsGroup", "actionsList", "content", "jsx", "jsxs", "Stack", "Text", "useMedplum", "useMedplumNavigate", "useState", "buildGraphQLQuery", "getResourcesFromResponse", "r", "isUUID", "dedupeResources", "formatHumanName", "Fragment", "jsx", "jsxs", "useMedplumNavigate", "useMedplumProfile", "useState", "onLinkClick", "MantineAppShell", "UnstyledButton", "Box", "Text", "Stack", "Divider", "Menu", "formatHumanName", "jsx", "jsxs", "useState", "useMedplum", "useMedplumProfile", "MantineAppShell", "isPopulated", "Anchor", "ContentType", "useCachedBinaryUrl", "Button", "useEffect", "useRef", "useState", "Fragment", "jsx", "jsxs", "useState", "useRef", "useEffect", "validationResult", "Button", "Loader", "useEffect", "useRef", "useState", "jsx", "jsx", "jsxs", "useCachedBinaryUrl", "ContentType", "Anchor", "root", "compact", "Fragment", "jsx", "jsxs", "Fragment", "jsx", "isPopulated", "useState", "useMedplum", "useRef", "Fragment", "jsx", "jsxs", "useMedplum", "useRef", "jsx", "jsxs", "useState", "props", "Button", "useState", "Fragment", "jsx", "jsxs", "useState", "Button", "props", "Button", "Flex", "Group", "Stack", "normalizeOperationOutcome", "useMedplum", "useState", "root", "jsx", "paper", "fill", "jsx", "jsx", "jsx", "jsxs", "jsx", "jsxs", "useMedplum", "useState", "normalizeOperationOutcome", "Flex", "Stack", "Group", "Button", "Alert", "Center", "Image", "Stack", "Text", "TextInput", "Title", "normalizeErrorString", "useState", "jsx", "jsxs", "useState", "normalizeErrorString", "Center", "Title", "Text", "Alert", "Stack", "Image", "TextInput", "normalizeOperationOutcome", "useMedplum", "useEffect", "useState", "Alert", "jsx", "Alert", "Anchor", "Flex", "Stack", "Text", "TextInput", "Title", "normalizeOperationOutcome", "useMedplum", "useState", "jsx", "jsxs", "useMedplum", "useState", "normalizeOperationOutcome", "Flex", "Title", "Stack", "TextInput", "Text", "Anchor", "Anchor", "Box", "Divider", "Flex", "PasswordInput", "Stack", "Text", "TextInput", "normalizeOperationOutcome", "useMedplum", "useEffect", "useState", "Box", "useEffect", "useRef", "useState", "jsx", "useRef", "useState", "useEffect", "Box", "locationUtils", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "normalizeOperationOutcome", "Flex", "Box", "Divider", "Stack", "TextInput", "PasswordInput", "Text", "Anchor", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "normalizeOperationOutcome", "Anchor", "Flex", "Stack", "Text", "TextInput", "Title", "normalizeOperationOutcome", "useMedplum", "useEffect", "useState", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "normalizeOperationOutcome", "Flex", "Title", "Stack", "TextInput", "Text", "Anchor", "Anchor", "Button", "Flex", "Group", "PasswordInput", "Stack", "Title", "normalizeOperationOutcome", "useMedplum", "useState", "jsx", "jsxs", "useMedplum", "useState", "normalizeOperationOutcome", "Flex", "Title", "Stack", "PasswordInput", "Group", "Button", "Anchor", "showNotification", "normalizeErrorString", "useMedplum", "useCallback", "useEffect", "useRef", "useState", "ActionIcon", "Anchor", "Box", "Checkbox", "Divider", "Flex", "PasswordInput", "Stack", "Text", "TextInput", "locationUtils", "normalizeOperationOutcome", "useMedplum", "useCallback", "useState", "Fragment", "jsx", "jsxs", "useState", "useMedplum", "useCallback", "locationUtils", "normalizeOperationOutcome", "Flex", "Box", "Divider", "TextInput", "Stack", "Text", "Anchor", "ActionIcon", "PasswordInput", "Checkbox", "Anchor", "Combobox", "Flex", "Stack", "Text", "TextInput", "Title", "useCombobox", "normalizeOperationOutcome", "useMedplum", "useState", "jsx", "jsxs", "useMedplum", "useCombobox", "useState", "normalizeOperationOutcome", "Combobox", "Stack", "Flex", "Title", "TextInput", "Text", "Anchor", "Checkbox", "Flex", "Group", "Stack", "Title", "useMedplum", "Fragment", "jsx", "jsxs", "useMedplum", "Stack", "Flex", "Title", "Fragment", "Checkbox", "Group", "jsx", "useMedplum", "useState", "useRef", "useCallback", "showNotification", "normalizeErrorString", "useEffect", "buildElementsContext", "getPathDisplayName", "isEmpty", "useContext", "useMemo", "ActionIcon", "Flex", "Tooltip", "useState", "Fragment", "jsx", "Fragment", "jsx", "Fragment", "jsx", "Fragment", "jsx", "jsxs", "isPopulated", "useMedplum", "useContext", "useEffect", "useMemo", "useState", "jsx", "useMedplum", "useContext", "useState", "useMemo", "isPopulated", "useEffect", "formatHumanName", "Fragment", "jsx", "jsxs", "Fragment", "jsx", "Fragment", "jsx", "Fragment", "jsx", "Fragment", "jsx", "jsxs", "Fragment", "jsx", "Group", "Text", "getPathDisplayName", "isPopulated", "useMedplum", "useContext", "useEffect", "useMemo", "useState", "isPopulated", "tryGetProfile", "isPopulated", "useContext", "useMemo", "jsx", "Fragment", "jsx", "useContext", "useMemo", "isPopulated", "Fragment", "jsx", "jsxs", "useMedplum", "useMemo", "useState", "useContext", "useEffect", "slices", "slicedValues", "isPopulated", "getPathDisplayName", "Group", "Text", "Fragment", "jsx", "jsxs", "Flex", "Tooltip", "ActionIcon", "useState", "jsx", "jsxs", "EXTENSION_KEYS", "IGNORED_PROPERTIES", "useContext", "useMemo", "buildElementsContext", "isEmpty", "getPathDisplayName", "Box", "buildElementsContext", "tryGetDataType", "useContext", "useMemo", "useState", "Stack", "getPathDisplayName", "useContext", "useMemo", "useState", "Group", "useContext", "dimmed", "preserveBreaks", "Tooltip", "jsx", "jsx", "jsxs", "useContext", "Group", "Input", "useContext", "jsx", "useContext", "Input", "isEmpty", "Checkbox", "Group", "NativeSelect", "Textarea", "TextInput", "capitalize", "isEmpty", "isPopulated", "PropertyType", "useContext", "useMemo", "useState", "useState", "jsx", "defaultValue", "useState", "useState", "jsx", "defaultValue", "useState", "Group", "TextInput", "useContext", "useMemo", "useState", "Group", "NativeSelect", "TextInput", "useContext", "useMemo", "useState", "jsx", "jsxs", "useContext", "useState", "useMemo", "Group", "NativeSelect", "TextInput", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "TextInput", "TextInput", "jsx", "TextInput", "isPopulated", "isProfileLoaded", "useMedplum", "useEffect", "useMemo", "useState", "jsx", "useMedplum", "useMemo", "isPopulated", "useState", "useEffect", "isProfileLoaded", "Group", "NativeSelect", "TextInput", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "NativeSelect", "TextInput", "Group", "TextInput", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "TextInput", "NativeSelect", "TextInput", "useCallback", "useContext", "useMemo", "useState", "jsx", "useState", "useContext", "useMemo", "useCallback", "NativeSelect", "TextInput", "Group", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "Group", "NativeSelect", "TextInput", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "NativeSelect", "TextInput", "Group", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "Group", "useContext", "useMemo", "useState", "jsx", "jsxs", "useState", "useContext", "useMemo", "Group", "Group", "NativeSelect", "createReference", "isEmpty", "isPopulated", "tryGetProfile", "useMedplum", "useCallback", "useEffect", "useMemo", "useRef", "useState", "useCallback", "Group", "Text", "getDisplayString", "getReferenceString", "isReference", "isResource", "useMedplum", "forwardRef", "useCallback", "useEffect", "useRef", "useState", "jsx", "jsxs", "toOption", "getReferenceString", "getDisplayString", "forwardRef", "Group", "Text", "useMedplum", "ItemComponent", "useRef", "useState", "useEffect", "isResource", "isReference", "r", "useCallback", "jsx", "useCallback", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useRef", "useMemo", "useEffect", "isPopulated", "useCallback", "createReference", "Group", "NativeSelect", "defaultValue", "tryGetProfile", "isEmpty", "Group", "Stack", "Text", "getPathDisplayName", "useMedplum", "useContext", "useEffect", "useState", "Group", "Stack", "Text", "buildElementsContext", "isEmpty", "isPopulated", "useContext", "useMemo", "useState", "indented", "ActionIcon", "Button", "jsx", "Button", "ActionIcon", "ActionIcon", "jsx", "ActionIcon", "jsx", "jsxs", "useState", "useContext", "useMemo", "isPopulated", "buildElementsContext", "isEmpty", "Text", "Stack", "Group", "jsx", "jsxs", "useMedplum", "useState", "defaultValue", "useContext", "useEffect", "slices", "slicedValues", "getPathDisplayName", "Stack", "Text", "Group", "ActionIcon", "Flex", "showNotification", "useRef", "useState", "jsx", "jsxs", "Flex", "ActionIcon", "showNotification", "Box", "Button", "Group", "Modal", "NativeSelect", "Stack", "TextInput", "formatTiming", "useContext", "useMemo", "useRef", "useState", "Fragment", "jsx", "jsxs", "useState", "Group", "formatTiming", "Button", "useRef", "useContext", "useMemo", "value", "Modal", "Stack", "TextInput", "NativeSelect", "Box", "jsx", "jsxs", "defaultValue", "PropertyType", "capitalize", "useState", "Group", "NativeSelect", "useContext", "useMemo", "isEmpty", "isPopulated", "TextInput", "Checkbox", "Textarea", "jsx", "useState", "useContext", "useMemo", "Stack", "getPathDisplayName", "nested", "jsx", "jsxs", "defaultValue", "useState", "useContext", "useMemo", "tryGetDataType", "buildElementsContext", "Box", "Button", "Group", "useMemo", "useState", "table", "jsx", "jsxs", "useState", "useMemo", "Group", "Button", "useMemo", "jsx", "useMemo", "ActionIcon", "Group", "Menu", "Paper", "ScrollArea", "Stack", "Text", "TextInput", "Title", "showNotification", "getDisplayString", "getReferenceString", "normalizeErrorString", "useCachedBinaryUrl", "useMedplum", "useResource", "useCallback", "useEffect", "useMemo", "useRef", "useState", "chatPaper", "chatTitle", "chatBody", "chatScrollArea", "chatInputContainer", "chatPendingFile", "chatBubbleOuterWrap", "chatBubbleRightAlignedInnerWrap", "chatBubbleLeftAlignedInnerWrap", "chatBubble", "chatBubbleNameRight", "chatBubbleAttachmentWithText", "chatBubbleAttachmentIcon", "chatBubbleMenu", "Box", "Divider", "Loader", "Stack", "Text", "TextInput", "UnstyledButton", "useDebouncedCallback", "getReferenceString", "useMedplum", "useEffect", "useState", "jsx", "jsxs", "useMedplum", "getReferenceString", "useDebouncedCallback", "Stack", "Text", "Box", "TextInput", "Divider", "Loader", "UnstyledButton", "jsx", "jsxs", "showNotification", "useMedplum", "useRef", "useState", "useMemo", "getReferenceString", "useCallback", "useEffect", "normalizeErrorString", "Paper", "Title", "Stack", "Group", "ScrollArea", "Text", "ActionIcon", "TextInput", "useResource", "getDisplayString", "useCachedBinaryUrl", "Menu", "ActionIcon", "useMedplumProfile", "useEffect", "useState", "iconContainer", "icon", "chatModalContainer", "Fragment", "jsx", "jsxs", "useMedplumProfile", "useState", "useEffect", "ActionIcon", "createReference", "formatCodeableConcept", "getReferenceString", "useMedplum", "useMedplumProfile", "useCallback", "useEffect", "useMemo", "useState", "jsx", "useMedplum", "useMedplumProfile", "useState", "useMemo", "createReference", "useEffect", "useCallback", "getReferenceString", "formatCodeableConcept", "Divider", "Stack", "Fragment", "Group", "Stack", "Text", "formatDateTime", "formatHumanName", "useResource", "content", "contentContainer", "selected", "jsx", "jsxs", "useResource", "formatHumanName", "Group", "Stack", "Text", "formatDateTime", "jsx", "jsxs", "Stack", "Fragment", "Divider", "Button", "Modal", "Stack", "Text", "TextInput", "showNotification", "createReference", "HTTP_HL7_ORG", "normalizeErrorString", "useMedplum", "useMedplumProfile", "useMemo", "useState", "Divider", "Group", "Stack", "Text", "Title", "createReference", "getExtension", "getReferenceString", "useMedplum", "useCallback", "useEffect", "useLayoutEffect", "useMemo", "useRef", "useState", "Button", "Paper", "createReference", "HTTP_HL7_ORG", "useMedplum", "useEffect", "useLayoutEffect", "useRef", "data", "ratio", "jsx", "jsxs", "useMedplum", "defaultValue", "useRef", "useLayoutEffect", "useEffect", "HTTP_HL7_ORG", "createReference", "Paper", "Button", "Divider", "Stack", "QuestionnaireItemType", "Fragment", "Title", "jsx", "jsxs", "Title", "Checkbox", "Group", "NativeSelect", "Text", "Textarea", "TextInput", "capitalize", "formatCoding", "HTTP_HL7_ORG", "stringify", "useMedplum", "useEffect", "useState", "Fragment", "jsx", "jsxs", "defaultValue", "HTTP_HL7_ORG", "Checkbox", "TextInput", "Textarea", "Group", "Text", "data", "NativeSelect", "capitalize", "formatCoding", "useMedplum", "useState", "useEffect", "stringify", "option", "Anchor", "Fragment", "jsx", "jsxs", "Anchor", "Anchor", "Stack", "QuestionnaireItemType", "jsx", "jsxs", "QuestionnaireItemType", "Stack", "Anchor", "jsx", "jsxs", "Stack", "QuestionnaireItemType", "Fragment", "Divider", "Button", "Group", "Fragment", "jsx", "jsxs", "Group", "Button", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useRef", "useLayoutEffect", "useCallback", "useEffect", "useMemo", "getExtension", "formState", "questionnaire", "createReference", "getReferenceString", "Title", "Stack", "Divider", "Text", "Group", "jsx", "jsxs", "useMedplum", "useMedplumProfile", "useMemo", "createReference", "useState", "Modal", "Stack", "Text", "TextInput", "Button", "showNotification", "normalizeErrorString", "HTTP_HL7_ORG", "ActionIcon", "Checkbox", "Group", "Popover", "Stack", "Text", "TextInput", "Tooltip", "useDebouncedCallback", "showNotification", "createReference", "formatHumanName", "getReferenceString", "normalizeErrorString", "useMedplum", "useMedplumProfile", "useResource", "useEffect", "useMemo", "useState", "participantItem", "jsx", "jsxs", "useState", "useMedplum", "useMedplumProfile", "useMemo", "createReference", "useDebouncedCallback", "getReferenceString", "showNotification", "normalizeErrorString", "useEffect", "r", "Popover", "Tooltip", "ActionIcon", "Stack", "Text", "TextInput", "useResource", "Group", "Checkbox", "formatHumanName", "ActionIcon", "Box", "Button", "Center", "Divider", "Flex", "Group", "Menu", "Paper", "ScrollArea", "Skeleton", "Stack", "Text", "Tooltip", "useDisclosure", "showNotification", "getReferenceString", "normalizeErrorString", "useMedplumNavigate", "useCallback", "useEffect", "useMemo", "Divider", "Flex", "Group", "Stack", "Text", "Tooltip", "formatHumanName", "useMedplum", "useResource", "useEffect", "useMemo", "useState", "panel", "patientSummaryBadge", "patientSummaryAddButton", "patientSummaryHeader", "patientSummaryCollapseIcon", "collapsed", "Stack", "formatAddress", "Box", "Flex", "Group", "Modal", "Text", "useDisclosure", "getDisplayString", "useMedplum", "useCallback", "useMemo", "useState", "jsx", "Group", "Stack", "TextInput", "HTTP_HL7_ORG", "createReference", "useCallback", "useState", "jsx", "jsxs", "HTTP_HL7_ORG", "useState", "useCallback", "createReference", "Stack", "code", "TextInput", "clinicalStatus", "Group", "ActionIcon", "Box", "Group", "Text", "useState", "root", "header", "chevron", "title", "addButton", "jsx", "jsxs", "useState", "Box", "Group", "ActionIcon", "Text", "ActionIcon", "Box", "gradient", "container", "chevron", "item", "itemText", "jsx", "jsxs", "Box", "ActionIcon", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useDisclosure", "useMemo", "getDisplayString", "useCallback", "Box", "Flex", "Text", "Group", "Modal", "Box", "Flex", "Group", "Text", "useResource", "jsx", "jsxs", "useResource", "Box", "Text", "Group", "Flex", "Box", "Flex", "Group", "Modal", "Text", "useDisclosure", "formatDate", "getDisplayString", "useState", "Group", "Stack", "Text", "Title", "formatCodeableConcept", "formatDateTime", "isReference", "useMedplum", "useResource", "useEffect", "useState", "Stack", "noteBody", "noteCite", "noteRoot", "jsx", "Stack", "Group", "Text", "getDisplayString", "normalizeErrorString", "useResource", "useState", "jsx", "useState", "useResource", "normalizeErrorString", "getDisplayString", "Text", "jsx", "jsxs", "Group", "table", "criticalRow", "noteBody", "noteCite", "noteRoot", "Fragment", "jsx", "jsxs", "useMedplum", "useResource", "useState", "useEffect", "Stack", "Title", "Text", "Group", "formatDateTime", "isReference", "formatCodeableConcept", "Fragment", "jsx", "jsxs", "useState", "useDisclosure", "basedOn", "Flex", "Box", "Text", "getDisplayString", "Group", "formatDate", "Modal", "Box", "Flex", "Group", "Modal", "Text", "useDisclosure", "getDisplayString", "useMedplum", "useCallback", "useState", "Alert", "Group", "Radio", "Stack", "HTTP_HL7_ORG", "addProfileToResource", "createReference", "useMedplumProfile", "useCallback", "useState", "jsx", "jsxs", "HTTP", "useMedplumProfile", "useState", "useCallback", "addProfileToResource", "createReference", "HTTP_HL7_ORG", "Stack", "Radio", "Group", "Alert", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useDisclosure", "useCallback", "Flex", "Box", "Text", "getDisplayString", "Group", "getStatusColor", "Modal", "Box", "Group", "Text", "Tooltip", "jsx", "jsxs", "Box", "Tooltip", "Group", "Text", "capitalize", "getExtension", "HTTP_HL7_ORG", "Box", "Flex", "Group", "Loader", "Modal", "Text", "useDisclosure", "formatAddress", "getReferenceString", "useMedplum", "useResource", "useCallback", "useEffect", "useMemo", "useState", "Fragment", "jsx", "jsxs", "useMedplum", "useDisclosure", "useState", "useResource", "useMemo", "useEffect", "useCallback", "getReferenceString", "Loader", "Text", "Box", "Flex", "Group", "formatAddress", "Modal", "Badge", "Box", "Flex", "Group", "Modal", "Text", "UnstyledButton", "useDisclosure", "formatDate", "getDisplayString", "useMedplum", "useCallback", "useMemo", "useState", "Group", "Stack", "HTTP_HL7_ORG", "addProfileToResource", "createReference", "useCallback", "useState", "jsx", "jsxs", "useState", "useCallback", "addProfileToResource", "createReference", "HTTP_HL7_ORG", "Stack", "code", "clinicalStatus", "Group", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useDisclosure", "useMemo", "useCallback", "Flex", "Box", "Group", "Text", "getDisplayString", "Badge", "getStatusColor", "formatDate", "UnstyledButton", "Modal", "Box", "Flex", "Group", "Modal", "Radio", "Stack", "Text", "UnstyledButton", "useDisclosure", "createReference", "HTTP_HL7_ORG", "HTTP_TERMINOLOGY_HL7_ORG", "useMedplum", "useCallback", "useState", "Fragment", "jsx", "jsxs", "HTTP_TERMINOLOGY_HL7_ORG", "useMedplum", "useState", "useDisclosure", "useCallback", "HTTP_HL7_ORG", "createReference", "Flex", "Box", "UnstyledButton", "Text", "Modal", "Stack", "Radio", "Group", "Group", "Modal", "Radio", "Stack", "Text", "UnstyledButton", "useDisclosure", "HTTP_HL7_ORG", "LOINC", "SNOMED", "createReference", "formatCodeableConcept", "useMedplum", "useCallback", "useState", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useDisclosure", "useCallback", "HTTP_HL7_ORG", "LOINC", "createReference", "SNOMED", "UnstyledButton", "Text", "formatCodeableConcept", "Modal", "Stack", "Radio", "Group", "Group", "Modal", "Stack", "Text", "Textarea", "TextInput", "useDisclosure", "formatQuantity", "useMedplum", "useCallback", "useState", "LOINC", "createReference", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useDisclosure", "useCallback", "Stack", "Group", "Text", "formatQuantity", "Modal", "TextInput", "Textarea", "jsx", "jsxs", "Stack", "formatAddress", "Fragment", "jsx", "jsxs", "useMedplum", "useResource", "useState", "useMemo", "useEffect", "Flex", "Group", "Stack", "Tooltip", "formatHumanName", "Text", "Divider", "container", "rightBorder", "Fragment", "jsx", "jsxs", "useMedplumNavigate", "useDisclosure", "useMemo", "useCallback", "useEffect", "showNotification", "normalizeErrorString", "error", "Flex", "Paper", "ScrollArea", "Group", "Tooltip", "ActionIcon", "Divider", "Stack", "Skeleton", "Box", "Center", "Text", "Menu", "Button", "getStatusColor", "getReferenceString", "ActionIcon", "Button", "Center", "Group", "Loader", "ScrollArea", "TextInput", "showNotification", "createReference", "normalizeErrorString", "useMedplum", "useResource", "useCallback", "useEffect", "useLayoutEffect", "useRef", "useState", "Table", "capitalize", "useMedplum", "useEffect", "useMemo", "useState", "Button", "useState", "removed", "added", "Fragment", "jsx", "jsxs", "useState", "Button", "root", "removed", "added", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "useMemo", "capitalize", "Table", "tryGetProfile", "useMedplum", "useResource", "useEffect", "useMemo", "useState", "jsx", "useMedplum", "useResource", "useState", "useEffect", "tryGetProfile", "useMemo", "ActionIcon", "Group", "Menu", "Text", "formatDateTime", "getReferenceString", "item", "itemPadding", "jsx", "jsxs", "Group", "Text", "formatDateTime", "Menu", "ActionIcon", "getReferenceString", "pinnedComment", "jsx", "jsxs", "useMedplum", "useRef", "useResource", "useState", "useLayoutEffect", "useCallback", "resource", "useEffect", "normalizeErrorString", "showNotification", "Center", "Loader", "Group", "TextInput", "ActionIcon", "createReference", "props", "Button", "ScrollArea", "jsx", "createReference", "jsx", "createReference", "Button", "Loader", "Table", "normalizeOperationOutcome", "useMedplum", "useEffect", "useState", "jsx", "ActionIcon", "Button", "Center", "Group", "Loader", "Menu", "Pagination", "Table", "Text", "UnstyledButton", "DEFAULT_SEARCH_COUNT", "deepEquals", "normalizeOperationOutcome", "useMedplum", "useCallback", "useEffect", "useLayoutEffect", "useRef", "useState", "Box", "Button", "Modal", "Text", "jsx", "jsxs", "Button", "Group", "Modal", "MultiSelect", "Stack", "getDataType", "stringify", "useEffect", "useMemo", "useRef", "useState", "capitalize", "evalFhirPathTyped", "formatDateTime", "Operator", "Fragment", "jsx", "Operator", "capitalize", "formatDateTime", "evalFhirPathTyped", "jsx", "jsxs", "useRef", "useState", "stringify", "useEffect", "useMemo", "getDataType", "Modal", "Stack", "MultiSelect", "Group", "Button", "ActionIcon", "Group", "Modal", "NativeSelect", "Operator", "deepClone", "getSearchParameters", "useEffect", "useLayoutEffect", "useRef", "useState", "Checkbox", "TextInput", "getSearchParameterDetails", "jsx", "getSearchParameterDetails", "Checkbox", "TextInput", "jsx", "jsxs", "useState", "deepClone", "useRef", "useLayoutEffect", "useEffect", "getSearchParameters", "Modal", "Group", "Operator", "NativeSelect", "ActionIcon", "Button", "Modal", "useState", "jsx", "jsxs", "useState", "Modal", "Button", "formatDateTime", "getSearchParameterDetails", "Operator", "SearchParameterType", "Fragment", "jsx", "Operator", "getSearchParameterDetails", "SearchParameterType", "formatDateTime", "Menu", "Operator", "Fragment", "jsx", "jsxs", "Menu", "Operator", "root", "table", "tr", "th", "control", "icon", "getElementDefinition", "getSearchParameterDetails", "getSearchParameters", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "deepEquals", "useRef", "useLayoutEffect", "useCallback", "normalizeOperationOutcome", "useEffect", "Center", "Loader", "Group", "Button", "Text", "ActionIcon", "Table", "Menu", "UnstyledButton", "Pagination", "DEFAULT_SEARCH_COUNT", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "normalizeOperationOutcome", "Loader", "Table", "Button", "ScrollArea", "root", "entry", "key", "value", "jsx", "ScrollArea", "Anchor", "Tabs", "isString", "locationUtils", "useMedplumNavigate", "useState", "list", "link", "jsx", "jsxs", "useMedplumNavigate", "useState", "locationUtils", "Tabs", "Anchor", "isString", "Box", "SimpleGrid", "useResource", "Box", "Flex", "Group", "Paper", "Text", "Title", "formatCodeableConcept", "Fragment", "jsx", "jsxs", "Paper", "Group", "Text", "formatCodeableConcept", "Box", "Title", "Flex", "jsx", "jsxs", "useResource", "Box", "SimpleGrid", "ActionIcon", "Indicator", "Tooltip", "useNotificationCount", "jsx", "ActionIcon", "Alert", "Badge", "Box", "Button", "Checkbox", "Divider", "Group", "Modal", "Stack", "Table", "Text", "Title", "normalizeErrorString", "useMedplum", "useCallback", "useMemo", "useState", "Fragment", "jsx", "jsxs", "useMedplum", "useMemo", "useState", "useCallback", "normalizeErrorString", "Stack", "Title", "Text", "Table", "ActionIcon", "Divider", "Group", "Badge", "Box", "Button", "Modal", "Checkbox", "Alert", "Group", "SegmentedControl", "Stack", "notifications", "ContentType", "normalizeErrorString", "resolveId", "useMedplum", "useCallback", "jsx", "jsxs", "NOTIFICATION_ID", "NOTIFICATION_TITLE", "ContentType", "useMedplum", "useCallback", "data", "resolveId", "notifications", "normalizeErrorString", "Stack", "SegmentedControl", "Group", "calculateAgeString", "useResource", "Fragment", "jsx", "jsxs", "useResource", "calculateAgeString", "Box", "Button", "Checkbox", "Flex", "Group", "Loader", "Radio", "Stack", "Text", "TextInput", "showNotification", "formatAddress", "normalizeErrorString", "useCallback", "useState", "pharmacyItem", "pharmacyItemSelected", "jsx", "jsxs", "Stack", "TextInput", "Group", "Button", "Box", "Radio", "Text", "formatAddress", "Flex", "Checkbox", "useState", "useCallback", "showNotification", "normalizeErrorString", "Loader", "Box", "Flex", "Group", "Text", "jsx", "jsxs", "Flex", "Box", "Text", "Group", "createReference", "useCallback", "jsx", "useCallback", "createReference", "Anchor", "Box", "Button", "CloseButton", "Flex", "Group", "Loader", "NativeSelect", "Paper", "Stack", "Text", "TextInput", "getReferenceString", "useMedplum", "useResource", "useEffect", "useState", "section", "hovering", "editing", "jsx", "jsxs", "useMedplum", "defaultValue", "useResource", "useState", "useEffect", "TextInput", "Stack", "Button", "resource", "Loader", "Paper", "Flex", "CloseButton", "Box", "NativeSelect", "Group", "Text", "Anchor", "getReferenceString", "Anchor", "Box", "Group", "NativeSelect", "Textarea", "TextInput", "Title", "getElementDefinition", "getQuestionnaireItemReferenceTargetTypes", "QUESTIONNAIRE_ITEM_CONTROL_URL", "QuestionnaireItemType", "useMedplum", "useResource", "useEffect", "useLayoutEffect", "useRef", "useState", "section", "hovering", "editing", "questionBody", "topActions", "bottomActions", "movementActions", "movementIcons", "columnAlignment", "linkIdInput", "typeSelect", "preserveBreaks", "Fragment", "jsx", "jsxs", "useMedplum", "defaultValue", "useResource", "useState", "useEffect", "questionnaire", "isResource", "QuestionnaireItemType", "useRef", "useLayoutEffect", "item", "TextInput", "Textarea", "Title", "NativeSelect", "Box", "Anchor", "generateId", "getElementDefinition", "getQuestionnaireItemReferenceTargetTypes", "Group", "nextId", "QUESTIONNAIRE_ITEM_CONTROL_URL", "ActionIcon", "Box", "Button", "Collapse", "Divider", "Flex", "Loader", "Stack", "Text", "useDebouncedCallback", "showNotification", "normalizeErrorString", "useMedplum", "useCallback", "useEffect", "useRef", "useState", "banner", "headerRow", "statusRow", "iconWrapper", "recordingPulse", "statusLabel", "statusLabelPrimary", "statusLabelFinishing", "dictationButton", "dictationButtonLoading", "instructions", "panelGrid", "panelColumn", "transcriptWrapper", "transcriptArea", "transcriptText", "Fragment", "jsx", "jsxs", "Stack", "Text", "useMedplum", "useState", "useRef", "useEffect", "useCallback", "transcript", "showNotification", "normalizeErrorString", "useDebouncedCallback", "Loader", "Box", "Flex", "Button", "ActionIcon", "Collapse", "Divider", "Stack", "useResource", "Stack", "Text", "formatDate", "useMemo", "Fragment", "jsx", "jsxs", "useMemo", "Text", "Stack", "value", "formatDate", "jsx", "useResource", "Stack", "ActionIcon", "Divider", "Group", "NativeSelect", "Stack", "Text", "TextInput", "formatRange", "useEffect", "useState", "section", "jsx", "jsxs", "useState", "useEffect", "Stack", "ActionIcon", "Group", "groupId", "Divider", "TextInput", "NativeSelect", "Text", "nextId", "formatRange", "Button", "Grid", "Text", "formatDateTime", "getReferenceString", "useMedplum", "useResource", "Fragment", "useEffect", "useState", "jsx", "jsxs", "useMedplum", "useResource", "useState", "useEffect", "Grid", "Fragment", "Text", "formatDateTime", "Button", "getReferenceString", "useMedplum", "useEffect", "useState", "stringify", "stringify", "container", "root", "startRow", "normalRow", "author", "onBehalfOf", "dateTime", "lineNumber", "line", "pre", "Fragment", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "stringify", "removed", "added", "Fragment", "jsx", "jsxs", "stringify", "ActionIcon", "Alert", "Button", "Group", "Menu", "Stack", "TextInput", "AccessPolicyInteraction", "isPopulated", "satisfiedAccessPolicy", "tryGetProfile", "useMedplum", "useResource", "useEffect", "useMemo", "useState", "splitButton", "menuControl", "jsx", "jsxs", "useMedplum", "defaultValue", "useResource", "useState", "useEffect", "tryGetProfile", "useMemo", "satisfiedAccessPolicy", "AccessPolicyInteraction", "isPopulated", "Stack", "TextInput", "Group", "Button", "Menu", "ActionIcon", "Alert", "Table", "formatDateTime", "normalizeErrorString", "useMedplum", "useEffect", "useState", "jsx", "jsxs", "useMedplum", "useState", "useEffect", "Table", "formatDateTime", "getVersionUrl", "normalizeErrorString", "Button", "Loader", "Stack", "Text", "showNotification", "arrayify", "getReferenceString", "isReference", "isResource", "normalizeErrorString", "useMedplum", "useCallback", "useEffect", "useMemo", "useState", "container", "info", "selection", "jsx", "jsxs", "useState", "useEffect", "getStart", "getEnd", "options", "useCallback", "useMemo", "Text", "Stack", "Button", "Loader", "isReference", "useMedplum", "arrayify", "getReferenceString", "schedule", "isResource", "showNotification", "normalizeErrorString", "useEffect", "useEffect", "createReference", "jsx", "createReference", "Anchor", "showNotification", "normalizeErrorString", "useMedplum", "useResource", "jsx"]
}
