Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): replace use-breakpoints with dify-ui useMediaQuery (#45595)
yyh54bace4594d4
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex c71ba7bc5ef..b8f58764fe4 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -351,9 +351,6 @@}},"web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 4- },"typescript/no-explicit-any": {"count": 3}@@ -497,11 +494,6 @@"count": 4}},- "web/app/components/app/configuration/dataset-config/card-item/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 1- }- },"web/app/components/app/configuration/dataset-config/context-var/index.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 3@@ -735,11 +727,6 @@"count": 1}},- "web/app/components/app/log/list.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 34- }- },"web/app/components/app/log/model-info.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 5@@ -831,9 +818,6 @@}},"web/app/components/app/workflow-log/list.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 27- },"eslint-react/set-state-in-effect": {"count": 2}@@ -1002,9 +986,6 @@}},"web/app/components/base/chat/chat-with-history/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 3- },"eslint-react/set-state-in-effect": {"count": 1}@@ -1150,11 +1131,6 @@"count": 14}},- "web/app/components/base/chat/embedded-chatbot/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 1- }- },"web/app/components/base/chat/embedded-chatbot/inputs-form/content.tsx": {"typescript/no-explicit-any": {"count": 3@@ -2664,11 +2640,6 @@"count": 1}},- "web/app/components/datasets/documents/detail/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 6- }- },"web/app/components/datasets/documents/detail/metadata/index.tsx": {"no-barrel-files/no-barrel-files": {"count": 1@@ -2864,9 +2835,6 @@}},"web/app/components/explore/try-app/app/text-generation.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 3- },"dify/require-disable-directive-description": {"count": 1},@@ -2888,9 +2856,6 @@}},"web/app/components/explore/try-app/preview/basic-app-preview.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 2- },"typescript/no-explicit-any": {"count": 2}@@ -3731,11 +3696,6 @@"count": 2}},- "web/app/components/share/text-generation/run-batch/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 2- }- },"web/app/components/share/text-generation/run-batch/res-download/index.tsx": {"eslint-react/static-components": {"count": 2@@ -5015,11 +4975,6 @@"count": 1}},- "web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 2- }- },"web/app/components/workflow/nodes/knowledge-retrieval/components/metadata/condition-list/condition-common-variable-selector.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 5@@ -6416,11 +6371,6 @@"count": 2}},- "web/features/agent-v2/agent-detail/logs/page.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 1- }- },"web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 2diff --git a/packages/dify-ui/README.md b/packages/dify-ui/README.mdindex c2b8fb86aeb..3b3eea22aee 100644--- a/packages/dify-ui/README.md+++ b/packages/dify-ui/README.md@@ -52,6 +52,7 @@ Utilities:- `./direction-provider` exports Base UI `DirectionProvider` and `useDirection`. Set HTML `dir` as well for CSS layout; pickers propagate their resolved direction to their trigger and portaled content.- `./cn` re-exports `cn` from the `cn` package through Dify UI's public subpath.+- `./use-media-query` exports Base UI's `useMediaQuery(query, options)`, which follows `matchMedia` change events and returns `defaultMatches` (false) on the server and during hydration.- `./use-merged-refs` exports `useMergedRefs` for combining internal and caller refs, including callback cleanup.- `./use-ref-with-init` exports `useRefWithInit` for lazy ref initialization. Later initializer or argument changes do not reset the ref; initialization runs during render and must be safe to retry or discard.- `./use-render` exports `useRender` for building a part with Base UI's `render` prop, `className(state)` callback and state data attributes; `./merge-props` exports `mergeProps` for chaining event handlers and merging `className`/`style` when composing parts.diff --git a/packages/dify-ui/package.json b/packages/dify-ui/package.jsonindex 7f4b244b2eb..6e88695f527 100644--- a/packages/dify-ui/package.json+++ b/packages/dify-ui/package.json@@ -17,6 +17,10 @@"types": "./src/use-ref-with-init.ts","import": "./src/use-ref-with-init.ts"},+ "./use-media-query": {+ "types": "./src/use-media-query.ts",+ "import": "./src/use-media-query.ts"+ },"./use-render": {"types": "./src/use-render.ts","import": "./src/use-render.ts"diff --git a/packages/dify-ui/src/use-media-query.ts b/packages/dify-ui/src/use-media-query.tsnew file mode 100644index 00000000000..5a8973ebba4--- /dev/null+++ b/packages/dify-ui/src/use-media-query.ts@@ -0,0 +1,3 @@+'use client'++export { useMediaQuery } from '@base-ui/react/unstable-use-media-query'diff --git a/web/AGENTS.md b/web/AGENTS.mdindex 97d2138e332..42574f185ed 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -20,6 +20,7 @@ Web owns application-specific requirements and consumes shared architecture guid- Follow the canonical [Button contract] and [IconButton contract] for action semantics, loading, accessible names, and primitive composition. Do not add a Web wrapper that hides those contracts.- Follow [Keyboard commands] for hotkey ownership, targets, event consumption, typed bindings, and keycap display. Keep widget and editor keyboard semantics in their local owners.- Follow [Accessible names and descriptions] when choosing or changing visible labels, ARIA naming, descriptions, or visually hidden text. Web owns localization and feature-specific status announcements; do not redefine the Dify UI naming contract locally.+- Before switching UI by viewport width, read [Responsive layout]: one component tree, CSS for appearance, width in JavaScript only for behaviour.- Follow the [Dify UI overlay contract] for primitive selection, portals, focus, and layering. Use `@langgenius/dify-ui/infotip` for an info glyph that opens explanatory content. Do not introduce a generic Web wrapper that recreates Dify UI overlay behavior.- For custom SVG icons, follow `../packages/iconify-collections/README.md`; do not add generated React icons under `app/components/base/icons/src/`.- `docs/test.md` is the single source of truth for Web automated-test policy. Skills may route and execute that policy but must not redefine it.@@ -42,6 +43,7 @@ This block is written and re-added by `next dev` — verify at `node_modules/nex[Input Group contract]: ../packages/dify-ui/src/input-group/README.md[Keyboard commands]: docs/hotkeys.md[Page landmarks]: docs/landmarks.md+[Responsive layout]: docs/responsive-layout.md[Toasts]: docs/toasts.md[Truncated Text Disclosure]: docs/truncated-text-disclosure.md[form contract]: ../packages/dify-ui/docs/forms.mddiff --git a/web/__tests__/base/chat-flow.test.tsx b/web/__tests__/base/chat-flow.test.tsxindex 2fb808f1812..123e0e15a03 100644--- a/web/__tests__/base/chat-flow.test.tsx+++ b/web/__tests__/base/chat-flow.test.tsx@@ -1,12 +1,12 @@import type { RefObject } from 'react'import type { ChatConfig } from '@/app/components/base/chat/types'import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import ChatWithHistory from '@/app/components/base/chat/chat-with-history'import { useChatWithHistoryContext } from '@/app/components/base/chat/chat-with-history/context'import { useChatWithHistory } from '@/app/components/base/chat/chat-with-history/hooks'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { renderWithConsoleQuery as render } from '@/test/console/query-data'vi.mock('@/app/components/base/chat/chat-with-history/hooks', () => ({@@ -27,13 +27,8 @@ vi.mock('@/app/components/base/chat/chat-with-history/chat-wrapper', () => {return { default: ChatThemeProbe }})-vi.mock('@/hooks/use-breakpoints', () => ({- default: vi.fn(),- MediaType: {- mobile: 'mobile',- tablet: 'tablet',- pc: 'pc',- },+vi.mock('@langgenius/dify-ui/use-media-query', () => ({+ useMediaQuery: vi.fn(),}))vi.mock('@/next/navigation', () => ({@@ -116,7 +111,7 @@ const defaultHookReturn: HookReturn = {describe('Base Chat Flow', () => {beforeEach(() => {vi.clearAllMocks()- vi.mocked(useBreakpoints).mockReturnValue(MediaType.pc)+ vi.mocked(useMediaQuery).mockReturnValue(false)vi.mocked(useChatWithHistory).mockReturnValue(defaultHookReturn)})@@ -149,7 +144,7 @@ describe('Base Chat Flow', () => {})it('falls back to the mobile loading shell when site metadata is unavailable', () => {- vi.mocked(useBreakpoints).mockReturnValue(MediaType.mobile)+ vi.mocked(useMediaQuery).mockReturnValue(true)vi.mocked(useChatWithHistory).mockReturnValue({...defaultHookReturn,appData: null,diff --git a/web/app/components/app-sidebar/dataset-detail-sidebar.tsx b/web/app/components/app-sidebar/dataset-detail-sidebar.tsxindex b7b0dd488b0..a791b5f0ee0 100644--- a/web/app/components/app-sidebar/dataset-detail-sidebar.tsx+++ b/web/app/components/app-sidebar/dataset-detail-sidebar.tsx@@ -1,18 +1,18 @@'use client'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { DetailSidebarFrame } from '@/app/components/detail-sidebar'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { usePathname } from '@/next/navigation'import DatasetDetailSection from './dataset-detail-section'import { DatasetDetailTop } from './dataset-detail-top'export function DatasetDetailSidebar() {- const media = useBreakpoints()+ const isMobile = useMediaQuery('(width < 40rem)', {})const pathname = usePathname()return (<DetailSidebarFrame- compact={media === MediaType.mobile && pathname.endsWith('/settings')}+ compact={isMobile && pathname.endsWith('/settings')}renderTop={({ expand, onToggle }) => <DatasetDetailTop expand={expand} onToggle={onToggle} />}renderSection={({ expand }) => <DatasetDetailSection expand={expand} />}/>diff --git a/web/app/components/app/configuration/__tests__/configuration-flow.spec.tsx b/web/app/components/app/configuration/__tests__/configuration-flow.spec.tsxindex 6dc4ee22098..3ba2446f2d4 100644--- a/web/app/components/app/configuration/__tests__/configuration-flow.spec.tsx+++ b/web/app/components/app/configuration/__tests__/configuration-flow.spec.tsx@@ -35,6 +35,7 @@ import { createAppDetailFixture, createAppModelConfigFixture } from '@/test/fixtimport { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'import { createNuqsTestWrapper } from '@/test/nuqs-testing'+import { resetViewportWidth, setViewportWidth } from '@/test/viewport'import { AppACLPermission } from '@/utils/permission'import Configuration from '../index'import { toast as configurationToast } from '../toast'@@ -257,7 +258,7 @@ afterEach(() =>act(() => {toast.dismiss()configurationToast.dismiss()- vi.unstubAllGlobals()+ resetViewportWidth()}),)@@ -558,7 +559,7 @@ it('preserves feature drafts across reopening and restores the last published fe})it('opens and closes the mobile debug drawer while preserving the configuration draft', async () => {- vi.stubGlobal('innerWidth', 390)+ setViewportWidth(390)const { user } = setup()await waitForPage()await user.type(prompt(), ' Mobile draft.')diff --git a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsxindex a5e915df6d2..9abce6cfc97 100644--- a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx@@ -25,7 +25,6 @@ import { INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '@/app/components/base/prompimport ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useModalContext } from '@/context/modal-context'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { getNewVar, getVars } from '@/utils/var'import ConfirmAddVar from './confirm-add-var'import PromptEditorHeightResizeWrap from './prompt-editor-height-resize-wrap'@@ -58,8 +57,6 @@ const Prompt: FC<ISimplePromptInput> = ({mode !== 'completion'? t(($) => $.chatSubTitle, { ns: 'appDebug' }): t(($) => $.completionSubTitle, { ns: 'appDebug' })- const media = useBreakpoints()- const isMobile = media === MediaType.mobileconst featuresStore = useFeaturesStore()const { features, setFeatures } = featuresStore!.getState()@@ -202,22 +199,22 @@ const Prompt: FC<ISimplePromptInput> = ({><div className="rounded-xl bg-background-section-burn">{!noTitle && (- <div className="flex h-11 items-center justify-between pr-2.5 pl-3">+ <div className="flex h-11 items-center justify-between ps-3 pe-2.5"><div className="flex items-center space-x-1"><h2 id={titleId} className="system-sm-semibold-uppercase text-text-secondary">{title}</h2>{!readonly && (<Infotip>- <InfotipTrigger aria-labelledby={titleId} className="ml-1" />+ <InfotipTrigger aria-labelledby={titleId} className="ms-1" /><InfotipContent aria-labelledby={titleId} className="w-45">{t(($) => $.promptTip, { ns: 'appDebug', input: '{{input}}' })}</InfotipContent></Infotip>)}</div>- <div className="flex items-center">- {!readonly && !isMobile && <AutomaticBtn onClick={showAutomaticTrue} />}+ <div className="flex items-center max-sm:hidden">+ {!readonly && <AutomaticBtn onClick={showAutomaticTrue} />}</div></div>)}@@ -229,7 +226,7 @@ const Prompt: FC<ISimplePromptInput> = ({onHeightChange={setEditorHeight}hideResize={noResize}footer={- <div className="flex rounded-b-xl bg-background-default pb-2 pl-4">+ <div className="flex rounded-b-xl bg-background-default ps-4 pb-2"><div className="h-4.5 rounded-md bg-components-badge-bg-gray-soft px-1 text-xs leading-4.5 text-text-tertiary">{promptTemplate.length}</div>diff --git a/web/app/components/app/configuration/dataset-config/card-item/index.tsx b/web/app/components/app/configuration/dataset-config/card-item/index.tsxindex e5782c70d77..b9b5bae148e 100644--- a/web/app/components/app/configuration/dataset-config/card-item/index.tsx+++ b/web/app/components/app/configuration/dataset-config/card-item/index.tsx@@ -18,7 +18,6 @@ import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import AppIcon from '@/app/components/base/app-icon'import Badge from '@/app/components/base/badge'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { useKnowledge } from '@/hooks/use-knowledge'import SettingsModal from '../settings-modal'@@ -32,8 +31,6 @@ type ItemProps = {}const Item: FC<ItemProps> = ({ config, onSave, onRemove, readonly = false, editable = true }) => {- const media = useBreakpoints()- const isMobile = media === MediaType.mobileconst settingsDrawerActionsRef = useRef<DrawerActions>(null)const { formatIndexingTechniqueAndMethod } = useKnowledge()const { t } = useTranslation(['common', 'dataset'])@@ -66,7 +63,7 @@ const Item: FC<ItemProps> = ({ config, onSave, onRemove, readonly = false, edita{config.name}</div></div>- <div className="ml-2 hidden shrink-0 items-center space-x-1 group-hover:flex">+ <div className="ms-2 hidden shrink-0 items-center space-x-1 group-hover:flex">{editable && !readonly && (<Drawer actionsRef={settingsDrawerActionsRef} modal swipeDirection="right"><DrawerTrigger@@ -83,7 +80,7 @@ const Item: FC<ItemProps> = ({ config, onSave, onRemove, readonly = false, edita}/><DrawerPortal>- <DrawerBackdrop className={cn(!isMobile && 'bg-transparent')} />+ <DrawerBackdrop className="sm:bg-transparent" /><DrawerViewport><DrawerPopup className="p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-160 data-[swipe-direction=right]:rounded-xl"><DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">diff --git a/web/app/components/app/configuration/hooks/use-configuration.ts b/web/app/components/app/configuration/hooks/use-configuration.tsindex 514e96a908a..97c393de2d8 100644--- a/web/app/components/app/configuration/hooks/use-configuration.ts+++ b/web/app/components/app/configuration/hooks/use-configuration.ts@@ -6,6 +6,7 @@ import type { ConfigurationAppMode } from '@/app/components/app/configuration/hoimport type { OnFeaturesChange } from '@/app/components/base/features/types'import type { Collection } from '@/app/components/tools/types'import type { Inputs, ModelConfig, PromptConfig, PromptVariable } from '@/models/debug'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { produce } from 'immer'@@ -25,7 +26,6 @@ import {settingsQueryParamName,settingsQueryParser,} from '@/app/components/header/account-setting/query-params'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { PromptMode } from '@/models/debug'import { consoleQuery } from '@/service/console'import { ModelModeType } from '@/types/app'@@ -68,8 +68,7 @@ export const useConfiguration = (): ConfigurationViewModel => {const [publishedConfig, setPublishedConfig] = useState<ConfigurationPublishConfig | null>(null)const [conversationId, setConversationId] = useState<string | null>('')- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isMobile = useMediaQuery('(width < 40rem)', {})const [isShowDebugPanel, { setTrue: showDebugPanel, setFalse: hideDebugPanel }] =useBoolean(false)diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex f84ac661b61..ec6d924402c 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -21,6 +21,7 @@ import {} from '@langgenius/dify-ui/dialog'import { StatusDot } from '@langgenius/dify-ui/status-dot'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { RiEditFill } from '@remixicon/react'import dayjs from 'dayjs'import timezone from 'dayjs/plugin/timezone'@@ -28,7 +29,6 @@ import utc from 'dayjs/plugin/utc'import { parseAsString, useQueryState } from 'nuqs'import { Suspense, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useTimestamp from '@/hooks/use-timestamp'import { ConversationDetail } from './conversation-detail'import EmptyElement from './empty-element'@@ -66,9 +66,9 @@ const HandThumbIconWithCount: FC<{ count: number; iconType: 'up' | 'down' }> = (const Icon = iconType === 'up' ? HandThumbUpIcon : HandThumbDownIconreturn (<div- className={`inline-flex w-fit items-center rounded-md p-1 text-xs ${classname} mr-1 last:mr-0`}+ className={`inline-flex w-fit items-center rounded-md p-1 text-xs ${classname} me-1 last:me-0`}>- <Icon className="mr-0.5 size-3 rounded-md" />+ <Icon className="me-0.5 size-3 rounded-md" />{count > 0 ? count : null}</div>)@@ -122,8 +122,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh }))const popupRef = useRef<HTMLDivElement>(null)- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isBelowSm = useMediaQuery('(width < 40rem)', {})const isChatMode = appDetail.mode !== 'completion'const isChatflow = appDetail.mode === 'advanced-chat'@@ -178,8 +177,8 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })<div className="relative mt-2 grow overflow-x-auto"><Dialogopen={!!conversationIdInUrl}- modal={isMobile}- disablePointerDismissal={!isMobile}+ modal={isBelowSm}+ disablePointerDismissal={!isBelowSm}onOpenChange={(open) => {if (!open) onCloseDialog()}}@@ -198,35 +197,35 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</colgroup><thead className="system-xs-medium-uppercase text-text-tertiary"><tr>- <td className="w-5 rounded-l-lg bg-background-section-burn pr-1 pl-2 whitespace-nowrap"></td>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <td className="w-5 rounded-s-lg bg-background-section-burn ps-2 pe-1 whitespace-nowrap"></td>+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{isChatMode? t(($) => $['table.header.summary'], { ns: 'appLog' }): t(($) => $['table.header.input'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.endUser'], { ns: 'appLog' })}</th>{isChatflow && (- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.status'], { ns: 'appLog' })}</th>)}- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{isChatMode? t(($) => $['table.header.messageCount'], { ns: 'appLog' }): t(($) => $['table.header.output'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.userRate'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.adminRate'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.updatedTime'], { ns: 'appLog' })}</th>- <th className="rounded-r-lg bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="rounded-e-lg bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.time'], { ns: 'appLog' })}</th></tr>@@ -266,7 +265,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })><td className="h-4">{!log.read_at && (- <div className="flex items-center p-3 pr-0.5">+ <div className="flex items-center p-3 pe-0.5"><spanaria-hidden="true"className="inline-block size-1.5 rounded-sm bg-util-colors-blue-blue-500"@@ -277,22 +276,22 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</div>)}</td>- <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>+ <td className="w-40 p-3 pe-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>{renderTdValue(leftValue,isLeftEmpty,isChatMode && 'annotated' in log && log.annotated,)}</td>- <td className="p-3 pr-2">+ <td className="p-3 pe-2">{renderTdValue(endUser || defaultValue, !endUser)}</td>{isChatflow && (- <td className="w-40 p-3 pr-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>+ <td className="w-40 p-3 pe-2" style={{ maxWidth: isChatMode ? 300 : 200 }}>{statusTdRender('status_count' in log ? log.status_count : undefined)}</td>)}- <td className="p-3 pr-2" style={{ maxWidth: isChatMode ? 100 : 200 }}>+ <td className="p-3 pe-2" style={{ maxWidth: isChatMode ? 100 : 200 }}>{renderTdValue(rightValue,isRightEmpty,@@ -300,7 +299,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })'annotation' in log ? log.annotation : undefined,)}</td>- <td className="p-3 pr-2">+ <td className="p-3 pe-2">{!log.user_feedback_stats?.like && !log.user_feedback_stats?.dislike ? (renderTdValue(defaultValue, true)) : (@@ -320,7 +319,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</>)}</td>- <td className="p-3 pr-2">+ <td className="p-3 pe-2">{!log.admin_feedback_stats?.like && !log.admin_feedback_stats?.dislike ? (renderTdValue(defaultValue, true)) : (@@ -340,7 +339,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</>)}</td>- <td className="w-40 p-3 pr-2">+ <td className="w-40 p-3 pe-2">{log.updated_at? formatTime(log.updated_at,@@ -348,10 +347,10 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })): defaultValue}</td>- <td className="w-40 p-3 pr-2">+ <td className="w-40 p-3 pe-2"><DialogTriggerdata-log-detail-trigger- className="w-full cursor-pointer rounded-sm text-left"+ className="w-full cursor-pointer rounded-sm text-start"onClick={(event) => {event.stopPropagation()handleRowClick(log)@@ -373,12 +372,12 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })</tbody></table><DialogPortal>- {isMobile && <DialogBackdrop />}+ {isBelowSm && <DialogBackdrop />}<DialogViewport className="pointer-events-none"><DialogPopupref={popupRef}initialFocus={popupRef}- className="pointer-events-auto fixed top-16 right-2 bottom-4 flex w-[calc(100%-1rem)] max-w-160 flex-col overflow-hidden rounded-xl bg-components-panel-bg shadow-xl outline-hidden"+ className="pointer-events-auto fixed inset-e-2 top-16 bottom-4 flex w-[calc(100%-1rem)] max-w-160 flex-col overflow-hidden rounded-xl bg-components-panel-bg shadow-xl outline-hidden"><div className="flex min-h-0 flex-1 flex-col"><ConversationSession appDetail={appDetail} conversationId={conversationIdInUrl} />diff --git a/web/app/components/app/workflow-log/__tests__/list.spec.tsx b/web/app/components/app/workflow-log/__tests__/list.spec.tsxindex 51b357af764..b2604cda605 100644--- a/web/app/components/app/workflow-log/__tests__/list.spec.tsx+++ b/web/app/components/app/workflow-log/__tests__/list.spec.tsx@@ -28,14 +28,6 @@ vi.mock('@/hooks/use-timestamp', () => ({}),}))-vi.mock('@/hooks/use-breakpoints', () => ({- default: () => 'pc', // Return desktop by default- MediaType: {- mobile: 'mobile',- pc: 'pc',- },-}))-const { fetchRunDetail, fetchTracingList } = vi.hoisted(() => ({fetchRunDetail: vi.fn(),fetchTracingList: vi.fn(),diff --git a/web/app/components/app/workflow-log/list.tsx b/web/app/components/app/workflow-log/list.tsxindex bddb1bca30e..eba1daecb8e 100644--- a/web/app/components/app/workflow-log/list.tsx+++ b/web/app/components/app/workflow-log/list.tsx@@ -23,7 +23,6 @@ import * as React from 'react'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useTimestamp from '@/hooks/use-timestamp'import DetailPanel from './detail'import TriggerByDisplay from './trigger-by-display'@@ -40,9 +39,6 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {const { t } = useTranslation(['appLog'])const { formatTime } = useTimestamp()- const media = useBreakpoints()- const isMobile = media === MediaType.mobile-const [showDrawer, setShowDrawer] = useState<boolean>(false)const [currentLog, setCurrentLog] = useState<WorkflowAppLogPartialResponse | undefined>()const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc')@@ -162,20 +158,20 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {<table className={cn('mt-2 w-full min-w-110 border-collapse border-0')}><thead className="system-xs-medium-uppercase text-text-tertiary"><tr>- <td className="w-5 rounded-l-lg bg-background-section-burn pr-1 pl-2 whitespace-nowrap"></td>+ <td className="w-5 rounded-s-lg bg-background-section-burn ps-2 pe-1 whitespace-nowrap"></td><tharia-sort={sortOrder === 'asc' ? 'ascending' : 'descending'}- className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap"+ className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap"><buttontype="button"- className="flex cursor-pointer items-center border-none bg-transparent p-0 text-left hover:text-text-secondary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ className="flex cursor-pointer items-center border-none bg-transparent p-0 text-start hover:text-text-secondary focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"onClick={handleSort}>{t(($) => $['table.header.startTime'], { ns: 'appLog' })}<ArrowDownIconclassName={cn(- 'ml-0.5 size-3 stroke-current stroke-2 transition-all',+ 'ms-0.5 size-3 stroke-current stroke-2 transition-all','text-text-tertiary',sortOrder === 'asc' ? 'rotate-180' : '',)}@@ -183,25 +179,25 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {/></button></th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.status'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.runtime'], { ns: 'appLog' })}</th>- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.tokens'], { ns: 'appLog' })}</th><thclassName={cn(- 'bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap',- !isWorkflow ? 'rounded-r-lg' : '',+ 'bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap',+ !isWorkflow ? 'rounded-e-lg' : '',)}>{t(($) => $['table.header.user'], { ns: 'appLog' })}</th>{isWorkflow && (- <th className="rounded-r-lg bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">+ <th className="rounded-e-lg bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">{t(($) => $['table.header.triggered_from'], { ns: 'appLog' })}</th>)}@@ -231,15 +227,15 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {<td className="h-4">{/* The console workflow-log response does not declare read_at yet. */}{!('read_at' in log && log.read_at) && (- <div className="flex items-center p-3 pr-0.5">+ <div className="flex items-center p-3 pe-0.5"><span className="inline-block size-1.5 rounded-sm bg-util-colors-blue-blue-500"></span></div>)}</td>- <td className="w-45 p-3 pr-2">+ <td className="w-45 p-3 pe-2"><DrawerTriggerdata-log-detail-trigger- className="w-full cursor-pointer rounded-sm text-left"+ className="w-full cursor-pointer rounded-sm text-start"onClick={(event) => {event.stopPropagation()setCurrentLog(log)@@ -254,14 +250,14 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {: defaultValue}</DrawerTrigger></td>- <td className="p-3 pr-2">{statusTdRender(log.workflow_run?.status)}</td>- <td className="p-3 pr-2">+ <td className="p-3 pe-2">{statusTdRender(log.workflow_run?.status)}</td>+ <td className="p-3 pe-2"><div className={cn(!log.workflow_run?.elapsed_time && 'text-text-quaternary')}>{`${(log.workflow_run?.elapsed_time ?? 0).toFixed(3)}s`}</div></td>- <td className="p-3 pr-2">{log.workflow_run?.total_tokens}</td>- <td className="p-3 pr-2">+ <td className="p-3 pe-2">{log.workflow_run?.total_tokens}</td>+ <td className="p-3 pe-2"><divclassName={cn(endUser === defaultValue ? 'text-text-quaternary' : 'text-text-secondary',@@ -272,7 +268,7 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {</div></td>{isWorkflow && (- <td className="p-3 pr-2">+ <td className="p-3 pe-2"><TriggerByDisplaytriggeredFrom={log.workflow_run?.triggered_from as WorkflowRunTriggeredFrom}triggerMetadata={@@ -287,7 +283,7 @@ const WorkflowAppLogList: FC<ILogs> = ({ logs, appDetail, onRefresh }) => {</tbody></table><DrawerPortal>- <DrawerBackdrop className={cn(!isMobile && 'bg-transparent')} />+ <DrawerBackdrop className="sm:bg-transparent" /><DrawerViewport><DrawerPopup className="p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-150 data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border data-[swipe-direction=right]:border-components-panel-border"><DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">diff --git a/web/app/components/base/chat/chat-with-history/__tests__/sidebar-focus.browser.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/sidebar-focus.browser.spec.tsxindex 5059dbb28cf..522444fcd96 100644--- a/web/app/components/base/chat/chat-with-history/__tests__/sidebar-focus.browser.spec.tsx+++ b/web/app/components/base/chat/chat-with-history/__tests__/sidebar-focus.browser.spec.tsx@@ -5,9 +5,8 @@ import { render } from 'vitest-browser-react'import { consoleQueryKey } from '@/test/console/operation-hooks'import ChatWithHistory from '../index'-vi.mock('@/hooks/use-breakpoints', () => ({- default: () => 'pc',- MediaType: { mobile: 'mobile', tablet: 'tablet', pc: 'pc' },+vi.mock('@langgenius/dify-ui/use-media-query', () => ({+ useMediaQuery: () => false,}))vi.mock('@/next/navigation', () => ({useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),diff --git a/web/app/components/base/chat/chat-with-history/index.tsx b/web/app/components/base/chat/chat-with-history/index.tsxindex 5792277d2fe..b19ed3a427a 100644--- a/web/app/components/base/chat/chat-with-history/index.tsx+++ b/web/app/components/base/chat/chat-with-history/index.tsx@@ -3,9 +3,9 @@ import type { InstalledAppResponse } from '@dify/contracts/api/console/installedimport type { FC } from 'react'import type { ChatProps } from '../chat'import { cn } from '@langgenius/dify-ui/cn'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useEffect, useLayoutEffect, useRef, useState } from 'react'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useDocumentTitle from '@/hooks/use-document-title'import { createTheme } from '../embedded-chatbot/theme/theme'import ChatWrapper from './chat-wrapper'@@ -57,7 +57,7 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {<divinert={isSidebarCollapsed}className={cn(- 'flex w-59 flex-col p-1 pr-0 transition-all duration-200 ease-in-out',+ 'flex w-59 flex-col p-1 pe-0 transition-all duration-200 ease-in-out',isSidebarCollapsed && 'w-0 overflow-hidden p-0!',)}>@@ -70,7 +70,7 @@ const ChatWithHistory: FC<ChatWithHistoryProps> = ({ className }) => {<divclassName={cn('absolute top-0 z-20 flex h-full w-[256px] flex-col p-2 transition-all duration-500 ease-in-out',- showSidePanel ? 'left-0' : '-left-62',+ showSidePanel ? 'inset-s-0' : '-inset-s-62',)}onMouseEnter={() => {sidePanelHoveredRef.current = true@@ -130,8 +130,7 @@ const ChatWithHistoryWrap: FC<ChatWithHistoryWrapProps> = ({isNewAgent = false,renderAgentContent,}) => {- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isMobile = useMediaQuery('(width < 40rem)', {})const {appData,diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsxindex dae0f0f0830..833d1ecb8b0 100644--- a/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/index.spec.tsx@@ -2,9 +2,9 @@ import type { ReactElement, RefObject } from 'react'import type { ChatConfig } from '../../types'import type { Theme } from '../theme/theme'import type { AppData, AppMeta, ConversationItem } from '@/models/share'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { screen } from '@testing-library/react'import { vi } from 'vite-plus/test'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { renderWithConsoleQuery } from '@/test/console/query-data'import { useEmbeddedChatbot } from '../hooks'import EmbeddedChatbot from '../index'@@ -21,13 +21,8 @@ vi.mock('../hooks', () => ({useEmbeddedChatbot: vi.fn(),}))-vi.mock('@/hooks/use-breakpoints', () => ({- default: vi.fn(),- MediaType: {- mobile: 'mobile',- tablet: 'tablet',- pc: 'pc',- },+vi.mock('@langgenius/dify-ui/use-media-query', () => ({+ useMediaQuery: vi.fn(),}))vi.mock('../chat-wrapper', () => ({@@ -121,7 +116,7 @@ describe('EmbeddedChatbot index', () => {beforeEach(() => {vi.clearAllMocks()mockBrandingWorkspaceLogo = ''- vi.mocked(useBreakpoints).mockReturnValue(MediaType.mobile)+ vi.mocked(useMediaQuery).mockReturnValue(true)vi.mocked(useEmbeddedChatbot).mockReturnValue(createHookReturn())})@@ -259,7 +254,7 @@ describe('EmbeddedChatbot index', () => {})it('should not show powered by section on desktop', () => {- vi.mocked(useBreakpoints).mockReturnValue(MediaType.pc)+ vi.mocked(useMediaQuery).mockReturnValue(false)vi.mocked(useEmbeddedChatbot).mockReturnValue(createHookReturn({ appData: null }))render(<EmbeddedChatbot />)diff --git a/web/app/components/base/chat/embedded-chatbot/index.tsx b/web/app/components/base/chat/embedded-chatbot/index.tsxindex cbb13e1a6c6..3d0453dece0 100644--- a/web/app/components/base/chat/embedded-chatbot/index.tsx+++ b/web/app/components/base/chat/embedded-chatbot/index.tsx@@ -1,6 +1,7 @@'use client'import type { AppData } from '@/models/share'import { cn } from '@langgenius/dify-ui/cn'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useSuspenseQuery } from '@tanstack/react-query'import { useTranslation } from 'react-i18next'import ChatWrapper from '@/app/components/base/chat/embedded-chatbot/chat-wrapper'@@ -9,7 +10,6 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { DifyLogo } from '@/app/components/base/logo/dify-logo'import LogoHeader from '@/app/components/base/logo/logo-embedded-chat-header'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useDocumentTitle from '@/hooks/use-document-title'import { AppSourceType } from '@/service/share'import { EmbeddedChatbotContext, useEmbeddedChatbotContext } from './context'@@ -68,7 +68,7 @@ const Chatbot = () => {</div>{/* powered by */}{isMobile && (- <div className="flex h-15 shrink-0 items-center pl-2">+ <div className="flex h-15 shrink-0 items-center ps-2">{!appData?.custom_config?.remove_webapp_brand && (<div className={cn('flex shrink-0 items-center gap-1.5 px-2')}><div className="system-2xs-medium-uppercase text-text-tertiary">@@ -98,8 +98,7 @@ const Chatbot = () => {}const EmbeddedChatbotWrapper = () => {- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isMobile = useMediaQuery('(width < 40rem)', {})const {appData,diff --git a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsxindex 6f41aed1718..bc99b5ba7de 100644--- a/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/step-two/__tests__/index.spec.tsx@@ -23,6 +23,7 @@ import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/consoleimport { createDeferred } from '@/test/deferred'import { createDatasetFixture } from '@/test/fixtures/dataset'import { createNuqsTestRenderer } from '@/test/nuqs-testing'+import { resetViewportWidth, setViewportWidth } from '@/test/viewport'import StepTwo from '../index'const api = vi.hoisted(() => ({@@ -169,7 +170,7 @@ beforeEach(() => {})afterEach(() => {act(() => toast.dismiss())- vi.unstubAllGlobals()+ resetViewportWidth()})it('keeps the chunk mode and preview while editing its delimiter with an arrow key', async () => {@@ -188,7 +189,7 @@ it('keeps the chunk mode and preview while editing its delimiter with an arrow k})it('opens the mobile preview with fetched chunks and restores its trigger after closing', async () => {- vi.stubGlobal('innerWidth', 480)+ setViewportWidth(480)const { user } = await setup()expect(screen.queryByRole('dialog')).not.toBeInTheDocument()const trigger = screen.getByRole('button', { name: 'datasetCreation.stepTwo.previewChunk' })diff --git a/web/app/components/datasets/create/step-two/index.tsx b/web/app/components/datasets/create/step-two/index.tsxindex 5949dd88fcd..708d12a775c 100644--- a/web/app/components/datasets/create/step-two/index.tsx+++ b/web/app/components/datasets/create/step-two/index.tsx@@ -2,9 +2,9 @@import type { FC, MouseEvent } from 'react'import type { StepTwoProps } from './types'-import { cn } from '@langgenius/dify-ui/cn'import { RadioGroup } from '@langgenius/dify-ui/radio-group'import { Separator } from '@langgenius/dify-ui/separator'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useMutation } from '@tanstack/react-query'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -17,7 +17,6 @@ import {} from '@/app/components/datasets/dataset-fields'import { toast } from '@/app/notifications'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { LanguagesSupported } from '@/i18n/language'import { DataSourceProvider } from '@/models/common'import { ChunkingMode, ProcessMode } from '@/models/datasets'@@ -69,7 +68,7 @@ const StepTwo: FC<StepTwoProps> = ({const { t } = useTranslation(['datasetCreation'])const locale = useLocale()- const isMobile = useBreakpoints() === MediaType.mobile+ const isBelowSm = useMediaQuery('(width < 40rem)', {})const [isPreviewOpen, setIsPreviewOpen] = useState(false)const previewTriggerRef = useRef<HTMLButtonElement | null>(null)const currentDataset = useDatasetDetailContextWithSelector((s) => s.dataset)@@ -301,13 +300,8 @@ const StepTwo: FC<StepTwoProps> = ({isInInitreturn (- <div className={cn('flex size-full min-w-0', isMobile && 'flex-col overflow-y-auto')}>- <div- className={cn(- '@container/chunkfields relative min-w-0 py-6',- isMobile ? 'w-full shrink-0 px-4' : 'h-full w-1/2 overflow-y-auto px-12',- )}- >+ <div className="flex size-full min-w-0 max-sm:flex-col max-sm:overflow-y-auto">+ <div className="@container/chunkfields relative min-w-0 py-6 max-sm:w-full max-sm:shrink-0 max-sm:px-4 sm:h-full sm:w-1/2 sm:overflow-y-auto sm:px-12"><h1 className="mb-1 system-md-semibold text-text-secondary">{t(($) => $['stepTwo.segmentation'], { ns: 'datasetCreation' })}</h1>@@ -392,7 +386,7 @@ const StepTwo: FC<StepTwoProps> = ({/></div><PreviewPanel- isMobile={isMobile}+ isMobile={isBelowSm}isOpen={isPreviewOpen}onClose={() => setIsPreviewOpen(false)}finalFocus={previewTriggerRef}diff --git a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsxindex 7e1d8b13747..5287d5eaca7 100644--- a/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/__tests__/index.spec.tsx@@ -20,6 +20,7 @@ import { consoleQuery } from '@/service/console'import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'import { createDatasetFixture } from '@/test/fixtures/dataset'import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'+import { resetViewportWidth, setViewportWidth } from '@/test/viewport'import { DatasetACLPermission } from '@/utils/permission'import DocumentDetail from '../index'const expectDocumentListInvalidated = (queryClient: QueryClient) =>@@ -300,7 +301,7 @@ describe('DocumentDetail', () => {it('opens metadata in a drawer on mobile instead of beside the chunks', async () => {const user = userEvent.setup()- vi.stubGlobal('innerWidth', 390)+ setViewportWidth(390)try {render(<DocumentDetail datasetId="ds-1" documentId="doc-1" />)expect(@@ -314,7 +315,27 @@ describe('DocumentDetail', () => {),).toBeVisible()} finally {- vi.unstubAllGlobals()+ resetViewportWidth()+ }+ })++ it('does not open the mobile drawer when an open inline panel crosses the breakpoint', () => {+ try {+ render(<DocumentDetail datasetId="ds-1" documentId="doc-1" />)+ const toggle = screen.getByRole('button', { name: /metadata\.title/ })+ expect(toggle).toHaveAttribute('aria-expanded', 'true')++ act(() => setViewportWidth(390))+ expect(toggle).toHaveAttribute('aria-expanded', 'false')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()++ act(() => resetViewportWidth())+ expect(toggle).toHaveAttribute('aria-expanded', 'true')+ expect(+ screen.getByText('dataset.metadata.documentMetadata.documentInformation'),+ ).toBeInTheDocument()+ } finally {+ resetViewportWidth()}})diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsxindex ec2a7c3de0c..506d5b88f9e 100644--- a/web/app/components/datasets/documents/detail/index.tsx+++ b/web/app/components/datasets/documents/detail/index.tsx@@ -24,6 +24,7 @@ import {ScrollAreaViewport,} from '@langgenius/dify-ui/scroll-area'import { Separator } from '@langgenius/dify-ui/separator'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'import * as React from 'react'@@ -36,7 +37,6 @@ import { toast } from '@/app/notifications'import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import useDocumentTitle from '@/hooks/use-document-title'import { ChunkingMode, DisplayStatusList, isDocumentDisplayStatus } from '@/models/datasets'import { useRouter, useSearchParams } from '@/next/navigation'@@ -72,8 +72,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {const searchParams = useSearchParams()const { t } = useTranslation(['common', 'datasetDocuments', 'navigation'])- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isBelowSm = useMediaQuery('(width < 40rem)', {})const dataset = useDatasetDetailContextWithSelector((s) => s.dataset)const { data: currentUserId } = useSuspenseQuery({@@ -92,7 +91,10 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {[dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys],)const canEditDocument = datasetACLCapabilities.canEdit- const [showMetadata, setShowMetadata] = useState(!isMobile)+ const [isMetadataPanelOpen, setIsMetadataPanelOpen] = useState(true)+ const [isMetadataDrawerOpen, setIsMetadataDrawerOpen] = useState(false)+ const showMetadata = isBelowSm ? isMetadataDrawerOpen : isMetadataPanelOpen+ const setShowMetadata = isBelowSm ? setIsMetadataDrawerOpen : setIsMetadataPanelOpenconst [newSegmentModalVisible, setNewSegmentModalVisible] = useState(false)const [batchModalVisible, setBatchModalVisible] = useState(false)const [importStatus, setImportStatus] = useState<SegmentImportStatus>()@@ -307,7 +309,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {const metadataPanel = docDetail && (<Metadata- className={cn(isMobile && 'mt-3 mr-2')}+ className={cn(isBelowSm && 'me-2 mt-3')}datasetId={datasetId}documentId={documentId}docDetail={docDetail}@@ -326,7 +328,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {// oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector contexts are not React 19 context components.<DocumentContext.Provider value={contextValue}><div className="flex h-full flex-col bg-background-default">- <div className="flex min-h-16 flex-wrap items-center justify-between border-b border-b-divider-subtle py-2.5 pr-4 pl-3">+ <div className="flex min-h-16 flex-wrap items-center justify-between border-b border-b-divider-subtle py-2.5 ps-3 pe-4"><buttontype="button"aria-label={backButtonLabel}@@ -393,7 +395,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {aria-label={metadataToggleLabel}aria-expanded={showMetadata}title={metadataToggleLabel}- className="ml-2"+ className="ms-2"onClick={() => setShowMetadata(!showMetadata)}>{showMetadata ? (@@ -418,7 +420,7 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {className={cn('flex h-full min-w-0 grow flex-col',!embedding && isFullDocMode && 'relative px-11 pt-4',- !embedding && !isFullDocMode && 'relative pt-3 pr-11 pl-5',+ !embedding && !isFullDocMode && 'relative ps-5 pe-11 pt-3',)}>{embedding ? (@@ -442,11 +444,11 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {showCloseisOpen={showMetadata}onClose={() => setShowMetadata(false)}- isMobile={isMobile}+ isMobile={isBelowSm}panelClassName="justify-start!">{metadataPanel &&- (isMobile ? (+ (isBelowSm ? (metadataPanel) : (<ScrollArea className="relative mt-3 min-h-0 shrink-0 overflow-hidden">diff --git a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsxindex 47050f073b5..06e8b99338f 100644--- a/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx+++ b/web/app/components/datasets/hit-testing/__tests__/index.spec.tsx@@ -14,6 +14,7 @@ import { createDeferred } from '@/test/deferred'import { createDatasetFixture } from '@/test/fixtures/dataset'import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'import { createHitTestingRecordFixture } from '@/test/fixtures/hit-testing'+import { resetViewportWidth, setViewportWidth } from '@/test/viewport'import { RETRIEVE_METHOD } from '@/types/app'import HitTestingPage from '../index'@@ -131,9 +132,8 @@ describe('HitTestingPage', () => {getRecords.mockReset().mockImplementation(async () => recordsData!)mockHitTestingMutateAsync.mockReset()mockExternalHitTestingMutateAsync.mockReset()- vi.stubGlobal('innerWidth', 1024)})- afterEach(() => vi.unstubAllGlobals())+ afterEach(() => resetViewportWidth())it('disables record loading and query input without retrieval recall permission', async () => {mockDataset.permission_keys = []@@ -185,7 +185,7 @@ describe('HitTestingPage', () => {it('removes stale mobile result counts while pending or failed and restores the latest successful count', async () => {const user = userEvent.setup()- vi.stubGlobal('innerWidth', 390)+ setViewportWidth(390)const response: HitTestingResponse = {query: { content: 'Test query' },records: [createMockHitTesting()],@@ -213,6 +213,21 @@ describe('HitTestingPage', () => {expect(await screen.findByRole('dialog', { name: '0 Retrieved Chunks' })).toBeInTheDocument()})+ it('does not open the results drawer when a wide-screen query is followed by a narrow window', async () => {+ const user = userEvent.setup()+ mockHitTestingMutateAsync.mockResolvedValueOnce({+ query: { content: 'Test query' },+ records: [createMockHitTesting()],+ })+ renderWithProviders(<HitTestingPage datasetId="dataset-1" />)+ await user.type(screen.getByRole('textbox'), 'Test query')+ await user.click(screen.getByRole('button', { name: /input.testing/ }))+ await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('1 Retrieved Chunks'))++ act(() => setViewportWidth(390))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })+it('announces zero retrieved chunks after an empty response', async () => {const user = userEvent.setup()const response: HitTestingResponse = {diff --git a/web/app/components/datasets/hit-testing/index.tsx b/web/app/components/datasets/hit-testing/index.tsxindex d8187009764..fff85e2ee9a 100644--- a/web/app/components/datasets/hit-testing/index.tsx+++ b/web/app/components/datasets/hit-testing/index.tsx@@ -21,11 +21,12 @@ import {DrawerViewport,} from '@langgenius/dify-ui/drawer'import { Pagination } from '@langgenius/dify-ui/pagination'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { keepPreviousData, useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import { useAtomValue } from 'jotai'import * as React from 'react'-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useContext } from 'use-context-selector'import FloatRightContainer from '@/app/components/base/float-right-container'@@ -35,7 +36,6 @@ import docStyle from '@/app/components/datasets/documents/detail/completed/styleimport DatasetDetailContext from '@/context/dataset-detail'import { workspacePermissionKeysAtom } from '@/context/permission-state'import { userProfileQueryOptions } from '@/features/account-profile/client'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { consoleClient, consoleQuery } from '@/service/console'import { getDatasetACLCapabilities } from '@/utils/permission'import { CardSkelton } from '../documents/detail/completed/skeleton/general-list-skeleton'@@ -55,8 +55,7 @@ type Props = Readonly<{const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {const { t } = useTranslation(['common', 'datasetHitTesting'])- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isBelowSm = useMediaQuery('(width < 40rem)', {})const [hitResult, setHitResult] = useState<HitTestingResponse | undefined>()const [externalHitResult, setExternalHitResult] = useState<@@ -98,10 +97,8 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {() => currentDataset && toRetrievalConfig(currentDataset.retrieval_model_dict),)const [isShowModifyRetrievalModal, setIsShowModifyRetrievalModal] = useState(false)- const [- isShowRightPanel,- { setTrue: showRightPanel, setFalse: hideRightPanel, set: setShowRightPanel },- ] = useBoolean(!isMobile)+ const [isResultDrawerOpen, { setTrue: openResultDrawer, setFalse: closeResultDrawer }] =+ useBoolean(false)const {mutate: hitTestingMutation,@@ -185,10 +182,6 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {setQueryInputKey(Date.now())}, [])- useEffect(() => {- setShowRightPanel(!isMobile)- }, [isMobile, setShowRightPanel])-if (!canRunRetrievalRecall) return <LoadingPlaceholder className="h-full" />return (@@ -210,7 +203,9 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {key={queryInputKey}setHitResult={setHitResult}setExternalHitResult={setExternalHitResult}- onSubmit={showRightPanel}+ onSubmit={() => {+ if (isBelowSm) openResultDrawer()+ }}onUpdateList={recordsRefetch}loading={isRetrievalLoading}queries={queries}@@ -256,9 +251,9 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {<FloatRightContainerpanelClassName="justify-start! overflow-y-auto!"showClose- isMobile={isMobile}- isOpen={isShowRightPanel}- onClose={hideRightPanel}+ isMobile={isBelowSm}+ isOpen={!isBelowSm || isResultDrawerOpen}+ onClose={closeResultDrawer}title={panelTitle}><div className="flex min-w-0 flex-1 flex-col pt-3">@@ -291,7 +286,7 @@ const HitTestingPage: FC<Props> = ({ datasetId }: Props) => {}}><DrawerPortal>- <DrawerBackdrop className={cn(!isMobile && 'bg-transparent')} />+ <DrawerBackdrop className="sm:bg-transparent" /><DrawerViewport><DrawerPopup className="p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-160 data-[swipe-direction=right]:rounded-xl"><DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">diff --git a/web/app/components/explore/try-app/app/chat.tsx b/web/app/components/explore/try-app/app/chat.tsxindex 728ce535c58..c3f3b23782e 100644--- a/web/app/components/explore/try-app/app/chat.tsx+++ b/web/app/components/explore/try-app/app/chat.tsx@@ -6,6 +6,7 @@ import { Alert, AlertClose, AlertTitle } from '@langgenius/dify-ui/alert'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { RiResetLeftLine } from '@remixicon/react'import { useBoolean } from 'ahooks'import * as React from 'react'@@ -17,7 +18,6 @@ import { EmbeddedChatbotContext } from '@/app/components/base/chat/embedded-chatimport { useEmbeddedChatbot } from '@/app/components/base/chat/embedded-chatbot/hooks'import ViewFormDropdown from '@/app/components/base/chat/embedded-chatbot/inputs-form/view-form-dropdown'import { createTheme } from '@/app/components/base/chat/embedded-chatbot/theme/theme'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { AppSourceType } from '@/service/share'type Props = Readonly<{@@ -28,8 +28,7 @@ type Props = Readonly<{const TryApp: FC<Props> = ({ appId, appDetail, className }) => {const { t } = useTranslation(['explore', 'share', 'common'])- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isMobile = useMediaQuery('(width < 40rem)', {})const { removeConversationIdInfo, ...chatData } = useEmbeddedChatbot(AppSourceType.tryApp, appId)const theme = createTheme(chatData.appData?.site?.chat_color_theme ?? null,diff --git a/web/app/components/explore/try-app/app/text-generation.tsx b/web/app/components/explore/try-app/app/text-generation.tsxindex 78a3bf0456f..4c4dec9f80e 100644--- a/web/app/components/explore/try-app/app/text-generation.tsx+++ b/web/app/components/explore/try-app/app/text-generation.tsx@@ -6,6 +6,7 @@ import type { AppData, CustomConfigValueType, SiteInfo } from '@/models/share'import type { VisionFile, VisionSettings } from '@/types/app'import { Alert, AlertClose, AlertTitle } from '@langgenius/dify-ui/alert'import { cn } from '@langgenius/dify-ui/cn'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { RiArrowDownSLine, RiArrowUpSLine } from '@remixicon/react'import { useBoolean } from 'ahooks'import { noop } from 'es-toolkit/function'@@ -18,7 +19,6 @@ import Res from '@/app/components/share/text-generation/result'import { TaskStatus } from '@/app/components/share/text-generation/types'import { appDefaultIconBackground } from '@/config'import { useWebAppStore } from '@/context/web-app-context'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { AppSourceType } from '@/service/share'import { useGetTryAppParams } from '@/service/use-try-app'import { Resolution, TransferMethod } from '@/types/app'@@ -39,8 +39,7 @@ const TextGeneration: FC<Props> = ({ appId, className, isWorkflow, appData }) =>const handleDescRef = useCallback((node: HTMLDivElement | null) => {setShowDescToggle(!!node && node.scrollHeight > node.clientHeight)}, [])- const media = useBreakpoints()- const isPC = media === MediaType.pc+ const isPC = !useMediaQuery('(width < 48rem)', {})const [inputs, doSetInputs] = useState<Record<string, InputValueTypes>>({})const inputsRef = useRef<Record<string, InputValueTypes>>(inputs)@@ -156,7 +155,7 @@ const TextGeneration: FC<Props> = ({ appId, className, isWorkflow, appData }) =>)const renderResWrap = (- <div className={cn('relative flex h-full flex-col', 'rounded-r-2xl bg-chatbot-bg')}>+ <div className={cn('relative flex h-full flex-col', 'rounded-e-2xl bg-chatbot-bg')}><div className={cn('flex h-0 grow flex-col overflow-y-auto p-6')}>{isCompleted && !isHideTryNotice && (<Alert type="info" className="mb-3 shrink-0">@@ -195,7 +194,7 @@ const TextGeneration: FC<Props> = ({ appId, className, isWorkflow, appData }) =>className={cn('relative flex h-full shrink-0 flex-col',isPC && 'w-150 max-w-[50%]',- 'rounded-l-2xl bg-components-panel-bg',+ 'rounded-s-2xl bg-components-panel-bg',)}>{/* Header */}@@ -278,7 +277,7 @@ const TextGeneration: FC<Props> = ({ appId, className, isWorkflow, appData }) =>className={cn(isShowResultPanel? 'flex items-center justify-center p-2 pt-6'- : 'absolute top-0 left-0 z-10 flex w-full items-center justify-center px-2 pt-0.75 pb-14.25',+ : 'absolute inset-s-0 top-0 z-10 flex w-full items-center justify-center px-2 pt-0.75 pb-14.25',)}onClick={() => {if (isShowResultPanel) hideResultPanel()diff --git a/web/app/components/explore/try-app/preview/basic-app-preview.tsx b/web/app/components/explore/try-app/preview/basic-app-preview.tsxindex f1ad3320e10..270cd0abaab 100644--- a/web/app/components/explore/try-app/preview/basic-app-preview.tsx+++ b/web/app/components/explore/try-app/preview/basic-app-preview.tsx@@ -6,6 +6,7 @@ import type { FormValue } from '@/app/components/header/account-setting/model-primport type { Collection } from '@/app/components/tools/types'import type { ModelConfig } from '@/models/debug'import type { PromptVariable } from '@/types/app'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useQuery } from '@tanstack/react-query'import { noop } from 'es-toolkit/function'import { clone } from 'es-toolkit/object'@@ -27,7 +28,6 @@ import {DEFAULT_COMPLETION_PROMPT_CONFIG,} from '@/config'import ConfigContext from '@/context/debug-configuration'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { PromptMode } from '@/models/debug'import { consoleQuery } from '@/service/console'import { useGetTryAppDataSets } from '@/service/use-try-app'@@ -330,8 +330,7 @@ const normalizeAgentTool = (}const BasicAppPreview: FC<Props> = ({ appId, appDetail }) => {- const media = useBreakpoints()- const isMobile = media === MediaType.mobile+ const isMobile = useMediaQuery('(width < 40rem)', {})const { data: collectionListFromServer, isLoading: isLoadingToolProviders } = useQuery(consoleQuery.workspaces.current.toolProviders.get.queryOptions({@@ -622,7 +621,7 @@ const BasicAppPreview: FC<Props> = ({ appId, appDetail }) => {className="relative flex h-full w-1/2 grow flex-col overflow-y-auto"style={{ borderColor: 'rgba(0, 0, 0, 0.02)' }}>- <div className="flex grow flex-col rounded-tl-2xl border-t-[0.5px] border-l-[0.5px] border-components-panel-border bg-chatbot-bg">+ <div className="flex grow flex-col rounded-ss-2xl border-s-[0.5px] border-t-[0.5px] border-components-panel-border bg-chatbot-bg"><DebugisPreviewonSetting={noop}diff --git a/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx b/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsxindex 42ca00e53c8..bd8c7fe8e85 100644--- a/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/index.hitl-v2.spec.tsx@@ -4,7 +4,6 @@ import type { ConsoleStateFixture } from '@/test/console/state-fixture'import { act, fireEvent, screen, waitFor } from '@testing-library/react'import { NuqsTestingAdapter } from 'nuqs/adapters/testing'import { useState } from 'react'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { consoleQuery } from '@/service/console'import {createConsoleQueryClient,@@ -61,15 +60,6 @@ vi.mock('@/features/contacts/im-platform/account-setting-page', () => ({ContactsImPlatformAccountSettingPage: () => <div data-testid="contacts-im-platform-page" />,}))-vi.mock('@/hooks/use-breakpoints', () => ({- MediaType: {- mobile: 'mobile',- tablet: 'tablet',- pc: 'pc',- },- default: vi.fn(),-}))-vi.mock('next-themes', () => ({useTheme: vi.fn(() => ({theme: 'system',@@ -275,7 +265,6 @@ describe('AccountSetting', () => {mockConfig.getFeatures.mockImplementation(() => new Promise(() => {}))canReplaceLogo = truemockConsoleState.current = baseConsoleState- vi.mocked(useBreakpoints).mockReturnValue(MediaType.pc)})describe('Rendering', () => {diff --git a/web/app/components/header/account-setting/__tests__/settings-loading.spec.tsx b/web/app/components/header/account-setting/__tests__/settings-loading.spec.tsxindex a584bc5961e..692d28c69e9 100644--- a/web/app/components/header/account-setting/__tests__/settings-loading.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/settings-loading.spec.tsx@@ -58,10 +58,6 @@ vi.mock('@/service/console', async (importOriginal) => {}),}})-vi.mock('@/hooks/use-breakpoints', () => ({- MediaType: { mobile: 'mobile', tablet: 'tablet', pc: 'pc' },- default: () => 'pc',-}))vi.mock('@/app/components/billing/billing-page', () => ({ default: () => null }))vi.mock('@/app/components/custom/custom-page', () => ({ default: () => null }))vi.mock('../access-rules-page', () => ({ default: () => null }))diff --git a/web/app/components/integrations/index.tsx b/web/app/components/integrations/index.tsxindex 8483e1894ad..05d5fc73250 100644--- a/web/app/components/integrations/index.tsx+++ b/web/app/components/integrations/index.tsx@@ -19,7 +19,8 @@ import {DrawerViewport,} from '@langgenius/dify-ui/drawer'import { IconButton } from '@langgenius/dify-ui/icon-button'-import { Suspense, useId, useRef, useState, useSyncExternalStore } from 'react'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'+import { Suspense, useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { UpdateSettingDialog } from '@/app/components/header/account-setting/update-setting-dialog'import {@@ -70,15 +71,6 @@ const headerDescriptionDocPaths = {'agent-strategy': '/develop-plugin/dev-guides-and-walkthroughs/agent-strategy-plugin',} satisfies Partial<Record<IntegrationSection, DocPathWithoutLang>>-const compactNavigationQuery = '(width < 48rem)'-const subscribeToCompactNavigation = (onChange: () => void) => {- const mediaQuery = window.matchMedia(compactNavigationQuery)- mediaQuery.addEventListener('change', onChange)- return () => mediaQuery.removeEventListener('change', onChange)-}-const getCompactNavigationSnapshot = () => window.matchMedia(compactNavigationQuery).matches-const getServerCompactNavigationSnapshot = () => false-type DescriptionWithLearnMoreProps = {children: ReactNodehref: string@@ -141,11 +133,7 @@ export default function IntegrationsPage({}: IntegrationsPageProps) {const { t } = useTranslation(['navigation', 'modelProvider', 'common'])const navigationTitleId = useId()- const isCompact = useSyncExternalStore(- subscribeToCompactNavigation,- getCompactNavigationSnapshot,- getServerCompactNavigationSnapshot,- )+ const isCompact = useMediaQuery('(width < 48rem)', {})const docLink = useDocLink()const router = useRouter()const section = useIntegrationSection(routeSection)diff --git a/web/app/components/share/text-generation/index.tsx b/web/app/components/share/text-generation/index.tsxindex 0169ef66250..82821a2e973 100644--- a/web/app/components/share/text-generation/index.tsx+++ b/web/app/components/share/text-generation/index.tsx@@ -4,12 +4,12 @@ import type { FC } from 'react'import type { InputValueTypes, TextGenerationRunControl } from './types'import type { VisionFile } from '@/types/app'import { cn } from '@langgenius/dify-ui/cn'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { useBoolean } from 'ahooks'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { toast } from '@/app/notifications'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { useSearchParams } from '@/next/navigation'import { useTextGenerationAppState } from './hooks/use-text-generation-app-state'import { useTextGenerationBatch } from './hooks/use-text-generation-batch'@@ -22,8 +22,7 @@ type IMainProps = {}const TextGeneration: FC<IMainProps> = ({ isInstalledApp = false, isWorkflow = false }) => {const { t } = useTranslation(['share', 'appDebug', 'common', 'workflow'])- const media = useBreakpoints()- const isPC = media === MediaType.pc+ const isPC = !useMediaQuery('(width < 48rem)', {})const searchParams = useSearchParams()const mode = searchParams.get('mode') || 'create'const [currentTab, setCurrentTab] = useState<string>(diff --git a/web/app/components/share/text-generation/run-batch/index.tsx b/web/app/components/share/text-generation/run-batch/index.tsxindex e302bef5eab..d1caf54cdb5 100644--- a/web/app/components/share/text-generation/run-batch/index.tsx+++ b/web/app/components/share/text-generation/run-batch/index.tsx@@ -5,7 +5,6 @@ import { cn } from '@langgenius/dify-ui/cn'import { RiLoader2Line, RiPlayLargeLine } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import CSVDownload from './csv-download'import CSVReader from './csv-reader'@@ -17,8 +16,6 @@ type IRunBatchProps = {const RunBatch: FC<IRunBatchProps> = ({ vars, onSend, isAllFinished }) => {const { t } = useTranslation(['share'])- const media = useBreakpoints()- const isPC = media === MediaType.pcconst [csvData, setCsvData] = React.useState<string[][]>([])const [isParsed, setIsParsed] = React.useState(false)@@ -39,7 +36,7 @@ const RunBatch: FC<IRunBatchProps> = ({ vars, onSend, isAllFinished }) => {<div className="flex justify-end"><Buttonvariant="primary"- className={cn('mt-4 pr-4 pl-3', !isPC && 'grow')}+ className="mt-4 ps-3 pe-4 max-md:grow"onClick={handleSend}disabled={!isParsed || !isAllFinished}>diff --git a/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx b/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsxindex 20617ba5c4f..0ebba9118da 100644--- a/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx+++ b/web/app/components/share/text-generation/run-once/__tests__/index.spec.tsx@@ -27,19 +27,6 @@ const createFileEntity = (overrides: Partial<FileEntity> = {}): FileEntity => ({...overrides,})-vi.mock('@/hooks/use-breakpoints', () => {- const MediaType = {- pc: 'pc',- pad: 'pad',- mobile: 'mobile',- }- const mockUseBreakpoints = vi.fn(() => MediaType.pc)- return {- default: mockUseBreakpoints,- MediaType,- }-})-const upload = vi.hoisted(() => vi.fn<typeof fileUpload>())vi.mock('@/next/navigation', () => ({useParams: () => ({}),diff --git a/web/app/components/share/text-generation/run-once/index.tsx b/web/app/components/share/text-generation/run-once/index.tsxindex eeeef8d7236..06f56989209 100644--- a/web/app/components/share/text-generation/run-once/index.tsx+++ b/web/app/components/share/text-generation/run-once/index.tsx@@ -6,7 +6,6 @@ import type { PromptConfig } from '@/models/debug'import type { SiteInfo } from '@/models/share'import type { VisionFile, VisionSettings } from '@/types/app'import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'import { Input } from '@langgenius/dify-ui/input'import {Select,@@ -27,7 +26,6 @@ import TextGenerationImageUploader from '@/app/components/base/image-uploader/teimport BoolInput from '@/app/components/workflow/nodes/_base/components/before-run-form/bool-input'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'type IRunOnceProps = {siteInfo: SiteInfo@@ -56,8 +54,6 @@ const RunOnce: FC<IRunOnceProps> = ({}) => {const { t } = useTranslation(['common', 'share', 'workflow'])const baseId = useId()- const media = useBreakpoints()- const isPC = media === MediaType.pcconst [isInitialized, setIsInitialized] = useState(false)const fileUploadersRef = useRef(new Map<string, FileUploaderInAttachmentRef>())@@ -328,7 +324,7 @@ const RunOnce: FC<IRunOnceProps> = ({</span></Button><Button- className={cn(!isPC && 'grow')}+ className="max-md:grow"type={isRunning ? 'button' : 'submit'}variant={isRunning ? 'secondary' : 'primary'}disabled={isRunning && runControl?.isStopping}diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsxindex 3dec83a5560..fe2dbb3871c 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx@@ -21,7 +21,6 @@ import AppIcon from '@/app/components/base/app-icon'import Badge from '@/app/components/base/badge'import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import FeatureIcon from '@/app/components/header/account-setting/model-provider-page/model-selector/feature-icon'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { useKnowledge } from '@/hooks/use-knowledge'type Props = Readonly<{@@ -47,9 +46,7 @@ const DatasetItem: FC<Props> = ({settingsDrawerPopupClassName,settingsModalHeight,}) => {- const media = useBreakpoints()const { t } = useTranslation(['common', 'dataset'])- const isMobile = media === MediaType.mobileconst { formatIndexingTechniqueAndMethod } = useKnowledge()const [isDeleteHovered, setIsDeleteHovered] = useState(false)@@ -91,7 +88,7 @@ const DatasetItem: FC<Props> = ({<div className="w-0 grow truncate system-sm-medium text-text-secondary">{payload.name}</div></div>{!readonly && (- <div className="ml-2 hidden shrink-0 items-center space-x-1 group-hover/dataset-item:flex">+ <div className="ms-2 hidden shrink-0 items-center space-x-1 group-hover/dataset-item:flex">{editable && (<Drawer actionsRef={settingsDrawerActionsRef} modal swipeDirection="right"><DrawerTrigger@@ -111,7 +108,7 @@ const DatasetItem: FC<Props> = ({<DrawerBackdropforceRender={settingsDrawerBackdropForceRender}className={cn(- !settingsDrawerBackdropClassName && !isMobile && 'bg-transparent',+ !settingsDrawerBackdropClassName && 'sm:bg-transparent',settingsDrawerBackdropClassName,)}/>@@ -148,7 +145,7 @@ const DatasetItem: FC<Props> = ({</div>)}{payload.is_multimodal && (- <div className="mr-1 shrink-0 group-hover/dataset-item:hidden">+ <div className="me-1 shrink-0 group-hover/dataset-item:hidden"><FeatureIcon feature={ModelFeatureEnum.vision} /></div>)}diff --git a/web/docs/responsive-layout.md b/web/docs/responsive-layout.mdnew file mode 100644index 00000000000..f7820e8c926--- /dev/null+++ b/web/docs/responsive-layout.md@@ -0,0 +1,17 @@+# Responsive Layout++Viewport width tells how much space there is, not which device the user has. A desktop browser zoomed in is as narrow as a phone.++A responsive surface is one component tree at every width. CSS decides how it looks at each breakpoint. JavaScript reads width only for behaviour CSS cannot express, through `@langgenius/dify-ui/use-media-query`, at the same breakpoints as Tailwind.++## What Goes Wrong++- **A component tree per breakpoint.** Crossing the breakpoint, including by zooming, remounts the subtree and drops focus and local state.+- **The query copied into state**, by an Effect or as a `useState` initial value. State and screen disagree after the width changes, and a first mount during hydration only sees the wide default. See [component state] and [Effects].+- **JavaScript and CSS switching at different widths.** The surface passes through a state neither side designed.+- **Width used as a device check.** Flags named like `isMobile` invite assumptions about touch or hover that width cannot support; input differences follow the `hover` and `pointer` media features.++Some existing surfaces still switch component trees by width. They are not examples to follow.++[Effects]: ../../.agents/skills/how-to-write-component/references/runtime.md+[component state]: ../../.agents/skills/how-to-write-component/references/state.mddiff --git a/web/features/agent-v2/agent-detail/detail-sidebar.tsx b/web/features/agent-v2/agent-detail/detail-sidebar.tsxindex 2c172ea2b34..a9a76af438d 100644--- a/web/features/agent-v2/agent-detail/detail-sidebar.tsx+++ b/web/features/agent-v2/agent-detail/detail-sidebar.tsx@@ -1,15 +1,15 @@'use client'+import { useMediaQuery } from '@langgenius/dify-ui/use-media-query'import { DetailSidebarFrame } from '@/app/components/detail-sidebar'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { AgentDetailSection, AgentDetailTop } from './navigation'export function AgentDetailSidebar() {- const media = useBreakpoints()+ const isBelowDesktop = useMediaQuery('(width < 48rem)', {})return (<DetailSidebarFrame- compact={media !== MediaType.pc}+ compact={isBelowDesktop}renderTop={({ expand, onToggle }) => <AgentDetailTop expand={expand} onToggle={onToggle} />}renderSection={({ expand }) => <AgentDetailSection expand={expand} />}/>diff --git a/web/features/agent-v2/agent-detail/logs/page.tsx b/web/features/agent-v2/agent-detail/logs/page.tsxindex e13e047196f..10273127913 100644--- a/web/features/agent-v2/agent-detail/logs/page.tsx+++ b/web/features/agent-v2/agent-detail/logs/page.tsx@@ -29,7 +29,6 @@ import Chip from '@/app/components/base/chip'import { SearchInput } from '@/app/components/base/search-input'import { Sort } from '@/app/components/base/sort'import { useDocLink } from '@/context/i18n'-import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { consoleQuery } from '@/service/console'import { AgentDetailSectionSurface } from '../section-surface'import { AgentLogDetailPanel } from './components/log-detail-panel'@@ -70,8 +69,6 @@ export function AgentLogsPage({ agentId }: AgentLogsPageProps) {const { t } = useTranslation(['agentV2'])const { t: tCommon } = useTranslation(['common'])const docLink = useDocLink()- const media = useBreakpoints()- const isMobile = media === MediaType.mobileconst [period, setPeriod] = useState<PeriodKey>('last7days')const [source, setSource] = useState<SourceFilterValue>([])const [keyword, setKeyword] = useState('')@@ -189,7 +186,7 @@ export function AgentLogsPage({ agentId }: AgentLogsPageProps) {}}/>- <div className="ml-auto max-w-full">+ <div className="ms-auto max-w-full"><Sortvalue={sort}items={[@@ -235,7 +232,7 @@ export function AgentLogsPage({ agentId }: AgentLogsPageProps) {}}><DrawerPortal>- <DrawerBackdrop className={!isMobile ? 'bg-transparent' : undefined} />+ <DrawerBackdrop className="sm:bg-transparent" /><DrawerViewport><DrawerPopup className="p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-150 data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border data-[swipe-direction=right]:border-components-panel-border"><DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">diff --git a/web/hooks/use-breakpoints.spec.ts b/web/hooks/use-breakpoints.spec.tsdeleted file mode 100644index 9bd82bedb4f..00000000000--- a/web/hooks/use-breakpoints.spec.ts+++ /dev/null@@ -1,71 +0,0 @@-import { act, renderHook } from '@testing-library/react'-import { createElement } from 'react'-import { hydrateRoot } from 'react-dom/client'-import { renderToString } from 'react-dom/server'-import useBreakpoints, { MediaType } from './use-breakpoints'--describe('useBreakpoints', () => {- const originalInnerWidth = window.innerWidth-- const fireResize = (width: number) => {- window.innerWidth = width- act(() => {- window.dispatchEvent(new Event('resize'))- })- }-- afterEach(() => {- window.innerWidth = originalInnerWidth- })-- it('should hydrate server markup on mobile without rebuilding it', async () => {- const ResponsiveContent = () => {- const media = useBreakpoints()- return createElement(media === MediaType.mobile ? 'nav' : 'aside', null, media)- }- const container = document.createElement('div')- const onRecoverableError = vi.fn()-- // The server has no viewport. Its markup must also be the first client render.- vi.stubGlobal('innerWidth', undefined)- try {- container.innerHTML = renderToString(createElement(ResponsiveContent))- } finally {- vi.unstubAllGlobals()- }- window.innerWidth = 390-- const root = hydrateRoot(container, createElement(ResponsiveContent), { onRecoverableError })- try {- await act(async () => {})- expect(onRecoverableError).not.toHaveBeenCalled()- expect(container).toHaveTextContent(MediaType.mobile)-- fireResize(1024)- expect(container).toHaveTextContent(MediaType.pc)- } finally {- act(() => root.unmount())- }- })-- it('should update media type when window resizes', () => {- // Start with desktop- Object.defineProperty(window, 'innerWidth', {- writable: true,- configurable: true,- value: 1024,- })-- const { result } = renderHook(() => useBreakpoints())- expect(result.current).toBe(MediaType.pc)-- fireResize(768)- expect(result.current).toBe(MediaType.tablet)- fireResize(641)- expect(result.current).toBe(MediaType.tablet)- fireResize(640)- expect(result.current).toBe(MediaType.mobile)- fireResize(769)- expect(result.current).toBe(MediaType.pc)- })-})diff --git a/web/hooks/use-breakpoints.ts b/web/hooks/use-breakpoints.tsdeleted file mode 100644index db4c804e941..00000000000--- a/web/hooks/use-breakpoints.ts+++ /dev/null@@ -1,29 +0,0 @@-'use client'-import * as React from 'react'--export const MediaType = {- mobile: 'mobile',- tablet: 'tablet',- pc: 'pc',-} as const--type MediaTypeValue = (typeof MediaType)[keyof typeof MediaType]--const subscribe = (onStoreChange: () => void) => {- window.addEventListener('resize', onStoreChange)- return () => window.removeEventListener('resize', onStoreChange)-}--const getSnapshot = (): MediaTypeValue => {- if (window.innerWidth <= 640) return MediaType.mobile- if (window.innerWidth <= 768) return MediaType.tablet- return MediaType.pc-}--// Match the server's desktop fallback during hydration before reading the viewport.-const getServerSnapshot = (): MediaTypeValue => MediaType.pc--const useBreakpoints = (): MediaTypeValue =>- React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)--export default useBreakpointsdiff --git a/web/test/viewport.ts b/web/test/viewport.tsnew file mode 100644index 00000000000..42daa502510--- /dev/null+++ b/web/test/viewport.ts@@ -0,0 +1,7 @@+import type { Window } from 'happy-dom'++export const setViewportWidth = (width: number) => {+ ;(window as unknown as Window).happyDOM.setViewport({ width })+}++export const resetViewportWidth = () => setViewportWidth(1024)