chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,136 @@
import type {
GetExploreAppsLearnDifyResponse,
RecommendedAppResponse,
} from '@dify/contracts/api/console/explore/types.gen'
import { act, screen, waitFor } from '@testing-library/react'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import { consoleQuery } from '@/service/console'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import LearnDify from '../index'
import { LEARN_DIFY_HIDDEN_STORAGE_KEY } from '../storage'
const { request, locale } = vi.hoisted(() => ({
request: vi.fn(),
locale: { value: 'en-US' },
}))
vi.mock('@/service/base', () => ({ request }))
vi.mock('#i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('#i18n')>()),
useLocale: () => locale.value,
}))
const createApp = (name: string, position: number | null = 1): RecommendedAppResponse => ({
app_id: name,
app: { id: name, name, icon_url: null },
can_trial: false,
position,
})
beforeEach(() => {
vi.clearAllMocks()
localStorage.clear()
locale.value = 'en-US'
request.mockImplementation(async () =>
Response.json({ recommended_apps: [createApp('Learn Dify App')] }),
)
})
describe('Learn Dify catalog', () => {
it('does not fetch hidden content until the step tour forces it visible', async () => {
localStorage.setItem(LEARN_DIFY_HIDDEN_STORAGE_KEY, 'true')
const { rerender } = render(<LearnDify />, {
systemFeatures: { enable_learn_app: true },
})
expect(
screen.queryByRole('heading', { name: 'explore.learnDify.title' }),
).not.toBeInTheDocument()
expect(request).not.toHaveBeenCalled()
rerender(<LearnDify forceVisible stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.home} />)
const section = await screen.findByRole('region', { name: 'explore.learnDify.title' })
expect(section).toHaveAttribute('data-step-by-step-tour-target', STEP_BY_STEP_TOUR_TARGETS.home)
expect(screen.queryByRole('button', { name: 'explore.learnDify.hide' })).not.toBeInTheDocument()
expect(request).toHaveBeenCalledTimes(1)
})
it('does not fetch when the system feature is disabled, even if visibility is forced', () => {
render(<LearnDify forceVisible />, { systemFeatures: { enable_learn_app: false } })
expect(
screen.queryByRole('heading', { name: 'explore.learnDify.title' }),
).not.toBeInTheDocument()
expect(request).not.toHaveBeenCalled()
})
it('sorts before limiting visible items while retaining the raw response in the generated cache', async () => {
const response: GetExploreAppsLearnDifyResponse = {
recommended_apps: [
createApp('Last', 5),
createApp('Null position', null),
createApp('Zero position', 0),
createApp('First', -1),
],
}
request.mockImplementation(async () => Response.json(response))
const { queryClient } = render(<LearnDify dismissible={false} itemLimit={3} />, {
systemFeatures: { enable_learn_app: true },
})
await screen.findByRole('heading', { name: 'First' })
expect(
screen.getAllByRole('heading', { level: 3 }).map((heading) => heading.textContent),
).toEqual(['First', 'Null position', 'Zero position'])
expect(screen.queryByRole('heading', { name: 'Last' })).not.toBeInTheDocument()
const cached = queryClient.getQueryData(
consoleQuery.explore.apps.learnDify.get.queryOptions({
input: { query: { language: 'en-US' } },
}).queryKey,
)
expect(cached).toEqual(response)
})
it('keeps each requested locale in its own generated cache entry', async () => {
const requestedLocales: Array<string | null> = []
request.mockImplementation(async (url: string) => {
const language = new URL(url).searchParams.get('language')
requestedLocales.push(language)
return Response.json({
recommended_apps: [createApp(language === 'pt-BR' ? 'Português' : 'English')],
})
})
const { rerender } = render(<LearnDify dismissible={false} title="English catalog" />, {
systemFeatures: { enable_learn_app: true },
})
expect(await screen.findByRole('heading', { name: 'English' })).toBeInTheDocument()
locale.value = 'pt-BR'
rerender(<LearnDify dismissible={false} title="Portuguese catalog" />)
expect(await screen.findByRole('heading', { name: 'Português' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'English' })).not.toBeInTheDocument()
locale.value = 'en-US'
rerender(<LearnDify dismissible={false} title="English catalog" />)
expect(await screen.findByRole('heading', { name: 'English' })).toBeInTheDocument()
expect(requestedLocales).toEqual(['en-US', 'pt-BR'])
})
it('shows the supplied loading fallback until the request resolves, then leaves an empty catalog hidden', async () => {
let resolveResponse!: (response: Response) => void
request.mockReturnValue(
new Promise<Response>((resolve) => {
resolveResponse = resolve
}),
)
render(<LearnDify loadingFallback={<div role="status">Loading lessons</div>} />, {
systemFeatures: { enable_learn_app: true },
})
expect(screen.getByRole('status')).toHaveTextContent('Loading lessons')
await act(async () => resolveResponse(Response.json({ recommended_apps: [] })))
await waitFor(() => expect(screen.queryByRole('status')).not.toBeInTheDocument())
expect(
screen.queryByRole('heading', { name: 'explore.learnDify.title' }),
).not.toBeInTheDocument()
})
})
@@ -0,0 +1,109 @@
import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'
import type { ReactElement } from 'react'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { trackEvent } from '@/app/components/base/amplitude'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import LearnDifyItem from '../item'
let deploymentEdition: DeploymentEdition = 'CLOUD'
const render = (ui: ReactElement) =>
renderWithConsoleQuery(ui, { systemFeatures: { deployment_edition: deploymentEdition } })
vi.mock('@/app/components/base/amplitude', () => ({
trackEvent: vi.fn(),
}))
const createApp = (overrides: Partial<RecommendedAppResponse> = {}): RecommendedAppResponse => ({
app: {
id: 'app-basic-id',
mode: 'chat' as const,
icon_type: 'emoji',
icon: '😀',
icon_background: '#fff',
icon_url: '',
name: 'Learn Dify App',
},
can_trial: true,
app_id: 'learn-dify-app',
description: 'Learn Dify description',
categories: ['Writing'],
position: 1,
...overrides,
})
describe('LearnDifyItem', () => {
const mockTrackEvent = vi.mocked(trackEvent)
beforeEach(() => {
deploymentEdition = 'CLOUD'
vi.clearAllMocks()
})
it('should create app when card is clicked outside cloud edition', async () => {
deploymentEdition = 'COMMUNITY'
const app = createApp()
const onCreate = vi.fn()
const user = userEvent.setup()
render(<LearnDifyItem canCreate item={app} onCreate={onCreate} onTry={vi.fn()} />)
await user.click(screen.getByRole('button', { name: 'Learn Dify App' }))
expect(onCreate).toHaveBeenCalledWith(app)
expect(mockTrackEvent).not.toHaveBeenCalled()
})
it('should not make the card clickable outside cloud edition when create is unavailable', () => {
deploymentEdition = 'COMMUNITY'
render(<LearnDifyItem canCreate={false} item={createApp()} onTry={vi.fn()} />)
expect(screen.queryByRole('button', { name: 'Learn Dify App' })).not.toBeInTheDocument()
})
it('should open detail when card is clicked in cloud edition', async () => {
const onTry = vi.fn()
const app = createApp()
const user = userEvent.setup()
render(<LearnDifyItem canCreate={false} item={app} onTry={onTry} />)
const card = screen.getByRole('button', { name: 'Learn Dify App' })
expect(card).toHaveAccessibleDescription('Learn Dify description')
await user.click(card)
expect(onTry).toHaveBeenCalledWith(app)
expect(mockTrackEvent).toHaveBeenCalledWith('preview_template', {
template_id: app.app_id,
template_name: app.app?.name,
template_mode: app.app?.mode,
template_categories: app.categories,
page: 'explore',
})
})
it('keeps nullable catalog metadata raw when previewing a card', async () => {
const app: RecommendedAppResponse = {
app_id: 'nullable-app',
app: null,
can_trial: true,
description: null,
}
const onTry = vi.fn()
const user = userEvent.setup()
render(<LearnDifyItem canCreate={false} item={app} onTry={onTry} />)
await user.click(screen.getByRole('button'))
expect(onTry).toHaveBeenCalledWith(app)
expect(mockTrackEvent).toHaveBeenCalledWith('preview_template', {
template_id: 'nullable-app',
template_name: '',
template_mode: '',
template_categories: [],
page: 'explore',
})
})
})
@@ -0,0 +1,173 @@
'use client'
import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
import { cn } from '@langgenius/dify-ui/cn'
import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { MAIN_NAV_APP_CARD_GRID_CLASS_NAME } from '@/app/components/main-nav/app-card-grid'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
import LearnDifyItem from './item'
import { useLearnDifyHiddenValue, useSetLearnDifyHidden } from './storage'
type LearnDifyProps = {
canCreate?: boolean
className?: string
dismissible?: boolean
forceVisible?: boolean
itemLimit?: number
loadingFallback?: React.ReactNode
onCreate?: (app: RecommendedAppResponse) => void
onTry?: (app: RecommendedAppResponse) => void
showDescription?: boolean
stepByStepTourTarget?: string
title?: string
}
type LearnDifyContentProps = LearnDifyProps & {
onHide?: () => void
}
const LearnDifyContent = ({
canCreate = false,
className,
itemLimit,
loadingFallback = null,
onHide,
onCreate,
onTry,
showDescription = true,
stepByStepTourTarget,
title,
}: LearnDifyContentProps) => {
const { t } = useTranslation(['explore'])
const locale = useLocale()
const [isClosing, setIsClosing] = useState(false)
const [collapseTransform, setCollapseTransform] = useState<string>()
const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const sectionRef = useRef<HTMLElement>(null)
const { data: learnDifyItems = [], isLoading } = useQuery(
consoleQuery.explore.apps.learnDify.get.queryOptions({
input: { query: { language: locale } },
select: (response) =>
[...response.recommended_apps].sort((a, b) => (a.position ?? 0) - (b.position ?? 0)),
}),
)
useEffect(() => {
return () => {
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
}
}, [])
const handleHide = () => {
const sectionRect = sectionRef.current?.getBoundingClientRect()
const helpTargetRect = document
.querySelector('[data-learn-dify-help-target]')
?.getBoundingClientRect()
if (sectionRect && helpTargetRect) {
const sectionCenterX = sectionRect.left + sectionRect.width / 2
const sectionCenterY = sectionRect.top + sectionRect.height / 2
const helpCenterX = helpTargetRect.left + helpTargetRect.width / 2
const helpCenterY = helpTargetRect.top + helpTargetRect.height / 2
setCollapseTransform(
`translate3d(${helpCenterX - sectionCenterX}px, ${helpCenterY - sectionCenterY}px, 0) scale(0.08)`,
)
} else {
setCollapseTransform('scale(0.08)')
}
setIsClosing(true)
hideTimerRef.current = setTimeout(() => {
onHide?.()
setIsClosing(false)
setCollapseTransform(undefined)
}, 800)
}
const visibleItems = itemLimit ? learnDifyItems.slice(0, itemLimit) : learnDifyItems
const sectionTitle = title ?? t(($) => $['learnDify.title'], { ns: 'explore' })
if (isLoading) return loadingFallback
if (visibleItems.length === 0) return null
return (
<section
ref={sectionRef}
className={cn(
'px-8 pb-6 transition-[opacity,transform] duration-800 ease-in-out',
isClosing && 'pointer-events-none relative z-50 opacity-20',
className,
)}
style={
isClosing ? { transform: collapseTransform, transformOrigin: 'center center' } : undefined
}
aria-labelledby="learn-dify-title"
data-step-by-step-tour-target={stepByStepTourTarget}
>
<div className="-mx-4 rounded-2xl bg-background-section p-4">
<div className="flex items-start justify-between gap-4 pb-2.5">
<div className="min-w-0">
<h2
id="learn-dify-title"
className="truncate system-xl-medium text-text-primary"
title={sectionTitle}
>
{sectionTitle}
</h2>
{showDescription && (
<p className="mt-0.5 truncate system-xs-regular text-text-tertiary">
{t(($) => $['learnDify.description'], { ns: 'explore' })}
</p>
)}
</div>
{onHide && (
<button
type="button"
className="flex size-8 shrink-0 touch-manipulation items-center justify-center rounded-lg text-text-tertiary outline-hidden transition-colors hover:bg-state-base-hover hover:text-text-secondary focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid motion-reduce:transition-none"
aria-label={t(($) => $['learnDify.hide'], { ns: 'explore' })}
onClick={handleHide}
>
<span className="i-ri-close-line size-4" aria-hidden="true" />
</button>
)}
</div>
<div className={cn('gap-2.5', MAIN_NAV_APP_CARD_GRID_CLASS_NAME)}>
{visibleItems.map((item) => (
<LearnDifyItem
key={item.app_id}
canCreate={canCreate}
item={item}
onCreate={onCreate}
onTry={onTry}
/>
))}
</div>
</div>
</section>
)
}
const DismissibleLearnDify = (props: LearnDifyProps) => {
const hidden = useLearnDifyHiddenValue()
const setHidden = useSetLearnDifyHidden()
if (hidden) return null
return <LearnDifyContent {...props} onHide={() => setHidden(true)} />
}
const LearnDify = (props: LearnDifyProps) => {
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
if (!systemFeatures.enable_learn_app) return null
if (props.dismissible === false || props.forceVisible) return <LearnDifyContent {...props} />
return <DismissibleLearnDify {...props} />
}
export default React.memo(LearnDify)
@@ -0,0 +1,84 @@
'use client'
import type { RecommendedAppResponse } from '@dify/contracts/api/console/explore/types.gen'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { trackEvent } from '@/app/components/base/amplitude'
import AppIcon from '@/app/components/base/app-icon'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
type LearnDifyItemProps = {
canCreate: boolean
item: RecommendedAppResponse
onCreate?: (app: RecommendedAppResponse) => void
onTry?: (app: RecommendedAppResponse) => void
}
const LearnDifyItem = ({ canCreate, item, onCreate, onTry }: LearnDifyItemProps) => {
const { data: deploymentEdition } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: ({ deployment_edition }) => deployment_edition,
})
const appNameId = React.useId()
const appDescriptionId = React.useId()
const appBasicInfo = item.app
const appName = appBasicInfo?.name ?? ''
const appMode = appBasicInfo?.mode ?? ''
const canViewApp = deploymentEdition === 'CLOUD'
const canShowCreate = canCreate && !!onCreate
const isClickable = canViewApp || canShowCreate
const handleTryApp = () => {
trackEvent('preview_template', {
template_id: item.app_id,
template_name: appName,
template_mode: appMode,
template_categories: item.categories ?? [],
page: 'explore',
})
onTry?.(item)
}
const handleCardClick = () => {
if (canViewApp) {
handleTryApp()
return
}
if (canShowCreate) onCreate?.(item)
}
return (
<article
className={cn(
'relative flex min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg px-4 pt-4 pb-4 text-left shadow-xs',
isClickable && 'cursor-pointer',
)}
>
{isClickable && (
<button
type="button"
className="absolute inset-0 z-10 cursor-pointer touch-manipulation appearance-none rounded-xl border-0 bg-transparent p-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid"
aria-labelledby={appNameId}
aria-describedby={item.description ? appDescriptionId : undefined}
onClick={handleCardClick}
/>
)}
<div className="flex flex-col items-start gap-2 pb-1">
<AppIcon size="large" icon={appBasicInfo} />
<h3 id={appNameId} className="w-full truncate system-md-semibold text-text-secondary">
{appName}
</h3>
</div>
<p
id={appDescriptionId}
className="line-clamp-2 min-h-8 system-xs-regular text-text-tertiary"
>
{item.description}
</p>
</article>
)
}
export default React.memo(LearnDifyItem)
@@ -0,0 +1,10 @@
'use client'
import { createLocalStorageState } from 'foxact/create-local-storage-state'
export const LEARN_DIFY_HIDDEN_STORAGE_KEY = 'explore-learn-dify-hidden'
const [_useLearnDifyHidden, useLearnDifyHiddenValue, useSetLearnDifyHidden] =
createLocalStorageState<boolean>(LEARN_DIFY_HIDDEN_STORAGE_KEY, false)
export { useLearnDifyHiddenValue, useSetLearnDifyHidden }