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-internal

v3.27.0

Published

Dynamic Flow web client for Wise

Downloads

1,234

Readme

Dynamic Flow Web Client for Wise

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

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

Integration

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

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

# pnpm
pnpm install @wise/dynamic-flow-client-internal
  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 prop-types react react-dom react-intl
yarn add @transferwise/components @transferwise/formatting @transferwise/icons @transferwise/neptune-css

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

# pnpm
pnpm install prop-types 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-internal/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-internal';

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-internal';

// 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' }}
  customFetch={(...args) => fetch(...args)}
  onCompletion={(result) => {
    console.log('Flow exited with', result);
  }}
  onError={(error, statusCode) => {
    console.error('Flow Error:', error, 'status code', statusCode);
  }}
/>

When to use initialStep instead of initialAction

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={someInitialStep}
  customFetch={...}
  onCompletion={...}
  onError={...}
/>

The customFetch

You probably want to pass a custom fetch function. This would allow you to add additional request headers to each network request and possibly prefix a base URL to relative paths.

You can take advantage of the makeCustomFetch utility function. This function takes a 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, such as { 'X-Access-Token': 'Tr4n5f3rw153' }:

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

const customFetch = makeCustomFetch('/gateway', {
  'Accept-Language': currentLanguage,
  'X-Access-Token': 'Tr4n5f3rw153',
  'X-Visual-Context': 'personal::light'
 });

...

<DynamicFlow
  initialAction={{ method: 'GET', url: '/my-flow' }}
  customFetch={customFetch}
  onCompletion={...}
  onError={...}
/>

Writing your own customFetch function

If you want to write your own customFetch (or if you're writing mocks), it's important that you return proper 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 mockCustomFetch = (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 mockCustomFetch = (input, init) => Promise.resolve(initialResponse);
// ✅ correct - a new instance is returned on each request
const mockCustomFetch = (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 |

DynamicFragment

If you need to get the submittable data outside of a submission, you can use the DynamicFragment component. This will give you access to two methods: getValue and validate via a ref. For example:

import type { DynamicFragmentController } from '@wise/dynamic-flow-client-internal';
import { DynamicFragment } from '@wise/dynamic-flow-client-internal';
import { useRef } from 'react';

function DynamicFlowWithRef() {
  const ref = useRef<DynamicFragmentController>(null);

  return (
    <>
      <DynamicFragment
          ref={ref}
          flowId={"id"}
          customFetch={fetch}
          initialStep={selectedStep}
          onValueChange={async () => {
              const value = (await ref.current?.getValue()) ?? null);
              console.log('Value changed to', JSON.stringify(value));
          }}
          onCompletion={(error) => console.error(error)}
          onCompletion={() => console.log('Completed')}
      />
      <Button
        onClick={async () => {
          // This will get the value, whether or not the form is valid
          const value = (await ref.current?.getValue()) ?? null);

          // This will trigger validation of the form and show any validation messages to the user.
          // The response is a boolean indicating whether or not the form is valid.
          const isValid = ref.current?.validate();

          // Whatever you want to do with value
        }}
      >
        Log value
      </Button>
    </>
  );
}

Contributing

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