Skip to content

Commit

Permalink
feat: add URL search params builder
Browse files Browse the repository at this point in the history
  • Loading branch information
chybisov committed Oct 6, 2022
1 parent 8fefee0 commit 9e9c396
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 39 deletions.
36 changes: 4 additions & 32 deletions packages/widget-embedded/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
import type { Route, Token } from '@lifi/sdk';
import type { Token } from '@lifi/sdk';
import {
addChain,
switchChain,
switchChainAndAddToken,
} from '@lifi/wallet-management';
import type { RouteExecutionUpdate } from '@lifi/widget';
import {
LiFiWidget,
LiFiWidgetDrawer,
useWidgetEvents,
WidgetEvent,
} from '@lifi/widget';
import { LiFiWidget, LiFiWidgetDrawer } from '@lifi/widget';
import {
Box,
// Button,
Expand All @@ -28,13 +22,13 @@ import {
import { createTheme, ThemeProvider } from '@mui/material/styles';
import React, { useEffect, useState } from 'react';
import { WalletButtons } from './components/WalletButtons';
import { WidgetEvents } from './components/WidgetEvents';
import { widgetConfig, widgetDrawerConfig } from './config';
import './index.css';
import { useWallet } from './providers/WalletProvider';

export const App = () => {
const { connect, disconnect, account } = useWallet();
const widgetEvents = useWidgetEvents();
const [searchParams] = useState(() =>
Object.fromEntries(new URLSearchParams(window?.location.search)),
);
Expand Down Expand Up @@ -174,31 +168,9 @@ export const App = () => {
}
}, [darkMode, prefersDarkMode, primary, secondary, systemColor]);

useEffect(() => {
const onRouteExecutionStarted = (route: Route) => {
// console.log('onRouteExecutionStarted fired.');
};
const onRouteExecutionUpdated = (update: RouteExecutionUpdate) => {
// console.log('onRouteExecutionUpdated fired.');
};
const onRouteExecutionCompleted = (route: Route) => {
// console.log('onRouteExecutionCompleted fired.');
};
const onRouteExecutionFailed = (update: RouteExecutionUpdate) => {
// console.log('onRouteExecutionFailed fired.');
};
widgetEvents.on(WidgetEvent.RouteExecutionStarted, onRouteExecutionStarted);
widgetEvents.on(WidgetEvent.RouteExecutionUpdated, onRouteExecutionUpdated);
widgetEvents.on(
WidgetEvent.RouteExecutionCompleted,
onRouteExecutionCompleted,
);
widgetEvents.on(WidgetEvent.RouteExecutionFailed, onRouteExecutionFailed);
return () => widgetEvents.all.clear();
}, [widgetEvents]);

return (
<ThemeProvider theme={theme}>
<WidgetEvents />
<Box display="flex" height="100vh">
<CssBaseline />
<Drawer
Expand Down
59 changes: 59 additions & 0 deletions packages/widget-embedded/src/components/WidgetEvents.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Route } from '@lifi/sdk';
import type { RouteExecutionUpdate } from '@lifi/widget';
import { useWidgetEvents, WidgetEvent } from '@lifi/widget';
import { useEffect } from 'react';

export const WidgetEvents = () => {
// const location = useLocation();
// const [urlSearchParams, setURLSearchParams] = useState<URLSearchParams>();
const widgetEvents = useWidgetEvents();

useEffect(() => {
const onRouteExecutionStarted = (route: Route) => {
// console.log('onRouteExecutionStarted fired.');
};
const onRouteExecutionUpdated = (update: RouteExecutionUpdate) => {
// console.log('onRouteExecutionUpdated fired.');
};
const onRouteExecutionCompleted = (route: Route) => {
// console.log('onRouteExecutionCompleted fired.');
};
const onRouteExecutionFailed = (update: RouteExecutionUpdate) => {
// console.log('onRouteExecutionFailed fired.');
};
// const onInputValuesUpdated = (values: InputValuesUpdated) => {
// console.log('InputValuesUpdated', values);

// const urlSearchParams = new URLSearchParams();
// for (const key in values) {
// if (Object.prototype.hasOwnProperty.call(values, key)) {
// urlSearchParams.set(key, (values as any)[key] || '');
// }
// }
// setURLSearchParams(urlSearchParams);
// };
widgetEvents.on(WidgetEvent.RouteExecutionStarted, onRouteExecutionStarted);
widgetEvents.on(WidgetEvent.RouteExecutionUpdated, onRouteExecutionUpdated);
widgetEvents.on(
WidgetEvent.RouteExecutionCompleted,
onRouteExecutionCompleted,
);
widgetEvents.on(WidgetEvent.RouteExecutionFailed, onRouteExecutionFailed);
// widgetEvents.on(WidgetEvent.InputValuesUpdated, onInputValuesUpdated);
return () => widgetEvents.all.clear();
}, [widgetEvents]);

// useLayoutEffect(() => {
// const url = new URL(window.location as any);
// urlSearchParams?.forEach((value, key) => {
// if (value) {
// url.searchParams.set(key, value);
// } else {
// url.searchParams.delete(key);
// }
// });
// window.history.replaceState({}, '', url);
// }, [urlSearchParams, location]);

return null;
};
1 change: 1 addition & 0 deletions packages/widget-embedded/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const widgetDrawerConfig: WidgetConfig = {
allow: [], // 1, 1285, 10, 56, 137
deny: [],
},
buildSwapUrl: true,
// sdkConfig: {
// apiUrl: 'https://developkub.li.finance/v1/',
// },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FormProvider, useForm } from 'react-hook-form';
import { useWidgetConfig } from '../WidgetProvider';
import type { SwapFormValues } from './types';
import { SwapFormKey } from './types';
import { URLSearchParamsBuilder } from './URLSearchParamsBuilder';

export const formDefaultValues = {
[SwapFormKey.FromAmount]: '',
Expand All @@ -12,8 +13,15 @@ export const formDefaultValues = {
export const SwapFormProvider: React.FC<React.PropsWithChildren<{}>> = ({
children,
}) => {
const { fromChain, fromToken, fromAmount, toChain, toToken, toAddress } =
useWidgetConfig();
const {
fromChain,
fromToken,
fromAmount,
toChain,
toToken,
toAddress,
buildSwapUrl,
} = useWidgetConfig();

const methods = useForm<SwapFormValues>({
defaultValues: {
Expand All @@ -30,5 +38,10 @@ export const SwapFormProvider: React.FC<React.PropsWithChildren<{}>> = ({
},
});

return <FormProvider {...methods}>{children}</FormProvider>;
return (
<FormProvider {...methods}>
{buildSwapUrl ? <URLSearchParamsBuilder /> : null}
{children}
</FormProvider>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { useEffect, useRef } from 'react';
import { useFormState, useWatch } from 'react-hook-form';
import { useLocation } from 'react-router-dom';
import { SwapFormKey } from './types';

const formValueKeys = [
SwapFormKey.FromAmount,
SwapFormKey.FromChain,
SwapFormKey.FromToken,
SwapFormKey.ToAddress,
SwapFormKey.ToChain,
SwapFormKey.ToToken,
];

const replcateUrlState = (urlSearchParams?: URLSearchParams) => {
if (!urlSearchParams) {
return;
}
const url = new URL(window.location as any);
urlSearchParams.forEach((value, key) => {
if (value) {
url.searchParams.set(key, value);
} else {
url.searchParams.delete(key);
}
});
window.history.replaceState(null, '', url);
};

export const URLSearchParamsBuilder = () => {
const { pathname } = useLocation();
const urlSearchParamsRef = useRef<URLSearchParams>();
const { dirtyFields } = useFormState();
const values = useWatch({ name: formValueKeys });

useEffect(() => {
const urlSearchParams = new URLSearchParams();
formValueKeys.forEach((key, index) => {
if (dirtyFields[key]) {
urlSearchParams.set(key, values[index] || '');
}
});
replcateUrlState(urlSearchParams);
urlSearchParamsRef.current = urlSearchParams;
}, [dirtyFields, values]);

useEffect(() => {
replcateUrlState(urlSearchParamsRef.current);
}, [pathname]);

return null;
};
8 changes: 4 additions & 4 deletions packages/widget/src/providers/SwapFormProvider/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ export enum SwapFormKey {
FromAmount = 'fromAmount',
FromChain = 'fromChain',
FromToken = 'fromToken',
TokenSearchFilter = 'tokenSearchFilter',
ToAddress = 'toAddress',
ToChain = 'toChain',
ToToken = 'toToken',
ToAddress = 'toAddress',
TokenSearchFilter = 'tokenSearchFilter',
}

export type SwapFormValues = {
[SwapFormKey.FromAmount]: string;
[SwapFormKey.FromChain]: number;
[SwapFormKey.FromToken]: string;
[SwapFormKey.TokenSearchFilter]: string;
[SwapFormKey.ToAddress]: string;
[SwapFormKey.ToChain]: number;
[SwapFormKey.ToToken]: string;
[SwapFormKey.ToAddress]: string;
[SwapFormKey.TokenSearchFilter]: string;
};

export type SwapFormType = 'from' | 'to';
Expand Down
2 changes: 2 additions & 0 deletions packages/widget/src/types/widget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ export interface WidgetConfig {
walletManagement?: WidgetWalletManagement;
sdkConfig?: ConfigUpdate;

buildSwapUrl?: boolean;

bridges?: {
allow?: string[];
deny?: string[];
Expand Down

0 comments on commit 9e9c396

Please sign in to comment.