Commit 9c670249 by liimin

refactor(app): 优化代码结构和格式

- 调整代码缩进和格式,提高可读性
- 简化部分复杂表达式,提高代码清晰度
- 统一使用箭头函数,提高代码一致性
- 移除冗余的空行和空格,精简代码
1 parent 12b1fe30
...@@ -9,20 +9,19 @@ type IAppUnavailableProps = { ...@@ -9,20 +9,19 @@ type IAppUnavailableProps = {
unknownReason?: string unknownReason?: string
} }
const AppUnavailable: FC<IAppUnavailableProps> = ({ const AppUnavailable: FC<IAppUnavailableProps> = ({ code = 404, isUnknownReason, unknownReason }) => {
code = 404,
isUnknownReason,
unknownReason,
}) => {
const { t } = useTranslation() const { t } = useTranslation()
return ( return (
<div className='flex h-screen w-screen items-center justify-center'> <div className="flex h-screen w-screen items-center justify-center">
<h1 className='mr-5 h-[50px] pr-5 text-[24px] font-medium leading-[50px]' <h1
className="mr-5 h-[50px] pr-5 text-[24px] font-medium leading-[50px]"
style={{ style={{
borderRight: '1px solid rgba(0,0,0,.3)', borderRight: '1px solid rgba(0,0,0,.3)',
}}>{code}</h1> }}>
<div className='text-sm'>{unknownReason || (isUnknownReason ? t('share.common.appUnknownError') : t('share.common.appUnavailable'))}</div> {code}
</h1>
<div className="text-sm">{unknownReason || (isUnknownReason ? t('share.common.appUnknownError') : t('share.common.appUnavailable'))}</div>
</div> </div>
) )
} }
......
...@@ -10,25 +10,10 @@ type BadgeProps = { ...@@ -10,25 +10,10 @@ type BadgeProps = {
hasRedCornerMark?: boolean hasRedCornerMark?: boolean
} }
const Badge = ({ const Badge = ({ className, text, children, uppercase = true, hasRedCornerMark }: BadgeProps) => {
className,
text,
children,
uppercase = true,
hasRedCornerMark,
}: BadgeProps) => {
return ( return (
<div <div className={cn('relative inline-flex h-5 items-center rounded-[5px] border border-divider-deep px-[5px] leading-3 text-text-tertiary', uppercase ? 'system-2xs-medium-uppercase' : 'system-xs-medium', className)}>
className={cn( {hasRedCornerMark && <div className="absolute right-[-2px] top-[-2px] h-1.5 w-1.5 rounded-[2px] border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm"></div>}
'relative inline-flex h-5 items-center rounded-[5px] border border-divider-deep px-[5px] leading-3 text-text-tertiary',
uppercase ? 'system-2xs-medium-uppercase' : 'system-xs-medium',
className,
)}
>
{hasRedCornerMark && (
<div className='absolute right-[-2px] top-[-2px] h-1.5 w-1.5 rounded-[2px] border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm'>
</div>
)}
{children || text} {children || text}
</div> </div>
) )
......
...@@ -11,7 +11,7 @@ import { getProcessedInputs, processOpeningStatement } from "./utils"; ...@@ -11,7 +11,7 @@ import { getProcessedInputs, processOpeningStatement } from "./utils";
import { TransferMethod } from "@/types/app"; import { TransferMethod } from "@/types/app";
import { useToastContext } from "@/app/components/base/toast"; import { useToastContext } from "@/app/components/base/toast";
import { ssePost } from "@/service/base"; import { ssePost } from "@/service/base";
import type { Annotation } from "@/models/log"; import type { Annotation } from "@/models/app";
import { WorkflowRunningStatus } from "@/app/components/workflow/types"; import { WorkflowRunningStatus } from "@/app/components/workflow/types";
import useTimestamp from "@/hooks/use-timestamp"; import useTimestamp from "@/hooks/use-timestamp";
import { AudioPlayerManager } from "@/app/components/base/audio-btn/audio.player.manager"; import { AudioPlayerManager } from "@/app/components/base/audio-btn/audio.player.manager";
......
...@@ -2,14 +2,11 @@ ...@@ -2,14 +2,11 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-06-11 14:57:49 * @LastEditTime: 2025-06-12 13:54:54
* @FilePath: \ai-assistant\app\components\base\chat\types.ts * @FilePath: \ai-assistant\app\components\base\chat\types.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import type { import type { ModelConfig, VisionSettings } from '@/types/app'
ModelConfig,
VisionSettings,
} from '@/types/app'
import type { IChatItem } from '@/app/components/base/chat/chat/type' import type { IChatItem } from '@/app/components/base/chat/chat/type'
import type { NodeTracing } from '@/types/workflow' import type { NodeTracing } from '@/types/workflow'
import type { WorkflowRunningStatus } from '@/app/components/workflow/types' import type { WorkflowRunningStatus } from '@/app/components/workflow/types'
...@@ -17,7 +14,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types' ...@@ -17,7 +14,7 @@ import type { FileEntity } from '@/app/components/base/file-uploader/types'
export type { VisionFile } from '@/types/app' export type { VisionFile } from '@/types/app'
export { TransferMethod } from '@/types/app' export { TransferMethod } from '@/types/app'
export type { Inputs } from '@/models/debug'
export type UserInputForm = { export type UserInputForm = {
default: string default: string
label: string label: string
...@@ -73,18 +70,18 @@ export type ChatItemInTree = { ...@@ -73,18 +70,18 @@ export type ChatItemInTree = {
children?: ChatItemInTree[] children?: ChatItemInTree[]
} & ChatItem } & ChatItem
export type InputMessageProp = { export type InputMessageProp = {
message:string message: string
type:InputMessageType type: InputMessageType
} }
export enum InputMessageType { export enum InputMessageType {
SELF = '0', SELF = '0',
SYSTEM = '1' SYSTEM = '1',
} }
export enum PracticeStatus { export enum PracticeStatus {
None = '0', None = '0',
Practicing = '1', Practicing = '1',
Passed = '2', Passed = '2',
Failed = '3' Failed = '3',
} }
export type OnSend = { export type OnSend = {
(message: InputMessageProp, files?: FileEntity[]): void (message: InputMessageProp, files?: FileEntity[]): void
......
...@@ -12,36 +12,32 @@ type Props = { ...@@ -12,36 +12,32 @@ type Props = {
onChange?: OnFeaturesChange onChange?: OnFeaturesChange
} }
const SpeechToText = ({ const SpeechToText = ({ disabled, onChange }: Props) => {
disabled,
onChange,
}: Props) => {
const { t } = useTranslation() const { t } = useTranslation()
const features = useFeatures(s => s.features) const features = useFeatures(s => s.features)
const featuresStore = useFeaturesStore() const featuresStore = useFeaturesStore()
const handleChange = useCallback((type: FeatureEnum, enabled: boolean) => { const handleChange = useCallback(
const { (type: FeatureEnum, enabled: boolean) => {
features, const { features, setFeatures } = featuresStore!.getState()
setFeatures,
} = featuresStore!.getState()
const newFeatures = produce(features, (draft) => { const newFeatures = produce(features, draft => {
draft[type] = { draft[type] = {
...draft[type], ...draft[type],
enabled, enabled,
} }
}) })
setFeatures(newFeatures) setFeatures(newFeatures)
if (onChange) if (onChange) onChange()
onChange() },
}, [featuresStore, onChange]) [featuresStore, onChange],
)
return ( return (
<FeatureCard <FeatureCard
icon={ icon={
<div className='shrink-0 rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-violet-violet-600 p-1 shadow-xs'> <div className="shrink-0 rounded-lg border-[0.5px] border-divider-subtle bg-util-colors-violet-violet-600 p-1 shadow-xs">
<Microphone01 className='h-4 w-4 text-text-primary-on-surface' /> <Microphone01 className="h-4 w-4 text-text-primary-on-surface" />
</div> </div>
} }
title={t('appDebug.feature.speechToText.title')} title={t('appDebug.feature.speechToText.title')}
......
...@@ -27,6 +27,7 @@ import useTheme from '@/hooks/use-theme' ...@@ -27,6 +27,7 @@ import useTheme from '@/hooks/use-theme'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import SVGRenderer from './svg-gallery' import SVGRenderer from './svg-gallery'
import ImagePreview from '@/app/components/base/image-uploader/image-preview' import ImagePreview from '@/app/components/base/image-uploader/image-preview'
import { InputMessageType } from '@/app/components/base/chat/types'
// Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
const capitalizationLanguageNameMap: Record<string, string> = { const capitalizationLanguageNameMap: Record<string, string> = {
...@@ -257,7 +258,10 @@ const Link = ({ node, children, ...props }: any) => { ...@@ -257,7 +258,10 @@ const Link = ({ node, children, ...props }: any) => {
const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1]) const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
return ( return (
<abbr className="cursor-pointer underline !decoration-primary-700 decoration-dashed" onClick={() => onSend?.(hidden_text)} title={node.children[0]?.value || ''}> <abbr className="cursor-pointer underline !decoration-primary-700 decoration-dashed" onClick={() => onSend?.({
message: hidden_text,
type: InputMessageType.SELF
})} title={node.children[0]?.value || ''}>
{node.children[0]?.value || ''} {node.children[0]?.value || ''}
</abbr> </abbr>
) )
......
/**
* @fileoverview AudioBlock component for rendering audio elements in Markdown.
* Extracted from the main markdown renderer for modularity.
* Uses the AudioGallery component to display audio players.
*/
import React, { memo } from 'react'
import AudioGallery from '@/app/components/base/audio-gallery'
const Audio: any = memo(({ node }: any) => {
const srcs = node.children.filter((child: any) => 'properties' in child).map((child: any) => (child as any).properties.src)
if (srcs.length === 0) {
const src = node.properties?.src
if (src)
return <AudioGallery key={src} srcs={[src]} />
return null
}
return <AudioGallery key={srcs.join()} srcs={srcs} />
})
Audio.displayName = 'Audio'
export default Audio
import { useChatContext } from '@/app/components/base/chat/chat/context'
import Button from '@/app/components/base/button'
import cn from '@/utils/classnames'
import { isValidUrl } from './utils'
const MarkdownButton = ({ node }: any) => {
const { onSend } = useChatContext()
const variant = node.properties.dataVariant
const message = node.properties.dataMessage
const link = node.properties.dataLink
const size = node.properties.dataSize
return <Button
variant={variant}
size={size}
className={cn('!h-auto min-h-8 select-none whitespace-normal !px-3')}
onClick={() => {
if (isValidUrl(link)) {
window.open(link, '_blank')
return
}
if(!message)
return
onSend?.(message)
}}
>
<span className='text-[13px]'>{node.children[0]?.value || ''}</span>
</Button>
}
MarkdownButton.displayName = 'MarkdownButton'
export default MarkdownButton
import React, { useEffect, useState } from 'react'
import Button from '@/app/components/base/button'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'
import TimePicker from '@/app/components/base/date-and-time-picker/time-picker'
import Checkbox from '@/app/components/base/checkbox'
import Select from '@/app/components/base/select'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { InputMessageType } from '@/app/components/base/chat/types'
enum DATA_FORMAT {
TEXT = 'text',
JSON = 'json',
}
enum SUPPORTED_TAGS {
LABEL = 'label',
INPUT = 'input',
TEXTAREA = 'textarea',
BUTTON = 'button',
}
enum SUPPORTED_TYPES {
TEXT = 'text',
PASSWORD = 'password',
EMAIL = 'email',
NUMBER = 'number',
DATE = 'date',
TIME = 'time',
DATETIME = 'datetime',
CHECKBOX = 'checkbox',
SELECT = 'select',
}
const MarkdownForm = ({ node }: any) => {
const { onSend } = useChatContext()
const [formValues, setFormValues] = useState<{ [key: string]: any }>({})
useEffect(() => {
const initialValues: { [key: string]: any } = {}
node.children.forEach((child: any) => {
if ([SUPPORTED_TAGS.INPUT, SUPPORTED_TAGS.TEXTAREA].includes(child.tagName)) initialValues[child.properties.name] = child.properties.value
})
setFormValues(initialValues)
}, [node.children])
const getFormValues = (children: any) => {
const values: { [key: string]: any } = {}
children.forEach((child: any) => {
if ([SUPPORTED_TAGS.INPUT, SUPPORTED_TAGS.TEXTAREA].includes(child.tagName)) values[child.properties.name] = formValues[child.properties.name]
})
return values
}
const onSubmit = (e: any) => {
e.preventDefault()
const format = node.properties.dataFormat || DATA_FORMAT.TEXT
const result = getFormValues(node.children)
if (format === DATA_FORMAT.JSON) {
onSend?.({
message: JSON.stringify(result),
type: InputMessageType.SELF,
})
} else {
const textResult = Object.entries(result)
.map(([key, value]) => `${key}: ${value}`)
.join('\n')
onSend?.({
message: textResult,
type: InputMessageType.SELF,
})
}
}
return (
<form
autoComplete="off"
className="flex flex-col self-stretch"
onSubmit={(e: any) => {
e.preventDefault()
e.stopPropagation()
}}>
{node.children
.filter((i: any) => i.type === 'element')
.map((child: any, index: number) => {
if (child.tagName === SUPPORTED_TAGS.LABEL) {
return (
<label key={index} htmlFor={child.properties.for} className="system-md-semibold my-2 text-text-secondary">
{child.children[0]?.value || ''}
</label>
)
}
if (child.tagName === SUPPORTED_TAGS.INPUT && Object.values(SUPPORTED_TYPES).includes(child.properties.type)) {
if (child.properties.type === SUPPORTED_TYPES.DATE || child.properties.type === SUPPORTED_TYPES.DATETIME) {
return (
<DatePicker
key={index}
value={formValues[child.properties.name]}
needTimePicker={child.properties.type === SUPPORTED_TYPES.DATETIME}
onChange={date => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: date,
}))
}}
onClear={() => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: undefined,
}))
}}
/>
)
}
if (child.properties.type === SUPPORTED_TYPES.TIME) {
return (
<TimePicker
key={index}
value={formValues[child.properties.name]}
onChange={time => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: time,
}))
}}
onClear={() => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: undefined,
}))
}}
/>
)
}
if (child.properties.type === SUPPORTED_TYPES.CHECKBOX) {
return (
<div className="mt-2 flex h-6 items-center space-x-2" key={index}>
<Checkbox
key={index}
checked={formValues[child.properties.name]}
onCheck={() => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: !prevValues[child.properties.name],
}))
}}
/>
<span>{child.properties.dataTip || child.properties['data-tip'] || ''}</span>
</div>
)
}
if (child.properties.type === SUPPORTED_TYPES.SELECT) {
return (
<Select
key={index}
allowSearch={false}
className="w-full"
items={(() => {
let options = child.properties.dataOptions || child.properties['data-options'] || []
if (typeof options === 'string') {
try {
options = JSON.parse(options)
} catch (e) {
console.error('Failed to parse options:', e)
options = []
}
}
return options.map((option: string) => ({
name: option,
value: option,
}))
})()}
defaultValue={formValues[child.properties.name]}
onSelect={item => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: item.value,
}))
}}
/>
)
}
return (
<Input
key={index}
type={child.properties.type}
name={child.properties.name}
placeholder={child.properties.placeholder}
value={formValues[child.properties.name]}
onChange={e => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: e.target.value,
}))
}}
/>
)
}
if (child.tagName === SUPPORTED_TAGS.TEXTAREA) {
return (
<Textarea
key={index}
name={child.properties.name}
placeholder={child.properties.placeholder}
value={formValues[child.properties.name]}
onChange={e => {
setFormValues(prevValues => ({
...prevValues,
[child.properties.name]: e.target.value,
}))
}}
/>
)
}
if (child.tagName === SUPPORTED_TAGS.BUTTON) {
const variant = child.properties.dataVariant
const size = child.properties.dataSize
return (
<Button variant={variant} size={size} className="mt-4" key={index} onClick={onSubmit}>
<span className="text-[13px]">{child.children[0]?.value || ''}</span>
</Button>
)
}
return <p key={index}>Unsupported tag: {child.tagName}</p>
})}
</form>
)
}
MarkdownForm.displayName = 'MarkdownForm'
export default MarkdownForm
/**
* @fileoverview Img component for rendering <img> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Uses the ImageGallery component to display images.
*/
import React from 'react'
import ImageGallery from '@/app/components/base/image-gallery'
const Img = ({ src }: any) => {
return <div className="markdown-img-wrapper"><ImageGallery srcs={[src]} /></div>
}
export default Img
/**
* @fileoverview Barrel file for all markdown block components.
* This allows for cleaner imports in other parts of the application.
*/
export { default as Audio } from './audio'
export { default as Code } from './code'
export { default as Img } from './img'
export { default as Link } from './link'
export { default as Paragraph } from './paragraph'
export { default as PreCode } from './pre-code'
export { default as Script } from './script'
export { default as Video } from './video'
// Assuming these are also standalone components in this directory intended for Markdown rendering
export { default as MarkdownButton } from './button'
export { default as MarkdownForm } from './form'
export { default as Think } from './think'
/**
* @fileoverview Link component for rendering <a> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Handles special rendering for "abbr:" type links for interactive chat actions.
*/
import React, { useState } from 'react'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { isValidUrl } from './utils'
import ImagePreview from '@/app/components/base/image-uploader/image-preview'
import { InputMessageType } from '@/app/components/base/chat/types'
const Link = ({ node, children, ...props }: any) => {
const { onSend } = useChatContext()
const [imagePreviewUrl, setImagePreviewUrl] = useState('')
if (node.properties?.href && node.properties.href?.toString().startsWith('abbr')) {
const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
return (
<abbr
className="cursor-pointer underline !decoration-primary-700 decoration-dashed"
onClick={() =>
onSend?.({
message: hidden_text,
type: InputMessageType.SELF,
})
}
title={node.children[0]?.value || ''}>
{node.children[0]?.value || ''}
</abbr>
)
} else if (isValidUrl(node.properties?.href) && /\.(jpg|jpeg|png|gif|webp)$/i.test(node.properties.href)) {
// 处理图片链接
return (
<>
<img src={node.properties.href} alt={node.children[0]?.value || ''} className="max-w-full h-auto rounded-lg cursor-pointer hover:opacity-90" onClick={() => setImagePreviewUrl(node.properties.href)} />
{imagePreviewUrl && <ImagePreview url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} title={''} />}
</>
)
} else {
const href = props.href || node.properties?.href
if (!isValidUrl(href)) return <span>{children}</span>
return (
<a href={href} target="_blank" className="cursor-pointer underline !decoration-primary-700 decoration-dashed">
{children || 'Download'}
</a>
)
}
}
export default Link
/**
* @fileoverview Paragraph component for rendering <p> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Handles special rendering for paragraphs that directly contain an image.
*/
import React from 'react'
import ImageGallery from '@/app/components/base/image-gallery'
const Paragraph = (paragraph: any) => {
const { node }: any = paragraph
const children_node = node.children
if (children_node && children_node[0] && 'tagName' in children_node[0] && children_node[0].tagName === 'img') {
return (
<div className="markdown-img-wrapper">
<ImageGallery srcs={[children_node[0].properties.src]} />
{
Array.isArray(paragraph.children) && paragraph.children.length > 1 && (
<div className="mt-2">{paragraph.children.slice(1)}</div>
)
}
</div>
)
}
return <p>{paragraph.children}</p>
}
export default Paragraph
/**
* @fileoverview PreCode component for rendering <pre> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* This is a simple wrapper around the HTML <pre> element.
*/
import React, { useRef } from 'react'
function PreCode(props: { children: any }) {
const ref = useRef<HTMLPreElement>(null)
return (
<pre ref={ref}>
<span
className="copy-code-button"
></span>
{props.children}
</pre>
)
}
export default PreCode
/**
* @fileoverview ScriptBlock component for handling <script> tags in Markdown.
* Extracted from the main markdown renderer for modularity.
* Note: Current implementation returns the script tag as a string, which might not execute as expected in React.
* This behavior is preserved from the original implementation and may need review for security and functionality.
*/
import { memo } from 'react'
const Script = memo(({ node }: any) => {
const scriptContent = node.children[0]?.value || ''
return `<script>${scriptContent}</script>`
})
Script.displayName = 'Script'
export default Script
import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
const hasEndThink = (children: any): boolean => {
if (typeof children === 'string')
return children.includes('[ENDTHINKFLAG]')
if (Array.isArray(children))
return children.some(child => hasEndThink(child))
if (children?.props?.children)
return hasEndThink(children.props.children)
return false
}
const removeEndThink = (children: any): any => {
if (typeof children === 'string')
return children.replace('[ENDTHINKFLAG]', '')
if (Array.isArray(children))
return children.map(child => removeEndThink(child))
if (children?.props?.children) {
return React.cloneElement(
children,
{
...children.props,
children: removeEndThink(children.props.children),
},
)
}
return children
}
const useThinkTimer = (children: any) => {
const [startTime] = useState(Date.now())
const [elapsedTime, setElapsedTime] = useState(0)
const [isComplete, setIsComplete] = useState(false)
const timerRef = useRef<NodeJS.Timeout>()
useEffect(() => {
if (isComplete) return
timerRef.current = setInterval(() => {
setElapsedTime(Math.floor((Date.now() - startTime) / 100) / 10)
}, 100)
return () => {
if (timerRef.current)
clearInterval(timerRef.current)
}
}, [startTime, isComplete])
useEffect(() => {
if (hasEndThink(children))
setIsComplete(true)
}, [children])
return { elapsedTime, isComplete }
}
export const Think = ({ children, ...props }: any) => {
const { elapsedTime, isComplete } = useThinkTimer(children)
const displayContent = removeEndThink(children)
const { t } = useTranslation()
if (!(props['data-think'] ?? false))
return (<details {...props}>{children}</details>)
return (
<details {...(!isComplete && { open: true })} className="group">
<summary className="flex cursor-pointer select-none list-none items-center whitespace-nowrap pl-2 font-bold text-text-secondary">
<div className="flex shrink-0 items-center">
<svg
className="mr-2 h-3 w-3 transition-transform duration-500 group-open:rotate-90"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 5l7 7-7 7"
/>
</svg>
{isComplete ? `${t('common.chat.thought')}(${elapsedTime.toFixed(1)}s)` : `${t('common.chat.thinking')}(${elapsedTime.toFixed(1)}s)`}
</div>
</summary>
<div className="ml-2 border-l border-components-panel-border bg-components-panel-bg-alt p-3 text-text-secondary">
{displayContent}
</div>
</details>
)
}
export default Think
export const isValidUrl = (url: string): boolean => {
return ['http:', 'https:', '//', 'mailto:'].some(prefix => url.startsWith(prefix))
}
export const isImageUrl = (url: string): boolean => {
return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}
/**
* @fileoverview VideoBlock component for rendering video elements in Markdown.
* Extracted from the main markdown renderer for modularity.
* Uses the VideoGallery component to display videos.
*/
import React, { memo } from 'react'
import VideoGallery from '@/app/components/base/video-gallery'
const Video: any = memo(({ node }: any) => {
const srcs = node.children.filter((child: any) => 'properties' in child).map((child: any) => (child as any).properties.src)
if (srcs.length === 0) {
const src = node.properties?.src
if (src)
return <VideoGallery key={src} srcs={[src]} />
return null
}
return <VideoGallery key={srcs.join()} srcs={srcs} />
})
Video.displayName = 'Video'
export default Video
/**
* @fileoverview ErrorBoundary component for React.
* This component was extracted from the main markdown renderer.
* It catches JavaScript errors anywhere in its child component tree,
* logs those errors, and displays a fallback UI instead of the crashed component tree.
* Primarily used around complex rendering logic like ECharts or SVG within Markdown.
*/
import React, { Component } from 'react'
// **Add an ECharts runtime error handler
// Avoid error #7832 (Crash when ECharts accesses undefined objects)
// This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash.
export default class ErrorBoundary extends Component {
constructor(props: any) {
super(props)
this.state = { hasError: false }
}
componentDidCatch(error: any, errorInfo: any) {
this.setState({ hasError: true })
console.error(error, errorInfo)
}
render() {
// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error
if (this.state.hasError)
return <div>Oops! An error occurred. This could be due to an ECharts runtime error or invalid SVG content. <br />(see the browser console for more information)</div>
// eslint-disable-next-line ts/ban-ts-comment
// @ts-expect-error
return this.props.children
}
}
import ReactMarkdown from 'react-markdown'
import 'katex/dist/katex.min.css'
import RemarkMath from 'remark-math'
import RemarkBreaks from 'remark-breaks'
import RehypeKatex from 'rehype-katex'
import RemarkGfm from 'remark-gfm'
import RehypeRaw from 'rehype-raw'
import { flow } from 'lodash-es'
import cn from '@/utils/classnames'
import { customUrlTransform, preprocessLaTeX, preprocessThinkTag } from './markdown-utils'
import { Audio, Code, Img, Link, MarkdownButton, MarkdownForm, Paragraph, Script, Think, Video } from './blocks'
/**
* @fileoverview Main Markdown rendering component.
* This file was refactored to extract individual block renderers and utility functions
* into separate modules for better organization and maintainability as of [Date of refactor].
* Further refactoring candidates (custom block components not fitting general categories)
* are noted in their respective files if applicable.
*/
export function Markdown(props: { content: string; className?: string; customDisallowedElements?: string[] }) {
const latexContent = flow([preprocessThinkTag, preprocessLaTeX])(props.content)
return (
<div className={cn('markdown-body', '!text-text-primary', props.className)}>
<ReactMarkdown
remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
rehypePlugins={[
RehypeKatex,
RehypeRaw as any,
// The Rehype plug-in is used to remove the ref attribute of an element
() => {
return (tree: any) => {
const iterate = (node: any) => {
if (node.type === 'element' && node.properties?.ref) delete node.properties.ref
if (node.type === 'element' && !/^[a-z][a-z0-9]*$/i.test(node.tagName)) {
node.type = 'text'
node.value = `<${node.tagName}`
}
if (node.children) node.children.forEach(iterate)
}
tree.children.forEach(iterate)
}
},
]}
urlTransform={customUrlTransform}
disallowedElements={['iframe', 'head', 'html', 'meta', 'link', 'style', 'body', ...(props.customDisallowedElements || [])]}
components={{
code: Code,
img: Img,
video: Video,
audio: Audio,
a: Link,
p: Paragraph,
button: MarkdownButton,
form: MarkdownForm,
script: Script as any,
details: Think,
}}>
{/* Markdown detect has problem. */}
{latexContent}
</ReactMarkdown>
</div>
)
}
/**
* @fileoverview Utility functions for preprocessing Markdown content.
* These functions were extracted from the main markdown renderer for better separation of concerns.
* Includes preprocessing for LaTeX and custom "think" tags.
*/
import { flow } from 'lodash-es'
export const preprocessLaTeX = (content: string) => {
if (typeof content !== 'string')
return content
const codeBlockRegex = /```[\s\S]*?```/g
const codeBlocks = content.match(codeBlockRegex) || []
let processedContent = content.replace(codeBlockRegex, 'CODE_BLOCK_PLACEHOLDER')
processedContent = flow([
(str: string) => str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`),
(str: string) => str.replace(/\\\[([\s\S]*?)\\\]/g, (_, equation) => `$$${equation}$$`),
(str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
(str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`),
])(processedContent)
codeBlocks.forEach((block) => {
processedContent = processedContent.replace('CODE_BLOCK_PLACEHOLDER', block)
})
return processedContent
}
export const preprocessThinkTag = (content: string) => {
const thinkOpenTagRegex = /<think>\n/g
const thinkCloseTagRegex = /\n<\/think>/g
return flow([
(str: string) => str.replace(thinkOpenTagRegex, '<details data-think=true>\n'),
(str: string) => str.replace(thinkCloseTagRegex, '\n[ENDTHINKFLAG]</details>'),
(str: string) => str.replace(/(<\/details>)(?![^\S\r\n]*[\r\n])(?![^\S\r\n]*$)/g, '$1\n'),
])(content)
}
/**
* Transforms a URI for use in react-markdown, ensuring security and compatibility.
* This function is designed to work with react-markdown v9+ which has stricter
* default URL handling.
*
* Behavior:
* 1. Always allows the custom 'abbr:' protocol.
* 2. Always allows page-local fragments (e.g., "#some-id").
* 3. Always allows protocol-relative URLs (e.g., "//example.com/path").
* 4. Always allows purely relative paths (e.g., "path/to/file", "/abs/path").
* 5. Allows absolute URLs if their scheme is in a permitted list (case-insensitive):
* 'http:', 'https:', 'mailto:', 'xmpp:', 'irc:', 'ircs:'.
* 6. Intelligently distinguishes colons used for schemes from colons within
* paths, query parameters, or fragments of relative-like URLs.
* 7. Returns the original URI if allowed, otherwise returns `undefined` to
* signal that the URI should be removed/disallowed by react-markdown.
*/
export const customUrlTransform = (uri: string): string | undefined => {
const PERMITTED_SCHEME_REGEX = /^(https?|ircs?|mailto|xmpp|abbr):$/i
if (uri.startsWith('#'))
return uri
if (uri.startsWith('//'))
return uri
const colonIndex = uri.indexOf(':')
if (colonIndex === -1)
return uri
const slashIndex = uri.indexOf('/')
const questionMarkIndex = uri.indexOf('?')
const hashIndex = uri.indexOf('#')
if (
(slashIndex !== -1 && colonIndex > slashIndex)
|| (questionMarkIndex !== -1 && colonIndex > questionMarkIndex)
|| (hashIndex !== -1 && colonIndex > hashIndex)
)
return uri
const scheme = uri.substring(0, colonIndex + 1).toLowerCase()
if (PERMITTED_SCHEME_REGEX.test(scheme))
return uri
return undefined
}
export function cleanUpSvgCode(svgCode: string): string { export function cleanUpSvgCode(svgCode: string): string {
return svgCode.replaceAll('<br>', '<br/>') return svgCode.replaceAll('<br>', '<br/>')
} }
/**
* Preprocesses mermaid code to fix common syntax issues
*/
export function preprocessMermaidCode(code: string): string {
if (!code || typeof code !== 'string')
return ''
// First check if this is a gantt chart
if (code.trim().startsWith('gantt')) {
// For gantt charts, we need to ensure each task is on its own line
// Split the code into lines and process each line separately
const lines = code.split('\n').map(line => line.trim())
return lines.join('\n')
}
return code
// Replace English colons with Chinese colons in section nodes to avoid parsing issues
.replace(/section\s+([^:]+):/g, (match, sectionName) => `section ${sectionName}:`)
// Fix common syntax issues
.replace(/fifopacket/g, 'rect')
// Ensure graph has direction
.replace(/^graph\s+((?:TB|BT|RL|LR)*)/, (match, direction) => {
return direction ? match : 'graph TD'
})
// Clean up empty lines and extra spaces
.trim()
}
/**
* Prepares mermaid code based on selected style
*/
export function prepareMermaidCode(code: string, style: 'classic' | 'handDrawn'): string {
let finalCode = preprocessMermaidCode(code)
// Special handling for gantt charts and mindmaps
if (finalCode.trim().startsWith('gantt') || finalCode.trim().startsWith('mindmap')) {
// For gantt charts and mindmaps, preserve the structure exactly as is
return finalCode
}
if (style === 'handDrawn') {
finalCode = finalCode
// Remove style definitions that interfere with hand-drawn style
.replace(/style\s+[^\n]+/g, '')
.replace(/linkStyle\s+[^\n]+/g, '')
.replace(/^flowchart/, 'graph')
// Remove any styles that might interfere with hand-drawn style
.replace(/class="[^"]*"/g, '')
.replace(/fill="[^"]*"/g, '')
.replace(/stroke="[^"]*"/g, '')
// Ensure hand-drawn style charts always start with graph
if (!finalCode.startsWith('graph') && !finalCode.startsWith('flowchart'))
finalCode = `graph TD\n${finalCode}`
}
return finalCode
}
/**
* Converts SVG to base64 string for image rendering
*/
export function svgToBase64(svgGraph: string): Promise<string> {
if (!svgGraph)
return Promise.resolve('')
try {
// Ensure SVG has correct XML declaration
if (!svgGraph.includes('<?xml'))
svgGraph = `<?xml version="1.0" encoding="UTF-8"?>${svgGraph}`
const blob = new Blob([new TextEncoder().encode(svgGraph)], { type: 'image/svg+xml;charset=utf-8' })
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result as string)
reader.onerror = reject
reader.readAsDataURL(blob)
})
}
catch (error) {
console.error('Error converting SVG to base64:', error)
return Promise.resolve('')
}
}
/**
* Processes SVG for theme styling
*/
export function processSvgForTheme(
svg: string,
isDark: boolean,
isHandDrawn: boolean,
themes: {
light: any
dark: any
},
): string {
let processedSvg = svg
if (isDark) {
processedSvg = processedSvg
.replace(/style="fill: ?#000000"/g, 'style="fill: #e2e8f0"')
.replace(/style="stroke: ?#000000"/g, 'style="stroke: #94a3b8"')
.replace(/<rect [^>]*fill="#ffffff"/g, '<rect $& fill="#1e293b"')
if (isHandDrawn) {
processedSvg = processedSvg
.replace(/fill="#[a-fA-F0-9]{6}"/g, `fill="${themes.dark.nodeColors[0].bg}"`)
.replace(/stroke="#[a-fA-F0-9]{6}"/g, `stroke="${themes.dark.connectionColor}"`)
.replace(/stroke-width="1"/g, 'stroke-width="1.5"')
}
else {
let i = 0
themes.dark.nodeColors.forEach(() => {
const regex = /fill="#[a-fA-F0-9]{6}"[^>]*class="node-[^"]*"/g
processedSvg = processedSvg.replace(regex, (match: string) => {
const colorIndex = i % themes.dark.nodeColors.length
i++
return match.replace(/fill="#[a-fA-F0-9]{6}"/, `fill="${themes.dark.nodeColors[colorIndex].bg}"`)
})
})
processedSvg = processedSvg
.replace(/<path [^>]*stroke="#[a-fA-F0-9]{6}"/g,
`<path stroke="${themes.dark.connectionColor}" stroke-width="1.5"`)
.replace(/<(line|polyline) [^>]*stroke="#[a-fA-F0-9]{6}"/g,
`<$1 stroke="${themes.dark.connectionColor}" stroke-width="1.5"`)
}
}
else {
if (isHandDrawn) {
processedSvg = processedSvg
.replace(/fill="#[a-fA-F0-9]{6}"/g, `fill="${themes.light.nodeColors[0].bg}"`)
.replace(/stroke="#[a-fA-F0-9]{6}"/g, `stroke="${themes.light.connectionColor}"`)
.replace(/stroke-width="1"/g, 'stroke-width="1.5"')
}
else {
themes.light.nodeColors.forEach(() => {
const regex = /fill="#[a-fA-F0-9]{6}"[^>]*class="node-[^"]*"/g
let i = 0
processedSvg = processedSvg.replace(regex, (match: string) => {
const colorIndex = i % themes.light.nodeColors.length
i++
return match.replace(/fill="#[a-fA-F0-9]{6}"/, `fill="${themes.light.nodeColors[colorIndex].bg}"`)
})
})
processedSvg = processedSvg
.replace(/<path [^>]*stroke="#[a-fA-F0-9]{6}"/g,
`<path stroke="${themes.light.connectionColor}"`)
.replace(/<(line|polyline) [^>]*stroke="#[a-fA-F0-9]{6}"/g,
`<$1 stroke="${themes.light.connectionColor}"`)
}
}
return processedSvg
}
/**
* Checks if mermaid code is complete and valid
*/
export function isMermaidCodeComplete(code: string): boolean {
if (!code || code.trim().length === 0)
return false
try {
const trimmedCode = code.trim()
// Special handling for gantt charts
if (trimmedCode.startsWith('gantt')) {
// For gantt charts, check if it has at least a title and one task
const lines = trimmedCode.split('\n').filter(line => line.trim().length > 0)
return lines.length >= 3
}
// Special handling for mindmaps
if (trimmedCode.startsWith('mindmap')) {
// For mindmaps, check if it has at least a root node
const lines = trimmedCode.split('\n').filter(line => line.trim().length > 0)
return lines.length >= 2
}
// Check for basic syntax structure
const hasValidStart = /^(graph|flowchart|sequenceDiagram|classDiagram|classDef|class|stateDiagram|gantt|pie|er|journey|requirementDiagram|mindmap)/.test(trimmedCode)
// Check for balanced brackets and parentheses
const isBalanced = (() => {
const stack = []
const pairs = { '{': '}', '[': ']', '(': ')' }
for (const char of trimmedCode) {
if (char in pairs) {
stack.push(char)
}
else if (Object.values(pairs).includes(char)) {
const last = stack.pop()
if (pairs[last as keyof typeof pairs] !== char)
return false
}
}
return stack.length === 0
})()
// Check for common syntax errors
const hasNoSyntaxErrors = !trimmedCode.includes('undefined')
&& !trimmedCode.includes('[object Object]')
&& trimmedCode.split('\n').every(line =>
!(line.includes('-->') && !line.match(/\S+\s*-->\s*\S+/)))
return hasValidStart && isBalanced && hasNoSyntaxErrors
}
catch (error) {
console.debug('Mermaid code validation error:', error)
return false
}
}
/**
* Helper to wait for DOM element with retry mechanism
*/
export function waitForDOMElement(callback: () => Promise<any>, maxAttempts = 3, delay = 100): Promise<any> {
return new Promise((resolve, reject) => {
let attempts = 0
const tryRender = async () => {
try {
resolve(await callback())
}
catch (error) {
attempts++
if (attempts < maxAttempts)
setTimeout(tryRender, delay)
else
reject(error)
}
}
tryRender()
})
}
...@@ -36,8 +36,7 @@ export const SVGRenderer = ({ content }: { content: string }) => { ...@@ -36,8 +36,7 @@ export const SVGRenderer = ({ content }: { content: string }) => {
const svgDoc = parser.parseFromString(content, 'image/svg+xml') const svgDoc = parser.parseFromString(content, 'image/svg+xml')
const svgElement = svgDoc.documentElement const svgElement = svgDoc.documentElement
if (!(svgElement instanceof SVGElement)) if (!(svgElement instanceof SVGElement)) throw new Error('Invalid SVG content')
throw new Error('Invalid SVG content')
const originalWidth = Number.parseInt(svgElement.getAttribute('width') || '400', 10) const originalWidth = Number.parseInt(svgElement.getAttribute('width') || '400', 10)
const originalHeight = Number.parseInt(svgElement.getAttribute('height') || '600', 10) const originalHeight = Number.parseInt(svgElement.getAttribute('height') || '600', 10)
...@@ -50,17 +49,17 @@ export const SVGRenderer = ({ content }: { content: string }) => { ...@@ -50,17 +49,17 @@ export const SVGRenderer = ({ content }: { content: string }) => {
rootElement.click(() => { rootElement.click(() => {
setImagePreview(svgToDataURL(svgElement as Element)) setImagePreview(svgToDataURL(svgElement as Element))
}) })
} } catch (error) {
catch (error) { if (svgRef.current) svgRef.current.innerHTML = '<span style="padding: 1rem;">Error rendering SVG. Wait for the image content to complete.</span>'
if (svgRef.current)
svgRef.current.innerHTML = '<span style="padding: 1rem;">Error rendering SVG. Wait for the image content to complete.</span>'
} }
} }
}, [content, windowSize]) }, [content, windowSize])
return ( return (
<> <>
<div ref={svgRef} style={{ <div
ref={svgRef}
style={{
maxHeight: '80vh', maxHeight: '80vh',
display: 'flex', display: 'flex',
justifyContent: 'center', justifyContent: 'center',
...@@ -69,8 +68,9 @@ export const SVGRenderer = ({ content }: { content: string }) => { ...@@ -69,8 +68,9 @@ export const SVGRenderer = ({ content }: { content: string }) => {
wordBreak: 'break-word', wordBreak: 'break-word',
whiteSpace: 'normal', whiteSpace: 'normal',
margin: '0 auto', margin: '0 auto',
}} /> }}
{imagePreview && (<ImagePreview url={imagePreview} title='Preview' onCancel={() => setImagePreview('')} />)} />
{imagePreview && <ImagePreview url={imagePreview} title="Preview" onCancel={() => setImagePreview('')} />}
</> </>
) )
} }
......
...@@ -8,12 +8,12 @@ type ISVGBtnProps = { ...@@ -8,12 +8,12 @@ type ISVGBtnProps = {
setIsSVG: React.Dispatch<React.SetStateAction<boolean>> setIsSVG: React.Dispatch<React.SetStateAction<boolean>>
} }
const SVGBtn = ({ const SVGBtn = ({ isSVG, setIsSVG }: ISVGBtnProps) => {
isSVG,
setIsSVG,
}: ISVGBtnProps) => {
return ( return (
<ActionButton onClick={() => { setIsSVG(prevIsSVG => !prevIsSVG) }}> <ActionButton
onClick={() => {
setIsSVG(prevIsSVG => !prevIsSVG)
}}>
<div className={cn('h-4 w-4', isSVG ? s.svgIconed : s.svgIcon)}></div> <div className={cn('h-4 w-4', isSVG ? s.svgIconed : s.svgIcon)}></div>
</ActionButton> </ActionButton>
) )
......
// import type { LangFuseConfig, LangSmithConfig, OpikConfig, TracingProvider } from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type' // import type { LangFuseConfig, LangSmithConfig, OpikConfig, TracingProvider } from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type'
// import type { App, AppMode, AppSSO, AppTemplate, SiteConfig } from '@/types/app' // import type { App, AppMode, AppSSO, AppTemplate, SiteConfig } from '@/types/app'
// import type { Dependency } from '@/app/components/plugins/types' // import type { Dependency } from '@/app/components/plugins/types'
import type { AppIconType, AppMode } from '@/types/app'
/* export type App = { /* export type App = {
id: string id: string
name: string name: string
...@@ -172,3 +172,57 @@ export type AppVoicesListResponse = [ ...@@ -172,3 +172,57 @@ export type AppVoicesListResponse = [
// tracing_provider: TracingProvider // tracing_provider: TracingProvider
// tracing_config: LangSmithConfig | LangFuseConfig | OpikConfig // tracing_config: LangSmithConfig | LangFuseConfig | OpikConfig
// } // }
export type LogAnnotation = {
id: string
content: string
account: {
id: string
name: string
email: string
}
created_at: number
}
export type Annotation = {
id: string
authorName: string
logAnnotation?: LogAnnotation
created_at?: number
}
export type AppBasicInfo = {
id: string
mode: AppMode
icon_type: AppIconType | null
icon: string
icon_background: string
icon_url: string
name: string
description: string
use_icon_as_answer_icon: boolean
}
export type AppCategory = 'Writing' | 'Translate' | 'HR' | 'Programming' | 'Assistant' | 'Agent' | 'Recommended' | 'Workflow'
export type App = {
app: AppBasicInfo
app_id: string
description: string
copyright: string
privacy_policy: string | null
custom_disclaimer: string | null
category: AppCategory
position: number
is_listed: boolean
install_count: number
installed: boolean
editable: boolean
is_agent: boolean
}
export type InstalledApp = {
app: AppBasicInfo
id: string
uninstallable: boolean
is_pinned: boolean
}
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
// MetadataFilteringModeEnum, // MetadataFilteringModeEnum,
// } from '@/app/components/workflow/nodes/knowledge-retrieval/types' // } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
// import type { ModelConfig as NodeModelConfig } from '@/app/components/workflow/types' // import type { ModelConfig as NodeModelConfig } from '@/app/components/workflow/types'
// export type Inputs = Record<string, string | number | object> export type Inputs = Record<string, string | number | object>
// export enum PromptMode { // export enum PromptMode {
// simple = 'simple', // simple = 'simple',
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!