@tellescope/react-components 1.228.0 → 1.229.0

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.
Files changed (57) hide show
  1. package/lib/cjs/Forms/forms.v2.d.ts +116 -0
  2. package/lib/cjs/Forms/forms.v2.d.ts.map +1 -0
  3. package/lib/cjs/Forms/forms.v2.js +760 -0
  4. package/lib/cjs/Forms/forms.v2.js.map +1 -0
  5. package/lib/cjs/Forms/hooks.d.ts.map +1 -1
  6. package/lib/cjs/Forms/hooks.js +8 -3
  7. package/lib/cjs/Forms/hooks.js.map +1 -1
  8. package/lib/cjs/Forms/index.d.ts +1 -0
  9. package/lib/cjs/Forms/index.d.ts.map +1 -1
  10. package/lib/cjs/Forms/index.js +6 -0
  11. package/lib/cjs/Forms/index.js.map +1 -1
  12. package/lib/cjs/Forms/inputs.v2.d.ts +81 -0
  13. package/lib/cjs/Forms/inputs.v2.d.ts.map +1 -0
  14. package/lib/cjs/Forms/inputs.v2.js +2289 -0
  15. package/lib/cjs/Forms/inputs.v2.js.map +1 -0
  16. package/lib/cjs/Forms/localization.d.ts.map +1 -1
  17. package/lib/cjs/Forms/localization.js +3 -0
  18. package/lib/cjs/Forms/localization.js.map +1 -1
  19. package/lib/cjs/Forms/types.d.ts +1 -0
  20. package/lib/cjs/Forms/types.d.ts.map +1 -1
  21. package/lib/cjs/state.d.ts +34 -0
  22. package/lib/cjs/state.d.ts.map +1 -1
  23. package/lib/cjs/state.js +16 -2
  24. package/lib/cjs/state.js.map +1 -1
  25. package/lib/esm/Forms/forms.v2.d.ts +116 -0
  26. package/lib/esm/Forms/forms.v2.d.ts.map +1 -0
  27. package/lib/esm/Forms/forms.v2.js +725 -0
  28. package/lib/esm/Forms/forms.v2.js.map +1 -0
  29. package/lib/esm/Forms/hooks.d.ts.map +1 -1
  30. package/lib/esm/Forms/hooks.js +8 -3
  31. package/lib/esm/Forms/hooks.js.map +1 -1
  32. package/lib/esm/Forms/index.d.ts +1 -0
  33. package/lib/esm/Forms/index.d.ts.map +1 -1
  34. package/lib/esm/Forms/index.js +2 -0
  35. package/lib/esm/Forms/index.js.map +1 -1
  36. package/lib/esm/Forms/inputs.v2.d.ts +81 -0
  37. package/lib/esm/Forms/inputs.v2.d.ts.map +1 -0
  38. package/lib/esm/Forms/inputs.v2.js +2218 -0
  39. package/lib/esm/Forms/inputs.v2.js.map +1 -0
  40. package/lib/esm/Forms/localization.d.ts.map +1 -1
  41. package/lib/esm/Forms/localization.js +3 -0
  42. package/lib/esm/Forms/localization.js.map +1 -1
  43. package/lib/esm/Forms/types.d.ts +1 -0
  44. package/lib/esm/Forms/types.d.ts.map +1 -1
  45. package/lib/esm/state.d.ts +34 -0
  46. package/lib/esm/state.d.ts.map +1 -1
  47. package/lib/esm/state.js +13 -0
  48. package/lib/esm/state.js.map +1 -1
  49. package/lib/tsconfig.tsbuildinfo +1 -1
  50. package/package.json +9 -9
  51. package/src/Forms/forms.v2.tsx +1321 -0
  52. package/src/Forms/hooks.tsx +10 -5
  53. package/src/Forms/index.ts +5 -2
  54. package/src/Forms/inputs.v2.tsx +3869 -0
  55. package/src/Forms/localization.ts +1 -0
  56. package/src/Forms/types.ts +1 -0
  57. package/src/state.tsx +25 -5
