Commit d3a08eca by liimin

fix: 优化代码格式并添加允许的开发源

修复了代码中的格式问题,如多余的空格和换行,提升了代码的可读性。同时,在 `next.config.js` 中新增了 `allowedDevOrigins` 配置,允许特定 IP 地址的开发源访问。
1 parent 94cf6c53
......@@ -7,10 +7,7 @@ import RehypeKatex from 'rehype-katex'
import RemarkGfm from 'remark-gfm'
import RehypeRaw from 'rehype-raw'
import SyntaxHighlighter from 'react-syntax-highlighter'
import {
atelierHeathDark,
atelierHeathLight,
} from 'react-syntax-highlighter/dist/esm/styles/hljs'
import { atelierHeathDark, atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs'
import { Component, memo, useMemo, useRef, useState } from 'react'
import { flow } from 'lodash-es'
import ActionButton from '@/app/components/base/action-button'
......@@ -55,31 +52,23 @@ const capitalizationLanguageNameMap: Record<string, string> = {
abc: 'ABC',
}
const getCorrectCapitalizationLanguageName = (language: string) => {
if (!language)
return 'Plain'
if (!language) return 'Plain'
if (language in capitalizationLanguageNameMap)
return capitalizationLanguageNameMap[language]
if (language in capitalizationLanguageNameMap) return capitalizationLanguageNameMap[language]
return language.charAt(0).toUpperCase() + language.substring(1)
}
const preprocessLaTeX = (content: string) => {
if (typeof content !== 'string')
return content
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(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`),
(str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`),
(str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`),
])(processedContent)
processedContent = flow([(str: string) => str.replace(/\\\[(.*?)\\\]/g, (_, equation) => `$$${equation}$$`), (str: string) => str.replace(/\\\[(.*?)\\\]/gs, (_, equation) => `$$${equation}$$`), (str: string) => str.replace(/\\\((.*?)\\\)/g, (_, equation) => `$$${equation}$$`), (str: string) => str.replace(/(^|[^\\])\$(.+?)\$/g, (_, prefix, equation) => `${prefix}$${equation}$`)])(processedContent)
codeBlocks.forEach((block) => {
codeBlocks.forEach(block => {
processedContent = processedContent.replace('CODE_BLOCK_PLACEHOLDER', block)
})
......@@ -89,10 +78,7 @@ const preprocessLaTeX = (content: string) => {
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>'),
])(content)
return flow([(str: string) => str.replace(thinkOpenTagRegex, '<details data-think=true>\n'), (str: string) => str.replace(thinkCloseTagRegex, '\n[ENDTHINKFLAG]</details>')])(content)
}
export function PreCode(props: { children: any }) {
......@@ -100,9 +86,7 @@ export function PreCode(props: { children: any }) {
return (
<pre ref={ref}>
<span
className="copy-code-button"
></span>
<span className="copy-code-button"></span>
{props.children}
</pre>
)
......@@ -132,13 +116,11 @@ const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any
if (language === 'echarts') {
try {
return JSON.parse(str)
}
catch { }
} catch {}
try {
// eslint-disable-next-line no-new-func, sonarjs/code-eval
return new Function(`return ${str}`)()
}
catch { }
} catch {}
}
return JSON.parse('{"title":{"text":"ECharts error - Wrong option."}}')
}, [language, children])
......@@ -147,8 +129,7 @@ const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any
const content = String(children).replace(/\n$/, '')
switch (language) {
case 'mermaid':
if (isSVG)
return <Flowchart PrimitiveCode={content} />
if (isSVG) return <Flowchart PrimitiveCode={content} />
break
case 'echarts':
return (
......@@ -186,8 +167,7 @@ const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any
}}
language={match?.[1]}
showLineNumbers
PreTag="div"
>
PreTag="div">
{content}
</SyntaxHighlighter>
)
......@@ -195,14 +175,18 @@ const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any
}, [children, language, isSVG, chartData, props, theme, match])
if (inline || !match)
return <code {...props} className={className}>{children}</code>
return (
<code {...props} className={className}>
{children}
</code>
)
return (
<div className='relative'>
<div className='flex h-8 items-center justify-between rounded-t-[10px] border-b border-divider-subtle bg-components-input-bg-normal p-1 pl-3'>
<div className='system-xs-semibold-uppercase text-text-secondary'>{languageShowName}</div>
<div className='flex items-center gap-1'>
{(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
<div className="relative">
<div className="flex h-8 items-center justify-between rounded-t-[10px] border-b border-divider-subtle bg-components-input-bg-normal p-1 pl-3">
<div className="system-xs-semibold-uppercase text-text-secondary">{languageShowName}</div>
<div className="flex items-center gap-1">
{['mermaid', 'svg'].includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
<ActionButton>
<CopyIcon content={String(children).replace(/\n$/, '')} />
</ActionButton>
......@@ -216,16 +200,14 @@ CodeBlock.displayName = 'CodeBlock'
const VideoBlock: 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)
return null
if (srcs.length === 0) return null
return <VideoGallery key={srcs.join()} srcs={srcs} />
})
VideoBlock.displayName = 'VideoBlock'
const AudioBlock: 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)
return null
if (srcs.length === 0) return null
return <AudioGallery key={srcs.join()} srcs={srcs} />
})
AudioBlock.displayName = 'AudioBlock'
......@@ -243,11 +225,7 @@ const Paragraph = (paragraph: any) => {
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>
)
}
{Array.isArray(paragraph.children) && paragraph.children.length > 1 && <div className="mt-2">{paragraph.children.slice(1)}</div>}
</div>
)
}
......@@ -255,7 +233,11 @@ const Paragraph = (paragraph: any) => {
}
const Img = ({ src }: any) => {
return <div className="markdown-img-wrapper"><ImageGallery srcs={[src]} /></div>
return (
<div className="markdown-img-wrapper">
<ImageGallery srcs={[src]} />
</div>
)
}
const Link = ({ node, children, ...props }: any) => {
......@@ -263,55 +245,49 @@ const Link = ({ node, children, ...props }: any) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { onSend } = useChatContext()
const hidden_text = decodeURIComponent(node.properties.href.toString().split('abbr:')[1])
return <abbr className="cursor-pointer underline !decoration-primary-700 decoration-dashed" onClick={() => onSend?.(hidden_text)} title={node.children[0]?.value || ''}>{node.children[0]?.value || ''}</abbr>
}
else {
return (
<abbr className="cursor-pointer underline !decoration-primary-700 decoration-dashed" onClick={() => onSend?.(hidden_text)} title={node.children[0]?.value || ''}>
{node.children[0]?.value || ''}
</abbr>
)
} else {
const href = node.properties?.href?.toString() || ''
const isImage = /\.(jpe?g|png|gif|webp|bmp|svg)(\?.*)?$/i.test(href)
return (
<div>
{isImage ? (
Img({ src: href })
) : (
<a {...props} target="_blank" className="cursor-pointer underline !decoration-primary-700 decoration-dashed">{children || 'Download'}</a>
)}
return isImage ? (
<div className="markdown-img-wrapper">
<ImageGallery srcs={[href]} />
</div>
) : (
<a {...props} target="_blank" className="cursor-pointer underline !decoration-primary-700 decoration-dashed">
{children || 'Download'}
</a>
)
// return <a {...props} target="_blank" className="cursor-pointer underline !decoration-primary-700 decoration-dashed">{children || 'Download'}</a>
}
}
export function Markdown(props: { content: string; className?: string; customDisallowedElements?: string[] }) {
const latexContent = flow([
preprocessThinkTag,
preprocessLaTeX,
])(props.content)
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,
]}
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) => {
return tree => {
const iterate = (node: any) => {
if (node.type === 'element' && node.properties?.ref)
delete node.properties.ref
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)
if (node.children) node.children.forEach(iterate)
}
tree.children.forEach(iterate)
}
......@@ -329,8 +305,7 @@ export function Markdown(props: { content: string; className?: string; customDis
form: MarkdownForm,
script: ScriptBlock as any,
details: ThinkBlock,
}}
>
}}>
{/* Markdown detect has problem. */}
{latexContent}
</ReactMarkdown>
......@@ -357,7 +332,12 @@ export default class ErrorBoundary extends Component {
// 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>
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
......
......@@ -47,6 +47,7 @@ const nextConfig = {
]
},
output: 'standalone',
allowedDevOrigins: ['192.168.1.237']
}
module.exports = withMDX(nextConfig)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!