Skip to content

Commit

Permalink
refactor(widget): make only one flat set of params (#3318)
Browse files Browse the repository at this point in the history
* docs(widget): typedoc for widget lib

* fix(widget): simplify metaData and use default value for it

* refactor(widget): make only one flat set of params

* chore: fix tests

* refactor: replace metaData just by appKey

* chore: add defaults for CowSwapWidgetParams docs

* chore: change widget and height types

* chore: fix docs

* chore: remove dynamicHeightEnabled

* chore: fix docs
  • Loading branch information
shoom3301 authored Nov 3, 2023
1 parent bb6e26f commit 7d6d49f
Show file tree
Hide file tree
Showing 22 changed files with 284 additions and 243 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useMemo } from 'react'
import { useEffect } from 'react'

import {
Dimensions,
Expand Down Expand Up @@ -76,10 +76,7 @@ export function useAnalyticsReporter() {

const walletName = _walletName || getConnectionName(connection.type, isMetaMask)

const injectedWidgetAppId = useMemo(
() => (injectedWidgetMetaData ? `${injectedWidgetMetaData.appKey}:${injectedWidgetMetaData.url}` : ''),
[injectedWidgetMetaData]
)
const injectedWidgetAppId = injectedWidgetMetaData.appKey

useEffect(() => {
// Custom dimension 2 - walletname
Expand Down
2 changes: 1 addition & 1 deletion apps/cowswap-frontend/src/modules/appData/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function useAppCode(): string | null {

return useMemo(() => {
if (isInjectedWidget()) {
return injectedWidgetMetaData?.appKey || null
return injectedWidgetMetaData.appKey
}

if (APP_CODE) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useAtomValue } from 'jotai'

import { InjectedWidgetMetaData, injectedWidgetMetaDataAtom } from '../state/injectedWidgetMetaDataAtom'
import { CowSwapWidgetMetaData, injectedWidgetMetaDataAtom } from '../state/injectedWidgetMetaDataAtom'

export function useInjectedWidgetMetaData(): InjectedWidgetMetaData | null {
export function useInjectedWidgetMetaData(): CowSwapWidgetMetaData {
return useAtomValue(injectedWidgetMetaDataAtom)
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { useAtomValue } from 'jotai'

import type { CowSwapWidgetAppParams } from '@cowprotocol/widget-lib'
import type { CowSwapWidgetParams } from '@cowprotocol/widget-lib'

import { injectedWidgetParamsAtom } from '../state/injectedWidgetParamsAtom'

export function useInjectedWidgetParams(): CowSwapWidgetAppParams {
export function useInjectedWidgetParams(): CowSwapWidgetParams {
return useAtomValue(injectedWidgetParamsAtom)
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { atom } from 'jotai'

export interface InjectedWidgetMetaData {
export interface CowSwapWidgetMetaData {
appKey: string
url: string
}

export const injectedWidgetMetaDataAtom = atom<InjectedWidgetMetaData | null>(null)
const DEFAULT_INJECTED_WIDGET_META_DATA: CowSwapWidgetMetaData = {
appKey: 'DEFAULT_INJECTED_WIDGET',
}

export const injectedWidgetMetaDataAtom = atom<CowSwapWidgetMetaData>(DEFAULT_INJECTED_WIDGET_META_DATA)
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { atom } from 'jotai'

import type { CowSwapWidgetAppParams } from '@cowprotocol/widget-lib'
import type { CowSwapWidgetParams } from '@cowprotocol/widget-lib'

export const injectedWidgetParamsAtom = atom<CowSwapWidgetAppParams>({})
export const injectedWidgetParamsAtom = atom<CowSwapWidgetParams>({})
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { useLayoutEffect, useRef } from 'react'

import { COW_SWAP_WIDGET_EVENT_KEY } from '../consts'
import { useInjectedWidgetParams } from '../hooks/useInjectedWidgetParams'

const TARGET_ORIGIN = '*' // Change to CoW specific origin in production

export function IframeResizer() {
const { dynamicHeightEnabled } = useInjectedWidgetParams()
const previousHeightRef = useRef(0)

useLayoutEffect(() => {
if (!dynamicHeightEnabled) return

// Initial height calculation and message
const sendHeightUpdate = () => {
const contentHeight = document.body.scrollHeight
Expand All @@ -37,7 +33,7 @@ export function IframeResizer() {
return () => {
observer.disconnect()
}
}, [dynamicHeightEnabled])
}, [])

return null
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export function InjectedWidgetUpdater() {
navigate(data.urlParams)
}

if (method === 'metaData') {
if (method === 'metaData' && data.metaData) {
updateMetaData(data.metaData)
}
},
Expand Down
12 changes: 5 additions & 7 deletions apps/widget-configurator/src/app/configurator/embedDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ import { nightOwl } from 'react-syntax-highlighter/dist/esm/styles/hljs'

export interface EmbedDialogProps {
params: CowSwapWidgetProps['params']
settings: CowSwapWidgetProps['settings']
}

export function EmbedDialog({ params, settings }: EmbedDialogProps) {
export function EmbedDialog({ params }: EmbedDialogProps) {
const [open, setOpen] = useState(false)
const [scroll, setScroll] = useState<DialogProps['scroll']>('paper')

Expand All @@ -42,18 +41,17 @@ export function EmbedDialog({ params, settings }: EmbedDialogProps) {

const paramsSanitized = {
...params,
container: `<YOUR_CONTAINER>`,
provider: `<eip-1193 provider>`,
}

const code = `
import { CowSwapWidgetParams, CowSwapWidgetSettings, cowSwapWidget } from '@cowprotocol/widget-lib'
import { CowSwapWidgetParams, cowSwapWidget } from '@cowprotocol/widget-lib'
const params: CowSwapWidgetParams = ${JSON.stringify(paramsSanitized, null, 4)}
const container = document.getElementById('<YOUR_CONTAINER>')
const settings: CowSwapWidgetSettings = ${JSON.stringify(settings, null, 4)}
const params: CowSwapWidgetParams = ${JSON.stringify(paramsSanitized, null, 4)}
const updateWidget = cowSwapWidget(params, settings)
const updateWidget = cowSwapWidget(container, params)
`

const handleCopy = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,17 +28,13 @@ export function useWidgetParamsAndSettings(
sellTokenAmount,
buyToken,
buyTokenAmount,
dynamicHeightEnabled,
} = configuratorState

const params: CowSwapWidgetProps['params'] = {
metaData: { appKey: '<YOUR_APP_ID>', url: '<https://YOUR_APP_URL>' },
width: 400,
height: 640,
appKey: '<YOUR_APP_ID>',
width: '400px',
height: '640px',
provider,
}

const settings: CowSwapWidgetProps['settings'] = {
theme,
chainId,
env: getEnv(),
Expand All @@ -47,16 +43,15 @@ export function useWidgetParamsAndSettings(
sell: { asset: sellToken, amount: sellTokenAmount ? sellTokenAmount.toString() : undefined },
buy: { asset: buyToken, amount: buyTokenAmount?.toString() },
},
dynamicHeightEnabled,
enabledTradeTypes,
// palette: {
// primaryColor: '#d9258e',
// screenBackground: '#c7860f',
// widgetBackground: '#eed4a7',
// textColor: '#413931',
// screenBackground: '#ee00cd',
// widgetBackground: '#b900ff',
// textColor: '#b348cc',
// },
}

return { params, settings }
return params
}, [provider, configuratorState])
}
10 changes: 4 additions & 6 deletions apps/widget-configurator/src/app/configurator/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,9 @@ export function Configurator({ title }: { title: string }) {
sellTokenAmount,
buyToken,
buyTokenAmount,
dynamicHeightEnabled: true,
}

const paramsAndSettings = useWidgetParamsAndSettings(provider, state)
const { params, settings } = paramsAndSettings || {}
const params = useWidgetParamsAndSettings(provider, state)

useEffect(() => {
web3Modal.setThemeMode(mode)
Expand Down Expand Up @@ -117,11 +115,11 @@ export function Configurator({ title }: { title: string }) {
</Drawer>

<Box sx={ContentStyled}>
{params && settings && (
{params && (
<>
<EmbedDialog params={params} settings={settings} />
<EmbedDialog params={params} />
<br />
<CowSwapWidget provider={provider} settings={settings} params={params} />
<CowSwapWidget provider={provider} params={params} />
</>
)}
</Box>
Expand Down
1 change: 0 additions & 1 deletion apps/widget-configurator/src/app/configurator/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,4 @@ export interface ConfiguratorState {
sellTokenAmount: number | undefined
buyToken: string
buyTokenAmount: number | undefined
dynamicHeightEnabled: boolean
}
24 changes: 11 additions & 13 deletions libs/widget-lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,29 +31,27 @@ Create a container somewhere in your website, the widget will be rendered inside
Import the widget and initialise it:

```js
import { cowSwapWidget } from '@cowprotocol/widget-lib'
import { cowSwapWidget, CowSwapWidgetParams } from '@cowprotocol/widget-lib'

// Initialise the widget
const widgetContainer = document.getElementById('cowswap-widget')

const updateWidget = cowSwapWidget({
container: widgetContainer,
width: 600,
height: 640,
metaData: {
appKey: '<YOUR_APP_KEY>', // Just an unique identifier for your app,
appUrl: '<YOUR_APP_URL>'
},
// Optionally, you can provide some additional params to customise your widget
}, {
const params: CowSwapWidgetParams = {
appKey: '<YOUR_APP_KEY>', // Just an unique identifier for your app
sell: { asset: 'DAI' },
buy: { asset: 'USDC', amount: '0.1' },
// instantiate your own web3 provider
provider: window.ethereum
})
}

const updateWidget = cowSwapWidget(
widgetContainer,
// Optionally, you can provide some additional params to customise your widget
params
)

// You also can change widget configuration on the fly
updateWidget({ tradeType: 'limit' })
updateWidget({ ...params, tradeType: 'limit' })
```

## Developers
Expand Down
14 changes: 2 additions & 12 deletions libs/widget-lib/demo/vanilla.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,12 @@
<head>
<meta charset="UTF-8">
<title>CoWSwap Widget demo</title>
<script src="https://cdn.jsdelivr.net/npm/@cowprotocol/[email protected].2/index.iife.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@cowprotocol/[email protected].3/index.iife.js"></script>
</head>
<body>
<div id="app"></div>
<script>
cowSwapWidget.cowSwapWidget({
container: document.getElementById("app"),
width: 400,
height: 600,
metaData: {
appKey: 'test',
appUrl: 'test',
}
}, {
env: 'dev'
})
cowSwapWidget.cowSwapWidget(document.getElementById("app"))
</script>
</body>
</html>
Loading

0 comments on commit 7d6d49f

Please sign in to comment.