npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wise/dynamic-flow-client

v3.7.0

Published

Dynamic Flow web client

Downloads

1,075

Readme

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.