@wise/dynamic-flow-client
TypeScript icon, indicating that this package has built-in type declarations

3.7.0 • Public • Published

Dynamic Flow Web Client

This is the Dynamic Flow web client. It provides a simple way to integrate a Dynamic Flow into your web app.

⚡ Access the latest deployed version of the Dynamic Flow Playground.

Integration

  1. Install @wise/dynamic-flow-client.
# yarn
yarn add @wise/dynamic-flow-client

# npm
npm install @wise/dynamic-flow-client

# pnpm
pnpm install @wise/dynamic-flow-client
  1. Install required peer dependencies (if not already installed). Please refer to setup instructions for @transferwise/components and @transferwise/neptune-css if installing up for the first time.
# yarn
yarn add react react-dom react-intl
yarn add @transferwise/components @transferwise/formatting @transferwise/icons @transferwise/neptune-css

# npm
npm install react react-dom react-intl
npm install @transferwise/components @transferwise/formatting @transferwise/icons @transferwise/neptune-css

# pnpm
pnpm install react react-dom react-intl
pnpm install @transferwise/components @transferwise/formatting @transferwise/icons @transferwise/neptune-css

Note: Keep in mind that some of these dependencies have their own peer dependencies. Don't forget to install those, for instance: @transferwise/components needs @wise/art and @wise/components-theming.

// Should be imported once in your application
import '@wise/dynamic-flow-client/build/main.css';

The DynamicFlow component must be wraped in a Neptune Provider to support localisation, a ThemeProvider to provide theming, and a SnackbarProvider to ensure snackbars display correctly. Translations should be imported from both components and dynamic flows, merged, and passed to the Provider component (as below).

For CRAB apps, use the getLocalisedMessages(...) function for translations

import {
  Provider,
  SnackbarProvider,
  translations as componentTranslations,
} from '@transferwise/components';
import { getLocalisedMessages } from '@transferwise/crab/client';
import {
  DynamicFlow,
  translations as dynamicFlowsTranslations,
} from '@wise/dynamic-flow-client';

const messages = getLocalisedMessages(locale, [componentTranslations, dynamicFlowsTranslations])

return (
  <Provider i18n={{ locale, messages }}>
    <ThemeProvider theme={theme} screenMode={screenMode}>
      <SnackbarProvider>
        <DynamicFlow {...props} />
      </SnackbarProvider>
    </ThemeProvider>
  </Provider>
);

For non-CRAB apps

You'll need to merge the '@transferwise/components' translations with the '@wise/dynamic-flow-client' translations.

import {
  Provider,
  SnackbarProvider,
  translations as componentTranslations,
} from '@transferwise/components';
import {
  DynamicFlow,
  translations as dynamicFlowsTranslations,
} from '@wise/dynamic-flow-client';

// create your messages object
const messages: Record<string, string> = {
  ...(componentTranslations[lang] || componentTranslations[lang.replace('-', '_')] || componentTranslations[lang.substring(0, 2)] || {}),
  ...(translations[lang] || translations[lang.replace('-', '_')] || translations[lang.substring(0, 2)] || {}),
}

return (
  <Provider i18n={{ locale, messages }}>
    <ThemeProvider theme={theme} screenMode={screenMode}>
      <SnackbarProvider>
        <DynamicFlow {...props} />
      </SnackbarProvider>
    </ThemeProvider>
  </Provider>
);

Configuring your Flow

DF can be initialised with initialAction (recommended) or with an initialStep.

<DynamicFlow
  initialAction={{ method: 'GET', url: '/my-amazing-new-flow' }}
  httpClient={(...args) => fetch(...args)}
  onCompletion={(result) => {
    console.log('Flow exited with', result);
  }}
  onError={(error, statusCode) => {
    console.error('Flow Error:', error, 'status code', statusCode);
  }}
/>

initialAction vs initialStep

In some cases you may want to obtain the initial step yourself, and then pass it to DF component. In these cases you don't provide a initialAction since the next steps will result from interactions in the provided initialStep:

<DynamicFlow
  initialStep={someInitialStepIfoundLayingAroundHere}
  httpClient={...}
  onCompletion={...}
  onError={...}
/>

The httpClient function prop

You must pass a httpClient function. This can be window.fetch itself or some wrapper function where you inject authorisation headers and anything else you many need.

You can take advantage of the provided makeHttpClient utility function. This function takes baseUrl and additionalHeaders arguments. The baseUrl will be prefixed to any relative request URLs. Absolute URLs will not be altered. The additionalHeaders parameter can be used to add any request headers you need in all requests.

import { makeHttpClient, DynamicFlow } from '@wise/dynamic-flow-client';

const myHttpClient = makeHttpClient('/my-base-url', { 'X-Access-Token': 'an-access-token' });

<DynamicFlow
  initialAction={{ method: 'GET', url: '/flow-starting-url' }}
  httpClient={myHttpClient}
  onCompletion={...}
  onError={...}
/>

Custom httpClient functions

If you want to write your own httpClient function (or if you're writing mocks), it's important that you return actual Response objects, and that you do not throw. Errors should result in a response with an error status code and potentially a body with an error message. For example:

const mockHttpClient = (input, init) => {
  switch (input) {
    case '/standard':
      return Promise.resolve(new Response(init.body));
    case '/exit':
      return Promise.resolve(new Response(init.body, { headers: { 'x-df-exit': true } }));
    case '/error':
    default:
      return Promise.resolve(new Response('An error has occurred.', { status: 500 }));
  }
};

Also, please make sure your mocks return a new Response instace every time. This is because responses are mutated when we parse their body, and they cannot be parsed a second time.

const initialResponse = new Response(JSON.stringify(initialStep));
// ❌ wrong - the same instance is returned on each request
const mockHttpClient = (input, init) => Promise.resolve(initialResponse);
// ✅ correct - a new instance is returned on each request
const mockHttpClient = (input, init) => Promise.resolve(new Response(JSON.stringify(initialStep)));

Telemetry

The DynamicFlow component accepts two optional props: onEvent and onLog which can be used to track and log.

In the example below we send tracking events to Mixpanel and logging events to Rollbar.

<DynamicFlow
  onEvent={(event, props) => mixpanel.track(event, props)}
  onLog={(level, message, extra) => Rollbar[level](message, extra)}
/>

Alternatively, you can log to the browser console:

onEvent={(event, props) => console.log(event, props)}
onLog={(level, message, extra) => {
  const levelToConsole = {
    critical: console.error,
    error: console.error,
    warning: console.warn,
    info: console.info,
    debug: console.log,
  } as const;
  levelToConsole[level](message, extra);
}}

Loader configuration

By default, DF will display a loading animation (The Loader component from Neptune) when the first step is loading. It will not display it during refresh-on-change or while submitting forms.

You can change the defaults by passing a loaderConfig prop:

type LoaderConfig = {
  size?: `xs | sm | md | lg | xl`;
  initial?: boolean;
  submission?: boolean;
};
property type notes default
size string The size of the Loader component. xl
initial boolean Whether or not to display the Loader component while loading the initial step. true
submission boolean Whether or not to display the Loader component during form submissions. false

Contributing

We love contributions! Check out CONTRIBUTING.md for more information.

Readme

Keywords

none

Package Sidebar

Install

npm i @wise/dynamic-flow-client

Weekly Downloads

174

Version

3.7.0

License

Apache-2.0

Unpacked Size

2.39 MB

Total Files

429

Last publish

Collaborators

  • tw-circleci