@10x-media/form-builder 0.1.0-beta.8 → 4.0.0-alpha.1
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/CHANGELOG.md +185 -0
- package/README.md +11 -3
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/body/serializeBody.d.ts +16 -14
- package/dist/actions/body/serializeBody.js +5 -8
- package/dist/actions/body/serializeBody.js.map +1 -1
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +15 -3
- package/dist/actions/builtin/emailAction.js +72 -20
- package/dist/actions/builtin/emailAction.js.map +1 -1
- package/dist/actions/builtin/emailTeam.js +11 -5
- package/dist/actions/builtin/emailTeam.js.map +1 -1
- package/dist/actions/defineAction.d.ts +37 -6
- package/dist/actions/defineAction.js +14 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.d.ts +12 -0
- package/dist/actions/dispatch.js +103 -30
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/dispatchContext.js +19 -0
- package/dist/actions/dispatchContext.js.map +1 -0
- package/dist/actions/emailRecipients.js +38 -8
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/emailRender.d.ts +27 -0
- package/dist/actions/fromAddresses.d.ts +19 -1
- package/dist/actions/fromAddresses.js +66 -9
- package/dist/actions/fromAddresses.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +23 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/registry.js +3 -1
- package/dist/actions/registry.js.map +1 -1
- package/dist/actions/runActions.d.ts +2 -0
- package/dist/actions/runActions.js +13 -8
- package/dist/actions/runActions.js.map +1 -1
- package/dist/actions/sign.js.map +1 -1
- package/dist/actions/submissionContext.d.ts +34 -0
- package/dist/actions/task.js +43 -16
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/aggregateResponses.js +3 -4
- package/dist/aggregation/aggregateResponses.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +69 -26
- package/dist/aggregation/resolveResultsRequest.js.map +1 -1
- package/dist/calc/computeCalcFields.d.ts +5 -3
- package/dist/calc/computeCalcFields.js +4 -3
- package/dist/calc/computeCalcFields.js.map +1 -1
- package/dist/calc/evaluate.d.ts +26 -3
- package/dist/calc/evaluate.js +33 -11
- package/dist/calc/evaluate.js.map +1 -1
- package/dist/calc/formatCalc.d.ts +11 -0
- package/dist/calc/formatCalc.js +35 -0
- package/dist/calc/formatCalc.js.map +1 -0
- package/dist/calc/formatCalcValue.d.ts +17 -0
- package/dist/calc/formatCalcValue.js +17 -0
- package/dist/calc/formatCalcValue.js.map +1 -0
- package/dist/calc/normalizeCalc.d.ts +17 -3
- package/dist/calc/normalizeCalc.js +39 -17
- package/dist/calc/normalizeCalc.js.map +1 -1
- package/dist/calc/registry.d.ts +43 -0
- package/dist/calc/registry.js +27 -0
- package/dist/calc/registry.js.map +1 -0
- package/dist/calc/resolveCalcContext.d.ts +36 -0
- package/dist/calc/resolveCalcContext.js +87 -0
- package/dist/calc/resolveCalcContext.js.map +1 -0
- package/dist/calc/types.d.ts +19 -4
- package/dist/calc/types.js +3 -2
- package/dist/calc/types.js.map +1 -1
- package/dist/client/ByteSizeField.js +11 -8
- package/dist/client/ByteSizeField.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +888 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/ClosePollButton.js +3 -3
- package/dist/client/ClosePollButton.js.map +1 -1
- package/dist/client/CondensedArray.d.ts +2 -2
- package/dist/client/CondensedArray.js +5 -7
- package/dist/client/CondensedArray.js.map +1 -1
- package/dist/client/ConditionBuilder.js +5 -7
- package/dist/client/ConditionBuilder.js.map +1 -1
- package/dist/client/ConditionRow.js +3 -3
- package/dist/client/ConditionRow.js.map +1 -1
- package/dist/client/ConsentBlockLabel.js +2 -2
- package/dist/client/ConsentBlockLabel.js.map +1 -1
- package/dist/client/ConsentRetentionNotice.d.ts +11 -0
- package/dist/client/ConsentRetentionNotice.js +23 -0
- package/dist/client/ConsentRetentionNotice.js.map +1 -0
- package/dist/client/EndpointOptionsSelect.d.ts +17 -7
- package/dist/client/EndpointOptionsSelect.js +18 -14
- package/dist/client/EndpointOptionsSelect.js.map +1 -1
- package/dist/client/FieldBlockLabel.js +2 -2
- package/dist/client/FieldBlockLabel.js.map +1 -1
- package/dist/client/FieldNameSelect.d.ts +1 -0
- package/dist/client/FieldNameSelect.js +2 -4
- package/dist/client/FieldNameSelect.js.map +1 -1
- package/dist/client/FlowBuilder.js +31 -23
- package/dist/client/FlowBuilder.js.map +1 -1
- package/dist/client/FormConditionField.js +0 -1
- package/dist/client/FormConditionField.js.map +1 -1
- package/dist/client/RecipientsSelect.d.ts +9 -2
- package/dist/client/RecipientsSelect.js +31 -10
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +345 -72
- package/dist/client/endpointOptions.d.ts +11 -0
- package/dist/client/endpointOptions.js +17 -8
- package/dist/client/endpointOptions.js.map +1 -1
- package/dist/collections/formSubmissions.js +145 -51
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +170 -65
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +31 -26
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +32 -0
- package/dist/collections/settingsFields.js +55 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/consent/captureConsent.d.ts +2 -1
- package/dist/consent/captureConsent.js +4 -1
- package/dist/consent/captureConsent.js.map +1 -1
- package/dist/consent/consentSourcesField.d.ts +7 -1
- package/dist/consent/consentSourcesField.js +15 -1
- package/dist/consent/consentSourcesField.js.map +1 -1
- package/dist/consent/effectiveStatement.js +16 -0
- package/dist/consent/effectiveStatement.js.map +1 -0
- package/dist/consent/resolveConsentSourcesRequest.js +2 -2
- package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
- package/dist/consent/resolveConsentStatements.js +3 -1
- package/dist/consent/resolveConsentStatements.js.map +1 -1
- package/dist/consent/resolvePublishedVersionRef.js +1 -0
- package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
- package/dist/consent/types.d.ts +8 -0
- package/dist/context/formContext.d.ts +30 -0
- package/dist/context/formContext.js +54 -0
- package/dist/context/formContext.js.map +1 -0
- package/dist/email/departmentsField.d.ts +6 -1
- package/dist/email/departmentsField.js +6 -1
- package/dist/email/departmentsField.js.map +1 -1
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/i18n.d.ts +14 -2
- package/dist/exports/i18n.js +14 -2
- package/dist/exports/react.d.ts +23 -5
- package/dist/exports/react.js +17 -1
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +7 -4
- package/dist/exports/types.d.ts +4 -3
- package/dist/fields/buildFieldBlocks.js +2 -1
- package/dist/fields/buildFieldBlocks.js.map +1 -1
- package/dist/fields/builtin/calculation.d.ts +17 -0
- package/dist/fields/builtin/calculation.js +70 -127
- package/dist/fields/builtin/calculation.js.map +1 -1
- package/dist/fields/builtin/checkbox.js +15 -0
- package/dist/fields/builtin/checkbox.js.map +1 -1
- package/dist/fields/builtin/consent.js +21 -1
- package/dist/fields/builtin/consent.js.map +1 -1
- package/dist/fields/builtin/email.js +7 -0
- package/dist/fields/builtin/email.js.map +1 -1
- package/dist/fields/builtin/index.d.ts +6 -2
- package/dist/fields/builtin/index.js +9 -4
- package/dist/fields/builtin/index.js.map +1 -1
- package/dist/fields/builtin/select.js +20 -1
- package/dist/fields/builtin/select.js.map +1 -1
- package/dist/fields/builtin/text.js +7 -0
- package/dist/fields/builtin/text.js.map +1 -1
- package/dist/fields/instanceOptions.js +1 -1
- package/dist/fields/instanceOptions.js.map +1 -1
- package/dist/fields/sharedConfig.js +15 -11
- package/dist/fields/sharedConfig.js.map +1 -1
- package/dist/fields/types.d.ts +8 -2
- package/dist/form/findFormAtLocale.d.ts +30 -0
- package/dist/form/findFormAtLocale.js +88 -0
- package/dist/form/findFormAtLocale.js.map +1 -0
- package/dist/form/pollState.d.ts +2 -1
- package/dist/form/pollState.js.map +1 -1
- package/dist/form/toFormDocument.d.ts +8 -0
- package/dist/form/toFormDocument.js +3 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +9 -1
- package/dist/index.d.ts +22 -6
- package/dist/index.js +63 -17
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +113 -4
- package/dist/plugin/collectionSlugs.d.ts +28 -0
- package/dist/plugin/collectionSlugs.js +65 -0
- package/dist/plugin/collectionSlugs.js.map +1 -0
- package/dist/plugin/customState.js +1 -1
- package/dist/plugin/customState.js.map +1 -1
- package/dist/plugin/registerCollections.js +38 -21
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +13 -10
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/outcomeBeforeChange.js +2 -2
- package/dist/poll/outcomeBeforeChange.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +5 -4
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOptionsRequest.js +2 -2
- package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +20 -6
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +55 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/answerValues.js +16 -0
- package/dist/poll/votes/answerValues.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +91 -0
- package/dist/poll/votes/bumpPollVote.js.map +1 -0
- package/dist/poll/votes/recountPollVotes.d.ts +20 -0
- package/dist/poll/votes/recountPollVotes.js +63 -0
- package/dist/poll/votes/recountPollVotes.js.map +1 -0
- package/dist/poll/votes/voteTallyHook.js +76 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +23 -0
- package/dist/poll/votes/votesCollection.js +96 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +49 -7
- package/dist/react/Form.js +183 -37
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +10 -2
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/FormResults.d.ts +4 -2
- package/dist/react/FormResults.js +21 -8
- package/dist/react/FormResults.js.map +1 -1
- package/dist/react/Poll.d.ts +25 -2
- package/dist/react/Poll.js +76 -25
- package/dist/react/Poll.js.map +1 -1
- package/dist/react/adapters.d.ts +35 -0
- package/dist/react/adapters.js +11 -0
- package/dist/react/adapters.js.map +1 -0
- package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
- package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
- package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
- package/dist/react/captcha/TurnstileCaptcha.js +2 -2
- package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
- package/dist/react/captcha/useCaptchaScript.js +23 -5
- package/dist/react/captcha/useCaptchaScript.js.map +1 -1
- package/dist/react/fetchResults.d.ts +6 -3
- package/dist/react/fetchResults.js +10 -5
- package/dist/react/fetchResults.js.map +1 -1
- package/dist/react/primitives/Checkbox.d.ts +4 -2
- package/dist/react/primitives/Checkbox.js +3 -2
- package/dist/react/primitives/Checkbox.js.map +1 -1
- package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
- package/dist/react/primitives/ChoiceGroup.js +33 -0
- package/dist/react/primitives/ChoiceGroup.js.map +1 -0
- package/dist/react/primitives/FieldShell.d.ts +11 -1
- package/dist/react/primitives/FieldShell.js +43 -33
- package/dist/react/primitives/FieldShell.js.map +1 -1
- package/dist/react/primitives/Input.d.ts +3 -1
- package/dist/react/primitives/Input.js +2 -1
- package/dist/react/primitives/Input.js.map +1 -1
- package/dist/react/renderers/calculation.js +6 -1
- package/dist/react/renderers/calculation.js.map +1 -1
- package/dist/react/renderers/checkbox.js +2 -1
- package/dist/react/renderers/checkbox.js.map +1 -1
- package/dist/react/renderers/consent.js +8 -3
- package/dist/react/renderers/consent.js.map +1 -1
- package/dist/react/renderers/email.js +3 -1
- package/dist/react/renderers/email.js.map +1 -1
- package/dist/react/renderers/repeater.js +5 -0
- package/dist/react/renderers/repeater.js.map +1 -1
- package/dist/react/renderers/select.js +20 -2
- package/dist/react/renderers/select.js.map +1 -1
- package/dist/react/renderers/text.js +3 -1
- package/dist/react/renderers/text.js.map +1 -1
- package/dist/react/state.d.ts +20 -1
- package/dist/react/state.js +57 -4
- package/dist/react/state.js.map +1 -1
- package/dist/react/submitForm.d.ts +20 -3
- package/dist/react/submitForm.js +8 -4
- package/dist/react/submitForm.js.map +1 -1
- package/dist/react/useCalcValues.d.ts +10 -0
- package/dist/react/useCalcValues.js +13 -0
- package/dist/react/useCalcValues.js.map +1 -0
- package/dist/react/useField.js +7 -5
- package/dist/react/useField.js.map +1 -1
- package/dist/recall/resolver.js +1 -1
- package/dist/recall/resolver.js.map +1 -1
- package/dist/spam/constants.js +7 -1
- package/dist/spam/constants.js.map +1 -1
- package/dist/spam/spamGuard.js +2 -1
- package/dist/spam/spamGuard.js.map +1 -1
- package/dist/submissions/SubmissionAnswersClient.js +14 -14
- package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
- package/dist/submissions/createSubmission.d.ts +7 -1
- package/dist/submissions/createSubmission.js +10 -5
- package/dist/submissions/createSubmission.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
- package/dist/submissions/resolveVotedSubmission.js +51 -0
- package/dist/submissions/resolveVotedSubmission.js.map +1 -0
- package/dist/submissions/runSubmission.js +6 -5
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/submissionLocale.js +39 -0
- package/dist/submissions/submissionLocale.js.map +1 -0
- package/dist/submissions/validateSubmission.js +125 -79
- package/dist/submissions/validateSubmission.js.map +1 -1
- package/dist/submissions/verifyContext.js +35 -0
- package/dist/submissions/verifyContext.js.map +1 -0
- package/dist/submissions/voteChange.js +21 -0
- package/dist/submissions/voteChange.js.map +1 -0
- package/dist/submissions/voteChangeEndpoint.js +110 -0
- package/dist/submissions/voteChangeEndpoint.js.map +1 -0
- package/dist/submissions/votedCookie.d.ts +10 -4
- package/dist/submissions/votedCookie.js +49 -11
- package/dist/submissions/votedCookie.js.map +1 -1
- package/dist/translations/ar.d.ts +7 -0
- package/dist/translations/ar.js +379 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/clientRuntimeKeys.d.ts +17 -0
- package/dist/translations/clientRuntimeKeys.js +48 -0
- package/dist/translations/clientRuntimeKeys.js.map +1 -0
- package/dist/translations/de.d.ts +12 -0
- package/dist/translations/de.js +80 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +80 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.d.ts +7 -0
- package/dist/translations/es.js +379 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.d.ts +7 -0
- package/dist/translations/fr.js +379 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.d.ts +7 -0
- package/dist/translations/id.js +379 -0
- package/dist/translations/id.js.map +1 -0
- package/dist/translations/index.d.ts +23 -6
- package/dist/translations/index.js +31 -6
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +78 -1
- package/dist/translations/keys.js +78 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.d.ts +7 -0
- package/dist/translations/ko.js +379 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/makeTranslate.d.ts +7 -3
- package/dist/translations/makeTranslate.js +12 -3
- package/dist/translations/makeTranslate.js.map +1 -1
- package/dist/translations/pt.d.ts +7 -0
- package/dist/translations/pt.js +379 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.d.ts +7 -0
- package/dist/translations/ru.js +379 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/uk.d.ts +7 -0
- package/dist/translations/uk.js +379 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.d.ts +7 -0
- package/dist/translations/zh.js +379 -0
- package/dist/translations/zh.js.map +1 -0
- package/dist/validation/builtin/index.js +2 -0
- package/dist/validation/builtin/index.js.map +1 -1
- package/dist/validation/builtin/integer.js +15 -0
- package/dist/validation/builtin/integer.js.map +1 -0
- package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
- package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
- package/package.json +23 -15
- package/styles/form-builder.css +84 -0
|
@@ -41,16 +41,21 @@ const linkOf = (raw) => {
|
|
|
41
41
|
* The `statement` and `link` this reads are server-resolved from the field's consent source and
|
|
42
42
|
* injected by `toFormDocument(doc, { consentStatements })`; the form document itself carries only
|
|
43
43
|
* the source key, so a form rendered without that step shows no statement rather than a stale one.
|
|
44
|
+
* The wording arrives already selected for the field's display (a notice source's
|
|
45
|
+
* `noticeStatement` lands here as `statement`), so this renderer never picks between phrasings.
|
|
46
|
+
* A `display: 'notice'` field renders the statement and link as passive prose with no checkbox and
|
|
47
|
+
* no required marker: submitting the form is the consent, and the server records the agreement.
|
|
44
48
|
*/
|
|
45
49
|
const consentRenderer = defineFieldRenderer(({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {
|
|
46
50
|
const describedById = `${id}-desc`;
|
|
51
|
+
const isNotice = field.display === "notice";
|
|
47
52
|
const plainStatement = text(textOfBody(field.statement));
|
|
48
53
|
const html = useMemo(() => richStatementHtml(field.statement), [field.statement]);
|
|
49
54
|
const link = linkOf(field.link);
|
|
50
55
|
return /* @__PURE__ */ jsxs(FieldShell, {
|
|
51
56
|
id,
|
|
52
57
|
description: typeof field.description === "string" ? field.description : void 0,
|
|
53
|
-
required,
|
|
58
|
+
required: isNotice ? false : required,
|
|
54
59
|
errors,
|
|
55
60
|
describedById,
|
|
56
61
|
children: [
|
|
@@ -61,12 +66,12 @@ const consentRenderer = defineFieldRenderer(({ field, id, name, value, onChange,
|
|
|
61
66
|
className: "fb-consent__statement",
|
|
62
67
|
children: plainStatement
|
|
63
68
|
}) : null,
|
|
64
|
-
required && (html || plainStatement) ? /* @__PURE__ */ jsx("span", {
|
|
69
|
+
!isNotice && required && (html || plainStatement) ? /* @__PURE__ */ jsx("span", {
|
|
65
70
|
className: "fb-field__required",
|
|
66
71
|
"aria-hidden": "true",
|
|
67
72
|
children: " *"
|
|
68
73
|
}) : null,
|
|
69
|
-
/* @__PURE__ */ jsx(Checkbox, {
|
|
74
|
+
isNotice ? null : /* @__PURE__ */ jsx(Checkbox, {
|
|
70
75
|
id,
|
|
71
76
|
name,
|
|
72
77
|
checked: value ?? false,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"consent.js","names":[],"sources":["../../../src/react/renderers/consent.tsx"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\nimport { sanitizeUrl } from '../../actions/body/converters'\nimport { serializeBody } from '../../actions/body/serializeBody'\nimport { textOfBody } from '../../actions/body/textOfBody'\nimport { defineFieldRenderer } from '../contract'\nimport { Checkbox } from '../primitives/Checkbox'\nimport { FieldShell } from '../primitives/FieldShell'\n\ntype ConsentLink = { label: string; url: string }\n\nconst text = (raw: unknown): string | undefined =>\n\ttypeof raw === 'string' && raw.trim() !== '' ? raw : undefined\n\n/**\n * HTML for a rich text statement. A plain string never goes through this path: `serializeBody`\n * interpolates a string body unescaped (its pre-richText behavior), so rendering one as HTML would\n * let literal markup execute; the renderer shows a plain string as text instead.\n */\nconst richStatementHtml = (statement: unknown): string | undefined => {\n\tif (typeof statement === 'string' || statement == null) {\n\t\treturn undefined\n\t}\n\tconst html = serializeBody(statement, { values: [], descriptors: [] })\n\treturn html === '' ? undefined : html\n}\n\n/**\n * The resolved policy link, or nothing unless the source carries both a url and a name to show\n * for it: an anchor labelled by a raw URL or a machine key is worse than no anchor. The href is\n * sanitized like every other url the package renders, since a source is admin-authored and can\n * point anywhere (`sanitizeUrl` keeps http(s)/mailto/tel and relative urls, and neutralizes the\n * rest to `#`).\n */\nconst linkOf = (raw: unknown): ConsentLink | undefined => {\n\tconst link = raw as Partial<ConsentLink> | undefined\n\tconst label = text(link?.label)\n\treturn label && typeof link?.url === 'string' && link.url !== ''\n\t\t? { label, url: sanitizeUrl(link.url) }\n\t\t: undefined\n}\n\n/**\n * The `statement` and `link` this reads are server-resolved from the field's consent source and\n * injected by `toFormDocument(doc, { consentStatements })`; the form document itself carries only\n * the source key, so a form rendered without that step shows no statement rather than a stale one.\n */\nexport const consentRenderer = defineFieldRenderer<boolean>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\n\t\t// The checkbox's accessible name is always plain text, regardless of the statement's shape,\n\t\t// so it stays a single unambiguous string even though the visible statement can carry\n\t\t// formatting and inline links. With no statement resolved the field is misconfigured; the\n\t\t// machine name still beats leaving the control unnamed.\n\t\tconst plainStatement = text(textOfBody(field.statement))\n\t\tconst html = useMemo(() => richStatementHtml(field.statement), [field.statement])\n\t\tconst link = linkOf(field.link)\n\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t{html ? (\n\t\t\t\t\t// The statement is a plain sibling, never a <label>: a native <label> forwards clicks to\n\t\t\t\t\t// its control even for descendant links (they aren't \"labelable\" elements per the HTML\n\t\t\t\t\t// spec), so an inline link here would also silently toggle the checkbox. The checkbox's\n\t\t\t\t\t// name comes from aria-label instead. A <div>, because serializeBody emits block\n\t\t\t\t\t// elements (<p>, headings, lists) that are invalid inside inline wrappers.\n\t\t\t\t\t// Safe to inject: serializeBody HTML-escapes all text and sanitizes link URLs.\n\t\t\t\t\t// biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is produced by our escaping serializer, never raw user input\n\t\t\t\t\t<div className=\"fb-consent__statement\" dangerouslySetInnerHTML={{ __html: html }} />\n\t\t\t\t) : plainStatement ? (\n\t\t\t\t\t<span className=\"fb-consent__statement\">{plainStatement}</span>\n\t\t\t\t) : null}\n\t\t\t\t{required && (html || plainStatement) ? (\n\t\t\t\t\t<span className=\"fb-field__required\" aria-hidden=\"true\">\n\t\t\t\t\t\t{' *'}\n\t\t\t\t\t</span>\n\t\t\t\t) : null}\n\t\t\t\t<Checkbox\n\t\t\t\t\tid={id}\n\t\t\t\t\tname={name}\n\t\t\t\t\tchecked={value ?? false}\n\t\t\t\t\tonChange={onChange}\n\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\trequired={required}\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\tariaLabel={plainStatement ?? name}\n\t\t\t\t/>\n\t\t\t\t{link ? (\n\t\t\t\t\t<span className=\"fb-consent__links\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref={link.url}\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\"\n\t\t\t\t\t\t\tclassName=\"fb-consent__link\"\n\t\t\t\t\t\t>\n\t\t\t\t\t\t\t{link.label}\n\t\t\t\t\t\t</a>\n\t\t\t\t\t</span>\n\t\t\t\t) : null}\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;;;;;AAYA,MAAM,QAAQ,QACb,OAAO,QAAQ,YAAY,IAAI,KAAK,MAAM,KAAK,MAAM,KAAA;;;;;;AAOtD,MAAM,qBAAqB,cAA2C;CACrE,IAAI,OAAO,cAAc,YAAY,aAAa,MACjD;CAED,MAAM,OAAO,cAAc,WAAW;EAAE,QAAQ,CAAC;EAAG,aAAa,CAAC;CAAE,CAAC;CACrE,OAAO,SAAS,KAAK,KAAA,IAAY;AAClC;;;;;;;;AASA,MAAM,UAAU,QAA0C;CACzD,MAAM,OAAO;CACb,MAAM,QAAQ,KAAK,MAAM,KAAK;CAC9B,OAAO,SAAS,OAAO,MAAM,QAAQ,YAAY,KAAK,QAAQ,KAC3D;EAAE;EAAO,KAAK,YAAY,KAAK,GAAG;CAAE,IACpC,KAAA;AACJ
|
|
1
|
+
{"version":3,"file":"consent.js","names":[],"sources":["../../../src/react/renderers/consent.tsx"],"sourcesContent":["'use client'\n\nimport { useMemo } from 'react'\nimport { sanitizeUrl } from '../../actions/body/converters'\nimport { serializeBody } from '../../actions/body/serializeBody'\nimport { textOfBody } from '../../actions/body/textOfBody'\nimport { defineFieldRenderer } from '../contract'\nimport { Checkbox } from '../primitives/Checkbox'\nimport { FieldShell } from '../primitives/FieldShell'\n\ntype ConsentLink = { label: string; url: string }\n\nconst text = (raw: unknown): string | undefined =>\n\ttypeof raw === 'string' && raw.trim() !== '' ? raw : undefined\n\n/**\n * HTML for a rich text statement. A plain string never goes through this path: `serializeBody`\n * interpolates a string body unescaped (its pre-richText behavior), so rendering one as HTML would\n * let literal markup execute; the renderer shows a plain string as text instead.\n */\nconst richStatementHtml = (statement: unknown): string | undefined => {\n\tif (typeof statement === 'string' || statement == null) {\n\t\treturn undefined\n\t}\n\tconst html = serializeBody(statement, { values: [], descriptors: [] })\n\treturn html === '' ? undefined : html\n}\n\n/**\n * The resolved policy link, or nothing unless the source carries both a url and a name to show\n * for it: an anchor labelled by a raw URL or a machine key is worse than no anchor. The href is\n * sanitized like every other url the package renders, since a source is admin-authored and can\n * point anywhere (`sanitizeUrl` keeps http(s)/mailto/tel and relative urls, and neutralizes the\n * rest to `#`).\n */\nconst linkOf = (raw: unknown): ConsentLink | undefined => {\n\tconst link = raw as Partial<ConsentLink> | undefined\n\tconst label = text(link?.label)\n\treturn label && typeof link?.url === 'string' && link.url !== ''\n\t\t? { label, url: sanitizeUrl(link.url) }\n\t\t: undefined\n}\n\n/**\n * The `statement` and `link` this reads are server-resolved from the field's consent source and\n * injected by `toFormDocument(doc, { consentStatements })`; the form document itself carries only\n * the source key, so a form rendered without that step shows no statement rather than a stale one.\n * The wording arrives already selected for the field's display (a notice source's\n * `noticeStatement` lands here as `statement`), so this renderer never picks between phrasings.\n * A `display: 'notice'` field renders the statement and link as passive prose with no checkbox and\n * no required marker: submitting the form is the consent, and the server records the agreement.\n */\nexport const consentRenderer = defineFieldRenderer<boolean>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\tconst isNotice = field.display === 'notice'\n\n\t\t// The checkbox's accessible name is always plain text, regardless of the statement's shape,\n\t\t// so it stays a single unambiguous string even though the visible statement can carry\n\t\t// formatting and inline links. With no statement resolved the field is misconfigured; the\n\t\t// machine name still beats leaving the control unnamed.\n\t\tconst plainStatement = text(textOfBody(field.statement))\n\t\tconst html = useMemo(() => richStatementHtml(field.statement), [field.statement])\n\t\tconst link = linkOf(field.link)\n\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={isNotice ? false : required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t{html ? (\n\t\t\t\t\t// The statement is a plain sibling, never a <label>: a native <label> forwards clicks to\n\t\t\t\t\t// its control even for descendant links (they aren't \"labelable\" elements per the HTML\n\t\t\t\t\t// spec), so an inline link here would also silently toggle the checkbox. The checkbox's\n\t\t\t\t\t// name comes from aria-label instead. A <div>, because serializeBody emits block\n\t\t\t\t\t// elements (<p>, headings, lists) that are invalid inside inline wrappers.\n\t\t\t\t\t// Safe to inject: serializeBody HTML-escapes all text and sanitizes link URLs.\n\t\t\t\t\t// biome-ignore lint/security/noDangerouslySetInnerHtml: HTML is produced by our escaping serializer, never raw user input\n\t\t\t\t\t<div className=\"fb-consent__statement\" dangerouslySetInnerHTML={{ __html: html }} />\n\t\t\t\t) : plainStatement ? (\n\t\t\t\t\t<span className=\"fb-consent__statement\">{plainStatement}</span>\n\t\t\t\t) : null}\n\t\t\t\t{!isNotice && required && (html || plainStatement) ? (\n\t\t\t\t\t<span className=\"fb-field__required\" aria-hidden=\"true\">\n\t\t\t\t\t\t{' *'}\n\t\t\t\t\t</span>\n\t\t\t\t) : null}\n\t\t\t\t{isNotice ? null : (\n\t\t\t\t\t<Checkbox\n\t\t\t\t\t\tid={id}\n\t\t\t\t\t\tname={name}\n\t\t\t\t\t\tchecked={value ?? false}\n\t\t\t\t\t\tonChange={onChange}\n\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\trequired={required}\n\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\t\tariaLabel={plainStatement ?? name}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t\t{link ? (\n\t\t\t\t\t<span className=\"fb-consent__links\">\n\t\t\t\t\t\t<a\n\t\t\t\t\t\t\thref={link.url}\n\t\t\t\t\t\t\ttarget=\"_blank\"\n\t\t\t\t\t\t\trel=\"noopener noreferrer\"\n\t\t\t\t\t\t\tclassName=\"fb-consent__link\"\n\t\t\t\t\t\t>\n\t\t\t\t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C,YAAY,aAAa,QAAQ,kBAClC,oBAAC,QAAD;IAAM,WAAU;IAAqB,eAAY;cAC/C;GACI,CAAA,IACH;GACH,WAAW,OACX,oBAAC,UAAD;IACK;IACE;IACN,SAAS,SAAS;IACR;IACF;IACE;IACA;IACV,SAAS,OAAO,SAAS;IACV;IACf,WAAW,kBAAkB;GAC7B,CAAA;GAED,OACA,oBAAC,QAAD;IAAM,WAAU;cACf,oBAAC,KAAD;KACC,MAAM,KAAK;KACX,QAAO;KACP,KAAI;KACJ,WAAU;eAET,KAAK;IACJ,CAAA;GACE,CAAA,IACH;EACO;;AAEd,CACD"}
|
|
@@ -6,6 +6,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
6
6
|
//#region src/react/renderers/email.tsx
|
|
7
7
|
const emailRenderer = defineFieldRenderer(({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {
|
|
8
8
|
const describedById = `${id}-desc`;
|
|
9
|
+
const autoComplete = typeof field.autocomplete === "string" && field.autocomplete.trim() ? field.autocomplete : void 0;
|
|
9
10
|
return /* @__PURE__ */ jsx(FieldShell, {
|
|
10
11
|
id,
|
|
11
12
|
label: field.label,
|
|
@@ -24,7 +25,8 @@ const emailRenderer = defineFieldRenderer(({ field, id, name, value, onChange, o
|
|
|
24
25
|
required,
|
|
25
26
|
disabled,
|
|
26
27
|
invalid: errors.length > 0,
|
|
27
|
-
describedById
|
|
28
|
+
describedById,
|
|
29
|
+
autoComplete
|
|
28
30
|
})
|
|
29
31
|
});
|
|
30
32
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.js","names":[],"sources":["../../../src/react/renderers/email.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Input } from '../primitives/Input'\n\nexport const emailRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tlabel={field.label}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t<Input\n\t\t\t\t\tid={id}\n\t\t\t\t\tname={name}\n\t\t\t\t\ttype=\"email\"\n\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\tonChange={onChange}\n\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\tplaceholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}\n\t\t\t\t\trequired={required}\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t/>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;AAMA,MAAa,gBAAgB,qBAC3B,EAAE,OAAO,IAAI,MAAM,OAAO,UAAU,QAAQ,QAAQ,UAAU,eAAe;CAC7E,MAAM,gBAAgB,GAAG,GAAG;CAC5B,OACC,oBAAC,YAAD;EACK;EACJ,OAAO,MAAM;EACb,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;EAC/D;EACF;EACO;YAEf,oBAAC,OAAD;GACK;GACE;GACN,MAAK;GACL,OAAO,SAAS;GACN;GACF;GACR,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;GAC/D;GACA;GACV,SAAS,OAAO,SAAS;GACV;
|
|
1
|
+
{"version":3,"file":"email.js","names":[],"sources":["../../../src/react/renderers/email.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Input } from '../primitives/Input'\n\nexport const emailRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\tconst autoComplete =\n\t\t\ttypeof field.autocomplete === 'string' && field.autocomplete.trim()\n\t\t\t\t? field.autocomplete\n\t\t\t\t: undefined\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tlabel={field.label}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t<Input\n\t\t\t\t\tid={id}\n\t\t\t\t\tname={name}\n\t\t\t\t\ttype=\"email\"\n\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\tonChange={onChange}\n\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\tplaceholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}\n\t\t\t\t\trequired={required}\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\tautoComplete={autoComplete}\n\t\t\t\t/>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;AAMA,MAAa,gBAAgB,qBAC3B,EAAE,OAAO,IAAI,MAAM,OAAO,UAAU,QAAQ,QAAQ,UAAU,eAAe;CAC7E,MAAM,gBAAgB,GAAG,GAAG;CAC5B,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,MAAM,aAAa,KAAK,IAC/D,MAAM,eACN,KAAA;CACJ,OACC,oBAAC,YAAD;EACK;EACJ,OAAO,MAAM;EACb,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;EAC/D;EACF;EACO;YAEf,oBAAC,OAAD;GACK;GACE;GACN,MAAK;GACL,OAAO,SAAS;GACN;GACF;GACR,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;GAC/D;GACA;GACV,SAAS,OAAO,SAAS;GACV;GACD;EACd,CAAA;CACU,CAAA;AAEd,CACD"}
|
|
@@ -49,6 +49,11 @@ const repeaterRenderer = defineFieldRenderer(({ field, name, id: rootId, errors,
|
|
|
49
49
|
};
|
|
50
50
|
const removeRow = (index) => {
|
|
51
51
|
rowKeysRef.current = rowKeysRef.current.filter((_, i) => i !== index);
|
|
52
|
+
dispatch({
|
|
53
|
+
type: "REMOVE_REPEATER_ROW",
|
|
54
|
+
name,
|
|
55
|
+
index
|
|
56
|
+
});
|
|
52
57
|
setValue(rows.filter((_, i) => i !== index));
|
|
53
58
|
onBlur();
|
|
54
59
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"repeater.js","names":[],"sources":["../../../src/react/renderers/repeater.tsx"],"sourcesContent":["'use client'\n\nimport { createElement, useId, useRef } from 'react'\nimport { isNamedField } from '../../fields/fieldKey'\nimport type { FormFieldInstance } from '../../submissions/types'\nimport { keys } from '../../translations/keys'\nimport type { FieldRenderer } from '../contract'\nimport { defineFieldRenderer } from '../contract'\nimport { useFormContext } from '../FormContext'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { useField } from '../useField'\n\ntype RepeaterRow = Record<string, unknown>\n\n/** Process-wide counter for stable per-row React keys (rows are plain objects with no id of their own). */\nlet rowKeySeq = 0\nconst nextRowKey = () => `fbrow-${rowKeySeq++}`\n\n/**\n * Thin wrapper so each sub-field renderer is a proper React component (has stable hook identity\n * per row/field). Reads errors for the composite path `field[row].subField` from\n * form state so server-side validation errors are surfaced inline next to the sub-field input,\n * overriding any static values passed by the parent.\n */\nconst SubFieldWrapper = ({\n\trenderer,\n\tname,\n\t...props\n}: { renderer: FieldRenderer } & Parameters<FieldRenderer>[0]) => {\n\tconst { state } = useFormContext()\n\tconst errors = (state.errors as Record<string, string[]>)?.[name] ?? []\n\treturn renderer({ ...props, name, errors })\n}\n\nexport const repeaterRenderer = defineFieldRenderer<RepeaterRow[]>(\n\t({ field, name, id: rootId, errors, required, t, locale }) => {\n\t\tconst { rendererRegistry, dispatch } = useFormContext()\n\t\tconst { value, setValue, onBlur } = useField<RepeaterRow[]>(name)\n\t\tconst addId = useId()\n\t\tconst rowKeysRef = useRef<string[]>([])\n\n\t\tconst rows = Array.isArray(value) ? value : []\n\t\t// One stable key per row so removing a middle row does not re-index survivors onto each other's\n\t\t// React instances (which would strand a stateful sub-renderer's local state, e.g. the file\n\t\t// renderer's filename). Reconciled to the row count each render; add/remove keep keys aligned.\n\t\tif (rowKeysRef.current.length !== rows.length) {\n\t\t\tconst next = rowKeysRef.current.slice(0, rows.length)\n\t\t\twhile (next.length < rows.length) next.push(nextRowKey())\n\t\t\trowKeysRef.current = next\n\t\t}\n\t\tconst subFields = (\n\t\t\tArray.isArray(field.subFields) ? (field.subFields as FormFieldInstance[]) : []\n\t\t).filter(isNamedField)\n\t\tconst maxRows = typeof field.maxRows === 'number' ? field.maxRows : undefined\n\t\tconst minRows = typeof field.minRows === 'number' ? field.minRows : 0\n\t\tconst addLabel =\n\t\t\ttypeof field.addLabel === 'string' && field.addLabel.length > 0\n\t\t\t\t? field.addLabel\n\t\t\t\t: t(keys.repeaterAddRow)\n\n\t\tconst addRow = () => {\n\t\t\tif (maxRows != null && rows.length >= maxRows) return\n\t\t\trowKeysRef.current = [...rowKeysRef.current, nextRowKey()]\n\t\t\tsetValue([...rows, {}])\n\t\t\tonBlur()\n\t\t}\n\n\t\tconst removeRow = (index: number) => {\n\t\t\trowKeysRef.current = rowKeysRef.current.filter((_, i) => i !== index)\n\t\t\tsetValue(rows.filter((_, i) => i !== index))\n\t\t\tonBlur()\n\t\t}\n\n\t\tconst updateRow = (index: number, fieldName: string, fieldValue: unknown) => {\n\t\t\tsetValue(rows.map((row, i) => (i === index ? { ...row, [fieldName]: fieldValue } : row)))\n\t\t\t// SET_VALUE clears only the repeater field's own error key, not composite sub-field keys, so a\n\t\t\t// stale server-side error for this sub-field would linger until the next submit. Clear it now.\n\t\t\tdispatch({ type: 'SET_FIELD_ISSUES', name: `${name}[${index}].${fieldName}`, errors: [] })\n\t\t}\n\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={rootId}\n\t\t\t\tlabel={typeof field.label === 'string' ? field.label : undefined}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={`${rootId}-desc`}\n\t\t\t>\n\t\t\t\t<div className=\"fb-repeater\">\n\t\t\t\t\t{rows.map((row, rowIndex) => {\n\t\t\t\t\t\tconst rowLabel = t(keys.repeaterRow).replace('{n}', String(rowIndex + 1))\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t<fieldset key={rowKeysRef.current[rowIndex]} className=\"fb-repeater__row\">\n\t\t\t\t\t\t\t\t<legend className=\"fb-repeater__row-legend\">\n\t\t\t\t\t\t\t\t\t{rowLabel}\n\t\t\t\t\t\t\t\t\t{rows.length > minRows && (\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tclassName=\"fb-repeater__remove\"\n\t\t\t\t\t\t\t\t\t\t\tonClick={() => removeRow(rowIndex)}\n\t\t\t\t\t\t\t\t\t\t\taria-label={`${t(keys.repeaterRemoveRow)} ${rowLabel}`}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{t(keys.repeaterRemoveRow)}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</legend>\n\t\t\t\t\t\t\t\t<div className=\"fb-repeater__row-fields\">\n\t\t\t\t\t\t\t\t\t{subFields.map((subField) => {\n\t\t\t\t\t\t\t\t\t\tconst renderer = rendererRegistry.get(subField.blockType)\n\t\t\t\t\t\t\t\t\t\tif (!renderer) return null\n\t\t\t\t\t\t\t\t\t\tconst subId = `${rootId}-${rowIndex}-${subField.name}`\n\t\t\t\t\t\t\t\t\t\tconst compositeName = `${name}[${rowIndex}].${subField.name}`\n\t\t\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t\t\t<div key={subField.name} className=\"fb-repeater__sub-field\">\n\t\t\t\t\t\t\t\t\t\t\t\t{createElement(SubFieldWrapper, {\n\t\t\t\t\t\t\t\t\t\t\t\t\trenderer,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfield: subField,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid: subId,\n\t\t\t\t\t\t\t\t\t\t\t\t\tname: compositeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue: row[subField.name],\n\t\t\t\t\t\t\t\t\t\t\t\t\tonChange: (v) => updateRow(rowIndex, subField.name, v),\n\t\t\t\t\t\t\t\t\t\t\t\t\tonBlur,\n\t\t\t\t\t\t\t\t\t\t\t\t\t// SubFieldWrapper overrides these from form state; passed here to satisfy the type\n\t\t\t\t\t\t\t\t\t\t\t\t\terrors: [],\n\t\t\t\t\t\t\t\t\t\t\t\t\trequired: subField.required ?? false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdisabled: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocale,\n\t\t\t\t\t\t\t\t\t\t\t\t\tt,\n\t\t\t\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</fieldset>\n\t\t\t\t\t\t)\n\t\t\t\t\t})}\n\t\t\t\t\t{(maxRows == null || rows.length < maxRows) && (\n\t\t\t\t\t\t<button id={addId} type=\"button\" className=\"fb-repeater__add\" onClick={addRow}>\n\t\t\t\t\t\t\t{addLabel}\n\t\t\t\t\t\t</button>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;;;;;;AAeA,IAAI,YAAY;AAChB,MAAM,mBAAmB,SAAS;;;;;;;AAQlC,MAAM,mBAAmB,EACxB,UACA,MACA,GAAG,YAC8D;CACj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derers/repeater.tsx"],"sourcesContent":["'use client'\n\nimport { createElement, useId, useRef } from 'react'\nimport { isNamedField } from '../../fields/fieldKey'\nimport type { FormFieldInstance } from '../../submissions/types'\nimport { keys } from '../../translations/keys'\nimport type { FieldRenderer } from '../contract'\nimport { defineFieldRenderer } from '../contract'\nimport { useFormContext } from '../FormContext'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { useField } from '../useField'\n\ntype RepeaterRow = Record<string, unknown>\n\n/** Process-wide counter for stable per-row React keys (rows are plain objects with no id of their own). */\nlet rowKeySeq = 0\nconst nextRowKey = () => `fbrow-${rowKeySeq++}`\n\n/**\n * Thin wrapper so each sub-field renderer is a proper React component (has stable hook identity\n * per row/field). Reads errors for the composite path `field[row].subField` from\n * form state so server-side validation errors are surfaced inline next to the sub-field input,\n * overriding any static values passed by the parent.\n */\nconst SubFieldWrapper = ({\n\trenderer,\n\tname,\n\t...props\n}: { renderer: FieldRenderer } & Parameters<FieldRenderer>[0]) => {\n\tconst { state } = useFormContext()\n\tconst errors = (state.errors as Record<string, string[]>)?.[name] ?? []\n\treturn renderer({ ...props, name, errors })\n}\n\nexport const repeaterRenderer = defineFieldRenderer<RepeaterRow[]>(\n\t({ field, name, id: rootId, errors, required, t, locale }) => {\n\t\tconst { rendererRegistry, dispatch } = useFormContext()\n\t\tconst { value, setValue, onBlur } = useField<RepeaterRow[]>(name)\n\t\tconst addId = useId()\n\t\tconst rowKeysRef = useRef<string[]>([])\n\n\t\tconst rows = Array.isArray(value) ? value : []\n\t\t// One stable key per row so removing a middle row does not re-index survivors onto each other's\n\t\t// React instances (which would strand a stateful sub-renderer's local state, e.g. the file\n\t\t// renderer's filename). Reconciled to the row count each render; add/remove keep keys aligned.\n\t\tif (rowKeysRef.current.length !== rows.length) {\n\t\t\tconst next = rowKeysRef.current.slice(0, rows.length)\n\t\t\twhile (next.length < rows.length) next.push(nextRowKey())\n\t\t\trowKeysRef.current = next\n\t\t}\n\t\tconst subFields = (\n\t\t\tArray.isArray(field.subFields) ? (field.subFields as FormFieldInstance[]) : []\n\t\t).filter(isNamedField)\n\t\tconst maxRows = typeof field.maxRows === 'number' ? field.maxRows : undefined\n\t\tconst minRows = typeof field.minRows === 'number' ? field.minRows : 0\n\t\tconst addLabel =\n\t\t\ttypeof field.addLabel === 'string' && field.addLabel.length > 0\n\t\t\t\t? field.addLabel\n\t\t\t\t: t(keys.repeaterAddRow)\n\n\t\tconst addRow = () => {\n\t\t\tif (maxRows != null && rows.length >= maxRows) return\n\t\t\trowKeysRef.current = [...rowKeysRef.current, nextRowKey()]\n\t\t\tsetValue([...rows, {}])\n\t\t\tonBlur()\n\t\t}\n\n\t\tconst removeRow = (index: number) => {\n\t\t\trowKeysRef.current = rowKeysRef.current.filter((_, i) => i !== index)\n\t\t\t// setValue removes the row value; SET_VALUE cannot reach the composite sub-field issue keys\n\t\t\t// (`name[i].sub`), so reindex them separately or a deleted row's errors strand on a survivor.\n\t\t\tdispatch({ type: 'REMOVE_REPEATER_ROW', name, index })\n\t\t\tsetValue(rows.filter((_, i) => i !== index))\n\t\t\tonBlur()\n\t\t}\n\n\t\tconst updateRow = (index: number, fieldName: string, fieldValue: unknown) => {\n\t\t\tsetValue(rows.map((row, i) => (i === index ? { ...row, [fieldName]: fieldValue } : row)))\n\t\t\t// SET_VALUE clears only the repeater field's own error key, not composite sub-field keys, so a\n\t\t\t// stale server-side error for this sub-field would linger until the next submit. Clear it now.\n\t\t\tdispatch({ type: 'SET_FIELD_ISSUES', name: `${name}[${index}].${fieldName}`, errors: [] })\n\t\t}\n\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={rootId}\n\t\t\t\tlabel={typeof field.label === 'string' ? field.label : undefined}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={`${rootId}-desc`}\n\t\t\t>\n\t\t\t\t<div className=\"fb-repeater\">\n\t\t\t\t\t{rows.map((row, rowIndex) => {\n\t\t\t\t\t\tconst rowLabel = t(keys.repeaterRow).replace('{n}', String(rowIndex + 1))\n\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t<fieldset key={rowKeysRef.current[rowIndex]} className=\"fb-repeater__row\">\n\t\t\t\t\t\t\t\t<legend className=\"fb-repeater__row-legend\">\n\t\t\t\t\t\t\t\t\t{rowLabel}\n\t\t\t\t\t\t\t\t\t{rows.length > minRows && (\n\t\t\t\t\t\t\t\t\t\t<button\n\t\t\t\t\t\t\t\t\t\t\ttype=\"button\"\n\t\t\t\t\t\t\t\t\t\t\tclassName=\"fb-repeater__remove\"\n\t\t\t\t\t\t\t\t\t\t\tonClick={() => removeRow(rowIndex)}\n\t\t\t\t\t\t\t\t\t\t\taria-label={`${t(keys.repeaterRemoveRow)} ${rowLabel}`}\n\t\t\t\t\t\t\t\t\t\t>\n\t\t\t\t\t\t\t\t\t\t\t{t(keys.repeaterRemoveRow)}\n\t\t\t\t\t\t\t\t\t\t</button>\n\t\t\t\t\t\t\t\t\t)}\n\t\t\t\t\t\t\t\t</legend>\n\t\t\t\t\t\t\t\t<div className=\"fb-repeater__row-fields\">\n\t\t\t\t\t\t\t\t\t{subFields.map((subField) => {\n\t\t\t\t\t\t\t\t\t\tconst renderer = rendererRegistry.get(subField.blockType)\n\t\t\t\t\t\t\t\t\t\tif (!renderer) return null\n\t\t\t\t\t\t\t\t\t\tconst subId = `${rootId}-${rowIndex}-${subField.name}`\n\t\t\t\t\t\t\t\t\t\tconst compositeName = `${name}[${rowIndex}].${subField.name}`\n\t\t\t\t\t\t\t\t\t\treturn (\n\t\t\t\t\t\t\t\t\t\t\t<div key={subField.name} className=\"fb-repeater__sub-field\">\n\t\t\t\t\t\t\t\t\t\t\t\t{createElement(SubFieldWrapper, {\n\t\t\t\t\t\t\t\t\t\t\t\t\trenderer,\n\t\t\t\t\t\t\t\t\t\t\t\t\tfield: subField,\n\t\t\t\t\t\t\t\t\t\t\t\t\tid: subId,\n\t\t\t\t\t\t\t\t\t\t\t\t\tname: compositeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\tvalue: row[subField.name],\n\t\t\t\t\t\t\t\t\t\t\t\t\tonChange: (v) => updateRow(rowIndex, subField.name, v),\n\t\t\t\t\t\t\t\t\t\t\t\t\tonBlur,\n\t\t\t\t\t\t\t\t\t\t\t\t\t// SubFieldWrapper overrides these from form state; passed here to satisfy the type\n\t\t\t\t\t\t\t\t\t\t\t\t\terrors: [],\n\t\t\t\t\t\t\t\t\t\t\t\t\trequired: subField.required ?? false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tdisabled: false,\n\t\t\t\t\t\t\t\t\t\t\t\t\tlocale,\n\t\t\t\t\t\t\t\t\t\t\t\t\tt,\n\t\t\t\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\t})}\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</fieldset>\n\t\t\t\t\t\t)\n\t\t\t\t\t})}\n\t\t\t\t\t{(maxRows == null || rows.length < maxRows) && (\n\t\t\t\t\t\t<button id={addId} type=\"button\" className=\"fb-repeater__add\" onClick={addRow}>\n\t\t\t\t\t\t\t{addLabel}\n\t\t\t\t\t\t</button>\n\t\t\t\t\t)}\n\t\t\t\t</div>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;;;;;;AAeA,IAAI,YAAY;AAChB,MAAM,mBAAmB,SAAS;;;;;;;AAQlC,MAAM,mBAAmB,EACxB,UACA,MACA,GAAG,YAC8D;CACjE,MAAM,EAAE,UAAU,eAAe;CACjC,MAAM,SAAU,MAAM,SAAsC,SAAS,CAAC;CACtE,OAAO,SAAS;EAAE,GAAG;EAAO;EAAM;CAAO,CAAC;AAC3C;AAEA,MAAa,mBAAmB,qBAC9B,EAAE,OAAO,MAAM,IAAI,QAAQ,QAAQ,UAAU,GAAG,aAAa;CAC7D,MAAM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,CAAC,IACC,WAAW,QAAQ,KAAK,SAAS,YAClC,oBAAC,UAAD;IAAQ,IAAI;IAAO,MAAK;IAAS,WAAU;IAAmB,SAAS;cACrE;GACM,CAAA,CAEL;;CACM,CAAA;AAEd,CACD"}
|
|
@@ -2,11 +2,16 @@
|
|
|
2
2
|
import { defineFieldRenderer } from "../contract.js";
|
|
3
3
|
import { FieldShell } from "../primitives/FieldShell.js";
|
|
4
4
|
import { Select } from "../primitives/Select.js";
|
|
5
|
+
import { ChoiceGroup } from "../primitives/ChoiceGroup.js";
|
|
5
6
|
import { jsx } from "react/jsx-runtime";
|
|
6
7
|
//#region src/react/renderers/select.tsx
|
|
7
8
|
const selectRenderer = defineFieldRenderer(({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {
|
|
8
9
|
const describedById = `${id}-desc`;
|
|
9
|
-
const options = Array.isArray(field.options) ? field.options : []
|
|
10
|
+
const options = (Array.isArray(field.options) ? field.options : []).map((option) => ({
|
|
11
|
+
value: option.value,
|
|
12
|
+
label: option.label?.trim() ? option.label : option.value
|
|
13
|
+
}));
|
|
14
|
+
const display = field.display === "radio" || field.display === "buttons" ? field.display : "dropdown";
|
|
10
15
|
return /* @__PURE__ */ jsx(FieldShell, {
|
|
11
16
|
id,
|
|
12
17
|
label: field.label,
|
|
@@ -14,7 +19,8 @@ const selectRenderer = defineFieldRenderer(({ field, id, name, value, onChange,
|
|
|
14
19
|
required,
|
|
15
20
|
errors,
|
|
16
21
|
describedById,
|
|
17
|
-
|
|
22
|
+
group: display !== "dropdown",
|
|
23
|
+
children: display === "dropdown" ? /* @__PURE__ */ jsx(Select, {
|
|
18
24
|
id,
|
|
19
25
|
name,
|
|
20
26
|
value: value ?? "",
|
|
@@ -26,6 +32,18 @@ const selectRenderer = defineFieldRenderer(({ field, id, name, value, onChange,
|
|
|
26
32
|
disabled,
|
|
27
33
|
invalid: errors.length > 0,
|
|
28
34
|
describedById
|
|
35
|
+
}) : /* @__PURE__ */ jsx(ChoiceGroup, {
|
|
36
|
+
name,
|
|
37
|
+
value: value ?? "",
|
|
38
|
+
options,
|
|
39
|
+
onChange,
|
|
40
|
+
onBlur,
|
|
41
|
+
required,
|
|
42
|
+
disabled,
|
|
43
|
+
invalid: errors.length > 0,
|
|
44
|
+
describedById,
|
|
45
|
+
labelledById: field.label ? `${id}-label` : void 0,
|
|
46
|
+
variant: display
|
|
29
47
|
})
|
|
30
48
|
});
|
|
31
49
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select.js","names":[],"sources":["../../../src/react/renderers/select.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Select } from '../primitives/Select'\n\nexport const selectRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\tconst options =
|
|
1
|
+
{"version":3,"file":"select.js","names":[],"sources":["../../../src/react/renderers/select.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { ChoiceGroup } from '../primitives/ChoiceGroup'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Select } from '../primitives/Select'\n\nexport const selectRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\tconst options = (\n\t\t\tArray.isArray(field.options) ? (field.options as { label?: string; value: string }[]) : []\n\t\t).map((option) => ({\n\t\t\tvalue: option.value,\n\t\t\tlabel: option.label?.trim() ? option.label : option.value,\n\t\t}))\n\t\tconst display =\n\t\t\tfield.display === 'radio' || field.display === 'buttons' ? field.display : 'dropdown'\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tlabel={field.label}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t\tgroup={display !== 'dropdown'}\n\t\t\t>\n\t\t\t\t{display === 'dropdown' ? (\n\t\t\t\t\t<Select\n\t\t\t\t\t\tid={id}\n\t\t\t\t\t\tname={name}\n\t\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\t\toptions={options}\n\t\t\t\t\t\tonChange={onChange}\n\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\tplaceholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}\n\t\t\t\t\t\trequired={required}\n\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\t/>\n\t\t\t\t) : (\n\t\t\t\t\t<ChoiceGroup\n\t\t\t\t\t\tname={name}\n\t\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\t\toptions={options}\n\t\t\t\t\t\tonChange={onChange}\n\t\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\t\trequired={required}\n\t\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\t\tlabelledById={field.label ? `${id}-label` : undefined}\n\t\t\t\t\t\tvariant={display}\n\t\t\t\t\t/>\n\t\t\t\t)}\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;;AAOA,MAAa,iBAAiB,qBAC5B,EAAE,OAAO,IAAI,MAAM,OAAO,UAAU,QAAQ,QAAQ,UAAU,eAAe;CAC7E,MAAM,gBAAgB,GAAG,GAAG;CAC5B,MAAM,WACL,MAAM,QAAQ,MAAM,OAAO,IAAK,MAAM,UAAkD,CAAC,GACxF,KAAK,YAAY;EAClB,OAAO,OAAO;EACd,OAAO,OAAO,OAAO,KAAK,IAAI,OAAO,QAAQ,OAAO;CACrD,EAAE;CACF,MAAM,UACL,MAAM,YAAY,WAAW,MAAM,YAAY,YAAY,MAAM,UAAU;CAC5E,OACC,oBAAC,YAAD;EACK;EACJ,OAAO,MAAM;EACb,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;EAC/D;EACF;EACO;EACf,OAAO,YAAY;YAElB,YAAY,aACZ,oBAAC,QAAD;GACK;GACE;GACN,OAAO,SAAS;GACP;GACC;GACF;GACR,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;GAC/D;GACA;GACV,SAAS,OAAO,SAAS;GACV;EACf,CAAA,IAED,oBAAC,aAAD;GACO;GACN,OAAO,SAAS;GACP;GACC;GACF;GACE;GACA;GACV,SAAS,OAAO,SAAS;GACV;GACf,cAAc,MAAM,QAAQ,GAAG,GAAG,UAAU,KAAA;GAC5C,SAAS;EACT,CAAA;CAES,CAAA;AAEd,CACD"}
|
|
@@ -6,6 +6,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
6
6
|
//#region src/react/renderers/text.tsx
|
|
7
7
|
const textRenderer = defineFieldRenderer(({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {
|
|
8
8
|
const describedById = `${id}-desc`;
|
|
9
|
+
const autoComplete = typeof field.autocomplete === "string" && field.autocomplete.trim() ? field.autocomplete : void 0;
|
|
9
10
|
return /* @__PURE__ */ jsx(FieldShell, {
|
|
10
11
|
id,
|
|
11
12
|
label: field.label,
|
|
@@ -24,7 +25,8 @@ const textRenderer = defineFieldRenderer(({ field, id, name, value, onChange, on
|
|
|
24
25
|
required,
|
|
25
26
|
disabled,
|
|
26
27
|
invalid: errors.length > 0,
|
|
27
|
-
describedById
|
|
28
|
+
describedById,
|
|
29
|
+
autoComplete
|
|
28
30
|
})
|
|
29
31
|
});
|
|
30
32
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","names":[],"sources":["../../../src/react/renderers/text.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Input } from '../primitives/Input'\n\nexport const textRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tlabel={field.label}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t<Input\n\t\t\t\t\tid={id}\n\t\t\t\t\tname={name}\n\t\t\t\t\ttype=\"text\"\n\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\tonChange={onChange}\n\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\tplaceholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}\n\t\t\t\t\trequired={required}\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t/>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;AAMA,MAAa,eAAe,qBAC1B,EAAE,OAAO,IAAI,MAAM,OAAO,UAAU,QAAQ,QAAQ,UAAU,eAAe;CAC7E,MAAM,gBAAgB,GAAG,GAAG;CAC5B,OACC,oBAAC,YAAD;EACK;EACJ,OAAO,MAAM;EACb,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;EAC/D;EACF;EACO;YAEf,oBAAC,OAAD;GACK;GACE;GACN,MAAK;GACL,OAAO,SAAS;GACN;GACF;GACR,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;GAC/D;GACA;GACV,SAAS,OAAO,SAAS;GACV;
|
|
1
|
+
{"version":3,"file":"text.js","names":[],"sources":["../../../src/react/renderers/text.tsx"],"sourcesContent":["'use client'\n\nimport { defineFieldRenderer } from '../contract'\nimport { FieldShell } from '../primitives/FieldShell'\nimport { Input } from '../primitives/Input'\n\nexport const textRenderer = defineFieldRenderer<string>(\n\t({ field, id, name, value, onChange, onBlur, errors, required, disabled }) => {\n\t\tconst describedById = `${id}-desc`\n\t\tconst autoComplete =\n\t\t\ttypeof field.autocomplete === 'string' && field.autocomplete.trim()\n\t\t\t\t? field.autocomplete\n\t\t\t\t: undefined\n\t\treturn (\n\t\t\t<FieldShell\n\t\t\t\tid={id}\n\t\t\t\tlabel={field.label}\n\t\t\t\tdescription={typeof field.description === 'string' ? field.description : undefined}\n\t\t\t\trequired={required}\n\t\t\t\terrors={errors}\n\t\t\t\tdescribedById={describedById}\n\t\t\t>\n\t\t\t\t<Input\n\t\t\t\t\tid={id}\n\t\t\t\t\tname={name}\n\t\t\t\t\ttype=\"text\"\n\t\t\t\t\tvalue={value ?? ''}\n\t\t\t\t\tonChange={onChange}\n\t\t\t\t\tonBlur={onBlur}\n\t\t\t\t\tplaceholder={typeof field.placeholder === 'string' ? field.placeholder : undefined}\n\t\t\t\t\trequired={required}\n\t\t\t\t\tdisabled={disabled}\n\t\t\t\t\tinvalid={errors.length > 0}\n\t\t\t\t\tdescribedById={describedById}\n\t\t\t\t\tautoComplete={autoComplete}\n\t\t\t\t/>\n\t\t\t</FieldShell>\n\t\t)\n\t}\n)\n"],"mappings":";;;;;;AAMA,MAAa,eAAe,qBAC1B,EAAE,OAAO,IAAI,MAAM,OAAO,UAAU,QAAQ,QAAQ,UAAU,eAAe;CAC7E,MAAM,gBAAgB,GAAG,GAAG;CAC5B,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,MAAM,aAAa,KAAK,IAC/D,MAAM,eACN,KAAA;CACJ,OACC,oBAAC,YAAD;EACK;EACJ,OAAO,MAAM;EACb,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;EAC/D;EACF;EACO;YAEf,oBAAC,OAAD;GACK;GACE;GACN,MAAK;GACL,OAAO,SAAS;GACN;GACF;GACR,aAAa,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc,KAAA;GAC/D;GACA;GACV,SAAS,OAAO,SAAS;GACV;GACD;EACd,CAAA;CACU,CAAA;AAEd,CACD"}
|
package/dist/react/state.d.ts
CHANGED
|
@@ -4,9 +4,20 @@ type FormState = {
|
|
|
4
4
|
values: Record<string, unknown>;
|
|
5
5
|
errors: FieldErrors;
|
|
6
6
|
touched: Record<string, boolean>;
|
|
7
|
+
/**
|
|
8
|
+
* Fields whose value changed since mount or the last reset. Blur reveals a field's error only
|
|
9
|
+
* once it is dirty (or its step was attempted), so focusing and leaving a pristine field says
|
|
10
|
+
* nothing, and a reset makes every field pristine again.
|
|
11
|
+
*/
|
|
12
|
+
dirty: Record<string, boolean>;
|
|
7
13
|
submitting: boolean;
|
|
8
14
|
submitted: boolean;
|
|
9
|
-
|
|
15
|
+
/**
|
|
16
|
+
* The step ids whose validation the user has attempted (a blocked advance, or a submit). A field
|
|
17
|
+
* reveals its error when it is touched or its own step is in this set, never via a single global flag,
|
|
18
|
+
* so a submit attempt cannot pre-reveal errors on a step the visitor has not reached.
|
|
19
|
+
*/
|
|
20
|
+
attemptedSteps: Set<string>;
|
|
10
21
|
submitError?: string;
|
|
11
22
|
};
|
|
12
23
|
type FormAction = {
|
|
@@ -23,6 +34,14 @@ type FormAction = {
|
|
|
23
34
|
} | {
|
|
24
35
|
type: 'SET_ALL_ISSUES';
|
|
25
36
|
errors: FieldErrors;
|
|
37
|
+
steps: string[];
|
|
38
|
+
} | {
|
|
39
|
+
type: 'MARK_STEP_ATTEMPTED';
|
|
40
|
+
stepId: string;
|
|
41
|
+
} | {
|
|
42
|
+
type: 'REMOVE_REPEATER_ROW';
|
|
43
|
+
name: string;
|
|
44
|
+
index: number;
|
|
26
45
|
} | {
|
|
27
46
|
type: 'SUBMIT_START';
|
|
28
47
|
} | {
|
package/dist/react/state.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { isNamedField } from "../fields/fieldKey.js";
|
|
2
|
+
import { consentDisplayOf } from "../consent/effectiveStatement.js";
|
|
2
3
|
//#region src/react/state.ts
|
|
3
4
|
/**
|
|
5
|
+
* The step a field's error reveal is keyed to when the form has no flow, or the field belongs to no
|
|
6
|
+
* step. A single-step form has exactly this one step, so its reveal collapses to the old global one.
|
|
7
|
+
*/
|
|
8
|
+
const DEFAULT_STEP_ID = "__form__";
|
|
9
|
+
/**
|
|
4
10
|
* Per-field defaults for the reducer's initial state. Nameless (bare) blocks carry no value and
|
|
5
11
|
* are skipped. A repeater with a positive `minRows` starts pre-seeded with that many empty rows,
|
|
6
12
|
* matching the schema's own floor. Computed once, ahead of the reducer, so seeding is never an
|
|
@@ -12,16 +18,49 @@ const seedFieldValues = (fields) => Object.fromEntries(fields.filter(isNamedFiel
|
|
|
12
18
|
const minRows = typeof field.minRows === "number" ? field.minRows : 0;
|
|
13
19
|
if (minRows > 0) return [field.name, Array.from({ length: minRows }, () => ({}))];
|
|
14
20
|
}
|
|
21
|
+
if (field.blockType === "consent" && consentDisplayOf(field) === "notice") return [field.name, true];
|
|
15
22
|
return [field.name, void 0];
|
|
16
23
|
}));
|
|
17
24
|
const initialFormState = (values) => ({
|
|
18
25
|
values,
|
|
19
26
|
errors: {},
|
|
20
27
|
touched: {},
|
|
28
|
+
dirty: {},
|
|
21
29
|
submitting: false,
|
|
22
30
|
submitted: false,
|
|
23
|
-
|
|
31
|
+
attemptedSteps: /* @__PURE__ */ new Set()
|
|
24
32
|
});
|
|
33
|
+
/**
|
|
34
|
+
* Re-key composite entries (`name[i].sub`) after repeater row `removed` is deleted: drop the removed
|
|
35
|
+
* index and shift every higher index down by one, so surviving rows keep their own errors/touched
|
|
36
|
+
* flags instead of inheriting a deleted or shifted neighbour's. Matches on the `name[<int>]` prefix,
|
|
37
|
+
* so it is agnostic to the sub-key shape after `]` and needs no sub-field list. Returns the same
|
|
38
|
+
* reference when nothing changed, so an unrelated dispatch does not churn state identity.
|
|
39
|
+
*/
|
|
40
|
+
const reindexRepeaterKeys = (map, name, removed) => {
|
|
41
|
+
const prefix = `${name}[`;
|
|
42
|
+
let changed = false;
|
|
43
|
+
const next = {};
|
|
44
|
+
for (const [key, value] of Object.entries(map)) {
|
|
45
|
+
if (!key.startsWith(prefix)) {
|
|
46
|
+
next[key] = value;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
const close = key.indexOf("]", prefix.length);
|
|
50
|
+
const idx = close === -1 ? NaN : Number(key.slice(prefix.length, close));
|
|
51
|
+
if (!Number.isInteger(idx) || idx < removed) {
|
|
52
|
+
next[key] = value;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (idx === removed) {
|
|
56
|
+
changed = true;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
next[`${name}[${idx - 1}]${key.slice(close + 1)}`] = value;
|
|
60
|
+
changed = true;
|
|
61
|
+
}
|
|
62
|
+
return changed ? next : map;
|
|
63
|
+
};
|
|
25
64
|
/** Changing a value clears that field's prior errors (re-validated by the caller). */
|
|
26
65
|
const formReducer = (state, action) => {
|
|
27
66
|
switch (action.type) {
|
|
@@ -33,7 +72,11 @@ const formReducer = (state, action) => {
|
|
|
33
72
|
...state.values,
|
|
34
73
|
[action.name]: action.value
|
|
35
74
|
},
|
|
36
|
-
errors: restErrors
|
|
75
|
+
errors: restErrors,
|
|
76
|
+
dirty: state.dirty[action.name] ? state.dirty : {
|
|
77
|
+
...state.dirty,
|
|
78
|
+
[action.name]: true
|
|
79
|
+
}
|
|
37
80
|
};
|
|
38
81
|
}
|
|
39
82
|
case "TOUCH": return state.touched[action.name] ? state : {
|
|
@@ -53,7 +96,17 @@ const formReducer = (state, action) => {
|
|
|
53
96
|
case "SET_ALL_ISSUES": return {
|
|
54
97
|
...state,
|
|
55
98
|
errors: action.errors,
|
|
56
|
-
|
|
99
|
+
attemptedSteps: new Set([...state.attemptedSteps, ...action.steps])
|
|
100
|
+
};
|
|
101
|
+
case "MARK_STEP_ATTEMPTED": return state.attemptedSteps.has(action.stepId) ? state : {
|
|
102
|
+
...state,
|
|
103
|
+
attemptedSteps: new Set([...state.attemptedSteps, action.stepId])
|
|
104
|
+
};
|
|
105
|
+
case "REMOVE_REPEATER_ROW": return {
|
|
106
|
+
...state,
|
|
107
|
+
errors: reindexRepeaterKeys(state.errors, action.name, action.index),
|
|
108
|
+
touched: reindexRepeaterKeys(state.touched, action.name, action.index),
|
|
109
|
+
dirty: reindexRepeaterKeys(state.dirty, action.name, action.index)
|
|
57
110
|
};
|
|
58
111
|
case "SUBMIT_START": return {
|
|
59
112
|
...state,
|
|
@@ -75,6 +128,6 @@ const formReducer = (state, action) => {
|
|
|
75
128
|
}
|
|
76
129
|
};
|
|
77
130
|
//#endregion
|
|
78
|
-
export { formReducer, initialFormState, seedFieldValues };
|
|
131
|
+
export { DEFAULT_STEP_ID, formReducer, initialFormState, seedFieldValues };
|
|
79
132
|
|
|
80
133
|
//# sourceMappingURL=state.js.map
|
package/dist/react/state.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../../src/react/state.ts"],"sourcesContent":["import { isNamedField } from '../fields/fieldKey'\nimport type { FormFieldInstance } from '../submissions/types'\n\nexport type FieldErrors = Record<string, string[]>\n\nexport type FormState = {\n\tvalues: Record<string, unknown>\n\terrors: FieldErrors\n\ttouched: Record<string, boolean>\n\tsubmitting: boolean\n\tsubmitted: boolean\n\
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../../src/react/state.ts"],"sourcesContent":["import { consentDisplayOf } from '../consent/effectiveStatement'\nimport { isNamedField } from '../fields/fieldKey'\nimport type { FormFieldInstance } from '../submissions/types'\n\nexport type FieldErrors = Record<string, string[]>\n\n/**\n * The step a field's error reveal is keyed to when the form has no flow, or the field belongs to no\n * step. A single-step form has exactly this one step, so its reveal collapses to the old global one.\n */\nexport const DEFAULT_STEP_ID = '__form__'\n\nexport type FormState = {\n\tvalues: Record<string, unknown>\n\terrors: FieldErrors\n\ttouched: Record<string, boolean>\n\t/**\n\t * Fields whose value changed since mount or the last reset. Blur reveals a field's error only\n\t * once it is dirty (or its step was attempted), so focusing and leaving a pristine field says\n\t * nothing, and a reset makes every field pristine again.\n\t */\n\tdirty: Record<string, boolean>\n\tsubmitting: boolean\n\tsubmitted: boolean\n\t/**\n\t * The step ids whose validation the user has attempted (a blocked advance, or a submit). A field\n\t * reveals its error when it is touched or its own step is in this set, never via a single global flag,\n\t * so a submit attempt cannot pre-reveal errors on a step the visitor has not reached.\n\t */\n\tattemptedSteps: Set<string>\n\tsubmitError?: string\n}\n\nexport type FormAction =\n\t| { type: 'SET_VALUE'; name: string; value: unknown }\n\t| { type: 'TOUCH'; name: string }\n\t| { type: 'SET_FIELD_ISSUES'; name: string; errors: string[] }\n\t| { type: 'SET_ALL_ISSUES'; errors: FieldErrors; steps: string[] }\n\t| { type: 'MARK_STEP_ATTEMPTED'; stepId: string }\n\t| { type: 'REMOVE_REPEATER_ROW'; name: string; index: number }\n\t| { type: 'SUBMIT_START' }\n\t| { type: 'SUBMIT_SUCCESS' }\n\t| { type: 'SUBMIT_ERROR'; message: string }\n\t| { type: 'RESET'; values: Record<string, unknown> }\n\n/**\n * Per-field defaults for the reducer's initial state. Nameless (bare) blocks carry no value and\n * are skipped. A repeater with a positive `minRows` starts pre-seeded with that many empty rows,\n * matching the schema's own floor. Computed once, ahead of the reducer, so seeding is never an\n * action: it can't touch a field, trigger validation, or (via `Form`'s dispatch wrapper) be\n * mistaken for the user's first edit and fire `form.started`.\n */\nexport const seedFieldValues = (fields: FormFieldInstance[]): Record<string, unknown> =>\n\tObject.fromEntries(\n\t\tfields.filter(isNamedField).map((field) => {\n\t\t\tif (field.blockType === 'repeater') {\n\t\t\t\tconst minRows = typeof field.minRows === 'number' ? field.minRows : 0\n\t\t\t\tif (minRows > 0) {\n\t\t\t\t\treturn [field.name, Array.from({ length: minRows }, () => ({}))]\n\t\t\t\t}\n\t\t\t}\n\t\t\t// A notice-display consent has no control and the submit is the agreement, so its value\n\t\t\t// is true from the start; the server coerces the same, keeping dependent conditions and\n\t\t\t// calc in agreement across both engines.\n\t\t\tif (field.blockType === 'consent' && consentDisplayOf(field) === 'notice') {\n\t\t\t\treturn [field.name, true]\n\t\t\t}\n\t\t\treturn [field.name, undefined]\n\t\t})\n\t)\n\nexport const initialFormState = (values: Record<string, unknown>): FormState => ({\n\tvalues,\n\terrors: {},\n\ttouched: {},\n\tdirty: {},\n\tsubmitting: false,\n\tsubmitted: false,\n\tattemptedSteps: new Set(),\n})\n\n/**\n * Re-key composite entries (`name[i].sub`) after repeater row `removed` is deleted: drop the removed\n * index and shift every higher index down by one, so surviving rows keep their own errors/touched\n * flags instead of inheriting a deleted or shifted neighbour's. Matches on the `name[<int>]` prefix,\n * so it is agnostic to the sub-key shape after `]` and needs no sub-field list. Returns the same\n * reference when nothing changed, so an unrelated dispatch does not churn state identity.\n */\nconst reindexRepeaterKeys = <T>(\n\tmap: Record<string, T>,\n\tname: string,\n\tremoved: number\n): Record<string, T> => {\n\tconst prefix = `${name}[`\n\tlet changed = false\n\tconst next: Record<string, T> = {}\n\tfor (const [key, value] of Object.entries(map)) {\n\t\tif (!key.startsWith(prefix)) {\n\t\t\tnext[key] = value\n\t\t\tcontinue\n\t\t}\n\t\tconst close = key.indexOf(']', prefix.length)\n\t\tconst idx = close === -1 ? Number.NaN : Number(key.slice(prefix.length, close))\n\t\tif (!Number.isInteger(idx) || idx < removed) {\n\t\t\tnext[key] = value\n\t\t\tcontinue\n\t\t}\n\t\tif (idx === removed) {\n\t\t\tchanged = true\n\t\t\tcontinue\n\t\t}\n\t\tnext[`${name}[${idx - 1}]${key.slice(close + 1)}`] = value\n\t\tchanged = true\n\t}\n\treturn changed ? next : map\n}\n\n/** Changing a value clears that field's prior errors (re-validated by the caller). */\nexport const formReducer = (state: FormState, action: FormAction): FormState => {\n\tswitch (action.type) {\n\t\tcase 'SET_VALUE': {\n\t\t\tconst { [action.name]: _removed, ...restErrors } = state.errors\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tvalues: { ...state.values, [action.name]: action.value },\n\t\t\t\terrors: restErrors,\n\t\t\t\tdirty: state.dirty[action.name] ? state.dirty : { ...state.dirty, [action.name]: true },\n\t\t\t}\n\t\t}\n\t\tcase 'TOUCH':\n\t\t\treturn state.touched[action.name]\n\t\t\t\t? state\n\t\t\t\t: { ...state, touched: { ...state.touched, [action.name]: true } }\n\t\tcase 'SET_FIELD_ISSUES':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\terrors: { ...state.errors, [action.name]: action.errors },\n\t\t\t}\n\t\tcase 'SET_ALL_ISSUES':\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\terrors: action.errors,\n\t\t\t\tattemptedSteps: new Set([...state.attemptedSteps, ...action.steps]),\n\t\t\t}\n\t\tcase 'MARK_STEP_ATTEMPTED':\n\t\t\treturn state.attemptedSteps.has(action.stepId)\n\t\t\t\t? state\n\t\t\t\t: { ...state, attemptedSteps: new Set([...state.attemptedSteps, action.stepId]) }\n\t\tcase 'REMOVE_REPEATER_ROW':\n\t\t\t// The row value is removed by the field's own SET_VALUE; this shifts the composite issue keys\n\t\t\t// (`name[i].sub`) that a plain value array cannot carry, so a deleted row's errors never strand\n\t\t\t// on a survivor or linger unreachably.\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\terrors: reindexRepeaterKeys(state.errors, action.name, action.index),\n\t\t\t\ttouched: reindexRepeaterKeys(state.touched, action.name, action.index),\n\t\t\t\tdirty: reindexRepeaterKeys(state.dirty, action.name, action.index),\n\t\t\t}\n\t\tcase 'SUBMIT_START':\n\t\t\treturn { ...state, submitting: true, submitError: undefined }\n\t\tcase 'SUBMIT_SUCCESS':\n\t\t\treturn { ...state, submitting: false, submitted: true }\n\t\tcase 'SUBMIT_ERROR':\n\t\t\treturn { ...state, submitting: false, submitError: action.message }\n\t\tcase 'RESET':\n\t\t\treturn initialFormState(action.values)\n\t\tdefault:\n\t\t\treturn state\n\t}\n}\n"],"mappings":";;;;;;;AAUA,MAAa,kBAAkB;;;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AAO;EAAQ;EACnE,KAAK,SACJ,OAAO,iBAAiB,OAAO,MAAM;EACtC,SACC,OAAO;CACT;AACD"}
|
|
@@ -4,7 +4,14 @@ import { SubmissionValue } from "../submissions/types.js";
|
|
|
4
4
|
type SubmitFormInput = {
|
|
5
5
|
formId: number | string;
|
|
6
6
|
values: SubmissionValue[]; /** Payload API route prefix; defaults to `/api`. */
|
|
7
|
-
apiRoute?: string; /**
|
|
7
|
+
apiRoute?: string; /** The submissions collection slug, when the host renamed it; defaults to `form-submissions`. */
|
|
8
|
+
collection?: string;
|
|
9
|
+
/**
|
|
10
|
+
* The Payload content locale (a `localization` code), sent as `?locale=` so the server stamps it on
|
|
11
|
+
* the submission and the post-submit actions (confirmation emails included) render in it. Absent,
|
|
12
|
+
* the server falls back to the host's default locale.
|
|
13
|
+
*/
|
|
14
|
+
locale?: string; /** Injectable for testing; defaults to global `fetch`. */
|
|
8
15
|
fetchImpl?: typeof fetch;
|
|
9
16
|
};
|
|
10
17
|
type SubmitFormResult = {
|
|
@@ -16,15 +23,25 @@ type SubmitFormResult = {
|
|
|
16
23
|
message?: string;
|
|
17
24
|
};
|
|
18
25
|
/**
|
|
19
|
-
* The default submission transport: POST `{apiRoute}/form-submissions`
|
|
26
|
+
* The default submission transport: POST `{apiRoute}/{collection}` (`form-submissions` unless the
|
|
27
|
+
* host renamed it; with `?locale=` when a
|
|
28
|
+
* `locale` is given) carrying `{ form, values }`. On 201
|
|
20
29
|
* returns the created submission id; on a 400 Payload `ValidationError` maps `data.errors[].path` to
|
|
21
30
|
* per-field messages; otherwise returns a generic message. Pure: inject `fetchImpl` in tests.
|
|
22
31
|
*/
|
|
23
32
|
declare const submitForm: (input: SubmitFormInput) => Promise<SubmitFormResult>;
|
|
24
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* A consumer override for the transport: given the form id + values, resolve to a submit result.
|
|
35
|
+
* `locale` is the `<Form>`'s `submissionLocale` prop (absent when the prop was not passed); forward
|
|
36
|
+
* it as `?locale=` so the submission and its emails carry the visitor's locale. `collection` is
|
|
37
|
+
* `<Form collections.formSubmissions>` (absent unless set), so a handler that forwards its input to
|
|
38
|
+
* `submitForm` reaches a renamed collection unchanged.
|
|
39
|
+
*/
|
|
25
40
|
type SubmitHandler = (input: {
|
|
26
41
|
formId: number | string;
|
|
27
42
|
values: SubmissionValue[];
|
|
43
|
+
locale?: string;
|
|
44
|
+
collection?: string;
|
|
28
45
|
}) => Promise<SubmitFormResult>;
|
|
29
46
|
//#endregion
|
|
30
47
|
export { SubmitFormResult, SubmitHandler, submitForm };
|
package/dist/react/submitForm.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { DEFAULT_COLLECTION_SLUGS } from "../plugin/collectionSlugs.js";
|
|
1
2
|
//#region src/react/submitForm.ts
|
|
2
3
|
const toFieldErrors = (body) => {
|
|
3
4
|
const nested = body.errors?.[0]?.data?.errors ?? [];
|
|
@@ -6,15 +7,18 @@ const toFieldErrors = (body) => {
|
|
|
6
7
|
return map;
|
|
7
8
|
};
|
|
8
9
|
/**
|
|
9
|
-
* The default submission transport: POST `{apiRoute}/form-submissions`
|
|
10
|
+
* The default submission transport: POST `{apiRoute}/{collection}` (`form-submissions` unless the
|
|
11
|
+
* host renamed it; with `?locale=` when a
|
|
12
|
+
* `locale` is given) carrying `{ form, values }`. On 201
|
|
10
13
|
* returns the created submission id; on a 400 Payload `ValidationError` maps `data.errors[].path` to
|
|
11
14
|
* per-field messages; otherwise returns a generic message. Pure: inject `fetchImpl` in tests.
|
|
12
15
|
*/
|
|
13
16
|
const submitForm = async (input) => {
|
|
14
|
-
const { formId, values, apiRoute = "/api", fetchImpl = fetch } = input;
|
|
17
|
+
const { formId, values, apiRoute = "/api", collection = DEFAULT_COLLECTION_SLUGS.formSubmissions, locale, fetchImpl = fetch } = input;
|
|
18
|
+
const query = locale ? `?locale=${encodeURIComponent(locale)}` : "";
|
|
15
19
|
let response;
|
|
16
20
|
try {
|
|
17
|
-
response = await fetchImpl(`${apiRoute}
|
|
21
|
+
response = await fetchImpl(`${apiRoute}/${collection}${query}`, {
|
|
18
22
|
method: "POST",
|
|
19
23
|
headers: { "Content-Type": "application/json" },
|
|
20
24
|
body: JSON.stringify({
|
|
@@ -49,7 +53,7 @@ const submitForm = async (input) => {
|
|
|
49
53
|
}
|
|
50
54
|
return {
|
|
51
55
|
ok: false,
|
|
52
|
-
message: `Request failed (${response.status})`
|
|
56
|
+
message: (await response.json().catch(() => ({}))).errors?.[0]?.message ?? `Request failed (${response.status})`
|
|
53
57
|
};
|
|
54
58
|
};
|
|
55
59
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"submitForm.js","names":[],"sources":["../../src/react/submitForm.ts"],"sourcesContent":["import type { SubmissionValue } from '../submissions/types'\n\nexport type SubmitFormInput = {\n\tformId: number | string\n\tvalues: SubmissionValue[]\n\t/** Payload API route prefix; defaults to `/api`. */\n\tapiRoute?: string\n\t/** Injectable for testing; defaults to global `fetch`. */\n\tfetchImpl?: typeof fetch\n}\n\nexport type SubmitFormResult =\n\t| { ok: true; submissionId?: string }\n\t| { ok: false; fieldErrors?: Record<string, string[]>; message?: string }\n\ntype ValidationErrorBody = {\n\terrors?: Array<{\n\t\tmessage?: string\n\t\tdata?: { errors?: Array<{ path?: string; message?: string }> }\n\t}>\n}\n\nconst toFieldErrors = (body: ValidationErrorBody): Record<string, string[]> => {\n\tconst nested = body.errors?.[0]?.data?.errors ?? []\n\tconst map: Record<string, string[]> = {}\n\tfor (const entry of nested) {\n\t\tif (typeof entry.path === 'string' && typeof entry.message === 'string') {\n\t\t\tmap[entry.path] = [...(map[entry.path] ?? []), entry.message]\n\t\t}\n\t}\n\treturn map\n}\n\n/**\n * The default submission transport: POST `{apiRoute}/form-submissions` with `{ form, values }`. On 201\n * returns the created submission id; on a 400 Payload `ValidationError` maps `data.errors[].path` to\n * per-field messages; otherwise returns a generic message. Pure: inject `fetchImpl` in tests.\n */\nexport const submitForm = async (input: SubmitFormInput): Promise<SubmitFormResult> => {\n\tconst {
|
|
1
|
+
{"version":3,"file":"submitForm.js","names":[],"sources":["../../src/react/submitForm.ts"],"sourcesContent":["import { DEFAULT_COLLECTION_SLUGS } from '../plugin/collectionSlugs'\nimport type { SubmissionValue } from '../submissions/types'\n\nexport type SubmitFormInput = {\n\tformId: number | string\n\tvalues: SubmissionValue[]\n\t/** Payload API route prefix; defaults to `/api`. */\n\tapiRoute?: string\n\t/** The submissions collection slug, when the host renamed it; defaults to `form-submissions`. */\n\tcollection?: string\n\t/**\n\t * The Payload content locale (a `localization` code), sent as `?locale=` so the server stamps it on\n\t * the submission and the post-submit actions (confirmation emails included) render in it. Absent,\n\t * the server falls back to the host's default locale.\n\t */\n\tlocale?: string\n\t/** Injectable for testing; defaults to global `fetch`. */\n\tfetchImpl?: typeof fetch\n}\n\nexport type SubmitFormResult =\n\t| { ok: true; submissionId?: string }\n\t| { ok: false; fieldErrors?: Record<string, string[]>; message?: string }\n\ntype ValidationErrorBody = {\n\terrors?: Array<{\n\t\tmessage?: string\n\t\tdata?: { errors?: Array<{ path?: string; message?: string }> }\n\t}>\n}\n\nconst toFieldErrors = (body: ValidationErrorBody): Record<string, string[]> => {\n\tconst nested = body.errors?.[0]?.data?.errors ?? []\n\tconst map: Record<string, string[]> = {}\n\tfor (const entry of nested) {\n\t\tif (typeof entry.path === 'string' && typeof entry.message === 'string') {\n\t\t\tmap[entry.path] = [...(map[entry.path] ?? []), entry.message]\n\t\t}\n\t}\n\treturn map\n}\n\n/**\n * The default submission transport: POST `{apiRoute}/{collection}` (`form-submissions` unless the\n * host renamed it; with `?locale=` when a\n * `locale` is given) carrying `{ form, values }`. On 201\n * returns the created submission id; on a 400 Payload `ValidationError` maps `data.errors[].path` to\n * per-field messages; otherwise returns a generic message. Pure: inject `fetchImpl` in tests.\n */\nexport const submitForm = async (input: SubmitFormInput): Promise<SubmitFormResult> => {\n\tconst {\n\t\tformId,\n\t\tvalues,\n\t\tapiRoute = '/api',\n\t\tcollection = DEFAULT_COLLECTION_SLUGS.formSubmissions,\n\t\tlocale,\n\t\tfetchImpl = fetch,\n\t} = input\n\tconst query = locale ? `?locale=${encodeURIComponent(locale)}` : ''\n\tlet response: Response\n\ttry {\n\t\tresponse = await fetchImpl(`${apiRoute}/${collection}${query}`, {\n\t\t\tmethod: 'POST',\n\t\t\theaders: { 'Content-Type': 'application/json' },\n\t\t\tbody: JSON.stringify({ form: formId, values }),\n\t\t})\n\t} catch (error) {\n\t\treturn { ok: false, message: error instanceof Error ? error.message : 'Network error' }\n\t}\n\tif (response.ok) {\n\t\tconst data = (await response.json().catch(() => ({}))) as { doc?: { id?: number | string } }\n\t\tconst id = data.doc?.id\n\t\treturn { ok: true, submissionId: id === undefined ? undefined : String(id) }\n\t}\n\tif (response.status === 400) {\n\t\tconst body = (await response.json().catch(() => ({}))) as ValidationErrorBody\n\t\tconst fieldErrors = toFieldErrors(body)\n\t\tif (Object.keys(fieldErrors).length > 0) {\n\t\t\treturn { ok: false, fieldErrors }\n\t\t}\n\t\treturn { ok: false, message: body.errors?.[0]?.message ?? 'Validation failed' }\n\t}\n\t// A non-400 failure can still carry a server-authored message worth showing verbatim, e.g. the\n\t// translated essential-action rejection; fall back to the generic line when there is none.\n\tconst body = (await response.json().catch(() => ({}))) as ValidationErrorBody\n\tconst message = body.errors?.[0]?.message\n\treturn { ok: false, message: message ?? `Request failed (${response.status})` }\n}\n\n/**\n * A consumer override for the transport: given the form id + values, resolve to a submit result.\n * `locale` is the `<Form>`'s `submissionLocale` prop (absent when the prop was not passed); forward\n * it as `?locale=` so the submission and its emails carry the visitor's locale. `collection` is\n * `<Form collections.formSubmissions>` (absent unless set), so a handler that forwards its input to\n * `submitForm` reaches a renamed collection unchanged.\n */\nexport type SubmitHandler = (input: {\n\tformId: number | string\n\tvalues: SubmissionValue[]\n\tlocale?: string\n\tcollection?: string\n}) => Promise<SubmitFormResult>\n"],"mappings":";;AA+BA,MAAM,iBAAiB,SAAwD;CAC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,CAAC,EAAE,GAC/B,SAAS,IAAI,WACM,mBAAmB,SAAS,OAAO;CAAG;AAC/E"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/react/useCalcValues.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Live computed calculation values (field name -> number), recomputed as answers change. For
|
|
4
|
+
* composed frontends (custom layouts over `useFormContext`/`FormFields`) that render running
|
|
5
|
+
* totals without re-evaluating expressions themselves.
|
|
6
|
+
*/
|
|
7
|
+
declare const useCalcValues: () => Record<string, number>;
|
|
8
|
+
//#endregion
|
|
9
|
+
export { useCalcValues };
|
|
10
|
+
//# sourceMappingURL=useCalcValues.d.ts.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useFormContext } from "./FormContext.js";
|
|
3
|
+
//#region src/react/useCalcValues.ts
|
|
4
|
+
/**
|
|
5
|
+
* Live computed calculation values (field name -> number), recomputed as answers change. For
|
|
6
|
+
* composed frontends (custom layouts over `useFormContext`/`FormFields`) that render running
|
|
7
|
+
* totals without re-evaluating expressions themselves.
|
|
8
|
+
*/
|
|
9
|
+
const useCalcValues = () => useFormContext().calcValues ?? {};
|
|
10
|
+
//#endregion
|
|
11
|
+
export { useCalcValues };
|
|
12
|
+
|
|
13
|
+
//# sourceMappingURL=useCalcValues.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useCalcValues.js","names":[],"sources":["../../src/react/useCalcValues.ts"],"sourcesContent":["'use client'\n\nimport { useFormContext } from './FormContext'\n\n/**\n * Live computed calculation values (field name -> number), recomputed as answers change. For\n * composed frontends (custom layouts over `useFormContext`/`FormFields`) that render running\n * totals without re-evaluating expressions themselves.\n */\nexport const useCalcValues = (): Record<string, number> => useFormContext().calcValues ?? {}\n"],"mappings":";;;;;;;;AASA,MAAa,sBAA8C,eAAe,EAAE,cAAc,CAAC"}
|
package/dist/react/useField.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useFormContext } from "./FormContext.js";
|
|
3
|
+
import "./state.js";
|
|
3
4
|
import { useCallback } from "react";
|
|
4
5
|
//#region src/react/useField.ts
|
|
5
6
|
/** Bind one field by name to the form controller: its value, issues, and change/blur handlers. */
|
|
6
7
|
const useField = (name) => {
|
|
7
|
-
const { state, dispatch, validateField } = useFormContext();
|
|
8
|
+
const { state, dispatch, validateField, stepIdOfField } = useFormContext();
|
|
8
9
|
const touched = state.touched[name] ?? false;
|
|
9
|
-
const
|
|
10
|
+
const dirty = state.dirty[name] ?? false;
|
|
11
|
+
const stepAttempted = state.attemptedSteps.has(stepIdOfField?.(name) ?? "__form__");
|
|
12
|
+
const showIssues = touched && dirty || stepAttempted;
|
|
10
13
|
const value = state.values[name];
|
|
11
14
|
const setValue = useCallback((next) => {
|
|
12
15
|
dispatch({
|
|
@@ -14,12 +17,11 @@ const useField = (name) => {
|
|
|
14
17
|
name,
|
|
15
18
|
value: next
|
|
16
19
|
});
|
|
17
|
-
if (
|
|
20
|
+
if (showIssues) validateField(name, next);
|
|
18
21
|
}, [
|
|
19
22
|
dispatch,
|
|
20
23
|
name,
|
|
21
|
-
|
|
22
|
-
state.submitAttempted,
|
|
24
|
+
showIssues,
|
|
23
25
|
validateField
|
|
24
26
|
]);
|
|
25
27
|
const onBlur = useCallback(() => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useField.js","names":[],"sources":["../../src/react/useField.ts"],"sourcesContent":["'use client'\n\nimport { useCallback } from 'react'\nimport { useFormContext } from './FormContext'\n\nexport type UseFieldResult<TValue = unknown> = {\n\tvalue: TValue | undefined\n\terrors: string[]\n\ttouched: boolean\n\tsetValue: (value: TValue) => void\n\t/** Mark touched and validate now (call on blur). */\n\tonBlur: () => void\n}\n\n/** Bind one field by name to the form controller: its value, issues, and change/blur handlers. */\nexport const useField = <TValue = unknown>(name: string): UseFieldResult<TValue> => {\n\tconst { state, dispatch, validateField } = useFormContext()\n\tconst touched = state.touched[name] ?? false\n\tconst
|
|
1
|
+
{"version":3,"file":"useField.js","names":[],"sources":["../../src/react/useField.ts"],"sourcesContent":["'use client'\n\nimport { useCallback } from 'react'\nimport { useFormContext } from './FormContext'\nimport { DEFAULT_STEP_ID } from './state'\n\nexport type UseFieldResult<TValue = unknown> = {\n\tvalue: TValue | undefined\n\terrors: string[]\n\ttouched: boolean\n\tsetValue: (value: TValue) => void\n\t/** Mark touched and validate now (call on blur). */\n\tonBlur: () => void\n}\n\n/** Bind one field by name to the form controller: its value, issues, and change/blur handlers. */\nexport const useField = <TValue = unknown>(name: string): UseFieldResult<TValue> => {\n\tconst { state, dispatch, validateField, stepIdOfField } = useFormContext()\n\tconst touched = state.touched[name] ?? false\n\tconst dirty = state.dirty[name] ?? false\n\t// Reveal is a function of this field's own step, never a single global flag: the field's error\n\t// shows once it is touched AND dirty (a pristine blur, focus-then-leave, reveals nothing), or\n\t// once the step it belongs to has been attempted (a blocked advance or submit).\n\tconst stepAttempted = state.attemptedSteps.has(stepIdOfField?.(name) ?? DEFAULT_STEP_ID)\n\tconst showIssues = (touched && dirty) || stepAttempted\n\tconst value = state.values[name] as TValue | undefined\n\n\tconst setValue = useCallback(\n\t\t(next: TValue) => {\n\t\t\tdispatch({ type: 'SET_VALUE', name, value: next })\n\t\t\t// Re-validate on change only once the error is already revealed; never reveal an untouched field mid-typing.\n\t\t\tif (showIssues) {\n\t\t\t\tvalidateField(name, next)\n\t\t\t}\n\t\t},\n\t\t[dispatch, name, showIssues, validateField]\n\t)\n\n\tconst onBlur = useCallback(() => {\n\t\tdispatch({ type: 'TOUCH', name })\n\t\tvalidateField(name, value)\n\t}, [dispatch, name, validateField, value])\n\n\treturn {\n\t\tvalue,\n\t\terrors: showIssues ? (state.errors[name] ?? []) : [],\n\t\ttouched,\n\t\tsetValue,\n\t\tonBlur,\n\t}\n}\n"],"mappings":";;;;;;AAgBA,MAAa,YAA8B,SAAyC;CACnF,MAAM,EAAE,OAAO,UAAU,eAAe,kBAAkB,eAAe;CACzE,MAAM,UAAU,MAAM,QAAQ,SAAS;CACvC,MAAM,QAAQ,MAAM,MAAM,SAAS;CAInC,MAAM,gBAAgB,MAAM,eAAe,IAAI,gBAAgB,IAAI,KAAA,UAAoB;CACvF,MAAM,aAAc,WAAW,SAAU;CACzC,MAAM,QAAQ,MAAM,OAAO;CAE3B,MAAM,WAAW,aACf,SAAiB;EACjB,SAAS;GAAE,MAAM;GAAa;GAAM,OAAO;EAAK,CAAC;EAEjD,IAAI,YACH,cAAc,MAAM,IAAI;CAE1B,GACA;EAAC;EAAU;EAAM;EAAY;CAAa,CAC3C;CAEA,MAAM,SAAS,kBAAkB;EAChC,SAAS;GAAE,MAAM;GAAS;EAAK,CAAC;EAChC,cAAc,MAAM,KAAK;CAC1B,GAAG;EAAC;EAAU;EAAM;EAAe;CAAK,CAAC;CAEzC,OAAO;EACN;EACA,QAAQ,aAAc,MAAM,OAAO,SAAS,CAAC,IAAK,CAAC;EACnD;EACA;EACA;CACD;AACD"}
|