2
0

feat(editor): Custom icon on typebot

This commit is contained in:
Baptiste Arnaud
2022-04-01 16:28:09 +02:00
parent 3585e63c48
commit 525887a32c
22 changed files with 2113 additions and 56 deletions

View File

@ -4,6 +4,7 @@ import {
Flex,
IconButton,
MenuItem,
Tag,
Text,
useDisclosure,
useToast,
@ -14,14 +15,15 @@ import { useRouter } from 'next/router'
import { isMobile } from 'services/utils'
import { MoreButton } from 'components/dashboard/FolderContent/MoreButton'
import { ConfirmModal } from 'components/modals/ConfirmModal'
import { GlobeIcon, GripIcon, ToolIcon } from 'assets/icons'
import { GripIcon } from 'assets/icons'
import { deleteTypebot, duplicateTypebot } from 'services/typebots'
import { Typebot } from 'models'
import { useTypebotDnd } from 'contexts/TypebotDndContext'
import { useDebounce } from 'use-debounce'
import { TypebotIcon } from 'components/shared/TypebotHeader/TypebotIcon'
type ChatbotCardProps = {
typebot: Pick<Typebot, 'id' | 'publishedTypebotId' | 'name'>
typebot: Pick<Typebot, 'id' | 'publishedTypebotId' | 'name' | 'icon'>
isReadOnly?: boolean
onTypebotDeleted?: () => void
onMouseDown?: (e: React.MouseEvent<HTMLButtonElement>) => void
@ -101,6 +103,18 @@ export const TypebotButton = ({
onMouseDown={onMouseDown}
cursor="pointer"
>
{typebot.publishedTypebotId && (
<Tag
colorScheme="blue"
variant="solid"
rounded="full"
pos="absolute"
top="27px"
size="sm"
>
Live
</Tag>
)}
{!isReadOnly && (
<>
<IconButton
@ -129,18 +143,12 @@ export const TypebotButton = ({
)}
<VStack spacing="4">
<Flex
boxSize="45px"
rounded="full"
justifyContent="center"
alignItems="center"
bgColor={typebot.publishedTypebotId ? 'blue.500' : 'gray.400'}
color="white"
fontSize={'4xl'}
>
{typebot.publishedTypebotId ? (
<GlobeIcon fontSize="20px" />
) : (
<ToolIcon fill="white" fontSize="20px" />
)}
{<TypebotIcon icon={typebot.icon} boxSize={'35px'} />}
</Flex>
<Text>{typebot.name}</Text>
</VStack>

View File

@ -1,31 +1,59 @@
import { useEffect, useState } from 'react'
import { Button, Flex, HStack, Stack, Text } from '@chakra-ui/react'
import { ChangeEvent, useEffect, useState } from 'react'
import {
Button,
Flex,
HStack,
Stack,
Text,
Input as ClassicInput,
SimpleGrid,
GridItem,
} from '@chakra-ui/react'
import { SearchContextManager } from '@giphy/react-components'
import { UploadButton } from '../buttons/UploadButton'
import { GiphySearch } from './GiphySearch'
import { useTypebot } from 'contexts/TypebotContext'
import { useDebounce } from 'use-debounce'
import { Input } from '../Textbox'
import { BaseEmoji, emojiIndex } from 'emoji-mart'
import { emojis } from './emojis'
type Props = {
url?: string
onSubmit: (url: string) => void
isEmojiEnabled?: boolean
isGiphyEnabled?: boolean
onSubmit: (url: string) => void
onClose?: () => void
}
export const ImageUploadContent = ({
url,
onSubmit,
isEmojiEnabled = false,
isGiphyEnabled = true,
onClose,
}: Props) => {
const [currentTab, setCurrentTab] = useState<'link' | 'upload' | 'giphy'>(
'upload'
)
const [currentTab, setCurrentTab] = useState<
'link' | 'upload' | 'giphy' | 'emoji'
>(isEmojiEnabled ? 'emoji' : 'upload')
const handleSubmit = (url: string) => {
onSubmit(url)
onClose && onClose()
}
const handleSubmit = (url: string) => onSubmit(url)
return (
<Stack>
<HStack>
{isEmojiEnabled && (
<Button
variant={currentTab === 'emoji' ? 'solid' : 'ghost'}
onClick={() => setCurrentTab('emoji')}
size="sm"
>
Emoji
</Button>
)}
<Button
variant={currentTab === 'upload' ? 'solid' : 'ghost'}
onClick={() => setCurrentTab('upload')}
@ -61,7 +89,7 @@ const BodyContent = ({
url,
onSubmit,
}: {
tab: 'upload' | 'link' | 'giphy'
tab: 'upload' | 'link' | 'giphy' | 'emoji'
url?: string
onSubmit: (url: string) => void
}) => {
@ -72,6 +100,8 @@ const BodyContent = ({
return <EmbedLinkContent initialUrl={url} onNewUrl={onSubmit} />
case 'giphy':
return <GiphyContent onNewUrl={onSubmit} />
case 'emoji':
return <EmojiContent onEmojiSelected={onSubmit} />
}
}
@ -114,6 +144,55 @@ const EmbedLinkContent = ({ initialUrl, onNewUrl }: ContentProps) => {
)
}
const EmojiContent = ({
onEmojiSelected,
}: {
onEmojiSelected: (emoji: string) => void
}) => {
const [searchValue, setSearchValue] = useState('')
const [filteredEmojis, setFilteredEmojis] = useState<string[]>(emojis)
const handleEmojiClick = (emoji: string) => () => onEmojiSelected(emoji)
const handleSearchChange = (e: ChangeEvent<HTMLInputElement>) => {
setSearchValue(e.target.value)
setFilteredEmojis(
emojiIndex.search(e.target.value)?.map((o) => (o as BaseEmoji).native) ??
emojis
)
}
return (
<Stack>
<ClassicInput
placeholder="Search..."
value={searchValue}
onChange={handleSearchChange}
/>
<SimpleGrid
maxH="350px"
overflowY="scroll"
overflowX="hidden"
spacing={0}
columns={7}
>
{filteredEmojis.map((emoji) => (
<GridItem key={emoji}>
<Button
onClick={handleEmojiClick(emoji)}
variant="ghost"
size="sm"
fontSize="xl"
>
{emoji}
</Button>
</GridItem>
))}
</SimpleGrid>
</Stack>
)
}
const GiphyContent = ({ onNewUrl }: ContentProps) => {
if (!process.env.NEXT_PUBLIC_GIPHY_API_KEY)
return <Text>NEXT_PUBLIC_GIPHY_API_KEY is missing in environment</Text>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,48 @@
import {
Popover,
Tooltip,
chakra,
PopoverTrigger,
PopoverContent,
} from '@chakra-ui/react'
import React from 'react'
import { ImageUploadContent } from '../ImageUploadContent'
import { TypebotIcon } from './TypebotIcon'
type Props = { icon?: string | null; onChangeIcon: (icon: string) => void }
export const EditableTypebotIcon = ({ icon, onChangeIcon }: Props) => {
return (
<Popover isLazy>
{({ onClose }) => (
<>
<Tooltip label="Change icon">
<chakra.span
cursor="pointer"
px="2"
rounded="md"
_hover={{ bgColor: 'gray.100' }}
transition="background-color 0.2s"
data-testid="editable-icon"
>
<PopoverTrigger>
<chakra.span>
<TypebotIcon icon={icon} emojiFontSize="2xl" />
</chakra.span>
</PopoverTrigger>
</chakra.span>
</Tooltip>
<PopoverContent p="2">
<ImageUploadContent
url={icon ?? ''}
onSubmit={onChangeIcon}
isGiphyEnabled={false}
isEmojiEnabled={true}
onClose={onClose}
/>
</PopoverContent>
</>
)}
</Popover>
)
}

View File

@ -24,7 +24,6 @@ export const EditableTypebotName = ({ name, onNewName }: EditableProps) => {
overflow="hidden"
display="flex"
alignItems="center"
minW="100px"
/>
<EditableInput />
</Editable>

View File

@ -16,6 +16,7 @@ import React from 'react'
import { isNotDefined } from 'utils'
import { PublishButton } from '../buttons/PublishButton'
import { CollaborationMenuButton } from './CollaborationMenuButton'
import { EditableTypebotIcon } from './EditableTypebotIcons'
import { EditableTypebotName } from './EditableTypebotName'
export const headerHeight = 56
@ -26,6 +27,7 @@ export const TypebotHeader = () => {
const {
typebot,
updateOnBothTypebots,
updateTypebot,
save,
undo,
redo,
@ -37,6 +39,8 @@ export const TypebotHeader = () => {
const handleNameSubmit = (name: string) => updateOnBothTypebots({ name })
const handleChangeIcon = (icon: string) => updateTypebot({ icon })
const handlePreviewClick = async () => {
save().then()
setRightPanel(RightPanel.PREVIEW)
@ -50,7 +54,7 @@ export const TypebotHeader = () => {
align="center"
pos="relative"
h={`${headerHeight}px`}
zIndex={2}
zIndex={100}
bgColor="white"
flexShrink={0}
>
@ -105,7 +109,7 @@ export const TypebotHeader = () => {
align="center"
spacing="6"
>
<HStack alignItems="center">
<HStack alignItems="center" spacing={4}>
<IconButton
as={NextChakraLink}
aria-label="Navigate back"
@ -118,12 +122,20 @@ export const TypebotHeader = () => {
: '/typebots'
}
/>
<HStack spacing={1}>
<EditableTypebotIcon
icon={typebot?.icon}
onChangeIcon={handleChangeIcon}
/>
{typebot?.name && (
<EditableTypebotName
name={typebot?.name}
onNewName={handleNameSubmit}
/>
)}
</HStack>
<HStack>
<Tooltip label="Undo">
<IconButton
display={['none', 'flex']}
@ -146,6 +158,7 @@ export const TypebotHeader = () => {
/>
</Tooltip>
</HStack>
</HStack>
{isSavingLoading && (
<HStack>
<Spinner speed="0.7s" size="sm" color="gray.400" />

View File

@ -0,0 +1,37 @@
import { ToolIcon } from 'assets/icons'
import React from 'react'
import { chakra, Image } from '@chakra-ui/react'
type Props = {
icon?: string | null
emojiFontSize?: string
boxSize?: string
}
export const TypebotIcon = ({
icon,
boxSize = '25px',
emojiFontSize,
}: Props) => {
return (
<>
{icon ? (
icon.startsWith('http') ? (
<Image
src={icon}
boxSize={boxSize}
objectFit={icon.endsWith('.svg') ? undefined : 'cover'}
alt="typebot icon"
rounded="md"
/>
) : (
<chakra.span role="img" fontSize={emojiFontSize}>
{icon}
</chakra.span>
)
) : (
<ToolIcon boxSize={boxSize} />
)}
</>
)
}

View File

@ -36,7 +36,7 @@ export const UploadButton = ({
id="file-input"
display="none"
onChange={handleInputChange}
accept=".jpg, .jpeg, .png"
accept=".jpg, .jpeg, .png, .svg"
/>
<Button
as="label"

View File

@ -52,6 +52,7 @@ type UpdateTypebotPayload = Partial<{
publicId: string
name: string
publishedTypebotId: string
icon: string
}>
export type SetTypebot = (
@ -167,10 +168,6 @@ export const TypebotContext = ({
new Date(typebot.updatedAt) >
new Date(currentTypebotRef.current.updatedAt)
) {
console.log(
new Date(typebot.updatedAt),
new Date(currentTypebotRef.current.updatedAt)
)
setLocalTypebot({ ...typebot })
}

View File

@ -45,6 +45,7 @@
"db": "*",
"deep-object-diff": "^1.1.7",
"dequal": "^2.0.2",
"emoji-mart": "^3.0.1",
"focus-visible": "^5.2.0",
"framer-motion": "^4",
"google-auth-library": "^7.14.0",
@ -87,6 +88,7 @@
"devDependencies": {
"@playwright/test": "^1.19.2",
"@types/canvas-confetti": "^1.4.2",
"@types/emoji-mart": "^3.0.9",
"@types/google-spreadsheet": "^3.1.5",
"@types/jsonwebtoken": "8.5.8",
"@types/micro-cors": "^0.1.2",

View File

@ -46,7 +46,7 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
folderId,
},
orderBy: { createdAt: 'desc' },
select: { name: true, publishedTypebotId: true, id: true },
select: { name: true, publishedTypebotId: true, id: true, icon: true },
})
return res.send({ typebots })
}

View File

@ -18,7 +18,14 @@ const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const sharedTypebots = await prisma.collaboratorsOnTypebots.findMany({
where: { userId: user.id },
include: {
typebot: { select: { name: true, publishedTypebotId: true, id: true } },
typebot: {
select: {
name: true,
publishedTypebotId: true,
id: true,
icon: true,
},
},
},
})
return res.send({

View File

@ -173,6 +173,7 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
createdAt: new Date().toISOString(),
publishedTypebotId: null,
customDomain: null,
icon: null,
variables: [{ id: 'var1', name: 'var1' }],
...partialTypebot,
edges: [

View File

@ -125,4 +125,28 @@ test.describe.parallel('Editor', () => {
await page.click('button[aria-label="Redo"]')
await expect(page.locator('text="Block #1"')).toBeHidden()
})
test('Rename and icon change should work', async ({ page }) => {
const typebotId = cuid()
await createTypebots([
{
id: typebotId,
name: 'My awesome typebot',
...parseDefaultBlockWithStep({
type: InputStepType.TEXT,
options: defaultTextInputOptions,
}),
},
])
await page.goto(`/typebots/${typebotId}/edit`)
await page.click('text="My awesome typebot"')
await page.fill('input[value="My awesome typebot"]', 'My superb typebot')
await page.click('[data-testid="editable-icon"]')
await page.fill('input[placeholder="Search..."]', 'love')
await page.click('text="😍"')
await page.goto(`/typebots`)
await expect(page.locator('text="😍"')).toBeVisible()
await expect(page.locator('text="My superb typebot"')).toBeVisible()
})
})

View File

@ -37,6 +37,7 @@ export const parsePublicTypebotToTypebot = (
publishedTypebotId: typebot.id,
folderId: existingTypebot.folderId,
ownerId: existingTypebot.ownerId,
icon: existingTypebot.icon,
})
export const createPublishedTypebot = async (typebot: PublicTypebot) =>

View File

@ -56,7 +56,7 @@ import { Plan, User } from 'db'
export type TypebotInDashboard = Pick<
Typebot,
'id' | 'name' | 'publishedTypebotId'
'id' | 'name' | 'publishedTypebotId' | 'icon'
>
export const useTypebots = ({
folderId,
@ -351,6 +351,7 @@ export const parseNewTypebot = ({
| 'publishedTypebotId'
| 'publicId'
| 'customDomain'
| 'icon'
> => {
const startBlockId = cuid()
const startStepId = cuid()

View File

@ -30,7 +30,12 @@ export const useSharedTypebots = ({
onError: (error: Error) => void
}) => {
const { data, error, mutate } = useSWR<
{ sharedTypebots: Pick<Typebot, 'name' | 'id' | 'publishedTypebotId'>[] },
{
sharedTypebots: Pick<
Typebot,
'name' | 'id' | 'publishedTypebotId' | 'icon'
>[]
},
Error
>(userId ? `/api/users/${userId}/sharedTypebots` : null, fetcher)
if (error) onError(error)

View File

@ -76,6 +76,7 @@ const parseTestTypebot = (partialTypebot: Partial<Typebot>): Typebot => ({
folderId: null,
name: 'My typebot',
ownerId: 'proUser',
icon: null,
theme: defaultTheme,
settings: defaultSettings,
publicId: partialTypebot.id + '-public',

View File

@ -14,7 +14,7 @@
"@prisma/client": "^3.10.0"
},
"scripts": {
"dx": "dotenv -e ../../apps/builder/.env.local prisma db push && yarn start:sutdio ",
"dx": "dotenv -e ../../apps/builder/.env.local prisma db push && yarn generate:schema && yarn start:sutdio ",
"build": "yarn generate:schema",
"start:sutdio": "dotenv -e ../../apps/builder/.env.local -v BROWSER=none prisma studio",
"generate:schema": "dotenv -e ../../apps/builder/.env.local prisma generate",

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Typebot" ADD COLUMN "icon" TEXT;

View File

@ -114,6 +114,7 @@ model Typebot {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
icon String?
name String
ownerId String
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)

View File

@ -4104,6 +4104,13 @@
dependencies:
cssnano "*"
"@types/emoji-mart@^3.0.9":
version "3.0.9"
resolved "https://registry.yarnpkg.com/@types/emoji-mart/-/emoji-mart-3.0.9.tgz#2f7ef5d9ec194f28029c46c81a5fc1e5b0efa73c"
integrity sha512-qdBo/2Y8MXaJ/2spKjDZocuq79GpnOhkwMHnK2GnVFa8WYFgfA+ei6sil3aeWQPCreOKIx9ogPpR5+7MaOqYAA==
dependencies:
"@types/react" "*"
"@types/eslint-scope@^3.7.3":
version "3.7.3"
resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.3.tgz#125b88504b61e3c8bc6f870882003253005c3224"
@ -7315,6 +7322,14 @@ emittery@^0.8.1:
resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.8.1.tgz#bb23cc86d03b30aa75a7f734819dee2e1ba70860"
integrity sha512-uDfvUjVrfGJJhymx/kz6prltenw1u7WrCg1oa94zYY8xxVpLLUu045LAT0dhDZdXG58/EpPL/5kA180fQ/qudg==
emoji-mart@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/emoji-mart/-/emoji-mart-3.0.1.tgz#9ce86706e02aea0506345f98464814a662ca54c6"
integrity sha512-sxpmMKxqLvcscu6mFn9ITHeZNkGzIvD0BSNFE/LJESPbCA8s1jM6bCDPjWbV31xHq7JXaxgpHxLB54RCbBZSlg==
dependencies:
"@babel/runtime" "^7.0.0"
prop-types "^15.6.0"
emoji-regex@^8.0.0:
version "8.0.0"
resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37"