@wix/himalaya-cli 0.1947.0 → 0.1948.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.
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/admob-ids.d.ts +4 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/index.d.ts +1 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/_types/core/ts/src/schema.d.ts +3 -0
- package/dist/authoring-runtime/node_modules/@wix/himalaya/dist/core.mjs +8 -2
- package/dist/browser-plane/assets.json +5 -5
- package/dist/browser-plane/preview-deferred/{da958a2a47eef7082c7892c1cc755a58bbeefcb4b617b47fde87f1ce567b3e64.bin → 1425fc7ef3149df8ba41fdbcca629cefd430a2cae524822c21985f0aade6430a.bin} +1 -1
- package/dist/browser-plane/sw.js +9 -9
- package/dist/cli.mjs +1820 -776
- package/dist/preview-assets.generated.bin +0 -0
- package/guides/getting-started.md +6 -1
- package/guides/himi-skill.md +6 -1
- package/guides/himi-test.md +30 -1
- package/guides/one-app-section-mappings.md +1 -1
- package/guides/one-app-to-himi-app.md +21 -14
- package/guides/sdk-reference.json +1 -1
- package/guides/skill.md +1 -1
- package/package.json +2 -2
- package/templates/branded-lite/recipes/form-section.json +958 -0
- package/templates/branded-lite/tier5-src/_shared/event-agenda.ts +15 -15
- package/templates/branded-lite/tier5-src/_shared/event-schedule-section.ts +8 -8
- package/templates/branded-lite/tier5-src/_shared/form-section.ts +640 -0
- package/templates/branded-lite/tier5-src/himi-branded-lite-form/index.ts +4 -588
- package/templates/branded-lite/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/community-club/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/conference/tier5-src/_shared/event-agenda.ts +15 -15
- package/templates/conference/tier5-src/himi-conference-agenda/index.ts +3 -5
- package/templates/conference/tier5-src/himi-conference-home/index.ts +5 -6
- package/templates/conference/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/events-meetups/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/gym-fitness/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/nonprofit-cause/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/podcast-creator/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/portfolio-creative/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/professional-services/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/restaurant/tier5-src/himi-events-detail/index.ts +7 -6
- package/templates/yoga-studio/tier5-src/himi-events-detail/index.ts +7 -6
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
// One Wix Form a visitor fills out and sends, as a registrable service: one worker for the
|
|
2
|
+
// himi_form screen and for a migrated page's inline form section.
|
|
3
|
+
// registerFormSection(name) -> the screen: the form named by the screen's `id` input, opened as a modal
|
|
4
|
+
// from the forms list or by a deep link (the himi-branded-lite-form bundle);
|
|
5
|
+
// registerFormSection(name, { formId }) -> a section: that form, laid out inline on its page (One App's
|
|
6
|
+
// `forms_full_form_by_short_id`). It never closes a modal.
|
|
7
|
+
// State, flags and actions are the screen's own, so the form-section recipe and the himi_form descriptor bind the same names.
|
|
8
|
+
//
|
|
9
|
+
// Reads a v4 form or a legacy short-ID form and renders its fields in layout order, one page at a time
|
|
10
|
+
// (_shared/branded-form.ts parses the schema). A signed-in member gets email, names and
|
|
11
|
+
// phone filled in from their member record, matched by each field's contact mapping.
|
|
12
|
+
// V4 send = local checks → validateFormSubmission → createSubmission (offline outbox).
|
|
13
|
+
// Legacy send uses the v2 form key/value contract, online only. Server errors land in each field's own
|
|
14
|
+
// slot; a failed send keeps every value and says so by the button.
|
|
15
|
+
//
|
|
16
|
+
// A form with a field the app cannot fill, or a conditional rule, shows a notice that
|
|
17
|
+
// opens the website instead (a hidden required field would fail the whole send). A form
|
|
18
|
+
// whose deadline passed shows a closed notice. Replaces wix-spaces-form-detail for this
|
|
19
|
+
// app only: the Spaces clone fixture still uses that worker.
|
|
20
|
+
import { classifyLoadError, defineService, navigate } from "@himalaya/state";
|
|
21
|
+
import { alert } from "@himalaya/ui";
|
|
22
|
+
import { dispatch } from "@himalaya/dispatch";
|
|
23
|
+
import { get as dbGet, remove as dbRemove, upsert as dbUpsert } from "@himalaya/local-db";
|
|
24
|
+
import { open as openUrl } from "@himalaya/open-url";
|
|
25
|
+
import { createSubmission, getForm, getLegacyFormByShortId, submitLegacyForm, validateFormSubmission } from "@himalaya/wix-forms";
|
|
26
|
+
import { getMyMember } from "@himalaya/wix-members";
|
|
27
|
+
import { copyParam, copyTemplate, stashCopy } from "./himi-copy.js";
|
|
28
|
+
import { detailInputId, presence, presenceAfterError, type PresenceFlags } from "./detail-presence.js";
|
|
29
|
+
import { memberAccess } from "./member-access.js";
|
|
30
|
+
import {
|
|
31
|
+
EMPTY_VALUE, isoDate, localProblems, parseForm, parseLegacyForm, serverProblems, submissionValues,
|
|
32
|
+
type FieldValue, type FormFieldModel, type FormModel,
|
|
33
|
+
} from "./branded-form.js";
|
|
34
|
+
|
|
35
|
+
export interface FormSectionOptions {
|
|
36
|
+
/** The form a page section shows inline: a v4 form id, or a legacy numeric short id. Absent: the screen's `id` input. */
|
|
37
|
+
formId?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface OptionRow { id: string; target: string; value: string; label: string; selected: boolean }
|
|
41
|
+
interface FieldRow {
|
|
42
|
+
id: string; target: string;
|
|
43
|
+
label: string; hideLabel: boolean; help: string; hideHelp: boolean; placeholder: string;
|
|
44
|
+
checkLabel: string; displayText: string;
|
|
45
|
+
value: string; checked: boolean;
|
|
46
|
+
/** The stored date as unix seconds (local noon), or "" — the inline date picker's literal
|
|
47
|
+
* `valuePath` seed. Unix, not `YYYY-MM-DD`: no renderer parses a bare date. */
|
|
48
|
+
dateUnix: string;
|
|
49
|
+
/** The field's error, drawn on the line under it (every kind: a TextField's `errorPath` takes
|
|
50
|
+
* only a `$service:` binding, so a row's error cannot use the field's own slot). */
|
|
51
|
+
error: string; noError: boolean;
|
|
52
|
+
options: OptionRow[];
|
|
53
|
+
// hiddenWhen hides on TRUE: one "not" flag per field kind.
|
|
54
|
+
notText: boolean; notArea: boolean; notEmail: boolean; notPhone: boolean; notNumber: boolean; notUrl: boolean;
|
|
55
|
+
notDate: boolean; notCheck: boolean; notChoice: boolean; notMulti: boolean; notDisplay: boolean;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface S extends PresenceFlags {
|
|
59
|
+
status: "loading" | "ready";
|
|
60
|
+
title: string;
|
|
61
|
+
rows: FieldRow[];
|
|
62
|
+
pageCaption: string; noPageCaption: boolean;
|
|
63
|
+
primaryLabel: string; backLabel: string;
|
|
64
|
+
/** The footer variant (hiddenWhen hides on TRUE): a one-page form; the first, a middle and
|
|
65
|
+
* the last page of a form with several. */
|
|
66
|
+
hideFooterSingle: boolean; hideFooterFirst: boolean; hideFooterMiddle: boolean; hideFooterLast: boolean;
|
|
67
|
+
/** "Clear form" shows once the visitor has entered an answer. */
|
|
68
|
+
hideClear: boolean;
|
|
69
|
+
sending: boolean;
|
|
70
|
+
sendError: string; noSendError: boolean;
|
|
71
|
+
/** The fields and the footer: hidden unless the form is there, fillable, open and not sent. */
|
|
72
|
+
hideForm: boolean;
|
|
73
|
+
hideUnsupported: boolean; hideClosed: boolean;
|
|
74
|
+
/** No site URL (hosted mode): the notice keeps its sentence and drops the link. */
|
|
75
|
+
hideOpenWebsite: boolean;
|
|
76
|
+
hideDone: boolean; doneTitle: string; doneBody: string;
|
|
77
|
+
hideOfflineError: boolean; hideServerError: boolean;
|
|
78
|
+
/** Neither load error shows (the shared section-error recipe's flag). */
|
|
79
|
+
notErrored: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const BASE: S = {
|
|
83
|
+
status: "loading", title: "", rows: [], pageCaption: "", noPageCaption: true,
|
|
84
|
+
primaryLabel: "", backLabel: "", hideFooterSingle: true, hideFooterFirst: true, hideFooterMiddle: true, hideFooterLast: true,
|
|
85
|
+
hideClear: true, sending: false, sendError: "", noSendError: true,
|
|
86
|
+
hideForm: true, hideUnsupported: true, hideClosed: true, hideOpenWebsite: true, hideDone: true, doneTitle: "", doneBody: "",
|
|
87
|
+
hideOfflineError: true, hideServerError: true, notErrored: true,
|
|
88
|
+
...presence("loading"),
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
function problemText(f: FormFieldModel, type: string): string {
|
|
92
|
+
switch (type) {
|
|
93
|
+
case "required":
|
|
94
|
+
return f.kind === "checkbox" ? copyParam("form.errorCheck", "Check this box to continue.")
|
|
95
|
+
: f.kind === "choice" || f.kind === "multi" ? copyParam("form.errorChoose", "Choose an option.")
|
|
96
|
+
: copyParam("form.errorRequired", "Enter a value.");
|
|
97
|
+
case "email": return copyParam("form.errorEmail", "Enter a valid email.");
|
|
98
|
+
case "number": return copyParam("form.errorNumber", "Enter a number.");
|
|
99
|
+
case "url": return copyParam("form.errorUrl", "Enter a valid link.");
|
|
100
|
+
case "phone": return copyParam("form.errorPhone", "Enter a valid phone number.");
|
|
101
|
+
case "REQUIRED_VALUE_ERROR": return problemText(f, "required");
|
|
102
|
+
case "FORMAT_ERROR":
|
|
103
|
+
return f.kind === "email" ? problemText(f, "email") : f.kind === "phone" ? copyParam("form.errorPhone", "Enter a valid phone number.")
|
|
104
|
+
: f.kind === "url" ? problemText(f, "url") : copyParam("form.errorInvalid", "Check this value.");
|
|
105
|
+
default: return copyParam("form.errorInvalid", "Check this value.");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Who is signed in: the member's email, or "" for a visitor (or an identity read that fails). */
|
|
110
|
+
async function currentOwner(): Promise<string> {
|
|
111
|
+
return (await memberAccess().catch(() => ({ email: "" }))).email;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Like currentOwner, but undefined when the identity cannot be read: an unread identity is never a sign-out. */
|
|
115
|
+
async function confirmedOwner(): Promise<string | undefined> {
|
|
116
|
+
try { return (await memberAccess({ throwOnUnavailable: true })).email; } catch { return undefined; }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A signed-in member's own details by contact field, or `{}` for a visitor or a member read
|
|
120
|
+
* that fails. Fetched beside the form (not after it), so a member does not wait twice. */
|
|
121
|
+
async function memberDetails(owner: Promise<string>): Promise<Record<string, string | undefined>> {
|
|
122
|
+
const email = await owner;
|
|
123
|
+
if (!email) return {};
|
|
124
|
+
let contact: { firstName?: string; lastName?: string; phones?: string[] } = {};
|
|
125
|
+
let loginEmail = email;
|
|
126
|
+
try {
|
|
127
|
+
const r = await getMyMember({ fieldsets: ["FULL"] }) as { member?: { loginEmail?: string; contact?: typeof contact } };
|
|
128
|
+
contact = r.member?.contact ?? {};
|
|
129
|
+
loginEmail = (r.member?.loginEmail || email).trim();
|
|
130
|
+
} catch { /* the email from the session is still the member's own */ }
|
|
131
|
+
return { EMAIL: loginEmail, FIRST_NAME: contact.firstName, LAST_NAME: contact.lastName, PHONE: contact.phones?.[0] };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// ---- Drafts ---------------------------------------------------------------------------------
|
|
135
|
+
// What the user typed survives leaving the form: every change rewrites this form's draft (the
|
|
136
|
+
// latest answers, a cleared field included), it is read back when the form opens again, and a sent
|
|
137
|
+
// or cleared form removes it. One draft per form id, so forms never share answers.
|
|
138
|
+
// Where it is kept depends on who is filling it in. A signed-in member's goes to the device
|
|
139
|
+
// database, whose partition is that member's own, in an entity encrypted at rest (config.ts
|
|
140
|
+
// dataSchema): it survives a restart. A visitor's stays in this worker's memory only: every
|
|
141
|
+
// visitor on a device or browser shares one database partition, so a written draft would show one
|
|
142
|
+
// visitor's names, emails and phone numbers to the next. It survives closing and reopening the form.
|
|
143
|
+
// The memory drafts belong to the person, not to one service: every form service in the worker shares them.
|
|
144
|
+
const DRAFTS = "form_drafts";
|
|
145
|
+
const memoryDrafts = new Map<string, Record<string, FieldValue>>();
|
|
146
|
+
/** Whose drafts `memoryDrafts` holds: the member's email, or "" for a visitor. The worker outlives
|
|
147
|
+
* the form modal, so a sign-in, a sign-out or another member clears them before any is read. */
|
|
148
|
+
let draftOwner: string | undefined;
|
|
149
|
+
|
|
150
|
+
function claimDrafts(owner: string): void {
|
|
151
|
+
if (owner === draftOwner) return;
|
|
152
|
+
memoryDrafts.clear();
|
|
153
|
+
draftOwner = owner;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function readDraft(id: string, persistent: boolean): Promise<Record<string, FieldValue>> {
|
|
157
|
+
const kept = memoryDrafts.get(id);
|
|
158
|
+
if (kept) return { ...kept };
|
|
159
|
+
if (!persistent) return {};
|
|
160
|
+
// A draft is a convenience on top of the form, which has already loaded: a draft that cannot be
|
|
161
|
+
// read means no saved answers, so the form opens empty (the catch falls through to that).
|
|
162
|
+
try {
|
|
163
|
+
const row = await dbGet(DRAFTS, id);
|
|
164
|
+
const raw = typeof row?.values === "string" ? JSON.parse(row.values) as unknown : null;
|
|
165
|
+
if (!raw || typeof raw !== "object") return {};
|
|
166
|
+
const out: Record<string, FieldValue> = {};
|
|
167
|
+
for (const [target, v] of Object.entries(raw as Record<string, Partial<FieldValue>>)) {
|
|
168
|
+
out[target] = {
|
|
169
|
+
text: typeof v?.text === "string" ? v.text : "",
|
|
170
|
+
checked: v?.checked === true,
|
|
171
|
+
selected: Array.isArray(v?.selected) ? v.selected.filter((x): x is string => typeof x === "string") : [],
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
} catch { /* an unreadable draft is no draft */ }
|
|
176
|
+
return {};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function argOf(arg: unknown): Record<string, unknown> {
|
|
180
|
+
return arg && typeof arg === "object" ? arg as Record<string, unknown> : {};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function messageFor(err: unknown): Partial<S> {
|
|
184
|
+
const offline = (err as { code?: unknown })?.code === "offline_write_blocked" || classifyLoadError(err) === "offline";
|
|
185
|
+
return {
|
|
186
|
+
sending: false,
|
|
187
|
+
sendError: offline ? copyParam("form.offlineError", "Connect to the internet, then try again.") : copyParam("form.sendError", "Couldn't send the form. Try again."),
|
|
188
|
+
noSendError: false,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** `YYYY-MM-DD` → unix seconds at local noon (a time zone shift cannot move the day), or "". */
|
|
193
|
+
function unixOfIsoDate(iso: string): string {
|
|
194
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
|
195
|
+
return m ? String(Math.floor(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 12).getTime() / 1000)) : "";
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type SendRequest = Parameters<typeof createSubmission>[0];
|
|
199
|
+
|
|
200
|
+
export function registerFormSection(serviceName: string, options: FormSectionOptions = {}) {
|
|
201
|
+
/** A page section's own form: it lives on its page, never in a modal. */
|
|
202
|
+
const sectionFormId = options.formId?.trim() ?? "";
|
|
203
|
+
const inputId = (): string => sectionFormId || detailInputId();
|
|
204
|
+
|
|
205
|
+
// The worker is the source of truth for what the visitor typed: a keystroke updates this
|
|
206
|
+
// map and returns the state unchanged, so typing never re-renders the field list.
|
|
207
|
+
let form: FormModel | undefined;
|
|
208
|
+
let loadedInputId = "";
|
|
209
|
+
/** Who was signed in when the form loaded ("" for a visitor). A member's form starts over when another person, or
|
|
210
|
+
* nobody, is signed in now (see `load`); a visitor's form keeps its answers through a sign-in. */
|
|
211
|
+
let loadedOwner = "";
|
|
212
|
+
let isLegacy = false;
|
|
213
|
+
let values: Record<string, FieldValue> = {};
|
|
214
|
+
let page = 0;
|
|
215
|
+
let problems: Record<string, string> = {};
|
|
216
|
+
let siteUrl = "";
|
|
217
|
+
|
|
218
|
+
const valueOf = (target: string): FieldValue => values[target] ?? EMPTY_VALUE;
|
|
219
|
+
const pageFields = (): FormFieldModel[] => (form?.pages[page] ?? []).map((id) => form!.fields[id]).filter(Boolean);
|
|
220
|
+
const allFields = (): FormFieldModel[] => (form ? form.pages.flat().map((id) => form!.fields[id]).filter(Boolean) : []);
|
|
221
|
+
const lastPage = (): boolean => !form || page >= form.pages.length - 1;
|
|
222
|
+
|
|
223
|
+
function row(f: FormFieldModel): FieldRow {
|
|
224
|
+
const v = valueOf(f.target);
|
|
225
|
+
const error = problems[f.target] ? problemText(f, problems[f.target]) : "";
|
|
226
|
+
const marked = f.label ? `${f.label}${f.required ? " *" : ""}` : "";
|
|
227
|
+
// A checkbox's label sits beside its box, and a text block is its own text: neither has
|
|
228
|
+
// a label line above it.
|
|
229
|
+
const label = f.kind === "checkbox" || f.kind === "display" ? "" : marked;
|
|
230
|
+
// After "Clear form" the rows take new ids: a native field keeps what was typed when only its
|
|
231
|
+
// literal value changes, so an emptied row must mount as a new field to show empty.
|
|
232
|
+
const id = generation ? `${f.id}_r${generation}` : f.id;
|
|
233
|
+
return {
|
|
234
|
+
id, target: f.target,
|
|
235
|
+
label, hideLabel: !label, help: f.help, hideHelp: !f.help,
|
|
236
|
+
checkLabel: f.kind === "checkbox" ? marked : "", displayText: f.kind === "display" ? f.label : "",
|
|
237
|
+
placeholder: f.placeholder,
|
|
238
|
+
value: v.text, checked: v.checked, dateUnix: f.kind === "date" ? unixOfIsoDate(v.text) : "",
|
|
239
|
+
error, noError: !error,
|
|
240
|
+
options: f.options.map((o, i) => ({ id: `${id}_${i}`, target: f.target, value: o.value, label: o.label, selected: v.selected.includes(o.value) })),
|
|
241
|
+
notText: f.kind !== "text", notArea: f.kind !== "area", notEmail: f.kind !== "email", notPhone: f.kind !== "phone",
|
|
242
|
+
notNumber: f.kind !== "number", notUrl: f.kind !== "url", notDate: f.kind !== "date", notCheck: f.kind !== "checkbox",
|
|
243
|
+
notChoice: f.kind !== "choice", notMulti: f.kind !== "multi", notDisplay: f.kind !== "display",
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** The visible state for the current form, page, values and problems. */
|
|
248
|
+
function view(s: S, patch: Partial<S> = {}): S {
|
|
249
|
+
if (!form) return { ...s, ...patch };
|
|
250
|
+
const pages = form.pages.length;
|
|
251
|
+
const fillable = !form.unsupported && !form.closed;
|
|
252
|
+
return {
|
|
253
|
+
...s,
|
|
254
|
+
status: "ready",
|
|
255
|
+
title: form.title || copyParam("form.untitled", "Untitled form"),
|
|
256
|
+
rows: fillable ? pageFields().map(row) : [],
|
|
257
|
+
pageCaption: pages > 1 ? copyTemplate("form.pageCaption", "Page {page} of {total}", { page: String(page + 1), total: String(pages) }) : "",
|
|
258
|
+
noPageCaption: !fillable || pages < 2,
|
|
259
|
+
primaryLabel: lastPage() ? (form.submitText || copyParam("form.submitCta", "Submit")) : (form.nextText || copyParam("form.nextCta", "Next")),
|
|
260
|
+
backLabel: form.backText || copyParam("form.previousCta", "Back"),
|
|
261
|
+
hideFooterSingle: !fillable || pages > 1,
|
|
262
|
+
hideFooterFirst: !fillable || pages < 2 || page !== 0,
|
|
263
|
+
hideFooterMiddle: !fillable || pages < 2 || page === 0 || lastPage(),
|
|
264
|
+
hideFooterLast: !fillable || pages < 2 || !lastPage(),
|
|
265
|
+
hideClear: !fillable || !hasAnswers(),
|
|
266
|
+
hideForm: !fillable,
|
|
267
|
+
hideUnsupported: !form.unsupported,
|
|
268
|
+
hideOpenWebsite: !siteUrl,
|
|
269
|
+
hideClosed: form.unsupported || !form.closed,
|
|
270
|
+
hideDone: true,
|
|
271
|
+
hideOfflineError: true, hideServerError: true, notErrored: true,
|
|
272
|
+
...presence("found"),
|
|
273
|
+
...patch,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** The member's details, written into the empty fields they map to. */
|
|
278
|
+
function prefill(byField: Record<string, string | undefined>): void {
|
|
279
|
+
for (const f of allFields()) {
|
|
280
|
+
const known = byField[f.contactField]?.trim();
|
|
281
|
+
// A field in the draft keeps the visitor's own answer, an emptied one included.
|
|
282
|
+
if (!known || f.target in values) continue;
|
|
283
|
+
values[f.target] = { ...valueOf(f.target), text: known };
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function setValue(target: string, next: Partial<FieldValue>): void {
|
|
288
|
+
values[target] = { ...valueOf(target), ...next };
|
|
289
|
+
touched = true;
|
|
290
|
+
saveDraft();
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** How many times "Clear form" ran on this form (row ids carry it, see row()). */
|
|
294
|
+
let generation = 0;
|
|
295
|
+
|
|
296
|
+
/** The visitor has started filling this form (a change, or a draft from an earlier visit):
|
|
297
|
+
* member details prefilled on open do not count. */
|
|
298
|
+
let touched = false;
|
|
299
|
+
|
|
300
|
+
/** Has the visitor entered an answer that "Clear form" would remove? */
|
|
301
|
+
function hasAnswers(): boolean {
|
|
302
|
+
return touched && Object.values(values).some((v) => v.text.trim() !== "" || v.checked || v.selected.length > 0);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** The loaded form belongs to a signed-in member (see Drafts). */
|
|
306
|
+
let persistDrafts = false;
|
|
307
|
+
|
|
308
|
+
function saveDraft(): void {
|
|
309
|
+
if (!loadedInputId) return;
|
|
310
|
+
memoryDrafts.set(loadedInputId, { ...values });
|
|
311
|
+
if (!persistDrafts) return;
|
|
312
|
+
void dbUpsert(DRAFTS, { id: loadedInputId, values: JSON.stringify(values) }).catch(() => { /* a lost draft is not an error */ });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** `persistent`: whether that draft lives in the device database (a send passes the flag it started with, since the
|
|
316
|
+
* form may have loaded again for someone else meanwhile). */
|
|
317
|
+
function dropDraft(id: string, persistent = persistDrafts): void {
|
|
318
|
+
if (!id) return;
|
|
319
|
+
memoryDrafts.delete(id);
|
|
320
|
+
if (persistent) void dbRemove(DRAFTS, id).catch(() => { /* nothing to drop */ });
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Keeps the problems that name a field the screen shows and moves to the first page with one;
|
|
324
|
+
* false when none does. A server error for a target the app does not render (a hidden field, an
|
|
325
|
+
* unknown path) cannot be shown in a field, so the caller says so by the button instead. */
|
|
326
|
+
function applyProblems(found: Record<string, string>): boolean {
|
|
327
|
+
const shown = new Set(allFields().map((f) => f.target));
|
|
328
|
+
problems = Object.fromEntries(Object.entries(found).filter(([target]) => shown.has(target)));
|
|
329
|
+
const targets = Object.keys(problems);
|
|
330
|
+
if (!targets.length || !form) return false;
|
|
331
|
+
const pageWithProblem = form.pages.findIndex((ids) => ids.some((id) => targets.includes(form!.fields[id]?.target ?? "")));
|
|
332
|
+
if (pageWithProblem >= 0) page = pageWithProblem;
|
|
333
|
+
return true;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The footer line when Next or Submit is blocked: it names the first field to fix, which may be
|
|
337
|
+
* below the fold (each field also shows its own error under it). */
|
|
338
|
+
function blocked(): Partial<S> {
|
|
339
|
+
showsBlocked = true;
|
|
340
|
+
return blockedLine();
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** The footer line naming the first field still to fix, or none once every field is fixed. */
|
|
344
|
+
function blockedLine(): Partial<S> {
|
|
345
|
+
const first = allFields().find((f) => problems[f.target]);
|
|
346
|
+
if (!first) { showsBlocked = false; return { noSendError: true, sendError: "" }; }
|
|
347
|
+
const field = first.label || first.help;
|
|
348
|
+
return {
|
|
349
|
+
noSendError: false,
|
|
350
|
+
sendError: field
|
|
351
|
+
? copyTemplate("form.fixField", "Check “{field}” and try again.", { field })
|
|
352
|
+
: copyParam("form.fixFields", "Check the highlighted answers and try again."),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The footer shows a blocked-Next line (not a send failure), which follows the fixes. */
|
|
357
|
+
let showsBlocked = false;
|
|
358
|
+
|
|
359
|
+
/** No footer line (a page change, a clear, a send starting). */
|
|
360
|
+
function noLine(): Partial<S> {
|
|
361
|
+
showsBlocked = false;
|
|
362
|
+
return { noSendError: true, sendError: "" };
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** A field's answer changed: a flagged field is checked again, so its error goes only once the
|
|
366
|
+
* value is valid, and a blocked-Next line names the next field still to fix. */
|
|
367
|
+
function fixed(s: S, target: string): S {
|
|
368
|
+
if (problems[target]) {
|
|
369
|
+
const field = allFields().find((f) => f.target === target);
|
|
370
|
+
const still = field ? localProblems([field], values)[target] : undefined;
|
|
371
|
+
if (still) problems[target] = still; else delete problems[target];
|
|
372
|
+
}
|
|
373
|
+
return view(s, showsBlocked ? blockedLine() : {});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** The forms list opens a form as a modal and says so (`modal: "1"`); a deep link does not, and a page section never is one. */
|
|
377
|
+
function openedAsModal(): boolean {
|
|
378
|
+
if (sectionFormId) return false;
|
|
379
|
+
return (globalThis as { himalaya?: { input?: { modal?: unknown } } }).himalaya?.input?.modal === "1";
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** After a send: close the modal form, and confirm in a dialog over the screen behind it. The
|
|
383
|
+
* dialog is the app's own (`ui.alert`), so it outlives the form; Back only closes it.
|
|
384
|
+
* The close is a host action, not a returned `_nav`: this runs after `finishSend`, which the
|
|
385
|
+
* worker calls itself, and the host reads `_nav` only from an action it dispatched.
|
|
386
|
+
* A binary without the `ui` handler refuses the alert at once, before it answers the next host
|
|
387
|
+
* call, so the form then stays open on its done state rather than closing with no confirmation. */
|
|
388
|
+
async function confirmAndClose(title: string, message: string, success: boolean): Promise<void> {
|
|
389
|
+
let refused = false, closed = false;
|
|
390
|
+
// Back on the dialog: the sheet is gone by then, so the done state goes too, and the form opened
|
|
391
|
+
// again from the list shows its loading state rather than the last "Thank you".
|
|
392
|
+
// A page section goes nowhere after a send: its dialog only closes.
|
|
393
|
+
const confirmLabel = sectionFormId ? copyParam("common.closeCta", "Close") : copyParam("form.doneBackCta", "Back");
|
|
394
|
+
void alert({ title, message, confirmLabel, ...(success ? { icon: "success" as const } : {}) })
|
|
395
|
+
.then(() => { if (closed) void svc.forgetDone(); })
|
|
396
|
+
.catch(() => { refused = true; });
|
|
397
|
+
if (!openedAsModal()) return;
|
|
398
|
+
await dbGet(DRAFTS, loadedInputId || "_").catch(() => null);
|
|
399
|
+
if (!refused) {
|
|
400
|
+
closed = true;
|
|
401
|
+
void dispatch("himi.open", { presentation: "dismiss" }).catch(() => { closed = false; /* the done state stays */ });
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** A send in flight is numbered; a later load or send makes an earlier answer stale. */
|
|
406
|
+
let sendVersion = 0;
|
|
407
|
+
|
|
408
|
+
/** V4 checks first, then its queueable send. Legacy forms use their separate v2 write:
|
|
409
|
+
* no v4 validation or offline queue is implied by resolving a short ID. */
|
|
410
|
+
async function send(version: number, request: SendRequest, legacy: boolean): Promise<void> {
|
|
411
|
+
// The form this send is for: its kept answers go once it is sent, even when another form has
|
|
412
|
+
// loaded since (its finishSend is then stale and does nothing).
|
|
413
|
+
const draftId = loadedInputId, draftPersistent = persistDrafts;
|
|
414
|
+
let outcome: Record<string, unknown>;
|
|
415
|
+
try {
|
|
416
|
+
if (legacy) {
|
|
417
|
+
const sent = await submitLegacyForm({ formId: request.submission.formId,
|
|
418
|
+
fields: Object.entries(request.submission.submissions).map(([key, value]) => ({ key, value: value as string | number | boolean | string[] })) });
|
|
419
|
+
if (!sent.submissionId) throw new Error("The form did not confirm a submission.");
|
|
420
|
+
outcome = { outcome: "sent" };
|
|
421
|
+
} else {
|
|
422
|
+
const check = await validateFormSubmission(request).catch(() => undefined);
|
|
423
|
+
const found = check && check.valid === false ? serverProblems(check) : {};
|
|
424
|
+
if (Object.keys(found).length) outcome = { outcome: "problems", problems: found };
|
|
425
|
+
else {
|
|
426
|
+
const sent = await createSubmission(request, { offline: "queue" });
|
|
427
|
+
outcome = { outcome: sent.status === "queued" ? "queued" : "sent" };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
} catch (err) {
|
|
431
|
+
const found = serverProblems(err);
|
|
432
|
+
outcome = Object.keys(found).length
|
|
433
|
+
? { outcome: "problems", problems: found }
|
|
434
|
+
: { outcome: "failed", error: { code: (err as { code?: unknown })?.code, message: String((err as Error)?.message ?? err) } };
|
|
435
|
+
}
|
|
436
|
+
if (outcome.outcome === "sent" || outcome.outcome === "queued") dropDraft(draftId, draftPersistent);
|
|
437
|
+
await svc.finishSend({ version, ...outcome });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/** The form was sent (or queued): its done state outlives a repeat onAppear load. */
|
|
441
|
+
let completed = false;
|
|
442
|
+
let inflight: Promise<S> | undefined;
|
|
443
|
+
let inflightId = "";
|
|
444
|
+
|
|
445
|
+
/** `knownOwner`: who `load` just read as signed in, so the identity is not read twice. */
|
|
446
|
+
async function loadForm(id: string, knownOwner?: string): Promise<S> {
|
|
447
|
+
form = undefined; loadedInputId = ""; values = {}; page = 0; problems = {}; completed = false; touched = false; generation = 0;
|
|
448
|
+
const version = ++sendVersion;
|
|
449
|
+
const legacy = /^\d+$/.test(id);
|
|
450
|
+
if (!id) return { ...BASE, status: "ready", ...presence("missing") };
|
|
451
|
+
const owner = knownOwner !== undefined ? Promise.resolve(knownOwner) : currentOwner();
|
|
452
|
+
const member = memberDetails(owner);
|
|
453
|
+
// Who is signed in says whether the draft may live in the device database.
|
|
454
|
+
const draft = owner.then((who) => { claimDrafts(who); return readDraft(id, Boolean(who)); });
|
|
455
|
+
try {
|
|
456
|
+
const res = legacy ? await getLegacyFormByShortId(id) : await getForm(id);
|
|
457
|
+
if (version !== sendVersion) return svc.getState();
|
|
458
|
+
const parsed = legacy ? parseLegacyForm(res) : parseForm(res);
|
|
459
|
+
if (!parsed.id || (res as { form?: { enabled?: boolean } }).form?.enabled === false) return { ...BASE, status: "ready", ...presence("missing") };
|
|
460
|
+
const memberInfo = await member;
|
|
461
|
+
if (version !== sendVersion) return svc.getState();
|
|
462
|
+
const saved = await draft;
|
|
463
|
+
if (version !== sendVersion) return svc.getState();
|
|
464
|
+
form = parsed;
|
|
465
|
+
loadedInputId = id;
|
|
466
|
+
loadedOwner = await owner;
|
|
467
|
+
isLegacy = legacy;
|
|
468
|
+
persistDrafts = Boolean(loadedOwner);
|
|
469
|
+
// The visitor's own latest answers first; member details fill only what is still empty.
|
|
470
|
+
const known = new Set(allFields().map((f) => f.target));
|
|
471
|
+
values = Object.fromEntries(Object.entries(saved).filter(([target]) => known.has(target)));
|
|
472
|
+
touched = Object.keys(values).length > 0;
|
|
473
|
+
prefill(memberInfo);
|
|
474
|
+
return view({ ...BASE });
|
|
475
|
+
} catch (err) {
|
|
476
|
+
if (version !== sendVersion) return svc.getState();
|
|
477
|
+
const p = presenceAfterError(err);
|
|
478
|
+
if (p.notFound) return { ...BASE, status: "ready", ...p };
|
|
479
|
+
const offline = classifyLoadError(err) === "offline";
|
|
480
|
+
return { ...BASE, status: "ready", ...p, hideLoadError: true, hideOfflineError: !offline, hideServerError: offline, notErrored: false };
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const svc = defineService<S, {
|
|
485
|
+
load: (s: S, arg?: unknown) => Promise<S>;
|
|
486
|
+
setText: (s: S, arg?: unknown) => S;
|
|
487
|
+
toggleCheck: (s: S, arg?: unknown) => S;
|
|
488
|
+
choose: (s: S, arg?: unknown) => S;
|
|
489
|
+
toggleOption: (s: S, arg?: unknown) => S;
|
|
490
|
+
setDate: (s: S, arg?: unknown) => S;
|
|
491
|
+
clearForm: (s: S) => S;
|
|
492
|
+
close: (s: S) => S;
|
|
493
|
+
next: (s: S) => S;
|
|
494
|
+
finishSend: (s: S, arg?: unknown) => S;
|
|
495
|
+
forgetDone: (s: S) => S;
|
|
496
|
+
back: (s: S) => S;
|
|
497
|
+
openWebsite: (s: S) => Promise<S>;
|
|
498
|
+
}>(serviceName, {
|
|
499
|
+
state: BASE,
|
|
500
|
+
actions: {
|
|
501
|
+
load: async (s, arg) => {
|
|
502
|
+
stashCopy(arg);
|
|
503
|
+
const a = argOf(arg);
|
|
504
|
+
if (typeof a.siteUrl === "string") siteUrl = a.siteUrl.trim();
|
|
505
|
+
const id = inputId();
|
|
506
|
+
// The boot load and the descriptor's onAppear both ask for the same form, and onAppear fires
|
|
507
|
+
// again when the screen comes back (a sheet or the in-app browser closes). The same form id
|
|
508
|
+
// keeps what the visitor typed and the page they are on; only a new id, or a retry after a
|
|
509
|
+
// failure (no form held), starts over.
|
|
510
|
+
// A form already sent keeps its thank-you state: re-opening the editable form would invite
|
|
511
|
+
// a second submission.
|
|
512
|
+
// A form opened again as a modal after its send starts over (the list reuses this worker);
|
|
513
|
+
// only a deep-linked form keeps its done state on a repeat onAppear.
|
|
514
|
+
// A member's form also needs the same member: a page section stays mounted across a sign-out or an account
|
|
515
|
+
// switch, and must not show that member's answers (or the details prefilled from their record) to the next
|
|
516
|
+
// person. Only a confirmed different identity counts; an unread one keeps the form. A visitor's form keeps its
|
|
517
|
+
// answers through a sign-in (nobody else's data is in it), so it reads no identity here.
|
|
518
|
+
const held = Boolean(form && id && loadedInputId === id && !(completed && openedAsModal()));
|
|
519
|
+
const now = held && loadedOwner ? await confirmedOwner() : undefined;
|
|
520
|
+
const otherPerson = now !== undefined && now !== loadedOwner;
|
|
521
|
+
if (held && !otherPerson) return completed ? s : view(s);
|
|
522
|
+
if (inflight && inflightId === id) return inflight;
|
|
523
|
+
inflightId = id;
|
|
524
|
+
const pending = loadForm(id, otherPerson ? now : undefined);
|
|
525
|
+
inflight = pending;
|
|
526
|
+
try { return await pending; } finally { if (inflight === pending) inflight = undefined; }
|
|
527
|
+
},
|
|
528
|
+
// Keystrokes: the value lives in the worker (and its draft); the state changes only to clear
|
|
529
|
+
// an error or to show / hide "Clear form", so typing does not re-render the field list.
|
|
530
|
+
setText: (s, arg) => {
|
|
531
|
+
const a = argOf(arg);
|
|
532
|
+
const target = String(a.target ?? "");
|
|
533
|
+
const text = typeof a.value === "string" ? a.value : typeof a.text === "string" ? a.text : "";
|
|
534
|
+
if (!target) return s;
|
|
535
|
+
const hadAnswers = hasAnswers();
|
|
536
|
+
setValue(target, { text });
|
|
537
|
+
if (!problems[target] && hadAnswers === hasAnswers()) return s;
|
|
538
|
+
return fixed(s, target);
|
|
539
|
+
},
|
|
540
|
+
toggleCheck: (s, arg) => {
|
|
541
|
+
const a = argOf(arg);
|
|
542
|
+
const target = String(a.target ?? "");
|
|
543
|
+
if (!target) return s;
|
|
544
|
+
setValue(target, { checked: typeof a.value === "boolean" ? a.value : !valueOf(target).checked });
|
|
545
|
+
return fixed(s, target);
|
|
546
|
+
},
|
|
547
|
+
choose: (s, arg) => {
|
|
548
|
+
const a = argOf(arg);
|
|
549
|
+
const target = String(a.target ?? ""), value = String(a.option ?? "");
|
|
550
|
+
if (!target || !value) return s;
|
|
551
|
+
setValue(target, { selected: [value] });
|
|
552
|
+
return fixed(s, target);
|
|
553
|
+
},
|
|
554
|
+
toggleOption: (s, arg) => {
|
|
555
|
+
const a = argOf(arg);
|
|
556
|
+
const target = String(a.target ?? ""), value = String(a.option ?? "");
|
|
557
|
+
if (!target || !value) return s;
|
|
558
|
+
const sel = valueOf(target).selected;
|
|
559
|
+
setValue(target, { selected: sel.includes(value) ? sel.filter((x) => x !== value) : [...sel, value] });
|
|
560
|
+
return fixed(s, target);
|
|
561
|
+
},
|
|
562
|
+
// The platform date picker sits in the field itself and reports the picked day (unix seconds).
|
|
563
|
+
// Dismissing it without a choice reports nothing, so the stored date stays as it was. A cleared
|
|
564
|
+
// input (web) reports an empty value, which clears the answer.
|
|
565
|
+
setDate: (s, arg) => {
|
|
566
|
+
const a = argOf(arg);
|
|
567
|
+
const target = String(a.target ?? "");
|
|
568
|
+
if (!target || s.sending) return s;
|
|
569
|
+
if (a.value === "" || a.value === null) {
|
|
570
|
+
setValue(target, { text: "" });
|
|
571
|
+
return fixed(s, target);
|
|
572
|
+
}
|
|
573
|
+
const v = Number(a.value);
|
|
574
|
+
if (!Number.isFinite(v) || v <= 0) return s;
|
|
575
|
+
setValue(target, { text: isoDate(v) });
|
|
576
|
+
return fixed(s, target);
|
|
577
|
+
},
|
|
578
|
+
// Every answer of this form, on every page, and its draft: reopening shows an empty form.
|
|
579
|
+
clearForm: (s) => {
|
|
580
|
+
if (!form || s.sending) return s;
|
|
581
|
+
values = {};
|
|
582
|
+
problems = {};
|
|
583
|
+
touched = false;
|
|
584
|
+
generation += 1;
|
|
585
|
+
dropDraft(loadedInputId);
|
|
586
|
+
return view(s, noLine());
|
|
587
|
+
},
|
|
588
|
+
// The closed-form notice's link: back to the list the modal opened from. A page section has no list
|
|
589
|
+
// to go back to, and must never leave the page it sits on.
|
|
590
|
+
close: (s) => (sectionFormId ? s : navigate(s, { presentation: openedAsModal() ? "dismiss" : "back" })),
|
|
591
|
+
back: (s) => {
|
|
592
|
+
if (page === 0 || s.sending) return s;
|
|
593
|
+
page -= 1;
|
|
594
|
+
return view(s, noLine());
|
|
595
|
+
},
|
|
596
|
+
// "Next" on an earlier page, "Submit" on the last one.
|
|
597
|
+
next: (s) => {
|
|
598
|
+
if (!form || form.unsupported || form.closed || s.sending) return s;
|
|
599
|
+
const local = localProblems(pageFields(), values);
|
|
600
|
+
if (applyProblems(local)) return view(s, blocked());
|
|
601
|
+
if (!lastPage()) { page += 1; problems = {}; return view(s, noLine()); }
|
|
602
|
+
const all = allFields();
|
|
603
|
+
const allLocal = localProblems(all, values);
|
|
604
|
+
if (applyProblems(allLocal)) return view(s, blocked());
|
|
605
|
+
const version = ++sendVersion;
|
|
606
|
+
void send(version, { submission: { formId: form.id, submissions: submissionValues(all, values) } }, isLegacy);
|
|
607
|
+
return { ...s, sending: true, ...noLine() };
|
|
608
|
+
},
|
|
609
|
+
finishSend: (s, arg) => {
|
|
610
|
+
const r = argOf(arg) as { version?: unknown; outcome?: unknown; problems?: unknown; error?: unknown };
|
|
611
|
+
if (r.version !== sendVersion || !form) return s;
|
|
612
|
+
if (r.outcome === "problems") {
|
|
613
|
+
if (applyProblems(r.problems as Record<string, string>)) return view(s, { sending: false, ...blocked() });
|
|
614
|
+
return view(s, { sending: false, noSendError: false, sendError: copyParam("form.checkError", "Some answers can't be sent. Check the form and try again.") });
|
|
615
|
+
}
|
|
616
|
+
if (r.outcome === "failed") return view(s, messageFor(r.error));
|
|
617
|
+
const queued = r.outcome === "queued";
|
|
618
|
+
completed = true;
|
|
619
|
+
dropDraft(loadedInputId);
|
|
620
|
+
const doneTitle = queued ? copyParam("form.queuedTitle", "Form saved") : copyParam("form.sentTitle", "Thank you");
|
|
621
|
+
const doneBody = queued ? copyParam("form.queuedBody", "We'll send your form when you're back online.")
|
|
622
|
+
: copyParam("form.sentBody", "Your answer was submitted successfully.");
|
|
623
|
+
void confirmAndClose(doneTitle, doneBody, !queued);
|
|
624
|
+
// The done state is what shows when the form cannot close (a deep link or a page section, not a modal) or
|
|
625
|
+
// the app has no dialog: never the editable form again.
|
|
626
|
+
return view(s, {
|
|
627
|
+
sending: false, hideForm: true, hideFooterSingle: true, hideFooterFirst: true, hideFooterMiddle: true,
|
|
628
|
+
hideFooterLast: true, hideClear: true, hideDone: false, rows: [], noPageCaption: true, doneTitle, doneBody,
|
|
629
|
+
});
|
|
630
|
+
},
|
|
631
|
+
// The modal form closed after its send (see confirmAndClose).
|
|
632
|
+
forgetDone: (s) => (completed && openedAsModal() ? { ...BASE } : s),
|
|
633
|
+
openWebsite: async (s) => {
|
|
634
|
+
if (siteUrl) { try { await openUrl(siteUrl, "in_app_browser"); } catch { /* the handoff is best-effort */ } }
|
|
635
|
+
return s;
|
|
636
|
+
},
|
|
637
|
+
},
|
|
638
|
+
});
|
|
639
|
+
return svc;
|
|
640
|
+
}
|