formanitor 0.0.12 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import { twMerge } from 'tailwind-merge';
6
6
  import * as LabelPrimitive from '@radix-ui/react-label';
7
7
  import { cva } from 'class-variance-authority';
8
8
  import * as SelectPrimitive from '@radix-ui/react-select';
9
- import { ChevronDown, ChevronUp, Check, Circle, X, Image, Upload, Trash2, Plus, PenTool, ChevronRight, Calendar as Calendar$1, ChevronLeft, RefreshCw, Clock } from 'lucide-react';
9
+ import { ChevronDown, ChevronUp, Check, Circle, X, Image, Upload, Trash2, Plus, Loader2, PenTool, ChevronRight, Calendar as Calendar$1, ChevronLeft, RefreshCw, Clock } from 'lucide-react';
10
10
  import * as CheckboxPrimitive from '@radix-ui/react-checkbox';
11
11
  import { Slot } from '@radix-ui/react-slot';
12
12
  import { format, addDays, addWeeks, addMonths, differenceInCalendarDays, parseISO } from 'date-fns';
@@ -15,6 +15,7 @@ import * as PopoverPrimitive from '@radix-ui/react-popover';
15
15
  import { useReactTable, getCoreRowModel, flexRender } from '@tanstack/react-table';
16
16
  import * as RadioGroupPrimitive from '@radix-ui/react-radio-group';
17
17
  import * as DialogPrimitive from '@radix-ui/react-dialog';
18
+ import nlp from 'compromise';
18
19
 
19
20
  // src/core/validate.ts
20
21
  var EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
@@ -27,6 +28,11 @@ function validateField(value, field) {
27
28
  if (Array.isArray(value) && value.length === 0) {
28
29
  return "This field is required";
29
30
  }
31
+ if (field.type === "smart_textarea" && typeof value === "object" && !Array.isArray(value)) {
32
+ if (!value.text || value.text.trim() === "") {
33
+ return "This field is required";
34
+ }
35
+ }
30
36
  }
31
37
  if (value === null || value === void 0 || value === "") {
32
38
  return null;
@@ -214,6 +220,7 @@ var FormStore = class {
214
220
  } else {
215
221
  if (field.type === "repeatable") values[field.id] = [];
216
222
  else if (field.type === "checkbox") values[field.id] = [];
223
+ else if (field.type === "smart_textarea") values[field.id] = { text: "", extractedKeywords: [] };
217
224
  else values[field.id] = null;
218
225
  }
219
226
  });
@@ -361,6 +368,15 @@ var FormStore = class {
361
368
  getSerializedValuesForSubmission() {
362
369
  return this.serializeValuesForSubmission(this.state.values);
363
370
  }
371
+ /**
372
+ * Raw form values as stored internally, without any serialization or
373
+ * transformation. Useful when consumers need access to richer structures
374
+ * (e.g. smart_textarea keyword metadata) alongside the flattened values
375
+ * returned by getSerializedValuesForSubmission.
376
+ */
377
+ getRawValues() {
378
+ return { ...this.state.values };
379
+ }
364
380
  serializeValuesForSubmission(values) {
365
381
  const result = { ...values };
366
382
  this.schema.fields.forEach((field) => {
@@ -368,6 +384,11 @@ var FormStore = class {
368
384
  delete result[field.id];
369
385
  return;
370
386
  }
387
+ if (field.type === "smart_textarea") {
388
+ const raw = values[field.id];
389
+ result[field.id] = raw?.text ?? null;
390
+ return;
391
+ }
371
392
  if (field.type === "image_upload" || field.type === "signature") {
372
393
  const raw = values[field.id];
373
394
  if (raw !== void 0 && raw !== null && raw !== "") {
@@ -658,6 +679,7 @@ function useForm() {
658
679
  availableTransitions: store.getAvailableTransitions(),
659
680
  hasPersistence: store.hasPersistence(),
660
681
  getSerializedValues: store.getSerializedValuesForSubmission.bind(store),
682
+ getRawValues: store.getRawValues.bind(store),
661
683
  markSubmitAttempted: store.markSubmitAttempted.bind(store),
662
684
  flushPendingUploads: store.flushPendingUploads.bind(store)
663
685
  };
@@ -3992,6 +4014,788 @@ var FollowupWidget = ({ fieldId }) => {
3992
4014
  error && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error })
3993
4015
  ] }) });
3994
4016
  };
