File size: 11,452 Bytes
149aa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
816fa8a
149aa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
 
149aa87
 
 
 
 
 
 
 
 
 
971c29d
 
149aa87
 
971c29d
149aa87
 
 
 
971c29d
 
 
 
 
149aa87
 
 
 
 
971c29d
149aa87
 
 
971c29d
149aa87
971c29d
 
 
 
149aa87
 
 
 
 
 
971c29d
 
 
 
149aa87
 
971c29d
 
149aa87
 
 
 
 
 
 
 
 
 
 
971c29d
 
149aa87
 
 
 
971c29d
149aa87
 
971c29d
149aa87
971c29d
149aa87
 
 
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149aa87
971c29d
 
 
 
 
 
149aa87
 
 
 
816fa8a
 
 
 
149aa87
 
 
971c29d
149aa87
816fa8a
 
 
971c29d
 
 
149aa87
 
 
 
 
 
816fa8a
 
 
971c29d
 
 
 
 
 
 
 
 
 
 
 
 
149aa87
 
 
 
 
 
 
816fa8a
 
 
149aa87
971c29d
149aa87
 
 
 
 
 
 
971c29d
149aa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
149aa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
971c29d
149aa87
 
 
 
971c29d
149aa87
 
 
 
 
971c29d
 
149aa87
 
971c29d
 
149aa87
 
 
 
 
 
971c29d
149aa87
 
 
 
 
 
 
 
 
 
 
971c29d
149aa87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// ---------------------------------------------------------------------------
// forms / FormPublic.tsx — ⭐ wave-23 item 8 (contract W23-C9).
//
// The page an ANONYMOUS person lands on at `#/form/<token>`. E mounts it in the
// Shell BEFORE the auth wall (wiring W23-W2); everything below assumes there is
// no session, no workspace, no nav and no viewer.
//
// ⛔ IT IMPORTS NOTHING FROM `customer-grid/**`, AND THAT IS A REQUIREMENT, NOT
// A PREFERENCE. The grid bundle drags glide-data-grid — hundreds of kilobytes
// of canvas table — into whatever chunk touches it, and this page is the one
// surface in the product that a stranger loads cold, once, probably on a phone,
// probably on mobile data, to type four answers. One convenience import from
// `types.ts` would put the whole spreadsheet engine on that wire. So the field
// vocabulary below is DECLARED HERE as plain strings rather than imported: the
// server sends `type` as a string and this page renders a control per string,
// which is the same "no client union over a server vocabulary" rule the rest of
// the wave follows, arriving here for a second reason.
//
// ⚠ Styling reuses `.lpf-*` rules in the D REGION of index.css — the shell's
// stylesheet is one file and already loaded; a second stylesheet for one page
// would be a second copy of the tokens.
// ---------------------------------------------------------------------------

import { useEffect, useRef, useState } from "react";
import { Brand } from "../shell/Brand";

/** One field, exactly as `routes_forms._public_form` builds it. Nothing here is
 *  optional-because-maybe: every key below is one the server always sends, and
 *  the three that are conditional say so. */
interface FormField {
  key: string;
  label: string;
  /** The server's own word. Deliberately `string`, not a union — an unknown
   *  type lands on the text input, which is the safe direction: a person can
   *  always type an answer, and a control this page has never heard of would
   *  otherwise render as nothing at all. */
  type: string;
  required: boolean;
  options?: string[];
  max?: number;
  secret?: boolean;
  hint?: string;
}

interface FormSpec {
  title: string;
  desc: string;
  submitLabel: string;
  fields: FormField[];
  /** The honeypot's field name — planted, never shown. Server-named so the two
   *  halves cannot drift into a trap nobody checks. */
  honeypot: string;
  kind?: string;
  singleUse?: boolean;
}

type Phase = "loading" | "ready" | "sent" | "gone" | "failed" | "unavailable";

const LONG_TEXT_MIN = 0;   // every text field gets a textarea when it is the only one

