@financial-times/n-conversion-forms

Containing jsx components and styles for forms included on Accounts and Acqusition apps (next-signup, next-profile, next-retention, etc).

Stats

StarsIssuesVersionUpdatedCreatedSize
@financial-times/n-conversion-forms
22220.2.119 days ago3 years agoMinified + gzip package size for @financial-times/n-conversion-forms in KB

Readme

n-conversion-forms

Contains HTML and CSS that's used within the conversion forms

CircleCI Known Vulnerabilities

make install # install all dependencies
make run # build and start documentation app at http://local.ft.com:5005/

Table of contents

Requirements

For installing dependencies, running the build process and the documentation app

Usage

This repository contains JSX components and CSS that can be used in your projects.

CSS

The styles can be used by including the main.scss file within your own SASS files.

@import 'n-conversion-forms/main';

JS

The utils can be used by including the individual file from within your own JS files. For more information see the Utilities section below.

import MyModule from 'n-conversion-forms/utils/my-module';

Utilities

Table of contents

AppBanner

new AppBanner(window);

Simple utility to use in conjunction with the app-banner partial that performs user agent sniffing. It will remove the App Store or Play Store link which ever is not relevant for the platform the user is on.

TrialBanner

Displays banner for trial only. Designed to take in dynamic period trialDuration. If period is not present, then default 30 day period would be used

Country

const country = new Country(document);

// Get the value on change
country.onChange(() => {
    const selected = country.getSelected();
});

Adds listener for country changes and retrieve the currently selected value.

Delivery Option

const deliveryOption = new DeliveryOption(document);

This utility provides the ability to bind a callback that gets fired when the delivery option gets changed by the user.

deliveryOption.handleDeliveryOptionChange(() => {
    // your code here.
});

Delivery Start Date

This utility provides the ability to call a backend service that validates the selected start date and updates the UI accordingly with the new information returned. The start date will be sent as a POST to the service as startDate in the body, along with any data returned by the given function (second parameter).

deliveryStartDate.handleDeliveryStartDateChange('/api/path', () => {
    // This function needs to return an object containing any extra data to send with the request.
});

† This requires the result of the endpoint to look as follows:

{
  firstDeliveryDate: '2019-02-16',
  firstDeliveryDateString: 'Saturday 16th of February 2019'
}

Email

const email = new Email(document);

This utility provides the following:

  • If a confirm email field is present will validate to ensure the email addresses match and present the user with an error if not.

  • Registering an email exists lookup as follows:

    email.registerEmailExistsCheck(
        backendServiceUrl,
        onFoundCallback,
        onNotFoundCallback
    );
    

    NB It's recommended you have a hidden #csrfToken input element that you validate the request with in your backend service to prevent having your service abused.

    The backend service will be sent the following as the body of a POST request: { email, csrfToken }.

Event Notifier

TBD

Loader

const loader = new Loader(document);

Requirements:

  • {{> n-conversion-forms/partials/loader }} - The element containing the overlay and loading message/spinner. Place this somewhere near the bottom of your document.

If you want to define some content, this can be done as follows:

<Loader showLoader={false} title={loaderTitle}>
    {loaderContent}
</Loader>

Showing/Hiding

The loader is hidden by default on page load.

loader.show();
loader.showAndPreventTabbing();
loader.hide();

or

To show loader on page load/render:

<Loader showLoader={true} title={loaderTitle}>

You can optionally pass in content when showing the loader:

loader.show({ title: 'Hello World!' });
loader.showAndPreventTabbing({ title: 'Hello World!' });

Loading Message

To dynamically set the message to be displayed (either of the properties are optional):

loader.setContent({
    content: '<p>Main content for the message can be defined in here</p>',
    title: 'Hooray!',
});

To clear the message entirely:

loader.clearContent();

Password

const password = new Password(document);

This utility's sole purpose (currently) is to enable the functionality behind the Show password checkbox that toggles whether the password is masked or not.

PaymentTerm

const paymentTerm = new PaymentTerm(document);