4017
+ function useSmartKeywords(text, onSearch, debounceDelay = 1e3) {
4018
+ console.log("[useSmartKeywords] render", {
4019
+ textLength: text?.length ?? 0,
4020
+ hasOnSearch: typeof onSearch === "function",
4021
+ debounceDelay
4022
+ });
4023
+ const [extractedNouns, setExtractedNouns] = useState([]);
4024
+ const [matchedConditions, setMatchedConditions] = useState([]);
4025
+ const [isProcessing, setIsProcessing] = useState(false);
4026
+ const [error, setError] = useState(null);
4027
+ const timerRef = useRef(null);
4028
+ const abortRef = useRef(0);
4029
+ const processText = useCallback(
4030
+ async (input, runId) => {
4031
+ if (!input || input.trim().length === 0) {
4032
+ console.log("[useSmartKeywords] skip empty input", {
4033
+ runId,
4034
+ inputLength: input?.length ?? 0
4035
+ });
4036
+ setExtractedNouns([]);
4037
+ setMatchedConditions([]);
4038
+ setIsProcessing(false);
4039
+ return;
4040
+ }
4041
+ console.log("[useSmartKeywords] processText start", {
4042
+ runId,
4043
+ inputLength: input.length
4044
+ });
4045
+ setIsProcessing(true);
4046
+ setError(null);
4047
+ try {
4048
+ const nouns = extractNouns(input);
4049
+ const uniqueNouns = Array.from(new Set(nouns));
4050
+ console.log("[useSmartKeywords] extracted nouns", {
4051
+ runId,
4052
+ nouns,
4053
+ uniqueNouns
4054
+ });
4055
+ if (runId !== abortRef.current) return;
4056
+ setExtractedNouns(uniqueNouns);
4057
+ if (uniqueNouns.length === 0) {
4058
+ console.log("[useSmartKeywords] no nouns, skipping search", { runId });
4059
+ setMatchedConditions([]);
4060
+ setIsProcessing(false);
4061
+ return;
4062
+ }
4063
+ const searchResults = await Promise.all(
4064
+ uniqueNouns.map(async (noun) => {
4065
+ const normalised = noun.replace(/\s+/g, " ").replace(/^[\s-]+/, "").trim();
4066
+ try {
4067
+ console.log("[useSmartKeywords] onSearch call", { runId, noun, normalised });
4068
+ const results = await onSearch(normalised);
4069
+ console.log("[useSmartKeywords] onSearch result", {
4070
+ runId,
4071
+ noun,
4072
+ normalised,
4073
+ count: Array.isArray(results) ? results.length : 0
4074
+ });
4075
+ const first = Array.isArray(results) && results.length > 0 ? [results[0]] : [];
4076
+ return { keyword: normalised, matches: first };
4077
+ } catch (err) {
4078
+ console.error("[useSmartKeywords] onSearch error", { runId, noun, err });
4079
+ return { keyword: normalised || noun, matches: [] };
4080
+ }
4081
+ })
4082
+ );
4083
+ if (runId !== abortRef.current) return;
4084
+ const allMatches = searchResults.flatMap(
4085
+ ({ keyword, matches }) => matches.map((record) => ({
4086
+ extractedKeyword: keyword,
4087
+ matchedCondition: {
4088
+ id: record.id,
4089
+ name: record.name,
4090
+ created_at: record.created_at,
4091
+ updated_at: record.updated_at
4092
+ }
4093
+ }))
4094
+ );
4095
+ console.log("[useSmartKeywords] allMatches computed", {
4096
+ runId,
4097
+ matchesCount: allMatches.length
4098
+ });
4099
+ setMatchedConditions(allMatches);
4100
+ } catch (err) {
4101
+ if (runId !== abortRef.current) return;
4102
+ console.error("[useSmartKeywords] processText error", { runId, err });
4103
+ setError(err instanceof Error ? err.message : "Keyword extraction failed");
4104
+ } finally {
4105
+ if (runId === abortRef.current) {
4106
+ console.log("[useSmartKeywords] processText end", { runId });
4107
+ setIsProcessing(false);
4108
+ }
4109
+ }
4110
+ },
4111
+ [onSearch]
4112
+ );
4113
+ useEffect(() => {
4114
+ if (timerRef.current) clearTimeout(timerRef.current);
4115
+ const runId = ++abortRef.current;
4116
+ console.log("[useSmartKeywords] schedule debounce", {
4117
+ runId,
4118
+ debounceDelay,
4119
+ textLength: text?.length ?? 0
4120
+ });
4121
+ timerRef.current = setTimeout(() => {
4122
+ console.log("[useSmartKeywords] debounce fired", { runId });
4123
+ processText(text, runId);
4124
+ }, debounceDelay);
4125
+ return () => {
4126
+ if (timerRef.current) clearTimeout(timerRef.current);
4127
+ };
4128
+ }, [text, debounceDelay, processText]);
4129
+ return { extractedNouns, matchedConditions, isProcessing, error };
4130
+ }
4131
+ function extractNouns(text) {
4132
+ const doc = nlp(text);
4133
+ const rawNouns = doc.nouns().out("array");
4134
+ const cleaned = rawNouns.map((n) => n.replace(/[^\w\s-]/g, "").trim().toLowerCase()).filter((n) => n.length > 2);
4135
+ console.log("[useSmartKeywords] extractNouns", {
4136
+ inputLength: text?.length ?? 0,
4137
+ rawNouns,
4138
+ cleaned
4139
+ });
4140
+ return cleaned;
4141
+ }
4142
+ var SmartTextareaWidget = ({ fieldId }) => {
4143
+ const { fieldDef, value, setValue, setTouched, error, disabled, touched } = useField(fieldId);
4144
+ const { state } = useForm();
4145
+ const handler = useFieldHandlers(fieldId);
4146
+ const def = fieldDef;
4147
+ const structured = value;
4148
+ const textValue = structured?.text ?? "";
4149
+ const showError = !!error && (touched || state.submitAttempted);
4150
+ const onSearch = useCallback(
4151
+ (query) => handler.onSearch(query),
4152
+ [handler]
4153
+ );
4154
+ const { matchedConditions, isProcessing } = useSmartKeywords(
4155
+ textValue,
4156
+ onSearch,
4157
+ def?.debounceDelay ?? 1e3
4158
+ );
4159
+ const currentKeywords = structured?.extractedKeywords ?? [];
4160
+ const nextKeywords = useMemo(() => {
4161
+ if (matchedConditions.length === 0 && currentKeywords.length === 0) return currentKeywords;
4162
+ if (matchedConditions.length === currentKeywords.length && matchedConditions.every(
4163
+ (m, i) => m.matchedCondition.id === currentKeywords[i]?.matchedCondition.id && m.extractedKeyword === currentKeywords[i]?.extractedKeyword
4164
+ )) {
4165
+ return currentKeywords;
4166
+ }
4167
+ return matchedConditions;
4168
+ }, [matchedConditions, currentKeywords]);
4169
+ const writeValue = useCallback(
4170
+ (text, keywords) => {
4171
+ const next = { text, extractedKeywords: keywords };
4172
+ setValue(next);
4173
+ },
4174
+ [setValue]
4175
+ );
4176
+ React11__default.useEffect(() => {
4177
+ if (nextKeywords !== currentKeywords) {
4178
+ writeValue(textValue, nextKeywords);
4179
+ }
4180
+ }, [nextKeywords]);
4181
+ const handleTextChange = useCallback(
4182
+ (e) => {
4183
+ writeValue(e.target.value, currentKeywords);
4184
+ },
4185
+ [writeValue, currentKeywords]
4186
+ );
4187
+ if (!def) return null;
4188
+ const height = def.height;
4189
+ const theme = getThemeConfig("textarea", def.theme);
4190
+ const wrapperClass = theme?.wrapperClassName ?? "space-y-2";
4191
+ const labelClass = theme?.labelClassName;
4192
+ const inputClass = cn(theme?.inputClassName, showError && "border-red-500");
4193
+ const labelContent = /* @__PURE__ */ jsxs(Fragment, { children: [
4194
+ def.label,
4195
+ " ",
4196
+ def.required && /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" }),
4197
+ isProcessing && /* @__PURE__ */ jsx(Loader2, { className: "inline-block ml-1.5 h-3 w-3 animate-spin text-muted-foreground" })
4198
+ ] });
4199
+ return /* @__PURE__ */ jsxs("div", { className: wrapperClass, children: [
4200
+ theme ? /* @__PURE__ */ jsx(Label, { htmlFor: fieldId, className: labelClass, children: labelContent }) : /* @__PURE__ */ jsx(Label, { htmlFor: fieldId, children: labelContent }),
4201
+ /* @__PURE__ */ jsx(
4202
+ Textarea,
4203
+ {
4204
+ id: fieldId,
4205
+ value: textValue,
4206
+ onChange: handleTextChange,
4207
+ onBlur: setTouched,
4208
+ disabled,
4209
+ placeholder: def.placeholder,
4210
+ className: inputClass,
4211
+ ...height != null ? { height } : {}
4212
+ }
4213
+ ),
4214
+ showError && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-500", children: error })
4215
+ ] });
4216
+ };
4217
+ var DEFAULT_DRAFT = {
4218
+ gpal: { G: 0, P: 0, A: 0, L: 0 },
4219
+ lmp: "",
4220
+ is_pregnant: false,
4221
+ eddUSG: "",
4222
+ primaryEDD: "lmp",
4223
+ complications: "",
4224
+ outcome: null
4225
+ };
4226
+ function pad2(n) {
4227
+ return String(n).padStart(2, "0");
4228
+ }
4229
+ function formatDdMmYyyy(iso) {
4230
+ const [y, m, d] = iso.split("-");
4231
+ if (!y || !m || !d) return iso;
4232
+ return `${pad2(Number(d))}/${pad2(Number(m))}/${y}`;
4233
+ }
4234
+ function todayIso() {
4235
+ const d = /* @__PURE__ */ new Date();
4236
+ const y = d.getFullYear();
4237
+ const m = pad2(d.getMonth() + 1);
4238
+ const day = pad2(d.getDate());
4239
+ return `${y}-${m}-${day}`;
4240
+ }
4241
+ function isValidIsoDate(val) {
4242
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(val)) return false;
4243
+ const dt = /* @__PURE__ */ new Date(`${val}T00:00:00.000Z`);
4244
+ return !Number.isNaN(dt.getTime());
4245
+ }
4246
+ function safeJsonParse(val) {
4247
+ try {
4248
+ return JSON.parse(val);
4249
+ } catch {
4250
+ return null;
4251
+ }
4252
+ }
4253
+ function clampInt(val, min, max) {
4254
+ if (!Number.isFinite(val)) return min;
4255
+ return Math.max(min, Math.min(max, Math.trunc(val)));
4256
+ }
4257
+ function parseLegacyString(input) {
4258
+ const result = {};
4259
+ const gpalMatch = input.match(/G(\d+)\s*P(\d+)\s*A(\d+)\s*L(\d+)/i);
4260
+ if (gpalMatch) {
4261
+ const [, g, p, a, l] = gpalMatch;
4262
+ result.gpal = {
4263
+ G: clampInt(Number(g), 0, 20),
4264
+ P: clampInt(Number(p), 0, 20),
4265
+ A: clampInt(Number(a), 0, 20),
4266
+ L: clampInt(Number(l), 0, 20)
4267
+ };
4268
+ }
4269
+ const lmpMatch = input.match(/LMP:\s*([^\n]+)/i);
4270
+ if (lmpMatch?.[1]) result.lmp = lmpMatch[1].trim();
4271
+ const eddUsgMatch = input.match(/EDD\s*\(USG\):\s*([^\n]+)/i);
4272
+ if (eddUsgMatch?.[1]) result.eddUSG = eddUsgMatch[1].trim();
4273
+ const primaryMatch = input.match(/Primary\s*EDD:\s*(lmp|usg)/i);
4274
+ if (primaryMatch?.[1]) result.primaryEDD = primaryMatch[1].toLowerCase();
4275
+ const compMatch = input.match(/Complications:\s*([^\n]+)/i);
4276
+ if (compMatch?.[1]) result.complications = compMatch[1].trim();
4277
+ return result;
4278
+ }
4279
+ function normalizeToDraft(value) {
4280
+ if (!value) return { draft: { ...DEFAULT_DRAFT }, isNewEntry: true };
4281
+ let parsed = value;
4282
+ if (typeof value === "string") {
4283
+ const json = safeJsonParse(value);
4284
+ parsed = json ?? value;
4285
+ }
4286
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed) && "gpal" in parsed && parsed.gpal && typeof parsed.gpal === "object") {
4287
+ const gpal = parsed.gpal ?? {};
4288
+ const edd = parsed.edd ?? null;
4289
+ const eddUSG = (edd && typeof edd === "object" ? edd.usg : void 0) ?? parsed.eddUSG ?? "";
4290
+ const primaryEDD = (edd && typeof edd === "object" ? edd.primary : void 0) ?? parsed.primaryEDD ?? "lmp";
4291
+ const lmp = parsed.lmp ?? "";
4292
+ const complications = parsed.complications ?? "";
4293
+ const outcome = parsed.outcome ?? null;
4294
+ const is_pregnant = !!parsed.is_pregnant;
4295
+ return {
4296
+ isNewEntry: false,
4297
+ draft: {
4298
+ gpal: {
4299
+ G: clampInt(Number(gpal.G ?? 0), 0, 20),
4300
+ P: clampInt(Number(gpal.P ?? 0), 0, 20),
4301
+ A: clampInt(Number(gpal.A ?? 0), 0, 20),
4302
+ L: clampInt(Number(gpal.L ?? 0), 0, 20)
4303
+ },
4304
+ lmp: typeof lmp === "string" ? lmp : "",
4305
+ is_pregnant,
4306
+ eddUSG: typeof eddUSG === "string" ? eddUSG : "",
4307
+ primaryEDD: primaryEDD === "usg" ? "usg" : "lmp",
4308
+ complications: typeof complications === "string" ? complications : "",
4309
+ outcome: outcome && typeof outcome === "object" ? {
4310
+ type: outcome.type ?? "",
4311
+ date: typeof outcome.date === "string" ? outcome.date : "",
4312
+ notes: typeof outcome.notes === "string" ? outcome.notes : "",
4313
+ is_final: !!outcome.is_final
4314
+ } : null
4315
+ }
4316
+ };
4317
+ }
4318
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
4319
+ const gpalFromFlat = {
4320
+ G: clampInt(Number(parsed.G ?? parsed.g ?? 0), 0, 20),
4321
+ P: clampInt(Number(parsed.P ?? parsed.p ?? 0), 0, 20),
4322
+ A: clampInt(Number(parsed.A ?? parsed.a ?? 0), 0, 20),
4323
+ L: clampInt(Number(parsed.L ?? parsed.l ?? 0), 0, 20)
4324
+ };
4325
+ return {
4326
+ isNewEntry: false,
4327
+ draft: {
4328
+ ...DEFAULT_DRAFT,
4329
+ gpal: gpalFromFlat,
4330
+ lmp: typeof parsed.lmp === "string" ? parsed.lmp : "",
4331
+ eddUSG: typeof parsed.eddUSG === "string" ? parsed.eddUSG : "",
4332
+ primaryEDD: parsed.primaryEDD === "usg" ? "usg" : "lmp",
4333
+ complications: typeof parsed.complications === "string" ? parsed.complications : "",
4334
+ outcome: parsed.outcome && typeof parsed.outcome === "object" ? {
4335
+ type: parsed.outcome.type ?? "",
4336
+ date: typeof parsed.outcome.date === "string" ? parsed.outcome.date : "",
4337
+ notes: typeof parsed.outcome.notes === "string" ? parsed.outcome.notes : "",
4338
+ is_final: !!parsed.outcome.is_final
4339
+ } : null,
4340
+ is_pregnant: !!parsed.is_pregnant
4341
+ }
4342
+ };
4343
+ }
4344
+ if (typeof parsed === "string") {
4345
+ const legacy = parseLegacyString(parsed);
4346
+ return { isNewEntry: false, draft: { ...DEFAULT_DRAFT, ...legacy } };
4347
+ }
4348
+ return { draft: { ...DEFAULT_DRAFT }, isNewEntry: true };
4349
+ }
4350
+ function computeEddFromLmp(lmpIso) {
4351
+ if (!isValidIsoDate(lmpIso)) return null;
4352
+ const base = /* @__PURE__ */ new Date(`${lmpIso}T00:00:00.000Z`);
4353
+ base.setUTCDate(base.getUTCDate() + 280);
4354
+ const y = base.getUTCFullYear();
4355
+ const m = pad2(base.getUTCMonth() + 1);
4356
+ const d = pad2(base.getUTCDate());
4357
+ return `${y}-${m}-${d}`;
4358
+ }
4359
+ function diffDaysUtc(fromIso, toIso) {
4360
+ if (!isValidIsoDate(fromIso) || !isValidIsoDate(toIso)) return null;
4361
+ const a = (/* @__PURE__ */ new Date(`${fromIso}T00:00:00.000Z`)).getTime();
4362
+ const b = (/* @__PURE__ */ new Date(`${toIso}T00:00:00.000Z`)).getTime();
4363
+ return Math.floor((b - a) / (1e3 * 60 * 60 * 24));
4364
+ }
4365
+ function computeGestationalAgeFromLmp(lmpIso, today) {
4366
+ const days = diffDaysUtc(lmpIso, today);
4367
+ if (days == null || days < 0) return null;
4368
+ const weeks = Math.floor(days / 7);
4369
+ const rem = days % 7;
4370
+ return { weeks, days: rem, totalDays: days, basedOn: "lmp" };
4371
+ }
4372
+ function computeGestationalAgeFromUsgEdd(eddUsgIso, today) {
4373
+ const daysToEdd = diffDaysUtc(today, eddUsgIso);
4374
+ if (daysToEdd == null) return null;
4375
+ const daysElapsed = 280 - daysToEdd;
4376
+ if (daysElapsed < 0) return null;
4377
+ const weeks = Math.floor(daysElapsed / 7);
4378
+ const rem = daysElapsed % 7;
4379
+ return { weeks, days: rem, totalDays: daysElapsed, basedOn: "usg" };
4380
+ }
4381
+ function computeTrimester(ga) {
4382
+ if (!ga) return null;
4383
+ if (ga.weeks < 13) return 1;
4384
+ if (ga.weeks < 27) return 2;
4385
+ if (ga.weeks < 42) return 3;
4386
+ return null;
4387
+ }
4388
+ function buildStored(draft, today) {
4389
+ const lmpIso = isValidIsoDate(draft.lmp) ? draft.lmp : null;
4390
+ const eddUsgIso = isValidIsoDate(draft.eddUSG) ? draft.eddUSG : null;
4391
+ if (!draft.is_pregnant) {
4392
+ return {
4393
+ gpal: draft.gpal,
4394
+ lmp: lmpIso,
4395
+ is_pregnant: false,
4396
+ edd: null,
4397
+ gestationalAge: null,
4398
+ trimester: null,
4399
+ complications: draft.complications.trim() ? draft.complications : null,
4400
+ outcome: draft.outcome
4401
+ };
4402
+ }
4403
+ const eddFromLmp = lmpIso ? computeEddFromLmp(lmpIso) : null;
4404
+ const gaFromLmp = lmpIso ? computeGestationalAgeFromLmp(lmpIso, today) : null;
4405
+ const gaFromUsg = eddUsgIso ? computeGestationalAgeFromUsgEdd(eddUsgIso, today) : null;
4406
+ const primary = draft.primaryEDD;
4407
+ const gaPrimary = primary === "usg" && gaFromUsg ? gaFromUsg : gaFromLmp ? gaFromLmp : null;
4408
+ return {
4409
+ gpal: draft.gpal,
4410
+ lmp: lmpIso,
4411
+ is_pregnant: true,
4412
+ edd: { lmp: eddFromLmp, usg: eddUsgIso, primary },
4413
+ gestationalAge: gaPrimary,
4414
+ trimester: computeTrimester(gaPrimary),
4415
+ complications: draft.complications.trim() ? draft.complications : null,
4416
+ outcome: draft.outcome
4417
+ };
4418
+ }
4419
+ function stripGpalSuffix(label) {
4420
+ return label.replace(/\s*\(G-P-A-L\)\s*$/i, "").trim();
4421
+ }
4422
+ function useDebouncedCommit(commit, delayMs) {
4423
+ const timeoutRef = useRef(null);
4424
+ const latestCommit = useRef(commit);
4425
+ latestCommit.current = commit;
4426
+ useEffect(() => {
4427
+ return () => {
4428
+ if (timeoutRef.current != null) window.clearTimeout(timeoutRef.current);
4429
+ };
4430
+ }, []);
4431
+ return (next) => {
4432
+ if (timeoutRef.current != null) window.clearTimeout(timeoutRef.current);
4433
+ timeoutRef.current = window.setTimeout(() => latestCommit.current(next), delayMs);
4434
+ };
4435
+ }
4436
+ var ObstetricHistoryWidget = ({ fieldId }) => {
4437
+ const { fieldDef, value, setValue, disabled } = useField(fieldId);
4438
+ const [{ draft, isNewEntry }, setDraftState] = useState(() => normalizeToDraft(value));
4439
+ const [lmpError, setLmpError] = useState(null);
4440
+ const [primaryEddError, setPrimaryEddError] = useState(null);
4441
+ const [activeGpalKey, setActiveGpalKey] = useState(null);
4442
+ const refs = {
4443
+ G: useRef(null),
4444
+ P: useRef(null),
4445
+ A: useRef(null),
4446
+ L: useRef(null)
4447
+ };
4448
+ const today = useMemo(() => todayIso(), []);
4449
+ useEffect(() => {
4450
+ const next = normalizeToDraft(value);
4451
+ const currStr = JSON.stringify(buildStored(draft, today));
4452
+ const nextStr = JSON.stringify(buildStored(next.draft, today));
4453
+ if (currStr !== nextStr) setDraftState(next);
4454
+ }, [value]);
4455
+ const commitImmediate = (nextDraft) => {
4456
+ const stored = buildStored(nextDraft, today);
4457
+ setValue(JSON.stringify(stored));
4458
+ };
4459
+ const commitDebounced = useDebouncedCommit(commitImmediate, 500);
4460
+ const storedComputed = useMemo(() => buildStored(draft, today), [draft, today]);
4461
+ const rightPanelEnabled = draft.is_pregnant && (!!storedComputed.lmp || !!storedComputed.edd?.usg);
4462
+ const headerLabel = fieldDef?.label ? stripGpalSuffix(fieldDef.label) : "Obstetric History";
4463
+ const setDraft = (updater, persist) => {
4464
+ setDraftState((prev) => {
4465
+ const nextDraft = updater(prev.draft);
4466
+ const nextState = { ...prev, draft: nextDraft };
4467
+ if (persist === "immediate") commitImmediate(nextDraft);
4468
+ else commitDebounced(nextDraft);
4469
+ return nextState;
4470
+ });
4471
+ };
4472
+ const sanitizeGpalInput = (raw) => {
4473
+ const digits = raw.replace(/[^\d]/g, "").slice(0, 2);
4474
+ if (!digits) return 0;
4475
+ return clampInt(Number(digits), 0, 20);
4476
+ };
4477
+ const handleGpalChange = (key, raw) => {
4478
+ const prevWasEmpty = draft.gpal[key] === 0 && activeGpalKey === key;
4479
+ const val = sanitizeGpalInput(raw);
4480
+ setDraft((prev) => ({ ...prev, gpal: { ...prev.gpal, [key]: val } }), "debounce");
4481
+ const digitsOnly = raw.replace(/[^\d]/g, "");
4482
+ const shouldAutoTab = digitsOnly.length === 1 && (prevWasEmpty || String(draft.gpal[key]).length >= 1);
4483
+ if (shouldAutoTab) {
4484
+ const order = ["G", "P", "A", "L"];
4485
+ const idx = order.indexOf(key);
4486
+ const nextKey = order[idx + 1];
4487
+ if (nextKey) refs[nextKey].current?.focus();
4488
+ }
4489
+ };
4490
+ const handleLmpChange = (nextIso) => {
4491
+ setPrimaryEddError(null);
4492
+ if (nextIso && nextIso > today) {
4493
+ setLmpError("LMP cannot be in the future");
4494
+ return;
4495
+ }
4496
+ setLmpError(null);
4497
+ setDraft((prev) => ({ ...prev, lmp: nextIso }), "debounce");
4498
+ };
4499
+ const handlePregStatus = (isPregnant) => {
4500
+ setLmpError(null);
4501
+ setPrimaryEddError(null);
4502
+ setDraft((prev) => ({ ...prev, is_pregnant: isPregnant }), "immediate");
4503
+ };
4504
+ const handleEddUsgChange = (nextIso) => {
4505
+ setPrimaryEddError(null);
4506
+ setDraft((prev) => ({ ...prev, eddUSG: nextIso }), "debounce");
4507
+ };
4508
+ const handlePrimaryEdd = (next) => {
4509
+ if (next === "usg" && !isValidIsoDate(draft.eddUSG)) {
4510
+ setPrimaryEddError("Please enter EDD from USG first");
4511
+ return;
4512
+ }
4513
+ setPrimaryEddError(null);
4514
+ setDraft((prev) => ({ ...prev, primaryEDD: next }), "immediate");
4515
+ };
4516
+ const ensureOutcome = () => {
4517
+ if (draft.outcome) return;
4518
+ setDraft(
4519
+ (prev) => ({
4520
+ ...prev,
4521
+ outcome: { type: "", date: "", notes: "", is_final: false }
4522
+ }),
4523
+ "immediate"
4524
+ );
4525
+ };
4526
+ const clearOutcome = () => {
4527
+ setDraft((prev) => ({ ...prev, outcome: null }), "immediate");
4528
+ };
4529
+ const updateOutcomeImmediate = (updater) => {
4530
+ setDraft(
4531
+ (prev) => {
4532
+ const o = prev.outcome ?? { type: "", date: "", notes: "", is_final: false };
4533
+ return { ...prev, outcome: updater(o) };
4534
+ },
4535
+ "immediate"
4536
+ );
4537
+ };
4538
+ const updateOutcomeNotesDebounced = (notes) => {
4539
+ setDraft(
4540
+ (prev) => {
4541
+ const o = prev.outcome ?? { type: "", date: "", notes: "", is_final: false };
4542
+ return { ...prev, outcome: { ...o, notes } };
4543
+ },
4544
+ "debounce"
4545
+ );
4546
+ };
4547
+ return /* @__PURE__ */ jsxs(Card, { className: cn("w-full", disabled && "opacity-70 pointer-events-none"), children: [
4548
+ /* @__PURE__ */ jsx(CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsx(CardTitle, { className: "text-base font-semibold", children: headerLabel }) }),
4549
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-4", children: [
4550
+ isNewEntry && /* @__PURE__ */ jsx("div", { className: "rounded-md border border-blue-200 bg-blue-50 px-3 py-2 text-xs text-blue-900", children: "No previous maternity episode found. Please fill obstetric details to start tracking." }),
4551
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-4 items-start", children: [
4552
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4553
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-white p-4", children: [
4554
+ /* @__PURE__ */ jsx("div", { className: "text-xs font-medium text-muted-foreground mb-2", children: "G-P-A-L" }),
4555
+ /* @__PURE__ */ jsx("div", { className: "grid grid-cols-4 gap-3", children: ["G", "P", "A", "L"].map((k) => /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
4556
+ /* @__PURE__ */ jsx(Label, { htmlFor: `${fieldId}-gpal-${k}`, className: "text-[11px] text-muted-foreground", children: k }),
4557
+ /* @__PURE__ */ jsx(
4558
+ Input,
4559
+ {
4560
+ ref: refs[k],
4561
+ id: `${fieldId}-gpal-${k}`,
4562
+ inputMode: "numeric",
4563
+ pattern: "\\d*",
4564
+ maxLength: 2,
4565
+ value: String(draft.gpal[k] ?? 0),
4566
+ onFocus: () => {
4567
+ setActiveGpalKey(k);
4568
+ const el = refs[k].current;
4569
+ if (el) el.select();
4570
+ },
4571
+ onChange: (e) => handleGpalChange(k, e.target.value),
4572
+ onKeyDown: (e) => {
4573
+ const allowed = ["Backspace", "Delete", "ArrowLeft", "ArrowRight", "Tab", "Home", "End"];
4574
+ if (allowed.includes(e.key)) return;
4575
+ if (/^\d$/.test(e.key)) return;
4576
+ e.preventDefault();
4577
+ },
4578
+ className: "text-center text-base"
4579
+ }
4580
+ )
4581
+ ] }, k)) })
4582
+ ] }),
4583
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 md:grid-cols-2 gap-3", children: [
4584
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-lg border bg-white p-4", children: [
4585
+ /* @__PURE__ */ jsx(Label, { htmlFor: `${fieldId}-lmp`, className: cn("text-sm", lmpError && "text-red-600"), children: "Last Menstrual Period (LMP)" }),
4586
+ /* @__PURE__ */ jsx(
4587
+ Input,
4588
+ {
4589
+ id: `${fieldId}-lmp`,
4590
+ type: "date",
4591
+ max: today,
4592
+ value: draft.lmp,
4593
+ onChange: (e) => handleLmpChange(e.target.value),
4594
+ className: cn(lmpError && "border-red-500")
4595
+ }
4596
+ ),
4597
+ lmpError && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: lmpError })
4598
+ ] }),
4599
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-lg border bg-white p-4", children: [
4600
+ /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: "Pregnancy Status" }),
4601
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
4602
+ /* @__PURE__ */ jsx(
4603
+ "button",
4604
+ {
4605
+ type: "button",
4606
+ onClick: () => handlePregStatus(false),
4607
+ className: cn(
4608
+ "flex-1 rounded-md border px-3 py-2 text-xs",
4609
+ !draft.is_pregnant ? "bg-green-600 text-white border-green-600" : "bg-white"
4610
+ ),
4611
+ children: "Not Pregnant"
4612
+ }
4613
+ ),
4614
+ /* @__PURE__ */ jsx(
4615
+ "button",
4616
+ {
4617
+ type: "button",
4618
+ onClick: () => handlePregStatus(true),
4619
+ className: cn(
4620
+ "flex-1 rounded-md border px-3 py-2 text-xs",
4621
+ draft.is_pregnant ? "bg-green-600 text-white border-green-600" : "bg-white"
4622
+ ),
4623
+ children: "Pregnant"
4624
+ }
4625
+ )
4626
+ ] })
4627
+ ] })
4628
+ ] }),
4629
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-lg border bg-white p-4", children: [
4630
+ /* @__PURE__ */ jsx(Label, { htmlFor: `${fieldId}-complications`, className: "text-sm", children: "Previous Pregnancy Complications" }),
4631
+ /* @__PURE__ */ jsx(
4632
+ Textarea,
4633
+ {
4634
+ id: `${fieldId}-complications`,
4635
+ placeholder: "e.g. Pre-eclampsia, Gestational diabetes, C-section, etc.",
4636
+ value: draft.complications,
4637
+ onChange: (e) => setDraft((prev) => ({ ...prev, complications: e.target.value }), "debounce"),
4638
+ className: "min-h-[140px]"
4639
+ }
4640
+ )
4641
+ ] })
4642
+ ] }),
4643
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-white p-4 min-h-[260px]", children: [
4644
+ !draft.is_pregnant && /* @__PURE__ */ jsx("div", { className: "h-full flex items-center justify-center text-center text-sm text-muted-foreground px-6 py-10", children: 'Only for "Pregnant Women" and enter LMP to calculate gestational age and EDD' }),
4645
+ draft.is_pregnant && !rightPanelEnabled && /* @__PURE__ */ jsx("div", { className: "h-full flex items-center justify-center text-center text-sm text-muted-foreground px-6 py-10", children: "Enter LMP and/or EDD (USG) to enable gestational age and EDD calculations." }),
4646
+ draft.is_pregnant && rightPanelEnabled && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4647
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border p-4", children: [
4648
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
4649
+ /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-blue-700", children: "Expected Delivery Date (EDD)" }),
4650
+ storedComputed.gestationalAge?.basedOn && /* @__PURE__ */ jsxs("span", { className: "rounded-full bg-blue-100 px-2 py-1 text-[11px] text-blue-700", children: [
4651
+ "Based on ",
4652
+ storedComputed.gestationalAge.basedOn.toUpperCase()
4653
+ ] })
4654
+ ] }),
4655
+ /* @__PURE__ */ jsxs("div", { className: "mt-3", children: [
4656
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "Gestational Age:" }),
4657
+ /* @__PURE__ */ jsx("div", { className: "text-lg font-semibold", children: storedComputed.gestationalAge ? `${storedComputed.gestationalAge.weeks} weeks ${storedComputed.gestationalAge.days} days` : "\u2014" }),
4658
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground mt-1", children: storedComputed.trimester ? `Trimester ${storedComputed.trimester}` : "Trimester \u2014" })
4659
+ ] })
4660
+ ] }),
4661
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4662
+ /* @__PURE__ */ jsx("div", { className: "text-xs text-muted-foreground", children: "EDD (from LMP):" }),
4663
+ /* @__PURE__ */ jsx("div", { className: "rounded-md border bg-muted/20 px-3 py-2 text-sm font-semibold", children: storedComputed.edd?.lmp ? formatDdMmYyyy(storedComputed.edd.lmp) : "\u2014" })
4664
+ ] }),
4665
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4666
+ /* @__PURE__ */ jsx(Label, { htmlFor: `${fieldId}-edd-usg`, className: "text-sm", children: "EDD (from USG):" }),
4667
+ /* @__PURE__ */ jsx(
4668
+ Input,
4669
+ {
4670
+ id: `${fieldId}-edd-usg`,
4671
+ type: "date",
4672
+ value: draft.eddUSG,
4673
+ onChange: (e) => handleEddUsgChange(e.target.value)
4674
+ }
4675
+ )
4676
+ ] }),
4677
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4678
+ /* @__PURE__ */ jsx("div", { className: "text-sm font-medium", children: "Primary EDD:" }),
4679
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
4680
+ /* @__PURE__ */ jsx(
4681
+ "button",
4682
+ {
4683
+ type: "button",
4684
+ onClick: () => handlePrimaryEdd("lmp"),
4685
+ className: cn(
4686
+ "flex-1 rounded-md border px-3 py-2 text-sm",
4687
+ draft.primaryEDD === "lmp" ? "bg-blue-600 text-white border-blue-600" : "bg-white"
4688
+ ),
4689
+ children: "LMP"
4690
+ }
4691
+ ),
4692
+ /* @__PURE__ */ jsx(
4693
+ "button",
4694
+ {
4695
+ type: "button",
4696
+ onClick: () => handlePrimaryEdd("usg"),
4697
+ className: cn(
4698
+ "flex-1 rounded-md border px-3 py-2 text-sm",
4699
+ draft.primaryEDD === "usg" ? "bg-blue-600 text-white border-blue-600" : "bg-white"
4700
+ ),
4701
+ children: "USG"
4702
+ }
4703
+ )
4704
+ ] }),
4705
+ primaryEddError && /* @__PURE__ */ jsx("p", { className: "text-xs text-red-600", children: primaryEddError })
4706
+ ] })
4707
+ ] })
4708
+ ] })
4709
+ ] }),
4710
+ /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-yellow-50/60 p-4", children: [
4711
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
4712
+ /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold", children: "Pregnancy Outcome (Optional - To Close Episode)" }),
4713
+ draft.outcome && /* @__PURE__ */ jsx("button", { type: "button", className: "text-sm text-red-600 hover:underline", onClick: clearOutcome, children: "Clear" })
4714
+ ] }),
4715
+ !draft.outcome && /* @__PURE__ */ jsx(
4716
+ "button",
4717
+ {
4718
+ type: "button",
4719
+ onClick: ensureOutcome,
4720
+ className: "mt-3 w-full rounded-md border border-yellow-300 bg-yellow-100 px-3 py-2 text-sm font-medium",
4721
+ children: "+ Add Pregnancy Outcome"
4722
+ }
4723
+ ),
4724
+ draft.outcome && /* @__PURE__ */ jsxs("div", { className: "mt-4 space-y-3", children: [
4725
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4726
+ /* @__PURE__ */ jsxs(Label, { className: "text-sm", children: [
4727
+ "Outcome Type ",
4728
+ /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
4729
+ ] }),
4730
+ /* @__PURE__ */ jsxs(
4731
+ "select",
4732
+ {
4733
+ className: "w-full rounded-md border px-3 py-2 text-sm bg-white",
4734
+ value: draft.outcome.type,
4735
+ onChange: (e) => updateOutcomeImmediate((o) => ({ ...o, type: e.target.value })),
4736
+ children: [
4737
+ /* @__PURE__ */ jsx("option", { value: "", children: "Select outcome..." }),
4738
+ /* @__PURE__ */ jsx("option", { value: "delivery", children: "Normal Delivery" }),
4739
+ /* @__PURE__ */ jsx("option", { value: "cesarean", children: "Cesarean Section" }),
4740
+ /* @__PURE__ */ jsx("option", { value: "abortion", children: "Abortion" }),
4741
+ /* @__PURE__ */ jsx("option", { value: "miscarriage", children: "Miscarriage" }),
4742
+ /* @__PURE__ */ jsx("option", { value: "stillbirth", children: "Stillbirth" })
4743
+ ]
4744
+ }
4745
+ )
4746
+ ] }),
4747
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4748
+ /* @__PURE__ */ jsxs(Label, { htmlFor: `${fieldId}-outcome-date`, className: "text-sm", children: [
4749
+ "Date ",
4750
+ /* @__PURE__ */ jsx("span", { className: "text-red-500", children: "*" })
4751
+ ] }),
4752
+ /* @__PURE__ */ jsx(
4753
+ Input,
4754
+ {
4755
+ id: `${fieldId}-outcome-date`,
4756
+ type: "date",
4757
+ max: today,
4758
+ value: draft.outcome.date,
4759
+ onChange: (e) => updateOutcomeImmediate((o) => ({ ...o, date: e.target.value }))
4760
+ }
4761
+ ),
4762
+ draft.outcome.date && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
4763
+ "Selected: ",
4764
+ formatDdMmYyyy(draft.outcome.date)
4765
+ ] })
4766
+ ] }),
4767
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
4768
+ /* @__PURE__ */ jsx(Label, { htmlFor: `${fieldId}-outcome-notes`, className: "text-sm", children: "Notes" }),
4769
+ /* @__PURE__ */ jsx(
4770
+ Textarea,
4771
+ {
4772
+ id: `${fieldId}-outcome-notes`,
4773
+ placeholder: "e.g. Normal vaginal delivery, healthy baby boy, 3.2kg",
4774
+ value: draft.outcome.notes,
4775
+ onChange: (e) => updateOutcomeNotesDebounced(e.target.value),
4776
+ className: "min-h-[90px]"
4777
+ }
4778
+ )
4779
+ ] }),
4780
+ /* @__PURE__ */ jsxs("div", { className: "rounded-md border bg-white p-3", children: [
4781
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
4782
+ /* @__PURE__ */ jsx(
4783
+ "input",
4784
+ {
4785
+ type: "checkbox",
4786
+ checked: !!draft.outcome.is_final,
4787
+ onChange: (e) => updateOutcomeImmediate((o) => ({ ...o, is_final: e.target.checked }))
4788
+ }
4789
+ ),
4790
+ "Close this pregnancy episode"
4791
+ ] }),
4792
+ draft.outcome.is_final && /* @__PURE__ */ jsx("div", { className: "mt-3 rounded-md border border-red-300 bg-red-50 px-3 py-2 text-xs text-red-800", children: "Checking this will mark the pregnancy as completed and is intended to close the maternity episode." })
4793
+ ] })
4794
+ ] })
4795
+ ] })
4796
+ ] })
4797
+ ] });
4798
+ };
3995
4799
  var FieldRenderer = ({ fieldId }) => {
3996
4800
  const { fieldDef, visible } = useField(fieldId);
3997
4801
  if (!visible || !fieldDef) {
@@ -4038,6 +4842,10 @@ var FieldRenderer = ({ fieldId }) => {
4038
4842
  return /* @__PURE__ */ jsx(ReferralWidget, { fieldId });
4039
4843
  case "followup":
4040
4844
  return /* @__PURE__ */ jsx(FollowupWidget, { fieldId });
4845
+ case "smart_textarea":
4846
+ return /* @__PURE__ */ jsx(SmartTextareaWidget, { fieldId });
4847
+ case "obstetric_history":
4848
+ return /* @__PURE__ */ jsx(ObstetricHistoryWidget, { fieldId });
4041
4849
  case "static_text": {
4042
4850
  const def = fieldDef;
4043
4851
  const size = def.size ?? "regular";
@@ -4786,6 +5594,6 @@ function createUploadHandler(options) {
4786
5594
  };
4787
5595
  }
4788
5596
 
4789
- export { AddInvestigationField, AddMedicationField, DifferentialDiagnosis, DynamicForm, EMAIL_REGEX, FieldRenderer, FormControls, FormProvider, FormStore, ImageUploadWidget, ReadOnlyForm, ReadOnlyImageUpload, ReadOnlySignature, ReadOnlyTable, SignatureUploadWidget, SmartForm, createUploadHandler, evaluateRules, useField, useFieldHandlers, useForm, useFormStore, validateField, validateForm };
5597
+ export { AddInvestigationField, AddMedicationField, DifferentialDiagnosis, DynamicForm, EMAIL_REGEX, FieldRenderer, FormControls, FormProvider, FormStore, ImageUploadWidget, ReadOnlyForm, ReadOnlyImageUpload, ReadOnlySignature, ReadOnlyTable, SignatureUploadWidget, SmartForm, SmartTextareaWidget, createUploadHandler, evaluateRules, useField, useFieldHandlers, useForm, useFormStore, useSmartKeywords, validateField, validateForm };
4790
5598
  //# sourceMappingURL=index.mjs.map
4791
5599
  //# sourceMappingURL=index.mjs.map