@medplum/react 3.2.30 → 3.2.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/index.mjs.map +3 -3
- package/package.json +19 -19
package/dist/cjs/index.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
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/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/IconBleachOff.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBleach.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/IconBucketOff.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconBucket.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/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/IconDots.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconEdit.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/IconFileAlert.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFilePlus.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconFilter.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconGenderFemale.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconGenderMale.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconLogout.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/IconMessage.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/IconSwitchHorizontal.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconTableExport.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconTrash.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconUserSquare.ts", "../../../../node_modules/@tabler/icons-react/src/icons/IconX.ts", "../../src/Loading/Loading.tsx", "../../src/AppShell/AppShell.module.css", "../../src/AppShell/Header.tsx", "../../../../node_modules/clsx/dist/clsx.mjs", "../../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", "../../src/HumanNameDisplay/HumanNameDisplay.tsx", "../../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/FormUtils.ts", "../../src/Form/Form.tsx", "../../src/ResourceTypeInput/ResourceTypeInput.tsx", "../../src/CodeInput/CodeInput.tsx", "../../src/ValueSetAutocomplete/ValueSetAutocomplete.tsx", "../../src/AppShell/Navbar.module.css", "../../src/AttachmentDisplay/AttachmentDisplay.tsx", "../../src/CcdaDisplay/CcdaDisplay.tsx", "../../src/DescriptionList/DescriptionList.module.css", "../../src/DescriptionList/DescriptionList.tsx", "../../src/AttachmentArrayDisplay/AttachmentArrayDisplay.tsx", "../../src/AttachmentArrayInput/AttachmentArrayInput.tsx", "../../src/AttachmentButton/AttachmentButton.tsx", "../../src/AttachmentInput/AttachmentInput.tsx", "../../src/auth/RegisterForm.tsx", "../../src/Container/Container.tsx", "../../src/Container/Container.module.css", "../../src/Panel/Panel.tsx", "../../src/Panel/Panel.module.css", "../../src/Document/Document.tsx", "../../src/auth/NewProjectForm.tsx", "../../src/Logo/Logo.tsx", "../../src/utils/outcomes.ts", "../../src/auth/NewUserForm.tsx", "../../src/GoogleButton/GoogleButton.tsx", "../../src/utils/script.ts", "../../src/GoogleButton/GoogleButton.utils.ts", "../../src/OperationOutcomeAlert/OperationOutcomeAlert.tsx", "../../src/utils/recaptcha.ts", "../../src/auth/SignInForm.tsx", "../../src/auth/AuthenticationForm.tsx", "../../src/auth/ChooseProfileForm.tsx", "../../src/auth/ChooseScopeForm.tsx", "../../src/auth/MfaForm.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/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/ExtensionDisplay/ExtensionDisplay.tsx", "../../src/ResourcePropertyDisplay/ResourcePropertyDisplay.utils.ts", "../../src/BackboneElementInput/BackboneElementInput.tsx", "../../src/ElementsInput/ElementsInput.tsx", "../../src/CheckboxFormSection/CheckboxFormSection.tsx", "../../src/utils/maybeWrapWithTooltip.tsx", "../../src/FormSection/FormSection.module.css", "../../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/ResourceArrayInput/ResourceArrayInput.tsx", "../../src/SliceInput/SliceInput.tsx", "../../src/ResourceArrayInput/ResourceArrayInput.module.css", "../../src/buttons/ArrayAddButton.tsx", "../../src/buttons/ArrayRemoveButton.tsx", "../../src/ResourcePropertyInput/ResourcePropertyInput.utils.ts", "../../src/SensitiveTextarea/SensitiveTextarea.tsx", "../../src/TimingInput/TimingInput.tsx", "../../src/CalendarInput/CalendarInput.tsx", "../../src/CalendarInput/CalendarInput.module.css", "../../src/CalendarInput/CalendarInput.utils.ts", "../../src/chat/BaseChat/BaseChat.tsx", "../../src/chat/BaseChat/BaseChat.module.css", "../../src/chat/ChatModal/ChatModal.tsx", "../../src/chat/ChatModal/ChatModal.module.css", "../../src/chat/ThreadChat/ThreadChat.tsx", "../../src/ResourceTimeline/ResourceTimeline.tsx", "../../src/DiagnosticReportDisplay/DiagnosticReportDisplay.tsx", "../../src/NoteDisplay/NoteDisplay.tsx", "../../src/NoteDisplay/NoteDisplay.module.css", "../../src/ResourceBadge/ResourceBadge.tsx", "../../src/ResourceName/ResourceName.tsx", "../../src/StatusBadge/StatusBadge.tsx", "../../src/DiagnosticReportDisplay/DiagnosticReportDisplay.module.css", "../../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/SearchControl/SearchControl.module.css", "../../src/SearchControl/SearchControlField.ts", "../../src/MeasureReportDisplay/MeasureReportDisplay.tsx", "../../src/MeasureReportDisplay/MeasureReportGroupDisplay/MeasureReportGroupDisplay.tsx", "../../src/NotificationIcon/NotificationIcon.tsx", "../../src/PatientSummary/PatientSummary.tsx", "../../src/PatientSummary/Allergies.tsx", "../../src/PatientSummary/AllergyDialog.tsx", "../../src/PatientSummary/ConceptBadge.tsx", "../../src/PatientSummary/Medications.tsx", "../../src/PatientSummary/MedicationDialog.tsx", "../../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/PatientTimeline/PatientTimeline.tsx", "../../src/PlanDefinitionBuilder/PlanDefinitionBuilder.tsx", "../../src/PlanDefinitionBuilder/PlanDefinitionBuilder.module.css", "../../src/QuestionnaireBuilder/QuestionnaireBuilder.tsx", "../../src/QuestionnaireForm/QuestionnaireFormItem/QuestionnaireFormItem.tsx", "../../src/utils/questionnaire.ts", "../../src/QuestionnaireForm/QuestionnaireForm.context.ts", "../../src/QuestionnaireBuilder/QuestionnaireBuilder.module.css", "../../src/QuestionnaireForm/QuestionnaireForm.tsx", "../../src/QuestionnaireForm/QuestionnaireFormComponents/QuestionnaireFormPageSequence.tsx", "../../src/QuestionnaireForm/QuestionnaireFormItem/QuestionnaireRepeatableItem.tsx", "../../src/QuestionnaireForm/QuestionnaireFormComponents/QuestionnaireFormGroup.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/ServiceRequestTimeline/ServiceRequestTimeline.tsx", "../../src/SmartAppLaunchLink/SmartAppLaunchLink.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Pointer = exports.escapeToken = exports.unescapeToken = void 0;\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}\nexports.unescapeToken = unescapeToken;\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}\nexports.escapeToken = escapeToken;\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 return Pointer;\n}());\nexports.Pointer = Pointer;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.clone = exports.objectType = exports.hasOwnProperty = void 0;\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}\nexports.objectType = objectType;\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_1 = source.length;\n // setting the Array length during construction is faster than just `[]` or `new Array()`\n var arrayTarget = new Array(length_1);\n for (var i = 0; i < length_1; 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}\nexports.clone = clone;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.diffAny = exports.diffObjects = exports.diffArrays = exports.intersection = exports.subtract = exports.isDestructive = void 0;\nvar util_1 = require(\"./util\");\nfunction isDestructive(_a) {\n var op = _a.op;\n return op === 'remove' || op === 'replace' || op === 'copy' || op === 'move';\n}\nexports.isDestructive = isDestructive;\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 // initialize empty object; we only care about the keys, the values can be anything\n var obj = {};\n // build up obj with all the properties of minuend\n for (var add_key in minuend) {\n if (util_1.hasOwnProperty.call(minuend, add_key) && minuend[add_key] !== undefined) {\n obj[add_key] = 1;\n }\n }\n // now delete all the properties of subtrahend from obj\n // (deleting a missing key has no effect)\n for (var del_key in subtrahend) {\n if (util_1.hasOwnProperty.call(subtrahend, del_key) && subtrahend[del_key] !== undefined) {\n delete obj[del_key];\n }\n }\n // finally, extract whatever keys remain in obj\n return Object.keys(obj);\n}\nexports.subtract = subtract;\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}\nexports.intersection = intersection;\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 memo = {\n '0,0': { operations: [], cost: 0 },\n };\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 = \"\".concat(i, \",\").concat(j);\n var memoized = memo[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[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}\nexports.diffArrays = diffArrays;\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 intersection([input, output]).forEach(function (key) {\n operations.push.apply(operations, diff(input[key], output[key], ptr.add(key)));\n });\n return operations;\n}\nexports.diffObjects = diffObjects;\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}\nexports.diffAny = diffAny;\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.apply = exports.InvalidOperationError = exports.test = exports.copy = exports.move = exports.replace = exports.remove = exports.add = exports.TestError = exports.MissingError = void 0;\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) {\n var endpoint = pointer_1.Pointer.fromJSON(operation.path).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 _add(endpoint.parent, endpoint.key, (0, util_1.clone)(operation.value));\n return null;\n}\nexports.add = add;\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) {\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}\nexports.remove = remove;\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) {\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}\nexports.replace = replace;\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) {\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}\nexports.move = move;\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) {\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}\nexports.copy = copy;\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) {\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}\nexports.test = test;\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) {\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);\n case 'remove': return remove(object, operation);\n case 'replace': return replace(object, operation);\n case 'move': return move(object, operation);\n case 'copy': return copy(object, operation);\n case 'test': return test(object, operation);\n }\n return new InvalidOperationError(operation);\n}\nexports.apply = apply;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createTests = exports.createPatch = exports.applyPatch = exports.Pointer = void 0;\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@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) {\n return patch.map(function (operation) { return (0, patch_1.apply)(object, operation); });\n}\nexports.applyPatch = applyPatch;\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}\nexports.createPatch = createPatch;\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}\nexports.createTests = createTests;\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 './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/RegisterForm';\nexport * from './auth/SignInForm';\nexport * from './BackboneElementDisplay/BackboneElementDisplay';\nexport * from './BackboneElementInput/BackboneElementInput';\nexport * from './CalendarInput/CalendarInput';\nexport * from './chat/BaseChat/BaseChat';\nexport * from './chat/ChatModal/ChatModal';\nexport * from './chat/ThreadChat/ThreadChat';\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 './FormSection/FormSection';\nexport * from './HumanNameDisplay/HumanNameDisplay';\nexport * from './HumanNameInput/HumanNameInput';\nexport * from './IdentifierDisplay/IdentifierDisplay';\nexport * from './IdentifierInput/IdentifierInput';\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 './PatientSummary/PatientSummary';\nexport * from './PatientTimeline/PatientTimeline';\nexport * from './PlanDefinitionBuilder/PlanDefinitionBuilder';\nexport * from './QuantityDisplay/QuantityDisplay';\nexport * from './QuantityInput/QuantityInput';\nexport * from './QuestionnaireBuilder/QuestionnaireBuilder';\nexport * from './QuestionnaireForm/QuestionnaireForm';\nexport * from './QuestionnaireForm/QuestionnaireForm.context';\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 './ResourceForm/ResourceForm';\nexport * from './ResourceForm/ResourceForm.utils';\nexport * from './ResourceHistoryTable/ResourceHistoryTable';\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 './SearchControl/SearchControl';\nexport * from './SearchControl/SearchControlField';\nexport * from './SearchControl/SearchUtils';\nexport * from './SearchFieldEditor/SearchFieldEditor';\nexport * from './SearchFilterEditor/SearchFilterEditor';\nexport * from './ServiceRequestTimeline/ServiceRequestTimeline';\nexport * from './SmartAppLaunchLink/SmartAppLaunchLink';\nexport * from './StatusBadge/StatusBadge';\nexport * from './Timeline/Timeline';\nexport * from './TimingInput/TimingInput';\nexport * from './utils/date';\nexport * from './utils/dom';\nexport * from './utils/outcomes';\nexport * from './utils/questionnaire';\nexport * from './utils/recaptcha';\nexport * from './utils/script';\nexport * from './ValueSetAutocomplete/ValueSetAutocomplete';\n", "import { formatAddress } from '@medplum/core';\nimport { Address } from '@medplum/fhirtypes';\n\nexport interface AddressDisplayProps {\n readonly value?: Address;\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)}</>;\n}\n", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { Address } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 };\n}\n\nexport type AddressInputProps = ComplexTypeInputProps<Address>;\n\nexport function AddressInput(props: AddressInputProps): JSX.Element {\n const [value, setValue] = useState<Address>(props.defaultValue || {});\n\n const valueRef = useRef<Address>();\n valueRef.current = value;\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: Address): void {\n setValue(newValue);\n if (props.onChange) {\n props.onChange(newValue);\n }\n }\n\n function setUse(use: 'home' | 'work' | 'temp' | 'old' | 'billing'): void {\n setValueWrapper({ ...valueRef.current, use });\n }\n\n function setType(type: 'postal' | 'physical' | 'both'): void {\n setValueWrapper({ ...valueRef.current, type });\n }\n\n function setLine1(line1: string): void {\n setValueWrapper(setLine(valueRef.current || {}, 0, line1));\n }\n\n function setLine2(line2: string): void {\n setValueWrapper(setLine(valueRef.current || {}, 1, line2));\n }\n\n function setCity(city: string): void {\n setValueWrapper({ ...valueRef.current, city });\n }\n\n function setState(state: string): void {\n setValueWrapper({ ...valueRef.current, state });\n }\n\n function setPostalCode(postalCode: string): void {\n setValueWrapper({ ...valueRef.current, 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", "import { ExtendedInternalSchemaElement, ElementsContextType, 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", "export 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", "import { TextInput } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport { Annotation } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { 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<Annotation>(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", "import { AppShell as MantineAppShell } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport { ReactNode, Suspense, useEffect, useState } from 'react';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { Loading } from '../Loading/Loading';\nimport classes from './AppShell.module.css';\nimport { Header } from './Header';\nimport { Navbar, NavbarMenu } from './Navbar';\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}\n\nexport function AppShell(props: AppShellProps): JSX.Element {\n const [navbarOpen, setNavbarOpen] = useState(localStorage['navbarOpen'] === 'true');\n const medplum = useMedplum();\n const profile = useMedplumProfile();\n\n useEffect(() => {\n function eventListener(): void {\n showNotification({ id: 'offline', color: 'red', message: 'No connection to server', autoClose: false });\n }\n medplum.addEventListener('offline', eventListener);\n return () => medplum.removeEventListener('offline', eventListener);\n }, [medplum]);\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 return (\n <MantineAppShell\n header={{ height: 60 }}\n navbar={{\n width: 250,\n breakpoint: 'sm',\n collapsed: {\n desktop: !profile || !navbarOpen,\n mobile: !profile || !navbarOpen,\n },\n }}\n padding={0}\n >\n {profile && (\n <Header\n pathname={props.pathname}\n searchParams={props.searchParams}\n headerSearchDisabled={props.headerSearchDisabled}\n logo={props.logo}\n version={props.version}\n navbarToggle={toggleNavbar}\n notifications={props.notifications}\n />\n )}\n {profile && navbarOpen ? (\n <Navbar\n pathname={props.pathname}\n searchParams={props.searchParams}\n menus={props.menus}\n closeNavbar={closeNavbar}\n displayAddBookmark={props.displayAddBookmark}\n resourceTypeSearchDisabled={props.resourceTypeSearchDisabled}\n />\n ) : undefined}\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", "import { Alert } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport { Component, ErrorInfo, ReactNode } 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: window.location.toString() };\n }\n\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n return { error, lastLocation: window.location.toString() };\n }\n\n componentDidUpdate(_prevProps: ErrorBoundaryProps, _prevState: ErrorBoundaryState): void {\n if (window.location.toString() !== this.state.lastLocation) {\n this.setState({\n lastLocation: window.location.toString(),\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 !== window.location.toString()) {\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 createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'adjustments-horizontal', 'IconAdjustmentsHorizontal', [[\"path\",{\"d\":\"M14 6m-2 0a2 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\":\"M8 12m-2 0a2 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\":\"M17 18m-2 0a2 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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'alert-circle', 'IconAlertCircle', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-down', 'IconArrowDown', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-right', 'IconArrowRight', [[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M13 18l6 -6\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M13 6l6 6\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-up', 'IconArrowUp', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bleach-off', 'IconBleachOff', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bleach', 'IconBleach', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'box-multiple', 'IconBoxMultiple', [[\"path\",{\"d\":\"M7 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'brackets-contain', 'IconBracketsContain', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bucket-off', 'IconBucketOff', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bucket', 'IconBucket', [[\"path\",{\"d\":\"M12 7m-8 0a8 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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'calendar', 'IconCalendar', [[\"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-12z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'check', 'IconCheck', [[\"path\",{\"d\":\"M5 12l5 5l10 -10\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'checkbox', 'IconCheckbox', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'chevron-down', 'IconChevronDown', [[\"path\",{\"d\":\"M6 9l6 6l6 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'chevron-up', 'IconChevronUp', [[\"path\",{\"d\":\"M6 15l6 -6l6 6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'circle-minus', 'IconCircleMinus', [[\"path\",{\"d\":\"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M9 12l6 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'circle-plus', 'IconCirclePlus', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'cloud-upload', 'IconCloudUpload', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'columns', 'IconColumns', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'copy', 'IconCopy', [[\"path\",{\"d\":\"M7 7m0 2.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.667z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'currency-dollar', 'IconCurrencyDollar', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'dots', 'IconDots', [[\"path\",{\"d\":\"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'edit', 'IconEdit', [[\"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.415z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M16 5l3 3\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'equal-not', 'IconEqualNot', [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M5 19l14 -14\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'equal', 'IconEqual', [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'file-alert', 'IconFileAlert', [[\"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 2z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 17l.01 0\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M12 11l0 3\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'file-plus', 'IconFilePlus', [[\"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 2z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 11l0 6\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M9 14l6 0\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'filter', 'IconFilter', [[\"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.227z\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'gender-female', 'IconGenderFemale', [[\"path\",{\"d\":\"M12 9m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M12 14v7\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M9 18h6\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'gender-male', 'IconGenderMale', [[\"path\",{\"d\":\"M10 14m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M19 5l-5.4 5.4\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M19 5h-5\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M19 5v5\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'logout', 'IconLogout', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'math-greater', 'IconMathGreater', [[\"path\",{\"d\":\"M5 18l14 -6l-14 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'math-lower', 'IconMathLower', [[\"path\",{\"d\":\"M19 18l-14 -6l14 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'message', 'IconMessage', [[\"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 -3h12z\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'plus', 'IconPlus', [[\"path\",{\"d\":\"M12 5l0 14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'refresh', 'IconRefresh', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'search', 'IconSearch', [[\"path\",{\"d\":\"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M21 21l-6 -6\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'settings', 'IconSettings', [[\"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.065z\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'sort-ascending', 'IconSortAscending', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'sort-descending', 'IconSortDescending', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'square', 'IconSquare', [[\"path\",{\"d\":\"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'stethoscope', 'IconStethoscope', [[\"path\",{\"d\":\"M6 4h-1a2 2 0 0 0 -2 2v3.5h0a5.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\":\"M20 10m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\",\"key\":\"svg-4\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'switch-horizontal', 'IconSwitchHorizontal', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'table-export', 'IconTableExport', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'trash', 'IconTrash', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'user-square', 'IconUserSquare', [[\"path\",{\"d\":\"M9 10a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M6 21v-1a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v1\",\"key\":\"svg-1\"}],[\"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-14z\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'x', 'IconX', [[\"path\",{\"d\":\"M18 6l-12 12\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M6 6l12 12\",\"key\":\"svg-1\"}]]);", "import { Center, Loader } from '@mantine/core';\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 padding-bottom: var(--mantine-spacing-lg);\n overflow-x: auto;\n}\n", "import { Group, AppShell as MantineAppShell, Menu, Text, UnstyledButton } from '@mantine/core';\nimport { formatHumanName } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { ReactNode, useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport classes from './Header.module.css';\nimport { HeaderDropdown } from './HeaderDropdown';\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 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 className={classes.logoButton} onClick={props.navbarToggle}>\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=\"xl\"\n position=\"bottom-end\"\n transitionProps={{ transition: 'pop-top-right' }}\n opened={userMenuOpened}\n onClose={() => setUserMenuOpened(false)}\n >\n <Menu.Target>\n <UnstyledButton\n className={cx(classes.user, { [classes.userActive]: userMenuOpened })}\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] as HumanName)}\n </Text>\n <IconChevronDown size={12} stroke={1.5} />\n </Group>\n </UnstyledButton>\n </Menu.Target>\n <Menu.Dropdown>\n <HeaderDropdown version={props.version} />\n </Menu.Dropdown>\n </Menu>\n </Group>\n </Group>\n </MantineAppShell.Header>\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;", "import { Avatar, AvatarProps } from '@mantine/core';\nimport { getDisplayString, getImageSrc } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl, useResource } from '@medplum/react-hooks';\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", "import { Anchor, TextProps } from '@mantine/core';\nimport { isReference, isResource } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport { MouseEvent, MouseEventHandler, ReactNode } from 'react';\nimport { killEvent } from '../utils/dom';\n\nexport interface MedplumLinkProps extends TextProps {\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 onClick={(e: MouseEvent) => {\n killEvent(e);\n if (onClick) {\n onClick(e);\n } else if (to) {\n navigate(href);\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", "import { 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 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", "export function getInitials(input: string): string {\n const words = input.split(' ').filter(Boolean);\n if (words.length > 1) {\n return words[0][0] + words[words.length - 1][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\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\n.userActive {\n background-color: var(--mantine-primary-color-light-hover);\n}\n", "import {\n Avatar,\n Group,\n MantineColorScheme,\n Menu,\n SegmentedControl,\n Stack,\n Text,\n useMantineColorScheme,\n} from '@mantine/core';\nimport { ProfileResource, getReferenceString } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useMedplumContext } from '@medplum/react-hooks';\nimport { IconLogout, IconSettings, IconSwitchHorizontal } from '@tabler/icons-react';\nimport { HumanNameDisplay } from '../HumanNameDisplay/HumanNameDisplay';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\n\nexport interface HeaderDropdownProps {\n readonly version?: string;\n}\n\nexport function HeaderDropdown(props: HeaderDropdownProps): JSX.Element {\n const context = useMedplumContext();\n const { medplum, profile, navigate } = context;\n const logins = medplum.getLogins();\n const { colorScheme, setColorScheme } = useMantineColorScheme();\n\n return (\n <>\n <Stack align=\"center\" p=\"xl\">\n <ResourceAvatar size=\"xl\" radius={100} value={context.profile} />\n <HumanNameDisplay value={context.profile?.name?.[0] as HumanName} />\n <Text c=\"dimmed\" size=\"xs\">\n {medplum.getActiveLogin()?.project.display}\n </Text>\n </Stack>\n {logins.length > 1 && <Menu.Divider />}\n {logins.map(\n (login) =>\n login.profile.reference !== getReferenceString(context.profile as ProfileResource) && (\n <Menu.Item\n key={login.profile.reference}\n onClick={() => {\n medplum\n .setActiveLogin(login)\n .then(() => window.location.reload())\n .catch(console.log);\n }}\n >\n <Group>\n <Avatar radius=\"xl\" />\n <div style={{ flex: 1 }}>\n <Text size=\"sm\" fw={500}>\n {login.profile.display}\n </Text>\n <Text c=\"dimmed\" size=\"xs\">\n {login.project.display}\n </Text>\n </div>\n </Group>\n </Menu.Item>\n )\n )}\n <Menu.Divider />\n <Group justify=\"center\">\n <SegmentedControl\n size=\"xs\"\n value={colorScheme}\n onChange={(newValue) => setColorScheme(newValue as MantineColorScheme)}\n data={[\n { label: 'Light', value: 'light' },\n { label: 'Dark', value: 'dark' },\n { label: 'Auto', value: 'auto' },\n ]}\n />\n </Group>\n <Menu.Divider />\n <Menu.Item leftSection={<IconSwitchHorizontal size={14} stroke={1.5} />} onClick={() => navigate('/signin')}>\n Add another account\n </Menu.Item>\n <Menu.Item\n leftSection={<IconSettings size={14} stroke={1.5} />}\n onClick={() => navigate(`/${getReferenceString(profile as ProfileResource)}`)}\n >\n Account settings\n </Menu.Item>\n <Menu.Item\n leftSection={<IconLogout size={14} stroke={1.5} />}\n onClick={async () => {\n await medplum.signOut();\n navigate('/signin');\n }}\n >\n Sign out\n </Menu.Item>\n <Text size=\"xs\" c=\"dimmed\" ta=\"center\">\n {props.version}\n </Text>\n </>\n );\n}\n", "import { formatHumanName, HumanNameFormatOptions } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\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", "import { Group, Text } from '@mantine/core';\nimport { formatHumanName, getDisplayString, getReferenceString, isUUID } from '@medplum/core';\nimport { Patient, ServiceRequest } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport { forwardRef, useCallback } from 'react';\nimport { AsyncAutocomplete, AsyncAutocompleteOption } 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 }`.replace(/\\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 }`.replace(/\\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", "import {\n Combobox,\n ComboboxItem,\n ComboboxProps,\n Group,\n Loader,\n Pill,\n PillsInput,\n ScrollAreaAutosize,\n useCombobox,\n} from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconCheck } from '@tabler/icons-react';\nimport { KeyboardEvent, ReactNode, SyntheticEvent, useCallback, useEffect, 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>\n extends Omit<ComboboxProps, 'data' | 'defaultValue' | 'loadOptions' | 'onChange' | 'onCreate' | 'searchable'> {\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<AsyncAutocompleteOption<T>[]>(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<string>();\n searchRef.current = search;\n\n const lastLoadOptionsRef = useRef<AsyncAutocompleteProps<T>['loadOptions']>();\n const lastValueRef = useRef<string>();\n\n const timerRef = useRef<number>();\n timerRef.current = timer;\n\n const abortControllerRef = useRef<AbortController>();\n abortControllerRef.current = abortController;\n\n const autoSubmitRef = useRef<boolean>();\n autoSubmitRef.current = autoSubmit;\n\n const optionsRef = useRef<AsyncAutocompleteOption<T>[]>();\n optionsRef.current = options;\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 item: AsyncAutocompleteOption<T>;\n disabled?: boolean;\n 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", "export 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", "import { Button, AppShell as MantineAppShell, ScrollArea, Space, Text } from '@mantine/core';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconPlus } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { Fragment, MouseEventHandler, ReactNode, SyntheticEvent, useState } from 'react';\nimport { BookmarkDialog } from '../BookmarkDialog/BookmarkDialog';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport classes from './Navbar.module.css';\n\nexport interface NavbarLink {\n readonly icon?: JSX.Element;\n readonly label?: string;\n readonly href: string;\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 menus?: NavbarMenu[];\n readonly closeNavbar: () => void;\n readonly displayAddBookmark?: boolean;\n readonly resourceTypeSearchDisabled?: boolean;\n}\n\nexport function Navbar(props: NavbarProps): JSX.Element {\n const navigate = useMedplumNavigate();\n const activeLink = getActiveLink(props.pathname, props.searchParams, props.menus);\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 return (\n <>\n <MantineAppShell.Navbar>\n <ScrollArea p=\"xs\">\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 <MantineAppShell.Section grow>\n {props.menus?.map((menu) => (\n <Fragment key={`menu-${menu.title}`}>\n <Text className={classes.menuTitle}>{menu.title}</Text>\n {menu.links?.map((link) => (\n <NavbarLink\n key={link.href}\n to={link.href}\n active={link.href === activeLink?.href}\n onClick={(e) => onLinkClick(e, link.href)}\n >\n <NavLinkIcon to={link.href} icon={link.icon} />\n <span>{link.label}</span>\n </NavbarLink>\n ))}\n </Fragment>\n ))}\n {props.displayAddBookmark && (\n <Button\n variant=\"subtle\"\n size=\"xs\"\n mt=\"xl\"\n leftSection={<IconPlus size=\"0.75rem\" />}\n onClick={() => setBookmarkDialogVisible(true)}\n >\n Add Bookmark\n </Button>\n )}\n </MantineAppShell.Section>\n </ScrollArea>\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 NavbarLinkProps {\n readonly to: string;\n readonly active: boolean;\n readonly onClick: MouseEventHandler;\n readonly children: ReactNode;\n}\n\nfunction NavbarLink(props: NavbarLinkProps): JSX.Element {\n return (\n <MedplumLink\n onClick={props.onClick}\n to={props.to}\n className={cx(classes.link, { [classes.linkActive]: props.active })}\n >\n {props.children}\n </MedplumLink>\n );\n}\n\ninterface NavLinkIconProps {\n readonly to: string;\n readonly icon?: JSX.Element;\n}\n\nfunction NavLinkIcon(props: NavLinkIconProps): JSX.Element {\n if (props.icon) {\n return props.icon;\n }\n return <Space w={30} />;\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", "import { Button, Group, Modal, NativeSelect, Stack, TextInput } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { deepClone, normalizeErrorString } from '@medplum/core';\nimport { UserConfiguration } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Form } from '../Form/Form';\n\ninterface BookmarkDialogProps {\n readonly pathname: string;\n readonly searchParams: URLSearchParams;\n readonly visible: boolean;\n readonly onOk: () => void;\n readonly onCancel: () => void;\n readonly defaultValue?: string;\n}\nexport function BookmarkDialog(props: BookmarkDialogProps): JSX.Element | null {\n const medplum = useMedplum();\n const config = medplum.getUserConfiguration() as 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) as UserConfiguration;\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 label=\"Bookmark Name\" type=\"text\" name=\"bookmarkname\" placeholder=\"Bookmark Name\" withAsterisk />\n <Group justify=\"flex-end\">\n <Button mt=\"sm\" type=\"submit\">\n OK\n </Button>\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", "/**\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", "import { CSSProperties, ReactNode, SyntheticEvent } from 'react';\nimport { parseForm } from './FormUtils';\n\nexport interface FormProps {\n readonly onSubmit?: (formData: Record<string, string>) => void;\n readonly style?: CSSProperties;\n readonly children?: ReactNode;\n readonly testid?: string;\n}\n\nexport function Form(props: FormProps): JSX.Element {\n return (\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 props.onSubmit(formData);\n }\n }}\n >\n {props.children}\n </form>\n );\n}\n", "import { ResourceType } from '@medplum/fhirtypes';\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<string | undefined>(props.defaultValue);\n const onChange = props.onChange;\n\n const setResourceTypeWrapper = useCallback(\n (newResourceType: string | undefined) => {\n setResourceType(newResourceType);\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", "import { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } 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<string | undefined>(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", "import { Group, Text } from '@mantine/core';\nimport { ValueSetExpandParams } from '@medplum/core';\nimport { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { forwardRef, useCallback } from 'react';\nimport {\n AsyncAutocomplete,\n AsyncAutocompleteOption,\n AsyncAutocompleteProps,\n} from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { IconCheck } from '@tabler/icons-react';\n\nexport interface ValueSetAutocompleteProps\n extends Omit<AsyncAutocompleteProps<ValueSetExpansionContains>, 'loadOptions' | 'toKey' | 'toOption'> {\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 ...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", ".menuTitle {\n margin: 20px 0 4px 6px;\n font-size: 9px;\n font-weight: normal;\n text-transform: uppercase;\n letter-spacing: 2px;\n}\n\n.link {\n display: flex;\n align-items: center;\n text-decoration: none;\n font-size: var(--mantine-font-size-sm);\n color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n padding: 8px 12px;\n border-radius: var(--mantine-radius-sm);\n font-weight: 500;\n\n &:hover {\n background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n color: light-dark(var(--mantine-color-black), var(--mantine-color-white));\n text-decoration: none;\n\n & svg {\n color: light-dark(var(--mantine-color-black), var(--mantine-color-white));\n }\n }\n\n & svg {\n color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));\n margin-right: var(--mantine-spacing-sm);\n stroke-width: 1.5;\n width: 18px;\n height: 18px;\n }\n}\n\n.linkActive {\n color: var(--mantine-primary-color-filled);\n background-color: light-dark(var(--mantine-primary-color-light), var(--mantine-primary-color-dark));\n\n &:hover {\n color: var(--mantine-primary-color-filled-hover);\n background-color: light-dark(var(--mantine-primary-color-light-hover), var(--mantine-primary-color-dark-hover));\n\n & svg {\n color: var(--mantine-color-blue-light-color);\n }\n }\n\n & svg {\n color: var(--mantine-color-blue-light-color);\n }\n}\n", "import { Anchor } from '@mantine/core';\nimport { ContentType } from '@medplum/core';\nimport { Attachment } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl } from '@medplum/react-hooks';\nimport { CcdaDisplay } from '../CcdaDisplay/CcdaDisplay';\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 <img 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 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", "import { useEffect, useRef, useState } from 'react';\nimport { sendCommand } from '../utils/dom';\n\nconst CCDA_VIEWER_URL = 'https://ccda.medplum.com';\n\nexport interface CcdaDisplayProps {\n readonly url?: string;\n readonly maxWidth?: number;\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\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 if (!url) {\n return null;\n }\n\n return (\n <div data-testid=\"ccda-iframe\" style={{ maxWidth: props.maxWidth, 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}\n", ".root {\n display: grid;\n grid-template-columns: 30% 70%;\n margin: 0;\n\n & > dt,\n & > dd {\n padding: var(--mantine-spacing-sm);\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 padding-top: 0;\n }\n\n & > dt:last-of-type,\n & > dd:last-of-type {\n padding-bottom: 0;\n }\n}\n\n.compact {\n grid-template-columns: auto 1fr;\n\n & > dt,\n & > dd {\n padding: 0 0 var(--mantine-spacing-xs);\n border-top: 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: 0;\n }\n}\n", "import cx from 'clsx';\nimport { 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", "import { Attachment } from '@medplum/fhirtypes';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { InternalSchemaElement, getPathDisplayName, isPopulated } from '@medplum/core';\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", "import { ActionIcon } from '@mantine/core';\nimport { Attachment } from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCloudUpload } from '@tabler/icons-react';\nimport { MouseEvent, useRef, 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<Attachment[]>(props.defaultValue ?? []);\n\n const valuesRef = useRef<Attachment[]>();\n valuesRef.current = values;\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([...(valuesRef.current as Attachment[]), 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", "import { normalizeOperationOutcome } from '@medplum/core';\nimport { Attachment, OperationOutcome, Reference } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ChangeEvent, MouseEvent, ReactNode, 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 {props.children({ onClick, disabled: props.disabled })}\n </>\n );\n}\n", "import { Button } from '@mantine/core';\nimport { Attachment, Reference } from '@medplum/fhirtypes';\nimport { MouseEvent, useState } from 'react';\nimport { AttachmentButton } from '../AttachmentButton/AttachmentButton';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { killEvent } from '../utils/dom';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\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", "import { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useEffect, useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { NewProjectForm } from './NewProjectForm';\nimport { NewUserForm } from './NewUserForm';\n\nexport interface RegisterFormProps {\n readonly type: 'patient' | 'project';\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>();\n const [outcome, setOutcome] = useState<OperationOutcome>();\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(console.log);\n } else if (response.login) {\n setLogin(response.login);\n }\n }\n\n return (\n <Document width={450}>\n {outcome && <pre>{JSON.stringify(outcome, null, 2)}</pre>}\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 {login && type === 'project' && <NewProjectForm login={login} handleAuthResponse={handleAuthResponse} />}\n </Document>\n );\n}\n", "import { ContainerProps, Container as MantineContainer } from '@mantine/core';\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", "import { Paper, PaperProps } from '@mantine/core';\nimport cx from 'clsx';\nimport { 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", "import { Container } from '../Container/Container';\nimport { Panel, PanelProps } 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", "import { Anchor, Button, Center, Group, Stack, Text, TextInput, Title } from '@mantine/core';\nimport { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\nimport { getErrorsForInput } 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 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 <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Create project</Title>\n </Center>\n <Stack gap=\"xl\">\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 <Text c=\"dimmed\" size=\"xs\">\n By clicking submit you agree to the Medplum{' '}\n <Anchor href=\"https://www.medplum.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://www.medplum.com/terms\">Terms of Service</Anchor>.\n </Text>\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\" wrap=\"nowrap\">\n <Button type=\"submit\">Create project</Button>\n </Group>\n </Form>\n );\n}\n", "export interface LogoProps {\n readonly size: number;\n readonly fill?: string;\n}\n\nexport function Logo(props: LogoProps): JSX.Element {\n return (\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 491 491\" style={{ width: props.size, height: props.size }}>\n <title>Medplum Logo</title>\n <path fill={props.fill ?? '#ad7136'} d=\"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z\" />\n <path\n fill={props.fill ?? '#946af9'}\n d=\"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z\"\n />\n <path\n fill={props.fill ?? '#7857c5'}\n d=\"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z\"\n />\n <path\n fill={props.fill ?? '#40bc26'}\n d=\"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z\"\n />\n <path fill={props.fill ?? '#33961e'} d=\"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z\" />\n </svg>\n );\n}\n", "import { 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", "import { Anchor, Button, Center, Checkbox, Divider, Group, PasswordInput, Stack, Text, TextInput } from '@mantine/core';\nimport { GoogleCredentialResponse, LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useEffect, useState } from 'react';\nimport { Form } from '../Form/Form';\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 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 <Center style={{ flexDirection: 'column' }}>{props.children}</Center>\n <OperationOutcomeAlert issues={issues} />\n {googleClientId && (\n <>\n <Group justify=\"center\" p=\"xl\" style={{ height: 70 }}>\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 </Group>\n <Divider label=\"or\" labelPosition=\"center\" my=\"lg\" />\n </>\n )}\n <Stack gap=\"xl\">\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 <Text c=\"dimmed\" size=\"xs\">\n By clicking submit you agree to the Medplum{' '}\n <Anchor href=\"https://www.medplum.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://www.medplum.com/terms\">Terms of Service</Anchor>.\n </Text>\n <Text c=\"dimmed\" size=\"xs\">\n This site is protected by reCAPTCHA and the Google{' '}\n <Anchor href=\"https://policies.google.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://policies.google.com/terms\">Terms of Service</Anchor> apply.\n </Text>\n </Stack>\n <Group justify=\"space-between\" mt=\"xl\" wrap=\"nowrap\">\n <Checkbox name=\"remember\" label=\"Remember me\" size=\"xs\" />\n <Button type=\"submit\">Create account</Button>\n </Group>\n </Form>\n );\n}\n", "import { GoogleCredentialResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\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 medplum = useMedplum();\n const { googleClientId, handleGoogleCredential } = props;\n const parentRef = useRef<HTMLDivElement>(null);\n const [scriptLoaded, setScriptLoaded] = useState<boolean>(typeof google !== 'undefined');\n const [initialized, setInitialized] = useState(false);\n const [buttonRendered, setButtonRendered] = useState(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 (!initialized) {\n google.accounts.id.initialize({\n client_id: googleClientId,\n callback: handleGoogleCredential,\n });\n setInitialized(true);\n }\n\n if (parentRef.current && !buttonRendered) {\n google.accounts.id.renderButton(parentRef.current, {});\n setButtonRendered(true);\n }\n }, [medplum, googleClientId, initialized, scriptLoaded, parentRef, buttonRendered, handleGoogleCredential]);\n\n if (!googleClientId) {\n return null;\n }\n\n return <div ref={parentRef} />;\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", "export function getGoogleClientId(clientId: string | undefined): string | undefined {\n if (clientId) {\n return clientId;\n }\n\n if (typeof window !== 'undefined') {\n const origin = window.location.protocol + '//' + window.location.host;\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", "import { Alert } from '@mantine/core';\nimport { operationOutcomeIssueToString } from '@medplum/core';\nimport { OperationOutcome, OperationOutcomeIssue } from '@medplum/fhirtypes';\nimport { IconAlertCircle } from '@tabler/icons-react';\n\nexport interface OperationOutcomeAlertProps {\n readonly outcome?: OperationOutcome;\n readonly issues?: OperationOutcomeIssue[];\n}\n\nexport function OperationOutcomeAlert(props: OperationOutcomeAlertProps): JSX.Element | null {\n const issues = props.outcome?.issue || props.issues;\n if (!issues || issues.length === 0) {\n return null;\n }\n return (\n <Alert icon={<IconAlertCircle size={16} />} color=\"red\">\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", "import { 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", "import { showNotification } from '@mantine/notifications';\nimport { BaseLoginRequest, LoginAuthenticationResponse, normalizeErrorString } from '@medplum/core';\nimport { ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, 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 [mfaRequired, setAuthenticatorRequired] = 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) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n }\n },\n [medplum, onCode, onSuccess]\n );\n\n const handleAuthResponse = useCallback(\n (response: LoginAuthenticationResponse): void => {\n setAuthenticatorRequired(!!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 as string);\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) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n }\n }, [medplum, loginCode, loginRequested, login, handleAuthResponse]);\n\n return (\n <Document width={450} px=\"sm\" py=\"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 (mfaRequired) {\n return (\n <MfaForm\n onSubmit={async (fields) => {\n const res = await medplum.post('auth/mfa/verify', {\n login: login,\n token: fields.token,\n });\n handleAuthResponse(res);\n }}\n />\n );\n } else if (memberships) {\n return <ChooseProfileForm login={login} memberships={memberships} handleAuthResponse={handleAuthResponse} />;\n } else if (props.projectId === 'new') {\n return <NewProjectForm login={login} 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", "import { Anchor, Button, Center, Checkbox, Divider, Group, PasswordInput, Stack, TextInput } from '@mantine/core';\nimport {\n BaseLoginRequest,\n GoogleCredentialResponse,\n GoogleLoginRequest,\n LoginAuthenticationResponse,\n normalizeOperationOutcome,\n} from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useCallback, useState } from 'react';\nimport { Form } from '../Form/Form';\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} {...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 });\n const url = new URL(authMethod.authorizeUrl);\n url.searchParams.set('state', state);\n window.location.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 <Center style={{ flexDirection: 'column' }}>{children}</Center>\n <OperationOutcomeAlert issues={issues} />\n {googleClientId && (\n <>\n <Group justify=\"center\" p=\"xl\" style={{ height: 70 }}>\n <GoogleButton googleClientId={googleClientId} handleGoogleCredential={handleGoogleCredential} />\n </Group>\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 placeholder=\"name@domain.com\"\n required={true}\n autoFocus={true}\n error={getErrorsForInput(outcome, 'email')}\n />\n )}\n <Group justify=\"space-between\" mt=\"xl\" gap={0} wrap=\"nowrap\">\n <div>\n {onRegister && (\n <Anchor component=\"button\" type=\"button\" color=\"dimmed\" onClick={onRegister} size=\"xs\">\n Register\n </Anchor>\n )}\n </div>\n {!disableEmailAuth && <Button type=\"submit\">Next</Button>}\n </Group>\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 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) => setOutcome(normalizeOperationOutcome(err)));\n },\n [medplum, baseLoginRequest, handleAuthResponse]\n );\n\n return (\n <Form onSubmit={handleSubmit}>\n <Center style={{ flexDirection: 'column' }}>{children}</Center>\n <OperationOutcomeAlert issues={issues} />\n <Stack gap=\"xl\">\n <PasswordInput\n name=\"password\"\n label=\"Password\"\n autoComplete=\"off\"\n required={true}\n autoFocus={true}\n error={getErrorsForInput(outcome, 'password')}\n />\n </Stack>\n <Group justify=\"space-between\" mt=\"xl\" gap={0} wrap=\"nowrap\">\n {onForgotPassword && (\n <Anchor component=\"button\" type=\"button\" c=\"dimmed\" onClick={onForgotPassword} size=\"xs\">\n Forgot password\n </Anchor>\n )}\n <Checkbox id=\"remember\" name=\"remember\" label=\"Remember me\" size=\"xs\" style={{ lineHeight: 1 }} />\n <Button type=\"submit\">Sign in</Button>\n </Group>\n </Form>\n );\n}\n", "import { Avatar, Combobox, Flex, Group, Stack, Text, TextInput, Title, useCombobox } from '@mantine/core';\nimport { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome, ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\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 filterDisplay(membership.profile?.display) || filterDisplay(membership.project?.display);\n }\n\n function handleValueSelect(membershipId: string): void {\n medplum\n .post('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}>\n <SelectOption {...item} />\n </Combobox.Option>\n ));\n\n return (\n <Stack>\n <Flex gap=\"md\" mb=\"md\" justify=\"center\" align=\"center\" direction=\"column\" wrap=\"nowrap\">\n <Logo size={32} />\n <Title order={3}>Choose profile</Title>\n </Flex>\n <OperationOutcomeAlert outcome={outcome} />\n <Combobox store={combobox} onOptionSubmit={handleValueSelect}>\n <Combobox.EventsTarget>\n <TextInput\n placeholder=\"Search\"\n value={search}\n onChange={(event) => {\n setSearch(event.currentTarget.value);\n combobox.updateSelectedOptionIndex();\n }}\n />\n </Combobox.EventsTarget>\n\n <div>\n <Combobox.Options>\n {options.length > 0 ? options : <Combobox.Empty>Nothing found...</Combobox.Empty>}\n </Combobox.Options>\n </div>\n </Combobox>\n </Stack>\n );\n}\n\nfunction SelectOption(membership: ProjectMembership): JSX.Element {\n return (\n <Group>\n <Avatar radius=\"xl\" />\n <div>\n <Text fz=\"sm\" fw={500}>\n {membership.profile?.display}\n </Text>\n <Text fz=\"xs\" opacity={0.6}>\n {membership.project?.display}\n </Text>\n </div>\n </Group>\n );\n}\n", "import { Button, Center, Checkbox, Group, Stack, Title } from '@mantine/core';\nimport { LoginAuthenticationResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Form } from '../Form/Form';\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\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('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 <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Choose scope</Title>\n </Center>\n <Stack>\n {(props.scope ?? 'openid').split(' ').map((scopeName: string) => (\n <Checkbox key={scopeName} id={scopeName} name={scopeName} label={scopeName} defaultChecked />\n ))}\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\">\n <Button type=\"submit\">Set scope</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Alert, Button, Center, Group, Stack, TextInput, Title } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\n\nexport type MfaFormFields = 'token';\n\nexport interface MfaFormProps {\n readonly onSubmit: (formData: Record<MfaFormFields, string>) => 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 <Stack>\n <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Enter MFA code</Title>\n </Center>\n {errorMessage && (\n <Alert icon={<IconAlertCircle size={16} />} title=\"Error\" color=\"red\">\n {errorMessage}\n </Alert>\n )}\n <Stack>\n <TextInput name=\"token\" label=\"MFA code\" required autoFocus />\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\">\n <Button type=\"submit\">Submit code</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import {\n buildElementsContext,\n ElementsContextType,\n getPathDisplayName,\n isEmpty,\n tryGetDataType,\n TypedValue,\n} from '@medplum/core';\nimport { DEFAULT_IGNORED_NON_NESTED_PROPERTIES, DEFAULT_IGNORED_PROPERTIES } from '../constants';\nimport { DescriptionList, DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { useContext, useMemo } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\nimport { AccessPolicyResource } from '@medplum/fhirtypes';\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} 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", "import { ActionIcon, Box, CopyButton, Tooltip } from '@mantine/core';\nimport {\n InternalSchemaElement,\n PropertyType,\n formatDateTime,\n formatPeriod,\n formatTiming,\n isEmpty,\n} from '@medplum/core';\nimport { IconCheck, IconCopy } from '@tabler/icons-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 { 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';\nimport { ExtensionDisplay } from '../ExtensionDisplay/ExtensionDisplay';\nimport { ElementDefinitionType } from '@medplum/fhirtypes';\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 <Box component=\"div\" style={{ display: 'flex', gap: 3, alignItems: '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 </Box>\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 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 return <>{value}</>;\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.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 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 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 Error(`Displaying property of type ${props.propertyType} requires element schema`);\n }\n if (!props.path) {\n throw 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", "import { formatCodeableConcept } from '@medplum/core';\nimport { CodeableConcept } from '@medplum/fhirtypes';\n\nexport interface CodeableConceptDisplayProps {\n readonly value?: CodeableConcept;\n}\n\nexport function CodeableConceptDisplay(props: CodeableConceptDisplayProps): JSX.Element {\n return <>{formatCodeableConcept(props.value)}</>;\n}\n", "import { formatCoding } from '@medplum/core';\nimport { Coding } from '@medplum/fhirtypes';\n\nexport interface CodingDisplayProps {\n readonly value?: Coding;\n}\n\nexport function CodingDisplay(props: CodingDisplayProps): JSX.Element {\n return <>{formatCoding(props.value)}</>;\n}\n", "import { ContactPoint } from '@medplum/fhirtypes';\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", "import { ContactDetail } from '@medplum/fhirtypes';\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", "import { Identifier } from '@medplum/fhirtypes';\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", "import { formatMoney } from '@medplum/core';\nimport { Money } from '@medplum/fhirtypes';\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", "import { formatQuantity } from '@medplum/core';\nimport { Quantity } from '@medplum/fhirtypes';\n\nexport interface QuantityDisplayProps {\n readonly value?: Quantity;\n}\n\nexport function QuantityDisplay(props: QuantityDisplayProps): JSX.Element | null {\n return <>{formatQuantity(props.value)}</>;\n}\n", "import { formatRange } from '@medplum/core';\nimport { Range } from '@medplum/fhirtypes';\n\nexport interface RangeDisplayProps {\n readonly value?: Range;\n}\n\nexport function RangeDisplay(props: RangeDisplayProps): JSX.Element | null {\n return <>{formatRange(props.value)}</>;\n}\n", "import { Ratio } from '@medplum/fhirtypes';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\n\nexport interface RatioDisplayProps {\n readonly value?: Ratio;\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} />\n / \n <QuantityDisplay value={value.denominator} />\n </>\n );\n}\n", "import { stringify } from '@medplum/core';\nimport { Reference } from '@medplum/fhirtypes';\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", "import { InternalSchemaElement, SliceDefinitionWithTypes, getPathDisplayName, isPopulated } from '@medplum/core';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { useState, useContext, useEffect, useMemo } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { prepareSlices, assignValuesIntoSlices } from '../ResourceArrayInput/ResourceArrayInput.utils';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { SliceDisplay } from '../SliceDisplay/SliceDisplay';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\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 ctx = useContext(ElementsContext);\n\n useEffect(() => {\n prepareSlices({\n medplum,\n property,\n })\n .then((slices) => {\n setSlices(slices);\n const slicedValues = assignValuesIntoSlices(values, 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 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 </>\n );\n}\n", "import {\n InternalSchemaElement,\n MedplumClient,\n SliceDefinitionWithTypes,\n SlicingRules,\n getValueSliceName,\n isPopulated,\n isSliceDefinitionWithTypes,\n tryGetProfile,\n} 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", "import {\n SliceDefinitionWithTypes,\n InternalSchemaElement,\n ElementsContextType,\n buildElementsContext,\n isPopulated,\n} from '@medplum/core';\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", "import { Context } 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", "import {\n ElementType,\n InternalTypeSchema,\n getDataType,\n isPopulated,\n isProfileLoaded,\n tryGetProfile,\n} from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\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<InternalTypeSchema>(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 as string, value: props.value }}\n compact={props.compact}\n ignoreMissingValues={props.ignoreMissingValues}\n link={props.link}\n profileUrl={profileUrl}\n />\n );\n}\n", "import {\n getTypedPropertyValue,\n getTypedPropertyValueWithSchema,\n InternalSchemaElement,\n TypedValue,\n} 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", "import { ElementsContextType, buildElementsContext, tryGetDataType } from '@medplum/core';\nimport { AccessPolicyResource } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsInput } from '../ElementsInput/ElementsInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\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} not implemented</div>;\n }\n\n return maybeWrapWithContext(\n ElementsContext.Provider,\n contextValue,\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 );\n}\n", "import { Stack } from '@mantine/core';\nimport { TypedValue, getPathDisplayName } from '@medplum/core';\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 { EXTENSION_KEYS, ElementsContext, getElementsToRender } from './ElementsInput.utils';\nimport { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.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<any>(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", "import { Group, Input } from '@mantine/core';\nimport { ReactNode, useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\nimport classes from '../FormSection/FormSection.module.css';\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", "import { Tooltip } from '@mantine/core';\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", ".dimmed {\n color: var(--mantine-color-dimmed);\n}\n\n.preserveBreaks {\n white-space: pre-wrap;\n}", "import cx from 'clsx';\nimport { Input } from '@mantine/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { ReactNode, useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\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", "import { capitalize, InternalSchemaElement, isEmpty } from '@medplum/core';\nimport { 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 as string));\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", "import { Checkbox, Group, NativeSelect, Textarea, TextInput } from '@mantine/core';\nimport {\n applyDefaultValuesToElement,\n capitalize,\n ExtendedInternalSchemaElement,\n getPathDifference,\n HTTP_HL7_ORG,\n isComplexTypeCode,\n isEmpty,\n isPopulated,\n PropertyType,\n} from '@medplum/core';\nimport { ElementDefinitionBinding, ElementDefinitionType } from '@medplum/fhirtypes';\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 { BaseInputProps, ComplexTypeInputProps, PrimitiveTypeInputProps } from './ResourcePropertyInput.utils';\n\nexport interface ResourcePropertyInputProps extends BaseInputProps {\n readonly property: ExtendedInternalSchemaElement;\n readonly name: string;\n readonly defaultPropertyType?: string | undefined;\n readonly defaultValue: any;\n readonly arrayElement?: boolean | undefined;\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 as string));\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) as ElementDefinitionType;\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 as string,\n label: type.code as string,\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 as string)));\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\n extends Pick<ResourcePropertyInputProps, 'name' | 'path' | 'valuePath' | 'defaultValue' | 'onChange' | 'outcome'> {\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.time:\n case PropertyType.uri:\n case PropertyType.url:\n if (props.path === 'Project.secret.value[x]') {\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.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 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", "import { CodeableConcept, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nexport interface CodeableConceptInputProps\n extends 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<CodeableConcept | undefined>(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", "import { Coding, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface CodingInputProps\n extends Omit<ValueSetAutocompleteProps, 'defaultValue' | 'onChange' | 'disabled' | 'name'>,\n ComplexTypeInputProps<Coding> {}\n\nexport function CodingInput(props: CodingInputProps): JSX.Element {\n const { defaultValue, onChange, withHelpText, ...rest } = props;\n const [value, setValue] = useState<Coding | undefined>(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)}\n maxValues={1}\n onChange={handleChange}\n withHelpText={withHelpText ?? true}\n {...rest}\n />\n );\n}\n\nfunction codingToValueSetElement(coding: Coding): ValueSetExpansionContains {\n return {\n system: coding.system,\n code: coding.code,\n display: coding.display,\n };\n}\n\nfunction valueSetElementToCoding(element: ValueSetExpansionContains): Coding {\n return {\n system: element.system,\n code: element.code,\n display: element.display,\n };\n}\n", "import { Group, TextInput } from '@mantine/core';\nimport { ContactDetail, ContactPoint } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ContactPointInput } from '../ContactPointInput/ContactPointInput';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nexport type ContactDetailInputProps = ComplexTypeInputProps<ContactDetail>;\n\nexport function ContactDetailInput(props: ContactDetailInputProps): JSX.Element {\n const [contactPoint, setContactDetail] = useState(props.defaultValue);\n\n const ref = useRef<ContactDetail>();\n ref.current = contactPoint;\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 = { ...ref.current, 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 = { ...ref.current, 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={contactPoint?.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={contactPoint?.telecom?.[0]}\n onChange={setTelecom}\n outcome={props.outcome}\n />\n </Group>\n );\n}\n", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { ContactPoint } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 ref = useRef<ContactPoint>();\n ref.current = contactPoint;\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 = { ...ref.current, 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 = { ...ref.current, use };\n if (!use) {\n delete newValue.use;\n }\n setContactPointWrapper(newValue);\n }\n\n function setValue(value: string): void {\n const newValue: ContactPoint = { ...ref.current, 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', '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", "import { TextInput } from '@mantine/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { ChangeEvent } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { convertIsoToLocal, convertLocalToIso } from './DateTimeInput.utils';\nimport { PrimitiveTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.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 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", "import { 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", "import { isPopulated, isProfileLoaded } from '@medplum/core';\nimport { ElementDefinitionType, Extension } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useMemo, useState } from 'react';\nimport { BackboneElementInput } from '../BackboneElementInput/BackboneElementInput';\nimport { 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", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nexport type HumanNameInputProps = ComplexTypeInputProps<HumanName>;\n\nexport function HumanNameInput(props: HumanNameInputProps): JSX.Element {\n const { outcome, path } = props;\n const [value, setValue] = useState<HumanName | undefined>(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", "import { Group, TextInput } from '@mantine/core';\nimport { Identifier } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\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", "import { NativeSelect, TextInput } from '@mantine/core';\nimport { Money } from '@medplum/fhirtypes';\nimport { IconCurrencyDollar } from '@tabler/icons-react';\nimport { ChangeEvent, useCallback, useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group } from '@mantine/core';\nimport { Period } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { Quantity } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState, WheelEvent } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 parseFloat(str);\n}\n", "import { Group } from '@mantine/core';\nimport { Range } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group } from '@mantine/core';\nimport { Ratio } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group, NativeSelect } from '@mantine/core';\nimport {\n LRUCache,\n MedplumClient,\n ReadablePromise,\n createReference,\n isEmpty,\n isPopulated,\n tryGetProfile,\n} from '@medplum/core';\nimport { Reference, Resource, ResourceType, StructureDefinition } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\n\nexport interface ReferenceInputProps {\n readonly name: string;\n readonly placeholder?: string;\n readonly defaultValue?: Reference;\n readonly targetTypes?: string[];\n readonly searchCriteria?: Record<string, string>;\n readonly autoFocus?: boolean;\n readonly required?: boolean;\n readonly onChange?: (value: Reference | 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(props: ReferenceInputProps): JSX.Element {\n const { onChange } = props;\n const medplum = useMedplum();\n const [value, setValue] = useState<Reference | undefined>(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: Resource | 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 <Group gap=\"xs\" grow wrap=\"nowrap\">\n {targetTypes && targetTypes.length > 1 && (\n <NativeSelect\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\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 }`.replace(/\\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", "import { Group, Text } from '@mantine/core';\nimport { getDisplayString, getReferenceString, isPopulated } from '@medplum/core';\nimport { OperationOutcome, Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { forwardRef, ReactNode, useCallback, useState } from 'react';\nimport {\n AsyncAutocomplete,\n AsyncAutocompleteOption,\n AsyncAutocompleteProps,\n} 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\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 loadOnFocus?: boolean;\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\nfunction toOption<T extends Resource>(resource: T): AsyncAutocompleteOption<T> {\n return {\n value: getReferenceString(resource),\n label: getDisplayString(resource),\n resource,\n };\n}\n\nexport function ResourceInput<T extends Resource = Resource>(props: ResourceInputProps<T>): JSX.Element | null {\n const medplum = useMedplum();\n const { resourceType, searchCriteria } = props;\n const [outcome, setOutcome] = useState<OperationOutcome>();\n const defaultValue = useResource(props.defaultValue, setOutcome);\n const ItemComponent = props.itemComponent ?? DefaultItemComponent;\n const onChange = props.onChange;\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[0]);\n }\n },\n [onChange]\n );\n\n if (isPopulated(props.defaultValue) && !outcome && !defaultValue) {\n // If a default value was specified, but the default resource is not loaded yet,\n // then return null to avoid rendering the input until the default resource is loaded.\n // The Mantine <MultiSelect> component does not reliably handle changes to defaultValue.\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={defaultValue}\n placeholder={props.placeholder}\n maxValues={1}\n toOption={toOption}\n loadOptions={loadValues}\n onChange={handleChange}\n clearable\n />\n );\n}\n\nconst DefaultItemComponent = 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\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", "import { Group, Stack, Text } from '@mantine/core';\nimport { ExtendedInternalSchemaElement, SliceDefinitionWithTypes, getPathDisplayName } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { MouseEvent, useContext, useEffect, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\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';\nimport { BaseInputProps, getValuePath } from '../ResourcePropertyInput/ResourcePropertyInput.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", "import { Group, Stack, Text } from '@mantine/core';\nimport {\n ExtendedInternalSchemaElement,\n ElementsContextType,\n SliceDefinitionWithTypes,\n buildElementsContext,\n getPropertyDisplayName,\n isEmpty,\n isPopulated,\n} from '@medplum/core';\nimport { MouseEvent, 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 { 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<any[]>(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", "import { ActionIcon, Button } from '@mantine/core';\nimport { IconCirclePlus } from '@tabler/icons-react';\nimport { 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", "import { ActionIcon } from '@mantine/core';\nimport { IconCircleMinus } from '@tabler/icons-react';\nimport { 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", "import { 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", "import { ActionIcon, Flex, Textarea, TextareaProps } from '@mantine/core';\nimport { useClipboard } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { IconCopy } from '@tabler/icons-react';\nimport { RefAttributes, 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", "import { Button, Chip, Group, Modal, NativeSelect, Stack, Switch, TextInput } from '@mantine/core';\nimport { formatTiming } from '@medplum/core';\nimport { Timing, TimingRepeat } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { FormSection } from '../FormSection/FormSection';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nconst daysOfWeek = ['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\nexport interface TimingInputProps extends ComplexTypeInputProps<Timing> {\n readonly defaultModalOpen?: boolean;\n}\n\nexport function TimingInput(props: TimingInputProps): JSX.Element {\n const [value, setValue] = useState<Timing | undefined>(props.defaultValue);\n const [open, setOpen] = useState(!props.disabled && (props.defaultModalOpen ?? false));\n\n const valueRef = useRef<Timing>();\n valueRef.current = value;\n\n return (\n <>\n <Group gap=\"xs\" grow wrap=\"nowrap\">\n <span>{formatTiming(valueRef.current) || '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={valueRef.current}\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<Timing>(props.defaultValue || defaultValue);\n const { getExtendedProps } = useContext(ElementsContext);\n const [eventProps, repeatProps, repeatPeriodProps, repeatPeriodUnitProps, repeatDayOfWeekProps] = useMemo(\n () =>\n ['event', 'repeat', 'repeat.period', 'repeat.periodUnit', 'repeat.dayOfWeek'].map((field) =>\n getExtendedProps(props.path + '.' + field)\n ),\n [getExtendedProps, props.path]\n );\n\n const valueRef = useRef<Timing>();\n valueRef.current = value;\n\n function setStart(newStart: string): void {\n setValue({ ...valueRef.current, event: [newStart] });\n }\n\n function setRepeat(repeat: TimingRepeat | undefined): void {\n setValue({ ...valueRef.current, repeat });\n }\n\n function setPeriod(newPeriod: number | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, period: newPeriod });\n }\n\n function setPeriodUnit(newPeriodUnit: PeriodUnit | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, periodUnit: newPeriodUnit });\n }\n\n function setDaysOfWeek(newDaysOfWeek: DayOfWeek[] | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, dayOfWeek: newDaysOfWeek });\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>\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(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: 'second', value: 's' },\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 multiple onChange={setDaysOfWeek as (v: string[] | undefined) => void}>\n <Group justify=\"space-between\" mt=\"md\" gap=\"xs\">\n {daysOfWeek.map((day) => (\n <Chip key={day} value={day} size=\"xs\" radius=\"xl\" disabled={repeatDayOfWeekProps?.readonly}>\n {day.charAt(0).toUpperCase()}\n </Chip>\n ))}\n </Group>\n </Chip.Group>\n </FormSection>\n )}\n </>\n )}\n <Group justify=\"flex-end\">\n <Button onClick={() => props.onOk(value)}>OK</Button>\n </Group>\n </Stack>\n </Modal>\n );\n}\n", "import { Button, Group } from '@mantine/core';\nimport { Slot } from '@medplum/fhirtypes';\nimport { useMemo, useState } from 'react';\nimport classes from './CalendarInput.module.css';\nimport { getMonthString, getStartMonth } from './CalendarInput.utils';\n\nexport interface CalendarInputProps {\n readonly slots: Slot[];\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 CalendarInput(props: CalendarInputProps): 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.getTime());\n newMonth.setMonth(currMonth.getMonth() + delta);\n onChangeMonth(newMonth);\n return newMonth;\n });\n }\n\n const grid = useMemo(() => buildGrid(month, props.slots), [month, props.slots]);\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 <\n </Button>\n <Button variant=\"outline\" aria-label=\"Next month\" onClick={() => moveMonth(1)}>\n >\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, slots: Slot[]): 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.getTime()),\n available: isDayAvailable(d, slots),\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 slots - The list of available slots.\n * @returns True if there are any available slots for the day.\n */\nfunction isDayAvailable(day: Date, slots: Slot[]): boolean {\n // Note that slot start and end time may or may not be in UTC.\n for (const slot of slots) {\n const slotStart = new Date(slot.start as string);\n if (\n slotStart.getFullYear() === day.getFullYear() &&\n slotStart.getMonth() === day.getMonth() &&\n slotStart.getDate() === day.getDate()\n ) {\n return true;\n }\n }\n\n return false;\n}\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 * 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", "import {\n ActionIcon,\n Group,\n LoadingOverlay,\n Paper,\n PaperProps,\n ScrollArea,\n Skeleton,\n Stack,\n TextInput,\n Title,\n} from '@mantine/core';\nimport { useResizeObserver } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { ProfileResource, getDisplayString, getReferenceString, normalizeErrorString } from '@medplum/core';\nimport { Bundle, Communication, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useResource, useSubscription } from '@medplum/react-hooks';\nimport { IconArrowRight } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { LegacyRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Form } from '../../Form/Form';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './BaseChat.module.css';\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 const sentTime = new Date(communication.sent ?? 0);\n const sentTimeMins = sentTime.getMinutes().toString();\n return `${sentTime.getHours()}:${sentTimeMins.length === 1 ? '0' : ''}${sentTimeMins}`;\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) => (a.sent as string).localeCompare(b.sent as string));\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) => void;\n readonly onMessageReceived?: (message: Communication) => void;\n readonly onMessageUpdated?: (message: Communication) => void;\n readonly inputDisabled?: boolean;\n readonly onError?: (err: Error) => void;\n}\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 ...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\n if (!loading) {\n initialLoadRef.current = false;\n }\n\n const profileRefStr = useMemo<string>(\n () => (profile ? getReferenceString(medplum.getProfile() as 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 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 if (inputRef.current) {\n inputRef.current.value = '';\n }\n sendMessage(formData.message);\n scrollToBottomRef.current = true;\n },\n [inputDisabled, sendMessage]\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<Communication[]>(communications);\n communicationsRef.current = communications;\n const prevCommunicationsRef = useRef<Communication[]>(communications);\n\n const scrollToBottomRef = useRef<boolean>(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 <Title order={2} className={classes.chatTitle}>\n {title}\n </Title>\n <div className={classes.chatBody} ref={parentRef as LegacyRef<HTMLDivElement>}>\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 return (\n <Stack key={`${c.id}--${c.meta?.versionId ?? 'no-version'}`} align=\"stretch\">\n {(!prevCommTime || currCommTime !== prevCommTime) && (\n <div style={{ textAlign: 'center' }}>{currCommTime}</div>\n )}\n {c.sender?.reference === profileRefStr ? (\n <Group justify=\"flex-end\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n <ChatBubble\n alignment=\"right\"\n communication={c}\n showDelivered={!!c.received && c.id === myLastDeliveredId}\n />\n <ResourceAvatar radius=\"xl\" color=\"orange\" value={c.sender} />\n </Group>\n ) : (\n <Group justify=\"flex-start\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n <ResourceAvatar radius=\"xl\" value={c.sender} />\n <ChatBubble alignment=\"left\" communication={c} />\n </Group>\n )}\n </Stack>\n );\n })}\n </ScrollArea>\n )}\n </div>\n <div className={classes.chatInputContainer}>\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 rightSectionWidth={42}\n disabled={inputDisabled}\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 content = communication.payload?.[0]?.contentString || '';\n const seenTime = new Date(communication.received ?? -1);\n const senderResource = useResource(communication.sender);\n return (\n <div className={classes.chatBubbleOuterWrap}>\n <div\n className={cx(classes.chatBubbleName, alignment === 'right' && classes.chatBubbleNameRight)}\n aria-label=\"Sender name\"\n >\n {senderResource ? getDisplayString(senderResource) : '[Unknown sender]'}\n </div>\n <div\n className={\n alignment === 'left' ? classes.chatBubbleLeftAlignedInnerWrap : classes.chatBubbleRightAlignedInnerWrap\n }\n >\n <div className={classes.chatBubble}>{content}</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\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 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 padding: 6px 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.chatBubbleName {\n margin-bottom: 5px;\n font-weight: 500;\n}\n\n.chatBubbleNameRight {\n text-align: right;\n}\n", "import { ActionIcon } from '@mantine/core';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown, IconChevronUp } from '@tabler/icons-react';\nimport { ReactNode, 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", "import { ProfileResource, createReference, formatCodeableConcept, getReferenceString } from '@medplum/core';\nimport { Communication } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile, usePrevious } from '@medplum/react-hooks';\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 onError?: (err: Error) => void;\n}\n\nexport function ThreadChat(props: ThreadChatProps): JSX.Element | null {\n const { thread, title, onMessageSent, inputDisabled, onError } = props;\n const medplum = useMedplum();\n const profile = useMedplumProfile();\n const prevThreadId = usePrevious<string | undefined>(thread?.id);\n const [communications, setCommunications] = useState<Communication[]>([]);\n\n const profileRef = useMemo(() => (profile ? createReference(profile as ProfileResource) : 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) => {\n const profileRefStr = profileRef ? getReferenceString(profileRef) : undefined;\n if (!profileRefStr) {\n return;\n }\n medplum\n .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: [{ contentString: message }],\n partOf: [threadRef],\n })\n .then((communication) => {\n setCommunications([...communications, communication]);\n onMessageSent?.(communication);\n })\n .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<Communication>({\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/organizing-communications#:~:text=THE%20Communication%20LIFECYCLE\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 onError={onError}\n />\n );\n}\n", "import { ActionIcon, Center, Group, Loader, ScrollArea, TextInput } from '@mantine/core';\nimport { showNotification, updateNotification } from '@mantine/notifications';\nimport { MedplumClient, ProfileResource, createReference, normalizeErrorString } from '@medplum/core';\nimport {\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 { ReactNode, useCallback, useEffect, 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 { Timeline, TimelineItem, TimelineItemProps } 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 loadTimelineResources = props.loadTimelineResources;\n\n const itemsRef = useRef<Resource[]>(items);\n itemsRef.current = items;\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 = [];\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 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 {items.map((item) => {\n if (!item) {\n // TODO: Handle null history items for deleted versions.\n return null;\n }\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 </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", "import { Group, List, Stack, Text, Title } from '@mantine/core';\nimport { capitalize, formatCodeableConcept, formatDateTime, formatObservationValue, isReference } from '@medplum/core';\nimport {\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 { 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}\n\nDiagnosticReportDisplay.defaultProps = {\n hideObservationNotes: false,\n hideSpecimenInfo: 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} />\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 </Stack>\n );\n}\n\ninterface DiagnosticReportHeaderProps {\n readonly value: DiagnosticReport;\n}\n\nfunction DiagnosticReportHeader({ value }: DiagnosticReportHeaderProps): JSX.Element {\n return (\n <Group mt=\"md\" gap={30}>\n {value.subject && (\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 <Text>{capitalize(value.status)}</Text>\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 as string)) {\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) => <ReferenceDisplay key={performer.reference} value={performer} />)}\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={\n props.ancestorIds ? [...props.ancestorIds, observation.id as string] : [observation.id as string]\n }\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", "import { Blockquote, Stack } from '@mantine/core';\nimport { Annotation } from '@medplum/fhirtypes';\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", "import { Group } from '@mantine/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\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", "import { Text, TextProps } from '@mantine/core';\nimport { getDisplayString, isOk, normalizeErrorString } from '@medplum/core';\nimport { OperationOutcome, Reference, Resource } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\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", "import { Badge, DefaultMantineColor } from '@mantine/core';\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};\n\nexport interface StatusBadgeProps {\n readonly status: string;\n}\n\nexport function StatusBadge(props: StatusBadgeProps): JSX.Element {\n return <Badge color={statusToColor[props.status]}>{props.status}</Badge>;\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", "import { Table } from '@mantine/core';\nimport {\n InternalSchemaElement,\n TypedValue,\n arrayify,\n capitalize,\n evalFhirPathTyped,\n getSearchParameterDetails,\n toTypedValue,\n} from '@medplum/core';\nimport { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Operation, 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 <ResourceDiffRow {...row} />\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 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}\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) as TypedValue[]).flatMap((v) => v.value);\n return isArray ? inputValue : inputValue[0];\n}\n", "import { useState } from 'react';\nimport { Table, Button } from '@mantine/core';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { InternalSchemaElement, TypedValue } from '@medplum/core';\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<boolean>(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", "import { AccessPolicyInteraction, satisfiedAccessPolicy, tryGetProfile } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\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", "import { ActionIcon, Group, Menu, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { IconDots } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { ReactNode } from 'react';\nimport { Container } from '../Container/Container';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { Panel, PanelProps } 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 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=\"dark\" fw={500} value={author} link={true} />\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 ·\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", "import { 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", "\n.pinnedComment {\n background-color: var(--mantine-color-blue-0);\n}", "import { MedplumClient } from '@medplum/core';\nimport { Reference, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Encounter, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { Button, Loader, Table } from '@mantine/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome, Resource } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ChangeEvent, MouseEvent, memo, useEffect, useRef, 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 const responseRef = useRef<SmartSearchResponse>();\n responseRef.current = response;\n\n const selectedRef = useRef<{ [id: string]: boolean }>({});\n selectedRef.current = selected;\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 = { ...selectedRef.current };\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 = responseRef.current?.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 = responseRef.current?.data.ResourceList;\n if (!resources || resources.length === 0) {\n return false;\n }\n for (const resource of resources) {\n if (resource.id && !selectedRef.current[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(selectedRef.current))}>\n Bulk...\n </Button>\n )}\n </div>\n );\n}\n\nexport const MemoizedFhirPathTable = memo(FhirPathTable);\n", "import { evalFhirPath } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\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", "import {\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 {\n DEFAULT_SEARCH_COUNT,\n Filter,\n SearchRequest,\n deepEquals,\n formatSearchQuery,\n isDataTypeLoaded,\n normalizeOperationOutcome,\n} from '@medplum/core';\nimport { Bundle, OperationOutcome, Resource, ResourceType, 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 { ChangeEvent, MouseEvent, useCallback, useEffect, 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 { isCheckboxCell, killEvent } from '../utils/dom';\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}\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<SearchControlState>(state);\n stateRef.current = state;\n\n const total = memoizedSearch.total ?? 'accurate';\n\n const loadResults = useCallback(\n (options?: RequestInit) => {\n setOutcome(undefined);\n medplum\n .requestSchema(memoizedSearch.resourceType as ResourceType)\n .then(() =>\n medplum.search(\n memoizedSearch.resourceType as 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 const state = stateRef.current;\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 = e.button === 1 || e.ctrlKey || e.metaKey;\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 })}\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 })}\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 ? props.onExport : () => setState({ ...stateRef.current, exportDialogVisible: true })\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 });\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={(control) => {\n switch (control) {\n case 'previous':\n return { 'aria-label': 'Previous page' };\n case 'next':\n return { 'aria-label': 'Next page' };\n default:\n return {};\n }\n }}\n />\n </Center>\n )}\n <SearchFieldEditor\n search={memoizedSearch}\n visible={stateRef.current.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 search={memoizedSearch}\n visible={stateRef.current.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 visible={stateRef.current.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={state.filterDialogSearchParam?.code}\n visible={stateRef.current.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\n/**\n * @deprecated\n *\n * The memoization `MemoizedSearchControl` provides has been merged into `SearchControl`. Previously the memoization was done via HOC but\n * it was proven that this wasn't effective for a large number of use cases, especially when:\n * 1. `search` was an inline static object, which would trigger the memo to recompute on every re-render of the parent component\n * 2. Any of the callbacks, such as `onClick` were not memoized via `useCallback`, which would result in the recomputation as well\n *\n * Scenario 1 also retriggered the effect that runs `loadResults` on change of the `search`, which was less than desirable.\n *\n * The memoization is now accomplished via checking deep equality of the incoming `search` prop in the body of the component, and setting a memoized\n * state whenever the incoming and current memoized value are not deeply equal. See: https://github.com/medplum/medplum/pull/5023\n */\nexport const MemoizedSearchControl = SearchControl;\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 \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", "import { Box, Button, Modal, Text } from '@mantine/core';\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", "import { Button, Group, Modal, MultiSelect, Stack } from '@mantine/core';\nimport {\n InternalTypeSchema,\n SearchRequest,\n getDataType,\n getSearchParameters,\n sortStringArray,\n stringify,\n} from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\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 if (!props.visible) {\n return null;\n }\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", "import {\n capitalize,\n DEFAULT_SEARCH_COUNT,\n evalFhirPathTyped,\n Filter,\n formatDateTime,\n InternalSchemaElement,\n Operator,\n SearchRequest,\n} from '@medplum/core';\nimport { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { 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],\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 \"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.replace(/([A-Z])/g, ' $1');\n\n // Convert dashes and underscores to spaces\n tmp = tmp.replace(/[-_]/g, ' ');\n\n // Normalize whitespace to single space character\n tmp = tmp.replace(/\\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 resource.id;\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 (field.elementDefinition && `${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 && 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", "import { ActionIcon, Button, Group, Modal, NativeSelect } from '@mantine/core';\nimport { Filter, Operator, SearchRequest, deepClone, getSearchParameters } from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\nimport { IconX } from '@tabler/icons-react';\nimport { useEffect, useRef, useState } from 'react';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { Form } from '../Form/Form';\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<SearchRequest>(deepClone(props.search) as SearchRequest);\n\n const searchRef = useRef<SearchRequest>(search);\n searchRef.current = search;\n\n useEffect(() => {\n setSearch(deepClone(props.search) as SearchRequest);\n }, [props.search]);\n\n function onAddFilter(filter: Filter): void {\n setSearch(addFilter(searchRef.current, filter.code, filter.operator, filter.value));\n }\n\n if (!props.visible) {\n return null;\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 <Button type=\"submit\">OK</Button>\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 const valueRef = useRef<Filter>(value);\n valueRef.current = value;\n\n function setFilterCode(newCode: string): void {\n valueRef.current.code = newCode;\n valueRef.current.operator = Operator.EQUALS;\n valueRef.current.value = '';\n props.onChange(valueRef.current);\n }\n\n function setFilterOperator(newOperator: Operator): void {\n valueRef.current.operator = newOperator;\n valueRef.current.value = '';\n props.onChange(valueRef.current);\n }\n\n function setFilterValue(newFilterValue: string): void {\n valueRef.current.value = newFilterValue;\n props.onChange(valueRef.current);\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 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 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", "import { Checkbox, TextInput } from '@mantine/core';\nimport { getSearchParameterDetails, SearchParameterType } from '@medplum/core';\nimport { Quantity, Reference, SearchParameter } from '@medplum/fhirtypes';\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: parseFloat(valueString),\n system: systemString,\n unit: unitString,\n };\n }\n }\n return undefined;\n}\n", "import { Button, Grid, Modal } from '@mantine/core';\nimport { Filter } from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\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<string>(props.defaultValue ?? '');\n\n if (!props.visible || !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", "import {\n Filter,\n formatDateTime,\n getSearchParameterDetails,\n globalSchema,\n Operator,\n SearchParameterType,\n} from '@medplum/core';\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", "import { Menu } from '@mantine/core';\nimport { Filter, Operator, SearchRequest } from '@medplum/core';\nimport { 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 {\n addLastMonthFilter,\n addMissingFilter,\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 as string, desc));\n }\n\n function onClear(searchParam: SearchParameter): void {\n onChange(clearFiltersOnField(props.search, searchParam.code as string));\n }\n\n function onPrompt(searchParam: SearchParameter, operator: Operator): void {\n props.onPrompt(searchParam, { code: searchParam.code as string, 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 as string)}</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 case 'uri':\n return <TokenFilterSubMenu {...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 as string;\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.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 <CommonMenuItems {...props} />\n </Menu.Dropdown>\n );\n}\n\nfunction CommonMenuItems(props: SearchPopupSubMenuProps): JSX.Element {\n const { searchParam } = props;\n const code = searchParam.code as string;\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", ".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", "import {\n getElementDefinition,\n getSearchParameter,\n getSearchParameterDetails,\n getSearchParameters,\n InternalSchemaElement,\n SearchRequest,\n} from '@medplum/core';\nimport { 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", "import { Box, SimpleGrid } from '@mantine/core';\nimport { MeasureReport, MeasureReportGroup, Reference } from '@medplum/fhirtypes';\nimport { useResource, useSearchOne } from '@medplum/react-hooks';\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", "import { Box, Flex, Group, Paper, RingProgress, Text, Title } from '@mantine/core';\nimport { formatCodeableConcept } from '@medplum/core';\nimport { Measure, MeasureReportGroup } from '@medplum/fhirtypes';\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", "import { ActionIcon, Indicator, Tooltip } from '@mantine/core';\nimport { ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useSubscription } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useState } from 'react';\n\nexport interface NotificationIconProps {\n readonly iconComponent: JSX.Element;\n readonly label: 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 medplum = useMedplum();\n const { label, resourceType, countCriteria, subscriptionCriteria, onClick } = props;\n const [unreadCount, setUnreadCount] = useState(0);\n\n const updateCount = useCallback(\n (cache: 'default' | 'reload') => {\n medplum\n .search(resourceType, countCriteria, { cache })\n .then((result) => setUnreadCount(result.total as number))\n .catch(console.error);\n },\n [medplum, resourceType, countCriteria]\n );\n\n // Initial count\n useEffect(() => {\n // Cache=default to use the default cache policy, and accept most recent data\n updateCount('default');\n }, [updateCount]);\n\n // Subscribe to the criteria\n useSubscription(subscriptionCriteria, () => {\n // Cache=reload to force a reload\n updateCount('reload');\n });\n\n const icon = (\n <Tooltip label={label}>\n <ActionIcon variant=\"subtle\" color=\"gray\" size=\"lg\" aria-label={label} onClick={onClick}>\n {props.iconComponent}\n </ActionIcon>\n </Tooltip>\n );\n\n return unreadCount > 0 ? (\n <Indicator inline label={unreadCount.toLocaleString()} size={16} offset={2} position=\"bottom-end\" color=\"red\">\n {icon}\n </Indicator>\n ) : (\n icon\n );\n}\n", "import { Card, CardProps, Divider, Flex, Group, Paper, Stack, Text } from '@mantine/core';\nimport { calculateAgeString, formatHumanName, resolveId } from '@medplum/core';\nimport {\n AllergyIntolerance,\n Appointment,\n Condition,\n Encounter,\n HumanName,\n MedicationRequest,\n Observation,\n Patient,\n Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconGenderFemale, IconGenderMale, IconStethoscope, IconUserSquare } from '@tabler/icons-react';\nimport { ReactNode, useEffect, useMemo, useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { Allergies } from './Allergies';\nimport { Medications } from './Medications';\nimport { ProblemList } from './ProblemList';\nimport { SexualOrientation } from './SexualOrientation';\nimport { SmokingStatus } from './SmokingStatus';\nimport { Vitals } from './Vitals';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\n\nexport interface PatientSummaryProps extends Omit<CardProps, 'children'> {\n readonly patient: Patient | Reference<Patient>;\n readonly background?: string;\n /** The URL that the upcoming appointments link should navigate to or `undefined` to not show the link. */\n readonly appointmentsUrl?: string | undefined;\n /** The URL that the documented visits (encounters) link should navigate to or `undefined` to not show the link. */\n readonly encountersUrl?: string | undefined;\n}\n\ninterface PatientMedicalData {\n readonly allergies: AllergyIntolerance[];\n readonly problems: Condition[];\n readonly sexualOrientation?: Observation;\n readonly smokingStatus?: Observation;\n readonly vitals: Observation[];\n readonly medicationRequests: MedicationRequest[];\n readonly encounters?: Encounter[];\n readonly appointments?: Appointment[];\n}\n\ntype IconType = typeof IconGenderFemale;\n\nfunction getGenderIcon(patient?: Patient): IconType | undefined {\n switch (patient?.gender) {\n case 'female':\n return IconGenderFemale;\n case 'male':\n return IconGenderMale;\n default:\n return undefined;\n }\n}\n\nfunction pluralize(count: number | undefined, singular: string, plural: string): string {\n if (count === 0) {\n return `No ${plural}`;\n } else if (count === 1) {\n return `1 ${singular}`;\n } else {\n return `${count} ${plural}`;\n }\n}\n\nexport function PatientSummary(props: PatientSummaryProps): JSX.Element | null {\n const medplum = useMedplum();\n const {\n patient: propsPatient,\n background,\n appointmentsUrl: propsAppointmentsUrl,\n encountersUrl: propsEncountersUrl,\n ...cardProps\n } = props;\n const patient = useResource(propsPatient);\n const [medicalData, setMedicalData] = useState<PatientMedicalData>();\n\n // If a URL is explicitly specified in `props`, use it even if `undefined`.\n // If not included in `props`, use '#' as a demonstration value.\n const appointmentsUrl = 'appointmentsUrl' in props ? propsAppointmentsUrl : '#';\n const encountersUrl = 'encountersUrl' in props ? propsEncountersUrl : '#';\n\n useEffect(() => {\n const id = resolveId(propsPatient) as string;\n const ref = `Patient/${id}`;\n const searchMeta = { _count: 100, _sort: '-_lastUpdated' };\n const today = new Date().toISOString().substring(0, 10);\n\n Promise.all([\n medplum.searchResources('AllergyIntolerance', { patient: ref, ...searchMeta }),\n medplum.searchResources('Condition', { patient: ref, ...searchMeta }),\n medplum.searchResources('MedicationRequest', { subject: ref, ...searchMeta }),\n medplum.searchResources('Observation', { subject: ref, ...searchMeta }),\n medplum.searchResources('Appointment', {\n patient: ref,\n date: `ge${today}`,\n status: 'proposed,pending,booked',\n ...searchMeta,\n }),\n medplum.searchResources('Encounter', { subject: ref, date: `le${today}`, status: 'finished', ...searchMeta }),\n ])\n .then((results) => {\n const observations = results[3];\n setMedicalData({\n allergies: results[0],\n problems: results[1],\n medicationRequests: results[2],\n sexualOrientation: observations.find((obs) => obs.code?.coding?.[0].code === '76690-7'),\n smokingStatus: observations.find((obs) => obs.code?.coding?.[0].code === '72166-2'),\n vitals: observations.filter((obs) => obs.category?.[0]?.coding?.[0].code === 'vital-signs'),\n appointments: results[4],\n encounters: results[5],\n });\n })\n .catch(console.error);\n }, [medplum, propsPatient]);\n\n const links: ReactNode[] = useMemo(() => {\n const appointmentsLink =\n appointmentsUrl === undefined ? undefined : (\n <MedplumLink key=\"appt\" to={appointmentsUrl}>\n {pluralize(medicalData?.appointments?.length, 'upcoming appointment', 'upcoming appointments')}\n </MedplumLink>\n );\n const encountersLink =\n encountersUrl === undefined ? undefined : (\n <MedplumLink key=\"enc\" to={encountersUrl}>\n {pluralize(medicalData?.encounters?.length, 'documented visit', 'documented visits')}\n </MedplumLink>\n );\n\n return [appointmentsLink, encountersLink].filter(Boolean);\n }, [appointmentsUrl, medicalData?.appointments?.length, medicalData?.encounters?.length, encountersUrl]);\n\n if (!patient) {\n return null;\n }\n\n const GenderIconComponent = getGenderIcon(patient);\n\n return (\n <Card {...cardProps}>\n <Card.Section h={100} style={{ background }} />\n <ResourceAvatar value={patient} size={80} radius={80} mx=\"auto\" mt={-50} style={{ border: '2px solid white' }} />\n <Text ta=\"center\" fz=\"lg\" fw={500}>\n {formatHumanName(patient.name?.[0] as HumanName)}\n </Text>\n {patient.birthDate && (\n <Text ta=\"center\" fz=\"xs\" c=\"dimmed\">\n {patient.birthDate} ({calculateAgeString(patient.birthDate)})\n </Text>\n )}\n <Paper withBorder p=\"md\" my=\"md\">\n <Group wrap=\"nowrap\" justify=\"space-evenly\">\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <IconUserSquare size={24} color=\"gray\" />\n <Text fz=\"xs\" ta=\"center\" style={{ whiteSpace: 'nowrap' }}>\n Self\n </Text>\n </Flex>\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <IconStethoscope size={24} color=\"gray\" />\n <Text fz=\"xs\" style={{ whiteSpace: 'nowrap' }}>\n {patient?.generalPractitioner?.[0]?.display ?? 'No provider'}\n </Text>\n </Flex>\n {GenderIconComponent && (\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <GenderIconComponent size={24} color=\"gray\" />\n <Text fz=\"xs\" style={{ whiteSpace: 'nowrap' }}>\n {patient.gender}\n </Text>\n </Flex>\n )}\n </Group>\n </Paper>\n <Stack gap=\"xs\">\n {links.length > 0 && (\n <>\n {links}\n <Divider />\n </>\n )}\n {medicalData && (\n <>\n <Allergies patient={patient} allergies={medicalData.allergies} />\n <Divider />\n <ProblemList patient={patient} problems={medicalData.problems} />\n <Divider />\n <Medications patient={patient} medicationRequests={medicalData.medicationRequests} />\n <Divider />\n <SexualOrientation patient={patient} sexualOrientation={medicalData.sexualOrientation} />\n <Divider />\n <SmokingStatus patient={patient} smokingStatus={medicalData.smokingStatus} />\n <Divider />\n <Vitals patient={patient} vitals={medicalData.vitals} />\n </>\n )}\n </Stack>\n </Card>\n );\n}\n", "import { Anchor, Box, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { AllergyIntolerance, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { AllergyDialog } from './AllergyDialog';\nimport { ConceptBadge } from './ConceptBadge';\n\nexport interface AllergiesProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly allergies: AllergyIntolerance[];\n}\n\nexport function Allergies(props: AllergiesProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [allergies, setAllergies] = useState<AllergyIntolerance[]>(props.allergies);\n const [opened, { open, close }] = useDisclosure(false);\n const [editAllergy, setEditAllergy] = useState<AllergyIntolerance>();\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Allergies\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditAllergy(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {allergies.length > 0 ? (\n <Box>\n {allergies.map((allergy) => (\n <ConceptBadge\n key={allergy.id}\n resource={allergy}\n onEdit={(a) => {\n setEditAllergy(a);\n open();\n }}\n />\n ))}\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Button, Group, Stack, TextInput } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { AllergyIntolerance, CodeableConcept, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { Form } from '../Form/Form';\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<CodeableConcept | undefined>(allergy?.code);\n const [clinicalStatus, setClinicalStatus] = useState<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Badge } from '@mantine/core';\nimport { getDisplayString } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\nimport { IconEdit } from '@tabler/icons-react';\nimport { ReactNode } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { killEvent } from '../utils/dom';\n\nexport interface ConceptBadgeProps<T extends Resource> {\n readonly resource: T;\n readonly onEdit?: (resource: T) => void;\n}\n\nexport function ConceptBadge<T extends Resource = Resource>(props: ConceptBadgeProps<T>): JSX.Element {\n const { resource, onEdit } = props;\n\n let rightSection: ReactNode | undefined = undefined;\n if (onEdit) {\n rightSection = (\n <IconEdit\n aria-label={`Edit ${getDisplayString(resource)}`}\n size={12}\n onClick={(e) => {\n killEvent(e);\n onEdit(resource);\n }}\n />\n );\n }\n\n return (\n <MedplumLink key={resource.id} to={resource}>\n <Badge variant=\"light\" maw=\"100%\" rightSection={rightSection}>\n {getDisplayString(resource)}\n </Badge>\n </MedplumLink>\n );\n}\n", "import { Anchor, Box, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Encounter, MedicationRequest, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { ConceptBadge } from './ConceptBadge';\nimport { MedicationDialog } from './MedicationDialog';\n\nexport interface MedicationsProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly medicationRequests: MedicationRequest[];\n}\n\nexport function Medications(props: MedicationsProps): JSX.Element {\n const medplum = useMedplum();\n const [medicationRequests, setMedicationRequests] = useState<MedicationRequest[]>(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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Medications\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditMedication(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {medicationRequests.length > 0 ? (\n <Box>\n {medicationRequests.map((request) => (\n <ConceptBadge<MedicationRequest>\n key={request.id}\n resource={request}\n onEdit={(mr) => {\n setEditMedication(mr);\n open();\n }}\n />\n ))}\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Alert, Button, Group, Radio, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { CodeableConcept, Encounter, MedicationRequest, Patient } from '@medplum/fhirtypes';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { Form } from '../Form/Form';\nimport { useMedplumProfile } from '@medplum/react-hooks';\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<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Anchor, Grid, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Condition, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Fragment, useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { ConceptBadge } from './ConceptBadge';\nimport { ConditionDialog } from './ConditionDialog';\n\nexport interface ProblemListProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly problems: Condition[];\n}\n\nexport function ProblemList(props: ProblemListProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [problems, setProblems] = useState<Condition[]>(props.problems);\n const [editCondition, setEditCondition] = useState<Condition>();\n const [opened, { open, close }] = useDisclosure(false);\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([...problems, newCondition]);\n }\n setEditCondition(undefined);\n close();\n },\n [medplum, problems, close]\n );\n\n return (\n <>\n <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Problem List\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditCondition(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {problems.length > 0 ? (\n <Grid gutter=\"xs\">\n {problems.map((problem) => (\n <Fragment key={problem.id}>\n <Grid.Col span={2}>{problem.onsetDateTime?.substring(0, 4)}</Grid.Col>\n <Grid.Col span={10}>\n <ConceptBadge<Condition>\n key={problem.id}\n resource={problem}\n onEdit={(c) => {\n setEditCondition(c);\n open();\n }}\n />\n </Grid.Col>\n </Fragment>\n ))}\n </Grid>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Button, Group, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { CodeableConcept, Condition, Encounter, Patient } from '@medplum/fhirtypes';\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';\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<CodeableConcept | undefined>(condition?.code);\n const [clinicalStatus, setClinicalStatus] = useState<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Anchor, Badge, Box, Button, Group, Modal, Radio, Stack, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, LOINC, SNOMED, createReference } from '@medplum/core';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { Form } from '../Form/Form';\nimport { killEvent } from '../utils/dom';\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}\n\nexport function SexualOrientation(props: SexualOrientationProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [sexualOrientation, setSexualOrientation] = useState<Observation | undefined>(props.sexualOrientation);\n const [opened, { open, close }] = useDisclosure(false);\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Sexual Orientation\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Edit\n </Anchor>\n </Group>\n {sexualOrientation?.valueCodeableConcept ? (\n <Box>\n <Badge variant=\"light\">\n <CodeableConceptDisplay value={sexualOrientation.valueCodeableConcept} />\n </Badge>\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { Anchor, Badge, Box, Button, Group, Modal, Radio, Stack, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { HTTP_HL7_ORG, LOINC, SNOMED, createReference } from '@medplum/core';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { Form } from '../Form/Form';\nimport { killEvent } from '../utils/dom';\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}\n\nexport function SmokingStatus(props: SmokingStatusProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [smokingStatus, setSmokingStatus] = useState<Observation | undefined>(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(patient),\n encounter: encounter ? createReference(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, patient, encounter, close]\n );\n\n return (\n <>\n <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Smoking Status\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Edit\n </Anchor>\n </Group>\n {smokingStatus?.valueCodeableConcept ? (\n <Box>\n <Badge variant=\"light\">\n <CodeableConceptDisplay value={smokingStatus.valueCodeableConcept} />\n </Badge>\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { Anchor, Button, Grid, Group, Modal, Stack, Text, Textarea, TextInput } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\nimport { killEvent } from '../utils/dom';\nimport {\n createCompoundObservation,\n createLoincCode,\n createObservation,\n createQuantity,\n getCompoundObservationValue,\n getObservationValue,\n} from './Vitals.utils';\n\ninterface ObservationMeta {\n readonly code: string;\n readonly title: string;\n readonly unit: string;\n}\n\nconst LOINC_CODES: Record<string, ObservationMeta> = {\n bloodPressure: {\n code: '85354-9',\n title: 'Blood Pressure',\n unit: 'mm[Hg]',\n },\n heartRate: {\n code: '8867-4',\n title: 'Heart Rate',\n unit: '/min',\n },\n bodyTemperature: {\n code: '8310-5',\n title: 'Body Temperature',\n unit: 'Cel',\n },\n respiratoryRate: {\n code: '9279-1',\n title: 'Respiratory Rate',\n unit: '/min',\n },\n height: {\n code: '8302-2',\n title: 'height',\n unit: 'cm',\n },\n weight: {\n code: '29463-7',\n title: 'weight',\n unit: 'kg',\n },\n bmi: {\n code: '39156-5',\n title: 'BMI',\n unit: 'kg/m2',\n },\n oxygen: {\n code: '2708-6',\n title: 'Oxygen',\n unit: '%',\n },\n headCircumference: {\n code: '9843-4',\n title: 'Head Circumference',\n unit: 'cm',\n },\n};\n\nconst SYSTOLIC = '8480-6';\nconst DIASTOLIC = '8462-4';\n\nexport interface VitalsProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly vitals: Observation[];\n}\n\nexport function Vitals(props: VitalsProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [vitals, setVitals] = useState<Observation[]>(props.vitals);\n const [opened, { open, close }] = useDisclosure(false);\n\n const handleSubmit = useCallback(\n (formData: Record<string, string>) => {\n const newObservations = Object.entries(LOINC_CODES)\n .map(([name, meta]) => {\n if (name === 'bloodPressure') {\n return createCompoundObservation(patient, encounter, meta.code, meta.title, [\n {\n code: createLoincCode(SYSTOLIC, 'Systolic blood pressure'),\n valueQuantity: createQuantity(parseFloat(formData['systolic']), 'mm[Hg]'),\n },\n {\n code: createLoincCode(DIASTOLIC, 'Diastolic blood pressure'),\n valueQuantity: createQuantity(parseFloat(formData['diastolic']), 'mm[Hg]'),\n },\n ]);\n }\n return createObservation(\n patient,\n encounter,\n meta.code,\n meta.title,\n createQuantity(parseFloat(formData[name]), meta.unit)\n );\n })\n .filter(Boolean) as Observation[];\n\n // Execute all create requests in parallel to take advantage of autobatching\n Promise.all(newObservations.map((obs) => medplum.createResource<Observation>(obs)))\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Vitals\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n <Grid>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BP Sys\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getCompoundObservationValue(vitals, LOINC_CODES.bloodPressure.code, SYSTOLIC)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BP Dias\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getCompoundObservationValue(vitals, LOINC_CODES.bloodPressure.code, DIASTOLIC)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n HR\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.heartRate.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Temp\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.bodyTemperature.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n RR\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.respiratoryRate.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Height\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.height.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Weight\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.weight.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BMI\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.bmi.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n O2\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.oxygen.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n HC\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.headCircumference.code)} />\n </Grid.Col>\n </Grid>\n <Modal opened={opened} onClose={close} title=\"Add Vitals\">\n <Form onSubmit={handleSubmit}>\n <Stack>\n <Group grow>\n <TextInput name=\"systolic\" label=\"BP Sys\" data-autofocus={true} autoFocus />\n <TextInput name=\"diastolic\" label=\"BP Dias\" />\n </Group>\n <Group grow>\n <TextInput name=\"heartRate\" label=\"HR\" />\n <TextInput name=\"bodyTemperature\" label=\"Temp\" />\n </Group>\n <Group grow>\n <TextInput name=\"respiratoryRate\" label=\"RR\" />\n <TextInput name=\"height\" label=\"height\" />\n </Group>\n <Group grow>\n <TextInput name=\"weight\" label=\"Wt\" />\n <TextInput name=\"bmi\" label=\"BMI\" />\n </Group>\n <Group grow>\n <TextInput name=\"oxygen\" label=\"O2\" />\n <TextInput name=\"headCircumference\" label=\"HC\" />\n </Group>\n <Textarea name=\"notes\" label=\"Notes\" />\n </Stack>\n <Group justify=\"flex-end\" gap={4} mt=\"md\">\n <Button type=\"submit\">Save</Button>\n </Group>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { LOINC, UCUM, createReference } from '@medplum/core';\nimport { CodeableConcept, Encounter, Observation, ObservationComponent, Patient, Quantity } from '@medplum/fhirtypes';\n\nexport function getObservationValue(observations: Observation[], code: string): Quantity | undefined {\n const observation = observations.find((o) => o.code?.coding?.[0].code === code);\n return observation?.valueQuantity;\n}\n\nexport function getCompoundObservationValue(\n observations: Observation[],\n code: string,\n innerCode: string\n): Quantity | undefined {\n const observation = observations.find((o) => o.code?.coding?.[0].code === code);\n const component = observation?.component?.find((c) => c.code?.coding?.[0].code === innerCode);\n return component?.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 && !isNaN(value) && isFinite(value);\n}\n", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Patient, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { useCallback } from 'react';\nimport { ResourceTimeline, ResourceTimelineProps } 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('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", "import { Anchor, Button, NativeSelect, Stack, TextInput } from '@mantine/core';\nimport { InternalSchemaElement, getReferenceString } from '@medplum/core';\nimport { PlanDefinition, PlanDefinitionAction, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport { MouseEvent, SyntheticEvent, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { FormSection } from '../FormSection/FormSection';\nimport { ReferenceDisplay } from '../ReferenceDisplay/ReferenceDisplay';\nimport { setPropertyValue } from '../ResourceForm/ResourceForm.utils';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\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 const valueRef = useRef<PlanDefinition>();\n valueRef.current = value;\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({\n ...valueRef.current,\n [property]: newValue,\n } as PlanDefinition);\n }\n\n return (\n <div>\n <Form testid=\"questionnaire-form\" onSubmit={() => props.onSubmit(value)}>\n <TextInput\n label=\"Plan Title\"\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 <Button type=\"submit\">Save</Button>\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 const actionsRef = useRef<PlanDefinitionAction[]>();\n actionsRef.current = props.actions;\n\n function changeAction(changedAction: PlanDefinitionAction): void {\n props.onChange(\n (actionsRef.current as PlanDefinition[]).map((i) => (i.id === changedAction.id ? changedAction : i))\n );\n }\n\n function addAction(addedAction: PlanDefinitionAction): void {\n props.onChange([...(actionsRef.current as PlanDefinition[]), addedAction]);\n props.setSelectedKey(addedAction.id);\n }\n\n function removeAction(removedAction: PlanDefinitionAction): void {\n props.onChange((actionsRef.current as PlanDefinition[]).filter((i) => i !== removedAction));\n }\n\n return (\n <div className={classes.section}>\n {props.actions.map((action) => (\n <div key={action.id}>\n <ActionBuilder\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 </div>\n ))}\n <div className={classes.bottomActions}>\n <Anchor\n href=\"#\"\n onClick={(e: MouseEvent) => {\n killEvent(e);\n addAction({ id: generateId() });\n }}\n >\n Add action\n </Anchor>\n </div>\n </div>\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 const actionType = getInitialActionType(action);\n const editing = props.selectedKey === props.action.id;\n const hovering = props.hoverKey === props.action.id;\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 const className = cx(classes.section, {\n [classes.editing]: editing,\n [classes.hovering]: hovering && !editing,\n });\n\n return (\n <div data-testid={action.id} className={className} onClick={onClick} onMouseOver={onHover} onFocus={onHover}>\n {editing ? (\n <ActionEditor\n action={action}\n actionType={actionType}\n onChange={props.onChange}\n selectedKey={props.selectedKey}\n setSelectedKey={props.setSelectedKey}\n hoverKey={props.hoverKey}\n setHoverKey={props.setHoverKey}\n onRemove={props.onRemove}\n />\n ) : (\n <ActionDisplay action={action} actionType={actionType} />\n )}\n <div className={classes.bottomActions}>\n <Anchor\n href=\"#\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n props.onRemove();\n }}\n >\n Remove\n </Anchor>\n </div>\n </div>\n );\n}\n\nconst timingProperty: InternalSchemaElement = {\n path: 'PlanDefinition.action.timing[x]',\n min: 0,\n max: 1,\n description: '',\n isArray: false,\n constraints: [],\n type: ['dateTime', 'Period', 'Range', 'Timing'].map((t) => ({ code: t })),\n};\n\ninterface ActionDisplayProps {\n readonly action: PlanDefinitionAction;\n readonly actionType: string | undefined;\n}\n\nfunction ActionDisplay(props: ActionDisplayProps): JSX.Element {\n const { action, actionType } = props;\n const [propertyValue, propertyType] = getActionTiming(action);\n return (\n <div>\n <div>\n {action.title || 'Untitled'} {actionType && `(${actionType})`}\n </div>\n {action.definitionCanonical && (\n <div>\n <ReferenceDisplay value={{ reference: action.definitionCanonical }} />\n </div>\n )}\n {propertyValue && (\n <div>\n <ResourcePropertyDisplay property={timingProperty} propertyType={propertyType} value={propertyValue} />\n </div>\n )}\n </div>\n );\n}\n\ninterface ActionEditorProps {\n readonly action: PlanDefinitionAction;\n readonly actionType: string | undefined;\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 ActionEditor(props: ActionEditorProps): JSX.Element {\n const { action } = props;\n const [actionType, setActionType] = useState<string | undefined>(props.actionType);\n\n function changeProperty(property: string, value: any): void {\n props.onChange({\n ...action,\n [property]: value,\n } as PlanDefinitionAction);\n }\n\n return (\n <Stack gap=\"xl\">\n <TextInput\n name={`actionTitle-${action.id}`}\n label=\"Title\"\n defaultValue={action.title}\n onChange={(e) => changeProperty('title', e.currentTarget.value)}\n />\n <TextInput\n name={`actionDescription-${action.id}`}\n label=\"Description\"\n defaultValue={action.description}\n onChange={(e) => changeProperty('description', e.currentTarget.value)}\n />\n <NativeSelect\n label=\"Type of Action\"\n description=\"The type of the action to be performed.\"\n name={`actionType-${action.id}`}\n defaultValue={actionType}\n onChange={(e) => setActionType(e.currentTarget.value)}\n data={['', 'appointment', 'lab', 'questionnaire', 'task']}\n />\n {action.action && action.action.length > 0 && (\n <ActionArrayBuilder\n actions={action.action}\n selectedKey={props.selectedKey}\n setSelectedKey={props.setSelectedKey}\n hoverKey={props.hoverKey}\n setHoverKey={props.setHoverKey}\n onChange={(x) => changeProperty('action', x)}\n />\n )}\n {(() => {\n switch (actionType) {\n case 'appointment':\n return (\n <ActionResourceTypeBuilder\n title=\"Appointment\"\n description=\"The subject must schedule an appointment from the schedule.\"\n resourceType=\"Schedule\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'lab':\n return (\n <ActionResourceTypeBuilder\n title=\"Lab\"\n description=\"The subject must complete the following lab panel.\"\n resourceType=\"ActivityDefinition\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'questionnaire':\n return (\n <ActionResourceTypeBuilder\n title=\"Questionnaire\"\n description=\"The subject must complete the selected questionnaire.\"\n resourceType=\"Questionnaire\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'task':\n return (\n <ActionResourceTypeBuilder\n title=\"Task\"\n description=\"The subject must complete the following task.\"\n resourceType=\"ActivityDefinition\"\n action={action}\n onChange={props.onChange}\n />\n );\n default:\n return null;\n }\n })()}\n <FormSection title=\"Timing\" description=\"When the action should take place.\">\n <ActionTimingInput name={'timing-' + action.id} action={action} onChange={props.onChange} />\n </FormSection>\n </Stack>\n );\n}\n\ninterface ActionResourceTypeBuilderProps {\n readonly action: PlanDefinitionAction;\n readonly title: string;\n readonly description: string;\n readonly resourceType: ResourceType;\n readonly onChange: (action: PlanDefinitionAction) => void;\n}\n\nfunction ActionResourceTypeBuilder(props: ActionResourceTypeBuilderProps): JSX.Element {\n const { id, definitionCanonical } = props.action;\n const reference = definitionCanonical?.startsWith(props.resourceType + '/')\n ? { reference: definitionCanonical }\n : undefined;\n return (\n <ResourceInput\n name={id as string}\n resourceType={props.resourceType}\n defaultValue={reference}\n loadOnFocus={true}\n onChange={(newValue) => {\n if (newValue) {\n props.onChange({ ...props.action, definitionCanonical: getReferenceString(newValue) });\n } else {\n props.onChange({ ...props.action, definitionCanonical: undefined });\n }\n }}\n />\n );\n}\n\ninterface ActionTimingInputProps {\n readonly name: string;\n readonly action: PlanDefinitionAction;\n readonly onChange: (action: PlanDefinitionAction) => void;\n}\n\nfunction ActionTimingInput(props: ActionTimingInputProps): JSX.Element {\n const value = props.action;\n const key = 'timing';\n const [propertyValue, propertyType] = getActionTiming(value);\n return (\n <ResourcePropertyInput\n property={timingProperty}\n name=\"timing[x]\"\n path=\"PlanDefinition.timing[x]\"\n defaultValue={propertyValue}\n defaultPropertyType={propertyType}\n onChange={(newValue: any, propName?: string) => {\n props.onChange(setPropertyValue(value, key, propName ?? key, timingProperty, newValue));\n }}\n outcome={undefined}\n />\n );\n}\n\nfunction getInitialActionType(action: PlanDefinitionAction): string | undefined {\n if (action.definitionCanonical?.startsWith('Schedule')) {\n return 'appointment';\n }\n\n if (action.definitionCanonical?.startsWith('Questionnaire/')) {\n return 'questionnaire';\n }\n\n if (action.definitionCanonical?.startsWith('ActivityDefinition/')) {\n return 'task';\n }\n\n return undefined;\n}\n\nfunction getActionTiming(action: PlanDefinitionAction): [any, string] {\n return getValueAndType({ type: 'PlanDefinitionAction', value: action }, 'timing');\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 = parseInt(existing.substring(3), 10);\n if (!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 } as PlanDefinition;\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", "\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}\n\n.bottomActions {\n position: absolute;\n right: 4px;\n bottom: 0;\n font-size: var(--mantine-font-size-xs);\n\n & a {\n margin-left: 8px;\n }\n}", "import { Anchor, Box, Button, Group, NativeSelect, Space, Textarea, TextInput, Title } from '@mantine/core';\nimport { getElementDefinition, isResource as isResourceType } from '@medplum/core';\nimport {\n Extension,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n Reference,\n ResourceType,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconArrowDown, IconArrowUp } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { MouseEvent, SyntheticEvent, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { QuestionnaireFormItem } from '../QuestionnaireForm/QuestionnaireFormItem/QuestionnaireFormItem';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport { killEvent } from '../utils/dom';\nimport {\n getQuestionnaireItemReferenceTargetTypes,\n isChoiceQuestion,\n QuestionnaireItemType,\n setQuestionnaireItemReferenceTargetTypes,\n} from '../utils/questionnaire';\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 <Button type=\"submit\">Save</Button>\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<T>();\n itemRef.current = props.item;\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 as T;\n props.onChange({\n ...curr,\n item: curr.item?.map((i) => (i.id === changedItem.id ? changedItem : i)),\n } as T);\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 } as T);\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\n item={item}\n index={0}\n onChange={() => undefined}\n response={{ linkId: item.linkId }}\n />\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 } as QuestionnaireItem);\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 } as QuestionnaireItem,\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 } as Questionnaire;\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, parseInt(item.id.substring(3), 10) + 1);\n }\n if (item.linkId?.match(/^q\\d+$/)) {\n nextLinkId = Math.max(nextLinkId, 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: 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl',\n valueCodeableConcept: {\n coding: [\n {\n system: 'http://hl7.org/fhir/questionnaire-item-control',\n code: 'page',\n },\n ],\n },\n } as Extension,\n ],\n } as QuestionnaireItem;\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", "import { Checkbox, ComboboxItem, Group, MultiSelect, NativeSelect, Radio, Textarea, TextInput } from '@mantine/core';\nimport {\n capitalize,\n deepEquals,\n formatCoding,\n getElementDefinition,\n HTTP_HL7_ORG,\n stringify,\n TypedValue,\n typedValueToString,\n} from '@medplum/core';\nimport {\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n QuestionnaireItemInitial,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n} from '@medplum/fhirtypes';\nimport { ChangeEvent, useContext } from 'react';\nimport { AttachmentInput } from '../../AttachmentInput/AttachmentInput';\nimport { CheckboxFormSection } from '../../CheckboxFormSection/CheckboxFormSection';\nimport { CodingInput } from '../../CodingInput/CodingInput';\nimport { DateTimeInput } from '../../DateTimeInput/DateTimeInput';\nimport { QuantityInput } from '../../QuantityInput/QuantityInput';\nimport { ReferenceInput } from '../../ReferenceInput/ReferenceInput';\nimport { ResourcePropertyDisplay } from '../../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport {\n getItemAnswerOptionValue,\n getItemInitialValue,\n getNewMultiSelectValues,\n getQuestionnaireItemReferenceFilter,\n getQuestionnaireItemReferenceTargetTypes,\n QuestionnaireItemType,\n} from '../../utils/questionnaire';\nimport { QuestionnaireFormContext } from '../QuestionnaireForm.context';\n\nexport interface QuestionnaireFormItemProps {\n readonly item: QuestionnaireItem;\n readonly index: number;\n readonly response: QuestionnaireResponseItem;\n readonly onChange: (newResponseItem: QuestionnaireResponseItem) => void;\n}\n\nexport function QuestionnaireFormItem(props: QuestionnaireFormItemProps): JSX.Element | null {\n const context = useContext(QuestionnaireFormContext);\n const item = props.item;\n const response = props.response;\n\n function onChangeAnswer(\n newResponseAnswer: QuestionnaireResponseItemAnswer | QuestionnaireResponseItemAnswer[]\n ): void {\n let updatedAnswers: QuestionnaireResponseItemAnswer[];\n if (Array.isArray(newResponseAnswer)) {\n // It's a multi-select case, so use the array directly.\n updatedAnswers = newResponseAnswer;\n } else if (props.index >= (props.response?.answer?.length ?? 0)) {\n // if adding a new answer\n updatedAnswers = (props.response?.answer ?? []).concat([newResponseAnswer]);\n } else {\n // if updating an existing answer\n const newAnswers = (props.response?.answer ?? []).map((a, idx) =>\n idx === props.index ? newResponseAnswer : a\n ) as QuestionnaireResponseItemAnswer[];\n updatedAnswers = newAnswers ?? [];\n }\n props.onChange({\n id: response?.id,\n linkId: response?.linkId,\n text: item.text,\n answer: updatedAnswers,\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 const initial = item.initial && item.initial.length > 0 ? item.initial[0] : undefined;\n const defaultValue = getCurrentAnswer(response, props.index) ?? getItemInitialValue(initial);\n\n switch (type) {\n case QuestionnaireItemType.display:\n return <p key={props.item.linkId}>{props.item.text}</p>;\n case QuestionnaireItemType.boolean:\n return (\n <CheckboxFormSection key={props.item.linkId} title={props.item.text} htmlFor={props.item.linkId}>\n <Checkbox\n id={props.item.linkId}\n name={props.item.linkId}\n defaultChecked={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueBoolean: e.currentTarget.checked })}\n />\n </CheckboxFormSection>\n );\n case QuestionnaireItemType.decimal:\n return (\n <TextInput\n type=\"number\"\n step=\"any\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueDecimal: e.currentTarget.valueAsNumber })}\n />\n );\n case QuestionnaireItemType.integer:\n return (\n <TextInput\n type=\"number\"\n step={1}\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueInteger: e.currentTarget.valueAsNumber })}\n />\n );\n case QuestionnaireItemType.date:\n return (\n <TextInput\n type=\"date\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueDate: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.dateTime:\n return (\n <DateTimeInput\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(newValue: string) => onChangeAnswer({ valueDateTime: newValue })}\n />\n );\n case QuestionnaireItemType.time:\n return (\n <TextInput\n type=\"time\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueTime: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.string:\n case QuestionnaireItemType.url:\n return (\n <TextInput\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueString: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.text:\n return (\n <Textarea\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueString: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.attachment:\n return (\n <Group py={4}>\n <AttachmentInput\n path=\"\"\n name={name}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueAttachment: newValue })}\n />\n </Group>\n );\n case QuestionnaireItemType.reference:\n return (\n <ReferenceInput\n name={name}\n required={item.required}\n targetTypes={getQuestionnaireItemReferenceTargetTypes(item)}\n searchCriteria={getQuestionnaireItemReferenceFilter(item, context.subject, context.encounter)}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueReference: newValue })}\n />\n );\n case QuestionnaireItemType.quantity:\n return (\n <QuantityInput\n path=\"\"\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueQuantity: newValue })}\n disableWheel\n />\n );\n case QuestionnaireItemType.choice:\n case QuestionnaireItemType.openChoice:\n if (isDropDownChoice(item) && !item.answerValueSet) {\n return (\n <QuestionnaireChoiceDropDownInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n } else if (isMultiSelectChoice(item) && !item.answerValueSet) {\n return (\n <QuestionnaireMultiSelectInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n } else {\n return (\n <QuestionnaireChoiceSetInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n }\n default:\n return null;\n }\n}\n\ninterface QuestionnaireChoiceInputProps {\n readonly name: string;\n readonly item: QuestionnaireItem;\n readonly initial: QuestionnaireItemInitial | undefined;\n readonly response: QuestionnaireResponseItem;\n readonly onChangeAnswer: (\n newResponseAnswer: QuestionnaireResponseItemAnswer | QuestionnaireResponseItemAnswer[]\n ) => void;\n}\n\nfunction QuestionnaireChoiceDropDownInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, response } = props;\n\n if (!item.answerOption?.length) {\n return <NoAnswerDisplay />;\n }\n\n const initialValue = getItemInitialValue(initial);\n\n const data = [''];\n\n for (const option of item.answerOption) {\n const optionValue = getItemAnswerOptionValue(option);\n data.push(typedValueToString(optionValue) as string);\n }\n\n const defaultValue = getCurrentAnswer(response) ?? initialValue;\n\n if (item.repeats) {\n const { propertyName, data } = formatSelectData(props.item);\n const currentAnswer = getCurrentMultiSelectAnswer(response);\n\n return (\n <MultiSelect\n data={data}\n placeholder=\"Select items\"\n searchable\n defaultValue={currentAnswer || [typedValueToString(initialValue)]}\n onChange={(selected) => {\n const values = getNewMultiSelectValues(selected, propertyName, item);\n props.onChangeAnswer(values);\n }}\n />\n );\n }\n\n return (\n <NativeSelect\n id={name}\n name={name}\n onChange={(e: ChangeEvent<HTMLSelectElement>) => {\n const index = e.currentTarget.selectedIndex;\n if (index === 0) {\n props.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 props.onChangeAnswer({ [propertyName]: optionValue.value });\n }}\n defaultValue={formatCoding(defaultValue?.value) || defaultValue?.value}\n data={data}\n />\n );\n}\n\nfunction QuestionnaireMultiSelectInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { item, initial, response } = props;\n\n if (!item.answerOption?.length) {\n return <NoAnswerDisplay />;\n }\n\n const initialValue = getItemInitialValue(initial);\n const { propertyName, data } = formatSelectData(props.item);\n const currentAnswer = getCurrentMultiSelectAnswer(response);\n\n return (\n <MultiSelect\n data={data}\n placeholder=\"Select items\"\n searchable\n defaultValue={currentAnswer || [typedValueToString(initialValue)]}\n onChange={(selected) => {\n const values = getNewMultiSelectValues(selected, propertyName, item);\n props.onChangeAnswer(values);\n }}\n />\n );\n}\n\nfunction QuestionnaireChoiceSetInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, onChangeAnswer, response } = props;\n\n if (!item.answerOption?.length && !item.answerValueSet) {\n return <NoAnswerDisplay />;\n }\n\n if (item.answerValueSet) {\n return (\n <CodingInput\n path=\"\"\n name={name}\n binding={item.answerValueSet}\n onChange={(code) => onChangeAnswer({ valueCoding: code })}\n creatable={item.type === QuestionnaireItemType.openChoice}\n />\n );\n }\n return (\n <QuestionnaireChoiceRadioInput\n name={response?.id ?? name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={onChangeAnswer}\n />\n );\n}\n\nfunction QuestionnaireChoiceRadioInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, onChangeAnswer, response } = props;\n const valueElementDefinition = getElementDefinition('QuestionnaireItemAnswerOption', 'value[x]');\n const initialValue = getItemInitialValue(initial);\n\n const options: [string, TypedValue][] = [];\n let defaultValue = undefined;\n if (item.answerOption) {\n for (let i = 0; i < item.answerOption.length; i++) {\n const option = item.answerOption[i];\n const optionName = `${name}-option-${i}`;\n const optionValue = getItemAnswerOptionValue(option);\n\n if (!optionValue?.value) {\n continue;\n }\n\n if (initialValue && stringify(optionValue) === stringify(initialValue)) {\n defaultValue = optionName;\n }\n options.push([optionName, optionValue]);\n }\n }\n\n const defaultAnswer = getCurrentAnswer(response);\n const answerLinkId = getCurrentRadioAnswer(options, defaultAnswer);\n\n return (\n <Radio.Group\n name={name}\n value={answerLinkId ?? defaultValue}\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 {options.map(([optionName, optionValue]) => (\n <Radio\n key={optionName}\n id={optionName}\n value={optionName}\n py={4}\n label={\n <ResourcePropertyDisplay\n property={valueElementDefinition}\n propertyType={optionValue.type}\n value={optionValue.value}\n />\n }\n />\n ))}\n </Radio.Group>\n );\n}\n\nfunction NoAnswerDisplay(): JSX.Element {\n return <TextInput disabled placeholder=\"No Answers Defined\" />;\n}\n\nfunction getCurrentAnswer(response: QuestionnaireResponseItem, index: number = 0): TypedValue {\n const results = response.answer;\n return getItemAnswerOptionValue(results?.[index] ?? {});\n}\n\nfunction getCurrentMultiSelectAnswer(response: QuestionnaireResponseItem): 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);\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\nfunction isDropDownChoice(item: QuestionnaireItem): boolean {\n return !!item.extension?.some(\n (e) =>\n e.url === 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl' &&\n e.valueCodeableConcept?.coding?.[0]?.code === 'drop-down'\n );\n}\n\nfunction isMultiSelectChoice(item: QuestionnaireItem): boolean {\n return !!item.extension?.some(\n (e) =>\n e.url === HTTP_HL7_ORG + '/fhir/StructureDefinition/questionnaire-itemControl' &&\n e.valueCodeableConcept?.coding?.[0]?.code === 'multi-select'\n );\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", "import {\n HTTP_HL7_ORG,\n PropertyType,\n TypedValue,\n deepClone,\n evalFhirPathTyped,\n getExtension,\n getReferenceString,\n getTypedPropertyValueWithoutSchema,\n splitN,\n toJsBoolean,\n toTypedValue,\n typedValueToString,\n} from '@medplum/core';\nimport {\n Encounter,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n QuestionnaireItemEnableWhen,\n QuestionnaireItemInitial,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n Reference,\n ResourceType,\n} from '@medplum/fhirtypes';\n\nexport enum QuestionnaireItemType {\n group = 'group',\n display = 'display',\n question = 'question',\n boolean = 'boolean',\n decimal = 'decimal',\n integer = 'integer',\n date = 'date',\n dateTime = 'dateTime',\n time = 'time',\n string = 'string',\n text = 'text',\n url = 'url',\n choice = 'choice',\n openChoice = 'open-choice',\n attachment = 'attachment',\n reference = 'reference',\n quantity = 'quantity',\n}\n\nexport function isChoiceQuestion(item: QuestionnaireItem): boolean {\n return item.type === 'choice' || item.type === 'open-choice';\n}\n\nexport function isQuestionEnabled(\n item: QuestionnaireItem,\n questionnaireResponse: QuestionnaireResponse | undefined\n): boolean {\n const extension = getExtension(\n item,\n HTTP_HL7_ORG + '/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-enableWhenExpression'\n );\n if (questionnaireResponse && extension) {\n const expression = extension.valueExpression?.expression;\n if (expression) {\n const value = toTypedValue(questionnaireResponse);\n const result = evalFhirPathTyped(expression, [value], { '%resource': value });\n return toJsBoolean(result);\n }\n }\n\n if (!item.enableWhen) {\n return true;\n }\n\n const enableBehavior = item.enableBehavior ?? 'any';\n for (const enableWhen of item.enableWhen) {\n const actualAnswers = getByLinkId(questionnaireResponse?.item, enableWhen.question as string);\n\n if (enableWhen.operator === 'exists' && !enableWhen.answerBoolean && !actualAnswers?.length) {\n if (enableBehavior === 'any') {\n return true;\n } else {\n continue;\n }\n }\n const { anyMatch, allMatch } = checkAnswers(enableWhen, actualAnswers, enableBehavior);\n\n if (enableBehavior === 'any' && anyMatch) {\n return true;\n }\n if (enableBehavior === 'all' && !allMatch) {\n return false;\n }\n }\n\n return enableBehavior !== 'any';\n}\n\nexport function evaluateCalculatedExpressionsInQuestionnaire(\n items: QuestionnaireItem[],\n response: QuestionnaireResponse | undefined\n): QuestionnaireResponseItem[] {\n return items\n .map((item): QuestionnaireResponseItem | null => {\n if (item.item) {\n return {\n ...item,\n item: evaluateCalculatedExpressionsInQuestionnaire(item.item, response),\n };\n } else {\n const calculatedValue = evaluateCalculatedExpression(item, response);\n if (!calculatedValue) {\n return null;\n }\n\n const answer = typedValueToResponseItem(item, calculatedValue);\n\n if (!answer) {\n return null;\n }\n\n return {\n id: item?.id,\n linkId: item?.linkId,\n text: item.text,\n answer: [answer],\n };\n }\n })\n .filter((item): item is QuestionnaireResponseItem => item !== null);\n}\n\nexport function typedValueToResponseItem(\n item: QuestionnaireItem,\n value: TypedValue\n): QuestionnaireResponseItemAnswer | undefined {\n if (!item.type) {\n return undefined;\n }\n\n switch (item.type) {\n case QuestionnaireItemType.boolean:\n return value.type === PropertyType.boolean ? { valueBoolean: value.value } : undefined;\n case QuestionnaireItemType.date:\n return value.type === PropertyType.date ? { valueDate: value.value } : undefined;\n case QuestionnaireItemType.dateTime:\n return value.type === PropertyType.dateTime ? { valueDateTime: value.value } : undefined;\n case QuestionnaireItemType.time:\n return value.type === PropertyType.time ? { valueTime: value.value } : undefined;\n case QuestionnaireItemType.url:\n return value.type === PropertyType.url ? { valueString: value.value } : undefined;\n case QuestionnaireItemType.text:\n return value.type === PropertyType.string ? { valueString: value.value } : undefined;\n case QuestionnaireItemType.attachment:\n return value.type === PropertyType.Attachment ? { valueAttachment: value.value } : undefined;\n case QuestionnaireItemType.reference:\n return value.type === PropertyType.Reference ? { valueReference: value.value } : undefined;\n case QuestionnaireItemType.quantity:\n return { valueQuantity: value.value };\n case QuestionnaireItemType.decimal:\n return { valueDecimal: value.value };\n case QuestionnaireItemType.integer:\n return { valueInteger: value.value };\n case QuestionnaireItemType.string:\n return { valueString: value.value };\n default:\n return undefined;\n }\n}\n\nfunction evaluateCalculatedExpression(\n item: QuestionnaireItem,\n response: QuestionnaireResponse | undefined\n): TypedValue | undefined {\n if (!response) {\n return undefined;\n }\n\n const extension = getExtension(\n item,\n HTTP_HL7_ORG + '/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression'\n );\n\n if (extension) {\n const expression = extension.valueExpression?.expression;\n if (expression) {\n const value = toTypedValue(response);\n const result = evalFhirPathTyped(expression, [value], { '%resource': value });\n return result.length !== 0 ? result[0] : undefined;\n }\n }\n return undefined;\n}\n\nexport function mergeUpdatedItems(\n mergedItems: QuestionnaireResponseItem[],\n updatedItems: QuestionnaireResponseItem[]\n): QuestionnaireResponseItem[] {\n return mergedItems.map((mergedItem) => {\n const updatedItem = updatedItems.find((updated) => updated.linkId === mergedItem.linkId);\n\n // Usually fields with calculated expressions would be readOnly in the case where it allows foe manual updates.\n // It would get replaced with content from calcultaed expresion.\n if (updatedItem) {\n return {\n ...mergedItem,\n item: updatedItem.item ? mergeUpdatedItems(mergedItem.item || [], updatedItem.item) : mergedItem.item,\n answer: updatedItem.answer || mergedItem.answer,\n };\n }\n return mergedItem;\n });\n}\n\nexport function getNewMultiSelectValues(\n selected: string[],\n propertyName: string,\n item: QuestionnaireItem\n): QuestionnaireResponseItemAnswer[] {\n const result: QuestionnaireResponseItemAnswer[] = [];\n\n for (const selectedStr of selected) {\n const option = item.answerOption?.find(\n (candidate) => typedValueToString(getItemAnswerOptionValue(candidate)) === selectedStr\n );\n if (option) {\n const optionValue = getItemAnswerOptionValue(option);\n if (optionValue) {\n result.push({ [propertyName]: optionValue.value });\n }\n }\n }\n\n return result;\n}\n\nfunction getByLinkId(\n responseItems: QuestionnaireResponseItem[] | undefined,\n linkId: string\n): QuestionnaireResponseItemAnswer[] | undefined {\n if (!responseItems) {\n return undefined;\n }\n\n for (const response of responseItems) {\n if (response.linkId === linkId) {\n return response.answer;\n }\n if (response.item) {\n const nestedAnswer = getByLinkId(response.item, linkId);\n if (nestedAnswer) {\n return nestedAnswer;\n }\n }\n }\n\n return undefined;\n}\n\nfunction evaluateMatch(actualAnswer: TypedValue | undefined, expectedAnswer: TypedValue, operator?: string): boolean {\n // We handle exists separately since its so different in terms of comparisons than the other mathematical operators\n if (operator === 'exists') {\n // if actualAnswer is not undefined, then exists: true passes\n // if actualAnswer is undefined, then exists: false passes\n return !!actualAnswer === expectedAnswer.value;\n } else if (!actualAnswer) {\n return false;\n } else {\n // `=` and `!=` should be treated as the FHIRPath `~` and `!~`\n // All other operators should be unmodified\n const fhirPathOperator = operator === '=' || operator === '!=' ? operator?.replace('=', '~') : operator;\n const [{ value }] = evalFhirPathTyped(`%actualAnswer ${fhirPathOperator} %expectedAnswer`, [actualAnswer], {\n '%actualAnswer': actualAnswer,\n '%expectedAnswer': expectedAnswer,\n });\n return value;\n }\n}\n\nfunction checkAnswers(\n enableWhen: QuestionnaireItemEnableWhen,\n answers: QuestionnaireResponseItemAnswer[] | undefined,\n enableBehavior: 'any' | 'all'\n): { anyMatch: boolean; allMatch: boolean } {\n const actualAnswers = answers || [];\n const expectedAnswer = getItemEnableWhenValueAnswer(enableWhen);\n\n let anyMatch = false;\n let allMatch = true;\n\n for (const actualAnswerValue of actualAnswers) {\n const actualAnswer = getResponseItemAnswerValue(actualAnswerValue);\n const { operator } = enableWhen;\n const match = evaluateMatch(actualAnswer, expectedAnswer, operator);\n if (match) {\n anyMatch = true;\n } else {\n allMatch = false;\n }\n\n if (enableBehavior === 'any' && anyMatch) {\n break;\n }\n }\n\n return { anyMatch, allMatch };\n}\n\nexport function getQuestionnaireItemReferenceTargetTypes(item: QuestionnaireItem): ResourceType[] | undefined {\n const extension = getExtension(item, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource');\n if (!extension) {\n return undefined;\n }\n if (extension.valueCode !== undefined) {\n return [extension.valueCode] as ResourceType[];\n }\n if (extension.valueCodeableConcept) {\n return extension.valueCodeableConcept?.coding?.map((c) => c.code) as ResourceType[];\n }\n return undefined;\n}\n\nexport function setQuestionnaireItemReferenceTargetTypes(\n item: QuestionnaireItem,\n targetTypes: ResourceType[] | undefined\n): QuestionnaireItem {\n const result = deepClone(item);\n let extension = getExtension(result, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource');\n\n if (!targetTypes || targetTypes.length === 0) {\n if (extension) {\n result.extension = result.extension?.filter((e) => e !== extension);\n }\n return result;\n }\n\n if (!extension) {\n if (!result.extension) {\n result.extension = [];\n }\n extension = { url: 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource' };\n result.extension.push(extension);\n }\n\n if (targetTypes.length === 1) {\n extension.valueCode = targetTypes[0];\n delete extension.valueCodeableConcept;\n } else {\n extension.valueCodeableConcept = { coding: targetTypes.map((t) => ({ code: t })) };\n delete extension.valueCode;\n }\n\n return result;\n}\n\n/**\n * Returns the reference filter for the given questionnaire item.\n * @see https://build.fhir.org/ig/HL7/fhir-extensions//StructureDefinition-questionnaire-referenceFilter-definitions.html\n * @param item - The questionnaire item to get the reference filter for.\n * @param subject - Optional subject reference.\n * @param encounter - Optional encounter reference.\n * @returns The reference filter as a map of key/value pairs.\n */\nexport function getQuestionnaireItemReferenceFilter(\n item: QuestionnaireItem,\n subject: Reference | undefined,\n encounter: Reference<Encounter> | undefined\n): Record<string, string> | undefined {\n const extension = getExtension(item, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter');\n if (!extension?.valueString) {\n return undefined;\n }\n\n // Replace variables\n let filter = extension.valueString;\n if (subject?.reference) {\n filter = filter.replaceAll('$subj', subject.reference);\n }\n if (encounter?.reference) {\n filter = filter.replaceAll('$encounter', encounter.reference);\n }\n\n // Parse the valueString into a map\n const result: Record<string, string> = {};\n const parts = filter.split('&');\n for (const part of parts) {\n const [key, value] = splitN(part, '=', 2);\n result[key] = value;\n }\n return result;\n}\n\nexport function buildInitialResponse(questionnaire: Questionnaire): QuestionnaireResponse {\n const response: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n questionnaire: getReferenceString(questionnaire),\n item: buildInitialResponseItems(questionnaire.item),\n status: 'in-progress',\n };\n\n return response;\n}\n\nfunction buildInitialResponseItems(items: QuestionnaireItem[] | undefined): QuestionnaireResponseItem[] {\n return items?.map(buildInitialResponseItem) ?? [];\n}\n\nexport function buildInitialResponseItem(item: QuestionnaireItem): QuestionnaireResponseItem {\n return {\n id: generateId(),\n linkId: item.linkId,\n text: item.text,\n item: buildInitialResponseItems(item.item),\n answer: item.initial?.map(buildInitialResponseAnswer) ?? [],\n };\n}\n\nlet nextId = 1;\nfunction generateId(): string {\n return 'id-' + nextId++;\n}\n\nfunction buildInitialResponseAnswer(answer: QuestionnaireItemInitial): QuestionnaireResponseItemAnswer {\n // This works because QuestionnaireItemInitial and QuestionnaireResponseItemAnswer\n // have the same properties.\n return { ...answer };\n}\n\n/**\n * Returns the number of pages in the questionnaire.\n *\n * By default, a questionnaire is represented as a simple single page questionnaire,\n * so the default return value is 1.\n *\n * If the questionnaire has a page extension on the first item, then the number of pages\n * is the number of top level items in the questionnaire.\n *\n * @param questionnaire - The questionnaire to get the number of pages for.\n * @returns The number of pages in the questionnaire. Default is 1.\n */\nexport function getNumberOfPages(questionnaire: Questionnaire): number {\n const firstItem = questionnaire?.item?.[0];\n if (firstItem) {\n const extension = getExtension(firstItem, 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl');\n if (extension?.valueCodeableConcept?.coding?.[0]?.code === 'page') {\n return (questionnaire.item as QuestionnaireItem[]).length;\n }\n }\n return 1;\n}\n\nexport function getItemInitialValue(initial: QuestionnaireItemInitial | undefined): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemInitial', value: initial },\n 'value'\n ) as TypedValue;\n}\n\nexport function getItemAnswerOptionValue(option: QuestionnaireItemAnswerOption): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemAnswerOption', value: option },\n 'value'\n ) as TypedValue;\n}\n\nexport function getItemEnableWhenValueAnswer(enableWhen: QuestionnaireItemEnableWhen): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemEnableWhen', value: enableWhen },\n 'answer'\n ) as TypedValue;\n}\n\nexport function getResponseItemAnswerValue(answer: QuestionnaireResponseItemAnswer): TypedValue | undefined {\n return getTypedPropertyValueWithoutSchema({ type: 'QuestionnaireResponseItemAnswer', value: answer }, 'value') as\n | TypedValue\n | undefined;\n}\n", "import { Encounter, Reference } from '@medplum/fhirtypes';\nimport { createContext } from 'react';\n\nexport const QuestionnaireFormContext = createContext<{ subject?: Reference; encounter?: Reference<Encounter> }>({});\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}", "import { Title } from '@mantine/core';\nimport { createReference, getReferenceString } from '@medplum/core';\nimport {\n Encounter,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, usePrevious, useResource } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport {\n buildInitialResponse,\n getNumberOfPages,\n isQuestionEnabled,\n evaluateCalculatedExpressionsInQuestionnaire,\n mergeUpdatedItems,\n} from '../utils/questionnaire';\nimport { QuestionnaireFormContext } from './QuestionnaireForm.context';\nimport { QuestionnairePageSequence } from './QuestionnaireFormComponents/QuestionnaireFormPageSequence';\n\nexport interface QuestionnaireFormProps {\n readonly questionnaire: Questionnaire | Reference<Questionnaire>;\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 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 { subject, source: sourceFromProps } = props;\n const questionnaire = useResource(props.questionnaire);\n const prevQuestionnaire = usePrevious(questionnaire);\n const [response, setResponse] = useState<QuestionnaireResponse | undefined>();\n const [activePage, setActivePage] = useState(0);\n\n const onChangeRef = useRef(props.onChange);\n onChangeRef.current = props.onChange;\n\n const onSubmitRef = useRef(props.onSubmit);\n onSubmitRef.current = props.onSubmit;\n\n useEffect(() => {\n // If the Questionnaire remains \"the same\", keep the existing response\n if (questionnaire && getQuestionnaireIdentity(prevQuestionnaire) === getQuestionnaireIdentity(questionnaire)) {\n return;\n }\n\n // throw out the existing response and start over\n setResponse(questionnaire ? buildInitialResponse(questionnaire) : undefined);\n }, [questionnaire, prevQuestionnaire]);\n\n useEffect(() => {\n if (response && onChangeRef.current) {\n try {\n onChangeRef.current(response);\n } catch (e) {\n console.error('Error invoking QuestionnaireForm.onChange callback', e);\n }\n }\n }, [response]);\n\n const setItems = useCallback(\n (newResponseItems: QuestionnaireResponseItem | QuestionnaireResponseItem[]): void => {\n setResponse((prevResponse) => {\n const currentItems = prevResponse?.item ?? [];\n const mergedItems = mergeItems(\n currentItems,\n Array.isArray(newResponseItems) ? newResponseItems : [newResponseItems]\n );\n\n const tempResponse: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n status: 'in-progress',\n item: mergedItems,\n };\n\n const updatedItems = evaluateCalculatedExpressionsInQuestionnaire(questionnaire?.item ?? [], tempResponse);\n const mergedItemsWithUpdates = mergeUpdatedItems(mergedItems, updatedItems);\n\n const newResponse: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n status: 'in-progress',\n item: mergedItemsWithUpdates,\n };\n\n return newResponse;\n });\n },\n [questionnaire]\n );\n\n const handleSubmit = useCallback(() => {\n const onSubmit = onSubmitRef.current;\n if (onSubmit && response) {\n let source = sourceFromProps;\n if (!source) {\n const profile = medplum.getProfile();\n if (profile) {\n source = createReference(profile);\n }\n }\n onSubmit({\n ...response,\n questionnaire: getReferenceString(questionnaire as Questionnaire),\n subject,\n source,\n authored: new Date().toISOString(),\n status: 'completed',\n });\n }\n }, [medplum, questionnaire, response, subject, sourceFromProps]);\n\n function checkForQuestionEnabled(item: QuestionnaireItem): boolean {\n return isQuestionEnabled(item, response);\n }\n\n if (!questionnaire || !response) {\n return null;\n }\n\n const numberOfPages = getNumberOfPages(questionnaire);\n const nextStep = (): void => setActivePage((current) => current + 1);\n const prevStep = (): void => setActivePage((current) => current - 1);\n\n return (\n <QuestionnaireFormContext.Provider value={{ subject: props.subject, encounter: props.encounter }}>\n <Form testid=\"questionnaire-form\" onSubmit={handleSubmit}>\n {questionnaire.title && <Title>{questionnaire.title}</Title>}\n <QuestionnairePageSequence\n items={questionnaire.item ?? []}\n response={response}\n onChange={setItems}\n renderPages={!props.disablePagination && numberOfPages > 1}\n activePage={activePage}\n numberOfPages={numberOfPages}\n excludeButtons={props.excludeButtons}\n submitButtonText={props.submitButtonText}\n checkForQuestionEnabled={checkForQuestionEnabled}\n nextStep={nextStep}\n prevStep={prevStep}\n />\n </Form>\n </QuestionnaireFormContext.Provider>\n );\n}\n\nfunction mergeIndividualItems(\n prevItem: QuestionnaireResponseItem,\n newItem: QuestionnaireResponseItem\n): QuestionnaireResponseItem {\n // Recursively merge the nested items based on their ids.\n const mergedNestedItems = mergeItems(prevItem.item ?? [], newItem.item ?? []);\n\n return {\n ...newItem,\n item: mergedNestedItems.length > 0 ? mergedNestedItems : undefined,\n answer: newItem.answer && newItem.answer.length > 0 ? newItem.answer : prevItem.answer,\n };\n}\n\nfunction mergeItems(\n prevItems: QuestionnaireResponseItem[],\n newItems: QuestionnaireResponseItem[]\n): QuestionnaireResponseItem[] {\n const result: QuestionnaireResponseItem[] = [];\n const usedIds = new Set<string>();\n\n for (const prevItem of prevItems) {\n const itemId = prevItem.id;\n const newItem = newItems.find((item) => item.id === itemId);\n\n if (newItem) {\n result.push(mergeIndividualItems(prevItem, newItem));\n usedIds.add(newItem.id as string);\n } else {\n result.push(prevItem);\n }\n }\n\n // Add items from newItems that were not in prevItems.\n for (const newItem of newItems) {\n if (!usedIds.has(newItem.id as string)) {\n result.push(newItem);\n }\n }\n\n return result;\n}\n\nfunction getQuestionnaireIdentity(questionnaire: Questionnaire | undefined): Questionnaire | string | undefined {\n return questionnaire?.id || questionnaire;\n}\n", "import { Button, Group, Stack, Stepper } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponse, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { QuestionnaireItemType } from '../../utils/questionnaire';\nimport { QuestionnaireRepeatableItem } from '../QuestionnaireFormItem/QuestionnaireRepeatableItem';\nimport { QuestionnaireRepeatedGroup } from './QuestionnaireFormGroup';\n\ninterface QuestionnairePageSequenceProps {\n readonly items: QuestionnaireItem[];\n readonly response?: QuestionnaireResponse;\n readonly renderPages: boolean;\n readonly activePage?: number;\n readonly numberOfPages: number;\n readonly excludeButtons?: boolean;\n readonly submitButtonText?: string;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (items: QuestionnaireResponseItem | QuestionnaireResponseItem[]) => void;\n readonly nextStep: () => void;\n readonly prevStep: () => void;\n}\n\nexport function QuestionnairePageSequence(props: QuestionnairePageSequenceProps): JSX.Element {\n const {\n items,\n response,\n activePage,\n onChange,\n nextStep,\n prevStep,\n numberOfPages,\n renderPages,\n submitButtonText,\n excludeButtons,\n checkForQuestionEnabled,\n } = props;\n\n const form = items.map((item) => {\n const itemResponse = response?.item?.filter((i) => i.linkId === item.linkId) ?? [];\n\n const repeatedItem =\n item.type === QuestionnaireItemType.group ? (\n <QuestionnaireRepeatedGroup\n key={item.linkId}\n item={item}\n response={itemResponse}\n onChange={onChange}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n ) : (\n <QuestionnaireRepeatableItem\n key={item.linkId}\n item={item}\n response={itemResponse?.[0]}\n onChange={onChange}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n );\n\n if (renderPages) {\n return (\n <Stepper.Step key={item.linkId} label={item.text}>\n {repeatedItem}\n </Stepper.Step>\n );\n }\n return repeatedItem;\n });\n\n return (\n <>\n {renderPages && (\n <Stepper active={activePage ?? 0} allowNextStepsSelect={false} p={6}>\n {form}\n </Stepper>\n )}\n {!renderPages && <Stack>{form}</Stack>}\n {!excludeButtons && (\n <ButtonGroup\n activePage={activePage ?? 0}\n numberOfPages={numberOfPages}\n nextStep={renderPages ? nextStep : undefined}\n prevStep={renderPages ? prevStep : undefined}\n renderPages={renderPages}\n submitButtonText={submitButtonText}\n />\n )}\n </>\n );\n}\n\ninterface ButtonGroupProps {\n readonly activePage: number;\n readonly numberOfPages: number;\n readonly renderPages: boolean;\n readonly submitButtonText?: string;\n readonly nextStep?: () => void;\n readonly prevStep?: () => void;\n}\n\nfunction ButtonGroup(props: ButtonGroupProps): JSX.Element {\n const showBackButton = props.renderPages && props.activePage > 0;\n const showNextButton = props.renderPages && props.activePage < props.numberOfPages - 1;\n const showSubmitButton = !props.renderPages || props.activePage === props.numberOfPages - 1;\n\n return (\n <Group justify=\"flex-end\" mt=\"xl\" gap=\"xs\">\n {showBackButton && <Button onClick={props.prevStep}>Back</Button>}\n {showNextButton && (\n <Button\n onClick={(e) => {\n const form = e.currentTarget.closest('form') as HTMLFormElement;\n if (props.nextStep && form.reportValidity()) {\n props.nextStep();\n }\n }}\n >\n Next\n </Button>\n )}\n {showSubmitButton && <Button type=\"submit\">{props.submitButtonText ?? 'Submit'}</Button>}\n </Group>\n );\n}\n", "import { Anchor } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { FormSection } from '../../FormSection/FormSection';\nimport { QuestionnaireItemType } from '../../utils/questionnaire';\nimport { QuestionnaireFormItem } from './QuestionnaireFormItem';\n\ninterface QuestionnaireRepeatableItemProps {\n readonly item: QuestionnaireItem;\n readonly response?: QuestionnaireResponseItem;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (items: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireRepeatableItem(props: QuestionnaireRepeatableItemProps): JSX.Element | null {\n const { item, response, onChange } = props;\n const [number, setNumber] = useState(getNumberOfRepeats(item, response ?? { linkId: item.linkId }));\n if (!props.checkForQuestionEnabled(item)) {\n return null;\n }\n\n if (!response) {\n return null;\n }\n\n if (item.type === QuestionnaireItemType.display) {\n return <p key={item.linkId}>{item.text}</p>;\n }\n\n const showAddButton =\n item?.repeats && item.type !== QuestionnaireItemType.choice && item.type !== QuestionnaireItemType.openChoice;\n\n // Styling reason to avoid duplicate text\n if (item.type === QuestionnaireItemType.boolean) {\n return (\n <QuestionnaireFormItem\n key={item.linkId}\n item={item}\n response={response}\n onChange={(r) => onChange([r])}\n index={0}\n />\n );\n }\n\n return (\n <FormSection\n key={props.item.linkId}\n htmlFor={props.item.linkId}\n title={props.item.text}\n withAsterisk={props.item.required}\n >\n {[...Array(number)].map((_, index) => (\n <QuestionnaireFormItem\n key={`${item.linkId}-${index}`}\n item={item}\n response={response}\n onChange={(r) => onChange([r])}\n index={index}\n />\n ))}\n {showAddButton && <Anchor onClick={() => setNumber((n) => n + 1)}>Add Item</Anchor>}\n </FormSection>\n );\n}\n\nfunction getNumberOfRepeats(item: QuestionnaireItem, response: QuestionnaireResponseItem): number {\n if (item.type === QuestionnaireItemType.choice || item.type === QuestionnaireItemType.openChoice) {\n return 1;\n }\n const answers = response.answer;\n return answers?.length ? answers.length : 1;\n}\n", "import { Anchor, Stack, Title } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { useEffect, useState } from 'react';\nimport { QuestionnaireItemType, buildInitialResponseItem } from '../../utils/questionnaire';\nimport { QuestionnaireRepeatableItem } from '../QuestionnaireFormItem/QuestionnaireRepeatableItem';\n\ninterface QuestionnaireRepeatableGroupProps {\n readonly item: QuestionnaireItem;\n readonly response: QuestionnaireResponseItem[];\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (responses: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireRepeatedGroup(props: QuestionnaireRepeatableGroupProps): JSX.Element | null {\n const [responses, setResponses] = useState(props.response);\n\n useEffect(() => {\n setResponses(props.response);\n }, [props.response]);\n\n if (responses.length === 0) {\n return null;\n }\n\n function handleRepeatableGroup(newResponseItems: QuestionnaireResponseItem[], index: number): void {\n const newResponses = responses.map((responses, idx) => (idx === index ? newResponseItems[0] : responses));\n setResponses(newResponses);\n props.onChange(newResponses);\n }\n\n function insertNewGroup(): void {\n const newResponse = buildInitialResponseItem(props.item);\n setResponses([...responses, newResponse]);\n }\n\n return (\n <>\n {responses.map((response, idx) => (\n <QuestionnaireGroup\n key={response.id}\n item={props.item}\n response={response}\n checkForQuestionEnabled={props.checkForQuestionEnabled}\n onChange={(r) => handleRepeatableGroup(r, idx)}\n />\n ))}\n {props.item.repeats && <Anchor onClick={insertNewGroup}>{`Add Group: ${props.item.text}`}</Anchor>}\n </>\n );\n}\n\ninterface QuestionnaireGroupProps {\n readonly item: QuestionnaireItem;\n readonly response: QuestionnaireResponseItem;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (response: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireGroup(props: QuestionnaireGroupProps): JSX.Element | null {\n const { response, checkForQuestionEnabled, onChange } = props;\n function onSetGroup(newResponseItem: QuestionnaireResponseItem[]): void {\n const newResponse = response.item?.map((current) => {\n const matchingItem = newResponseItem.find((newResponse) => newResponse.id === current.id);\n return matchingItem ?? current;\n });\n // This checks to see if there were any nested repeated groups that we need to add\n const mergedResponse = newResponse?.concat(newResponseItem.slice(1));\n const groupResponse = { ...response, item: mergedResponse };\n onChange([groupResponse]);\n }\n\n if (!props.checkForQuestionEnabled(props.item)) {\n return null;\n }\n\n return (\n <div key={props.item.linkId}>\n {props.item.text && (\n <Title order={3} mb=\"md\">\n {props.item.text}\n </Title>\n )}\n <Stack>\n {props.item.item?.map((item) => {\n if (item.type === QuestionnaireItemType.group) {\n return item.repeats ? (\n <QuestionnaireRepeatedGroup\n key={item.linkId}\n item={item}\n response={response.item?.filter((i) => i.linkId === item.linkId) ?? []}\n checkForQuestionEnabled={checkForQuestionEnabled}\n onChange={onSetGroup}\n />\n ) : (\n <QuestionnaireGroup\n key={item.linkId}\n item={item}\n checkForQuestionEnabled={checkForQuestionEnabled}\n response={response.item?.find((i) => i.linkId === item.linkId) ?? { linkId: item.linkId }}\n onChange={onSetGroup}\n />\n );\n }\n\n return (\n <QuestionnaireRepeatableItem\n key={item.linkId}\n item={item}\n response={response.item?.find((i) => i.linkId === item.linkId)}\n onChange={onSetGroup}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n );\n })}\n </Stack>\n </div>\n );\n}\n", "import { ActionIcon, Button, Divider, Group, NativeSelect, Stack, Text, TextInput } from '@mantine/core';\nimport { formatRange, getCodeBySystem } from '@medplum/core';\nimport { CodeableConcept, ObservationDefinition, ObservationDefinitionQualifiedInterval } from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCirclePlus } from '@tabler/icons-react';\nimport { MouseEvent, useEffect, useState } from 'react';\nimport { Container } from '../Container/Container';\nimport { Form } from '../Form/Form';\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: {} as IntervalGroup['filters'], intervals: [] });\n setGroupId((id) => id + 1);\n }}\n >\n <IconCirclePlus />\n </ActionIcon>\n\n <Group justify=\"flex-end\">\n <Button type=\"submit\">Save</Button>\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\n if (!intervalGroup.filters.age) {\n intervalGroup.filters.age = {};\n }\n for (const key of ['low', 'high']) {\n if (!intervalGroup.filters.age[key]?.unit) {\n intervalGroup.filters.age[key] = {\n ...intervalGroup.filters.age[key],\n unit: 'years',\n system: 'http://unitsofmeasure.org',\n };\n }\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={intervalGroup.filters['age']}\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 = parseInt(interval.id?.substring(3) || '', 10);\n return !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]])) as Record<string, any>,\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", "import { Button, Grid, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport { Bundle, BundleEntry, Reference, RequestGroup, Resource, Task } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconCheckbox, IconSquare } from '@tabler/icons-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 \n <ResourceName value={task?.meta?.author as Reference} />\n on \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", "import { Bundle, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceBadge } from '../ResourceBadge/ResourceBadge';\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<Bundle | undefined>(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 <ResourceBadge value={row.meta.author} link={true} />\n </td>\n <td className={classes.dateTime} rowSpan={row.span}>\n <MedplumLink to={getVersionUrl(resource, row.meta.versionId as string)}>\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", "import { stringify } from '@medplum/core';\nimport { 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", "/*\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 */\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 = (size / 2) | 0;\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] as PathNode;\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: 100px;\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}\n\n.normalRow {\n border-top: 0;\n}\n\n.author {\n line-height: 10px;\n}\n\n.dateTime {\n border-right: 0.1px solid var(--mantine-color-gray-3);\n line-height: 20px;\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-sm);\n padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n}\n\n.pre {\n margin: 0;\n}\n", "import { 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", "import { stringify } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\nimport { Delta, 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) as string[];\n const revised = stringify(revisedResource, true).match(/[^\\r\\n]+/g) as string[];\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", "\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}", "import { 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 { 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 { FormEvent, 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", "import { Table } from '@mantine/core';\nimport { formatDateTime, normalizeErrorString } from '@medplum/core';\nimport { Bundle, BundleEntry, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\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<Bundle | undefined>(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>Date</Table.Th>\n <Table.Th>Version</Table.Th>\n </Table.Tr>\n </Table.Thead>\n <Table.Tbody>\n {value.entry?.map((entry, index) => <HistoryRow key={'entry-' + index} entry={entry} />)}\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>{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={3}>{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", "import { Button, Stack, Text } from '@mantine/core';\nimport { getReferenceString, isReference } from '@medplum/core';\nimport { Questionnaire, QuestionnaireResponse, Reference, Schedule, Slot } from '@medplum/fhirtypes';\nimport { useResource, useSearchResources } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { CalendarInput } from '../CalendarInput/CalendarInput';\nimport { getStartMonth } from '../CalendarInput/CalendarInput.utils';\nimport { QuestionnaireForm } from '../QuestionnaireForm/QuestionnaireForm';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport classes from './Scheduler.module.css';\n\nexport interface SchedulerProps {\n readonly schedule: Schedule | Reference<Schedule>;\n readonly questionnaire: Questionnaire | Reference<Questionnaire>;\n}\n\nexport function Scheduler(props: SchedulerProps): JSX.Element | null {\n const schedule = useResource(props.schedule);\n const questionnaire = useResource(props.questionnaire);\n\n const [month, setMonth] = useState<Date>(getStartMonth());\n const [date, setDate] = useState<Date>();\n const [slot, setSlot] = useState<Slot>();\n const [response, setResponse] = useState<QuestionnaireResponse>();\n\n const [slots] = useSearchResources(\n 'Slot',\n new URLSearchParams([\n ['_count', (30 * 24).toString()],\n [\n 'schedule',\n isReference(props.schedule)\n ? (props.schedule.reference as string)\n : getReferenceString(props.schedule as Schedule),\n ],\n ['start', 'gt' + getStart(month)],\n ['start', 'lt' + getEnd(month)],\n ])\n );\n\n if (!schedule || !slots || !questionnaire) {\n return null;\n }\n\n const actor = schedule.actor?.[0];\n\n return (\n <div className={classes.container} data-testid=\"scheduler\">\n <div className={classes.info}>\n {actor && <ResourceAvatar value={actor} size=\"xl\" />}\n {actor && (\n <Text size=\"xl\" fw={500}>\n <ResourceName value={actor} />\n </Text>\n )}\n <p>1 hour</p>\n {date && <p>{date.toLocaleDateString()}</p>}\n {slot && <p>{formatTime(new Date(slot.start as string))}</p>}\n </div>\n <div className={classes.selection}>\n {!date && (\n <div>\n <h3>Select date</h3>\n <CalendarInput slots={slots} onChangeMonth={setMonth} onClick={setDate} />\n </div>\n )}\n {date && !slot && (\n <div>\n <h3>Select time</h3>\n <Stack>\n {slots.map((s) => {\n const slotStart = new Date(s.start as string);\n return (\n slotStart.getTime() > date.getTime() &&\n slotStart.getTime() < date.getTime() + 24 * 3600 * 1000 && (\n <div key={s.id}>\n <Button variant=\"outline\" style={{ width: 150 }} onClick={() => setSlot(s)}>\n {formatTime(slotStart)}\n </Button>\n </div>\n )\n );\n })}\n </Stack>\n </div>\n )}\n {date && slot && !response && (\n <QuestionnaireForm questionnaire={questionnaire} submitButtonText=\"Next\" onSubmit={setResponse} />\n )}\n {date && slot && response && (\n <div>\n <h3>You're all set!</h3>\n <p>Check your email for a calendar invite.</p>\n </div>\n )}\n </div>\n </div>\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", "\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}", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Group, Patient, Reference, ResourceType, ServiceRequest } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { Anchor, AnchorProps } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { ensureTrailingSlash, normalizeErrorString } from '@medplum/core';\nimport { ClientApplication, Encounter, Patient, Reference, SmartAppLaunch } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { 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 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\n function launchApp(): void {\n medplum\n .createResource<SmartAppLaunch>({\n resourceType: 'SmartAppLaunch',\n patient,\n encounter,\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 as string);\n window.location.assign(url.toString());\n })\n .catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err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Q,YACR,QAAS,IAAC,gCAAgB,QAAQ,CAAC,EACnC,QAAS,SAAS,QAClB,UAAQ,gCAAgB,MAAM,EAC9B,KAAM,IAAI,KAAK,EAAE,YAAY,EAC7B,QAAS,CAAC,CAAE,cAAe,IAAK,CAAC,CACnC,GACA,YAAa,CAAC,SAA0B,SAA2B,WAAyB,CAC1F,aAAc,QACd,OAAQ,YACR,QAAS,IAAC,gCAAgB,QAAQ,CAAC,EACnC,QAAS,SAAS,QAClB,YAAU,gCAAgB,QAAQ,EAClC,OAAQ,IAAI,KAAK,EAAE,YAAY,EAC/B,OACF,GACC,GAAG,KACN,CAEJ,CC9CA,IAAAC,eAAoC,yBACpCC,sBAAiC,kCACjCD,eAA0D,yBAE1DE,qBAA2B,gCA+BvBC,sBAAA,6BArBG,SAAS,mBAAmB,MAAoD,CACrF,IAAM,WAAU,iCAAW,EACrB,CAAE,OAAQ,QAAS,UAAW,SAAU,GAAG,IAAK,EAAI,MAE1D,SAAS,WAAkB,CACzB,QACG,eAA+B,CAC9B,aAAc,iBACd,QACA,SACF,CAAC,EACA,KAAM,QAAW,CAChB,IAAM,IAAM,IAAI,IAAI,OAAO,SAAmB,EAC9C,IAAI,aAAa,IAAI,SAAO,oCAAoB,QAAQ,QAAQ,EAAE,SAAS,CAAC,CAAC,EAC7E,IAAI,aAAa,IAAI,SAAU,OAAO,EAAY,EAClD,OAAO,SAAS,OAAO,IAAI,SAAS,CAAC,CACvC,CAAC,EACA,MAAO,QAAQ,wCAAiB,CAAE,MAAO,MAAO,WAAS,qCAAqB,GAAG,EAAG,UAAW,EAAM,CAAC,CAAC,CAC5G,CAEA,SACE,2BAAC,uBAAO,QAAS,IAAM,UAAU,EAAI,GAAG,KACrC,SACH,CAEJ",
|
|
4
|
+
"sourcesContent": ["\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Pointer = exports.escapeToken = exports.unescapeToken = void 0;\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}\nexports.unescapeToken = unescapeToken;\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}\nexports.escapeToken = escapeToken;\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 return Pointer;\n}());\nexports.Pointer = Pointer;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.clone = exports.objectType = exports.hasOwnProperty = void 0;\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}\nexports.objectType = objectType;\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_1 = source.length;\n // setting the Array length during construction is faster than just `[]` or `new Array()`\n var arrayTarget = new Array(length_1);\n for (var i = 0; i < length_1; 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}\nexports.clone = clone;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.diffAny = exports.diffObjects = exports.diffArrays = exports.intersection = exports.subtract = exports.isDestructive = void 0;\nvar util_1 = require(\"./util\");\nfunction isDestructive(_a) {\n var op = _a.op;\n return op === 'remove' || op === 'replace' || op === 'copy' || op === 'move';\n}\nexports.isDestructive = isDestructive;\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 // initialize empty object; we only care about the keys, the values can be anything\n var obj = {};\n // build up obj with all the properties of minuend\n for (var add_key in minuend) {\n if (util_1.hasOwnProperty.call(minuend, add_key) && minuend[add_key] !== undefined) {\n obj[add_key] = 1;\n }\n }\n // now delete all the properties of subtrahend from obj\n // (deleting a missing key has no effect)\n for (var del_key in subtrahend) {\n if (util_1.hasOwnProperty.call(subtrahend, del_key) && subtrahend[del_key] !== undefined) {\n delete obj[del_key];\n }\n }\n // finally, extract whatever keys remain in obj\n return Object.keys(obj);\n}\nexports.subtract = subtract;\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}\nexports.intersection = intersection;\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 memo = {\n '0,0': { operations: [], cost: 0 },\n };\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 = \"\".concat(i, \",\").concat(j);\n var memoized = memo[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[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}\nexports.diffArrays = diffArrays;\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 intersection([input, output]).forEach(function (key) {\n operations.push.apply(operations, diff(input[key], output[key], ptr.add(key)));\n });\n return operations;\n}\nexports.diffObjects = diffObjects;\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}\nexports.diffAny = diffAny;\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.apply = exports.InvalidOperationError = exports.test = exports.copy = exports.move = exports.replace = exports.remove = exports.add = exports.TestError = exports.MissingError = void 0;\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) {\n var endpoint = pointer_1.Pointer.fromJSON(operation.path).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 _add(endpoint.parent, endpoint.key, (0, util_1.clone)(operation.value));\n return null;\n}\nexports.add = add;\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) {\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}\nexports.remove = remove;\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) {\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}\nexports.replace = replace;\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) {\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}\nexports.move = move;\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) {\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}\nexports.copy = copy;\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) {\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}\nexports.test = test;\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) {\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);\n case 'remove': return remove(object, operation);\n case 'replace': return replace(object, operation);\n case 'move': return move(object, operation);\n case 'copy': return copy(object, operation);\n case 'test': return test(object, operation);\n }\n return new InvalidOperationError(operation);\n}\nexports.apply = apply;\n", "\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.createTests = exports.createPatch = exports.applyPatch = exports.Pointer = void 0;\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@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) {\n return patch.map(function (operation) { return (0, patch_1.apply)(object, operation); });\n}\nexports.applyPatch = applyPatch;\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}\nexports.createPatch = createPatch;\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}\nexports.createTests = createTests;\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 './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/RegisterForm';\nexport * from './auth/SignInForm';\nexport * from './BackboneElementDisplay/BackboneElementDisplay';\nexport * from './BackboneElementInput/BackboneElementInput';\nexport * from './CalendarInput/CalendarInput';\nexport * from './chat/BaseChat/BaseChat';\nexport * from './chat/ChatModal/ChatModal';\nexport * from './chat/ThreadChat/ThreadChat';\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 './FormSection/FormSection';\nexport * from './HumanNameDisplay/HumanNameDisplay';\nexport * from './HumanNameInput/HumanNameInput';\nexport * from './IdentifierDisplay/IdentifierDisplay';\nexport * from './IdentifierInput/IdentifierInput';\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 './PatientSummary/PatientSummary';\nexport * from './PatientTimeline/PatientTimeline';\nexport * from './PlanDefinitionBuilder/PlanDefinitionBuilder';\nexport * from './QuantityDisplay/QuantityDisplay';\nexport * from './QuantityInput/QuantityInput';\nexport * from './QuestionnaireBuilder/QuestionnaireBuilder';\nexport * from './QuestionnaireForm/QuestionnaireForm';\nexport * from './QuestionnaireForm/QuestionnaireForm.context';\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 './ResourceForm/ResourceForm';\nexport * from './ResourceForm/ResourceForm.utils';\nexport * from './ResourceHistoryTable/ResourceHistoryTable';\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 './SearchControl/SearchControl';\nexport * from './SearchControl/SearchControlField';\nexport * from './SearchControl/SearchUtils';\nexport * from './SearchFieldEditor/SearchFieldEditor';\nexport * from './SearchFilterEditor/SearchFilterEditor';\nexport * from './ServiceRequestTimeline/ServiceRequestTimeline';\nexport * from './SmartAppLaunchLink/SmartAppLaunchLink';\nexport * from './StatusBadge/StatusBadge';\nexport * from './Timeline/Timeline';\nexport * from './TimingInput/TimingInput';\nexport * from './utils/date';\nexport * from './utils/dom';\nexport * from './utils/outcomes';\nexport * from './utils/questionnaire';\nexport * from './utils/recaptcha';\nexport * from './utils/script';\nexport * from './ValueSetAutocomplete/ValueSetAutocomplete';\n", "import { formatAddress } from '@medplum/core';\nimport { Address } from '@medplum/fhirtypes';\n\nexport interface AddressDisplayProps {\n readonly value?: Address;\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)}</>;\n}\n", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { Address } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 };\n}\n\nexport type AddressInputProps = ComplexTypeInputProps<Address>;\n\nexport function AddressInput(props: AddressInputProps): JSX.Element {\n const [value, setValue] = useState<Address>(props.defaultValue || {});\n\n const valueRef = useRef<Address>();\n valueRef.current = value;\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: Address): void {\n setValue(newValue);\n if (props.onChange) {\n props.onChange(newValue);\n }\n }\n\n function setUse(use: 'home' | 'work' | 'temp' | 'old' | 'billing'): void {\n setValueWrapper({ ...valueRef.current, use });\n }\n\n function setType(type: 'postal' | 'physical' | 'both'): void {\n setValueWrapper({ ...valueRef.current, type });\n }\n\n function setLine1(line1: string): void {\n setValueWrapper(setLine(valueRef.current || {}, 0, line1));\n }\n\n function setLine2(line2: string): void {\n setValueWrapper(setLine(valueRef.current || {}, 1, line2));\n }\n\n function setCity(city: string): void {\n setValueWrapper({ ...valueRef.current, city });\n }\n\n function setState(state: string): void {\n setValueWrapper({ ...valueRef.current, state });\n }\n\n function setPostalCode(postalCode: string): void {\n setValueWrapper({ ...valueRef.current, 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", "import { ExtendedInternalSchemaElement, ElementsContextType, 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", "export 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", "import { TextInput } from '@mantine/core';\nimport { createReference } from '@medplum/core';\nimport { Annotation } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { 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<Annotation>(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", "import { AppShell as MantineAppShell } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { useMedplum, useMedplumProfile } from '@medplum/react-hooks';\nimport { ReactNode, Suspense, useEffect, useState } from 'react';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { Loading } from '../Loading/Loading';\nimport classes from './AppShell.module.css';\nimport { Header } from './Header';\nimport { Navbar, NavbarMenu } from './Navbar';\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}\n\nexport function AppShell(props: AppShellProps): JSX.Element {\n const [navbarOpen, setNavbarOpen] = useState(localStorage['navbarOpen'] === 'true');\n const medplum = useMedplum();\n const profile = useMedplumProfile();\n\n useEffect(() => {\n function eventListener(): void {\n showNotification({ id: 'offline', color: 'red', message: 'No connection to server', autoClose: false });\n }\n medplum.addEventListener('offline', eventListener);\n return () => medplum.removeEventListener('offline', eventListener);\n }, [medplum]);\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 return (\n <MantineAppShell\n header={{ height: 60 }}\n navbar={{\n width: 250,\n breakpoint: 'sm',\n collapsed: {\n desktop: !profile || !navbarOpen,\n mobile: !profile || !navbarOpen,\n },\n }}\n padding={0}\n >\n {profile && (\n <Header\n pathname={props.pathname}\n searchParams={props.searchParams}\n headerSearchDisabled={props.headerSearchDisabled}\n logo={props.logo}\n version={props.version}\n navbarToggle={toggleNavbar}\n notifications={props.notifications}\n />\n )}\n {profile && navbarOpen ? (\n <Navbar\n pathname={props.pathname}\n searchParams={props.searchParams}\n menus={props.menus}\n closeNavbar={closeNavbar}\n displayAddBookmark={props.displayAddBookmark}\n resourceTypeSearchDisabled={props.resourceTypeSearchDisabled}\n />\n ) : undefined}\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", "import { Alert } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport { Component, ErrorInfo, ReactNode } 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: window.location.toString() };\n }\n\n static getDerivedStateFromError(error: Error): ErrorBoundaryState {\n return { error, lastLocation: window.location.toString() };\n }\n\n componentDidUpdate(_prevProps: ErrorBoundaryProps, _prevState: ErrorBoundaryState): void {\n if (window.location.toString() !== this.state.lastLocation) {\n this.setState({\n lastLocation: window.location.toString(),\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 !== window.location.toString()) {\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 createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'adjustments-horizontal', 'IconAdjustmentsHorizontal', [[\"path\",{\"d\":\"M14 6m-2 0a2 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\":\"M8 12m-2 0a2 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\":\"M17 18m-2 0a2 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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'alert-circle', 'IconAlertCircle', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-down', 'IconArrowDown', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-right', 'IconArrowRight', [[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M13 18l6 -6\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M13 6l6 6\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'arrow-up', 'IconArrowUp', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bleach-off', 'IconBleachOff', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bleach', 'IconBleach', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'box-multiple', 'IconBoxMultiple', [[\"path\",{\"d\":\"M7 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v10a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'brackets-contain', 'IconBracketsContain', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bucket-off', 'IconBucketOff', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'bucket', 'IconBucket', [[\"path\",{\"d\":\"M12 7m-8 0a8 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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'calendar', 'IconCalendar', [[\"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-12z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'check', 'IconCheck', [[\"path\",{\"d\":\"M5 12l5 5l10 -10\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'checkbox', 'IconCheckbox', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'chevron-down', 'IconChevronDown', [[\"path\",{\"d\":\"M6 9l6 6l6 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'chevron-up', 'IconChevronUp', [[\"path\",{\"d\":\"M6 15l6 -6l6 6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'circle-minus', 'IconCircleMinus', [[\"path\",{\"d\":\"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M9 12l6 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'circle-plus', 'IconCirclePlus', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'cloud-upload', 'IconCloudUpload', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'columns', 'IconColumns', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'copy', 'IconCopy', [[\"path\",{\"d\":\"M7 7m0 2.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.667z\",\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'currency-dollar', 'IconCurrencyDollar', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'dots', 'IconDots', [[\"path\",{\"d\":\"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'edit', 'IconEdit', [[\"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.415z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M16 5l3 3\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'equal-not', 'IconEqualNot', [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M5 19l14 -14\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'equal', 'IconEqual', [[\"path\",{\"d\":\"M5 10h14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 14h14\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'file-alert', 'IconFileAlert', [[\"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 2z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 17l.01 0\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M12 11l0 3\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'file-plus', 'IconFilePlus', [[\"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 2z\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M12 11l0 6\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M9 14l6 0\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'filter', 'IconFilter', [[\"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.227z\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'gender-female', 'IconGenderFemale', [[\"path\",{\"d\":\"M12 9m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M12 14v7\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M9 18h6\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'gender-male', 'IconGenderMale', [[\"path\",{\"d\":\"M10 14m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M19 5l-5.4 5.4\",\"key\":\"svg-1\"}],[\"path\",{\"d\":\"M19 5h-5\",\"key\":\"svg-2\"}],[\"path\",{\"d\":\"M19 5v5\",\"key\":\"svg-3\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'logout', 'IconLogout', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'math-greater', 'IconMathGreater', [[\"path\",{\"d\":\"M5 18l14 -6l-14 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'math-lower', 'IconMathLower', [[\"path\",{\"d\":\"M19 18l-14 -6l14 -6\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'message', 'IconMessage', [[\"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 -3h12z\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'plus', 'IconPlus', [[\"path\",{\"d\":\"M12 5l0 14\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M5 12l14 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'refresh', 'IconRefresh', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'search', 'IconSearch', [[\"path\",{\"d\":\"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M21 21l-6 -6\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'settings', 'IconSettings', [[\"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.065z\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M9 12a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\",\"key\":\"svg-1\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'sort-ascending', 'IconSortAscending', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'sort-descending', 'IconSortDescending', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'square', 'IconSquare', [[\"path\",{\"d\":\"M3 3m0 2a2 2 0 0 1 2 -2h14a2 2 0 0 1 2 2v14a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2z\",\"key\":\"svg-0\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'stethoscope', 'IconStethoscope', [[\"path\",{\"d\":\"M6 4h-1a2 2 0 0 0 -2 2v3.5h0a5.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\":\"M20 10m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0\",\"key\":\"svg-4\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'switch-horizontal', 'IconSwitchHorizontal', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'table-export', 'IconTableExport', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'trash', 'IconTrash', [[\"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\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'user-square', 'IconUserSquare', [[\"path\",{\"d\":\"M9 10a3 3 0 1 0 6 0a3 3 0 0 0 -6 0\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M6 21v-1a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v1\",\"key\":\"svg-1\"}],[\"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-14z\",\"key\":\"svg-2\"}]]);", "import createReactComponent from '../createReactComponent';\nexport default createReactComponent('outline', 'x', 'IconX', [[\"path\",{\"d\":\"M18 6l-12 12\",\"key\":\"svg-0\"}],[\"path\",{\"d\":\"M6 6l12 12\",\"key\":\"svg-1\"}]]);", "import { Center, Loader } from '@mantine/core';\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 padding-bottom: var(--mantine-spacing-lg);\n overflow-x: auto;\n}\n", "import { Group, AppShell as MantineAppShell, Menu, Text, UnstyledButton } from '@mantine/core';\nimport { formatHumanName } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { ReactNode, useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport classes from './Header.module.css';\nimport { HeaderDropdown } from './HeaderDropdown';\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 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 className={classes.logoButton} onClick={props.navbarToggle}>\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=\"xl\"\n position=\"bottom-end\"\n transitionProps={{ transition: 'pop-top-right' }}\n opened={userMenuOpened}\n onClose={() => setUserMenuOpened(false)}\n >\n <Menu.Target>\n <UnstyledButton\n className={cx(classes.user, { [classes.userActive]: userMenuOpened })}\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] as HumanName)}\n </Text>\n <IconChevronDown size={12} stroke={1.5} />\n </Group>\n </UnstyledButton>\n </Menu.Target>\n <Menu.Dropdown>\n <HeaderDropdown version={props.version} />\n </Menu.Dropdown>\n </Menu>\n </Group>\n </Group>\n </MantineAppShell.Header>\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;", "import { Avatar, AvatarProps } from '@mantine/core';\nimport { getDisplayString, getImageSrc } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl, useResource } from '@medplum/react-hooks';\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", "import { Anchor, TextProps } from '@mantine/core';\nimport { isReference, isResource } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport { MouseEvent, MouseEventHandler, ReactNode } from 'react';\nimport { killEvent } from '../utils/dom';\n\nexport interface MedplumLinkProps extends TextProps {\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 onClick={(e: MouseEvent) => {\n killEvent(e);\n if (onClick) {\n onClick(e);\n } else if (to) {\n navigate(href);\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", "import { 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 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", "export function getInitials(input: string): string {\n const words = input.split(' ').filter(Boolean);\n if (words.length > 1) {\n return words[0][0] + words[words.length - 1][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\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\n.userActive {\n background-color: var(--mantine-primary-color-light-hover);\n}\n", "import {\n Avatar,\n Group,\n MantineColorScheme,\n Menu,\n SegmentedControl,\n Stack,\n Text,\n useMantineColorScheme,\n} from '@mantine/core';\nimport { ProfileResource, getReferenceString } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useMedplumContext } from '@medplum/react-hooks';\nimport { IconLogout, IconSettings, IconSwitchHorizontal } from '@tabler/icons-react';\nimport { HumanNameDisplay } from '../HumanNameDisplay/HumanNameDisplay';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\n\nexport interface HeaderDropdownProps {\n readonly version?: string;\n}\n\nexport function HeaderDropdown(props: HeaderDropdownProps): JSX.Element {\n const context = useMedplumContext();\n const { medplum, profile, navigate } = context;\n const logins = medplum.getLogins();\n const { colorScheme, setColorScheme } = useMantineColorScheme();\n\n return (\n <>\n <Stack align=\"center\" p=\"xl\">\n <ResourceAvatar size=\"xl\" radius={100} value={context.profile} />\n <HumanNameDisplay value={context.profile?.name?.[0] as HumanName} />\n <Text c=\"dimmed\" size=\"xs\">\n {medplum.getActiveLogin()?.project.display}\n </Text>\n </Stack>\n {logins.length > 1 && <Menu.Divider />}\n {logins.map(\n (login) =>\n login.profile.reference !== getReferenceString(context.profile as ProfileResource) && (\n <Menu.Item\n key={login.profile.reference}\n onClick={() => {\n medplum\n .setActiveLogin(login)\n .then(() => window.location.reload())\n .catch(console.log);\n }}\n >\n <Group>\n <Avatar radius=\"xl\" />\n <div style={{ flex: 1 }}>\n <Text size=\"sm\" fw={500}>\n {login.profile.display}\n </Text>\n <Text c=\"dimmed\" size=\"xs\">\n {login.project.display}\n </Text>\n </div>\n </Group>\n </Menu.Item>\n )\n )}\n <Menu.Divider />\n <Group justify=\"center\">\n <SegmentedControl\n size=\"xs\"\n value={colorScheme}\n onChange={(newValue) => setColorScheme(newValue as MantineColorScheme)}\n data={[\n { label: 'Light', value: 'light' },\n { label: 'Dark', value: 'dark' },\n { label: 'Auto', value: 'auto' },\n ]}\n />\n </Group>\n <Menu.Divider />\n <Menu.Item leftSection={<IconSwitchHorizontal size={14} stroke={1.5} />} onClick={() => navigate('/signin')}>\n Add another account\n </Menu.Item>\n <Menu.Item\n leftSection={<IconSettings size={14} stroke={1.5} />}\n onClick={() => navigate(`/${getReferenceString(profile as ProfileResource)}`)}\n >\n Account settings\n </Menu.Item>\n <Menu.Item\n leftSection={<IconLogout size={14} stroke={1.5} />}\n onClick={async () => {\n await medplum.signOut();\n navigate('/signin');\n }}\n >\n Sign out\n </Menu.Item>\n <Text size=\"xs\" c=\"dimmed\" ta=\"center\">\n {props.version}\n </Text>\n </>\n );\n}\n", "import { formatHumanName, HumanNameFormatOptions } from '@medplum/core';\nimport { HumanName } from '@medplum/fhirtypes';\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", "import { Group, Text } from '@mantine/core';\nimport { formatHumanName, getDisplayString, getReferenceString, isUUID } from '@medplum/core';\nimport { Patient, ServiceRequest } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconSearch } from '@tabler/icons-react';\nimport { forwardRef, useCallback } from 'react';\nimport { AsyncAutocomplete, AsyncAutocompleteOption } 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 }`.replace(/\\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 }`.replace(/\\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", "import {\n Combobox,\n ComboboxItem,\n ComboboxProps,\n Group,\n Loader,\n Pill,\n PillsInput,\n ScrollAreaAutosize,\n useCombobox,\n} from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconCheck } from '@tabler/icons-react';\nimport { KeyboardEvent, ReactNode, SyntheticEvent, useCallback, useEffect, 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>\n extends Omit<ComboboxProps, 'data' | 'defaultValue' | 'loadOptions' | 'onChange' | 'onCreate' | 'searchable'> {\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<AsyncAutocompleteOption<T>[]>(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<string>();\n searchRef.current = search;\n\n const lastLoadOptionsRef = useRef<AsyncAutocompleteProps<T>['loadOptions']>();\n const lastValueRef = useRef<string>();\n\n const timerRef = useRef<number>();\n timerRef.current = timer;\n\n const abortControllerRef = useRef<AbortController>();\n abortControllerRef.current = abortController;\n\n const autoSubmitRef = useRef<boolean>();\n autoSubmitRef.current = autoSubmit;\n\n const optionsRef = useRef<AsyncAutocompleteOption<T>[]>();\n optionsRef.current = options;\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 item: AsyncAutocompleteOption<T>;\n disabled?: boolean;\n 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", "export 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", "import { Button, AppShell as MantineAppShell, ScrollArea, Space, Text } from '@mantine/core';\nimport { useMedplumNavigate } from '@medplum/react-hooks';\nimport { IconPlus } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { Fragment, MouseEventHandler, ReactNode, SyntheticEvent, useState } from 'react';\nimport { BookmarkDialog } from '../BookmarkDialog/BookmarkDialog';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport classes from './Navbar.module.css';\n\nexport interface NavbarLink {\n readonly icon?: JSX.Element;\n readonly label?: string;\n readonly href: string;\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 menus?: NavbarMenu[];\n readonly closeNavbar: () => void;\n readonly displayAddBookmark?: boolean;\n readonly resourceTypeSearchDisabled?: boolean;\n}\n\nexport function Navbar(props: NavbarProps): JSX.Element {\n const navigate = useMedplumNavigate();\n const activeLink = getActiveLink(props.pathname, props.searchParams, props.menus);\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 return (\n <>\n <MantineAppShell.Navbar>\n <ScrollArea p=\"xs\">\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 <MantineAppShell.Section grow>\n {props.menus?.map((menu) => (\n <Fragment key={`menu-${menu.title}`}>\n <Text className={classes.menuTitle}>{menu.title}</Text>\n {menu.links?.map((link) => (\n <NavbarLink\n key={link.href}\n to={link.href}\n active={link.href === activeLink?.href}\n onClick={(e) => onLinkClick(e, link.href)}\n >\n <NavLinkIcon to={link.href} icon={link.icon} />\n <span>{link.label}</span>\n </NavbarLink>\n ))}\n </Fragment>\n ))}\n {props.displayAddBookmark && (\n <Button\n variant=\"subtle\"\n size=\"xs\"\n mt=\"xl\"\n leftSection={<IconPlus size=\"0.75rem\" />}\n onClick={() => setBookmarkDialogVisible(true)}\n >\n Add Bookmark\n </Button>\n )}\n </MantineAppShell.Section>\n </ScrollArea>\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 NavbarLinkProps {\n readonly to: string;\n readonly active: boolean;\n readonly onClick: MouseEventHandler;\n readonly children: ReactNode;\n}\n\nfunction NavbarLink(props: NavbarLinkProps): JSX.Element {\n return (\n <MedplumLink\n onClick={props.onClick}\n to={props.to}\n className={cx(classes.link, { [classes.linkActive]: props.active })}\n >\n {props.children}\n </MedplumLink>\n );\n}\n\ninterface NavLinkIconProps {\n readonly to: string;\n readonly icon?: JSX.Element;\n}\n\nfunction NavLinkIcon(props: NavLinkIconProps): JSX.Element {\n if (props.icon) {\n return props.icon;\n }\n return <Space w={30} />;\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", "import { Button, Group, Modal, NativeSelect, Stack, TextInput } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { deepClone, normalizeErrorString } from '@medplum/core';\nimport { UserConfiguration } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Form } from '../Form/Form';\n\ninterface BookmarkDialogProps {\n readonly pathname: string;\n readonly searchParams: URLSearchParams;\n readonly visible: boolean;\n readonly onOk: () => void;\n readonly onCancel: () => void;\n readonly defaultValue?: string;\n}\nexport function BookmarkDialog(props: BookmarkDialogProps): JSX.Element | null {\n const medplum = useMedplum();\n const config = medplum.getUserConfiguration() as 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) as UserConfiguration;\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 label=\"Bookmark Name\" type=\"text\" name=\"bookmarkname\" placeholder=\"Bookmark Name\" withAsterisk />\n <Group justify=\"flex-end\">\n <Button mt=\"sm\" type=\"submit\">\n OK\n </Button>\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", "/**\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", "import { CSSProperties, ReactNode, SyntheticEvent } from 'react';\nimport { parseForm } from './FormUtils';\n\nexport interface FormProps {\n readonly onSubmit?: (formData: Record<string, string>) => void;\n readonly style?: CSSProperties;\n readonly children?: ReactNode;\n readonly testid?: string;\n}\n\nexport function Form(props: FormProps): JSX.Element {\n return (\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 props.onSubmit(formData);\n }\n }}\n >\n {props.children}\n </form>\n );\n}\n", "import { ResourceType } from '@medplum/fhirtypes';\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<string | undefined>(props.defaultValue);\n const onChange = props.onChange;\n\n const setResourceTypeWrapper = useCallback(\n (newResourceType: string | undefined) => {\n setResourceType(newResourceType);\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", "import { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } 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<string | undefined>(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", "import { Group, Text } from '@mantine/core';\nimport { ValueSetExpandParams } from '@medplum/core';\nimport { ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { forwardRef, useCallback } from 'react';\nimport {\n AsyncAutocomplete,\n AsyncAutocompleteOption,\n AsyncAutocompleteProps,\n} from '../AsyncAutocomplete/AsyncAutocomplete';\nimport { IconCheck } from '@tabler/icons-react';\n\nexport interface ValueSetAutocompleteProps\n extends Omit<AsyncAutocompleteProps<ValueSetExpansionContains>, 'loadOptions' | 'toKey' | 'toOption'> {\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 ...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", ".menuTitle {\n margin: 20px 0 4px 6px;\n font-size: 9px;\n font-weight: normal;\n text-transform: uppercase;\n letter-spacing: 2px;\n}\n\n.link {\n display: flex;\n align-items: center;\n text-decoration: none;\n font-size: var(--mantine-font-size-sm);\n color: light-dark(var(--mantine-color-gray-7), var(--mantine-color-dark-1));\n padding: 8px 12px;\n border-radius: var(--mantine-radius-sm);\n font-weight: 500;\n\n &:hover {\n background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));\n color: light-dark(var(--mantine-color-black), var(--mantine-color-white));\n text-decoration: none;\n\n & svg {\n color: light-dark(var(--mantine-color-black), var(--mantine-color-white));\n }\n }\n\n & svg {\n color: light-dark(var(--mantine-color-gray-6), var(--mantine-color-dark-2));\n margin-right: var(--mantine-spacing-sm);\n stroke-width: 1.5;\n width: 18px;\n height: 18px;\n }\n}\n\n.linkActive {\n color: var(--mantine-primary-color-filled);\n background-color: light-dark(var(--mantine-primary-color-light), var(--mantine-primary-color-dark));\n\n &:hover {\n color: var(--mantine-primary-color-filled-hover);\n background-color: light-dark(var(--mantine-primary-color-light-hover), var(--mantine-primary-color-dark-hover));\n\n & svg {\n color: var(--mantine-color-blue-light-color);\n }\n }\n\n & svg {\n color: var(--mantine-color-blue-light-color);\n }\n}\n", "import { Anchor } from '@mantine/core';\nimport { ContentType } from '@medplum/core';\nimport { Attachment } from '@medplum/fhirtypes';\nimport { useCachedBinaryUrl } from '@medplum/react-hooks';\nimport { CcdaDisplay } from '../CcdaDisplay/CcdaDisplay';\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 <img 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 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", "import { useEffect, useRef, useState } from 'react';\nimport { sendCommand } from '../utils/dom';\n\nconst CCDA_VIEWER_URL = 'https://ccda.medplum.com';\n\nexport interface CcdaDisplayProps {\n readonly url?: string;\n readonly maxWidth?: number;\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\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 if (!url) {\n return null;\n }\n\n return (\n <div data-testid=\"ccda-iframe\" style={{ maxWidth: props.maxWidth, 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}\n", ".root {\n display: grid;\n grid-template-columns: 30% 70%;\n margin: 0;\n\n & > dt,\n & > dd {\n padding: var(--mantine-spacing-sm);\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 padding-top: 0;\n }\n\n & > dt:last-of-type,\n & > dd:last-of-type {\n padding-bottom: 0;\n }\n}\n\n.compact {\n grid-template-columns: auto 1fr;\n\n & > dt,\n & > dd {\n padding: 0 0 var(--mantine-spacing-xs);\n border-top: 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: 0;\n }\n}\n", "import cx from 'clsx';\nimport { 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", "import { Attachment } from '@medplum/fhirtypes';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { InternalSchemaElement, getPathDisplayName, isPopulated } from '@medplum/core';\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", "import { ActionIcon } from '@mantine/core';\nimport { Attachment } from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCloudUpload } from '@tabler/icons-react';\nimport { MouseEvent, useRef, 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<Attachment[]>(props.defaultValue ?? []);\n\n const valuesRef = useRef<Attachment[]>();\n valuesRef.current = values;\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([...(valuesRef.current as Attachment[]), 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", "import { normalizeOperationOutcome } from '@medplum/core';\nimport { Attachment, OperationOutcome, Reference } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ChangeEvent, MouseEvent, ReactNode, 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 {props.children({ onClick, disabled: props.disabled })}\n </>\n );\n}\n", "import { Button } from '@mantine/core';\nimport { Attachment, Reference } from '@medplum/fhirtypes';\nimport { MouseEvent, useState } from 'react';\nimport { AttachmentButton } from '../AttachmentButton/AttachmentButton';\nimport { AttachmentDisplay } from '../AttachmentDisplay/AttachmentDisplay';\nimport { killEvent } from '../utils/dom';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\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", "import { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useEffect, useState } from 'react';\nimport { Document } from '../Document/Document';\nimport { NewProjectForm } from './NewProjectForm';\nimport { NewUserForm } from './NewUserForm';\n\nexport interface RegisterFormProps {\n readonly type: 'patient' | 'project';\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>();\n const [outcome, setOutcome] = useState<OperationOutcome>();\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(console.log);\n } else if (response.login) {\n setLogin(response.login);\n }\n }\n\n return (\n <Document width={450}>\n {outcome && <pre>{JSON.stringify(outcome, null, 2)}</pre>}\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 {login && type === 'project' && <NewProjectForm login={login} handleAuthResponse={handleAuthResponse} />}\n </Document>\n );\n}\n", "import { ContainerProps, Container as MantineContainer } from '@mantine/core';\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", "import { Paper, PaperProps } from '@mantine/core';\nimport cx from 'clsx';\nimport { 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", "import { Container } from '../Container/Container';\nimport { Panel, PanelProps } 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", "import { Anchor, Button, Center, Group, Stack, Text, TextInput, Title } from '@mantine/core';\nimport { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\nimport { getErrorsForInput } 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 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 <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Create project</Title>\n </Center>\n <Stack gap=\"xl\">\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 <Text c=\"dimmed\" size=\"xs\">\n By clicking submit you agree to the Medplum{' '}\n <Anchor href=\"https://www.medplum.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://www.medplum.com/terms\">Terms of Service</Anchor>.\n </Text>\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\" wrap=\"nowrap\">\n <Button type=\"submit\">Create project</Button>\n </Group>\n </Form>\n );\n}\n", "export interface LogoProps {\n readonly size: number;\n readonly fill?: string;\n}\n\nexport function Logo(props: LogoProps): JSX.Element {\n return (\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 491 491\" style={{ width: props.size, height: props.size }}>\n <title>Medplum Logo</title>\n <path fill={props.fill ?? '#ad7136'} d=\"M282 67c6-16 16-29 29-40L289 0c-22 17-37 41-43 68l17 23 19-24z\" />\n <path\n fill={props.fill ?? '#946af9'}\n d=\"M311 63c-17 0-33 4-48 11-16-7-32-11-49-11-87 0-158 96-158 214s71 214 158 214c17 0 33-4 49-11 15 7 31 11 48 11 87 0 158-96 158-214S398 63 311 63z\"\n />\n <path\n fill={props.fill ?? '#7857c5'}\n d=\"M231 489l-17 2c-87 0-158-96-158-214S127 63 214 63l17 1c-39 12-70 102-70 213s31 201 70 212z\"\n />\n <path\n fill={props.fill ?? '#40bc26'}\n d=\"M207 220a176 176 0 01-177 43A176 176 0 01251 43l1 5c17 59 2 125-45 172z\"\n />\n <path fill={props.fill ?? '#33961e'} d=\"M252 48A421 421 0 0057 270l-27-7A176 176 0 01251 43l1 5z\" />\n </svg>\n );\n}\n", "import { 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", "import { Anchor, Button, Center, Checkbox, Divider, Group, PasswordInput, Stack, Text, TextInput } from '@mantine/core';\nimport { GoogleCredentialResponse, LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useEffect, useState } from 'react';\nimport { Form } from '../Form/Form';\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 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 <Center style={{ flexDirection: 'column' }}>{props.children}</Center>\n <OperationOutcomeAlert issues={issues} />\n {googleClientId && (\n <>\n <Group justify=\"center\" p=\"xl\" style={{ height: 70 }}>\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 </Group>\n <Divider label=\"or\" labelPosition=\"center\" my=\"lg\" />\n </>\n )}\n <Stack gap=\"xl\">\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 <Text c=\"dimmed\" size=\"xs\">\n By clicking submit you agree to the Medplum{' '}\n <Anchor href=\"https://www.medplum.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://www.medplum.com/terms\">Terms of Service</Anchor>.\n </Text>\n <Text c=\"dimmed\" size=\"xs\">\n This site is protected by reCAPTCHA and the Google{' '}\n <Anchor href=\"https://policies.google.com/privacy\">Privacy Policy</Anchor>\n {' and '}\n <Anchor href=\"https://policies.google.com/terms\">Terms of Service</Anchor> apply.\n </Text>\n </Stack>\n <Group justify=\"space-between\" mt=\"xl\" wrap=\"nowrap\">\n <Checkbox name=\"remember\" label=\"Remember me\" size=\"xs\" />\n <Button type=\"submit\">Create account</Button>\n </Group>\n </Form>\n );\n}\n", "import { GoogleCredentialResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\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 medplum = useMedplum();\n const { googleClientId, handleGoogleCredential } = props;\n const parentRef = useRef<HTMLDivElement>(null);\n const [scriptLoaded, setScriptLoaded] = useState<boolean>(typeof google !== 'undefined');\n const [initialized, setInitialized] = useState(false);\n const [buttonRendered, setButtonRendered] = useState(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 (!initialized) {\n google.accounts.id.initialize({\n client_id: googleClientId,\n callback: handleGoogleCredential,\n });\n setInitialized(true);\n }\n\n if (parentRef.current && !buttonRendered) {\n google.accounts.id.renderButton(parentRef.current, {});\n setButtonRendered(true);\n }\n }, [medplum, googleClientId, initialized, scriptLoaded, parentRef, buttonRendered, handleGoogleCredential]);\n\n if (!googleClientId) {\n return null;\n }\n\n return <div ref={parentRef} />;\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", "export function getGoogleClientId(clientId: string | undefined): string | undefined {\n if (clientId) {\n return clientId;\n }\n\n if (typeof window !== 'undefined') {\n const origin = window.location.protocol + '//' + window.location.host;\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", "import { Alert } from '@mantine/core';\nimport { operationOutcomeIssueToString } from '@medplum/core';\nimport { OperationOutcome, OperationOutcomeIssue } from '@medplum/fhirtypes';\nimport { IconAlertCircle } from '@tabler/icons-react';\n\nexport interface OperationOutcomeAlertProps {\n readonly outcome?: OperationOutcome;\n readonly issues?: OperationOutcomeIssue[];\n}\n\nexport function OperationOutcomeAlert(props: OperationOutcomeAlertProps): JSX.Element | null {\n const issues = props.outcome?.issue || props.issues;\n if (!issues || issues.length === 0) {\n return null;\n }\n return (\n <Alert icon={<IconAlertCircle size={16} />} color=\"red\">\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", "import { 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", "import { showNotification } from '@mantine/notifications';\nimport { BaseLoginRequest, LoginAuthenticationResponse, normalizeErrorString } from '@medplum/core';\nimport { ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, 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 [mfaRequired, setAuthenticatorRequired] = 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) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n }\n },\n [medplum, onCode, onSuccess]\n );\n\n const handleAuthResponse = useCallback(\n (response: LoginAuthenticationResponse): void => {\n setAuthenticatorRequired(!!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 as string);\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) => showNotification({ color: 'red', message: normalizeErrorString(err) }));\n }\n }, [medplum, loginCode, loginRequested, login, handleAuthResponse]);\n\n return (\n <Document width={450} px=\"sm\" py=\"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 (mfaRequired) {\n return (\n <MfaForm\n onSubmit={async (fields) => {\n const res = await medplum.post('auth/mfa/verify', {\n login: login,\n token: fields.token,\n });\n handleAuthResponse(res);\n }}\n />\n );\n } else if (memberships) {\n return <ChooseProfileForm login={login} memberships={memberships} handleAuthResponse={handleAuthResponse} />;\n } else if (props.projectId === 'new') {\n return <NewProjectForm login={login} 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", "import { Anchor, Button, Center, Checkbox, Divider, Group, PasswordInput, Stack, TextInput } from '@mantine/core';\nimport {\n BaseLoginRequest,\n GoogleCredentialResponse,\n GoogleLoginRequest,\n LoginAuthenticationResponse,\n normalizeOperationOutcome,\n} from '@medplum/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ReactNode, useCallback, useState } from 'react';\nimport { Form } from '../Form/Form';\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} {...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 });\n const url = new URL(authMethod.authorizeUrl);\n url.searchParams.set('state', state);\n window.location.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 <Center style={{ flexDirection: 'column' }}>{children}</Center>\n <OperationOutcomeAlert issues={issues} />\n {googleClientId && (\n <>\n <Group justify=\"center\" p=\"xl\" style={{ height: 70 }}>\n <GoogleButton googleClientId={googleClientId} handleGoogleCredential={handleGoogleCredential} />\n </Group>\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 placeholder=\"name@domain.com\"\n required={true}\n autoFocus={true}\n error={getErrorsForInput(outcome, 'email')}\n />\n )}\n <Group justify=\"space-between\" mt=\"xl\" gap={0} wrap=\"nowrap\">\n <div>\n {onRegister && (\n <Anchor component=\"button\" type=\"button\" color=\"dimmed\" onClick={onRegister} size=\"xs\">\n Register\n </Anchor>\n )}\n </div>\n {!disableEmailAuth && <Button type=\"submit\">Next</Button>}\n </Group>\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 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) => setOutcome(normalizeOperationOutcome(err)));\n },\n [medplum, baseLoginRequest, handleAuthResponse]\n );\n\n return (\n <Form onSubmit={handleSubmit}>\n <Center style={{ flexDirection: 'column' }}>{children}</Center>\n <OperationOutcomeAlert issues={issues} />\n <Stack gap=\"xl\">\n <PasswordInput\n name=\"password\"\n label=\"Password\"\n autoComplete=\"off\"\n required={true}\n autoFocus={true}\n error={getErrorsForInput(outcome, 'password')}\n />\n </Stack>\n <Group justify=\"space-between\" mt=\"xl\" gap={0} wrap=\"nowrap\">\n {onForgotPassword && (\n <Anchor component=\"button\" type=\"button\" c=\"dimmed\" onClick={onForgotPassword} size=\"xs\">\n Forgot password\n </Anchor>\n )}\n <Checkbox id=\"remember\" name=\"remember\" label=\"Remember me\" size=\"xs\" style={{ lineHeight: 1 }} />\n <Button type=\"submit\">Sign in</Button>\n </Group>\n </Form>\n );\n}\n", "import { Avatar, Combobox, Flex, Group, Stack, Text, TextInput, Title, useCombobox } from '@mantine/core';\nimport { LoginAuthenticationResponse, normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome, ProjectMembership } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { Logo } from '../Logo/Logo';\nimport { OperationOutcomeAlert } from '../OperationOutcomeAlert/OperationOutcomeAlert';\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 filterDisplay(membership.profile?.display) || filterDisplay(membership.project?.display);\n }\n\n function handleValueSelect(membershipId: string): void {\n medplum\n .post('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}>\n <SelectOption {...item} />\n </Combobox.Option>\n ));\n\n return (\n <Stack>\n <Flex gap=\"md\" mb=\"md\" justify=\"center\" align=\"center\" direction=\"column\" wrap=\"nowrap\">\n <Logo size={32} />\n <Title order={3}>Choose profile</Title>\n </Flex>\n <OperationOutcomeAlert outcome={outcome} />\n <Combobox store={combobox} onOptionSubmit={handleValueSelect}>\n <Combobox.EventsTarget>\n <TextInput\n placeholder=\"Search\"\n value={search}\n onChange={(event) => {\n setSearch(event.currentTarget.value);\n combobox.updateSelectedOptionIndex();\n }}\n />\n </Combobox.EventsTarget>\n\n <div>\n <Combobox.Options>\n {options.length > 0 ? options : <Combobox.Empty>Nothing found...</Combobox.Empty>}\n </Combobox.Options>\n </div>\n </Combobox>\n </Stack>\n );\n}\n\nfunction SelectOption(membership: ProjectMembership): JSX.Element {\n return (\n <Group>\n <Avatar radius=\"xl\" />\n <div>\n <Text fz=\"sm\" fw={500}>\n {membership.profile?.display}\n </Text>\n <Text fz=\"xs\" opacity={0.6}>\n {membership.project?.display}\n </Text>\n </div>\n </Group>\n );\n}\n", "import { Button, Center, Checkbox, Group, Stack, Title } from '@mantine/core';\nimport { LoginAuthenticationResponse } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Form } from '../Form/Form';\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('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 <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Choose scope</Title>\n </Center>\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 <>\n <Checkbox key={scopeName} id={scopeName} name={scopeName} label={scopeName} defaultChecked />\n {additionalScopes?.map((scope) => <Checkbox key={scope} id={scope} name={scope} label={scope} />)}\n </>\n );\n })}\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\">\n <Button type=\"submit\">Set scope</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Alert, Button, Center, Group, Stack, TextInput, Title } from '@mantine/core';\nimport { normalizeErrorString } from '@medplum/core';\nimport { IconAlertCircle } from '@tabler/icons-react';\nimport { useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { Logo } from '../Logo/Logo';\n\nexport type MfaFormFields = 'token';\n\nexport interface MfaFormProps {\n readonly onSubmit: (formData: Record<MfaFormFields, string>) => 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 <Stack>\n <Center style={{ flexDirection: 'column' }}>\n <Logo size={32} />\n <Title>Enter MFA code</Title>\n </Center>\n {errorMessage && (\n <Alert icon={<IconAlertCircle size={16} />} title=\"Error\" color=\"red\">\n {errorMessage}\n </Alert>\n )}\n <Stack>\n <TextInput name=\"token\" label=\"MFA code\" required autoFocus />\n </Stack>\n <Group justify=\"flex-end\" mt=\"xl\">\n <Button type=\"submit\">Submit code</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import {\n buildElementsContext,\n ElementsContextType,\n getPathDisplayName,\n isEmpty,\n tryGetDataType,\n TypedValue,\n} from '@medplum/core';\nimport { DEFAULT_IGNORED_NON_NESTED_PROPERTIES, DEFAULT_IGNORED_PROPERTIES } from '../constants';\nimport { DescriptionList, DescriptionListEntry } from '../DescriptionList/DescriptionList';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { useContext, useMemo } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\nimport { AccessPolicyResource } from '@medplum/fhirtypes';\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} 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", "import { ActionIcon, Box, CopyButton, Tooltip } from '@mantine/core';\nimport {\n InternalSchemaElement,\n PropertyType,\n formatDateTime,\n formatPeriod,\n formatTiming,\n isEmpty,\n} from '@medplum/core';\nimport { IconCheck, IconCopy } from '@tabler/icons-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 { 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';\nimport { ExtensionDisplay } from '../ExtensionDisplay/ExtensionDisplay';\nimport { ElementDefinitionType } from '@medplum/fhirtypes';\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 <Box component=\"div\" style={{ display: 'flex', gap: 3, alignItems: '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 </Box>\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 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 return <>{value}</>;\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.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 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 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 Error(`Displaying property of type ${props.propertyType} requires element schema`);\n }\n if (!props.path) {\n throw 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", "import { formatCodeableConcept } from '@medplum/core';\nimport { CodeableConcept } from '@medplum/fhirtypes';\n\nexport interface CodeableConceptDisplayProps {\n readonly value?: CodeableConcept;\n}\n\nexport function CodeableConceptDisplay(props: CodeableConceptDisplayProps): JSX.Element {\n return <>{formatCodeableConcept(props.value)}</>;\n}\n", "import { formatCoding } from '@medplum/core';\nimport { Coding } from '@medplum/fhirtypes';\n\nexport interface CodingDisplayProps {\n readonly value?: Coding;\n}\n\nexport function CodingDisplay(props: CodingDisplayProps): JSX.Element {\n return <>{formatCoding(props.value)}</>;\n}\n", "import { ContactPoint } from '@medplum/fhirtypes';\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", "import { ContactDetail } from '@medplum/fhirtypes';\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", "import { Identifier } from '@medplum/fhirtypes';\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", "import { formatMoney } from '@medplum/core';\nimport { Money } from '@medplum/fhirtypes';\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", "import { formatQuantity } from '@medplum/core';\nimport { Quantity } from '@medplum/fhirtypes';\n\nexport interface QuantityDisplayProps {\n readonly value?: Quantity;\n}\n\nexport function QuantityDisplay(props: QuantityDisplayProps): JSX.Element | null {\n return <>{formatQuantity(props.value)}</>;\n}\n", "import { formatRange } from '@medplum/core';\nimport { Range } from '@medplum/fhirtypes';\n\nexport interface RangeDisplayProps {\n readonly value?: Range;\n}\n\nexport function RangeDisplay(props: RangeDisplayProps): JSX.Element | null {\n return <>{formatRange(props.value)}</>;\n}\n", "import { Ratio } from '@medplum/fhirtypes';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\n\nexport interface RatioDisplayProps {\n readonly value?: Ratio;\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} />\n / \n <QuantityDisplay value={value.denominator} />\n </>\n );\n}\n", "import { stringify } from '@medplum/core';\nimport { Reference } from '@medplum/fhirtypes';\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", "import { InternalSchemaElement, SliceDefinitionWithTypes, getPathDisplayName, isPopulated } from '@medplum/core';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { useState, useContext, useEffect, useMemo } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { prepareSlices, assignValuesIntoSlices } from '../ResourceArrayInput/ResourceArrayInput.utils';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { SliceDisplay } from '../SliceDisplay/SliceDisplay';\nimport { DescriptionListEntry } from '../DescriptionList/DescriptionList';\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 ctx = useContext(ElementsContext);\n\n useEffect(() => {\n prepareSlices({\n medplum,\n property,\n })\n .then((slices) => {\n setSlices(slices);\n const slicedValues = assignValuesIntoSlices(values, 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 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 </>\n );\n}\n", "import {\n InternalSchemaElement,\n MedplumClient,\n SliceDefinitionWithTypes,\n SlicingRules,\n getValueSliceName,\n isPopulated,\n isSliceDefinitionWithTypes,\n tryGetProfile,\n} 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", "import {\n SliceDefinitionWithTypes,\n InternalSchemaElement,\n ElementsContextType,\n buildElementsContext,\n isPopulated,\n} from '@medplum/core';\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", "import { Context } 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", "import {\n ElementType,\n InternalTypeSchema,\n getDataType,\n isPopulated,\n isProfileLoaded,\n tryGetProfile,\n} from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\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<InternalTypeSchema>(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 as string, value: props.value }}\n compact={props.compact}\n ignoreMissingValues={props.ignoreMissingValues}\n link={props.link}\n profileUrl={profileUrl}\n />\n );\n}\n", "import {\n getTypedPropertyValue,\n getTypedPropertyValueWithSchema,\n InternalSchemaElement,\n TypedValue,\n} 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", "import { ElementsContextType, buildElementsContext, tryGetDataType } from '@medplum/core';\nimport { AccessPolicyResource } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { ElementsInput } from '../ElementsInput/ElementsInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { maybeWrapWithContext } from '../utils/maybeWrapWithContext';\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} not implemented</div>;\n }\n\n return maybeWrapWithContext(\n ElementsContext.Provider,\n contextValue,\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 );\n}\n", "import { Stack } from '@mantine/core';\nimport { TypedValue, getPathDisplayName } from '@medplum/core';\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 { EXTENSION_KEYS, ElementsContext, getElementsToRender } from './ElementsInput.utils';\nimport { BaseInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.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<any>(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", "import { Group, Input } from '@mantine/core';\nimport { ReactNode, useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\nimport classes from '../FormSection/FormSection.module.css';\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", "import { Tooltip } from '@mantine/core';\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", ".dimmed {\n color: var(--mantine-color-dimmed);\n}\n\n.preserveBreaks {\n white-space: pre-wrap;\n}", "import cx from 'clsx';\nimport { Input } from '@mantine/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { ReactNode, useContext } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { READ_ONLY_TOOLTIP_TEXT, maybeWrapWithTooltip } from '../utils/maybeWrapWithTooltip';\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", "import { capitalize, InternalSchemaElement, isEmpty } from '@medplum/core';\nimport { 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 as string));\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", "import { Checkbox, Group, NativeSelect, Textarea, TextInput } from '@mantine/core';\nimport {\n applyDefaultValuesToElement,\n capitalize,\n ExtendedInternalSchemaElement,\n getPathDifference,\n HTTP_HL7_ORG,\n isComplexTypeCode,\n isEmpty,\n isPopulated,\n PropertyType,\n} from '@medplum/core';\nimport { ElementDefinitionBinding, ElementDefinitionType } from '@medplum/fhirtypes';\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 { BaseInputProps, ComplexTypeInputProps, PrimitiveTypeInputProps } from './ResourcePropertyInput.utils';\n\nexport interface ResourcePropertyInputProps extends BaseInputProps {\n readonly property: ExtendedInternalSchemaElement;\n readonly name: string;\n readonly defaultPropertyType?: string | undefined;\n readonly defaultValue: any;\n readonly arrayElement?: boolean | undefined;\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 as string));\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) as ElementDefinitionType;\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 as string,\n label: type.code as string,\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 as string)));\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\n extends Pick<ResourcePropertyInputProps, 'name' | 'path' | 'valuePath' | 'defaultValue' | 'onChange' | 'outcome'> {\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.time:\n case PropertyType.uri:\n case PropertyType.url:\n if (props.path === 'Project.secret.value[x]') {\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.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 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", "import { CodeableConcept, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\n\nexport interface CodeableConceptInputProps\n extends 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<CodeableConcept | undefined>(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", "import { Coding, ValueSetExpansionContains } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { ValueSetAutocomplete, ValueSetAutocompleteProps } from '../ValueSetAutocomplete/ValueSetAutocomplete';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\n\nexport interface CodingInputProps\n extends Omit<ValueSetAutocompleteProps, 'defaultValue' | 'onChange' | 'disabled' | 'name'>,\n ComplexTypeInputProps<Coding> {}\n\nexport function CodingInput(props: CodingInputProps): JSX.Element {\n const { defaultValue, onChange, withHelpText, ...rest } = props;\n const [value, setValue] = useState<Coding | undefined>(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)}\n maxValues={1}\n onChange={handleChange}\n withHelpText={withHelpText ?? true}\n {...rest}\n />\n );\n}\n\nfunction codingToValueSetElement(coding: Coding): ValueSetExpansionContains {\n return {\n system: coding.system,\n code: coding.code,\n display: coding.display,\n };\n}\n\nfunction valueSetElementToCoding(element: ValueSetExpansionContains): Coding {\n return {\n system: element.system,\n code: element.code,\n display: element.display,\n };\n}\n", "import { Group, TextInput } from '@mantine/core';\nimport { ContactDetail, ContactPoint } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ContactPointInput } from '../ContactPointInput/ContactPointInput';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nexport type ContactDetailInputProps = ComplexTypeInputProps<ContactDetail>;\n\nexport function ContactDetailInput(props: ContactDetailInputProps): JSX.Element {\n const [contactPoint, setContactDetail] = useState(props.defaultValue);\n\n const ref = useRef<ContactDetail>();\n ref.current = contactPoint;\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 = { ...ref.current, 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 = { ...ref.current, 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={contactPoint?.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={contactPoint?.telecom?.[0]}\n onChange={setTelecom}\n outcome={props.outcome}\n />\n </Group>\n );\n}\n", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { ContactPoint } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 ref = useRef<ContactPoint>();\n ref.current = contactPoint;\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 = { ...ref.current, 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 = { ...ref.current, use };\n if (!use) {\n delete newValue.use;\n }\n setContactPointWrapper(newValue);\n }\n\n function setValue(value: string): void {\n const newValue: ContactPoint = { ...ref.current, 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', '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", "import { TextInput } from '@mantine/core';\nimport { OperationOutcome } from '@medplum/fhirtypes';\nimport { ChangeEvent } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { convertIsoToLocal, convertLocalToIso } from './DateTimeInput.utils';\nimport { PrimitiveTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.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 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", "import { 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", "import { isPopulated, isProfileLoaded } from '@medplum/core';\nimport { ElementDefinitionType, Extension } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useMemo, useState } from 'react';\nimport { BackboneElementInput } from '../BackboneElementInput/BackboneElementInput';\nimport { 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", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { HumanName } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nexport type HumanNameInputProps = ComplexTypeInputProps<HumanName>;\n\nexport function HumanNameInput(props: HumanNameInputProps): JSX.Element {\n const { outcome, path } = props;\n const [value, setValue] = useState<HumanName | undefined>(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", "import { Group, TextInput } from '@mantine/core';\nimport { Identifier } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { getErrorsForInput } from '../utils/outcomes';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\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", "import { NativeSelect, TextInput } from '@mantine/core';\nimport { Money } from '@medplum/fhirtypes';\nimport { IconCurrencyDollar } from '@tabler/icons-react';\nimport { ChangeEvent, useCallback, useContext, useMemo, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group } from '@mantine/core';\nimport { Period } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group, NativeSelect, TextInput } from '@mantine/core';\nimport { Quantity } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState, WheelEvent } from 'react';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.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 parseFloat(str);\n}\n", "import { Group } from '@mantine/core';\nimport { Range } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group } from '@mantine/core';\nimport { Ratio } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useState } from 'react';\nimport { QuantityInput } from '../QuantityInput/QuantityInput';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { 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", "import { Group, NativeSelect } from '@mantine/core';\nimport {\n LRUCache,\n MedplumClient,\n ReadablePromise,\n createReference,\n isEmpty,\n isPopulated,\n tryGetProfile,\n} from '@medplum/core';\nimport { Reference, Resource, ResourceType, StructureDefinition } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\n\nexport interface ReferenceInputProps {\n readonly name: string;\n readonly placeholder?: string;\n readonly defaultValue?: Reference;\n readonly targetTypes?: string[];\n readonly searchCriteria?: Record<string, string>;\n readonly autoFocus?: boolean;\n readonly required?: boolean;\n readonly onChange?: (value: Reference | 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(props: ReferenceInputProps): JSX.Element {\n const { onChange } = props;\n const medplum = useMedplum();\n const [value, setValue] = useState<Reference | undefined>(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: Resource | 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 <Group gap=\"xs\" grow wrap=\"nowrap\">\n {targetTypes && targetTypes.length > 1 && (\n <NativeSelect\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\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 }`.replace(/\\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", "import { Group, Text } from '@mantine/core';\nimport { getDisplayString, getReferenceString, isPopulated } from '@medplum/core';\nimport { OperationOutcome, Patient, Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { forwardRef, ReactNode, useCallback, useState } from 'react';\nimport {\n AsyncAutocomplete,\n AsyncAutocompleteOption,\n AsyncAutocompleteProps,\n} 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\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 loadOnFocus?: boolean;\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\nfunction toOption<T extends Resource>(resource: T): AsyncAutocompleteOption<T> {\n return {\n value: getReferenceString(resource),\n label: getDisplayString(resource),\n resource,\n };\n}\n\nexport function ResourceInput<T extends Resource = Resource>(props: ResourceInputProps<T>): JSX.Element | null {\n const medplum = useMedplum();\n const { resourceType, searchCriteria } = props;\n const [outcome, setOutcome] = useState<OperationOutcome>();\n const defaultValue = useResource(props.defaultValue, setOutcome);\n const ItemComponent = props.itemComponent ?? DefaultItemComponent;\n const onChange = props.onChange;\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[0]);\n }\n },\n [onChange]\n );\n\n if (isPopulated(props.defaultValue) && !outcome && !defaultValue) {\n // If a default value was specified, but the default resource is not loaded yet,\n // then return null to avoid rendering the input until the default resource is loaded.\n // The Mantine <MultiSelect> component does not reliably handle changes to defaultValue.\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={defaultValue}\n placeholder={props.placeholder}\n maxValues={1}\n toOption={toOption}\n loadOptions={loadValues}\n onChange={handleChange}\n clearable\n />\n );\n}\n\nconst DefaultItemComponent = 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\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", "import { Group, Stack, Text } from '@mantine/core';\nimport { ExtendedInternalSchemaElement, SliceDefinitionWithTypes, getPathDisplayName } from '@medplum/core';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { MouseEvent, useContext, useEffect, useState } from 'react';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\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';\nimport { BaseInputProps, getValuePath } from '../ResourcePropertyInput/ResourcePropertyInput.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", "import { Group, Stack, Text } from '@mantine/core';\nimport {\n ExtendedInternalSchemaElement,\n ElementsContextType,\n SliceDefinitionWithTypes,\n buildElementsContext,\n getPropertyDisplayName,\n isEmpty,\n isPopulated,\n} from '@medplum/core';\nimport { MouseEvent, 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 { 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<any[]>(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", "import { ActionIcon, Button } from '@mantine/core';\nimport { IconCirclePlus } from '@tabler/icons-react';\nimport { 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", "import { ActionIcon } from '@mantine/core';\nimport { IconCircleMinus } from '@tabler/icons-react';\nimport { 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", "import { 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", "import { ActionIcon, Flex, Textarea, TextareaProps } from '@mantine/core';\nimport { useClipboard } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { IconCopy } from '@tabler/icons-react';\nimport { RefAttributes, 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", "import { Button, Chip, Group, Modal, NativeSelect, Stack, Switch, TextInput } from '@mantine/core';\nimport { formatTiming } from '@medplum/core';\nimport { Timing, TimingRepeat } from '@medplum/fhirtypes';\nimport { useContext, useMemo, useRef, useState } from 'react';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { FormSection } from '../FormSection/FormSection';\nimport { ComplexTypeInputProps } from '../ResourcePropertyInput/ResourcePropertyInput.utils';\nimport { ElementsContext } from '../ElementsInput/ElementsInput.utils';\n\nconst daysOfWeek = ['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\nexport interface TimingInputProps extends ComplexTypeInputProps<Timing> {\n readonly defaultModalOpen?: boolean;\n}\n\nexport function TimingInput(props: TimingInputProps): JSX.Element {\n const [value, setValue] = useState<Timing | undefined>(props.defaultValue);\n const [open, setOpen] = useState(!props.disabled && (props.defaultModalOpen ?? false));\n\n const valueRef = useRef<Timing>();\n valueRef.current = value;\n\n return (\n <>\n <Group gap=\"xs\" grow wrap=\"nowrap\">\n <span>{formatTiming(valueRef.current) || '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={valueRef.current}\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<Timing>(props.defaultValue || defaultValue);\n const { getExtendedProps } = useContext(ElementsContext);\n const [eventProps, repeatProps, repeatPeriodProps, repeatPeriodUnitProps, repeatDayOfWeekProps] = useMemo(\n () =>\n ['event', 'repeat', 'repeat.period', 'repeat.periodUnit', 'repeat.dayOfWeek'].map((field) =>\n getExtendedProps(props.path + '.' + field)\n ),\n [getExtendedProps, props.path]\n );\n\n const valueRef = useRef<Timing>();\n valueRef.current = value;\n\n function setStart(newStart: string): void {\n setValue({ ...valueRef.current, event: [newStart] });\n }\n\n function setRepeat(repeat: TimingRepeat | undefined): void {\n setValue({ ...valueRef.current, repeat });\n }\n\n function setPeriod(newPeriod: number | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, period: newPeriod });\n }\n\n function setPeriodUnit(newPeriodUnit: PeriodUnit | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, periodUnit: newPeriodUnit });\n }\n\n function setDaysOfWeek(newDaysOfWeek: DayOfWeek[] | undefined): void {\n setRepeat({ ...valueRef.current?.repeat, dayOfWeek: newDaysOfWeek });\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>\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(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: 'second', value: 's' },\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 multiple onChange={setDaysOfWeek as (v: string[] | undefined) => void}>\n <Group justify=\"space-between\" mt=\"md\" gap=\"xs\">\n {daysOfWeek.map((day) => (\n <Chip key={day} value={day} size=\"xs\" radius=\"xl\" disabled={repeatDayOfWeekProps?.readonly}>\n {day.charAt(0).toUpperCase()}\n </Chip>\n ))}\n </Group>\n </Chip.Group>\n </FormSection>\n )}\n </>\n )}\n <Group justify=\"flex-end\">\n <Button onClick={() => props.onOk(value)}>OK</Button>\n </Group>\n </Stack>\n </Modal>\n );\n}\n", "import { Button, Group } from '@mantine/core';\nimport { Slot } from '@medplum/fhirtypes';\nimport { useMemo, useState } from 'react';\nimport classes from './CalendarInput.module.css';\nimport { getMonthString, getStartMonth } from './CalendarInput.utils';\n\nexport interface CalendarInputProps {\n readonly slots: Slot[];\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 CalendarInput(props: CalendarInputProps): 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.getTime());\n newMonth.setMonth(currMonth.getMonth() + delta);\n onChangeMonth(newMonth);\n return newMonth;\n });\n }\n\n const grid = useMemo(() => buildGrid(month, props.slots), [month, props.slots]);\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 <\n </Button>\n <Button variant=\"outline\" aria-label=\"Next month\" onClick={() => moveMonth(1)}>\n >\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, slots: Slot[]): 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.getTime()),\n available: isDayAvailable(d, slots),\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 slots - The list of available slots.\n * @returns True if there are any available slots for the day.\n */\nfunction isDayAvailable(day: Date, slots: Slot[]): boolean {\n // Note that slot start and end time may or may not be in UTC.\n for (const slot of slots) {\n const slotStart = new Date(slot.start as string);\n if (\n slotStart.getFullYear() === day.getFullYear() &&\n slotStart.getMonth() === day.getMonth() &&\n slotStart.getDate() === day.getDate()\n ) {\n return true;\n }\n }\n\n return false;\n}\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 * 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", "import {\n ActionIcon,\n Group,\n LoadingOverlay,\n Paper,\n PaperProps,\n ScrollArea,\n Skeleton,\n Stack,\n TextInput,\n Title,\n} from '@mantine/core';\nimport { useResizeObserver } from '@mantine/hooks';\nimport { showNotification } from '@mantine/notifications';\nimport { ProfileResource, getDisplayString, getReferenceString, normalizeErrorString } from '@medplum/core';\nimport { Bundle, Communication, Reference } from '@medplum/fhirtypes';\nimport { useMedplum, useResource, useSubscription } from '@medplum/react-hooks';\nimport { IconArrowRight } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { LegacyRef, useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { Form } from '../../Form/Form';\nimport { ResourceAvatar } from '../../ResourceAvatar/ResourceAvatar';\nimport classes from './BaseChat.module.css';\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 const sentTime = new Date(communication.sent ?? 0);\n const sentTimeMins = sentTime.getMinutes().toString();\n return `${sentTime.getHours()}:${sentTimeMins.length === 1 ? '0' : ''}${sentTimeMins}`;\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) => (a.sent as string).localeCompare(b.sent as string));\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) => void;\n readonly onMessageReceived?: (message: Communication) => void;\n readonly onMessageUpdated?: (message: Communication) => void;\n readonly inputDisabled?: boolean;\n readonly onError?: (err: Error) => void;\n}\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 ...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\n if (!loading) {\n initialLoadRef.current = false;\n }\n\n const profileRefStr = useMemo<string>(\n () => (profile ? getReferenceString(medplum.getProfile() as 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 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 if (inputRef.current) {\n inputRef.current.value = '';\n }\n sendMessage(formData.message);\n scrollToBottomRef.current = true;\n },\n [inputDisabled, sendMessage]\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<Communication[]>(communications);\n communicationsRef.current = communications;\n const prevCommunicationsRef = useRef<Communication[]>(communications);\n\n const scrollToBottomRef = useRef<boolean>(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 <Title order={2} className={classes.chatTitle}>\n {title}\n </Title>\n <div className={classes.chatBody} ref={parentRef as LegacyRef<HTMLDivElement>}>\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 return (\n <Stack key={`${c.id}--${c.meta?.versionId ?? 'no-version'}`} align=\"stretch\">\n {(!prevCommTime || currCommTime !== prevCommTime) && (\n <div style={{ textAlign: 'center' }}>{currCommTime}</div>\n )}\n {c.sender?.reference === profileRefStr ? (\n <Group justify=\"flex-end\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n <ChatBubble\n alignment=\"right\"\n communication={c}\n showDelivered={!!c.received && c.id === myLastDeliveredId}\n />\n <ResourceAvatar radius=\"xl\" color=\"orange\" value={c.sender} />\n </Group>\n ) : (\n <Group justify=\"flex-start\" align=\"flex-end\" gap=\"xs\" mb=\"sm\">\n <ResourceAvatar radius=\"xl\" value={c.sender} />\n <ChatBubble alignment=\"left\" communication={c} />\n </Group>\n )}\n </Stack>\n );\n })}\n </ScrollArea>\n )}\n </div>\n <div className={classes.chatInputContainer}>\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 rightSectionWidth={42}\n disabled={inputDisabled}\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 content = communication.payload?.[0]?.contentString || '';\n const seenTime = new Date(communication.received ?? -1);\n const senderResource = useResource(communication.sender);\n return (\n <div className={classes.chatBubbleOuterWrap}>\n <div\n className={cx(classes.chatBubbleName, alignment === 'right' && classes.chatBubbleNameRight)}\n aria-label=\"Sender name\"\n >\n {senderResource ? getDisplayString(senderResource) : '[Unknown sender]'}\n </div>\n <div\n className={\n alignment === 'left' ? classes.chatBubbleLeftAlignedInnerWrap : classes.chatBubbleRightAlignedInnerWrap\n }\n >\n <div className={classes.chatBubble}>{content}</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\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 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 padding: 6px 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.chatBubbleName {\n margin-bottom: 5px;\n font-weight: 500;\n}\n\n.chatBubbleNameRight {\n text-align: right;\n}\n", "import { ActionIcon } from '@mantine/core';\nimport { useMedplumProfile } from '@medplum/react-hooks';\nimport { IconChevronDown, IconChevronUp } from '@tabler/icons-react';\nimport { ReactNode, 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", "import { ProfileResource, createReference, formatCodeableConcept, getReferenceString } from '@medplum/core';\nimport { Communication } from '@medplum/fhirtypes';\nimport { useMedplum, useMedplumProfile, usePrevious } from '@medplum/react-hooks';\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 onError?: (err: Error) => void;\n}\n\nexport function ThreadChat(props: ThreadChatProps): JSX.Element | null {\n const { thread, title, onMessageSent, inputDisabled, onError } = props;\n const medplum = useMedplum();\n const profile = useMedplumProfile();\n const prevThreadId = usePrevious<string | undefined>(thread?.id);\n const [communications, setCommunications] = useState<Communication[]>([]);\n\n const profileRef = useMemo(() => (profile ? createReference(profile as ProfileResource) : 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) => {\n const profileRefStr = profileRef ? getReferenceString(profileRef) : undefined;\n if (!profileRefStr) {\n return;\n }\n medplum\n .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: [{ contentString: message }],\n partOf: [threadRef],\n })\n .then((communication) => {\n setCommunications([...communications, communication]);\n onMessageSent?.(communication);\n })\n .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<Communication>({\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/organizing-communications#:~:text=THE%20Communication%20LIFECYCLE\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 onError={onError}\n />\n );\n}\n", "import { ActionIcon, Center, Group, Loader, ScrollArea, TextInput } from '@mantine/core';\nimport { showNotification, updateNotification } from '@mantine/notifications';\nimport { MedplumClient, ProfileResource, createReference, normalizeErrorString } from '@medplum/core';\nimport {\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 { ReactNode, useCallback, useEffect, 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 { Timeline, TimelineItem, TimelineItemProps } 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 loadTimelineResources = props.loadTimelineResources;\n\n const itemsRef = useRef<Resource[]>(items);\n itemsRef.current = items;\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 = [];\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 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 {items.map((item) => {\n if (!item) {\n // TODO: Handle null history items for deleted versions.\n return null;\n }\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 </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", "import { Group, List, Stack, Text, Title } from '@mantine/core';\nimport { capitalize, formatCodeableConcept, formatDateTime, formatObservationValue, isReference } from '@medplum/core';\nimport {\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 { 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}\n\nDiagnosticReportDisplay.defaultProps = {\n hideObservationNotes: false,\n hideSpecimenInfo: 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} />\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 </Stack>\n );\n}\n\ninterface DiagnosticReportHeaderProps {\n readonly value: DiagnosticReport;\n}\n\nfunction DiagnosticReportHeader({ value }: DiagnosticReportHeaderProps): JSX.Element {\n return (\n <Group mt=\"md\" gap={30}>\n {value.subject && (\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 <Text>{capitalize(value.status)}</Text>\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 as string)) {\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) => <ReferenceDisplay key={performer.reference} value={performer} />)}\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={\n props.ancestorIds ? [...props.ancestorIds, observation.id as string] : [observation.id as string]\n }\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", "import { Blockquote, Stack } from '@mantine/core';\nimport { Annotation } from '@medplum/fhirtypes';\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", "import { Group } from '@mantine/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\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", "import { Text, TextProps } from '@mantine/core';\nimport { getDisplayString, isOk, normalizeErrorString } from '@medplum/core';\nimport { OperationOutcome, Reference, Resource } from '@medplum/fhirtypes';\nimport { useResource } from '@medplum/react-hooks';\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", "import { Badge, DefaultMantineColor } from '@mantine/core';\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};\n\nexport interface StatusBadgeProps {\n readonly status: string;\n}\n\nexport function StatusBadge(props: StatusBadgeProps): JSX.Element {\n return <Badge color={statusToColor[props.status]}>{props.status}</Badge>;\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", "import { Table } from '@mantine/core';\nimport {\n InternalSchemaElement,\n TypedValue,\n arrayify,\n capitalize,\n evalFhirPathTyped,\n getSearchParameterDetails,\n toTypedValue,\n} from '@medplum/core';\nimport { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useMemo, useState } from 'react';\nimport { Operation, 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 <ResourceDiffRow {...row} />\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 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}\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) as TypedValue[]).flatMap((v) => v.value);\n return isArray ? inputValue : inputValue[0];\n}\n", "import { useState } from 'react';\nimport { Table, Button } from '@mantine/core';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { InternalSchemaElement, TypedValue } from '@medplum/core';\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<boolean>(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", "import { AccessPolicyInteraction, satisfiedAccessPolicy, tryGetProfile } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\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", "import { ActionIcon, Group, Menu, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport { Reference, Resource } from '@medplum/fhirtypes';\nimport { IconDots } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { ReactNode } from 'react';\nimport { Container } from '../Container/Container';\nimport { ErrorBoundary } from '../ErrorBoundary/ErrorBoundary';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { Panel, PanelProps } 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 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=\"dark\" fw={500} value={author} link={true} />\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 ·\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", "import { 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", "\n.pinnedComment {\n background-color: var(--mantine-color-blue-0);\n}", "import { MedplumClient } from '@medplum/core';\nimport { Reference, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Encounter, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { Button, Loader, Table } from '@mantine/core';\nimport { normalizeOperationOutcome } from '@medplum/core';\nimport { OperationOutcome, Resource } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { ChangeEvent, MouseEvent, memo, useEffect, useRef, 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 const responseRef = useRef<SmartSearchResponse>();\n responseRef.current = response;\n\n const selectedRef = useRef<{ [id: string]: boolean }>({});\n selectedRef.current = selected;\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 = { ...selectedRef.current };\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 = responseRef.current?.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 = responseRef.current?.data.ResourceList;\n if (!resources || resources.length === 0) {\n return false;\n }\n for (const resource of resources) {\n if (resource.id && !selectedRef.current[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(selectedRef.current))}>\n Bulk...\n </Button>\n )}\n </div>\n );\n}\n\nexport const MemoizedFhirPathTable = memo(FhirPathTable);\n", "import { evalFhirPath } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\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", "import {\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 {\n DEFAULT_SEARCH_COUNT,\n Filter,\n SearchRequest,\n deepEquals,\n formatSearchQuery,\n isDataTypeLoaded,\n normalizeOperationOutcome,\n} from '@medplum/core';\nimport { Bundle, OperationOutcome, Resource, ResourceType, 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 { ChangeEvent, MouseEvent, useCallback, useEffect, 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 { isCheckboxCell, killEvent } from '../utils/dom';\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}\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<SearchControlState>(state);\n stateRef.current = state;\n\n const total = memoizedSearch.total ?? 'accurate';\n\n const loadResults = useCallback(\n (options?: RequestInit) => {\n setOutcome(undefined);\n medplum\n .requestSchema(memoizedSearch.resourceType as ResourceType)\n .then(() =>\n medplum.search(\n memoizedSearch.resourceType as 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 const state = stateRef.current;\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 = e.button === 1 || e.ctrlKey || e.metaKey;\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 })}\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 })}\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 ? props.onExport : () => setState({ ...stateRef.current, exportDialogVisible: true })\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 });\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={(control) => {\n switch (control) {\n case 'previous':\n return { 'aria-label': 'Previous page' };\n case 'next':\n return { 'aria-label': 'Next page' };\n default:\n return {};\n }\n }}\n />\n </Center>\n )}\n <SearchFieldEditor\n search={memoizedSearch}\n visible={stateRef.current.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 search={memoizedSearch}\n visible={stateRef.current.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 visible={stateRef.current.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={state.filterDialogSearchParam?.code}\n visible={stateRef.current.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\n/**\n * @deprecated\n *\n * The memoization `MemoizedSearchControl` provides has been merged into `SearchControl`. Previously the memoization was done via HOC but\n * it was proven that this wasn't effective for a large number of use cases, especially when:\n * 1. `search` was an inline static object, which would trigger the memo to recompute on every re-render of the parent component\n * 2. Any of the callbacks, such as `onClick` were not memoized via `useCallback`, which would result in the recomputation as well\n *\n * Scenario 1 also retriggered the effect that runs `loadResults` on change of the `search`, which was less than desirable.\n *\n * The memoization is now accomplished via checking deep equality of the incoming `search` prop in the body of the component, and setting a memoized\n * state whenever the incoming and current memoized value are not deeply equal. See: https://github.com/medplum/medplum/pull/5023\n */\nexport const MemoizedSearchControl = SearchControl;\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 \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", "import { Box, Button, Modal, Text } from '@mantine/core';\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", "import { Button, Group, Modal, MultiSelect, Stack } from '@mantine/core';\nimport {\n InternalTypeSchema,\n SearchRequest,\n getDataType,\n getSearchParameters,\n sortStringArray,\n stringify,\n} from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\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 if (!props.visible) {\n return null;\n }\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", "import {\n capitalize,\n DEFAULT_SEARCH_COUNT,\n evalFhirPathTyped,\n Filter,\n formatDateTime,\n InternalSchemaElement,\n Operator,\n SearchRequest,\n} from '@medplum/core';\nimport { Resource, SearchParameter } from '@medplum/fhirtypes';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { 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],\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 \"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.replace(/([A-Z])/g, ' $1');\n\n // Convert dashes and underscores to spaces\n tmp = tmp.replace(/[-_]/g, ' ');\n\n // Normalize whitespace to single space character\n tmp = tmp.replace(/\\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 resource.id;\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 (field.elementDefinition && `${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 && 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", "import { ActionIcon, Button, Group, Modal, NativeSelect } from '@mantine/core';\nimport { Filter, Operator, SearchRequest, deepClone, getSearchParameters } from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\nimport { IconX } from '@tabler/icons-react';\nimport { useEffect, useRef, useState } from 'react';\nimport { ArrayAddButton } from '../buttons/ArrayAddButton';\nimport { Form } from '../Form/Form';\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<SearchRequest>(deepClone(props.search) as SearchRequest);\n\n const searchRef = useRef<SearchRequest>(search);\n searchRef.current = search;\n\n useEffect(() => {\n setSearch(deepClone(props.search) as SearchRequest);\n }, [props.search]);\n\n function onAddFilter(filter: Filter): void {\n setSearch(addFilter(searchRef.current, filter.code, filter.operator, filter.value));\n }\n\n if (!props.visible) {\n return null;\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 <Button type=\"submit\">OK</Button>\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 const valueRef = useRef<Filter>(value);\n valueRef.current = value;\n\n function setFilterCode(newCode: string): void {\n valueRef.current.code = newCode;\n valueRef.current.operator = Operator.EQUALS;\n valueRef.current.value = '';\n props.onChange(valueRef.current);\n }\n\n function setFilterOperator(newOperator: Operator): void {\n valueRef.current.operator = newOperator;\n valueRef.current.value = '';\n props.onChange(valueRef.current);\n }\n\n function setFilterValue(newFilterValue: string): void {\n valueRef.current.value = newFilterValue;\n props.onChange(valueRef.current);\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 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 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", "import { Checkbox, TextInput } from '@mantine/core';\nimport { getSearchParameterDetails, SearchParameterType } from '@medplum/core';\nimport { Quantity, Reference, SearchParameter } from '@medplum/fhirtypes';\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: parseFloat(valueString),\n system: systemString,\n unit: unitString,\n };\n }\n }\n return undefined;\n}\n", "import { Button, Grid, Modal } from '@mantine/core';\nimport { Filter } from '@medplum/core';\nimport { SearchParameter } from '@medplum/fhirtypes';\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<string>(props.defaultValue ?? '');\n\n if (!props.visible || !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", "import {\n Filter,\n formatDateTime,\n getSearchParameterDetails,\n globalSchema,\n Operator,\n SearchParameterType,\n} from '@medplum/core';\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", "import { Menu } from '@mantine/core';\nimport { Filter, Operator, SearchRequest } from '@medplum/core';\nimport { 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 {\n addLastMonthFilter,\n addMissingFilter,\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 as string, desc));\n }\n\n function onClear(searchParam: SearchParameter): void {\n onChange(clearFiltersOnField(props.search, searchParam.code as string));\n }\n\n function onPrompt(searchParam: SearchParameter, operator: Operator): void {\n props.onPrompt(searchParam, { code: searchParam.code as string, 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 as string)}</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 case 'uri':\n return <TokenFilterSubMenu {...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 as string;\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.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 <CommonMenuItems {...props} />\n </Menu.Dropdown>\n );\n}\n\nfunction CommonMenuItems(props: SearchPopupSubMenuProps): JSX.Element {\n const { searchParam } = props;\n const code = searchParam.code as string;\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", ".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", "import {\n getElementDefinition,\n getSearchParameter,\n getSearchParameterDetails,\n getSearchParameters,\n InternalSchemaElement,\n SearchRequest,\n} from '@medplum/core';\nimport { 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", "import { Box, SimpleGrid } from '@mantine/core';\nimport { MeasureReport, MeasureReportGroup, Reference } from '@medplum/fhirtypes';\nimport { useResource, useSearchOne } from '@medplum/react-hooks';\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", "import { Box, Flex, Group, Paper, RingProgress, Text, Title } from '@mantine/core';\nimport { formatCodeableConcept } from '@medplum/core';\nimport { Measure, MeasureReportGroup } from '@medplum/fhirtypes';\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", "import { ActionIcon, Indicator, Tooltip } from '@mantine/core';\nimport { ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useSubscription } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useState } from 'react';\n\nexport interface NotificationIconProps {\n readonly iconComponent: JSX.Element;\n readonly label: 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 medplum = useMedplum();\n const { label, resourceType, countCriteria, subscriptionCriteria, onClick } = props;\n const [unreadCount, setUnreadCount] = useState(0);\n\n const updateCount = useCallback(\n (cache: 'default' | 'reload') => {\n medplum\n .search(resourceType, countCriteria, { cache })\n .then((result) => setUnreadCount(result.total as number))\n .catch(console.error);\n },\n [medplum, resourceType, countCriteria]\n );\n\n // Initial count\n useEffect(() => {\n // Cache=default to use the default cache policy, and accept most recent data\n updateCount('default');\n }, [updateCount]);\n\n // Subscribe to the criteria\n useSubscription(subscriptionCriteria, () => {\n // Cache=reload to force a reload\n updateCount('reload');\n });\n\n const icon = (\n <Tooltip label={label}>\n <ActionIcon variant=\"subtle\" color=\"gray\" size=\"lg\" aria-label={label} onClick={onClick}>\n {props.iconComponent}\n </ActionIcon>\n </Tooltip>\n );\n\n return unreadCount > 0 ? (\n <Indicator inline label={unreadCount.toLocaleString()} size={16} offset={2} position=\"bottom-end\" color=\"red\">\n {icon}\n </Indicator>\n ) : (\n icon\n );\n}\n", "import { Card, CardProps, Divider, Flex, Group, Paper, Stack, Text } from '@mantine/core';\nimport { calculateAgeString, formatHumanName, resolveId } from '@medplum/core';\nimport {\n AllergyIntolerance,\n Appointment,\n Condition,\n Encounter,\n HumanName,\n MedicationRequest,\n Observation,\n Patient,\n Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconGenderFemale, IconGenderMale, IconStethoscope, IconUserSquare } from '@tabler/icons-react';\nimport { ReactNode, useEffect, useMemo, useState } from 'react';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { Allergies } from './Allergies';\nimport { Medications } from './Medications';\nimport { ProblemList } from './ProblemList';\nimport { SexualOrientation } from './SexualOrientation';\nimport { SmokingStatus } from './SmokingStatus';\nimport { Vitals } from './Vitals';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\n\nexport interface PatientSummaryProps extends Omit<CardProps, 'children'> {\n readonly patient: Patient | Reference<Patient>;\n readonly background?: string;\n /** The URL that the upcoming appointments link should navigate to or `undefined` to not show the link. */\n readonly appointmentsUrl?: string | undefined;\n /** The URL that the documented visits (encounters) link should navigate to or `undefined` to not show the link. */\n readonly encountersUrl?: string | undefined;\n}\n\ninterface PatientMedicalData {\n readonly allergies: AllergyIntolerance[];\n readonly problems: Condition[];\n readonly sexualOrientation?: Observation;\n readonly smokingStatus?: Observation;\n readonly vitals: Observation[];\n readonly medicationRequests: MedicationRequest[];\n readonly encounters?: Encounter[];\n readonly appointments?: Appointment[];\n}\n\ntype IconType = typeof IconGenderFemale;\n\nfunction getGenderIcon(patient?: Patient): IconType | undefined {\n switch (patient?.gender) {\n case 'female':\n return IconGenderFemale;\n case 'male':\n return IconGenderMale;\n default:\n return undefined;\n }\n}\n\nfunction pluralize(count: number | undefined, singular: string, plural: string): string {\n if (count === 0) {\n return `No ${plural}`;\n } else if (count === 1) {\n return `1 ${singular}`;\n } else {\n return `${count} ${plural}`;\n }\n}\n\nexport function PatientSummary(props: PatientSummaryProps): JSX.Element | null {\n const medplum = useMedplum();\n const {\n patient: propsPatient,\n background,\n appointmentsUrl: propsAppointmentsUrl,\n encountersUrl: propsEncountersUrl,\n ...cardProps\n } = props;\n const patient = useResource(propsPatient);\n const [medicalData, setMedicalData] = useState<PatientMedicalData>();\n\n // If a URL is explicitly specified in `props`, use it even if `undefined`.\n // If not included in `props`, use '#' as a demonstration value.\n const appointmentsUrl = 'appointmentsUrl' in props ? propsAppointmentsUrl : '#';\n const encountersUrl = 'encountersUrl' in props ? propsEncountersUrl : '#';\n\n useEffect(() => {\n const id = resolveId(propsPatient) as string;\n const ref = `Patient/${id}`;\n const searchMeta = { _count: 100, _sort: '-_lastUpdated' };\n const today = new Date().toISOString().substring(0, 10);\n\n Promise.all([\n medplum.searchResources('AllergyIntolerance', { patient: ref, ...searchMeta }),\n medplum.searchResources('Condition', { patient: ref, ...searchMeta }),\n medplum.searchResources('MedicationRequest', { subject: ref, ...searchMeta }),\n medplum.searchResources('Observation', { subject: ref, ...searchMeta }),\n medplum.searchResources('Appointment', {\n patient: ref,\n date: `ge${today}`,\n status: 'proposed,pending,booked',\n ...searchMeta,\n }),\n medplum.searchResources('Encounter', { subject: ref, date: `le${today}`, status: 'finished', ...searchMeta }),\n ])\n .then((results) => {\n const observations = results[3];\n setMedicalData({\n allergies: results[0],\n problems: results[1],\n medicationRequests: results[2],\n sexualOrientation: observations.find((obs) => obs.code?.coding?.[0].code === '76690-7'),\n smokingStatus: observations.find((obs) => obs.code?.coding?.[0].code === '72166-2'),\n vitals: observations.filter((obs) => obs.category?.[0]?.coding?.[0].code === 'vital-signs'),\n appointments: results[4],\n encounters: results[5],\n });\n })\n .catch(console.error);\n }, [medplum, propsPatient]);\n\n const links: ReactNode[] = useMemo(() => {\n const appointmentsLink =\n appointmentsUrl === undefined ? undefined : (\n <MedplumLink key=\"appt\" to={appointmentsUrl}>\n {pluralize(medicalData?.appointments?.length, 'upcoming appointment', 'upcoming appointments')}\n </MedplumLink>\n );\n const encountersLink =\n encountersUrl === undefined ? undefined : (\n <MedplumLink key=\"enc\" to={encountersUrl}>\n {pluralize(medicalData?.encounters?.length, 'documented visit', 'documented visits')}\n </MedplumLink>\n );\n\n return [appointmentsLink, encountersLink].filter(Boolean);\n }, [appointmentsUrl, medicalData?.appointments?.length, medicalData?.encounters?.length, encountersUrl]);\n\n if (!patient) {\n return null;\n }\n\n const GenderIconComponent = getGenderIcon(patient);\n\n return (\n <Card {...cardProps}>\n <Card.Section h={100} style={{ background }} />\n <ResourceAvatar value={patient} size={80} radius={80} mx=\"auto\" mt={-50} style={{ border: '2px solid white' }} />\n <Text ta=\"center\" fz=\"lg\" fw={500}>\n {formatHumanName(patient.name?.[0] as HumanName)}\n </Text>\n {patient.birthDate && (\n <Text ta=\"center\" fz=\"xs\" c=\"dimmed\">\n {patient.birthDate} ({calculateAgeString(patient.birthDate)})\n </Text>\n )}\n <Paper withBorder p=\"md\" my=\"md\">\n <Group wrap=\"nowrap\" justify=\"space-evenly\">\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <IconUserSquare size={24} color=\"gray\" />\n <Text fz=\"xs\" ta=\"center\" style={{ whiteSpace: 'nowrap' }}>\n Self\n </Text>\n </Flex>\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <IconStethoscope size={24} color=\"gray\" />\n <Text fz=\"xs\" style={{ whiteSpace: 'nowrap' }}>\n {patient?.generalPractitioner?.[0]?.display ?? 'No provider'}\n </Text>\n </Flex>\n {GenderIconComponent && (\n <Flex justify=\"center\" align=\"center\" direction=\"column\" gap={0}>\n <GenderIconComponent size={24} color=\"gray\" />\n <Text fz=\"xs\" style={{ whiteSpace: 'nowrap' }}>\n {patient.gender}\n </Text>\n </Flex>\n )}\n </Group>\n </Paper>\n <Stack gap=\"xs\">\n {links.length > 0 && (\n <>\n {links}\n <Divider />\n </>\n )}\n {medicalData && (\n <>\n <Allergies patient={patient} allergies={medicalData.allergies} />\n <Divider />\n <ProblemList patient={patient} problems={medicalData.problems} />\n <Divider />\n <Medications patient={patient} medicationRequests={medicalData.medicationRequests} />\n <Divider />\n <SexualOrientation patient={patient} sexualOrientation={medicalData.sexualOrientation} />\n <Divider />\n <SmokingStatus patient={patient} smokingStatus={medicalData.smokingStatus} />\n <Divider />\n <Vitals patient={patient} vitals={medicalData.vitals} />\n </>\n )}\n </Stack>\n </Card>\n );\n}\n", "import { Anchor, Box, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { AllergyIntolerance, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { AllergyDialog } from './AllergyDialog';\nimport { ConceptBadge } from './ConceptBadge';\n\nexport interface AllergiesProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly allergies: AllergyIntolerance[];\n}\n\nexport function Allergies(props: AllergiesProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [allergies, setAllergies] = useState<AllergyIntolerance[]>(props.allergies);\n const [opened, { open, close }] = useDisclosure(false);\n const [editAllergy, setEditAllergy] = useState<AllergyIntolerance>();\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Allergies\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditAllergy(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {allergies.length > 0 ? (\n <Box>\n {allergies.map((allergy) => (\n <ConceptBadge\n key={allergy.id}\n resource={allergy}\n onEdit={(a) => {\n setEditAllergy(a);\n open();\n }}\n />\n ))}\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Button, Group, Stack, TextInput } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { AllergyIntolerance, CodeableConcept, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { DateTimeInput } from '../DateTimeInput/DateTimeInput';\nimport { Form } from '../Form/Form';\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<CodeableConcept | undefined>(allergy?.code);\n const [clinicalStatus, setClinicalStatus] = useState<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Badge } from '@mantine/core';\nimport { getDisplayString } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\nimport { IconEdit } from '@tabler/icons-react';\nimport { ReactNode } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { killEvent } from '../utils/dom';\n\nexport interface ConceptBadgeProps<T extends Resource> {\n readonly resource: T;\n readonly onEdit?: (resource: T) => void;\n}\n\nexport function ConceptBadge<T extends Resource = Resource>(props: ConceptBadgeProps<T>): JSX.Element {\n const { resource, onEdit } = props;\n\n let rightSection: ReactNode | undefined = undefined;\n if (onEdit) {\n rightSection = (\n <IconEdit\n aria-label={`Edit ${getDisplayString(resource)}`}\n size={12}\n onClick={(e) => {\n killEvent(e);\n onEdit(resource);\n }}\n />\n );\n }\n\n return (\n <MedplumLink key={resource.id} to={resource}>\n <Badge variant=\"light\" maw=\"100%\" rightSection={rightSection}>\n {getDisplayString(resource)}\n </Badge>\n </MedplumLink>\n );\n}\n", "import { Anchor, Box, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Encounter, MedicationRequest, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { ConceptBadge } from './ConceptBadge';\nimport { MedicationDialog } from './MedicationDialog';\n\nexport interface MedicationsProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly medicationRequests: MedicationRequest[];\n}\n\nexport function Medications(props: MedicationsProps): JSX.Element {\n const medplum = useMedplum();\n const [medicationRequests, setMedicationRequests] = useState<MedicationRequest[]>(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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Medications\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditMedication(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {medicationRequests.length > 0 ? (\n <Box>\n {medicationRequests.map((request) => (\n <ConceptBadge<MedicationRequest>\n key={request.id}\n resource={request}\n onEdit={(mr) => {\n setEditMedication(mr);\n open();\n }}\n />\n ))}\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Alert, Button, Group, Radio, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { CodeableConcept, Encounter, MedicationRequest, Patient } from '@medplum/fhirtypes';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptInput } from '../CodeableConceptInput/CodeableConceptInput';\nimport { Form } from '../Form/Form';\nimport { useMedplumProfile } from '@medplum/react-hooks';\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<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Anchor, Grid, Group, Modal, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Condition, Encounter, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { Fragment, useCallback, useState } from 'react';\nimport { killEvent } from '../utils/dom';\nimport { ConceptBadge } from './ConceptBadge';\nimport { ConditionDialog } from './ConditionDialog';\n\nexport interface ProblemListProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly problems: Condition[];\n}\n\nexport function ProblemList(props: ProblemListProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [problems, setProblems] = useState<Condition[]>(props.problems);\n const [editCondition, setEditCondition] = useState<Condition>();\n const [opened, { open, close }] = useDisclosure(false);\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([...problems, newCondition]);\n }\n setEditCondition(undefined);\n close();\n },\n [medplum, problems, close]\n );\n\n return (\n <>\n <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Problem List\n </Text>\n <Anchor\n component=\"button\"\n onClick={(e) => {\n killEvent(e);\n setEditCondition(undefined);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n {problems.length > 0 ? (\n <Grid gutter=\"xs\">\n {problems.map((problem) => (\n <Fragment key={problem.id}>\n <Grid.Col span={2}>{problem.onsetDateTime?.substring(0, 4)}</Grid.Col>\n <Grid.Col span={10}>\n <ConceptBadge<Condition>\n key={problem.id}\n resource={problem}\n onEdit={(c) => {\n setEditCondition(c);\n open();\n }}\n />\n </Grid.Col>\n </Fragment>\n ))}\n </Grid>\n ) : (\n <Text>(none)</Text>\n )}\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", "import { Button, Group, Stack } from '@mantine/core';\nimport { HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, addProfileToResource, createReference } from '@medplum/core';\nimport { CodeableConcept, Condition, Encounter, Patient } from '@medplum/fhirtypes';\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';\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<CodeableConcept | undefined>(condition?.code);\n const [clinicalStatus, setClinicalStatus] = useState<CodeableConcept | undefined>(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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n );\n}\n", "import { Anchor, Badge, Box, Button, Group, Modal, Radio, Stack, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { HTTP_HL7_ORG, HTTP_TERMINOLOGY_HL7_ORG, LOINC, SNOMED, createReference } from '@medplum/core';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { Form } from '../Form/Form';\nimport { killEvent } from '../utils/dom';\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}\n\nexport function SexualOrientation(props: SexualOrientationProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [sexualOrientation, setSexualOrientation] = useState<Observation | undefined>(props.sexualOrientation);\n const [opened, { open, close }] = useDisclosure(false);\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Sexual Orientation\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Edit\n </Anchor>\n </Group>\n {sexualOrientation?.valueCodeableConcept ? (\n <Box>\n <Badge variant=\"light\">\n <CodeableConceptDisplay value={sexualOrientation.valueCodeableConcept} />\n </Badge>\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { Anchor, Badge, Box, Button, Group, Modal, Radio, Stack, Text } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { HTTP_HL7_ORG, LOINC, SNOMED, createReference } from '@medplum/core';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { CodeableConceptDisplay } from '../CodeableConceptDisplay/CodeableConceptDisplay';\nimport { Form } from '../Form/Form';\nimport { killEvent } from '../utils/dom';\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}\n\nexport function SmokingStatus(props: SmokingStatusProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [smokingStatus, setSmokingStatus] = useState<Observation | undefined>(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(patient),\n encounter: encounter ? createReference(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, patient, encounter, close]\n );\n\n return (\n <>\n <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Smoking Status\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Edit\n </Anchor>\n </Group>\n {smokingStatus?.valueCodeableConcept ? (\n <Box>\n <Badge variant=\"light\">\n <CodeableConceptDisplay value={smokingStatus.valueCodeableConcept} />\n </Badge>\n </Box>\n ) : (\n <Text>(none)</Text>\n )}\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 <Button type=\"submit\">Save</Button>\n </Group>\n </Stack>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { Anchor, Button, Grid, Group, Modal, Stack, Text, Textarea, TextInput } from '@mantine/core';\nimport { useDisclosure } from '@mantine/hooks';\nimport { Encounter, Observation, Patient } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useCallback, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { QuantityDisplay } from '../QuantityDisplay/QuantityDisplay';\nimport { killEvent } from '../utils/dom';\nimport {\n createCompoundObservation,\n createLoincCode,\n createObservation,\n createQuantity,\n getCompoundObservationValue,\n getObservationValue,\n} from './Vitals.utils';\n\ninterface ObservationMeta {\n readonly code: string;\n readonly title: string;\n readonly unit: string;\n}\n\nconst LOINC_CODES: Record<string, ObservationMeta> = {\n bloodPressure: {\n code: '85354-9',\n title: 'Blood Pressure',\n unit: 'mm[Hg]',\n },\n heartRate: {\n code: '8867-4',\n title: 'Heart Rate',\n unit: '/min',\n },\n bodyTemperature: {\n code: '8310-5',\n title: 'Body Temperature',\n unit: 'Cel',\n },\n respiratoryRate: {\n code: '9279-1',\n title: 'Respiratory Rate',\n unit: '/min',\n },\n height: {\n code: '8302-2',\n title: 'height',\n unit: 'cm',\n },\n weight: {\n code: '29463-7',\n title: 'weight',\n unit: 'kg',\n },\n bmi: {\n code: '39156-5',\n title: 'BMI',\n unit: 'kg/m2',\n },\n oxygen: {\n code: '2708-6',\n title: 'Oxygen',\n unit: '%',\n },\n headCircumference: {\n code: '9843-4',\n title: 'Head Circumference',\n unit: 'cm',\n },\n};\n\nconst SYSTOLIC = '8480-6';\nconst DIASTOLIC = '8462-4';\n\nexport interface VitalsProps {\n readonly patient: Patient;\n readonly encounter?: Encounter;\n readonly vitals: Observation[];\n}\n\nexport function Vitals(props: VitalsProps): JSX.Element {\n const medplum = useMedplum();\n const { patient, encounter } = props;\n const [vitals, setVitals] = useState<Observation[]>(props.vitals);\n const [opened, { open, close }] = useDisclosure(false);\n\n const handleSubmit = useCallback(\n (formData: Record<string, string>) => {\n const newObservations = Object.entries(LOINC_CODES)\n .map(([name, meta]) => {\n if (name === 'bloodPressure') {\n return createCompoundObservation(patient, encounter, meta.code, meta.title, [\n {\n code: createLoincCode(SYSTOLIC, 'Systolic blood pressure'),\n valueQuantity: createQuantity(parseFloat(formData['systolic']), 'mm[Hg]'),\n },\n {\n code: createLoincCode(DIASTOLIC, 'Diastolic blood pressure'),\n valueQuantity: createQuantity(parseFloat(formData['diastolic']), 'mm[Hg]'),\n },\n ]);\n }\n return createObservation(\n patient,\n encounter,\n meta.code,\n meta.title,\n createQuantity(parseFloat(formData[name]), meta.unit)\n );\n })\n .filter(Boolean) as Observation[];\n\n // Execute all create requests in parallel to take advantage of autobatching\n Promise.all(newObservations.map((obs) => medplum.createResource<Observation>(obs)))\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 <Group justify=\"space-between\">\n <Text fz=\"md\" fw={700}>\n Vitals\n </Text>\n <Anchor\n href=\"#\"\n onClick={(e) => {\n killEvent(e);\n open();\n }}\n >\n + Add\n </Anchor>\n </Group>\n <Grid>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BP Sys\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getCompoundObservationValue(vitals, LOINC_CODES.bloodPressure.code, SYSTOLIC)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BP Dias\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getCompoundObservationValue(vitals, LOINC_CODES.bloodPressure.code, DIASTOLIC)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n HR\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.heartRate.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Temp\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.bodyTemperature.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n RR\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.respiratoryRate.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Height\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.height.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n Weight\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.weight.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n BMI\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.bmi.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n O2\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.oxygen.code)} />\n </Grid.Col>\n <Grid.Col span={3} ta=\"right\" c=\"dimmed\">\n HC\n </Grid.Col>\n <Grid.Col span={3}>\n <QuantityDisplay value={getObservationValue(vitals, LOINC_CODES.headCircumference.code)} />\n </Grid.Col>\n </Grid>\n <Modal opened={opened} onClose={close} title=\"Add Vitals\">\n <Form onSubmit={handleSubmit}>\n <Stack>\n <Group grow>\n <TextInput name=\"systolic\" label=\"BP Sys\" data-autofocus={true} autoFocus />\n <TextInput name=\"diastolic\" label=\"BP Dias\" />\n </Group>\n <Group grow>\n <TextInput name=\"heartRate\" label=\"HR\" />\n <TextInput name=\"bodyTemperature\" label=\"Temp\" />\n </Group>\n <Group grow>\n <TextInput name=\"respiratoryRate\" label=\"RR\" />\n <TextInput name=\"height\" label=\"height\" />\n </Group>\n <Group grow>\n <TextInput name=\"weight\" label=\"Wt\" />\n <TextInput name=\"bmi\" label=\"BMI\" />\n </Group>\n <Group grow>\n <TextInput name=\"oxygen\" label=\"O2\" />\n <TextInput name=\"headCircumference\" label=\"HC\" />\n </Group>\n <Textarea name=\"notes\" label=\"Notes\" />\n </Stack>\n <Group justify=\"flex-end\" gap={4} mt=\"md\">\n <Button type=\"submit\">Save</Button>\n </Group>\n </Form>\n </Modal>\n </>\n );\n}\n", "import { LOINC, UCUM, createReference } from '@medplum/core';\nimport { CodeableConcept, Encounter, Observation, ObservationComponent, Patient, Quantity } from '@medplum/fhirtypes';\n\nexport function getObservationValue(observations: Observation[], code: string): Quantity | undefined {\n const observation = observations.find((o) => o.code?.coding?.[0].code === code);\n return observation?.valueQuantity;\n}\n\nexport function getCompoundObservationValue(\n observations: Observation[],\n code: string,\n innerCode: string\n): Quantity | undefined {\n const observation = observations.find((o) => o.code?.coding?.[0].code === code);\n const component = observation?.component?.find((c) => c.code?.coding?.[0].code === innerCode);\n return component?.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 && !isNaN(value) && isFinite(value);\n}\n", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Patient, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { useCallback } from 'react';\nimport { ResourceTimeline, ResourceTimelineProps } 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('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", "import { Anchor, Button, NativeSelect, Stack, TextInput } from '@mantine/core';\nimport { InternalSchemaElement, getReferenceString } from '@medplum/core';\nimport { PlanDefinition, PlanDefinitionAction, Reference, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport cx from 'clsx';\nimport { MouseEvent, SyntheticEvent, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { FormSection } from '../FormSection/FormSection';\nimport { ReferenceDisplay } from '../ReferenceDisplay/ReferenceDisplay';\nimport { setPropertyValue } from '../ResourceForm/ResourceForm.utils';\nimport { ResourceInput } from '../ResourceInput/ResourceInput';\nimport { ResourcePropertyDisplay } from '../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\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 const valueRef = useRef<PlanDefinition>();\n valueRef.current = value;\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({\n ...valueRef.current,\n [property]: newValue,\n } as PlanDefinition);\n }\n\n return (\n <div>\n <Form testid=\"questionnaire-form\" onSubmit={() => props.onSubmit(value)}>\n <TextInput\n label=\"Plan Title\"\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 <Button type=\"submit\">Save</Button>\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 const actionsRef = useRef<PlanDefinitionAction[]>();\n actionsRef.current = props.actions;\n\n function changeAction(changedAction: PlanDefinitionAction): void {\n props.onChange(\n (actionsRef.current as PlanDefinition[]).map((i) => (i.id === changedAction.id ? changedAction : i))\n );\n }\n\n function addAction(addedAction: PlanDefinitionAction): void {\n props.onChange([...(actionsRef.current as PlanDefinition[]), addedAction]);\n props.setSelectedKey(addedAction.id);\n }\n\n function removeAction(removedAction: PlanDefinitionAction): void {\n props.onChange((actionsRef.current as PlanDefinition[]).filter((i) => i !== removedAction));\n }\n\n return (\n <div className={classes.section}>\n {props.actions.map((action) => (\n <div key={action.id}>\n <ActionBuilder\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 </div>\n ))}\n <div className={classes.bottomActions}>\n <Anchor\n href=\"#\"\n onClick={(e: MouseEvent) => {\n killEvent(e);\n addAction({ id: generateId() });\n }}\n >\n Add action\n </Anchor>\n </div>\n </div>\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 const actionType = getInitialActionType(action);\n const editing = props.selectedKey === props.action.id;\n const hovering = props.hoverKey === props.action.id;\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 const className = cx(classes.section, {\n [classes.editing]: editing,\n [classes.hovering]: hovering && !editing,\n });\n\n return (\n <div data-testid={action.id} className={className} onClick={onClick} onMouseOver={onHover} onFocus={onHover}>\n {editing ? (\n <ActionEditor\n action={action}\n actionType={actionType}\n onChange={props.onChange}\n selectedKey={props.selectedKey}\n setSelectedKey={props.setSelectedKey}\n hoverKey={props.hoverKey}\n setHoverKey={props.setHoverKey}\n onRemove={props.onRemove}\n />\n ) : (\n <ActionDisplay action={action} actionType={actionType} />\n )}\n <div className={classes.bottomActions}>\n <Anchor\n href=\"#\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n props.onRemove();\n }}\n >\n Remove\n </Anchor>\n </div>\n </div>\n );\n}\n\nconst timingProperty: InternalSchemaElement = {\n path: 'PlanDefinition.action.timing[x]',\n min: 0,\n max: 1,\n description: '',\n isArray: false,\n constraints: [],\n type: ['dateTime', 'Period', 'Range', 'Timing'].map((t) => ({ code: t })),\n};\n\ninterface ActionDisplayProps {\n readonly action: PlanDefinitionAction;\n readonly actionType: string | undefined;\n}\n\nfunction ActionDisplay(props: ActionDisplayProps): JSX.Element {\n const { action, actionType } = props;\n const [propertyValue, propertyType] = getActionTiming(action);\n return (\n <div>\n <div>\n {action.title || 'Untitled'} {actionType && `(${actionType})`}\n </div>\n {action.definitionCanonical && (\n <div>\n <ReferenceDisplay value={{ reference: action.definitionCanonical }} />\n </div>\n )}\n {propertyValue && (\n <div>\n <ResourcePropertyDisplay property={timingProperty} propertyType={propertyType} value={propertyValue} />\n </div>\n )}\n </div>\n );\n}\n\ninterface ActionEditorProps {\n readonly action: PlanDefinitionAction;\n readonly actionType: string | undefined;\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 ActionEditor(props: ActionEditorProps): JSX.Element {\n const { action } = props;\n const [actionType, setActionType] = useState<string | undefined>(props.actionType);\n\n function changeProperty(property: string, value: any): void {\n props.onChange({\n ...action,\n [property]: value,\n } as PlanDefinitionAction);\n }\n\n return (\n <Stack gap=\"xl\">\n <TextInput\n name={`actionTitle-${action.id}`}\n label=\"Title\"\n defaultValue={action.title}\n onChange={(e) => changeProperty('title', e.currentTarget.value)}\n />\n <TextInput\n name={`actionDescription-${action.id}`}\n label=\"Description\"\n defaultValue={action.description}\n onChange={(e) => changeProperty('description', e.currentTarget.value)}\n />\n <NativeSelect\n label=\"Type of Action\"\n description=\"The type of the action to be performed.\"\n name={`actionType-${action.id}`}\n defaultValue={actionType}\n onChange={(e) => setActionType(e.currentTarget.value)}\n data={['', 'appointment', 'lab', 'questionnaire', 'task']}\n />\n {action.action && action.action.length > 0 && (\n <ActionArrayBuilder\n actions={action.action}\n selectedKey={props.selectedKey}\n setSelectedKey={props.setSelectedKey}\n hoverKey={props.hoverKey}\n setHoverKey={props.setHoverKey}\n onChange={(x) => changeProperty('action', x)}\n />\n )}\n {(() => {\n switch (actionType) {\n case 'appointment':\n return (\n <ActionResourceTypeBuilder\n title=\"Appointment\"\n description=\"The subject must schedule an appointment from the schedule.\"\n resourceType=\"Schedule\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'lab':\n return (\n <ActionResourceTypeBuilder\n title=\"Lab\"\n description=\"The subject must complete the following lab panel.\"\n resourceType=\"ActivityDefinition\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'questionnaire':\n return (\n <ActionResourceTypeBuilder\n title=\"Questionnaire\"\n description=\"The subject must complete the selected questionnaire.\"\n resourceType=\"Questionnaire\"\n action={action}\n onChange={props.onChange}\n />\n );\n case 'task':\n return (\n <ActionResourceTypeBuilder\n title=\"Task\"\n description=\"The subject must complete the following task.\"\n resourceType=\"ActivityDefinition\"\n action={action}\n onChange={props.onChange}\n />\n );\n default:\n return null;\n }\n })()}\n <FormSection title=\"Timing\" description=\"When the action should take place.\">\n <ActionTimingInput name={'timing-' + action.id} action={action} onChange={props.onChange} />\n </FormSection>\n </Stack>\n );\n}\n\ninterface ActionResourceTypeBuilderProps {\n readonly action: PlanDefinitionAction;\n readonly title: string;\n readonly description: string;\n readonly resourceType: ResourceType;\n readonly onChange: (action: PlanDefinitionAction) => void;\n}\n\nfunction ActionResourceTypeBuilder(props: ActionResourceTypeBuilderProps): JSX.Element {\n const { id, definitionCanonical } = props.action;\n const reference = definitionCanonical?.startsWith(props.resourceType + '/')\n ? { reference: definitionCanonical }\n : undefined;\n return (\n <ResourceInput\n name={id as string}\n resourceType={props.resourceType}\n defaultValue={reference}\n loadOnFocus={true}\n onChange={(newValue) => {\n if (newValue) {\n props.onChange({ ...props.action, definitionCanonical: getReferenceString(newValue) });\n } else {\n props.onChange({ ...props.action, definitionCanonical: undefined });\n }\n }}\n />\n );\n}\n\ninterface ActionTimingInputProps {\n readonly name: string;\n readonly action: PlanDefinitionAction;\n readonly onChange: (action: PlanDefinitionAction) => void;\n}\n\nfunction ActionTimingInput(props: ActionTimingInputProps): JSX.Element {\n const value = props.action;\n const key = 'timing';\n const [propertyValue, propertyType] = getActionTiming(value);\n return (\n <ResourcePropertyInput\n property={timingProperty}\n name=\"timing[x]\"\n path=\"PlanDefinition.timing[x]\"\n defaultValue={propertyValue}\n defaultPropertyType={propertyType}\n onChange={(newValue: any, propName?: string) => {\n props.onChange(setPropertyValue(value, key, propName ?? key, timingProperty, newValue));\n }}\n outcome={undefined}\n />\n );\n}\n\nfunction getInitialActionType(action: PlanDefinitionAction): string | undefined {\n if (action.definitionCanonical?.startsWith('Schedule')) {\n return 'appointment';\n }\n\n if (action.definitionCanonical?.startsWith('Questionnaire/')) {\n return 'questionnaire';\n }\n\n if (action.definitionCanonical?.startsWith('ActivityDefinition/')) {\n return 'task';\n }\n\n return undefined;\n}\n\nfunction getActionTiming(action: PlanDefinitionAction): [any, string] {\n return getValueAndType({ type: 'PlanDefinitionAction', value: action }, 'timing');\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 = parseInt(existing.substring(3), 10);\n if (!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 } as PlanDefinition;\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", "\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}\n\n.bottomActions {\n position: absolute;\n right: 4px;\n bottom: 0;\n font-size: var(--mantine-font-size-xs);\n\n & a {\n margin-left: 8px;\n }\n}", "import { Anchor, Box, Button, Group, NativeSelect, Space, Textarea, TextInput, Title } from '@mantine/core';\nimport { getElementDefinition, isResource as isResourceType } from '@medplum/core';\nimport {\n Extension,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n Reference,\n ResourceType,\n} from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconArrowDown, IconArrowUp } from '@tabler/icons-react';\nimport cx from 'clsx';\nimport { MouseEvent, SyntheticEvent, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport { QuestionnaireFormItem } from '../QuestionnaireForm/QuestionnaireFormItem/QuestionnaireFormItem';\nimport { getValueAndType } from '../ResourcePropertyDisplay/ResourcePropertyDisplay.utils';\nimport { ResourcePropertyInput } from '../ResourcePropertyInput/ResourcePropertyInput';\nimport { ResourceTypeInput } from '../ResourceTypeInput/ResourceTypeInput';\nimport { killEvent } from '../utils/dom';\nimport {\n getQuestionnaireItemReferenceTargetTypes,\n isChoiceQuestion,\n QuestionnaireItemType,\n setQuestionnaireItemReferenceTargetTypes,\n} from '../utils/questionnaire';\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 <Button type=\"submit\">Save</Button>\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<T>();\n itemRef.current = props.item;\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 as T;\n props.onChange({\n ...curr,\n item: curr.item?.map((i) => (i.id === changedItem.id ? changedItem : i)),\n } as T);\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 } as T);\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\n item={item}\n index={0}\n onChange={() => undefined}\n response={{ linkId: item.linkId }}\n />\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 } as QuestionnaireItem);\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 } as QuestionnaireItem,\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 } as Questionnaire;\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, parseInt(item.id.substring(3), 10) + 1);\n }\n if (item.linkId?.match(/^q\\d+$/)) {\n nextLinkId = Math.max(nextLinkId, 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: 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl',\n valueCodeableConcept: {\n coding: [\n {\n system: 'http://hl7.org/fhir/questionnaire-item-control',\n code: 'page',\n },\n ],\n },\n } as Extension,\n ],\n } as QuestionnaireItem;\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", "import { Checkbox, ComboboxItem, Group, MultiSelect, NativeSelect, Radio, Textarea, TextInput } from '@mantine/core';\nimport {\n capitalize,\n deepEquals,\n formatCoding,\n getElementDefinition,\n HTTP_HL7_ORG,\n stringify,\n TypedValue,\n typedValueToString,\n} from '@medplum/core';\nimport {\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n QuestionnaireItemInitial,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n} from '@medplum/fhirtypes';\nimport { ChangeEvent, useContext } from 'react';\nimport { AttachmentInput } from '../../AttachmentInput/AttachmentInput';\nimport { CheckboxFormSection } from '../../CheckboxFormSection/CheckboxFormSection';\nimport { CodingInput } from '../../CodingInput/CodingInput';\nimport { DateTimeInput } from '../../DateTimeInput/DateTimeInput';\nimport { QuantityInput } from '../../QuantityInput/QuantityInput';\nimport { ReferenceInput } from '../../ReferenceInput/ReferenceInput';\nimport { ResourcePropertyDisplay } from '../../ResourcePropertyDisplay/ResourcePropertyDisplay';\nimport {\n getItemAnswerOptionValue,\n getItemInitialValue,\n getNewMultiSelectValues,\n getQuestionnaireItemReferenceFilter,\n getQuestionnaireItemReferenceTargetTypes,\n QuestionnaireItemType,\n} from '../../utils/questionnaire';\nimport { QuestionnaireFormContext } from '../QuestionnaireForm.context';\n\nexport interface QuestionnaireFormItemProps {\n readonly item: QuestionnaireItem;\n readonly index: number;\n readonly response: QuestionnaireResponseItem;\n readonly onChange: (newResponseItem: QuestionnaireResponseItem) => void;\n}\n\nexport function QuestionnaireFormItem(props: QuestionnaireFormItemProps): JSX.Element | null {\n const context = useContext(QuestionnaireFormContext);\n const item = props.item;\n const response = props.response;\n\n function onChangeAnswer(\n newResponseAnswer: QuestionnaireResponseItemAnswer | QuestionnaireResponseItemAnswer[]\n ): void {\n let updatedAnswers: QuestionnaireResponseItemAnswer[];\n if (Array.isArray(newResponseAnswer)) {\n // It's a multi-select case, so use the array directly.\n updatedAnswers = newResponseAnswer;\n } else if (props.index >= (props.response?.answer?.length ?? 0)) {\n // if adding a new answer\n updatedAnswers = (props.response?.answer ?? []).concat([newResponseAnswer]);\n } else {\n // if updating an existing answer\n const newAnswers = (props.response?.answer ?? []).map((a, idx) =>\n idx === props.index ? newResponseAnswer : a\n ) as QuestionnaireResponseItemAnswer[];\n updatedAnswers = newAnswers ?? [];\n }\n props.onChange({\n id: response?.id,\n linkId: response?.linkId,\n text: item.text,\n answer: updatedAnswers,\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 const initial = item.initial && item.initial.length > 0 ? item.initial[0] : undefined;\n const defaultValue = getCurrentAnswer(response, props.index) ?? getItemInitialValue(initial);\n\n switch (type) {\n case QuestionnaireItemType.display:\n return <p key={props.item.linkId}>{props.item.text}</p>;\n case QuestionnaireItemType.boolean:\n return (\n <CheckboxFormSection key={props.item.linkId} title={props.item.text} htmlFor={props.item.linkId}>\n <Checkbox\n id={props.item.linkId}\n name={props.item.linkId}\n defaultChecked={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueBoolean: e.currentTarget.checked })}\n />\n </CheckboxFormSection>\n );\n case QuestionnaireItemType.decimal:\n return (\n <TextInput\n type=\"number\"\n step=\"any\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueDecimal: e.currentTarget.valueAsNumber })}\n />\n );\n case QuestionnaireItemType.integer:\n return (\n <TextInput\n type=\"number\"\n step={1}\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueInteger: e.currentTarget.valueAsNumber })}\n />\n );\n case QuestionnaireItemType.date:\n return (\n <TextInput\n type=\"date\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueDate: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.dateTime:\n return (\n <DateTimeInput\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(newValue: string) => onChangeAnswer({ valueDateTime: newValue })}\n />\n );\n case QuestionnaireItemType.time:\n return (\n <TextInput\n type=\"time\"\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueTime: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.string:\n case QuestionnaireItemType.url:\n return (\n <TextInput\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueString: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.text:\n return (\n <Textarea\n id={name}\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(e) => onChangeAnswer({ valueString: e.currentTarget.value })}\n />\n );\n case QuestionnaireItemType.attachment:\n return (\n <Group py={4}>\n <AttachmentInput\n path=\"\"\n name={name}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueAttachment: newValue })}\n />\n </Group>\n );\n case QuestionnaireItemType.reference:\n return (\n <ReferenceInput\n name={name}\n required={item.required}\n targetTypes={getQuestionnaireItemReferenceTargetTypes(item)}\n searchCriteria={getQuestionnaireItemReferenceFilter(item, context.subject, context.encounter)}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueReference: newValue })}\n />\n );\n case QuestionnaireItemType.quantity:\n return (\n <QuantityInput\n path=\"\"\n name={name}\n required={item.required}\n defaultValue={defaultValue?.value}\n onChange={(newValue) => onChangeAnswer({ valueQuantity: newValue })}\n disableWheel\n />\n );\n case QuestionnaireItemType.choice:\n case QuestionnaireItemType.openChoice:\n if (isDropDownChoice(item) && !item.answerValueSet) {\n return (\n <QuestionnaireChoiceDropDownInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n } else if (isMultiSelectChoice(item) && !item.answerValueSet) {\n return (\n <QuestionnaireMultiSelectInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n } else {\n return (\n <QuestionnaireChoiceSetInput\n name={name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={(e) => onChangeAnswer(e)}\n />\n );\n }\n default:\n return null;\n }\n}\n\ninterface QuestionnaireChoiceInputProps {\n readonly name: string;\n readonly item: QuestionnaireItem;\n readonly initial: QuestionnaireItemInitial | undefined;\n readonly response: QuestionnaireResponseItem;\n readonly onChangeAnswer: (\n newResponseAnswer: QuestionnaireResponseItemAnswer | QuestionnaireResponseItemAnswer[]\n ) => void;\n}\n\nfunction QuestionnaireChoiceDropDownInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, response } = props;\n\n if (!item.answerOption?.length) {\n return <NoAnswerDisplay />;\n }\n\n const initialValue = getItemInitialValue(initial);\n\n const data = [''];\n\n for (const option of item.answerOption) {\n const optionValue = getItemAnswerOptionValue(option);\n data.push(typedValueToString(optionValue) as string);\n }\n\n const defaultValue = getCurrentAnswer(response) ?? initialValue;\n\n if (item.repeats) {\n const { propertyName, data } = formatSelectData(props.item);\n const currentAnswer = getCurrentMultiSelectAnswer(response);\n\n return (\n <MultiSelect\n data={data}\n placeholder=\"Select items\"\n searchable\n defaultValue={currentAnswer || [typedValueToString(initialValue)]}\n onChange={(selected) => {\n const values = getNewMultiSelectValues(selected, propertyName, item);\n props.onChangeAnswer(values);\n }}\n />\n );\n }\n\n return (\n <NativeSelect\n id={name}\n name={name}\n onChange={(e: ChangeEvent<HTMLSelectElement>) => {\n const index = e.currentTarget.selectedIndex;\n if (index === 0) {\n props.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 props.onChangeAnswer({ [propertyName]: optionValue.value });\n }}\n defaultValue={formatCoding(defaultValue?.value) || defaultValue?.value}\n data={data}\n />\n );\n}\n\nfunction QuestionnaireMultiSelectInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { item, initial, response } = props;\n\n if (!item.answerOption?.length) {\n return <NoAnswerDisplay />;\n }\n\n const initialValue = getItemInitialValue(initial);\n const { propertyName, data } = formatSelectData(props.item);\n const currentAnswer = getCurrentMultiSelectAnswer(response);\n\n return (\n <MultiSelect\n data={data}\n placeholder=\"Select items\"\n searchable\n defaultValue={currentAnswer || [typedValueToString(initialValue)]}\n onChange={(selected) => {\n const values = getNewMultiSelectValues(selected, propertyName, item);\n props.onChangeAnswer(values);\n }}\n />\n );\n}\n\nfunction QuestionnaireChoiceSetInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, onChangeAnswer, response } = props;\n\n if (!item.answerOption?.length && !item.answerValueSet) {\n return <NoAnswerDisplay />;\n }\n\n if (item.answerValueSet) {\n return (\n <CodingInput\n path=\"\"\n name={name}\n binding={item.answerValueSet}\n onChange={(code) => onChangeAnswer({ valueCoding: code })}\n creatable={item.type === QuestionnaireItemType.openChoice}\n />\n );\n }\n return (\n <QuestionnaireChoiceRadioInput\n name={response?.id ?? name}\n item={item}\n initial={initial}\n response={response}\n onChangeAnswer={onChangeAnswer}\n />\n );\n}\n\nfunction QuestionnaireChoiceRadioInput(props: QuestionnaireChoiceInputProps): JSX.Element {\n const { name, item, initial, onChangeAnswer, response } = props;\n const valueElementDefinition = getElementDefinition('QuestionnaireItemAnswerOption', 'value[x]');\n const initialValue = getItemInitialValue(initial);\n\n const options: [string, TypedValue][] = [];\n let defaultValue = undefined;\n if (item.answerOption) {\n for (let i = 0; i < item.answerOption.length; i++) {\n const option = item.answerOption[i];\n const optionName = `${name}-option-${i}`;\n const optionValue = getItemAnswerOptionValue(option);\n\n if (!optionValue?.value) {\n continue;\n }\n\n if (initialValue && stringify(optionValue) === stringify(initialValue)) {\n defaultValue = optionName;\n }\n options.push([optionName, optionValue]);\n }\n }\n\n const defaultAnswer = getCurrentAnswer(response);\n const answerLinkId = getCurrentRadioAnswer(options, defaultAnswer);\n\n return (\n <Radio.Group\n name={name}\n value={answerLinkId ?? defaultValue}\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 {options.map(([optionName, optionValue]) => (\n <Radio\n key={optionName}\n id={optionName}\n value={optionName}\n py={4}\n label={\n <ResourcePropertyDisplay\n property={valueElementDefinition}\n propertyType={optionValue.type}\n value={optionValue.value}\n />\n }\n />\n ))}\n </Radio.Group>\n );\n}\n\nfunction NoAnswerDisplay(): JSX.Element {\n return <TextInput disabled placeholder=\"No Answers Defined\" />;\n}\n\nfunction getCurrentAnswer(response: QuestionnaireResponseItem, index: number = 0): TypedValue {\n const results = response.answer;\n return getItemAnswerOptionValue(results?.[index] ?? {});\n}\n\nfunction getCurrentMultiSelectAnswer(response: QuestionnaireResponseItem): 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);\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\nfunction isDropDownChoice(item: QuestionnaireItem): boolean {\n return !!item.extension?.some(\n (e) =>\n e.url === 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl' &&\n e.valueCodeableConcept?.coding?.[0]?.code === 'drop-down'\n );\n}\n\nfunction isMultiSelectChoice(item: QuestionnaireItem): boolean {\n return !!item.extension?.some(\n (e) =>\n e.url === HTTP_HL7_ORG + '/fhir/StructureDefinition/questionnaire-itemControl' &&\n e.valueCodeableConcept?.coding?.[0]?.code === 'multi-select'\n );\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", "import {\n HTTP_HL7_ORG,\n PropertyType,\n TypedValue,\n deepClone,\n evalFhirPathTyped,\n getExtension,\n getReferenceString,\n getTypedPropertyValueWithoutSchema,\n splitN,\n toJsBoolean,\n toTypedValue,\n typedValueToString,\n} from '@medplum/core';\nimport {\n Encounter,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireItemAnswerOption,\n QuestionnaireItemEnableWhen,\n QuestionnaireItemInitial,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n QuestionnaireResponseItemAnswer,\n Reference,\n ResourceType,\n} from '@medplum/fhirtypes';\n\nexport enum QuestionnaireItemType {\n group = 'group',\n display = 'display',\n question = 'question',\n boolean = 'boolean',\n decimal = 'decimal',\n integer = 'integer',\n date = 'date',\n dateTime = 'dateTime',\n time = 'time',\n string = 'string',\n text = 'text',\n url = 'url',\n choice = 'choice',\n openChoice = 'open-choice',\n attachment = 'attachment',\n reference = 'reference',\n quantity = 'quantity',\n}\n\nexport function isChoiceQuestion(item: QuestionnaireItem): boolean {\n return item.type === 'choice' || item.type === 'open-choice';\n}\n\nexport function isQuestionEnabled(\n item: QuestionnaireItem,\n questionnaireResponse: QuestionnaireResponse | undefined\n): boolean {\n const extension = getExtension(\n item,\n HTTP_HL7_ORG + '/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-enableWhenExpression'\n );\n if (questionnaireResponse && extension) {\n const expression = extension.valueExpression?.expression;\n if (expression) {\n const value = toTypedValue(questionnaireResponse);\n const result = evalFhirPathTyped(expression, [value], { '%resource': value });\n return toJsBoolean(result);\n }\n }\n\n if (!item.enableWhen) {\n return true;\n }\n\n const enableBehavior = item.enableBehavior ?? 'any';\n for (const enableWhen of item.enableWhen) {\n const actualAnswers = getByLinkId(questionnaireResponse?.item, enableWhen.question as string);\n\n if (enableWhen.operator === 'exists' && !enableWhen.answerBoolean && !actualAnswers?.length) {\n if (enableBehavior === 'any') {\n return true;\n } else {\n continue;\n }\n }\n const { anyMatch, allMatch } = checkAnswers(enableWhen, actualAnswers, enableBehavior);\n\n if (enableBehavior === 'any' && anyMatch) {\n return true;\n }\n if (enableBehavior === 'all' && !allMatch) {\n return false;\n }\n }\n\n return enableBehavior !== 'any';\n}\n\nexport function evaluateCalculatedExpressionsInQuestionnaire(\n items: QuestionnaireItem[],\n response: QuestionnaireResponse | undefined\n): QuestionnaireResponseItem[] {\n return items\n .map((item): QuestionnaireResponseItem | null => {\n if (item.item) {\n return {\n ...item,\n item: evaluateCalculatedExpressionsInQuestionnaire(item.item, response),\n };\n } else {\n const calculatedValue = evaluateCalculatedExpression(item, response);\n if (!calculatedValue) {\n return null;\n }\n\n const answer = typedValueToResponseItem(item, calculatedValue);\n\n if (!answer) {\n return null;\n }\n\n return {\n id: item?.id,\n linkId: item?.linkId,\n text: item.text,\n answer: [answer],\n };\n }\n })\n .filter((item): item is QuestionnaireResponseItem => item !== null);\n}\n\nexport function typedValueToResponseItem(\n item: QuestionnaireItem,\n value: TypedValue\n): QuestionnaireResponseItemAnswer | undefined {\n if (!item.type) {\n return undefined;\n }\n\n switch (item.type) {\n case QuestionnaireItemType.boolean:\n return value.type === PropertyType.boolean ? { valueBoolean: value.value } : undefined;\n case QuestionnaireItemType.date:\n return value.type === PropertyType.date ? { valueDate: value.value } : undefined;\n case QuestionnaireItemType.dateTime:\n return value.type === PropertyType.dateTime ? { valueDateTime: value.value } : undefined;\n case QuestionnaireItemType.time:\n return value.type === PropertyType.time ? { valueTime: value.value } : undefined;\n case QuestionnaireItemType.url:\n return value.type === PropertyType.url ? { valueString: value.value } : undefined;\n case QuestionnaireItemType.text:\n return value.type === PropertyType.string ? { valueString: value.value } : undefined;\n case QuestionnaireItemType.attachment:\n return value.type === PropertyType.Attachment ? { valueAttachment: value.value } : undefined;\n case QuestionnaireItemType.reference:\n return value.type === PropertyType.Reference ? { valueReference: value.value } : undefined;\n case QuestionnaireItemType.quantity:\n return { valueQuantity: value.value };\n case QuestionnaireItemType.decimal:\n return { valueDecimal: value.value };\n case QuestionnaireItemType.integer:\n return { valueInteger: value.value };\n case QuestionnaireItemType.string:\n return { valueString: value.value };\n default:\n return undefined;\n }\n}\n\nfunction evaluateCalculatedExpression(\n item: QuestionnaireItem,\n response: QuestionnaireResponse | undefined\n): TypedValue | undefined {\n if (!response) {\n return undefined;\n }\n\n const extension = getExtension(\n item,\n HTTP_HL7_ORG + '/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-calculatedExpression'\n );\n\n if (extension) {\n const expression = extension.valueExpression?.expression;\n if (expression) {\n const value = toTypedValue(response);\n const result = evalFhirPathTyped(expression, [value], { '%resource': value });\n return result.length !== 0 ? result[0] : undefined;\n }\n }\n return undefined;\n}\n\nexport function mergeUpdatedItems(\n mergedItems: QuestionnaireResponseItem[],\n updatedItems: QuestionnaireResponseItem[]\n): QuestionnaireResponseItem[] {\n return mergedItems.map((mergedItem) => {\n const updatedItem = updatedItems.find((updated) => updated.linkId === mergedItem.linkId);\n\n // Usually fields with calculated expressions would be readOnly in the case where it allows foe manual updates.\n // It would get replaced with content from calcultaed expresion.\n if (updatedItem) {\n return {\n ...mergedItem,\n item: updatedItem.item ? mergeUpdatedItems(mergedItem.item || [], updatedItem.item) : mergedItem.item,\n answer: updatedItem.answer || mergedItem.answer,\n };\n }\n return mergedItem;\n });\n}\n\nexport function getNewMultiSelectValues(\n selected: string[],\n propertyName: string,\n item: QuestionnaireItem\n): QuestionnaireResponseItemAnswer[] {\n const result: QuestionnaireResponseItemAnswer[] = [];\n\n for (const selectedStr of selected) {\n const option = item.answerOption?.find(\n (candidate) => typedValueToString(getItemAnswerOptionValue(candidate)) === selectedStr\n );\n if (option) {\n const optionValue = getItemAnswerOptionValue(option);\n if (optionValue) {\n result.push({ [propertyName]: optionValue.value });\n }\n }\n }\n\n return result;\n}\n\nfunction getByLinkId(\n responseItems: QuestionnaireResponseItem[] | undefined,\n linkId: string\n): QuestionnaireResponseItemAnswer[] | undefined {\n if (!responseItems) {\n return undefined;\n }\n\n for (const response of responseItems) {\n if (response.linkId === linkId) {\n return response.answer;\n }\n if (response.item) {\n const nestedAnswer = getByLinkId(response.item, linkId);\n if (nestedAnswer) {\n return nestedAnswer;\n }\n }\n }\n\n return undefined;\n}\n\nfunction evaluateMatch(actualAnswer: TypedValue | undefined, expectedAnswer: TypedValue, operator?: string): boolean {\n // We handle exists separately since its so different in terms of comparisons than the other mathematical operators\n if (operator === 'exists') {\n // if actualAnswer is not undefined, then exists: true passes\n // if actualAnswer is undefined, then exists: false passes\n return !!actualAnswer === expectedAnswer.value;\n } else if (!actualAnswer) {\n return false;\n } else {\n // `=` and `!=` should be treated as the FHIRPath `~` and `!~`\n // All other operators should be unmodified\n const fhirPathOperator = operator === '=' || operator === '!=' ? operator?.replace('=', '~') : operator;\n const [{ value }] = evalFhirPathTyped(`%actualAnswer ${fhirPathOperator} %expectedAnswer`, [actualAnswer], {\n '%actualAnswer': actualAnswer,\n '%expectedAnswer': expectedAnswer,\n });\n return value;\n }\n}\n\nfunction checkAnswers(\n enableWhen: QuestionnaireItemEnableWhen,\n answers: QuestionnaireResponseItemAnswer[] | undefined,\n enableBehavior: 'any' | 'all'\n): { anyMatch: boolean; allMatch: boolean } {\n const actualAnswers = answers || [];\n const expectedAnswer = getItemEnableWhenValueAnswer(enableWhen);\n\n let anyMatch = false;\n let allMatch = true;\n\n for (const actualAnswerValue of actualAnswers) {\n const actualAnswer = getResponseItemAnswerValue(actualAnswerValue);\n const { operator } = enableWhen;\n const match = evaluateMatch(actualAnswer, expectedAnswer, operator);\n if (match) {\n anyMatch = true;\n } else {\n allMatch = false;\n }\n\n if (enableBehavior === 'any' && anyMatch) {\n break;\n }\n }\n\n return { anyMatch, allMatch };\n}\n\nexport function getQuestionnaireItemReferenceTargetTypes(item: QuestionnaireItem): ResourceType[] | undefined {\n const extension = getExtension(item, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource');\n if (!extension) {\n return undefined;\n }\n if (extension.valueCode !== undefined) {\n return [extension.valueCode] as ResourceType[];\n }\n if (extension.valueCodeableConcept) {\n return extension.valueCodeableConcept?.coding?.map((c) => c.code) as ResourceType[];\n }\n return undefined;\n}\n\nexport function setQuestionnaireItemReferenceTargetTypes(\n item: QuestionnaireItem,\n targetTypes: ResourceType[] | undefined\n): QuestionnaireItem {\n const result = deepClone(item);\n let extension = getExtension(result, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource');\n\n if (!targetTypes || targetTypes.length === 0) {\n if (extension) {\n result.extension = result.extension?.filter((e) => e !== extension);\n }\n return result;\n }\n\n if (!extension) {\n if (!result.extension) {\n result.extension = [];\n }\n extension = { url: 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceResource' };\n result.extension.push(extension);\n }\n\n if (targetTypes.length === 1) {\n extension.valueCode = targetTypes[0];\n delete extension.valueCodeableConcept;\n } else {\n extension.valueCodeableConcept = { coding: targetTypes.map((t) => ({ code: t })) };\n delete extension.valueCode;\n }\n\n return result;\n}\n\n/**\n * Returns the reference filter for the given questionnaire item.\n * @see https://build.fhir.org/ig/HL7/fhir-extensions//StructureDefinition-questionnaire-referenceFilter-definitions.html\n * @param item - The questionnaire item to get the reference filter for.\n * @param subject - Optional subject reference.\n * @param encounter - Optional encounter reference.\n * @returns The reference filter as a map of key/value pairs.\n */\nexport function getQuestionnaireItemReferenceFilter(\n item: QuestionnaireItem,\n subject: Reference | undefined,\n encounter: Reference<Encounter> | undefined\n): Record<string, string> | undefined {\n const extension = getExtension(item, 'http://hl7.org/fhir/StructureDefinition/questionnaire-referenceFilter');\n if (!extension?.valueString) {\n return undefined;\n }\n\n // Replace variables\n let filter = extension.valueString;\n if (subject?.reference) {\n filter = filter.replaceAll('$subj', subject.reference);\n }\n if (encounter?.reference) {\n filter = filter.replaceAll('$encounter', encounter.reference);\n }\n\n // Parse the valueString into a map\n const result: Record<string, string> = {};\n const parts = filter.split('&');\n for (const part of parts) {\n const [key, value] = splitN(part, '=', 2);\n result[key] = value;\n }\n return result;\n}\n\nexport function buildInitialResponse(questionnaire: Questionnaire): QuestionnaireResponse {\n const response: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n questionnaire: getReferenceString(questionnaire),\n item: buildInitialResponseItems(questionnaire.item),\n status: 'in-progress',\n };\n\n return response;\n}\n\nfunction buildInitialResponseItems(items: QuestionnaireItem[] | undefined): QuestionnaireResponseItem[] {\n return items?.map(buildInitialResponseItem) ?? [];\n}\n\nexport function buildInitialResponseItem(item: QuestionnaireItem): QuestionnaireResponseItem {\n return {\n id: generateId(),\n linkId: item.linkId,\n text: item.text,\n item: buildInitialResponseItems(item.item),\n answer: item.initial?.map(buildInitialResponseAnswer) ?? [],\n };\n}\n\nlet nextId = 1;\nfunction generateId(): string {\n return 'id-' + nextId++;\n}\n\nfunction buildInitialResponseAnswer(answer: QuestionnaireItemInitial): QuestionnaireResponseItemAnswer {\n // This works because QuestionnaireItemInitial and QuestionnaireResponseItemAnswer\n // have the same properties.\n return { ...answer };\n}\n\n/**\n * Returns the number of pages in the questionnaire.\n *\n * By default, a questionnaire is represented as a simple single page questionnaire,\n * so the default return value is 1.\n *\n * If the questionnaire has a page extension on the first item, then the number of pages\n * is the number of top level items in the questionnaire.\n *\n * @param questionnaire - The questionnaire to get the number of pages for.\n * @returns The number of pages in the questionnaire. Default is 1.\n */\nexport function getNumberOfPages(questionnaire: Questionnaire): number {\n const firstItem = questionnaire?.item?.[0];\n if (firstItem) {\n const extension = getExtension(firstItem, 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl');\n if (extension?.valueCodeableConcept?.coding?.[0]?.code === 'page') {\n return (questionnaire.item as QuestionnaireItem[]).length;\n }\n }\n return 1;\n}\n\nexport function getItemInitialValue(initial: QuestionnaireItemInitial | undefined): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemInitial', value: initial },\n 'value'\n ) as TypedValue;\n}\n\nexport function getItemAnswerOptionValue(option: QuestionnaireItemAnswerOption): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemAnswerOption', value: option },\n 'value'\n ) as TypedValue;\n}\n\nexport function getItemEnableWhenValueAnswer(enableWhen: QuestionnaireItemEnableWhen): TypedValue {\n return getTypedPropertyValueWithoutSchema(\n { type: 'QuestionnaireItemEnableWhen', value: enableWhen },\n 'answer'\n ) as TypedValue;\n}\n\nexport function getResponseItemAnswerValue(answer: QuestionnaireResponseItemAnswer): TypedValue | undefined {\n return getTypedPropertyValueWithoutSchema({ type: 'QuestionnaireResponseItemAnswer', value: answer }, 'value') as\n | TypedValue\n | undefined;\n}\n", "import { Encounter, Reference } from '@medplum/fhirtypes';\nimport { createContext } from 'react';\n\nexport const QuestionnaireFormContext = createContext<{ subject?: Reference; encounter?: Reference<Encounter> }>({});\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}", "import { Title } from '@mantine/core';\nimport { createReference, getReferenceString } from '@medplum/core';\nimport {\n Encounter,\n Questionnaire,\n QuestionnaireItem,\n QuestionnaireResponse,\n QuestionnaireResponseItem,\n Reference,\n} from '@medplum/fhirtypes';\nimport { useMedplum, usePrevious, useResource } from '@medplum/react-hooks';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { Form } from '../Form/Form';\nimport {\n buildInitialResponse,\n getNumberOfPages,\n isQuestionEnabled,\n evaluateCalculatedExpressionsInQuestionnaire,\n mergeUpdatedItems,\n} from '../utils/questionnaire';\nimport { QuestionnaireFormContext } from './QuestionnaireForm.context';\nimport { QuestionnairePageSequence } from './QuestionnaireFormComponents/QuestionnaireFormPageSequence';\n\nexport interface QuestionnaireFormProps {\n readonly questionnaire: Questionnaire | Reference<Questionnaire>;\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 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 { subject, source: sourceFromProps } = props;\n const questionnaire = useResource(props.questionnaire);\n const prevQuestionnaire = usePrevious(questionnaire);\n const [response, setResponse] = useState<QuestionnaireResponse | undefined>();\n const [activePage, setActivePage] = useState(0);\n\n const onChangeRef = useRef(props.onChange);\n onChangeRef.current = props.onChange;\n\n const onSubmitRef = useRef(props.onSubmit);\n onSubmitRef.current = props.onSubmit;\n\n useEffect(() => {\n // If the Questionnaire remains \"the same\", keep the existing response\n if (questionnaire && getQuestionnaireIdentity(prevQuestionnaire) === getQuestionnaireIdentity(questionnaire)) {\n return;\n }\n\n // throw out the existing response and start over\n setResponse(questionnaire ? buildInitialResponse(questionnaire) : undefined);\n }, [questionnaire, prevQuestionnaire]);\n\n useEffect(() => {\n if (response && onChangeRef.current) {\n try {\n onChangeRef.current(response);\n } catch (e) {\n console.error('Error invoking QuestionnaireForm.onChange callback', e);\n }\n }\n }, [response]);\n\n const setItems = useCallback(\n (newResponseItems: QuestionnaireResponseItem | QuestionnaireResponseItem[]): void => {\n setResponse((prevResponse) => {\n const currentItems = prevResponse?.item ?? [];\n const mergedItems = mergeItems(\n currentItems,\n Array.isArray(newResponseItems) ? newResponseItems : [newResponseItems]\n );\n\n const tempResponse: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n status: 'in-progress',\n item: mergedItems,\n };\n\n const updatedItems = evaluateCalculatedExpressionsInQuestionnaire(questionnaire?.item ?? [], tempResponse);\n const mergedItemsWithUpdates = mergeUpdatedItems(mergedItems, updatedItems);\n\n const newResponse: QuestionnaireResponse = {\n resourceType: 'QuestionnaireResponse',\n status: 'in-progress',\n item: mergedItemsWithUpdates,\n };\n\n return newResponse;\n });\n },\n [questionnaire]\n );\n\n const handleSubmit = useCallback(() => {\n const onSubmit = onSubmitRef.current;\n if (onSubmit && response) {\n let source = sourceFromProps;\n if (!source) {\n const profile = medplum.getProfile();\n if (profile) {\n source = createReference(profile);\n }\n }\n onSubmit({\n ...response,\n questionnaire: getReferenceString(questionnaire as Questionnaire),\n subject,\n source,\n authored: new Date().toISOString(),\n status: 'completed',\n });\n }\n }, [medplum, questionnaire, response, subject, sourceFromProps]);\n\n function checkForQuestionEnabled(item: QuestionnaireItem): boolean {\n return isQuestionEnabled(item, response);\n }\n\n if (!questionnaire || !response) {\n return null;\n }\n\n const numberOfPages = getNumberOfPages(questionnaire);\n const nextStep = (): void => setActivePage((current) => current + 1);\n const prevStep = (): void => setActivePage((current) => current - 1);\n\n return (\n <QuestionnaireFormContext.Provider value={{ subject: props.subject, encounter: props.encounter }}>\n <Form testid=\"questionnaire-form\" onSubmit={handleSubmit}>\n {questionnaire.title && <Title>{questionnaire.title}</Title>}\n <QuestionnairePageSequence\n items={questionnaire.item ?? []}\n response={response}\n onChange={setItems}\n renderPages={!props.disablePagination && numberOfPages > 1}\n activePage={activePage}\n numberOfPages={numberOfPages}\n excludeButtons={props.excludeButtons}\n submitButtonText={props.submitButtonText}\n checkForQuestionEnabled={checkForQuestionEnabled}\n nextStep={nextStep}\n prevStep={prevStep}\n />\n </Form>\n </QuestionnaireFormContext.Provider>\n );\n}\n\nfunction mergeIndividualItems(\n prevItem: QuestionnaireResponseItem,\n newItem: QuestionnaireResponseItem\n): QuestionnaireResponseItem {\n // Recursively merge the nested items based on their ids.\n const mergedNestedItems = mergeItems(prevItem.item ?? [], newItem.item ?? []);\n\n return {\n ...newItem,\n item: mergedNestedItems.length > 0 ? mergedNestedItems : undefined,\n answer: newItem.answer && newItem.answer.length > 0 ? newItem.answer : prevItem.answer,\n };\n}\n\nfunction mergeItems(\n prevItems: QuestionnaireResponseItem[],\n newItems: QuestionnaireResponseItem[]\n): QuestionnaireResponseItem[] {\n const result: QuestionnaireResponseItem[] = [];\n const usedIds = new Set<string>();\n\n for (const prevItem of prevItems) {\n const itemId = prevItem.id;\n const newItem = newItems.find((item) => item.id === itemId);\n\n if (newItem) {\n result.push(mergeIndividualItems(prevItem, newItem));\n usedIds.add(newItem.id as string);\n } else {\n result.push(prevItem);\n }\n }\n\n // Add items from newItems that were not in prevItems.\n for (const newItem of newItems) {\n if (!usedIds.has(newItem.id as string)) {\n result.push(newItem);\n }\n }\n\n return result;\n}\n\nfunction getQuestionnaireIdentity(questionnaire: Questionnaire | undefined): Questionnaire | string | undefined {\n return questionnaire?.id || questionnaire;\n}\n", "import { Button, Group, Stack, Stepper } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponse, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { QuestionnaireItemType } from '../../utils/questionnaire';\nimport { QuestionnaireRepeatableItem } from '../QuestionnaireFormItem/QuestionnaireRepeatableItem';\nimport { QuestionnaireRepeatedGroup } from './QuestionnaireFormGroup';\n\ninterface QuestionnairePageSequenceProps {\n readonly items: QuestionnaireItem[];\n readonly response?: QuestionnaireResponse;\n readonly renderPages: boolean;\n readonly activePage?: number;\n readonly numberOfPages: number;\n readonly excludeButtons?: boolean;\n readonly submitButtonText?: string;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (items: QuestionnaireResponseItem | QuestionnaireResponseItem[]) => void;\n readonly nextStep: () => void;\n readonly prevStep: () => void;\n}\n\nexport function QuestionnairePageSequence(props: QuestionnairePageSequenceProps): JSX.Element {\n const {\n items,\n response,\n activePage,\n onChange,\n nextStep,\n prevStep,\n numberOfPages,\n renderPages,\n submitButtonText,\n excludeButtons,\n checkForQuestionEnabled,\n } = props;\n\n const form = items.map((item) => {\n const itemResponse = response?.item?.filter((i) => i.linkId === item.linkId) ?? [];\n\n const repeatedItem =\n item.type === QuestionnaireItemType.group ? (\n <QuestionnaireRepeatedGroup\n key={item.linkId}\n item={item}\n response={itemResponse}\n onChange={onChange}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n ) : (\n <QuestionnaireRepeatableItem\n key={item.linkId}\n item={item}\n response={itemResponse?.[0]}\n onChange={onChange}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n );\n\n if (renderPages) {\n return (\n <Stepper.Step key={item.linkId} label={item.text}>\n {repeatedItem}\n </Stepper.Step>\n );\n }\n return repeatedItem;\n });\n\n return (\n <>\n {renderPages && (\n <Stepper active={activePage ?? 0} allowNextStepsSelect={false} p={6}>\n {form}\n </Stepper>\n )}\n {!renderPages && <Stack>{form}</Stack>}\n {!excludeButtons && (\n <ButtonGroup\n activePage={activePage ?? 0}\n numberOfPages={numberOfPages}\n nextStep={renderPages ? nextStep : undefined}\n prevStep={renderPages ? prevStep : undefined}\n renderPages={renderPages}\n submitButtonText={submitButtonText}\n />\n )}\n </>\n );\n}\n\ninterface ButtonGroupProps {\n readonly activePage: number;\n readonly numberOfPages: number;\n readonly renderPages: boolean;\n readonly submitButtonText?: string;\n readonly nextStep?: () => void;\n readonly prevStep?: () => void;\n}\n\nfunction ButtonGroup(props: ButtonGroupProps): JSX.Element {\n const showBackButton = props.renderPages && props.activePage > 0;\n const showNextButton = props.renderPages && props.activePage < props.numberOfPages - 1;\n const showSubmitButton = !props.renderPages || props.activePage === props.numberOfPages - 1;\n\n return (\n <Group justify=\"flex-end\" mt=\"xl\" gap=\"xs\">\n {showBackButton && <Button onClick={props.prevStep}>Back</Button>}\n {showNextButton && (\n <Button\n onClick={(e) => {\n const form = e.currentTarget.closest('form') as HTMLFormElement;\n if (props.nextStep && form.reportValidity()) {\n props.nextStep();\n }\n }}\n >\n Next\n </Button>\n )}\n {showSubmitButton && <Button type=\"submit\">{props.submitButtonText ?? 'Submit'}</Button>}\n </Group>\n );\n}\n", "import { Anchor } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { useState } from 'react';\nimport { FormSection } from '../../FormSection/FormSection';\nimport { QuestionnaireItemType } from '../../utils/questionnaire';\nimport { QuestionnaireFormItem } from './QuestionnaireFormItem';\n\ninterface QuestionnaireRepeatableItemProps {\n readonly item: QuestionnaireItem;\n readonly response?: QuestionnaireResponseItem;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (items: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireRepeatableItem(props: QuestionnaireRepeatableItemProps): JSX.Element | null {\n const { item, response, onChange } = props;\n const [number, setNumber] = useState(getNumberOfRepeats(item, response ?? { linkId: item.linkId }));\n if (!props.checkForQuestionEnabled(item)) {\n return null;\n }\n\n if (!response) {\n return null;\n }\n\n if (item.type === QuestionnaireItemType.display) {\n return <p key={item.linkId}>{item.text}</p>;\n }\n\n const showAddButton =\n item?.repeats && item.type !== QuestionnaireItemType.choice && item.type !== QuestionnaireItemType.openChoice;\n\n // Styling reason to avoid duplicate text\n if (item.type === QuestionnaireItemType.boolean) {\n return (\n <QuestionnaireFormItem\n key={item.linkId}\n item={item}\n response={response}\n onChange={(r) => onChange([r])}\n index={0}\n />\n );\n }\n\n return (\n <FormSection\n key={props.item.linkId}\n htmlFor={props.item.linkId}\n title={props.item.text}\n withAsterisk={props.item.required}\n >\n {[...Array(number)].map((_, index) => (\n <QuestionnaireFormItem\n key={`${item.linkId}-${index}`}\n item={item}\n response={response}\n onChange={(r) => onChange([r])}\n index={index}\n />\n ))}\n {showAddButton && <Anchor onClick={() => setNumber((n) => n + 1)}>Add Item</Anchor>}\n </FormSection>\n );\n}\n\nfunction getNumberOfRepeats(item: QuestionnaireItem, response: QuestionnaireResponseItem): number {\n if (item.type === QuestionnaireItemType.choice || item.type === QuestionnaireItemType.openChoice) {\n return 1;\n }\n const answers = response.answer;\n return answers?.length ? answers.length : 1;\n}\n", "import { Anchor, Stack, Title } from '@mantine/core';\nimport { QuestionnaireItem, QuestionnaireResponseItem } from '@medplum/fhirtypes';\nimport { useEffect, useState } from 'react';\nimport { QuestionnaireItemType, buildInitialResponseItem } from '../../utils/questionnaire';\nimport { QuestionnaireRepeatableItem } from '../QuestionnaireFormItem/QuestionnaireRepeatableItem';\n\ninterface QuestionnaireRepeatableGroupProps {\n readonly item: QuestionnaireItem;\n readonly response: QuestionnaireResponseItem[];\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (responses: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireRepeatedGroup(props: QuestionnaireRepeatableGroupProps): JSX.Element | null {\n const [responses, setResponses] = useState(props.response);\n\n useEffect(() => {\n setResponses(props.response);\n }, [props.response]);\n\n if (responses.length === 0) {\n return null;\n }\n\n function handleRepeatableGroup(newResponseItems: QuestionnaireResponseItem[], index: number): void {\n const newResponses = responses.map((responses, idx) => (idx === index ? newResponseItems[0] : responses));\n setResponses(newResponses);\n props.onChange(newResponses);\n }\n\n function insertNewGroup(): void {\n const newResponse = buildInitialResponseItem(props.item);\n setResponses([...responses, newResponse]);\n }\n\n return (\n <>\n {responses.map((response, idx) => (\n <QuestionnaireGroup\n key={response.id}\n item={props.item}\n response={response}\n checkForQuestionEnabled={props.checkForQuestionEnabled}\n onChange={(r) => handleRepeatableGroup(r, idx)}\n />\n ))}\n {props.item.repeats && <Anchor onClick={insertNewGroup}>{`Add Group: ${props.item.text}`}</Anchor>}\n </>\n );\n}\n\ninterface QuestionnaireGroupProps {\n readonly item: QuestionnaireItem;\n readonly response: QuestionnaireResponseItem;\n readonly checkForQuestionEnabled: (item: QuestionnaireItem) => boolean;\n readonly onChange: (response: QuestionnaireResponseItem[]) => void;\n}\n\nexport function QuestionnaireGroup(props: QuestionnaireGroupProps): JSX.Element | null {\n const { response, checkForQuestionEnabled, onChange } = props;\n function onSetGroup(newResponseItem: QuestionnaireResponseItem[]): void {\n const newResponse = response.item?.map((current) => {\n const matchingItem = newResponseItem.find((newResponse) => newResponse.id === current.id);\n return matchingItem ?? current;\n });\n // This checks to see if there were any nested repeated groups that we need to add\n const mergedResponse = newResponse?.concat(newResponseItem.slice(1));\n const groupResponse = { ...response, item: mergedResponse };\n onChange([groupResponse]);\n }\n\n if (!props.checkForQuestionEnabled(props.item)) {\n return null;\n }\n\n return (\n <div key={props.item.linkId}>\n {props.item.text && (\n <Title order={3} mb=\"md\">\n {props.item.text}\n </Title>\n )}\n <Stack>\n {props.item.item?.map((item) => {\n if (item.type === QuestionnaireItemType.group) {\n return item.repeats ? (\n <QuestionnaireRepeatedGroup\n key={item.linkId}\n item={item}\n response={response.item?.filter((i) => i.linkId === item.linkId) ?? []}\n checkForQuestionEnabled={checkForQuestionEnabled}\n onChange={onSetGroup}\n />\n ) : (\n <QuestionnaireGroup\n key={item.linkId}\n item={item}\n checkForQuestionEnabled={checkForQuestionEnabled}\n response={response.item?.find((i) => i.linkId === item.linkId) ?? { linkId: item.linkId }}\n onChange={onSetGroup}\n />\n );\n }\n\n return (\n <QuestionnaireRepeatableItem\n key={item.linkId}\n item={item}\n response={response.item?.find((i) => i.linkId === item.linkId)}\n onChange={onSetGroup}\n checkForQuestionEnabled={checkForQuestionEnabled}\n />\n );\n })}\n </Stack>\n </div>\n );\n}\n", "import { ActionIcon, Button, Divider, Group, NativeSelect, Stack, Text, TextInput } from '@mantine/core';\nimport { formatRange, getCodeBySystem } from '@medplum/core';\nimport { CodeableConcept, ObservationDefinition, ObservationDefinitionQualifiedInterval } from '@medplum/fhirtypes';\nimport { IconCircleMinus, IconCirclePlus } from '@tabler/icons-react';\nimport { MouseEvent, useEffect, useState } from 'react';\nimport { Container } from '../Container/Container';\nimport { Form } from '../Form/Form';\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: {} as IntervalGroup['filters'], intervals: [] });\n setGroupId((id) => id + 1);\n }}\n >\n <IconCirclePlus />\n </ActionIcon>\n\n <Group justify=\"flex-end\">\n <Button type=\"submit\">Save</Button>\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\n if (!intervalGroup.filters.age) {\n intervalGroup.filters.age = {};\n }\n for (const key of ['low', 'high']) {\n if (!intervalGroup.filters.age[key]?.unit) {\n intervalGroup.filters.age[key] = {\n ...intervalGroup.filters.age[key],\n unit: 'years',\n system: 'http://unitsofmeasure.org',\n };\n }\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={intervalGroup.filters['age']}\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 = parseInt(interval.id?.substring(3) || '', 10);\n return !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]])) as Record<string, any>,\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", "import { Button, Grid, Text } from '@mantine/core';\nimport { formatDateTime, getReferenceString } from '@medplum/core';\nimport { Bundle, BundleEntry, Reference, RequestGroup, Resource, Task } from '@medplum/fhirtypes';\nimport { useMedplum, useResource } from '@medplum/react-hooks';\nimport { IconCheckbox, IconSquare } from '@tabler/icons-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 \n <ResourceName value={task?.meta?.author as Reference} />\n on \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", "import { Bundle, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { useEffect, useState } from 'react';\nimport { MedplumLink } from '../MedplumLink/MedplumLink';\nimport { ResourceBadge } from '../ResourceBadge/ResourceBadge';\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<Bundle | undefined>(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 <ResourceBadge value={row.meta.author} link={true} />\n </td>\n <td className={classes.dateTime} rowSpan={row.span}>\n <MedplumLink to={getVersionUrl(resource, row.meta.versionId as string)}>\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", "import { stringify } from '@medplum/core';\nimport { 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", "/*\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 */\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 = (size / 2) | 0;\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] as PathNode;\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: 100px;\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}\n\n.normalRow {\n border-top: 0;\n}\n\n.author {\n line-height: 10px;\n}\n\n.dateTime {\n border-right: 0.1px solid var(--mantine-color-gray-3);\n line-height: 20px;\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-sm);\n padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);\n}\n\n.pre {\n margin: 0;\n}\n", "import { 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", "import { stringify } from '@medplum/core';\nimport { Resource } from '@medplum/fhirtypes';\nimport { Delta, 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) as string[];\n const revised = stringify(revisedResource, true).match(/[^\\r\\n]+/g) as string[];\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", "\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}", "import { 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 { 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 { FormEvent, 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", "import { Table } from '@mantine/core';\nimport { formatDateTime, normalizeErrorString } from '@medplum/core';\nimport { Bundle, BundleEntry, Resource, ResourceType } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\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<Bundle | undefined>(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>Date</Table.Th>\n <Table.Th>Version</Table.Th>\n </Table.Tr>\n </Table.Thead>\n <Table.Tbody>\n {value.entry?.map((entry, index) => <HistoryRow key={'entry-' + index} entry={entry} />)}\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>{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={3}>{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", "import { Button, Stack, Text } from '@mantine/core';\nimport { getReferenceString, isReference } from '@medplum/core';\nimport { Questionnaire, QuestionnaireResponse, Reference, Schedule, Slot } from '@medplum/fhirtypes';\nimport { useResource, useSearchResources } from '@medplum/react-hooks';\nimport { useState } from 'react';\nimport { CalendarInput } from '../CalendarInput/CalendarInput';\nimport { getStartMonth } from '../CalendarInput/CalendarInput.utils';\nimport { QuestionnaireForm } from '../QuestionnaireForm/QuestionnaireForm';\nimport { ResourceAvatar } from '../ResourceAvatar/ResourceAvatar';\nimport { ResourceName } from '../ResourceName/ResourceName';\nimport classes from './Scheduler.module.css';\n\nexport interface SchedulerProps {\n readonly schedule: Schedule | Reference<Schedule>;\n readonly questionnaire: Questionnaire | Reference<Questionnaire>;\n}\n\nexport function Scheduler(props: SchedulerProps): JSX.Element | null {\n const schedule = useResource(props.schedule);\n const questionnaire = useResource(props.questionnaire);\n\n const [month, setMonth] = useState<Date>(getStartMonth());\n const [date, setDate] = useState<Date>();\n const [slot, setSlot] = useState<Slot>();\n const [response, setResponse] = useState<QuestionnaireResponse>();\n\n const [slots] = useSearchResources(\n 'Slot',\n new URLSearchParams([\n ['_count', (30 * 24).toString()],\n [\n 'schedule',\n isReference(props.schedule)\n ? (props.schedule.reference as string)\n : getReferenceString(props.schedule as Schedule),\n ],\n ['start', 'gt' + getStart(month)],\n ['start', 'lt' + getEnd(month)],\n ])\n );\n\n if (!schedule || !slots || !questionnaire) {\n return null;\n }\n\n const actor = schedule.actor?.[0];\n\n return (\n <div className={classes.container} data-testid=\"scheduler\">\n <div className={classes.info}>\n {actor && <ResourceAvatar value={actor} size=\"xl\" />}\n {actor && (\n <Text size=\"xl\" fw={500}>\n <ResourceName value={actor} />\n </Text>\n )}\n <p>1 hour</p>\n {date && <p>{date.toLocaleDateString()}</p>}\n {slot && <p>{formatTime(new Date(slot.start as string))}</p>}\n </div>\n <div className={classes.selection}>\n {!date && (\n <div>\n <h3>Select date</h3>\n <CalendarInput slots={slots} onChangeMonth={setMonth} onClick={setDate} />\n </div>\n )}\n {date && !slot && (\n <div>\n <h3>Select time</h3>\n <Stack>\n {slots.map((s) => {\n const slotStart = new Date(s.start as string);\n return (\n slotStart.getTime() > date.getTime() &&\n slotStart.getTime() < date.getTime() + 24 * 3600 * 1000 && (\n <div key={s.id}>\n <Button variant=\"outline\" style={{ width: 150 }} onClick={() => setSlot(s)}>\n {formatTime(slotStart)}\n </Button>\n </div>\n )\n );\n })}\n </Stack>\n </div>\n )}\n {date && slot && !response && (\n <QuestionnaireForm questionnaire={questionnaire} submitButtonText=\"Next\" onSubmit={setResponse} />\n )}\n {date && slot && response && (\n <div>\n <h3>You're all set!</h3>\n <p>Check your email for a calendar invite.</p>\n </div>\n )}\n </div>\n </div>\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", "\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}", "import { createReference, MedplumClient, ProfileResource } from '@medplum/core';\nimport { Attachment, Group, Patient, Reference, ResourceType, ServiceRequest } from '@medplum/fhirtypes';\nimport { ResourceTimeline, ResourceTimelineProps } 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", "import { Anchor, AnchorProps } from '@mantine/core';\nimport { showNotification } from '@mantine/notifications';\nimport { ensureTrailingSlash, normalizeErrorString } from '@medplum/core';\nimport { ClientApplication, Encounter, Patient, Reference, SmartAppLaunch } from '@medplum/fhirtypes';\nimport { useMedplum } from '@medplum/react-hooks';\nimport { 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 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\n function launchApp(): void {\n medplum\n .createResource<SmartAppLaunch>({\n resourceType: 'SmartAppLaunch',\n patient,\n encounter,\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 as string);\n window.location.assign(url.toString());\n })\n .catch((err) => showNotification({ color: 'red', message: normalizeErrorString(err), autoClose: false }));\n }\n\n return (\n <Anchor onClick={() => launchApp()} {...rest}>\n {children}\n </Anchor>\n );\n}\n"],
|
|
5
|
+
"mappings": "mpCAAA,8FACA,OAAO,eAAe,QAAS,aAAc,CAAE,MAAO,EAAK,CAAC,EAC5D,QAAQ,QAAU,QAAQ,YAAc,QAAQ,cAAgB,OAqBhE,SAAS,cAAc,MAAO,CAC1B,OAAO,MAAM,QA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CAAC,CAC5G,CAEA,SACE,2BAAC,uBAAO,QAAS,IAAM,UAAU,EAAI,GAAG,KACrC,SACH,CAEJ",
|
|
6
6
|
"names": ["Pointer", "diff", "memo", "d", "b", "MissingError", "TestError", "InvalidOperationError", "diff", "createPatch", "import_core", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "Component", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "main", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_core", "import_react_hooks", "data", "import_jsx_runtime", "import_jsx_runtime", "logoButton", "user", "userName", "userActive", "import_core", "import_react_hooks", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "defaultValue", "toOption", "ItemComponent", "option", "searchInput", "import_jsx_runtime", "import_jsx_runtime", "MantineAppShell", "import_core", "import_react_hooks", "import_react", "import_core", "import_notifications", "import_react_hooks", "import_jsx_runtime", "import_jsx_runtime", "import_react", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "toOption", "ItemComponent", "import_jsx_runtime", "defaultValue", "import_jsx_runtime", "menuTitle", "link", "linkActive", "import_jsx_runtime", "MantineAppShell", "import_jsx_runtime", "MantineAppShell", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "root", "compact", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "props", "import_core", "import_react", "import_jsx_runtime", "props", "import_core", "import_react_hooks", "import_react", "import_core", "root", "import_jsx_runtime", "MantineContainer", "import_core", "paper", "fill", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "import_notifications", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_core", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_react_hooks", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "slices", "slicedValues", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_react", "import_jsx_runtime", "EXTENSION_KEYS", "IGNORED_PROPERTIES", "import_core", "import_react", "import_core", "import_react", "import_core", "import_react", "import_core", "import_jsx_runtime", "dimmed", "preserveBreaks", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_core", "import_react", "import_react", "import_jsx_runtime", "defaultValue", "import_react", "import_jsx_runtime", "defaultValue", "import_core", "import_react", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "toOption", "defaultValue", "ItemComponent", "DefaultItemComponent", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "indented", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_jsx_runtime", "defaultValue", "slices", "slicedValues", "import_core", "import_notifications", "import_react", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_jsx_runtime", "defaultValue", "import_jsx_runtime", "import_jsx_runtime", "defaultValue", "import_core", "import_react", "table", "import_jsx_runtime", "import_core", "import_hooks", "import_notifications", "import_react_hooks", "import_react", "chatPaper", "chatTitle", "chatBody", "chatScrollArea", "chatInputContainer", "chatBubbleOuterWrap", "chatBubbleRightAlignedInnerWrap", "chatBubbleLeftAlignedInnerWrap", "chatBubble", "chatBubbleName", "chatBubbleNameRight", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "iconContainer", "icon", "chatModalContainer", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_react", "import_core", "import_react_hooks", "import_react", "import_core", "noteBody", "noteCite", "noteRoot", "import_jsx_runtime", "import_core", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_jsx_runtime", "table", "criticalRow", "noteBody", "noteCite", "noteRoot", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_react", "import_core", "removed", "added", "import_jsx_runtime", "root", "removed", "added", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "item", "itemPadding", "import_jsx_runtime", "pinnedComment", "import_jsx_runtime", "resource", "props", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_jsx_runtime", "import_core", "import_jsx_runtime", "root", "table", "tr", "th", "control", "icon", "import_core", "import_jsx_runtime", "state", "import_jsx_runtime", "import_core", "import_react_hooks", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "code", "clinicalStatus", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_react_hooks", "import_jsx_runtime", "HTTP", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_react", "import_jsx_runtime", "code", "clinicalStatus", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_jsx_runtime", "import_core", "import_hooks", "import_react_hooks", "import_react", "import_core", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "section", "hovering", "editing", "bottomActions", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_core", "import_react", "import_core", "QuestionnaireItemType", "generateId", "nextId", "import_react", "import_jsx_runtime", "defaultValue", "data", "option", "section", "hovering", "editing", "questionBody", "topActions", "bottomActions", "movementActions", "movementIcons", "columnAlignment", "linkIdInput", "typeSelect", "preserveBreaks", "import_jsx_runtime", "defaultValue", "isResource", "isResourceType", "item", "generateId", "nextId", "import_core", "import_react_hooks", "import_react", "import_core", "import_core", "import_react", "import_jsx_runtime", "r", "import_core", "import_react", "import_jsx_runtime", "responses", "r", "newResponse", "import_jsx_runtime", "import_jsx_runtime", "import_core", "import_react", "section", "import_jsx_runtime", "groupId", "nextId", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "import_react_hooks", "import_react", "import_core", "container", "root", "startRow", "normalRow", "author", "dateTime", "lineNumber", "line", "pre", "import_jsx_runtime", "import_core", "removed", "added", "import_jsx_runtime", "import_core", "import_react_hooks", "import_react", "splitButton", "menuControl", "import_jsx_runtime", "defaultValue", "import_core", "import_react_hooks", "import_react", "import_jsx_runtime", "getVersionUrl", "import_core", "import_react_hooks", "import_react", "container", "info", "selection", "import_jsx_runtime", "getStart", "getEnd", "import_core", "import_jsx_runtime", "import_core", "import_notifications", "import_react_hooks", "import_jsx_runtime"]
|
|
7
7
|
}
|