From 10ae4afb2967f4a6aa2391d41d71a5864c1538db Mon Sep 17 00:00:00 2001 From: Stephen Zhou <38493346+hyoban@users.noreply.github.com> Date: Fri, 8 May 2026 18:59:30 +0800 Subject: [PATCH] tweaks --- .../skills/how-to-write-component/SKILL.md | 6 + .../components/create-instance-modal.tsx | 268 ++++-------------- .../deployments/detail/deployment-sidebar.tsx | 10 +- web/hooks/create-storage-hook.ts | 249 ---------------- web/hooks/use-local-storage.ts | 26 -- 5 files changed, 66 insertions(+), 493 deletions(-) delete mode 100644 web/hooks/create-storage-hook.ts delete mode 100644 web/hooks/use-local-storage.ts diff --git a/.agents/skills/how-to-write-component/SKILL.md b/.agents/skills/how-to-write-component/SKILL.md index 5d90040c2c..3d03bfbf36 100644 --- a/.agents/skills/how-to-write-component/SKILL.md +++ b/.agents/skills/how-to-write-component/SKILL.md @@ -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`. diff --git a/web/features/deployments/components/create-instance-modal.tsx b/web/features/deployments/components/create-instance-modal.tsx index c3de0bb639..c7314e4de5 100644 --- a/web/features/deployments/components/create-instance-modal.tsx +++ b/web/features/deployments/components/create-instance-modal.tsx @@ -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 ( -
- {t('createModal.loadingApps')} - -
- ) - } - - const selected = apps.find(a => a.id === value) - - if (apps.length === 0) { - return ( -
- {t('createModal.noApps')} -
- ) - } + const apps = data?.pages.flatMap(page => page.data) ?? [] return ( - - - )} - > - {selected - ? ( -
-
- - -
- {selected.name} - {selected.mode} -
- ) - : ( - - {t('createModal.appPickerPlaceholder')} - - )} - -
- -
-
- setKeywords(e.target.value)} - onClear={() => setKeywords('')} - autoFocus - /> -
-
- {filtered.length === 0 - ? ( -
- {t('createModal.appSearchEmpty')} -
- ) - : filtered.map((app) => { - const isSelected = app.id === value - return ( - - ) - })} -
-
-
-
+ } + 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('') + const [sourceApp, setSourceApp] = useState() - 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() {
-
@@ -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" /> diff --git a/web/features/deployments/detail/deployment-sidebar.tsx b/web/features/deployments/detail/deployment-sidebar.tsx index 0746622cbc..ed866a7770 100644 --- a/web/features/deployments/detail/deployment-sidebar.tsx +++ b/web/features/deployments/detail/deployment-sidebar.tsx @@ -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( + const [persistedMode, setPersistedMode] = useLocalStorageState( 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') diff --git a/web/hooks/create-storage-hook.ts b/web/hooks/create-storage-hook.ts deleted file mode 100644 index fe88b387b1..0000000000 --- a/web/hooks/create-storage-hook.ts +++ /dev/null @@ -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 extends undefined ? never : T -export type StateHookTuple = readonly [T, Dispatch>] -export type StateHookTupleNullable = readonly [T | null, Dispatch>] -export type Serializer = (value: T) => string -export type Deserializer = (value: string) => T -export type CustomStorageEvent = CustomEvent -export type UseStorageRawOption = { - raw: true -} -export type UseStorageParserOption = { - raw?: false - serializer: Serializer - deserializer: Deserializer -} - -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 -const useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffectFromReact - -function isFunction(value: SetStateAction): value is (prevState: T | null) => T | null { - return typeof value === 'function' -} - -function identity(value: T) { - return value -} - -function stringIdentity(value: string) { - return value as T -} - -function getOption( - option: UseStorageRawOption | UseStorageParserOption = defaultStorageOption as UseStorageParserOption, -) { - return { - serializer: option.raw ? identity : option.serializer, - deserializer: option.raw ? stringIdentity : 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( - key: string, - option?: UseStorageRawOption | UseStorageParserOption, - ) { - const { serializer, deserializer } = getOption(option) - - return useCallback((value: SetStateAction) => { - 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( - key: string, - serverValue: NotUndefined, - option?: UseStorageRawOption | UseStorageParserOption, - ): T - function useStorageValue( - key: string, - serverValue?: undefined, - option?: UseStorageRawOption | UseStorageParserOption, - ): T | null - function useStorageValue( - key: string, - serverValue?: NotUndefined, - option?: UseStorageRawOption | UseStorageParserOption, - ) { - 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( - key: string, - serverValue: NotUndefined, - option?: UseStorageRawOption | UseStorageParserOption, - ): StateHookTuple - function useStorage( - key: string, - serverValue?: undefined, - option?: UseStorageRawOption | UseStorageParserOption, - ): StateHookTupleNullable - function useStorage( - key: string, - serverValue?: NotUndefined, - option?: UseStorageRawOption | UseStorageParserOption, - ): StateHookTuple | StateHookTupleNullable { - const value = useStorageValue(key, serverValue as NotUndefined, option) - const setValue = useSetStorage(key, option) - - return [value, setValue] as const - } - - return { - useStorage, - useSetStorage, - useStorageValue, - } -} diff --git a/web/hooks/use-local-storage.ts b/web/hooks/use-local-storage.ts deleted file mode 100644 index 30ef7cd6e0..0000000000 --- a/web/hooks/use-local-storage.ts +++ /dev/null @@ -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 = UseStorageParserOption -export type UseLocalStorageSerializer = Serializer -export type UseLocalStorageDeserializer = Deserializer - -const { - useStorage: useLocalStorage, - useSetStorage: useSetLocalStorage, - useStorageValue: useLocalStorageValue, -} = createStorage('localStorage') - -/** @see https://foxact.skk.moe/use-local-storage */ -export { - useLocalStorage, - useLocalStorageValue, - useSetLocalStorage, -}