@wix/himalaya-cli 0.1649.0 → 0.1650.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$source": "en",
3
- "$generated": "2026-11-10T16:25:29.005Z",
3
+ "$generated": "2026-11-11T03:01:14.140Z",
4
4
  "messages": {
5
5
  "h_042c862e4467": {
6
6
  "source": "Try again",
@@ -52,7 +52,7 @@
52
52
  "himi_videos#payload.body.props.children[7].body.props.children[8].body.props.children[2].body.props.title",
53
53
  "himi_video#payload.body.props.children[7].body.props.title",
54
54
  "himi_podcasts#payload.body.props.children[2].body.props.children[8].body.props.children[2].body.props.title",
55
- "himi_forms#payload.body.props.children[5].body.props.ctaLabel",
55
+ "himi_forms#payload.body.props.children[4].body.props.ctaLabel",
56
56
  "himi_form#payload.body.props.children[6].body.props.ctaLabel",
57
57
  "himi_galleries#payload.body.props.children[4].body.props.children[8].body.props.children[2].body.props.title",
58
58
  "himi_business_chat#payload.body.props.children[1].body.props.children[3].body.props.title",
@@ -430,7 +430,7 @@
430
430
  "himi_video_channel#payload.body.props.children[8].body.props.title",
431
431
  "himi_video#payload.body.props.children[13].body.props.title",
432
432
  "himi_podcasts#payload.body.props.children[2].body.props.children[8].body.props.children[3].body.props.title",
433
- "himi_forms#payload.body.props.children[7].body.props.ctaLabel",
433
+ "himi_forms#payload.body.props.children[6].body.props.ctaLabel",
434
434
  "himi_galleries#payload.body.props.children[4].body.props.children[8].body.props.children[3].body.props.title",
435
435
  "himi_business_chat#payload.body.props.children[1].body.props.children[2].body.props.title",
436
436
  "himi_inbox#payload.body.props.children[7].body.props.children[2].body.props.title",
@@ -13,6 +13,7 @@
13
13
  // image choice, rating, time) or any conditional rule makes the whole form "unsupported":
14
14
  // a hidden required field would fail the whole send, so the screen offers the website instead.
15
15
  import { ricosToPlainText } from "@himalaya/wix-rich-content";
16
+ import { validate } from "@himalaya/core/validation";
16
17
 
17
18
  export type FieldKind = "text" | "area" | "email" | "phone" | "number" | "url" | "date" | "checkbox" | "choice" | "multi" | "display";
18
19
 
@@ -238,7 +239,17 @@ function isEmpty(f: FormFieldModel, v: FieldValue): boolean {
238
239
  return v.text.trim() === "";
239
240
  }
240
241
 
241
- export type FieldProblem = "required" | "email" | "number" | "url";
242
+ export type FieldProblem = "required" | "email" | "number" | "url" | "phone";
243
+
244
+ /** An email's loose shape: one @ and a dot after it (see localProblems). */
245
+ const LOOSE_EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
246
+ /** A link's loose shape: an optional http(s) scheme, then a name with a dot in it. */
247
+ const LOOSE_URL = /^(https?:\/\/)?[^\s.]+\.[^\s]+$/i;
248
+ /** The platform's own semantic type for a field kind: the same rule a `TextField` with
249
+ * `validation: { type }` applies on iOS, Android and web. */
250
+ const SEMANTIC_TYPE: Partial<Record<FieldKind, "email" | "phone" | "url" | "number">> = {
251
+ email: "email", phone: "phone", url: "url", number: "number",
252
+ };
242
253
 
243
254
  /** The checks the app can make before Wix sees the values. Wix's own validation (format,
244
255
  * length, allowed values) runs on the server; v4 can also check without submitting. */
@@ -249,9 +260,16 @@ export function localProblems(fields: FormFieldModel[], values: Record<string, F
249
260
  const v = values[f.target] ?? EMPTY_VALUE;
250
261
  if (isEmpty(f, v)) { if (f.required) out[f.target] = "required"; continue; }
251
262
  const t = v.text.trim();
252
- if (f.kind === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) out[f.target] = "email";
253
- else if (f.kind === "number" && !Number.isFinite(toNumber(t))) out[f.target] = "number";
254
- else if (f.kind === "url" && !/^(https?:\/\/)?[^\s.]+\.[^\s]+$/i.test(t)) out[f.target] = "url";
263
+ const type = SEMANTIC_TYPE[f.kind];
264
+ if (!type) continue;
265
+ // An email and a link get only a loose shape check: the shared rules are ASCII only and
266
+ // would block valid addresses (münchen.de); Wix's own check still runs on send.
267
+ if (type === "email") { if (!LOOSE_EMAIL.test(t)) out[f.target] = type; continue; }
268
+ if (type === "url") { if (!LOOSE_URL.test(t)) out[f.target] = type; continue; }
269
+ // A decimal comma is a decimal point; the text itself is checked otherwise, so a very small
270
+ // or very large number is not turned into exponent notation the rule refuses.
271
+ const checked = type === "number" && /^[+-]?\d*,\d+$/.test(t) ? t.replace(",", ".") : t;
272
+ if (validate({ type }, checked)) out[f.target] = type;
255
273
  }
256
274
  return out;
257
275
  }
@@ -12,14 +12,16 @@
12
12
  // opens the website instead (a hidden required field would fail the whole send). A form
13
13
  // whose deadline passed shows a closed notice. Replaces wix-spaces-form-detail for this
14
14
  // app only: the Spaces clone fixture still uses that worker.
15
- import { classifyLoadError, defineService } from "@himalaya/state";
15
+ import { classifyLoadError, defineService, navigate } from "@himalaya/state";
16
+ import { alert } from "@himalaya/ui";
17
+ import { dispatch } from "@himalaya/dispatch";
18
+ import { get as dbGet, remove as dbRemove, upsert as dbUpsert } from "@himalaya/local-db";
16
19
  import { open as openUrl } from "@himalaya/open-url";
17
20
  import { createSubmission, getForm, getLegacyFormByShortId, submitLegacyForm, validateFormSubmission } from "@himalaya/wix-forms";
18
21
  import { getMyMember } from "@himalaya/wix-members";
19
22
  import { copyParam, copyTemplate, stashCopy } from "../_shared/himi-copy.js";
20
23
  import { detailInputId, presence, presenceAfterError, type PresenceFlags } from "../_shared/detail-presence.js";
21
24
  import { memberAccess } from "../_shared/member-access.js";
22
- import { formatDateMedium } from "../_shared/engine-intl.js";
23
25
  import {
24
26
  EMPTY_VALUE, isoDate, localProblems, parseForm, parseLegacyForm, serverProblems, submissionValues,
25
27
  type FieldValue, type FormFieldModel, type FormModel,
@@ -30,10 +32,13 @@ interface FieldRow {
30
32
  id: string; target: string;
31
33
  label: string; hideLabel: boolean; help: string; hideHelp: boolean; placeholder: string;
32
34
  checkLabel: string; displayText: string;
33
- value: string; dateText: string; hideDateValue: boolean; hideDatePlaceholder: boolean; checked: boolean;
35
+ value: string; checked: boolean;
36
+ /** The stored date as unix seconds (local noon), or "" — the inline date picker's literal
37
+ * `valuePath` seed. Unix, not `YYYY-MM-DD`: no renderer parses a bare date. */
38
+ dateUnix: string;
39
+ /** The field's error, drawn on the line under it (every kind: a TextField's `errorPath` takes
40
+ * only a `$service:` binding, so a row's error cannot use the field's own slot). */
34
41
  error: string; noError: boolean;
35
- /** The error line under a control with no error slot of its own (date, choice, checkbox). */
36
- noErrorLine: boolean;
37
42
  options: OptionRow[];
38
43
  // hiddenWhen hides on TRUE: one "not" flag per field kind.
39
44
  notText: boolean; notArea: boolean; notEmail: boolean; notPhone: boolean; notNumber: boolean; notUrl: boolean;
@@ -45,7 +50,12 @@ interface S extends PresenceFlags {
45
50
  title: string;
46
51
  rows: FieldRow[];
47
52
  pageCaption: string; noPageCaption: boolean;
48
- primaryLabel: string; backLabel: string; hideSingle: boolean; hidePair: boolean;
53
+ primaryLabel: string; backLabel: string;
54
+ /** The footer variant (hiddenWhen hides on TRUE): a one-page form; the first, a middle and
55
+ * the last page of a form with several. */
56
+ hideFooterSingle: boolean; hideFooterFirst: boolean; hideFooterMiddle: boolean; hideFooterLast: boolean;
57
+ /** "Clear form" shows once the visitor has entered an answer. */
58
+ hideClear: boolean;
49
59
  sending: boolean;
50
60
  sendError: string; noSendError: boolean;
51
61
  /** The fields and the footer: hidden unless the form is there, fillable, open and not sent. */
@@ -55,16 +65,14 @@ interface S extends PresenceFlags {
55
65
  hideOpenWebsite: boolean;
56
66
  hideDone: boolean; doneTitle: string; doneBody: string;
57
67
  hideOfflineError: boolean; hideServerError: boolean;
58
- dateSheetOpen: boolean; dateSheetTitle: string;
59
- /** The sheet's date (unix seconds) — the picker shows it and Done writes it. */
60
- dateDraft: number;
61
68
  }
62
69
 
63
70
  const BASE: S = {
64
71
  status: "loading", title: "", rows: [], pageCaption: "", noPageCaption: true,
65
- primaryLabel: "", backLabel: "", hideSingle: true, hidePair: true, sending: false, sendError: "", noSendError: true,
72
+ primaryLabel: "", backLabel: "", hideFooterSingle: true, hideFooterFirst: true, hideFooterMiddle: true, hideFooterLast: true,
73
+ hideClear: true, sending: false, sendError: "", noSendError: true,
66
74
  hideForm: true, hideUnsupported: true, hideClosed: true, hideOpenWebsite: true, hideDone: true, doneTitle: "", doneBody: "",
67
- hideOfflineError: true, hideServerError: true, dateSheetOpen: false, dateSheetTitle: "", dateDraft: 0,
75
+ hideOfflineError: true, hideServerError: true,
68
76
  ...presence("loading"),
69
77
  };
70
78
 
@@ -77,11 +85,6 @@ let values: Record<string, FieldValue> = {};
77
85
  let page = 0;
78
86
  let problems: Record<string, string> = {};
79
87
  let siteUrl = "";
80
- let dateTarget = "";
81
- let dateDraft = 0;
82
- /** Done writes only a date the visitor picked: Android's standalone DatePicker does not read
83
- * `valuePath` and opens blank, so an untouched Done must not write a date nobody saw. */
84
- let datePicked = false;
85
88
 
86
89
  const valueOf = (target: string): FieldValue => values[target] ?? EMPTY_VALUE;
87
90
  const pageFields = (): FormFieldModel[] => (form?.pages[page] ?? []).map((id) => form!.fields[id]).filter(Boolean);
@@ -97,6 +100,7 @@ function problemText(f: FormFieldModel, type: string): string {
97
100
  case "email": return copyParam("form.errorEmail", "Enter a valid email.");
98
101
  case "number": return copyParam("form.errorNumber", "Enter a number.");
99
102
  case "url": return copyParam("form.errorUrl", "Enter a valid link.");
103
+ case "phone": return copyParam("form.errorPhone", "Enter a valid phone number.");
100
104
  case "REQUIRED_VALUE_ERROR": return problemText(f, "required");
101
105
  case "FORMAT_ERROR":
102
106
  return f.kind === "email" ? problemText(f, "email") : f.kind === "phone" ? copyParam("form.errorPhone", "Enter a valid phone number.")
@@ -105,11 +109,6 @@ function problemText(f: FormFieldModel, type: string): string {
105
109
  }
106
110
  }
107
111
 
108
- function dateDisplay(iso: string): string {
109
- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
110
- return m ? formatDateMedium(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))) : iso;
111
- }
112
-
113
112
  function row(f: FormFieldModel): FieldRow {
114
113
  const v = valueOf(f.target);
115
114
  const error = problems[f.target] ? problemText(f, problems[f.target]) : "";
@@ -117,15 +116,17 @@ function row(f: FormFieldModel): FieldRow {
117
116
  // A checkbox's label sits beside its box, and a text block is its own text: neither has
118
117
  // a label line above it.
119
118
  const label = f.kind === "checkbox" || f.kind === "display" ? "" : marked;
119
+ // After "Clear form" the rows take new ids: a native field keeps what was typed when only its
120
+ // literal value changes, so an emptied row must mount as a new field to show empty.
121
+ const id = generation ? `${f.id}_r${generation}` : f.id;
120
122
  return {
121
- id: f.id, target: f.target,
123
+ id, target: f.target,
122
124
  label, hideLabel: !label, help: f.help, hideHelp: !f.help,
123
125
  checkLabel: f.kind === "checkbox" ? marked : "", displayText: f.kind === "display" ? f.label : "",
124
- placeholder: f.kind === "date" ? (f.placeholder || copyParam("form.datePlaceholder", "Choose a date")) : f.placeholder,
125
- value: v.text, dateText: dateDisplay(v.text), hideDateValue: !v.text, hideDatePlaceholder: !!v.text, checked: v.checked,
126
+ placeholder: f.placeholder,
127
+ value: v.text, checked: v.checked, dateUnix: f.kind === "date" ? unixOfIsoDate(v.text) : "",
126
128
  error, noError: !error,
127
- noErrorLine: !error || !(f.kind === "date" || f.kind === "checkbox" || f.kind === "choice" || f.kind === "multi"),
128
- options: f.options.map((o, i) => ({ id: `${f.id}_${i}`, target: f.target, value: o.value, label: o.label, selected: v.selected.includes(o.value) })),
129
+ options: f.options.map((o, i) => ({ id: `${id}_${i}`, target: f.target, value: o.value, label: o.label, selected: v.selected.includes(o.value) })),
129
130
  notText: f.kind !== "text", notArea: f.kind !== "area", notEmail: f.kind !== "email", notPhone: f.kind !== "phone",
130
131
  notNumber: f.kind !== "number", notUrl: f.kind !== "url", notDate: f.kind !== "date", notCheck: f.kind !== "checkbox",
131
132
  notChoice: f.kind !== "choice", notMulti: f.kind !== "multi", notDisplay: f.kind !== "display",
@@ -146,8 +147,11 @@ function view(s: S, patch: Partial<S> = {}): S {
146
147
  noPageCaption: !fillable || pages < 2,
147
148
  primaryLabel: lastPage() ? (form.submitText || copyParam("form.submitCta", "Submit")) : (form.nextText || copyParam("form.nextCta", "Next")),
148
149
  backLabel: form.backText || copyParam("form.previousCta", "Back"),
149
- hideSingle: !fillable || page > 0,
150
- hidePair: !fillable || page === 0,
150
+ hideFooterSingle: !fillable || pages > 1,
151
+ hideFooterFirst: !fillable || pages < 2 || page !== 0,
152
+ hideFooterMiddle: !fillable || pages < 2 || page === 0 || lastPage(),
153
+ hideFooterLast: !fillable || pages < 2 || !lastPage(),
154
+ hideClear: !fillable || !hasAnswers(),
151
155
  hideForm: !fillable,
152
156
  hideUnsupported: !form.unsupported,
153
157
  hideOpenWebsite: !siteUrl,
@@ -178,13 +182,87 @@ async function memberDetails(): Promise<Record<string, string | undefined>> {
178
182
  function prefill(byField: Record<string, string | undefined>): void {
179
183
  for (const f of allFields()) {
180
184
  const known = byField[f.contactField]?.trim();
181
- if (!known || valueOf(f.target).text) continue;
185
+ // A field in the draft keeps the visitor's own answer, an emptied one included.
186
+ if (!known || f.target in values) continue;
182
187
  values[f.target] = { ...valueOf(f.target), text: known };
183
188
  }
184
189
  }
185
190
 
186
191
  function setValue(target: string, next: Partial<FieldValue>): void {
187
192
  values[target] = { ...valueOf(target), ...next };
193
+ touched = true;
194
+ saveDraft();
195
+ }
196
+
197
+ /** How many times "Clear form" ran on this form (row ids carry it, see row()). */
198
+ let generation = 0;
199
+
200
+ /** The visitor has started filling this form (a change, or a draft from an earlier visit):
201
+ * member details prefilled on open do not count. */
202
+ let touched = false;
203
+
204
+ /** Has the visitor entered an answer that "Clear form" would remove? */
205
+ function hasAnswers(): boolean {
206
+ return touched && Object.values(values).some((v) => v.text.trim() !== "" || v.checked || v.selected.length > 0);
207
+ }
208
+
209
+ // ---- Drafts ---------------------------------------------------------------------------------
210
+ // What the user typed survives leaving the form: every change rewrites this form's draft (the
211
+ // latest answers, a cleared field included), it is read back when the form opens again, and a sent
212
+ // or cleared form removes it. One draft per form id, so forms never share answers.
213
+ // Where it is kept depends on who is filling it in. A signed-in member's goes to the device
214
+ // database, whose partition is that member's own, in an entity encrypted at rest (config.ts
215
+ // dataSchema): it survives a restart. A visitor's stays in this worker's memory only: every
216
+ // visitor on a device or browser shares one database partition, so a written draft would show one
217
+ // visitor's names, emails and phone numbers to the next. It survives closing and reopening the form.
218
+ const DRAFTS = "form_drafts";
219
+ const memoryDrafts = new Map<string, Record<string, FieldValue>>();
220
+ /** The loaded form belongs to a signed-in member (see Drafts). */
221
+ let persistDrafts = false;
222
+ /** Whose drafts `memoryDrafts` holds: the member's email, or "" for a visitor. The worker outlives
223
+ * the form modal, so a sign-in, a sign-out or another member clears them before any is read. */
224
+ let draftOwner: string | undefined;
225
+
226
+ function claimDrafts(owner: string): void {
227
+ if (owner === draftOwner) return;
228
+ memoryDrafts.clear();
229
+ draftOwner = owner;
230
+ }
231
+
232
+ function saveDraft(): void {
233
+ if (!loadedInputId) return;
234
+ memoryDrafts.set(loadedInputId, { ...values });
235
+ if (!persistDrafts) return;
236
+ void dbUpsert(DRAFTS, { id: loadedInputId, values: JSON.stringify(values) }).catch(() => { /* a lost draft is not an error */ });
237
+ }
238
+
239
+ function dropDraft(id: string): void {
240
+ if (!id) return;
241
+ memoryDrafts.delete(id);
242
+ if (persistDrafts) void dbRemove(DRAFTS, id).catch(() => { /* nothing to drop */ });
243
+ }
244
+
245
+ async function readDraft(id: string, persistent: boolean): Promise<Record<string, FieldValue>> {
246
+ const kept = memoryDrafts.get(id);
247
+ if (kept) return { ...kept };
248
+ if (!persistent) return {};
249
+ // A draft is a convenience on top of the form, which has already loaded: a draft that cannot be
250
+ // read means no saved answers, so the form opens empty (the catch falls through to that).
251
+ try {
252
+ const row = await dbGet(DRAFTS, id);
253
+ const raw = typeof row?.values === "string" ? JSON.parse(row.values) as unknown : null;
254
+ if (!raw || typeof raw !== "object") return {};
255
+ const out: Record<string, FieldValue> = {};
256
+ for (const [target, v] of Object.entries(raw as Record<string, Partial<FieldValue>>)) {
257
+ out[target] = {
258
+ text: typeof v?.text === "string" ? v.text : "",
259
+ checked: v?.checked === true,
260
+ selected: Array.isArray(v?.selected) ? v.selected.filter((x): x is string => typeof x === "string") : [],
261
+ };
262
+ }
263
+ return out;
264
+ } catch { /* an unreadable draft is no draft */ }
265
+ return {};
188
266
  }
189
267
 
190
268
  function argOf(arg: unknown): Record<string, unknown> {
@@ -213,6 +291,78 @@ function applyProblems(found: Record<string, string>): boolean {
213
291
  return true;
214
292
  }
215
293
 
294
+ /** `YYYY-MM-DD` → unix seconds at local noon (a time zone shift cannot move the day), or "". */
295
+ function unixOfIsoDate(iso: string): string {
296
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
297
+ return m ? String(Math.floor(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 12).getTime() / 1000)) : "";
298
+ }
299
+
300
+ /** The footer line when Next or Submit is blocked: it names the first field to fix, which may be
301
+ * below the fold (each field also shows its own error under it). */
302
+ function blocked(): Partial<S> {
303
+ showsBlocked = true;
304
+ return blockedLine();
305
+ }
306
+
307
+ /** The footer line naming the first field still to fix, or none once every field is fixed. */
308
+ function blockedLine(): Partial<S> {
309
+ const first = allFields().find((f) => problems[f.target]);
310
+ if (!first) { showsBlocked = false; return { noSendError: true, sendError: "" }; }
311
+ const field = first.label || first.help;
312
+ return {
313
+ noSendError: false,
314
+ sendError: field
315
+ ? copyTemplate("form.fixField", "Check “{field}” and try again.", { field })
316
+ : copyParam("form.fixFields", "Check the highlighted answers and try again."),
317
+ };
318
+ }
319
+
320
+ /** The footer shows a blocked-Next line (not a send failure), which follows the fixes. */
321
+ let showsBlocked = false;
322
+
323
+ /** No footer line (a page change, a clear, a send starting). */
324
+ function noLine(): Partial<S> {
325
+ showsBlocked = false;
326
+ return { noSendError: true, sendError: "" };
327
+ }
328
+
329
+ /** A field's answer changed: a flagged field is checked again, so its error goes only once the
330
+ * value is valid, and a blocked-Next line names the next field still to fix. */
331
+ function fixed(s: S, target: string): S {
332
+ if (problems[target]) {
333
+ const field = allFields().find((f) => f.target === target);
334
+ const still = field ? localProblems([field], values)[target] : undefined;
335
+ if (still) problems[target] = still; else delete problems[target];
336
+ }
337
+ return view(s, showsBlocked ? blockedLine() : {});
338
+ }
339
+
340
+ /** The forms list opens a form as a modal and says so (`modal: "1"`); a deep link does not. */
341
+ function openedAsModal(): boolean {
342
+ return (globalThis as { himalaya?: { input?: { modal?: unknown } } }).himalaya?.input?.modal === "1";
343
+ }
344
+
345
+ /** After a send: close the modal form, and confirm in a dialog over the screen behind it. The
346
+ * dialog is the app's own (`ui.alert`), so it outlives the form; Back only closes it.
347
+ * The close is a host action, not a returned `_nav`: this runs after `finishSend`, which the
348
+ * worker calls itself, and the host reads `_nav` only from an action it dispatched.
349
+ * A binary without the `ui` handler refuses the alert at once, before it answers the next host
350
+ * call, so the form then stays open on its done state rather than closing with no confirmation. */
351
+ async function confirmAndClose(title: string, message: string, success: boolean): Promise<void> {
352
+ let refused = false, closed = false;
353
+ // Back on the dialog: the sheet is gone by then, so the done state goes too, and the form opened
354
+ // again from the list shows its loading state rather than the last "Thank you".
355
+ void alert({ title, message, confirmLabel: copyParam("form.doneBackCta", "Back"), ...(success ? { icon: "success" as const } : {}) })
356
+ .then(() => { if (closed) void svc.forgetDone(); })
357
+ .catch(() => { refused = true; });
358
+ if (!openedAsModal()) return;
359
+ await dbGet(DRAFTS, loadedInputId || "_").catch(() => null);
360
+ if (!refused) {
361
+ closed = true;
362
+ void dispatch("himi.open", { presentation: "dismiss" }).catch(() => { closed = false; /* the done state stays */ });
363
+ }
364
+ }
365
+
216
366
  /** A send in flight is numbered; a later load or send makes an earlier answer stale. */
217
367
  let sendVersion = 0;
218
368
 
@@ -221,6 +371,9 @@ type SendRequest = Parameters<typeof createSubmission>[0];
221
371
  /** V4 checks first, then its queueable send. Legacy forms use their separate v2 write:
222
372
  * no v4 validation or offline queue is implied by resolving a short ID. */
223
373
  async function send(version: number, request: SendRequest, legacy: boolean): Promise<void> {
374
+ // The form this send is for: its kept answers go once it is sent, even when another form has
375
+ // loaded since (its finishSend is then stale and does nothing).
376
+ const draftId = loadedInputId;
224
377
  let outcome: Record<string, unknown>;
225
378
  try {
226
379
  if (legacy) {
@@ -243,6 +396,7 @@ async function send(version: number, request: SendRequest, legacy: boolean): Pro
243
396
  ? { outcome: "problems", problems: found }
244
397
  : { outcome: "failed", error: { code: (err as { code?: unknown })?.code, message: String((err as Error)?.message ?? err) } };
245
398
  }
399
+ if (outcome.outcome === "sent" || outcome.outcome === "queued") dropDraft(draftId);
246
400
  await svc.finishSend({ version, ...outcome });
247
401
  }
248
402
 
@@ -252,11 +406,13 @@ let inflight: Promise<S> | undefined;
252
406
  let inflightId = "";
253
407
 
254
408
  async function loadForm(id: string): Promise<S> {
255
- form = undefined; loadedInputId = ""; values = {}; page = 0; problems = {}; completed = false;
409
+ form = undefined; loadedInputId = ""; values = {}; page = 0; problems = {}; completed = false; touched = false; generation = 0;
256
410
  const version = ++sendVersion;
257
411
  const legacy = /^\d+$/.test(id);
258
412
  if (!id) return { ...BASE, status: "ready", ...presence("missing") };
259
413
  const member = memberDetails();
414
+ // A member's details (an email) say whether the draft may live in the device database.
415
+ const draft = member.then((m) => { claimDrafts(m.EMAIL ?? ""); return readDraft(id, Boolean(m.EMAIL)); });
260
416
  try {
261
417
  const res = legacy ? await getLegacyFormByShortId(id) : await getForm(id);
262
418
  if (version !== sendVersion) return svc.getState();
@@ -264,9 +420,16 @@ async function loadForm(id: string): Promise<S> {
264
420
  if (!parsed.id || (res as { form?: { enabled?: boolean } }).form?.enabled === false) return { ...BASE, status: "ready", ...presence("missing") };
265
421
  const memberInfo = await member;
266
422
  if (version !== sendVersion) return svc.getState();
423
+ const saved = await draft;
424
+ if (version !== sendVersion) return svc.getState();
267
425
  form = parsed;
268
426
  loadedInputId = id;
269
427
  isLegacy = legacy;
428
+ persistDrafts = Boolean(memberInfo.EMAIL);
429
+ // The visitor's own latest answers first; member details fill only what is still empty.
430
+ const known = new Set(allFields().map((f) => f.target));
431
+ values = Object.fromEntries(Object.entries(saved).filter(([target]) => known.has(target)));
432
+ touched = Object.keys(values).length > 0;
270
433
  prefill(memberInfo);
271
434
  return view({ ...BASE });
272
435
  } catch (err) {
@@ -284,12 +447,12 @@ const svc = defineService<S, {
284
447
  toggleCheck: (s: S, arg?: unknown) => S;
285
448
  choose: (s: S, arg?: unknown) => S;
286
449
  toggleOption: (s: S, arg?: unknown) => S;
287
- openDate: (s: S, arg?: unknown) => S;
288
- draftDate: (s: S, arg?: unknown) => S;
289
- applyDate: (s: S) => S;
290
- closeDate: (s: S) => S;
450
+ setDate: (s: S, arg?: unknown) => S;
451
+ clearForm: (s: S) => S;
452
+ close: (s: S) => S;
291
453
  next: (s: S) => S;
292
454
  finishSend: (s: S, arg?: unknown) => S;
455
+ forgetDone: (s: S) => S;
293
456
  back: (s: S) => S;
294
457
  openWebsite: (s: S) => Promise<S>;
295
458
  }>("himiBrandedForm", {
@@ -306,39 +469,40 @@ const svc = defineService<S, {
306
469
  // failure (no form held), starts over.
307
470
  // A form already sent keeps its thank-you state: re-opening the editable form would invite
308
471
  // a second submission.
309
- if (form && id && loadedInputId === id) return completed ? s : view(s);
472
+ // A form opened again as a modal after its send starts over (the list reuses this worker);
473
+ // only a deep-linked form keeps its done state on a repeat onAppear.
474
+ if (form && id && loadedInputId === id && !(completed && openedAsModal())) return completed ? s : view(s);
310
475
  if (inflight && inflightId === id) return inflight;
311
476
  inflightId = id;
312
477
  const pending = loadForm(id);
313
478
  inflight = pending;
314
479
  try { return await pending; } finally { if (inflight === pending) inflight = undefined; }
315
480
  },
316
- // Keystrokes: the value lives in the worker; the state only changes to clear an error.
481
+ // Keystrokes: the value lives in the worker (and its draft); the state changes only to clear
482
+ // an error or to show / hide "Clear form", so typing does not re-render the field list.
317
483
  setText: (s, arg) => {
318
484
  const a = argOf(arg);
319
485
  const target = String(a.target ?? "");
320
486
  const text = typeof a.value === "string" ? a.value : typeof a.text === "string" ? a.text : "";
321
487
  if (!target) return s;
488
+ const hadAnswers = hasAnswers();
322
489
  setValue(target, { text });
323
- if (!problems[target]) return s;
324
- delete problems[target];
325
- return view(s);
490
+ if (!problems[target] && hadAnswers === hasAnswers()) return s;
491
+ return fixed(s, target);
326
492
  },
327
493
  toggleCheck: (s, arg) => {
328
494
  const a = argOf(arg);
329
495
  const target = String(a.target ?? "");
330
496
  if (!target) return s;
331
497
  setValue(target, { checked: typeof a.value === "boolean" ? a.value : !valueOf(target).checked });
332
- delete problems[target];
333
- return view(s);
498
+ return fixed(s, target);
334
499
  },
335
500
  choose: (s, arg) => {
336
501
  const a = argOf(arg);
337
502
  const target = String(a.target ?? ""), value = String(a.option ?? "");
338
503
  if (!target || !value) return s;
339
504
  setValue(target, { selected: [value] });
340
- delete problems[target];
341
- return view(s);
505
+ return fixed(s, target);
342
506
  },
343
507
  toggleOption: (s, arg) => {
344
508
  const a = argOf(arg);
@@ -346,66 +510,78 @@ const svc = defineService<S, {
346
510
  if (!target || !value) return s;
347
511
  const sel = valueOf(target).selected;
348
512
  setValue(target, { selected: sel.includes(value) ? sel.filter((x) => x !== value) : [...sel, value] });
349
- delete problems[target];
350
- return view(s);
351
- },
352
- openDate: (s, arg) => {
353
- const target = String(argOf(arg).target ?? "");
354
- const f = allFields().find((x) => x.target === target);
355
- if (!f || s.sending) return s;
356
- dateTarget = target;
357
- datePicked = false;
358
- const iso = valueOf(target).text;
359
- dateDraft = /^\d{4}-\d{2}-\d{2}$/.test(iso) ? Math.floor(new Date(`${iso}T12:00:00`).getTime() / 1000) : Math.floor(Date.now() / 1000);
360
- return { ...s, dateSheetOpen: true, dateSheetTitle: f.label, dateDraft };
513
+ return fixed(s, target);
361
514
  },
362
- draftDate: (s, arg) => {
363
- const v = Number(argOf(arg).value);
515
+ // The platform date picker sits in the field itself and reports the picked day (unix seconds).
516
+ // Dismissing it without a choice reports nothing, so the stored date stays as it was. A cleared
517
+ // input (web) reports an empty value, which clears the answer.
518
+ setDate: (s, arg) => {
519
+ const a = argOf(arg);
520
+ const target = String(a.target ?? "");
521
+ if (!target || s.sending) return s;
522
+ if (a.value === "" || a.value === null) {
523
+ setValue(target, { text: "" });
524
+ return fixed(s, target);
525
+ }
526
+ const v = Number(a.value);
364
527
  if (!Number.isFinite(v) || v <= 0) return s;
365
- dateDraft = v;
366
- datePicked = true;
367
- return { ...s, dateDraft };
528
+ setValue(target, { text: isoDate(v) });
529
+ return fixed(s, target);
368
530
  },
369
- applyDate: (s) => {
370
- if (dateTarget && dateDraft && datePicked) { setValue(dateTarget, { text: isoDate(dateDraft) }); delete problems[dateTarget]; }
371
- return view({ ...s, dateSheetOpen: false });
531
+ // Every answer of this form, on every page, and its draft: reopening shows an empty form.
532
+ clearForm: (s) => {
533
+ if (!form || s.sending) return s;
534
+ values = {};
535
+ problems = {};
536
+ touched = false;
537
+ generation += 1;
538
+ dropDraft(loadedInputId);
539
+ return view(s, noLine());
372
540
  },
373
- closeDate: (s) => ({ ...s, dateSheetOpen: false }),
541
+ // The closed-form notice's link: back to the list the modal opened from.
542
+ close: (s) => navigate(s, { presentation: openedAsModal() ? "dismiss" : "back" }),
374
543
  back: (s) => {
375
544
  if (page === 0 || s.sending) return s;
376
545
  page -= 1;
377
- return view(s, { noSendError: true, sendError: "" });
546
+ return view(s, noLine());
378
547
  },
379
548
  // "Next" on an earlier page, "Submit" on the last one.
380
549
  next: (s) => {
381
550
  if (!form || form.unsupported || form.closed || s.sending) return s;
382
551
  const local = localProblems(pageFields(), values);
383
- if (applyProblems(local)) return view(s, { noSendError: true, sendError: "" });
384
- if (!lastPage()) { page += 1; problems = {}; return view(s, { noSendError: true, sendError: "" }); }
552
+ if (applyProblems(local)) return view(s, blocked());
553
+ if (!lastPage()) { page += 1; problems = {}; return view(s, noLine()); }
385
554
  const all = allFields();
386
555
  const allLocal = localProblems(all, values);
387
- if (applyProblems(allLocal)) return view(s, { noSendError: true, sendError: "" });
556
+ if (applyProblems(allLocal)) return view(s, blocked());
388
557
  const version = ++sendVersion;
389
558
  void send(version, { submission: { formId: form.id, submissions: submissionValues(all, values) } }, isLegacy);
390
- return { ...s, sending: true, noSendError: true, sendError: "" };
559
+ return { ...s, sending: true, ...noLine() };
391
560
  },
392
561
  finishSend: (s, arg) => {
393
562
  const r = argOf(arg) as { version?: unknown; outcome?: unknown; problems?: unknown; error?: unknown };
394
563
  if (r.version !== sendVersion || !form) return s;
395
564
  if (r.outcome === "problems") {
396
- if (applyProblems(r.problems as Record<string, string>)) return view(s, { sending: false, noSendError: true, sendError: "" });
565
+ if (applyProblems(r.problems as Record<string, string>)) return view(s, { sending: false, ...blocked() });
397
566
  return view(s, { sending: false, noSendError: false, sendError: copyParam("form.checkError", "Some answers can't be sent. Check the form and try again.") });
398
567
  }
399
568
  if (r.outcome === "failed") return view(s, messageFor(r.error));
400
569
  const queued = r.outcome === "queued";
401
570
  completed = true;
571
+ dropDraft(loadedInputId);
572
+ const doneTitle = queued ? copyParam("form.queuedTitle", "Form saved") : copyParam("form.sentTitle", "Thank you");
573
+ const doneBody = queued ? copyParam("form.queuedBody", "We'll send your form when you're back online.")
574
+ : copyParam("form.sentBody", "Your answer was submitted successfully.");
575
+ void confirmAndClose(doneTitle, doneBody, !queued);
576
+ // The done state is what shows when the form cannot close (a deep link, not a modal) or the
577
+ // app has no dialog: never the editable form again.
402
578
  return view(s, {
403
- sending: false, hideForm: true, hideSingle: true, hidePair: true, hideDone: false, rows: [], noPageCaption: true,
404
- doneTitle: queued ? copyParam("form.queuedTitle", "Form saved") : copyParam("form.sentTitle", "Thank you"),
405
- doneBody: queued ? copyParam("form.queuedBody", "We'll send your form when you're back online.")
406
- : (form.thankYou || copyParam("form.sentBody", "Thanks, we received your submission.")),
579
+ sending: false, hideForm: true, hideFooterSingle: true, hideFooterFirst: true, hideFooterMiddle: true,
580
+ hideFooterLast: true, hideClear: true, hideDone: false, rows: [], noPageCaption: true, doneTitle, doneBody,
407
581
  });
408
582
  },
583
+ // The modal form closed after its send (see confirmAndClose).
584
+ forgetDone: (s) => (completed && openedAsModal() ? { ...BASE } : s),
409
585
  openWebsite: async (s) => {
410
586
  if (siteUrl) { try { await openUrl(siteUrl, "in_app_browser"); } catch { /* the handoff is best-effort */ } }
411
587
  return s;
@@ -399,7 +399,7 @@ export default defineApp({
399
399
  // Your on-device database. It must declare every entity a worker reads or writes,
400
400
  // or those calls fail closed — keep it in step with `local_database` above.
401
401
  dataSchema: {
402
- "version": 3,
402
+ "version": 4,
403
403
  "entities": [
404
404
  {
405
405
  "name": "products",
@@ -583,6 +583,21 @@ export default defineApp({
583
583
  "type": "string"
584
584
  }
585
585
  ]
586
+ },
587
+ {
588
+ "name": "form_drafts",
589
+ "encrypted": true,
590
+ "fields": [
591
+ {
592
+ "name": "id",
593
+ "type": "string",
594
+ "required": true
595
+ },
596
+ {
597
+ "name": "values",
598
+ "type": "string"
599
+ }
600
+ ]
586
601
  }
587
602
  ]
588
603
  },