export default function FormPublic({ token }: { token: string }) {
  // Changing capabilities unmounts the old inputs and destroys all typed values.
  return <PublicForm key={token} token={token} />;
}

function PublicForm({ token }: { token: string }) {
  const [spec, setSpec] = useState<FormSpec | null>(null);
  const [phase, setPhase] = useState<Phase>("loading");
  const [values, setValues] = useState<Record<string, string>>({});
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const post = useRef<AbortController | null>(null);

  useEffect(() => {
    let live = true;
    const controller = new AbortController();
    setPhase("loading");
    setSpec(null);
    setValues({});
    setError("");
    fetch(`/api/v1/forms/${encodeURIComponent(token)}`, { signal: controller.signal })
      .then((r) => (r.ok ? r.json() : Promise.reject(new Error(String(r.status)))))
      .then((data: FormSpec) => {
        if (!live) return;
        setSpec(data);
        setPhase("ready");
      })
      // Invalid capabilities share one expired state; a transport failure proves no expiry.
      .catch((failure: unknown) => {
        if (live) setPhase(failure instanceof Error && failure.message === "403" ? "gone" : "unavailable");
      });
    return () => {
      live = false;
      controller.abort();
      post.current?.abort();
    };
  }, [token]);

  const set = (key: string, v: string) =>
    setValues((prev) => ({ ...prev, [key]: v }));

  const submit = (event: React.FormEvent) => {
    event.preventDefault();
    if (busy) return;
    setBusy(true);
    setError("");
    const controller = new AbortController();
    post.current = controller;
    fetch(`/api/v1/forms/${encodeURIComponent(token)}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ values }),
      signal: controller.signal,
    })
      .then(async (r) => {
        if (controller.signal.aborted) return;
        if (r.ok) {
          setValues({});
          setPhase("sent");
          return;
        }
        const body = await r.json().catch(() => null);
        if (controller.signal.aborted) return;
        if (body?.error?.code === "data_input_frozen") {
          setError(String(body.error.message));
        } else if (!spec?.singleUse) {
          setError(String(body?.error?.message || "That could not be sent; check your answers and try again."));
        } else if (r.status === 403) {
          setPhase("gone");
        } else if (body?.error?.code === "setup_write_failed") {
          setPhase("failed");
        } else {
          setError(r.status === 400 ? "Invalid fields" : r.status === 429 ? "Busy" : "Not sent");
        }
      })
      .catch(() => {
        if (!controller.signal.aborted) setError(spec?.singleUse ? "Not sent" : "That could not be sent; check your connection and try again.");
      })
      .finally(() => {
        if (controller.signal.aborted) return;
        if (spec?.singleUse) setValues({});
        setBusy(false);
        post.current = null;
      });
  };

  if (phase === "loading")
    return (
      <div className="lpf-page signed-out">
        <div className="lpf-card signed-out-panel" role="status" aria-label="Loading form">
          <Brand size={44} className="signed-out-brand" />
        </div>
      </div>
    );

  if (phase === "gone" || phase === "failed" || phase === "unavailable")
    return (
      <div className="lpf-page signed-out">
        <div className="lpf-card signed-out-panel">
          <Brand size={44} className="signed-out-brand" />
          <h1 className="lpf-title">
            {phase === "failed" ? "Save failed" : phase === "unavailable" ? "Unavailable" : "Expired"}
          </h1>
        </div>
      </div>
    );

  if (phase === "sent")
    return (
      <div className="lpf-page signed-out">
        <div className="lpf-card signed-out-panel">
          <Brand size={44} className="signed-out-brand" />
          <h1 className="lpf-title">{spec?.singleUse ? "Saved" : "Submitted"}</h1>
          {!spec?.singleUse && (
            <button
              type="button"
              className="lpf-btn"
              onClick={() => {
                setValues({});
                setPhase("ready");
              }}
            >
              Submit another
            </button>
          )}
        </div>
      </div>
    );

  if (!spec) return null;

  return (
    <div className="lpf-page signed-out">
      <form className="lpf-card signed-out-panel" onSubmit={submit}>
        <Brand size={44} className="signed-out-brand" />
        <h1 className="lpf-title">{spec.title || "Form"}</h1>
        {!spec.singleUse && spec.desc && <p className="lpf-desc">{spec.desc}</p>}

        {spec.fields.map((f) => (
          <label key={f.key} className="lpf-field">
            <span className="lpf-label">
              {f.label}
              {f.required && <span className="lpf-req" aria-hidden> *</span>}
            </span>
            <FieldControl field={f} value={values[f.key] ?? ""} onChange={set} disabled={busy} />
          </label>
        ))}

        {/* ⛔ THE HONEYPOT. Off-screen rather than `display:none` — several bot frameworks skip
            hidden inputs on purpose, and a trap they know to skip is not a trap. `tabIndex={-1}`
            and `aria-hidden` keep it away from a keyboard user and a screen reader alike, and
            `autoComplete="off"` stops a browser filling it for a real person, which would
            silently drop their submission. */}
        <input
          className="lpf-hp"
          type="text"
          name={spec.honeypot}
          value={values[spec.honeypot] ?? ""}
          onChange={(e) => set(spec.honeypot, e.target.value)}
          tabIndex={-1}
          autoComplete="off"
          aria-hidden
        />

        {error && <p className="lpf-err" role="alert">{error}</p>}
        <button type="submit" className="lpf-btn lpf-btn--primary" disabled={busy}>
          {busy ? "Sending…" : spec.submitLabel || "Submit"}
        </button>
      </form>
    </div>
  );
}

/** One control per server type string. An unrecognised type falls through to text — see the
 *  `FormField.type` note: a stranger can always type an answer, and a blank where a control
 *  should be is the one failure they cannot work around. */
function FieldControl({
  field,
  value,
  onChange,
  disabled,
}: {
  field: FormField;
  value: string;
  onChange: (key: string, v: string) => void;
  disabled: boolean;
}) {
  const common = {
    className: "lpf-input",
    value,
    required: field.required,
    disabled,
    title: field.hint,
    onChange: (e: { target: { value: string } }) => onChange(field.key, e.target.value),
  };
  if (field.secret || field.type === "password")
    return <input {...common} type="password" autoComplete="new-password" spellCheck={false} />;
  switch (field.type) {
    case "checkbox":
      return (
        <input
          type="checkbox"
          className="lpf-check"
          disabled={disabled}
          checked={value === "1"}
          onChange={(e) => onChange(field.key, e.target.checked ? "1" : "")}
        />
      );
    case "select":
    case "status":
      return (
        <select {...common} className="lpf-input lpf-select">
          {/* An explicit empty option, always. A `<select>` with no blank member has its first
              choice pre-selected, so an untouched optional field silently submits a value the
              person never picked. */}
          <option value="">{field.required ? "Choose…" : "None"}</option>
          {(field.options ?? []).map((o) => (
            <option key={o} value={o}>{o}</option>
          ))}
        </select>
      );
    case "int":
    case "currency":
    case "pct":
    case "rating":
      return <input {...common} type="number" inputMode="decimal" />;
    case "date":
      // ⚠ `type="date"` submits ISO (`YYYY-MM-DD`) whatever the browser DISPLAYS, which is
      // exactly what the server's refuse-never-coerce date check demands. A text input here
      // would send whatever the locale suggested and be refused on half the planet.
      return <input {...common} type="date" />;
    case "email":
      return <input {...common} type="email" inputMode="email" />;
    case "phone":
      return <input {...common} type="tel" inputMode="tel" />;
    case "url":
      return <input {...common} type="url" inputMode="url" />;
    case "text":
      return (
        <textarea
          {...common}
          className="lpf-input lpf-textarea"
          rows={value.length > 60 ? 4 : 2}
          minLength={LONG_TEXT_MIN}
        />
      );
    default:
      return <input {...common} type="text" />;
  }
}