@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
- 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/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.