@@ -0,0 +1,2218 @@
1
+ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
2
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
3
+ return cooked;
4
+ };
5
+ var __assign = (this && this.__assign) || function () {
6
+ __assign = Object.assign || function(t) {
7
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
8
+ s = arguments[i];
9
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
10
+ t[p] = s[p];
11
+ }
12
+ return t;
13
+ };
14
+ return __assign.apply(this, arguments);
15
+ };
16
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
+ return new (P || (P = Promise))(function (resolve, reject) {
19
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
23
+ });
24
+ };
25
+ var __generator = (this && this.__generator) || function (thisArg, body) {
26
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
27
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
28
+ function verb(n) { return function (v) { return step([n, v]); }; }
29
+ function step(op) {
30
+ if (f) throw new TypeError("Generator is already executing.");
31
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
32
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
33
+ if (y = 0, t) op = [op[0] & 2, t.value];
34
+ switch (op[0]) {
35
+ case 0: case 1: t = op; break;
36
+ case 4: _.label++; return { value: op[1], done: false };
37
+ case 5: _.label++; y = op[1]; op = [0]; continue;
38
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
39
+ default:
40
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
41
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
42
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
43
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
44
+ if (t[2]) _.ops.pop();
45
+ _.trys.pop(); continue;
46
+ }
47
+ op = body.call(thisArg, _);
48
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
49
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
50
+ }
51
+ };
52
+ var __rest = (this && this.__rest) || function (s, e) {
53
+ var t = {};
54
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
55
+ t[p] = s[p];
56
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
57
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
58
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
59
+ t[p[i]] = s[p[i]];
60
+ }
61
+ return t;
62
+ };
63
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
64
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
65
+ if (ar || !(i in from)) {
66
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
67
+ ar[i] = from[i];
68
+ }
69
+ }
70
+ return to.concat(ar || Array.prototype.slice.call(from));
71
+ };
72
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
73
+ import React, { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from "react";
74
+ import axios from "axios";
75
+ import { Autocomplete, Box, Button, Checkbox, Chip, Collapse, Divider, FormControl, FormControlLabel, Grid, IconButton as MuiIconButton, InputLabel, MenuItem, Radio, RadioGroup, Select, TextField, Typography } from "@mui/material";
76
+ import { useDropzone } from "react-dropzone";
77
+ import { CANVAS_TITLE, EMOTII_TITLE, INSURANCE_RELATIONSHIPS, INSURANCE_RELATIONSHIPS_CANVAS, PRIMARY_HEX, RELATIONSHIP_TYPES, TELLESCOPE_GENDERS } from "@tellescope/constants";
78
+ import { MM_DD_YYYY_to_YYYY_MM_DD, capture_is_supported, downloadFile, emit_gtm_event, first_letter_capitalized, form_response_value_to_string, getLocalTimezone, getPublicFileURL, mm_dd_yyyy, replace_enduser_template_values, truncate_string, update_local_storage, user_display_name } from "@tellescope/utilities";
79
+ import { TIMEZONES_USA } from "@tellescope/types-models";
80
+ import { VALID_STATES, emailValidator, phoneValidator } from "@tellescope/validation";
81
+ import Slider from '@mui/material/Slider';
82
+ import LinearProgress from '@mui/material/LinearProgress';
83
+ import DatePicker from "react-datepicker";
84
+ import { datepickerCSS } from "./css/react-datepicker"; // avoids build issue with RN
85
+ import { CancelIcon, IconButton, LabeledIconButton, LoadingButton, form_display_text_for_language, isDateString, useResolvedSession } from "..";
86
+ import { css } from '@emotion/css';
87
+ import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";
88
+ import DragIndicatorIcon from '@mui/icons-material/DragIndicator';
89
+ import heic2any from "heic2any";
90
+ import AddPhotoAlternateIcon from '@mui/icons-material/AddPhotoAlternate';
91
+ import LanguageIcon from '@mui/icons-material/Language';
92
+ import { Elements, PaymentElement, useStripe, useElements, EmbeddedCheckout, EmbeddedCheckoutProvider } from '@stripe/react-stripe-js';
93
+ import { loadStripe } from '@stripe/stripe-js';
94
+ import { CheckCircleOutline, Delete, Edit, ExpandMore, UploadFile } from "@mui/icons-material";
95
+ import { WYSIWYG } from "./wysiwyg";
96
+ export var LanguageSelect = function (_a) {
97
+ var value = _a.value, props = __rest(_a, ["value"]);
98
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center", justifyContent: "center", wrap: "nowrap", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(LanguageIcon, { color: "primary" }) })), _jsx(Grid, __assign({ item: true, style: { width: 150 } }, { children: _jsx(StringSelector, __assign({}, props, { options: ["English", "Español"], size: "small", value: value === 'Spanish' ? 'Español' : value, label: (value === 'Español' || value === 'Spanish') ? 'Idioma'
99
+ : "Language" })) }))] })));
100
+ };
101
+ export var defaultInputProps = { sx: {
102
+ borderRadius: 1.5,
103
+ backgroundColor: '#FFFFFF',
104
+ '& .MuiOutlinedInput-root': {
105
+ backgroundColor: '#FFFFFF',
106
+ '&.Mui-error': {
107
+ boxShadow: '0 0 8px 2px rgba(211, 47, 47, 0.3)',
108
+ },
109
+ '&.Mui-error .MuiOutlinedInput-notchedOutline': {
110
+ borderColor: '#d32f2f',
111
+ borderWidth: '2px',
112
+ },
113
+ },
114
+ '& .MuiInputBase-input': {
115
+ padding: '10px 14px',
116
+ },
117
+ } };
118
+ export var defaultButtonStyles = {
119
+ borderRadius: '10px',
120
+ };
121
+ export var PdfViewer = function (_a) {
122
+ // const [numPages, setNumPages] = useState<number>();
123
+ // const [page, setPage] = useState(1);
124
+ var url = _a.url, _b = _a.height, height = _b === void 0 ? 420 : _b;
125
+ // const parentRef = useRef<HTMLDivElement | null>(null);
126
+ // const canvasRef = useRef<HTMLCanvasElement | null>(null);
127
+ // function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
128
+ // setNumPages(numPages);
129
+ // }
130
+ // const pdfHeight: number | undefined = pdfPage?._pageInfo?.view?.[3]
131
+ // const pdfWidth: number | undefined = pdfPage?._pageInfo?.view?.[2]
132
+ // const parentWidth = parentRef.current?.clientWidth
133
+ return (_jsxs(Grid, __assign({ container: true, direction: "column" }, { children: [_jsx("iframe", { src:
134
+ // url
135
+ // encodeURI(`http://localhost:5173?url=${url}`)
136
+ // encodeURI(`http://tellescope-pdf-renderer.s3-website.us-east-2.amazonaws.com?url=${url}`)
137
+ encodeURI("https://pdf.tellescope.com?url=".concat(url)), title: "PDF Viewer", style: {
138
+ border: 'none',
139
+ height: height,
140
+ width: '100%',
141
+ marginBottom: '5px'
142
+ } }), _jsx("a", __assign({ href: url, target: "__blank", rel: "noopener noreferrer", style: { marginTop: 5 } }, { children: "View in new tab or download here" }))] })));
143
+ };
144
+ export var RatingInput = function (_a) {
145
+ var _b, _d, _e, _f, _g;
146
+ var field = _a.field, value = _a.value, onChange = _a.onChange;
147
+ var from = (_d = (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.from) !== null && _d !== void 0 ? _d : 1; // allow 0
148
+ var to = (_f = (_e = field === null || field === void 0 ? void 0 : field.options) === null || _e === void 0 ? void 0 : _e.to) !== null && _f !== void 0 ? _f : 10; // allow 0
149
+ var step = ((_g = field.options) === null || _g === void 0 ? void 0 : _g.rangeStepSize) || 1;
150
+ var allMarks = [];
151
+ for (var i = from; i <= to; i += (step)) {
152
+ allMarks.push({ value: i, label: i });
153
+ }
154
+ var marks = __spreadArray([], allMarks, true);
155
+ while (marks.length > 25) {
156
+ marks = marks.filter(function (_, i) { return i % 2 === 0; });
157
+ }
158
+ return (_jsx(Slider, { min: from, max: to, step: step, marks: marks, valueLabelDisplay: marks.length < allMarks.length ? 'auto' : "off", value: value, onChange: function (e, v) { return onChange(v, field.id); }, sx: {
159
+ '& .MuiSlider-thumb': value === undefined ? { display: 'none' } : {}, // Hide thumb until value is set
160
+ } }, field.id));
161
+ };
162
+ // a little function to help us with reordering the result
163
+ var reorder = function (list, startIndex, endIndex) {
164
+ var result = Array.from(list);
165
+ var removed = result.splice(startIndex, 1)[0];
166
+ result.splice(endIndex, 0, removed);
167
+ return result;
168
+ };
169
+ var grid = 8;
170
+ var getItemStyle = function (isDragging, draggableStyle) { return (__assign({
171
+ // some basic styles to make the items look a bit nicer
172
+ userSelect: "none", padding: "".concat(grid * 2, "px"), margin: "0 0 ".concat(grid, "px 0"),
173
+ // change background colour if dragging
174
+ backgroundColor: isDragging ? "#ffffff88" : undefined, border: '1px solid', borderColor: "primary.main", borderRadius: 5 }, draggableStyle)); };
175
+ var getListStyle = function (isDraggingOver) { return ({
176
+ // background: isDraggingOver ? "#ffffff44" : undefined,
177
+ // padding: `${grid}px`,
178
+ // width: '250px'
179
+ }); };
180
+ export var RankingInput = function (_a) {
181
+ var field = _a.field, value = _a.value, onChange = _a.onChange;
182
+ return (_jsxs(Grid, __assign({ container: true, direction: 'column' }, { children: [_jsx(DragDropContext, __assign({ onDragEnd: function (result) {
183
+ if (!value)
184
+ return;
185
+ if (!result.destination) {
186
+ return;
187
+ }
188
+ onChange(reorder(value, result.source.index, result.destination.index), field.id);
189
+ } }, { children: _jsx(Droppable, __assign({ droppableId: "droppable" }, { children: function (provided, snapshot) { return (_jsxs(Box, __assign({}, provided.droppableProps, { ref: provided.innerRef, sx: getListStyle(snapshot.isDraggingOver) }, { children: [(value !== null && value !== void 0 ? value : []).map(function (item, index) { return (_jsx(Draggable, __assign({ draggableId: item, index: index }, { children: function (provided, snapshot) { return (_jsxs(Grid, __assign({ container: true, alignItems: "center", justifyContent: "space-between", ref: provided.innerRef }, provided.draggableProps, provided.dragHandleProps, { sx: getItemStyle(snapshot.isDragging, provided.draggableProps.style) }, { children: [item, _jsx(DragIndicatorIcon, { color: "primary" })] }))); } }), item)); }), provided.placeholder] }))); } })) })), _jsx(Typography, __assign({ color: "primary", style: { marginTop: 3 } }, { children: "Drag and drop to re-order the above options" }))] })));
190
+ };
191
+ var CustomDateInput = forwardRef(function (props, ref) { return (_jsx(TextField, __assign({ InputProps: defaultInputProps, fullWidth: true, inputRef: ref }, props))); });
192
+ export var DateInput = function (_a) {
193
+ var field = _a.field, value = _a.value, onChange = _a.onChange, _b = _a.placement, placement = _b === void 0 ? 'top' : _b, props = __rest(_a, ["field", "value", "onChange", "placement"]);
194
+ var inputRef = useRef(null);
195
+ return (_jsx(DatePicker // wrap in item to prevent movement on focused
196
+ , { selected: value, onChange: function (d) { return onChange === null || onChange === void 0 ? void 0 : onChange(d, field.id); }, showTimeSelect: true, required: !field.isOptional, dateFormat: "Pp", autoComplete: "off", timeIntervals: 15, popperPlacement: placement, customInput: _jsx(CustomDateInput, __assign({ inputRef: inputRef }, props)),
197
+ // className={css`width: 100%;`}
198
+ className: css(templateObject_1 || (templateObject_1 = __makeTemplateObject(["", ""], ["", ""])), datepickerCSS) }));
199
+ };
200
+ export var TableInput = function (_a) {
201
+ var _b;
202
+ var field = _a.field, _d = _a.value, value = _d === void 0 ? [] : _d, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
203
+ var choices = (_b = field.options) === null || _b === void 0 ? void 0 : _b.tableChoices;
204
+ var handleNewRow = useCallback(function () {
205
+ if (!(choices === null || choices === void 0 ? void 0 : choices.length))
206
+ return;
207
+ onChange(__spreadArray(__spreadArray([], value, true), [choices.map(function (c) { return ({
208
+ label: c.label,
209
+ entry: '',
210
+ }); })], false), field.id, true);
211
+ }, [value, field.id]);
212
+ var handleChange = useCallback(function (r, c, u) {
213
+ onChange(value.map(function (v, _i) {
214
+ return _i !== r
215
+ ? v
216
+ : v.map(function (e, _c) { return _c === c ? u : e; });
217
+ }), field.id, true);
218
+ }, [value, onChange, field.id]);
219
+ var handleRemove = useCallback(function (i) {
220
+ onChange(value.filter(function (_, _i) { return i !== _i; }), field.id, true);
221
+ }, [value, onChange, field.id]);
222
+ useEffect(function () {
223
+ if (field.isOptional)
224
+ return;
225
+ if (value.length)
226
+ return;
227
+ handleNewRow();
228
+ }, [field.isOptional, value, handleNewRow]);
229
+ if (!(choices === null || choices === void 0 ? void 0 : choices.length)) {
230
+ return _jsx(Typography, __assign({ color: "error" }, { children: "No input choices available" }));
231
+ }
232
+ var length = choices.length || 1;
233
+ var iconWidth = '35px';
234
+ var width = "calc(".concat((100 / length).toFixed(2), "% - calc(").concat(iconWidth, " / ").concat(length, "))");
235
+ return (_jsxs(Grid, __assign({ container: true, direction: "column" }, { children: [value.map(function (row, i) { return (_jsxs(_Fragment, { children: [_jsxs(Grid, __assign({ container: true, alignItems: "center", spacing: 1 }, { children: [choices.map(function (v, columnIndex) {
236
+ var _a, _b, _d, _e, _f, _g, _h;
237
+ return (_jsx(Grid, __assign({ item: true, sx: { width: width } }, { children: v.type === 'Text'
238
+ ? (_jsx(TextField, { label: v.label, size: "small", fullWidth: true, title: v.label, InputProps: defaultInputProps, value: (_a = row.find(function (c, _i) { return columnIndex === _i; })) === null || _a === void 0 ? void 0 : _a.entry, onChange: function (e) { return handleChange(i, columnIndex, { label: v.label, entry: e.target.value }); } }))
239
+ : v.type === 'Date' ? (_jsx(DateStringInput, { label: v.label, size: "small", fullWidth: true, title: v.label, field: field, value: (_b = row.find(function (c, _i) { return columnIndex === _i; })) === null || _b === void 0 ? void 0 : _b.entry, onChange: function (entry) {
240
+ if (entry === void 0) { entry = ''; }
241
+ return handleChange(i, columnIndex, { label: v.label, entry: entry });
242
+ } }))
243
+ : v.type === 'Select' ? (_jsxs(FormControl, __assign({ size: "small", fullWidth: true }, { children: [_jsx(InputLabel, __assign({ id: "demo-select-small" }, { children: v.label })), _jsxs(Select, __assign({ label: v.label, size: "small", title: v.label, sx: defaultInputProps.sx, value: (_d = row.find(function (c, _i) { return columnIndex === _i; })) === null || _d === void 0 ? void 0 : _d.entry, onChange: function (e) { return handleChange(i, columnIndex, { label: v.label, entry: e.target.value }); } }, { children: [_jsx(MenuItem, __assign({ value: "" }, { children: _jsx("em", { children: "None" }) })), v.info.choices.map(function (c) { return (_jsx(MenuItem, __assign({ value: c }, { children: c }), c)); })] }))] })))
244
+ : (v.type === 'Database' && v.info.databaseId && v.info.databaseLabel) ? (_jsx(DatabaseSelectInput, { responses: [], size: "small", field: __assign(__assign({}, field), { options: { databaseId: v.info.databaseId, databaseLabel: v.info.databaseLabel }, title: v.label }), value: ((_e = row.find(function (_, _i) { return columnIndex === _i; })) === null || _e === void 0 ? void 0 : _e.entry) ? [{
245
+ text: JSON.parse(((_f = row.find(function (_, _i) { return columnIndex === _i; })) === null || _f === void 0 ? void 0 : _f.entry) || '{}').text || '',
246
+ databaseId: JSON.parse(((_g = row.find(function (_, _i) { return columnIndex === _i; })) === null || _g === void 0 ? void 0 : _g.entry) || '{}').databaseId || '',
247
+ recordId: JSON.parse(((_h = row.find(function (_, _i) { return columnIndex === _i; })) === null || _h === void 0 ? void 0 : _h.entry) || '{}').recordId || '',
248
+ }] : [], onChange: function (records) { var _a; return handleChange(i, columnIndex, { label: v.label, entry: JSON.stringify((_a = records === null || records === void 0 ? void 0 : records[0]) !== null && _a !== void 0 ? _a : '') }); } }))
249
+ : null }), v.label));
250
+ }), _jsx(Grid, __assign({ item: true, sx: { ml: 'auto', width: iconWidth } }, { children: _jsx(LabeledIconButton, { Icon: CancelIcon, label: "Remove", onClick: function () { return handleRemove(i); }, disabled: !field.isOptional && value.length === 1 }) }))] }), i), _jsx(Divider, { flexItem: true, sx: { my: 1 } })] })); }), _jsx(Button, __assign({ variant: "outlined", size: "small", onClick: handleNewRow, sx: { width: 200 } }, { children: "Add new entry" }))] })));
251
+ };
252
+ export var AutoFocusTextField = function (props) { return (_jsx(TextField, __assign({ InputProps: defaultInputProps }, props))); };
253
+ var CustomDateStringInput = forwardRef(function (props, ref) { return (_jsx(TextField, __assign({ InputProps: defaultInputProps, fullWidth: true, inputRef: ref }, props))); });
254
+ export var DateStringInput = function (_a) {
255
+ var _b;
256
+ var field = _a.field, value = _a.value, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
257
+ var inputRef = useRef(null);
258
+ // if (value && isDateString(value)) {
259
+ // console.log(value, new Date(
260
+ // new Date(MM_DD_YYYY_to_YYYY_MM_DD(value)).getTime()
261
+ // + (new Date().getTimezoneOffset() * 60 * 1000)
262
+ // ))
263
+ // }
264
+ return (((_b = field.options) === null || _b === void 0 ? void 0 : _b.useDatePicker)
265
+ ? (_jsx(DatePicker // wrap in item to prevent movement on focused
266
+ , { selected: (value && isDateString(value))
267
+ ? new Date(new Date(MM_DD_YYYY_to_YYYY_MM_DD(value)).getTime()
268
+ + ((new Date().getTimezoneOffset() + 60) * 60 * 1000) // additional hour (60 minutes) needs to be added for date to line up properly
269
+ )
270
+ : undefined, onChange: function (d) { return onChange === null || onChange === void 0 ? void 0 : onChange(mm_dd_yyyy(d), field.id); }, showTimeSelect: false, required: !field.isOptional, autoComplete: "off", dateFormat: "MM-dd-yyyy", customInput: _jsx(CustomDateStringInput, __assign({ inputRef: inputRef }, props, { label: (!field.title && field.placeholder) ? field.placeholder : props.label })),
271
+ // className={css`width: 100%;`}
272
+ className: css(templateObject_2 || (templateObject_2 = __makeTemplateObject(["", ""], ["", ""])), datepickerCSS) }))
273
+ : (_jsx(AutoFocusTextField, __assign({}, props, { required: !field.isOptional, fullWidth: true, placeholder: "MM-DD-YYYY", value: value, label: (!field.title && field.placeholder) ? field.placeholder : props.label, onChange: function (e) {
274
+ var v = e.target.value || '';
275
+ onChange((v.length === 2 && /\d{2}/.test(v) && (value === null || value === void 0 ? void 0 : value.length) !== 3 // allow deletion
276
+ ? v + '-'
277
+ : v.length === 5 && /\d{2}-\d{2}/.test(v) && (value === null || value === void 0 ? void 0 : value.length) !== 6 // allow deletion
278
+ ? v + '-'
279
+ : v)
280
+ .replaceAll('/', '-'), field.id);
281
+ } }))));
282
+ };
283
+ export var StringInput = function (_a) {
284
+ var field = _a.field, value = _a.value, form = _a.form, onChange = _a.onChange, props = __rest(_a, ["field", "value", "form", "onChange"]);
285
+ return (_jsx(AutoFocusTextField, __assign({}, props, { required: !field.isOptional, fullWidth: true, value: value, onChange: function (e) { return onChange(e.target.value, field.id); }, placeholder: (field.placeholder || form_display_text_for_language(form, "Answer here...", '')), label: (!field.title && field.placeholder) ? field.placeholder : props.label })));
286
+ };
287
+ export var StringLongInput = function (_a) {
288
+ var field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, props = __rest(_a, ["field", "value", "onChange", "form"]);
289
+ return (_jsx(AutoFocusTextField, __assign({}, props, { multiline: true, minRows: 3, maxRows: 8, required: !field.isOptional, fullWidth: true, value: value, onChange: function (e) { return onChange(e.target.value, field.id); }, placeholder: field.placeholder || form_display_text_for_language(form, "Answer here...", ''), label: (!field.title && field.placeholder) ? field.placeholder : props.label })));
290
+ };
291
+ export var PhoneInput = function (_a) {
292
+ var field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, props = __rest(_a, ["field", "value", "onChange", "form"]);
293
+ return (_jsx(AutoFocusTextField, __assign({}, props, { required: !field.isOptional, fullWidth: true, value: value, onChange: function (e) { return onChange(e.target.value, field.id); }, placeholder: field.placeholder || form_display_text_for_language(form, "Enter phone...", ''), label: (!field.title && field.placeholder) ? field.placeholder : props.label })));
294
+ };
295
+ export var EmailInput = function (_a) {
296
+ var field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, props = __rest(_a, ["field", "value", "onChange", "form"]);
297
+ return (_jsx(AutoFocusTextField, __assign({}, props, { required: !field.isOptional, fullWidth: true, type: "email", value: value, onChange: function (e) { return onChange(e.target.value, field.id); }, placeholder: field.placeholder || form_display_text_for_language(form, "Enter email...", ''), label: (!field.title && field.placeholder) ? field.placeholder : props.label })));
298
+ };
299
+ export var NumberInput = function (_a) {
300
+ var field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, props = __rest(_a, ["field", "value", "onChange", "form"]);
301
+ // Prevent the default scroll behavior when focused on this input
302
+ var inputRef = useRef(null);
303
+ useEffect(function () {
304
+ var _a;
305
+ var handleWheel = function (e) {
306
+ var _a;
307
+ (_a = e === null || e === void 0 ? void 0 : e.preventDefault) === null || _a === void 0 ? void 0 : _a.call(e);
308
+ };
309
+ // Get the actual input element inside the TextField
310
+ var inputElement = (_a = inputRef.current) === null || _a === void 0 ? void 0 : _a.querySelector('input');
311
+ if (inputElement) {
312
+ inputElement.addEventListener('wheel', handleWheel, { passive: false });
313
+ // Clean up event listener when component unmounts
314
+ return function () {
315
+ inputElement.removeEventListener('wheel', handleWheel);
316
+ };
317
+ }
318
+ }, []);
319
+ return (_jsx(TextField, __assign({ ref: inputRef, autoFocus: true, InputProps: defaultInputProps }, props, { required: !field.isOptional, fullWidth: true, type: "number", value: value, onChange: function (e) { return onChange(parseInt(e.target.value), field.id); }, label: (!field.title && field.placeholder) ? field.placeholder : props.label, placeholder: field.placeholder || form_display_text_for_language(form, "Enter a number...", ''), onScroll: function (e) { return e.preventDefault(); }, sx: {
320
+ '& input[type=number]': {
321
+ '-moz-appearance': 'textfield'
322
+ },
323
+ '& input[type=number]::-webkit-outer-spin-button': {
324
+ '-webkit-appearance': 'none',
325
+ margin: 0
326
+ },
327
+ '& input[type=number]::-webkit-inner-spin-button': {
328
+ '-webkit-appearance': 'none',
329
+ margin: 0
330
+ }
331
+ } })));
332
+ };
333
+ export var InsuranceInput = function (_a) {
334
+ var _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
335
+ var field = _a.field, onDatabaseSelect = _a.onDatabaseSelect, value = _a.value, onChange = _a.onChange, form = _a.form, responses = _a.responses, enduser = _a.enduser, props = __rest(_a, ["field", "onDatabaseSelect", "value", "onChange", "form", "responses", "enduser"]);
336
+ var session = useResolvedSession();
337
+ var _t = useState([]), payers = _t[0], setPayers = _t[1];
338
+ var _u = useState(''), query = _u[0], setQuery = _u[1];
339
+ var addressQuestion = useMemo(function () { return responses === null || responses === void 0 ? void 0 : responses.find(function (r) {
340
+ var _a;
341
+ if (r.answer.type !== 'Address')
342
+ return false;
343
+ if (r.field.intakeField !== 'Address')
344
+ return false;
345
+ // make sure state is actually defined (in case of multiple address questions, where 1+ are blank)
346
+ if (!((_a = r.answer.value) === null || _a === void 0 ? void 0 : _a.state))
347
+ return false;
348
+ return true;
349
+ }); }, [responses]);
350
+ var state = useMemo(function () {
351
+ var _a, _b, _d;
352
+ return ((((_a = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _a === void 0 ? void 0 : _a.type) === 'Address' ? (_d = (_b = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _b === void 0 ? void 0 : _b.value) === null || _d === void 0 ? void 0 : _d.state : undefined) || (enduser === null || enduser === void 0 ? void 0 : enduser.state));
353
+ }, [enduser === null || enduser === void 0 ? void 0 : enduser.state, addressQuestion]);
354
+ var loadRef = useRef(false); // so session changes don't cause
355
+ useEffect(function () {
356
+ var _a;
357
+ if (((_a = field === null || field === void 0 ? void 0 : field.options) === null || _a === void 0 ? void 0 : _a.dataSource) === CANVAS_TITLE)
358
+ return; // instead, look-up while typing against Canvas Search API
359
+ if (loadRef.current)
360
+ return;
361
+ loadRef.current = true;
362
+ // just load all at once, should be reasonably performant compared to paging
363
+ session.api.form_fields.load_choices_from_database({ fieldId: field.id, limit: 10000 })
364
+ .then(function (_a) {
365
+ var choices = _a.choices;
366
+ return setPayers(choices
367
+ .map(function (c) {
368
+ var _a, _b, _d, _e, _f, _g, _h, _j;
369
+ return ({
370
+ id: ((_b = (_a = c.values.find(function (v) { var _a, _b; return ((_b = (_a = v.label) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'id'; })) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.toString()) || '',
371
+ name: ((_e = (_d = c.values.find(function (v) { var _a, _b; return ((_b = (_a = v.label) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'name'; })) === null || _d === void 0 ? void 0 : _d.value) === null || _e === void 0 ? void 0 : _e.toString()) || '',
372
+ state: ((_g = (_f = c.values.find(function (v) { var _a, _b; return ((_b = (_a = v.label) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'state'; })) === null || _f === void 0 ? void 0 : _f.value) === null || _g === void 0 ? void 0 : _g.toString()) || '',
373
+ type: ((_j = (_h = c.values.find(function (v) { var _a, _b; return ((_b = (_a = v.label) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'type'; })) === null || _h === void 0 ? void 0 : _h.value) === null || _j === void 0 ? void 0 : _j.toString()) || '',
374
+ databaseRecord: c,
375
+ });
376
+ })
377
+ .filter(function (c) { return !c.state || !state || (c.state === state); }));
378
+ })
379
+ .catch(console.error);
380
+ }, [session, state, (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.dataSource]);
381
+ var searchRef = useRef(query);
382
+ useEffect(function () {
383
+ var _a;
384
+ if (((_a = field === null || field === void 0 ? void 0 : field.options) === null || _a === void 0 ? void 0 : _a.dataSource) !== CANVAS_TITLE) {
385
+ return;
386
+ }
387
+ if (!query)
388
+ return;
389
+ if (searchRef.current === query)
390
+ return;
391
+ searchRef.current = query;
392
+ session.api.integrations.proxy_read({
393
+ integration: CANVAS_TITLE,
394
+ query: query,
395
+ type: 'organizations',
396
+ })
397
+ .then(function (_a) {
398
+ var data = _a.data;
399
+ try {
400
+ setPayers(data.map(function (d) { return ({
401
+ id: d.resource.id,
402
+ name: d.resource.name,
403
+ }); }));
404
+ }
405
+ catch (err) {
406
+ console.error;
407
+ }
408
+ })
409
+ .catch(console.error);
410
+ }, [session, (_d = field === null || field === void 0 ? void 0 : field.options) === null || _d === void 0 ? void 0 : _d.dataSource, query]);
411
+ return (_jsxs(Grid, __assign({ container: true, spacing: 2, sx: { mt: '0' } }, { children: [_jsx(Grid, __assign({ item: true, xs: 12, sm: 6 }, { children: _jsx(Autocomplete, { freeSolo: !((_e = field.options) === null || _e === void 0 ? void 0 : _e.requirePredefinedInsurer), options: payers.map(function (p) { return p.name; }), value: (value === null || value === void 0 ? void 0 : value.payerName) || '', onChange: function (e, v) {
412
+ var _a, _b;
413
+ return onChange(__assign(__assign({}, value), { payerName: v || '', payerId: ((_a = payers.find(function (p) { return p.name === v; })) === null || _a === void 0 ? void 0 : _a.id) || '', payerType: ((_b = payers.find(function (p) { return p.name === v; })) === null || _b === void 0 ? void 0 : _b.type) || '' }), field.id);
414
+ }, onInputChange: ((_f = field.options) === null || _f === void 0 ? void 0 : _f.requirePredefinedInsurer)
415
+ ? function (e, v) { if (v) {
416
+ setQuery(v);
417
+ } }
418
+ : function (e, v) {
419
+ var _a, _b, _d;
420
+ if (v) {
421
+ setQuery(v);
422
+ }
423
+ var databaseRecord = (_a = payers.find(function (p) { return p.name === v; })) === null || _a === void 0 ? void 0 : _a.databaseRecord;
424
+ if (databaseRecord) {
425
+ onDatabaseSelect === null || onDatabaseSelect === void 0 ? void 0 : onDatabaseSelect([databaseRecord]);
426
+ }
427
+ onChange(__assign(__assign({}, value), { payerName: v || '', payerId: ((_b = payers.find(function (p) { return p.name === v; })) === null || _b === void 0 ? void 0 : _b.id) || '', payerType: ((_d = payers.find(function (p) { return p.name === v; })) === null || _d === void 0 ? void 0 : _d.type) || '' }), field.id);
428
+ }, renderInput: function (params) {
429
+ var _a;
430
+ return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, size: "small", label: "Insurer", placeholder: ((_a = field.options) === null || _a === void 0 ? void 0 : _a.dataSource) === CANVAS_TITLE ? "Search insurer..." : "Insurer" })));
431
+ } }) })), _jsx(Grid, __assign({ item: true, xs: 12, sm: 6 }, { children: _jsx(TextField, { InputProps: defaultInputProps, required: !field.isOptional, fullWidth: true, value: (_g = value === null || value === void 0 ? void 0 : value.memberId) !== null && _g !== void 0 ? _g : '', onChange: function (e) { return onChange(__assign(__assign({}, value), { memberId: e.target.value }), field.id); }, label: form_display_text_for_language(form, "Member ID", ''), size: "small" }) })), _jsx(Grid, __assign({ item: true, xs: 12, sm: 6 }, { children: _jsx(TextField, { InputProps: defaultInputProps, required: false, fullWidth: true, value: (_h = value === null || value === void 0 ? void 0 : value.planName) !== null && _h !== void 0 ? _h : '', onChange: function (e) { return onChange(__assign(__assign({}, value), { planName: e.target.value }), field.id); }, label: form_display_text_for_language(form, "Plan Name", ''), size: "small" }) })), _jsx(Grid, __assign({ item: true, xs: 12, sm: 6 }, { children: _jsx(DateStringInput, { size: "small", label: "Plan Start Date", field: __assign(__assign({}, field), { isOptional: true }), value: (value === null || value === void 0 ? void 0 : value.startDate) || '', onChange: function (startDate) {
432
+ return onChange(__assign(__assign({}, value), { startDate: startDate }), field.id);
433
+ } }) })), ((_j = field.options) === null || _j === void 0 ? void 0 : _j.includeGroupNumber) &&
434
+ _jsx(Grid, __assign({ item: true, xs: 12 }, { children: _jsx(TextField, { InputProps: defaultInputProps, fullWidth: true, value: (_k = value === null || value === void 0 ? void 0 : value.groupNumber) !== null && _k !== void 0 ? _k : '', onChange: function (e) { return onChange(__assign(__assign({}, value), { groupNumber: e.target.value }), field.id); }, label: form_display_text_for_language(form, "Group Number", ''), size: "small" }) })), _jsx(Grid, __assign({ item: true, xs: 12 }, { children: _jsx(StringSelector, { size: "small", label: "Relationship to Policy Owner", options: ((((_l = field.options) === null || _l === void 0 ? void 0 : _l.billingProvider) === CANVAS_TITLE || ((_m = field.options) === null || _m === void 0 ? void 0 : _m.dataSource) === CANVAS_TITLE)
435
+ ? INSURANCE_RELATIONSHIPS_CANVAS
436
+ : INSURANCE_RELATIONSHIPS)
437
+ .sort(function (x, y) { return x.localeCompare(y); }), value: (value === null || value === void 0 ? void 0 : value.relationship) || 'Self', onChange: function (relationship) {
438
+ return onChange(__assign(__assign({}, value), { relationship: relationship || 'Self' }), field.id);
439
+ } }) })), ((value === null || value === void 0 ? void 0 : value.relationship) || 'Self') !== 'Self' &&
440
+ _jsxs(_Fragment, { children: [_jsx(Grid, __assign({ item: true, xs: 12 }, { children: _jsx(Typography, __assign({ sx: { fontWeight: 'bold' } }, { children: "Policy Owner Details" })) })), _jsx(Grid, __assign({ item: true, xs: 6 }, { children: _jsx(TextField, { label: "First Name", size: "small", InputProps: defaultInputProps, fullWidth: true, value: ((_o = value === null || value === void 0 ? void 0 : value.relationshipDetails) === null || _o === void 0 ? void 0 : _o.fname) || '', required: !field.isOptional, onChange: function (e) {
441
+ return onChange(__assign(__assign({}, value), { relationshipDetails: __assign(__assign({}, value === null || value === void 0 ? void 0 : value.relationshipDetails), { fname: e.target.value }) }), field.id);
442
+ } }) })), _jsx(Grid, __assign({ item: true, xs: 6 }, { children: _jsx(TextField, { label: "Last Name", size: "small", InputProps: defaultInputProps, fullWidth: true, value: ((_p = value === null || value === void 0 ? void 0 : value.relationshipDetails) === null || _p === void 0 ? void 0 : _p.lname) || '', required: !field.isOptional, onChange: function (e) {
443
+ return onChange(__assign(__assign({}, value), { relationshipDetails: __assign(__assign({}, value === null || value === void 0 ? void 0 : value.relationshipDetails), { lname: e.target.value }) }), field.id);
444
+ } }) })), _jsx(Grid, __assign({ item: true, xs: 6 }, { children: _jsx(StringSelector, { options: TELLESCOPE_GENDERS, size: "small", label: "Gender", value: ((_q = value === null || value === void 0 ? void 0 : value.relationshipDetails) === null || _q === void 0 ? void 0 : _q.gender) || '', required: !field.isOptional, onChange: function (v) {
445
+ return onChange(__assign(__assign({}, value), { relationshipDetails: __assign(__assign({}, value === null || value === void 0 ? void 0 : value.relationshipDetails), { gender: v }) }), field.id);
446
+ } }) })), _jsx(Grid, __assign({ item: true, xs: 6 }, { children: _jsx(DateStringInput, { size: "small", label: "Date of Birth", field: __assign(__assign({}, field), { isOptional: field.isOptional || ((_r = field.options) === null || _r === void 0 ? void 0 : _r.billingProvider) === 'Candid' }), value: ((_s = value === null || value === void 0 ? void 0 : value.relationshipDetails) === null || _s === void 0 ? void 0 : _s.dateOfBirth) || '', onChange: function (dateOfBirth) {
447
+ return onChange(__assign(__assign({}, value), { relationshipDetails: __assign(__assign({}, value === null || value === void 0 ? void 0 : value.relationshipDetails), { dateOfBirth: dateOfBirth }) }), field.id);
448
+ } }) }))] })] })));
449
+ };
450
+ var StringSelector = function (_a) {
451
+ var options = _a.options, value = _a.value, onChange = _a.onChange, required = _a.required, getDisplayValue = _a.getDisplayValue, props = __rest(_a, ["options", "value", "onChange", "required", "getDisplayValue"]);
452
+ return (_jsxs(FormControl, __assign({ fullWidth: true, size: props.size, required: required }, { children: [_jsx(InputLabel, { children: props.label }), _jsx(Select, __assign({}, props, { value: value, onChange: function (e) { return onChange(e.target.value); }, fullWidth: true, sx: defaultInputProps.sx }, { children: options.map(function (o, i) {
453
+ var _a;
454
+ return (_jsx(MenuItem, __assign({ value: o }, { children: (_a = getDisplayValue === null || getDisplayValue === void 0 ? void 0 : getDisplayValue(o)) !== null && _a !== void 0 ? _a : o }), o || i));
455
+ }) }))] })));
456
+ };
457
+ var HourSelector = function (props) { return (_jsx(StringSelector, __assign({}, props, { options: Array(12).fill('').map(function (_, i) { return (i + 1) <= 9 ? "0".concat(i + 1) : (i + 1).toString(); }) }))); };
458
+ var MinuteSelector = function (props) { return (_jsx(StringSelector, __assign({}, props, { options: Array(60).fill('').map(function (_, i) { return i <= 9 ? "0".concat(i) : i.toString(); }) }))); };
459
+ var AmPmSelector = function (props) { return (_jsx(StringSelector, __assign({}, props, { options: ['AM', 'PM'] }))); };
460
+ export var TimeInput = function (_a) {
461
+ var field = _a.field, value = _a.value, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
462
+ var _b = (value || '').split(':'), hour = _b[0], _d = _b[1], rest = _d === void 0 ? '' : _d;
463
+ var _e = rest.split(' '), minute = _e[0], amPm = _e[1], _f = _e[2], zone = _f === void 0 ? getLocalTimezone() : _f;
464
+ return (_jsxs(Grid, __assign({ container: true, alignItems: 'center', spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true, sx: { width: 100 } }, { children: _jsx(HourSelector, { value: hour, onChange: function (hour) { return onChange("".concat(hour, ":").concat(minute, " ").concat(amPm, " ").concat(zone), field.id); } }) })), _jsx(Grid, __assign({ item: true, sx: { width: 100 } }, { children: _jsx(MinuteSelector, { value: minute, onChange: function (minute) { return onChange("".concat(hour, ":").concat(minute, " ").concat(amPm, " ").concat(zone), field.id); } }) })), _jsx(Grid, __assign({ item: true, sx: { width: 100 } }, { children: _jsx(AmPmSelector, { value: amPm, onChange: function (amPm) { return onChange("".concat(hour, ":").concat(minute, " ").concat(amPm, " ").concat(zone), field.id); } }) }))] })));
465
+ };
466
+ export var TimezoneInput = function (_a) {
467
+ var _b = _a.value, value = _b === void 0 ? '' : _b, field = _a.field, onChange = _a.onChange, props = __rest(_a, ["value", "field", "onChange"]);
468
+ return (_jsx(StringSelector, __assign({}, props, { value: value, options: TIMEZONES_USA, onChange: function (v) { return onChange(v, field.id); } })));
469
+ };
470
+ export var AddressInput = function (_a) {
471
+ var _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
472
+ var field = _a.field, form = _a.form, value = _a.value, onChange = _a.onChange, props = __rest(_a, ["field", "form", "value", "onChange"]);
473
+ return (
474
+ // state only
475
+ ((_d = (_b = field.options) === null || _b === void 0 ? void 0 : _b.addressFields) === null || _d === void 0 ? void 0 : _d.includes('state'))
476
+ ? (_jsx(Autocomplete, __assign({ value: (value === null || value === void 0 ? void 0 : value.state) || '', options: ((_f = (_e = field.options) === null || _e === void 0 ? void 0 : _e.validStates) === null || _f === void 0 ? void 0 : _f.length) ? field.options.validStates : VALID_STATES, disablePortal: true, onChange: function (e, v) { return v &&
477
+ onChange(__assign(__assign({}, value), { state: v !== null && v !== void 0 ? v : '' }), field.id); }, renderInput: function (params) { return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional,
478
+ // don't use 'small' so as to be consistent with other text fields, in case this is used in a group
479
+ // size={'small'}
480
+ label: form_display_text_for_language(form, "State") }))); } }, props)))
481
+ : (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 2, sx: { mt: 0 } }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(AutoFocusTextField, __assign({}, props, { size: "small", required: !field.isOptional, fullWidth: true, value: (_g = value === null || value === void 0 ? void 0 : value.addressLineOne) !== null && _g !== void 0 ? _g : '', label: form_display_text_for_language(form, "Address Line 1"), placeholder: form_display_text_for_language(form, "Address Line 1"), onChange: function (e) {
482
+ var _a;
483
+ return onChange(__assign(__assign({}, value), { addressLineOne: (_a = e.target.value) !== null && _a !== void 0 ? _a : '' }), field.id);
484
+ } })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(TextField, __assign({}, props, { size: "small", required: false, fullWidth: true, InputProps: defaultInputProps, value: (_h = value === null || value === void 0 ? void 0 : value.addressLineTwo) !== null && _h !== void 0 ? _h : '', label: form_display_text_for_language(form, "Address Line 2"), placeholder: form_display_text_for_language(form, "Address Line 2"), onChange: function (e) {
485
+ var _a;
486
+ return onChange(__assign(__assign({}, value), { addressLineTwo: (_a = e.target.value) !== null && _a !== void 0 ? _a : '' }), field.id);
487
+ } })) })), _jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", justifyContent: "space-between", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true, xs: 12, sm: field.fullZIP ? 5 : 6 }, { children: _jsx(TextField, __assign({}, props, { size: "small", required: !field.isOptional, InputProps: defaultInputProps, fullWidth: true, value: (_j = value === null || value === void 0 ? void 0 : value.city) !== null && _j !== void 0 ? _j : '', label: form_display_text_for_language(form, "City"), placeholder: form_display_text_for_language(form, "City"), onChange: function (e) {
488
+ var _a;
489
+ return onChange(__assign(__assign({}, value), { city: (_a = e.target.value) !== null && _a !== void 0 ? _a : '' }), field.id);
490
+ } })) })), _jsx(Grid, __assign({ item: true, xs: field.fullZIP ? 4 : 6, sm: field.fullZIP ? 2 : 3 }, { children: _jsx(Autocomplete, __assign({ value: (value === null || value === void 0 ? void 0 : value.state) || '', fullWidth: true, options: ((_l = (_k = field.options) === null || _k === void 0 ? void 0 : _k.validStates) === null || _l === void 0 ? void 0 : _l.length) ? field.options.validStates : VALID_STATES, disablePortal: true, onChange: function (e, v) { return v &&
491
+ onChange(__assign(__assign({}, value), { state: v !== null && v !== void 0 ? v : '' }), field.id); }, renderInput: function (params) { return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), size: 'small', required: !field.isOptional, label: form_display_text_for_language(form, "State") }))); } }, props)) })), _jsx(Grid, __assign({ item: true, xs: field.fullZIP ? 5 : 6, sm: field.fullZIP ? 2 : 3 }, { children: _jsx(TextField, __assign({}, props, { size: "small", required: !field.isOptional, InputProps: defaultInputProps, fullWidth: true, value: (_m = value === null || value === void 0 ? void 0 : value.zipCode) !== null && _m !== void 0 ? _m : '', label: form_display_text_for_language(form, "ZIP Code"), placeholder: form_display_text_for_language(form, "ZIP Code"), onChange: function (e) {
492
+ var _a;
493
+ return onChange(__assign(__assign({}, value), { zipCode: (_a = e.target.value) !== null && _a !== void 0 ? _a : '' }), field.id);
494
+ } })) })), field.fullZIP &&
495
+ _jsx(Grid, __assign({ item: true, xs: 3 }, { children: _jsx(TextField, __assign({}, props, { size: "small", label: "ZIP+4", required: !field.isOptional && field.fullZIP, InputProps: defaultInputProps, value: (_o = value === null || value === void 0 ? void 0 : value.zipPlusFour) !== null && _o !== void 0 ? _o : '', placeholder: "ZIP + 4", onChange: function (e) {
496
+ var _a;
497
+ return onChange(__assign(__assign({}, value), { zipPlusFour: (_a = e.target.value) !== null && _a !== void 0 ? _a : '' }), field.id);
498
+ } })) }))] })) }))] }))));
499
+ };
500
+ export var ESignatureTerms = function () {
501
+ var companyName = 'Tellescope';
502
+ try {
503
+ var indexOfName = window.location.href.indexOf('name=');
504
+ if (indexOfName !== -1) {
505
+ companyName = (decodeURIComponent(window.location.href.substring(indexOfName + 5))
506
+ || companyName);
507
+ }
508
+ }
509
+ catch (err) {
510
+ console.error(err);
511
+ }
512
+ return (_jsxs("div", __assign({ style: { paddingLeft: 10 } }, { children: [_jsxs("h1", { children: [companyName, " Electronic Signature Terms"] }), _jsxs("p", { children: ["By selecting the \"I consent to use electronic signatures\" checkbox, you are signing this Agreement electronically. You agree your electronic signature is the legal equivalent of your manual/handwritten signature on this Agreement. By selecting \"I consent to use electronic signatures\" using any device, means or action, you consent to the legally binding terms and conditions of this Agreement. You further agree that your signature on this document (hereafter referred to as your \"E-Signature\") is as valid as if you signed the document in writing. You also agree that no certification authority or other third party verification is necessary to validate your E-Signature, and that the lack of such certification or third party verification will not in any way affect the enforceability of your E-Signature or any resulting agreement between you and", companyName, " or between you and a customer of ", companyName, "."] })] })));
513
+ };
514
+ export var SignatureInput = function (_a) {
515
+ var _b, _d, _e, _f, _g;
516
+ var value = _a.value, field = _a.field, _h = _a.autoFocus, autoFocus = _h === void 0 ? true : _h, enduser = _a.enduser, onChange = _a.onChange;
517
+ var prefill = (((_b = field.options) === null || _b === void 0 ? void 0 : _b.prefillSignature) && (enduser === null || enduser === void 0 ? void 0 : enduser.fname) && enduser.lname
518
+ ? "".concat(enduser.fname, " ").concat(enduser.lname)
519
+ : undefined);
520
+ var handleConsentChange = function () {
521
+ var _a, _b, _d, _e;
522
+ var newConsent = !(value === null || value === void 0 ? void 0 : value.signed);
523
+ onChange({
524
+ pdfAttachment: (_a = field.options) === null || _a === void 0 ? void 0 : _a.pdfAttachment,
525
+ fullName: (_d = (_b = value === null || value === void 0 ? void 0 : value.fullName) !== null && _b !== void 0 ? _b : prefill) !== null && _d !== void 0 ? _d : '',
526
+ signed: newConsent,
527
+ url: (_e = field.options) === null || _e === void 0 ? void 0 : _e.signatureUrl,
528
+ }, field.id);
529
+ };
530
+ var handleNameChange = function (newName) {
531
+ var _a, _b, _d;
532
+ onChange({
533
+ pdfAttachment: (_a = field.options) === null || _a === void 0 ? void 0 : _a.pdfAttachment,
534
+ signed: (_b = value === null || value === void 0 ? void 0 : value.signed) !== null && _b !== void 0 ? _b : false,
535
+ fullName: newName,
536
+ url: (_d = field.options) === null || _d === void 0 ? void 0 : _d.signatureUrl,
537
+ }, field.id);
538
+ };
539
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center" }, { children: [((_d = field.options) === null || _d === void 0 ? void 0 : _d.pdfAttachment) &&
540
+ _jsx(PdfViewer, { url: getPublicFileURL({ businessId: field.businessId, name: field.options.pdfAttachment }) }), !((_e = field.options) === null || _e === void 0 ? void 0 : _e.pdfAttachment) && ((_f = field.options) === null || _f === void 0 ? void 0 : _f.signatureUrl) &&
541
+ _jsxs(Grid, __assign({ container: true, direction: "column", sx: { mb: 2 } }, { children: [_jsx("iframe", { src: field.options.signatureUrl, style: {
542
+ border: 'none',
543
+ height: 400,
544
+ width: '100%',
545
+ marginBottom: '5px'
546
+ } }), _jsx("a", __assign({ href: field.options.signatureUrl, target: "_blank", rel: "noopener noreferrer" }, { children: "View document in new tab" }))] })), _jsxs(Grid, __assign({ item: true, xs: 12 }, { children: [_jsx(Checkbox, { style: { margin: 0, marginTop: 5, padding: 0, paddingRight: 3 }, color: "primary", checked: !!(value === null || value === void 0 ? void 0 : value.signed), onClick: function () { return handleConsentChange(); }, inputProps: { 'aria-label': 'consent to e-signature checkbox' } }), _jsxs(Typography, __assign({ component: "span", style: { position: 'relative', top: 5, left: 2 } }, { children: ["I consent to use ", _jsx("a", __assign({ href: "/e-signature-terms?name=".concat(((_g = field.options) === null || _g === void 0 ? void 0 : _g.esignatureTermsCompanyName) || ''), target: "_blank", rel: "noopener noreferrer" }, { children: " electronic signatures " }))] }))] })), _jsxs(Grid, __assign({ item: true, xs: 12, style: { marginTop: 12 } }, { children: [_jsx(TextField, { disabled: !(value === null || value === void 0 ? void 0 : value.signed), autoFocus: autoFocus, style: { width: '100%' }, size: "small", "aria-label": "Full Name", value: value === null || value === void 0 ? void 0 : value.fullName, placeholder: prefill || "Full Name", variant: "outlined", onChange: function (e) { return handleNameChange(e.target.value); }, InputProps: defaultInputProps }), _jsx(Typography, __assign({ color: "primary", style: { fontSize: 15, marginTop: 2 } }, { children: "Enter your legal full name to complete the signature" }))] }))] })));
547
+ };
548
+ var formatBytes = function (bytes) {
549
+ if (bytes === 0)
550
+ return '0 Bytes';
551
+ var k = 1024;
552
+ var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
553
+ var i = Math.floor(Math.log(bytes) / Math.log(k));
554
+ return "".concat(parseFloat((bytes / Math.pow(k, i)).toFixed(2)), " ").concat(sizes[i]);
555
+ };
556
+ export function convertHEIC(file) {
557
+ return __awaiter(this, void 0, void 0, function () {
558
+ var blobURL, blobRes, blob, conversionResult, url;
559
+ return __generator(this, function (_a) {
560
+ switch (_a.label) {
561
+ case 0:
562
+ blobURL = (typeof file === 'string' ? file : URL.createObjectURL(file));
563
+ return [4 /*yield*/, fetch(blobURL)
564
+ // convert response to blob
565
+ ];
566
+ case 1:
567
+ blobRes = _a.sent();
568
+ return [4 /*yield*/, blobRes.blob()
569
+ // convert to PNG - response is blob
570
+ ];
571
+ case 2:
572
+ blob = _a.sent();
573
+ return [4 /*yield*/, heic2any({ blob: blob })
574
+ // convert to blob url
575
+ ];
576
+ case 3:
577
+ conversionResult = _a.sent();
578
+ url = URL.createObjectURL(Array.isArray(conversionResult) ? conversionResult[0] : conversionResult);
579
+ return [2 /*return*/, url];
580
+ }
581
+ });
582
+ });
583
+ }
584
+ ;
585
+ var value_is_image = function (f) { var _a; return (_a = f === null || f === void 0 ? void 0 : f.type) === null || _a === void 0 ? void 0 : _a.includes('image'); };
586
+ export var FileInput = function (_a) {
587
+ var _b;
588
+ var value = _a.value, onChange = _a.onChange, field = _a.field, existingFileName = _a.existingFileName, uploadingFiles = _a.uploadingFiles, handleFileUpload = _a.handleFileUpload, setUploadingFiles = _a.setUploadingFiles;
589
+ var _d = useState(''), error = _d[0], setError = _d[1];
590
+ var _e = useDropzone({
591
+ onDrop: useCallback(function (acceptedFiles) {
592
+ var _a, _b, _d, _e;
593
+ var file = acceptedFiles.pop();
594
+ if (!file)
595
+ return;
596
+ if (((_a = field.options) === null || _a === void 0 ? void 0 : _a.maxFileSize) && file.size > field.options.maxFileSize) {
597
+ return setError("File size must be less than ".concat(formatBytes(field.options.maxFileSize)));
598
+ }
599
+ if ((_d = (_b = field.options) === null || _b === void 0 ? void 0 : _b.validFileTypes) === null || _d === void 0 ? void 0 : _d.length) {
600
+ var match = field.options.validFileTypes.find(function (t) { return file.type.includes(t.toLowerCase()); });
601
+ if (!match) {
602
+ return setError("File must have type: ".concat(field.options.validFileTypes.join(', ')));
603
+ }
604
+ }
605
+ setError('');
606
+ onChange(file, field.id);
607
+ if (((_e = field.options) === null || _e === void 0 ? void 0 : _e.autoUploadFiles) && handleFileUpload) {
608
+ setUploadingFiles === null || setUploadingFiles === void 0 ? void 0 : setUploadingFiles(function (fs) { return __spreadArray(__spreadArray([], fs, true), [{ fieldId: field.id }], false); });
609
+ handleFileUpload(file, field.id)
610
+ .finally(function () { return setUploadingFiles === null || setUploadingFiles === void 0 ? void 0 : setUploadingFiles(function (fs) { return fs.filter(function (f) { return f.fieldId !== field.id; }); }); });
611
+ }
612
+ }, [onChange, (_b = field.options) === null || _b === void 0 ? void 0 : _b.validFileTypes, handleFileUpload, setUploadingFiles]),
613
+ }), getRootProps = _e.getRootProps, getInputProps = _e.getInputProps, isDragActive = _e.isDragActive;
614
+ var _f = useState(''), preview = _f[0], setPreview = _f[1];
615
+ useEffect(function () {
616
+ if (!value_is_image(value))
617
+ return;
618
+ if ((value.type.includes('heif') || value.type.includes('heic'))) {
619
+ convertHEIC(value).then(setPreview).catch(console.error);
620
+ return;
621
+ }
622
+ try {
623
+ setPreview(URL.createObjectURL(value));
624
+ }
625
+ catch (err) {
626
+ console.error(err);
627
+ }
628
+ }, [value]);
629
+ if (uploadingFiles === null || uploadingFiles === void 0 ? void 0 : uploadingFiles.find(function (f) { return f.fieldId === field.id; })) {
630
+ return _jsx(LinearProgress, {});
631
+ }
632
+ return (_jsxs(Grid, __assign({ container: true, direction: "column" }, { children: [_jsxs(Grid, __assign({ container: true }, getRootProps(), { sx: {
633
+ width: "100%",
634
+ border: "1px dashed #00000033",
635
+ borderRadius: 1,
636
+ padding: (preview && !isDragActive) ? 0 : 6,
637
+ '&:hover': {
638
+ border: "1px solid ".concat(PRIMARY_HEX),
639
+ cursor: 'pointer',
640
+ }
641
+ }, alignItems: "center", justifyContent: "center" }, { children: [_jsx("input", __assign({}, getInputProps({ multiple: false }))), _jsx("p", { children: value
642
+ ? (preview
643
+ ? _jsx("img", { src: preview, style: { paddingLeft: '10%', width: '80%', maxHeight: 200 } })
644
+ : "".concat(truncate_string(value.name, { length: 30, showEllipsis: true }), " selected!"))
645
+ : capture_is_supported()
646
+ ? (_jsxs(Grid, __assign({ container: true, direction: "column", alignItems: "center" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(AddPhotoAlternateIcon, { color: "primary" }) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ sx: { fontSize: 14, textAlign: 'center' } }, { children: "Select file or take picture" })) }))] })))
647
+ : _jsxs(Grid, __assign({ container: true, direction: "column", alignItems: "center", rowGap: 2 }, { children: [_jsx(UploadFile, { color: "primary", sx: { fontSize: 25 } }), _jsx(Typography, { children: isDragActive ? "Drop to select file" : "Click or drag and drop" })] })) })] })), _jsx(Grid, __assign({ item: true, alignSelf: "center", sx: { mt: 0.5 } }, { children: (!(value === null || value === void 0 ? void 0 : value.name) && existingFileName) &&
648
+ _jsxs(Typography, { children: [existingFileName, " selected!"] }) })), error &&
649
+ _jsx(Grid, __assign({ item: true, alignSelf: "center", sx: { mt: 0.5 } }, { children: _jsx(Typography, __assign({ color: "error" }, { children: error })) }))] })));
650
+ };
651
+ export var safe_create_url = function (file) {
652
+ try {
653
+ return URL.createObjectURL(file);
654
+ }
655
+ catch (err) {
656
+ console.error('safe_create_url error:', err);
657
+ return null;
658
+ }
659
+ };
660
+ export var FilesInput = function (_a) {
661
+ var _b;
662
+ var value = _a.value, onChange = _a.onChange, field = _a.field, existingFileName = _a.existingFileName, uploadingFiles = _a.uploadingFiles, handleFileUpload = _a.handleFileUpload, setUploadingFiles = _a.setUploadingFiles;
663
+ var _d = useState(''), error = _d[0], setError = _d[1];
664
+ var _e = useDropzone({
665
+ onDrop: useCallback(function (acceptedFiles) { return __awaiter(void 0, void 0, void 0, function () {
666
+ var _loop_1, _a, acceptedFiles_1, file, state_1;
667
+ var _b, _d, _e;
668
+ return __generator(this, function (_f) {
669
+ switch (_f.label) {
670
+ case 0:
671
+ setUploadingFiles === null || setUploadingFiles === void 0 ? void 0 : setUploadingFiles(function (fs) { return __spreadArray(__spreadArray([], fs, true), [{ fieldId: field.id }], false); });
672
+ _loop_1 = function (file) {
673
+ var match;
674
+ return __generator(this, function (_g) {
675
+ switch (_g.label) {
676
+ case 0:
677
+ if ((_d = (_b = field.options) === null || _b === void 0 ? void 0 : _b.validFileTypes) === null || _d === void 0 ? void 0 : _d.length) {
678
+ match = field.options.validFileTypes.find(function (t) { return file.type.includes(t.toLowerCase()); });
679
+ if (!match) {
680
+ return [2 /*return*/, { value: setError("File must have type: ".concat(field.options.validFileTypes.join(', '))) }];
681
+ }
682
+ }
683
+ if (!(((_e = field.options) === null || _e === void 0 ? void 0 : _e.autoUploadFiles) && handleFileUpload)) return [3 /*break*/, 2];
684
+ return [4 /*yield*/, handleFileUpload(file, field.id).catch(console.error)];
685
+ case 1:
686
+ _g.sent();
687
+ _g.label = 2;
688
+ case 2: return [2 /*return*/];
689
+ }
690
+ });
691
+ };
692
+ _a = 0, acceptedFiles_1 = acceptedFiles;
693
+ _f.label = 1;
694
+ case 1:
695
+ if (!(_a < acceptedFiles_1.length)) return [3 /*break*/, 4];
696
+ file = acceptedFiles_1[_a];
697
+ return [5 /*yield**/, _loop_1(file)];
698
+ case 2:
699
+ state_1 = _f.sent();
700
+ if (typeof state_1 === "object")
701
+ return [2 /*return*/, state_1.value];
702
+ _f.label = 3;
703
+ case 3:
704
+ _a++;
705
+ return [3 /*break*/, 1];
706
+ case 4:
707
+ setUploadingFiles === null || setUploadingFiles === void 0 ? void 0 : setUploadingFiles(function (fs) { return fs.filter(function (f) { return f.fieldId !== field.id; }); });
708
+ setError('');
709
+ onChange(__spreadArray(__spreadArray([], (value !== null && value !== void 0 ? value : []), true), acceptedFiles, true), field.id);
710
+ return [2 /*return*/];
711
+ }
712
+ });
713
+ }); }, [onChange, value, (_b = field.options) === null || _b === void 0 ? void 0 : _b.validFileTypes, handleFileUpload, setUploadingFiles]),
714
+ }), getRootProps = _e.getRootProps, getInputProps = _e.getInputProps, isDragActive = _e.isDragActive;
715
+ var previews = useMemo(function () { return ((value !== null && value !== void 0 ? value : []).map(function (v) {
716
+ return value_is_image(v) ? safe_create_url(v) : null;
717
+ })); }, [value]);
718
+ if (uploadingFiles === null || uploadingFiles === void 0 ? void 0 : uploadingFiles.find(function (f) { return f.fieldId === field.id; })) {
719
+ return _jsx(LinearProgress, {});
720
+ }
721
+ return (_jsxs(Grid, __assign({ container: true, direction: "column" }, { children: [_jsxs(Grid, __assign({ container: true }, getRootProps(), { sx: {
722
+ width: "100%",
723
+ border: "1px dashed #00000033",
724
+ borderRadius: 1,
725
+ padding: 2,
726
+ '&:hover': {
727
+ border: "1px solid ".concat(PRIMARY_HEX),
728
+ cursor: 'pointer',
729
+ }
730
+ }, alignItems: "center", justifyContent: "center" }, { children: [_jsx("input", __assign({}, getInputProps({ multiple: false }))), _jsx("p", { children: capture_is_supported()
731
+ ? (_jsxs(Grid, __assign({ container: true, direction: "column", alignItems: "center" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(AddPhotoAlternateIcon, { color: "primary" }) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ sx: { fontSize: 14, textAlign: 'center' } }, { children: "Select files or take pictures" })) }))] })))
732
+ : _jsxs(Grid, __assign({ container: true, direction: "column", alignItems: "center", rowGap: 2 }, { children: [_jsx(UploadFile, { color: "primary", sx: { fontSize: 25 } }), _jsx(Typography, { children: isDragActive ? "Drop to select files" : "Click or drag and drop" })] })) })] })), _jsx(Grid, __assign({ container: true, direction: "column", sx: { overflowY: 'auto', maxHeight: '250px', mt: 1 }, wrap: "nowrap" }, { children: value === null || value === void 0 ? void 0 : value.map(function (file, i) {
733
+ var _a;
734
+ return (_jsx(Grid, __assign({ item: true, sx: { mt: 0.5 } }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", justifyContent: "space-between", wrap: "nowrap" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center" }, { children: [_jsx(Typography, __assign({ sx: { mr: 1 } }, { children: file.name })), ((_a = file.type) === null || _a === void 0 ? void 0 : _a.includes('image')) && previews[i] &&
735
+ _jsx(Grid, __assign({ item: true }, { children: _jsx("img", { src: previews[i], style: { maxWidth: '45%', maxHeight: 80, height: '100%' } }) }))] })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(LabeledIconButton, { label: "Remove", Icon: Delete, onClick: function () { return onChange(value.filter(function (f, _i) { return i !== _i; }), field.id); } }) }))] })) }), i));
736
+ }) })), error &&
737
+ _jsx(Grid, __assign({ item: true, alignSelf: "center", sx: { mt: 0.5 } }, { children: _jsx(Typography, __assign({ color: "error" }, { children: error })) }))] })));
738
+ };
739
+ export var MultipleChoiceInput = function (_a) {
740
+ var _b, _d, _e;
741
+ var field = _a.field, form = _a.form, _value = _a.value, onChange = _a.onChange;
742
+ var value = typeof _value === 'string' ? [_value] : _value; // if loading existingResponses, allows them to be a string
743
+ var _f = field.options, choices = _f.choices, radio = _f.radio, other = _f.other, optionDetails = _f.optionDetails;
744
+ var _g = useState({}), expandedDescriptions = _g[0], setExpandedDescriptions = _g[1];
745
+ // current other string
746
+ var enteringOtherStringRef = React.useRef(''); // if typing otherString as prefix of a checkbox value, don't auto-select
747
+ var otherString = (_b = value === null || value === void 0 ? void 0 : value.find(function (v) { var _a; return v === enteringOtherStringRef.current || !((_a = (choices !== null && choices !== void 0 ? choices : [])) === null || _a === void 0 ? void 0 : _a.find(function (c) { return c === v; })); })) !== null && _b !== void 0 ? _b : '';
748
+ // Get primary color from form customization or use default
749
+ var primaryColor = (_e = (_d = form === null || form === void 0 ? void 0 : form.customization) === null || _d === void 0 ? void 0 : _d.primaryColor) !== null && _e !== void 0 ? _e : '#798ED0';
750
+ var getDescriptionForChoice = useCallback(function (choice) {
751
+ var _a;
752
+ return (_a = optionDetails === null || optionDetails === void 0 ? void 0 : optionDetails.find(function (detail) { return detail.option === choice; })) === null || _a === void 0 ? void 0 : _a.description;
753
+ }, [optionDetails]);
754
+ var toggleDescription = useCallback(function (index) {
755
+ setExpandedDescriptions(function (prev) {
756
+ var _a;
757
+ return (__assign(__assign({}, prev), (_a = {}, _a[index] = !prev[index], _a)));
758
+ });
759
+ }, []);
760
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center", rowGap: 1.5 }, { children: [radio
761
+ ? (_jsx(FormControl, __assign({ fullWidth: true }, { children: _jsx(RadioGroup, __assign({ "aria-labelledby": "radio-group-".concat(field.id, "-label"), defaultValue: "female", name: "radio-group-".concat(field.id) }, { children: (choices !== null && choices !== void 0 ? choices : []).map(function (c, i) {
762
+ var description = getDescriptionForChoice(c);
763
+ var hasDescription = !!description;
764
+ var isExpanded = expandedDescriptions[i];
765
+ var isSelected = !!(value === null || value === void 0 ? void 0 : value.includes(c)) && c !== otherString;
766
+ return (_jsxs(Box, __assign({ sx: { width: '100%' } }, { children: [_jsxs(Box, __assign({ sx: {
767
+ display: 'flex',
768
+ alignItems: 'center',
769
+ width: '100%',
770
+ border: isSelected ? '2px solid' : '1px solid',
771
+ borderColor: 'primary.main',
772
+ borderRadius: 1,
773
+ padding: '16px 16px',
774
+ marginBottom: '12px',
775
+ cursor: 'pointer',
776
+ backgroundColor: 'transparent',
777
+ '&:hover': {
778
+ backgroundColor: function (theme) { return "".concat(theme.palette.primary.main, "14"); },
779
+ },
780
+ }, onClick: function () { return onChange((value === null || value === void 0 ? void 0 : value.includes(c)) ? [] : [c], field.id); } }, { children: [_jsx(Typography, __assign({ component: "span", sx: { flex: 1, color: 'primary.main', fontSize: 13, fontWeight: 600 } }, { children: c })), hasDescription && (_jsx(MuiIconButton, __assign({ className: "expand-button", size: "small", onClick: function (e) {
781
+ e.stopPropagation();
782
+ toggleDescription(i);
783
+ }, sx: {
784
+ transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
785
+ transition: 'transform 0.2s',
786
+ ml: 1
787
+ } }, { children: _jsx(ExpandMore, { fontSize: "small" }) })))] })), hasDescription && (_jsx(Collapse, __assign({ in: isExpanded }, { children: _jsx(Box, __assign({ sx: { pl: 2, pr: 2, pb: 1, pt: 1 } }, { children: _jsx(Typography, __assign({ variant: "body2", color: "text.secondary" }, { children: description })) })) })))] }), i));
788
+ }) })) }))) : ((choices !== null && choices !== void 0 ? choices : []).map(function (c, i) {
789
+ var description = getDescriptionForChoice(c);
790
+ var hasDescription = !!description;
791
+ var isExpanded = expandedDescriptions[i];
792
+ return (_jsx(Grid, __assign({ xs: 12 }, { children: _jsxs(Box, __assign({ sx: { width: '100%' } }, { children: [_jsxs(Box, __assign({ sx: {
793
+ display: 'flex',
794
+ alignItems: 'center',
795
+ cursor: 'pointer',
796
+ width: '100%'
797
+ }, onClick: function (e) {
798
+ var _a, _b, _d, _e;
799
+ // Don't trigger selection if clicking on the expand button
800
+ if (e.target.closest('.expand-button')) {
801
+ return;
802
+ }
803
+ onChange(((value === null || value === void 0 ? void 0 : value.includes(c))
804
+ ? ((radio || ((_b = (_a = field.options) === null || _a === void 0 ? void 0 : _a.radioChoices) === null || _b === void 0 ? void 0 : _b.includes(c)))
805
+ ? []
806
+ : value.filter(function (v) { return v !== c; }))
807
+ : ((radio || ((_e = (_d = field.options) === null || _d === void 0 ? void 0 : _d.radioChoices) === null || _e === void 0 ? void 0 : _e.includes(c)))
808
+ ? [c]
809
+ : __spreadArray(__spreadArray([], (value !== null && value !== void 0 ? value : []).filter(function (x) { var _a, _b; return !((_b = (_a = field.options) === null || _a === void 0 ? void 0 : _a.radioChoices) === null || _b === void 0 ? void 0 : _b.includes(x)); }), true), [c], false))), field.id);
810
+ } }, { children: [_jsx(Checkbox, { color: "primary", checked: !!(value === null || value === void 0 ? void 0 : value.includes(c)) && c !== otherString, inputProps: { 'aria-label': 'primary checkbox' } }), _jsx(Typography, __assign({ component: "span", sx: { flex: 1 } }, { children: c })), hasDescription && (_jsx(MuiIconButton, __assign({ className: "expand-button", size: "small", onClick: function (e) {
811
+ e.stopPropagation();
812
+ toggleDescription(i);
813
+ }, sx: {
814
+ transform: isExpanded ? 'rotate(180deg)' : 'rotate(0deg)',
815
+ transition: 'transform 0.2s',
816
+ ml: 1
817
+ } }, { children: _jsx(ExpandMore, { fontSize: "small" }) })))] })), hasDescription && (_jsx(Collapse, __assign({ in: isExpanded }, { children: _jsx(Box, __assign({ sx: { pl: '42px', pr: 2, pb: 1 } }, { children: _jsx(Typography, __assign({ variant: "body2", color: "text.secondary" }, { children: description })) })) })))] })) }), i));
818
+ })), other &&
819
+ _jsx(Grid, __assign({ item: true, xs: 12 }, { children: _jsx(TextField // className={classes.textField}
820
+ , { InputProps: { sx: { borderRadius: 2.5 } }, sx: { width: radio ? "calc(100% - 15px)" : '100%' }, size: "small", "aria-label": form_display_text_for_language(form, "Other"), value: otherString, placeholder: form_display_text_for_language(form, "Other"), variant: "outlined",
821
+ // onClick={() => !otherChecked && handleOtherChecked()} // allow click to enable when disabled
822
+ onChange: function (e) {
823
+ enteringOtherStringRef.current = e.target.value;
824
+ onChange((radio
825
+ ? (e.target.value.trim()
826
+ ? [e.target.value]
827
+ : [])
828
+ : (e.target.value.trim()
829
+ // remove existing other string (if exists) and append new one
830
+ ? __spreadArray(__spreadArray([], (value !== null && value !== void 0 ? value : []).filter(function (v) { return v !== otherString; }), true), [e.target.value], false) : value === null || value === void 0 ? void 0 : value.filter(function (v) { return v !== otherString; }))), field.id);
831
+ } }) }))] })));
832
+ };
833
+ export var StripeInput = function (_a) {
834
+ var _b, _d;
835
+ var field = _a.field, value = _a.value, onChange = _a.onChange, setCustomerId = _a.setCustomerId, enduserId = _a.enduserId;
836
+ var session = useResolvedSession();
837
+ var _e = useState(''), clientSecret = _e[0], setClientSecret = _e[1];
838
+ var _f = useState(''), businessName = _f[0], setBusinessName = _f[1];
839
+ var _g = useState(false), isCheckout = _g[0], setIsCheckout = _g[1];
840
+ var _h = useState(), stripePromise = _h[0], setStripePromise = _h[1];
841
+ var _j = useState(''), answertext = _j[0], setAnswertext = _j[1];
842
+ var _k = useState(''), error = _k[0], setError = _k[1];
843
+ var _l = useState([]), selectedProducts = _l[0], setSelectedProducts = _l[1];
844
+ var _m = useState(false), showProductSelection = _m[0], setShowProductSelection = _m[1];
845
+ var _o = useState([]), availableProducts = _o[0], setAvailableProducts = _o[1];
846
+ var _p = useState(false), loadingProducts = _p[0], setLoadingProducts = _p[1];
847
+ var fetchRef = useRef(false);
848
+ useEffect(function () {
849
+ var _a, _b, _d;
850
+ if (fetchRef.current)
851
+ return;
852
+ if (value && ((_a = session.userInfo) === null || _a === void 0 ? void 0 : _a.stripeCustomerId)) {
853
+ return setCustomerId(function (c) { var _a; return c ? c : (_a = session.userInfo) === null || _a === void 0 ? void 0 : _a.stripeCustomerId; }); // already paid or saved card
854
+ }
855
+ // Check if product selection mode is enabled
856
+ if (((_b = field.options) === null || _b === void 0 ? void 0 : _b.stripeProductSelectionMode) && (((_d = field.options) === null || _d === void 0 ? void 0 : _d.productIds) || []).length > 1) {
857
+ setShowProductSelection(true);
858
+ setLoadingProducts(true);
859
+ // Fetch product data with real-time Stripe pricing via proxy_read
860
+ var productIds = (field.options.productIds || []).join(',');
861
+ session.api.integrations.proxy_read({
862
+ integration: 'Stripe',
863
+ type: 'product-prices',
864
+ id: productIds,
865
+ query: field.options.stripeKey
866
+ })
867
+ .then(function (_a) {
868
+ var data = _a.data;
869
+ setAvailableProducts(data.products || []);
870
+ setLoadingProducts(false);
871
+ })
872
+ .catch(function (e) {
873
+ var _a, _b;
874
+ console.error('Error loading product data:', e);
875
+ var errorMessage = ((_b = (_a = e === null || e === void 0 ? void 0 : e.message) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, 'Stripe pricing error:'))
876
+ ? e.message.replace('Stripe pricing error: ', '')
877
+ : 'Failed to load product information from Stripe';
878
+ setError("Product configuration error: ".concat(errorMessage));
879
+ setLoadingProducts(false);
880
+ });
881
+ return;
882
+ }
883
+ fetchRef.current = true;
884
+ session.api.form_responses.stripe_details({ fieldId: field.id, enduserId: enduserId })
885
+ .then(function (_a) {
886
+ var clientSecret = _a.clientSecret, publishableKey = _a.publishableKey, stripeAccount = _a.stripeAccount, businessName = _a.businessName, customerId = _a.customerId, isCheckout = _a.isCheckout, answerText = _a.answerText;
887
+ setAnswertext(answerText || '');
888
+ setIsCheckout(!!isCheckout);
889
+ setClientSecret(clientSecret);
890
+ setStripePromise(loadStripe(publishableKey, { stripeAccount: stripeAccount }));
891
+ setBusinessName(businessName);
892
+ setCustomerId(customerId);
893
+ })
894
+ .catch(function (e) {
895
+ console.error(e);
896
+ if (typeof (e === null || e === void 0 ? void 0 : e.message) === 'string') {
897
+ setError(e.message);
898
+ }
899
+ });
900
+ }, [session, value, field.id, enduserId]);
901
+ var cost = (showProductSelection
902
+ ? selectedProducts.reduce(function (total, productId) {
903
+ var _a;
904
+ var product = availableProducts.find(function (p) { return p._id === productId; });
905
+ if (product === null || product === void 0 ? void 0 : product.currentPrice) {
906
+ return total + (product.currentPrice.amount || 0);
907
+ }
908
+ return total + (((_a = product === null || product === void 0 ? void 0 : product.cost) === null || _a === void 0 ? void 0 : _a.amount) || 0);
909
+ }, 0)
910
+ : 0 // Will be calculated by existing Stripe flow when not in selection mode
911
+ );
912
+ // Handle product selection step
913
+ if (showProductSelection) {
914
+ if (error) {
915
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 2, alignItems: "center" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ color: "error", variant: "h6" }, { children: "Product Configuration Error" })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ color: "error", sx: { textAlign: 'center' } }, { children: error })) }))] })));
916
+ }
917
+ if (loadingProducts) {
918
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 2, alignItems: "center" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(LinearProgress, {}) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, { children: "Loading product information..." }) }))] })));
919
+ }
920
+ var isSingleSelection_1 = ((_b = field.options) === null || _b === void 0 ? void 0 : _b.radio) === true;
921
+ var handleProductSelection_1 = function (productId) {
922
+ if (isSingleSelection_1) {
923
+ setSelectedProducts([productId]);
924
+ }
925
+ else {
926
+ setSelectedProducts(function (prev) {
927
+ return prev.includes(productId)
928
+ ? prev.filter(function (id) { return id !== productId; })
929
+ : __spreadArray(__spreadArray([], prev, true), [productId], false);
930
+ });
931
+ }
932
+ };
933
+ var handleContinueToPayment = function () {
934
+ if (selectedProducts.length === 0)
935
+ return;
936
+ setShowProductSelection(false);
937
+ fetchRef.current = true;
938
+ // Now fetch Stripe details with selected products
939
+ session.api.form_responses.stripe_details(__assign({ fieldId: field.id, enduserId: enduserId }, (selectedProducts.length > 0 && { selectedProductIds: selectedProducts }) // Pass selected products to Stripe checkout
940
+ ))
941
+ .then(function (_a) {
942
+ var clientSecret = _a.clientSecret, publishableKey = _a.publishableKey, stripeAccount = _a.stripeAccount, businessName = _a.businessName, customerId = _a.customerId, isCheckout = _a.isCheckout, answerText = _a.answerText;
943
+ setAnswertext(answerText || '');
944
+ setIsCheckout(!!isCheckout);
945
+ setClientSecret(clientSecret);
946
+ setStripePromise(loadStripe(publishableKey, { stripeAccount: stripeAccount }));
947
+ setBusinessName(businessName);
948
+ setCustomerId(customerId);
949
+ })
950
+ .catch(function (e) {
951
+ console.error(e);
952
+ if (typeof (e === null || e === void 0 ? void 0 : e.message) === 'string') {
953
+ setError(e.message);
954
+ }
955
+ });
956
+ };
957
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 2 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Typography, __assign({ variant: "h6" }, { children: ["Select Product", isSingleSelection_1 ? '' : 's'] })) })), availableProducts.map(function (product) {
958
+ var _a;
959
+ // Use real-time Stripe pricing if available, fallback to Tellescope pricing
960
+ var price = product.currentPrice || product.cost;
961
+ var priceAmount = (price === null || price === void 0 ? void 0 : price.amount) || 0;
962
+ var priceCurrency = (price === null || price === void 0 ? void 0 : price.currency) || 'USD';
963
+ return (_jsx(Grid, __assign({ item: true }, { children: _jsx(FormControlLabel, { control: isSingleSelection_1 ? (_jsx(Radio, { checked: selectedProducts.includes(product._id), onChange: function () { return handleProductSelection_1(product._id); } })) : (_jsx(Checkbox, { checked: selectedProducts.includes(product._id), onChange: function () { return handleProductSelection_1(product._id); } })), label: _jsxs(Box, { children: [_jsx(Typography, __assign({ variant: "body1", fontWeight: "bold" }, { children: product.title })), product.description && (_jsx(Typography, __assign({ variant: "body2", color: "textSecondary" }, { children: product.description }))), _jsxs(Typography, __assign({ variant: "body2", color: "primary" }, { children: ["$", (priceAmount / 100).toFixed(2), " ", priceCurrency.toUpperCase(), ((_a = product.currentPrice) === null || _a === void 0 ? void 0 : _a.isSubscription) && (_jsx(Typography, __assign({ component: "span", variant: "caption", sx: { ml: 0.5 } }, { children: "/month" })))] }))] }) }) }), product._id));
964
+ }), _jsx(Grid, __assign({ item: true }, { children: _jsx(Button, __assign({ variant: "contained", onClick: handleContinueToPayment, disabled: selectedProducts.length === 0, sx: { mt: 2 } }, { children: "Continue to Payment" })) }))] })));
965
+ }
966
+ if (error) {
967
+ return (_jsx(Typography, __assign({ color: "error" }, { children: error })));
968
+ }
969
+ if (value) {
970
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap" }, { children: [_jsx(CheckCircleOutline, { color: "success" }), _jsx(Typography, __assign({ sx: { ml: 1, fontSize: 20 } }, { children: ((_d = field.options) === null || _d === void 0 ? void 0 : _d.chargeImmediately) ? 'Your purchase was successful' : "Your payment details have been saved!" }))] })));
971
+ }
972
+ if (!(clientSecret && stripePromise))
973
+ return _jsx(LinearProgress, {});
974
+ if (isCheckout && stripePromise)
975
+ return (_jsx(EmbeddedCheckoutProvider, __assign({ stripe: stripePromise, options: {
976
+ clientSecret: clientSecret,
977
+ onComplete: function () { return onChange(answertext || 'Completed checkout', field.id); },
978
+ } }, { children: _jsx(EmbeddedCheckout, {}) })));
979
+ return (_jsx(Elements, __assign({ stripe: stripePromise, options: {
980
+ clientSecret: clientSecret,
981
+ } }, { children: _jsx(StripeForm, { businessName: businessName, onSuccess: function () { return onChange(answertext || 'Saved card details', field.id); }, cost: cost, field: field }) })));
982
+ };
983
+ var StripeForm = function (_a) {
984
+ var _b, _d, _e;
985
+ var businessName = _a.businessName, onSuccess = _a.onSuccess, field = _a.field, cost = _a.cost;
986
+ var stripe = useStripe();
987
+ var elements = useElements();
988
+ var _f = useState(false), ready = _f[0], setReady = _f[1];
989
+ var _g = useState(''), errorMessage = _g[0], setErrorMessage = _g[1];
990
+ var handleSubmit = function (event) { return __awaiter(void 0, void 0, void 0, function () {
991
+ var error;
992
+ var _a, _b;
993
+ return __generator(this, function (_d) {
994
+ switch (_d.label) {
995
+ case 0:
996
+ // We don't want to let default form submission happen here,
997
+ // which would refresh the page.
998
+ event === null || event === void 0 ? void 0 : event.preventDefault();
999
+ if (!stripe || !elements) {
1000
+ // Stripe.js hasn't yet loaded.
1001
+ // Make sure to disable form submission until Stripe.js has loaded.
1002
+ return [2 /*return*/, null];
1003
+ }
1004
+ return [4 /*yield*/, (((_a = field.options) === null || _a === void 0 ? void 0 : _a.chargeImmediately) ? stripe.confirmPayment : stripe.confirmSetup)({
1005
+ //`Elements` instance that was used to create the Payment Element
1006
+ elements: elements,
1007
+ confirmParams: {
1008
+ return_url: window.location.href,
1009
+ },
1010
+ redirect: 'if_required', // ensures the redirect url won't be used, unless the Bank redirect payment type is enabled (it's not, just card)
1011
+ })];
1012
+ case 1:
1013
+ error = (_d.sent()).error;
1014
+ if (error) {
1015
+ // This point will only be reached if there is an immediate error when
1016
+ // confirming the payment. Show error to your customer (for example, payment
1017
+ // details incomplete)
1018
+ setErrorMessage((_b = error === null || error === void 0 ? void 0 : error.message) !== null && _b !== void 0 ? _b : '');
1019
+ }
1020
+ else {
1021
+ onSuccess();
1022
+ // Your customer will be redirected to your `return_url`. For some payment
1023
+ // methods like iDEAL, your customer will be redirected to an intermediate
1024
+ // site first to authorize the payment, then redirected to the `return_url`.
1025
+ }
1026
+ return [2 /*return*/];
1027
+ }
1028
+ });
1029
+ }); };
1030
+ return (_jsxs("form", __assign({ onSubmit: handleSubmit }, { children: [_jsx(PaymentElement, { onReady: function () { return setReady(true); }, options: {
1031
+ business: { name: businessName },
1032
+ } }), _jsx(Button, __assign({ variant: "contained", color: "primary", type: "submit", sx: { mt: 1 }, disabled: !(stripe && ready) }, { children: ((_b = field.options) === null || _b === void 0 ? void 0 : _b.chargeImmediately) ? 'Make Payment' : 'Save Payment Details' })), cost > 0 &&
1033
+ _jsx(Typography, __assign({ sx: { mt: 0.5 } }, { children: ((_d = field.options) === null || _d === void 0 ? void 0 : _d.customPriceMessage)
1034
+ ? field.options.customPriceMessage.replaceAll('{{PRICE}}', "$".concat((cost / 100).toFixed(2)))
1035
+ : "You will be charged $".concat((cost / 100).toFixed(2), " ").concat(((_e = field.options) === null || _e === void 0 ? void 0 : _e.chargeImmediately) ? '' : 'on form submission') })), errorMessage &&
1036
+ _jsx(Typography, __assign({ color: "error", sx: { mt: 0.5 } }, { children: errorMessage }))] })));
1037
+ };
1038
+ export var Progress = function (_a) {
1039
+ var numerator = _a.numerator, denominator = _a.denominator, style = _a.style, color = _a.color;
1040
+ return (_jsx(Box, __assign({ sx: __assign({ display: 'flex', alignItems: 'center' }, style) }, { children: _jsx(Box, __assign({ sx: { width: '100%' } }, { children: _jsx(LinearProgress, { variant: "determinate", value: (numerator / (denominator || 1)) * 100, sx: color ? {
1041
+ height: '16px',
1042
+ borderRadius: '8px',
1043
+ backgroundColor: "".concat(color, "20"),
1044
+ '& .MuiLinearProgress-bar': {
1045
+ backgroundColor: color,
1046
+ borderRadius: '8px',
1047
+ }
1048
+ } : {
1049
+ height: '16px',
1050
+ borderRadius: '8px',
1051
+ '& .MuiLinearProgress-bar': {
1052
+ borderRadius: '8px',
1053
+ }
1054
+ } }) })) })));
1055
+ };
1056
+ export var DropdownInput = function (_a) {
1057
+ var _b, _d, _e, _f, _g, _h, _j;
1058
+ var field = _a.field, value = _a.value, onChange = _a.onChange;
1059
+ var _k = useState(''), typing = _k[0], setTyping = _k[1];
1060
+ // this should run only once, even if the field updates but the id is unchanged, otherwise will overwrite input
1061
+ var typingRef = useRef('');
1062
+ useEffect(function () {
1063
+ if (typingRef.current === field.id)
1064
+ return;
1065
+ typingRef.current = field.id;
1066
+ setTyping('');
1067
+ }, [field]);
1068
+ return (_jsx(Autocomplete, { id: field.id, style: { marginTop: 5 }, multiple: !((_b = field.options) === null || _b === void 0 ? void 0 : _b.radio), freeSolo: !!((_d = field.options) === null || _d === void 0 ? void 0 : _d.other), value: ((_e = field.options) === null || _e === void 0 ? void 0 : _e.radio)
1069
+ ? ((_f = value === null || value === void 0 ? void 0 : value[0]) !== null && _f !== void 0 ? _f : '')
1070
+ : (value !== null && value !== void 0 ? value : []), onChange: function (_, v) { return (onChange((typeof v === 'string' || v === null) ? [v !== null && v !== void 0 ? v : ''] : v, field.id)); }, options: (_h = (_g = field.options) === null || _g === void 0 ? void 0 : _g.choices) !== null && _h !== void 0 ? _h : [], inputValue: ((_j = field.options) === null || _j === void 0 ? void 0 : _j.radio) && Array.isArray(value) && value[0]
1071
+ ? value[0]
1072
+ : typing, onInputChange: function (e, value) { return setTyping(value); }, renderInput: function (params) {
1073
+ var _a, _b;
1074
+ return _jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), onChange: function (e) {
1075
+ var _a;
1076
+ return ((((_a = field.options) === null || _a === void 0 ? void 0 : _a.radio) && field.options.other)
1077
+ ? onChange(e.target.value ? [e.target.value] : [], field.id)
1078
+ : undefined);
1079
+ }, placeholder: field.placeholder
1080
+ ? field.placeholder + ((!field.title && !field.isOptional) ? '*' : '')
1081
+ : undefined, label: (!((_a = field.options) === null || _a === void 0 ? void 0 : _a.radio) && ((_b = field.options) === null || _b === void 0 ? void 0 : _b.other))
1082
+ ? "Press enter to save a custom value"
1083
+ : '' }));
1084
+ } }));
1085
+ };
1086
+ var choicesForDatabase = {};
1087
+ var preventRefetch = {};
1088
+ var LOAD_CHOICES_LIMIT = 500;
1089
+ var useDatabaseChoices = function (_a) {
1090
+ var _b, _d, _e, _f;
1091
+ var _g = _a.databaseId, databaseId = _g === void 0 ? '' : _g, field = _a.field, otherAnswers = _a.otherAnswers;
1092
+ var session = useResolvedSession();
1093
+ var _h = useState(0), renderCount = _h[0], setRenderCount = _h[1];
1094
+ // todo: make searchable, don't load all
1095
+ useEffect(function () {
1096
+ var _a, _b, _d, _e;
1097
+ if ((_a = choicesForDatabase[databaseId]) === null || _a === void 0 ? void 0 : _a.done)
1098
+ return;
1099
+ if (renderCount > 100)
1100
+ return; // limit to 50000 entries / prevent infinite looping
1101
+ var choices = (_d = (_b = choicesForDatabase[databaseId]) === null || _b === void 0 ? void 0 : _b.records) !== null && _d !== void 0 ? _d : [];
1102
+ var lastId = (_e = choicesForDatabase[databaseId]) === null || _e === void 0 ? void 0 : _e.lastId;
1103
+ if (preventRefetch[databaseId + field.id + lastId])
1104
+ return;
1105
+ preventRefetch[databaseId + field.id + lastId] = true;
1106
+ session.api.form_fields.load_choices_from_database({
1107
+ fieldId: field.id,
1108
+ lastId: lastId,
1109
+ limit: LOAD_CHOICES_LIMIT,
1110
+ databaseId: databaseId,
1111
+ })
1112
+ .then(function (_a) {
1113
+ var _b;
1114
+ var newChoices = _a.choices;
1115
+ choicesForDatabase[databaseId] = {
1116
+ lastId: (_b = newChoices === null || newChoices === void 0 ? void 0 : newChoices[newChoices.length - 1]) === null || _b === void 0 ? void 0 : _b.id,
1117
+ records: __spreadArray(__spreadArray([], choices, true), newChoices, true).sort(function (c1, c2) { return (label_for_database_record(field, c1)
1118
+ .localeCompare(label_for_database_record(field, c2))); }),
1119
+ done: newChoices.length < LOAD_CHOICES_LIMIT,
1120
+ };
1121
+ setRenderCount(function (r) { return r + 1; });
1122
+ })
1123
+ .catch(function (err) {
1124
+ console.error(err);
1125
+ preventRefetch[databaseId + field.id + lastId] = false;
1126
+ });
1127
+ }, [session, field, databaseId, renderCount]);
1128
+ var addChoice = useCallback(function (record) {
1129
+ if (!choicesForDatabase[databaseId]) {
1130
+ choicesForDatabase[databaseId] = {
1131
+ done: false,
1132
+ records: [],
1133
+ };
1134
+ }
1135
+ choicesForDatabase[databaseId].records.push(record);
1136
+ }, [choicesForDatabase, databaseId]);
1137
+ return {
1138
+ addChoice: addChoice,
1139
+ doneLoading: (_d = (_b = choicesForDatabase[databaseId]) === null || _b === void 0 ? void 0 : _b.done) !== null && _d !== void 0 ? _d : false,
1140
+ choices: __spreadArray(__spreadArray([], (_f = (_e = choicesForDatabase[databaseId]) === null || _e === void 0 ? void 0 : _e.records) !== null && _f !== void 0 ? _f : [], true), (otherAnswers || []).map(function (v) {
1141
+ var _a;
1142
+ return ({
1143
+ id: v.text,
1144
+ databaseId: databaseId,
1145
+ values: [{ label: ((_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseLabel) || '', type: 'Text', value: v.text }],
1146
+ });
1147
+ }), true),
1148
+ renderCount: renderCount,
1149
+ };
1150
+ };
1151
+ var label_for_database_record = function (field, record) {
1152
+ var _a, _b, _d, _e;
1153
+ if (!record)
1154
+ return '';
1155
+ var addedLabels = ((((_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseLabels) || [])
1156
+ .map(function (l) { var _a, _b; return (_b = (_a = record.values.find(function (v) { return v.label === l; })) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.toString(); })
1157
+ .filter(function (v) { return v === null || v === void 0 ? void 0 : v.trim(); }));
1158
+ return (((_e = (_d = (_b = record.values.find(function (v) { var _a; return v.label === ((_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseLabel); })) === null || _b === void 0 ? void 0 : _b.value) === null || _d === void 0 ? void 0 : _d.toString()) !== null && _e !== void 0 ? _e : '')
1159
+ + (addedLabels.length
1160
+ ? " (".concat(addedLabels.join(', '), ")")
1161
+ : ''));
1162
+ };
1163
+ var get_other_answers = function (_value, typing) {
1164
+ try {
1165
+ var existing = ((_value || [])
1166
+ .filter(function (v) { return typeof v === 'string' || v.recordId === v.text; })
1167
+ .map(function (v) { return typeof v === 'string' ? { databaseId: '', recordId: v, text: v } : v; }));
1168
+ if (typing) {
1169
+ existing.push({ text: typing, databaseId: '', recordId: typing });
1170
+ }
1171
+ return existing;
1172
+ }
1173
+ catch (err) {
1174
+ console.error(err);
1175
+ }
1176
+ return [];
1177
+ };
1178
+ export var DatabaseSelectInput = function (_a) {
1179
+ var _b, _d, _e, _f, _g, _h, _j, _k;
1180
+ var AddToDatabase = _a.AddToDatabase, field = _a.field, _value = _a.value, onChange = _a.onChange, onDatabaseSelect = _a.onDatabaseSelect, responses = _a.responses, size = _a.size, disabled = _a.disabled, enduser = _a.enduser;
1181
+ var _l = useState(''), typing = _l[0], setTyping = _l[1];
1182
+ var _m = useDatabaseChoices({
1183
+ databaseId: (_b = field.options) === null || _b === void 0 ? void 0 : _b.databaseId,
1184
+ field: field,
1185
+ otherAnswers: get_other_answers(_value, ((_d = field === null || field === void 0 ? void 0 : field.options) === null || _d === void 0 ? void 0 : _d.other) ? typing : undefined),
1186
+ }), addChoice = _m.addChoice, choices = _m.choices, doneLoading = _m.doneLoading;
1187
+ var value = React.useMemo(function () {
1188
+ var _a, _b;
1189
+ try {
1190
+ // if the value is a string (some single answer that was save), make sure we coerce to array
1191
+ var __value = typeof _value === 'string' ? [_value] : _value;
1192
+ return ((_b = (_a = __value === null || __value === void 0 ? void 0 : __value.map(function (v) {
1193
+ return choices.find(function (c) {
1194
+ return c.id === v.recordId || (typeof v === 'string' && label_for_database_record(field, c) === v);
1195
+ });
1196
+ })) === null || _a === void 0 ? void 0 : _a.filter(function (v) { return v; })) !== null && _b !== void 0 ? _b : []);
1197
+ }
1198
+ catch (err) {
1199
+ console.error('Error resolving database answers for _value', err);
1200
+ return [];
1201
+ }
1202
+ }, [_value, choices, field]);
1203
+ var filterResponse = useMemo(function () {
1204
+ var _a, _b, _d, _e;
1205
+ return (((_b = (_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseFilter) === null || _b === void 0 ? void 0 : _b.fieldId)
1206
+ ? (_e = (_d = responses.find(function (r) { var _a, _b; return r.fieldId === ((_b = (_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseFilter) === null || _b === void 0 ? void 0 : _b.fieldId); })) === null || _d === void 0 ? void 0 : _d.answer) === null || _e === void 0 ? void 0 : _e.value
1207
+ : undefined);
1208
+ }, [responses, (_e = field.options) === null || _e === void 0 ? void 0 : _e.databaseFilter]);
1209
+ // State filtering logic similar to Insurance component
1210
+ var addressQuestion = useMemo(function () { return responses === null || responses === void 0 ? void 0 : responses.find(function (r) {
1211
+ var _a;
1212
+ if (r.answer.type !== 'Address')
1213
+ return false;
1214
+ if (r.field.intakeField !== 'Address')
1215
+ return false;
1216
+ // make sure state is actually defined (in case of multiple address questions, where 1+ are blank)
1217
+ if (!((_a = r.answer.value) === null || _a === void 0 ? void 0 : _a.state))
1218
+ return false;
1219
+ return true;
1220
+ }); }, [responses]);
1221
+ var state = useMemo(function () {
1222
+ var _a, _b, _d, _e;
1223
+ return (((_a = field.options) === null || _a === void 0 ? void 0 : _a.filterByEnduserState)
1224
+ ? ((((_b = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _b === void 0 ? void 0 : _b.type) === 'Address' ? (_e = (_d = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _d === void 0 ? void 0 : _d.value) === null || _e === void 0 ? void 0 : _e.state : undefined) || (enduser === null || enduser === void 0 ? void 0 : enduser.state))
1225
+ : undefined);
1226
+ }, [enduser === null || enduser === void 0 ? void 0 : enduser.state, addressQuestion, (_f = field.options) === null || _f === void 0 ? void 0 : _f.filterByEnduserState]);
1227
+ var filteredChoicesWithPotentialDuplicates = useMemo(function () {
1228
+ var _a, _b;
1229
+ if (!choices)
1230
+ return [];
1231
+ if (!filterResponse)
1232
+ return choices;
1233
+ if (!((_b = (_a = field === null || field === void 0 ? void 0 : field.options) === null || _a === void 0 ? void 0 : _a.databaseFilter) === null || _b === void 0 ? void 0 : _b.databaseLabel))
1234
+ if (!value || value.length === 0)
1235
+ return choices;
1236
+ return (choices
1237
+ .filter(function (c) {
1238
+ var _a;
1239
+ var v = (_a = c.values.find(function (_v) { var _a, _b; return _v.label === ((_b = (_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseFilter) === null || _b === void 0 ? void 0 : _b.databaseLabel); })) === null || _a === void 0 ? void 0 : _a.value;
1240
+ if (!v)
1241
+ return true;
1242
+ // use .text on r values to handle Database Select types as filter source (in addition to basic text and list of text)
1243
+ if (typeof v === 'object') {
1244
+ return !!(Object.values(v).find(function (oVal) { return (typeof oVal === 'string' || typeof oVal === 'number'
1245
+ ? (Array.isArray(filterResponse)
1246
+ ? filterResponse.find(function (r) { return r === oVal.toString() || (typeof r === 'object' && r.text === oVal); })
1247
+ : (typeof filterResponse === 'string' || typeof filterResponse === 'number')
1248
+ ? filterResponse.toString() === oVal.toString()
1249
+ : false)
1250
+ : false); }));
1251
+ }
1252
+ if (typeof v === 'string' || typeof v === 'number') {
1253
+ return !!(Array.isArray(filterResponse)
1254
+ ? filterResponse.find(function (r) { return r === v.toString() || (typeof r === 'object' && r.text === v); })
1255
+ : (typeof filterResponse === 'string' || typeof filterResponse === 'number')
1256
+ ? filterResponse.toString() === v.toString()
1257
+ : (typeof filterResponse === 'object' && filterResponse.city === v.toString()) ? true
1258
+ : (typeof filterResponse === 'object' && filterResponse.state === v.toString()) ? true
1259
+ : (typeof filterResponse === 'object' && filterResponse.zipCode === v.toString()) ? true
1260
+ : false);
1261
+ }
1262
+ return false;
1263
+ }));
1264
+ }, [choices, filterResponse, (_g = field.options) === null || _g === void 0 ? void 0 : _g.databaseFilter, value]);
1265
+ // Apply state filtering as a secondary filter (doesn't modify existing logic)
1266
+ var stateFilteredChoices = useMemo(function () {
1267
+ var _a;
1268
+ if (!((_a = field.options) === null || _a === void 0 ? void 0 : _a.filterByEnduserState) || !state) {
1269
+ return filteredChoicesWithPotentialDuplicates;
1270
+ }
1271
+ return filteredChoicesWithPotentialDuplicates.filter(function (c) {
1272
+ var _a, _b;
1273
+ var recordState = ((_b = (_a = c.values.find(function (v) { var _a, _b; return ((_b = (_a = v.label) === null || _a === void 0 ? void 0 : _a.trim()) === null || _b === void 0 ? void 0 : _b.toLowerCase()) === 'state'; })) === null || _a === void 0 ? void 0 : _a.value) === null || _b === void 0 ? void 0 : _b.toString()) || '';
1274
+ return !recordState || recordState === state;
1275
+ });
1276
+ }, [filteredChoicesWithPotentialDuplicates, (_h = field.options) === null || _h === void 0 ? void 0 : _h.filterByEnduserState, state]);
1277
+ var filteredChoices = useMemo(function () {
1278
+ var filtered = [];
1279
+ var uniques = new Set([]);
1280
+ for (var _a = 0, stateFilteredChoices_1 = stateFilteredChoices; _a < stateFilteredChoices_1.length; _a++) {
1281
+ var c = stateFilteredChoices_1[_a];
1282
+ var text = label_for_database_record(field, c);
1283
+ if (uniques.has(text))
1284
+ continue; // duplicate found
1285
+ uniques.add(text);
1286
+ filtered.push(c);
1287
+ }
1288
+ return filtered;
1289
+ }, [field, stateFilteredChoices]);
1290
+ if (!doneLoading)
1291
+ return _jsx(LinearProgress, {});
1292
+ return (_jsxs(_Fragment, { children: [_jsx(Autocomplete, { id: field.id, freeSolo: false, size: size, componentsProps: { popper: { sx: { wordBreak: "break-word" } } }, options: filteredChoices, multiple: true, getOptionLabel: function (o) { return (Array.isArray(o) // edge case
1293
+ ? ''
1294
+ : label_for_database_record(field, o)); }, value: value, disabled: disabled, onChange: function (_, v) {
1295
+ var _a, _b, _d, _e, _f;
1296
+ if (v.length && onDatabaseSelect) {
1297
+ onDatabaseSelect(((_a = field.options) === null || _a === void 0 ? void 0 : _a.radio)
1298
+ ? [v[v.length - 1]] // if radio, only last selected
1299
+ : v);
1300
+ }
1301
+ return onChange((!((_b = field.options) === null || _b === void 0 ? void 0 : _b.radio)
1302
+ ? v.map(function (_v) {
1303
+ var _a;
1304
+ return ({
1305
+ databaseId: (_a = field.options) === null || _a === void 0 ? void 0 : _a.databaseId,
1306
+ recordId: _v.id,
1307
+ text: label_for_database_record(field, _v),
1308
+ });
1309
+ })
1310
+ : [{
1311
+ databaseId: (_d = field.options) === null || _d === void 0 ? void 0 : _d.databaseId,
1312
+ recordId: (_f = (_e = v[v.length - 1]) === null || _e === void 0 ? void 0 : _e.id) !== null && _f !== void 0 ? _f : '',
1313
+ text: label_for_database_record(field, v[v.length - 1]),
1314
+ }]), field.id);
1315
+ }, inputValue: typing, onInputChange: function (e, v) { return e && setTyping(v); }, renderInput: function (params) { return _jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }) })); },
1316
+ // use custom Chip to ensure very long entries break properly (whitespace: normal)
1317
+ renderTags: function (value, getTagProps) {
1318
+ return value.map(function (value, index) { return (_jsx(Chip, __assign({ label: _jsx(Typography, __assign({ style: { whiteSpace: 'normal' } }, { children: Array.isArray(value) ? '' : label_for_database_record(field, value) })) }, getTagProps({ index: index }), { sx: { height: "100%", py: 0.5 } }))); });
1319
+ } }), AddToDatabase && ((_j = field === null || field === void 0 ? void 0 : field.options) === null || _j === void 0 ? void 0 : _j.allowAddToDatabase) && (_jsx(AddToDatabase, { databaseId: (_k = field.options) === null || _k === void 0 ? void 0 : _k.databaseId, onAdd: addChoice }))] }));
1320
+ };
1321
+ var displayTermsCache = undefined;
1322
+ var DRUGS_FOR_DISPLAY_TERM = {};
1323
+ var RX_NORM_CODE_FOR_DRUG = {};
1324
+ var NDC_CODES_FOR_RX_NORM_CODE = {};
1325
+ var useMedications = function (_a) {
1326
+ var dontFetch = _a.dontFetch;
1327
+ var _b = useState(displayTermsCache), displayTerms = _b[0], setDisplayTerms = _b[1];
1328
+ var fetchRef = useRef(displayTerms !== undefined);
1329
+ useEffect(function () {
1330
+ if (dontFetch)
1331
+ return;
1332
+ if (fetchRef.current)
1333
+ return;
1334
+ fetchRef.current = true;
1335
+ // thankfully, this endpoint has cache control, so repeated requests should fetch from disk anyway
1336
+ axios.get('https://rxnav.nlm.nih.gov/REST/displaynames.json')
1337
+ .then(function (result) {
1338
+ var _a, _b, _d;
1339
+ return setDisplayTerms({
1340
+ displayTermsList: {
1341
+ term: ((_d = (_b = (_a = result.data) === null || _a === void 0 ? void 0 : _a.displayTermsList) === null || _b === void 0 ? void 0 : _b.term) === null || _d === void 0 ? void 0 : _d.filter(function (t) {
1342
+ try {
1343
+ // parse out some of the not immediately useful / non-human-readable options
1344
+ if (t.startsWith('('))
1345
+ return false;
1346
+ if (t.startsWith('.'))
1347
+ return false;
1348
+ if (!isNaN(parseInt(t.charAt(0))))
1349
+ return false; // starts with a number
1350
+ return true;
1351
+ }
1352
+ catch (err) {
1353
+ return false;
1354
+ }
1355
+ }))
1356
+ }
1357
+ });
1358
+ })
1359
+ .catch(console.error);
1360
+ }, [dontFetch]);
1361
+ var getDrugsForDisplayTerm = useCallback(function (s) { return __awaiter(void 0, void 0, void 0, function () {
1362
+ var drugs, _a;
1363
+ var _b, _d, _e, _f;
1364
+ return __generator(this, function (_g) {
1365
+ switch (_g.label) {
1366
+ case 0:
1367
+ _a = DRUGS_FOR_DISPLAY_TERM[s];
1368
+ if (_a) return [3 /*break*/, 2];
1369
+ return [4 /*yield*/, axios.get("https://rxnav.nlm.nih.gov/REST/drugs.json?name=".concat(s))];
1370
+ case 1:
1371
+ _a = ((_f = (_e = (_d = (_b = (_g.sent())
1372
+ .data) === null || _b === void 0 ? void 0 : _b.drugGroup) === null || _d === void 0 ? void 0 : _d.conceptGroup) === null || _e === void 0 ? void 0 : _e.find(function (v) { return v.conceptProperties; })) === null || _f === void 0 ? void 0 : _f.conceptProperties);
1373
+ _g.label = 2;
1374
+ case 2:
1375
+ drugs = _a;
1376
+ if (!DRUGS_FOR_DISPLAY_TERM[s]) {
1377
+ DRUGS_FOR_DISPLAY_TERM[s] = drugs; // cache for future lookups
1378
+ }
1379
+ return [2 /*return*/, drugs];
1380
+ }
1381
+ });
1382
+ }); }, []);
1383
+ var getCodesForDrug = useCallback(function (s) { return __awaiter(void 0, void 0, void 0, function () {
1384
+ var rxNormCode, _a, NDCs, _b;
1385
+ var _d, _e, _f, _g, _h, _j, _k;
1386
+ return __generator(this, function (_l) {
1387
+ switch (_l.label) {
1388
+ case 0:
1389
+ _a = RX_NORM_CODE_FOR_DRUG[s];
1390
+ if (_a) return [3 /*break*/, 2];
1391
+ return [4 /*yield*/, axios.get("https://rxnav.nlm.nih.gov/REST/rxcui.json?name=".concat(s, "&allsrc=1"))];
1392
+ case 1:
1393
+ _a = ((_f = (_e = (_d = (_l.sent())
1394
+ .data) === null || _d === void 0 ? void 0 : _d.idGroup) === null || _e === void 0 ? void 0 : _e.rxnormId) === null || _f === void 0 ? void 0 : _f[0]);
1395
+ _l.label = 2;
1396
+ case 2:
1397
+ rxNormCode = _a;
1398
+ RX_NORM_CODE_FOR_DRUG[s] = rxNormCode; // cache for future lookups
1399
+ _b = NDC_CODES_FOR_RX_NORM_CODE[rxNormCode];
1400
+ if (_b) return [3 /*break*/, 4];
1401
+ return [4 /*yield*/, axios.get("https://rxnav.nlm.nih.gov/REST/rxcui/".concat(rxNormCode, "/ndcs.json"))];
1402
+ case 3:
1403
+ _b = ((_k = (_j = (_h = (_g = (_l.sent())
1404
+ .data) === null || _g === void 0 ? void 0 : _g.ndcGroup) === null || _h === void 0 ? void 0 : _h.ndcList) === null || _j === void 0 ? void 0 : _j.ndc) !== null && _k !== void 0 ? _k : []);
1405
+ _l.label = 4;
1406
+ case 4:
1407
+ NDCs = _b;
1408
+ NDC_CODES_FOR_RX_NORM_CODE[rxNormCode] = NDCs; // cache for future lookups
1409
+ return [2 /*return*/, {
1410
+ rxNormCode: rxNormCode,
1411
+ NDCs: NDCs,
1412
+ }];
1413
+ }
1414
+ });
1415
+ }); }, []);
1416
+ if (displayTerms === undefined) {
1417
+ return {
1418
+ displayTerms: undefined,
1419
+ doneLoading: false,
1420
+ getDrugsForDisplayTerm: getDrugsForDisplayTerm,
1421
+ getCodesForDrug: getCodesForDrug,
1422
+ };
1423
+ }
1424
+ return {
1425
+ displayTerms: displayTerms,
1426
+ doneLoading: true,
1427
+ getDrugsForDisplayTerm: getDrugsForDisplayTerm,
1428
+ getCodesForDrug: getCodesForDrug,
1429
+ };
1430
+ };
1431
+ var filterOptions = function (options, _a) {
1432
+ var inputValue = _a.inputValue;
1433
+ return ((inputValue
1434
+ ? (options
1435
+ .filter(function (o) { return o.toLowerCase().includes(inputValue.toLowerCase()); })
1436
+ // show shorter matches first (tends to promote exact match and simpler medications)
1437
+ .sort(function (v1, v2) { return v1.length - v2.length; })
1438
+ // .reverse()
1439
+ ) : (options))
1440
+ .slice(0, 100) // dramatic performance improvement (when not virtualized) to show a subset like this
1441
+ );
1442
+ };
1443
+ var FDB_URL = "http://www.fdbhealth.com/";
1444
+ export var CanvasMedicationsInput = function (_a) {
1445
+ var _b;
1446
+ var field = _a.field, _d = _a.value, value = _d === void 0 ? [] : _d, onChange = _a.onChange;
1447
+ var session = useResolvedSession();
1448
+ var _e = useState(''), query = _e[0], setQuery = _e[1];
1449
+ var _f = useState([]), results = _f[0], setResults = _f[1];
1450
+ // if two Medications questions shown in a row, reset state
1451
+ useEffect(function () {
1452
+ setQuery('');
1453
+ setResults([]);
1454
+ }, [field.id]);
1455
+ var fetchRef = useRef(query);
1456
+ useEffect(function () {
1457
+ if (fetchRef.current === query)
1458
+ return;
1459
+ fetchRef.current = query;
1460
+ if (!query)
1461
+ return;
1462
+ var t = setTimeout(function () {
1463
+ session.api.integrations
1464
+ .proxy_read({
1465
+ integration: CANVAS_TITLE,
1466
+ type: 'medications',
1467
+ query: query,
1468
+ })
1469
+ .then(function (r) {
1470
+ var _a;
1471
+ setResults((((_a = r.data) === null || _a === void 0 ? void 0 : _a.entry) || [])
1472
+ .map(function (v) {
1473
+ var fdbCode = v.resource.code.coding.find(function (c) { return c.system === FDB_URL; });
1474
+ return {
1475
+ displayTerm: (fdbCode === null || fdbCode === void 0 ? void 0 : fdbCode.display) || '',
1476
+ drugName: (fdbCode === null || fdbCode === void 0 ? void 0 : fdbCode.display) || '',
1477
+ fdbCode: (fdbCode === null || fdbCode === void 0 ? void 0 : fdbCode.code) || '',
1478
+ };
1479
+ }));
1480
+ });
1481
+ }, 200);
1482
+ return function () { clearTimeout(t); };
1483
+ }, [session, query, (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.dataSource]);
1484
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Autocomplete, { multiple: true, value: value, options: results, style: { marginTop: 5 }, noOptionsText: query.length ? 'No results found' : 'Type to start search', onChange: function (e, v) {
1485
+ if (!v) {
1486
+ return;
1487
+ }
1488
+ onChange(v, field.id);
1489
+ setResults([]);
1490
+ }, getOptionLabel: function (v) { return first_letter_capitalized(v.displayTerm); }, filterOptions: function (o) { return o; }, inputValue: query, onInputChange: function (e, v) { return e && setQuery(v); }, renderInput: function (params) { return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, size: "small", label: "", placeholder: "Search medications..." }))); }, renderTags: function (value, getTagProps) {
1491
+ return value.map(function (value, index) { return (_jsx(Chip, __assign({ label: _jsx(Typography, __assign({ style: { whiteSpace: 'normal' } }, { children: value.displayTerm })) }, getTagProps({ index: index }), { sx: { height: "100%", py: 0.5 } }))); });
1492
+ } }) })), (value || []).map(function (medication, i) {
1493
+ var _a;
1494
+ return (_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, direction: "column", spacing: 0.75 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ noWrap: true, sx: { fontSize: 14 } }, { children: medication.drugName })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(TextField, { InputProps: { sx: defaultInputProps.sx }, fullWidth: true, size: "small", label: "Medication instructions: how much you take, how often, and when", value: ((_a = medication.dosage) === null || _a === void 0 ? void 0 : _a.description) || '', onChange: function (e) { return (onChange((value || []).map(function (v, _i) {
1495
+ return i === _i
1496
+ ? __assign(__assign({}, v), { dosage: __assign(__assign({}, v.dosage), { description: e.target.value }) }) : v;
1497
+ }), field.id)); } }) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Divider, { flexItem: true, sx: { my: 0.5 } }) }))] })) }), i));
1498
+ })] })));
1499
+ };
1500
+ export var MedicationsInput = function (_a) {
1501
+ var _b, _d;
1502
+ var field = _a.field, value = _a.value, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
1503
+ var _e = useMedications({
1504
+ dontFetch: ((_b = field.options) === null || _b === void 0 ? void 0 : _b.dataSource) === CANVAS_TITLE
1505
+ }), displayTerms = _e.displayTerms, doneLoading = _e.doneLoading, getCodesForDrug = _e.getCodesForDrug, getDrugsForDisplayTerm = _e.getDrugsForDisplayTerm;
1506
+ var _f = useState({}), drugs = _f[0], setDrugs = _f[1];
1507
+ // uncomment to load data after initial typing
1508
+ // const [query, setQuery] = useState('')
1509
+ // useEffect(() => {
1510
+ // if (!value?.length) return
1511
+ // Promise.all((value ?? []).map(v => (
1512
+ // v.displayTerm ? getDrugsForDisplayTerm(v.displayTerm) : null
1513
+ // )))
1514
+ // .then(values => {
1515
+ // const toSet: typeof drugs = {}
1516
+ // values.forEach((v, i) => {
1517
+ // toSet[value[i].displayTerm] = v ?? []
1518
+ // if (!v?.length) {
1519
+ // // drug is unknown, and previously looked-up NDCs and rxNormCode should be reset
1520
+ // value[i].drugName = "Unknown"
1521
+ // value[i].NDCs = []
1522
+ // value[i].rxNormCode = ''
1523
+ // }
1524
+ // })
1525
+ // setDrugs(toSet)
1526
+ // })
1527
+ // .catch(console.error)
1528
+ // }, [value, getDrugsForDisplayTerm])
1529
+ if (((_d = field.options) === null || _d === void 0 ? void 0 : _d.dataSource) === CANVAS_TITLE) {
1530
+ return _jsx(CanvasMedicationsInput, __assign({ field: field, value: value, onChange: onChange }, props));
1531
+ }
1532
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", sx: { mt: 2 } }, { children: [(value !== null && value !== void 0 ? value : []).map(function (v, i) {
1533
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k, _l;
1534
+ return (_jsxs(_Fragment, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap" }, { children: _jsx(Grid, __assign({ item: true, sx: { width: '100%' } }, { children: _jsxs(Grid, __assign({ container: true, direction: "column" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Autocomplete, { freeSolo: false, multiple: false, loading: !doneLoading, options:
1535
+ // uncomment to load data after initial typing
1536
+ // query.length === 0 ? [] :
1537
+ ((_b = (_a = displayTerms === null || displayTerms === void 0 ? void 0 : displayTerms.displayTermsList) === null || _a === void 0 ? void 0 : _a.term) !== null && _b !== void 0 ? _b : []),
1538
+ // uncomment to load data after initial typing
1539
+ // noOptionsText={query.length === 0 ? "Start typing..." : undefined}
1540
+ // uncomment to load data after initial typing
1541
+ // inputValue={query} onInputChange={(e, v) => setQuery(v)}
1542
+ getOptionLabel: first_letter_capitalized, filterOptions: filterOptions, value: v.displayTerm, onChange: function (_, displayTerm) { return __awaiter(void 0, void 0, void 0, function () {
1543
+ var drugs, _a;
1544
+ return __generator(this, function (_b) {
1545
+ switch (_b.label) {
1546
+ case 0:
1547
+ if (!displayTerm) return [3 /*break*/, 2];
1548
+ return [4 /*yield*/, getDrugsForDisplayTerm(displayTerm)];
1549
+ case 1:
1550
+ _a = _b.sent();
1551
+ return [3 /*break*/, 3];
1552
+ case 2:
1553
+ _a = null;
1554
+ _b.label = 3;
1555
+ case 3:
1556
+ drugs = _a;
1557
+ if (displayTerm) {
1558
+ setDrugs(function (ds) {
1559
+ var _a;
1560
+ return (__assign(__assign({}, ds), (_a = {}, _a[displayTerm] = drugs !== null && drugs !== void 0 ? drugs : [], _a)));
1561
+ });
1562
+ }
1563
+ onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1564
+ ? __assign(__assign({}, _v), { displayTerm: displayTerm || '', drugName: (drugs === null || drugs === void 0 ? void 0 : drugs.length) ? '' : "Unknown", drugSynonym: '', reasonForTaking: '', dosage: {
1565
+ unit: '',
1566
+ value: '',
1567
+ quantity: '',
1568
+ frequency: '',
1569
+ },
1570
+ // reset these on new search term to avoid stale data
1571
+ NDCs: [], rxNormCode: '' }) : _v); }), field.id);
1572
+ return [2 /*return*/];
1573
+ }
1574
+ });
1575
+ }); }, renderInput: function (params) {
1576
+ return _jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, label: "Search", size: "small", fullWidth: true }));
1577
+ } }) })), v.displayTerm && v.drugName !== "Unknown" && !v.otherDrug &&
1578
+ _jsx(Grid, __assign({ item: true, sx: { mt: 1.5 } }, { children: _jsx(Autocomplete, { freeSolo: false, options: drugs[v.displayTerm]
1579
+ ? drugs[v.displayTerm].length
1580
+ ? drugs[v.displayTerm]
1581
+ : [{ name: 'Unknown', rxcui: '' }]
1582
+ : [] // still loading
1583
+ , multiple: false, getOptionLabel: function (d) { return (d === null || d === void 0 ? void 0 : d.synonym) ? d.synonym : ((d === null || d === void 0 ? void 0 : d.name) || ''); }, value: (_e = __spreadArray(__spreadArray([], (_d = drugs[v.displayTerm]) !== null && _d !== void 0 ? _d : [], true), [{ name: "Unknown", rxcui: '' }], false).find(function (d) { return d.name === v.drugName; })) !== null && _e !== void 0 ? _e : null, onChange: function (_, drug) { return __awaiter(void 0, void 0, void 0, function () {
1584
+ var info, _a;
1585
+ return __generator(this, function (_b) {
1586
+ switch (_b.label) {
1587
+ case 0:
1588
+ if (!drug)
1589
+ return [2 /*return*/];
1590
+ if (!(drug.name === 'Unknown')) return [3 /*break*/, 2];
1591
+ return [4 /*yield*/, getCodesForDrug(v.displayTerm)]; // might get us a value, better than searching Unknown or keeping a prior value
1592
+ case 1:
1593
+ _a = _b.sent(); // might get us a value, better than searching Unknown or keeping a prior value
1594
+ return [3 /*break*/, 4];
1595
+ case 2: return [4 /*yield*/, getCodesForDrug(drug.name)];
1596
+ case 3:
1597
+ _a = _b.sent();
1598
+ _b.label = 4;
1599
+ case 4:
1600
+ info = (_a);
1601
+ onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1602
+ ? __assign(__assign(__assign({}, _v), { drugName: drug.name, drugSynonym: drug.synonym || '' }), info) : _v); }), field.id);
1603
+ return [2 /*return*/];
1604
+ }
1605
+ });
1606
+ }); }, renderInput: function (params) {
1607
+ return _jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, label: "Drug Select", size: "small", fullWidth: true }));
1608
+ } }) })), v.displayTerm && (v.drugName === "Unknown" || !v.drugName) &&
1609
+ _jsx(Grid, __assign({ item: true, sx: { mt: 1 } }, { children: _jsx(TextField, { label: 'Other Drug', fullWidth: true, size: "small", required: true, InputProps: defaultInputProps, value: (_g = (_f = value === null || value === void 0 ? void 0 : value.find(function (v, _i) { return _i === i; })) === null || _f === void 0 ? void 0 : _f.otherDrug) !== null && _g !== void 0 ? _g : '', onChange: function (e) { return (onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1610
+ ? __assign(__assign({}, _v), { otherDrug: e.target.value }) : _v); }), field.id)); } }) })), v.displayTerm &&
1611
+ _jsxs(Grid, __assign({ container: true, spacing: 1, sx: { mt: 0 } }, { children: [_jsxs(Grid, __assign({ item: true, xs: 12, md: 6 }, { children: [_jsx(Typography, __assign({ sx: { fontSize: 13.5 } }, { children: "Units (e.g. capsule, table, puff) per dose?" })), _jsx(TextField, { type: "number", size: "small", fullWidth: true, InputProps: defaultInputProps, value: (_h = v.dosage) === null || _h === void 0 ? void 0 : _h.quantity, onChange: function (e) {
1612
+ return onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1613
+ ? __assign(__assign({}, _v), { dosage: __assign(__assign({}, _v.dosage), { quantity: e.target.value }) }) : _v); }), field.id);
1614
+ },
1615
+ // hide arrows for number input, which continue to increase after initial press
1616
+ sx: {
1617
+ '& input[type=number]': {
1618
+ '-moz-appearance': 'textfield'
1619
+ },
1620
+ '& input[type=number]::-webkit-outer-spin-button': {
1621
+ '-webkit-appearance': 'none',
1622
+ margin: 0
1623
+ },
1624
+ '& input[type=number]::-webkit-inner-spin-button': {
1625
+ '-webkit-appearance': 'none',
1626
+ margin: 0
1627
+ }
1628
+ } })] })), _jsxs(Grid, __assign({ item: true, xs: 12, md: 6 }, { children: [_jsxs(Typography, __assign({ sx: { fontSize: 13.5 } }, { children: ["How many times per ", _jsx("strong", { children: "day" }), "?"] })), _jsx(StringSelector, { size: "small", options: ["1", "2", "3", "4", "5", "6", "As Needed"], value: (_k = (_j = v.dosage) === null || _j === void 0 ? void 0 : _j.frequency) !== null && _k !== void 0 ? _k : '', onChange: function (frequency) { return __awaiter(void 0, void 0, void 0, function () {
1629
+ return __generator(this, function (_a) {
1630
+ onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1631
+ ? __assign(__assign({}, _v), { dosage: __assign(__assign({}, _v.dosage), { frequency: frequency || '' }) }) : _v); }), field.id);
1632
+ return [2 /*return*/];
1633
+ });
1634
+ }); } })] }))] })), v.displayTerm &&
1635
+ _jsx(Grid, __assign({ item: true, sx: { mt: 1.25 } }, { children: _jsx(TextField, { label: "Reason for taking medication", size: "small", fullWidth: true, InputProps: defaultInputProps, value: (_l = v.reasonForTaking) !== null && _l !== void 0 ? _l : '', onChange: function (e) {
1636
+ return onChange((value !== null && value !== void 0 ? value : []).map(function (_v, _i) { return (i === _i
1637
+ ? __assign(__assign({}, _v), { reasonForTaking: e.target.value }) : _v); }), field.id);
1638
+ } }) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ color: "primary", sx: { textDecoration: 'underline', cursor: 'pointer' }, onClick: function () { return onChange((value !== null && value !== void 0 ? value : []).filter(function (_, _i) { return i !== _i; }), field.id); } }, { children: "Remove medication" })) })), window.location.origin.includes(':300') && i === 0 &&
1639
+ _jsxs(Grid, __assign({ item: true, sx: { mt: 3 } }, { children: [_jsx("strong", { children: "DEBUG:" }), " ", _jsx("br", {}), _jsx("pre", __assign({ style: { wordWrap: 'break-word' } }, { children: JSON.stringify(value !== null && value !== void 0 ? value : {}, null, 2) }))] })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Grid, { container: true }) }))] })) })) })) }), i), _jsx(Grid, __assign({ item: true }, { children: _jsx(Divider, { flexItem: true, sx: { my: 1 } }) }))] }));
1640
+ }), _jsx(Grid, __assign({ item: true }, { children: _jsx(Button, __assign({ color: "primary", variant: "outlined", onClick: function () { return onChange(__spreadArray(__spreadArray([], (value !== null && value !== void 0 ? value : []), true), [{ displayTerm: '', drugName: '' }], false), field.id); } }, { children: "Add Medication" })) }))] })));
1641
+ };
1642
+ export var contact_is_valid = function (e) {
1643
+ if (e.email) {
1644
+ try {
1645
+ emailValidator.validate()(e.email);
1646
+ }
1647
+ catch (err) {
1648
+ return "Email is invalid";
1649
+ }
1650
+ }
1651
+ if (e.phone) {
1652
+ try {
1653
+ phoneValidator.validate()(e.phone);
1654
+ }
1655
+ catch (err) {
1656
+ return "Phone is invalid";
1657
+ }
1658
+ }
1659
+ if (e.dateOfBirth && !isDateString(e.dateOfBirth)) {
1660
+ return "Date of birth should be MM-DD-YYYY";
1661
+ }
1662
+ };
1663
+ export var RelatedContactsInput = function (_a) {
1664
+ var _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _w, _x;
1665
+ var field = _a.field, _value = _a.value, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
1666
+ // safeguard against any rogue values like empty string
1667
+ var value = Array.isArray(_value) ? _value : [];
1668
+ var _y = useState(value.length === 1 ? 0 : -1), editing = _y[0], setEditing = _y[1];
1669
+ var handleAddContact = useCallback(function () {
1670
+ var _a, _b;
1671
+ onChange(__spreadArray(__spreadArray([], value, true), [
1672
+ { relationships: ((_b = (_a = field === null || field === void 0 ? void 0 : field.options) === null || _a === void 0 ? void 0 : _a.relatedContactTypes) === null || _b === void 0 ? void 0 : _b.length) === 1 ? [{ type: field.options.relatedContactTypes[0], id: '' }] : [] }
1673
+ ], false), field.id, true);
1674
+ setEditing(value.length);
1675
+ }, [onChange, value, field === null || field === void 0 ? void 0 : field.id, (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.relatedContactTypes]);
1676
+ if (value[editing]) {
1677
+ var _z = value[editing], fname = _z.fname, lname = _z.lname, email = _z.email, phone = _z.phone, _0 = _z.fields, fields_1 = _0 === void 0 ? {} : _0, _1 = _z.dateOfBirth, dateOfBirth = _1 === void 0 ? '' : _1, relationships = _z.relationships;
1678
+ var errorMessage = contact_is_valid(value[editing]);
1679
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap", spacing: 1 }, { children: [!((_e = (_d = field.options) === null || _d === void 0 ? void 0 : _d.hiddenDefaultFields) === null || _e === void 0 ? void 0 : _e.includes('First Name')) &&
1680
+ _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(TextField, { label: "First Name", size: "small", fullWidth: true, InputProps: defaultInputProps, value: fname, onChange: function (e) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { fname: e.target.value }) : v; }), field.id); } }) })), !((_g = (_f = field.options) === null || _f === void 0 ? void 0 : _f.hiddenDefaultFields) === null || _g === void 0 ? void 0 : _g.includes('Last Name')) &&
1681
+ _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(TextField, { label: "Last Name", size: "small", fullWidth: true, InputProps: defaultInputProps, value: lname, onChange: function (e) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { lname: e.target.value }) : v; }), field.id); } }) })), _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(StringSelector, { options: ((_j = (_h = field.options) === null || _h === void 0 ? void 0 : _h.relatedContactTypes) === null || _j === void 0 ? void 0 : _j.length) ? field.options.relatedContactTypes : RELATIONSHIP_TYPES, label: "Relationship", size: "small", disabled: ((_l = (_k = field === null || field === void 0 ? void 0 : field.options) === null || _k === void 0 ? void 0 : _k.relatedContactTypes) === null || _l === void 0 ? void 0 : _l.length) === 1, value: (_o = (_m = relationships === null || relationships === void 0 ? void 0 : relationships[0]) === null || _m === void 0 ? void 0 : _m.type) !== null && _o !== void 0 ? _o : '', onChange: function (type) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { relationships: [{ type: type, id: '' /* to be filled on server-side */ }] }) : v; }), field.id); } }) }))] })) })), _jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap", spacing: 1 }, { children: [!((_q = (_p = field.options) === null || _p === void 0 ? void 0 : _p.hiddenDefaultFields) === null || _q === void 0 ? void 0 : _q.includes('Date of Birth')) &&
1682
+ _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(DateStringInput, { value: dateOfBirth, field: __assign(__assign({}, field), { isOptional: true }), size: "small", label: "Date of Birth (MM-DD-YYYY)", onChange: function (dateOfBirth) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { dateOfBirth: dateOfBirth }) : v; }), field.id); } }) })), !((_s = (_r = field.options) === null || _r === void 0 ? void 0 : _r.hiddenDefaultFields) === null || _s === void 0 ? void 0 : _s.includes('Email')) &&
1683
+ _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(TextField, { label: "Email", size: "small", fullWidth: true, type: "email", InputProps: defaultInputProps, value: email, onChange: function (e) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { email: e.target.value }) : v; }), field.id); } }) })), !((_u = (_t = field.options) === null || _t === void 0 ? void 0 : _t.hiddenDefaultFields) === null || _u === void 0 ? void 0 : _u.includes('Phone Number')) &&
1684
+ _jsx(Grid, __assign({ item: true, xs: 4 }, { children: _jsx(TextField, { label: "Phone Number", size: "small", fullWidth: true, InputProps: defaultInputProps, value: phone, onChange: function (e) { return onChange(value.map(function (v, i) { return i === editing ? __assign(__assign({}, v), { phone: e.target.value }) : v; }), field.id); } }) }))] })) })), (((_w = field.options) === null || _w === void 0 ? void 0 : _w.tableChoices) || []).length > 0 &&
1685
+ _jsx(Grid, __assign({ item: true }, { children: _jsx(Grid, __assign({ container: true, spacing: 1 }, { children: (((_x = field.options) === null || _x === void 0 ? void 0 : _x.tableChoices) || []).map(function (_a, i) {
1686
+ var info = _a.info, label = _a.label, type = _a.type;
1687
+ return (_jsx(Grid, __assign({ item: true, xs: 6 }, { children: type === 'Text'
1688
+ ? (_jsx(TextField, { label: label, size: "small", fullWidth: true, InputProps: defaultInputProps, value: fields_1[label] || '', onChange: function (e) { return onChange(value.map(function (v, i) {
1689
+ var _a;
1690
+ return i === editing ? __assign(__assign({}, v), { fields: __assign(__assign({}, fields_1), (_a = {}, _a[label] = e.target.value, _a)) }) : v;
1691
+ }), field.id); } }))
1692
+ : type === 'Date' ? (_jsx(DateStringInput, { label: label, size: "small", fullWidth: true, field: __assign(__assign({}, field), { isOptional: true }), value: fields_1[label] || '', onChange: function (e) {
1693
+ if (e === void 0) { e = ''; }
1694
+ return onChange(value.map(function (v, i) {
1695
+ var _a;
1696
+ return i === editing ? __assign(__assign({}, v), { fields: __assign(__assign({}, fields_1), (_a = {}, _a[label] = e, _a)) }) : v;
1697
+ }), field.id);
1698
+ } }))
1699
+ : type === 'Select' ? (_jsxs(FormControl, __assign({ size: "small", fullWidth: true }, { children: [_jsx(InputLabel, __assign({ id: "demo-select-small" }, { children: label })), _jsxs(Select, __assign({ label: label, size: "small", sx: defaultInputProps.sx, value: fields_1[label] || '', onChange: function (e) { return onChange(value.map(function (v, i) {
1700
+ var _a;
1701
+ return i === editing ? __assign(__assign({}, v), { fields: __assign(__assign({}, fields_1), (_a = {}, _a[label] = e.target.value, _a)) }) : v;
1702
+ }), field.id); } }, { children: [_jsx(MenuItem, __assign({ value: "" }, { children: _jsx("em", { children: "None" }) })), info.choices.map(function (c) { return (_jsx(MenuItem, __assign({ value: c }, { children: c }), c)); })] }))] })))
1703
+ : null }), i));
1704
+ }) })) })), _jsx(Grid, __assign({ item: true, sx: { my: 0.75 } }, { children: _jsx(Button, __assign({ variant: "outlined", onClick: function () { return setEditing(-1); }, size: "small" }, { children: "Save Contact" })) })), errorMessage &&
1705
+ _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ color: "error" }, { children: errorMessage })) }))] })));
1706
+ }
1707
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: value.map(function (contact, i) { return (_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", justifyContent: "space-between", wrap: "nowrap", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center" }, { children: [_jsx(IconButton, __assign({ onClick: function () { return setEditing(i); }, color: "primary", size: "small" }, { children: _jsx(Edit, {}) })), _jsx(Typography, __assign({ noWrap: true }, { children: user_display_name(contact) || "Unnamed Contact ".concat(i + 1) }))] })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(LabeledIconButton, { Icon: Delete, label: "Remove", onClick: function () { return onChange(value.filter(function (v, _i) { return i !== _i; }), field.id); } }) }))] })) }), i)); }) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(Button, __assign({ variant: "contained", onClick: handleAddContact }, { children: "Add Contact" })) }))] })));
1708
+ };
1709
+ export var AppointmentBookingInput = function (_a) {
1710
+ var _b, _d, _e, _f, _g, _h, _j, _k, _l;
1711
+ var formResponseId = _a.formResponseId, field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, responses = _a.responses, goToPreviousField = _a.goToPreviousField, isPreviousDisabled = _a.isPreviousDisabled, enduserId = _a.enduserId, props = __rest(_a, ["formResponseId", "field", "value", "onChange", "form", "responses", "goToPreviousField", "isPreviousDisabled", "enduserId"]);
1712
+ var session = useResolvedSession();
1713
+ var _m = useState(), loaded = _m[0], setLoaded = _m[1];
1714
+ var _o = useState(''), error = _o[0], setError = _o[1];
1715
+ var _p = useState(false), acknowledgedWarning = _p[0], setAcknowledgedWarning = _p[1];
1716
+ var _q = useState(450), height = _q[0], setHeight = _q[1];
1717
+ var _r = useState(false), confirming = _r[0], setConfirming = _r[1];
1718
+ var bookingPageId = (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.bookingPageId;
1719
+ var downloadICS = useCallback(function (event) { return __awaiter(void 0, void 0, void 0, function () {
1720
+ var _a, err_1;
1721
+ return __generator(this, function (_b) {
1722
+ switch (_b.label) {
1723
+ case 0:
1724
+ _b.trys.push([0, 2, , 3]);
1725
+ _a = downloadFile;
1726
+ return [4 /*yield*/, session.api.calendar_events.download_ics_file({ calendarEventId: event.id, excludeAttendee: true })];
1727
+ case 1:
1728
+ _a.apply(void 0, [_b.sent(),
1729
+ { name: "event.ics", dataIsURL: true, type: 'text/calendar' }]);
1730
+ return [3 /*break*/, 3];
1731
+ case 2:
1732
+ err_1 = _b.sent();
1733
+ console.error(err_1);
1734
+ return [3 /*break*/, 3];
1735
+ case 3: return [2 /*return*/];
1736
+ }
1737
+ });
1738
+ }); }, [session]);
1739
+ var addressQuestion = useMemo(function () { return responses === null || responses === void 0 ? void 0 : responses.find(function (r) {
1740
+ var _a;
1741
+ if (r.answer.type !== 'Address')
1742
+ return false;
1743
+ if (r.field.intakeField !== 'Address')
1744
+ return false;
1745
+ // make sure state is actually defined (in case of multiple address questions, where 1+ are blank)
1746
+ if (!((_a = r.answer.value) === null || _a === void 0 ? void 0 : _a.state))
1747
+ return false;
1748
+ return true;
1749
+ }); }, [responses]);
1750
+ var state = useMemo(function () {
1751
+ var _a, _b, _d;
1752
+ return (((_a = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _a === void 0 ? void 0 : _a.type) === 'Address' ? (_d = (_b = addressQuestion === null || addressQuestion === void 0 ? void 0 : addressQuestion.answer) === null || _b === void 0 ? void 0 : _b.value) === null || _d === void 0 ? void 0 : _d.state : undefined);
1753
+ }, [addressQuestion]);
1754
+ var loadBookingInfo = useCallback(function () {
1755
+ if (!bookingPageId)
1756
+ return;
1757
+ setError('');
1758
+ session.api.form_fields.booking_info({
1759
+ enduserId: enduserId,
1760
+ bookingPageId: bookingPageId,
1761
+ enduserFields: { state: state }
1762
+ })
1763
+ .then(setLoaded)
1764
+ .catch(function (e) { return setError((e === null || e === void 0 ? void 0 : e.message) || (e === null || e === void 0 ? void 0 : e.toString()) || 'Error loading appointment details'); });
1765
+ }, [enduserId, bookingPageId, session, state]);
1766
+ var fetchRef = useRef(false);
1767
+ useEffect(function () {
1768
+ if (value)
1769
+ return;
1770
+ if (!bookingPageId)
1771
+ return;
1772
+ if (fetchRef.current)
1773
+ return;
1774
+ fetchRef.current = true;
1775
+ loadBookingInfo();
1776
+ }, [bookingPageId, loadBookingInfo, value]);
1777
+ useEffect(function () {
1778
+ var handleMessage = function (m) {
1779
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k;
1780
+ // entropy to separate from other booking pages rendered on the same screen
1781
+ if (((_a = m === null || m === void 0 ? void 0 : m.data) === null || _a === void 0 ? void 0 : _a.type) === 'Booking Success'
1782
+ && typeof ((_b = m === null || m === void 0 ? void 0 : m.data) === null || _b === void 0 ? void 0 : _b.bookedEventId) === 'string'
1783
+ && (!((_d = m === null || m === void 0 ? void 0 : m.data) === null || _d === void 0 ? void 0 : _d.entropy) || ((_e = m === null || m === void 0 ? void 0 : m.data) === null || _e === void 0 ? void 0 : _e.entropy) === (loaded === null || loaded === void 0 ? void 0 : loaded.entropy))) {
1784
+ onChange(m.data.bookedEventId, field.id);
1785
+ emit_gtm_event({ event: 'form_progress', fieldId: field.id, formId: field.formId, title: field.title, status: "Appointment Booked" });
1786
+ }
1787
+ if (((_f = m === null || m === void 0 ? void 0 : m.data) === null || _f === void 0 ? void 0 : _f.type) === 'CalendarPicker') {
1788
+ setHeight(750);
1789
+ }
1790
+ if (((_g = m === null || m === void 0 ? void 0 : m.data) === null || _g === void 0 ? void 0 : _g.type) === 'UsersPicker') {
1791
+ setHeight(450);
1792
+ }
1793
+ if (((_h = m === null || m === void 0 ? void 0 : m.data) === null || _h === void 0 ? void 0 : _h.type) === 'Confirmation') {
1794
+ setConfirming(true);
1795
+ }
1796
+ if (((_j = m === null || m === void 0 ? void 0 : m.data) === null || _j === void 0 ? void 0 : _j.type) === 'Join Link' && ((_k = m === null || m === void 0 ? void 0 : m.data) === null || _k === void 0 ? void 0 : _k.link)) {
1797
+ update_local_storage('tellescope_last_booking_page_join_link', m.data.link);
1798
+ }
1799
+ else {
1800
+ setConfirming(false);
1801
+ }
1802
+ };
1803
+ window.addEventListener('message', handleMessage);
1804
+ return function () { window.removeEventListener('message', handleMessage); };
1805
+ }, [field === null || field === void 0 ? void 0 : field.id, field === null || field === void 0 ? void 0 : field.formId, field === null || field === void 0 ? void 0 : field.title, onChange, acknowledgedWarning, value, loaded === null || loaded === void 0 ? void 0 : loaded.entropy]);
1806
+ if (value) {
1807
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap" }, { children: [_jsx(CheckCircleOutline, { color: "success" }), _jsx(Typography, __assign({ sx: { ml: 1, fontSize: 20 } }, { children: "Your appointment has been booked" }))] })) })), _jsx(Grid, __assign({ item: true, sx: { maxWidth: 250 } }, { children: _jsx(LoadingButton, { variant: "contained", style: { maxWidth: 250 }, submitText: "Add to Calendar", submittingText: "Downloading...", onClick: function () { return downloadICS({ id: value }); } }) }))] })));
1808
+ }
1809
+ if (!bookingPageId) {
1810
+ return _jsx(Typography, { children: "No booking page specified" });
1811
+ }
1812
+ if (error) {
1813
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsxs(Typography, __assign({ color: "error" }, { children: ["Error: ", error] })) })), _jsx(Grid, __assign({ item: true }, { children: _jsx(LoadingButton, { disabled: !bookingPageId, style: { maxWidth: 300 }, variant: "contained", onClick: loadBookingInfo, submitText: "Try Again", submittingText: "Loading..." }) }))] })));
1814
+ }
1815
+ if (!(loaded === null || loaded === void 0 ? void 0 : loaded.bookingURL)) {
1816
+ return _jsx(LinearProgress, {});
1817
+ }
1818
+ var bookingURL = loaded.bookingURL;
1819
+ if ((_e = (_d = field.options) === null || _d === void 0 ? void 0 : _d.userTags) === null || _e === void 0 ? void 0 : _e.length) {
1820
+ bookingURL += "&userTags=".concat(field.options.userTags
1821
+ .flatMap(function (t) {
1822
+ var _a, _b;
1823
+ // set dynamic tags if found
1824
+ if (t === '{{logic}}') {
1825
+ return new URL(window.location.href).searchParams.get('logic') || '{{logic}}';
1826
+ }
1827
+ if (t.startsWith("{{field.") && t.endsWith(".value}}")) {
1828
+ var fieldId_1 = t.replace('{{field.', '').replace(".value}}", '');
1829
+ var answer = (_a = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.fieldId === fieldId_1; })) === null || _a === void 0 ? void 0 : _a.answer;
1830
+ if (!(answer === null || answer === void 0 ? void 0 : answer.value))
1831
+ return t;
1832
+ if (answer.type === 'Insurance') {
1833
+ return answer.value.payerName || '';
1834
+ }
1835
+ if (Array.isArray(answer.value) && typeof ((_b = answer.value) === null || _b === void 0 ? void 0 : _b[0]) === 'string') {
1836
+ return answer.value;
1837
+ }
1838
+ return form_response_value_to_string(answer.value);
1839
+ }
1840
+ return t;
1841
+ })
1842
+ .join(','));
1843
+ }
1844
+ if ((_g = (_f = field.options) === null || _f === void 0 ? void 0 : _f.userFilterTags) === null || _g === void 0 ? void 0 : _g.length) {
1845
+ bookingURL += "&userFilterTags=".concat(field.options.userFilterTags
1846
+ .flatMap(function (t) {
1847
+ var _a, _b;
1848
+ // set dynamic tags if found
1849
+ if (t === '{{logic}}') {
1850
+ return new URL(window.location.href).searchParams.get('logic') || '{{logic}}';
1851
+ }
1852
+ if (t.startsWith("{{field.") && t.endsWith(".value}}")) {
1853
+ var fieldId_2 = t.replace('{{field.', '').replace(".value}}", '');
1854
+ var answer = (_a = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.fieldId === fieldId_2; })) === null || _a === void 0 ? void 0 : _a.answer;
1855
+ if (!(answer === null || answer === void 0 ? void 0 : answer.value))
1856
+ return t;
1857
+ if (answer.type === 'Insurance') {
1858
+ return answer.value.payerName || '';
1859
+ }
1860
+ if (Array.isArray(answer.value) && typeof ((_b = answer.value) === null || _b === void 0 ? void 0 : _b[0]) === 'string') {
1861
+ return answer.value;
1862
+ }
1863
+ return form_response_value_to_string(answer.value);
1864
+ }
1865
+ return t;
1866
+ })
1867
+ .join(','));
1868
+ }
1869
+ // need to use form?.id for internally-submitted forms because formResponseId isn't generated until initial submission or saved draft
1870
+ if (((_h = field.options) === null || _h === void 0 ? void 0 : _h.holdAppointmentMinutes) && (formResponseId || (field === null || field === void 0 ? void 0 : field.id))) {
1871
+ bookingURL += "&formResponseId=".concat(formResponseId || (field === null || field === void 0 ? void 0 : field.id));
1872
+ bookingURL += "&holdAppointmentMinutes=".concat(field.options.holdAppointmentMinutes);
1873
+ }
1874
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1, sx: { mt: 1 } }, { children: [!!((_k = (_j = field.options) === null || _j === void 0 ? void 0 : _j.userFilterTags) === null || _k === void 0 ? void 0 : _k.length) && !((_l = field.options.userTags) === null || _l === void 0 ? void 0 : _l.length) && !(isPreviousDisabled === null || isPreviousDisabled === void 0 ? void 0 : isPreviousDisabled()) && !confirming &&
1875
+ _jsx(Grid, __assign({ item: true, alignSelf: "flex-start" }, { children: _jsx(Button, __assign({ variant: "outlined", onClick: goToPreviousField, sx: { height: 25, p: 0.5, px: 1 } }, { children: "Back" })) })), loaded.warningMessage &&
1876
+ _jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ color: "error", sx: { fontSize: 20, fontWeight: 'bold' } }, { children: loaded.warningMessage })) })), _jsx(Grid, __assign({ item: true }, { children: (!loaded.warningMessage || acknowledgedWarning)
1877
+ ? (_jsx("iframe", { title: "Appointment Booking Embed", src: bookingURL, style: { border: 'none', width: '100%', height: height } }))
1878
+ : (_jsx(Button, __assign({ variant: "outlined", onClick: function () { return setAcknowledgedWarning(true); } }, { children: "Show Booking Page Preview" }))) }))] })));
1879
+ };
1880
+ export var HeightInput = function (_a) {
1881
+ var _b;
1882
+ var field = _a.field, _d = _a.value, value = _d === void 0 ? {} : _d, onChange = _a.onChange, props = __rest(_a, ["field", "value", "onChange"]);
1883
+ return (_jsxs(Grid, __assign({ container: true, alignItems: 'center', wrap: "nowrap", spacing: 1, style: { marginTop: 5 } }, { children: [_jsx(Grid, __assign({ item: true, sx: { width: '100%' } }, { children: _jsx(TextField, { fullWidth: true, size: "small", label: "Feet", type: "number", value: (value === null || value === void 0 ? void 0 : value.feet) || '', onChange: function (e) { return onChange(__assign(__assign({}, value), { feet: parseInt(e.target.value) }), field.id); } }) })), _jsx(Grid, __assign({ item: true, sx: { width: '100%' } }, { children: _jsx(TextField, { fullWidth: true, size: "small", label: "Inches", type: "number", value: (_b = value === null || value === void 0 ? void 0 : value.inches) !== null && _b !== void 0 ? _b : '', onChange: function (e) { return onChange(__assign(__assign({}, value), { inches: parseInt(e.target.value) }), field.id); } }) }))] })));
1884
+ };
1885
+ export var include_current_url_parameters_if_templated = function (url) {
1886
+ try {
1887
+ // get parameters from the current URL, and replace all values where {{URL_PARAM.paramName}} is used
1888
+ var params_1 = new URL(window.location.href).searchParams;
1889
+ return url.replace(/{{URL_PARAM\.(.*?)}}/g, function (_, paramName) {
1890
+ var value = params_1.get(paramName);
1891
+ console.log(paramName, value);
1892
+ if (value === null)
1893
+ return '';
1894
+ return value;
1895
+ });
1896
+ }
1897
+ catch (err) {
1898
+ console.error(err);
1899
+ }
1900
+ return url;
1901
+ };
1902
+ export var RedirectInput = function (_a) {
1903
+ var _b, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
1904
+ var enduserId = _a.enduserId, groupId = _a.groupId, groupInsance = _a.groupInsance, rootResponseId = _a.rootResponseId, formResponseId = _a.formResponseId, field = _a.field, submit = _a.submit, _u = _a.value, value = _u === void 0 ? {} : _u, onChange = _a.onChange, responses = _a.responses, enduser = _a.enduser, props = __rest(_a, ["enduserId", "groupId", "groupInsance", "rootResponseId", "formResponseId", "field", "submit", "value", "onChange", "responses", "enduser"]);
1905
+ var session = useResolvedSession();
1906
+ var eId = '';
1907
+ try {
1908
+ eId = new URL(window.location.href).searchParams.get('eId') || enduserId || (enduser === null || enduser === void 0 ? void 0 : enduser.id) || '';
1909
+ }
1910
+ catch (err) { }
1911
+ var email = (((_d = (_b = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'email'; })) === null || _b === void 0 ? void 0 : _b.answer) === null || _d === void 0 ? void 0 : _d.value)
1912
+ || (enduser === null || enduser === void 0 ? void 0 : enduser.email)
1913
+ || session.userInfo.email);
1914
+ var phone = (((_f = (_e = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'phone'; })) === null || _e === void 0 ? void 0 : _e.answer) === null || _f === void 0 ? void 0 : _f.value)
1915
+ || (enduser === null || enduser === void 0 ? void 0 : enduser.phone)
1916
+ || session.userInfo.phone);
1917
+ var fname = (((_h = (_g = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'fname'; })) === null || _g === void 0 ? void 0 : _g.answer) === null || _h === void 0 ? void 0 : _h.value)
1918
+ || (enduser === null || enduser === void 0 ? void 0 : enduser.fname)
1919
+ || ((_j = session.userInfo) === null || _j === void 0 ? void 0 : _j.fname));
1920
+ var lname = (((_l = (_k = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'lname'; })) === null || _k === void 0 ? void 0 : _k.answer) === null || _l === void 0 ? void 0 : _l.value)
1921
+ || (enduser === null || enduser === void 0 ? void 0 : enduser.lname)
1922
+ || ((_m = session.userInfo) === null || _m === void 0 ? void 0 : _m.lname));
1923
+ var state = (((_p = (_o = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'state'; })) === null || _o === void 0 ? void 0 : _o.answer) === null || _p === void 0 ? void 0 : _p.value)
1924
+ || ((_s = (_r = (_q = responses === null || responses === void 0 ? void 0 : responses.find(function (r) { return r.intakeField === 'Address'; })) === null || _q === void 0 ? void 0 : _q.answer) === null || _r === void 0 ? void 0 : _r.value) === null || _s === void 0 ? void 0 : _s.state)
1925
+ || (enduser === null || enduser === void 0 ? void 0 : enduser.state)
1926
+ || ((_t = session.userInfo) === null || _t === void 0 ? void 0 : _t.state));
1927
+ useEffect(function () {
1928
+ var _a, _b;
1929
+ if (session.type === 'user') {
1930
+ return;
1931
+ }
1932
+ if ((_a = field.options) === null || _a === void 0 ? void 0 : _a.redirectExternalUrl) {
1933
+ submit === null || submit === void 0 ? void 0 : submit().finally(function () {
1934
+ var _a;
1935
+ if (!((_a = field.options) === null || _a === void 0 ? void 0 : _a.redirectExternalUrl)) {
1936
+ return;
1937
+ }
1938
+ window.location.href = (include_current_url_parameters_if_templated(replace_enduser_template_values(field.options.redirectExternalUrl, __assign(__assign({}, session.userInfo), { id: eId, email: email, fname: fname, lname: lname, state: state, phone: phone }))));
1939
+ }).catch(console.error);
1940
+ return;
1941
+ }
1942
+ if (!((_b = field.options) === null || _b === void 0 ? void 0 : _b.redirectFormId)) {
1943
+ return;
1944
+ }
1945
+ session.api.form_responses.prepare_form_response({
1946
+ enduserId: session.userInfo.id || eId,
1947
+ formId: field.options.redirectFormId,
1948
+ rootResponseId: rootResponseId || formResponseId,
1949
+ parentResponseId: formResponseId,
1950
+ })
1951
+ .then(function (_a) {
1952
+ var fullURL = _a.fullURL;
1953
+ return (
1954
+ // we should still redirect even if submission fails
1955
+ submit === null || submit === void 0 ? void 0 : submit().catch(console.error).finally(function () {
1956
+ // if accessing form group in portal
1957
+ if (window.location.href.includes('/documents') && groupId && groupInsance) {
1958
+ var toRedirect = "".concat(window.location.origin, "/documents?groupId=").concat(groupId, "&groupInstance=").concat(groupInsance);
1959
+ if (fullURL.endsWith('&')) {
1960
+ window.location.replace(fullURL + "back=".concat(toRedirect, "&"));
1961
+ }
1962
+ else {
1963
+ window.location.replace(fullURL + "&back=".concat(toRedirect));
1964
+ }
1965
+ }
1966
+ else {
1967
+ window.location.replace(fullURL);
1968
+ }
1969
+ }));
1970
+ })
1971
+ .catch(console.error);
1972
+ }, [session, email, fname, lname, state, phone]);
1973
+ if (session.type === 'user') {
1974
+ return (_jsx(Typography, { children: "Redirect is for patient-facing forms only" }));
1975
+ }
1976
+ return null;
1977
+ };
1978
+ export var HiddenValueInput = function (_a) {
1979
+ var goToNextField = _a.goToNextField, goToPreviousField = _a.goToPreviousField, field = _a.field, value = _a.value, onChange = _a.onChange, isSinglePage = _a.isSinglePage, groupFields = _a.groupFields;
1980
+ var lastRef = useRef(0);
1981
+ var lastIdRef = useRef('');
1982
+ // in a Question Group, only the first Hidden Value should navigate
1983
+ // AND, it should only navigate if the group only contains hidden values
1984
+ var firstHiddenValue = groupFields === null || groupFields === void 0 ? void 0 : groupFields.find(function (v) { return v.type === 'Hidden Value'; });
1985
+ var dontNavigate = ((firstHiddenValue && (firstHiddenValue === null || firstHiddenValue === void 0 ? void 0 : firstHiddenValue.id) !== field.id) // is in a group, but not the first hidden value
1986
+ || !!(groupFields === null || groupFields === void 0 ? void 0 : groupFields.find(function (v) { return v.type !== 'Hidden Value'; })) // group contains at least 1 non-hidden value
1987
+ );
1988
+ var publicIdentifier = useMemo(function () {
1989
+ try {
1990
+ return new URL(window.location.href).searchParams.get('publicIdentifier') || '';
1991
+ }
1992
+ catch (err) {
1993
+ return '';
1994
+ }
1995
+ }, []);
1996
+ var valueToSet = useMemo(function () { return ((field.title === "{{PUBLIC_IDENTIFIER}}" && publicIdentifier) ? publicIdentifier
1997
+ : field.title); }, [field.title, publicIdentifier]);
1998
+ useEffect(function () {
1999
+ if (lastRef.current > Date.now() - 1000 && lastIdRef.current === field.id)
2000
+ return;
2001
+ lastRef.current = Date.now();
2002
+ lastIdRef.current = field.id;
2003
+ if (value) {
2004
+ if (isSinglePage)
2005
+ return;
2006
+ onChange('', field.id);
2007
+ if (dontNavigate)
2008
+ return;
2009
+ goToPreviousField === null || goToPreviousField === void 0 ? void 0 : goToPreviousField();
2010
+ }
2011
+ else {
2012
+ onChange(valueToSet, field.id);
2013
+ if (dontNavigate)
2014
+ return;
2015
+ // pass value that is set after above onChange
2016
+ goToNextField === null || goToNextField === void 0 ? void 0 : goToNextField({ type: 'Hidden Value', value: valueToSet });
2017
+ }
2018
+ }, [value, onChange, field.id, valueToSet, goToNextField, goToPreviousField, isSinglePage, dontNavigate]);
2019
+ return _jsx(_Fragment, {});
2020
+ };
2021
+ export var EmotiiInput = function (_a) {
2022
+ var goToNextField = _a.goToNextField, goToPreviousField = _a.goToPreviousField, field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, formResponseId = _a.formResponseId, props = __rest(_a, ["goToNextField", "goToPreviousField", "field", "value", "onChange", "form", "formResponseId"]);
2023
+ var session = useResolvedSession();
2024
+ var requestIdRef = useRef(value || "".concat(field.id).concat(formResponseId || Date.now()));
2025
+ var _b = useState(), data = _b[0], setData = _b[1];
2026
+ var _d = useState(0), loadCount = _d[0], setLoadCount = _d[1];
2027
+ var fetchRef = useRef(false);
2028
+ useEffect(function () {
2029
+ if (value)
2030
+ return;
2031
+ if (fetchRef.current)
2032
+ return;
2033
+ fetchRef.current = true;
2034
+ session.api.integrations
2035
+ .proxy_read({
2036
+ integration: EMOTII_TITLE,
2037
+ type: 'get_survey',
2038
+ id: props === null || props === void 0 ? void 0 : props.enduserId,
2039
+ query: requestIdRef.current,
2040
+ })
2041
+ .then(function (r) { return setData(r.data); });
2042
+ }, [session, value, props === null || props === void 0 ? void 0 : props.enduserId]);
2043
+ var loadAnswerRef = useRef(false);
2044
+ useEffect(function () {
2045
+ if (loadCount !== 2)
2046
+ return;
2047
+ if (loadAnswerRef.current)
2048
+ return;
2049
+ loadAnswerRef.current = true;
2050
+ onChange(requestIdRef.current, field.id);
2051
+ }, [loadCount]);
2052
+ if (value || loadCount === 2)
2053
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap" }, { children: [_jsx(CheckCircleOutline, { color: "success" }), _jsx(Typography, __assign({ sx: { ml: 1, fontSize: 20 } }, { children: "Please click Next or Submit to continue." }))] })));
2054
+ if (!data) {
2055
+ return _jsx(LinearProgress, {});
2056
+ }
2057
+ return (_jsx("iframe", { src: data.surveyUrl, style: { border: 'none', height: 650, width: '100%' }, onLoad: function () { return setLoadCount(function (l) { return l + 1; }); } }));
2058
+ };
2059
+ export var AllergiesInput = function (_a) {
2060
+ var _b;
2061
+ var goToNextField = _a.goToNextField, goToPreviousField = _a.goToPreviousField, field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, formResponseId = _a.formResponseId, props = __rest(_a, ["goToNextField", "goToPreviousField", "field", "value", "onChange", "form", "formResponseId"]);
2062
+ var session = useResolvedSession();
2063
+ var _d = useState(''), query = _d[0], setQuery = _d[1];
2064
+ var _e = useState([]), results = _e[0], setResults = _e[1];
2065
+ // if two allergy questions shown in a row, reset state
2066
+ useEffect(function () {
2067
+ setQuery('');
2068
+ setResults([]);
2069
+ }, [field.id]);
2070
+ var fetchRef = useRef(query);
2071
+ useEffect(function () {
2072
+ if (fetchRef.current === query)
2073
+ return;
2074
+ fetchRef.current = query;
2075
+ if (!query)
2076
+ return;
2077
+ var t = setTimeout(function () {
2078
+ var _a;
2079
+ if (((_a = field.options) === null || _a === void 0 ? void 0 : _a.dataSource) === CANVAS_TITLE) {
2080
+ session.api.integrations
2081
+ .proxy_read({
2082
+ integration: CANVAS_TITLE,
2083
+ type: 'allergies',
2084
+ query: query,
2085
+ })
2086
+ .then(function (r) {
2087
+ var deduped = [];
2088
+ var totalResults = ((r.data.entry || [])
2089
+ .flatMap(function (v) { var _a, _b; return ((_b = (_a = v === null || v === void 0 ? void 0 : v.resource) === null || _a === void 0 ? void 0 : _a.code) === null || _b === void 0 ? void 0 : _b.coding) || []; })
2090
+ .filter(function (v) { return v.system.includes('fdbhealth'); })
2091
+ .map(function (v) { return ({ code: v.code, display: v.display, system: v.system }); }));
2092
+ var _loop_2 = function (v) {
2093
+ if (deduped.find(function (d) { return d.display === v.display; })) {
2094
+ return "continue";
2095
+ }
2096
+ deduped.push(v);
2097
+ };
2098
+ for (var _a = 0, totalResults_1 = totalResults; _a < totalResults_1.length; _a++) {
2099
+ var v = totalResults_1[_a];
2100
+ _loop_2(v);
2101
+ }
2102
+ setResults(deduped);
2103
+ });
2104
+ }
2105
+ else {
2106
+ session.api.allergy_codes.getSome({ search: { query: query } })
2107
+ .then(function (results) {
2108
+ var deduped = [];
2109
+ var _loop_3 = function (v) {
2110
+ if (deduped.find(function (d) { return d.display === v.display; })) {
2111
+ return "continue";
2112
+ }
2113
+ deduped.push(v);
2114
+ };
2115
+ for (var _a = 0, results_1 = results; _a < results_1.length; _a++) {
2116
+ var v = results_1[_a];
2117
+ _loop_3(v);
2118
+ }
2119
+ setResults(deduped);
2120
+ });
2121
+ }
2122
+ }, 200);
2123
+ return function () { clearTimeout(t); };
2124
+ }, [session, query, (_b = field === null || field === void 0 ? void 0 : field.options) === null || _b === void 0 ? void 0 : _b.dataSource]);
2125
+ return (_jsxs(Grid, __assign({ container: true, direction: "column", spacing: 1 }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Autocomplete, { multiple: true, value: value || [], options: results, style: { marginTop: 5 }, noOptionsText: query.length ? 'No results found' : 'Type to start search', onChange: function (e, v) {
2126
+ if (!v) {
2127
+ return;
2128
+ }
2129
+ onChange(v, field.id);
2130
+ setResults([]);
2131
+ }, getOptionLabel: function (v) { return first_letter_capitalized(v.display); }, filterOptions: function (o) { return o; }, inputValue: query, onInputChange: function (e, v) { return e && setQuery(v); }, renderInput: function (params) { return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, size: "small", label: "", placeholder: "Search allergies..." }))); }, renderTags: function (value, getTagProps) {
2132
+ return value.map(function (value, index) { return (_jsx(Chip, __assign({ label: _jsx(Typography, __assign({ style: { whiteSpace: 'normal' } }, { children: value.display })) }, getTagProps({ index: index }), { sx: { height: "100%", py: 0.5 } }))); });
2133
+ } }) })), (value || []).map(function (allergy, i) { return (_jsx(Grid, __assign({ item: true }, { children: _jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap", columnGap: 0.5, justifyContent: "space-between" }, { children: [_jsx(Grid, __assign({ item: true }, { children: _jsx(Typography, __assign({ noWrap: true, sx: { width: 85, fontSize: 14 } }, { children: allergy.display })) })), _jsx(Grid, __assign({ item: true, sx: { width: 140 } }, { children: _jsx(StringSelector, { options: ['mild', 'moderate', 'severe'], size: "small", label: "Severity", value: allergy.severity || '', onChange: function (severity) { return onChange((value || []).map(function (v, _i) { return i === _i ? __assign(__assign({}, v), { severity: severity }) : v; }), field.id); }, getDisplayValue: first_letter_capitalized }) })), _jsx(Grid, __assign({ item: true, sx: { width: "50%" } }, { children: _jsx(TextField, { InputProps: { sx: defaultInputProps.sx }, fullWidth: true, size: "small", label: "Note", value: allergy.note || '', onChange: function (e) { return onChange((value || []).map(function (v, _i) { return i === _i ? __assign(__assign({}, v), { note: e.target.value }) : v; }), field.id); } }) }))] })) }), i)); })] })));
2134
+ };
2135
+ var display_with_code = function (v) { return "".concat(v.code, ": ").concat(first_letter_capitalized(v.display)); };
2136
+ export var ConditionsInput = function (_a) {
2137
+ var goToNextField = _a.goToNextField, goToPreviousField = _a.goToPreviousField, field = _a.field, value = _a.value, onChange = _a.onChange, form = _a.form, formResponseId = _a.formResponseId, props = __rest(_a, ["goToNextField", "goToPreviousField", "field", "value", "onChange", "form", "formResponseId"]);
2138
+ var session = useResolvedSession();
2139
+ var _b = useState(''), query = _b[0], setQuery = _b[1];
2140
+ var _d = useState([]), results = _d[0], setResults = _d[1];
2141
+ var fetchRef = useRef(query);
2142
+ useEffect(function () {
2143
+ if (fetchRef.current === query)
2144
+ return;
2145
+ fetchRef.current = query;
2146
+ if (!query)
2147
+ return;
2148
+ var t = setTimeout(function () {
2149
+ session.api.diagnosis_codes.getSome({ search: { query: query } })
2150
+ .then(function (codes) {
2151
+ var deduped = [];
2152
+ var _loop_4 = function (v) {
2153
+ if (deduped.find(function (d) { return d.display === v.display; })) {
2154
+ return "continue";
2155
+ }
2156
+ deduped.push(v);
2157
+ };
2158
+ for (var _a = 0, codes_1 = codes; _a < codes_1.length; _a++) {
2159
+ var v = codes_1[_a];
2160
+ _loop_4(v);
2161
+ }
2162
+ setResults(deduped);
2163
+ });
2164
+ }, 200);
2165
+ return function () { clearTimeout(t); };
2166
+ }, [session, query]);
2167
+ return (_jsx(Autocomplete, { multiple: true, value: value || [], options: results, style: { marginTop: 5 }, noOptionsText: query.length ? 'No results found' : 'Type to start search', onChange: function (e, v) {
2168
+ if (!v) {
2169
+ return;
2170
+ }
2171
+ onChange(v, field.id);
2172
+ setResults([]);
2173
+ }, getOptionLabel: display_with_code, filterOptions: function (o) { return o; }, inputValue: query, onInputChange: function (e, v) { return e && setQuery(v); }, renderInput: function (params) { return (_jsx(TextField, __assign({}, params, { InputProps: __assign(__assign({}, params.InputProps), { sx: defaultInputProps.sx }), required: !field.isOptional, size: "small", label: "", placeholder: "Search conditions..." }))); }, renderTags: function (value, getTagProps) {
2174
+ return value.map(function (value, index) { return (_jsx(Chip, __assign({ label: _jsx(Typography, __assign({ style: { whiteSpace: 'normal' } }, { children: display_with_code(value) })) }, getTagProps({ index: index }), { sx: { height: "100%", py: 0.5 } }))); });
2175
+ } }));
2176
+ };
2177
+ export var RichTextInput = function (_a) {
2178
+ var field = _a.field, value = _a.value, onChange = _a.onChange;
2179
+ return (_jsx(WYSIWYG, { stopEnterPropagation: true, initialHTML: value, onChange: function (v) { return onChange(v, field.id); }, style: { width: '100%' }, editorStyle: { width: '100%' } }));
2180
+ };
2181
+ export var ChargeebeeInput = function (_a) {
2182
+ var field = _a.field, value = _a.value, onChange = _a.onChange, setCustomerId = _a.setCustomerId;
2183
+ var session = useResolvedSession();
2184
+ var _b = useState(''), url = _b[0], setUrl = _b[1];
2185
+ var _d = useState(''), error = _d[0], setError = _d[1];
2186
+ var _e = useState(0), loadCount = _e[0], setLoadCount = _e[1];
2187
+ var fetchRef = useRef(false);
2188
+ useEffect(function () {
2189
+ if (fetchRef.current)
2190
+ return;
2191
+ fetchRef.current = true;
2192
+ session.api.form_responses.chargebee_details({ fieldId: field.id })
2193
+ .then(function (_a) {
2194
+ var url = _a.url;
2195
+ return setUrl(url);
2196
+ })
2197
+ .catch(setError);
2198
+ }, [session]);
2199
+ var loadAnswerRef = useRef(false);
2200
+ useEffect(function () {
2201
+ if (loadCount !== 2)
2202
+ return;
2203
+ if (loadAnswerRef.current)
2204
+ return;
2205
+ loadAnswerRef.current = true;
2206
+ onChange({ url: url }, field.id);
2207
+ }, [loadCount, url]);
2208
+ if (value || loadCount === 2) {
2209
+ return (_jsxs(Grid, __assign({ container: true, alignItems: "center", wrap: "nowrap" }, { children: [_jsx(CheckCircleOutline, { color: "success" }), _jsx(Typography, __assign({ sx: { ml: 1, fontSize: 20 } }, { children: "Your purchase was successful" }))] })));
2210
+ }
2211
+ if (error && typeof error === 'string')
2212
+ return _jsx(Typography, __assign({ color: "error" }, { children: error }));
2213
+ if (!url)
2214
+ return _jsx(LinearProgress, {});
2215
+ return (_jsx("iframe", { src: url, title: "Checkout", style: { border: 'none', width: '100%', height: 700 }, onLoad: function () { return setLoadCount(function (l) { return l + 1; }); } }));
2216
+ };
2217
+ var templateObject_1, templateObject_2;
2218
+ //# sourceMappingURL=inputs.v2.js.map