// Return the currently selected payment term
paymentTerm.getSelected();

// Update the payment term options displayed
const options = [
    {
        name: 'Name of term',
        value: 'Value to send',
        description: 'Can contain <strong>HTML</strong>',
    },
];
paymentTerm.updateOptions(options);

Update and get the currently selected payment term on the form

PaymentType

const paymentType = new PaymentType(document);

// Show payment type
paymentType.show(PaymentType.APPLEPAY);

// Hide payment type
paymentType.hide(PaymentType.CREDITCARD);

Allows the control of which payment types are shown to the user. It relies on the {{> payment-type }} partial being used and has show and hide methods.

The following payment types are allowed:

PaymentType.CREDITCARD;
PaymentType.DIRECTDEBIT;
PaymentType.PAYPAL;
PaymentType.APPLEPAY;

Salesforce

Utility for converting salesforce country names to ISO country codes.

// isoCode will equal GBR
const isoCode = salesforceNameToIsoCode('United Kingdom');

// salesfoceName will equal United Kingdom
const salesforceName = isoCodeToSalesforceName('GBR');

Submit

const submit = new Submit(document);

// Update the button text
submit.updateText('Pay with Apple Pay');

// Enable the button
submit.enable();

// Disable the button
submit.disable();

// Whether or not the button is disabled.
submit.isDisabled();

Tracking

const tracking = new Tracking(window, document.body);

TBD

Validation

const validation = new Validation();
validation.init();

This utility will set up the form for client side validation using o-forms.

NB: By default, using this utility will prompt the user with a dialog before leaving the page if there have been changes on the form. It can be disabled as follows: new Validation({mutePromptBeforeLeaving: true})

One useful property made available is the main form DOM element via validation.$form. Use this for scoping querySelector calls to find elements within your form.

Custom Validation

You can add some custom validation functionality as follows:

validation.addCustomValidation({
    errorMessage: 'Custom error message here.',
    field: domElementToValidate,
    validator: () => {
        // Custom validation code here. *Must* return truthy or falsey.
    },
});

If the validation fails, the field will look like it usually does when validation fails with your specified message displayed underneath.

Zuora

The Zuora utility aims to wrap the Zuora client side library to make it more user friendly.

Requirements:

  • {{> n-conversion-forms/partials/zuora }} - Place this where you want the form to render. This partial also includes the Zuora client side library.
const zuora = new Zuora(window);

// Will render the 3rd party Zuora iframe with client side validation and custom error messages.
// Returns a Promise that resolves ONLY once the form has loaded.
zuora.render({ params, prePopulatedFields, renderCallback });

// Will attempt to submit the 3rd party Zuora iframe form and reject if there are client side
// validation errors or if the user refuses the Direct Debit mandate confirmation.
zuora.submit(paymentType);

// Call a provided function upon the value of the direct debit agreement checkbox changing
// (inside the 3rd party Zuora iframe).
// @param {boolean} checked - whether the box was checked or not
zuora.onAgreementCheckboxChange((checked) => {});

// Call a provided function upon the confirmation or cancellation of the direct debit mandate
// (inside the 3rd party Zuora iframe).
// @param {boolean} confirmed - whether confirmed or not
zuora.onDirectDebitConfirmation((confirmed) => {});

// Sets necessary static parameters for credential user profile
// Makes a call to Zuora supplying those parameters for agreement validation
zuora.setAgreement();

// Example implementation on form submission
try {
    await this.zuora.submit('directdebit');
} catch (error) {
    if (error instanceof Zuora.ZuoraErrorValidation) {
        // Validation messages will be shown on HPM fields
        // Put other functionality on validation failure here
    } else if (error instanceof Zuora.ZuoraErrorMandateCancel) {
        // Fail silently, the direct debit mandate has been cancelled
    } else if (error instanceof Zuora.ZuoraErrorInvalidPaymentType) {
        // Invalid payment type
    } else {
        // General payment failure
    }
}

Additional Notes

Autocomplete attributes

Autocomplete fields documentation is available here: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.