@ebitex/forms-sdk
v1.2.350
Published
Fetch and render ebitex Forms in your own application.
Readme
@ebitex/forms-sdk
Fetch and render ebitex Forms in your own application.
Two entry points, split deliberately:
@ebitex/forms-sdk— fetches a form definition and validates a submission against it. No React dependency, so a server-only consumer never pulls one in.@ebitex/forms-sdk/react— the rendering components. Imports React as apeerDependency(never bundled), so it never conflicts with your own app's copy.
Your organization's API key is server-side only. Fetch the form definition with
createFormsClient on your server or in a build step, then pass the result to <EbitexForm> —
which never receives the key itself, only the already-fetched definition.
Install
npm install @ebitex/forms-sdkQuick start
// Server-side (a route handler, a loader, a build step — never in a browser bundle)
import { createFormsClient } from '@ebitex/forms-sdk'
const client = createFormsClient({ apiKey: process.env.EBITEX_FORMS_API_KEY! })
const form = await client.getForm('contact-us')// Client-side — `form` is whatever getForm(...) returned above, passed down as a prop
import { EbitexForm } from '@ebitex/forms-sdk/react'
import '@ebitex/forms-sdk/styles.css'
function ContactPage({ form }: { form: SdkForm }) {
return <EbitexForm form={form} onSubmitted={() => console.log('done')} />
}<EbitexForm> posts directly to the form's own public submissionUrl — the same anonymous
endpoint ebitex's own hosted page and iframe embed use — so it never needs your API key either.
Multi-step forms save progress as the respondent advances.
Errors
getForm throws FormsApiError for a non-2xx response, carrying status, the parsed body, and
requestId: the request's reference, from the X-Request-Id response header or an unhandled
500's body (null when a proxy answered and the request never reached ebitex). The message ends
[request <id>] when there is one. Log it, and quote it to support.
Accessibility, errors and your own wording
<EbitexForm> looks after what happens around an error, so a keyboard or screen-reader visitor is never left
wondering why nothing happened.
- Focus goes to the first problem. After a step or a submit fails validation, focus moves to the first
field that needs fixing, so its label and its error are read out. Server-side
validation_failederrors behave the same way. PassfocusOnError={false}if your page manages focus itself. - An error summary for two or more. When more than one field on the step needs fixing, a summary above the step says how many and lists each as a link that focuses it. With one, focus on the field is enough.
- A visible message when sending fails. A network failure or a server error shows "Your answers could not be
sent. Check your connection and try again." and keeps what was entered.
onErroris still called. PassshowErrorMessage={false}if you render your own fromonError. - A busy server is not a bad connection. When the server answers that it is too busy to take a send (HTTP 429),
the message says "This form is busy. Wait a minute, then send again. Your answers are still here." instead. Replace
it with the
busylabel. - Steps. Progress is a
progressbarwith its value, range and text ("Step 2 of 3: Your details"), and that text takes focus when the step changes. - Keypads and autofill. Email, phone and URL fields set
autocompleteandinputMode, and a number field setsinputMode(numeric, ordecimalwhen it takes fractions). A field definition may carry anautocompletePurposeto say what a plain text field holds (given-name,family-name,organization,postal-code, and the other HTML autofill tokens for names and addresses), oroffto turn autofill off. A value that is not an autofill token is ignored.
Nothing in the form animates except the lookup spinner, and that stops under prefers-reduced-motion.
Your own wording
Every string the package writes itself can be replaced with the labels prop. Anything you leave out stays
English. A value may use {n}, {total}, {count}, {status} or {text} where the table says so.
<EbitexForm
form={form}
labels={{
back: 'Retour',
next: 'Suivant',
required: 'Ce champ est obligatoire.',
errorSummary: 'Veuillez corriger {count} champs',
stepIndicator: 'Étape {n} sur {total}',
}}
/>| Label | Default | Where |
|---|---|---|
| back, next, submit | Back, Next, Submit | The step buttons. submit is used only when the form defines no button of its own. |
| complete | Thanks — your response has been submitted. | Replaces the form after a successful submission. |
| required | This field is required. | Under a required field left empty. |
| requiredHint | (required) | Read aloud after a required group's label. |
| select | Select… | The empty first option of a drop-down. |
| errorSummary | Please fix {count} fields | The summary heading. |
| failure | Your answers could not be sent. Check your connection and try again. | When sending fails. |
| busy | This form is busy. Wait a minute, then send again. Your answers are still here. | When the server answers 429 to a send. |
| progress, stepIndicator | Form progress, Step {n} of {total} | The progress indicator. |
| preview | This form is {status} and isn't accepting responses yet. It's shown here for preview only. | Above a form that is not live. |
| lookupUnavailable, lookupFound, lookupNew, lookupUseNew | | The type-ahead field. |
The form's own field labels, option labels and button labels come from the form, and the server's error
messages are the server's. The type is exported as FormsLabels from both entry points.
The pieces, for a form you render yourself
If you render a form with NodeList rather than <EbitexForm> (a server-rendered page, say), the three pieces
<EbitexForm> uses for the behaviour above are exported from @ebitex/forms-sdk/react, so your form behaves the
same way for a keyboard or screen-reader visitor:
ErrorSummarytakesfields(each with anid, alabeland amessage, in page order), optionallabelsand an optionalonFocusField. It renders nothing for fewer than two fields. Each link is a real#idanchor, so it also works in a page sent without any script; with script it focuses the control.StepProgresstakescurrent,total, an optionalstepLabeland optionallabels, and renders theprogressbartext. Pass it arefand callfocus()on it when the step changes. It renders nothing for one step.focusFormControl(element)focuses a control, or the first option of a radio or checkbox group.
<StepProgress ref={progressRef} current={2} total={3} stepLabel="Your details" />
<ErrorSummary fields={invalid} />Theming
styles.css is one custom property per concern, targeting .ebitex-forms:
.ebitex-forms {
--ebitex-forms-accent: #7c3aed;
--ebitex-forms-accent-contrast: #ffffff;
--ebitex-forms-text: #111827;
--ebitex-forms-muted: #6b7280;
--ebitex-forms-border: #d1d5db;
--ebitex-forms-error: #dc2626;
--ebitex-forms-surface: transparent;
--ebitex-forms-radius: 0.375rem;
--ebitex-forms-gap: 1rem;
}Override what you need; the rest inherit the shipped default. There's no font stack and no imposed max-width either — a form embedded in someone else's page should look like it belongs there.
Dark mode
The shipped default reacts to dark mode two ways, both covering every color property above:
prefers-color-scheme: dark (the visitor's OS setting, with no toggle of your own) and a .dark
class on any ancestor element (an explicit light/dark choice your app already tracks — this is the
convention @ebitex/theme-core uses, and what ebitex's own hosted page and iframe
embed run on). Add data-ebitex-theme="light" to .ebitex-forms (or an ancestor) to opt out of both
and force light regardless of OS preference or a .dark class above it.
In dark mode the default accent is lighter, so the text on it (--ebitex-forms-accent-contrast) is near-black rather than white, which keeps the button label above the 4.5:1 AA ratio. If you set your own accent, set the contrast colour that suits it too.
If you set your own --ebitex-forms-accent/--ebitex-forms-surface/etc. and want a distinct dark
variant rather than the same value in both modes, set it again under your own .dark (or
prefers-color-scheme: dark) rule — the shipped dark values only apply to whichever properties
you haven't overridden. deriveDarkVariant (exported from @ebitex/forms-sdk, no /react import
needed) suggests one from a #rrggbb light color, the same heuristic ebitex's own look-and-feel
settings UI uses to pre-fill a dark color picker — a starting point, not a requirement, and a no-op
for any non-hex CSS color string:
import { deriveDarkVariant } from '@ebitex/forms-sdk'
deriveDarkVariant('#7c3aed') // '#aa7ff3'Rendering nodes yourself
If you're not using <EbitexForm> — building a custom renderer, or validating a submission
server-side without a browser involved — collectDataFields/resolveVariant/
isFieldComparisonSatisfied/isAllOfSatisfied/isSatisfied are the same evaluators it uses
internally, exported so a second, independently-written implementation never has a chance to drift
from the real one.
A form's content tree (SdkForm.actions, each FormStep.nodes) is FormNode[]: a Fieldset or
Row groups other nodes; a field type (InputField/TextareaField/NumberField/ChoiceField/
ButtonField) is a leaf; a VariantNode shows at most one of its branches (first whose when
is satisfied) or its fallback, based on the respondent's own answers so far.
interface VariantNode {
nodeType: 'Variant'
branches: VariantBranch[]
/** Always an array — empty means "nothing" rather than `null`. */
fallback: FormNode[]
}
interface VariantBranch {
when: VariantPredicate
/** May hold more than one node — not capped at one. */
nodes: FormNode[]
}
type VariantPredicate = FieldComparisonPredicate | AllOfPredicate
interface FieldComparisonPredicate {
kind: 'FieldComparison'
field: string // a submissionKey answered *earlier* in the form
operator: 'Equals' | 'NotEquals' | 'IsEmpty' | 'IsNotEmpty'
value?: string // present for Equals/NotEquals, absent otherwise
}
/** AND-combination of two or more FieldComparisonPredicates — every one must be satisfied. */
interface AllOfPredicate {
kind: 'AllOf'
predicates: FieldComparisonPredicate[]
}import { resolveVariant, isSatisfied } from '@ebitex/forms-sdk'
// Which of a Variant's branches (or its fallback) the respondent currently sees, given their
// answers so far — returns that branch's/fallback's own node list, possibly empty.
const visibleNodes = resolveVariant(variantNode, currentAnswers)
// Evaluating one branch's own `when` directly, regardless of which predicate kind it is.
const branchApplies = isSatisfied(someBranch.when, currentAnswers)A field's answer is submitted under its own submissionKey — not necessarily its name: a field
placed by reference to one you've reused across forms is keyed by that shared field's own external
id instead. Always read/write SubmissionData by submissionKey.
Validating a submission
import { validateSubmission } from '@ebitex/forms-sdk'
const errors = validateSubmission(form, submittedData, { requireAll: true })<EbitexForm> calls this itself for inline feedback before every request; the server is always the
final authority regardless — a client-side pass is for a good respondent experience, not enforcement.
Consent and the visitor token
A multi-step form keeps its progress against a visitor token that the API issues. The package holds that token
in memory only. It never writes to localStorage, sessionStorage, a cookie or IndexedDB, so by default a
page load is a new visitor and nothing is remembered across visits.
Recognising a respondent across visits needs their consent. Tell the form what they chose, and, if you want the token to survive between visits, give it somewhere to keep it:
import { EbitexForm } from '@ebitex/forms-sdk/react'
<EbitexForm
form={form}
consent={{ cmp: 'granted' }} // from your consent banner; 'denied' is a withdrawal
storage={{
get: () => localStorage.getItem('visitor'),
set: (token) => localStorage.setItem('visitor', token),
remove: () => localStorage.removeItem('visitor'),
}}
/>setis called only when the API reports that recognising the respondent is granted, and only when the token has changed.removeis called when it is not, when the respondent withdraws consent, when you callforget, and when a response says nothing about consent (an older server).- Without a
consentoption the organization's default applies. That default is denied until an Owner changes it or you pass a signal from your banner, so out of the box nothing is recognised across visits. gpcanddntdefault to the browser's Global Privacy Control and Do Not Track settings. Pass them to override. Either one set means "do not recognise me" unless your banner records an explicit choice.- If you keep the token anywhere other than through
storage, the same rule applies to you: store it only while recognition is granted, and remove it as soon as it is not.
To change consent after the form has mounted, update the consent prop, or share one session across forms and
call setConsent yourself. forget asks the API to forget the browser and clears the token:
import { createVisitorSession } from '@ebitex/forms-sdk'
const visitor = createVisitorSession({ storage, consent: { cmp: 'granted' } })
// <EbitexForm visitor={visitor} ... />
visitor.setConsent({ cmp: 'denied' }) // drops the token and calls storage.remove()
await visitor.forget(form) // resolves with the organization's confirmation message
visitor.consent?.messages.recognitionDeclined // wording to show where something needs recognitionVersioning
This package's public wire shape mirrors ebitex's own Forms API responses directly (see
SdkForm/FormNode above) — a breaking shape change on the server ships as a new minor version
here (pre-1.0), not a patch. Pin a specific version if that matters to your build.
Full guide: developers.ebitex.io.
