@10x-media/form-builder 0.1.0-beta.9 → 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 +173 -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 +48 -13
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +8 -1
- 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 +10 -0
- package/dist/react/state.js +45 -1
- 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 +2 -1
- 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 +78 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +78 -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 +76 -1
- package/dist/translations/keys.js +76 -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 +24 -16
- package/styles/form-builder.css +84 -0
package/dist/react/Poll.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { keys } from "../translations/keys.js";
|
|
3
|
-
import { isPollClosed } from "../form/pollState.js";
|
|
3
|
+
import { isPollClosed, pollConfigOf } from "../form/pollState.js";
|
|
4
|
+
import { answerValues } from "../poll/votes/answerValues.js";
|
|
4
5
|
import { en } from "../translations/en.js";
|
|
5
6
|
import { makeTranslate } from "../translations/makeTranslate.js";
|
|
6
7
|
import { Form } from "./Form.js";
|
|
@@ -9,17 +10,28 @@ import { fetchFormResults } from "./fetchResults.js";
|
|
|
9
10
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
10
11
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
11
12
|
//#region src/react/Poll.tsx
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
13
|
+
const localStorageVoteStorage = {
|
|
14
|
+
read: (key) => {
|
|
15
|
+
try {
|
|
16
|
+
return window.localStorage.getItem(key) != null;
|
|
17
|
+
} catch {
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
write: (key) => {
|
|
22
|
+
try {
|
|
23
|
+
window.localStorage.setItem(key, "1");
|
|
24
|
+
} catch {}
|
|
17
25
|
}
|
|
18
26
|
};
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
27
|
+
/** `false` disables client persistence entirely (`hasVoted` still marks voted). */
|
|
28
|
+
const noopVoteStorage = {
|
|
29
|
+
read: () => false,
|
|
30
|
+
write: () => {}
|
|
31
|
+
};
|
|
32
|
+
const resolveVoteStorage = (configured) => {
|
|
33
|
+
if (configured === false) return noopVoteStorage;
|
|
34
|
+
return configured ?? localStorageVoteStorage;
|
|
23
35
|
};
|
|
24
36
|
/**
|
|
25
37
|
* A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows
|
|
@@ -33,22 +45,33 @@ const writeVoted = (key) => {
|
|
|
33
45
|
* integrity (bypassable): server-enforced
|
|
34
46
|
* one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.
|
|
35
47
|
*/
|
|
36
|
-
const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchFormResults, apiRoute, onSuccess, ...formProps }) => {
|
|
48
|
+
const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchFormResults, apiRoute, onSuccess, currentVote, renderResults, ...formProps }) => {
|
|
49
|
+
const renderResultsView = renderResults ?? ((props) => /* @__PURE__ */ jsx(FormResults, { ...props }));
|
|
37
50
|
const key = storageKey ?? `fb-poll-${formProps.form.id}`;
|
|
38
51
|
const poll = formProps.form.poll;
|
|
39
52
|
const closed = isPollClosed(poll);
|
|
53
|
+
const allowChange = pollConfigOf(poll)?.allowChange === true;
|
|
40
54
|
const winningValues = poll?.outcome?.winningValues;
|
|
41
55
|
const finalized = Array.isArray(winningValues) && winningValues.length > 0;
|
|
42
56
|
const resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === "afterClose";
|
|
43
|
-
const [voted, setVoted] = useState(
|
|
57
|
+
const [voted, setVoted] = useState(hasVoted === true || currentVote != null);
|
|
58
|
+
const [changing, setChanging] = useState(false);
|
|
59
|
+
const [pick, setPick] = useState(currentVote?.pick);
|
|
60
|
+
const [prefill, setPrefill] = useState(currentVote?.value);
|
|
61
|
+
const [changeReady, setChangeReady] = useState(currentVote != null);
|
|
44
62
|
const [results, setResults] = useState(null);
|
|
45
63
|
const [loadFailed, setLoadFailed] = useState(false);
|
|
46
64
|
const translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t]);
|
|
65
|
+
const configuredVoteStorage = formProps.adapters?.voteStorage;
|
|
66
|
+
const voteStorage = useMemo(() => resolveVoteStorage(configuredVoteStorage), [configuredVoteStorage]);
|
|
67
|
+
const formsCollection = formProps.collections?.forms;
|
|
47
68
|
const loadResults = useCallback(async () => {
|
|
48
69
|
const result = await fetchResultsImpl({
|
|
49
70
|
formId: formProps.form.id,
|
|
50
71
|
field: resultsField,
|
|
51
|
-
apiRoute
|
|
72
|
+
apiRoute,
|
|
73
|
+
...formsCollection ? { collection: formsCollection } : {},
|
|
74
|
+
locale: formProps.submissionLocale
|
|
52
75
|
});
|
|
53
76
|
if (result.ok) {
|
|
54
77
|
setResults(result.results);
|
|
@@ -58,7 +81,9 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
|
|
|
58
81
|
fetchResultsImpl,
|
|
59
82
|
formProps.form.id,
|
|
60
83
|
resultsField,
|
|
61
|
-
apiRoute
|
|
84
|
+
apiRoute,
|
|
85
|
+
formsCollection,
|
|
86
|
+
formProps.submissionLocale
|
|
62
87
|
]);
|
|
63
88
|
const resultsError = /* @__PURE__ */ jsx("p", {
|
|
64
89
|
className: "fb-poll__error",
|
|
@@ -66,36 +91,47 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
|
|
|
66
91
|
children: translate(keys.pollResultsError)
|
|
67
92
|
});
|
|
68
93
|
useEffect(() => {
|
|
69
|
-
const already = hasVoted === true ||
|
|
94
|
+
const already = hasVoted === true || currentVote != null || voteStorage.read(key);
|
|
70
95
|
if (already) setVoted(true);
|
|
71
96
|
if (already && !resultsAwaitClose || closed || finalized) loadResults();
|
|
72
97
|
}, [
|
|
73
98
|
hasVoted,
|
|
99
|
+
currentVote,
|
|
74
100
|
key,
|
|
75
101
|
loadResults,
|
|
76
102
|
closed,
|
|
77
103
|
resultsAwaitClose,
|
|
78
|
-
finalized
|
|
104
|
+
finalized,
|
|
105
|
+
voteStorage
|
|
79
106
|
]);
|
|
80
107
|
const handleSuccess = useCallback((submissionId, result) => {
|
|
81
|
-
|
|
108
|
+
voteStorage.write(key);
|
|
82
109
|
setVoted(true);
|
|
110
|
+
setChanging(false);
|
|
111
|
+
setChangeReady(true);
|
|
112
|
+
if (result?.values) {
|
|
113
|
+
setPrefill(result.values.find((row) => row.field === resultsField)?.value);
|
|
114
|
+
setPick(answerValues(result.values, resultsField));
|
|
115
|
+
}
|
|
83
116
|
if (!resultsAwaitClose) loadResults();
|
|
84
117
|
onSuccess?.(submissionId, result);
|
|
85
118
|
}, [
|
|
86
119
|
key,
|
|
87
120
|
loadResults,
|
|
88
121
|
onSuccess,
|
|
89
|
-
resultsAwaitClose
|
|
122
|
+
resultsAwaitClose,
|
|
123
|
+
voteStorage,
|
|
124
|
+
resultsField
|
|
90
125
|
]);
|
|
91
126
|
if (finalized) return /* @__PURE__ */ jsxs("div", {
|
|
92
127
|
className: "fb-poll fb-poll--final",
|
|
93
128
|
children: [/* @__PURE__ */ jsx("p", {
|
|
94
129
|
className: "fb-poll__final",
|
|
95
130
|
children: translate(keys.pollFinalResult)
|
|
96
|
-
}), loadFailed ? resultsError : results ?
|
|
131
|
+
}), loadFailed ? resultsError : results ? renderResultsView({
|
|
97
132
|
results,
|
|
98
133
|
winningValues,
|
|
134
|
+
currentValues: pick,
|
|
99
135
|
t: formProps.t,
|
|
100
136
|
locale: formProps.locale
|
|
101
137
|
}) : null]
|
|
@@ -105,26 +141,41 @@ const Poll = ({ resultsField, storageKey, hasVoted, fetchResultsImpl = fetchForm
|
|
|
105
141
|
children: [/* @__PURE__ */ jsx("p", {
|
|
106
142
|
className: "fb-poll__closed",
|
|
107
143
|
children: translate(keys.pollClosed)
|
|
108
|
-
}), loadFailed ? resultsError : results ?
|
|
144
|
+
}), loadFailed ? resultsError : results ? renderResultsView({
|
|
109
145
|
results,
|
|
146
|
+
currentValues: pick,
|
|
110
147
|
t: formProps.t,
|
|
111
148
|
locale: formProps.locale
|
|
112
149
|
}) : null]
|
|
113
150
|
});
|
|
114
|
-
if (voted) {
|
|
151
|
+
if (voted && !changing) {
|
|
115
152
|
if (resultsAwaitClose) return /* @__PURE__ */ jsx("p", {
|
|
116
153
|
className: "fb-poll__await-close",
|
|
117
154
|
children: translate(keys.pollResultsAfterClose)
|
|
118
155
|
});
|
|
119
156
|
if (loadFailed) return resultsError;
|
|
120
|
-
return results ? /* @__PURE__ */
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
157
|
+
return results ? /* @__PURE__ */ jsxs("div", {
|
|
158
|
+
className: "fb-poll fb-poll--voted",
|
|
159
|
+
children: [renderResultsView({
|
|
160
|
+
results,
|
|
161
|
+
currentValues: pick,
|
|
162
|
+
t: formProps.t,
|
|
163
|
+
locale: formProps.locale
|
|
164
|
+
}), allowChange && changeReady ? /* @__PURE__ */ jsx("button", {
|
|
165
|
+
className: "fb-poll__change",
|
|
166
|
+
type: "button",
|
|
167
|
+
onClick: () => setChanging(true),
|
|
168
|
+
children: translate(keys.pollChangeVote)
|
|
169
|
+
}) : null]
|
|
124
170
|
}) : null;
|
|
125
171
|
}
|
|
172
|
+
const initialValues = changing && prefill !== void 0 ? {
|
|
173
|
+
...formProps.initialValues ?? {},
|
|
174
|
+
[resultsField]: prefill
|
|
175
|
+
} : formProps.initialValues;
|
|
126
176
|
return /* @__PURE__ */ jsx(Form, {
|
|
127
177
|
...formProps,
|
|
178
|
+
initialValues,
|
|
128
179
|
apiRoute,
|
|
129
180
|
onSuccess: handleSuccess
|
|
130
181
|
});
|
package/dist/react/Poll.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Poll.js","names":[],"sources":["../../src/react/Poll.tsx"],"sourcesContent":["'use client'\n\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { isPollClosed } from '../form/pollState'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport { Form, type FormProps } from './Form'\nimport { FormResults } from './FormResults'\nimport { type FetchResultsResult, fetchFormResults } from './fetchResults'\n\nexport type PollProps = FormProps & {\n\t/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */\n\tresultsField: string\n\t/** localStorage key for the per-browser voted guard. Default `fb-poll-{form.id}`. */\n\tstorageKey?: string\n\t/**\n\t * Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;\n\t * `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`\n\t * option pass `hasVotedCookie(cookieHeader, form.id)` here.\n\t */\n\thasVoted?: boolean\n\t/**\n\t * Injectable results fetch (testing); defaults to `fetchFormResults`. Pass a stable reference (module\n\t * scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.\n\t */\n\tfetchResultsImpl?: typeof fetchFormResults\n}\n\nconst readVoted = (key: string): boolean => {\n\ttry {\n\t\treturn window.localStorage.getItem(key) != null\n\t} catch {\n\t\treturn false\n\t}\n}\n\nconst writeVoted = (key: string): void => {\n\ttry {\n\t\twindow.localStorage.setItem(key, '1')\n\t} catch {\n\t\t// Private mode / storage disabled: the guard is best-effort UX, never integrity.\n\t}\n}\n\n/**\n * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows\n * `<FormResults>`. Lifecycle comes from `form.poll`: past `closesAt` the poll is closed (a translated\n * notice plus results, which the endpoint serves for any visibility once closed); a voted-but-open\n * `afterClose` poll shows a translated wait notice instead of fetching (the endpoint would refuse). A\n * recorded `outcome.winningValues` (via `resolvePollOutcome`) supersedes everything: a translated final\n * notice plus results with every winning bucket highlighted (a tie highlights more than one). A\n * per-browser localStorage flag (`storageKey`) skips straight to results on revisit; `hasVoted: true`\n * (e.g. from the server-set voted cookie) marks voted regardless of localStorage. The guard is UX, not\n * integrity (bypassable): server-enforced\n * one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.\n */\nexport const Poll = ({\n\tresultsField,\n\tstorageKey,\n\thasVoted,\n\tfetchResultsImpl = fetchFormResults,\n\tapiRoute,\n\tonSuccess,\n\t...formProps\n}: PollProps) => {\n\tconst key = storageKey ?? `fb-poll-${formProps.form.id}`\n\tconst poll = formProps.form.poll\n\tconst closed = isPollClosed(poll)\n\tconst winningValues = poll?.outcome?.winningValues\n\tconst finalized = Array.isArray(winningValues) && winningValues.length > 0\n\tconst resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === 'afterClose'\n\tconst [voted, setVoted] = useState(false)\n\tconst [results, setResults] = useState<FieldAggregation[] | null>(null)\n\tconst [loadFailed, setLoadFailed] = useState(false)\n\tconst translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t])\n\n\tconst loadResults = useCallback(async () => {\n\t\tconst result: FetchResultsResult = await fetchResultsImpl({\n\t\t\tformId: formProps.form.id,\n\t\t\tfield: resultsField,\n\t\t\tapiRoute,\n\t\t})\n\t\t// A failed load surfaces as an error, not an empty result set: `[]` would read as \"no votes yet\".\n\t\tif (result.ok) {\n\t\t\tsetResults(result.results)\n\t\t\tsetLoadFailed(false)\n\t\t} else {\n\t\t\tsetLoadFailed(true)\n\t\t}\n\t}, [fetchResultsImpl, formProps.form.id, resultsField, apiRoute])\n\n\tconst resultsError = (\n\t\t<p className=\"fb-poll__error\" role=\"alert\">\n\t\t\t{translate(keys.pollResultsError)}\n\t\t</p>\n\t)\n\n\tuseEffect(() => {\n\t\tconst already = hasVoted === true || readVoted(key)\n\t\tif (already) {\n\t\t\tsetVoted(true)\n\t\t}\n\t\tif ((already && !resultsAwaitClose) || closed || finalized) {\n\t\t\tvoid loadResults()\n\t\t}\n\t}, [hasVoted, key, loadResults, closed, resultsAwaitClose, finalized])\n\n\tconst handleSuccess = useCallback<NonNullable<FormProps['onSuccess']>>(\n\t\t(submissionId, result) => {\n\t\t\twriteVoted(key)\n\t\t\tsetVoted(true)\n\t\t\tif (!resultsAwaitClose) {\n\t\t\t\tvoid loadResults()\n\t\t\t}\n\t\t\t// Forward the resolved success response so a Poll host gets the same onSuccess payload as a Form host.\n\t\t\tonSuccess?.(submissionId, result)\n\t\t},\n\t\t[key, loadResults, onSuccess, resultsAwaitClose]\n\t)\n\n\tif (finalized) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--final\">\n\t\t\t\t<p className=\"fb-poll__final\">{translate(keys.pollFinalResult)}</p>\n\t\t\t\t{loadFailed ? (\n\t\t\t\t\tresultsError\n\t\t\t\t) : results ? (\n\t\t\t\t\t<FormResults\n\t\t\t\t\t\tresults={results}\n\t\t\t\t\t\twinningValues={winningValues}\n\t\t\t\t\t\tt={formProps.t}\n\t\t\t\t\t\tlocale={formProps.locale}\n\t\t\t\t\t/>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (closed) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--closed\">\n\t\t\t\t<p className=\"fb-poll__closed\">{translate(keys.pollClosed)}</p>\n\t\t\t\t{loadFailed ? (\n\t\t\t\t\tresultsError\n\t\t\t\t) : results ? (\n\t\t\t\t\t<FormResults results={results} t={formProps.t} locale={formProps.locale} />\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (voted) {\n\t\tif (resultsAwaitClose) {\n\t\t\treturn <p className=\"fb-poll__await-close\">{translate(keys.pollResultsAfterClose)}</p>\n\t\t}\n\t\tif (loadFailed) {\n\t\t\treturn resultsError\n\t\t}\n\t\treturn results ? (\n\t\t\t<FormResults results={results} t={formProps.t} locale={formProps.locale} />\n\t\t) : null\n\t}\n\n\treturn <Form {...formProps} apiRoute={apiRoute} onSuccess={handleSuccess} />\n}\n"],"mappings":";;;;;;;;;;;AA8BA,MAAM,aAAa,QAAyB;CAC3C,IAAI;EACH,OAAO,OAAO,aAAa,QAAQ,GAAG,KAAK;CAC5C,QAAQ;EACP,OAAO;CACR;AACD;AAEA,MAAM,cAAc,QAAsB;CACzC,IAAI;EACH,OAAO,aAAa,QAAQ,KAAK,GAAG;CACrC,QAAQ,CAER;AACD;;;;;;;;;;;;;AAcA,MAAa,QAAQ,EACpB,cACA,YACA,UACA,mBAAmB,kBACnB,UACA,WACA,GAAG,gBACa;CAChB,MAAM,MAAM,cAAc,WAAW,UAAU,KAAK;CACpD,MAAM,OAAO,UAAU,KAAK;CAC5B,MAAM,SAAS,aAAa,IAAI;CAChC,MAAM,gBAAgB,MAAM,SAAS;CACrC,MAAM,YAAY,MAAM,QAAQ,aAAa,KAAK,cAAc,SAAS;CACzE,MAAM,oBAAoB,CAAC,UAAU,CAAC,aAAa,MAAM,sBAAsB;CAC/E,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,MAAM,CAAC,SAAS,cAAc,SAAoC,IAAI;CACtE,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,YAAY,cAAc,UAAU,KAAK,cAAc,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;CAE/E,MAAM,cAAc,YAAY,YAAY;EAC3C,MAAM,SAA6B,MAAM,iBAAiB;GACzD,QAAQ,UAAU,KAAK;GACvB,OAAO;GACP;EACD,CAAC;EAED,IAAI,OAAO,IAAI;GACd,WAAW,OAAO,OAAO;GACzB,cAAc,KAAK;EACpB,OACC,cAAc,IAAI;CAEpB,GAAG;EAAC;EAAkB,UAAU,KAAK;EAAI;EAAc;CAAQ,CAAC;CAEhE,MAAM,eACL,oBAAC,KAAD;EAAG,WAAU;EAAiB,MAAK;YACjC,UAAU,KAAK,gBAAgB;CAC9B,CAAA;CAGJ,gBAAgB;EACf,MAAM,UAAU,aAAa,QAAQ,UAAU,GAAG;EAClD,IAAI,SACH,SAAS,IAAI;EAEd,IAAK,WAAW,CAAC,qBAAsB,UAAU,WAChD,YAAiB;CAEnB,GAAG;EAAC;EAAU;EAAK;EAAa;EAAQ;EAAmB;CAAS,CAAC;CAErE,MAAM,gBAAgB,aACpB,cAAc,WAAW;EACzB,WAAW,GAAG;EACd,SAAS,IAAI;EACb,IAAI,CAAC,mBACJ,YAAiB;EAGlB,YAAY,cAAc,MAAM;CACjC,GACA;EAAC;EAAK;EAAa;EAAW;CAAiB,CAChD;CAEA,IAAI,WACH,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf,CACC,oBAAC,KAAD;GAAG,WAAU;aAAkB,UAAU,KAAK,eAAe;EAAK,CAAA,GACjE,aACA,eACG,UACH,oBAAC,aAAD;GACU;GACM;GACf,GAAG,UAAU;GACb,QAAQ,UAAU;EAClB,CAAA,IACE,IACA;;CAIP,IAAI,QACH,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf,CACC,oBAAC,KAAD;GAAG,WAAU;aAAmB,UAAU,KAAK,UAAU;EAAK,CAAA,GAC7D,aACA,eACG,UACH,oBAAC,aAAD;GAAsB;GAAS,GAAG,UAAU;GAAG,QAAQ,UAAU;EAAS,CAAA,IACvE,IACA;;CAIP,IAAI,OAAO;EACV,IAAI,mBACH,OAAO,oBAAC,KAAD;GAAG,WAAU;aAAwB,UAAU,KAAK,qBAAqB;EAAK,CAAA;EAEtF,IAAI,YACH,OAAO;EAER,OAAO,UACN,oBAAC,aAAD;GAAsB;GAAS,GAAG,UAAU;GAAG,QAAQ,UAAU;EAAS,CAAA,IACvE;CACL;CAEA,OAAO,oBAAC,MAAD;EAAM,GAAI;EAAqB;EAAU,WAAW;CAAgB,CAAA;AAC5E"}
|
|
1
|
+
{"version":3,"file":"Poll.js","names":[],"sources":["../../src/react/Poll.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { isPollClosed, pollConfigOf } from '../form/pollState'\nimport { answerValues } from '../poll/votes/answerValues'\nimport type { VotedSubmission } from '../submissions/resolveVotedSubmission'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport type { VoteStorage } from './adapters'\nimport { Form, type FormProps } from './Form'\nimport { FormResults, type FormResultsProps } from './FormResults'\nimport { type FetchResultsResult, fetchFormResults } from './fetchResults'\n\nexport type PollProps = FormProps & {\n\t/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */\n\tresultsField: string\n\t/**\n\t * Key for the per-browser voted guard (localStorage by default; overridable or disabled via\n\t * `adapters.voteStorage`). Default `fb-poll-{form.id}`.\n\t */\n\tstorageKey?: string\n\t/**\n\t * Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;\n\t * `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`\n\t * option pass `hasVotedCookie(cookieHeader, form.id, payload)` here.\n\t */\n\thasVoted?: boolean\n\t/**\n\t * Injectable results fetch (testing); defaults to `fetchFormResults`. Pass a stable reference (module\n\t * scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.\n\t */\n\tfetchResultsImpl?: typeof fetchFormResults\n\t/**\n\t * The voter's server-resolved current vote (`resolveVotedSubmission`, read from the httpOnly voted\n\t * cookie). Presence implies voted; `pick` marks the voter's option in results and `value` prefills\n\t * the form when they change their vote. Read at mount: after a client-side change the component\n\t * tracks the new pick itself.\n\t */\n\tcurrentVote?: Pick<VotedSubmission, 'value' | 'pick'> | null\n\t/**\n\t * Replaces the built-in `<FormResults>` wherever the poll shows results (after voting, when\n\t * closed, and for a recorded outcome). Receives exactly what `<FormResults>` receives at that\n\t * site, so the default is `(props) => <FormResults {...props} />`; surrounding chrome (the\n\t * closed/final notices, the change-vote button) stays the poll's.\n\t */\n\trenderResults?: (props: FormResultsProps) => ReactNode\n}\n\nconst localStorageVoteStorage: VoteStorage = {\n\tread: (key) => {\n\t\ttry {\n\t\t\treturn window.localStorage.getItem(key) != null\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t},\n\twrite: (key) => {\n\t\ttry {\n\t\t\twindow.localStorage.setItem(key, '1')\n\t\t} catch {\n\t\t\t// Private mode / storage disabled: the guard is best-effort UX, never integrity.\n\t\t}\n\t},\n}\n\n/** `false` disables client persistence entirely (`hasVoted` still marks voted). */\nconst noopVoteStorage: VoteStorage = { read: () => false, write: () => {} }\n\nconst resolveVoteStorage = (configured: VoteStorage | false | undefined): VoteStorage => {\n\tif (configured === false) {\n\t\treturn noopVoteStorage\n\t}\n\treturn configured ?? localStorageVoteStorage\n}\n\n/**\n * A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows\n * `<FormResults>`. Lifecycle comes from `form.poll`: past `closesAt` the poll is closed (a translated\n * notice plus results, which the endpoint serves for any visibility once closed); a voted-but-open\n * `afterClose` poll shows a translated wait notice instead of fetching (the endpoint would refuse). A\n * recorded `outcome.winningValues` (via `resolvePollOutcome`) supersedes everything: a translated final\n * notice plus results with every winning bucket highlighted (a tie highlights more than one). A\n * per-browser localStorage flag (`storageKey`) skips straight to results on revisit; `hasVoted: true`\n * (e.g. from the server-set voted cookie) marks voted regardless of localStorage. The guard is UX, not\n * integrity (bypassable): server-enforced\n * one-per-identity dedup composes via `req.user` (authed forms) or a `notAlreadySubmitted` rule.\n */\nexport const Poll = ({\n\tresultsField,\n\tstorageKey,\n\thasVoted,\n\tfetchResultsImpl = fetchFormResults,\n\tapiRoute,\n\tonSuccess,\n\tcurrentVote,\n\trenderResults,\n\t...formProps\n}: PollProps) => {\n\tconst renderResultsView =\n\t\trenderResults ?? ((props: FormResultsProps): ReactNode => <FormResults {...props} />)\n\tconst key = storageKey ?? `fb-poll-${formProps.form.id}`\n\tconst poll = formProps.form.poll\n\tconst closed = isPollClosed(poll)\n\tconst allowChange = pollConfigOf(poll)?.allowChange === true\n\tconst winningValues = poll?.outcome?.winningValues\n\tconst finalized = Array.isArray(winningValues) && winningValues.length > 0\n\tconst resultsAwaitClose = !closed && !finalized && poll?.resultsVisibility === 'afterClose'\n\t// Server-known voted state renders the results view on the very first paint; the effect below\n\t// only adds the localStorage read.\n\tconst [voted, setVoted] = useState(hasVoted === true || currentVote != null)\n\tconst [changing, setChanging] = useState(false)\n\tconst [pick, setPick] = useState<string[] | undefined>(currentVote?.pick)\n\tconst [prefill, setPrefill] = useState<unknown>(currentVote?.value)\n\t// Changing is offered only when the signed cookie verifiably identifies a submission: at mount\n\t// via a resolved `currentVote`, or after an in-session vote (the server just issued the cookie).\n\t// A localStorage-only voted flag proves nothing about the cookie, and a \"change\" without one\n\t// would create a second submission instead of updating.\n\tconst [changeReady, setChangeReady] = useState(currentVote != null)\n\tconst [results, setResults] = useState<FieldAggregation[] | null>(null)\n\tconst [loadFailed, setLoadFailed] = useState(false)\n\tconst translate = useMemo(() => formProps.t ?? makeTranslate(en), [formProps.t])\n\tconst configuredVoteStorage = formProps.adapters?.voteStorage\n\tconst voteStorage = useMemo(\n\t\t() => resolveVoteStorage(configuredVoteStorage),\n\t\t[configuredVoteStorage]\n\t)\n\n\tconst formsCollection = formProps.collections?.forms\n\tconst loadResults = useCallback(async () => {\n\t\tconst result: FetchResultsResult = await fetchResultsImpl({\n\t\t\tformId: formProps.form.id,\n\t\t\tfield: resultsField,\n\t\t\tapiRoute,\n\t\t\t...(formsCollection ? { collection: formsCollection } : {}),\n\t\t\tlocale: formProps.submissionLocale,\n\t\t})\n\t\t// A failed load surfaces as an error, not an empty result set: `[]` would read as \"no votes yet\".\n\t\tif (result.ok) {\n\t\t\tsetResults(result.results)\n\t\t\tsetLoadFailed(false)\n\t\t} else {\n\t\t\tsetLoadFailed(true)\n\t\t}\n\t}, [\n\t\tfetchResultsImpl,\n\t\tformProps.form.id,\n\t\tresultsField,\n\t\tapiRoute,\n\t\tformsCollection,\n\t\tformProps.submissionLocale,\n\t])\n\n\tconst resultsError = (\n\t\t<p className=\"fb-poll__error\" role=\"alert\">\n\t\t\t{translate(keys.pollResultsError)}\n\t\t</p>\n\t)\n\n\tuseEffect(() => {\n\t\tconst already = hasVoted === true || currentVote != null || voteStorage.read(key)\n\t\tif (already) {\n\t\t\tsetVoted(true)\n\t\t}\n\t\tif ((already && !resultsAwaitClose) || closed || finalized) {\n\t\t\tvoid loadResults()\n\t\t}\n\t}, [hasVoted, currentVote, key, loadResults, closed, resultsAwaitClose, finalized, voteStorage])\n\n\tconst handleSuccess = useCallback<NonNullable<FormProps['onSuccess']>>(\n\t\t(submissionId, result) => {\n\t\t\tvoteStorage.write(key)\n\t\t\tsetVoted(true)\n\t\t\tsetChanging(false)\n\t\t\tsetChangeReady(true)\n\t\t\t// Track the pick client-side so the \"your vote\" marker is fresh right after a (re-)vote,\n\t\t\t// without waiting for a server-resolved currentVote on the next page load.\n\t\t\tif (result?.values) {\n\t\t\t\tconst entry = result.values.find((row) => row.field === resultsField)\n\t\t\t\tsetPrefill(entry?.value)\n\t\t\t\tsetPick(answerValues(result.values, resultsField))\n\t\t\t}\n\t\t\tif (!resultsAwaitClose) {\n\t\t\t\tvoid loadResults()\n\t\t\t}\n\t\t\t// Forward the resolved success response so a Poll host gets the same onSuccess payload as a Form host.\n\t\t\tonSuccess?.(submissionId, result)\n\t\t},\n\t\t[key, loadResults, onSuccess, resultsAwaitClose, voteStorage, resultsField]\n\t)\n\n\tif (finalized) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--final\">\n\t\t\t\t<p className=\"fb-poll__final\">{translate(keys.pollFinalResult)}</p>\n\t\t\t\t{loadFailed\n\t\t\t\t\t? resultsError\n\t\t\t\t\t: results\n\t\t\t\t\t\t? renderResultsView({\n\t\t\t\t\t\t\t\tresults,\n\t\t\t\t\t\t\t\twinningValues,\n\t\t\t\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\t\t\t\tt: formProps.t,\n\t\t\t\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (closed) {\n\t\treturn (\n\t\t\t<div className=\"fb-poll fb-poll--closed\">\n\t\t\t\t<p className=\"fb-poll__closed\">{translate(keys.pollClosed)}</p>\n\t\t\t\t{loadFailed\n\t\t\t\t\t? resultsError\n\t\t\t\t\t: results\n\t\t\t\t\t\t? renderResultsView({\n\t\t\t\t\t\t\t\tresults,\n\t\t\t\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\t\t\t\tt: formProps.t,\n\t\t\t\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: null}\n\t\t\t</div>\n\t\t)\n\t}\n\n\tif (voted && !changing) {\n\t\tif (resultsAwaitClose) {\n\t\t\treturn <p className=\"fb-poll__await-close\">{translate(keys.pollResultsAfterClose)}</p>\n\t\t}\n\t\tif (loadFailed) {\n\t\t\treturn resultsError\n\t\t}\n\t\treturn results ? (\n\t\t\t<div className=\"fb-poll fb-poll--voted\">\n\t\t\t\t{renderResultsView({\n\t\t\t\t\tresults,\n\t\t\t\t\tcurrentValues: pick,\n\t\t\t\t\tt: formProps.t,\n\t\t\t\t\tlocale: formProps.locale,\n\t\t\t\t})}\n\t\t\t\t{allowChange && changeReady ? (\n\t\t\t\t\t<button className=\"fb-poll__change\" type=\"button\" onClick={() => setChanging(true)}>\n\t\t\t\t\t\t{translate(keys.pollChangeVote)}\n\t\t\t\t\t</button>\n\t\t\t\t) : null}\n\t\t\t</div>\n\t\t) : null\n\t}\n\n\t// While changing, the current pick prefills the results field; the server identifies the\n\t// submission to update from the httpOnly voted cookie, so the client sends a normal submit.\n\tconst initialValues =\n\t\tchanging && prefill !== undefined\n\t\t\t? { ...(formProps.initialValues ?? {}), [resultsField]: prefill }\n\t\t\t: formProps.initialValues\n\treturn (\n\t\t<Form\n\t\t\t{...formProps}\n\t\t\tinitialValues={initialValues}\n\t\t\tapiRoute={apiRoute}\n\t\t\tonSuccess={handleSuccess}\n\t\t/>\n\t)\n}\n"],"mappings":";;;;;;;;;;;;AAmDA,MAAM,0BAAuC;CAC5C,OAAO,QAAQ;EACd,IAAI;GACH,OAAO,OAAO,aAAa,QAAQ,GAAG,KAAK;EAC5C,QAAQ;GACP,OAAO;EACR;CACD;CACA,QAAQ,QAAQ;EACf,IAAI;GACH,OAAO,aAAa,QAAQ,KAAK,GAAG;EACrC,QAAQ,CAER;CACD;AACD;;AAGA,MAAM,kBAA+B;CAAE,YAAY;CAAO,aAAa,CAAC;AAAE;AAE1E,MAAM,sBAAsB,eAA6D;CACxF,IAAI,eAAe,OAClB,OAAO;CAER,OAAO,cAAc;AACtB;;;;;;;;;;;;;AAcA,MAAa,QAAQ,EACpB,cACA,YACA,UACA,mBAAmB,kBACnB,UACA,WACA,aACA,eACA,GAAG,gBACa;CAChB,MAAM,oBACL,mBAAmB,UAAuC,oBAAC,aAAD,EAAa,GAAI,MAAQ,CAAA;CACpF,MAAM,MAAM,cAAc,WAAW,UAAU,KAAK;CACpD,MAAM,OAAO,UAAU,KAAK;CAC5B,MAAM,SAAS,aAAa,IAAI;CAChC,MAAM,cAAc,aAAa,IAAI,GAAG,gBAAgB;CACxD,MAAM,gBAAgB,MAAM,SAAS;CACrC,MAAM,YAAY,MAAM,QAAQ,aAAa,KAAK,cAAc,SAAS;CACzE,MAAM,oBAAoB,CAAC,UAAU,CAAC,aAAa,MAAM,sBAAsB;CAG/E,MAAM,CAAC,OAAO,YAAY,SAAS,aAAa,QAAQ,eAAe,IAAI;CAC3E,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,MAAM,WAAW,SAA+B,aAAa,IAAI;CACxE,MAAM,CAAC,SAAS,cAAc,SAAkB,aAAa,KAAK;CAKlE,MAAM,CAAC,aAAa,kBAAkB,SAAS,eAAe,IAAI;CAClE,MAAM,CAAC,SAAS,cAAc,SAAoC,IAAI;CACtE,MAAM,CAAC,YAAY,iBAAiB,SAAS,KAAK;CAClD,MAAM,YAAY,cAAc,UAAU,KAAK,cAAc,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;CAC/E,MAAM,wBAAwB,UAAU,UAAU;CAClD,MAAM,cAAc,cACb,mBAAmB,qBAAqB,GAC9C,CAAC,qBAAqB,CACvB;CAEA,MAAM,kBAAkB,UAAU,aAAa;CAC/C,MAAM,cAAc,YAAY,YAAY;EAC3C,MAAM,SAA6B,MAAM,iBAAiB;GACzD,QAAQ,UAAU,KAAK;GACvB,OAAO;GACP;GACA,GAAI,kBAAkB,EAAE,YAAY,gBAAgB,IAAI,CAAC;GACzD,QAAQ,UAAU;EACnB,CAAC;EAED,IAAI,OAAO,IAAI;GACd,WAAW,OAAO,OAAO;GACzB,cAAc,KAAK;EACpB,OACC,cAAc,IAAI;CAEpB,GAAG;EACF;EACA,UAAU,KAAK;EACf;EACA;EACA;EACA,UAAU;CACX,CAAC;CAED,MAAM,eACL,oBAAC,KAAD;EAAG,WAAU;EAAiB,MAAK;YACjC,UAAU,KAAK,gBAAgB;CAC9B,CAAA;CAGJ,gBAAgB;EACf,MAAM,UAAU,aAAa,QAAQ,eAAe,QAAQ,YAAY,KAAK,GAAG;EAChF,IAAI,SACH,SAAS,IAAI;EAEd,IAAK,WAAW,CAAC,qBAAsB,UAAU,WAChD,YAAiB;CAEnB,GAAG;EAAC;EAAU;EAAa;EAAK;EAAa;EAAQ;EAAmB;EAAW;CAAW,CAAC;CAE/F,MAAM,gBAAgB,aACpB,cAAc,WAAW;EACzB,YAAY,MAAM,GAAG;EACrB,SAAS,IAAI;EACb,YAAY,KAAK;EACjB,eAAe,IAAI;EAGnB,IAAI,QAAQ,QAAQ;GAEnB,WADc,OAAO,OAAO,MAAM,QAAQ,IAAI,UAAU,YACzC,GAAG,KAAK;GACvB,QAAQ,aAAa,OAAO,QAAQ,YAAY,CAAC;EAClD;EACA,IAAI,CAAC,mBACJ,YAAiB;EAGlB,YAAY,cAAc,MAAM;CACjC,GACA;EAAC;EAAK;EAAa;EAAW;EAAmB;EAAa;CAAY,CAC3E;CAEA,IAAI,WACH,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf,CACC,oBAAC,KAAD;GAAG,WAAU;aAAkB,UAAU,KAAK,eAAe;EAAK,CAAA,GACjE,aACE,eACA,UACC,kBAAkB;GAClB;GACA;GACA,eAAe;GACf,GAAG,UAAU;GACb,QAAQ,UAAU;EACnB,CAAC,IACA,IACA;;CAIP,IAAI,QACH,OACC,qBAAC,OAAD;EAAK,WAAU;YAAf,CACC,oBAAC,KAAD;GAAG,WAAU;aAAmB,UAAU,KAAK,UAAU;EAAK,CAAA,GAC7D,aACE,eACA,UACC,kBAAkB;GAClB;GACA,eAAe;GACf,GAAG,UAAU;GACb,QAAQ,UAAU;EACnB,CAAC,IACA,IACA;;CAIP,IAAI,SAAS,CAAC,UAAU;EACvB,IAAI,mBACH,OAAO,oBAAC,KAAD;GAAG,WAAU;aAAwB,UAAU,KAAK,qBAAqB;EAAK,CAAA;EAEtF,IAAI,YACH,OAAO;EAER,OAAO,UACN,qBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAkB;IAClB;IACA,eAAe;IACf,GAAG,UAAU;IACb,QAAQ,UAAU;GACnB,CAAC,GACA,eAAe,cACf,oBAAC,UAAD;IAAQ,WAAU;IAAkB,MAAK;IAAS,eAAe,YAAY,IAAI;cAC/E,UAAU,KAAK,cAAc;GACvB,CAAA,IACL,IACA;OACF;CACL;CAIA,MAAM,gBACL,YAAY,YAAY,KAAA,IACrB;EAAE,GAAI,UAAU,iBAAiB,CAAC;GAAK,eAAe;CAAQ,IAC9D,UAAU;CACd,OACC,oBAAC,MAAD;EACC,GAAI;EACW;EACL;EACV,WAAW;CACX,CAAA;AAEH"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
//#region src/react/adapters.d.ts
|
|
2
|
+
/** The plugin's navigation intent for a post-submit redirect, passed through to the adapter. */
|
|
3
|
+
type NavigateOptions = {
|
|
4
|
+
replace: boolean;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Client persistence for a poll's per-browser voted flag. `read` reports whether the flag is set;
|
|
8
|
+
* `write` sets it after a successful vote.
|
|
9
|
+
*/
|
|
10
|
+
type VoteStorage = {
|
|
11
|
+
read: (key: string) => boolean;
|
|
12
|
+
write: (key: string) => void;
|
|
13
|
+
};
|
|
14
|
+
/** Loads a third-party script and resolves once it is executable (e.g. a consent-gated loader). */
|
|
15
|
+
type LoadScript = (src: string) => Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Host-owned effects. Every member is optional and defaults to the current DOM behavior, so
|
|
18
|
+
* omitting the prop entirely preserves the default semantics exactly.
|
|
19
|
+
*
|
|
20
|
+
* - `navigate`: replaces `window.location.assign`/`.replace` for the post-submit redirect. When
|
|
21
|
+
* set, the plugin never touches `window.location` for that form; a throwing adapter propagates
|
|
22
|
+
* and never falls back to a hard navigation. Not awaited.
|
|
23
|
+
* - `voteStorage`: replaces the `<Poll>` localStorage voted-flag read/write; `false` disables
|
|
24
|
+
* client persistence entirely (e.g. when the server-side `poll.votedCookie` is the source of truth).
|
|
25
|
+
* - `loadScript`: replaces the captcha widgets' `document.head` script injection (consent
|
|
26
|
+
* managers, CSP nonces). The per-src cache and evict-on-failure retry still apply.
|
|
27
|
+
*/
|
|
28
|
+
type FormAdapters = {
|
|
29
|
+
navigate?: (url: string, options: NavigateOptions) => void;
|
|
30
|
+
voteStorage?: VoteStorage | false;
|
|
31
|
+
loadScript?: LoadScript;
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { FormAdapters, LoadScript, NavigateOptions, VoteStorage };
|
|
35
|
+
//# sourceMappingURL=adapters.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/react/adapters.ts
|
|
2
|
+
/** The default navigation: a full document load, push semantics unless `replace` is requested. */
|
|
3
|
+
const defaultNavigate = (url, options) => {
|
|
4
|
+
if (typeof window === "undefined") return;
|
|
5
|
+
if (options.replace) window.location.replace(url);
|
|
6
|
+
else window.location.assign(url);
|
|
7
|
+
};
|
|
8
|
+
//#endregion
|
|
9
|
+
export { defaultNavigate };
|
|
10
|
+
|
|
11
|
+
//# sourceMappingURL=adapters.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"adapters.js","names":[],"sources":["../../src/react/adapters.ts"],"sourcesContent":["/** The plugin's navigation intent for a post-submit redirect, passed through to the adapter. */\nexport type NavigateOptions = { replace: boolean }\n\n/**\n * Client persistence for a poll's per-browser voted flag. `read` reports whether the flag is set;\n * `write` sets it after a successful vote.\n */\nexport type VoteStorage = {\n\tread: (key: string) => boolean\n\twrite: (key: string) => void\n}\n\n/** Loads a third-party script and resolves once it is executable (e.g. a consent-gated loader). */\nexport type LoadScript = (src: string) => Promise<void>\n\n/**\n * Host-owned effects. Every member is optional and defaults to the current DOM behavior, so\n * omitting the prop entirely preserves the default semantics exactly.\n *\n * - `navigate`: replaces `window.location.assign`/`.replace` for the post-submit redirect. When\n * set, the plugin never touches `window.location` for that form; a throwing adapter propagates\n * and never falls back to a hard navigation. Not awaited.\n * - `voteStorage`: replaces the `<Poll>` localStorage voted-flag read/write; `false` disables\n * client persistence entirely (e.g. when the server-side `poll.votedCookie` is the source of truth).\n * - `loadScript`: replaces the captcha widgets' `document.head` script injection (consent\n * managers, CSP nonces). The per-src cache and evict-on-failure retry still apply.\n */\nexport type FormAdapters = {\n\tnavigate?: (url: string, options: NavigateOptions) => void\n\tvoteStorage?: VoteStorage | false\n\tloadScript?: LoadScript\n}\n\n/** The default navigation: a full document load, push semantics unless `replace` is requested. */\nexport const defaultNavigate = (url: string, options: NavigateOptions): void => {\n\tif (typeof window === 'undefined') {\n\t\treturn\n\t}\n\tif (options.replace) {\n\t\twindow.location.replace(url)\n\t} else {\n\t\twindow.location.assign(url)\n\t}\n}\n"],"mappings":";;AAkCA,MAAa,mBAAmB,KAAa,YAAmC;CAC/E,IAAI,OAAO,WAAW,aACrB;CAED,IAAI,QAAQ,SACX,OAAO,SAAS,QAAQ,GAAG;MAE3B,OAAO,SAAS,OAAO,GAAG;AAE5B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FormAdapters } from "../adapters.js";
|
|
1
2
|
import { CaptchaWidgetHandle } from "./types.js";
|
|
2
3
|
import { Ref } from "react";
|
|
3
4
|
|
|
@@ -8,7 +9,8 @@ type HcaptchaCaptchaProps = {
|
|
|
8
9
|
onToken: (token: string | null) => void; /** Extra vendor render params (theme, size, ...). */
|
|
9
10
|
options?: Record<string, unknown>;
|
|
10
11
|
className?: string; /** Override the vendor script URL. */
|
|
11
|
-
scriptSrc?: string;
|
|
12
|
+
scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
|
|
13
|
+
adapters?: Pick<FormAdapters, 'loadScript'>;
|
|
12
14
|
ref?: Ref<CaptchaWidgetHandle>;
|
|
13
15
|
};
|
|
14
16
|
/**
|
|
@@ -21,6 +23,7 @@ declare const HcaptchaCaptcha: ({
|
|
|
21
23
|
options,
|
|
22
24
|
className,
|
|
23
25
|
scriptSrc,
|
|
26
|
+
adapters,
|
|
24
27
|
ref
|
|
25
28
|
}: HcaptchaCaptchaProps) => import("react/jsx-runtime").JSX.Element;
|
|
26
29
|
//#endregion
|
|
@@ -9,14 +9,14 @@ const HCAPTCHA_SCRIPT_URL = "https://js.hcaptcha.com/1/api.js?render=explicit";
|
|
|
9
9
|
* Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,
|
|
10
10
|
* and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.
|
|
11
11
|
*/
|
|
12
|
-
const HcaptchaCaptcha = ({ siteKey, onToken, options, className, scriptSrc = HCAPTCHA_SCRIPT_URL, ref }) => {
|
|
12
|
+
const HcaptchaCaptcha = ({ siteKey, onToken, options, className, scriptSrc = HCAPTCHA_SCRIPT_URL, adapters, ref }) => {
|
|
13
13
|
const containerRef = useRef(null);
|
|
14
14
|
const widgetIdRef = useRef(null);
|
|
15
15
|
const onTokenRef = useRef(onToken);
|
|
16
16
|
onTokenRef.current = onToken;
|
|
17
17
|
const optionsRef = useRef(options);
|
|
18
18
|
optionsRef.current = options;
|
|
19
|
-
const ready = useCaptchaScript(scriptSrc);
|
|
19
|
+
const ready = useCaptchaScript(scriptSrc, adapters?.loadScript);
|
|
20
20
|
useImperativeHandle(ref, () => ({ reset: () => {
|
|
21
21
|
const api = getHcaptcha();
|
|
22
22
|
if (api && widgetIdRef.current !== null) api.reset(widgetIdRef.current);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HcaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/HcaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getHcaptcha } from './vendors'\n\nexport const HCAPTCHA_SCRIPT_URL = 'https://js.hcaptcha.com/1/api.js?render=explicit'\n\nexport type HcaptchaCaptchaProps = {\n\t/** hCaptcha site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,\n * and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const HcaptchaCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = HCAPTCHA_SCRIPT_URL,\n\tref,\n}: HcaptchaCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getHcaptcha()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getHcaptcha()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"HcaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/HcaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getHcaptcha } from './vendors'\n\nexport const HCAPTCHA_SCRIPT_URL = 'https://js.hcaptcha.com/1/api.js?render=explicit'\n\nexport type HcaptchaCaptchaProps = {\n\t/** hCaptcha site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless hCaptcha widget: loads the vendor script once, renders the widget into a bare div,\n * and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const HcaptchaCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = HCAPTCHA_SCRIPT_URL,\n\tadapters,\n\tref,\n}: HcaptchaCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc, adapters?.loadScript)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getHcaptcha()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getHcaptcha()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,sBAAsB;;;;;AAqBnC,MAAa,mBAAmB,EAC/B,SACA,SACA,SACA,WACA,YAAY,qBACZ,UACA,UAC2B;CAC3B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,WAAW,UAAU,UAAU;CAE9D,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,YAAY;EACxB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,YAAY;EACxB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FormAdapters } from "../adapters.js";
|
|
1
2
|
import { CaptchaWidgetHandle } from "./types.js";
|
|
2
3
|
import { Ref } from "react";
|
|
3
4
|
|
|
@@ -18,7 +19,8 @@ type RecaptchaCaptchaProps = {
|
|
|
18
19
|
onToken: (token: string | null) => void; /** Extra vendor render params for v2 (theme, size, ...). */
|
|
19
20
|
options?: Record<string, unknown>;
|
|
20
21
|
className?: string; /** Override the vendor script URL (the version-specific `render` query is not appended). */
|
|
21
|
-
scriptSrc?: string;
|
|
22
|
+
scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
|
|
23
|
+
adapters?: Pick<FormAdapters, 'loadScript'>;
|
|
22
24
|
ref?: Ref<RecaptchaCaptchaHandle>;
|
|
23
25
|
};
|
|
24
26
|
/**
|
|
@@ -34,6 +36,7 @@ declare const RecaptchaCaptcha: ({
|
|
|
34
36
|
options,
|
|
35
37
|
className,
|
|
36
38
|
scriptSrc,
|
|
39
|
+
adapters,
|
|
37
40
|
ref
|
|
38
41
|
}: RecaptchaCaptchaProps) => import("react/jsx-runtime").JSX.Element;
|
|
39
42
|
//#endregion
|
|
@@ -10,7 +10,7 @@ const RECAPTCHA_SCRIPT_URL = "https://www.google.com/recaptcha/api.js";
|
|
|
10
10
|
* tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes
|
|
11
11
|
* `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.
|
|
12
12
|
*/
|
|
13
|
-
const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, className, scriptSrc, ref }) => {
|
|
13
|
+
const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, className, scriptSrc, adapters, ref }) => {
|
|
14
14
|
const src = scriptSrc ?? `https://www.google.com/recaptcha/api.js?render=${version === "v3" ? siteKey : "explicit"}`;
|
|
15
15
|
const containerRef = useRef(null);
|
|
16
16
|
const widgetIdRef = useRef(null);
|
|
@@ -20,7 +20,7 @@ const RecaptchaCaptcha = ({ siteKey, version, action, onToken, options, classNam
|
|
|
20
20
|
optionsRef.current = options;
|
|
21
21
|
const actionRef = useRef(action);
|
|
22
22
|
actionRef.current = action;
|
|
23
|
-
const ready = useCaptchaScript(src);
|
|
23
|
+
const ready = useCaptchaScript(src, adapters?.loadScript);
|
|
24
24
|
const execute = useCallback(async (overrideAction) => {
|
|
25
25
|
const api = getGrecaptcha();
|
|
26
26
|
if (!api || version !== "v3") return null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RecaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/RecaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useCallback, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getGrecaptcha } from './vendors'\n\nexport const RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js'\n\nexport type RecaptchaCaptchaHandle = CaptchaWidgetHandle & {\n\t/**\n\t * v3 only: fetch a fresh token on demand and report it through `onToken`. v3 tokens expire\n\t * after about two minutes, so call this right before submit for a long-lived form. Resolves\n\t * null for v2 or when execution fails.\n\t */\n\texecute: (action?: string) => Promise<string | null>\n}\n\nexport type RecaptchaCaptchaProps = {\n\t/** reCAPTCHA site key (public). */\n\tsiteKey: string\n\t/** 'v2' renders the checkbox widget; 'v3' runs invisibly and produces score-based tokens. */\n\tversion: 'v2' | 'v3'\n\t/** v3 action name reported to reCAPTCHA. Default 'submit'. */\n\taction?: string\n\t/** Receives each fresh token, and null when the token expires, errors, or is reset. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params for v2 (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL (the version-specific `render` query is not appended). */\n\tscriptSrc?: string\n\tref?: Ref<RecaptchaCaptchaHandle>\n}\n\n/**\n * Headless Google reCAPTCHA widget for v2 (checkbox) and v3 (invisible, score-based). v2 reports\n * tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes\n * `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.\n */\nexport const RecaptchaCaptcha = ({\n\tsiteKey,\n\tversion,\n\taction,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc,\n\tref,\n}: RecaptchaCaptchaProps) => {\n\tconst src =\n\t\tscriptSrc ?? `${RECAPTCHA_SCRIPT_URL}?render=${version === 'v3' ? siteKey : 'explicit'}`\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<number | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst actionRef = useRef(action)\n\tactionRef.current = action\n\tconst ready = useCaptchaScript(src)\n\n\tconst execute = useCallback(\n\t\tasync (overrideAction?: string): Promise<string | null> => {\n\t\t\tconst api = getGrecaptcha()\n\t\t\tif (!api || version !== 'v3') {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst token = await api.execute(siteKey, {\n\t\t\t\t\taction: overrideAction ?? actionRef.current ?? 'submit',\n\t\t\t\t})\n\t\t\t\tonTokenRef.current(token)\n\t\t\t\treturn token\n\t\t\t} catch {\n\t\t\t\tonTokenRef.current(null)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[siteKey, version]\n\t)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getGrecaptcha()\n\t\t\t\tif (api && version === 'v2' && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t\texecute,\n\t\t}),\n\t\t[execute, version]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst api = getGrecaptcha()\n\t\tif (!api) {\n\t\t\treturn\n\t\t}\n\t\tlet active = true\n\t\tif (version === 'v3') {\n\t\t\tapi.ready(() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tvoid execute()\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn () => {\n\t\t\t\tactive = false\n\t\t\t}\n\t\t}\n\t\tconst container = containerRef.current\n\t\tif (!container) {\n\t\t\treturn\n\t\t}\n\t\tapi.ready(() => {\n\t\t\tif (!active || widgetIdRef.current !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twidgetIdRef.current = api.render(container, {\n\t\t\t\t...optionsRef.current,\n\t\t\t\tsitekey: siteKey,\n\t\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t\t})\n\t\t})\n\t\treturn () => {\n\t\t\tactive = false\n\t\t\tif (widgetIdRef.current !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t} catch {}\n\t\t\t\twidgetIdRef.current = null\n\t\t\t}\n\t\t\t// grecaptcha has no remove(); clearing the container drops the detached widget DOM.\n\t\t\tcontainer.replaceChildren()\n\t\t}\n\t}, [ready, siteKey, version, execute])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"RecaptchaCaptcha.js","names":[],"sources":["../../../src/react/captcha/RecaptchaCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useCallback, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getGrecaptcha } from './vendors'\n\nexport const RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js'\n\nexport type RecaptchaCaptchaHandle = CaptchaWidgetHandle & {\n\t/**\n\t * v3 only: fetch a fresh token on demand and report it through `onToken`. v3 tokens expire\n\t * after about two minutes, so call this right before submit for a long-lived form. Resolves\n\t * null for v2 or when execution fails.\n\t */\n\texecute: (action?: string) => Promise<string | null>\n}\n\nexport type RecaptchaCaptchaProps = {\n\t/** reCAPTCHA site key (public). */\n\tsiteKey: string\n\t/** 'v2' renders the checkbox widget; 'v3' runs invisibly and produces score-based tokens. */\n\tversion: 'v2' | 'v3'\n\t/** v3 action name reported to reCAPTCHA. Default 'submit'. */\n\taction?: string\n\t/** Receives each fresh token, and null when the token expires, errors, or is reset. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params for v2 (theme, size, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL (the version-specific `render` query is not appended). */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<RecaptchaCaptchaHandle>\n}\n\n/**\n * Headless Google reCAPTCHA widget for v2 (checkbox) and v3 (invisible, score-based). v2 reports\n * tokens as the user solves the challenge; v3 fetches an initial token on mount and exposes\n * `execute` on the ref for on-demand refresh. Pass the latest token to `<Form captchaToken>`.\n */\nexport const RecaptchaCaptcha = ({\n\tsiteKey,\n\tversion,\n\taction,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc,\n\tadapters,\n\tref,\n}: RecaptchaCaptchaProps) => {\n\tconst src =\n\t\tscriptSrc ?? `${RECAPTCHA_SCRIPT_URL}?render=${version === 'v3' ? siteKey : 'explicit'}`\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<number | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst actionRef = useRef(action)\n\tactionRef.current = action\n\tconst ready = useCaptchaScript(src, adapters?.loadScript)\n\n\tconst execute = useCallback(\n\t\tasync (overrideAction?: string): Promise<string | null> => {\n\t\t\tconst api = getGrecaptcha()\n\t\t\tif (!api || version !== 'v3') {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst token = await api.execute(siteKey, {\n\t\t\t\t\taction: overrideAction ?? actionRef.current ?? 'submit',\n\t\t\t\t})\n\t\t\t\tonTokenRef.current(token)\n\t\t\t\treturn token\n\t\t\t} catch {\n\t\t\t\tonTokenRef.current(null)\n\t\t\t\treturn null\n\t\t\t}\n\t\t},\n\t\t[siteKey, version]\n\t)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getGrecaptcha()\n\t\t\t\tif (api && version === 'v2' && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t\texecute,\n\t\t}),\n\t\t[execute, version]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst api = getGrecaptcha()\n\t\tif (!api) {\n\t\t\treturn\n\t\t}\n\t\tlet active = true\n\t\tif (version === 'v3') {\n\t\t\tapi.ready(() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tvoid execute()\n\t\t\t\t}\n\t\t\t})\n\t\t\treturn () => {\n\t\t\t\tactive = false\n\t\t\t}\n\t\t}\n\t\tconst container = containerRef.current\n\t\tif (!container) {\n\t\t\treturn\n\t\t}\n\t\tapi.ready(() => {\n\t\t\tif (!active || widgetIdRef.current !== null) {\n\t\t\t\treturn\n\t\t\t}\n\t\t\twidgetIdRef.current = api.render(container, {\n\t\t\t\t...optionsRef.current,\n\t\t\t\tsitekey: siteKey,\n\t\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t\t})\n\t\t})\n\t\treturn () => {\n\t\t\tactive = false\n\t\t\tif (widgetIdRef.current !== null) {\n\t\t\t\ttry {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t} catch {}\n\t\t\t\twidgetIdRef.current = null\n\t\t\t}\n\t\t\t// grecaptcha has no remove(); clearing the container drops the detached widget DOM.\n\t\t\tcontainer.replaceChildren()\n\t\t}\n\t}, [ready, siteKey, version, execute])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,uBAAuB;;;;;;AAmCpC,MAAa,oBAAoB,EAChC,SACA,SACA,QACA,SACA,SACA,WACA,WACA,UACA,UAC4B;CAC5B,MAAM,MACL,aAAa,kDAAkC,YAAY,OAAO,UAAU;CAC7E,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,YAAY,OAAO,MAAM;CAC/B,UAAU,UAAU;CACpB,MAAM,QAAQ,iBAAiB,KAAK,UAAU,UAAU;CAExD,MAAM,UAAU,YACf,OAAO,mBAAoD;EAC1D,MAAM,MAAM,cAAc;EAC1B,IAAI,CAAC,OAAO,YAAY,MACvB,OAAO;EAER,IAAI;GACH,MAAM,QAAQ,MAAM,IAAI,QAAQ,SAAS,EACxC,QAAQ,kBAAkB,UAAU,WAAW,SAChD,CAAC;GACD,WAAW,QAAQ,KAAK;GACxB,OAAO;EACR,QAAQ;GACP,WAAW,QAAQ,IAAI;GACvB,OAAO;EACR;CACD,GACA,CAAC,SAAS,OAAO,CAClB;CAEA,oBACC,YACO;EACN,aAAa;GACZ,MAAM,MAAM,cAAc;GAC1B,IAAI,OAAO,YAAY,QAAQ,YAAY,YAAY,MACtD,IAAI,MAAM,YAAY,OAAO;GAE9B,WAAW,QAAQ,IAAI;EACxB;EACA;CACD,IACA,CAAC,SAAS,OAAO,CAClB;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,MAAM,cAAc;EAC1B,IAAI,CAAC,KACJ;EAED,IAAI,SAAS;EACb,IAAI,YAAY,MAAM;GACrB,IAAI,YAAY;IACf,IAAI,QACH,QAAa;GAEf,CAAC;GACD,aAAa;IACZ,SAAS;GACV;EACD;EACA,MAAM,YAAY,aAAa;EAC/B,IAAI,CAAC,WACJ;EAED,IAAI,YAAY;GACf,IAAI,CAAC,UAAU,YAAY,YAAY,MACtC;GAED,YAAY,UAAU,IAAI,OAAO,WAAW;IAC3C,GAAG,WAAW;IACd,SAAS;IACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;IACrD,0BAA0B,WAAW,QAAQ,IAAI;IACjD,wBAAwB,WAAW,QAAQ,IAAI;GAChD,CAAC;EACF,CAAC;EACD,aAAa;GACZ,SAAS;GACT,IAAI,YAAY,YAAY,MAAM;IACjC,IAAI;KACH,IAAI,MAAM,YAAY,OAAO;IAC9B,QAAQ,CAAC;IACT,YAAY,UAAU;GACvB;GAEA,UAAU,gBAAgB;EAC3B;CACD,GAAG;EAAC;EAAO;EAAS;EAAS;CAAO,CAAC;CAErC,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FormAdapters } from "../adapters.js";
|
|
1
2
|
import { CaptchaWidgetHandle } from "./types.js";
|
|
2
3
|
import { Ref } from "react";
|
|
3
4
|
|
|
@@ -8,7 +9,8 @@ type TurnstileCaptchaProps = {
|
|
|
8
9
|
onToken: (token: string | null) => void; /** Extra vendor render params (theme, size, appearance, ...). */
|
|
9
10
|
options?: Record<string, unknown>;
|
|
10
11
|
className?: string; /** Override the vendor script URL. */
|
|
11
|
-
scriptSrc?: string;
|
|
12
|
+
scriptSrc?: string; /** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */
|
|
13
|
+
adapters?: Pick<FormAdapters, 'loadScript'>;
|
|
12
14
|
ref?: Ref<CaptchaWidgetHandle>;
|
|
13
15
|
};
|
|
14
16
|
/**
|
|
@@ -21,6 +23,7 @@ declare const TurnstileCaptcha: ({
|
|
|
21
23
|
options,
|
|
22
24
|
className,
|
|
23
25
|
scriptSrc,
|
|
26
|
+
adapters,
|
|
24
27
|
ref
|
|
25
28
|
}: TurnstileCaptchaProps) => import("react/jsx-runtime").JSX.Element;
|
|
26
29
|
//#endregion
|
|
@@ -9,14 +9,14 @@ const TURNSTILE_SCRIPT_URL = "https://challenges.cloudflare.com/turnstile/v0/api
|
|
|
9
9
|
* Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a
|
|
10
10
|
* bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.
|
|
11
11
|
*/
|
|
12
|
-
const TurnstileCaptcha = ({ siteKey, onToken, options, className, scriptSrc = TURNSTILE_SCRIPT_URL, ref }) => {
|
|
12
|
+
const TurnstileCaptcha = ({ siteKey, onToken, options, className, scriptSrc = TURNSTILE_SCRIPT_URL, adapters, ref }) => {
|
|
13
13
|
const containerRef = useRef(null);
|
|
14
14
|
const widgetIdRef = useRef(null);
|
|
15
15
|
const onTokenRef = useRef(onToken);
|
|
16
16
|
onTokenRef.current = onToken;
|
|
17
17
|
const optionsRef = useRef(options);
|
|
18
18
|
optionsRef.current = options;
|
|
19
|
-
const ready = useCaptchaScript(scriptSrc);
|
|
19
|
+
const ready = useCaptchaScript(scriptSrc, adapters?.loadScript);
|
|
20
20
|
useImperativeHandle(ref, () => ({ reset: () => {
|
|
21
21
|
const api = getTurnstile();
|
|
22
22
|
if (api && widgetIdRef.current !== null) api.reset(widgetIdRef.current);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TurnstileCaptcha.js","names":[],"sources":["../../../src/react/captcha/TurnstileCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getTurnstile } from './vendors'\n\nexport const TURNSTILE_SCRIPT_URL =\n\t'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'\n\nexport type TurnstileCaptchaProps = {\n\t/** Turnstile site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, appearance, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a\n * bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const TurnstileCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = TURNSTILE_SCRIPT_URL,\n\tref,\n}: TurnstileCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getTurnstile()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getTurnstile()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"TurnstileCaptcha.js","names":[],"sources":["../../../src/react/captcha/TurnstileCaptcha.tsx"],"sourcesContent":["'use client'\n\nimport { type Ref, useEffect, useImperativeHandle, useRef } from 'react'\nimport type { FormAdapters } from '../adapters'\nimport type { CaptchaWidgetHandle } from './types'\nimport { useCaptchaScript } from './useCaptchaScript'\nimport { getTurnstile } from './vendors'\n\nexport const TURNSTILE_SCRIPT_URL =\n\t'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'\n\nexport type TurnstileCaptchaProps = {\n\t/** Turnstile site key (public). */\n\tsiteKey: string\n\t/** Receives each fresh token, and null when the token expires or errors. */\n\tonToken: (token: string | null) => void\n\t/** Extra vendor render params (theme, size, appearance, ...). */\n\toptions?: Record<string, unknown>\n\tclassName?: string\n\t/** Override the vendor script URL. */\n\tscriptSrc?: string\n\t/** Host-owned effects; only `loadScript` applies here (consent-gated or CSP-nonced script loading). */\n\tadapters?: Pick<FormAdapters, 'loadScript'>\n\tref?: Ref<CaptchaWidgetHandle>\n}\n\n/**\n * Headless Cloudflare Turnstile widget: loads the vendor script once, renders the widget into a\n * bare div, and reports tokens through `onToken`. Pass the latest token to `<Form captchaToken>`.\n */\nexport const TurnstileCaptcha = ({\n\tsiteKey,\n\tonToken,\n\toptions,\n\tclassName,\n\tscriptSrc = TURNSTILE_SCRIPT_URL,\n\tadapters,\n\tref,\n}: TurnstileCaptchaProps) => {\n\tconst containerRef = useRef<HTMLDivElement>(null)\n\tconst widgetIdRef = useRef<string | null>(null)\n\tconst onTokenRef = useRef(onToken)\n\tonTokenRef.current = onToken\n\tconst optionsRef = useRef(options)\n\toptionsRef.current = options\n\tconst ready = useCaptchaScript(scriptSrc, adapters?.loadScript)\n\n\tuseImperativeHandle(\n\t\tref,\n\t\t() => ({\n\t\t\treset: () => {\n\t\t\t\tconst api = getTurnstile()\n\t\t\t\tif (api && widgetIdRef.current !== null) {\n\t\t\t\t\tapi.reset(widgetIdRef.current)\n\t\t\t\t}\n\t\t\t\tonTokenRef.current(null)\n\t\t\t},\n\t\t}),\n\t\t[]\n\t)\n\n\tuseEffect(() => {\n\t\tif (!ready) {\n\t\t\treturn\n\t\t}\n\t\tconst container = containerRef.current\n\t\tconst api = getTurnstile()\n\t\tif (!container || !api) {\n\t\t\treturn\n\t\t}\n\t\tconst widgetId = api.render(container, {\n\t\t\t...optionsRef.current,\n\t\t\tsitekey: siteKey,\n\t\t\tcallback: (token: string) => onTokenRef.current(token),\n\t\t\t'expired-callback': () => onTokenRef.current(null),\n\t\t\t'error-callback': () => onTokenRef.current(null),\n\t\t})\n\t\twidgetIdRef.current = widgetId\n\t\treturn () => {\n\t\t\twidgetIdRef.current = null\n\t\t\ttry {\n\t\t\t\tapi.remove(widgetId)\n\t\t\t} catch {}\n\t\t}\n\t}, [ready, siteKey])\n\n\treturn <div ref={containerRef} className={className} />\n}\n"],"mappings":";;;;;;AAQA,MAAa,uBACZ;;;;;AAqBD,MAAa,oBAAoB,EAChC,SACA,SACA,SACA,WACA,YAAY,sBACZ,UACA,UAC4B;CAC5B,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAsB,IAAI;CAC9C,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CACrB,MAAM,QAAQ,iBAAiB,WAAW,UAAU,UAAU;CAE9D,oBACC,YACO,EACN,aAAa;EACZ,MAAM,MAAM,aAAa;EACzB,IAAI,OAAO,YAAY,YAAY,MAClC,IAAI,MAAM,YAAY,OAAO;EAE9B,WAAW,QAAQ,IAAI;CACxB,EACD,IACA,CAAC,CACF;CAEA,gBAAgB;EACf,IAAI,CAAC,OACJ;EAED,MAAM,YAAY,aAAa;EAC/B,MAAM,MAAM,aAAa;EACzB,IAAI,CAAC,aAAa,CAAC,KAClB;EAED,MAAM,WAAW,IAAI,OAAO,WAAW;GACtC,GAAG,WAAW;GACd,SAAS;GACT,WAAW,UAAkB,WAAW,QAAQ,KAAK;GACrD,0BAA0B,WAAW,QAAQ,IAAI;GACjD,wBAAwB,WAAW,QAAQ,IAAI;EAChD,CAAC;EACD,YAAY,UAAU;EACtB,aAAa;GACZ,YAAY,UAAU;GACtB,IAAI;IACH,IAAI,OAAO,QAAQ;GACpB,QAAQ,CAAC;EACV;CACD,GAAG,CAAC,OAAO,OAAO,CAAC;CAEnB,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAyB;CAAY,CAAA;AACvD"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { useEffect, useState } from "react";
|
|
3
3
|
//#region src/react/captcha/useCaptchaScript.ts
|
|
4
4
|
const pending = /* @__PURE__ */ new Map();
|
|
5
|
-
const
|
|
5
|
+
const injectScript = (src) => {
|
|
6
6
|
const cached = pending.get(src);
|
|
7
7
|
if (cached) return cached;
|
|
8
8
|
const promise = new Promise((resolve, reject) => {
|
|
@@ -20,23 +20,41 @@ const loadScript = (src) => {
|
|
|
20
20
|
pending.set(src, promise);
|
|
21
21
|
return promise;
|
|
22
22
|
};
|
|
23
|
+
const customCaches = /* @__PURE__ */ new WeakMap();
|
|
24
|
+
const loadThrough = (loader, src) => {
|
|
25
|
+
let cache = customCaches.get(loader);
|
|
26
|
+
if (!cache) {
|
|
27
|
+
cache = /* @__PURE__ */ new Map();
|
|
28
|
+
customCaches.set(loader, cache);
|
|
29
|
+
}
|
|
30
|
+
const cached = cache.get(src);
|
|
31
|
+
if (cached) return cached;
|
|
32
|
+
const promise = loader(src).catch((error) => {
|
|
33
|
+
cache.delete(src);
|
|
34
|
+
throw error;
|
|
35
|
+
});
|
|
36
|
+
cache.set(src, promise);
|
|
37
|
+
return promise;
|
|
38
|
+
};
|
|
23
39
|
/**
|
|
24
40
|
* Load a vendor captcha script once per src, shared across all widget instances. SSR-safe (the
|
|
25
41
|
* DOM is only touched inside the effect). A failed load evicts the cache entry so a later mount
|
|
26
|
-
* can retry; consumers just see `ready` stay false.
|
|
42
|
+
* can retry; consumers just see `ready` stay false. A host `loadScript` (e.g. a consent-gated
|
|
43
|
+
* loader) replaces the `document.head` injection; pass a stable reference, since a new function
|
|
44
|
+
* identity re-runs the load with a fresh cache.
|
|
27
45
|
*/
|
|
28
|
-
const useCaptchaScript = (src) => {
|
|
46
|
+
const useCaptchaScript = (src, loadScript) => {
|
|
29
47
|
const [ready, setReady] = useState(false);
|
|
30
48
|
useEffect(() => {
|
|
31
49
|
let active = true;
|
|
32
50
|
setReady(false);
|
|
33
|
-
loadScript(src).then(() => {
|
|
51
|
+
(loadScript ? loadThrough(loadScript, src) : injectScript(src)).then(() => {
|
|
34
52
|
if (active) setReady(true);
|
|
35
53
|
}, () => {});
|
|
36
54
|
return () => {
|
|
37
55
|
active = false;
|
|
38
56
|
};
|
|
39
|
-
}, [src]);
|
|
57
|
+
}, [src, loadScript]);
|
|
40
58
|
return ready;
|
|
41
59
|
};
|
|
42
60
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCaptchaScript.js","names":[],"sources":["../../../src/react/captcha/useCaptchaScript.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useState } from 'react'\n\nconst pending = new Map<string, Promise<void>>()\n\nconst
|
|
1
|
+
{"version":3,"file":"useCaptchaScript.js","names":[],"sources":["../../../src/react/captcha/useCaptchaScript.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useState } from 'react'\nimport type { LoadScript } from '../adapters'\n\nconst pending = new Map<string, Promise<void>>()\n\nconst injectScript = (src: string): Promise<void> => {\n\tconst cached = pending.get(src)\n\tif (cached) {\n\t\treturn cached\n\t}\n\tconst promise = new Promise<void>((resolve, reject) => {\n\t\tconst script = document.createElement('script')\n\t\tscript.src = src\n\t\tscript.async = true\n\t\tscript.addEventListener('load', () => resolve())\n\t\tscript.addEventListener('error', () => {\n\t\t\tpending.delete(src)\n\t\t\tscript.remove()\n\t\t\treject(new Error(`Failed to load ${src}`))\n\t\t})\n\t\tdocument.head.appendChild(script)\n\t})\n\tpending.set(src, promise)\n\treturn promise\n}\n\n// A custom loader gets the same per-src cache and evict-on-failure retry, keyed per loader so two\n// adapters (or the default injector) never share entries.\nconst customCaches = new WeakMap<LoadScript, Map<string, Promise<void>>>()\n\nconst loadThrough = (loader: LoadScript, src: string): Promise<void> => {\n\tlet cache = customCaches.get(loader)\n\tif (!cache) {\n\t\tcache = new Map()\n\t\tcustomCaches.set(loader, cache)\n\t}\n\tconst cached = cache.get(src)\n\tif (cached) {\n\t\treturn cached\n\t}\n\tconst promise = loader(src).catch((error) => {\n\t\tcache.delete(src)\n\t\tthrow error\n\t})\n\tcache.set(src, promise)\n\treturn promise\n}\n\n/**\n * Load a vendor captcha script once per src, shared across all widget instances. SSR-safe (the\n * DOM is only touched inside the effect). A failed load evicts the cache entry so a later mount\n * can retry; consumers just see `ready` stay false. A host `loadScript` (e.g. a consent-gated\n * loader) replaces the `document.head` injection; pass a stable reference, since a new function\n * identity re-runs the load with a fresh cache.\n */\nexport const useCaptchaScript = (src: string, loadScript?: LoadScript): boolean => {\n\tconst [ready, setReady] = useState(false)\n\tuseEffect(() => {\n\t\tlet active = true\n\t\tsetReady(false)\n\t\tconst load = loadScript ? loadThrough(loadScript, src) : injectScript(src)\n\t\tload.then(\n\t\t\t() => {\n\t\t\t\tif (active) {\n\t\t\t\t\tsetReady(true)\n\t\t\t\t}\n\t\t\t},\n\t\t\t() => {}\n\t\t)\n\t\treturn () => {\n\t\t\tactive = false\n\t\t}\n\t}, [src, loadScript])\n\treturn ready\n}\n"],"mappings":";;;AAKA,MAAM,0BAAU,IAAI,IAA2B;AAE/C,MAAM,gBAAgB,QAA+B;CACpD,MAAM,SAAS,QAAQ,IAAI,GAAG;CAC9B,IAAI,QACH,OAAO;CAER,MAAM,UAAU,IAAI,SAAe,SAAS,WAAW;EACtD,MAAM,SAAS,SAAS,cAAc,QAAQ;EAC9C,OAAO,MAAM;EACb,OAAO,QAAQ;EACf,OAAO,iBAAiB,cAAc,QAAQ,CAAC;EAC/C,OAAO,iBAAiB,eAAe;GACtC,QAAQ,OAAO,GAAG;GAClB,OAAO,OAAO;GACd,uBAAO,IAAI,MAAM,kBAAkB,KAAK,CAAC;EAC1C,CAAC;EACD,SAAS,KAAK,YAAY,MAAM;CACjC,CAAC;CACD,QAAQ,IAAI,KAAK,OAAO;CACxB,OAAO;AACR;AAIA,MAAM,+BAAe,IAAI,QAAgD;AAEzE,MAAM,eAAe,QAAoB,QAA+B;CACvE,IAAI,QAAQ,aAAa,IAAI,MAAM;CACnC,IAAI,CAAC,OAAO;EACX,wBAAQ,IAAI,IAAI;EAChB,aAAa,IAAI,QAAQ,KAAK;CAC/B;CACA,MAAM,SAAS,MAAM,IAAI,GAAG;CAC5B,IAAI,QACH,OAAO;CAER,MAAM,UAAU,OAAO,GAAG,EAAE,OAAO,UAAU;EAC5C,MAAM,OAAO,GAAG;EAChB,MAAM;CACP,CAAC;CACD,MAAM,IAAI,KAAK,OAAO;CACtB,OAAO;AACR;;;;;;;;AASA,MAAa,oBAAoB,KAAa,eAAqC;CAClF,MAAM,CAAC,OAAO,YAAY,SAAS,KAAK;CACxC,gBAAgB;EACf,IAAI,SAAS;EACb,SAAS,KAAK;EAEd,CADa,aAAa,YAAY,YAAY,GAAG,IAAI,aAAa,GAAG,GACpE,WACE;GACL,IAAI,QACH,SAAS,IAAI;EAEf,SACM,CAAC,CACR;EACA,aAAa;GACZ,SAAS;EACV;CACD,GAAG,CAAC,KAAK,UAAU,CAAC;CACpB,OAAO;AACR"}
|
|
@@ -4,7 +4,9 @@ import { FieldAggregation } from "../aggregation/types.js";
|
|
|
4
4
|
type FetchResultsInput = {
|
|
5
5
|
formId: number | string; /** Restrict to one field. Omit to get every public/enumerable field. */
|
|
6
6
|
field?: string; /** Payload API route prefix; defaults to `/api`. */
|
|
7
|
-
apiRoute?: string; /**
|
|
7
|
+
apiRoute?: string; /** The forms collection slug, when the host renamed it; defaults to `forms`. */
|
|
8
|
+
collection?: string; /** The Payload content locale (a `localization` code) option labels are returned in, sent as `?locale=`. */
|
|
9
|
+
locale?: string; /** Injectable for testing; defaults to global `fetch`. */
|
|
8
10
|
fetchImpl?: typeof fetch;
|
|
9
11
|
};
|
|
10
12
|
type FetchResultsResult = {
|
|
@@ -16,8 +18,9 @@ type FetchResultsResult = {
|
|
|
16
18
|
};
|
|
17
19
|
/**
|
|
18
20
|
* Fetch aggregate poll/survey results from the form-builder results endpoint
|
|
19
|
-
* (`GET {apiRoute}/
|
|
20
|
-
* access by the form's poll opt-in and
|
|
21
|
+
* (`GET {apiRoute}/{collection}/:id/results`, `forms` unless the host renamed it). Returns the
|
|
22
|
+
* server-resolved aggregations; the endpoint gates public access by the form's poll opt-in and
|
|
23
|
+
* results visibility. Pure: inject `fetchImpl` in tests.
|
|
21
24
|
*/
|
|
22
25
|
declare const fetchFormResults: (input: FetchResultsInput) => Promise<FetchResultsResult>;
|
|
23
26
|
//#endregion
|
|
@@ -1,15 +1,20 @@
|
|
|
1
|
+
import { DEFAULT_COLLECTION_SLUGS } from "../plugin/collectionSlugs.js";
|
|
1
2
|
//#region src/react/fetchResults.ts
|
|
2
3
|
/**
|
|
3
4
|
* Fetch aggregate poll/survey results from the form-builder results endpoint
|
|
4
|
-
* (`GET {apiRoute}/
|
|
5
|
-
* access by the form's poll opt-in and
|
|
5
|
+
* (`GET {apiRoute}/{collection}/:id/results`, `forms` unless the host renamed it). Returns the
|
|
6
|
+
* server-resolved aggregations; the endpoint gates public access by the form's poll opt-in and
|
|
7
|
+
* results visibility. Pure: inject `fetchImpl` in tests.
|
|
6
8
|
*/
|
|
7
9
|
const fetchFormResults = async (input) => {
|
|
8
|
-
const { formId, field, apiRoute = "/api", fetchImpl = fetch } = input;
|
|
9
|
-
const
|
|
10
|
+
const { formId, field, apiRoute = "/api", collection = DEFAULT_COLLECTION_SLUGS.forms, locale, fetchImpl = fetch } = input;
|
|
11
|
+
const params = new URLSearchParams();
|
|
12
|
+
if (field) params.set("field", field);
|
|
13
|
+
if (locale) params.set("locale", locale);
|
|
14
|
+
const query = params.size > 0 ? `?${params}` : "";
|
|
10
15
|
let response;
|
|
11
16
|
try {
|
|
12
|
-
response = await fetchImpl(`${apiRoute}
|
|
17
|
+
response = await fetchImpl(`${apiRoute}/${collection}/${formId}/results${query}`, { method: "GET" });
|
|
13
18
|
} catch (error) {
|
|
14
19
|
return {
|
|
15
20
|
ok: false,
|