Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(web): redesign icon picker and clarify autocomplete highlighting (#43007)

yyhd6c96ce1a517
diff --git a/packages/dify-ui/src/autocomplete/index.tsx b/packages/dify-ui/src/autocomplete/index.tsx
index acf9c316f4a..40f73b8b955 100644
--- a/packages/dify-ui/src/autocomplete/index.tsx
+++ b/packages/dify-ui/src/autocomplete/index.tsx
@@ -75,9 +75,8 @@ const autocompleteListClassName = [
const autocompleteItemClassName = [
'mx-1 flex min-h-8 cursor-pointer select-none items-center gap-2 rounded-lg px-2 py-1.5 text-text-secondary outline-hidden',
- 'hover:bg-state-base-hover-alt hover:text-text-primary',
'data-highlighted:bg-state-base-hover data-highlighted:text-text-primary',
- 'data-disabled:cursor-not-allowed data-disabled:opacity-30 data-disabled:hover:bg-transparent data-disabled:hover:text-text-secondary',
+ 'data-disabled:cursor-not-allowed data-disabled:opacity-30',
]
const autocompleteInputGroupVariants = cva(
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2fd73bc1f03..54b353d1363 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -536,9 +536,6 @@ catalogs:
foxact:
specifier: 0.3.12
version: 0.3.12
- frimousse:
- specifier: 0.3.0
- version: 0.3.0
fuse.js:
specifier: 7.5.0
version: 7.5.0
@@ -1530,9 +1527,6 @@ importers:
foxact:
specifier: 'catalog:'
- frimousse:
- specifier: 'catalog:'
- version: 0.3.0(@typescript/[email protected])([email protected])
fuse.js:
specifier: 'catalog:'
version: 7.5.0
@@ -6882,15 +6876,6 @@ packages:
react-dom:
optional: true
- resolution: {integrity: sha512-kO6LMoKY/cLAYEhXXtqLRaLIE6L/DagpFPrUZaLv3LsUa1/8Iza3HhwZcgN8eZ+weXnhv69eoclNUPohcCa/IQ==}
- peerDependencies:
- react: ^18 || ^19
- typescript: '>=5.1.0'
- peerDependenciesMeta:
- typescript:
- optional: true
-
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
@@ -14519,12 +14504,6 @@ snapshots:
react: 19.3.0
react-dom: 19.3.0([email protected])
- dependencies:
- react: 19.3.0
- optionalDependencies:
- typescript: '@typescript/[email protected]'
-
optional: true
@@ -17915,7 +17894,6 @@ time:
[email protected]: '2026-09-15T18:30:29.195Z'
[email protected]: '2020-06-08T07:27:28.474Z'
[email protected]: '2026-09-18T13:19:15.594Z'
- [email protected]: '2025-07-15T10:44:32.958Z'
[email protected]: '2026-07-13T17:23:36.705Z'
[email protected]: '2026-09-12T00:07:47.688Z'
[email protected]: '2025-03-05T11:30:29.166Z'
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index a4a0317bc7b..faa267c4584 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -191,7 +191,6 @@ catalog:
eventsource-parser: 4.1.1
fast-deep-equal: 3.1.3
foxact: 0.3.12
- frimousse: 0.3.0
fuse.js: 7.5.0
happy-dom: 20.14.5
hast-util-to-jsx-runtime: 2.3.6
diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
index 269ab557f14..46704aac95b 100644
--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx
@@ -1,35 +1,30 @@
'use client'
import type { AvatarProps } from '@langgenius/dify-ui/avatar'
-import type { Area } from 'react-easy-crop'
-import type { OnImageInput } from '@/app/components/base/app-icon-picker/ImageInput'
+import type { ImageIconInputValue } from '@/app/components/base/icon-picker/image-input'
import type { ImageFile } from '@/types/app'
import { Avatar } from '@langgenius/dify-ui/avatar'
import { Button } from '@langgenius/dify-ui/button'
-import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Separator } from '@langgenius/dify-ui/separator'
import { useMutation } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import ImageInput from '@/app/components/base/app-icon-picker/ImageInput'
+import { ImageIconInput } from '@/app/components/base/icon-picker/image-input'
import { useLocalFileUploader } from '@/app/components/base/image-uploader/hooks'
import { toast } from '@/app/notifications'
import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
import { consoleQuery } from '@/service/console'
import { createAvatarImageFile, createCroppedAvatarImage } from './avatar-image'
-type InputImageInfo =
- | { file: File }
- | { tempUrl: string; croppedAreaPixels: Area; fileName: string }
-
const AvatarWithEdit = (props: AvatarProps) => {
const { t } = useTranslation(['app', 'common'])
const { mutateAsync: updateProfile } = useMutation(
consoleQuery.account.profile.patch.mutationOptions(),
)
- const [inputImageInfo, setInputImageInfo] = useState<InputImageInfo>()
+ const [inputImageInfo, setInputImageInfo] = useState<ImageIconInputValue | null>(null)
const [isShowAvatarPicker, setIsShowAvatarPicker] = useState(false)
const [uploading, setUploading] = useState(false)
const [isShowDeleteConfirm, setIsShowDeleteConfirm] = useState(false)
@@ -37,26 +32,6 @@ const AvatarWithEdit = (props: AvatarProps) => {
const [onAvatarError, setOnAvatarError] = useState(false)
const canDeleteAvatar = !!props.avatar && !onAvatarError
- const handleImageInput: OnImageInput = useCallback(
- async (
- isCropped: boolean,
- fileOrTempUrl: string | File,
- croppedAreaPixels?: Area,
- fileName?: string,
- ) => {
- setInputImageInfo(
- isCropped
- ? {
- tempUrl: fileOrTempUrl as string,
- croppedAreaPixels: croppedAreaPixels!,
- fileName: fileName!,
- }
- : { file: fileOrTempUrl as File },
- )
- },
- [setInputImageInfo],
- )
-
const handleSaveAvatar = useCallback(
async (uploadedFileId: string) => {
try {
@@ -91,7 +66,7 @@ const AvatarWithEdit = (props: AvatarProps) => {
onUpload: (imageFile: ImageFile) => {
if (imageFile.progress === 100 && imageFile.fileId) {
setUploading(false)
- setInputImageInfo(undefined)
+ setInputImageInfo(null)
handleSaveAvatar(imageFile.fileId)
}
@@ -108,8 +83,8 @@ const AvatarWithEdit = (props: AvatarProps) => {
return
}
const blob = await createCroppedAvatarImage(
- inputImageInfo.tempUrl,
- inputImageInfo.croppedAreaPixels,
+ inputImageInfo.url,
+ inputImageInfo.area,
inputImageInfo.fileName,
)
const file = createAvatarImageFile(blob, inputImageInfo.fileName)
@@ -125,7 +100,10 @@ const AvatarWithEdit = (props: AvatarProps) => {
type="button"
aria-label={t(($) => $['avatar.editAction'], { ns: 'common' })}
className="group relative inline-flex overflow-hidden rounded-full border-none bg-transparent p-0 outline-hidden hover:opacity-90 focus-visible:ring-2 focus-visible:ring-components-input-border-hover active:opacity-80"
- onClick={() => setIsShowAvatarPicker(true)}
+ onClick={() => {
+ setInputImageInfo(null)
+ setIsShowAvatarPicker(true)
+ }}
>
<Avatar
{...props}
@@ -142,7 +120,10 @@ const AvatarWithEdit = (props: AvatarProps) => {
onOpenChange={(open) => !open && setIsShowAvatarPicker(false)}
>
<DialogContent className="w-90.5! p-0!">
- <ImageInput onImageInput={handleImageInput} cropShape="round" />
+ <DialogTitle className="sr-only">
+ {t(($) => $['avatar.editAction'], { ns: 'common' })}
+ </DialogTitle>
+ <ImageIconInput onChange={setInputImageInfo} cropShape="round" />
<Separator decorative className="m-0 h-[0.5px]" />
<div className="flex w-full items-center justify-center gap-2 p-3">
@@ -173,9 +154,9 @@ const AvatarWithEdit = (props: AvatarProps) => {
onOpenChange={(open) => !open && setIsShowDeleteConfirm(false)}
>
<DialogContent className="w-90.5! p-6!">
- <div className="mb-3 title-2xl-semi-bold text-text-primary">
+ <DialogTitle className="mb-3 title-2xl-semi-bold text-text-primary">
{t(($) => $['avatar.deleteTitle'], { ns: 'common' })}
- </div>
+ </DialogTitle>
<p className="mb-8 text-text-secondary">
{t(($) => $['avatar.deleteDescription'], { ns: 'common' })}
</p>
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx
index 88cab526160..f137813984c 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/AvatarWithEdit.spec.tsx
@@ -1,4 +1,4 @@
-import type { OnImageInput } from '@/app/components/base/app-icon-picker/ImageInput'
+import type { ImageIconInputProps } from '@/app/components/base/icon-picker/image-input'
import type { ImageFile } from '@/types/app'
import { QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
@@ -28,23 +28,23 @@ vi.mock('@/service/base', () => ({
request: mocks.request,
}))
-vi.mock('@/app/components/base/app-icon-picker/ImageInput', () => ({
- default: ({ onImageInput }: { onImageInput?: OnImageInput }) => (
+vi.mock('@/app/components/base/icon-picker/image-input', () => ({
+ ImageIconInput: ({ onChange }: ImageIconInputProps) => (
<div>
<button
type="button"
onClick={() =>
- onImageInput?.(
- true,
- 'blob:static-avatar',
- { x: 10, y: 20, width: 1000, height: 1000 },
- 'avatar.png',
- )
+ onChange?.({
+ type: 'crop',
+ url: 'blob:static-avatar',
+ area: { x: 10, y: 20, width: 1000, height: 1000 },
+ fileName: 'avatar.png',
+ })
}
>
Select static avatar
</button>
- <button type="button" onClick={() => onImageInput?.(false, mocks.animatedFile)}>
+ <button type="button" onClick={() => onChange?.({ type: 'file', file: mocks.animatedFile })}>
Select animated avatar
</button>
</div>
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/avatar-image.spec.ts b/web/app/account/(commonLayout)/account-page/__tests__/avatar-image.spec.ts
index 5b22a3c709f..385e9ff0959 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/avatar-image.spec.ts
+++ b/web/app/account/(commonLayout)/account-page/__tests__/avatar-image.spec.ts
@@ -1,14 +1,14 @@
import type { Area } from 'react-easy-crop'
-import { createImage } from '@/app/components/base/app-icon-picker/utils'
+import { createImage } from '@/app/components/base/icon-picker/image-crop'
import {
createAvatarImageFile,
createCroppedAvatarImage,
getBoundedAvatarImageSize,
} from '../avatar-image'
-vi.mock('@/app/components/base/app-icon-picker/utils', async (importOriginal) => {
+vi.mock('@/app/components/base/icon-picker/image-crop', async (importOriginal) => {
const actual =
- await importOriginal<typeof import('@/app/components/base/app-icon-picker/utils')>()
+ await importOriginal<typeof import('@/app/components/base/icon-picker/image-crop')>()
return {
...actual,
createImage: vi.fn(),
diff --git a/web/app/account/(commonLayout)/account-page/avatar-image.ts b/web/app/account/(commonLayout)/account-page/avatar-image.ts
index 8d5b66b1d72..f0c6fbe5f7a 100644
--- a/web/app/account/(commonLayout)/account-page/avatar-image.ts
+++ b/web/app/account/(commonLayout)/account-page/avatar-image.ts
@@ -1,5 +1,5 @@
import type { Area } from 'react-easy-crop'
-import { createImage, getMimeType } from '@/app/components/base/app-icon-picker/utils'
+import { createImage, getMimeType } from '@/app/components/base/icon-picker/image-crop'
const AVATAR_IMAGE_MAX_SIZE = 256
const AVATAR_IMAGE_QUALITY = 0.85
diff --git a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
index bb3bcffa0f0..31974460474 100644
--- a/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
+++ b/web/app/components/app/configuration/tools/__tests__/external-data-tool-modal.spec.tsx
@@ -1,5 +1,5 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { mockEmojiData } from '@/test/emoji-picker'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { mockEmojiData, renderWithEmoji as render } from '@/test/emoji-picker'
import ExternalDataToolModal from '../external-data-tool-modal'
const mockToastError = vi.fn()
@@ -141,7 +141,7 @@ describe('ExternalDataToolModal', () => {
const emojiButton = await screen.findByRole('gridcell', { name: 'Grinning face' })
expect(emojiButton).toBeTruthy()
fireEvent.click(emojiButton!)
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
fireEvent.click(screen.getByText(/(?:^|\.)operation\.save(?=$|:)/))
diff --git a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
index 019eb821e26..be5238000c9 100644
--- a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
+++ b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx
@@ -17,8 +17,8 @@ import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { toast } from '@/app/components/app/configuration/toast'
import AppIcon from '@/app/components/base/app-icon'
-import EmojiPicker from '@/app/components/base/emoji-picker'
import FormGeneration from '@/app/components/base/features/new-feature-panel/moderation/form-generation'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { ApiBasedExtensionSelector } from '@/app/components/header/account-setting/api-based-extension-page/selector'
import { useDocLink } from '@/context/i18n'
import { useCodeBasedExtensions } from '@/service/use-common'
@@ -218,15 +218,25 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
- {showEmojiPicker && (
- <EmojiPicker
- open={showEmojiPicker}
- onOpenChange={setShowEmojiPicker}
- onSelect={(icon, icon_background) => {
- handleValueChange({ icon, icon_background })
- }}
- />
- )}
+ <IconPickerDialog
+ enableImageUpload={false}
+ defaultValue={
+ localeData.icon
+ ? {
+ type: 'emoji',
+ icon: localeData.icon,
+ background: localeData.icon_background,
+ }
+ : undefined
+ }
+ open={showEmojiPicker}
+ onOpenChange={setShowEmojiPicker}
+ onConfirm={(value) => {
+ if (value.type !== 'emoji') return
+ const { icon, background: icon_background } = value
+ handleValueChange({ icon, icon_background })
+ }}
+ />
</DialogContent>
</Dialog>
)
diff --git a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
index b87c1cfceff..f8a2beb3089 100644
--- a/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/create-app-modal/__tests__/index.spec.tsx
@@ -42,6 +42,7 @@ vi.mock('@/service/console', async (importOriginal) => {
consoleQuery: {
...actual.consoleQuery,
features: actual.consoleQuery.features,
+ files: actual.consoleQuery.files,
account: {
profile: {
get: {
@@ -259,7 +260,7 @@ describe('CreateAppModal', () => {
await waitFor(() => {
expect(screen.getByPlaceholderText('app.iconPicker.search')).toBeInTheDocument()
})
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
await waitFor(() => {
expect(screen.queryByPlaceholderText('app.iconPicker.search')).not.toBeInTheDocument()
diff --git a/web/app/components/app/create-app-modal/index.tsx b/web/app/components/app/create-app-modal/index.tsx
index 62905ae78d3..9df0a884635 100644
--- a/web/app/components/app/create-app-modal/index.tsx
+++ b/web/app/components/app/create-app-modal/index.tsx
@@ -1,7 +1,7 @@
'use client'
import type { Hotkey } from '@tanstack/react-hotkeys'
-import type { AppIconSelection } from '../../base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import { zPostAppsBody } from '@dify/contracts/api/console/apps/zod.gen'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -16,6 +16,7 @@ import { useAtomValue } from 'jotai'
import { useCallback, useId, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { toast } from '@/app/notifications'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
@@ -29,7 +30,6 @@ import { getRedirection } from '@/utils/app-redirection'
import { trackCreateApp } from '@/utils/create-app-tracking'
import { hasPermission } from '@/utils/permission'
import { basePath } from '@/utils/var'
-import AppIconPicker from '../../base/app-icon-picker'
import { CreateAppDialogShell } from '../create-app-dialog-shell'
type CreateAppProps = {
@@ -55,12 +55,12 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
const contentRef = useRef<HTMLDivElement>(null)
const [appMode, setAppMode] = useState<AppModeEnum>(defaultAppMode || AppModeEnum.ADVANCED_CHAT)
- const [appIcon, setAppIcon] = useState<AppIconSelection>({
+ const [appIcon, setAppIcon] = useState<IconPickerValue>({
type: 'emoji',
icon: '🤖',
background: '#FFEAD5',
})
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const [name, setName] = useState('')
const [description, setDescription] = useState('')
const [isAppTypeExpanded, setIsAppTypeExpanded] = useState(() =>
@@ -178,7 +178,7 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
},
{
target: contentRef,
- enabled: !createDisabled && !isCreating && !showAppIconPicker,
+ enabled: !createDisabled && !isCreating && !showIconPicker,
ignoreInputs: false,
preventDefault: false,
stopPropagation: false,
@@ -332,23 +332,17 @@ function CreateApp({ onClose, onCreateFromTemplate, defaultAppMode }: CreateAppP
size="xxl"
className="cursor-pointer rounded-2xl"
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
+ }}
+ />
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={(payload) => {
+ setAppIcon(payload)
}}
/>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={(payload) => {
- setAppIcon(payload)
- }}
- />
- )}
</div>
<div>
<div className="mb-1 flex h-6 items-center">
diff --git a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx
index 081afa0339e..33c3b7a16f9 100644
--- a/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/duplicate-modal/__tests__/index.spec.tsx
@@ -28,14 +28,17 @@ vi.mock('@/app/components/billing/apps-full-in-dialog', () => ({
default: () => <div>apps-full</div>,
}))
-vi.mock('@/app/components/base/app-icon-picker', () => ({
- default: ({
+vi.mock('@/app/components/base/icon-picker', () => ({
+ IconPickerDialog: ({
+ open,
onOpenChange,
- onSelect,
+ onConfirm,
}: {
+ open: boolean
onOpenChange: (open: boolean) => void
- onSelect: (payload: { type: 'emoji'; icon: string; background: string }) => void
+ onConfirm: (payload: { type: 'emoji'; icon: string; background: string }) => void
}) => {
+ if (!open) return null
let selectedBackground = '#FFEAD5'
return (
<div>
@@ -53,7 +56,7 @@ vi.mock('@/app/components/base/app-icon-picker', () => ({
<button
type="button"
onClick={() => {
- onSelect({ type: 'emoji', icon: '🤖', background: selectedBackground })
+ onConfirm({ type: 'emoji', icon: '🤖', background: selectedBackground })
onOpenChange(false)
}}
>
diff --git a/web/app/components/app/duplicate-modal/index.tsx b/web/app/components/app/duplicate-modal/index.tsx
index 9bce608f4f1..f5c9bd9800d 100644
--- a/web/app/components/app/duplicate-modal/index.tsx
+++ b/web/app/components/app/duplicate-modal/index.tsx
@@ -11,11 +11,11 @@ import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { toast } from '@/app/notifications'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
-import AppIconPicker from '../../base/app-icon-picker'
export type DuplicateAppModalProps = {
appName: string
@@ -47,10 +47,10 @@ const DuplicateAppModal = ({
const [name, setName] = React.useState(appName)
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const [appIcon, setAppIcon] = useState(
icon_type === 'image'
- ? { type: 'image' as const, url: icon_url, fileId: icon }
+ ? { type: 'image' as const, url: icon_url ?? '', fileId: icon }
: { type: 'emoji' as const, icon, background: icon_background },
)
@@ -121,7 +121,7 @@ const DuplicateAppModal = ({
type="button"
aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${t(($) => $['appCustomize.subTitle'], { ns: 'explore' })}`}
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}}
className="shrink-0 cursor-pointer rounded-[10px] focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
@@ -160,20 +160,14 @@ const DuplicateAppModal = ({
</form>
</DialogContent>
</Dialog>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={(payload) => {
- setAppIcon(payload)
- }}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={(payload) => {
+ setAppIcon(payload)
+ }}
+ />
</>
)
}
diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsx
index 349c038b00d..f313bc35fa0 100644
--- a/web/app/components/app/overview/settings/index.tsx
+++ b/web/app/components/app/overview/settings/index.tsx
@@ -1,7 +1,7 @@
'use client'
import type { FC } from 'react'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { AppIconType, Language, SiteConfig } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -36,7 +36,7 @@ import * as React from 'react'
import { useCallback, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { PremiumBadgeButton } from '@/app/components/base/premium-badge'
import {
pricingQueryParamName,
@@ -79,7 +79,7 @@ type SettingsSiteInfo = Pick<
>
type SettingsAppIconSelection =
- | AppIconSelection
+ | IconPickerValue
| {
type: 'link'
icon: string
@@ -202,7 +202,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({
const [saveLoading, setSaveLoading] = useState(false)
const { t } = useTranslation(['app', 'appOverview', 'billing', 'common'])
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const [appIcon, setAppIcon] = useState<SettingsAppIconSelection>(nextAppIcon)
const [previousIsShow, setPreviousIsShow] = useState(isShow)
const [previousSettingsResetKey, setPreviousSettingsResetKey] = useState(settingsResetKey)
@@ -444,7 +444,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({
<AppIcon
size="xxl"
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}}
className="mt-2 cursor-pointer"
iconType={appIcon.type === 'link' ? 'image' : appIcon.type}
@@ -803,15 +803,11 @@ const SettingsModal: FC<ISettingsModalProps> = ({
</Form>
</DialogContent>
</Dialog>
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={setAppIcon}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon.type === 'link' ? undefined : appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={setAppIcon}
/>
</>
)
diff --git a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
index 85d9ca7cb94..72939daaa33 100644
--- a/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/switch-app-modal/__tests__/index.spec.tsx
@@ -23,18 +23,22 @@ vi.mock('@/next/navigation', () => ({
const mockConvertToWorkflow = vi.hoisted(() => vi.fn())
const mockDeleteOriginalApp = vi.hoisted(() => vi.fn())
-const mockMutationState = vi.hoisted(() => ({ hookIndex: 0 }))
vi.mock('@tanstack/react-query', async (importOriginal) => {
const actual = await importOriginal<typeof import('@tanstack/react-query')>()
return {
...actual,
- useMutation: () => {
- const mutationIndex = mockMutationState.hookIndex++ % 2
- return {
- mutateAsync: mutationIndex === 0 ? mockConvertToWorkflow : mockDeleteOriginalApp,
- }
+ useMutation: (options: Parameters<typeof actual.useMutation>[0]) => {
+ const key = JSON.stringify(options.mutationKey)
+ return actual.useMutation({
+ ...options,
+ ...(key.includes('convertToWorkflow')
+ ? { mutationFn: (input: unknown) => mockConvertToWorkflow(input) }
+ : key.includes('delete')
+ ? { mutationFn: (input: unknown) => mockDeleteOriginalApp(input) }
+ : {}),
+ })
},
}
})
@@ -146,7 +150,6 @@ function render(ui: ReactElement) {
describe('SwitchAppModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockMutationState.hookIndex = 0
mockConvertToWorkflow.mockReset()
mockDeleteOriginalApp.mockReset()
// Spy on setAppDetail
@@ -299,7 +302,7 @@ describe('SwitchAppModal', () => {
expect(screen.getByPlaceholderText('app.iconPicker.search')).toBeInTheDocument()
})
- await user.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ await user.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
await user.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
await waitFor(() => {
expect(screen.queryByPlaceholderText('app.iconPicker.search')).not.toBeInTheDocument()
diff --git a/web/app/components/app/switch-app-modal/index.tsx b/web/app/components/app/switch-app-modal/index.tsx
index 8ec6218b0c1..d776d5186fd 100644
--- a/web/app/components/app/switch-app-modal/index.tsx
+++ b/web/app/components/app/switch-app-modal/index.tsx
@@ -21,6 +21,7 @@ import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
import AppIcon from '@/app/components/base/app-icon'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { toast } from '@/app/notifications'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
@@ -28,7 +29,6 @@ import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { AppModeEnum } from '@/types/app'
import { getRedirection } from '@/utils/app-redirection'
-import AppIconPicker from '../../base/app-icon-picker'
type SwitchAppModalProps = {
show: boolean
@@ -63,11 +63,11 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc
appQuota.limit > 0 &&
appQuota.size >= appQuota.limit
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const appIconType = zIconType.safeParse(appDetail.icon_type).data
const [appIcon, setAppIcon] = useState(
appIconType === 'image'
- ? { type: 'image' as const, url: appDetail.icon_url, fileId: appDetail.icon ?? '' }
+ ? { type: 'image' as const, url: appDetail.icon_url ?? '', fileId: appDetail.icon ?? '' }
: {
type: 'emoji' as const,
icon: appDetail.icon ?? '',
@@ -172,7 +172,7 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc
<AppIcon
size="large"
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}}
className="cursor-pointer"
iconType={appIcon.type}
@@ -188,20 +188,14 @@ const SwitchAppModal = ({ show, appDetail, inAppDetail = false, onClose }: Switc
className="h-10 grow"
/>
</div>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={(payload) => {
- setAppIcon(payload)
- }}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={(payload) => {
+ setAppIcon(payload)
+ }}
+ />
</div>
{isAppsFull && <AppsFull loc="app-switch" />}
<div className="flex items-center justify-between pt-6">
diff --git a/web/app/components/base/app-icon-picker/ImageInput.tsx b/web/app/components/base/app-icon-picker/ImageInput.tsx
deleted file mode 100644
index 6506645e605..00000000000
--- a/web/app/components/base/app-icon-picker/ImageInput.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-'use client'
-
-import type { ChangeEvent, FC } from 'react'
-import type { Area, CropperProps } from 'react-easy-crop'
-import { cn } from '@langgenius/dify-ui/cn'
-import { useEffect, useRef, useState } from 'react'
-import Cropper from 'react-easy-crop'
-import { useTranslation } from 'react-i18next'
-import { ALLOW_FILE_EXTENSIONS } from '@/types/app'
-import { useDraggableUploader } from './hooks'
-import { checkIsAnimatedImage } from './utils'
-
-export type OnImageInput = {
- (isCropped: true, tempUrl: string, croppedAreaPixels: Area, fileName: string): void
- (isCropped: false, file: File): void
-}
-
-type UploaderProps = {
- className?: string
- cropShape?: CropperProps['cropShape']
- onImageInput?: OnImageInput
-}
-
-const ImageInput: FC<UploaderProps> = ({ className, cropShape, onImageInput }) => {
- const { t } = useTranslation(['common'])
- const [inputImage, setInputImage] = useState<{ file: File; url: string }>()
- const [isAnimatedImage, setIsAnimatedImage] = useState<boolean>(false)
- useEffect(() => {
- return () => {
- if (inputImage) URL.revokeObjectURL(inputImage.url)
- }
- }, [inputImage])
-
- const [crop, setCrop] = useState({ x: 0, y: 0 })
- const [zoom, setZoom] = useState(1)
-
- const onCropComplete = async (_: Area, croppedAreaPixels: Area) => {
- /* v8 ignore next -- unreachable guard when Cropper is rendered @preserve */
- if (!inputImage) return
- onImageInput?.(true, inputImage.url, croppedAreaPixels, inputImage.file.name)
- }
-
- const handleLocalFileInput = (e: ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0]
- if (file) {
- setInputImage({ file, url: URL.createObjectURL(file) })
- checkIsAnimatedImage(file).then((isAnimatedImage) => {
- setIsAnimatedImage(!!isAnimatedImage)
- if (isAnimatedImage) onImageInput?.(false, file)
- })
- }
- }
-
- const { isDragActive, handleDragEnter, handleDragOver, handleDragLeave, handleDrop } =
- useDraggableUploader((file: File) => setInputImage({ file, url: URL.createObjectURL(file) }))
-
- const inputRef = useRef<HTMLInputElement>(null)
-
- const handleShowImage = () => {
- if (isAnimatedImage) {
- return (
- <img
- src={inputImage?.url}
- alt=""
- className="h-full w-full object-contain"
- data-testid="animated-image"
- />
- )
- }
-
- return (
- <Cropper
- image={inputImage?.url}
- crop={crop}
- zoom={zoom}
- aspect={1}
- cropShape={cropShape}
- onCropChange={setCrop}
- onCropComplete={onCropComplete}
- onZoomChange={setZoom}
- />
- )
- }
-
- return (
- <div className={cn(className, 'w-full p-3')}>
- <div
- className={cn(
- 'relative flex h-60 flex-col items-center justify-center gap-2 overflow-hidden rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-4 py-3 text-center text-text-secondary',
- isDragActive &&
- 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
- )}
- onDragEnter={handleDragEnter}
- onDragOver={handleDragOver}
- onDragLeave={handleDragLeave}
- onDrop={handleDrop}
- >
- {!inputImage ? (
- <>
- <span
- className="pointer-events-none i-ri-image-add-line size-5 text-text-tertiary"
- aria-hidden="true"
- />
- <div className="system-sm-medium">
- <span className="pointer-events-none">
- {t(($) => $['imageInput.dropImageHere'], { ns: 'common' })}
- &nbsp;
- </span>
- <button
- type="button"
- className="rounded-sm text-text-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid"
- onClick={() => inputRef.current?.click()}
- >
- {t(($) => $['imageInput.browse'], { ns: 'common' })}
- </button>
- <input
- ref={inputRef}
- type="file"
- className="hidden"
- onClick={(e) => ((e.target as HTMLInputElement).value = '')}
- accept={ALLOW_FILE_EXTENSIONS.map((ext) => `.${ext}`).join(',')}
- onChange={handleLocalFileInput}
- data-testid="image-input"
- />
- </div>
- <div className="pointer-events-none system-xs-regular text-text-tertiary">
- {t(($) => $['imageInput.supportedFormats'], { ns: 'common' })}
- </div>
- </>
- ) : (
- handleShowImage()
- )}
- </div>
- </div>
- )
-}
-
-export default ImageInput
diff --git a/web/app/components/base/app-icon-picker/__tests__/hooks.spec.tsx b/web/app/components/base/app-icon-picker/__tests__/hooks.spec.tsx
deleted file mode 100644
index ca9e22f4795..00000000000
--- a/web/app/components/base/app-icon-picker/__tests__/hooks.spec.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { act, renderHook } from '@testing-library/react'
-import { useDraggableUploader } from '../hooks'
-
-type MockDragEventOverrides = {
- dataTransfer?: { files: File[] }
-}
-
-const createDragEvent = (overrides: MockDragEventOverrides = {}): React.DragEvent<HTMLDivElement> =>
- ({
- preventDefault: vi.fn(),
- stopPropagation: vi.fn(),
- dataTransfer: { files: [] as unknown as FileList },
- ...overrides,
- }) as unknown as React.DragEvent<HTMLDivElement>
-
-describe('useDraggableUploader', () => {
- let setImageFn: ReturnType<typeof vi.fn<(file: File) => void>>
-
- beforeEach(() => {
- vi.clearAllMocks()
- setImageFn = vi.fn<(file: File) => void>()
- })
-
- describe('Rendering', () => {
- it('should return all expected handler functions and isDragActive state', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
-
- expect(result.current.handleDragEnter).toBeInstanceOf(Function)
- expect(result.current.handleDragOver).toBeInstanceOf(Function)
- expect(result.current.handleDragLeave).toBeInstanceOf(Function)
- expect(result.current.handleDrop).toBeInstanceOf(Function)
- expect(result.current.isDragActive).toBe(false)
- })
- })
-
- describe('Drag Events', () => {
- it('should set isDragActive to true on drag enter', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
- const event = createDragEvent()
-
- act(() => {
- result.current.handleDragEnter(event)
- })
-
- expect(result.current.isDragActive).toBe(true)
- expect(event.preventDefault).toHaveBeenCalled()
- expect(event.stopPropagation).toHaveBeenCalled()
- })
-
- it('should call preventDefault and stopPropagation on drag over without changing isDragActive', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
- const event = createDragEvent()
-
- act(() => {
- result.current.handleDragOver(event)
- })
-
- expect(result.current.isDragActive).toBe(false)
- expect(event.preventDefault).toHaveBeenCalled()
- expect(event.stopPropagation).toHaveBeenCalled()
- })
-
- it('should set isDragActive to false on drag leave', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
- const enterEvent = createDragEvent()
- const leaveEvent = createDragEvent()
-
- act(() => {
- result.current.handleDragEnter(enterEvent)
- })
- expect(result.current.isDragActive).toBe(true)
-
- act(() => {
- result.current.handleDragLeave(leaveEvent)
- })
-
- expect(result.current.isDragActive).toBe(false)
- expect(leaveEvent.preventDefault).toHaveBeenCalled()
- expect(leaveEvent.stopPropagation).toHaveBeenCalled()
- })
- })
-
- describe('Drop', () => {
- it('should call setImageFn with the dropped file and set isDragActive to false', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
- const file = new File(['test'], 'image.png', { type: 'image/png' })
- const event = createDragEvent({
- dataTransfer: { files: [file] },
- })
-
- // First set isDragActive to true
- act(() => {
- result.current.handleDragEnter(createDragEvent())
- })
- expect(result.current.isDragActive).toBe(true)
-
- act(() => {
- result.current.handleDrop(event)
- })
-
- expect(result.current.isDragActive).toBe(false)
- expect(setImageFn).toHaveBeenCalledWith(file)
- expect(event.preventDefault).toHaveBeenCalled()
- expect(event.stopPropagation).toHaveBeenCalled()
- })
-
- it('should not call setImageFn when no file is dropped', () => {
- const { result } = renderHook(() => useDraggableUploader(setImageFn))
- const event = createDragEvent({
- dataTransfer: { files: [] },
- })
-
- act(() => {
- result.current.handleDrop(event)
- })
-
- expect(setImageFn).not.toHaveBeenCalled()
- expect(result.current.isDragActive).toBe(false)
- })
- })
-})
diff --git a/web/app/components/base/app-icon-picker/__tests__/index.spec.tsx b/web/app/components/base/app-icon-picker/__tests__/index.spec.tsx
deleted file mode 100644
index 9afb29abfe2..00000000000
--- a/web/app/components/base/app-icon-picker/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,429 +0,0 @@
-import type { ComponentProps } from 'react'
-import type { Area } from 'react-easy-crop'
-import type { ImageFile } from '@/types/app'
-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { mockEmojiData } from '@/test/emoji-picker'
-import { TransferMethod } from '@/types/app'
-import AppIconPicker from '../index'
-import 'vitest-canvas-mock'
-
-type LocalFileUploaderOptions = {
- disabled?: boolean
- limit?: number
- onUpload: (imageFile: ImageFile) => void
-}
-
-class MockLoadedImage {
- width = 320
- height = 160
- private listeners: Record<string, EventListener[]> = {}
-
- addEventListener(type: string, listener: EventListenerOrEventListenerObject) {
- const eventListener =
- typeof listener === 'function' ? listener : listener.handleEvent.bind(listener)
- if (!this.listeners[type]) this.listeners[type] = []
- this.listeners[type].push(eventListener)
- }
-
- setAttribute(_name: string, _value: string) {}
-
- set src(_value: string) {
- queueMicrotask(() => {
- for (const listener of this.listeners.load ?? []) listener(new Event('load'))
- })
- }
-
- get src() {
- return ''
- }
-}
-
-const createImageFile = (overrides: Partial<ImageFile> = {}): ImageFile => ({
- type: TransferMethod.local_file,
- _id: 'test-image-id',
- fileId: 'uploaded-image-id',
- progress: 100,
- url: 'https://example.com/uploaded.png',
- ...overrides,
-})
-
-const createCanvasContextMock = (): CanvasRenderingContext2D =>
- ({
- translate: vi.fn(),
- rotate: vi.fn(),
- scale: vi.fn(),
- drawImage: vi.fn(),
- }) as unknown as CanvasRenderingContext2D
-
-const createCanvasElementMock = (
- context: CanvasRenderingContext2D | null,
- blob: Blob | null = new Blob(['ok'], { type: 'image/png' }),
-) =>
- ({
- width: 0,
- height: 0,
- getContext: vi.fn(() => context),
- toBlob: vi.fn((callback: BlobCallback) => callback(blob)),
- }) as unknown as HTMLCanvasElement
-
-const mocks = vi.hoisted(() => ({
- disableUpload: false,
- uploadResult: null as ImageFile | null,
- onUpload: null as ((imageFile: ImageFile) => void) | null,
- handleLocalFileUpload: vi.fn<(file: File) => void>(),
-}))
-
-vi.mock('@/config', () => ({
- get DISABLE_UPLOAD_IMAGE_AS_ICON() {
- return mocks.disableUpload
- },
-}))
-
-vi.mock('react-easy-crop', () => ({
- default: ({
- onCropComplete,
- }: {
- onCropComplete: (_area: Area, croppedAreaPixels: Area) => void
- }) => (
- <div data-testid="mock-cropper">
- <button
- type="button"
- data-testid="trigger-crop"
- onClick={() =>
- onCropComplete(
- { x: 0, y: 0, width: 100, height: 100 },
- { x: 0, y: 0, width: 100, height: 100 },
- )
- }
- >
- Trigger Crop
- </button>
- </div>
- ),
-}))
-
-vi.mock('../../image-uploader/hooks', () => ({
- useLocalFileUploader: (options: LocalFileUploaderOptions) => {
- mocks.onUpload = options.onUpload
- return { handleLocalFileUpload: mocks.handleLocalFileUpload }
- },
-}))
-
-describe('AppIconPicker', () => {
- const originalCreateElement = document.createElement.bind(document)
- const originalCreateObjectURL = globalThis.URL.createObjectURL
- const originalRevokeObjectURL = globalThis.URL.revokeObjectURL
- let originalImage: typeof Image
-
- const mockCanvasCreation = (canvases: HTMLCanvasElement[]) => {
- vi.spyOn(document, 'createElement').mockImplementation(
- (...args: Parameters<Document['createElement']>) => {
- if (args[0] === 'canvas') {
- const nextCanvas = canvases.shift()
- if (!nextCanvas) throw new Error('Unexpected canvas creation')
- return nextCanvas as ReturnType<Document['createElement']>
- }
- return originalCreateElement(...args)
- },
- )
- }
-
- const renderPicker = (props: Partial<ComponentProps<typeof AppIconPicker>> = {}) => {
- const onSelect = vi.fn()
- const onOpenChange = vi.fn()
-
- const { container } = render(
- <AppIconPicker open onOpenChange={onOpenChange} onSelect={onSelect} {...props} />,
- )
-
- return { onSelect, onOpenChange, container }
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- mocks.disableUpload = false
- mocks.uploadResult = createImageFile()
- mocks.onUpload = null
- mocks.handleLocalFileUpload.mockImplementation(() => {
- if (mocks.uploadResult) mocks.onUpload?.(mocks.uploadResult)
- })
-
- originalImage = globalThis.Image
- globalThis.URL.createObjectURL = vi.fn(() => 'blob:mock-url')
- globalThis.URL.revokeObjectURL = vi.fn()
- })
-
- afterEach(() => {
- globalThis.Image = originalImage
- globalThis.URL.createObjectURL = originalCreateObjectURL
- globalThis.URL.revokeObjectURL = originalRevokeObjectURL
- })
-
- describe('Rendering', () => {
- it('should render emoji and image tabs when upload is enabled', async () => {
- renderPicker()
-
- expect(screen.getByRole('dialog', { name: /emoji/i })).toBeInTheDocument()
- expect(await screen.findByRole('radio', { name: /emoji/i }))!.toBeInTheDocument()
- expect(screen.getByRole('radio', { name: /image/i }))!.toBeInTheDocument()
- expect(screen.getByText(/tryYourLuck/i))!.toBeInTheDocument()
- expect(screen.getByText(/ok/i))!.toBeInTheDocument()
- })
-
- it('should hide the image tab when upload is disabled', () => {
- mocks.disableUpload = true
- renderPicker()
-
- expect(screen.queryByText(/image/i)).not.toBeInTheDocument()
- expect(screen.getByPlaceholderText(/search/i))!.toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('records only confirmed selections and restores them when reopened', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
- const onOpenChange = vi.fn()
- const { rerender } = render(
- <AppIconPicker open onOpenChange={onOpenChange} onSelect={onSelect} />,
- )
- await user.click(
- within(screen.getByRole('region', { name: 'app.iconPicker.recommend' })).getByRole(
- 'button',
- { name: '😆' },
- ),
- )
- expect(onSelect).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
- expect(onSelect).toHaveBeenCalledWith({ type: 'emoji', icon: '😆', background: '#FEF3F2' })
- rerender(<AppIconPicker open={false} onOpenChange={onOpenChange} onSelect={onSelect} />)
- rerender(<AppIconPicker open onOpenChange={onOpenChange} onSelect={onSelect} />)
- const recent = await screen.findByRole('region', { name: 'app.iconPicker.recent' })
- await user.click(within(recent).getByRole('button', { name: '😆' }))
- await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
- expect(onSelect).toHaveBeenCalledTimes(2)
- })
-
- it('randomizes both emoji and background before confirmation', async () => {
- vi.spyOn(Math, 'random').mockReturnValue(0)
- const user = userEvent.setup()
- const { onSelect } = renderPicker({ initialEmoji: { icon: '😃', background: '#FEF3F2' } })
- await user.click(screen.getByRole('button', { name: 'app.iconPicker.tryYourLuck' }))
- expect(screen.getByRole('button', { name: '#FFF1F3' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
- expect(onSelect).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
- expect(onSelect).toHaveBeenCalledWith({ type: 'emoji', icon: '😆', background: '#FFF1F3' })
- })
-
- it('shows styles after selecting an emoji and confirms the selected background', async () => {
- const user = userEvent.setup()
- const { onSelect } = renderPicker()
- expect(
- screen.queryByRole('region', { name: 'app.iconPicker.chooseStyle' }),
- ).not.toBeInTheDocument()
- await user.click(
- within(screen.getByRole('region', { name: 'app.iconPicker.recommend' })).getByRole(
- 'button',
- { name: '😃' },
- ),
- )
- const style = screen.getByRole('button', { name: '#F0F2F5' })
- await user.click(style)
- expect(style).toHaveAttribute('aria-pressed', 'true')
- expect(screen.getByRole('gridcell', { name: 'Grinning face with big eyes' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
- expect(onSelect).not.toHaveBeenCalled()
- await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
- expect(onSelect).toHaveBeenCalledWith({ type: 'emoji', icon: '😃', background: '#F0F2F5' })
- })
-
- it('should switch between emoji and image tabs', async () => {
- renderPicker()
-
- await userEvent.click(screen.getByText(/image/i))
- expect(screen.getByText(/drop.*here/i))!.toBeInTheDocument()
-
- await userEvent.click(screen.getByRole('radio', { name: /emoji/i }))
- expect(screen.getByPlaceholderText(/search/i))!.toBeInTheDocument()
- })
-
- it('should call onSelect with emoji data after emoji selection', async () => {
- const { onSelect } = renderPicker()
-
- await waitFor(async () => {
- expect(await screen.findByRole('gridcell', { name: 'Grinning face' }))!.toBeInTheDocument()
- })
-
- const firstEmoji = await screen.findByRole('gridcell', { name: 'Grinning face' })
- if (!firstEmoji) throw new Error('Could not find emoji option')
-
- await userEvent.click(firstEmoji)
- await userEvent.click(screen.getByText(/ok/i))
-
- await waitFor(() => {
- expect(onSelect).toHaveBeenCalledWith(
- expect.objectContaining({
- type: 'emoji',
- icon: expect.any(String),
- background: expect.any(String),
- }),
- )
- })
- })
-
- it('should close through the dialog open change contract when Escape is pressed', async () => {
- const { onOpenChange } = renderPicker()
-
- await userEvent.keyboard('{Escape}')
-
- expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything())
- })
-
- it('should not call onSelect when no emoji has been selected', async () => {
- const { onSelect } = renderPicker()
-
- await userEvent.click(screen.getByText(/ok/i))
-
- expect(onSelect).not.toHaveBeenCalled()
- })
-
- it('should submit the initial emoji when provided', async () => {
- const { onSelect } = renderPicker({ initialEmoji: { icon: 'rabbit', background: '#E4FBCC' } })
-
- await userEvent.click(screen.getByText(/ok/i))
-
- await waitFor(() => {
- expect(onSelect).toHaveBeenCalledWith({
- type: 'emoji',
- icon: '🐰',
- background: '#E4FBCC',
- })
- })
- })
- })
-
- describe('Image Upload', () => {
- it('hides confirmation actions in the empty image state', async () => {
- const { onSelect } = renderPicker()
-
- await userEvent.click(screen.getByText(/image/i))
- expect(screen.queryByRole('button', { name: 'app.iconPicker.ok' })).not.toBeInTheDocument()
- expect(
- screen.queryByRole('button', { name: 'app.iconPicker.cancel' }),
- ).not.toBeInTheDocument()
-
- expect(mocks.handleLocalFileUpload).not.toHaveBeenCalled()
- expect(onSelect).not.toHaveBeenCalled()
- })
-
- it('should upload cropped static image and emit selected image metadata', async () => {
- globalThis.Image = MockLoadedImage as unknown as typeof Image
-
- const sourceCanvas = createCanvasElementMock(createCanvasContextMock())
- const croppedBlob = new Blob(['cropped-image'], { type: 'image/png' })
- const croppedCanvas = createCanvasElementMock(createCanvasContextMock(), croppedBlob)
- mockCanvasCreation([sourceCanvas, croppedCanvas])
-
- const { onSelect } = renderPicker()
- await userEvent.click(screen.getByText(/image/i))
-
- const input = screen.queryByTestId('image-input')
- if (!input) throw new Error('Could not find image input')
-
- fireEvent.change(input, {
- target: { files: [new File(['png'], 'avatar.png', { type: 'image/png' })] },
- })
-
- await waitFor(() => {
- expect(screen.getByTestId('mock-cropper'))!.toBeInTheDocument()
- })
-
- await userEvent.click(screen.getByTestId('trigger-crop'))
- await userEvent.click(screen.getByText(/ok/i))
-
- await waitFor(() => {
- expect(mocks.handleLocalFileUpload).toHaveBeenCalledTimes(1)
- })
-
- const uploadedFile = mocks.handleLocalFileUpload.mock.calls[0]![0]
- expect(uploadedFile).toBeInstanceOf(File)
- expect(uploadedFile.name).toBe('avatar.png')
- expect(uploadedFile.type).toBe('image/png')
-
- await waitFor(() => {
- expect(onSelect).toHaveBeenCalledWith({
- type: 'image',
- fileId: 'uploaded-image-id',
- url: 'https://example.com/uploaded.png',
- })
- })
- })
-
- it('should upload animated image directly without crop', async () => {
- const { onSelect } = renderPicker()
- await userEvent.click(screen.getByText(/image/i))
-
- const gifBytes = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
- const gifFile = new File([gifBytes], 'animated.gif', { type: 'image/gif' })
-
- const input = screen.queryByTestId('image-input')
- if (!input) throw new Error('Could not find image input')
-
- fireEvent.change(input, { target: { files: [gifFile] } })
-
- await waitFor(() => {
- expect(screen.queryByTestId('mock-cropper')).not.toBeInTheDocument()
- const preview = screen.queryByTestId('animated-image')
- expect(preview)!.toBeInTheDocument()
- expect(preview?.getAttribute('src')).toContain('blob:mock-url')
- })
-
- await userEvent.click(screen.getByText(/ok/i))
-
- await waitFor(() => {
- expect(mocks.handleLocalFileUpload).toHaveBeenCalledWith(gifFile)
- })
-
- await waitFor(() => {
- expect(onSelect).toHaveBeenCalledWith({
- type: 'image',
- fileId: 'uploaded-image-id',
- url: 'https://example.com/uploaded.png',
- })
- })
- })
-
- it('should not call onSelect when upload callback returns image without fileId', async () => {
- mocks.uploadResult = createImageFile({ fileId: '' })
- const { onSelect } = renderPicker()
- await userEvent.click(screen.getByText(/image/i))
-
- const gifBytes = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
- const gifFile = new File([gifBytes], 'no-file-id.gif', { type: 'image/gif' })
-
- const input = screen.queryByTestId('image-input')
- if (!input) throw new Error('Could not find image input')
-
- fireEvent.change(input, { target: { files: [gifFile] } })
-
- await waitFor(() => {
- expect(screen.queryByTestId('mock-cropper')).not.toBeInTheDocument()
- })
-
- await userEvent.click(screen.getByText(/ok/i))
-
- await waitFor(() => {
- expect(mocks.handleLocalFileUpload).toHaveBeenCalledWith(gifFile)
- })
- expect(onSelect).not.toHaveBeenCalled()
- })
- })
-})
-
-mockEmojiData()
diff --git a/web/app/components/base/app-icon-picker/hooks.tsx b/web/app/components/base/app-icon-picker/hooks.tsx
deleted file mode 100644
index 5fb7656c949..00000000000
--- a/web/app/components/base/app-icon-picker/hooks.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { useCallback, useState } from 'react'
-
-export const useDraggableUploader = <T extends HTMLElement>(setImageFn: (file: File) => void) => {
- const [isDragActive, setIsDragActive] = useState(false)
-
- const handleDragEnter = useCallback((e: React.DragEvent<T>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragActive(true)
- }, [])
-
- const handleDragOver = useCallback((e: React.DragEvent<T>) => {
- e.preventDefault()
- e.stopPropagation()
- }, [])
-
- const handleDragLeave = useCallback((e: React.DragEvent<T>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragActive(false)
- }, [])
-
- const handleDrop = useCallback(
- (e: React.DragEvent<T>) => {
- e.preventDefault()
- e.stopPropagation()
- setIsDragActive(false)
-
- const file = e.dataTransfer.files[0]
-
- if (!file) return
-
- setImageFn(file)
- },
- [setImageFn],
- )
-
- return {
- handleDragEnter,
- handleDragOver,
- handleDragLeave,
- handleDrop,
- isDragActive,
- }
-}
diff --git a/web/app/components/base/app-icon-picker/index.tsx b/web/app/components/base/app-icon-picker/index.tsx
deleted file mode 100644
index 3bdb30a5fba..00000000000
--- a/web/app/components/base/app-icon-picker/index.tsx
+++ /dev/null
@@ -1,280 +0,0 @@
-import type { Area } from 'react-easy-crop'
-import type { OnImageInput } from './ImageInput'
-import type { AppIconType, ImageFile } from '@/types/app'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
-import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
-import { Separator } from '@langgenius/dify-ui/separator'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
-import { resolveEmoji } from '@/utils/emoji'
-import {
- defaultEmojiBackground,
- getRandomEmoji,
- getRandomEmojiBackground,
-} from '../emoji-picker/constants'
-import EmojiPickerInner from '../emoji-picker/Inner'
-import { addRecentEmoji, useRecentEmojis } from '../emoji-picker/storage'
-import { useLocalFileUploader } from '../image-uploader/hooks'
-import ImageInput from './ImageInput'
-import getCroppedImg from './utils'
-
-export type AppIconEmojiSelection = {
- type: 'emoji'
- icon: string
- background: string
-}
-
-export type AppIconImageSelection = {
- type: 'image'
- fileId: string
- url: string
-}
-
-export type AppIconSelection = AppIconEmojiSelection | AppIconImageSelection
-
-type AppIconPickerProps = {
- open: boolean
- onOpenChange: (open: boolean) => void
- onSelect?: (payload: AppIconSelection) => void
- enableImageUpload?: boolean
- initialEmoji?: {
- icon: string
- background?: string | null
- }
- className?: string
-}
-
-function AppIconPicker({
- open,
- onOpenChange,
- onSelect,
- enableImageUpload = true,
- initialEmoji,
- className,
-}: AppIconPickerProps) {
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- {open ? (
- <AppIconPickerContent
- key={`${initialEmoji?.icon ?? ''}:${initialEmoji?.background ?? ''}`}
- initialEmoji={initialEmoji}
- enableImageUpload={enableImageUpload}
- className={className}
- onOpenChange={onOpenChange}
- onSelect={onSelect}
- />
- ) : null}
- </Dialog>
- )
-}
-
-type AppIconPickerContentProps = {
- className?: string
- initialEmoji?: {
- icon: string
- background?: string | null
- }
- enableImageUpload: boolean
- onOpenChange: (open: boolean) => void
- onSelect?: (payload: AppIconSelection) => void
-}
-
-function AppIconPickerContent({
- className,
- initialEmoji,
- enableImageUpload,
- onOpenChange,
- onSelect,
-}: AppIconPickerContentProps) {
- const { t } = useTranslation(['app'])
-
- const tabs = [
- {
- key: 'emoji',
- label: t(($) => $['iconPicker.emoji'], { ns: 'app' }),
- icon: <span className="text-base">🤖</span>,
- },
- {
- key: 'image',
- label: t(($) => $['iconPicker.image'], { ns: 'app' }),
- icon: <span className="i-ri-image-circle-ai-line size-4" />,
- },
- ]
- const [activeTab, setActiveTab] = useState<AppIconType>('emoji')
- const showImageUpload = enableImageUpload && !DISABLE_UPLOAD_IMAGE_AS_ICON
-
- const [emoji, setEmoji] = useState<{ emoji: string; background: string } | undefined>(() => {
- if (!initialEmoji?.icon) return undefined
-
- return {
- emoji: resolveEmoji(initialEmoji.icon),
- background: initialEmoji.background ?? defaultEmojiBackground,
- }
- })
-
- const [, setRecentEmojis] = useRecentEmojis()
-
- const [uploading, setUploading] = useState<boolean>()
-
- const { handleLocalFileUpload } = useLocalFileUploader({
- limit: 3,
- disabled: false,
- onUpload: (imageFile: ImageFile) => {
- if (imageFile.fileId) {
- setUploading(false)
- onSelect?.({
- type: 'image',
- fileId: imageFile.fileId,
- url: imageFile.url,
- })
- onOpenChange(false)
- }
- },
- })
-
- type InputImageInfo =
- | { file: File }
- | { tempUrl: string; croppedAreaPixels: Area; fileName: string }
- const [inputImageInfo, setInputImageInfo] = useState<InputImageInfo>()
-
- const handleImageInput: OnImageInput = async (
- isCropped: boolean,
- fileOrTempUrl: string | File,
- croppedAreaPixels?: Area,
- fileName?: string,
- ) => {
- setInputImageInfo(
- isCropped
- ? {
- tempUrl: fileOrTempUrl as string,
- croppedAreaPixels: croppedAreaPixels!,
- fileName: fileName!,
- }
- : { file: fileOrTempUrl as File },
- )
- }
-
- const handleSelect = async () => {
- if (activeTab === 'emoji') {
- if (emoji) {
- setRecentEmojis((recent) => addRecentEmoji(recent, emoji.emoji))
- onSelect?.({
- type: 'emoji',
- icon: emoji.emoji,
- background: emoji.background,
- })
- onOpenChange(false)
- }
- } else {
- if (!inputImageInfo) return
- setUploading(true)
- if ('file' in inputImageInfo) {
- handleLocalFileUpload(inputImageInfo.file)
- return
- }
- const blob = await getCroppedImg(
- inputImageInfo.tempUrl,
- inputImageInfo.croppedAreaPixels,
- inputImageInfo.fileName,
- )
- const file = new File([blob], inputImageInfo.fileName, { type: blob.type })
- handleLocalFileUpload(file)
- }
- }
-
- return (
- <DialogContent
- backdropProps={{ forceRender: true }}
- className={cn(
- 'flex max-h-[calc(100dvh-2rem)] w-80.5 flex-col overflow-hidden p-0 text-left',
- activeTab === 'emoji' && 'h-[min(480px,calc(100dvh-2rem))]',
- className,
- )}
- >
- <DialogTitle className="sr-only">
- {t(($) => $['iconPicker.emoji'], { ns: 'app' })}
- </DialogTitle>
-
- {showImageUpload && (
- <div
- className={cn(
- 'w-full shrink-0 px-3 pt-3 pb-2',
- activeTab === 'image' && 'border-b border-divider-subtle',
- )}
- >
- <SegmentedControl
- className="flex w-full"
- aria-label={t(($) => $['iconPicker.emoji'], { ns: 'app' })}
- value={activeTab}
- onValueChange={(value) => {
- setActiveTab(value)
- setInputImageInfo(undefined)
- }}
- >
- {tabs.map((tab) => (
- <SegmentedControlItem key={tab.key} value={tab.key} className="flex-1">
- <span className="flex size-5 items-center justify-center" aria-hidden="true">
- {tab.icon}
- </span>
- <span className="p-0.5">{tab.label}</span>
- </SegmentedControlItem>
- ))}
- </SegmentedControl>
- </div>
- )}
-
- {activeTab === 'emoji' && (
- <EmojiPickerInner
- className={cn('flex-1 overflow-hidden', !showImageUpload && 'pt-3')}
- emoji={emoji?.emoji}
- background={emoji?.background}
- onSelect={(emoji, background) => setEmoji({ emoji, background })}
- />
- )}
- {activeTab === 'image' && (
- <ImageInput className="min-h-0 overflow-y-auto" onImageInput={handleImageInput} />
- )}
-
- {(activeTab === 'emoji' || inputImageInfo) && (
- <>
- <Separator decorative className="m-0 h-[0.5px]" />
- <div className="flex w-full shrink-0 items-center justify-center gap-2 bg-components-panel-bg-blur p-3 backdrop-blur-sm">
- {activeTab === 'emoji' ? (
- <Button
- className="min-w-0 flex-1"
- onClick={() =>
- setEmoji({
- emoji: getRandomEmoji(emoji?.emoji),
- background: getRandomEmojiBackground(emoji?.background),
- })
- }
- >
- <span className="i-ri-dice-line size-4" aria-hidden="true" />
- {t(($) => $['iconPicker.tryYourLuck'], { ns: 'app' })}
- </Button>
- ) : (
- <Button className="min-w-0 flex-1" onClick={() => onOpenChange(false)}>
- {t(($) => $['iconPicker.cancel'], { ns: 'app' })}
- </Button>
- )}
-
- <Button
- variant="primary"
- className="min-w-0 flex-1"
- disabled={activeTab === 'emoji' ? !emoji : !inputImageInfo}
- loading={uploading}
- onClick={handleSelect}
- >
- {t(($) => $['iconPicker.ok'], { ns: 'app' })}
- </Button>
- </div>
- </>
- )}
- </DialogContent>
- )
-}
-
-export default AppIconPicker
diff --git a/web/app/components/base/emoji-picker/Inner.stories.tsx b/web/app/components/base/emoji-picker/Inner.stories.tsx
deleted file mode 100644
index 14bfd976896..00000000000
--- a/web/app/components/base/emoji-picker/Inner.stories.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useState } from 'react'
-import EmojiPickerInner from './Inner'
-
-const meta = {
- title: 'Base/Data Entry/EmojiPickerInner',
- component: EmojiPickerInner,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component:
- 'Core emoji grid with search, recent selections, and recommendations. Use this when embedding the selector inline without a modal frame.',
- },
- },
- },
- tags: ['autodocs'],
-} satisfies Meta<typeof EmojiPickerInner>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const InnerDemo = () => {
- const [selection, setSelection] = useState<{ emoji: string; background: string } | null>(null)
-
- return (
- <div className="flex h-130 flex-col gap-4 rounded-xl border border-divider-subtle bg-components-panel-bg p-6 shadow-lg">
- <EmojiPickerInner
- emoji={selection?.emoji}
- onSelect={(emoji, background) => setSelection({ emoji, background })}
- className="flex-1 overflow-hidden rounded-xl border border-divider-subtle bg-white"
- />
- <div className="rounded-lg border border-divider-subtle bg-background-default-subtle p-3 text-xs text-text-secondary">
- <div className="font-medium text-text-primary">Latest selection</div>
- <pre className="mt-1 max-h-40 overflow-auto font-mono">
- {selection ? JSON.stringify(selection, null, 2) : 'Tap an emoji to select it.'}
- </pre>
- </div>
- </div>
- )
-}
-
-export const Playground: Story = {
- render: () => <InnerDemo />,
- parameters: {
- docs: {
- source: {
- language: 'tsx',
- code: `
-const [selection, setSelection] = useState<{ emoji: string; background: string } | null>(null)
-
-return (
- <EmojiPickerInner onSelect={(emoji, background) => setSelection({ emoji, background })} />
-)
- `.trim(),
- },
- },
- },
-}
diff --git a/web/app/components/base/emoji-picker/Inner.tsx b/web/app/components/base/emoji-picker/Inner.tsx
deleted file mode 100644
index cb0a4769155..00000000000
--- a/web/app/components/base/emoji-picker/Inner.tsx
+++ /dev/null
@@ -1,206 +0,0 @@
-'use client'
-import type { EmojiPickerListEmojiProps } from 'frimousse'
-import { cn } from '@langgenius/dify-ui/cn'
-import { EmojiPicker } from 'frimousse'
-import * as React from 'react'
-import { createContext, use, useRef, useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { resolveEmoji } from '@/utils/emoji'
-import { basePath } from '@/utils/var'
-import { defaultEmojiBackground, emojiStyles, recommendedEmojis } from './constants'
-import { useRecentEmojisValue } from './storage'
-
-type IEmojiPickerInnerProps = {
- emoji?: string
- background?: string
- onSelect?: (emoji: string, background: string) => void
- className?: string
-}
-
-const emojiButtonClassName =
- 'flex h-8 w-full min-w-0 max-w-8 flex-1 items-center justify-center rounded-lg text-2xl leading-none hover:bg-state-base-hover focus-visible:outline-2 focus-visible:outline-state-accent-solid data-[active]:bg-state-base-hover aria-pressed:ring-[1.5px] aria-pressed:ring-components-option-card-option-selected-border aria-pressed:ring-inset'
-
-const SelectedEmojiContext = createContext('')
-
-function EmojiButton({ emoji, ...props }: EmojiPickerListEmojiProps) {
- const selectedEmoji = use(SelectedEmojiContext)
- return (
- <button
- {...props}
- type="button"
- aria-pressed={selectedEmoji === emoji.emoji}
- className={emojiButtonClassName}
- >
- {emoji.emoji}
- </button>
- )
-}
-
-const listComponents: NonNullable<React.ComponentProps<typeof EmojiPicker.List>['components']> = {
- CategoryHeader: ({ category, ...props }) => (
- <div
- {...props}
- className="bg-components-panel-bg px-3.5 py-1 system-xs-medium-uppercase text-text-tertiary"
- >
- {category.label}
- </div>
- ),
- Row: ({ children, ...props }) => (
- <div {...props} className="scroll-my-1 gap-px px-3 pb-px">
- {children}
- </div>
- ),
- Emoji: EmojiButton,
-}
-
-function EmojiPickerInner({ emoji, background, onSelect, className }: IEmojiPickerInnerProps) {
- const { t } = useTranslation(['app', 'common'])
- const [search, setSearch] = useState('')
- const scrollRef = useRef<HTMLDivElement>(null)
- const recentEmojis = useRecentEmojisValue()
- const selectedEmoji = emoji ? resolveEmoji(emoji) : ''
- const handleEmojiSelect = (value: string) =>
- onSelect?.(value, background || defaultEmojiBackground)
-
- const renderGroup = (label: string, emojis: string[]) => (
- <section aria-label={label} className="px-3 pb-2">
- <h3 className="px-0.5 py-1 system-xs-medium-uppercase text-text-tertiary">{label}</h3>
- <div className="grid grid-cols-9 gap-px">
- {emojis.map((value) => (
- <button
- key={value}
- type="button"
- aria-label={value}
- aria-pressed={selectedEmoji === value}
- className={emojiButtonClassName}
- onClick={() => handleEmojiSelect(value)}
- >
- {value}
- </button>
- ))}
- </div>
- </section>
- )
-
- return (
- <EmojiPicker.Root
- className={cn('flex min-h-0 w-full min-w-0 flex-col', className)}
- locale="en"
- columns={9}
- emojibaseUrl={`${basePath}/emoji/emojibase-17.0.0`}
- onEmojiSelect={({ emoji }) => handleEmojiSelect(emoji)}
- onKeyUp={(event) => {
- if (
- ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)
- ) {
- scrollRef.current
- ?.querySelector<HTMLElement>('[frimousse-emoji][data-active]')
- ?.scrollIntoView({ block: 'nearest' })
- }
- }}
- >
- <div className="shrink-0 border-b border-divider-subtle px-3 pb-2">
- <div className="flex h-8 items-center gap-1.5 rounded-lg border border-transparent bg-components-input-bg-normal px-2 focus-within:border-components-input-border-active focus-within:bg-components-input-bg-active">
- <span
- className="i-ri-search-line size-4 shrink-0 text-components-input-text-placeholder"
- aria-hidden="true"
- />
- <EmojiPicker.Search
- aria-label={t(($) => $['iconPicker.search'], { ns: 'app' })}
- placeholder={t(($) => $['iconPicker.search'], { ns: 'app' })}
- value={search}
- onChange={(event) => {
- setSearch(event.target.value)
- scrollRef.current?.scrollTo({ top: 0 })
- }}
- className="h-full min-w-0 flex-1 appearance-none border-0 bg-transparent p-0 system-sm-regular text-components-input-text-filled outline-none placeholder:text-components-input-text-placeholder [&::-webkit-search-cancel-button]:appearance-none"
- />
- </div>
- </div>
- <div
- ref={scrollRef}
- role="region"
- aria-label={t(($) => $['iconPicker.emoji'], { ns: 'app' })}
- className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain"
- style={{ scrollbarWidth: 'none' }}
- >
- <div className="py-2">
- {!search && (
- <div className="shrink-0">
- {!!recentEmojis.length &&
- renderGroup(
- t(($) => $['iconPicker.recent'], { ns: 'app' }),
- recentEmojis,
- )}
- {renderGroup(
- t(($) => $['iconPicker.recommend'], { ns: 'app' }),
- recommendedEmojis,
- )}
- </div>
- )}
- <EmojiPicker.Viewport
- className="relative w-full"
- // The outer scroller owns all groups; let this viewport grow with its list.
- style={{
- contain: 'none',
- containIntrinsicSize: 'none',
- overflow: 'visible',
- scrollbarGutter: 'auto',
- willChange: 'auto',
- }}
- >
- <EmojiPicker.Loading className="block p-3 text-text-tertiary">
- {t(($) => $.loading, { ns: 'common' })}
- </EmojiPicker.Loading>
- <EmojiPicker.Empty className="block p-3 text-text-tertiary">
- {t(($) => $.noData, { ns: 'common' })}
- </EmojiPicker.Empty>
- <SelectedEmojiContext value={selectedEmoji}>
- <EmojiPicker.List components={listComponents} />
- </SelectedEmojiContext>
- </EmojiPicker.Viewport>
- </div>
- </div>
- {selectedEmoji && (
- <section
- aria-label={t(($) => $['iconPicker.chooseStyle'], { ns: 'app' })}
- className="shrink-0 border-t border-divider-subtle bg-components-panel-bg-blur px-3 pt-2 pb-3 backdrop-blur-sm"
- >
- <h3 className="px-0.5 py-1 system-xs-semibold-uppercase text-text-primary">
- {t(($) => $['iconPicker.chooseStyle'], { ns: 'app' })}
- </h3>
- <div className="grid grid-cols-6 justify-items-center gap-0.75 pt-0.5">
- {emojiStyles.map((style) => (
- <button
- key={style.background}
- type="button"
- aria-label={style.background}
- aria-pressed={
- (background || defaultEmojiBackground).toUpperCase() === style.background
- }
- className={cn(
- 'flex aspect-square w-full max-w-11.5 items-center justify-center rounded-xl p-0.75 ring-inset focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid',
- (background || defaultEmojiBackground).toUpperCase() === style.background && [
- 'ring-[1.5px]',
- style.selectedClassName,
- ],
- )}
- onClick={() => onSelect?.(selectedEmoji, style.background)}
- >
- <span
- className={cn(
- 'flex aspect-square w-full items-center justify-center rounded-[10px] border-[0.5px] border-divider-regular text-2xl leading-none',
- style.backgroundClassName,
- )}
- >
- {selectedEmoji}
- </span>
- </button>
- ))}
- </div>
- </section>
- )}
- </EmojiPicker.Root>
- )
-}
-export default EmojiPickerInner
diff --git a/web/app/components/base/emoji-picker/__tests__/Inner.browser.spec.tsx b/web/app/components/base/emoji-picker/__tests__/Inner.browser.spec.tsx
deleted file mode 100644
index 23ba8215b86..00000000000
--- a/web/app/components/base/emoji-picker/__tests__/Inner.browser.spec.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { page, userEvent } from 'vite-plus/test/browser'
-import { render } from 'vitest-browser-react'
-import AppIconPicker from '../../app-icon-picker'
-import EmojiPickerInner from '../Inner'
-
-// Real layout verifies keyboard navigation scrolls the shared list to the active row.
-it('selects a searched emoji and scrolls to later rows with the keyboard', async () => {
- const onSelect = vi.fn()
- await render(
- <div style={{ width: 322, height: 480, display: 'flex' }}>
- <EmojiPickerInner onSelect={onSelect} />
- </div>,
- )
- const search = page.getByRole('searchbox')
- await search.fill('rabbit face')
- await expect.element(page.getByRole('gridcell', { name: 'Rabbit face' })).toBeVisible()
- await userEvent.keyboard('{Enter}')
- await expect.poll(() => onSelect.mock.lastCall).toEqual(['🐰', '#FEF3F2'])
- await search.fill('')
- await expect
- .element(page.getByRole('gridcell', { name: 'Grinning face', exact: true }))
- .toBeVisible()
- await search.click()
- await userEvent.keyboard(
- '{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}{ArrowDown}{Enter}',
- )
- expect(onSelect).toHaveBeenCalledTimes(2)
-})
-
-// Guard against the scrollbar clipping the ninth column or the footer obscuring selectable rows.
-it('keeps the rightmost emoji clickable inside the app icon dialog', async () => {
- const onSelect = vi.fn()
- await render(<AppIconPicker open onOpenChange={() => {}} onSelect={onSelect} />)
- const option = page.getByRole('gridcell', { name: 'Slightly smiling face', exact: true })
- await expect.element(option).toBeVisible()
- const dialogBounds = page.getByRole('dialog').element().getBoundingClientRect()
- const optionBounds = option.element().getBoundingClientRect()
- expect(optionBounds.right).toBeLessThanOrEqual(dialogBounds.right)
- await option.click()
- await page.getByRole('button', { name: 'app.iconPicker.ok', exact: true }).click()
- expect(onSelect).toHaveBeenCalledWith({ type: 'emoji', icon: '🙂', background: '#FEF3F2' })
-})
-
-// The old layout pinned recommendations while only the category grid scrolled.
-it('scrolls recommendations and categories together while keeping search and actions fixed', async () => {
- await render(<AppIconPicker open onOpenChange={() => {}} initialEmoji={{ icon: '🤖' }} />)
- await expect
- .element(page.getByRole('gridcell', { name: 'Grinning face', exact: true }))
- .toBeVisible()
- const scroller = page.getByRole('region', { name: 'app.iconPicker.emoji', exact: true }).element()
- const recommendation = page.getByRole('region', { name: 'app.iconPicker.recommend' }).element()
- const search = page.getByRole('searchbox').element()
- const confirm = page.getByRole('button', { name: 'app.iconPicker.ok', exact: true }).element()
- const styles = page.getByRole('region', { name: 'app.iconPicker.chooseStyle' }).element()
- const stylesTop = styles.getBoundingClientRect().top
- const searchTop = search.getBoundingClientRect().top
- const confirmTop = confirm.getBoundingClientRect().top
- scroller.scrollTo({ top: 400 })
- await expect
- .poll(() => recommendation.getBoundingClientRect().bottom)
- .toBeLessThan(scroller.getBoundingClientRect().top)
- const category = page.getByText('Smileys & emotion', { exact: true }).element()
- expect(category.getBoundingClientRect().top).toBe(scroller.getBoundingClientRect().top)
- expect(styles.getBoundingClientRect().top).toBe(stylesTop)
- await page.getByRole('button', { name: '#F0F2F5', exact: true }).click()
- await expect
- .element(page.getByRole('button', { name: '#F0F2F5', exact: true }))
- .toHaveAttribute('aria-pressed', 'true')
- expect(search.getBoundingClientRect().top).toBe(searchTop)
- expect(confirm.getBoundingClientRect().top).toBe(confirmTop)
-})
diff --git a/web/app/components/base/emoji-picker/__tests__/Inner.spec.tsx b/web/app/components/base/emoji-picker/__tests__/Inner.spec.tsx
deleted file mode 100644
index 850abc333f9..00000000000
--- a/web/app/components/base/emoji-picker/__tests__/Inner.spec.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { mockEmojiData } from '@/test/emoji-picker'
-import EmojiPickerInner from '../Inner'
-
-vi.mock('@/utils/var', () => ({ basePath: '/console' }))
-mockEmojiData()
-
-it('selects Unicode from self-hosted data while preserving the existing background', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
- render(<EmojiPickerInner background="#E4FBCC" onSelect={onSelect} />)
- await user.click(await screen.findByRole('gridcell', { name: 'Grinning face' }))
- expect(onSelect).toHaveBeenCalledWith('😀', '#E4FBCC')
- expect(fetch).toHaveBeenCalledWith(
- '/console/emoji/emojibase-17.0.0/en/data.json',
- expect.any(Object),
- )
-})
-
-it('filters search, selects a result, shows empty state and restores recommendations on clear', async () => {
- const user = userEvent.setup()
- const onSelect = vi.fn()
- render(<EmojiPickerInner onSelect={onSelect} />)
- const search = screen.getByRole('searchbox')
- await user.type(search, 'rabbit')
- await user.click(await screen.findByRole('gridcell', { name: 'Rabbit face' }))
- expect(onSelect).toHaveBeenLastCalledWith('🐰', '#FEF3F2')
- expect(screen.queryByRole('region', { name: 'app.iconPicker.recommend' })).not.toBeInTheDocument()
- await user.clear(search)
- await user.type(search, 'zzzz-no-emoji')
- await screen.findByText('common.noData')
- await user.clear(search)
- expect(screen.getByRole('region', { name: 'app.iconPicker.recommend' })).toBeInTheDocument()
- await screen.findByRole('gridcell', { name: 'Grinning face' })
-})
diff --git a/web/app/components/base/emoji-picker/__tests__/index.spec.tsx b/web/app/components/base/emoji-picker/__tests__/index.spec.tsx
deleted file mode 100644
index 17f8ce27181..00000000000
--- a/web/app/components/base/emoji-picker/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { act, fireEvent, render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { mockEmojiData } from '@/test/emoji-picker'
-import EmojiPicker from '../index'
-
-mockEmojiData()
-
-describe('EmojiPicker', () => {
- const mockOnSelect = vi.fn()
- const mockOnOpenChange = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('Rendering', () => {
- it('renders nothing when closed', () => {
- const { container } = render(<EmojiPicker open={false} onOpenChange={mockOnOpenChange} />)
- expect(container.firstChild).toBeNull()
- })
-
- it('renders modal when open', async () => {
- await act(async () => {
- render(<EmojiPicker open onOpenChange={mockOnOpenChange} />)
- })
- expect(screen.getByRole('dialog', { name: /Emoji/i }))!.toBeInTheDocument()
- expect(screen.getByPlaceholderText('app.iconPicker.search'))!.toBeInTheDocument()
- expect(screen.getByText(/tryYourLuck/i))!.toBeInTheDocument()
- expect(screen.getByText(/OK/i))!.toBeInTheDocument()
- })
-
- it('OK button is disabled initially', async () => {
- await act(async () => {
- render(<EmojiPicker open onOpenChange={mockOnOpenChange} />)
- })
- const okButton = screen.getByText(/OK/i).closest('button')
- expect(okButton)!.toBeDisabled()
- })
- })
-
- describe('User Interactions', () => {
- it('calls onSelect with selected emoji and background when OK is clicked', async () => {
- await act(async () => {
- render(<EmojiPicker open onOpenChange={mockOnOpenChange} onSelect={mockOnSelect} />)
- })
-
- fireEvent.click(await screen.findByRole('gridcell', { name: 'Grinning face' }))
-
- const okButton = screen.getByText(/OK/i)
- expect(okButton.closest('button')).not.toBeDisabled()
-
- await act(async () => {
- fireEvent.click(okButton)
- })
-
- expect(mockOnSelect).toHaveBeenCalledWith(expect.any(String), expect.any(String))
- })
-
- it('randomizes emoji and background without submitting until confirmed', async () => {
- vi.spyOn(Math, 'random').mockReturnValue(0)
- const user = userEvent.setup()
- render(<EmojiPicker open onOpenChange={mockOnOpenChange} onSelect={mockOnSelect} />)
- await user.click(screen.getByRole('button', { name: /tryYourLuck/i }))
- expect(mockOnSelect).not.toHaveBeenCalled()
- expect(mockOnOpenChange).not.toHaveBeenCalled()
- expect(screen.getByRole('button', { name: /ok/i })).toBeEnabled()
- await user.click(screen.getByRole('button', { name: /ok/i }))
- expect(screen.getByRole('button', { name: '#FFF1F3' })).toHaveAttribute(
- 'aria-pressed',
- 'true',
- )
- expect(mockOnSelect).toHaveBeenCalledWith('😃', '#FFF1F3')
- expect(mockOnOpenChange).toHaveBeenCalledWith(false)
- })
- })
-})
diff --git a/web/app/components/base/emoji-picker/index.stories.tsx b/web/app/components/base/emoji-picker/index.stories.tsx
deleted file mode 100644
index 94e61e5b167..00000000000
--- a/web/app/components/base/emoji-picker/index.stories.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import { useState } from 'react'
-import EmojiPicker from '.'
-
-const meta = {
- title: 'Base/Data Entry/EmojiPicker',
- component: EmojiPicker,
- parameters: {
- layout: 'fullscreen',
- docs: {
- description: {
- component:
- 'Modal-based emoji selector that powers the icon picker. Supports search, recent selections, random selection, and confirmation callbacks.',
- },
- },
- nextjs: {
- appDirectory: true,
- navigation: {
- pathname: '/apps/demo-app/emoji-picker',
- params: { appId: 'demo-app' },
- },
- },
- },
- tags: ['autodocs'],
-} satisfies Meta<typeof EmojiPicker>
-
-export default meta
-type Story = StoryObj<typeof meta>
-
-const EmojiPickerDemo = () => {
- const [open, setOpen] = useState(false)
- const [selection, setSelection] = useState<{ emoji: string; background: string } | null>(null)
-
- return (
- <div className="flex min-h-80 flex-col items-start gap-4 px-6 py-8 md:px-12">
- <button
- type="button"
- className="rounded-md bg-primary-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-primary-700"
- onClick={() => setOpen(true)}
- >
- Open emoji picker…
- </button>
-
- <div className="rounded-lg border border-divider-subtle bg-components-panel-bg p-4 text-sm text-text-secondary shadow-sm">
- <div className="font-medium text-text-primary">Selection preview</div>
- <pre className="mt-2 max-h-44 overflow-auto rounded-md bg-background-default-subtle p-3 font-mono text-xs/tight text-text-primary">
- {selection ? JSON.stringify(selection, null, 2) : 'No emoji selected yet.'}
- </pre>
- </div>
-
- <EmojiPicker
- open={open}
- onOpenChange={setOpen}
- onSelect={(emoji, background) => setSelection({ emoji, background })}
- />
- </div>
- )
-}
-
-export const Playground: Story = {
- args: {
- open: false,
- onOpenChange: () => {},
- },
- render: () => <EmojiPickerDemo />,
- parameters: {
- docs: {
- source: {
- language: 'tsx',
- code: `
-const [open, setOpen] = useState(false)
-const [selection, setSelection] = useState<{ emoji: string; background: string } | null>(null)
-
-return (
- <>
- <button onClick={() => setOpen(true)}>Open emoji picker…</button>
- <EmojiPicker
- open={open}
- onOpenChange={setOpen}
- onSelect={(emoji, background) => setSelection({ emoji, background })}
- />
- </>
-)
- `.trim(),
- },
- },
- },
-}
diff --git a/web/app/components/base/emoji-picker/index.tsx b/web/app/components/base/emoji-picker/index.tsx
deleted file mode 100644
index a5522e32f85..00000000000
--- a/web/app/components/base/emoji-picker/index.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-'use client'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
-import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
-import { Separator } from '@langgenius/dify-ui/separator'
-import { useState } from 'react'
-import { useTranslation } from 'react-i18next'
-import { defaultEmojiBackground, getRandomEmoji, getRandomEmojiBackground } from './constants'
-import EmojiPickerInner from './Inner'
-import { addRecentEmoji, useRecentEmojis } from './storage'
-
-type EmojiPickerProps = {
- open: boolean
- onOpenChange: (open: boolean) => void
- onSelect?: (emoji: string, background: string) => void
- className?: string
-}
-
-function EmojiPicker({ open, onOpenChange, onSelect, className }: EmojiPickerProps) {
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- {open ? (
- <EmojiPickerContent className={className} onOpenChange={onOpenChange} onSelect={onSelect} />
- ) : null}
- </Dialog>
- )
-}
-
-type EmojiPickerContentProps = {
- className?: string
- onOpenChange: (open: boolean) => void
- onSelect?: (emoji: string, background: string) => void
-}
-
-function EmojiPickerContent({ className, onOpenChange, onSelect }: EmojiPickerContentProps) {
- const { t } = useTranslation(['app'])
- const [selectedEmoji, setSelectedEmoji] = useState('')
- const [selectedBackground, setSelectedBackground] = useState(defaultEmojiBackground)
- const [, setRecentEmojis] = useRecentEmojis()
-
- return (
- <DialogContent
- className={cn(
- 'flex h-[min(480px,calc(100dvh-2rem))] max-h-none w-80.5 flex-col overflow-hidden p-0 text-left',
- className,
- )}
- >
- <DialogTitle className="sr-only">
- {t(($) => $['iconPicker.emoji'], { ns: 'app' })}
- </DialogTitle>
-
- <EmojiPickerInner
- className="flex-1 overflow-hidden pt-3"
- emoji={selectedEmoji}
- background={selectedBackground}
- onSelect={(emoji, background) => {
- setSelectedEmoji(emoji)
- setSelectedBackground(background)
- }}
- />
- <Separator decorative className="m-0 h-[0.5px]" />
- <div className="flex w-full shrink-0 items-center justify-center gap-2 bg-components-panel-bg-blur p-3 backdrop-blur-sm">
- <Button
- className="min-w-0 flex-1"
- onClick={() => {
- setSelectedEmoji(getRandomEmoji(selectedEmoji))
- setSelectedBackground(getRandomEmojiBackground(selectedBackground))
- }}
- >
- <span className="i-ri-dice-line size-4" aria-hidden="true" />
- {t(($) => $['iconPicker.tryYourLuck'], { ns: 'app' })}
- </Button>
- <Button
- disabled={selectedEmoji === '' || !selectedBackground}
- variant="primary"
- className="min-w-0 flex-1"
- onClick={() => {
- setRecentEmojis((recent) => addRecentEmoji(recent, selectedEmoji))
- onSelect?.(selectedEmoji, selectedBackground)
- onOpenChange(false)
- }}
- >
- {t(($) => $['iconPicker.ok'], { ns: 'app' })}
- </Button>
- </div>
- </DialogContent>
- )
-}
-export default EmojiPicker
diff --git a/web/app/components/base/icon-picker/__tests__/image-confirmation.spec.tsx b/web/app/components/base/icon-picker/__tests__/image-confirmation.spec.tsx
new file mode 100644
index 00000000000..1430e18d652
--- /dev/null
+++ b/web/app/components/base/icon-picker/__tests__/image-confirmation.spec.tsx
@@ -0,0 +1,291 @@
+import type {
+ PostFilesUploadData,
+ PostFilesUploadResponse,
+} from '@dify/contracts/api/console/files/types.gen'
+import type { IconPickerDefaultValue } from '..'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { IconPickerDialog } from '..'
+import { emojiCatalogOptions } from '../emoji-data'
+
+const { uploadImage } = vi.hoisted(() => ({
+ uploadImage:
+ vi.fn<(input: Pick<PostFilesUploadData, 'body'>) => Promise<PostFilesUploadResponse>>(),
+}))
+
+vi.mock('@/service/console', () => ({
+ consoleQuery: {
+ files: { upload: { post: { mutationOptions: () => ({ mutationFn: uploadImage }) } } },
+ },
+}))
+
+beforeEach(() => {
+ uploadImage.mockReset()
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:preview')
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})
+})
+
+afterEach(() => vi.restoreAllMocks())
+
+async function selectImage(defaultValue?: IconPickerDefaultValue) {
+ const user = userEvent.setup()
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ const onConfirm = vi.fn()
+ const onOpenChange = vi.fn()
+ const view = render(
+ <QueryClientProvider client={client}>
+ <IconPickerDialog
+ open
+ defaultValue={defaultValue}
+ onConfirm={onConfirm}
+ onOpenChange={onOpenChange}
+ />
+ </QueryClientProvider>,
+ )
+ await user.click(screen.getByRole('tab', { name: 'app.iconPicker.image' }))
+ if (defaultValue?.type === 'image')
+ await user.click(screen.getByRole('button', { name: 'common.operation.change' }))
+ const file = new File(['GIF89a'], 'icon.gif', { type: 'image/gif' })
+ await user.upload(screen.getByTestId('image-input'), file)
+ const confirm = await screen.findByRole('button', { name: 'app.iconPicker.ok' })
+ return { ...view, user, client, file, confirm, onConfirm, onOpenChange }
+}
+
+it('keeps the image draft after an upload failure and confirms the retried upload', async () => {
+ uploadImage.mockRejectedValueOnce(new Error('Upload failed'))
+ uploadImage.mockResolvedValueOnce({ id: 'uploaded-image', name: 'icon.gif', size: 6 })
+ const { user, client, file, confirm, onConfirm, onOpenChange } = await selectImage()
+ await user.click(confirm)
+ await waitFor(() => expect(uploadImage).toHaveBeenCalledOnce())
+ expect(uploadImage.mock.calls[0]![0].body.file).toBe(file)
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'common.imageUploader.uploadFromComputerUploadError',
+ )
+ await user.click(confirm)
+ await waitFor(() => expect(uploadImage).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith({
+ type: 'image',
+ fileId: 'uploaded-image',
+ url: expect.stringContaining('data:image/gif;base64,'),
+ })
+ expect(onOpenChange).toHaveBeenCalledExactlyOnceWith(false)
+ client.clear()
+})
+
+it('does not confirm an upload that finishes after the picker is unmounted', async () => {
+ let finishUpload!: (response: PostFilesUploadResponse) => void
+ uploadImage.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishUpload = resolve
+ }),
+ )
+ const { user, client, confirm, onConfirm, onOpenChange, unmount } = await selectImage()
+ await user.click(confirm)
+ await waitFor(() => expect(uploadImage).toHaveBeenCalledOnce())
+ unmount()
+ await act(async () => {
+ finishUpload({ id: 'late-image', name: 'icon.gif', size: 6 })
+ })
+ expect(onConfirm).not.toHaveBeenCalled()
+ expect(onOpenChange).not.toHaveBeenCalled()
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:preview')
+ client.clear()
+})
+
+it('opens the file input directly and preserves the existing image on cancellation or invalid selection', async () => {
+ const user = userEvent.setup({ applyAccept: false })
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ const onConfirm = vi.fn()
+ const value = { type: 'image' as const, fileId: 'existing', url: '/existing.png' }
+ render(
+ <QueryClientProvider client={client}>
+ <IconPickerDialog open defaultValue={value} onConfirm={onConfirm} onOpenChange={() => {}} />
+ </QueryClientProvider>,
+ )
+ const input = screen.getByTestId('image-input')
+ const openFilePicker = vi.spyOn(input, 'click')
+ await user.click(screen.getByRole('button', { name: 'common.operation.change' }))
+ expect(openFilePicker).toHaveBeenCalledOnce()
+ fireEvent(input, new Event('cancel', { bubbles: true }))
+ expect(screen.getByRole('img', { name: 'app.iconPicker.image' })).toHaveAttribute(
+ 'src',
+ value.url,
+ )
+ expect(screen.queryByRole('button', { name: 'common.imageInput.browse' })).not.toBeInTheDocument()
+ expect(onConfirm).not.toHaveBeenCalled()
+ await user.upload(input, new File(['text'], 'invalid.txt', { type: 'text/plain' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.imageInput.supportedFormats')
+ expect(screen.getByRole('img', { name: 'app.iconPicker.image' })).toHaveAttribute(
+ 'src',
+ value.url,
+ )
+ await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(value)
+ expect(uploadImage).not.toHaveBeenCalled()
+ client.clear()
+})
+
+it('allows retry after reading the image preview fails', async () => {
+ const { user, client, confirm, onConfirm } = await selectImage()
+ const read = vi.spyOn(FileReader.prototype, 'readAsDataURL').mockImplementationOnce(function (
+ this: FileReader,
+ ) {
+ this.dispatchEvent(new Event('error'))
+ })
+ await user.click(confirm)
+ expect(await screen.findByRole('alert')).toHaveTextContent(
+ 'common.imageUploader.uploadFromComputerReadError',
+ )
+ expect(confirm).toBeEnabled()
+ expect(uploadImage).not.toHaveBeenCalled()
+ read.mockRestore()
+ uploadImage.mockResolvedValueOnce({ id: 'retried-image', name: 'icon.gif', size: 6 })
+ await user.click(confirm)
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ client.clear()
+})
+
+it.each([undefined, null])(
+ 'resolves a missing emoji background only when confirmed (%s)',
+ async (background) => {
+ const user = userEvent.setup()
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ const onConfirm = vi.fn()
+ render(
+ <QueryClientProvider client={client}>
+ <IconPickerDialog
+ open
+ defaultValue={{ type: 'emoji', icon: '😀', background }}
+ onConfirm={onConfirm}
+ onOpenChange={() => {}}
+ />
+ </QueryClientProvider>,
+ )
+ expect(onConfirm).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith({
+ type: 'emoji',
+ icon: '😀',
+ background: '#FEF3F2',
+ })
+ client.clear()
+ },
+)
+
+it('keeps open-session edits and reads the latest default when reopened', async () => {
+ const user = userEvent.setup()
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ const onConfirm = vi.fn()
+ const picker = (open: boolean, defaultValue: IconPickerDefaultValue) => (
+ <QueryClientProvider client={client}>
+ <IconPickerDialog
+ open={open}
+ defaultValue={defaultValue}
+ onConfirm={onConfirm}
+ onOpenChange={() => {}}
+ />
+ </QueryClientProvider>
+ )
+ const view = render(picker(true, { type: 'emoji', icon: '😀', background: '#FEF3F2' }))
+ await user.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
+ const nextDefault = { type: 'image' as const, fileId: 'new-image', url: '/new-image.png' }
+ view.rerender(picker(true, nextDefault))
+ await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
+ expect(onConfirm).toHaveBeenLastCalledWith({ type: 'emoji', icon: '😀', background: '#F3FEE7' })
+ view.rerender(picker(false, nextDefault))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ view.rerender(picker(true, nextDefault))
+ await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
+ expect(onConfirm).toHaveBeenLastCalledWith(nextDefault)
+ expect(uploadImage).not.toHaveBeenCalled()
+ client.clear()
+})
+
+it.each(['upload', 'preview'])(
+ 'clears a %s error when replacing the image and uploads the replacement',
+ async (failure) => {
+ const read = vi.spyOn(FileReader.prototype, 'readAsDataURL')
+ if (failure === 'upload') uploadImage.mockRejectedValueOnce(new Error('Upload failed'))
+ else
+ read.mockImplementationOnce(function (this: FileReader) {
+ this.dispatchEvent(new Event('error'))
+ })
+ const { user, client, confirm, onConfirm } = await selectImage()
+ await user.click(confirm)
+ await screen.findByRole('alert')
+ read.mockRestore()
+ await user.click(screen.getByRole('button', { name: 'common.operation.change' }))
+ const replacement = new File(['GIF89a-replacement'], 'replacement.gif', { type: 'image/gif' })
+ await user.upload(screen.getByTestId('image-input'), replacement)
+ await waitFor(() => expect(screen.queryByRole('alert')).not.toBeInTheDocument())
+ uploadImage.mockResolvedValueOnce({
+ id: 'replacement',
+ name: 'replacement.gif',
+ size: replacement.size,
+ })
+ await user.click(await screen.findByRole('button', { name: 'app.iconPicker.ok' }))
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ expect(uploadImage.mock.lastCall![0].body.file).toBe(replacement)
+ expect(onConfirm).toHaveBeenCalledWith(expect.objectContaining({ fileId: 'replacement' }))
+ client.clear()
+ },
+)
+
+it('blocks replacement by browsing or dropping while uploading and restores editing on failure', async () => {
+ let rejectUpload!: (reason: Error) => void
+ uploadImage.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ rejectUpload = reject
+ }),
+ )
+ const { user, client, confirm, file, onConfirm } = await selectImage()
+ await user.click(confirm)
+ await waitFor(() => expect(uploadImage).toHaveBeenCalledOnce())
+ const change = screen.getByRole('button', { name: 'common.operation.change' })
+ const input = screen.getByTestId('image-input')
+ expect(change).toBeDisabled()
+ expect(input).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'app.iconPicker.cancel' })).toBeEnabled()
+ const replacement = new File(['GIF89a-replacement'], 'replacement.gif', { type: 'image/gif' })
+ await user.click(change)
+ await user.upload(input, replacement)
+ fireEvent.drop(screen.getByRole('img', { name: 'app.iconPicker.image' }), {
+ dataTransfer: { types: ['Files'], files: [replacement] },
+ })
+ await act(async () => {
+ rejectUpload(new Error('Upload failed'))
+ })
+ await screen.findByRole('alert')
+ expect(change).toBeEnabled()
+ expect(input).toBeEnabled()
+ uploadImage.mockResolvedValueOnce({ id: 'original', name: file.name, size: file.size })
+ await user.click(confirm)
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ expect(uploadImage.mock.calls[1]![0].body.file).toBe(file)
+ client.clear()
+})
+
+it('replaces an existing image only after selecting a file and confirms the new upload', async () => {
+ const previous = { type: 'image' as const, fileId: 'existing', url: '/existing.png' }
+ uploadImage.mockResolvedValueOnce({ id: 'replacement', name: 'icon.gif', size: 6 })
+ const { user, client, file, confirm, onConfirm } = await selectImage(previous)
+ expect(screen.getByRole('img', { name: 'app.iconPicker.image' })).not.toHaveAttribute(
+ 'src',
+ previous.url,
+ )
+ expect(onConfirm).not.toHaveBeenCalled()
+ await user.click(confirm)
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ expect(uploadImage.mock.calls[0]![0].body.file).toBe(file)
+ expect(onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'image', fileId: 'replacement' }),
+ )
+ client.clear()
+})
diff --git a/web/app/components/base/app-icon-picker/__tests__/utils.spec.ts b/web/app/components/base/icon-picker/__tests__/image-crop.spec.ts
similarity index 99%
rename from web/app/components/base/app-icon-picker/__tests__/utils.spec.ts
rename to web/app/components/base/icon-picker/__tests__/image-crop.spec.ts
index 55dd2f5db2b..ad5a72af29c 100644
--- a/web/app/components/base/app-icon-picker/__tests__/utils.spec.ts
+++ b/web/app/components/base/icon-picker/__tests__/image-crop.spec.ts
@@ -4,7 +4,7 @@ import getCroppedImg, {
getMimeType,
getRadianAngle,
rotateSize,
-} from '../utils'
+} from '../image-crop'
type ImageLoadEventType = 'load' | 'error'
diff --git a/web/app/components/base/app-icon-picker/__tests__/ImageInput.spec.tsx b/web/app/components/base/icon-picker/__tests__/image-input.spec.tsx
similarity index 54%
rename from web/app/components/base/app-icon-picker/__tests__/ImageInput.spec.tsx
rename to web/app/components/base/icon-picker/__tests__/image-input.spec.tsx
index 875eadf47f1..1be92512085 100644
--- a/web/app/components/base/app-icon-picker/__tests__/ImageInput.spec.tsx
+++ b/web/app/components/base/icon-picker/__tests__/image-input.spec.tsx
@@ -1,5 +1,5 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
-import ImageInput from '../ImageInput'
+import { createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { ImageIconInput as ImageInput } from '../image-input'
const createObjectURLMock = vi.fn(() => 'blob:mock-url')
const revokeObjectURLMock = vi.fn()
@@ -67,9 +67,9 @@ describe('ImageInput', () => {
expect(screen.queryByText(/browse/i)).not.toBeInTheDocument()
})
- it('should call onImageInput with cropped data when crop completes on static image', async () => {
- const onImageInput = vi.fn()
- render(<ImageInput onImageInput={onImageInput} />)
+ it('should call onChange with cropped data when crop completes on static image', async () => {
+ const onChange = vi.fn()
+ render(<ImageInput onChange={onChange} />)
const file = new File(['image-data'], 'photo.png', { type: 'image/png' })
const input = screen.getByTestId('image-input')
@@ -77,24 +77,27 @@ describe('ImageInput', () => {
await loadCropperImage()
+ expect(screen.getByRole('group', { name: 'app.iconPicker.crop' })).toBeInTheDocument()
+ expect(screen.getByRole('slider', { name: 'app.iconPicker.zoom' })).toBeInTheDocument()
+
await waitFor(() => {
- expect(onImageInput).toHaveBeenCalledWith(
- true,
- 'blob:mock-url',
- expect.objectContaining({
+ expect(onChange).toHaveBeenCalledWith({
+ type: 'crop',
+ url: 'blob:mock-url',
+ area: expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
width: expect.any(Number),
height: expect.any(Number),
}),
- 'photo.png',
- )
+ fileName: 'photo.png',
+ })
})
})
- it('should show img tag and call onImageInput with isCropped=false for animated GIF', async () => {
- const onImageInput = vi.fn()
- render(<ImageInput onImageInput={onImageInput} />)
+ it('should show img tag and call onChange with isCropped=false for animated GIF', async () => {
+ const onChange = vi.fn()
+ render(<ImageInput onChange={onChange} />)
const gifBytes = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61])
const file = new File([gifBytes], 'anim.gif', { type: 'image/gif' })
@@ -109,21 +112,82 @@ describe('ImageInput', () => {
// Cropper should NOT be shown
expect(screen.queryByTestId('container')).not.toBeInTheDocument()
- expect(onImageInput).toHaveBeenCalledWith(false, file)
+ expect(onChange).toHaveBeenCalledWith({ type: 'file', file })
})
- it('should reset file input value on click', () => {
+ it('should reset file input value after selection', () => {
render(<ImageInput />)
const input = screen.getByTestId('image-input') as HTMLInputElement
// Simulate previous value
Object.defineProperty(input, 'value', { writable: true, value: 'old-file.png' })
- fireEvent.click(input)
+ fireEvent.change(input, { target: { files: [] } })
expect(input.value).toBe('')
})
})
describe('Drag and Drop', () => {
+ it('accepts file drag gestures on nested content without consuming text drags', async () => {
+ const onDragEnter = vi.fn()
+ const onDragOver = vi.fn()
+ const onDragLeave = vi.fn()
+ render(
+ <div onDragEnter={onDragEnter} onDragOver={onDragOver} onDragLeave={onDragLeave}>
+ <ImageInput />
+ </div>,
+ )
+ const target = screen.getByRole('button', { name: /browse/i })
+ const fileTransfer = {
+ types: ['Files'],
+ files: [new File(['image'], 'photo.png', { type: 'image/png' })],
+ dropEffect: 'none',
+ }
+ for (const dataTransfer of [{ types: ['text/plain'], files: [] }, fileTransfer]) {
+ for (const createDragEvent of [
+ createEvent.dragEnter,
+ createEvent.dragOver,
+ createEvent.dragLeave,
+ ]) {
+ const event = createDragEvent(target, { dataTransfer })
+ fireEvent(target, event)
+ expect(event.defaultPrevented).toBe(dataTransfer === fileTransfer && event.cancelable)
+ if (event.type === 'dragover' && dataTransfer === fileTransfer)
+ expect((event as DragEvent).dataTransfer?.dropEffect).toBe('copy')
+ }
+ }
+ expect(onDragEnter).toHaveBeenCalledOnce()
+ expect(onDragOver).toHaveBeenCalledOnce()
+ expect(onDragLeave).toHaveBeenCalledOnce()
+ fireEvent.drop(target, { dataTransfer: fileTransfer })
+ await waitForCropperContainer()
+ })
+
+ it('consumes file drops inside the picker but leaves text drops to the parent', async () => {
+ const onDrop = vi.fn()
+ render(
+ <div onDrop={onDrop}>
+ <ImageInput />
+ </div>,
+ )
+ const target = screen.getByRole('button', { name: /browse/i })
+ const textDrop = createEvent.drop(target, {
+ dataTransfer: { types: ['text/plain'], files: [] },
+ })
+ fireEvent(target, textDrop)
+ expect(textDrop.defaultPrevented).toBe(false)
+ expect(onDrop).toHaveBeenCalledOnce()
+ const fileDrop = createEvent.drop(target, {
+ dataTransfer: {
+ types: ['Files'],
+ files: [new File(['image'], 'photo.png', { type: 'image/png' })],
+ },
+ })
+ fireEvent(target, fileDrop)
+ expect(fileDrop.defaultPrevented).toBe(true)
+ expect(onDrop).toHaveBeenCalledOnce()
+ await waitForCropperContainer()
+ })
+
it('should show image after dropping a file', async () => {
render(<ImageInput />)
@@ -133,7 +197,7 @@ describe('ImageInput', () => {
const file = new File(['image-data'], 'dropped.png', { type: 'image/png' })
fireEvent.drop(dropZone, {
- dataTransfer: { files: [file] },
+ dataTransfer: { files: [file], types: ['Files'] },
})
await waitForCropperContainer()
@@ -163,6 +227,19 @@ describe('ImageInput', () => {
})
describe('Edge Cases', () => {
+ it('invalidates an unreadable image and makes a replacement available', async () => {
+ const onChange = vi.fn()
+ render(<ImageInput onChange={onChange} />)
+ fireEvent.change(screen.getByTestId('image-input'), {
+ target: { files: [new File(['broken'], 'photo.png', { type: 'image/png' })] },
+ })
+ await waitForCropperContainer()
+ fireEvent.error(screen.getByTestId('container').querySelector('img')!)
+ expect(onChange).toHaveBeenLastCalledWith(null)
+ expect(screen.getByRole('alert').textContent).toMatch(/ReadError/)
+ expect(screen.getByRole('button', { name: /browse/i })).toBeInTheDocument()
+ })
+
it('should accept the correct file extensions', () => {
render(<ImageInput />)
diff --git a/web/app/components/base/icon-picker/__tests__/picker.browser.spec.tsx b/web/app/components/base/icon-picker/__tests__/picker.browser.spec.tsx
new file mode 100644
index 00000000000..bd110a07634
--- /dev/null
+++ b/web/app/components/base/icon-picker/__tests__/picker.browser.spec.tsx
@@ -0,0 +1,287 @@
+import type { PostFilesUploadResponse } from '@dify/contracts/api/console/files/types.gen'
+import type { EmojiIcon } from '..'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { useState } from 'react'
+import { page, userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { IconPickerDialog } from '..'
+import { emojiCatalogOptions } from '../emoji-data'
+
+const { uploadImage } = vi.hoisted(() => ({
+ uploadImage: vi.fn<() => Promise<PostFilesUploadResponse>>(),
+}))
+
+vi.mock('@/service/console', () => ({
+ consoleQuery: {
+ files: { upload: { post: { mutationOptions: () => ({ mutationFn: uploadImage }) } } },
+ },
+}))
+
+vi.mock('@/next/navigation', () => ({ useParams: () => ({}) }))
+
+const emojis = [
+ '😀',
+ '😃',
+ '😄',
+ '😁',
+ '😆',
+ '😅',
+ '😂',
+ '🤣',
+ '🥲',
+ '☺️',
+ '😊',
+ '😇',
+ '🙂',
+ '😍',
+ '😘',
+ '😙',
+ '😝',
+ '🤪',
+ '🤓',
+ '😎',
+]
+const initial: EmojiIcon = { type: 'emoji', icon: '😀', background: '#FEF3F2' }
+
+function Harness() {
+ const [open, setOpen] = useState(false)
+ const [value, setValue] = useState(initial)
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>
+ Choose
+ </button>
+ <output aria-label="Saved icon">{value.icon}</output>
+ <IconPickerDialog
+ open={open}
+ onOpenChange={setOpen}
+ defaultValue={value}
+ onConfirm={(next) => {
+ if (next.type === 'emoji') setValue(next)
+ }}
+ />
+ </>
+ )
+}
+
+it('navigates a visible candidate after filtering, confirms with Enter, and discards cancelled drafts', async () => {
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [
+ {
+ id: 'faces',
+ label: 'Faces',
+ items: emojis.map((emoji, index) => ({ emoji, label: `Face ${index}`, version: 1 })),
+ },
+ ])
+ await render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ )
+ await page.getByRole('button', { name: 'Choose', exact: true }).click()
+ await expect.element(page.getByRole('dialog', { name: 'app.iconPicker.title' })).toBeVisible()
+ await expect.element(page.getByRole('tabpanel', { name: 'app.iconPicker.emoji' })).toBeVisible()
+ await expect
+ .element(page.getByRole('radiogroup', { name: 'app.iconPicker.chooseStyle' }))
+ .toBeVisible()
+ const input = page.getByRole('combobox', { name: 'app.iconPicker.search' })
+ await expect.element(input).toHaveFocus()
+ const clear = page.getByRole('button', { name: 'app.iconPicker.clearSearch' })
+ await expect.element(clear).not.toBeInTheDocument()
+ const unfilteredCount = page.getByRole('gridcell').all().length
+ await input.fill('Face')
+ await expect.poll(() => page.getByRole('gridcell').all().length).toBe(20)
+ await userEvent.keyboard('{ArrowDown}{ArrowRight}')
+ const activeId = input.element().getAttribute('aria-activedescendant')!
+ const active = document.getElementById(activeId)!
+ expect(active).not.toBeNull()
+ const style = getComputedStyle(active)
+ const inactive = page
+ .getByRole('gridcell')
+ .all()
+ .find((cell) => cell.element() !== active)!
+ expect(style.backgroundColor).not.toBe(getComputedStyle(inactive.element()).backgroundColor)
+ const keyboardBackground = style.backgroundColor
+ await inactive.hover()
+ await expect.element(input).toHaveAttribute('aria-activedescendant', inactive.element().id)
+ expect(getComputedStyle(inactive.element()).backgroundColor).toBe(keyboardBackground)
+ expect(document.querySelectorAll('[role="gridcell"][data-highlighted]')).toHaveLength(1)
+ await userEvent.keyboard('{ArrowDown}')
+ const keyboardCandidate = document.getElementById(
+ input.element().getAttribute('aria-activedescendant')!,
+ )!
+ expect(keyboardCandidate).not.toBe(inactive.element())
+ expect(getComputedStyle(keyboardCandidate).backgroundColor).toBe(keyboardBackground)
+ expect(getComputedStyle(inactive.element()).backgroundColor).toBe('rgba(0, 0, 0, 0)')
+ const chosen = keyboardCandidate.textContent!
+ await userEvent.keyboard('{Enter}')
+ await expect.element(input).toHaveValue('Face')
+ const green = page.getByRole('radio', { name: 'app.iconPicker.color.green' })
+ await expect.element(green).toHaveTextContent(chosen)
+ await green.click()
+ await input.fill('Face 0')
+ await expect.poll(() => page.getByRole('gridcell').all().length).toBe(1)
+ await userEvent.keyboard('{Enter}')
+ const finalEmoji = '😀'
+ await expect.element(green).toBeChecked()
+ await clear.click()
+ await expect.element(input).toHaveValue('')
+ await expect.element(input).toHaveFocus()
+ await expect.element(clear).not.toBeInTheDocument()
+ await expect.poll(() => page.getByRole('gridcell').all().length).toBe(unfilteredCount)
+ await expect.element(green).toBeChecked()
+ await page.getByRole('button', { name: 'app.iconPicker.ok' }).click()
+ await expect
+ .element(page.getByRole('status', { name: 'Saved icon' }))
+ .toHaveTextContent(finalEmoji)
+ const trigger = page.getByRole('button', { name: 'Choose', exact: true })
+ await expect.element(trigger).toHaveFocus()
+ await trigger.click()
+ await expect.element(input).toHaveValue('')
+ await page.getByRole('button', { name: 'app.iconPicker.tryYourLuck' }).click()
+ await userEvent.keyboard('{Escape}')
+ await expect.element(page.getByRole('dialog')).not.toBeInTheDocument()
+ await expect.element(trigger).toHaveFocus()
+ await expect
+ .element(page.getByRole('status', { name: 'Saved icon' }))
+ .toHaveTextContent(finalEmoji)
+ await trigger.click()
+ await expect
+ .element(page.getByRole('radio', { name: 'app.iconPicker.color.green' }))
+ .toBeChecked()
+ client.clear()
+})
+
+it('focuses the visible image action when reopening an existing image icon', async () => {
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ await render(
+ <QueryClientProvider client={client}>
+ <IconPickerDialog
+ open
+ defaultValue={{
+ type: 'image',
+ fileId: 'image-id',
+ url: 'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>',
+ }}
+ onOpenChange={() => {}}
+ onConfirm={() => {}}
+ />
+ </QueryClientProvider>,
+ )
+ await expect
+ .element(page.getByRole('tab', { name: 'app.iconPicker.image' }))
+ .toHaveAttribute('aria-selected', 'true')
+ await expect.element(page.getByRole('button', { name: 'common.operation.change' })).toHaveFocus()
+ client.clear()
+})
+
+it.each(['light', 'dark'])(
+ 'distinguishes keyboard focus from the selected color in %s mode',
+ async (theme) => {
+ document.documentElement.dataset.theme = theme
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ try {
+ await render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ )
+ await page.getByRole('button', { name: 'Choose', exact: true }).click()
+ const red = page.getByRole('radio', { name: 'app.iconPicker.color.red' })
+ const rose = page.getByRole('radio', { name: 'app.iconPicker.color.rose' })
+ await expect.element(red).toBeChecked()
+ expect(getComputedStyle(red.element()).outlineStyle).toBe('none')
+
+ await userEvent.tab()
+ await expect.element(red).toHaveFocus()
+ expect(getComputedStyle(red.element()).outlineStyle).toBe('solid')
+ expect(Number.parseFloat(getComputedStyle(red.element()).outlineWidth)).toBeGreaterThan(0)
+
+ await userEvent.keyboard('{ArrowRight}')
+ await expect.element(rose).toHaveFocus()
+ await expect.element(rose).toBeChecked()
+ expect(getComputedStyle(rose.element()).outlineStyle).toBe('solid')
+ expect(getComputedStyle(red.element()).outlineStyle).toBe('none')
+
+ await userEvent.tab()
+ await expect
+ .element(page.getByRole('button', { name: 'app.iconPicker.tryYourLuck' }))
+ .toHaveFocus()
+ await expect.element(rose).toBeChecked()
+ expect(getComputedStyle(rose.element()).outlineStyle).toBe('none')
+ } finally {
+ document.documentElement.dataset.theme = 'light'
+ client.clear()
+ }
+ },
+)
+
+it('discards the cancelled draft when reopened immediately from the keyboard', async () => {
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ await render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ )
+ await page.getByRole('button', { name: 'Choose', exact: true }).click()
+ await page.getByRole('radio', { name: 'app.iconPicker.color.green' }).click()
+ await userEvent.keyboard('{Escape}{Enter}')
+ await expect.element(page.getByRole('dialog', { name: 'app.iconPicker.title' })).toBeVisible()
+ await expect.element(page.getByRole('radio', { name: 'app.iconPicker.color.red' })).toBeChecked()
+ client.clear()
+})
+
+it('locks image editing during submission and restores it after failure', async () => {
+ let rejectUpload!: (reason: Error) => void
+ uploadImage.mockReturnValueOnce(
+ new Promise((_, reject) => {
+ rejectUpload = reject
+ }),
+ )
+ const client = new QueryClient()
+ client.setQueryData(emojiCatalogOptions.queryKey, [])
+ await render(
+ <QueryClientProvider client={client}>
+ <Harness />
+ </QueryClientProvider>,
+ )
+ await page.getByRole('button', { name: 'Choose', exact: true }).click()
+ await page.getByRole('tab', { name: 'app.iconPicker.image' }).click()
+ const canvas = document.createElement('canvas')
+ canvas.width = 100
+ canvas.height = 100
+ canvas.getContext('2d')!.fillRect(0, 0, 100, 100)
+ const blob = await new Promise<Blob>((resolve) =>
+ canvas.toBlob((value) => resolve(value!), 'image/png'),
+ )
+ await page.getByTestId('image-input').upload(new File([blob], 'icon.png', { type: 'image/png' }))
+ const crop = page.getByRole('group', { name: 'app.iconPicker.crop' })
+ await expect.element(crop).toBeVisible()
+ const cropElement = crop.element() as HTMLElement
+ cropElement.focus()
+ await expect.element(crop).toHaveFocus()
+ const zoom = page.getByRole('slider', { name: 'app.iconPicker.zoom' })
+ const change = page.getByRole('button', { name: 'common.operation.change' })
+ await page.getByRole('button', { name: 'app.iconPicker.ok' }).click()
+ await expect.poll(() => uploadImage.mock.calls.length).toBe(1)
+ await expect.element(zoom).toBeDisabled()
+ await expect.element(change).toBeDisabled()
+ cropElement.focus()
+ expect(document.activeElement).not.toBe(cropElement)
+ const cancel = page.getByRole('button', { name: 'app.iconPicker.cancel' })
+ await expect.element(cancel).toBeEnabled()
+ rejectUpload(new Error('Upload failed'))
+ await expect.element(page.getByRole('alert')).toBeVisible()
+ await expect.element(zoom).toBeEnabled()
+ await expect.element(change).toBeEnabled()
+ cropElement.focus()
+ await expect.element(crop).toHaveFocus()
+ await userEvent.tab()
+ await expect.element(zoom).toHaveFocus()
+ await userEvent.keyboard('{ArrowRight}')
+ await expect.element(page.getByRole('alert')).not.toBeInTheDocument()
+ client.clear()
+})
diff --git a/web/app/components/base/icon-picker/emoji-data.ts b/web/app/components/base/icon-picker/emoji-data.ts
new file mode 100644
index 00000000000..d31521f3a53
--- /dev/null
+++ b/web/app/components/base/icon-picker/emoji-data.ts
@@ -0,0 +1,70 @@
+import { queryOptions } from '@tanstack/react-query'
+import { basePath } from '@/utils/var'
+import { isEmojiSupported } from './emoji-support'
+
+export type Emoji = {
+ emoji: string
+ label: string
+ tags?: string[]
+ group?: number
+ subgroup?: number
+ version: number
+}
+
+type Messages = {
+ groups: { key: string; message: string; order: number }[]
+ subgroups: { key: string; order: number }[]
+}
+export type EmojiGroup = { id: string; label: string; items: Emoji[] }
+
+const catalogUrl = `${basePath}/emoji/emojibase-17.0.0/en`
+
+async function fetchJson<T>(file: string, signal: AbortSignal): Promise<T> {
+ const response = await fetch(`${catalogUrl}/${file}.json`, { signal })
+ if (!response.ok) throw new Error(`Unable to load emoji ${file}: ${response.status}`)
+ return response.json()
+}
+
+export const emojiCatalogOptions = queryOptions({
+ queryKey: ['emoji-catalog', catalogUrl],
+ staleTime: Infinity,
+ gcTime: Infinity,
+ queryFn: async ({ signal }) => {
+ const [emojis, messages] = await Promise.all([
+ fetchJson<Emoji[]>('data', signal),
+ fetchJson<Messages>('messages', signal),
+ ])
+ // Probe once per Unicode version, rather than reading pixels for every emoji.
+ const versions = new Map<number, string>()
+ for (const emoji of emojis) {
+ if (!versions.has(emoji.version)) versions.set(emoji.version, emoji.emoji)
+ }
+ const supportedVersion =
+ [...versions.keys()]
+ .sort((a, b) => b - a)
+ .find((version) => isEmojiSupported(versions.get(version)!)) ?? Infinity
+ const flagGroups = new Set(
+ messages.subgroups
+ .filter((group) => group.key === 'country-flag' || group.key === 'subdivision-flag')
+ .map((group) => group.order),
+ )
+ const supportsFlags = isEmojiSupported('🇪🇺')
+ const supportedEmojis = emojis.filter(
+ (emoji) =>
+ emoji.version <= supportedVersion &&
+ (supportsFlags || emoji.subgroup === undefined || !flagGroups.has(emoji.subgroup)),
+ )
+ return messages.groups
+ .filter((group) => group.key !== 'component')
+ .map((group) => ({
+ id: group.key,
+ label: group.message.charAt(0).toUpperCase() + group.message.slice(1),
+ items: supportedEmojis
+ .filter((emoji) => emoji.group === group.order)
+ .map((emoji) => ({
+ ...emoji,
+ label: emoji.label.charAt(0).toUpperCase() + emoji.label.slice(1),
+ })),
+ }))
+ },
+})
diff --git a/web/app/components/base/icon-picker/emoji-icon-editor.tsx b/web/app/components/base/icon-picker/emoji-icon-editor.tsx
new file mode 100644
index 00000000000..2154fe44989
--- /dev/null
+++ b/web/app/components/base/icon-picker/emoji-icon-editor.tsx
@@ -0,0 +1,63 @@
+import type { Ref } from 'react'
+import type { EmojiIcon } from '.'
+import { cn } from '@langgenius/dify-ui/cn'
+import { RadioGroup, RadioItem } from '@langgenius/dify-ui/radio-group'
+import { useId } from 'react'
+import { useTranslation } from 'react-i18next'
+import { EmojiPicker } from './emoji-picker'
+import { emojiStyles } from './emoji-styles'
+
+export function EmojiIconEditor({
+ value,
+ inputRef,
+ onEmojiChange,
+ onBackgroundChange,
+}: {
+ inputRef?: Ref<HTMLInputElement>
+ value?: EmojiIcon
+ onEmojiChange: (icon: string) => void
+ onBackgroundChange: (background: string) => void
+}) {
+ const { t } = useTranslation(['app'])
+ const labelId = useId()
+ return (
+ <>
+ <EmojiPicker ref={inputRef} value={value?.icon} onValueChange={onEmojiChange} />
+ {value && (
+ <section className="shrink-0 border-t border-divider-subtle bg-components-panel-bg-blur px-3 pt-2 pb-3 backdrop-blur-sm">
+ <h3 id={labelId} className="px-0.5 py-1 system-xs-semibold-uppercase text-text-primary">
+ {t(($) => $['iconPicker.chooseStyle'], { ns: 'app' })}
+ </h3>
+ <RadioGroup
+ aria-labelledby={labelId}
+ value={value.background.toUpperCase()}
+ onValueChange={onBackgroundChange}
+ className="grid grid-cols-6 justify-items-center gap-0.75 pt-0.5"
+ >
+ {emojiStyles.map((style) => (
+ <RadioItem
+ key={style.background}
+ value={style.background}
+ aria-label={t(($) => $[style.label], { ns: 'app' })}
+ className={cn(
+ 'flex aspect-square w-full max-w-11.5 items-center justify-center rounded-xl p-0.75 outline-none ring-inset hover:bg-state-base-hover focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-state-accent-solid focus-visible:outline-solid data-checked:ring-[1.5px]',
+ style.selectedClassName,
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'flex aspect-square w-full items-center justify-center rounded-[10px] border-[0.5px] border-divider-regular text-2xl leading-none',
+ style.backgroundClassName,
+ )}
+ >
+ {value.icon}
+ </span>
+ </RadioItem>
+ ))}
+ </RadioGroup>
+ </section>
+ )}
+ </>
+ )
+}
diff --git a/web/app/components/base/icon-picker/emoji-picker.tsx b/web/app/components/base/icon-picker/emoji-picker.tsx
new file mode 100644
index 00000000000..ef18caef144
--- /dev/null
+++ b/web/app/components/base/icon-picker/emoji-picker.tsx
@@ -0,0 +1,256 @@
+'use client'
+
+import type { Ref } from 'react'
+import type { Emoji, EmojiGroup } from './emoji-data'
+import {
+ Autocomplete,
+ AutocompleteClear,
+ AutocompleteEmpty,
+ AutocompleteGroup,
+ AutocompleteGroupLabel,
+ AutocompleteInput,
+ AutocompleteInputGroup,
+ AutocompleteItem,
+ AutocompleteList,
+ AutocompleteRow,
+ AutocompleteStatus,
+} from '@langgenius/dify-ui/autocomplete'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { useQuery } from '@tanstack/react-query'
+import { memo, useDeferredValue, useMemo, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { emojiCatalogOptions } from './emoji-data'
+import { recommendedEmojis } from './emoji-styles'
+import { useRecentEmojisValue } from './recent-emojis'
+
+export type EmojiPickerProps = {
+ ref?: Ref<HTMLInputElement>
+ value?: string
+ onValueChange: (emoji: string) => void
+ className?: string
+}
+
+const columns = 9
+const emptyGroups: EmojiGroup[] = []
+const itemToString = (item: Emoji) => item.label
+
+type IndexedGroup = EmojiGroup & { startIndex: number }
+
+const EmojiGridRow = memo(
+ ({
+ items,
+ startIndex,
+ currentEmoji,
+ onValueChange,
+ }: {
+ items: Emoji[]
+ startIndex: number
+ currentEmoji?: string
+ onValueChange: (emoji: string) => void
+ }) => (
+ <AutocompleteRow className="grid grid-cols-9 gap-px px-3 pb-px">
+ {items.map((item, column) => (
+ <AutocompleteItem
+ key={item.emoji}
+ index={startIndex + column}
+ value={item}
+ aria-label={item.label}
+ onClick={() => onValueChange(item.emoji)}
+ className={cn(
+ currentEmoji === item.emoji &&
+ 'ring-[1.5px] ring-components-option-card-option-selected-border ring-inset',
+ 'm-0 flex size-8 min-h-0 items-center justify-center rounded-lg p-0 text-2xl leading-none data-highlighted:bg-state-base-hover-alt',
+ )}
+ >
+ <span aria-hidden="true">{item.emoji}</span>
+ </AutocompleteItem>
+ ))}
+ </AutocompleteRow>
+ ),
+)
+
+const EmojiList = memo(
+ ({
+ groups,
+ value,
+ onValueChange,
+ label,
+ }: {
+ groups: IndexedGroup[]
+ value?: string
+ onValueChange: (emoji: string) => void
+ label: string
+ }) => {
+ const rowGroups = useMemo(
+ () =>
+ groups.map((group) => ({
+ ...group,
+ rows: Array.from({ length: Math.ceil(group.items.length / columns) }, (_, row) => ({
+ items: group.items.slice(row * columns, (row + 1) * columns),
+ startIndex: group.startIndex + row * columns,
+ })),
+ })),
+ [groups],
+ )
+ return (
+ <AutocompleteList aria-label={label} className="max-h-none min-h-0 flex-1 scroll-py-8 p-0">
+ {rowGroups.map((group) => (
+ <AutocompleteGroup key={group.id} items={group.items} className="mb-2 first:mt-2">
+ <AutocompleteGroupLabel className="sticky top-0 z-1 mb-0.5 bg-components-panel-bg px-3.5 py-1 system-xs-medium-uppercase text-text-tertiary">
+ {group.label}
+ </AutocompleteGroupLabel>
+ {group.rows.map((row) => (
+ <EmojiGridRow
+ key={row.startIndex}
+ items={row.items}
+ startIndex={row.startIndex}
+ currentEmoji={row.items.some((item) => item.emoji === value) ? value : undefined}
+ onValueChange={onValueChange}
+ />
+ ))}
+ </AutocompleteGroup>
+ ))}
+ </AutocompleteList>
+ )
+ },
+)
+
+/** Search is transient; choosing a candidate changes the caller's value, never the query. */
+export const EmojiPicker = memo(({ value, onValueChange, className, ref }: EmojiPickerProps) => {
+ const { t } = useTranslation(['app', 'common'])
+ const [search, setSearch] = useState('')
+ const deferredSearch = useDeferredValue(search)
+ const recent = useRecentEmojisValue()
+ const catalog = useQuery(emojiCatalogOptions)
+ const categories = catalog.data ?? emptyGroups
+ const groups = useMemo(() => {
+ const byEmoji = new Map(
+ categories.flatMap((group) => group.items.map((item) => [item.emoji, item] as const)),
+ )
+ const toItems = (values: string[]) =>
+ values.flatMap((emoji) => {
+ const item = byEmoji.get(emoji)
+ return item ? [{ ...item }] : []
+ })
+ return [
+ {
+ id: 'recent',
+ label: t(($) => $['iconPicker.recent'], { ns: 'app' }),
+ items: toItems(recent),
+ },
+ {
+ id: 'recommended',
+ label: t(($) => $['iconPicker.recommend'], { ns: 'app' }),
+ items: toItems(recommendedEmojis),
+ },
+ ...categories,
+ ].filter((group) => group.items.length)
+ }, [categories, recent, t])
+ const searchIndex = useMemo(
+ () =>
+ new Map(
+ categories.flatMap((group) =>
+ group.items.map(
+ (item) =>
+ [
+ item.emoji,
+ `${item.emoji} ${item.label} ${item.tags?.join(' ') ?? ''}`.toLocaleLowerCase('en'),
+ ] as const,
+ ),
+ ),
+ ),
+ [categories],
+ )
+ const filteredGroups = useMemo(() => {
+ const query = deferredSearch.trim().toLocaleLowerCase('en')
+ const filtered = query
+ ? categories
+ .map((group) => ({
+ ...group,
+ items: group.items.filter((item) => searchIndex.get(item.emoji)?.includes(query)),
+ }))
+ .filter((group) => group.items.length)
+ : groups
+ let startIndex = 0
+ return filtered.map((group) => {
+ const result = { ...group, startIndex }
+ startIndex += group.items.length
+ return result
+ })
+ }, [categories, deferredSearch, groups, searchIndex])
+
+ return (
+ <Autocomplete
+ inline
+ open
+ grid
+ autoHighlight
+ items={groups}
+ value={search}
+ onValueChange={(next, details) => {
+ if (details.reason !== 'item-press') setSearch(next)
+ }}
+ filteredItems={filteredGroups}
+ filter={null}
+ itemToStringValue={itemToString}
+ >
+ <div className={cn('flex min-h-0 flex-1 flex-col', className)}>
+ <div className="shrink-0 border-b border-divider-subtle px-3 pb-2">
+ <AutocompleteInputGroup>
+ <span
+ className="ms-2 i-ri-search-line size-4 shrink-0 text-components-input-text-placeholder"
+ aria-hidden="true"
+ />
+ <AutocompleteInput
+ ref={ref}
+ aria-label={t(($) => $['iconPicker.search'], { ns: 'app' })}
+ placeholder={t(($) => $['iconPicker.search'], { ns: 'app' })}
+ className="ps-1.5"
+ />
+ <AutocompleteClear aria-label={t(($) => $['iconPicker.clearSearch'], { ns: 'app' })} />
+ </AutocompleteInputGroup>
+ </div>
+ <output className="sr-only">
+ {value
+ ? t(($) => $['iconPicker.currentEmoji'], {
+ ns: 'app',
+ emoji:
+ categories.flatMap((group) => group.items).find((item) => item.emoji === value)
+ ?.label ?? value,
+ })
+ : null}
+ </output>
+ <AutocompleteStatus className="sr-only">
+ {catalog.isPending
+ ? t(($) => $.loading, { ns: 'common' })
+ : catalog.isError
+ ? t(($) => $.error, { ns: 'common' })
+ : null}
+ </AutocompleteStatus>
+ {catalog.isError && (
+ <div className="p-3">
+ <p>{t(($) => $.error, { ns: 'common' })}</p>
+ <Button onClick={() => void catalog.refetch()}>
+ {t(($) => $['errorBoundary.tryAgain'], { ns: 'common' })}
+ </Button>
+ </div>
+ )}
+ {catalog.isPending && (
+ <div className="p-3 text-text-tertiary">{t(($) => $.loading, { ns: 'common' })}</div>
+ )}
+ {!catalog.isPending && !catalog.isError && (
+ <AutocompleteEmpty className="p-3 text-text-tertiary">
+ {t(($) => $.noData, { ns: 'common' })}
+ </AutocompleteEmpty>
+ )}
+ <EmojiList
+ groups={filteredGroups}
+ value={value}
+ onValueChange={onValueChange}
+ label={t(($) => $['iconPicker.emoji'], { ns: 'app' })}
+ />
+ </div>
+ </Autocomplete>
+ )
+})
diff --git a/web/app/components/base/emoji-picker/constants.ts b/web/app/components/base/icon-picker/emoji-styles.ts
similarity index 83%
rename from web/app/components/base/emoji-picker/constants.ts
rename to web/app/components/base/icon-picker/emoji-styles.ts
index 7794604b79f..5d21e2ac780 100644
--- a/web/app/components/base/emoji-picker/constants.ts
+++ b/web/app/components/base/icon-picker/emoji-styles.ts
@@ -1,61 +1,73 @@
export const emojiStyles = [
{
background: '#FEF3F2',
+ label: 'iconPicker.color.red' as const,
backgroundClassName: 'bg-components-icon-bg-red-soft',
selectedClassName: 'ring-util-colors-red-red-400',
},
{
background: '#FFF1F3',
+ label: 'iconPicker.color.rose' as const,
backgroundClassName: 'bg-components-icon-bg-rose-soft',
selectedClassName: 'ring-util-colors-rose-rose-400',
},
{
background: '#FDF2FA',
+ label: 'iconPicker.color.pink' as const,
backgroundClassName: 'bg-components-icon-bg-pink-soft',
selectedClassName: 'ring-util-colors-pink-pink-400',
},
{
background: '#FFF4ED',
+ label: 'iconPicker.color.orange' as const,
backgroundClassName: 'bg-components-icon-bg-orange-dark-soft',
selectedClassName: 'ring-util-colors-orange-dark-orange-dark-400',
},
{
background: '#FEFBE8',
+ label: 'iconPicker.color.yellow' as const,
backgroundClassName: 'bg-components-icon-bg-yellow-soft',
selectedClassName: 'ring-util-colors-yellow-yellow-400',
},
{
background: '#F3FEE7',
+ label: 'iconPicker.color.green' as const,
backgroundClassName: 'bg-components-icon-bg-green-soft',
selectedClassName: 'ring-util-colors-green-green-400',
},
{
background: '#F0FDF9',
+ label: 'iconPicker.color.teal' as const,
backgroundClassName: 'bg-components-icon-bg-teal-soft',
selectedClassName: 'ring-util-colors-teal-teal-400',
},
{
background: '#F0F9FF',
+ label: 'iconPicker.color.lightBlue' as const,
backgroundClassName: 'bg-components-icon-bg-blue-light-soft',
selectedClassName: 'ring-util-colors-blue-light-blue-light-400',
},
{
background: '#E9F0FF',
+ label: 'iconPicker.color.blue' as const,
backgroundClassName: 'bg-components-icon-bg-blue-soft',
selectedClassName: 'ring-util-colors-blue-blue-400',
},
{
background: '#F5F3FF',
+ label: 'iconPicker.color.violet' as const,
backgroundClassName: 'bg-components-icon-bg-violet-soft',
selectedClassName: 'ring-util-colors-violet-violet-400',
},
{
background: '#EEF4FF',
+ label: 'iconPicker.color.indigo' as const,
backgroundClassName: 'bg-components-icon-bg-indigo-soft',
selectedClassName: 'ring-util-colors-indigo-indigo-400',
},
{
background: '#F0F2F5',
+ label: 'iconPicker.color.gray' as const,
backgroundClassName: 'bg-components-icon-bg-midnight-soft',
selectedClassName: 'ring-util-colors-midnight-midnight-400',
},
diff --git a/web/app/components/base/icon-picker/emoji-support.LICENSE b/web/app/components/base/icon-picker/emoji-support.LICENSE
new file mode 100644
index 00000000000..d3a8556a3ae
--- /dev/null
+++ b/web/app/components/base/icon-picker/emoji-support.LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Liveblocks
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/web/app/components/base/icon-picker/emoji-support.ts b/web/app/components/base/icon-picker/emoji-support.ts
new file mode 100644
index 00000000000..1743e8f0c4d
--- /dev/null
+++ b/web/app/components/base/icon-picker/emoji-support.ts
@@ -0,0 +1,59 @@
+// Adapted from Frimousse 0.3.0 (MIT). See emoji-support.LICENSE.
+const EMOJI_FONT_FAMILY = '"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif'
+
+const CANVAS_SIZE = 2
+
+let context: CanvasRenderingContext2D | null = null
+
+export function isEmojiSupported(emoji: string): boolean {
+ try {
+ context ??= document.createElement('canvas').getContext('2d', { willReadFrequently: true })
+ } catch {}
+
+ // Keep the catalog available when canvas rendering cannot be probed.
+ if (!context) {
+ return true
+ }
+
+ // Schedule to dispose of the context
+ queueMicrotask(() => {
+ if (context) {
+ context = null
+ }
+ })
+
+ context.canvas.width = CANVAS_SIZE
+ context.canvas.height = CANVAS_SIZE
+ context.font = `2px ${EMOJI_FONT_FAMILY}`
+ context.textBaseline = 'middle'
+
+ // Unsupported ZWJ sequence emojis show up as separate emojis
+ if (context.measureText(emoji).width >= CANVAS_SIZE * 2) {
+ return false
+ }
+
+ context.fillStyle = '#00f'
+ context.fillText(emoji, 0, 0)
+
+ const blue = context.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE).data
+
+ context.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE)
+
+ context.fillStyle = '#f00'
+ context.fillText(emoji, 0, 0)
+
+ const red = context.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE).data
+
+ // Emojis have an immutable color so they should look the same regardless of the text color
+ for (let i = 0; i < CANVAS_SIZE * CANVAS_SIZE * 4; i += 4) {
+ if (
+ blue[i] !== red[i] || // R
+ blue[i + 1] !== red[i + 1] || // G
+ blue[i + 2] !== red[i + 2] // B
+ ) {
+ return false
+ }
+ }
+
+ return true
+}
diff --git a/web/app/components/base/app-icon-picker/utils.ts b/web/app/components/base/icon-picker/image-crop.ts
similarity index 100%
rename from web/app/components/base/app-icon-picker/utils.ts
rename to web/app/components/base/icon-picker/image-crop.ts
diff --git a/web/app/components/base/icon-picker/image-input-drag.tsx b/web/app/components/base/icon-picker/image-input-drag.tsx
new file mode 100644
index 00000000000..faca49db6e7
--- /dev/null
+++ b/web/app/components/base/icon-picker/image-input-drag.tsx
@@ -0,0 +1,40 @@
+import type { DragEvent } from 'react'
+import { useRef, useState } from 'react'
+
+export function useImageDrop(onFile: (file: File) => void, disabled = false) {
+ const [isDragActive, setIsDragActive] = useState(false)
+ const depthRef = useRef(0)
+ const isFileDrag = (event: DragEvent) => event.dataTransfer.types.includes('Files')
+ return {
+ isDragActive: !disabled && isDragActive,
+ onDragEnter(event: DragEvent<HTMLDivElement>) {
+ if (!isFileDrag(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ depthRef.current += 1
+ setIsDragActive(!disabled)
+ },
+ onDragOver(event: DragEvent<HTMLDivElement>) {
+ if (!isFileDrag(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ event.dataTransfer.dropEffect = disabled ? 'none' : 'copy'
+ },
+ onDragLeave(event: DragEvent<HTMLDivElement>) {
+ if (!isFileDrag(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ depthRef.current = Math.max(0, depthRef.current - 1)
+ if (!depthRef.current) setIsDragActive(false)
+ },
+ onDrop(event: DragEvent<HTMLDivElement>) {
+ if (!isFileDrag(event)) return
+ event.preventDefault()
+ event.stopPropagation()
+ depthRef.current = 0
+ setIsDragActive(false)
+ const file = event.dataTransfer.files[0]
+ if (file && !disabled) onFile(file)
+ },
+ }
+}
diff --git a/web/app/components/base/icon-picker/image-input.tsx b/web/app/components/base/icon-picker/image-input.tsx
new file mode 100644
index 00000000000..f0c33723690
--- /dev/null
+++ b/web/app/components/base/icon-picker/image-input.tsx
@@ -0,0 +1,238 @@
+'use client'
+
+import type { Ref } from 'react'
+import type { Area, CropperProps } from 'react-easy-crop'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import {
+ Slider,
+ SliderControl,
+ SliderIndicator,
+ SliderLabel,
+ SliderThumb,
+ SliderTrack,
+} from '@langgenius/dify-ui/slider'
+import { useEffect, useRef, useState } from 'react'
+import Cropper from 'react-easy-crop'
+import { useTranslation } from 'react-i18next'
+import { ALLOW_FILE_EXTENSIONS } from '@/types/app'
+import { checkIsAnimatedImage } from './image-crop'
+import { useImageDrop } from './image-input-drag'
+
+export type ImageIconInputValue =
+ | { type: 'file'; file: File }
+ | { type: 'crop'; url: string; area: Area; fileName: string }
+
+export type ImageIconInputProps = {
+ previewUrl?: string
+ initialFocusRef?: Ref<HTMLButtonElement>
+ disabled?: boolean
+ className?: string
+ cropShape?: CropperProps['cropShape']
+ onChange?: (value: ImageIconInputValue | null) => void
+}
+
+export function ImageIconInput({
+ className,
+ cropShape,
+ onChange,
+ initialFocusRef,
+ previewUrl,
+ disabled = false,
+}: ImageIconInputProps) {
+ const { t } = useTranslation(['common', 'app'])
+ const [inputImage, setInputImage] = useState<{ file: File; url: string; animated: boolean }>()
+ const [error, setError] = useState('')
+ const [pending, setPending] = useState(false)
+ const [crop, setCrop] = useState({ x: 0, y: 0 })
+ const [zoom, setZoom] = useState(1)
+ const inputRef = useRef<HTMLInputElement>(null)
+ const selectionRef = useRef(0)
+ useEffect(
+ () => () => {
+ selectionRef.current += 1
+ },
+ [],
+ )
+ useEffect(
+ () => () => {
+ if (inputImage) URL.revokeObjectURL(inputImage.url)
+ },
+ [inputImage],
+ )
+
+ const selectFile = async (file: File) => {
+ if (disabled) return
+ if (!ALLOW_FILE_EXTENSIONS.includes(file.type.split('/')[1]!) || file.size > 3 * 1024 * 1024) {
+ setError(
+ file.size > 3 * 1024 * 1024
+ ? t(($) => $['imageUploader.uploadFromComputerLimit'], { ns: 'common', size: 3 })
+ : t(($) => $['imageInput.supportedFormats'], { ns: 'common' }),
+ )
+ return
+ }
+ const selection = ++selectionRef.current
+ setPending(true)
+ setError('')
+ setInputImage(undefined)
+ onChange?.(null)
+ try {
+ const animated = await checkIsAnimatedImage(file)
+ if (selection !== selectionRef.current) return
+ setCrop({ x: 0, y: 0 })
+ setZoom(1)
+ setInputImage({ file, url: URL.createObjectURL(file), animated })
+ if (animated) onChange?.({ type: 'file', file })
+ } catch {
+ if (selection === selectionRef.current)
+ setError(t(($) => $['imageUploader.uploadFromComputerReadError'], { ns: 'common' }))
+ } finally {
+ if (selection === selectionRef.current) setPending(false)
+ }
+ }
+ const showPreview = !inputImage && !!previewUrl
+ const { isDragActive, ...dropHandlers } = useImageDrop((file) => void selectFile(file), disabled)
+ const handleImageError = () => {
+ setInputImage(undefined)
+ onChange?.(null)
+ setError(t(($) => $['imageUploader.uploadFromComputerReadError'], { ns: 'common' }))
+ }
+
+ return (
+ <div className={cn('w-full p-3', className)}>
+ <input
+ ref={inputRef}
+ type="file"
+ disabled={disabled}
+ className="hidden"
+ accept={ALLOW_FILE_EXTENSIONS.map((ext) => `.${ext}`).join(',')}
+ onChange={(event) => {
+ const file = event.target.files?.[0]
+ event.target.value = ''
+ if (file) void selectFile(file)
+ }}
+ data-testid="image-input"
+ />
+ <div
+ {...dropHandlers}
+ className={cn(
+ 'relative flex flex-col items-center justify-center overflow-hidden text-center',
+ showPreview
+ ? 'h-46 gap-3'
+ : 'h-60 gap-2 rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg px-4 py-3 text-text-secondary',
+ isDragActive &&
+ 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
+ )}
+ >
+ {showPreview ? (
+ <>
+ <img
+ src={previewUrl}
+ alt={t(($) => $['iconPicker.image'], { ns: 'app' })}
+ className="size-16 rounded-2xl object-contain"
+ />
+ <Button
+ ref={initialFocusRef}
+ disabled={disabled}
+ onClick={() => inputRef.current?.click()}
+ >
+ {t(($) => $['operation.change'], { ns: 'common' })}
+ </Button>
+ </>
+ ) : inputImage ? (
+ inputImage.animated ? (
+ <img
+ src={inputImage.url}
+ alt={t(($) => $['iconPicker.image'], { ns: 'app' })}
+ className="h-full w-full object-contain"
+ data-testid="animated-image"
+ onError={handleImageError}
+ />
+ ) : (
+ <div inert={disabled}>
+ <Cropper
+ image={inputImage.url}
+ crop={crop}
+ zoom={zoom}
+ aspect={1}
+ cropShape={cropShape}
+ onCropChange={setCrop}
+ onZoomChange={setZoom}
+ mediaProps={{ onError: handleImageError }}
+ cropperProps={{
+ role: 'group',
+ 'aria-label': t(($) => $['iconPicker.crop'], { ns: 'app' }),
+ }}
+ classes={{
+ cropAreaClassName:
+ 'focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-state-accent-solid',
+ }}
+ onCropComplete={(_, area) =>
+ onChange?.({
+ type: 'crop',
+ url: inputImage.url,
+ area,
+ fileName: inputImage.file.name,
+ })
+ }
+ />
+ </div>
+ )
+ ) : (
+ <>
+ <span className="i-ri-image-add-line size-5 text-text-tertiary" aria-hidden="true" />
+ <div className="system-sm-medium">
+ {t(($) => $['imageInput.dropImageHere'], { ns: 'common' })}{' '}
+ <button
+ type="button"
+ ref={initialFocusRef}
+ disabled={disabled}
+ className="rounded-sm text-text-accent focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-state-accent-solid"
+ onClick={() => inputRef.current?.click()}
+ >
+ {t(($) => $['imageInput.browse'], { ns: 'common' })}
+ </button>
+ </div>
+ <div className="system-xs-regular text-text-tertiary">
+ {t(($) => $['imageInput.supportedFormats'], { ns: 'common' })}
+ </div>
+ </>
+ )}
+ </div>
+ {pending && <p role="status">{t(($) => $.loading, { ns: 'common' })}</p>}
+ {error && (
+ <p role="alert" className="mt-2 text-text-destructive">
+ {error}
+ </p>
+ )}
+ {inputImage && (
+ <div className="mt-3 flex items-center justify-end gap-2">
+ {!inputImage.animated && (
+ <Slider
+ disabled={disabled}
+ min={1}
+ max={3}
+ step={0.1}
+ value={zoom}
+ onValueChange={setZoom}
+ className="min-w-0 flex-1 items-center gap-2"
+ >
+ <SliderLabel className="shrink-0 system-xs-regular">
+ {t(($) => $['iconPicker.zoom'], { ns: 'app' })}
+ </SliderLabel>
+ <SliderControl>
+ <SliderTrack>
+ <SliderIndicator />
+ <SliderThumb />
+ </SliderTrack>
+ </SliderControl>
+ </Slider>
+ )}
+ <Button disabled={disabled} onClick={() => inputRef.current?.click()}>
+ {t(($) => $['operation.change'], { ns: 'common' })}
+ </Button>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/components/base/app-icon-picker/index.stories.tsx b/web/app/components/base/icon-picker/index.stories.tsx
similarity index 76%
rename from web/app/components/base/app-icon-picker/index.stories.tsx
rename to web/app/components/base/icon-picker/index.stories.tsx
index 61492b9b8c8..4165486a081 100644
--- a/web/app/components/base/app-icon-picker/index.stories.tsx
+++ b/web/app/components/base/icon-picker/index.stories.tsx
@@ -1,11 +1,11 @@
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
-import type { AppIconSelection } from '.'
+import type { IconPickerValue } from '.'
import { useState } from 'react'
-import AppIconPicker from '.'
+import { IconPickerDialog } from '.'
const meta = {
- title: 'Base/Data Entry/AppIconPicker',
- component: AppIconPicker,
+ title: 'Base/Data Entry/IconPickerDialog',
+ component: IconPickerDialog,
parameters: {
layout: 'fullscreen',
docs: {
@@ -23,14 +23,14 @@ const meta = {
},
},
tags: ['autodocs'],
-} satisfies Meta<typeof AppIconPicker>
+} satisfies Meta<typeof IconPickerDialog>
export default meta
type Story = StoryObj<typeof meta>
-const AppIconPickerDemo = () => {
+const IconPickerDialogDemo = () => {
const [open, setOpen] = useState(false)
- const [selection, setSelection] = useState<AppIconSelection | null>(null)
+ const [selection, setSelection] = useState<IconPickerValue | null>(null)
return (
<div className="flex min-h-80 flex-col items-start gap-4 px-6 py-8 md:px-12">
@@ -49,7 +49,7 @@ const AppIconPickerDemo = () => {
</pre>
</div>
- <AppIconPicker open={open} onOpenChange={setOpen} onSelect={setSelection} />
+ <IconPickerDialog open={open} onOpenChange={setOpen} onConfirm={setSelection} />
</div>
)
}
@@ -58,23 +58,24 @@ export const Playground: Story = {
args: {
open: false,
onOpenChange: () => {},
+ onConfirm: () => {},
},
- render: () => <AppIconPickerDemo />,
+ render: () => <IconPickerDialogDemo />,
parameters: {
docs: {
source: {
language: 'tsx',
code: `
const [open, setOpen] = useState(false)
-const [selection, setSelection] = useState<AppIconSelection | null>(null)
+const [selection, setSelection] = useState<IconPickerValue | null>(null)
return (
<>
<button onClick={() => setOpen(true)}>Choose icon…</button>
- <AppIconPicker
+ <IconPickerDialog
open={open}
onOpenChange={setOpen}
- onSelect={setSelection}
+ onConfirm={setSelection}
/>
</>
)
diff --git a/web/app/components/base/icon-picker/index.tsx b/web/app/components/base/icon-picker/index.tsx
new file mode 100644
index 00000000000..967a51a72ec
--- /dev/null
+++ b/web/app/components/base/icon-picker/index.tsx
@@ -0,0 +1,354 @@
+'use client'
+
+import type { DialogContentProps } from '@langgenius/dify-ui/dialog'
+import type { RefCallback } from 'react'
+import type { ImageIconInputValue } from './image-input'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
+import { useMutation } from '@tanstack/react-query'
+import { useCallback, useLayoutEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { DISABLE_UPLOAD_IMAGE_AS_ICON } from '@/config'
+import { consoleQuery } from '@/service/console'
+import { resolveEmoji } from '@/utils/emoji'
+import { EmojiIconEditor } from './emoji-icon-editor'
+import { defaultEmojiBackground, getRandomEmoji, getRandomEmojiBackground } from './emoji-styles'
+import getCroppedImg from './image-crop'
+import { ImageIconInput } from './image-input'
+import { addRecentEmoji, useRecentEmojis } from './recent-emojis'
+
+export type EmojiIcon = {
+ type: 'emoji'
+ icon: string
+ background: string
+}
+
+export type ImageIcon = {
+ type: 'image'
+ fileId: string
+ url: string
+}
+
+export type IconPickerValue = EmojiIcon | ImageIcon
+
+export type IconPickerDefaultValue =
+ | (Omit<EmojiIcon, 'background'> & { background?: EmojiIcon['background'] | null })
+ | ImageIcon
+
+export type IconPickerDialogProps = Pick<DialogContentProps, 'initialFocus' | 'finalFocus'> & {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ /** Initial draft for each mounted dialog session; changes while open do not replace edits. */
+ defaultValue?: IconPickerDefaultValue
+ /** Receives the confirmed value after any image upload; does not await consumer persistence. */
+ onConfirm: (value: IconPickerValue) => void
+ enableImageUpload?: boolean
+ className?: string
+}
+
+export function IconPickerDialog({
+ open,
+ onOpenChange,
+ className,
+ initialFocus,
+ finalFocus,
+ ...props
+}: IconPickerDialogProps) {
+ const { t } = useTranslation(['app'])
+ const popupRef = useRef<HTMLDivElement>(null)
+ const focusTargetRef = useRef<HTMLElement | null>(null)
+ const setFocusTarget = useCallback((element: HTMLElement | null) => {
+ focusTargetRef.current = element
+ }, [])
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent
+ ref={popupRef}
+ backdropProps={{ forceRender: true }}
+ initialFocus={
+ initialFocus ??
+ ((interaction) =>
+ interaction === 'touch' ? popupRef.current : (focusTargetRef.current ?? true))
+ }
+ finalFocus={finalFocus}
+ className={cn(
+ 'flex max-h-[calc(100dvh-2rem)] w-80.5 flex-col overflow-hidden p-0 text-left',
+ className,
+ )}
+ >
+ <DialogTitle className="sr-only">
+ {t(($) => $['iconPicker.title'], { ns: 'app' })}
+ </DialogTitle>
+ <IconPickerSession
+ {...props}
+ open={open}
+ onOpenChange={onOpenChange}
+ initialFocusRef={setFocusTarget}
+ />
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function IconPickerSession({
+ open,
+ defaultValue,
+ onConfirm,
+ onOpenChange,
+ enableImageUpload = true,
+ initialFocusRef,
+}: Pick<
+ IconPickerDialogProps,
+ 'open' | 'defaultValue' | 'onConfirm' | 'onOpenChange' | 'enableImageUpload'
+> & { initialFocusRef: RefCallback<HTMLElement> }) {
+ const { t } = useTranslation(['app', 'common'])
+ const imageEnabled = enableImageUpload && !DISABLE_UPLOAD_IMAGE_AS_ICON
+ const [activeTab, setActiveTab] = useState<IconPickerValue['type']>(
+ defaultValue?.type === 'image' && imageEnabled ? 'image' : 'emoji',
+ )
+ const [emoji, setEmoji] = useState<EmojiIcon | undefined>(() =>
+ defaultValue?.type === 'emoji'
+ ? {
+ ...defaultValue,
+ icon: resolveEmoji(defaultValue.icon),
+ background: defaultValue.background || defaultEmojiBackground,
+ }
+ : undefined,
+ )
+ const handleEmojiChange = useCallback((icon: string) => {
+ setEmoji((current) =>
+ current?.icon === icon
+ ? current
+ : {
+ type: 'emoji',
+ icon,
+ background: current?.background ?? defaultEmojiBackground,
+ },
+ )
+ }, [])
+ const handleBackgroundChange = useCallback((background: string) => {
+ setEmoji((current) =>
+ !current || current.background === background ? current : { ...current, background },
+ )
+ }, [])
+ const [imageDraft, setImageDraft] = useState<ImageIcon | ImageIconInputValue | null>(() =>
+ defaultValue?.type === 'image' ? defaultValue : null,
+ )
+ const [preparing, setPreparing] = useState(false)
+ const [, setRecentEmojis] = useRecentEmojis()
+ const [preparationError, setPreparationError] = useState('')
+ const isOpenRef = useRef(open)
+ useLayoutEffect(() => {
+ isOpenRef.current = open
+ return () => {
+ isOpenRef.current = false
+ }
+ }, [open])
+
+ const upload = useMutation(
+ consoleQuery.files.upload.post.mutationOptions({ context: { silent: true } }),
+ )
+ const uploading = preparing || upload.isPending
+ const uploadError =
+ preparationError ||
+ (upload.isError
+ ? t(($) => $['imageUploader.uploadFromComputerUploadError'], { ns: 'common' })
+ : '')
+ const handleImageChange = (value: ImageIconInputValue | null) => {
+ if (uploading) return
+ setImageDraft(value)
+ setPreparationError('')
+ upload.reset()
+ }
+ const confirm = async () => {
+ if (activeTab === 'emoji') {
+ if (!emoji) return
+ setRecentEmojis((recent) => addRecentEmoji(recent, emoji.icon))
+ onConfirm(emoji)
+ onOpenChange(false)
+ } else if (imageDraft) {
+ if (!imageEnabled || uploading) return
+ if (imageDraft.type === 'image') {
+ onConfirm(imageDraft)
+ onOpenChange(false)
+ return
+ }
+ setPreparationError('')
+ upload.reset()
+ setPreparing(true)
+ try {
+ let file: File
+ if (imageDraft.type === 'file') file = imageDraft.file
+ else {
+ const blob = await getCroppedImg(imageDraft.url, imageDraft.area, imageDraft.fileName)
+ file = new File([blob], imageDraft.fileName, { type: blob.type })
+ }
+ if (!isOpenRef.current) return
+ if (file.size > 3 * 1024 * 1024) {
+ setPreparationError(
+ t(($) => $['imageUploader.uploadFromComputerLimit'], { ns: 'common', size: 3 }),
+ )
+ return
+ }
+ const url = await readImageDataURL(file)
+ if (!isOpenRef.current) return
+ upload.mutate(
+ { body: { file } },
+ {
+ onSuccess: (uploaded) => {
+ if (!isOpenRef.current) return
+ onConfirm({ type: 'image', fileId: uploaded.id, url })
+ onOpenChange(false)
+ },
+ },
+ )
+ } catch {
+ if (isOpenRef.current)
+ setPreparationError(
+ t(($) => $['imageUploader.uploadFromComputerReadError'], { ns: 'common' }),
+ )
+ } finally {
+ if (isOpenRef.current) setPreparing(false)
+ }
+ }
+ }
+
+ return (
+ <Tabs
+ value={activeTab}
+ onValueChange={(value) => {
+ if (value === 'emoji' || value === 'image') setActiveTab(value)
+ }}
+ className={cn(
+ 'flex min-h-0 flex-col',
+ activeTab === 'emoji'
+ ? 'h-[min(479px,calc(100dvh-2rem-1px))]'
+ : 'max-h-[calc(100dvh-2rem)]',
+ )}
+ >
+ {imageEnabled && (
+ <div
+ className={cn(
+ 'shrink-0 px-3 pt-3 pb-2',
+ activeTab === 'image' && 'border-b border-divider-subtle',
+ )}
+ >
+ <TabsList
+ aria-label={t(($) => $['iconPicker.title'], { ns: 'app' })}
+ className="gap-px rounded-[10px] bg-components-segmented-control-bg-normal p-0.5"
+ >
+ {(['emoji', 'image'] as const).map((kind) => (
+ <TabsTab
+ key={kind}
+ value={kind}
+ disabled={uploading}
+ className="flex h-7 flex-1 items-center justify-center gap-1 rounded-lg border-0 p-1 system-sm-medium data-active:bg-components-segmented-control-item-active-bg data-active:text-text-accent-light-mode-only data-active:shadow-xs"
+ >
+ <span
+ aria-hidden="true"
+ className={kind === 'image' ? 'i-ri-image-circle-ai-line size-4' : 'text-base'}
+ >
+ {kind === 'emoji' ? '🤖' : null}
+ </span>
+ {t(($) => $[kind === 'emoji' ? 'iconPicker.emoji' : 'iconPicker.image'], {
+ ns: 'app',
+ })}
+ </TabsTab>
+ ))}
+ </TabsList>
+ </div>
+ )}
+ {imageEnabled ? (
+ <TabsPanel
+ keepMounted
+ value="emoji"
+ tabIndex={-1}
+ className="flex min-h-0 flex-1 flex-col data-hidden:hidden"
+ >
+ <EmojiIconEditor
+ inputRef={activeTab === 'emoji' ? initialFocusRef : undefined}
+ value={emoji}
+ onEmojiChange={handleEmojiChange}
+ onBackgroundChange={handleBackgroundChange}
+ />
+ </TabsPanel>
+ ) : (
+ <div className="flex min-h-0 flex-1 flex-col pt-3">
+ <EmojiIconEditor
+ inputRef={activeTab === 'emoji' ? initialFocusRef : undefined}
+ value={emoji}
+ onEmojiChange={handleEmojiChange}
+ onBackgroundChange={handleBackgroundChange}
+ />
+ </div>
+ )}
+ {imageEnabled && (
+ <TabsPanel
+ keepMounted
+ value="image"
+ tabIndex={-1}
+ className="min-h-0 overflow-y-auto data-hidden:hidden"
+ >
+ <ImageIconInput
+ previewUrl={imageDraft?.type === 'image' ? imageDraft.url : undefined}
+ initialFocusRef={activeTab === 'image' ? initialFocusRef : undefined}
+ disabled={uploading}
+ onChange={handleImageChange}
+ />
+ </TabsPanel>
+ )}
+ {uploadError && (
+ <p role="alert" className="px-3 text-text-destructive">
+ {uploadError}
+ </p>
+ )}
+ {(activeTab === 'emoji' || imageDraft) && (
+ <div className="flex shrink-0 gap-2 border-t border-divider-subtle bg-components-panel-bg-blur p-3 backdrop-blur-sm">
+ {activeTab === 'emoji' ? (
+ <Button
+ className="min-w-0 flex-1"
+ onClick={() =>
+ setEmoji({
+ type: 'emoji',
+ icon: getRandomEmoji(emoji?.icon),
+ background: getRandomEmojiBackground(emoji?.background),
+ })
+ }
+ >
+ <span className="i-ri-dice-line size-4" aria-hidden="true" />
+ {t(($) => $['iconPicker.tryYourLuck'], { ns: 'app' })}
+ </Button>
+ ) : (
+ <Button className="min-w-0 flex-1" onClick={() => onOpenChange(false)}>
+ {t(($) => $['iconPicker.cancel'], { ns: 'app' })}
+ </Button>
+ )}
+ <Button
+ variant="primary"
+ className="min-w-0 flex-1"
+ disabled={activeTab === 'emoji' ? !emoji : !imageDraft}
+ loading={uploading}
+ onClick={() => void confirm()}
+ >
+ {t(($) => $['iconPicker.ok'], { ns: 'app' })}
+ </Button>
+ </div>
+ )}
+ </Tabs>
+ )
+}
+
+function readImageDataURL(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onload = () => {
+ if (typeof reader.result === 'string') resolve(reader.result)
+ else reject(new Error('Invalid image preview'))
+ }
+ reader.onerror = () => reject(reader.error)
+ reader.onabort = () => reject(new DOMException('Image read aborted', 'AbortError'))
+ reader.readAsDataURL(file)
+ })
+}
diff --git a/web/app/components/base/emoji-picker/storage.ts b/web/app/components/base/icon-picker/recent-emojis.ts
similarity index 100%
rename from web/app/components/base/emoji-picker/storage.ts
rename to web/app/components/base/icon-picker/recent-emojis.ts
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/edit-pipeline-info.spec.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/edit-pipeline-info.spec.tsx
index 0764c7f3c72..af7a31ac8b5 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/edit-pipeline-info.spec.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/__tests__/edit-pipeline-info.spec.tsx
@@ -1,11 +1,11 @@
import type { ReactElement } from 'react'
import type { PipelineTemplate } from '@/models/pipeline'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
-import { fireEvent, screen, render as testingLibraryRender, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { ChunkingMode } from '@/models/datasets'
-import { mockEmojiData } from '@/test/emoji-picker'
+import { mockEmojiData, renderWithEmoji as testingLibraryRender } from '@/test/emoji-picker'
import EditPipelineInfo from '../edit-pipeline-info'
const render = (ui: ReactElement) =>
@@ -371,10 +371,11 @@ describe('EditPipelineInfo', () => {
// Open picker and select emoji
fireEvent.click(getIconButton())
+ fireEvent.click(screen.getByRole('tab', { name: 'app.iconPicker.emoji' }))
const emojiButton = await screen.findByRole('gridcell', { name: 'Grinning face' })
expect(emojiButton).toBeTruthy()
fireEvent.click(emojiButton!)
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
const saveButton = screen.getByText(/operation\.save/i)
@@ -398,15 +399,18 @@ describe('EditPipelineInfo', () => {
render(<EditPipelineInfo {...defaultProps} />)
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('radio', { name: /iconPicker\.image/ }))
+ fireEvent.click(screen.getByRole('tab', { name: /iconPicker\.image/ }))
- expect(screen.getByRole('radio', { name: /iconPicker\.image/ })).toBeChecked()
+ expect(screen.getByRole('tab', { name: /iconPicker\.image/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
expect(screen.queryByRole('button', { name: /iconPicker\.ok/ })).not.toBeInTheDocument()
})
})
- // AppIconPicker Tests (Branch Coverage)
- describe('AppIconPicker', () => {
+ // IconPickerDialog Tests (Branch Coverage)
+ describe('IconPickerDialog', () => {
it('should not show picker initially', () => {
render(<EditPipelineInfo {...defaultProps} />)
expect(screen.queryByPlaceholderText('app.iconPicker.search')).not.toBeInTheDocument()
@@ -423,7 +427,7 @@ describe('EditPipelineInfo', () => {
render(<EditPipelineInfo {...defaultProps} />)
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
await waitFor(() => {
@@ -435,9 +439,12 @@ describe('EditPipelineInfo', () => {
render(<EditPipelineInfo {...defaultProps} />)
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('radio', { name: /iconPicker\.image/ }))
+ fireEvent.click(screen.getByRole('tab', { name: /iconPicker\.image/ }))
- expect(screen.getByRole('radio', { name: /iconPicker\.image/ })).toBeChecked()
+ expect(screen.getByRole('tab', { name: /iconPicker\.image/ })).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ )
expect(screen.queryByRole('button', { name: /iconPicker\.ok/ })).not.toBeInTheDocument()
})
@@ -462,7 +469,7 @@ describe('EditPipelineInfo', () => {
// Open picker and select new emoji
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
const saveButton = screen.getByText(/operation\.save/i)
@@ -491,10 +498,11 @@ describe('EditPipelineInfo', () => {
render(<EditPipelineInfo {...defaultProps} pipeline={createImagePipelineTemplate()} />)
fireEvent.click(getIconButton())
+ fireEvent.click(screen.getByRole('tab', { name: 'app.iconPicker.emoji' }))
const emojiButton = await screen.findByRole('gridcell', { name: 'Grinning face' })
expect(emojiButton).toBeTruthy()
fireEvent.click(emojiButton!)
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
const saveButton = screen.getByText(/operation\.save/i)
diff --git a/web/app/components/datasets/create-from-pipeline/list/template-card/edit-pipeline-info.tsx b/web/app/components/datasets/create-from-pipeline/list/template-card/edit-pipeline-info.tsx
index 19b5b0b144e..533a581782c 100644
--- a/web/app/components/datasets/create-from-pipeline/list/template-card/edit-pipeline-info.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/template-card/edit-pipeline-info.tsx
@@ -1,4 +1,4 @@
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { PipelineTemplate } from '@/models/pipeline'
import { Button } from '@langgenius/dify-ui/button'
import { DialogTitle } from '@langgenius/dify-ui/dialog'
@@ -10,7 +10,7 @@ import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { toast } from '@/app/notifications'
import { useInvalidCustomizedTemplateList, useUpdateTemplateInfo } from '@/service/use-pipeline'
@@ -23,7 +23,7 @@ const EditPipelineInfo = ({ onClose, pipeline }: EditPipelineInfoProps) => {
const { t } = useTranslation(['common', 'datasetPipeline'])
const [name, setName] = useState(pipeline.name)
const iconInfo = pipeline.icon
- const [appIcon, setAppIcon] = useState<AppIconSelection>(
+ const [appIcon, setAppIcon] = useState<IconPickerValue>(
iconInfo.icon_type === 'image'
? { type: 'image' as const, url: iconInfo.icon_url || '', fileId: iconInfo.icon || '' }
: {
@@ -33,7 +33,7 @@ const EditPipelineInfo = ({ onClose, pipeline }: EditPipelineInfoProps) => {
},
)
const [description, setDescription] = useState(pipeline.description)
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const handleAppNameChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value
@@ -41,10 +41,10 @@ const EditPipelineInfo = ({ onClose, pipeline }: EditPipelineInfoProps) => {
}, [])
const handleOpenAppIconPicker = useCallback(() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}, [])
- const handleSelectAppIcon = useCallback((icon: AppIconSelection) => {
+ const handleSelectAppIcon = useCallback((icon: IconPickerValue) => {
setAppIcon(icon)
}, [])
@@ -157,18 +157,12 @@ const EditPipelineInfo = ({ onClose, pipeline }: EditPipelineInfoProps) => {
{t(($) => $['operation.save'], { ns: 'common' })}
</Button>
</div>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={handleSelectAppIcon}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={handleSelectAppIcon}
+ />
</form>
)
}
diff --git a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
index 98773598bbc..8ba219127d5 100644
--- a/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
+++ b/web/app/components/datasets/rename-modal/__tests__/index.spec.tsx
@@ -1,9 +1,9 @@
import type { DataSet } from '@/models/datasets'
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { IndexingType } from '@/app/components/datasets/create/step-two'
import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'
-import { mockEmojiData } from '@/test/emoji-picker'
+import { mockEmojiData, renderWithEmoji as render } from '@/test/emoji-picker'
import RenameDatasetModal from '../index'
const { mockToast } = vi.hoisted(() => {
@@ -32,14 +32,17 @@ vi.mock('../../../base/app-icon', () => ({
default: () => <span data-testid="app-icon">Icon</span>,
}))
-vi.mock('@/app/components/base/app-icon-picker', () => ({
- default: ({
+vi.mock('@/app/components/base/icon-picker', () => ({
+ IconPickerDialog: ({
+ open,
onOpenChange,
- onSelect,
+ onConfirm,
}: {
+ open: boolean
onOpenChange: (open: boolean) => void
- onSelect: (payload: { type: 'emoji'; icon: string; background: string }) => void
+ onConfirm: (payload: { type: 'emoji'; icon: string; background: string }) => void
}) => {
+ if (!open) return null
let selectedBackground = '#FFEAD5'
return (
<div>
@@ -61,7 +64,7 @@ vi.mock('@/app/components/base/app-icon-picker', () => ({
<button
type="button"
onClick={() => {
- onSelect({ type: 'emoji', icon: '📊', background: selectedBackground })
+ onConfirm({ type: 'emoji', icon: '📊', background: selectedBackground })
onOpenChange(false)
}}
>
diff --git a/web/app/components/datasets/rename-modal/index.tsx b/web/app/components/datasets/rename-modal/index.tsx
index e609b0a3665..be6c9a6b6b4 100644
--- a/web/app/components/datasets/rename-modal/index.tsx
+++ b/web/app/components/datasets/rename-modal/index.tsx
@@ -1,5 +1,5 @@
'use client'
-import type { AppIconSelection } from '../../base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { DataSet } from '@/models/datasets'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
@@ -9,10 +9,10 @@ import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { toast } from '@/app/notifications'
import { updateDatasetSetting } from '@/service/datasets'
import AppIcon from '../../base/app-icon'
-import AppIconPicker from '../../base/app-icon-picker'
type RenameDatasetModalProps = {
show: boolean
@@ -27,7 +27,7 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset
const [description, setDescription] = useState<string>(dataset.description)
const externalKnowledgeId = dataset.external_knowledge_info.external_knowledge_id
const externalKnowledgeApiId = dataset.external_knowledge_info.external_knowledge_api_id
- const [appIcon, setAppIcon] = useState<AppIconSelection>(
+ const [appIcon, setAppIcon] = useState<IconPickerValue>(
dataset.icon_info?.icon_type === 'image'
? {
type: 'image' as const,
@@ -40,11 +40,11 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset
background: dataset.icon_info?.icon_background || '',
},
)
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const handleOpenAppIconPicker = useCallback(() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}, [])
- const handleSelectAppIcon = useCallback((icon: AppIconSelection) => {
+ const handleSelectAppIcon = useCallback((icon: IconPickerValue) => {
setAppIcon(icon)
}, [])
const onConfirm = useCallback(async () => {
@@ -168,18 +168,12 @@ const RenameDatasetModal = ({ show, dataset, onSuccess, onClose }: RenameDataset
</Button>
</div>
</form>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={handleSelectAppIcon}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={handleSelectAppIcon}
+ />
</DialogContent>
</Dialog>
)
diff --git a/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx b/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx
index a705da7e542..1386f3f9fa1 100644
--- a/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx
+++ b/web/app/components/datasets/settings/form/components/__tests__/basic-info-section.spec.tsx
@@ -41,7 +41,7 @@ const render = (ui: ReactElement) => {
return renderWithConsoleState(ui, { wrapper })
}
-// Mock image uploader hooks for AppIconPicker
+// Mock image uploader hooks for IconPickerDialog
vi.mock('@/app/components/base/image-uploader/hooks', () => ({
useLocalFileUploader: () => ({
disabled: false,
@@ -168,10 +168,10 @@ describe('BasicInfoSection', () => {
description: 'Test description',
setDescription: vi.fn(),
iconInfo: mockIconInfo,
- showAppIconPicker: false,
+ showIconPicker: false,
handleOpenAppIconPicker: vi.fn(),
handleSelectAppIcon: vi.fn(),
- setShowAppIconPicker: vi.fn(),
+ setShowIconPicker: vi.fn(),
permission: DatasetPermission.onlyMe,
setPermission: vi.fn(),
selectedMemberIDs: ['user-1'],
@@ -334,41 +334,41 @@ describe('BasicInfoSection', () => {
expect(handleOpenAppIconPicker).toHaveBeenCalledOnce()
})
- it('should not render AppIconPicker when showAppIconPicker is false', () => {
- const { container } = render(<BasicInfoSection {...defaultProps} showAppIconPicker={false} />)
-
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
- // Check that AppIconPicker is not rendered
+ it('should not render IconPickerDialog when showIconPicker is false', () => {
+ const { container } = render(<BasicInfoSection {...defaultProps} showIconPicker={false} />)
+
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
+ // Check that IconPickerDialog is not rendered
expect(container.querySelector('[data-testid="app-icon-picker"]')).not.toBeInTheDocument()
})
diff --git a/web/app/components/datasets/settings/form/components/basic-info-section.tsx b/web/app/components/datasets/settings/form/components/basic-info-section.tsx
index 30107d0dae7..231bee8c690 100644
--- a/web/app/components/datasets/settings/form/components/basic-info-section.tsx
+++ b/web/app/components/datasets/settings/form/components/basic-info-section.tsx
@@ -1,5 +1,5 @@
'use client'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { Member } from '@/models/common'
import type { DataSet, DatasetPermission, IconInfo } from '@/models/datasets'
import type { AppIconType } from '@/types/app'
@@ -9,7 +9,7 @@ import { Textarea } from '@langgenius/dify-ui/textarea'
import { useId } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import PermissionSelector from '../../permission-selector'
const rowClass = 'flex min-w-0 flex-col gap-2 @3xl/settings:flex-row @3xl/settings:gap-x-1'
@@ -22,10 +22,10 @@ type BasicInfoSectionProps = {
description: string
setDescription: (value: string) => void
iconInfo: IconInfo
- showAppIconPicker: boolean
+ showIconPicker: boolean
handleOpenAppIconPicker: () => void
- handleSelectAppIcon: (icon: AppIconSelection) => void
- setShowAppIconPicker: (show: boolean) => void
+ handleSelectAppIcon: (icon: IconPickerValue) => void
+ setShowIconPicker: (show: boolean) => void
permission: DatasetPermission | undefined
setPermission: (value: DatasetPermission | undefined) => void
selectedMemberIDs: string[]
@@ -41,10 +41,10 @@ const BasicInfoSection = ({
description,
setDescription,
iconInfo,
- showAppIconPicker,
+ showIconPicker,
handleOpenAppIconPicker,
handleSelectAppIcon,
- setShowAppIconPicker,
+ setShowIconPicker,
permission,
setPermission,
selectedMemberIDs,
@@ -130,18 +130,20 @@ const BasicInfoSection = ({
</div>
</div>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- iconInfo.icon_type === 'emoji'
- ? { icon: iconInfo.icon, background: iconInfo.icon_background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={handleSelectAppIcon}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={
+ iconInfo.icon_type === 'emoji'
+ ? {
+ type: 'emoji',
+ icon: iconInfo.icon,
+ background: iconInfo.icon_background,
+ }
+ : { type: 'image', fileId: iconInfo.icon, url: iconInfo.icon_url || '' }
+ }
+ onOpenChange={setShowIconPicker}
+ onConfirm={handleSelectAppIcon}
+ />
</>
)
}
diff --git a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
index cc26c0b116f..34b942aaa91 100644
--- a/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
+++ b/web/app/components/datasets/settings/form/hooks/__tests__/use-form-state.spec.ts
@@ -323,7 +323,7 @@ describe('useFormState', () => {
result.current.handleOpenAppIconPicker()
})
- expect(result.current.showAppIconPicker).toBe(true)
+ expect(result.current.showIconPicker).toBe(true)
})
it('should select emoji icon without owning picker close state', () => {
@@ -341,7 +341,7 @@ describe('useFormState', () => {
})
})
- expect(result.current.showAppIconPicker).toBe(true)
+ expect(result.current.showIconPicker).toBe(true)
expect(result.current.iconInfo).toEqual({
icon_type: 'emoji',
icon: '🎉',
@@ -365,7 +365,7 @@ describe('useFormState', () => {
})
})
- expect(result.current.showAppIconPicker).toBe(true)
+ expect(result.current.showIconPicker).toBe(true)
expect(result.current.iconInfo).toEqual({
icon_type: 'image',
icon: 'file-123',
@@ -390,10 +390,10 @@ describe('useFormState', () => {
})
act(() => {
- result.current.setShowAppIconPicker(false)
+ result.current.setShowIconPicker(false)
})
- expect(result.current.showAppIconPicker).toBe(false)
+ expect(result.current.showIconPicker).toBe(false)
expect(result.current.iconInfo).toEqual({
icon_type: 'emoji',
icon: '🎉',
diff --git a/web/app/components/datasets/settings/form/hooks/use-form-state.ts b/web/app/components/datasets/settings/form/hooks/use-form-state.ts
index 9ba535d7a01..c32c1e15c35 100644
--- a/web/app/components/datasets/settings/form/hooks/use-form-state.ts
+++ b/web/app/components/datasets/settings/form/hooks/use-form-state.ts
@@ -1,5 +1,5 @@
'use client'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Member } from '@/models/common'
import type { IconInfo, SummaryIndexSetting as SummaryIndexSettingType } from '@/models/datasets'
@@ -64,7 +64,7 @@ export const useFormState = () => {
// Icon state
const [iconInfo, setIconInfo] = useState(currentDataset?.icon_info || DEFAULT_APP_ICON)
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
// Permission state
const [permission, setPermission] = useState(currentDataset?.permission)
@@ -127,10 +127,10 @@ export const useFormState = () => {
// Icon handlers
const handleOpenAppIconPicker = useCallback(() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}, [])
- const handleSelectAppIcon = useCallback((icon: AppIconSelection) => {
+ const handleSelectAppIcon = useCallback((icon: IconPickerValue) => {
const newIconInfo: IconInfo = {
icon_type: icon.type,
icon: icon.type === 'emoji' ? icon.icon : icon.fileId,
@@ -274,8 +274,8 @@ export const useFormState = () => {
// Icon
iconInfo,
- showAppIconPicker,
- setShowAppIconPicker,
+ showIconPicker,
+ setShowIconPicker,
handleOpenAppIconPicker,
handleSelectAppIcon,
diff --git a/web/app/components/datasets/settings/form/index.tsx b/web/app/components/datasets/settings/form/index.tsx
index 84c186274cc..141c7cd14e4 100644
--- a/web/app/components/datasets/settings/form/index.tsx
+++ b/web/app/components/datasets/settings/form/index.tsx
@@ -25,8 +25,8 @@ const Form = () => {
// Icon
iconInfo,
- showAppIconPicker,
- setShowAppIconPicker,
+ showIconPicker,
+ setShowIconPicker,
handleOpenAppIconPicker,
handleSelectAppIcon,
@@ -77,8 +77,8 @@ const Form = () => {
description={description}
setDescription={setDescription}
iconInfo={iconInfo}
- showAppIconPicker={showAppIconPicker}
- setShowAppIconPicker={setShowAppIconPicker}
+ showIconPicker={showIconPicker}
+ setShowIconPicker={setShowIconPicker}
handleOpenAppIconPicker={handleOpenAppIconPicker}
handleSelectAppIcon={handleSelectAppIcon}
permission={permission}
diff --git a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
index 7da46affed6..aa98d0e0ec6 100644
--- a/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
+++ b/web/app/components/explore/create-app-modal/__tests__/index.spec.tsx
@@ -55,7 +55,7 @@ const getAppIconTrigger = (): HTMLElement => {
const openAppIconPicker = () => {
fireEvent.click(getAppIconTrigger())
- return screen.getByRole('dialog', { name: 'app.iconPicker.emoji' })
+ return screen.getByRole('dialog', { name: 'app.iconPicker.title' })
}
function render(ui: ReactElement) {
@@ -307,6 +307,20 @@ describe('CreateAppModal', () => {
})
describe('App Icon Picker', () => {
+ it('does not fill a missing background when the picker is cancelled', async () => {
+ const { onConfirm } = await setup({ appIconBackground: undefined })
+ openAppIconPicker()
+ await userEvent.setup().keyboard('{Escape}')
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('dialog', { name: 'app.iconPicker.title' }),
+ ).not.toBeInTheDocument(),
+ )
+ fireEvent.click(screen.getByRole('button', { name: /common\.operation\.create/ }))
+ await waitFor(() => expect(onConfirm).toHaveBeenCalledOnce())
+ expect(onConfirm.mock.calls[0]![0].icon_background).toBeUndefined()
+ })
+
it('should open and close the picker when Escape is pressed', async () => {
await setup({
appIconType: 'image',
@@ -317,14 +331,14 @@ describe('CreateAppModal', () => {
const pickerDialog = openAppIconPicker()
expect(
- within(pickerDialog).getByRole('button', { name: 'app.iconPicker.tryYourLuck' }),
+ within(pickerDialog).getByRole('tabpanel', { name: 'app.iconPicker.image' }),
)!.toBeInTheDocument()
await userEvent.setup().keyboard('{Escape}')
await waitFor(() => {
expect(
- screen.queryByRole('dialog', { name: 'app.iconPicker.emoji' }),
+ screen.queryByRole('dialog', { name: 'app.iconPicker.title' }),
).not.toBeInTheDocument()
})
})
@@ -338,6 +352,7 @@ describe('CreateAppModal', () => {
const pickerDialog = openAppIconPicker()
+ fireEvent.click(within(pickerDialog).getByRole('tab', { name: 'app.iconPicker.emoji' }))
fireEvent.click(await within(pickerDialog).findByRole('gridcell', { name: 'Grinning face' }))
fireEvent.click(within(pickerDialog).getByRole('button', { name: 'app.iconPicker.ok' }))
@@ -365,7 +380,9 @@ describe('CreateAppModal', () => {
const pickerDialog = openAppIconPicker()
- fireEvent.click(within(pickerDialog).getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(
+ within(pickerDialog).getByRole('radio', { name: 'app.iconPicker.color.green' }),
+ )
fireEvent.click(within(pickerDialog).getByRole('button', { name: 'app.iconPicker.ok' }))
fireEvent.click(screen.getByRole('button', { name: /common\.operation\.create/ }))
diff --git a/web/app/components/explore/create-app-modal/index.tsx b/web/app/components/explore/create-app-modal/index.tsx
index 321f5437da1..60b9151ad1e 100644
--- a/web/app/components/explore/create-app-modal/index.tsx
+++ b/web/app/components/explore/create-app-modal/index.tsx
@@ -16,12 +16,12 @@ import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import AppsFull from '@/app/components/billing/apps-full-in-dialog'
import { toast } from '@/app/notifications'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
import { AppModeEnum } from '@/types/app'
-import AppIconPicker from '../../base/app-icon-picker'
export type CreateAppModalProps = {
show: boolean
@@ -76,10 +76,10 @@ const CreateAppModal = ({
const [name, setName] = React.useState(appName)
const [appIcon, setAppIcon] = useState(() =>
appIconType === 'image'
- ? { type: 'image' as const, fileId: _appIcon, url: appIconUrl }
+ ? { type: 'image' as const, fileId: _appIcon, url: appIconUrl ?? '' }
: { type: 'emoji' as const, icon: _appIcon, background: appIconBackground },
)
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
const [description, setDescription] = useState(appDescription || '')
const [useIconAsAnswerIcon, setUseIconAsAnswerIcon] = useState(appUseIconAsAnswerIcon || false)
@@ -120,7 +120,7 @@ const CreateAppModal = ({
name,
icon_type: appIcon.type,
icon: appIcon.type === 'emoji' ? appIcon.icon : appIcon.fileId,
- icon_background: appIcon.type === 'emoji' ? appIcon.background! : undefined,
+ icon_background: appIcon.type === 'emoji' ? (appIcon.background ?? undefined) : undefined,
description,
use_icon_as_answer_icon: useIconAsAnswerIcon,
}
@@ -156,7 +156,7 @@ const CreateAppModal = ({
if (
!show ||
submitDisabled ||
- showAppIconPicker ||
+ showIconPicker ||
event.defaultPrevented ||
event.nativeEvent.isComposing ||
!(event.target instanceof Node) ||
@@ -206,7 +206,7 @@ const CreateAppModal = ({
<AppIcon
size="large"
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}}
className="cursor-pointer"
iconType={appIcon.type}
@@ -311,20 +311,14 @@ const CreateAppModal = ({
</div>
</DialogContent>
</Dialog>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- appIcon.type === 'emoji'
- ? { icon: appIcon.icon, background: appIcon.background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={(payload) => {
- setAppIcon(payload)
- }}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={appIcon}
+ onOpenChange={setShowIconPicker}
+ onConfirm={(payload) => {
+ setAppIcon(payload)
+ }}
+ />
</>
)
}
diff --git a/web/app/components/goto-anything/index.tsx b/web/app/components/goto-anything/index.tsx
index 4655d4c0651..707b92953be 100644
--- a/web/app/components/goto-anything/index.tsx
+++ b/web/app/components/goto-anything/index.tsx
@@ -522,6 +522,7 @@ export function GotoAnything() {
open
inline
autoHighlight="always"
+ highlightItemOnHover={false}
keepHighlight
loopFocus
>
@@ -607,7 +608,7 @@ export function GotoAnything() {
<AutocompleteItem
key={option.shortcut}
value={option}
- className="group m-0 min-h-18 items-start gap-3 rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg/90 p-3 shadow-xs shadow-shadow-shadow-3 backdrop-blur-sm hover:border-divider-regular hover:bg-state-base-hover-alt data-highlighted:border-state-accent-solid data-highlighted:bg-state-base-hover"
+ className="group m-0 min-h-18 items-start gap-3 rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg/90 p-3 shadow-xs shadow-shadow-shadow-3 backdrop-blur-sm hover:text-text-primary not-data-highlighted:hover:border-divider-regular not-data-highlighted:hover:bg-state-base-hover-alt data-highlighted:border-state-accent-solid data-highlighted:bg-state-base-hover"
onClick={() => selectOption(option)}
>
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-divider-regular bg-background-default text-text-tertiary group-data-highlighted:text-text-accent">
@@ -643,7 +644,7 @@ export function GotoAnything() {
<AutocompleteItem
key={`${result.type}-${result.id}`}
value={result}
- className="mx-2 gap-3 p-3"
+ className="mx-2 gap-3 p-3 hover:text-text-primary not-data-highlighted:hover:bg-state-base-hover-alt"
onClick={() => selectOption(result)}
>
{result.icon}
diff --git a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
index 6b27a9ca91d..4354e3bccc2 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.browser.spec.tsx
@@ -2,7 +2,7 @@ import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useState } from 'react'
-import { page } from 'vite-plus/test/browser'
+import { page, userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { MARKETPLACE_CONTAINER_ID } from '../../constants'
import HomeCatalogNavigation from '../home-catalog-navigation'
@@ -113,6 +113,60 @@ describe('Marketplace search autocomplete layout', () => {
mockTemplateSearch.mockResolvedValue({ data: { templates: [], total: 0 } })
})
+ it('preserves the keyboard activation target while the pointer visits another suggestion', async () => {
+ mockTemplateSearch.mockResolvedValue({
+ data: {
+ templates: ['First', 'Second'].map((name) => ({
+ id: name.toLowerCase(),
+ template_name: `${name} template`,
+ overview: '',
+ publisher_handle: 'dify',
+ usage_count: 1,
+ categories: [],
+ icon: '📄',
+ icon_background: '#FFFFFF',
+ icon_file_key: '',
+ })),
+ total: 2,
+ },
+ })
+ const onSelect = vi.fn()
+ function Search() {
+ const [value, setValue] = useState('')
+ return (
+ <MarketplaceSearchAutocomplete
+ locale="en-US"
+ onValueChange={setValue}
+ onSuggestionSelect={onSelect}
+ placeholder="Search templates"
+ scope="templates"
+ value={value}
+ />
+ )
+ }
+ const screen = await render(
+ <Wrapper>
+ <Search />
+ </Wrapper>,
+ )
+ const input = screen.getByRole('combobox', { name: 'Search templates' })
+ await input.fill('template')
+ const first = screen.getByRole('option', { name: /First template/ })
+ const second = screen.getByRole('option', { name: /Second template/ })
+ await expect.element(first).toBeVisible()
+ await userEvent.keyboard('{ArrowDown}')
+ await expect.element(input).toHaveAttribute('aria-activedescendant', first.element().id)
+ await second.hover()
+ await expect.element(input).toHaveAttribute('aria-activedescendant', first.element().id)
+ await userEvent.keyboard('{Enter}')
+ expect(onSelect).toHaveBeenCalledWith(
+ expect.objectContaining({
+ kind: 'template',
+ template: expect.objectContaining({ id: 'first' }),
+ }),
+ )
+ })
+
it('keeps the pinned catalog layout stable while the results popup opens', async () => {
await page.viewport(1280, 720)
diff --git a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
index 262df0be342..5d3be387357 100644
--- a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
+++ b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
@@ -117,7 +117,7 @@ function MarketplaceSuggestionList({
<AutocompleteItem
key={item.id}
value={item}
- className="mx-0 items-start gap-1 rounded-lg py-1 pr-1 pl-3 hover:bg-state-base-hover data-highlighted:bg-state-base-hover"
+ className="mx-0 items-start gap-1 rounded-lg py-1 pr-1 pl-3 hover:text-text-primary not-data-highlighted:hover:bg-state-base-hover"
onClick={() => onSelect(item.selection)}
>
<span className="flex shrink-0 items-start py-1">
@@ -323,6 +323,7 @@ export function MarketplaceSearchAutocomplete({
<div ref={searchRootRef} className="relative">
<Autocomplete
filter={null}
+ highlightItemOnHover={false}
itemToStringValue={(item) => item.label}
items={suggestionGroups}
mode="list"
diff --git a/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
index 6ef2fb0c78e..0b93d437889 100644
--- a/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
+++ b/web/app/components/rag-pipeline/components/__tests__/publish-as-knowledge-pipeline-modal.spec.tsx
@@ -1,7 +1,7 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { mockEmojiData } from '@/test/emoji-picker'
+import { mockEmojiData, renderWithEmoji as render } from '@/test/emoji-picker'
import PublishAsKnowledgePipelineModal from '../publish-as-knowledge-pipeline-modal'
vi.mock('@/app/components/workflow/store', () => ({
@@ -169,7 +169,7 @@ describe('PublishAsKnowledgePipelineModal', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
await waitFor(() => {
@@ -181,7 +181,7 @@ describe('PublishAsKnowledgePipelineModal', () => {
render(<PublishAsKnowledgePipelineModal {...defaultProps} />)
fireEvent.click(getIconButton())
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
expect(screen.getByPlaceholderText('app.iconPicker.search')).toBeInTheDocument()
})
diff --git a/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx b/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
index a54ea04537e..41d6f33f911 100644
--- a/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
+++ b/web/app/components/rag-pipeline/components/publish-as-knowledge-pipeline-modal.tsx
@@ -1,5 +1,5 @@
'use client'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { IconInfo } from '@/models/datasets'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
@@ -10,7 +10,7 @@ import { Textarea } from '@langgenius/dify-ui/textarea'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { useWorkflowStore } from '@/app/components/workflow/store'
type PublishAsKnowledgePipelineModalProps = {
@@ -28,15 +28,15 @@ const PublishAsKnowledgePipelineModal = ({
const [pipelineName, setPipelineName] = useState(() => workflowStore.getState().knowledgeName!)
const [pipelineIcon, setPipelineIcon] = useState(() => workflowStore.getState().knowledgeIcon!)
const [description, setDescription] = useState('')
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [showIconPicker, setShowIconPicker] = useState(false)
- const handleSelectIcon = useCallback((item: AppIconSelection) => {
+ const handleSelectIcon = useCallback((item: IconPickerValue) => {
if (item.type === 'image') {
setPipelineIcon({
icon_type: 'image',
icon_url: item.url,
icon_background: '',
- icon: '',
+ icon: item.fileId,
})
}
@@ -104,7 +104,7 @@ const PublishAsKnowledgePipelineModal = ({
type="button"
aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${t(($) => $['common.publishAsPipeline.name'], { ns: 'pipeline' })}`}
onClick={() => {
- setShowAppIconPicker(true)
+ setShowIconPicker(true)
}}
className="mt-2 shrink-0 cursor-pointer rounded-2xl focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
@@ -146,18 +146,20 @@ const PublishAsKnowledgePipelineModal = ({
{t(($) => $['common.publish'], { ns: 'workflow' })}
</Button>
</div>
- {showAppIconPicker && (
- <AppIconPicker
- open={showAppIconPicker}
- initialEmoji={
- pipelineIcon.icon_type === 'emoji'
- ? { icon: pipelineIcon.icon, background: pipelineIcon.icon_background }
- : undefined
- }
- onOpenChange={setShowAppIconPicker}
- onSelect={handleSelectIcon}
- />
- )}
+ <IconPickerDialog
+ open={showIconPicker}
+ defaultValue={
+ pipelineIcon.icon_type === 'emoji'
+ ? {
+ type: 'emoji',
+ icon: pipelineIcon.icon,
+ background: pipelineIcon.icon_background,
+ }
+ : { type: 'image', fileId: pipelineIcon.icon, url: pipelineIcon.icon_url || '' }
+ }
+ onOpenChange={setShowIconPicker}
+ onConfirm={handleSelectIcon}
+ />
</form>
</DialogContent>
</Dialog>
diff --git a/web/app/components/tools/edit-custom-collection-modal/index.tsx b/web/app/components/tools/edit-custom-collection-modal/index.tsx
index a3541c0a974..63fbe67df80 100644
--- a/web/app/components/tools/edit-custom-collection-modal/index.tsx
+++ b/web/app/components/tools/edit-custom-collection-modal/index.tsx
@@ -22,7 +22,7 @@ import * as React from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import EmojiPicker from '@/app/components/base/emoji-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import LabelSelector from '@/app/components/tools/labels/selector'
import { toast } from '@/app/notifications'
import { parseParamsSchema } from '@/service/tools'
@@ -481,15 +481,21 @@ const EditCustomCollectionModal: FC<Props> = ({
</Button>
</div>
</div>
- {showEmojiPicker && (
- <EmojiPicker
- open={showEmojiPicker}
- onOpenChange={setShowEmojiPicker}
- onSelect={(icon, icon_background) => {
- setEmoji({ content: icon, background: icon_background })
- }}
- />
- )}
+ <IconPickerDialog
+ enableImageUpload={false}
+ defaultValue={{
+ type: 'emoji',
+ icon: emoji.content,
+ background: emoji.background,
+ }}
+ open={showEmojiPicker}
+ onOpenChange={setShowEmojiPicker}
+ onConfirm={(value) => {
+ if (value.type !== 'emoji') return
+ const { icon, background: icon_background } = value
+ setEmoji({ content: icon, background: icon_background })
+ }}
+ />
{credentialsModalShow && (
<ConfigCredentials
positionCenter={isAdd}
diff --git a/web/app/components/tools/mcp/__tests__/modal.spec.tsx b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
index a978d1da5f1..e86dcaa5063 100644
--- a/web/app/components/tools/mcp/__tests__/modal.spec.tsx
+++ b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
@@ -1,11 +1,11 @@
import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
-import { mockEmojiData } from '@/test/emoji-picker'
+import { mockEmojiData, renderWithEmoji as render } from '@/test/emoji-picker'
import MCPModal from '../modal'
// Mock the service API
@@ -697,7 +697,7 @@ describe('MCPModal', () => {
.click(screen.getByRole('button', { name: 'tools.mcp.modal.changeIcon' }))
expect(await screen.findByPlaceholderText('app.iconPicker.search')).toBeInTheDocument()
- fireEvent.click(screen.getByRole('button', { name: '#F3FEE7' }))
+ fireEvent.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
fireEvent.click(screen.getByRole('button', { name: /iconPicker\.ok/ }))
await waitFor(() => {
diff --git a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
index d7b04c7517e..75ee8a0ade5 100644
--- a/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
+++ b/web/app/components/tools/mcp/hooks/__tests__/use-mcp-modal-form.spec.ts
@@ -1,7 +1,4 @@
-import type {
- AppIconEmojiSelection,
- AppIconImageSelection,
-} from '@/app/components/base/app-icon-picker'
+import type { EmojiIcon, ImageIcon } from '@/app/components/base/icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { act, renderHook } from '@testing-library/react'
import { describe, expect, it, vi } from 'vite-plus/test'
@@ -183,8 +180,8 @@ describe('useMCPModalForm', () => {
const { result } = renderHook(() => useMCPModalForm(mockData))
expect(result.current.state.appIcon.type).toBe('emoji')
- expect((result.current.state.appIcon as AppIconEmojiSelection).icon).toBe('🚀')
- expect((result.current.state.appIcon as AppIconEmojiSelection).background).toBe('#FF0000')
+ expect((result.current.state.appIcon as EmojiIcon).icon).toBe('🚀')
+ expect((result.current.state.appIcon as EmojiIcon).background).toBe('#FF0000')
})
it('should store original server URL and ID', () => {
@@ -202,14 +199,26 @@ describe('useMCPModalForm', () => {
icon: 'https://example.com/files/abc123/file-preview/icon.png',
} as unknown as ToolWithProvider
+ it('uses the default icon when the existing URL has no uploaded file id', () => {
+ const { result } = renderHook(() =>
+ useMCPModalForm({ ...mockDataWithImageIcon, icon: 'https://example.com/icon.png' }),
+ )
+
+ expect(result.current.state.appIcon).toEqual({
+ type: 'emoji',
+ icon: '🔗',
+ background: '#6366F1',
+ })
+ })
+
it('should initialize image icon from string URL', () => {
const { result } = renderHook(() => useMCPModalForm(mockDataWithImageIcon))
expect(result.current.state.appIcon.type).toBe('image')
- expect((result.current.state.appIcon as AppIconImageSelection).url).toBe(
+ expect((result.current.state.appIcon as ImageIcon).url).toBe(
'https://example.com/files/abc123/file-preview/icon.png',
)
- expect((result.current.state.appIcon as AppIconImageSelection).fileId).toBe('abc123')
+ expect((result.current.state.appIcon as ImageIcon).fileId).toBe('abc123')
})
})
})
@@ -327,16 +336,16 @@ describe('useMCPModalForm', () => {
expect(result.current.state.appIcon).toEqual(newIcon)
})
- it('should toggle showAppIconPicker', () => {
+ it('should toggle showIconPicker', () => {
const { result } = renderHook(() => useMCPModalForm())
- expect(result.current.state.showAppIconPicker).toBe(false)
+ expect(result.current.state.showIconPicker).toBe(false)
act(() => {
- result.current.actions.setShowAppIconPicker(true)
+ result.current.actions.setShowIconPicker(true)
})
- expect(result.current.state.showAppIconPicker).toBe(true)
+ expect(result.current.state.showIconPicker).toBe(true)
})
it('should reset icon to default', () => {
@@ -347,7 +356,7 @@ describe('useMCPModalForm', () => {
result.current.actions.setAppIcon({ type: 'emoji', icon: '🎉', background: '#00FF00' })
})
- expect((result.current.state.appIcon as AppIconEmojiSelection).icon).toBe('🎉')
+ expect((result.current.state.appIcon as EmojiIcon).icon).toBe('🎉')
// Reset icon
act(() => {
@@ -389,6 +398,28 @@ describe('useMCPModalForm', () => {
expect(result.current.state.isFetchingIcon).toBe(false)
})
+ it('uses the uploaded file id independently of the preview URL format', async () => {
+ const { uploadRemoteFileInfo } = await import('@/service/common')
+ vi.mocked(uploadRemoteFileInfo).mockResolvedValueOnce({
+ id: 'uploaded-icon-id',
+ name: 'icon.png',
+ size: 1024,
+ mime_type: 'image/png',
+ url: 'https://example.com/icon.png',
+ })
+ const { result } = renderHook(() => useMCPModalForm())
+
+ await act(async () => {
+ await result.current.actions.handleUrlBlur('https://example.com/mcp')
+ })
+
+ expect(result.current.state.appIcon).toEqual({
+ type: 'image',
+ fileId: 'uploaded-icon-id',
+ url: 'https://example.com/icon.png',
+ })
+ })
+
it('should handle error when icon fetch fails with error code', async () => {
const { uploadRemoteFileInfo } = await import('@/service/common')
const mockError = {
@@ -485,7 +516,7 @@ describe('useMCPModalForm', () => {
})
expect(result.current.state.appIcon.type).toBe('image')
- expect((result.current.state.appIcon as AppIconImageSelection).url).toBe(
+ expect((result.current.state.appIcon as ImageIcon).url).toBe(
'https://example.com/files/file456/file-preview/icon2.png',
)
expect(result.current.state.isFetchingIcon).toBe(false)
@@ -512,7 +543,7 @@ describe('useMCPModalForm', () => {
// Icon should be set to image type
expect(result.current.state.appIcon.type).toBe('image')
- expect((result.current.state.appIcon as AppIconImageSelection).url).toBe(
+ expect((result.current.state.appIcon as ImageIcon).url).toBe(
'https://example.com/files/file123/file-preview/icon.png',
)
expect(result.current.state.isFetchingIcon).toBe(false)
@@ -560,21 +591,6 @@ describe('useMCPModalForm', () => {
expect(result.current.state.isDynamicRegistration).toBe(true)
})
-
- it('should handle string icon URL', () => {
- const mockData = {
- id: 'test',
- name: 'Test',
- icon: 'https://example.com/icon.png',
- } as unknown as ToolWithProvider
-
- const { result } = renderHook(() => useMCPModalForm(mockData))
-
- expect(result.current.state.appIcon.type).toBe('image')
- expect((result.current.state.appIcon as AppIconImageSelection).url).toBe(
- 'https://example.com/icon.png',
- )
- })
})
// M3 — Forward-user-identity toggle (PR #36840). The hook stores a bool,
diff --git a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
index d7db9a1bcff..68afc0597dd 100644
--- a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
+++ b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
@@ -1,6 +1,6 @@
'use client'
import type { HeaderItem } from '../headers-input'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { useCallback, useMemo, useRef, useState } from 'react'
import { v4 as uuid } from 'uuid'
@@ -8,20 +8,22 @@ import { MCPAuthMethod } from '@/app/components/tools/types'
import { toast } from '@/app/notifications'
import { uploadRemoteFileInfo } from '@/service/common'
-const DEFAULT_ICON = { type: 'emoji', icon: '🔗', background: '#6366F1' }
+const DEFAULT_ICON = { type: 'emoji', icon: '🔗', background: '#6366F1' } satisfies IconPickerValue
const extractFileId = (url: string) => {
const match = /files\/(.+?)\/file-preview/.exec(url)
return match ? match[1] : null
}
-const getIcon = (data?: ToolWithProvider): AppIconSelection => {
- if (!data) return DEFAULT_ICON as AppIconSelection
- if (typeof data.icon === 'string')
- return { type: 'image', url: data.icon, fileId: extractFileId(data.icon) } as AppIconSelection
+const getIcon = (data?: ToolWithProvider): IconPickerValue => {
+ if (!data) return DEFAULT_ICON
+ if (typeof data.icon === 'string') {
+ const fileId = extractFileId(data.icon)
+ return fileId ? { type: 'image', url: data.icon, fileId } : DEFAULT_ICON
+ }
return {
- ...data.icon,
- icon: data.icon.content,
type: 'emoji',
- } as unknown as AppIconSelection
+ icon: data.icon.content,
+ background: data.icon.background,
+ }
}
const getInitialHeaders = (data?: ToolWithProvider): HeaderItem[] => {
return Object.entries(data?.masked_headers || {}).map(([key, value]) => ({
@@ -44,8 +46,8 @@ export const isValidServerID = (str: string) => {
type MCPModalFormState = {
url: string
name: string
- appIcon: AppIconSelection
- showAppIconPicker: boolean
+ appIcon: IconPickerValue
+ showIconPicker: boolean
serverIdentifier: string
timeout: number
sseReadTimeout: number
@@ -60,8 +62,8 @@ type MCPModalFormState = {
type MCPModalFormActions = {
setUrl: (url: string) => void
setName: (name: string) => void
- setAppIcon: (icon: AppIconSelection) => void
- setShowAppIconPicker: (show: boolean) => void
+ setAppIcon: (icon: IconPickerValue) => void
+ setShowIconPicker: (show: boolean) => void
setServerIdentifier: (id: string) => void
setTimeout: (timeout: number) => void
setSseReadTimeout: (timeout: number) => void
@@ -90,8 +92,8 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
// Form state - initialized from data
const [url, setUrl] = useState(() => data?.server_url || '')
const [name, setName] = useState(() => data?.name || '')
- const [appIcon, setAppIcon] = useState<AppIconSelection>(() => getIcon(data))
- const [showAppIconPicker, setShowAppIconPicker] = useState(false)
+ const [appIcon, setAppIcon] = useState<IconPickerValue>(() => getIcon(data))
+ const [showIconPicker, setShowIconPicker] = useState(false)
const [serverIdentifier, setServerIdentifier] = useState(() => data?.server_identifier || '')
const [timeout, setMcpTimeout] = useState(() => data?.configuration?.timeout || 30)
const [sseReadTimeout, setSseReadTimeout] = useState(
@@ -133,7 +135,7 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
const res = await uploadRemoteFileInfo(remoteIcon, undefined, true)
if (isStale()) return
- setAppIcon({ type: 'image', url: res.url, fileId: extractFileId(res.url) || '' })
+ setAppIcon({ type: 'image', url: res.url, fileId: res.id })
} catch (e) {
if (isStale()) return
@@ -175,7 +177,7 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
url,
name,
appIcon,
- showAppIconPicker,
+ showIconPicker,
serverIdentifier,
timeout,
sseReadTimeout,
@@ -192,7 +194,7 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
setUrl,
setName,
setAppIcon,
- setShowAppIconPicker,
+ setShowIconPicker,
setServerIdentifier,
setTimeout: setMcpTimeout,
setSseReadTimeout,
diff --git a/web/app/components/tools/mcp/modal.tsx b/web/app/components/tools/mcp/modal.tsx
index faf58235b39..4e27b128f6b 100644
--- a/web/app/components/tools/mcp/modal.tsx
+++ b/web/app/components/tools/mcp/modal.tsx
@@ -1,6 +1,6 @@
'use client'
import type { FC } from 'react'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import type { AppIconType } from '@/types/app'
import { zSsoProtocol } from '@dify/contracts/api/console/system-features/zod.gen'
@@ -15,7 +15,7 @@ import { useHover } from 'ahooks'
import { useId } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { MCPAuthMethod } from '@/app/components/tools/types'
import { toast } from '@/app/notifications'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
@@ -137,7 +137,7 @@ const MCPModalContent: FC<MCPModalContentProps> = ({ data, onConfirm, onHide })
if (isCreate) onHide()
}
- const handleIconSelect = (payload: AppIconSelection) => {
+ const handleIconSelect = (payload: IconPickerValue) => {
actions.setAppIcon(payload)
}
@@ -203,7 +203,7 @@ const MCPModalContent: FC<MCPModalContentProps> = ({ data, onConfirm, onHide })
<IconButton
aria-label={t(($) => $['mcp.modal.changeIcon'], { ns: 'tools' })}
className="size-14 rounded-2xl p-0"
- onClick={() => actions.setShowAppIconPicker(true)}
+ onClick={() => actions.setShowIconPicker(true)}
>
<AppIcon
decorative
@@ -349,18 +349,12 @@ const MCPModalContent: FC<MCPModalContentProps> = ({ data, onConfirm, onHide })
<Button onClick={onHide}>{t(($) => $['mcp.modal.cancel'], { ns: 'tools' })}</Button>
</div>
- {state.showAppIconPicker && (
- <AppIconPicker
- open={state.showAppIconPicker}
- initialEmoji={
- state.appIcon.type === 'emoji'
- ? { icon: state.appIcon.icon, background: state.appIcon.background }
- : undefined
- }
- onOpenChange={actions.setShowAppIconPicker}
- onSelect={handleIconSelect}
- />
- )}
+ <IconPickerDialog
+ open={state.showIconPicker}
+ defaultValue={state.appIcon}
+ onOpenChange={actions.setShowIconPicker}
+ onConfirm={handleIconSelect}
+ />
</>
)
}
diff --git a/web/app/components/tools/workflow-tool/index.tsx b/web/app/components/tools/workflow-tool/index.tsx
index 9d9bd02127b..0434ecc892f 100644
--- a/web/app/components/tools/workflow-tool/index.tsx
+++ b/web/app/components/tools/workflow-tool/index.tsx
@@ -29,7 +29,7 @@ import * as React from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import LabelSelector from '@/app/components/tools/labels/selector'
import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'
import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'
@@ -579,15 +579,16 @@ export function WorkflowToolDrawer({
</div>
</form>
</WorkflowToolDrawerFrame>
- <AppIconPicker
+ <IconPickerDialog
open={showEmojiPicker}
enableImageUpload={false}
- initialEmoji={{
+ defaultValue={{
+ type: 'emoji',
icon: emoji.content,
background: emoji.background,
}}
onOpenChange={setShowEmojiPicker}
- onSelect={(payload) => {
+ onConfirm={(payload) => {
if (payload.type === 'emoji')
setEmoji({ content: payload.icon, background: payload.background })
}}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx
index fd49aa752a8..9378644d469 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx
@@ -24,23 +24,23 @@ vi.mock('@/app/notifications', () => ({
toast: toastMock,
}))
-vi.mock('@/app/components/base/app-icon-picker', () => ({
+vi.mock('@/app/components/base/icon-picker', () => ({
__esModule: true,
- default: ({
- initialEmoji,
- onSelect,
+ IconPickerDialog: ({
+ defaultValue,
+ onConfirm,
open,
}: {
- initialEmoji?: { icon: string; background: string }
- onSelect: (payload: { type: 'emoji'; icon: string; background: string }) => void
+ defaultValue?: { icon: string; background: string }
+ onConfirm: (payload: { type: 'emoji'; icon: string; background: string }) => void
open: boolean
}) =>
open ? (
<div>
- <span>{`${initialEmoji?.icon}:${initialEmoji?.background}`}</span>
+ <span>{`${defaultValue?.icon}:${defaultValue?.background}`}</span>
<button
type="button"
- onClick={() => onSelect({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}
+ onClick={() => onConfirm({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}
>
Select brain icon
</button>
diff --git a/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx
index 706010c0125..fc75362528e 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx
@@ -21,7 +21,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useMutation } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { createAgentIconSelection } from '@/features/agent-v2/roster/components/agent-form'
import { AgentFormFields } from '@/features/agent-v2/roster/components/agent-form-fields'
import { consoleQuery } from '@/service/console'
@@ -95,15 +95,11 @@ function SaveInlineAgentToRosterFormSession({
</Button>
</div>
</Form>
- <AppIconPicker
+ <IconPickerDialog
open={iconPickerOpen}
- initialEmoji={
- agentIcon.type === 'emoji'
- ? { icon: agentIcon.icon, background: agentIcon.background }
- : undefined
- }
+ defaultValue={agentIcon.type === 'link' ? undefined : agentIcon}
onOpenChange={setIconPickerOpen}
- onSelect={setAgentIcon}
+ onConfirm={setAgentIcon}
/>
</>
)
diff --git a/web/features/agent-v2/roster/components/__tests__/agent-form.spec.ts b/web/features/agent-v2/roster/components/__tests__/agent-form.spec.ts
index d083bc288ae..57e20316a5d 100644
--- a/web/features/agent-v2/roster/components/__tests__/agent-form.spec.ts
+++ b/web/features/agent-v2/roster/components/__tests__/agent-form.spec.ts
@@ -1,6 +1,24 @@
import { createAgentIconSelection } from '../agent-form'
describe('createAgentIconSelection', () => {
+ it('preserves a Composer image when its response has no resolved icon URL', () => {
+ expect(createAgentIconSelection({ icon_type: 'image', icon: 'uploaded-file-id' })).toEqual({
+ type: 'image',
+ fileId: 'uploaded-file-id',
+ url: 'uploaded-file-id',
+ })
+ })
+
+ it('preserves a Composer link icon', () => {
+ expect(
+ createAgentIconSelection({ icon_type: 'link', icon: 'https://example.com/icon.png' }),
+ ).toEqual({
+ type: 'link',
+ icon: 'https://example.com/icon.png',
+ url: 'https://example.com/icon.png',
+ })
+ })
+
it('uses the resolved image URL while preserving the uploaded file id', () => {
expect(
createAgentIconSelection({
diff --git a/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx
index 4a65d40daea..ff75a4756da 100644
--- a/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx
@@ -17,7 +17,8 @@ const routerPushMock = vi.hoisted(() => vi.fn())
const trackCreateAppMock = vi.hoisted(() => vi.fn())
-vi.mock('@tanstack/react-query', () => ({
+vi.mock('@tanstack/react-query', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@tanstack/react-query')>()),
useMutation: () => ({
isPending: mutationMock.isPending,
mutate: mutationMock.mutate,
diff --git a/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
index 2651f8ac6f0..4b81154e1cf 100644
--- a/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/duplicate-agent-dialog.spec.tsx
@@ -16,15 +16,15 @@ vi.mock('@tanstack/react-query', () => ({
}),
}))
-vi.mock('@/app/components/base/app-icon-picker', () => ({
+vi.mock('@/app/components/base/icon-picker', () => ({
__esModule: true,
- default: ({
- initialEmoji,
+ IconPickerDialog: ({
+ defaultValue,
open,
}: {
- initialEmoji?: { icon: string; background: string }
+ defaultValue?: { icon: string; background: string }
open: boolean
- }) => (open ? <span>{`${initialEmoji?.icon}:${initialEmoji?.background}`}</span> : null),
+ }) => (open ? <span>{`${defaultValue?.icon}:${defaultValue?.background}`}</span> : null),
}))
vi.mock('@/service/console', () => ({
diff --git a/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
index 2ada5b026e6..ca36620d2d1 100644
--- a/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx
@@ -24,23 +24,23 @@ vi.mock('@/app/notifications', () => ({
toast: toastMock,
}))
-vi.mock('@/app/components/base/app-icon-picker', () => ({
+vi.mock('@/app/components/base/icon-picker', () => ({
__esModule: true,
- default: ({
- initialEmoji,
- onSelect,
+ IconPickerDialog: ({
+ defaultValue,
+ onConfirm,
open,
}: {
- initialEmoji?: { icon: string; background: string }
- onSelect: (payload: { type: 'emoji'; icon: string; background: string }) => void
+ defaultValue?: { icon: string; background: string }
+ onConfirm: (payload: { type: 'emoji'; icon: string; background: string }) => void
open: boolean
}) =>
open ? (
<div>
- <span>{`${initialEmoji?.icon}:${initialEmoji?.background}`}</span>
+ <span>{`${defaultValue?.icon}:${defaultValue?.background}`}</span>
<button
type="button"
- onClick={() => onSelect({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}
+ onClick={() => onConfirm({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}
>
Select brain icon
</button>
diff --git a/web/features/agent-v2/roster/components/agent-form.ts b/web/features/agent-v2/roster/components/agent-form.ts
index 89c140fe4f6..482b2014053 100644
--- a/web/features/agent-v2/roster/components/agent-form.ts
+++ b/web/features/agent-v2/roster/components/agent-form.ts
@@ -2,7 +2,8 @@ import type {
AgentAppCreatePayload,
AgentAppPartial,
} from '@dify/contracts/api/console/agent/types.gen'
-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
+import type { AgentComposerAgentResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { IconPickerValue } from '@/app/components/base/icon-picker'
type AgentFormField = 'description' | 'name' | 'role'
@@ -16,7 +17,7 @@ export type AgentFormSource = Pick<
>
export type AgentIconSelection =
- | AppIconSelection
+ | IconPickerValue
| {
type: 'link'
icon: string
@@ -27,21 +28,18 @@ export const defaultAgentIcon = {
type: 'emoji',
icon: '🧸',
background: '#F5F3FF',
-} satisfies AppIconSelection
+} satisfies IconPickerValue
-type AgentIconSource = {
- icon?: string | null
- icon_background?: string | null
- icon_type?: string | null
- icon_url?: string | null
-}
+type AgentIconSource =
+ | Pick<AgentAppPartial, 'icon' | 'icon_background' | 'icon_type' | 'icon_url'>
+ | Pick<AgentComposerAgentResponse, 'icon' | 'icon_background' | 'icon_type'>
export const createAgentIconSelection = (agent: AgentIconSource): AgentIconSelection => {
if (agent.icon_type === 'image' && agent.icon) {
return {
type: 'image',
fileId: agent.icon,
- url: agent.icon_url ?? agent.icon,
+ url: ('icon_url' in agent ? agent.icon_url : undefined) ?? agent.icon,
}
}
diff --git a/web/features/agent-v2/roster/components/create-agent-dialog.tsx b/web/features/agent-v2/roster/components/create-agent-dialog.tsx
index 8f146052f3c..3596da59b80 100644
--- a/web/features/agent-v2/roster/components/create-agent-dialog.tsx
+++ b/web/features/agent-v2/roster/components/create-agent-dialog.tsx
@@ -16,7 +16,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useMutation } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { AgentScope } from '@/features/agent-v2/analytics'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
@@ -84,15 +84,11 @@ function CreateAgentFormSession({
</Button>
</div>
</Form>
- <AppIconPicker
+ <IconPickerDialog
open={iconPickerOpen}
- initialEmoji={
- agentIcon.type === 'emoji'
- ? { icon: agentIcon.icon, background: agentIcon.background }
- : undefined
- }
+ defaultValue={agentIcon.type === 'link' ? undefined : agentIcon}
onOpenChange={setIconPickerOpen}
- onSelect={setAgentIcon}
+ onConfirm={setAgentIcon}
/>
</>
)
diff --git a/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx b/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx
index 79339201ffb..683f02c5762 100644
--- a/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx
+++ b/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx
@@ -15,7 +15,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { createAgentIconSelection } from './agent-form'
@@ -97,15 +97,11 @@ function DuplicateAgentFormSession({
</Button>
</div>
</Form>
- <AppIconPicker
+ <IconPickerDialog
open={iconPickerOpen}
- initialEmoji={
- agentIcon.type === 'emoji'
- ? { icon: agentIcon.icon, background: agentIcon.background }
- : undefined
- }
+ defaultValue={agentIcon.type === 'link' ? undefined : agentIcon}
onOpenChange={setIconPickerOpen}
- onSelect={setAgentIcon}
+ onConfirm={setAgentIcon}
/>
</>
)
diff --git a/web/features/agent-v2/roster/components/edit-agent-dialog.tsx b/web/features/agent-v2/roster/components/edit-agent-dialog.tsx
index e7aec041ece..88661b83134 100644
--- a/web/features/agent-v2/roster/components/edit-agent-dialog.tsx
+++ b/web/features/agent-v2/roster/components/edit-agent-dialog.tsx
@@ -15,7 +15,7 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useMutation } from '@tanstack/react-query'
import { useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { IconPickerDialog } from '@/app/components/base/icon-picker'
import { consoleQuery } from '@/service/console'
import { createAgentIconSelection, getAgentIconKey } from './agent-form'
import { AgentFormFields } from './agent-form-fields'
@@ -119,15 +119,11 @@ function EditAgentFormSession({
</Button>
</div>
</Form>
- <AppIconPicker
+ <IconPickerDialog
open={iconPickerOpen}
- initialEmoji={
- agentIcon.type === 'emoji'
- ? { icon: agentIcon.icon, background: agentIcon.background }
- : undefined
- }
+ defaultValue={agentIcon.type === 'link' ? undefined : agentIcon}
onOpenChange={setIconPickerOpen}
- onSelect={setAgentIcon}
+ onConfirm={setAgentIcon}
/>
</>
)
diff --git a/web/i18n/locales/ar-TN/app.json b/web/i18n/locales/ar-TN/app.json
index aff6bd6cef8..6f9d5dd5a32 100644
--- a/web/i18n/locales/ar-TN/app.json
+++ b/web/i18n/locales/ar-TN/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "جرب مصطلح بحث مختلف",
"iconPicker.cancel": "إلغاء",
"iconPicker.chooseStyle": "اختر النمط",
+ "iconPicker.clearSearch": "مسح البحث",
+ "iconPicker.color.blue": "أزرق",
+ "iconPicker.color.gray": "رمادي",
+ "iconPicker.color.green": "أخضر",
+ "iconPicker.color.indigo": "نيلي",
+ "iconPicker.color.lightBlue": "أزرق فاتح",
+ "iconPicker.color.orange": "برتقالي",
+ "iconPicker.color.pink": "وردي",
+ "iconPicker.color.red": "أحمر",
+ "iconPicker.color.rose": "وردي داكن",
+ "iconPicker.color.teal": "أخضر مزرق",
+ "iconPicker.color.violet": "بنفسجي",
+ "iconPicker.color.yellow": "أصفر",
+ "iconPicker.crop": "اقتصاص الصورة",
+ "iconPicker.currentEmoji": "الرمز التعبيري الحالي: {{emoji}}",
"iconPicker.emoji": "رموز تعبيرية",
"iconPicker.image": "صورة",
"iconPicker.ok": "موافق",
"iconPicker.recent": "الأخيرة",
"iconPicker.recommend": "المقترحة",
"iconPicker.search": "ابحث عن رمز تعبيري…",
+ "iconPicker.title": "اختيار أيقونة",
"iconPicker.tryYourLuck": "جرّب حظك",
+ "iconPicker.zoom": "التكبير",
"importApp": "استيراد التطبيق",
"importAppDescription": "حزمة تطبيق أو ملف DSL",
"importAppFormats": "يدعم .ifpkg و.yaml و.yml",
diff --git a/web/i18n/locales/az-AZ/app.json b/web/i18n/locales/az-AZ/app.json
index b2c086a3c36..606441e59d2 100644
--- a/web/i18n/locales/az-AZ/app.json
+++ b/web/i18n/locales/az-AZ/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Başqa axtarış ifadəsi sınayın",
"iconPicker.cancel": "Ləğv et",
"iconPicker.chooseStyle": "Üslub seçin",
+ "iconPicker.clearSearch": "Axtarışı təmizlə",
+ "iconPicker.color.blue": "Mavi",
+ "iconPicker.color.gray": "Boz",
+ "iconPicker.color.green": "Yaşıl",
+ "iconPicker.color.indigo": "İndiqo",
+ "iconPicker.color.lightBlue": "Açıq mavi",
+ "iconPicker.color.orange": "Narıncı",
+ "iconPicker.color.pink": "Çəhrayı",
+ "iconPicker.color.red": "Qırmızı",
+ "iconPicker.color.rose": "Gül rəngi",
+ "iconPicker.color.teal": "Mavi-yaşıl",
+ "iconPicker.color.violet": "Bənövşəyi",
+ "iconPicker.color.yellow": "Sarı",
+ "iconPicker.crop": "Şəkli kəs",
+ "iconPicker.currentEmoji": "Cari emoji: {{emoji}}",
"iconPicker.emoji": "Emoci",
"iconPicker.image": "Şəkil",
"iconPicker.ok": "Təsdiqlə",
"iconPicker.recent": "Son istifadə olunanlar",
"iconPicker.recommend": "Tövsiyə olunanlar",
"iconPicker.search": "Emoji axtar…",
+ "iconPicker.title": "İkon seçin",
"iconPicker.tryYourLuck": "Şansını sına",
+ "iconPicker.zoom": "Miqyas",
"importApp": "Tətbiq idxal et",
"importAppDescription": "Tətbiq paketi və ya DSL faylı",
"importAppFormats": ".ifpkg, .yaml və .yml dəstəklənir",
diff --git a/web/i18n/locales/de-DE/app.json b/web/i18n/locales/de-DE/app.json
index ff34740d02f..dd27fc8443d 100644
--- a/web/i18n/locales/de-DE/app.json
+++ b/web/i18n/locales/de-DE/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Versuchen Sie es mit einem anderen Suchbegriff",
"iconPicker.cancel": "Abbrechen",
"iconPicker.chooseStyle": "Stil wählen",
+ "iconPicker.clearSearch": "Suche löschen",
+ "iconPicker.color.blue": "Blau",
+ "iconPicker.color.gray": "Grau",
+ "iconPicker.color.green": "Grün",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Hellblau",
+ "iconPicker.color.orange": "Orange",
+ "iconPicker.color.pink": "Pink",
+ "iconPicker.color.red": "Rot",
+ "iconPicker.color.rose": "Rosé",
+ "iconPicker.color.teal": "Blaugrün",
+ "iconPicker.color.violet": "Violett",
+ "iconPicker.color.yellow": "Gelb",
+ "iconPicker.crop": "Bild zuschneiden",
+ "iconPicker.currentEmoji": "Aktuelles Emoji: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Bild",
"iconPicker.ok": "OK",
"iconPicker.recent": "Zuletzt verwendet",
"iconPicker.recommend": "Empfohlen",
"iconPicker.search": "Emoji suchen…",
+ "iconPicker.title": "Symbol auswählen",
"iconPicker.tryYourLuck": "Auf gut Glück",
+ "iconPicker.zoom": "Zoom",
"importApp": "App importieren",
"importAppDescription": "App-Paket oder DSL-Datei",
"importAppFormats": "Unterstützt .ifpkg, .yaml und .yml",
diff --git a/web/i18n/locales/en-US/app.json b/web/i18n/locales/en-US/app.json
index 26ac54877b4..8d423239531 100644
--- a/web/i18n/locales/en-US/app.json
+++ b/web/i18n/locales/en-US/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Try a different search term",
"iconPicker.cancel": "Cancel",
"iconPicker.chooseStyle": "Choose Style",
+ "iconPicker.clearSearch": "Clear search",
+ "iconPicker.color.blue": "Blue",
+ "iconPicker.color.gray": "Gray",
+ "iconPicker.color.green": "Green",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Light blue",
+ "iconPicker.color.orange": "Orange",
+ "iconPicker.color.pink": "Pink",
+ "iconPicker.color.red": "Red",
+ "iconPicker.color.rose": "Rose",
+ "iconPicker.color.teal": "Teal",
+ "iconPicker.color.violet": "Violet",
+ "iconPicker.color.yellow": "Yellow",
+ "iconPicker.crop": "Crop image",
+ "iconPicker.currentEmoji": "Current emoji: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Image",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recent",
"iconPicker.recommend": "Recommend",
"iconPicker.search": "Search emoji...",
+ "iconPicker.title": "Choose icon",
"iconPicker.tryYourLuck": "Try your luck",
+ "iconPicker.zoom": "Zoom",
"importApp": "Import App",
"importAppDescription": "App package or DSL file",
"importAppFormats": "Supports .ifpkg, .yaml, and .yml",
diff --git a/web/i18n/locales/es-ES/app.json b/web/i18n/locales/es-ES/app.json
index 9910714f616..843eb0bc456 100644
--- a/web/i18n/locales/es-ES/app.json
+++ b/web/i18n/locales/es-ES/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Prueba con un término de búsqueda diferente",
"iconPicker.cancel": "Cancelar",
"iconPicker.chooseStyle": "Elegir estilo",
+ "iconPicker.clearSearch": "Borrar búsqueda",
+ "iconPicker.color.blue": "Azul",
+ "iconPicker.color.gray": "Gris",
+ "iconPicker.color.green": "Verde",
+ "iconPicker.color.indigo": "Índigo",
+ "iconPicker.color.lightBlue": "Azul claro",
+ "iconPicker.color.orange": "Naranja",
+ "iconPicker.color.pink": "Rosa",
+ "iconPicker.color.red": "Rojo",
+ "iconPicker.color.rose": "Rosa intenso",
+ "iconPicker.color.teal": "Verde azulado",
+ "iconPicker.color.violet": "Violeta",
+ "iconPicker.color.yellow": "Amarillo",
+ "iconPicker.crop": "Recortar imagen",
+ "iconPicker.currentEmoji": "Emoji actual: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Imagen",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recientes",
"iconPicker.recommend": "Recomendados",
"iconPicker.search": "Buscar emoji…",
+ "iconPicker.title": "Elegir icono",
"iconPicker.tryYourLuck": "Prueba suerte",
+ "iconPicker.zoom": "Zoom",
"importApp": "Importar App",
"importAppDescription": "Paquete de aplicación o archivo DSL",
"importAppFormats": "Admite .ifpkg, .yaml y .yml",
diff --git a/web/i18n/locales/fa-IR/app.json b/web/i18n/locales/fa-IR/app.json
index 75bfe92c116..a822ec1a54f 100644
--- a/web/i18n/locales/fa-IR/app.json
+++ b/web/i18n/locales/fa-IR/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "عبارت جستجوی دیگری را امتحان کنید",
"iconPicker.cancel": "لغو",
"iconPicker.chooseStyle": "انتخاب سبک",
+ "iconPicker.clearSearch": "پاک کردن جستجو",
+ "iconPicker.color.blue": "آبی",
+ "iconPicker.color.gray": "خاکستری",
+ "iconPicker.color.green": "سبز",
+ "iconPicker.color.indigo": "نیلی",
+ "iconPicker.color.lightBlue": "آبی روشن",
+ "iconPicker.color.orange": "نارنجی",
+ "iconPicker.color.pink": "صورتی",
+ "iconPicker.color.red": "قرمز",
+ "iconPicker.color.rose": "رز",
+ "iconPicker.color.teal": "سبزآبی",
+ "iconPicker.color.violet": "بنفش",
+ "iconPicker.color.yellow": "زرد",
+ "iconPicker.crop": "برش تصویر",
+ "iconPicker.currentEmoji": "ایموجی فعلی: {{emoji}}",
"iconPicker.emoji": "ایموجی",
"iconPicker.image": "تصویر",
"iconPicker.ok": "باشه",
"iconPicker.recent": "اخیر",
"iconPicker.recommend": "پیشنهادی",
"iconPicker.search": "جستجوی ایموجی…",
+ "iconPicker.title": "انتخاب نماد",
"iconPicker.tryYourLuck": "شانست را امتحان کن",
+ "iconPicker.zoom": "بزرگ‌نمایی",
"importApp": "وارد کردن برنامه",
"importAppDescription": "بستهٔ برنامه یا فایل DSL",
"importAppFormats": "از .ifpkg، .yaml و .yml پشتیبانی می‌کند",
diff --git a/web/i18n/locales/fr-FR/app.json b/web/i18n/locales/fr-FR/app.json
index 6c61b7a7550..29144b96e9b 100644
--- a/web/i18n/locales/fr-FR/app.json
+++ b/web/i18n/locales/fr-FR/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Essayez un autre terme de recherche",
"iconPicker.cancel": "Annuler",
"iconPicker.chooseStyle": "Choisir un style",
+ "iconPicker.clearSearch": "Effacer la recherche",
+ "iconPicker.color.blue": "Bleu",
+ "iconPicker.color.gray": "Gris",
+ "iconPicker.color.green": "Vert",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Bleu clair",
+ "iconPicker.color.orange": "Orange",
+ "iconPicker.color.pink": "Rose",
+ "iconPicker.color.red": "Rouge",
+ "iconPicker.color.rose": "Rose soutenu",
+ "iconPicker.color.teal": "Sarcelle",
+ "iconPicker.color.violet": "Violet",
+ "iconPicker.color.yellow": "Jaune",
+ "iconPicker.crop": "Recadrer l’image",
+ "iconPicker.currentEmoji": "Emoji actuel : {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Image",
"iconPicker.ok": "OK",
"iconPicker.recent": "Récents",
"iconPicker.recommend": "Recommandés",
"iconPicker.search": "Rechercher un emoji…",
+ "iconPicker.title": "Choisir une icône",
"iconPicker.tryYourLuck": "J’ai de la chance",
+ "iconPicker.zoom": "Zoom",
"importApp": "Importer l'App",
"importAppDescription": "Paquet d’application ou fichier DSL",
"importAppFormats": "Formats pris en charge : .ifpkg, .yaml et .yml",
diff --git a/web/i18n/locales/hi-IN/app.json b/web/i18n/locales/hi-IN/app.json
index 98d9d9f5df3..b038b96ab0d 100644
--- a/web/i18n/locales/hi-IN/app.json
+++ b/web/i18n/locales/hi-IN/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "एक अलग खोज शब्द आजमाएँ",
"iconPicker.cancel": "रद्द करें",
"iconPicker.chooseStyle": "शैली चुनें",
+ "iconPicker.clearSearch": "खोज साफ़ करें",
+ "iconPicker.color.blue": "नीला",
+ "iconPicker.color.gray": "धूसर",
+ "iconPicker.color.green": "हरा",
+ "iconPicker.color.indigo": "जामुनी",
+ "iconPicker.color.lightBlue": "हल्का नीला",
+ "iconPicker.color.orange": "नारंगी",
+ "iconPicker.color.pink": "गुलाबी",
+ "iconPicker.color.red": "लाल",
+ "iconPicker.color.rose": "गुलाब रंग",
+ "iconPicker.color.teal": "नीला-हरा",
+ "iconPicker.color.violet": "बैंगनी",
+ "iconPicker.color.yellow": "पीला",
+ "iconPicker.crop": "चित्र क्रॉप करें",
+ "iconPicker.currentEmoji": "वर्तमान इमोजी: {{emoji}}",
"iconPicker.emoji": "इमोजी",
"iconPicker.image": "छवि",
"iconPicker.ok": "ठीक है",
"iconPicker.recent": "हाल के",
"iconPicker.recommend": "सुझाए गए",
"iconPicker.search": "इमोजी खोजें…",
+ "iconPicker.title": "आइकन चुनें",
"iconPicker.tryYourLuck": "किस्मत आज़माएँ",
+ "iconPicker.zoom": "ज़ूम",
"importApp": "ऐप आयात करें",
"importAppDescription": "ऐप पैकेज या DSL फ़ाइल",
"importAppFormats": ".ifpkg, .yaml और .yml समर्थित हैं",
diff --git a/web/i18n/locales/id-ID/app.json b/web/i18n/locales/id-ID/app.json
index ad75caf24b6..51f7ad40ee7 100644
--- a/web/i18n/locales/id-ID/app.json
+++ b/web/i18n/locales/id-ID/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Coba istilah penelusuran lain",
"iconPicker.cancel": "Batal",
"iconPicker.chooseStyle": "Pilih gaya",
+ "iconPicker.clearSearch": "Hapus pencarian",
+ "iconPicker.color.blue": "Biru",
+ "iconPicker.color.gray": "Abu-abu",
+ "iconPicker.color.green": "Hijau",
+ "iconPicker.color.indigo": "Nila",
+ "iconPicker.color.lightBlue": "Biru muda",
+ "iconPicker.color.orange": "Oranye",
+ "iconPicker.color.pink": "Merah muda",
+ "iconPicker.color.red": "Merah",
+ "iconPicker.color.rose": "Merah mawar",
+ "iconPicker.color.teal": "Hijau kebiruan",
+ "iconPicker.color.violet": "Ungu",
+ "iconPicker.color.yellow": "Kuning",
+ "iconPicker.crop": "Pangkas gambar",
+ "iconPicker.currentEmoji": "Emoji saat ini: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Citra",
"iconPicker.ok": "OK",
"iconPicker.recent": "Terbaru",
"iconPicker.recommend": "Rekomendasi",
"iconPicker.search": "Cari emoji…",
+ "iconPicker.title": "Pilih ikon",
"iconPicker.tryYourLuck": "Coba keberuntungan",
+ "iconPicker.zoom": "Zoom",
"importApp": "Impor Aplikasi",
"importAppDescription": "Paket aplikasi atau file DSL",
"importAppFormats": "Mendukung .ifpkg, .yaml, dan .yml",
diff --git a/web/i18n/locales/it-IT/app.json b/web/i18n/locales/it-IT/app.json
index 0a2d61daf70..e86b4347888 100644
--- a/web/i18n/locales/it-IT/app.json
+++ b/web/i18n/locales/it-IT/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Prova un termine di ricerca diverso",
"iconPicker.cancel": "Annulla",
"iconPicker.chooseStyle": "Scegli stile",
+ "iconPicker.clearSearch": "Cancella ricerca",
+ "iconPicker.color.blue": "Blu",
+ "iconPicker.color.gray": "Grigio",
+ "iconPicker.color.green": "Verde",
+ "iconPicker.color.indigo": "Indaco",
+ "iconPicker.color.lightBlue": "Azzurro",
+ "iconPicker.color.orange": "Arancione",
+ "iconPicker.color.pink": "Rosa",
+ "iconPicker.color.red": "Rosso",
+ "iconPicker.color.rose": "Rosa intenso",
+ "iconPicker.color.teal": "Verde acqua",
+ "iconPicker.color.violet": "Viola",
+ "iconPicker.color.yellow": "Giallo",
+ "iconPicker.crop": "Ritaglia immagine",
+ "iconPicker.currentEmoji": "Emoji attuale: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Immagine",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recenti",
"iconPicker.recommend": "Consigliati",
"iconPicker.search": "Cerca emoji…",
+ "iconPicker.title": "Scegli icona",
"iconPicker.tryYourLuck": "Tenta la fortuna",
+ "iconPicker.zoom": "Zoom",
"importApp": "Importa App",
"importAppDescription": "Pacchetto app o file DSL",
"importAppFormats": "Supporta .ifpkg, .yaml e .yml",
diff --git a/web/i18n/locales/ja-JP/app.json b/web/i18n/locales/ja-JP/app.json
index d5bbf457306..0f98ae1678c 100644
--- a/web/i18n/locales/ja-JP/app.json
+++ b/web/i18n/locales/ja-JP/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "別の検索語句をお試しください",
"iconPicker.cancel": "キャンセル",
"iconPicker.chooseStyle": "スタイルを選択",
+ "iconPicker.clearSearch": "検索をクリア",
+ "iconPicker.color.blue": "青",
+ "iconPicker.color.gray": "グレー",
+ "iconPicker.color.green": "緑",
+ "iconPicker.color.indigo": "藍色",
+ "iconPicker.color.lightBlue": "水色",
+ "iconPicker.color.orange": "オレンジ",
+ "iconPicker.color.pink": "ピンク",
+ "iconPicker.color.red": "赤",
+ "iconPicker.color.rose": "ローズ",
+ "iconPicker.color.teal": "青緑",
+ "iconPicker.color.violet": "紫",
+ "iconPicker.color.yellow": "黄",
+ "iconPicker.crop": "画像を切り抜く",
+ "iconPicker.currentEmoji": "現在の絵文字:{{emoji}}",
"iconPicker.emoji": "絵文字",
"iconPicker.image": "画像",
"iconPicker.ok": "OK",
"iconPicker.recent": "最近使用",
"iconPicker.recommend": "おすすめ",
"iconPicker.search": "絵文字を検索…",
+ "iconPicker.title": "アイコンを選択",
"iconPicker.tryYourLuck": "運試し",
+ "iconPicker.zoom": "ズーム",
"importApp": "アプリをインポート",
"importAppDescription": "アプリパッケージまたは DSL ファイル",
"importAppFormats": "対応形式:.ifpkg、.yaml、.yml",
diff --git a/web/i18n/locales/ko-KR/app.json b/web/i18n/locales/ko-KR/app.json
index debd4f26ab3..de55c0e7ce8 100644
--- a/web/i18n/locales/ko-KR/app.json
+++ b/web/i18n/locales/ko-KR/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "다른 검색어 사용해 보기",
"iconPicker.cancel": "취소",
"iconPicker.chooseStyle": "스타일 선택",
+ "iconPicker.clearSearch": "검색 지우기",
+ "iconPicker.color.blue": "파랑",
+ "iconPicker.color.gray": "회색",
+ "iconPicker.color.green": "초록",
+ "iconPicker.color.indigo": "남색",
+ "iconPicker.color.lightBlue": "하늘색",
+ "iconPicker.color.orange": "주황",
+ "iconPicker.color.pink": "분홍",
+ "iconPicker.color.red": "빨강",
+ "iconPicker.color.rose": "장미색",
+ "iconPicker.color.teal": "청록",
+ "iconPicker.color.violet": "보라",
+ "iconPicker.color.yellow": "노랑",
+ "iconPicker.crop": "이미지 자르기",
+ "iconPicker.currentEmoji": "현재 이모지: {{emoji}}",
"iconPicker.emoji": "이모지",
"iconPicker.image": "이미지",
"iconPicker.ok": "확인",
"iconPicker.recent": "최근 사용",
"iconPicker.recommend": "추천",
"iconPicker.search": "이모지 검색…",
+ "iconPicker.title": "아이콘 선택",
"iconPicker.tryYourLuck": "행운을 시험해 보세요",
+ "iconPicker.zoom": "확대/축소",
"importApp": "앱 가져오기",
"importAppDescription": "앱 패키지 또는 DSL 파일",
"importAppFormats": ".ifpkg, .yaml 및 .yml 지원",
diff --git a/web/i18n/locales/lo-LA/app.json b/web/i18n/locales/lo-LA/app.json
index b08fd49df17..c499854c48c 100644
--- a/web/i18n/locales/lo-LA/app.json
+++ b/web/i18n/locales/lo-LA/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "ລອງໃຊ້ຄຳຄົ້ນຫາອື່ນ",
"iconPicker.cancel": "ຍົກເລີກ",
"iconPicker.chooseStyle": "ເລືອກຮູບແບບ",
+ "iconPicker.clearSearch": "ລ້າງການຄົ້ນຫາ",
+ "iconPicker.color.blue": "ສີຟ້າ",
+ "iconPicker.color.gray": "ສີເທົາ",
+ "iconPicker.color.green": "ສີຂຽວ",
+ "iconPicker.color.indigo": "ສີຄາມ",
+ "iconPicker.color.lightBlue": "ສີຟ້າອ່ອນ",
+ "iconPicker.color.orange": "ສີສົ້ມ",
+ "iconPicker.color.pink": "ສີບົວ",
+ "iconPicker.color.red": "ສີແດງ",
+ "iconPicker.color.rose": "ສີກຸຫຼາບ",
+ "iconPicker.color.teal": "ສີຂຽວອົມຟ້າ",
+ "iconPicker.color.violet": "ສີມ່ວງ",
+ "iconPicker.color.yellow": "ສີເຫຼືອງ",
+ "iconPicker.crop": "ຕັດຮູບພາບ",
+ "iconPicker.currentEmoji": "ອີໂມຈິປັດຈຸບັນ: {{emoji}}",
"iconPicker.emoji": "ອີໂມຈິ",
"iconPicker.image": "ຮູບພາບ",
"iconPicker.ok": "ຕົກລົງ",
"iconPicker.recent": "ຫຼ້າສຸດ",
"iconPicker.recommend": "ແນະນຳ",
"iconPicker.search": "ຄົ້ນຫາອີໂມຈິ…",
+ "iconPicker.title": "ເລືອກໄອຄອນ",
"iconPicker.tryYourLuck": "ລອງໂຊກຂອງທ່ານ",
+ "iconPicker.zoom": "ຊູມ",
"importApp": "ນຳເຂົ້າແອັບ",
"importAppDescription": "ແພັກເກດແອັບ ຫຼື ໄຟລ໌ DSL",
"importAppFormats": "ຮອງຮັບ .ifpkg, .yaml ແລະ .yml",
diff --git a/web/i18n/locales/nl-NL/app.json b/web/i18n/locales/nl-NL/app.json
index 3b311ccdf82..399a1f12194 100644
--- a/web/i18n/locales/nl-NL/app.json
+++ b/web/i18n/locales/nl-NL/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Try a different search term",
"iconPicker.cancel": "Cancel",
"iconPicker.chooseStyle": "Kies stijl",
+ "iconPicker.clearSearch": "Zoekopdracht wissen",
+ "iconPicker.color.blue": "Blauw",
+ "iconPicker.color.gray": "Grijs",
+ "iconPicker.color.green": "Groen",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Lichtblauw",
+ "iconPicker.color.orange": "Oranje",
+ "iconPicker.color.pink": "Roze",
+ "iconPicker.color.red": "Rood",
+ "iconPicker.color.rose": "Rozerood",
+ "iconPicker.color.teal": "Blauwgroen",
+ "iconPicker.color.violet": "Violet",
+ "iconPicker.color.yellow": "Geel",
+ "iconPicker.crop": "Afbeelding bijsnijden",
+ "iconPicker.currentEmoji": "Huidige emoji: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Image",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recent",
"iconPicker.recommend": "Aanbevolen",
"iconPicker.search": "Emoji zoeken…",
+ "iconPicker.title": "Pictogram kiezen",
"iconPicker.tryYourLuck": "Doe een gok",
+ "iconPicker.zoom": "Zoom",
"importApp": "App importeren",
"importAppDescription": "App-pakket of DSL-bestand",
"importAppFormats": "Ondersteunt .ifpkg, .yaml en .yml",
diff --git a/web/i18n/locales/pl-PL/app.json b/web/i18n/locales/pl-PL/app.json
index a37e8d05833..81852de195e 100644
--- a/web/i18n/locales/pl-PL/app.json
+++ b/web/i18n/locales/pl-PL/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Spróbuj użyć innego hasła",
"iconPicker.cancel": "Anuluj",
"iconPicker.chooseStyle": "Wybierz styl",
+ "iconPicker.clearSearch": "Wyczyść wyszukiwanie",
+ "iconPicker.color.blue": "Niebieski",
+ "iconPicker.color.gray": "Szary",
+ "iconPicker.color.green": "Zielony",
+ "iconPicker.color.indigo": "Indygo",
+ "iconPicker.color.lightBlue": "Jasnoniebieski",
+ "iconPicker.color.orange": "Pomarańczowy",
+ "iconPicker.color.pink": "Różowy",
+ "iconPicker.color.red": "Czerwony",
+ "iconPicker.color.rose": "Różany",
+ "iconPicker.color.teal": "Morski",
+ "iconPicker.color.violet": "Fioletowy",
+ "iconPicker.color.yellow": "Żółty",
+ "iconPicker.crop": "Przytnij obraz",
+ "iconPicker.currentEmoji": "Bieżące emoji: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Obraz",
"iconPicker.ok": "OK",
"iconPicker.recent": "Ostatnie",
"iconPicker.recommend": "Polecane",
"iconPicker.search": "Szukaj emoji…",
+ "iconPicker.title": "Wybierz ikonę",
"iconPicker.tryYourLuck": "Spróbuj szczęścia",
+ "iconPicker.zoom": "Powiększenie",
"importApp": "Importuj aplikację",
"importAppDescription": "Pakiet aplikacji lub plik DSL",
"importAppFormats": "Obsługuje .ifpkg, .yaml i .yml",
diff --git a/web/i18n/locales/pt-BR/app.json b/web/i18n/locales/pt-BR/app.json
index 4f67659f4ee..19f390e9423 100644
--- a/web/i18n/locales/pt-BR/app.json
+++ b/web/i18n/locales/pt-BR/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Tente um termo de pesquisa diferente",
"iconPicker.cancel": "Cancelar",
"iconPicker.chooseStyle": "Escolher estilo",
+ "iconPicker.clearSearch": "Limpar pesquisa",
+ "iconPicker.color.blue": "Azul",
+ "iconPicker.color.gray": "Cinza",
+ "iconPicker.color.green": "Verde",
+ "iconPicker.color.indigo": "Índigo",
+ "iconPicker.color.lightBlue": "Azul-claro",
+ "iconPicker.color.orange": "Laranja",
+ "iconPicker.color.pink": "Rosa",
+ "iconPicker.color.red": "Vermelho",
+ "iconPicker.color.rose": "Rosa intenso",
+ "iconPicker.color.teal": "Verde-azulado",
+ "iconPicker.color.violet": "Violeta",
+ "iconPicker.color.yellow": "Amarelo",
+ "iconPicker.crop": "Recortar imagem",
+ "iconPicker.currentEmoji": "Emoji atual: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Imagem",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recentes",
"iconPicker.recommend": "Recomendados",
"iconPicker.search": "Buscar emoji…",
+ "iconPicker.title": "Escolher ícone",
"iconPicker.tryYourLuck": "Tente a sorte",
+ "iconPicker.zoom": "Zoom",
"importApp": "Importar App",
"importAppDescription": "Pacote de aplicativo ou arquivo DSL",
"importAppFormats": "Suporta .ifpkg, .yaml e .yml",
diff --git a/web/i18n/locales/ro-RO/app.json b/web/i18n/locales/ro-RO/app.json
index 184f2598838..1a187d1b3ee 100644
--- a/web/i18n/locales/ro-RO/app.json
+++ b/web/i18n/locales/ro-RO/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Încercați un alt termen de căutare",
"iconPicker.cancel": "Anulează",
"iconPicker.chooseStyle": "Alege stilul",
+ "iconPicker.clearSearch": "Șterge căutarea",
+ "iconPicker.color.blue": "Albastru",
+ "iconPicker.color.gray": "Gri",
+ "iconPicker.color.green": "Verde",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Albastru deschis",
+ "iconPicker.color.orange": "Portocaliu",
+ "iconPicker.color.pink": "Roz",
+ "iconPicker.color.red": "Roșu",
+ "iconPicker.color.rose": "Trandafiriu",
+ "iconPicker.color.teal": "Verde-albăstrui",
+ "iconPicker.color.violet": "Violet",
+ "iconPicker.color.yellow": "Galben",
+ "iconPicker.crop": "Decupează imaginea",
+ "iconPicker.currentEmoji": "Emoji curent: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Imagine",
"iconPicker.ok": "OK",
"iconPicker.recent": "Recente",
"iconPicker.recommend": "Recomandate",
"iconPicker.search": "Caută emoji…",
+ "iconPicker.title": "Alege pictograma",
"iconPicker.tryYourLuck": "Încearcă-ți norocul",
+ "iconPicker.zoom": "Zoom",
"importApp": "Importați aplicația",
"importAppDescription": "Pachet de aplicație sau fișier DSL",
"importAppFormats": "Acceptă .ifpkg, .yaml și .yml",
diff --git a/web/i18n/locales/ru-RU/app.json b/web/i18n/locales/ru-RU/app.json
index 7a2eb619d6c..eb7f4340b6f 100644
--- a/web/i18n/locales/ru-RU/app.json
+++ b/web/i18n/locales/ru-RU/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Попробуйте использовать другой поисковый запрос",
"iconPicker.cancel": "Отмена",
"iconPicker.chooseStyle": "Выбрать стиль",
+ "iconPicker.clearSearch": "Очистить поиск",
+ "iconPicker.color.blue": "Синий",
+ "iconPicker.color.gray": "Серый",
+ "iconPicker.color.green": "Зелёный",
+ "iconPicker.color.indigo": "Индиго",
+ "iconPicker.color.lightBlue": "Голубой",
+ "iconPicker.color.orange": "Оранжевый",
+ "iconPicker.color.pink": "Розовый",
+ "iconPicker.color.red": "Красный",
+ "iconPicker.color.rose": "Розово-красный",
+ "iconPicker.color.teal": "Бирюзовый",
+ "iconPicker.color.violet": "Фиолетовый",
+ "iconPicker.color.yellow": "Жёлтый",
+ "iconPicker.crop": "Обрезать изображение",
+ "iconPicker.currentEmoji": "Текущий эмодзи: {{emoji}}",
"iconPicker.emoji": "Эмодзи",
"iconPicker.image": "Изображение",
"iconPicker.ok": "ОК",
"iconPicker.recent": "Недавние",
"iconPicker.recommend": "Рекомендуемые",
"iconPicker.search": "Поиск эмодзи…",
+ "iconPicker.title": "Выбрать значок",
"iconPicker.tryYourLuck": "Испытать удачу",
+ "iconPicker.zoom": "Масштаб",
"importApp": "Импортировать приложение",
"importAppDescription": "Пакет приложения или файл DSL",
"importAppFormats": "Поддерживаются .ifpkg, .yaml и .yml",
diff --git a/web/i18n/locales/sl-SI/app.json b/web/i18n/locales/sl-SI/app.json
index e6cb88a7320..ac89540b88f 100644
--- a/web/i18n/locales/sl-SI/app.json
+++ b/web/i18n/locales/sl-SI/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Poskusite uporabiti drug iskalni izraz",
"iconPicker.cancel": "Prekliči",
"iconPicker.chooseStyle": "Izberi slog",
+ "iconPicker.clearSearch": "Počisti iskanje",
+ "iconPicker.color.blue": "Modra",
+ "iconPicker.color.gray": "Siva",
+ "iconPicker.color.green": "Zelena",
+ "iconPicker.color.indigo": "Indigo",
+ "iconPicker.color.lightBlue": "Svetlo modra",
+ "iconPicker.color.orange": "Oranžna",
+ "iconPicker.color.pink": "Rožnata",
+ "iconPicker.color.red": "Rdeča",
+ "iconPicker.color.rose": "Rožnato rdeča",
+ "iconPicker.color.teal": "Modrozelena",
+ "iconPicker.color.violet": "Vijolična",
+ "iconPicker.color.yellow": "Rumena",
+ "iconPicker.crop": "Obreži sliko",
+ "iconPicker.currentEmoji": "Trenutni čustvenček: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Slika",
"iconPicker.ok": "V redu",
"iconPicker.recent": "Nedavno",
"iconPicker.recommend": "Priporočeno",
"iconPicker.search": "Poišči čustveni simbol…",
+ "iconPicker.title": "Izberi ikono",
"iconPicker.tryYourLuck": "Poskusi srečo",
+ "iconPicker.zoom": "Povečava",
"importApp": "Uvozi aplikacijo",
"importAppDescription": "Paket aplikacije ali datoteka DSL",
"importAppFormats": "Podpira .ifpkg, .yaml in .yml",
diff --git a/web/i18n/locales/th-TH/app.json b/web/i18n/locales/th-TH/app.json
index 6c16cb6a1ec..79334f2c20b 100644
--- a/web/i18n/locales/th-TH/app.json
+++ b/web/i18n/locales/th-TH/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "ลองใช้ข้อความค้นหาอื่น",
"iconPicker.cancel": "ยกเลิก",
"iconPicker.chooseStyle": "เลือกรูปแบบ",
+ "iconPicker.clearSearch": "ล้างการค้นหา",
+ "iconPicker.color.blue": "น้ำเงิน",
+ "iconPicker.color.gray": "เทา",
+ "iconPicker.color.green": "เขียว",
+ "iconPicker.color.indigo": "คราม",
+ "iconPicker.color.lightBlue": "ฟ้าอ่อน",
+ "iconPicker.color.orange": "ส้ม",
+ "iconPicker.color.pink": "ชมพู",
+ "iconPicker.color.red": "แดง",
+ "iconPicker.color.rose": "สีกุหลาบ",
+ "iconPicker.color.teal": "เขียวอมฟ้า",
+ "iconPicker.color.violet": "ม่วง",
+ "iconPicker.color.yellow": "เหลือง",
+ "iconPicker.crop": "ครอบตัดรูปภาพ",
+ "iconPicker.currentEmoji": "อีโมจิปัจจุบัน: {{emoji}}",
"iconPicker.emoji": "อิโมจิ",
"iconPicker.image": "ภาพ",
"iconPicker.ok": "ตกลง, ได้",
"iconPicker.recent": "ล่าสุด",
"iconPicker.recommend": "แนะนำ",
"iconPicker.search": "ค้นหาอีโมจิ…",
+ "iconPicker.title": "เลือกไอคอน",
"iconPicker.tryYourLuck": "ลองเสี่ยงโชค",
+ "iconPicker.zoom": "ซูม",
"importApp": "นำเข้าแอป",
"importAppDescription": "แพ็กเกจแอปหรือไฟล์ DSL",
"importAppFormats": "รองรับ .ifpkg, .yaml และ .yml",
diff --git a/web/i18n/locales/tr-TR/app.json b/web/i18n/locales/tr-TR/app.json
index 1f8e36c24eb..c1c3ec2169a 100644
--- a/web/i18n/locales/tr-TR/app.json
+++ b/web/i18n/locales/tr-TR/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Farklı bir arama terimi deneyin",
"iconPicker.cancel": "İptal",
"iconPicker.chooseStyle": "Stil seç",
+ "iconPicker.clearSearch": "Aramayı temizle",
+ "iconPicker.color.blue": "Mavi",
+ "iconPicker.color.gray": "Gri",
+ "iconPicker.color.green": "Yeşil",
+ "iconPicker.color.indigo": "Çivit mavisi",
+ "iconPicker.color.lightBlue": "Açık mavi",
+ "iconPicker.color.orange": "Turuncu",
+ "iconPicker.color.pink": "Pembe",
+ "iconPicker.color.red": "Kırmızı",
+ "iconPicker.color.rose": "Gül rengi",
+ "iconPicker.color.teal": "Camgöbeği",
+ "iconPicker.color.violet": "Mor",
+ "iconPicker.color.yellow": "Sarı",
+ "iconPicker.crop": "Görseli kırp",
+ "iconPicker.currentEmoji": "Geçerli emoji: {{emoji}}",
"iconPicker.emoji": "Emoji",
"iconPicker.image": "Görsel",
"iconPicker.ok": "Tamam",
"iconPicker.recent": "Son kullanılanlar",
"iconPicker.recommend": "Önerilenler",
"iconPicker.search": "Emoji ara…",
+ "iconPicker.title": "Simge seç",
"iconPicker.tryYourLuck": "Şansını dene",
+ "iconPicker.zoom": "Yakınlaştırma",
"importApp": "Uygulamayı İçe Aktar",
"importAppDescription": "Uygulama paketi veya DSL dosyası",
"importAppFormats": ".ifpkg, .yaml ve .yml desteklenir",
diff --git a/web/i18n/locales/uk-UA/app.json b/web/i18n/locales/uk-UA/app.json
index b407051da7b..b658e0276f4 100644
--- a/web/i18n/locales/uk-UA/app.json
+++ b/web/i18n/locales/uk-UA/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Спробуйте інший пошуковий термін",
"iconPicker.cancel": "Скасувати",
"iconPicker.chooseStyle": "Вибрати стиль",
+ "iconPicker.clearSearch": "Очистити пошук",
+ "iconPicker.color.blue": "Синій",
+ "iconPicker.color.gray": "Сірий",
+ "iconPicker.color.green": "Зелений",
+ "iconPicker.color.indigo": "Індиго",
+ "iconPicker.color.lightBlue": "Блакитний",
+ "iconPicker.color.orange": "Помаранчевий",
+ "iconPicker.color.pink": "Рожевий",
+ "iconPicker.color.red": "Червоний",
+ "iconPicker.color.rose": "Трояндовий",
+ "iconPicker.color.teal": "Бірюзовий",
+ "iconPicker.color.violet": "Фіолетовий",
+ "iconPicker.color.yellow": "Жовтий",
+ "iconPicker.crop": "Обрізати зображення",
+ "iconPicker.currentEmoji": "Поточний емодзі: {{emoji}}",
"iconPicker.emoji": "Емодзі",
"iconPicker.image": "Зображення",
"iconPicker.ok": "OK",
"iconPicker.recent": "Нещодавні",
"iconPicker.recommend": "Рекомендовані",
"iconPicker.search": "Пошук емодзі…",
+ "iconPicker.title": "Вибрати піктограму",
"iconPicker.tryYourLuck": "Спробувати удачу",
+ "iconPicker.zoom": "Масштаб",
"importApp": "Імпортувати додаток",
"importAppDescription": "Пакет застосунку або файл DSL",
"importAppFormats": "Підтримуються .ifpkg, .yaml та .yml",
diff --git a/web/i18n/locales/vi-VN/app.json b/web/i18n/locales/vi-VN/app.json
index 11bf8f99780..82fb18da6f3 100644
--- a/web/i18n/locales/vi-VN/app.json
+++ b/web/i18n/locales/vi-VN/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "Thử một cụm từ tìm kiếm khác",
"iconPicker.cancel": "Hủy",
"iconPicker.chooseStyle": "Chọn kiểu",
+ "iconPicker.clearSearch": "Xóa tìm kiếm",
+ "iconPicker.color.blue": "Xanh dương",
+ "iconPicker.color.gray": "Xám",
+ "iconPicker.color.green": "Xanh lá",
+ "iconPicker.color.indigo": "Chàm",
+ "iconPicker.color.lightBlue": "Xanh dương nhạt",
+ "iconPicker.color.orange": "Cam",
+ "iconPicker.color.pink": "Hồng",
+ "iconPicker.color.red": "Đỏ",
+ "iconPicker.color.rose": "Hồng đậm",
+ "iconPicker.color.teal": "Xanh mòng két",
+ "iconPicker.color.violet": "Tím",
+ "iconPicker.color.yellow": "Vàng",
+ "iconPicker.crop": "Cắt ảnh",
+ "iconPicker.currentEmoji": "Biểu tượng cảm xúc hiện tại: {{emoji}}",
"iconPicker.emoji": "Biểu tượng cảm xúc",
"iconPicker.image": "Hình ảnh",
"iconPicker.ok": "Đồng ý",
"iconPicker.recent": "Gần đây",
"iconPicker.recommend": "Đề xuất",
"iconPicker.search": "Tìm biểu tượng cảm xúc…",
+ "iconPicker.title": "Chọn biểu tượng",
"iconPicker.tryYourLuck": "Thử vận may",
+ "iconPicker.zoom": "Thu phóng",
"importApp": "Nhập App",
"importAppDescription": "Gói ứng dụng hoặc tệp DSL",
"importAppFormats": "Hỗ trợ .ifpkg, .yaml và .yml",
diff --git a/web/i18n/locales/zh-Hans/app.json b/web/i18n/locales/zh-Hans/app.json
index be15cf15726..af786e11aaf 100644
--- a/web/i18n/locales/zh-Hans/app.json
+++ b/web/i18n/locales/zh-Hans/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "请尝试不同的搜索词",
"iconPicker.cancel": "取消",
"iconPicker.chooseStyle": "选择样式",
+ "iconPicker.clearSearch": "清空搜索",
+ "iconPicker.color.blue": "蓝色",
+ "iconPicker.color.gray": "灰色",
+ "iconPicker.color.green": "绿色",
+ "iconPicker.color.indigo": "靛蓝色",
+ "iconPicker.color.lightBlue": "浅蓝色",
+ "iconPicker.color.orange": "橙色",
+ "iconPicker.color.pink": "粉色",
+ "iconPicker.color.red": "红色",
+ "iconPicker.color.rose": "玫瑰色",
+ "iconPicker.color.teal": "青绿色",
+ "iconPicker.color.violet": "紫色",
+ "iconPicker.color.yellow": "黄色",
+ "iconPicker.crop": "裁剪图片",
+ "iconPicker.currentEmoji": "当前表情:{{emoji}}",
"iconPicker.emoji": "表情符号",
"iconPicker.image": "图片",
"iconPicker.ok": "确认",
"iconPicker.recent": "最近使用",
"iconPicker.recommend": "推荐",
"iconPicker.search": "搜索表情…",
+ "iconPicker.title": "选择图标",
"iconPicker.tryYourLuck": "试试手气",
+ "iconPicker.zoom": "缩放",
"importApp": "导入应用",
"importAppDescription": "应用包或 DSL 文件",
"importAppFormats": "支持 .ifpkg、.yaml 和 .yml",
diff --git a/web/i18n/locales/zh-Hant/app.json b/web/i18n/locales/zh-Hant/app.json
index 32762ea4893..d7e4c4491c0 100644
--- a/web/i18n/locales/zh-Hant/app.json
+++ b/web/i18n/locales/zh-Hant/app.json
@@ -113,13 +113,30 @@
"gotoAnything.tryDifferentSearch": "嘗試其他搜尋字詞",
"iconPicker.cancel": "取消",
"iconPicker.chooseStyle": "選擇樣式",
+ "iconPicker.clearSearch": "清除搜尋",
+ "iconPicker.color.blue": "藍色",
+ "iconPicker.color.gray": "灰色",
+ "iconPicker.color.green": "綠色",
+ "iconPicker.color.indigo": "靛藍色",
+ "iconPicker.color.lightBlue": "淺藍色",
+ "iconPicker.color.orange": "橙色",
+ "iconPicker.color.pink": "粉紅色",
+ "iconPicker.color.red": "紅色",
+ "iconPicker.color.rose": "玫瑰色",
+ "iconPicker.color.teal": "青綠色",
+ "iconPicker.color.violet": "紫色",
+ "iconPicker.color.yellow": "黃色",
+ "iconPicker.crop": "裁剪圖片",
+ "iconPicker.currentEmoji": "目前表情:{{emoji}}",
"iconPicker.emoji": "表情符號",
"iconPicker.image": "圖片",
"iconPicker.ok": "確認",
"iconPicker.recent": "最近使用",
"iconPicker.recommend": "推薦",
"iconPicker.search": "搜尋表情…",
+ "iconPicker.title": "選擇圖示",
"iconPicker.tryYourLuck": "試試手氣",
+ "iconPicker.zoom": "縮放",
"importApp": "匯入應用",
"importAppDescription": "應用套件或 DSL 檔案",
"importAppFormats": "支援 .ifpkg、.yaml 和 .yml",
diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts
index e89f211cfb6..f2e2df1b8a9 100644
--- a/web/i18n/resources.generated.d.ts
+++ b/web/i18n/resources.generated.d.ts
@@ -595,13 +595,30 @@ export default interface Resources {
'gotoAnything.tryDifferentSearch': 'Try a different search term'
'iconPicker.cancel': 'Cancel'
'iconPicker.chooseStyle': 'Choose Style'
+ 'iconPicker.clearSearch': 'Clear search'
+ 'iconPicker.color.blue': 'Blue'
+ 'iconPicker.color.gray': 'Gray'
+ 'iconPicker.color.green': 'Green'
+ 'iconPicker.color.indigo': 'Indigo'
+ 'iconPicker.color.lightBlue': 'Light blue'
+ 'iconPicker.color.orange': 'Orange'
+ 'iconPicker.color.pink': 'Pink'
+ 'iconPicker.color.red': 'Red'
+ 'iconPicker.color.rose': 'Rose'
+ 'iconPicker.color.teal': 'Teal'
+ 'iconPicker.color.violet': 'Violet'
+ 'iconPicker.color.yellow': 'Yellow'
+ 'iconPicker.crop': 'Crop image'
+ 'iconPicker.currentEmoji': 'Current emoji: {{emoji}}'
'iconPicker.emoji': 'Emoji'
'iconPicker.image': 'Image'
'iconPicker.ok': 'OK'
'iconPicker.recent': 'Recent'
'iconPicker.recommend': 'Recommend'
'iconPicker.search': 'Search emoji...'
+ 'iconPicker.title': 'Choose icon'
'iconPicker.tryYourLuck': 'Try your luck'
+ 'iconPicker.zoom': 'Zoom'
importApp: 'Import App'
importAppDescription: 'App package or DSL file'
importAppFormats: 'Supports .ifpkg, .yaml, and .yml'
diff --git a/web/package.json b/web/package.json
index c3ec74eaf11..218a622ef72 100644
--- a/web/package.json
+++ b/web/package.json
@@ -84,7 +84,6 @@
"es-toolkit": "catalog:",
"fast-deep-equal": "catalog:",
"foxact": "catalog:",
- "frimousse": "catalog:",
"fuse.js": "catalog:",
"hast-util-to-jsx-runtime": "catalog:",
"html-entities": "catalog:",
diff --git a/web/service/console/client.spec.ts b/web/service/console/client.spec.ts
index 940fdd817c4..be80aa86d00 100644
--- a/web/service/console/client.spec.ts
+++ b/web/service/console/client.spec.ts
@@ -184,6 +184,33 @@ const createWorkflowComposerState = (
// Scenario: base URL selection and warnings.
describe('consoleQuery transport context', () => {
+ it('uploads icon files as multipart data through the Console transport', async () => {
+ const file = new File(['GIF89a'], 'icon.gif', { type: 'image/gif' })
+ const response = { id: 'uploaded-icon', name: file.name, size: file.size }
+ const request = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify(response), {
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ }),
+ )
+ const consoleQuery = await loadConsoleQueryWithRequest(request)
+ const mutation = new MutationObserver(
+ new QueryClient(),
+ consoleQuery.files.upload.post.mutationOptions(),
+ )
+ await expect(mutation.mutate({ body: { file } })).resolves.toEqual(response)
+ const outgoing = request.mock.calls[0]?.[2]?.request as Request
+ expect(outgoing.url).toContain('/files/upload')
+ expect(outgoing.headers.get('content-type')).toContain('multipart/form-data; boundary=')
+ const form = await outgoing.formData()
+ expect(Array.from(form.keys())).toEqual(['file'])
+ const uploaded = form.get('file')
+ if (!(uploaded instanceof File)) throw new TypeError('Expected an uploaded icon')
+ expect(uploaded.name).toBe(file.name)
+ expect(uploaded.type).toBe(file.type)
+ expect(await uploaded.text()).toBe('GIF89a')
+ })
+
afterEach(() => {
vi.restoreAllMocks()
})
diff --git a/web/test/emoji-picker.ts b/web/test/emoji-picker.ts
index dfd328285f8..375fa61c77d 100644
--- a/web/test/emoji-picker.ts
+++ b/web/test/emoji-picker.ts
@@ -1,16 +1,30 @@
+import type { RenderOptions } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { render } from '@testing-library/react'
+import { createElement } from 'react'
import data from '@/public/emoji/emojibase-17.0.0/en/data.json'
import messages from '@/public/emoji/emojibase-17.0.0/en/messages.json'
-/** Exercise the real picker with the same data served in production, without network. */
+const clients: QueryClient[] = []
+export function renderWithEmoji(ui: ReactNode, options: RenderOptions = {}) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ clients.push(client)
+ const Wrapper = options.wrapper
+ return render(ui, {
+ ...options,
+ wrapper: ({ children }) =>
+ createElement(
+ QueryClientProvider,
+ { client },
+ Wrapper ? createElement(Wrapper, null, children) : children,
+ ),
+ })
+}
+
+/** Exercise the same catalog used in production at the network boundary. */
export function mockEmojiData() {
beforeEach(() => {
- // oxlint-disable-next-line no-restricted-globals -- Reset Frimousse's own cache to exercise its data loader.
- localStorage.removeItem('frimousse/data/en')
- sessionStorage.removeItem('frimousse/metadata')
- sessionStorage.setItem(
- 'frimousse/metadata',
- JSON.stringify({ emojiVersion: 17, countryFlags: true }),
- )
vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
const url = String(input)
if (!/^\/.*emoji\/emojibase-17\.0\.0\/en\/(?:data|messages)\.json$/.test(url))
@@ -18,5 +32,8 @@ export function mockEmojiData() {
return new Response(JSON.stringify(url.endsWith('/messages.json') ? messages : data))
})
})
- afterEach(() => vi.restoreAllMocks())
+ afterEach(() => {
+ clients.splice(0).forEach((client) => client.clear())
+ vi.restoreAllMocks()
+ })
}