@bettercms-ai/next 0.38.0 → 0.40.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/README.md CHANGED
@@ -64,10 +64,8 @@ are only a convention. The package reads env in two places:
64
64
  | `BETTERCMS_PREVIEW` | `getContent()` | `1` reads live instead of `bcms-content.json` (preview builds) |
65
65
 
66
66
  **Revalidation secret.** The value is the project's revalidation webhook secret (Project →
67
- Settings). The dashboard tells you to store it as `BETTERCMS_WEBHOOK_SECRET`, and that is the
68
- value `createRevalidateRoute({ secret })` needs. `BCMS_REVALIDATE_SECRET` in the route's source
69
- comment is the same value under another name. Without `secret` the route accepts unsigned
70
- requests, so always pass it.
67
+ Settings → Revalidation). Store it as `BCMS_REVALIDATE_SECRET`: `createRevalidateRoute()` reads
68
+ that when no `secret` is passed. Without either, the route accepts unsigned requests.
71
69
 
72
70
  **BetterCMS-generated deploy workflow** (connected repo). The repo secret is `BCMS_API_KEY`
73
71
  (given only to the content-fetch step, never to the build) and the workspace is the repo
@@ -319,6 +317,37 @@ function of its own passes it in: `sectionsStaticProps("home", pageStaticProps)`
319
317
  `sectionsServerSideProps`) calls it and adds `bcmsSections` to the props it answers.
320
318
  `npx @bettercms-ai/convert --sections` writes this wrap for you.
321
319
 
320
+ ### File fields (attachments)
321
+
322
+ Needs `@bettercms-ai/next` 0.40.0 and `@bettercms-ai/sdk` 1.43.0 or later; an older version
323
+ draws a text box, and the server treats what is typed there as no file.
324
+
325
+ A `file` field renders a native file picker. Each pick uploads at once (one request per file); the
326
+ submission carries the stored files' ids, and Submit waits while a file is on its way. A field that
327
+ takes one file replaces it on the next pick.
328
+
329
+ | Class | Element |
330
+ |---|---|
331
+ | `bcms-field--file` | the field's wrapper (beside `bcms-field`) |
332
+ | `bcms-file-list` | the list of attached files |
333
+ | `bcms-file-name` | a file's name, as text |
334
+ | `bcms-file-remove` | its Remove button |
335
+ | `bcms-file-pending` | "Uploading…", while a file is on its way |
336
+
337
+ A refused file shows the server's sentence in a `bcms-field-error`.
338
+
339
+ Two things to know before you style it:
340
+
341
+ - **Never hide the native file input with `display:none`.** The field's validity ("Please attach a
342
+ file.", "Please wait: a file is still uploading.") lives on that input, and a hidden invalid
343
+ control blocks the submit with no message. Style its label or a wrapper instead.
344
+ - **Not included:** files are not scanned (a `zip` is stored as sent), there is no upload without
345
+ JavaScript, and a visitor cannot delete an upload (one never submitted is removed after 24 hours).
346
+
347
+ Files are private to the workspace: the owner's email, a Sheet and a CRM get the file names and a
348
+ dashboard link; a webhook gets the names only. Limits and refusals: the BetterCMS skill's
349
+ `references/forms-and-interactions.md`.
350
+
322
351
  ### Phone fields with a country code picker
323
352
 
324
353
  A phone field whose author enabled **Country code picker** in the builder renders a country
package/dist/blocks.js CHANGED
@@ -21,10 +21,29 @@ import {
21
21
  shouldShowField,
22
22
  formInitialValues,
23
23
  asStringArray,
24
- toggleOption
24
+ toggleOption,
25
+ uploadFormFile,
26
+ fileFieldLimits,
27
+ fileFieldRefusal
25
28
  } from "@bettercms-ai/sdk/read";
26
29
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
27
30
  var TURNSTILE_SRC = "https://challenges.cloudflare.com/turnstile/v0/api.js";
