@10x-media/form-builder 0.1.0-beta.8 → 4.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/README.md +11 -3
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/body/serializeBody.d.ts +16 -14
- package/dist/actions/body/serializeBody.js +5 -8
- package/dist/actions/body/serializeBody.js.map +1 -1
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +15 -3
- package/dist/actions/builtin/emailAction.js +72 -20
- package/dist/actions/builtin/emailAction.js.map +1 -1
- package/dist/actions/builtin/emailTeam.js +11 -5
- package/dist/actions/builtin/emailTeam.js.map +1 -1
- package/dist/actions/defineAction.d.ts +37 -6
- package/dist/actions/defineAction.js +14 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.d.ts +12 -0
- package/dist/actions/dispatch.js +103 -30
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/dispatchContext.js +19 -0
- package/dist/actions/dispatchContext.js.map +1 -0
- package/dist/actions/emailRecipients.js +38 -8
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/emailRender.d.ts +27 -0
- package/dist/actions/fromAddresses.d.ts +19 -1
- package/dist/actions/fromAddresses.js +66 -9
- package/dist/actions/fromAddresses.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +23 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/registry.js +3 -1
- package/dist/actions/registry.js.map +1 -1
- package/dist/actions/runActions.d.ts +2 -0
- package/dist/actions/runActions.js +13 -8
- package/dist/actions/runActions.js.map +1 -1
- package/dist/actions/sign.js.map +1 -1
- package/dist/actions/submissionContext.d.ts +34 -0
- package/dist/actions/task.js +43 -16
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/aggregateResponses.js +3 -4
- package/dist/aggregation/aggregateResponses.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +69 -26
- package/dist/aggregation/resolveResultsRequest.js.map +1 -1
- package/dist/calc/computeCalcFields.d.ts +5 -3
- package/dist/calc/computeCalcFields.js +4 -3
- package/dist/calc/computeCalcFields.js.map +1 -1
- package/dist/calc/evaluate.d.ts +26 -3
- package/dist/calc/evaluate.js +33 -11
- package/dist/calc/evaluate.js.map +1 -1
- package/dist/calc/formatCalc.d.ts +11 -0
- package/dist/calc/formatCalc.js +35 -0
- package/dist/calc/formatCalc.js.map +1 -0
- package/dist/calc/formatCalcValue.d.ts +17 -0
- package/dist/calc/formatCalcValue.js +17 -0
- package/dist/calc/formatCalcValue.js.map +1 -0
- package/dist/calc/normalizeCalc.d.ts +17 -3
- package/dist/calc/normalizeCalc.js +39 -17
- package/dist/calc/normalizeCalc.js.map +1 -1
- package/dist/calc/registry.d.ts +43 -0
- package/dist/calc/registry.js +27 -0
- package/dist/calc/registry.js.map +1 -0
- package/dist/calc/resolveCalcContext.d.ts +36 -0
- package/dist/calc/resolveCalcContext.js +87 -0
- package/dist/calc/resolveCalcContext.js.map +1 -0
- package/dist/calc/types.d.ts +19 -4
- package/dist/calc/types.js +3 -2
- package/dist/calc/types.js.map +1 -1
- package/dist/client/ByteSizeField.js +11 -8
- package/dist/client/ByteSizeField.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +888 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/ClosePollButton.js +3 -3
- package/dist/client/ClosePollButton.js.map +1 -1
- package/dist/client/CondensedArray.d.ts +2 -2
- package/dist/client/CondensedArray.js +5 -7
- package/dist/client/CondensedArray.js.map +1 -1
- package/dist/client/ConditionBuilder.js +5 -7
- package/dist/client/ConditionBuilder.js.map +1 -1
- package/dist/client/ConditionRow.js +3 -3
- package/dist/client/ConditionRow.js.map +1 -1
- package/dist/client/ConsentBlockLabel.js +2 -2
- package/dist/client/ConsentBlockLabel.js.map +1 -1
- package/dist/client/ConsentRetentionNotice.d.ts +11 -0
- package/dist/client/ConsentRetentionNotice.js +23 -0
- package/dist/client/ConsentRetentionNotice.js.map +1 -0
- package/dist/client/EndpointOptionsSelect.d.ts +17 -7
- package/dist/client/EndpointOptionsSelect.js +18 -14
- package/dist/client/EndpointOptionsSelect.js.map +1 -1
- package/dist/client/FieldBlockLabel.js +2 -2
- package/dist/client/FieldBlockLabel.js.map +1 -1
- package/dist/client/FieldNameSelect.d.ts +1 -0
- package/dist/client/FieldNameSelect.js +2 -4
- package/dist/client/FieldNameSelect.js.map +1 -1
- package/dist/client/FlowBuilder.js +31 -23
- package/dist/client/FlowBuilder.js.map +1 -1
- package/dist/client/FormConditionField.js +0 -1
- package/dist/client/FormConditionField.js.map +1 -1
- package/dist/client/RecipientsSelect.d.ts +9 -2
- package/dist/client/RecipientsSelect.js +31 -10
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +345 -72
- package/dist/client/endpointOptions.d.ts +11 -0
- package/dist/client/endpointOptions.js +17 -8
- package/dist/client/endpointOptions.js.map +1 -1
- package/dist/collections/formSubmissions.js +145 -51
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +170 -65
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +31 -26
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +32 -0
- package/dist/collections/settingsFields.js +55 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/consent/captureConsent.d.ts +2 -1
- package/dist/consent/captureConsent.js +4 -1
- package/dist/consent/captureConsent.js.map +1 -1
- package/dist/consent/consentSourcesField.d.ts +7 -1
- package/dist/consent/consentSourcesField.js +15 -1
- package/dist/consent/consentSourcesField.js.map +1 -1
- package/dist/consent/effectiveStatement.js +16 -0
- package/dist/consent/effectiveStatement.js.map +1 -0
- package/dist/consent/resolveConsentSourcesRequest.js +2 -2
- package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
- package/dist/consent/resolveConsentStatements.js +3 -1
- package/dist/consent/resolveConsentStatements.js.map +1 -1
- package/dist/consent/resolvePublishedVersionRef.js +1 -0
- package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
- package/dist/consent/types.d.ts +8 -0
- package/dist/context/formContext.d.ts +30 -0
- package/dist/context/formContext.js +54 -0
- package/dist/context/formContext.js.map +1 -0
- package/dist/email/departmentsField.d.ts +6 -1
- package/dist/email/departmentsField.js +6 -1
- package/dist/email/departmentsField.js.map +1 -1
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/i18n.d.ts +14 -2
- package/dist/exports/i18n.js +14 -2
- package/dist/exports/react.d.ts +23 -5
- package/dist/exports/react.js +17 -1
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +7 -4
- package/dist/exports/types.d.ts +4 -3
- package/dist/fields/buildFieldBlocks.js +2 -1
- package/dist/fields/buildFieldBlocks.js.map +1 -1
- package/dist/fields/builtin/calculation.d.ts +17 -0
- package/dist/fields/builtin/calculation.js +70 -127
- package/dist/fields/builtin/calculation.js.map +1 -1
- package/dist/fields/builtin/checkbox.js +15 -0
- package/dist/fields/builtin/checkbox.js.map +1 -1
- package/dist/fields/builtin/consent.js +21 -1
- package/dist/fields/builtin/consent.js.map +1 -1
- package/dist/fields/builtin/email.js +7 -0
- package/dist/fields/builtin/email.js.map +1 -1
- package/dist/fields/builtin/index.d.ts +6 -2
- package/dist/fields/builtin/index.js +9 -4
- package/dist/fields/builtin/index.js.map +1 -1
- package/dist/fields/builtin/select.js +20 -1
- package/dist/fields/builtin/select.js.map +1 -1
- package/dist/fields/builtin/text.js +7 -0
- package/dist/fields/builtin/text.js.map +1 -1
- package/dist/fields/instanceOptions.js +1 -1
- package/dist/fields/instanceOptions.js.map +1 -1
- package/dist/fields/sharedConfig.js +15 -11
- package/dist/fields/sharedConfig.js.map +1 -1
- package/dist/fields/types.d.ts +8 -2
- package/dist/form/findFormAtLocale.d.ts +30 -0
- package/dist/form/findFormAtLocale.js +88 -0
- package/dist/form/findFormAtLocale.js.map +1 -0
- package/dist/form/pollState.d.ts +2 -1
- package/dist/form/pollState.js.map +1 -1
- package/dist/form/toFormDocument.d.ts +8 -0
- package/dist/form/toFormDocument.js +3 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +9 -1
- package/dist/index.d.ts +22 -6
- package/dist/index.js +63 -17
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +113 -4
- package/dist/plugin/collectionSlugs.d.ts +28 -0
- package/dist/plugin/collectionSlugs.js +65 -0
- package/dist/plugin/collectionSlugs.js.map +1 -0
- package/dist/plugin/customState.js +1 -1
- package/dist/plugin/customState.js.map +1 -1
- package/dist/plugin/registerCollections.js +38 -21
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +13 -10
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/outcomeBeforeChange.js +2 -2
- package/dist/poll/outcomeBeforeChange.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +5 -4
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOptionsRequest.js +2 -2
- package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +20 -6
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +55 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/answerValues.js +16 -0
- package/dist/poll/votes/answerValues.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +91 -0
- package/dist/poll/votes/bumpPollVote.js.map +1 -0
- package/dist/poll/votes/recountPollVotes.d.ts +20 -0
- package/dist/poll/votes/recountPollVotes.js +63 -0
- package/dist/poll/votes/recountPollVotes.js.map +1 -0
- package/dist/poll/votes/voteTallyHook.js +76 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +23 -0
- package/dist/poll/votes/votesCollection.js +96 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +49 -7
- package/dist/react/Form.js +183 -37
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +10 -2
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/FormResults.d.ts +4 -2
- package/dist/react/FormResults.js +21 -8
- package/dist/react/FormResults.js.map +1 -1
- package/dist/react/Poll.d.ts +25 -2
- package/dist/react/Poll.js +76 -25
- package/dist/react/Poll.js.map +1 -1
- package/dist/react/adapters.d.ts +35 -0
- package/dist/react/adapters.js +11 -0
- package/dist/react/adapters.js.map +1 -0
- package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
- package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
- package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
- package/dist/react/captcha/TurnstileCaptcha.js +2 -2
- package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
- package/dist/react/captcha/useCaptchaScript.js +23 -5
- package/dist/react/captcha/useCaptchaScript.js.map +1 -1
- package/dist/react/fetchResults.d.ts +6 -3
- package/dist/react/fetchResults.js +10 -5
- package/dist/react/fetchResults.js.map +1 -1
- package/dist/react/primitives/Checkbox.d.ts +4 -2
- package/dist/react/primitives/Checkbox.js +3 -2
- package/dist/react/primitives/Checkbox.js.map +1 -1
- package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
- package/dist/react/primitives/ChoiceGroup.js +33 -0
- package/dist/react/primitives/ChoiceGroup.js.map +1 -0
- package/dist/react/primitives/FieldShell.d.ts +11 -1
- package/dist/react/primitives/FieldShell.js +43 -33
- package/dist/react/primitives/FieldShell.js.map +1 -1
- package/dist/react/primitives/Input.d.ts +3 -1
- package/dist/react/primitives/Input.js +2 -1
- package/dist/react/primitives/Input.js.map +1 -1
- package/dist/react/renderers/calculation.js +6 -1
- package/dist/react/renderers/calculation.js.map +1 -1
- package/dist/react/renderers/checkbox.js +2 -1
- package/dist/react/renderers/checkbox.js.map +1 -1
- package/dist/react/renderers/consent.js +8 -3
- package/dist/react/renderers/consent.js.map +1 -1
- package/dist/react/renderers/email.js +3 -1
- package/dist/react/renderers/email.js.map +1 -1
- package/dist/react/renderers/repeater.js +5 -0
- package/dist/react/renderers/repeater.js.map +1 -1
- package/dist/react/renderers/select.js +20 -2
- package/dist/react/renderers/select.js.map +1 -1
- package/dist/react/renderers/text.js +3 -1
- package/dist/react/renderers/text.js.map +1 -1
- package/dist/react/state.d.ts +20 -1
- package/dist/react/state.js +57 -4
- package/dist/react/state.js.map +1 -1
- package/dist/react/submitForm.d.ts +20 -3
- package/dist/react/submitForm.js +8 -4
- package/dist/react/submitForm.js.map +1 -1
- package/dist/react/useCalcValues.d.ts +10 -0
- package/dist/react/useCalcValues.js +13 -0
- package/dist/react/useCalcValues.js.map +1 -0
- package/dist/react/useField.js +7 -5
- package/dist/react/useField.js.map +1 -1
- package/dist/recall/resolver.js +1 -1
- package/dist/recall/resolver.js.map +1 -1
- package/dist/spam/constants.js +7 -1
- package/dist/spam/constants.js.map +1 -1
- package/dist/spam/spamGuard.js +2 -1
- package/dist/spam/spamGuard.js.map +1 -1
- package/dist/submissions/SubmissionAnswersClient.js +14 -14
- package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
- package/dist/submissions/createSubmission.d.ts +7 -1
- package/dist/submissions/createSubmission.js +10 -5
- package/dist/submissions/createSubmission.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
- package/dist/submissions/resolveVotedSubmission.js +51 -0
- package/dist/submissions/resolveVotedSubmission.js.map +1 -0
- package/dist/submissions/runSubmission.js +6 -5
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/submissionLocale.js +39 -0
- package/dist/submissions/submissionLocale.js.map +1 -0
- package/dist/submissions/validateSubmission.js +125 -79
- package/dist/submissions/validateSubmission.js.map +1 -1
- package/dist/submissions/verifyContext.js +35 -0
- package/dist/submissions/verifyContext.js.map +1 -0
- package/dist/submissions/voteChange.js +21 -0
- package/dist/submissions/voteChange.js.map +1 -0
- package/dist/submissions/voteChangeEndpoint.js +110 -0
- package/dist/submissions/voteChangeEndpoint.js.map +1 -0
- package/dist/submissions/votedCookie.d.ts +10 -4
- package/dist/submissions/votedCookie.js +49 -11
- package/dist/submissions/votedCookie.js.map +1 -1
- package/dist/translations/ar.d.ts +7 -0
- package/dist/translations/ar.js +379 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/clientRuntimeKeys.d.ts +17 -0
- package/dist/translations/clientRuntimeKeys.js +48 -0
- package/dist/translations/clientRuntimeKeys.js.map +1 -0
- package/dist/translations/de.d.ts +12 -0
- package/dist/translations/de.js +80 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +80 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.d.ts +7 -0
- package/dist/translations/es.js +379 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.d.ts +7 -0
- package/dist/translations/fr.js +379 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.d.ts +7 -0
- package/dist/translations/id.js +379 -0
- package/dist/translations/id.js.map +1 -0
- package/dist/translations/index.d.ts +23 -6
- package/dist/translations/index.js +31 -6
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +78 -1
- package/dist/translations/keys.js +78 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.d.ts +7 -0
- package/dist/translations/ko.js +379 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/makeTranslate.d.ts +7 -3
- package/dist/translations/makeTranslate.js +12 -3
- package/dist/translations/makeTranslate.js.map +1 -1
- package/dist/translations/pt.d.ts +7 -0
- package/dist/translations/pt.js +379 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.d.ts +7 -0
- package/dist/translations/ru.js +379 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/uk.d.ts +7 -0
- package/dist/translations/uk.js +379 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.d.ts +7 -0
- package/dist/translations/zh.js +379 -0
- package/dist/translations/zh.js.map +1 -0
- package/dist/validation/builtin/index.js +2 -0
- package/dist/validation/builtin/index.js.map +1 -1
- package/dist/validation/builtin/integer.js +15 -0
- package/dist/validation/builtin/integer.js.map +1 -0
- package/dist/validation/builtin/notAlreadySubmitted.js +5 -3
- package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
- package/package.json +23 -15
- package/styles/form-builder.css +84 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FormContext.js","names":[],"sources":["../../src/react/FormContext.ts"],"sourcesContent":["'use client'\n\nimport type { Dispatch } from 'react'\nimport { createContext, useContext } from 'react'\nimport type { BodyConverter } from '../actions/body/converters'\nimport type { FormFlow } from '../flow/types'\nimport type { FormDocument } from '../form/types'\nimport type { RecallResolver } from '../recall/resolver'\nimport type { FormFieldInstance } from '../submissions/types'\nimport type { RendererTranslate } from './contract'\nimport type { RendererRegistry } from './registry'\nimport type { FormAction, FormState } from './state'\n\n/** Multi-step navigation state. Defaults to a single terminal step when the form has no flow. */\nexport type FormStepInfo = {\n\tflow?: FormFlow\n\tcurrentStepId?: string\n\tstepIndex: number\n\tstepCount: number\n\tisFirst: boolean\n\tisTerminal: boolean\n\tgoNext: () => void\n\tgoBack: () => void\n}\n\n/** Resolved chrome button labels. Precedence per label: the `<Form>` prop, then the form's `buttons` value, then the translated default. */\nexport type FormControlLabels = {\n\tprev: string\n\tnext: string\n\tsubmit: string\n}\n\n/**\n * The form controller's context, read via `useFormContext` (or the focused `useField`,\n * `useFormState`, and `useFormStep` hooks). Available anywhere under `<Form>`, including\n * custom `children` layouts and custom field renderers.\n */\nexport type FormContextValue = {\n\t/** The document rendered by this `<Form>`. Custom chrome reads host-added `buttons` keys from here. */\n\tform: FormDocument\n\t/** Current form state: values, errors, touched, submitting, submitted, submitError. */\n\tstate: FormState\n\t/**\n\t * Dispatch a `FormAction` (see `./state` for the action union). Custom field layouts\n\t * typically dispatch `TOUCH` or `SET_FIELD_ISSUES`; prefer `useField` for value binding,\n\t * which wires `SET_VALUE` and validation for you.\n\t */\n\tdispatch: Dispatch<FormAction>\n\t/** Validate one field now (client mode) against the supplied value and store its issues. */\n\tvalidateField: (name: string, value: unknown) => void\n\t/** The locale passed to `<Form>` (defaults to `'en'`). */\n\tlocale: string\n\t/** Multi-step navigation state and the `goNext`/`goBack` handlers. */\n\tstep: FormStepInfo\n\t/** The active renderer registry, exposed so nested renderers (e.g. repeater) can look up sub-renderers. */\n\trendererRegistry: RendererRegistry\n\t/** Resolved prev/next/submit labels used by `<FormControls>` and available to custom chrome. */\n\tlabels: FormControlLabels\n\t/** The active translator: the `<Form>` `t` prop, else the bundled English fallback. */\n\tt: RendererTranslate\n\t/** Calc-authoritative answers: `state.values` overlaid with derived calc values. Consumers fall back to `state.values` when absent. */\n\teffectiveValues?: Record<string, unknown>\n\t/** Recall resolver for token interpolation, exposed so `<FormFields>` and custom layouts can format values. */\n\trecall?: RecallResolver\n\t/** The exact visible field list the default loop renders (post hidden/calc filter). Consumed by `<FormFields>`. */\n\trenderedFields?: FormFieldInstance[]\n\t/** The `<Form>` `converters` prop, so client rich-text serialization (e.g. the `message` renderer) honors host blocks. */\n\tconverters?: Record<string, BodyConverter>\n}\n\nexport const FormContext = createContext<FormContextValue | null>(null)\n\n/** Read the form controller context. Throws if used outside `<Form>`. */\nexport const useFormContext = (): FormContextValue => {\n\tconst context = useContext(FormContext)\n\tif (!context) {\n\t\tthrow new Error('useFormContext must be used within a <Form>')\n\t}\n\treturn context\n}\n"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"FormContext.js","names":[],"sources":["../../src/react/FormContext.ts"],"sourcesContent":["'use client'\n\nimport type { Dispatch } from 'react'\nimport { createContext, useContext } from 'react'\nimport type { BodyConverter } from '../actions/body/converters'\nimport type { FormFlow } from '../flow/types'\nimport type { FormDocument } from '../form/types'\nimport type { RecallResolver } from '../recall/resolver'\nimport type { FormFieldInstance } from '../submissions/types'\nimport type { RendererTranslate } from './contract'\nimport type { RendererRegistry } from './registry'\nimport type { FormAction, FormState } from './state'\n\n/** Multi-step navigation state. Defaults to a single terminal step when the form has no flow. */\nexport type FormStepInfo = {\n\tflow?: FormFlow\n\tcurrentStepId?: string\n\tstepIndex: number\n\tstepCount: number\n\tisFirst: boolean\n\tisTerminal: boolean\n\tgoNext: () => void\n\tgoBack: () => void\n}\n\n/** Resolved chrome button labels. Precedence per label: the `<Form>` prop, then the form's `buttons` value, then the translated default. */\nexport type FormControlLabels = {\n\tprev: string\n\tnext: string\n\tsubmit: string\n}\n\n/**\n * The form controller's context, read via `useFormContext` (or the focused `useField`,\n * `useFormState`, and `useFormStep` hooks). Available anywhere under `<Form>`, including\n * custom `children` layouts and custom field renderers.\n */\nexport type FormContextValue = {\n\t/** The document rendered by this `<Form>`. Custom chrome reads host-added `buttons` keys from here. */\n\tform: FormDocument\n\t/** Current form state: values, errors, touched, submitting, submitted, submitError. */\n\tstate: FormState\n\t/**\n\t * Dispatch a `FormAction` (see `./state` for the action union). Custom field layouts\n\t * typically dispatch `TOUCH` or `SET_FIELD_ISSUES`; prefer `useField` for value binding,\n\t * which wires `SET_VALUE` and validation for you.\n\t */\n\tdispatch: Dispatch<FormAction>\n\t/** Validate one field now (client mode) against the supplied value and store its issues. */\n\tvalidateField: (name: string, value: unknown) => void\n\t/** The locale passed to `<Form>` (defaults to `'en'`). */\n\tlocale: string\n\t/** Multi-step navigation state and the `goNext`/`goBack` handlers. */\n\tstep: FormStepInfo\n\t/** The active renderer registry, exposed so nested renderers (e.g. repeater) can look up sub-renderers. */\n\trendererRegistry: RendererRegistry\n\t/** Resolved prev/next/submit labels used by `<FormControls>` and available to custom chrome. */\n\tlabels: FormControlLabels\n\t/** The active translator: the `<Form>` `t` prop, else the bundled English fallback. */\n\tt: RendererTranslate\n\t/** Calc-authoritative answers: `state.values` overlaid with derived calc values. Consumers fall back to `state.values` when absent. */\n\teffectiveValues?: Record<string, unknown>\n\t/**\n\t * Live computed values of the calculation fields only (name -> number), derived from the same\n\t * memo as `effectiveValues`. Composed frontends read running totals from here (or via\n\t * `useCalcValues`) without recomputing expressions. Optional like `effectiveValues` so\n\t * hand-built context values (tests, harnesses) stay assignable.\n\t */\n\tcalcValues?: Record<string, number>\n\t/** Recall resolver for token interpolation, exposed so `<FormFields>` and custom layouts can format values. */\n\trecall?: RecallResolver\n\t/** The exact visible field list the default loop renders (post hidden/calc filter). Consumed by `<FormFields>`. */\n\trenderedFields?: FormFieldInstance[]\n\t/** The `<Form>` `converters` prop, so client rich-text serialization (e.g. the `message` renderer) honors host blocks. */\n\tconverters?: Record<string, BodyConverter>\n\t/** Maps a field key to the id of the step it belongs to (or the default step), for per-step error reveal. */\n\tstepIdOfField?: (fieldKey: string) => string\n}\n\nexport const FormContext = createContext<FormContextValue | null>(null)\n\n/** Read the form controller context. Throws if used outside `<Form>`. */\nexport const useFormContext = (): FormContextValue => {\n\tconst context = useContext(FormContext)\n\tif (!context) {\n\t\tthrow new Error('useFormContext must be used within a <Form>')\n\t}\n\treturn context\n}\n"],"mappings":";;;AA+EA,MAAa,cAAc,cAAuC,IAAI;;AAGtE,MAAa,uBAAyC;CACrD,MAAM,UAAU,WAAW,WAAW;CACtC,IAAI,CAAC,SACJ,MAAM,IAAI,MAAM,6CAA6C;CAE9D,OAAO;AACR"}
|
|
@@ -8,7 +8,8 @@ type FormResultsProps = {
|
|
|
8
8
|
t?: RendererTranslate;
|
|
9
9
|
locale?: string; /** Show the raw count beside each option. Default true. */
|
|
10
10
|
showCounts?: boolean; /** The recorded outcome's stable option values; every matching bucket is highlighted as a winner (a tie highlights more than one). */
|
|
11
|
-
winningValues?: string[];
|
|
11
|
+
winningValues?: string[]; /** The viewing voter's own pick (e.g. `resolveVotedSubmission().pick`); every matching bucket carries a "your vote" marker. */
|
|
12
|
+
currentValues?: string[];
|
|
12
13
|
};
|
|
13
14
|
/**
|
|
14
15
|
* Presentational results view for polls and survey summaries: per-option bars with percentages. Headless,
|
|
@@ -21,7 +22,8 @@ declare const FormResults: ({
|
|
|
21
22
|
results,
|
|
22
23
|
t,
|
|
23
24
|
showCounts,
|
|
24
|
-
winningValues
|
|
25
|
+
winningValues,
|
|
26
|
+
currentValues
|
|
25
27
|
}: FormResultsProps) => ReactNode;
|
|
26
28
|
//#endregion
|
|
27
29
|
export { FormResults, FormResultsProps };
|
|
@@ -4,7 +4,7 @@ import { en } from "../translations/en.js";
|
|
|
4
4
|
import { makeTranslate } from "../translations/makeTranslate.js";
|
|
5
5
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
6
6
|
//#region src/react/FormResults.tsx
|
|
7
|
-
const OneResult = ({ result, t, showCounts, winningValues }) => {
|
|
7
|
+
const OneResult = ({ result, t, showCounts, winningValues, currentValues }) => {
|
|
8
8
|
if (result.total === 0) return /* @__PURE__ */ jsxs("section", {
|
|
9
9
|
className: "fb-results__field",
|
|
10
10
|
children: [result.label ? /* @__PURE__ */ jsx("h3", {
|
|
@@ -26,15 +26,27 @@ const OneResult = ({ result, t, showCounts, winningValues }) => {
|
|
|
26
26
|
className: "fb-results__list",
|
|
27
27
|
children: result.buckets.map((bucket) => {
|
|
28
28
|
const isWinner = winningValues?.includes(bucket.value) ?? false;
|
|
29
|
+
const isYours = currentValues?.includes(bucket.value) ?? false;
|
|
29
30
|
return /* @__PURE__ */ jsxs("li", {
|
|
30
|
-
className:
|
|
31
|
+
className: [
|
|
32
|
+
"fb-results__row",
|
|
33
|
+
...isWinner ? ["fb-results__bucket--winner"] : [],
|
|
34
|
+
...isYours ? ["fb-results__bucket--yours"] : []
|
|
35
|
+
].join(" "),
|
|
31
36
|
children: [
|
|
32
37
|
/* @__PURE__ */ jsxs("span", {
|
|
33
38
|
className: "fb-results__option",
|
|
34
|
-
children: [
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
39
|
+
children: [
|
|
40
|
+
bucket.label,
|
|
41
|
+
isWinner ? /* @__PURE__ */ jsx("span", {
|
|
42
|
+
className: "fb-results__winner-badge",
|
|
43
|
+
children: t(keys.resultsWinner)
|
|
44
|
+
}) : null,
|
|
45
|
+
isYours ? /* @__PURE__ */ jsx("span", {
|
|
46
|
+
className: "fb-results__your-vote-badge",
|
|
47
|
+
children: t(keys.resultsYourVote)
|
|
48
|
+
}) : null
|
|
49
|
+
]
|
|
38
50
|
}),
|
|
39
51
|
/* @__PURE__ */ jsx("span", {
|
|
40
52
|
className: "fb-results__bar",
|
|
@@ -75,7 +87,7 @@ const OneResult = ({ result, t, showCounts, winningValues }) => {
|
|
|
75
87
|
* is `aria-hidden` visual sugar sized by inline width. With `winningValues`, every matching bucket gets
|
|
76
88
|
* the winner class and a translated badge (real text, so the outcome is accessible); a tie highlights more than one.
|
|
77
89
|
*/
|
|
78
|
-
const FormResults = ({ results, t, showCounts = true, winningValues }) => {
|
|
90
|
+
const FormResults = ({ results, t, showCounts = true, winningValues, currentValues }) => {
|
|
79
91
|
const translate = t ?? makeTranslate(en);
|
|
80
92
|
return /* @__PURE__ */ jsx("div", {
|
|
81
93
|
className: "fb-results",
|
|
@@ -83,7 +95,8 @@ const FormResults = ({ results, t, showCounts = true, winningValues }) => {
|
|
|
83
95
|
result,
|
|
84
96
|
t: translate,
|
|
85
97
|
showCounts,
|
|
86
|
-
winningValues
|
|
98
|
+
winningValues,
|
|
99
|
+
currentValues
|
|
87
100
|
}, result.field))
|
|
88
101
|
});
|
|
89
102
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FormResults.js","names":[],"sources":["../../src/react/FormResults.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport type { RendererTranslate } from './contract'\n\nexport type FormResultsProps = {\n\t/** One field aggregation or several (a survey summary), resolved server-side and passed in. */\n\tresults: FieldAggregation | FieldAggregation[]\n\t/** Localized translator for built-in copy. Defaults to identity (returns the key). */\n\tt?: RendererTranslate\n\tlocale?: string\n\t/** Show the raw count beside each option. Default true. */\n\tshowCounts?: boolean\n\t/** The recorded outcome's stable option values; every matching bucket is highlighted as a winner (a tie highlights more than one). */\n\twinningValues?: string[]\n}\n\nconst OneResult = ({\n\tresult,\n\tt,\n\tshowCounts,\n\twinningValues,\n}: {\n\tresult: FieldAggregation\n\tt: RendererTranslate\n\tshowCounts: boolean\n\twinningValues?: string[]\n}): ReactNode => {\n\tif (result.total === 0) {\n\t\treturn (\n\t\t\t<section className=\"fb-results__field\">\n\t\t\t\t{result.label ? <h3 className=\"fb-results__label\">{result.label}</h3> : null}\n\t\t\t\t<p className=\"fb-results__empty\">{t(keys.resultsNoResponses)}</p>\n\t\t\t</section>\n\t\t)\n\t}\n\treturn (\n\t\t<section className=\"fb-results__field\">\n\t\t\t{result.label ? <h3 className=\"fb-results__label\">{result.label}</h3> : null}\n\t\t\t<ul className=\"fb-results__list\">\n\t\t\t\t{result.buckets.map((bucket) => {\n\t\t\t\t\tconst isWinner = winningValues?.includes(bucket.value) ?? false\n\t\t\t\t\
|
|
1
|
+
{"version":3,"file":"FormResults.js","names":[],"sources":["../../src/react/FormResults.tsx"],"sourcesContent":["'use client'\n\nimport type { ReactNode } from 'react'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { en } from '../translations/en'\nimport { keys } from '../translations/keys'\nimport { makeTranslate } from '../translations/makeTranslate'\nimport type { RendererTranslate } from './contract'\n\nexport type FormResultsProps = {\n\t/** One field aggregation or several (a survey summary), resolved server-side and passed in. */\n\tresults: FieldAggregation | FieldAggregation[]\n\t/** Localized translator for built-in copy. Defaults to identity (returns the key). */\n\tt?: RendererTranslate\n\tlocale?: string\n\t/** Show the raw count beside each option. Default true. */\n\tshowCounts?: boolean\n\t/** The recorded outcome's stable option values; every matching bucket is highlighted as a winner (a tie highlights more than one). */\n\twinningValues?: string[]\n\t/** The viewing voter's own pick (e.g. `resolveVotedSubmission().pick`); every matching bucket carries a \"your vote\" marker. */\n\tcurrentValues?: string[]\n}\n\nconst OneResult = ({\n\tresult,\n\tt,\n\tshowCounts,\n\twinningValues,\n\tcurrentValues,\n}: {\n\tresult: FieldAggregation\n\tt: RendererTranslate\n\tshowCounts: boolean\n\twinningValues?: string[]\n\tcurrentValues?: string[]\n}): ReactNode => {\n\tif (result.total === 0) {\n\t\treturn (\n\t\t\t<section className=\"fb-results__field\">\n\t\t\t\t{result.label ? <h3 className=\"fb-results__label\">{result.label}</h3> : null}\n\t\t\t\t<p className=\"fb-results__empty\">{t(keys.resultsNoResponses)}</p>\n\t\t\t</section>\n\t\t)\n\t}\n\treturn (\n\t\t<section className=\"fb-results__field\">\n\t\t\t{result.label ? <h3 className=\"fb-results__label\">{result.label}</h3> : null}\n\t\t\t<ul className=\"fb-results__list\">\n\t\t\t\t{result.buckets.map((bucket) => {\n\t\t\t\t\tconst isWinner = winningValues?.includes(bucket.value) ?? false\n\t\t\t\t\tconst isYours = currentValues?.includes(bucket.value) ?? false\n\t\t\t\t\tconst rowClass = [\n\t\t\t\t\t\t'fb-results__row',\n\t\t\t\t\t\t...(isWinner ? ['fb-results__bucket--winner'] : []),\n\t\t\t\t\t\t...(isYours ? ['fb-results__bucket--yours'] : []),\n\t\t\t\t\t].join(' ')\n\t\t\t\t\treturn (\n\t\t\t\t\t\t<li key={bucket.value} className={rowClass}>\n\t\t\t\t\t\t\t<span className=\"fb-results__option\">\n\t\t\t\t\t\t\t\t{bucket.label}\n\t\t\t\t\t\t\t\t{isWinner ? (\n\t\t\t\t\t\t\t\t\t<span className=\"fb-results__winner-badge\">{t(keys.resultsWinner)}</span>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t\t{isYours ? (\n\t\t\t\t\t\t\t\t\t<span className=\"fb-results__your-vote-badge\">{t(keys.resultsYourVote)}</span>\n\t\t\t\t\t\t\t\t) : null}\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<span className=\"fb-results__bar\">\n\t\t\t\t\t\t\t\t<span\n\t\t\t\t\t\t\t\t\tclassName=\"fb-results__bar-fill\"\n\t\t\t\t\t\t\t\t\tstyle={{ width: `${bucket.percentage}%` }}\n\t\t\t\t\t\t\t\t\taria-hidden=\"true\"\n\t\t\t\t\t\t\t\t/>\n\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t<span className=\"fb-results__pct\">{bucket.percentage}%</span>\n\t\t\t\t\t\t\t{showCounts ? <span className=\"fb-results__count\">{bucket.count}</span> : null}\n\t\t\t\t\t\t</li>\n\t\t\t\t\t)\n\t\t\t\t})}\n\t\t\t</ul>\n\t\t\t<p className=\"fb-results__total\">\n\t\t\t\t{result.total} {t(keys.resultsResponses)}\n\t\t\t\t{result.truncated ? ` (${t(keys.resultsTruncated)})` : ''}\n\t\t\t</p>\n\t\t</section>\n\t)\n}\n\n/**\n * Presentational results view for polls and survey summaries: per-option bars with percentages. Headless,\n * data resolved server-side via `aggregateFieldResponses`/`aggregateFormResponses` and passed in (it never\n * fetches). The option label, count, and percentage are real text (the accessible content); the bar fill\n * is `aria-hidden` visual sugar sized by inline width. With `winningValues`, every matching bucket gets\n * the winner class and a translated badge (real text, so the outcome is accessible); a tie highlights more than one.\n */\nexport const FormResults = ({\n\tresults,\n\tt,\n\tshowCounts = true,\n\twinningValues,\n\tcurrentValues,\n}: FormResultsProps): ReactNode => {\n\tconst translate: RendererTranslate = t ?? makeTranslate(en)\n\tconst list = Array.isArray(results) ? results : [results]\n\treturn (\n\t\t<div className=\"fb-results\">\n\t\t\t{list.map((result) => (\n\t\t\t\t<OneResult\n\t\t\t\t\tkey={result.field}\n\t\t\t\t\tresult={result}\n\t\t\t\t\tt={translate}\n\t\t\t\t\tshowCounts={showCounts}\n\t\t\t\t\twinningValues={winningValues}\n\t\t\t\t\tcurrentValues={currentValues}\n\t\t\t\t/>\n\t\t\t))}\n\t\t</div>\n\t)\n}\n"],"mappings":";;;;;;AAuBA,MAAM,aAAa,EAClB,QACA,GACA,YACA,eACA,oBAOgB;CAChB,IAAI,OAAO,UAAU,GACpB,OACC,qBAAC,WAAD;EAAS,WAAU;YAAnB,CACE,OAAO,QAAQ,oBAAC,MAAD;GAAI,WAAU;aAAqB,OAAO;EAAU,CAAA,IAAI,MACxE,oBAAC,KAAD;GAAG,WAAU;aAAqB,EAAE,KAAK,kBAAkB;EAAK,CAAA,CACxD;;CAGX,OACC,qBAAC,WAAD;EAAS,WAAU;YAAnB;GACE,OAAO,QAAQ,oBAAC,MAAD;IAAI,WAAU;cAAqB,OAAO;GAAU,CAAA,IAAI;GACxE,oBAAC,MAAD;IAAI,WAAU;cACZ,OAAO,QAAQ,KAAK,WAAW;KAC/B,MAAM,WAAW,eAAe,SAAS,OAAO,KAAK,KAAK;KAC1D,MAAM,UAAU,eAAe,SAAS,OAAO,KAAK,KAAK;KAMzD,OACC,qBAAC,MAAD;MAAuB,WANP;OAChB;OACA,GAAI,WAAW,CAAC,4BAA4B,IAAI,CAAC;OACjD,GAAI,UAAU,CAAC,2BAA2B,IAAI,CAAC;MAChD,EAAE,KAAK,GAEmC;gBAAzC;OACC,qBAAC,QAAD;QAAM,WAAU;kBAAhB;SACE,OAAO;SACP,WACA,oBAAC,QAAD;UAAM,WAAU;oBAA4B,EAAE,KAAK,aAAa;SAAQ,CAAA,IACrE;SACH,UACA,oBAAC,QAAD;UAAM,WAAU;oBAA+B,EAAE,KAAK,eAAe;SAAQ,CAAA,IAC1E;QACC;;OACN,oBAAC,QAAD;QAAM,WAAU;kBACf,oBAAC,QAAD;SACC,WAAU;SACV,OAAO,EAAE,OAAO,GAAG,OAAO,WAAW,GAAG;SACxC,eAAY;QACZ,CAAA;OACI,CAAA;OACN,qBAAC,QAAD;QAAM,WAAU;kBAAhB,CAAmC,OAAO,YAAW,GAAO;;OAC3D,aAAa,oBAAC,QAAD;QAAM,WAAU;kBAAqB,OAAO;OAAY,CAAA,IAAI;MACvE;QAnBK,OAAO,KAmBZ;IAEN,CAAC;GACE,CAAA;GACJ,qBAAC,KAAD;IAAG,WAAU;cAAb;KACE,OAAO;KAAM;KAAE,EAAE,KAAK,gBAAgB;KACtC,OAAO,YAAY,KAAK,EAAE,KAAK,gBAAgB,EAAE,KAAK;IACrD;;EACK;;AAEX;;;;;;;;AASA,MAAa,eAAe,EAC3B,SACA,GACA,aAAa,MACb,eACA,oBACkC;CAClC,MAAM,YAA+B,KAAK,cAAc,EAAE;CAE1D,OACC,oBAAC,OAAD;EAAK,WAAU;aAFH,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,OAAO,GAGhD,KAAK,WACV,oBAAC,WAAD;GAES;GACR,GAAG;GACS;GACG;GACA;EACf,GANK,OAAO,KAMZ,CACD;CACG,CAAA;AAEP"}
|
package/dist/react/Poll.d.ts
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
import { FormProps } from "./Form.js";
|
|
2
|
+
import { FormResultsProps } from "./FormResults.js";
|
|
2
3
|
import { fetchFormResults } from "./fetchResults.js";
|
|
4
|
+
import { VotedSubmission } from "../submissions/resolveVotedSubmission.js";
|
|
5
|
+
import { ReactNode } from "react";
|
|
3
6
|
|
|
4
7
|
//#region src/react/Poll.d.ts
|
|
5
8
|
type PollProps = FormProps & {
|
|
6
|
-
/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */resultsField: string;
|
|
9
|
+
/** The choice field whose results are shown after voting (should match the form's public `poll.resultsField`). */resultsField: string;
|
|
10
|
+
/**
|
|
11
|
+
* Key for the per-browser voted guard (localStorage by default; overridable or disabled via
|
|
12
|
+
* `adapters.voteStorage`). Default `fb-poll-{form.id}`.
|
|
13
|
+
*/
|
|
7
14
|
storageKey?: string;
|
|
8
15
|
/**
|
|
9
16
|
* Server-known voted state, ORed with the localStorage guard: `true` marks the visitor as voted;
|
|
10
17
|
* `false`/omitted falls back to localStorage. SSR hosts using the plugin's `poll.votedCookie`
|
|
11
|
-
* option pass `hasVotedCookie(cookieHeader, form.id)` here.
|
|
18
|
+
* option pass `hasVotedCookie(cookieHeader, form.id, payload)` here.
|
|
12
19
|
*/
|
|
13
20
|
hasVoted?: boolean;
|
|
14
21
|
/**
|
|
@@ -16,6 +23,20 @@ type PollProps = FormProps & {
|
|
|
16
23
|
* scope, `useCallback`, or `useMemo`): an inline function re-runs the load effect and double-fetches.
|
|
17
24
|
*/
|
|
18
25
|
fetchResultsImpl?: typeof fetchFormResults;
|
|
26
|
+
/**
|
|
27
|
+
* The voter's server-resolved current vote (`resolveVotedSubmission`, read from the httpOnly voted
|
|
28
|
+
* cookie). Presence implies voted; `pick` marks the voter's option in results and `value` prefills
|
|
29
|
+
* the form when they change their vote. Read at mount: after a client-side change the component
|
|
30
|
+
* tracks the new pick itself.
|
|
31
|
+
*/
|
|
32
|
+
currentVote?: Pick<VotedSubmission, 'value' | 'pick'> | null;
|
|
33
|
+
/**
|
|
34
|
+
* Replaces the built-in `<FormResults>` wherever the poll shows results (after voting, when
|
|
35
|
+
* closed, and for a recorded outcome). Receives exactly what `<FormResults>` receives at that
|
|
36
|
+
* site, so the default is `(props) => <FormResults {...props} />`; surrounding chrome (the
|
|
37
|
+
* closed/final notices, the change-vote button) stays the poll's.
|
|
38
|
+
*/
|
|
39
|
+
renderResults?: (props: FormResultsProps) => ReactNode;
|
|
19
40
|
};
|
|
20
41
|
/**
|
|
21
42
|
* A poll: renders `<Form>` while open and not yet voted, then fetches the aggregate results and shows
|
|
@@ -36,6 +57,8 @@ declare const Poll: ({
|
|
|
36
57
|
fetchResultsImpl,
|
|
37
58
|
apiRoute,
|
|
38
59
|
onSuccess,
|
|
60
|
+
currentVote,
|
|
61
|
+
renderResults,
|
|
39
62
|
...formProps
|
|
40
63
|
}: PollProps) => import("react/jsx-runtime").JSX.Element | null;
|
|
41
64
|
//#endregion
|
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;
|