Commit d3a08eca by liimin

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

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