31
+ function planFilePick(limits, stored, picked) {
32
+ const take = limits.maxFiles === 1 ? picked.slice(0, 1) : [...picked];
33
+ if (limits.maxFiles > 1 && stored + take.length > limits.maxFiles) {
34
+ return { refusal: `You can attach at most ${limits.maxFiles} files.` };
35
+ }
36
+ for (const file of take) {
37
+ const refusal = fileFieldRefusal(limits, file);
38
+ if (refusal) return { refusal };
39
+ }
40
+ return { take, replace: limits.maxFiles === 1 };
41
+ }
42
+ function fileFieldValidity(required, stored, uploading) {
43
+ if (uploading) return "Please wait: a file is still uploading.";
44
+ if (required && stored === 0) return "Please attach a file.";
45
+ return "";
46
+ }
28
47
  var HONEYPOT_STYLE = {
29
48
  position: "absolute",
30
49
  width: "1px",
@@ -89,6 +108,80 @@ function BcmsForm({
89
108
  });
90
109
  const [status, setStatus] = useState({ state: "idle" });
91
110
  const [fieldErrors, setFieldErrors] = useState({});
111
+ const [files, setFiles] = useState({});
112
+ const [uploading, setUploading] = useState({});
113
+ const [fileNotes, setFileNotes] = useState({});
114
+ const fileInputs = useRef({});
115
+ const uploadQueue = useRef(Promise.resolve());
116
+ const pickTurn = useRef({});
117
+ const anyUploading = Object.values(uploading).some((n) => n > 0);
118
+ useEffect(() => {
119
+ for (const field of form.fields) {
120
+ if (field.type !== "file") continue;
121
+ fileInputs.current[field.key]?.setCustomValidity(
122
+ fileFieldValidity(field.required, files[field.key]?.length ?? 0, (uploading[field.key] ?? 0) > 0)
123
+ );
124
+ }
125
+ });
126
+ function pickFiles(field, picked) {
127
+ const key = field.key;
128
+ const plan = planFilePick(fileFieldLimits(field), (files[key]?.length ?? 0) + (uploading[key] ?? 0), picked);
129
+ if ("refusal" in plan) {
130
+ setFileNotes((n) => ({ ...n, [key]: plan.refusal }));
131
+ return;
132
+ }
133
+ if (plan.take.length === 0) return;
134
+ setFileNotes((n) => ({ ...n, [key]: "" }));
135
+ const turn = pickTurn.current[key] = (pickTurn.current[key] ?? 0) + 1;
136
+ setUploading((u) => ({ ...u, [key]: (u[key] ?? 0) + plan.take.length }));
137
+ for (const file of plan.take) {
138
+ uploadQueue.current = uploadQueue.current.then(async () => {
139
+ try {
140
+ if (plan.replace && pickTurn.current[key] !== turn) return;
141
+ const stored = await uploadFormFile({ formId: form.id, fieldKey: key, file, baseUrl: apiBase });
142
+ setFiles((f) => ({ ...f, [key]: plan.replace ? [stored] : [...f[key] ?? [], stored] }));
143
+ } catch (err) {
144
+ const message = err instanceof Error && err.message ? err.message : "This file could not be uploaded. Please try again.";
145
+ setFileNotes((n) => ({ ...n, [key]: message }));
146
+ } finally {
147
+ setUploading((u) => ({ ...u, [key]: Math.max(0, (u[key] ?? 1) - 1) }));
148
+ }
149
+ });
150
+ }
151
+ }
152
+ function removeFile(key, id) {
153
+ setFiles((f) => ({ ...f, [key]: (f[key] ?? []).filter((x) => x.id !== id) }));
154
+ }
155
+ function renderField(field) {
156
+ if (field.type === "file") {
157
+ return /* @__PURE__ */ jsx(
158
+ FileField,
159
+ {
160
+ field,
161
+ stored: files[field.key] ?? [],
162
+ uploading: (uploading[field.key] ?? 0) > 0,
163
+ note: fileNotes[field.key],
164
+ error: fieldErrors[field.key],
165
+ inputRef: (el) => {
166
+ fileInputs.current[field.key] = el;
167
+ },
168
+ onPick: (picked) => pickFiles(field, picked),
169
+ onRemove: (id) => removeFile(field.key, id)
170
+ },
171
+ field.key
172
+ );
173
+ }
174
+ return /* @__PURE__ */ jsx(
175
+ Field,
176
+ {
177
+ field,
178
+ value: values[field.key],
179
+ error: fieldErrors[field.key],
180
+ onChange: (v) => setValue(field.key, v)
181
+ },
182
+ field.key
183
+ );
184
+ }
92
185
  const pages = useMemo(() => splitSteps(form.fields), [form.fields]);
93
186
  const [enhanced, setEnhanced] = useState(false);
94
187
  const [step, setStep] = useState(0);
@@ -140,6 +233,10 @@ function BcmsForm({
140
233
  async function handleSubmit(e) {
141
234
  e.preventDefault();
142
235
  if (paged && step < last) return next();
236
+ if (anyUploading) {
237
+ setStatus({ state: "error", message: "Please wait: a file is still uploading." });
238
+ return;
239
+ }
143
240
  setStatus({ state: "submitting" });
144
241
  setFieldErrors({});
145
242
  const tokenEl = e.currentTarget.querySelector(
@@ -150,7 +247,7 @@ function BcmsForm({
150
247
  for (const field of form.fields) {
151
248
  if (field.type === "step") continue;
152
249
  if (field.type === "hidden" || shouldShowField(field, values)) {
153
- data[field.key] = values[field.key];
250
+ data[field.key] = field.type === "file" ? (files[field.key] ?? []).map((f) => f.id) : values[field.key];
154
251
  }
155
252
  }
156
253
  if (form.honeypotField) data[form.honeypotField] = values[form.honeypotField] ?? "";
@@ -166,6 +263,8 @@ function BcmsForm({
166
263
  const reset = formInitialValues(form);
167
264
  if (form.honeypotField) reset[form.honeypotField] = "";
168
265
  setValues(reset);
266
+ setFiles({});
267
+ setFileNotes({});
169
268
  setStep(0);
170
269
  setStatus({
171
270
  state: "success",
@@ -223,16 +322,7 @@ function BcmsForm({
223
322
  ]
224
323
  }
225
324
  ),
226
- visibleFields.filter((f) => page.fields.includes(f)).map((field) => /* @__PURE__ */ jsx(
227
- Field,
228
- {
229
- field,
230
- value: values[field.key],
231
- error: fieldErrors[field.key],
232
- onChange: (v) => setValue(field.key, v)
233
- },
234
- field.key
235
- )),
325
+ visibleFields.filter((f) => page.fields.includes(f)).map(renderField),
236
326
  paged ? /* @__PURE__ */ jsxs("div", { className: "bcms-step-nav", children: [
237
327
  i > 0 ? /* @__PURE__ */ jsx("button", { type: "button", "data-bcms-step-back": true, onClick: () => goTo(i - 1), children: "Back" }) : null,
238
328
  i < last ? /* @__PURE__ */ jsx("button", { type: "button", "data-bcms-step-next": true, onClick: next, children: "Next" }) : null
@@ -240,16 +330,7 @@ function BcmsForm({
240
330
  ]
241
331
  },
242
332
  page.key ?? "first"
243
- )) : visibleFields.map((field) => /* @__PURE__ */ jsx(
244
- Field,
245
- {
246
- field,
247
- value: values[field.key],
248
- error: fieldErrors[field.key],
249
- onChange: (v) => setValue(field.key, v)
250
- },
251
- field.key
252
- )),
333
+ )) : visibleFields.map(renderField),
253
334
  form.honeypotField ? /* @__PURE__ */ jsx("span", { "aria-hidden": "true", style: { position: "absolute", left: "-9999px" }, children: /* @__PURE__ */ jsx(
254
335
  "input",
255
336
  {
@@ -268,7 +349,7 @@ function BcmsForm({
268
349
  {
269
350
  type: "submit",
270
351
  hidden: paged && step < last,
271
- disabled: status.state === "submitting",
352
+ disabled: status.state === "submitting" || anyUploading,
272
353
  "data-bcms-form-part": "submit",
273
354
  children: status.state === "submitting" ? "Submitting\u2026" : form.submitLabel ?? "Submit"
274
355
  }
@@ -285,6 +366,41 @@ function BcmsForm({
285
366
  ] })
286
367
  );
287
368
  }
369
+ function FileField({ field, stored, uploading, note, error, inputRef, onPick, onRemove }) {
370
+ const limits = fileFieldLimits(field);
371
+ const id = `bcms-f-${field.key}`;
372
+ return /* @__PURE__ */ jsxs("p", { className: "bcms-field bcms-field--file", "data-field": field.key, "data-bcms-form-field": field.key, children: [
373
+ /* @__PURE__ */ jsxs("label", { htmlFor: id, "data-bcms-form-part": "label", children: [
374
+ field.label,
375
+ field.required ? " *" : ""
376
+ ] }),
377
+ /* @__PURE__ */ jsx("br", {}),
378
+ /* @__PURE__ */ jsx(
379
+ "input",
380
+ {
381
+ type: "file",
382
+ id,
383
+ ref: inputRef,
384
+ accept: limits.accept.map((e) => `.${e}`).join(","),
385
+ multiple: limits.maxFiles > 1,
386
+ onChange: (e) => {
387
+ const picked = Array.from(e.target.files ?? []);
388
+ e.target.value = "";
389
+ onPick(picked);
390
+ }
391
+ }
392
+ ),
393
+ stored.length > 0 ? /* @__PURE__ */ jsx("ul", { className: "bcms-file-list", children: stored.map((file) => /* @__PURE__ */ jsxs("li", { children: [
394
+ /* @__PURE__ */ jsx("span", { className: "bcms-file-name", children: file.name }),
395
+ " ",
396
+ /* @__PURE__ */ jsx("button", { type: "button", className: "bcms-file-remove", "aria-label": `Remove ${file.name}`, onClick: () => onRemove(file.id), children: "Remove" })
397
+ ] }, file.id)) }) : null,
398
+ uploading ? /* @__PURE__ */ jsx("span", { className: "bcms-file-pending", "aria-live": "polite", children: "Uploading\u2026" }) : null,
399
+ note ? /* @__PURE__ */ jsx("span", { className: "bcms-field-error", "aria-live": "polite", children: note }) : null,
400
+ field.helpText ? /* @__PURE__ */ jsx("span", { className: "bcms-field-help", "data-bcms-form-part": "help", children: field.helpText }) : null,
401
+ error ? /* @__PURE__ */ jsx("span", { className: "bcms-field-error", role: "alert", children: error }) : null
402
+ ] });
403
+ }
288
404
  function Field({ field, value, error, onChange }) {
289
405
  const required = field.required;
290
406
  const errorNode = error ? /* @__PURE__ */ jsx("span", { className: "bcms-field-error", role: "alert", children: error }) : null;