This commit is contained in:
Stephen Zhou 2026-05-08 18:59:30 +08:00
parent 3b72f4e6f5
commit 10ae4afb29
No known key found for this signature in database
5 changed files with 66 additions and 493 deletions

View File

@ -7,6 +7,12 @@ description: React/TypeScript component style guide. Use when writing, refactori
Follow existing project patterns first. Use these rules to resolve unclear component decisions:
Do not copy existing code blindly. Existing implementations are reference material, not automatic precedent; when existing code conflicts with these rules, follow this skill and adapt the approach instead of reproducing the violation.
## Reuse Existing Implementations
- Before creating new UI, hooks, helpers, or styling patterns, search for and reuse existing base components, feature components, shared hooks, utilities, and established design styles. Add new implementations only when the existing ones cannot express the required behavior cleanly.
## Component Declaration And Exports
- Type component signatures directly; do not use `FC` or `React.FC`.

View File

@ -1,211 +1,68 @@
'use client'
import type { App } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { toast } from '@langgenius/dify-ui/toast'
import { useMutation, useQuery } from '@tanstack/react-query'
import { keepPreviousData, useInfiniteQuery, useMutation } from '@tanstack/react-query'
import { useAtomValue, useSetAtom } from 'jotai'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { AppTypeIcon } from '@/app/components/app/type-selector'
import AppIcon from '@/app/components/base/app-icon'
import Input from '@/app/components/base/input'
import { AppPicker } from '@/app/components/plugins/plugin-detail-panel/app-selector/app-picker'
import { AppTrigger } from '@/app/components/plugins/plugin-detail-panel/app-selector/app-trigger'
import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/client'
import { AppModeEnum } from '@/types/app'
import { closeCreateInstanceModalAtom, createInstanceModalOpenAtom } from '../store'
const MAX_STUDIO_SOURCE_APPS = 100
const SOURCE_APP_PAGE_SIZE = 20
type StudioSourceApp = {
id: string
name: string
mode: AppModeEnum
iconType?: App['icon_type']
icon?: string
iconBackground?: string
iconUrl?: string | null
description?: string
}
function SourceAppPicker({ value, onChange }: {
value?: App
onChange: (app: App) => void
}) {
const [isShow, setIsShow] = useState(false)
const [searchText, setSearchText] = useState('')
function toStudioSourceAppInfo(app: App): StudioSourceApp {
return {
id: app.id,
name: app.name,
mode: app.mode || AppModeEnum.WORKFLOW,
iconType: app.icon_type,
icon: app.icon,
iconBackground: app.icon_background ?? undefined,
iconUrl: app.icon_url,
description: app.description || undefined,
}
}
const {
data,
isLoading,
isFetchingNextPage,
fetchNextPage,
hasNextPage,
} = useInfiniteQuery({
...consoleQuery.apps.list.infiniteOptions({
input: pageParam => ({
query: {
page: Number(pageParam),
limit: SOURCE_APP_PAGE_SIZE,
name: searchText,
},
}),
getNextPageParam: lastPage => lastPage.has_more ? lastPage.page + 1 : undefined,
initialPageParam: 1,
placeholderData: keepPreviousData,
}),
})
type AppPickerProps = {
apps: StudioSourceApp[]
isLoading: boolean
value: string
onChange: (sourceAppId: string) => void
}
function AppPicker({ apps, isLoading, value, onChange }: AppPickerProps) {
const { t } = useTranslation('deployments')
const [open, setOpen] = useState(false)
const [keywords, setKeywords] = useState('')
const q = keywords.trim().toLowerCase()
const filtered = q
? apps.filter(a => a.name.toLowerCase().includes(q) || a.mode.toLowerCase().includes(q))
: apps
const handleOpenChange = (next: boolean) => {
if (!next)
setKeywords('')
setOpen(next)
}
if (isLoading) {
return (
<div
className="flex h-10 w-full items-center justify-between rounded-lg border-[0.5px] border-components-input-border-active bg-components-input-bg-normal pr-2 pl-2 text-left"
aria-busy="true"
>
<span className="truncate system-sm-regular text-text-quaternary">{t('createModal.loadingApps')}</span>
<span aria-hidden className="h-4 w-4 shrink-0" />
</div>
)
}
const selected = apps.find(a => a.id === value)
if (apps.length === 0) {
return (
<div className="flex h-10 w-full items-center rounded-lg border-[0.5px] border-components-input-border-active bg-components-input-bg-normal px-3 system-sm-regular text-text-tertiary">
<span className="truncate">{t('createModal.noApps')}</span>
</div>
)
}
const apps = data?.pages.flatMap(page => page.data) ?? []
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger
render={(
<button
type="button"
className={cn(
'flex h-10 w-full items-center justify-between rounded-lg border-[0.5px] bg-components-input-bg-normal pr-2 pl-2 text-left transition-colors',
open
? 'border-components-input-border-active'
: 'border-components-input-border-active hover:border-components-input-border-hover',
)}
/>
)}
>
{selected
? (
<div className="flex min-w-0 items-center gap-2">
<div className="relative shrink-0">
<AppIcon
size="tiny"
iconType={selected.iconType}
icon={selected.icon}
background={selected.iconBackground}
imageUrl={selected.iconUrl}
/>
<AppTypeIcon
type={selected.mode}
wrapperClassName="absolute -bottom-0.5 -right-0.5 w-3 h-3 shadow-sm"
className="h-2 w-2"
/>
</div>
<span className="truncate system-sm-medium text-text-secondary">{selected.name}</span>
<span className="shrink-0 system-2xs-medium-uppercase text-text-tertiary">{selected.mode}</span>
</div>
)
: (
<span className="system-sm-regular text-text-quaternary">
{t('createModal.appPickerPlaceholder')}
</span>
)}
<span
aria-hidden
className={cn('i-ri-arrow-down-s-line h-4 w-4 shrink-0 text-text-tertiary transition-transform', open && 'rotate-180')}
/>
</PopoverTrigger>
<PopoverContent
placement="bottom-start"
sideOffset={4}
popupClassName="p-0 overflow-hidden"
popupProps={{ style: { width: 'var(--anchor-width, auto)' } }}
>
<div className="flex flex-col">
<div className="p-2">
<Input
showLeftIcon
showClearIcon
placeholder={t('createModal.appSearchPlaceholder')}
value={keywords}
onChange={e => setKeywords(e.target.value)}
onClear={() => setKeywords('')}
autoFocus
/>
</div>
<div className="max-h-[280px] overflow-y-auto px-1 pb-1">
{filtered.length === 0
? (
<div className="px-3 py-6 text-center system-sm-regular text-text-tertiary">
{t('createModal.appSearchEmpty')}
</div>
)
: filtered.map((app) => {
const isSelected = app.id === value
return (
<button
key={app.id}
type="button"
onClick={() => {
onChange(app.id)
setOpen(false)
setKeywords('')
}}
className={cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors',
'hover:bg-state-base-hover',
isSelected && 'bg-state-base-hover',
)}
>
<div className="relative shrink-0">
<AppIcon
size="tiny"
iconType={app.iconType}
icon={app.icon}
background={app.iconBackground}
imageUrl={app.iconUrl}
/>
<AppTypeIcon
type={app.mode}
wrapperClassName="absolute -bottom-0.5 -right-0.5 w-3 h-3 shadow-sm"
className="h-2 w-2"
/>
</div>
<span className="min-w-0 grow truncate system-sm-medium text-text-secondary">
{app.name}
</span>
<span className="shrink-0 system-2xs-medium-uppercase text-text-tertiary">
{app.mode}
</span>
{isSelected && (
<span aria-hidden className="i-ri-check-line h-4 w-4 shrink-0 text-text-accent" />
)}
</button>
)
})}
</div>
</div>
</PopoverContent>
</Popover>
<AppPicker
disabled={false}
trigger={<AppTrigger open={isShow} appDetail={value} />}
isShow={isShow}
onShowChange={setIsShow}
onSelect={onChange}
apps={apps}
isLoading={isLoading || isFetchingNextPage}
hasMore={hasNextPage ?? true}
onLoadMore={() => {
void fetchNextPage()
}}
searchText={searchText}
onSearchChange={setSearchText}
placement="bottom-start"
offset={4}
/>
)
}
@ -214,24 +71,13 @@ function CreateInstanceForm() {
const router = useRouter()
const closeModal = useSetAtom(closeCreateInstanceModalAtom)
const createInstance = useMutation(consoleQuery.enterprise.appDeploy.createAppInstance.mutationOptions())
const { data: appList, isLoading } = useQuery(consoleQuery.apps.list.queryOptions({
input: {
query: {
page: 1,
limit: MAX_STUDIO_SOURCE_APPS,
name: '',
},
},
}))
const apps = (appList?.data ?? []).map(toStudioSourceAppInfo)
const [sourceAppId, setSourceAppId] = useState<string>('')
const [sourceApp, setSourceApp] = useState<App>()
const selectedApp = apps.find(a => a.id === sourceAppId)
const canCreate = Boolean(sourceAppId && !createInstance.isPending)
const canCreate = Boolean(sourceApp?.id && !createInstance.isPending)
const handleCreate = async (form: HTMLFormElement) => {
if (!canCreate)
if (!canCreate || !sourceApp?.id)
return
const formData = new FormData(form)
@ -243,7 +89,7 @@ function CreateInstanceForm() {
try {
const result = await createInstance.mutateAsync({
body: {
sourceAppId,
sourceAppId: sourceApp.id,
name: name.trim(),
description: description.trim() || undefined,
},
@ -277,11 +123,9 @@ function CreateInstanceForm() {
<div className="flex flex-col gap-2">
<label className="system-xs-medium-uppercase text-text-tertiary">{t('createModal.sourceApp')}</label>
<AppPicker
apps={apps}
isLoading={isLoading}
value={sourceAppId}
onChange={setSourceAppId}
<SourceAppPicker
value={sourceApp}
onChange={setSourceApp}
/>
</div>
@ -293,7 +137,7 @@ function CreateInstanceForm() {
id="instance-name"
name="name"
type="text"
placeholder={selectedApp?.name ?? t('createModal.namePlaceholder')}
placeholder={sourceApp?.name ?? t('createModal.namePlaceholder')}
required
className="flex h-8 items-center rounded-lg border-[0.5px] border-components-input-border-active bg-components-input-bg-normal px-3 text-[13px] font-medium text-text-secondary outline-hidden placeholder:text-text-quaternary"
/>

View File

@ -5,7 +5,7 @@ import type { ComponentProps, PropsWithoutRef } from 'react'
import type { InstanceDetailTabKey } from './tabs'
import type { NavIcon } from '@/app/components/app-sidebar/nav-link'
import { cn } from '@langgenius/dify-ui/cn'
import { useHover, useKeyPress } from 'ahooks'
import { useHover, useKeyPress, useLocalStorageState } from 'ahooks'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { getAppModeLabel } from '@/app/components/app-sidebar/app-info/app-mode-labels'
@ -15,7 +15,6 @@ import AppIcon from '@/app/components/base/app-icon'
import Divider from '@/app/components/base/divider'
import { getKeyboardKeyCodeBySystem } from '@/app/components/workflow/utils'
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
import { useLocalStorage } from '@/hooks/use-local-storage'
import { toAppMode } from '../utils'
type TabDef = {
@ -82,12 +81,11 @@ function isShortcutFromInputArea(target: EventTarget | null) {
}
function useDeploymentSidebarMode(isMobile: boolean) {
const [persistedMode, setPersistedMode] = useLocalStorage<DeploymentSidebarMode>(
const [persistedMode, setPersistedMode] = useLocalStorageState<DeploymentSidebarMode>(
DEPLOYMENT_SIDEBAR_MODE_KEY,
'expand',
{ raw: true },
{ defaultValue: 'expand' },
)
const sidebarMode = isMobile ? 'collapse' : persistedMode
const sidebarMode = isMobile ? 'collapse' : persistedMode ?? 'expand'
function toggleSidebarMode() {
setPersistedMode(sidebarMode === 'expand' ? 'collapse' : 'expand')

View File

@ -1,249 +0,0 @@
/* eslint-disable react/component-hook-factories -- Mirrors foxact's storage hook factory shape. */
import type { Dispatch, SetStateAction } from 'react'
import { useCallback, useEffect, useLayoutEffect as useLayoutEffectFromReact, useMemo, useSyncExternalStore } from 'react'
import { noop } from './noop'
import 'client-only'
/*
* Adapted from foxact/create-storage-hook.
*
* MIT License
* Copyright (c) 2023 Sukka
*
* 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.
*/
export type StorageType = 'localStorage' | 'sessionStorage'
export type NotUndefined<T> = T extends undefined ? never : T
export type StateHookTuple<T> = readonly [T, Dispatch<SetStateAction<T | null>>]
export type StateHookTupleNullable<T> = readonly [T | null, Dispatch<SetStateAction<T | null>>]
export type Serializer<T> = (value: T) => string
export type Deserializer<T> = (value: string) => T
export type CustomStorageEvent = CustomEvent<string>
export type UseStorageRawOption = {
raw: true
}
export type UseStorageParserOption<T> = {
raw?: false
serializer: Serializer<T>
deserializer: Deserializer<T>
}
declare global {
// eslint-disable-next-line ts/consistent-type-definitions -- WindowEventMap uses interface merging.
interface WindowEventMap {
'foxact-use-local-storage': CustomStorageEvent
'foxact-use-session-storage': CustomStorageEvent
}
}
const defaultStorageOption = {
raw: false,
serializer: JSON.stringify,
deserializer: JSON.parse,
} satisfies UseStorageParserOption<unknown>
const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffectFromReact
function isFunction<T>(value: SetStateAction<T | null>): value is (prevState: T | null) => T | null {
return typeof value === 'function'
}
function identity<T>(value: T) {
return value
}
function stringIdentity<T>(value: string) {
return value as T
}
function getOption<T>(
option: UseStorageRawOption | UseStorageParserOption<T> = defaultStorageOption as UseStorageParserOption<T>,
) {
return {
serializer: option.raw ? identity<T> : option.serializer,
deserializer: option.raw ? stringIdentity<T> : option.deserializer,
}
}
export function createStorage(type: StorageType) {
const storageEventKey = type === 'localStorage' ? 'foxact-use-local-storage' : 'foxact-use-session-storage'
const hookName = type === 'localStorage' ? 'useLocalStorage' : 'useSessionStorage'
function getServerSnapshotWithoutServerValue(): never {
throw new Error(`[${hookName}] cannot be used on the server without a serverValue`)
}
function dispatchStorageEvent(key: string) {
window.dispatchEvent(new CustomEvent(storageEventKey, { detail: key }))
}
function setStorageItem(key: string, value: string) {
try {
window[type].setItem(key, value)
}
catch {
console.warn(`[${hookName}] Failed to set value to ${type}, it might be blocked`)
}
finally {
dispatchStorageEvent(key)
}
}
function removeStorageItem(key: string) {
try {
window[type].removeItem(key)
}
catch {
console.warn(`[${hookName}] Failed to remove value from ${type}, it might be blocked`)
}
finally {
dispatchStorageEvent(key)
}
}
function getStorageItem(key: string) {
if (typeof window === 'undefined')
return null
try {
return window[type].getItem(key)
}
catch {
console.warn(`[${hookName}] Failed to get value from ${type}, it might be blocked`)
return null
}
}
function useSetStorage<T>(
key: string,
option?: UseStorageRawOption | UseStorageParserOption<T>,
) {
const { serializer, deserializer } = getOption(option)
return useCallback((value: SetStateAction<T | null>) => {
try {
let nextState: T | null
if (isFunction(value)) {
const currentRaw = getStorageItem(key)
const currentState = currentRaw === null ? null : deserializer(currentRaw)
nextState = value(currentState)
}
else {
nextState = value
}
if (nextState === null)
removeStorageItem(key)
else
setStorageItem(key, serializer(nextState) as string)
}
catch (error) {
console.warn(error)
}
}, [deserializer, key, serializer])
}
function useStorageValue<T>(
key: string,
serverValue: NotUndefined<T>,
option?: UseStorageRawOption | UseStorageParserOption<T>,
): T
function useStorageValue<T = string>(
key: string,
serverValue?: undefined,
option?: UseStorageRawOption | UseStorageParserOption<T>,
): T | null
function useStorageValue<T>(
key: string,
serverValue?: NotUndefined<T>,
option?: UseStorageRawOption | UseStorageParserOption<T>,
) {
const subscribeToKey = useCallback((callback: () => void) => {
if (typeof window === 'undefined')
return noop
const handleStorageEvent = (event: StorageEvent) => {
if (!('key' in event) || event.key === key)
callback()
}
const handleCustomStorageEvent = (event: CustomStorageEvent) => {
if (event.detail === key)
callback()
}
window.addEventListener('storage', handleStorageEvent)
window.addEventListener(storageEventKey, handleCustomStorageEvent)
return () => {
window.removeEventListener('storage', handleStorageEvent)
window.removeEventListener(storageEventKey, handleCustomStorageEvent)
}
}, [key])
const { serializer, deserializer } = getOption(option)
const getClientSnapshot = () => getStorageItem(key)
const getServerSnapshot = serverValue === undefined
? getServerSnapshotWithoutServerValue
: () => serializer(serverValue) as string
const store = useSyncExternalStore(
subscribeToKey,
getClientSnapshot,
getServerSnapshot,
)
const deserialized = useMemo(() => (store === null ? null : deserializer(store)), [deserializer, store])
useIsomorphicLayoutEffect(() => {
if (getStorageItem(key) === null && serverValue !== undefined)
setStorageItem(key, serializer(serverValue) as string)
}, [key, serializer, serverValue])
return deserialized === null
? serverValue === undefined
? null
: serverValue
: deserialized
}
function useStorage<T>(
key: string,
serverValue: NotUndefined<T>,
option?: UseStorageRawOption | UseStorageParserOption<T>,
): StateHookTuple<T>
function useStorage<T = string>(
key: string,
serverValue?: undefined,
option?: UseStorageRawOption | UseStorageParserOption<T>,
): StateHookTupleNullable<T>
function useStorage<T>(
key: string,
serverValue?: NotUndefined<T>,
option?: UseStorageRawOption | UseStorageParserOption<T>,
): StateHookTuple<T> | StateHookTupleNullable<T> {
const value = useStorageValue<T>(key, serverValue as NotUndefined<T>, option)
const setValue = useSetStorage<T>(key, option)
return [value, setValue] as const
}
return {
useStorage,
useSetStorage,
useStorageValue,
}
}

View File

@ -1,26 +0,0 @@
import type {
Deserializer,
Serializer,
UseStorageParserOption,
UseStorageRawOption,
} from './create-storage-hook'
import { createStorage } from './create-storage-hook'
import 'client-only'
export type UseLocalStorageRawOption = UseStorageRawOption
export type UseLocalStorageParserOption<T> = UseStorageParserOption<T>
export type UseLocalStorageSerializer<T> = Serializer<T>
export type UseLocalStorageDeserializer<T> = Deserializer<T>
const {
useStorage: useLocalStorage,
useSetStorage: useSetLocalStorage,
useStorageValue: useLocalStorageValue,
} = createStorage('localStorage')
/** @see https://foxact.skk.moe/use-local-storage */
export {
useLocalStorage,
useLocalStorageValue,
useSetLocalStorage,
}