2
0

♻️ (editor) Improve webhook creation

Remove terrible useEffects
This commit is contained in:
Baptiste Arnaud
2023-02-15 14:51:58 +01:00
parent 6e066c44e1
commit ac464eabdf
23 changed files with 481 additions and 528 deletions

View File

@ -22,17 +22,16 @@ import {
VariableForTest,
ResponseVariableMapping,
WebhookBlock,
defaultWebhookAttributes,
Webhook,
MakeComBlock,
PabblyConnectBlock,
Webhook,
} from 'models'
import { DropdownList } from '@/components/DropdownList'
import { CodeEditor } from '@/components/CodeEditor'
import { HeadersInputs, QueryParamsInputs } from './KeyValueInputs'
import { VariableForTestInputs } from './VariableForTestInputs'
import { DataVariableInputs } from './ResponseMappingInputs'
import { byId } from 'utils'
import { byId, env } from 'utils'
import { ExternalLinkIcon } from '@/components/icons'
import { useToast } from '@/hooks/useToast'
import { SwitchWithLabel } from '@/components/SwitchWithLabel'
@ -41,11 +40,15 @@ import { executeWebhook } from '../../queries/executeWebhookQuery'
import { getDeepKeys } from '../../utils/getDeepKeys'
import { Input } from '@/components/inputs'
import { convertVariablesForTestToVariables } from '../../utils/convertVariablesForTestToVariables'
import { useDebouncedCallback } from 'use-debounce'
const debounceWebhookTimeout = 2000
type Provider = {
name: 'Make.com' | 'Pabbly Connect'
name: 'Pabbly Connect'
url: string
}
type Props = {
block: WebhookBlock | MakeComBlock | PabblyConnectBlock
onOptionsChange: (options: WebhookOptions) => void
@ -61,39 +64,28 @@ export const WebhookSettings = ({
const [isTestResponseLoading, setIsTestResponseLoading] = useState(false)
const [testResponse, setTestResponse] = useState<string>()
const [responseKeys, setResponseKeys] = useState<string[]>([])
const { showToast } = useToast()
const [localWebhook, setLocalWebhook] = useState(
const [localWebhook, _setLocalWebhook] = useState(
webhooks.find(byId(webhookId))
)
const updateWebhookDebounced = useDebouncedCallback(
async (newLocalWebhook) => {
await updateWebhook(newLocalWebhook.id, newLocalWebhook)
},
env('E2E_TEST') === 'true' ? 0 : debounceWebhookTimeout
)
useEffect(() => {
if (localWebhook) return
const incomingWebhook = webhooks.find(byId(webhookId))
setLocalWebhook(incomingWebhook)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [webhooks])
const setLocalWebhook = (newLocalWebhook: Webhook) => {
_setLocalWebhook(newLocalWebhook)
updateWebhookDebounced(newLocalWebhook)
}
useEffect(() => {
if (!typebot) return
if (!localWebhook) {
const newWebhook = {
id: webhookId,
...defaultWebhookAttributes,
typebotId: typebot.id,
} as Webhook
updateWebhook(webhookId, newWebhook)
}
return () => {
setLocalWebhook((localWebhook) => {
if (!localWebhook) return
updateWebhook(webhookId, localWebhook).then()
return localWebhook
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(
() => () => {
updateWebhookDebounced.flush()
},
[updateWebhookDebounced]
)
const handleUrlChange = (url?: string) =>
localWebhook && setLocalWebhook({ ...localWebhook, url: url ?? null })
@ -126,8 +118,7 @@ export const WebhookSettings = ({
const handleTestRequestClick = async () => {
if (!typebot || !localWebhook) return
setIsTestResponseLoading(true)
await updateWebhook(localWebhook.id, localWebhook)
await save()
await Promise.all([updateWebhook(localWebhook.id, localWebhook), save()])
const { data, error } = await executeWebhook(
typebot.id,
convertVariablesForTestToVariables(
@ -152,6 +143,7 @@ export const WebhookSettings = ({
)
if (!localWebhook) return <Spinner />
return (
<Stack spacing={4}>
{provider && (

View File

@ -1,4 +1,4 @@
export { duplicateWebhookQueries } from './queries/duplicateWebhookQuery'
export { duplicateWebhookQuery } from './queries/duplicateWebhookQuery'
export { WebhookSettings } from './components/WebhookSettings'
export { WebhookContent } from './components/WebhookContent'
export { WebhookIcon } from './components/WebhookIcon'

View File

@ -0,0 +1,14 @@
import { Webhook } from 'models'
import { sendRequest } from 'utils'
type Props = {
typebotId: string
data: Partial<Omit<Webhook, 'typebotId'>>
}
export const createWebhookQuery = ({ typebotId, data }: Props) =>
sendRequest<{ webhook: Webhook }>({
method: 'POST',
url: `/api/typebots/${typebotId}/webhooks`,
body: { data },
})

View File

@ -1,17 +1,27 @@
import { Webhook } from 'models'
import { sendRequest } from 'utils'
import { saveWebhookQuery } from './saveWebhookQuery'
import { createWebhookQuery } from './createWebhookQuery'
export const duplicateWebhookQueries = async (
typebotId: string,
existingWebhookId: string,
newWebhookId: string
): Promise<Webhook | undefined> => {
type Props = {
existingIds: { typebotId: string; webhookId: string }
newIds: { typebotId: string; webhookId: string }
}
export const duplicateWebhookQuery = async ({
existingIds,
newIds,
}: Props): Promise<Webhook | undefined> => {
const { data } = await sendRequest<{ webhook: Webhook }>(
`/api/webhooks/${existingWebhookId}`
`/api/typebots/${existingIds.typebotId}/webhooks/${existingIds.webhookId}`
)
if (!data) return
const newWebhook = { ...data.webhook, id: newWebhookId, typebotId }
await saveWebhookQuery(newWebhook.id, newWebhook)
const newWebhook = {
...data.webhook,
id: newIds.webhookId,
typebotId: newIds.typebotId,
}
await createWebhookQuery({
typebotId: newIds.typebotId,
data: { ...data.webhook, id: newIds.webhookId },
})
return newWebhook
}

View File

@ -1,12 +0,0 @@
import { Webhook } from 'models'
import { sendRequest } from 'utils'
export const saveWebhookQuery = (
webhookId: string,
webhook: Partial<Webhook>
) =>
sendRequest<{ webhook: Webhook }>({
method: 'PUT',
url: `/api/webhooks/${webhookId}`,
body: webhook,
})

View File

@ -0,0 +1,15 @@
import { Webhook } from 'models'
import { sendRequest } from 'utils'
type Props = {
typebotId: string
webhookId: string
data: Partial<Omit<Webhook, 'id' | 'typebotId'>>
}
export const updateWebhookQuery = ({ typebotId, webhookId, data }: Props) =>
sendRequest<{ webhook: Webhook }>({
method: 'PATCH',
url: `/api/typebots/${typebotId}/webhooks/${webhookId}`,
body: { data },
})

View File

@ -1,4 +1,4 @@
import { duplicateWebhookQueries } from '@/features/blocks/integrations/webhook'
import { duplicateWebhookQuery } from '@/features/blocks/integrations/webhook'
import { createId } from '@paralleldrive/cuid2'
import { Plan, Prisma } from 'db'
import {
@ -25,11 +25,13 @@ export const importTypebotQuery = async (typebot: Typebot, userPlan: Plan) => {
.filter(isWebhookBlock)
await Promise.all(
webhookBlocks.map((s) =>
duplicateWebhookQueries(
newTypebot.id,
s.webhookId,
webhookIdsMapping.get(s.webhookId) as string
)
duplicateWebhookQuery({
existingIds: { typebotId: typebot.id, webhookId: s.webhookId },
newIds: {
typebotId: newTypebot.id,
webhookId: webhookIdsMapping.get(s.webhookId) as string,
},
})
)
)
return { data, error }

View File

@ -11,6 +11,7 @@ import { Router, useRouter } from 'next/router'
import {
createContext,
ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
@ -34,7 +35,7 @@ import {
updatePublishedTypebotQuery,
deletePublishedTypebotQuery,
} from '@/features/publish/queries'
import { saveWebhookQuery } from '@/features/blocks/integrations/webhook/queries/saveWebhookQuery'
import { updateWebhookQuery } from '@/features/blocks/integrations/webhook/queries/updateWebhookQuery'
import {
checkIfTypebotsAreEqual,
checkIfPublished,
@ -43,6 +44,8 @@ import {
parsePublicTypebotToTypebot,
} from '@/features/publish/utils'
import { useAutoSave } from '@/hooks/useAutoSave'
import { createWebhookQuery } from '@/features/blocks/integrations/webhook/queries/createWebhookQuery'
import { duplicateWebhookQuery } from '@/features/blocks/integrations/webhook/queries/duplicateWebhookQuery'
const autoSaveTimeout = 10000
@ -306,20 +309,61 @@ export const TypebotProvider = ({
return saveTypebot()
}
const updateWebhook = async (
webhookId: string,
updates: Partial<Webhook>
const updateWebhook = useCallback(
async (webhookId: string, updates: Partial<Webhook>) => {
if (!typebot) return
const { data } = await updateWebhookQuery({
typebotId: typebot.id,
webhookId,
data: updates,
})
if (data)
mutate({
typebot,
publishedTypebot,
webhooks: (webhooks ?? []).map((w) =>
w.id === webhookId ? data.webhook : w
),
})
},
[mutate, publishedTypebot, typebot, webhooks]
)
const createWebhook = async (data: Partial<Webhook>) => {
if (!typebot) return
const response = await createWebhookQuery({
typebotId: typebot.id,
data,
})
if (!response.data?.webhook) return
mutate({
typebot,
publishedTypebot,
webhooks: (webhooks ?? []).concat(response.data?.webhook),
})
}
const duplicateWebhook = async (
existingWebhookId: string,
newWebhookId: string
) => {
if (!typebot) return
const { data } = await saveWebhookQuery(webhookId, updates)
if (data)
mutate({
typebot,
publishedTypebot,
webhooks: (webhooks ?? []).map((w) =>
w.id === webhookId ? data.webhook : w
),
})
const newWebhook = await duplicateWebhookQuery({
existingIds: {
typebotId: typebot.id,
webhookId: existingWebhookId,
},
newIds: {
typebotId: typebot.id,
webhookId: newWebhookId,
},
})
if (!newWebhook) return
mutate({
typebot,
publishedTypebot,
webhooks: (webhooks ?? []).concat(newWebhook),
})
}
return (
@ -343,8 +387,14 @@ export const TypebotProvider = ({
updateTypebot: updateLocalTypebot,
restorePublishedTypebot,
updateWebhook,
...groupsActions(setLocalTypebot as SetTypebot),
...blocksAction(setLocalTypebot as SetTypebot),
...groupsActions(setLocalTypebot as SetTypebot, {
onWebhookBlockCreated: createWebhook,
onWebhookBlockDuplicated: duplicateWebhook,
}),
...blocksAction(setLocalTypebot as SetTypebot, {
onWebhookBlockCreated: createWebhook,
onWebhookBlockDuplicated: duplicateWebhook,
}),
...variablesAction(setLocalTypebot as SetTypebot),
...edgesAction(setLocalTypebot as SetTypebot),
...itemsAction(setLocalTypebot as SetTypebot),

View File

@ -4,6 +4,7 @@ import {
DraggableBlock,
DraggableBlockType,
BlockIndices,
Webhook,
} from 'models'
import { WritableDraft } from 'immer/dist/types/types-external'
import { SetTypebot } from '../TypebotProvider'
@ -29,7 +30,18 @@ export type BlocksActions = {
deleteBlock: (indices: BlockIndices) => void
}
export const blocksAction = (setTypebot: SetTypebot): BlocksActions => ({
export type WebhookCallBacks = {
onWebhookBlockCreated: (data: Partial<Webhook>) => void
onWebhookBlockDuplicated: (
existingWebhookId: string,
newWebhookId: string
) => void
}
export const blocksAction = (
setTypebot: SetTypebot,
{ onWebhookBlockCreated, onWebhookBlockDuplicated }: WebhookCallBacks
): BlocksActions => ({
createBlock: (
groupId: string,
block: DraggableBlock | DraggableBlockType,
@ -37,7 +49,13 @@ export const blocksAction = (setTypebot: SetTypebot): BlocksActions => ({
) =>
setTypebot((typebot) =>
produce(typebot, (typebot) => {
createBlockDraft(typebot, block, groupId, indices)
createBlockDraft(
typebot,
block,
groupId,
indices,
onWebhookBlockCreated
)
})
),
updateBlock: (
@ -54,7 +72,10 @@ export const blocksAction = (setTypebot: SetTypebot): BlocksActions => ({
setTypebot((typebot) =>
produce(typebot, (typebot) => {
const block = { ...typebot.groups[groupIndex].blocks[blockIndex] }
const newBlock = duplicateBlockDraft(block.groupId)(block)
const newBlock = duplicateBlockDraft(block.groupId)(
block,
onWebhookBlockDuplicated
)
typebot.groups[groupIndex].blocks.splice(blockIndex + 1, 0, newBlock)
})
),
@ -81,7 +102,8 @@ export const createBlockDraft = (
typebot: WritableDraft<Typebot>,
block: DraggableBlock | DraggableBlockType,
groupId: string,
{ groupIndex, blockIndex }: BlockIndices
{ groupIndex, blockIndex }: BlockIndices,
onWebhookBlockCreated?: (data: Partial<Webhook>) => void
) => {
const blocks = typebot.groups[groupIndex].blocks
if (
@ -91,7 +113,13 @@ export const createBlockDraft = (
)
deleteEdgeDraft(typebot, blocks[blockIndex - 1].outgoingEdgeId as string)
typeof block === 'string'
? createNewBlock(typebot, block, groupId, { groupIndex, blockIndex })
? createNewBlock(
typebot,
block,
groupId,
{ groupIndex, blockIndex },
onWebhookBlockCreated
)
: moveBlockToGroup(typebot, block, groupId, { groupIndex, blockIndex })
removeEmptyGroups(typebot)
}
@ -100,10 +128,13 @@ const createNewBlock = async (
typebot: WritableDraft<Typebot>,
type: DraggableBlockType,
groupId: string,
{ groupIndex, blockIndex }: BlockIndices
{ groupIndex, blockIndex }: BlockIndices,
onWebhookBlockCreated?: (data: Partial<Webhook>) => void
) => {
const newBlock = parseNewBlock(type, groupId)
typebot.groups[groupIndex].blocks.splice(blockIndex ?? 0, 0, newBlock)
if (onWebhookBlockCreated && 'webhookId' in newBlock && newBlock.webhookId)
onWebhookBlockCreated({ id: newBlock.webhookId })
}
const moveBlockToGroup = (
@ -140,7 +171,10 @@ const moveBlockToGroup = (
export const duplicateBlockDraft =
(groupId: string) =>
(block: Block): Block => {
(
block: Block,
onWebhookBlockDuplicated: WebhookCallBacks['onWebhookBlockDuplicated']
): Block => {
const blockId = createId()
if (blockHasItems(block))
return {
@ -150,14 +184,17 @@ export const duplicateBlockDraft =
items: block.items.map(duplicateItemDraft(blockId)),
outgoingEdgeId: undefined,
} as Block
if (isWebhookBlock(block))
if (isWebhookBlock(block)) {
const newWebhookId = createId()
onWebhookBlockDuplicated(block.webhookId, newWebhookId)
return {
...block,
groupId,
id: blockId,
webhookId: createId(),
webhookId: newWebhookId,
outgoingEdgeId: undefined,
}
}
return {
...block,
groupId,

View File

@ -6,6 +6,7 @@ import {
deleteGroupDraft,
createBlockDraft,
duplicateBlockDraft,
WebhookCallBacks,
} from './blocks'
import { Coordinates } from '@/features/graph'
@ -22,7 +23,10 @@ export type GroupsActions = {
deleteGroup: (groupIndex: number) => void
}
const groupsActions = (setTypebot: SetTypebot): GroupsActions => ({
const groupsActions = (
setTypebot: SetTypebot,
{ onWebhookBlockCreated, onWebhookBlockDuplicated }: WebhookCallBacks
): GroupsActions => ({
createGroup: ({
id,
block,
@ -42,7 +46,13 @@ const groupsActions = (setTypebot: SetTypebot): GroupsActions => ({
blocks: [],
}
typebot.groups.push(newGroup)
createBlockDraft(typebot, block, newGroup.id, indices)
createBlockDraft(
typebot,
block,
newGroup.id,
indices,
onWebhookBlockCreated
)
})
),
updateGroup: (groupIndex: number, updates: Partial<Omit<Group, 'id'>>) =>
@ -61,7 +71,9 @@ const groupsActions = (setTypebot: SetTypebot): GroupsActions => ({
...group,
title: `${group.title} copy`,
id,
blocks: group.blocks.map(duplicateBlockDraft(id)),
blocks: group.blocks.map((block) =>
duplicateBlockDraft(id)(block, onWebhookBlockDuplicated)
),
graphCoordinates: {
x: group.graphCoordinates.x + 200,
y: group.graphCoordinates.y + 100,

View File

@ -159,7 +159,7 @@ export const TypebotButton = ({
<MenuItem onClick={handleUnpublishClick}>Unpublish</MenuItem>
)}
<MenuItem onClick={handleDuplicateClick}>Duplicate</MenuItem>
<MenuItem color="red" onClick={handleDeleteClick}>
<MenuItem color="red.400" onClick={handleDeleteClick}>
Delete
</MenuItem>
</MoreButton>

View File

@ -223,7 +223,12 @@ export const Graph = ({
const zoomOut = () => zoom({ delta: -zoomButtonsScaleBlock })
return (
<Flex ref={graphContainerRef} position="relative" {...props}>
<Flex
ref={graphContainerRef}
position="relative"
style={{ touchAction: 'none' }}
{...props}
>
<ZoomButtons onZoomInClick={zoomIn} onZoomOutClick={zoomOut} />
<Flex
flex="1"

View File

@ -16,7 +16,6 @@ import {
Block,
BlockOptions,
BlockWithOptions,
Webhook,
} from 'models'
import { useRef } from 'react'
import { DateInputSettingsBody } from '@/features/blocks/inputs/date'
@ -45,7 +44,6 @@ import { ScriptSettings } from '@/features/blocks/logic/script/components/Script
type Props = {
block: BlockWithOptions
webhook?: Webhook
onExpandClick: () => void
onBlockChange: (updates: Partial<Block>) => void
}
@ -93,7 +91,6 @@ export const BlockSettings = ({
onBlockChange,
}: {
block: BlockWithOptions
webhook?: Webhook
onBlockChange: (block: Partial<Block>) => void
}): JSX.Element => {
const handleOptionsChange = (options: BlockOptions) => {

View File

@ -195,6 +195,7 @@ const NonMemoizedDraggableGroupNode = ({
transform: `translate(${currentCoordinates?.x ?? 0}px, ${
currentCoordinates?.y ?? 0
}px)`,
touchAction: 'none',
}}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}

View File

@ -112,9 +112,7 @@ export const MembersList = () => {
{isDefined(seatsLimit) && (
<Heading fontSize="2xl">
Members{' '}
{seatsLimit === -1
? ''
: `(${currentMembersCount + invitations.length}/${seatsLimit})`}
{seatsLimit === -1 ? '' : `(${currentMembersCount}/${seatsLimit})`}
</Heading>
)}
{workspace?.id && canEdit && (

View File

@ -88,6 +88,9 @@ test('can manage members', async ({ page }) => {
await page.goto('/typebots')
await page.click('text=Settings & Members')
await page.click('text="Members"')
await expect(
page.getByRole('heading', { name: 'Members (1/5)' })
).toBeVisible()
await expect(page.locator('text="user@email.com"').nth(1)).toBeVisible()
await expect(page.locator('button >> text="Invite"')).toBeEnabled()
await page.fill(