@wise/dynamic-flow-client-internal
v5.1.0
Published
Dynamic Flow web client for Wise
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
- 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- Install required peer dependencies (if not already installed). Please refer to setup instructions for
@transferwise/componentsand@transferwise/neptune-cssif installing 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-cssNote: 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.
- In addition to the design system styles, you need to import the DynamicFlow styles once into your application. You can do this either via JavaScript or CSS.
import '@wise/dynamic-flow-client-internal/main.css'; // JavaScript@import url('@wise/dynamic-flow-client-internal/build/main.css'); /* 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 dsTranslations,
} from '@transferwise/components';
import { getLocalisedMessages } from '@transferwise/crab/client';
import {
DynamicFlow,
translations as dfTranslations,
} from '@wise/dynamic-flow-client-internal';
const messages = getLocalisedMessages(locale, [dsTranslations, dfTranslations]);
return (
<Provider i18n={{ locale, messages }}>
<ThemeProvider theme={theme} screenMode={screenMode}>
<SnackbarProvider>
<DynamicFlow {...props} />
</SnackbarProvider>
</ThemeProvider>
</Provider>
);Container-based image sizes
To enable container queries for image layout components, add the following class name to the className property of the DynamicFlow component:
<DynamicFlow
className="df-prefer-container-queries"
{...allOtherProps}
/>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 dsTranslations,
} from '@transferwise/components';
import {
DynamicFlow,
translations as dfTranslations,
} from '@wise/dynamic-flow-client-internal';
// create your messages object
const messages: Record<string, string> = {
...(dsTranslations[lang] || dsTranslations[lang.replace('-', '_')] || dsTranslations[lang.substring(0, 2)] || {}),
...(dfTranslations[lang] || dfTranslations[lang.replace('-', '_')] || dfTranslations[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: onAnalytics 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
onAnalytics={(event, props) => mixpanel.track(event, props)}
onLog={(level, message, extra) => Rollbar[level](message, extra)}
/>Alternatively, you can log to the browser console:
onAnalytics={(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);
}}DynamicForm Component
If you need to get the submittable data outside of a submission, you can use the DynamicForm component. This will give you access to two methods: getValue and validate via a ref. For example:
import type { DynamicFormController } from '@wise/dynamic-flow-client-internal';
import { DynamicForm } from '@wise/dynamic-flow-client-internal';
import { useRef } from 'react';
function DynamicFlowWithRef() {
const ref = useRef<DynamicFormController>(null);
return (
<div>
<DynamicForm
ref={ref}
flowId={"id"}
customFetch={fetch}
initialStep={myStep}
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>
</div>
);
}Contributing
We love contributions! Check out CONTRIBUTING.md for more information.
