diff --git a/.agents/skills/how-to-write-component/SKILL.md b/.agents/skills/how-to-write-component/SKILL.md index bf523070740..4a5a73088ec 100644 --- a/.agents/skills/how-to-write-component/SKILL.md +++ b/.agents/skills/how-to-write-component/SKILL.md @@ -1,71 +1,59 @@ --- name: how-to-write-component -description: React/TypeScript component style guide. Use when writing, refactoring, or reviewing React components, especially around abstraction choices, props typing, state boundaries, shared local state with Jotai atoms, API types, query/mutation contracts, navigation, memoization, wrappers, and empty-state handling. +description: Use when writing, refactoring, or reviewing React/TypeScript components in Dify web, especially decisions about component ownership, props/types, URL/query state, Jotai state, async state, generated API contracts, queries/mutations, overlays, effects, navigation, performance, and empty states. --- # How To Write A Component -Use this as the decision guide for React/TypeScript component structure. Existing code is reference material, not automatic precedent; when it conflicts with these rules, adapt the approach instead of reproducing the violation. +Use this as the component decision guide for Dify web. Existing code is reference material, not automatic precedent; if touched code violates these rules, adapt it and fix equivalent patterns in the same feature branch. + +## First Decisions + +| Question | Default | Promote or extract only when | +| --- | --- | --- | +| Where should code live? | Keep it local to the feature workflow, route, or owner. | Multiple verticals need the same stable primitive. | +| Who owns state, data, and handlers? | The lowest component that uses them. | A parent coordinates shared loading, errors, empty UI, selection, submission, navigation, or one consistent snapshot. | +| Should this become Jotai state? | Keep synchronous UI/form state in component or DOM state. | Siblings need one source of truth, the value drives atoms, or scoped workflow state must survive hidden/unmounted steps. | +| Should URL state enter Jotai? | Let Next.js route params and `nuqs` own URL state and updates. | Query atoms or shared derived atoms need a read-only bridge hydrated at the route/surface boundary. | +| Should this query/mutation become an atom? | Use TanStack Query hooks at the lowest owner. | It reads atom state, feeds derived atoms, or participates in shared Jotai workflow orchestration. | +| Should this be a helper/wrapper? | Prefer direct readable code at the use site. | The name captures a stable domain rule or the wrapper owns real behavior, validation, state, error handling, or semantics. | +| Is an Effect needed? | No. Derive during render or handle the user action in the event handler. | It synchronizes with an external system such as browser APIs, subscriptions, timers, analytics, or imperative DOM/non-React widgets. | ## Core Defaults -- Search before adding UI, hooks, helpers, or styling patterns. Reuse existing base components, feature components, hooks, utilities, and design styles when they fit. -- Group code by feature workflow, route, or ownership area: components, hooks, local types, query helpers, atoms, constants, and small utilities should live near the code that changes with them. -- Promote code to shared only when multiple verticals need the same stable primitive. Otherwise keep it local and compose shared primitives inside the owning feature. -- Prefer local code and purpose-named helpers over catch-all utility modules; do not group workflow-specific defaults, validation, payload shaping, or metadata merging in a generic utils file just because they share a DTO. -- Keep source/default selection, validation, and payload shaping close to the workflow that owns the behavior. Do not extract a shared helper just because two flows read the same DTO when their priority order, fallback behavior, or submit semantics differ. -- Prefer direct, readable conditionals at the use site for small branch-specific decisions, especially form source selection and request payload assembly. Extract only when the helper name captures a stable domain rule and removes repeated complexity without hiding flow-specific behavior. -- When fixing an invalid pattern, scan the touched feature or branch for equivalent patterns and fix them together. -- Follow Dify's CSS-first Tailwind v4 contract from `packages/dify-ui/README.md` and `packages/dify-ui/AGENTS.md`. Prefer design-system tokens, utilities, and radius mappings over generic Tailwind guidance. +- Search before adding UI, hooks, helpers, query utilities, or styling patterns. Reuse existing base components, feature components, hooks, utilities, and design styles when they fit. +- Follow Dify's CSS-first Tailwind v4 contract from `packages/dify-ui/README.md` and `packages/dify-ui/AGENTS.md`. Prefer design-system tokens, utilities, and radius mappings over generic Tailwind choices. +- Group feature code by workflow, route, or ownership area: components, hooks, local types, query helpers, atoms, constants, and small utilities should live near the code that changes with them. +- Keep source/default selection, validation, dirty checks, and payload shaping close to the workflow that owns submit behavior. Do not hide flow-specific priority order, fallback behavior, or submit semantics in generic utilities. +- Prefer direct conditionals for small branch-specific decisions, especially form source selection and request payload assembly. +- Loading states for page sections, cards, lists, tables, forms, and drawers should be skeletons scoped to the content being loaded. Use spinners only for small inline busy indicators. -## Feature Workflow Layout +## Layout And Ownership -- State-heavy wizards, drawers, modals, and secondary workflows work best as a small feature surface with route/entry files, a single feature-local state file, and feature-local UI. -- Keep `ui/` shallow with owner files that map to the workflow's real composition boundaries and major visual regions. -- Owner files contain the section components, field components, skeletons, and one-off helper components that belong to their visual region. -- Folders represent groups of related files with a shared owner and a stable reason to change together. -- The entry file handles route integration, provider wiring, close behavior, and feature surface mounting. The composition owner handles high-level workflow branching, and the closest visual owner handles section branching. +- State-heavy wizards, drawers, modals, and secondary workflows can be a small feature surface: an entry file, one feature-local state file when Jotai is actually needed, and shallow `ui/` owners that match real visual regions. +- The entry file handles route integration, provider wiring, close behavior, and surface mounting. The composition owner handles high-level workflow branching. The closest visual owner handles section branching. +- Repeated TanStack query calls in sibling components are acceptable when each component independently consumes the data; TanStack Query deduplicates and shares cache. +- Pass stable domain identity across boundaries. Do not forward derived presentation state when the receiver can derive it from its own data source. +- A component that owns a visual surface should also own data access, loading, empty, and error states for content rendered inside it unless a parent truly coordinates that state. +- Avoid prop drilling. One pass-through layer is acceptable; repeated forwarding means ownership should move down or into feature-scoped Jotai UI state. Keep server/cache state in Query and API flow. +- Do not replace prop drilling with one large view-model hook threaded through section props. Move each hook, query, derived value, and handler to the concrete section that consumes it. +- Keep callbacks in a parent only for workflow coordination such as form submission, shared selection, batch behavior, or navigation. Otherwise let the child, menu, or row own the action. -## Ownership +## Feature-Scoped Jotai -- Put local state, queries, mutations, handlers, and derived UI data in the lowest component that uses them. Extract a purpose-built owner component only when the logic has no natural home. -- Repeated TanStack query calls in sibling components are acceptable when each component independently consumes the data. Do not hoist a query only because it is duplicated; TanStack Query handles deduplication and cache sharing. -- Hoist state, queries, or callbacks to a parent only when the parent consumes the data, coordinates shared loading/error/empty UI, needs one consistent snapshot, or owns a workflow spanning children. -- Pass stable domain identity across boundaries; avoid forwarding derived presentation state when the receiver can derive it from its own data source. A component that owns a visual surface should also own the data access, loading, empty, and error states for content rendered inside it unless a parent truly coordinates that state. -- Loading states for visual surfaces should use skeleton placeholders scoped to the content that is actually loading, with shape, density, and dimensions close to the final UI. Avoid generic loading text or centered spinners for page sections, cards, lists, tables, forms, and drawers; reserve spinners for small inline busy indicators such as an in-progress status icon. -- Avoid prop drilling. One pass-through layer is acceptable; repeated forwarding means ownership should move down or into feature-scoped Jotai UI state. Keep server/cache state in query and API data flow. -- Do not replace prop drilling with one top-level hook that returns a large view model and then thread that object through section props. Move each hook, query, derived value, and handler to the concrete section that consumes it, or use feature-scoped Jotai atoms for simple shared form/UI state when siblings need the same source of truth. -- When using feature-scoped Jotai state for a form, drawer, or other secondary surface, scope the store to that surface instance when stale cross-instance state is possible. Initialize stable config at the owning boundary, then let descendants read only the atoms or purpose-named hooks they actually need. -- For Jotai-backed surfaces, put shared query atoms, mutation atoms, derived state, and write actions in the feature state file when they coordinate multiple descendants. Do not create a query or mutation atom only because the surrounding feature uses Jotai. If the query or mutation does not read atom state, feed another atom, or participate in shared workflow orchestration, use `useQuery` or `useMutation` directly at the lowest owner. -- For repeated row/menu action surfaces that need reset, hydrate the stable identity at the surface entry and scope only the primitives that truly need per-instance reset, such as open flags, drafts, or selected local options. -- Keep callbacks in a parent only for workflow coordination such as form submission, shared selection, batch behavior, or navigation. Otherwise let the child or row own its action. -- Default to uncontrolled form and DOM state. Add controlled props or atom-backed drafts only when live cross-component reactions, multi-step persistence, or external synchronization require them. - -## Feature-Scoped Jotai State - -- A module's feature-local state lives in one state file for Jotai-backed features: primitive atoms, shared query atoms, derived atoms, write-only action atoms, shared mutation atoms, submission orchestration, provider exports, and optional scope configuration. -- Keep synchronous UI state local when one component owns it, even inside Jotai-backed features. Dialog open flags, menu/popover visibility, confirmation visibility, form/input drafts, and selected local options usually belong in component state. -- Do not put simple form drafts in Jotai atoms. For edit/create forms whose fields are only read at submit time, use uncontrolled `@langgenius/dify-ui/form` and `@langgenius/dify-ui/field` controls with `defaultValue`, browser/form validation, and keyed remounts for query-backed initial values. -- Promote form state to Jotai only when another component must react to in-progress field changes, the draft must survive unmount/remount within the same scoped workflow, or multiple steps/surfaces share the same editable draft before submit. -- Keep submit-time normalization, dirty checks, and payload shaping beside the form submit handler. Do not create form atoms, field atoms, or derived can-save atoms only to mirror uncontrolled form values or disable a submit button. -- In Jotai-backed feature surfaces, never hand-roll async loading, error, or in-flight guards with `useState` or `useRef`. For async work that depends on atom state, feeds derived atoms, or participates in shared submission orchestration, model the work with `atomWithQuery` or `atomWithMutation`; write atoms should only update the inputs that drive those atoms. For component-owned remote work that does not participate in atom state, use TanStack Query hooks directly. -- Row-local async state should belong to the row owner. Use `useQuery` or `useMutation` directly for row actions that do not depend on atom state and are not consumed by other atoms. Use a per-instance query or mutation atom only when the row action participates in a Jotai-backed shared workflow or needs atom-scoped reset semantics. -- Promote UI state to an atom only when siblings need the same source of truth, the value drives a query or mutation atom, a parent workflow coordinates the state, or the state intentionally persists across hidden or unmounted descendants within a scoped surface. -- Reflect atom-backed surface-wide locks or invariants in every affected trigger. If only one row, menu, or dialog should be disabled, keep the pending or lock scope local to that row, menu, or dialog with the lowest-owner query/mutation hook unless it genuinely participates in shared atom state. -- Atom order in the state file follows the dependency graph: types/constants, editable primitives, query atoms, query-data derived atoms, readiness/business derived atoms, write actions, mutation atoms, submission orchestration, provider exports. -- Derived atom names read as business facts. Write atom names read as user or workflow commands. -- UI components read and write the exact atom they use with `useAtomValue` or `useSetAtom`. Repeated workflow semantics live in named derived atoms or write atoms. -- Non-query derived atoms return a narrow value with a clear domain name; avoid pass-through aliases or bundling unrelated UI facts. Query atoms expose the TanStack Query result object so loading, error, fetch, and pagination state stay attached to the query contract. -- Write-only atoms own synchronous state transitions that update multiple primitives, reset dependent state, or advance the workflow. Async work with loading, error, caching, retry, stale-result, or in-flight concerns should be modeled as query or mutation atoms, with write atoms only changing the inputs that drive them. -- Avoid feature hooks that aggregate form values, query results, derived state, and commands for sibling components. Prefer named derived atoms and write atoms so UI components read the exact shared fact or command they need. -- When a form library owns validation, keep submit orchestration in feature state when post-submit result or error state is shared by the surface. Avoid duplicating validation gates or request shaping in UI hooks. -- `jotai-tanstack-query` atoms use the same QueryClient as the React Query provider. Query atoms belong in feature state only when they need atom inputs, provide data to derived atoms, or coordinate a shared Jotai-backed workflow. -- Jotai scope is an optional instance-isolation tool for secondary surfaces with independent local state. Query and mutation atoms keep shared cache behavior through the shared QueryClient. -- Do not put `atomWithQuery`, `atomWithInfiniteQuery`, `atomWithMutation`, or broad derived orchestration atoms in a `ScopeProvider` just to reset a surface. Scoped derived atoms implicitly scope their dependencies, which can duplicate query client access and break shared invalidation. Leave query/mutation atoms unscoped; let them read scoped primitive inputs. -- Scope providers should list resettable primitive atoms and explicit hydration tuples. If a derived atom must be scoped, confirm that every dependency it implicitly scopes is meant to be private to that surface. -- For scoped primitives that are always hydrated by a `ScopeProvider` tuple, prefer `atomWithLazy(() => { throw new Error(...) })` when consumers should see a non-null type. This keeps missing provider hydration as a runtime invariant without leaking `T | undefined` or adding pass-through "required" derived atoms only for narrowing. -- Keep independent dialog lifecycles separate. Avoid a single discriminated "current action dialog" atom when edit, delete, and other dialogs have their own open state, loading guard, or reset behavior. -- Route-derived stable identities that do not need instance reset or scoped isolation can be hydrated at the route or layout boundary into a feature route atom. Use scoped atoms only when stale cross-instance state or per-surface reset semantics are needed. +- A Jotai-backed feature has one feature-local state file for shared primitive atoms, query atoms, derived atoms, write-only actions, mutation atoms, submission orchestration, provider exports, and optional scope configuration. +- Keep component-owned synchronous UI state local even inside Jotai features: dialog open flags, menus/popovers, confirmations, field drafts, and selected local options usually belong in component state. +- Use uncontrolled `@langgenius/dify-ui/form` and `@langgenius/dify-ui/field` controls for edit/create forms whose fields are read only at submit time. Initialize query-backed defaults with `defaultValue` and keyed remounts. +- Promote form state to atoms only when another component must react to in-progress values, a draft must survive unmount/remount in the scoped workflow, or multiple steps share the same editable draft before submit. +- Treat `useParams`, route args, and `nuqs` query state as framework-owned state. When atom logic needs those values, hydrate primitive atoms at the route or surface boundary, such as with `useHydrateAtoms(..., { dangerouslyForceHydrate: true })`; keep URL updates in the route/query-state APIs instead of write atoms. +- For async work tied to atom state, use `atomWithQuery` or `atomWithMutation`; write atoms should update only the inputs that drive those atoms. This applies to pure frontend async work as well as network requests, so do not hand-roll loading/error/in-flight state with `useState` or `useRef` for atom-orchestrated async behavior. For component-owned remote work, use `useQuery` or `useMutation` directly. +- Row-local async state belongs to the row owner unless it participates in a shared Jotai workflow or needs atom-scoped reset semantics. +- Leave query and mutation atoms unscoped so they keep shared QueryClient cache and invalidation behavior. Scope resettable primitives and explicit hydration tuples; scope a derived atom only when every dependency should be private to that surface. +- For scoped primitives that are always hydrated by `ScopeProvider`, prefer `atomWithLazy(() => { throw new Error(...) })` when consumers should see a non-null type. +- Order state files by dependency graph: types/constants, primitives, query atoms, query-data derived atoms, business/readiness derived atoms, write actions, mutation atoms, submission orchestration, provider exports. +- Name derived atoms as business facts and write atoms as user or workflow commands. Components should read or write the exact atom they need with `useAtomValue` or `useSetAtom`. +- Menu/dialog `open` state usually stays local, but a scoped atom is acceptable when a composed menu plus secondary surface would otherwise pass confusing `open`/`onClose` props through unrelated layers. Scope that primitive with the surface instance so reset behavior stays local. +- Keep independent dialog lifecycles separate. Avoid one discriminated "current action dialog" atom when dialogs have separate open state, loading guards, or reset behavior. ## Components, Props, And Types @@ -74,86 +62,56 @@ Use this as the decision guide for React/TypeScript component structure. Existin - Prefer named exports. Use default exports only where the framework requires them, such as Next.js route files. - Type simple one-off props inline. Use a named `Props` type only when reused, exported, complex, or clearer. - Use API-generated or API-returned types at component boundaries. Keep small UI conversion helpers and one-off UI extensions beside the component that needs them. -- Do not create type aliases that only rename another type. Use an alias only when it encodes a real UI concept, refinement, or reusable local contract. -- Name values by their domain role and backend API contract, and keep that name stable across the call chain, especially persistent IDs and route params. Normalize framework or route params at the boundary. -- Keep fallback and invariant checks at the lowest component that already handles that state; avoid defensive fallbacks that mask impossible states. -- Do not extract fallback helpers whose only behavior is hiding missing display data. The component that renders the surface owns the empty, disabled, hidden, or placeholder state. +- Do not create type aliases that only rename another type. Use aliases only for real UI concepts, refinements, or reusable local contracts. +- Name values by their domain role and backend API contract, especially persistent IDs and route params. Normalize framework or route params at the boundary. +- Put fallback and invariant checks in the lowest component that already handles that state. Do not extract helpers whose only behavior is hiding missing display data. -## Generated API Contracts +## Generated API And Nullable Data - Treat generated contracts as authoritative at API, query, mutation, cache, and service boundaries. For enterprise APIs, use `packages/contracts/generated/enterprise/*`. -- Do not hand-write local request/response/reply/page/cache-data types that mirror generated DTOs. Import or infer the generated type. -- Do not widen generated fields or enums for compatibility. Normalize legacy input at the boundary, then return the generated field type. -- Do not repair generated or API-returned contract fields in components unless the API contract or product requirement says they need normalization. Treat enums, statuses, and presence flags as exact contract values. -- Use generated enum objects and union types directly in props, comparisons, status logic, and i18n keys. Do not add local enum constants or parallel frontend enum/status layers unless they model real product state not represented by the API. Presentation-only tone maps should be keyed by the generated enum. -- Normalize or coerce only at a real boundary, such as user-entered forms, search, URL/query params, file names, DOM IDs, or legacy adapters. Preserve user-entered values when whitespace or formatting can be meaningful. -- Do not coerce nullable or optional API strings to `''` in query, derived model, or payload-building code. Keep `undefined` or `null` until the final boundary that requires a string. -- Do not use `value || undefined` for mutation payload fields where an empty string means "clear this value". Trim or normalize at the form boundary, then preserve `''` when the API contract treats it as an intentional update. -- Local UI models are fine for presentation, form state, select options, or guarded required-field refinements. Name them as UI concepts, not generated DTO mirrors. -- Required-value refinements are allowed only after same-branch filtering or early return. Prefer nullable-tolerant props for render-only data. -- When a component needs a stricter shape than a generated DTO, refine once at the API/query-to-UI boundary into a purpose-named UI type instead of hiding missing fields with generic fallback or coercion helpers. - -## Nullable API Data - -- Prefer nullable-tolerant call boundaries. Pass API-returned types through for render-only rows, and let the component render fallback, disabled state, or nothing. -- Narrow only where a real value is required, such as mutation params, route hrefs, select values, or query input. Build that target model with `flatMap`, a local loop, or an early return so the required value is captured in the same branch. -- If design says a field is the display value, use that field. Only the final component should decide whether a nullable display value renders a placeholder, hides content, or disables an action. -- Do not wrap required arrays or fields in null-fallback helpers. Use empty collection fallbacks only for not-yet-loaded query data or genuinely nullable collections at the owning render boundary. -- Do not drop rows only to satisfy props or React keys; use a stable fallback key when possible. -- Use conditional spreads or explicit pushes for conditional array items instead of `undefined` placeholders followed by a narrowing filter. -- Avoid truthiness type guards, `filter(Boolean)`, `filter(item => item.id)`, and `!` after those filters. -- Use type guards only for meaningful domain or runtime validation, such as enum membership, object shape, or a reusable business invariant. +- Do not hand-write DTO mirrors, widen generated fields/enums, or add parallel frontend enum/status layers unless they model product state not represented by the API. +- Use generated enum objects and union types directly in props, comparisons, status logic, and i18n keys. Presentation-only tone maps should be keyed by generated enums. +- Normalize or coerce only at real boundaries: user-entered forms, search, URL/query params, file names, DOM IDs, or legacy adapters. +- Do not coerce nullable or optional API strings to `''` in query, derived model, or payload-building code. Keep `null` or `undefined` until the final boundary requiring a string. +- Do not use `value || undefined` for mutation fields where `''` means "clear this value". Trim or normalize at the form boundary, then preserve intentional empty strings. +- Prefer nullable-tolerant render props for API-returned rows. Narrow only where a real value is required, such as mutation params, route hrefs, select values, query input, or required React keys. +- Build required values in the same branch that proves them, using `flatMap`, a local loop, or an early return. Avoid truthiness guards, `filter(Boolean)`, `filter(item => item.id)`, and `!` after filters. +- Use conditional spreads or explicit pushes for conditional array items instead of `undefined` placeholders followed by narrowing filters. +- Empty collection fallbacks are for not-yet-loaded query data or genuinely nullable collections at the owning render boundary, not for hiding required API fields. ## Queries And Mutations -- Keep `web/contract/*` as the single source of truth for API shape; follow existing domain/router patterns and the `{ params, query?, body? }` input shape. -- Consume queries directly with `useQuery(consoleQuery.xxx.queryOptions(...))` or `useQuery(marketplaceQuery.xxx.queryOptions(...))`. -- Do not promote a query or mutation to an atom just because the feature already has a state file. Use `atomWithQuery` or `atomWithMutation` only when the query/mutation reads atom state, is consumed by another atom, or is part of shared workflow orchestration. -- In `atomWithQuery` and `atomWithInfiniteQuery`, return generated `queryOptions()` or `infiniteOptions()` directly. Pass `enabled`, `retry`, `placeholderData`, `select`, and pagination options into that call instead of spreading generated options into a hand-built object. -- When prefetch and render consume the same server request, extract local query options or a query-options atom so `queryClient.prefetchQuery(...)` and `useQuery`/`atomWithQuery` share the exact generated query options. -- In `atomWithMutation`, return generated `mutationOptions()` directly when using generated clients. Put request shaping and submit orchestration in write atoms; do not rebuild mutation option objects just to pass through the generated mutation function. -- For custom query functions that do not come from generated clients, wrap the options object with TanStack `queryOptions(...)` so query atoms still return a query options contract. -- Avoid pass-through hooks and thin `web/service/use-*` wrappers that only rename `queryOptions()` or `mutationOptions()`. Extract a small `queryOptions` helper only when repeated call-site options justify it. -- Keep feature hooks for real orchestration, workflow state, or shared domain behavior. -- For TanStack cache data, use generated or query-derived types; do not create local wrappers for `getQueryData` or `getQueriesData`. -- For generated oRPC `queryOptions()` / `infiniteOptions()`, keep returning the generated options directly. When required input is missing, use a whole-input branch such as `input: condition ? validInput : skipToken` together with `enabled: Boolean(condition)` so no request runs and no fake payload is built. -- Do not put `skipToken` inside a nested placeholder payload, such as `{ params: { appInstanceId: skipToken } }`. Do not create hand-written "missing queryOptions" objects or coerce required IDs to `''`. -- Consume mutations directly with `useMutation(consoleQuery.xxx.mutationOptions(...))` or `useMutation(marketplaceQuery.xxx.mutationOptions(...))` when the mutation is owned by one component, menu, dialog, or row and its pending/error state is not consumed by feature atoms. In Jotai-backed workflow orchestration, expose mutations from feature state with `atomWithMutation` so pending/error state stays attached to the mutation atom. For component-owned custom mutation functions, use `useMutation(mutationOptions(...))` at the owner. -- Put shared cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`; components may add UI feedback callbacks, but should not own shared invalidation rules. -- Component or atom mutation callbacks can handle local UI feedback such as toasts, closing dialogs, or navigation. They should not replace shared invalidation or add local cache patches for shared server state. -- For overlays that may open a heavier secondary surface, prefetch server data from the trigger/menu open event with `queryClient.prefetchQuery(queryOptions)` when the primitive exposes `onOpenChange`. Do not mount a hidden component or subscribe to a query only to warm the cache. Do not make an otherwise uncontrolled menu controlled only for prefetching. +- Keep `web/contract/*` as the API shape source of truth and follow the `{ params, query?, body? }` input shape. +- Consume generated queries with `useQuery(consoleQuery.xxx.queryOptions(...))` or `useQuery(marketplaceQuery.xxx.queryOptions(...))`. +- Consume owner-local mutations with `useMutation(consoleQuery.xxx.mutationOptions(...))` or `useMutation(marketplaceQuery.xxx.mutationOptions(...))` when pending/error state is not consumed by feature atoms. +- In `atomWithQuery`, `atomWithInfiniteQuery`, and `atomWithMutation`, return generated `queryOptions()`, `infiniteOptions()`, or `mutationOptions()` directly. Pass `enabled`, `retry`, `placeholderData`, `select`, and pagination options into the generated call instead of spreading options into a hand-built object. +- For generated oRPC options with missing required input, branch the whole input with `input: condition ? validInput : skipToken` and `enabled: Boolean(condition)`. Never place `skipToken` inside a nested placeholder payload or coerce required IDs to `''`. +- When prefetch and render use the same request, extract local query options or a query-options atom so `prefetchQuery` and `useQuery`/`atomWithQuery` share the exact options. +- For custom query or mutation functions, wrap options with TanStack `queryOptions(...)` or `mutationOptions(...)`. +- Avoid pass-through hooks and thin `web/service/use-*` wrappers that only rename generated options. Keep feature hooks for real orchestration, workflow state, or shared domain behavior. +- Put shared cache behavior in `createTanstackQueryUtils(...experimental_defaults...)`. Component or atom callbacks may handle local toasts, closing dialogs, and navigation, but should not replace shared invalidation or patch shared server state locally. +- For overlays that may open heavier secondary content, prefetch from the trigger/menu open event with `queryClient.prefetchQuery(queryOptions)` when `onOpenChange` is available. Do not mount hidden subscribers just to warm cache. - Do not use deprecated `useInvalid` or `useReset`. - Prefer `mutate(...)`; use `mutateAsync(...)` only when Promise semantics are required, and wrap awaited calls in `try/catch`. -## Component Boundaries +## Boundaries And Overlays -- Use the first level below a page or tab to organize independent page sections when it adds real structure. This layer is layout/semantic first, not automatically the data owner. -- Treat component names, semantic roles, and user- or design-marked visual regions as boundary constraints. Do not expand a child component's responsibility just because its data is useful nearby; keep adjacent UI as a sibling owner or introduce a correctly named broader owner. -- Split deeper components by the data and state each layer actually needs. Each component should access only necessary data, and ownership should stay at the lowest consumer. +- Use the first level below a page or tab to organize independent page sections when it adds structure. This layer is layout/semantic first, not automatically the data owner. +- Treat component names, semantic roles, and user- or design-marked visual regions as boundary constraints. Keep adjacent UI as a sibling owner or introduce a correctly named broader owner. - Keep cohesive forms, menu bodies, and one-off helpers local unless they need their own state, reuse, or semantic boundary. -- Separate hidden secondary surfaces from the trigger's main flow. For dialogs, dropdowns, popovers, and similar branches, extract a small local component that owns the trigger, open state, and hidden content when it would obscure the parent flow. -- Preserve composability by separating behavior ownership from layout ownership. A dropdown action may own its trigger, open state, and menu content; the caller owns placement such as slots, offsets, and alignment. -- When a dialog, dropdown, or popover component already accepts controlled `open` state, mount the surface unconditionally unless unmounting is required for performance or reset semantics. Use keyed scope or local state reset for reset behavior instead of `{open && }` wrappers. -- When opening a dialog from a menu item, keep the menu and dialog as sibling surfaces. Let the menu item command open the dialog through local state or scoped atoms, and mount the dialog outside the menu popup content. Avoid wrapping menu items with dialog triggers when the menu primitive already owns item activation and dismissal behavior. -- For dialogs and alert dialogs, keep the root component responsible for `open` wiring and put query/mutation hooks inside the content component when the work should only mount after the overlay opens. Do not put closed-surface remote work in the root just because the root owns the open atom. -- Prefer uncontrolled overlay roots when the library can own their open state. Use `onOpenChange` for side effects such as prefetching, and CSS/data selectors for visual open-state styling instead of adding controlled state only for observation. -- Avoid unnecessary DOM hierarchy. Do not add wrapper elements unless they provide layout, semantics, accessibility, state ownership, or integration with a library API; prefer fragments or styling an existing element when possible. -- Avoid shallow wrappers, hook-to-props adapter components, layout-only render-prop wrappers, children-as-pass-through composition, and prop renaming unless the wrapper adds validation, orchestration, error handling, state ownership, or a real semantic boundary. If a component only calls a hook, forwards props, or passes trigger/content through to one child, move the logic into that child or make the wrapper own a real surface. +- Separate hidden secondary surfaces from the trigger's main flow. For dialogs, dropdowns, popovers, and similar branches, extract a small local component when hidden content would obscure the parent. +- Preserve composability by separating behavior ownership from placement ownership: an action can own trigger/open/menu content while the caller owns slots, offsets, and alignment. +- When a dialog, dropdown, or popover accepts controlled `open`, mount it unconditionally unless unmounting is required for performance or reset semantics. Use keyed scope or local state reset instead of `{open && }` wrappers. +- When opening a dialog from a menu item, keep the menu and dialog as sibling surfaces. Let the menu command open the dialog, and mount the dialog outside menu popup content. +- For dialogs and alert dialogs, keep the root responsible for `open` wiring and put query/mutation hooks inside the content component when work should mount only after the overlay opens. +- Prefer uncontrolled overlay roots when the library can own open state. Use `onOpenChange` for side effects and CSS/data selectors for open-state styling. +- Avoid wrapper DOM unless it provides layout, semantics, accessibility, state ownership, or library integration. Avoid shallow wrappers, hook-to-props adapters, layout-only render props, children pass-through wrappers, and prop renaming unless they add real behavior or a real boundary. -## You Might Not Need An Effect - -- Use Effects only to synchronize with external systems such as browser APIs, non-React widgets, subscriptions, timers, analytics that must run because the component was shown, or imperative DOM integration. -- Do not use Effects to transform props or state for rendering. Calculate derived values during render, and use `useMemo` only when the calculation is actually expensive. -- Do not use Effects to handle user actions. Put action-specific logic in the event handler where the cause is known. -- Do not use Effects to copy one state value into another state value representing the same concept. Pick one source of truth and derive the rest during render. -- Do not reset or adjust state from props with an Effect. Prefer a `key` reset, storing a stable ID and deriving the selected object, or guarded same-component render-time adjustment when truly necessary. -- For forms initialized from query data, prefer keyed remounts or surface-entry hydration of form/field atoms over an Effect that copies query data into form state. -- Prefer framework data APIs or TanStack Query for data fetching instead of writing request Effects in components. -- If an Effect still seems necessary, first name the external system it synchronizes with. If there is no external system, remove the Effect and restructure the state or event flow. - -## Navigation And Performance +## Effects, Navigation, And Performance +- Use Effects only to synchronize with external systems. Do not use Effects to transform props/state for rendering, handle user actions, copy state, reset state from props, or fetch data. +- For forms initialized from query data, prefer keyed remounts or surface-entry atom hydration over Effects that copy query data into form state. +- Prefer framework data APIs or TanStack Query for data fetching. - Prefer `Link` for normal navigation. Use router APIs only for command-flow side effects such as mutation success, guarded redirects, or form submission. -- Before reaching for `memo`, first try moving changing state down to the smallest component that actually uses it so unrelated sibling trees stay untouched. -- If changing state must wrap other content, lift the unchanged content up and pass it as `children` so the stateful wrapper can update without React visiting that subtree. +- Before using `memo`, move changing state down to the smallest component that uses it. If state must wrap stable content, lift the stable content up and pass it as `children`. - Avoid `memo`, `useMemo`, and `useCallback` unless there is a clear performance reason. diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index e4c686adb31..c80e1f3d2be 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -105,6 +105,10 @@ jobs: if: steps.changed-files.outputs.any_changed == 'true' run: vp run knip + - name: Web dead code check production + if: steps.changed-files.outputs.any_changed == 'true' + run: vp run knip:production + ts-common-style: name: TS Common runs-on: depot-ubuntu-24.04 diff --git a/eslint-suppressions.json b/eslint-suppressions.json index 48f94044d8d..ba5b7366185 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -121,11 +121,6 @@ "count": 3 } }, - "web/__tests__/navigation-utils.test.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/__tests__/plugin-tool-workflow-error.test.tsx": { "ts/no-explicit-any": { "count": 2 @@ -343,14 +338,6 @@ "count": 4 } }, - "web/app/components/app-sidebar/app-sidebar-dropdown.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/app-sidebar/dataset-info/__tests__/index.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -559,14 +546,6 @@ "count": 1 } }, - "web/app/components/app/configuration/config-var/select-type-item/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/app/configuration/config-var/select-var-type.tsx": { "ts/no-explicit-any": { "count": 1 @@ -616,17 +595,6 @@ "count": 4 } }, - "web/app/components/app/configuration/config/assistant-type-picker/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/app/configuration/config/automatic/get-automatic-res.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -808,11 +776,6 @@ "count": 1 } }, - "web/app/components/app/configuration/prompt-value-panel/utils.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/app/create-app-dialog/app-list/index.tsx": { "no-restricted-imports": { "count": 1 @@ -1001,11 +964,6 @@ "count": 1 } }, - "web/app/components/apps/new-app-card.tsx": { - "react/set-state-in-effect": { - "count": 3 - } - }, "web/app/components/apps/starred-app-card.tsx": { "jsx-a11y/no-noninteractive-element-to-interactive-role": { "count": 1 @@ -1622,17 +1580,6 @@ "count": 2 } }, - "web/app/components/base/form/components/field/mixed-variable-text-input/placeholder.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 2 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 2 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/base/form/components/field/variable-selector.tsx": { "no-console": { "count": 1 @@ -1648,22 +1595,12 @@ "count": 1 } }, - "web/app/components/base/form/form-scenarios/base/index.tsx": { - "react/static-components": { - "count": 2 - } - }, "web/app/components/base/form/form-scenarios/base/types.ts": { "erasable-syntax-only/enums": { "count": 1 }, "ts/no-explicit-any": { - "count": 3 - } - }, - "web/app/components/base/form/form-scenarios/demo/index.tsx": { - "no-console": { - "count": 2 + "count": 1 } }, "web/app/components/base/form/form-scenarios/input-field/__tests__/field.spec.tsx": { @@ -1684,24 +1621,6 @@ "count": 2 } }, - "web/app/components/base/form/form-scenarios/node-panel/__tests__/field.spec.tsx": { - "react/static-components": { - "count": 2 - } - }, - "web/app/components/base/form/form-scenarios/node-panel/field.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/base/form/form-scenarios/node-panel/types.ts": { - "erasable-syntax-only/enums": { - "count": 1 - }, - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/base/form/hooks/index.ts": { "no-barrel-files/no-barrel-files": { "count": 3 @@ -1807,7 +1726,7 @@ }, "web/app/components/base/icons/src/vender/line/arrows/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 6 + "count": 5 } }, "web/app/components/base/icons/src/vender/line/communication/index.ts": { @@ -1832,7 +1751,7 @@ }, "web/app/components/base/icons/src/vender/line/files/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 6 + "count": 4 } }, "web/app/components/base/icons/src/vender/line/financeAndECommerce/index.ts": { @@ -1842,7 +1761,7 @@ }, "web/app/components/base/icons/src/vender/line/general/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 11 + "count": 10 } }, "web/app/components/base/icons/src/vender/line/images/index.ts": { @@ -1850,11 +1769,6 @@ "count": 1 } }, - "web/app/components/base/icons/src/vender/line/layout/index.ts": { - "no-barrel-files/no-barrel-files": { - "count": 1 - } - }, "web/app/components/base/icons/src/vender/line/mediaAndDevices/index.ts": { "no-barrel-files/no-barrel-files": { "count": 2 @@ -1917,7 +1831,7 @@ }, "web/app/components/base/icons/src/vender/solid/education/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 3 + "count": 2 } }, "web/app/components/base/icons/src/vender/solid/files/index.ts": { @@ -1986,17 +1900,6 @@ "count": 3 } }, - "web/app/components/base/image-uploader/audio-preview.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/media-has-caption": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/base/image-uploader/hooks.ts": { "ts/no-explicit-any": { "count": 4 @@ -2034,17 +1937,6 @@ "count": 2 } }, - "web/app/components/base/image-uploader/video-preview.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/media-has-caption": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/base/inline-delete-confirm/index.stories.tsx": { "no-console": { "count": 2 @@ -2594,27 +2486,6 @@ "count": 4 } }, - "web/app/components/base/with-input-validation/index.stories.tsx": { - "jsx-a11y/aria-role": { - "count": 7 - }, - "no-console": { - "count": 1 - } - }, - "web/app/components/base/with-input-validation/index.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/billing/header-billing-btn/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/billing/plan/assets/index.tsx": { "no-barrel-files/no-barrel-files": { "count": 4 @@ -2892,14 +2763,6 @@ "count": 3 } }, - "web/app/components/datasets/create/step-two/preview-item/index.tsx": { - "erasable-syntax-only/enums": { - "count": 1 - }, - "react-refresh/only-export-components": { - "count": 1 - } - }, "web/app/components/datasets/create/website/base/crawled-result-item.tsx": { "jsx-a11y/label-has-associated-control": { "count": 1 @@ -3364,14 +3227,6 @@ "count": 1 } }, - "web/app/components/datasets/list/dataset-card/operation-item.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/datasets/metadata/edit-metadata-batch/add-row.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -3655,19 +3510,6 @@ "count": 2 } }, - "web/app/components/header/account-setting/key-validator/Operate.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 4 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 4 - } - }, - "web/app/components/header/account-setting/key-validator/declarations.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx": { "jsx-a11y/no-autofocus": { "count": 1 @@ -3900,14 +3742,6 @@ "count": 1 } }, - "web/app/components/header/nav/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/main-nav/components/workspace-switcher.tsx": { "jsx-a11y/no-autofocus": { "count": 1 @@ -4044,11 +3878,6 @@ "count": 2 } }, - "web/app/components/plugins/plugin-auth/utils.ts": { - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -4212,17 +4041,9 @@ "count": 1 } }, - "web/app/components/plugins/plugin-detail-panel/tool-selector/__tests__/index.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 5 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 5 - } - }, "web/app/components/plugins/plugin-detail-panel/tool-selector/components/index.ts": { "no-barrel-files/no-barrel-files": { - "count": 7 + "count": 6 } }, "web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx": { @@ -4252,11 +4073,6 @@ "count": 3 } }, - "web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/index.ts": { - "no-barrel-files/no-barrel-files": { - "count": 2 - } - }, "web/app/components/plugins/plugin-detail-panel/tool-selector/index.tsx": { "no-restricted-imports": { "count": 1 @@ -4297,14 +4113,6 @@ "count": 1 } }, - "web/app/components/plugins/plugin-page/filter-management/__tests__/index.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/plugins/plugin-page/filter-management/category-filter.tsx": { "no-restricted-imports": { "count": 1 @@ -4629,11 +4437,6 @@ "count": 1 } }, - "web/app/components/share/utils.ts": { - "ts/no-explicit-any": { - "count": 2 - } - }, "web/app/components/snippet-list/components/snippet-card.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -4971,11 +4774,6 @@ "count": 4 } }, - "web/app/components/workflow/block-selector/use-check-vertical-scrollbar.ts": { - "react/set-state-in-effect": { - "count": 1 - } - }, "web/app/components/workflow/block-selector/use-sticky-scroll.ts": { "erasable-syntax-only/enums": { "count": 1 @@ -5342,30 +5140,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/__tests__/placeholder.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/index.tsx": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/workflow/nodes/_base/components/mixed-variable-text-input/placeholder.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 2 - }, - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/nodes/_base/components/next-step/operator.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 2 @@ -5421,14 +5195,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/_base/components/support-var-input/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -5627,11 +5393,6 @@ "count": 7 } }, - "web/app/components/workflow/nodes/agent/use-single-run-form-params.ts": { - "ts/no-explicit-any": { - "count": 3 - } - }, "web/app/components/workflow/nodes/answer/default.ts": { "ts/no-explicit-any": { "count": 1 @@ -5675,20 +5436,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/code/dependency-picker.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-autofocus": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - }, - "no-restricted-imports": { - "count": 1 - } - }, "web/app/components/workflow/nodes/code/types.ts": { "erasable-syntax-only/enums": { "count": 1 @@ -5784,14 +5531,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/http/components/key-value/bulk-edit/index.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/nodes/http/components/key-value/key-value-edit/index.tsx": { "ts/no-explicit-any": { "count": 2 @@ -6385,11 +6124,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/tool/components/input-var-list.tsx": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/nodes/tool/components/mixed-variable-text-input/index.tsx": { "ts/no-explicit-any": { "count": 1 @@ -6487,11 +6221,6 @@ "count": 1 } }, - "web/app/components/workflow/nodes/trigger-plugin/utils/form-helpers.ts": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/nodes/trigger-schedule/default.ts": { "regexp/no-unused-capturing-group": { "count": 2 @@ -6843,14 +6572,6 @@ "count": 1 } }, - "web/app/components/workflow/run/__tests__/loop-result-panel.spec.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/run/__tests__/special-result-panel.spec.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -6938,14 +6659,6 @@ "count": 2 } }, - "web/app/components/workflow/run/loop-result-panel.tsx": { - "jsx-a11y/click-events-have-key-events": { - "count": 1 - }, - "jsx-a11y/no-static-element-interactions": { - "count": 1 - } - }, "web/app/components/workflow/run/node.tsx": { "jsx-a11y/click-events-have-key-events": { "count": 1 @@ -7022,26 +6735,11 @@ "count": 11 } }, - "web/app/components/workflow/run/utils/format-log/graph-to-log-struct.ts": { - "ts/no-explicit-any": { - "count": 7 - } - }, "web/app/components/workflow/run/utils/format-log/index.ts": { "ts/no-explicit-any": { "count": 2 } }, - "web/app/components/workflow/run/utils/format-log/iteration/index.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, - "web/app/components/workflow/run/utils/format-log/loop/index.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/run/utils/format-log/parallel/index.ts": { "no-console": { "count": 4 @@ -7091,11 +6789,6 @@ "count": 1 } }, - "web/app/components/workflow/utils/debug.ts": { - "ts/no-explicit-any": { - "count": 1 - } - }, "web/app/components/workflow/utils/index.ts": { "no-barrel-files/no-barrel-files": { "count": 10 @@ -7924,11 +7617,6 @@ "count": 6 } }, - "web/utils/navigation.spec.ts": { - "ts/no-explicit-any": { - "count": 4 - } - }, "web/utils/tool-call.spec.ts": { "ts/no-explicit-any": { "count": 1 diff --git a/web/.storybook/utils/form-story-wrapper.tsx b/web/.storybook/utils/form-story-wrapper.tsx deleted file mode 100644 index 7503e9905d3..00000000000 --- a/web/.storybook/utils/form-story-wrapper.tsx +++ /dev/null @@ -1,88 +0,0 @@ -import type { ReactNode } from 'react' -import { useStore } from '@tanstack/react-form' -import { useState } from 'react' -import { useAppForm } from '@/app/components/base/form' - -type UseAppFormOptions = Parameters[0] -type AppFormInstance = ReturnType - -type FormStoryWrapperProps = { - options?: UseAppFormOptions - children: (form: AppFormInstance) => ReactNode - title?: string - subtitle?: string -} - -export const FormStoryWrapper = ({ - options, - children, - title, - subtitle, -}: FormStoryWrapperProps) => { - const [lastSubmitted, setLastSubmitted] = useState(null) - const [submitCount, setSubmitCount] = useState(0) - - const form = useAppForm({ - ...options, - onSubmit: (context) => { - setSubmitCount(count => count + 1) - setLastSubmitted(context.value) - options?.onSubmit?.(context) - }, - }) - - const values = useStore(form.store, state => state.values) - const isSubmitting = useStore(form.store, state => state.isSubmitting) - const canSubmit = useStore(form.store, state => state.canSubmit) - - return ( -
-
- {(title || subtitle) && ( -
- {title &&

{title}

} - {subtitle &&

{subtitle}

} -
- )} - {children(form)} -
- -
- ) -} - -export type FormStoryRender = (form: AppFormInstance) => ReactNode diff --git a/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx b/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx deleted file mode 100644 index c1f3a1c62d4..00000000000 --- a/web/__tests__/app-sidebar/sidebar-shell-flow.test.tsx +++ /dev/null @@ -1,151 +0,0 @@ -import type { SVGProps } from 'react' -import { fireEvent, render, screen } from '@testing-library/react' -import * as React from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import AppDetailNav from '@/app/components/app-sidebar' - -const mockSetDetailSidebarMode = vi.fn() - -let mockDetailSidebarMode = 'expand' -let mockPathname = '/app/app-1/logs' -let mockSelectedSegment = 'logs' -let mockIsHovering = true -let hotkeyHandler: ((event: { preventDefault: () => void }) => void) | null = null - -vi.mock('react-i18next', () => ({ - useTranslation: () => ({ - t: (key: string) => key, - }), -})) - -vi.mock('@/app/components/main-nav/storage', () => ({ - useDetailSidebarMode: () => [mockDetailSidebarMode, mockSetDetailSidebarMode], -})) - -vi.mock('@/next/navigation', () => ({ - usePathname: () => mockPathname, - useSelectedLayoutSegment: () => mockSelectedSegment, -})) - -vi.mock('@/next/link', () => ({ - default: ({ - href, - children, - className, - title, - }: { - href: string - children?: React.ReactNode - className?: string - title?: string - }) => ( - - {children} - - ), -})) - -vi.mock('ahooks', () => ({ - useHover: () => mockIsHovering, -})) - -vi.mock('@tanstack/react-hotkeys', async (importOriginal) => { - const actual = await importOriginal() - return { - ...actual, - useHotkey: (_hotkey: string, handler: (event: { preventDefault: () => void }) => void) => { - hotkeyHandler = handler - }, - } -}) - -vi.mock('@/hooks/use-breakpoints', () => ({ - default: () => 'desktop', - MediaType: { - mobile: 'mobile', - desktop: 'desktop', - }, -})) - -vi.mock('@/context/event-emitter', () => ({ - useEventEmitterContextContext: () => ({ - eventEmitter: { - useSubscription: vi.fn(), - }, - }), -})) - -vi.mock('@/context/app-context', () => ({ - useAppContext: () => ({ - isCurrentWorkspaceEditor: true, - }), -})) - -vi.mock('@langgenius/dify-ui/dropdown-menu', () => import('@/__mocks__/base-ui-dropdown-menu')) -vi.mock('@langgenius/dify-ui/tooltip', () => import('@/__mocks__/base-ui-tooltip')) - -vi.mock('@/app/components/app-sidebar/app-info', () => ({ - default: ({ - expand, - onlyShowDetail, - openState, - }: { - expand: boolean - onlyShowDetail?: boolean - openState?: boolean - }) => ( -
- ), -})) - -const MockIcon = (props: SVGProps) => - -const navigation = [ - { name: 'Overview', href: '/app/app-1/overview', icon: MockIcon, selectedIcon: MockIcon }, - { name: 'Logs', href: '/app/app-1/logs', icon: MockIcon, selectedIcon: MockIcon }, -] - -describe('App Sidebar Shell Flow', () => { - beforeEach(() => { - vi.clearAllMocks() - localStorage.clear() - mockDetailSidebarMode = 'expand' - mockPathname = '/app/app-1/logs' - mockSelectedSegment = 'logs' - mockIsHovering = true - hotkeyHandler = null - }) - - it('renders the expanded sidebar, marks the active nav item, and toggles collapse by click and shortcut', () => { - render() - - expect(screen.getByTestId('app-info')).toHaveAttribute('data-expand', 'true') - - const logsLink = screen.getByRole('link', { name: /Logs/i }) - expect(logsLink.className).toContain('bg-components-menu-item-bg-active') - - fireEvent.click(screen.getByRole('button')) - expect(mockSetDetailSidebarMode).toHaveBeenCalledWith('collapse') - - const preventDefault = vi.fn() - hotkeyHandler?.({ preventDefault }) - - expect(preventDefault).toHaveBeenCalled() - expect(mockSetDetailSidebarMode).toHaveBeenCalledWith('collapse') - }) - - it('keeps the normal sidebar on workflow routes', () => { - mockPathname = '/app/app-1/workflow' - mockSelectedSegment = 'workflow' - - render() - - expect(screen.getByTestId('app-info')).toBeInTheDocument() - expect(screen.getByRole('link', { name: /Overview/i })).toBeInTheDocument() - expect(screen.getByRole('link', { name: /Logs/i })).toBeInTheDocument() - }) -}) diff --git a/web/__tests__/base/form-demo-flow.test.tsx b/web/__tests__/base/form-demo-flow.test.tsx deleted file mode 100644 index afb36528c0f..00000000000 --- a/web/__tests__/base/form-demo-flow.test.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import { render, screen, waitFor, within } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import DemoForm from '@/app/components/base/form/form-scenarios/demo' - -describe('Base Form Demo Flow', () => { - const consoleLogSpy = vi.spyOn(console, 'log').mockImplementation(() => {}) - - beforeEach(() => { - vi.clearAllMocks() - }) - - it('reveals contact fields and submits the composed form values through the shared form actions', async () => { - const user = userEvent.setup() - render() - - expect(screen.queryByRole('heading', { name: /contacts/i })).not.toBeInTheDocument() - - await user.type(screen.getByRole('textbox', { name: /^name$/i }), 'Alice') - await user.type(screen.getByRole('textbox', { name: /^surname$/i }), 'Smith') - await user.click(screen.getByText(/i accept the terms and conditions/i)) - - expect(await screen.findByRole('heading', { name: /contacts/i })).toBeInTheDocument() - - await user.type(screen.getByRole('textbox', { name: /^email$/i }), 'alice@example.com') - - const preferredMethodLabel = screen.getByText('Preferred Contact Method') - const preferredMethodField = preferredMethodLabel.parentElement?.parentElement - expect(preferredMethodField).toBeTruthy() - - await user.click(within(preferredMethodField as HTMLElement).getByText('Email')) - await user.click(screen.getByText('Whatsapp')) - - const submitButton = screen.getByRole('button', { name: /operation\.submit/i }) - expect(submitButton).toBeEnabled() - await user.click(submitButton) - - await waitFor(() => { - expect(consoleLogSpy).toHaveBeenCalledWith('Form submitted:', expect.objectContaining({ - name: 'Alice', - surname: 'Smith', - isAcceptingTerms: true, - contact: expect.objectContaining({ - email: 'alice@example.com', - preferredContactMethod: 'whatsapp', - }), - })) - }) - }) - - it('removes the nested contact section again when the name field is cleared', async () => { - const user = userEvent.setup() - render() - - const nameInput = screen.getByRole('textbox', { name: /^name$/i }) - await user.type(nameInput, 'Alice') - expect(await screen.findByRole('heading', { name: /contacts/i })).toBeInTheDocument() - - await user.clear(nameInput) - - await waitFor(() => { - expect(screen.queryByRole('heading', { name: /contacts/i })).not.toBeInTheDocument() - }) - }) -}) diff --git a/web/__tests__/billing/billing-integration.test.tsx b/web/__tests__/billing/billing-integration.test.tsx index 2fde9b506f4..e82a6d8eac2 100644 --- a/web/__tests__/billing/billing-integration.test.tsx +++ b/web/__tests__/billing/billing-integration.test.tsx @@ -7,7 +7,6 @@ import AnnotationFullModal from '@/app/components/billing/annotation-full/modal' import AppsFull from '@/app/components/billing/apps-full-in-dialog' import Billing from '@/app/components/billing/billing-page' import { defaultPlan, NUM_INFINITE } from '@/app/components/billing/config' -import HeaderBillingBtn from '@/app/components/billing/header-billing-btn' import PlanComp from '@/app/components/billing/plan' import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal' import PriorityLabel from '@/app/components/billing/priority-label' @@ -696,83 +695,7 @@ describe('Capacity Full Components Integration', () => { }) // ═══════════════════════════════════════════════════════════════════════════ -// 5. Header Billing Button Integration -// Tests HeaderBillingBtn behavior for different plan states -// ═══════════════════════════════════════════════════════════════════════════ -describe('Header Billing Button Integration', () => { - beforeEach(() => { - vi.clearAllMocks() - setupAppContext() - }) - - it('should render UpgradeBtn (premium badge) for sandbox plan', () => { - setupProviderContext({ type: Plan.sandbox }) - - render() - - expect(screen.getByText(/upgradeBtn\.encourageShort/i)).toBeInTheDocument() - }) - - it('should render "pro" badge for professional plan', () => { - setupProviderContext({ type: Plan.professional }) - - render() - - expect(screen.getByText('pro')).toBeInTheDocument() - expect(screen.queryByText(/upgradeBtn/i)).not.toBeInTheDocument() - }) - - it('should render "team" badge for team plan', () => { - setupProviderContext({ type: Plan.team }) - - render() - - expect(screen.getByText('team')).toBeInTheDocument() - }) - - it('should return null when billing is disabled', () => { - setupProviderContext({ type: Plan.sandbox }, { enableBilling: false }) - - const { container } = render() - - expect(container.innerHTML).toBe('') - }) - - it('should return null when plan is not fetched yet', () => { - setupProviderContext({ type: Plan.sandbox }, { isFetchedPlan: false }) - - const { container } = render() - - expect(container.innerHTML).toBe('') - }) - - it('should call onClick when clicking pro/team badge in non-display-only mode', async () => { - const user = userEvent.setup() - const onClick = vi.fn() - setupProviderContext({ type: Plan.professional }) - - render() - - await user.click(screen.getByText('pro')) - - expect(onClick).toHaveBeenCalledTimes(1) - }) - - it('should not call onClick when isDisplayOnly is true', async () => { - const user = userEvent.setup() - const onClick = vi.fn() - setupProviderContext({ type: Plan.professional }) - - render() - - await user.click(screen.getByText('pro')) - - expect(onClick).not.toHaveBeenCalled() - }) -}) - -// ═══════════════════════════════════════════════════════════════════════════ -// 6. PriorityLabel Integration +// 5. PriorityLabel Integration // Tests priority badge display for different plan types // ═══════════════════════════════════════════════════════════════════════════ describe('PriorityLabel Integration', () => { diff --git a/web/__tests__/header/nav-flow.test.tsx b/web/__tests__/header/nav-flow.test.tsx deleted file mode 100644 index 33927f19da4..00000000000 --- a/web/__tests__/header/nav-flow.test.tsx +++ /dev/null @@ -1,168 +0,0 @@ -import { fireEvent, render, screen, waitFor } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import * as React from 'react' -import { beforeEach, describe, expect, it, vi } from 'vitest' -import Nav from '@/app/components/header/nav' -import { AppModeEnum } from '@/types/app' - -const mockPush = vi.fn() -const mockSetAppDetail = vi.fn() -const mockOnCreate = vi.fn() -const mockOnLoadMore = vi.fn() - -let mockSelectedSegment = 'app' -let mockIsCurrentWorkspaceEditor = true - -vi.mock('react-i18next', () => ({ - useTranslation: () => ({ - t: (key: string) => key, - }), -})) - -vi.mock('@/next/navigation', () => ({ - useSelectedLayoutSegment: () => mockSelectedSegment, - useRouter: () => ({ - push: mockPush, - }), -})) - -vi.mock('@/next/link', () => ({ - default: ({ - href, - children, - }: { - href: string - children?: React.ReactNode - }) => {children}, -})) - -vi.mock('@/app/components/app/store', () => ({ - useStore: () => mockSetAppDetail, -})) - -vi.mock('@/context/app-context', () => ({ - useAppContext: () => ({ - isCurrentWorkspaceEditor: mockIsCurrentWorkspaceEditor, - workspacePermissionKeys: mockIsCurrentWorkspaceEditor ? ['app.create_and_management'] : [], - }), -})) - -const navigationItems = [ - { - id: 'app-1', - name: 'Alpha', - link: '/app/app-1/configuration', - icon_type: 'emoji' as const, - icon: '🤖', - icon_background: '#FFEAD5', - icon_url: null, - mode: AppModeEnum.CHAT, - }, - { - id: 'app-2', - name: 'Bravo', - link: '/app/app-2/workflow', - icon_type: 'emoji' as const, - icon: '⚙️', - icon_background: '#E0F2FE', - icon_url: null, - mode: AppModeEnum.WORKFLOW, - }, -] - -const curNav = { - id: 'app-1', - name: 'Alpha', - icon_type: 'emoji' as const, - icon: '🤖', - icon_background: '#FFEAD5', - icon_url: null, - mode: AppModeEnum.CHAT, -} - -const renderNav = (nav = curNav) => { - return render( -