diff --git a/package.json b/package.json index 7c7364018..095b35192 100644 --- a/package.json +++ b/package.json @@ -38,9 +38,9 @@ "circular-dependency-plugin": "^5.2.2", "dekko": "^0.2.1", "father": "^4.6.0", + "gh-pages": "^6.3.0", "husky": "^9.1.6", "lint-staged": "^16.1.5", - "gh-pages": "^6.3.0", "marked-emoji": "^2.0.1", "prettier": "^3.3.3", "react-markdown": "^10.1.0", @@ -49,7 +49,7 @@ "size-limit": [ { "path": "./packages/x/dist/antdx.min.js", - "limit": "350 KiB" + "limit": "500 KiB" }, { "path": "./packages/x-sdk/dist/x-sdk.min.js", @@ -57,19 +57,11 @@ }, { "path": "./packages/x-markdown/dist/x-markdown.min.js", - "limit": "350 KiB" - }, - { - "path": "./packages/x-markdown/dist/plugins/code-high-light.min.js", - "limit": "700 KiB" + "limit": "150 KiB" }, { "path": "./packages/x-markdown/dist/plugins/latex.min.js", - "limit": "700 KiB" - }, - { - "path": "./packages/x-markdown/dist/plugins/mermaid.min.js", - "limit": "900 KiB" + "limit": "300 KiB" } ], "description": "Craft AI-driven interfaces effortlessly", @@ -89,4 +81,4 @@ "@emotion/hash": "^0.9.2", "react-is": "^18.3.1" } -} \ No newline at end of file +} diff --git a/packages/x-markdown/.fatherrc.ts b/packages/x-markdown/.fatherrc.ts index f18bddfa1..8b509b875 100644 --- a/packages/x-markdown/.fatherrc.ts +++ b/packages/x-markdown/.fatherrc.ts @@ -46,15 +46,6 @@ export default defineConfig({ filename: 'x-markdown', }, }, - 'src/plugins/HighlightCode/index.tsx': { - name: 'HighlightCode', - sourcemap: true, - generateUnminified: true, - output: { - path: 'dist/plugins', - filename: 'code-high-light', - }, - }, 'src/plugins/Latex/index.ts': { name: 'Latex', sourcemap: true, @@ -64,15 +55,6 @@ export default defineConfig({ filename: 'latex', }, }, - 'src/plugins/Mermaid/index.tsx': { - name: 'Mermaid', - sourcemap: true, - generateUnminified: true, - output: { - path: 'dist/plugins', - filename: 'mermaid', - }, - }, }, bundler: 'webpack', // bundler: 'utoopack', @@ -89,17 +71,7 @@ export default defineConfig({ commonjs: 'react-dom', commonjs2: 'react-dom', }, - '@ant-design/cssinjs': { - root: 'antdCssinjs', - commonjs: 'antdCssinjs', - commonjs2: 'antdCssinjs', - }, }, - // externals: { - // react: 'React', - // 'react-dom': 'ReactDOM', - // '@ant-design/cssinjs': 'antdCssinjs', - // }, transformRuntime: { absoluteRuntime: process.cwd(), }, @@ -116,26 +88,12 @@ export default defineConfig({ memo.plugin('circular-dependency-checker').use(CircularDependencyPlugin, [ { failOnError: true, - exclude: /node_modules[\\/](chevrotain|d3-.*|langium)/, }, ]); memo.plugin('duplicate-package-checker').use(DuplicatePackageCheckerPlugin, [ { verbose: true, emitError: true, - exclude: (instance: any) => { - // 排除特定包 - if ( - instance.name === 'cose-base' || - instance.name === 'layout-base' || - instance.name.startsWith('d3-') || - instance.name === 'internmap' - ) { - return true; - } - - return false; - }, }, ]); } diff --git a/packages/x-markdown/package.json b/packages/x-markdown/package.json index 79f4b9a72..e33162b4c 100644 --- a/packages/x-markdown/package.json +++ b/packages/x-markdown/package.json @@ -13,14 +13,12 @@ "test": "jest --config .jest.js --no-cache --collect-coverage", "coverage": "jest --config .jest.js --no-cache --collect-coverage --coverage", "plugin:meta": "tsx scripts/generate-plugin-meta.ts", - "prestart": "npm run version && npm run token:statistic && npm run plugin:meta && npm run token:meta", + "prestart": "npm run version && npm run plugin:meta", "precompile": "npm run prestart", "version": "tsx scripts/generate-version.ts", "test:dekko": "tsx ./tests/dekko/index.test.ts", "clean": "rm -rf es lib coverage plugins dist themes", - "test:package-diff": "antd-tools run package-diff", - "token:meta": "tsx scripts/generate-token-meta.ts", - "token:statistic": "tsx scripts/collect-token-statistic.ts" + "test:package-diff": "antd-tools run package-diff" }, "sideEffects": false, "main": "lib/index.js", @@ -49,19 +47,11 @@ "license": "MIT", "description": "placeholder for @ant-design/x-markdown", "dependencies": { - "@ant-design/cssinjs": "^2.0.1", - "@ant-design/cssinjs-utils": "^2.0.2", - "@ant-design/fast-color": "^3.0.0", - "@ant-design/icons": "^6.0.0", - "@ant-design/x": "*", "classnames": "^2.5.1", "dompurify": "^3.2.6", "html-react-parser": "^5.2.5", "katex": "^0.16.22", - "lodash.throttle": "^4.1.1", - "marked": "^15.0.12", - "mermaid": "^11.11.0", - "react-syntax-highlighter": "^15.6.1" + "marked": "^15.0.12" }, "devDependencies": { "@types/dompurify": "^3.0.5", @@ -76,7 +66,6 @@ "react-dom": "^19.0.0" }, "peerDependencies": { - "antd": "^6.0.1", "react": ">=18.0.0", "react-dom": ">=18.0.0" }, diff --git a/packages/x-markdown/scripts/collect-token-statistic.ts b/packages/x-markdown/scripts/collect-token-statistic.ts deleted file mode 100644 index 5d011adfa..000000000 --- a/packages/x-markdown/scripts/collect-token-statistic.ts +++ /dev/null @@ -1,53 +0,0 @@ -/* eslint-disable no-console */ - -import { statistic } from '@ant-design/cssinjs-utils'; -import { theme } from 'antd'; -import chalk from 'chalk'; -import cliProgress from 'cli-progress'; -import fs from 'fs-extra'; -import React from 'react'; -import ReactDOMServer from 'react-dom/server'; -import { generateCssinjs, styleFiles } from './generate-cssinjs'; - -console.log(`🪄 Collecting token statistics...`); - -const bar = new cliProgress.SingleBar( - { - format: `🪄 Collecting by component: [${chalk.cyan('{bar}')}] {component} | {value}/{total}`, - }, - cliProgress.Presets.rect, -); - -bar.start(styleFiles.length, 0); - -(async () => { - await generateCssinjs({ - key: 'file', - beforeRender(componentName: string) { - bar.increment({ component: componentName }); - }, - render(Component: any) { - ReactDOMServer.renderToString(React.createElement(Component)); - // Render wireframe - const wireframeToken = { ...theme.defaultConfig.token, wireframe: true }; - ReactDOMServer.renderToString( - React.createElement( - theme._internalContext.Provider, - { - value: { - token: wireframeToken, - override: { - override: wireframeToken, - }, - }, - }, - React.createElement(Component), - ), - ); - }, - }); - bar.stop(); - const tokenPath = `${process.cwd()}/src/plugins/version/token.json`; - fs.writeJsonSync(tokenPath, statistic, 'utf8'); - console.log(chalk.green(`✅ Collected token statistics successfully, check it in`), tokenPath); -})(); diff --git a/packages/x-markdown/scripts/generate-cssinjs.ts b/packages/x-markdown/scripts/generate-cssinjs.ts deleted file mode 100644 index 24a2bcd3b..000000000 --- a/packages/x-markdown/scripts/generate-cssinjs.ts +++ /dev/null @@ -1,48 +0,0 @@ -import url from 'node:url'; -import { globSync } from 'glob'; -import path from 'path'; -import React from 'react'; - -type StyleFn = (prefix?: string) => void; - -interface GenCssinjsOptions { - key: string; - render: (component: React.FC) => void; - beforeRender?: (componentName: string) => void; -} - -export const styleFiles = globSync( - path - .join( - process.cwd(), - 'src/plugins/!(version|config-provider|icon|auto-complete|col|row|time-picker|qrcode)/style/index.?(ts|tsx)', - ) - .split(path.sep) - .join('/'), -); - -export const generateCssinjs = ({ key, beforeRender, render }: GenCssinjsOptions) => - Promise.all( - styleFiles.map(async (file) => { - const absPath = url.pathToFileURL(file).href; - const pathArr = file.split('/'); - const styleIndex = pathArr.lastIndexOf('style'); - const componentName = pathArr[styleIndex - 1]; - let useStyle: StyleFn = () => {}; - if (file.includes('grid')) { - const { useColStyle, useRowStyle } = await import(absPath); - useStyle = (prefixCls) => { - useRowStyle(prefixCls); - useColStyle(prefixCls); - }; - } else { - useStyle = (await import(absPath)).default; - } - const Demo: React.FC = () => { - useStyle(`${key}-${componentName}`); - return React.createElement('div'); - }; - beforeRender?.(componentName); - render?.(Demo); - }), - ); diff --git a/packages/x-markdown/scripts/generate-plugin-meta.ts b/packages/x-markdown/scripts/generate-plugin-meta.ts index 12c404277..4bba6c2c9 100644 --- a/packages/x-markdown/scripts/generate-plugin-meta.ts +++ b/packages/x-markdown/scripts/generate-plugin-meta.ts @@ -17,6 +17,7 @@ function getPluginMeta(list?: DeclarationReflection[]) { }; }); } + const main = async () => { const app = await (Application as any).bootstrap( { diff --git a/packages/x-markdown/scripts/generate-token-meta.ts b/packages/x-markdown/scripts/generate-token-meta.ts deleted file mode 100644 index 5dd904073..000000000 --- a/packages/x-markdown/scripts/generate-token-meta.ts +++ /dev/null @@ -1,144 +0,0 @@ -import fs from 'fs-extra'; -import type { DeclarationReflection } from 'typedoc'; -import { Application, TSConfigReader, TypeDocReader } from 'typedoc'; - -interface TokenMeta { - seed: ReturnType; - map: ReturnType; - alias: ReturnType; - components: Record>; -} - -function getTokenList(list?: DeclarationReflection[], source?: string) { - return (list || []) - .filter( - (item) => - !item.comment?.blockTags.some( - (tag) => tag.tag === '@internal' || tag.tag === '@private' || tag.tag === '@deprecated', - ), - ) - .map((item) => ({ - source, - token: item.name, - type: item?.type?.toString(), - desc: - item.comment?.blockTags - ?.find((tag) => tag.tag === '@desc') - ?.content.reduce((result, str) => result.concat(str.text), '') || '', - descEn: - item.comment?.blockTags - ?.find((tag) => tag.tag === '@descEN') - ?.content.reduce((result, str) => result.concat(str.text), '') || '', - name: - item.comment?.blockTags - ?.find((tag) => tag.tag === '@nameZH') - ?.content.reduce((result, str) => result.concat(str.text), '') || '', - nameEn: - item.comment?.blockTags - ?.find((tag) => tag.tag === '@nameEN') - ?.content.reduce((result, str) => result.concat(str.text), '') || '', - })); -} - -const main = async () => { - const app = await (Application as any).bootstrap( - { - // typedoc options here - entryPoints: [ - 'src/plugins/theme/interface/index.ts', - 'src/plugins/theme/interface/components.ts', - ], - skipErrorChecking: true, - logLevel: 'Error', - }, - [new TSConfigReader(), new TypeDocReader()], - ); - - const project = await app.convert(); - - if (project) { - // Project may not have converted correctly - const output = 'src/plugins/version/token-meta.json'; - const tokenMeta: TokenMeta = { - seed: [], - map: [], - alias: [], - components: {}, - }; - - // eslint-disable-next-line no-restricted-syntax - project?.children?.forEach((file: any) => { - // Global Token - if (file.name === 'index') { - let presetColors: string[] = []; - - file.children?.forEach((type: any) => { - if (type.name === 'SeedToken') { - tokenMeta.seed = getTokenList(type.children, 'seed'); - } else if (type.name === 'MapToken') { - tokenMeta.map = getTokenList(type.children, 'map'); - } else if (type.name === 'AliasToken') { - tokenMeta.alias = getTokenList(type.children, 'alias'); - } else if (type.name === 'PresetColors') { - presetColors = (type?.type as any)?.target?.elements?.map((item: any) => item.value); - } - }); - - // Exclude preset colors - tokenMeta.seed = tokenMeta.seed.filter( - (item) => !presetColors.some((color) => item.token.startsWith(color)), - ); - tokenMeta.map = tokenMeta.map.filter( - (item) => !presetColors.some((color) => item.token.startsWith(color)), - ); - tokenMeta.alias = tokenMeta.alias.filter( - (item) => !presetColors.some((color) => item.token.startsWith(color)), - ); - - tokenMeta.alias = tokenMeta.alias.filter( - (item) => !tokenMeta.map.some((mapItem) => mapItem.token === item.token), - ); - tokenMeta.map = tokenMeta.map.filter( - (item) => !tokenMeta.seed.some((seedItem) => seedItem.token === item.token), - ); - } else { - const componentTokens = file.children?.filter((item: any) => - item?.name?.includes('PluginToken'), - ); - componentTokens.forEach( - (componentToken: { name: string; children: DeclarationReflection[] | undefined }) => { - const component = componentToken.name.replace('PluginToken', ''); - if (componentToken) { - tokenMeta.components[component] = getTokenList(componentToken.children, component); - } - }, - ); - } - }); - - const finalMeta = Object.entries(tokenMeta).reduce((acc, [key, value]) => { - if (key !== 'components') { - (value as any[]).forEach((item) => { - acc.global = acc.global || {}; - acc.global[item.token] = { - name: item.name, - nameEn: item.nameEn, - desc: item.desc, - descEn: item.descEn, - type: item.type, - source: key, - }; - }); - } else { - acc.components = value; - } - return acc; - }, {} as any); - - fs.writeJsonSync(output, finalMeta, 'utf8'); - // eslint-disable-next-line no-console - console.log(`✅ Token Meta has been written to ${output}`); - } -}; - -main(); diff --git a/packages/x-markdown/src/XMarkdown/__test__/__snapshots__/index.test.tsx.snap b/packages/x-markdown/src/XMarkdown/__test__/__snapshots__/index.test.tsx.snap index c1efa6868..21109cd0f 100644 --- a/packages/x-markdown/src/XMarkdown/__test__/__snapshots__/index.test.tsx.snap +++ b/packages/x-markdown/src/XMarkdown/__test__/__snapshots__/index.test.tsx.snap @@ -3,8 +3,7 @@ exports[`XMarkdown animation parent is custom components 1`] = `

This is Text. @@ -16,8 +15,7 @@ exports[`XMarkdown animation parent is custom components 1`] = ` exports[`XMarkdown animation parent is not custom components 1`] = `

  • @@ -53,8 +50,7 @@ exports[`XMarkdown support checkbox is checked 1`] = ` exports[`XMarkdown support checkbox not checked 1`] = `
    • diff --git a/packages/x-markdown/src/XMarkdown/__test__/index.test.tsx b/packages/x-markdown/src/XMarkdown/__test__/index.test.tsx index 461807130..fdc8b6df0 100644 --- a/packages/x-markdown/src/XMarkdown/__test__/index.test.tsx +++ b/packages/x-markdown/src/XMarkdown/__test__/index.test.tsx @@ -194,7 +194,7 @@ describe('XMarkdown', () => { // XMarkdown wraps content in a div with class "ant-x-markdown" const wrapper = container.firstChild as HTMLElement; - expect(wrapper).toHaveClass('ant-x-markdown'); + expect(wrapper).toHaveClass('x-markdown'); expect(wrapper.innerHTML).toBe('
      This is a paragraph.
      \n'); }); diff --git a/packages/x-markdown/src/XMarkdown/index.tsx b/packages/x-markdown/src/XMarkdown/index.tsx index c9c2f8ab9..a9402fe2c 100644 --- a/packages/x-markdown/src/XMarkdown/index.tsx +++ b/packages/x-markdown/src/XMarkdown/index.tsx @@ -1,6 +1,5 @@ import classnames from 'classnames'; import React, { useMemo } from 'react'; -import useXProviderContext from '../hooks/use-x-provider-context'; import { Parser, Renderer } from './core'; import { useStreaming } from './hooks'; import { XMarkdownProps } from './interface'; @@ -15,7 +14,6 @@ const XMarkdown: React.FC = React.memo((props) => { content, children, rootClassName, - prefixCls: customizePrefixCls, className, style, openLinksInNewTab, @@ -23,19 +21,7 @@ const XMarkdown: React.FC = React.memo((props) => { } = props; // ============================ style ============================ - const { direction: contextDirection, getPrefixCls } = useXProviderContext(); - - const prefixCls = getPrefixCls('x-markdown', customizePrefixCls); - - const mergedCls = classnames(prefixCls, 'x-markdown', rootClassName, className); - - const mergedStyle: React.CSSProperties = useMemo( - () => ({ - direction: contextDirection === 'rtl' ? 'rtl' : 'ltr', - ...style, - }), - [contextDirection, style], - ); + const mergedCls = classnames('x-markdown', rootClassName, className); // ============================ Streaming ============================ const displayContent = useStreaming(content || children || '', { streaming, components }); @@ -69,7 +55,7 @@ const XMarkdown: React.FC = React.memo((props) => { if (!displayContent) return null; return ( -
      +
      {renderer.render(htmlString)}
      ); diff --git a/packages/x-markdown/src/hooks/use-x-provider-context.ts b/packages/x-markdown/src/hooks/use-x-provider-context.ts deleted file mode 100644 index 97adbfb0a..000000000 --- a/packages/x-markdown/src/hooks/use-x-provider-context.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { ConfigProvider } from 'antd'; -import React from 'react'; - -export const defaultPrefixCls = 'ant'; - -function useXProviderContext() { - const { getPrefixCls, direction, csp, iconPrefixCls, theme } = React.useContext( - ConfigProvider.ConfigContext, - ); - - return { - theme, - getPrefixCls, - direction, - csp, - iconPrefixCls, - }; -} - -export default useXProviderContext; diff --git a/packages/x-markdown/src/plugins/HighlightCode/__test__/index.test.tsx b/packages/x-markdown/src/plugins/HighlightCode/__test__/index.test.tsx deleted file mode 100644 index b2eff1bb1..000000000 --- a/packages/x-markdown/src/plugins/HighlightCode/__test__/index.test.tsx +++ /dev/null @@ -1,180 +0,0 @@ -import { render } from '@testing-library/react'; -import React from 'react'; -import XMarkdown from '../../../XMarkdown'; -import HighlightCode from '..'; - -jest.mock('react', () => ({ - ...jest.requireActual('react'), - useId: () => 'mock-id-123', -})); - -describe('HighlightCode', () => { - it('render normal code', () => { - const content = `\`\`\`javascript -console.log("javascript"); -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return {children}; - }, - }} - />, - ); - expect(container.querySelector('pre')).toBeInTheDocument(); - expect(container.querySelector('code')).toBeInTheDocument(); - expect(container.textContent).toContain('console.log("javascript");'); - }); - - it('render normal code with header', () => { - const content = `\`\`\`javascript -console.log("javascript"); -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return {children}; - }, - }} - />, - ); - expect(container.querySelector('.ant-highlightCode-header')).toBeInTheDocument(); - expect(container.querySelector('.ant-highlightCode-header')?.textContent).toContain( - 'javascript', - ); - }); - - it('render normal code with custom header class', () => { - const content = `\`\`\`javascript -console.log("javascript"); -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return ( - - {children} - - ); - }, - }} - />, - ); - expect(container.querySelector('.customHeader')).toBeInTheDocument(); - }); - - it('render normal code with custom header', () => { - const content = `\`\`\`javascript -console.log("javascript"); -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return ( - custom header
      } - > - {children} - - ); - }, - }} - />, - ); - expect(container.querySelector('.myCustomClass')).toBeInTheDocument(); - expect(container.querySelector('.myCustomClass')?.textContent).toContain('custom header'); - }); - - it('render normal code with no header', () => { - const content = `\`\`\`javascript -console.log("javascript"); -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return ( - - {children} - - ); - }, - }} - />, - ); - expect(container.querySelector('.ant-highlightCode-header')).toBeNull(); - }); - - it('render normal code with no children', () => { - const { container } = render({''}); - expect(container.querySelector('code')).toBeNull(); - }); - - it('mermaid code is render as text', () => { - const content = `\`\`\`mermaid -graph TD; A-->B; -\`\`\``; - - const { container } = render( - ) => { - const { class: className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return {children}; - }, - }} - />, - ); - expect(container.querySelector('pre')).toBeInTheDocument(); - expect(container.textContent).toContain('graph TD; A-->B;'); - }); - - it('should handle undefined lang', () => { - const content = ` - \`\`\` -plain text -\`\`\``; - - const { container } = render( - ) => { - const { className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - return {children}; - }, - }} - />, - ); - expect(container.querySelector('pre')).toBeInTheDocument(); - expect(container.textContent).toContain('plain text'); - }); -}); diff --git a/packages/x-markdown/src/plugins/HighlightCode/style/index.ts b/packages/x-markdown/src/plugins/HighlightCode/style/index.ts deleted file mode 100644 index 48a9db221..000000000 --- a/packages/x-markdown/src/plugins/HighlightCode/style/index.ts +++ /dev/null @@ -1,69 +0,0 @@ -import type { CSSObject } from '@ant-design/cssinjs'; -import { mergeToken } from '@ant-design/cssinjs-utils'; -import { genStyleHooks } from '../../theme/genStyleUtils'; -import type { GenerateStyle } from '../../theme/interface'; -import type { FullToken, GetDefaultToken } from '../../theme/useToken'; - -export interface HighlightCodeToken extends FullToken<'HighlightCode'> {} - -const genHighlightCodeStyle: GenerateStyle = ( - token: HighlightCodeToken, -): CSSObject => { - const { componentCls } = token; - - return { - [componentCls]: { - [`${componentCls}-header`]: { - display: 'flex', - alignItems: 'center', - justifyContent: 'space-between', - color: token.colorTextTitle, - background: token.colorBgTitle, - padding: token.paddingSM, - borderTopLeftRadius: token.borderRadius, - borderTopRightRadius: token.borderRadius, - }, - [`${componentCls}-code`]: { - borderBottomRightRadius: token.borderRadius, - borderBottomLeftRadius: token.borderRadius, - borderTopLeftRadius: 0, - borderTopRightRadius: 0, - background: token.colorBgContainer, - border: `1px solid ${token.colorBgTitle}`, - borderTop: 'none', - overflow: 'hidden', - 'pre,code': { - whiteSpace: 'pre', - fontSize: token.fontSize, - fontFamily: token.fontFamilyCode, - lineHeight: 2, - borderRadius: 0, - border: 'none', - }, - "code[class*='language-'],pre[class*='language-']": { - background: 'none', - }, - }, - [`&${componentCls}-rtl`]: { - direction: 'rtl', - }, - }, - }; -}; - -export const prepareComponentToken: GetDefaultToken<'HighlightCode'> = (token) => { - return { - colorBgTitle: token.colorFillContent, - colorBorderCode: token.colorBorderSecondary, - colorTextTitle: token.colorText, - }; -}; - -export default genStyleHooks<'HighlightCode'>( - 'HighlightCode', - (token) => { - const highlightCodeToken = mergeToken(token, {}); - return [genHighlightCodeStyle(highlightCodeToken)]; - }, - prepareComponentToken, -); diff --git a/packages/x-markdown/src/plugins/Latex/__test__/__snapshots__/index.test.tsx.snap b/packages/x-markdown/src/plugins/Latex/__test__/__snapshots__/index.test.tsx.snap index cadeda2cf..5e9593766 100644 --- a/packages/x-markdown/src/plugins/Latex/__test__/__snapshots__/index.test.tsx.snap +++ b/packages/x-markdown/src/plugins/Latex/__test__/__snapshots__/index.test.tsx.snap @@ -3,8 +3,7 @@ exports[`LaTeX Plugin should handle LaTeX with surrounding text 1`] = `

      This is an equation: @@ -117,8 +116,7 @@ exports[`LaTeX Plugin should handle LaTeX with surrounding text 1`] = ` exports[`LaTeX Plugin should handle align* syntax replacement 1`] = `

      Just plain text @@ -748,8 +744,7 @@ exports[`LaTeX Plugin should handle empty content 1`] = `

      `; exports[`LaTeX Plugin should handle mixed LaTeX syntaxes 1`] = `

      Inline: @@ -966,8 +961,7 @@ exports[`LaTeX Plugin should handle mixed LaTeX syntaxes 1`] = ` exports[`LaTeX Plugin should handle multiple LaTeX formulas 1`] = `

      latex: @@ -1174,8 +1167,7 @@ exports[`LaTeX Plugin should not throw error by default 1`] = ` exports[`LaTeX Plugin should render block LaTeX with $$..$$ syntax 1`] = `

      latex: @@ -1681,8 +1671,7 @@ exports[`LaTeX Plugin should render inline LaTeX with $$\\n..\\n$$ syntax 1`] = exports[`LaTeX Plugin should render inline LaTeX with $..$ syntax 1`] = `

      latex: diff --git a/packages/x-markdown/src/plugins/theme/genStyleUtils.ts b/packages/x-markdown/src/plugins/theme/genStyleUtils.ts deleted file mode 100644 index eae95bf7d..000000000 --- a/packages/x-markdown/src/plugins/theme/genStyleUtils.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { genStyleUtils } from '@ant-design/cssinjs-utils'; -import useXProviderContext from '@ant-design/x/es/x-provider/hooks/use-x-provider-context'; -import type { AliasToken, SeedToken } from 'antd/es/theme/internal'; -import { ComponentTokenMap } from './interface/components'; -import { useInternalToken } from './useToken'; - -export const { genStyleHooks, genComponentStyleHook, genSubStyleComponent } = genStyleUtils< - ComponentTokenMap, - AliasToken, - SeedToken ->({ - usePrefix: () => { - const { getPrefixCls, iconPrefixCls } = useXProviderContext(); - return { - iconPrefixCls, - rootPrefixCls: getPrefixCls(), - }; - }, - useToken: () => { - const [theme, realToken, hashId, token, cssVar] = useInternalToken(); - return { theme, realToken, hashId, token, cssVar }; - }, - useCSP: () => { - const { csp } = useXProviderContext(); - return csp ?? {}; - }, - layer: { - name: 'antdx', - dependencies: ['antd'], - }, -}); diff --git a/packages/x-markdown/src/plugins/theme/interface/alias.ts b/packages/x-markdown/src/plugins/theme/interface/alias.ts deleted file mode 100644 index 180a09d89..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/alias.ts +++ /dev/null @@ -1,612 +0,0 @@ -import type * as React from 'react'; - -import type { MapToken } from './maps'; - -// ====================================================================== -// == Alias Token == -// ====================================================================== -// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 - -export interface AliasToken extends MapToken { - // Background - /** - * @nameZH 内容区域背景色(悬停) - * @nameEN Background color of content area (hover) - * @desc 控制内容区域背景色在鼠标悬停时的样式。 - * @descEN Control the style of background color of content area when mouse hovers over it. - */ - colorFillContentHover: string; - /** - * @nameZH 替代背景色 - * @nameEN Alternative background color - * @desc 控制元素替代背景色。 - * @descEN Control the alternative background color of element. - */ - colorFillAlter: string; - /** - * @nameZH 内容区域背景色 - * @nameEN Background color of content area - * @desc 控制内容区域的背景色。 - * @descEN Control the background color of content area. - */ - colorFillContent: string; - /** - * @nameZH 容器禁用态下的背景色 - * @nameEN Disabled container background color - * @desc 控制容器在禁用状态下的背景色。 - * @descEN Control the background color of container in disabled state. - */ - colorBgContainerDisabled: string; - /** - * @nameZH 文本悬停态背景色 - * @nameEN Text hover background color - * @desc 控制文本在悬停状态下的背景色。 - * @descEN Control the background color of text in hover state. - */ - colorBgTextHover: string; - /** - * @nameZH 文本激活态背景色 - * @nameEN Text active background color - * @desc 控制文本在激活状态下的背景色。 - * @descEN Control the background color of text in active state. - */ - colorBgTextActive: string; - - // Border - /** - * @nameZH 背景边框颜色 - * @nameEN Background border color - * @desc 控制元素背景边框的颜色。 - * @descEN Control the color of background border of element. - */ - colorBorderBg: string; - /** - * @nameZH 分割线颜色 - * @nameEN Separator Color - * @desc 用于作为分割线的颜色,此颜色和 colorBorderSecondary 的颜色一致,但是用的是透明色。 - * @descEN Used as the color of separator, this color is the same as colorBorderSecondary but with transparency. - */ - colorSplit: string; - - // Text - /** - * @nameZH 占位文本颜色 - * @nameEN Placeholder Text Color - * @desc 控制占位文本的颜色。 - * @descEN Control the color of placeholder text. - */ - colorTextPlaceholder: string; - /** - * @nameZH 禁用字体颜色 - * @nameEN Disabled Text Color - * @desc 控制禁用状态下的字体颜色。 - * @descEN Control the color of text in disabled state. - */ - colorTextDisabled: string; - /** - * @nameZH 标题字体颜色 - * @nameEN Heading Text Color - * @desc 控制标题字体颜色。 - * @descEN Control the font color of heading. - */ - colorTextHeading: string; - /** - * @nameZH 文本标签字体颜色 - * @nameEN Text label font color - * @desc 控制文本标签字体颜色。 - * @descEN Control the font color of text label. - */ - colorTextLabel: string; - /** - * @nameZH 文本描述字体颜色 - * @nameEN Text description font color - * @desc 控制文本描述字体颜色。 - * @descEN Control the font color of text description. - */ - colorTextDescription: string; - /** - * @nameZH 固定文本高亮颜色 - * @nameEN Fixed text highlight color - * @desc 控制带背景色的文本,例如 Primary Button 组件中的文本高亮颜色。 - * @descEN Control the highlight color of text with background color, such as the text in Primary Button components. - */ - colorTextLightSolid: string; - - /** - /** - * @nameZH 弱操作图标颜色 - * @nameEN Weak action icon color - * @desc 控制弱操作图标的颜色,例如 allowClear 或 Alert 关闭按钮。 - * @descEN Weak action. Such as `allowClear` or Alert close button - */ - colorIcon: string; - - /** */ - /** - * @nameZH 弱操作图标悬浮态颜色 - * @nameEN Weak action icon hover color - * @desc 控制弱操作图标在悬浮状态下的颜色,例如 allowClear 或 Alert 关闭按钮。 - * @descEN Weak action hover color. Such as `allowClear` or Alert close button - */ - colorIconHover: string; - - /** - * @nameZH 高亮颜色 - * @nameEN Highlight color - * @desc 控制页面元素高亮时的颜色。 - * @descEN Control the color of page element when highlighted. - */ - colorHighlight: string; - - /** - * @nameZH 输入组件的 Outline 颜色 - * @nameEN Input component outline color - * @desc 控制输入组件的外轮廓线颜色。 - * @descEN Control the outline color of input component. - */ - controlOutline: string; - - /** - * @nameZH 警告状态下的 Outline 颜色 - * @nameEN Warning outline color - * @desc 控制输入组件警告状态下的外轮廓线颜色。 - * @descEN Control the outline color of input component in warning state. - */ - colorWarningOutline: string; - - /** - * @nameZH 错误状态下的 Outline 颜色 - * @nameEN Error outline color - * @desc 控制输入组件错误状态下的外轮廓线颜色。 - * @descEN Control the outline color of input component in error state. - */ - colorErrorOutline: string; - - // Font - /** - * @nameZH 选择器、级联选择器等中的操作图标字体大小 - * @nameEN Operation icon font size in Select, Cascader, etc. - * @desc 控制选择器、级联选择器等中的操作图标字体大小。正常情况下与 fontSizeSM 相同。 - * @descEN Control the font size of operation icon in Select, Cascader, etc. Normally same as fontSizeSM. - */ - fontSizeIcon: number; - - /** - * @nameZH 标题类组件(如 h1、h2、h3)或选中项的字体粗细 - * @nameEN Font weight for heading components (such as h1, h2, h3) or selected item - * @desc 控制标题类组件(如 h1、h2、h3)或选中项的字体粗细。 - * @descEN Control the font weight of heading components (such as h1, h2, h3) or selected item. - */ - fontWeightStrong: number; - - // Control - - /** - * @nameZH 输入组件的外轮廓线宽度 - * @nameEN Input component outline width - * @desc 控制输入组件的外轮廓线宽度。 - * @descEN Control the outline width of input component. - */ - controlOutlineWidth: number; - - /** - * @nameZH 控制组件项在鼠标悬浮时的背景颜色 - * @nameEN Background color of control component item when hovering - * @desc 控制组件项在鼠标悬浮时的背景颜色。 - * @descEN Control the background color of control component item when hovering. - */ - controlItemBgHover: string; // Note. It also is a color - - /** - * @nameZH 控制组件项在激活状态下的背景颜色 - * @nameEN Background color of control component item when active - * @desc 控制组件项在激活状态下的背景颜色。 - * @descEN Control the background color of control component item when active. - */ - controlItemBgActive: string; // Note. It also is a color - - /** - * @nameZH 控制组件项在鼠标悬浮且激活状态下的背景颜色 - * @nameEN Background color of control component item when hovering and active - * @desc 控制组件项在鼠标悬浮且激活状态下的背景颜色。 - * @descEN Control the background color of control component item when hovering and active. - */ - controlItemBgActiveHover: string; // Note. It also is a color - - /** - * @nameZH 控制组件的交互大小 - * @nameEN Interactive size of control component - * @desc 控制组件的交互大小。 - * @descEN Control the interactive size of control component. - */ - controlInteractiveSize: number; - - /** - * @nameZH 控制组件项在禁用状态下的激活背景颜色 - * @nameEN Background color of control component item when active and disabled - * @desc 控制组件项在禁用状态下的激活背景颜色。 - * @descEN Control the background color of control component item when active and disabled. - */ - controlItemBgActiveDisabled: string; // Note. It also is a color - - // Line - /** - * @nameZH 线条宽度(聚焦态) - * @nameEN Line width(focus state) - * @desc 控制线条的宽度,当组件处于聚焦态时。 - * @descEN Control the width of the line when the component is in focus state. - */ - lineWidthFocus: number; - - // Padding - /** - * @nameZH 极小内间距 - * @nameEN Extra extra small padding - * @desc 控制元素的极小内间距。 - * @descEN Control the extra extra small padding of the element. - */ - paddingXXS: number; - /** - * @nameZH 特小内间距 - * @nameEN Extra small padding - * @desc 控制元素的特小内间距。 - * @descEN Control the extra small padding of the element. - */ - paddingXS: number; - /** - * @nameZH 小内间距 - * @nameEN Small padding - * @desc 控制元素的小内间距。 - * @descEN Control the small padding of the element. - */ - paddingSM: number; - /** - * @nameZH 内间距 - * @nameEN Padding - * @desc 控制元素的内间距。 - * @descEN Control the padding of the element. - */ - padding: number; - /** - * @nameZH 中等内间距 - * @nameEN Medium padding - * @desc 控制元素的中等内间距。 - * @descEN Control the medium padding of the element. - */ - paddingMD: number; - /** - * @nameZH 大内间距 - * @nameEN Large padding - * @desc 控制元素的大内间距。 - * @descEN Control the large padding of the element. - */ - paddingLG: number; - /** - * @nameZH 特大内间距 - * @nameEN Extra large padding - * @desc 控制元素的特大内间距。 - * @descEN Control the extra large padding of the element. - */ - paddingXL: number; - - // Padding Content - /** - * @nameZH 内容水平内间距(LG) - * @nameEN Content horizontal padding (LG) - * @desc 控制内容元素水平内间距,适用于大屏幕设备。 - * @descEN Control the horizontal padding of content element, suitable for large screen devices. - */ - paddingContentHorizontalLG: number; - /** - * @nameZH 内容水平内间距 - * @nameEN Content horizontal padding - * @desc 控制内容元素水平内间距。 - * @descEN Control the horizontal padding of content element. - */ - paddingContentHorizontal: number; - /** - * @nameZH 内容水平内间距(SM) - * @nameEN Content horizontal padding (SM) - * @desc 控制内容元素水平内间距,适用于小屏幕设备。 - * @descEN Control the horizontal padding of content element, suitable for small screen devices. - */ - paddingContentHorizontalSM: number; - /** - * @nameZH 内容垂直内间距(LG) - * @nameEN Content vertical padding (LG) - * @desc 控制内容元素垂直内间距,适用于大屏幕设备。 - * @descEN Control the vertical padding of content element, suitable for large screen devices. - */ - paddingContentVerticalLG: number; - /** - * @nameZH 内容垂直内间距 - * @nameEN Content vertical padding - * @desc 控制内容元素垂直内间距。 - * @descEN Control the vertical padding of content element. - */ - paddingContentVertical: number; - /** - * @nameZH 内容垂直内间距(SM) - * @nameEN Content vertical padding (SM) - * @desc 控制内容元素垂直内间距,适用于小屏幕设备。 - * @descEN Control the vertical padding of content element, suitable for small screen devices. - */ - paddingContentVerticalSM: number; - - // Margin - /** - * @nameZH 外边距 XXS - * @nameEN Margin XXS - * @desc 控制元素外边距,最小尺寸。 - * @descEN Control the margin of an element, with the smallest size. - */ - marginXXS: number; - /** - * @nameZH 外边距 XS - * @nameEN Margin XS - * @desc 控制元素外边距,小尺寸。 - * @descEN Control the margin of an element, with a small size. - */ - marginXS: number; - /** - * @nameZH 外边距 SM - * @nameEN Margin SM - * @desc 控制元素外边距,中小尺寸。 - * @descEN Control the margin of an element, with a medium-small size. - */ - marginSM: number; - /** - * @nameZH 外边距 - * @nameEN Margin - * @desc 控制元素外边距,中等尺寸。 - * @descEN Control the margin of an element, with a medium size. - */ - margin: number; - /** - * @nameZH 外边距 MD - * @nameEN Margin MD - * @desc 控制元素外边距,中大尺寸。 - * @descEN Control the margin of an element, with a medium-large size. - */ - marginMD: number; - /** - * @nameZH 外边距 LG - * @nameEN Margin LG - * @desc 控制元素外边距,大尺寸。 - * @descEN Control the margin of an element, with a large size. - */ - marginLG: number; - /** - * @nameZH 外边距 XL - * @nameEN Margin XL - * @desc 控制元素外边距,超大尺寸。 - * @descEN Control the margin of an element, with an extra-large size. - */ - marginXL: number; - /** - * @nameZH 外边距 XXL - * @nameEN Margin XXL - * @desc 控制元素外边距,最大尺寸。 - * @descEN Control the margin of an element, with the largest size. - */ - marginXXL: number; - - // =============== Legacy: should be remove =============== - /** - * @nameZH 加载状态透明度 - * @nameEN Loading opacity - * @desc 控制加载状态的透明度。 - * @descEN Control the opacity of the loading state. - */ - opacityLoading: number; - - /** - * @nameZH 一级阴影 - * @nameEN Box shadow - * @desc 控制元素阴影样式。 - * @descEN Control the box shadow style of an element. - */ - boxShadow: string; - /** - * @nameZH 二级阴影 - * @nameEN Secondary box shadow - * @desc 控制元素二级阴影样式。 - * @descEN Control the secondary box shadow style of an element. - */ - boxShadowSecondary: string; - /** - * @nameZH 三级阴影 - * @nameEN Tertiary box shadow - * @desc 控制元素三级盒子阴影样式。 - * @descEN Control the tertiary box shadow style of an element. - */ - boxShadowTertiary: string; - - /** - * @nameZH 链接文本装饰 - * @nameEN Link text decoration - * @desc 控制链接文本的装饰样式。 - * @descEN Control the text decoration style of a link. - */ - linkDecoration: React.CSSProperties['textDecoration']; - /** - * @nameZH 链接鼠标悬浮时文本装饰 - * @nameEN Link text decoration on mouse hover - * @desc 控制链接鼠标悬浮时文本的装饰样式。 - * @descEN Control the text decoration style of a link on mouse hover. - */ - linkHoverDecoration: React.CSSProperties['textDecoration']; - /** - * @nameZH 链接聚焦时文本装饰 - * @nameEN Link text decoration on focus - * @desc 控制链接聚焦时文本的装饰样式。 - * @descEN Control the text decoration style of a link on focus. - */ - linkFocusDecoration: React.CSSProperties['textDecoration']; - - /** - * @nameZH 控制水平内间距 - * @nameEN Control horizontal padding - * @desc 控制元素水平内间距。 - * @descEN Control the horizontal padding of an element. - */ - controlPaddingHorizontal: number; - /** - * @nameZH 控制中小尺寸水平内间距 - * @nameEN Control horizontal padding with a small-medium size - * @desc 控制元素中小尺寸水平内间距。 - * @descEN Control the horizontal padding of an element with a small-medium size. - */ - controlPaddingHorizontalSM: number; - - // Media queries breakpoints - /** - * @nameZH 屏幕宽度(像素) - 超小屏幕 - * @nameEN Screen width (pixels) - Extra small screens - * @desc 控制超小屏幕的屏幕宽度。 - * @descEN Control the screen width of extra small screens. - */ - screenXS: number; - /** - * @nameZH 屏幕宽度(像素) - 超小屏幕最小值 - * @nameEN Screen width (pixels) - Extra small screens minimum value - * @desc 控制超小屏幕的最小宽度。 - * @descEN Control the minimum width of extra small screens. - */ - screenXSMin: number; - /** - * @nameZH 屏幕宽度(像素) - 超小屏幕最大值 - * @nameEN Screen width (pixels) - Extra small screens maximum value - * @desc 控制超小屏幕的最大宽度。 - * @descEN Control the maximum width of extra small screens. - */ - screenXSMax: number; - /** - * @nameZH 屏幕宽度(像素) - 小屏幕 - * @nameEN Screen width (pixels) - Small screens - * @desc 控制小屏幕的屏幕宽度。 - * @descEN Control the screen width of small screens. - */ - screenSM: number; - /** - * @nameZH 屏幕宽度(像素) - 小屏幕最小值 - * @nameEN Screen width (pixels) - Small screens minimum value - * @desc 控制小屏幕的最小宽度。 - * @descEN Control the minimum width of small screens. - */ - screenSMMin: number; - /** - * @nameZH 屏幕宽度(像素) - 小屏幕最大值 - * @nameEN Screen width (pixels) - Small screens maximum value - * @desc 控制小屏幕的最大宽度。 - * @descEN Control the maximum width of small screens. - */ - screenSMMax: number; - /** - * @nameZH 屏幕宽度(像素) - 中等屏幕 - * @nameEN Screen width (pixels) - Medium screens - * @desc 控制中等屏幕的屏幕宽度。 - * @descEN Control the screen width of medium screens. - */ - screenMD: number; - /** - * @nameZH 屏幕宽度(像素) - 中等屏幕最小值 - * @nameEN Screen width (pixels) - Medium screens minimum value - * @desc 控制中等屏幕的最小宽度。 - * @descEN Control the minimum width of medium screens. - */ - screenMDMin: number; - /** - * @nameZH 屏幕宽度(像素) - 中等屏幕最大值 - * @nameEN Screen width (pixels) - Medium screens maximum value - * @desc 控制中等屏幕的最大宽度。 - * @descEN Control the maximum width of medium screens. - */ - screenMDMax: number; - /** - * @nameZH 屏幕宽度(像素) - 大屏幕 - * @nameEN Screen width (pixels) - Large screens - * @desc 控制大屏幕的屏幕宽度。 - * @descEN Control the screen width of large screens. - */ - screenLG: number; - /** - * @nameZH 屏幕宽度(像素) - 大屏幕最小值 - * @nameEN Screen width (pixels) - Large screens minimum value - * @desc 控制大屏幕的最小宽度。 - * @descEN Control the minimum width of large screens. - */ - screenLGMin: number; - /** - * @nameZH 屏幕宽度(像素) - 大屏幕最大值 - * @nameEN Screen width (pixels) - Large screens maximum value - * @desc 控制大屏幕的最大宽度。 - * @descEN Control the maximum width of large screens. - */ - screenLGMax: number; - /** - * @nameZH 屏幕宽度(像素) - 超大屏幕 - * @nameEN Screen width (pixels) - Extra large screens - * @desc 控制超大屏幕的屏幕宽度。 - * @descEN Control the screen width of extra large screens. - */ - screenXL: number; - /** - * @nameZH 屏幕宽度(像素) - 超大屏幕最小值 - * @nameEN Screen width (pixels) - Extra large screens minimum value - * @desc 控制超大屏幕的最小宽度。 - * @descEN Control the minimum width of extra large screens. - */ - screenXLMin: number; - /** - * @nameZH 屏幕宽度(像素) - 超大屏幕最大值 - * @nameEN Screen width (pixels) - Extra large screens maximum value - * @desc 控制超大屏幕的最大宽度。 - * @descEN Control the maximum width of extra large screens. - */ - screenXLMax: number; - /** - * @nameZH 屏幕宽度(像素) - 超超大屏幕 - * @nameEN Screen width (pixels) - Extra extra large screens - * @desc 控制超超大屏幕的屏幕宽度。 - * @descEN Control the screen width of extra extra large screens. - */ - screenXXL: number; - /** - * @nameZH 屏幕宽度(像素) - 超超大屏幕最小值 - * @nameEN Screen width (pixels) - Extra extra large screens minimum value - * @desc 控制超超大屏幕的最小宽度。 - * @descEN Control the minimum width of extra extra large screens. - */ - screenXXLMin: number; - - /** - * @deprecated - * Used for DefaultButton, Switch which has default outline - * @desc 默认样式的 Outline 颜色 - * @descEN Default style outline color. - */ - controlTmpOutline: string; - - // FIXME: component box-shadow, should be removed - /** @internal */ - boxShadowPopoverArrow: string; - /** @internal */ - boxShadowCard: string; - /** @internal */ - boxShadowDrawerRight: string; - /** @internal */ - boxShadowDrawerLeft: string; - /** @internal */ - boxShadowDrawerUp: string; - /** @internal */ - boxShadowDrawerDown: string; - /** @internal */ - boxShadowTabsOverflowLeft: string; - /** @internal */ - boxShadowTabsOverflowRight: string; - /** @internal */ - boxShadowTabsOverflowTop: string; - /** @internal */ - boxShadowTabsOverflowBottom: string; -} diff --git a/packages/x-markdown/src/plugins/theme/interface/components.ts b/packages/x-markdown/src/plugins/theme/interface/components.ts deleted file mode 100644 index e01f47936..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/components.ts +++ /dev/null @@ -1,48 +0,0 @@ -export interface HighlightCodePluginToken { - /** - * @desc 标题背景颜色 - * @descEN Title background color - */ - colorBgTitle: string; - /** - * @desc 标题文本颜色 - * @descEN Title text color - */ - colorTextTitle: string; - /** - * @desc 代码块边框颜色 - * @descEN Code block border color - */ - colorBorderCode: string; -} - -export interface MermaidPluginToken { - /** - * @desc 标题背景颜色 - * @descEN Title background color - */ - colorBgTitle: string; - - /** - * @desc 标题文本颜色 - * @descEN Title text color - */ - colorTextTitle: string; - - /** - * @desc 代码块边框颜色 - * @descEN Code block border color - */ - colorBorderCode: string; - - /** - * @desc 图表边框颜色 - * @descEN Graph border color - */ - colorBorderGraph: string; -} - -export interface ComponentTokenMap { - Mermaid: MermaidPluginToken; - HighlightCode: HighlightCodePluginToken; -} diff --git a/packages/x-markdown/src/plugins/theme/interface/cssinjs-utils.ts b/packages/x-markdown/src/plugins/theme/interface/cssinjs-utils.ts deleted file mode 100644 index f71a50694..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/cssinjs-utils.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type { - FullToken as FullTokenTypeUtil, - GenStyleFn as GenStyleFnTypeUtil, - GetDefaultToken as GetDefaultTokenTypeUtil, - GlobalToken as GlobalTokenTypeUtil, - OverrideTokenMap as OverrideTokenTypeUtil, - TokenMapKey, -} from '@ant-design/cssinjs-utils'; - -import type { AliasToken } from './alias'; -import type { ComponentTokenMap } from './components'; - -/** Final token which contains the components level override */ -export type GlobalToken = GlobalTokenTypeUtil; - -export type OverrideToken = OverrideTokenTypeUtil; - -export type OverrideComponent = TokenMapKey; - -export type FullToken> = FullTokenTypeUtil< - ComponentTokenMap, - AliasToken, - C ->; - -export type GetDefaultToken> = GetDefaultTokenTypeUtil< - ComponentTokenMap, - AliasToken, - C ->; - -export type GenStyleFn> = GenStyleFnTypeUtil< - ComponentTokenMap, - AliasToken, - C ->; diff --git a/packages/x-markdown/src/plugins/theme/interface/index.ts b/packages/x-markdown/src/plugins/theme/interface/index.ts deleted file mode 100644 index d92169275..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { CSSInterpolation, DerivativeFunc } from '@ant-design/cssinjs'; - -import type { AliasToken } from './alias'; -import type { MapToken } from './maps'; -import type { SeedToken } from './seeds'; - -export type AnyObject = Record; - -export type MappingAlgorithm = DerivativeFunc; - -export type { AliasToken } from './alias'; -export type { ComponentTokenMap } from './components'; -export type { - FullToken, - GenStyleFn, - GetDefaultToken, - GlobalToken, - OverrideComponent, - OverrideToken, -} from './cssinjs-utils'; -export type { - ColorMapToken, - ColorNeutralMapToken, - CommonMapToken, - FontMapToken, - HeightMapToken, - MapToken, - SizeMapToken, - StyleMapToken, -} from './maps'; -export type { - ColorPalettes, - LegacyColorPalettes, - PresetColorKey, - PresetColorType, -} from './presetColors'; -export { PresetColors } from './presetColors'; -export type { SeedToken } from './seeds'; - -export type UseComponentStyleResult = [(node: React.ReactNode) => React.ReactElement, string]; - -export type GenerateStyle< - ComponentToken extends AnyObject = AliasToken, - ReturnType = CSSInterpolation, -> = (token: ComponentToken) => ReturnType; diff --git a/packages/x-markdown/src/plugins/theme/interface/maps/colors.ts b/packages/x-markdown/src/plugins/theme/interface/maps/colors.ts deleted file mode 100644 index fe3d1b148..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/maps/colors.ts +++ /dev/null @@ -1,639 +0,0 @@ -export interface ColorNeutralMapToken { - /** - * @internal - */ - colorTextBase: string; - - /** - * @internal - */ - colorBgBase: string; - - // ---------- Text ---------- // - - /** - * @nameZH 一级文本色 - * @nameEN Text Color - * @desc 最深的文本色。为了符合W3C标准,默认的文本颜色使用了该色,同时这个颜色也是最深的中性色。 - * @descEN Default text color which comply with W3C standards, and this color is also the darkest neutral color. - */ - colorText: string; - - /** - * @nameZH 二级文本色 - * @nameEN Secondary Text Color - * @desc 作为第二梯度的文本色,一般用在不那么需要强化文本颜色的场景,例如 Label 文本、Menu 的文本选中态等场景。 - * @descEN The second level of text color is generally used in scenarios where text color is not emphasized, such as label text, menu text selection state, etc. - */ - colorTextSecondary: string; - - /** - * @nameZH 三级文本色 - * @desc 第三级文本色一般用于描述性文本,例如表单的中的补充说明文本、列表的描述性文本等场景。 - * @descEN The third level of text color is generally used for descriptive text, such as form supplementary explanation text, list descriptive text, etc. - */ - colorTextTertiary: string; - - /** - * @nameZH 四级文本色 - * @desc 第四级文本色是最浅的文本色,例如表单的输入提示文本、禁用色文本等。 - * @descEN The fourth level of text color is the lightest text color, such as form input prompt text, disabled color text, etc. - */ - colorTextQuaternary: string; - - // ---------- Border ---------- // - - /** - * @nameZH 一级边框色 - * @nameEN Default Border Color - * @desc 默认使用的边框颜色, 用于分割不同的元素,例如:表单的分割线、卡片的分割线等。 - * @descEN Default border color, used to separate different elements, such as: form separator, card separator, etc. - */ - colorBorder: string; - - /** - * @nameZH 二级边框色 - * @nameEN Secondary Border Color - * @desc 比默认使用的边框色要浅一级,此颜色和 colorSplit 的颜色一致。使用的是实色。 - * @descEN Slightly lighter than the default border color, this color is the same as `colorSplit`. Solid color is used. - */ - colorBorderSecondary: string; - - /** - * @nameZH 禁用态边框颜色 - * @nameEN Disabled state border color - * @desc 控制元素在禁用状态下的边框颜色。 - * @descEN Control the border color of the element in the disabled state. - */ - colorBorderDisabled: string; - - // ---------- Fill ---------- // - - /** - * @nameZH 一级填充色 - * @desc 最深的填充色,用于拉开与二、三级填充色的区分度,目前只用在 Slider 的 hover 效果。 - * @descEN The darkest fill color is used to distinguish between the second and third level of fill color, and is currently only used in the hover effect of Slider. - */ - colorFill: string; - - /** - * @nameZH 二级填充色 - * @desc 二级填充色可以较为明显地勾勒出元素形体,如 Rate、Skeleton 等。也可以作为三级填充色的 Hover 状态,如 Table 等。 - * @descEN The second level of fill color can outline the shape of the element more clearly, such as Rate, Skeleton, etc. It can also be used as the Hover state of the third level of fill color, such as Table, etc. - */ - colorFillSecondary: string; - - /** - * @nameZH 三级填充色 - * @desc 三级填充色用于勾勒出元素形体的场景,如 Slider、Segmented 等。如无强调需求的情况下,建议使用三级填色作为默认填色。 - * @descEN The third level of fill color is used to outline the shape of the element, such as Slider, Segmented, etc. If there is no emphasis requirement, it is recommended to use the third level of fill color as the default fill color. - */ - colorFillTertiary: string; - - /** - * @nameZH 四级填充色 - * @desc 最弱一级的填充色,适用于不易引起注意的色块,例如斑马纹、区分边界的色块等。 - * @descEN The weakest level of fill color is suitable for color blocks that are not easy to attract attention, such as zebra stripes, color blocks that distinguish boundaries, etc. - */ - colorFillQuaternary: string; - - // ---------- Surface ---------- // - - /** - * @nameZH 布局背景色 - * @nameEN Layout Background Color - * @desc 该色用于页面整体布局的背景色,只有需要在页面中处于 B1 的视觉层级时才会使用该 token,其他用法都是错误的 - * @descEN This color is used for the background color of the overall layout of the page. This token will only be used when it is necessary to be at the B1 visual level in the page. Other usages are wrong. - */ - colorBgLayout: string; - - /** - * @nameZH 组件容器背景色 - * @desc 组件的容器背景色,例如:默认按钮、输入框等。务必不要将其与 `colorBgElevated` 混淆。 - * @descEN Container background color, e.g: default button, input box, etc. Be sure not to confuse this with `colorBgElevated`. - */ - colorBgContainer: string; - - /** - * @nameZH 浮层容器背景色 - * @desc 浮层容器背景色,在暗色模式下该 token 的色值会比 `colorBgContainer` 要亮一些。例如:模态框、弹出框、菜单等。 - * @descEN Container background color of the popup layer, in dark mode the color value of this token will be a little brighter than `colorBgContainer`. E.g: modal, pop-up, menu, etc. - */ - colorBgElevated: string; - - /** - * @nameZH 引起注意的背景色 - * @desc 该色用于引起用户强烈关注注意的背景色,目前只用在 Tooltip 的背景色上。 - * @descEN This color is used to draw the user's strong attention to the background color, and is currently only used in the background color of Tooltip. - */ - colorBgSpotlight: string; - /** - * @nameZH 毛玻璃容器背景色 - * @nameEN Frosted glass container background color - * @desc 控制毛玻璃容器的背景色,通常为透明色。 - * @descEN Control the background color of frosted glass container, usually transparent. - */ - colorBgBlur: string; - - // ---------- Solid ---------- // - - /** - * @desc 实心的背景颜色,目前只用在默认实心按钮背景色上。 - * @descEN Solid background color, currently only used for the default solid button background color. - */ - colorBgSolid: string; - /** - * @desc 实心的背景颜色激活态,目前只用在默认实心按钮的 active 效果。 - * @descEN Solid background color active state, currently only used in the active effect of the default solid button. - */ - colorBgSolidActive: string; - /** - * @desc 实心的背景颜色悬浮态,目前只用在默认实心按钮的 hover 效果。 - * @descEN Solid background color hover state, currently only used in the hover effect of the default solid button. - */ - colorBgSolidHover: string; -} - -/** - * 品牌色梯度变量 - */ -interface ColorPrimaryMapToken { - /** - * @nameZH 品牌主色 - * @nameEN Primary color of the brand - * @desc 品牌色是体现产品特性和传播理念最直观的视觉元素之一,用于产品的主色调、主按钮、主图标、主文本等 - * @descEN The brand color is one of the most intuitive visual elements that reflects product characteristics and communication concepts, and is used for the main color tone, main buttons, main icons, main text, etc. of the product. - */ - colorPrimary: string; // 6 - - /** - * @nameZH 主色浅色背景色 - * @nameEN Light background color of primary color - * @desc 主色浅色背景颜色,一般用于视觉层级较弱的选中状态。 - * @descEN Light background color of primary color, usually used for weak visual level selection state. - */ - colorPrimaryBg: string; // 1 - - /** - * @nameZH 主色浅色背景悬浮态 - * @nameEN Hover state of light background color of primary color - * @desc 与主色浅色背景颜色相对应的悬浮态颜色。 - * @descEN The hover state color corresponding to the light background color of the primary color. - */ - colorPrimaryBgHover: string; // 2 - - /** - * @nameZH 主色描边色 - * @nameEN Border color of primary color - * @desc 主色梯度下的描边用色,用在 Slider 等组件的描边上。 - * @descEN The stroke color under the main color gradient, used on the stroke of components such as Slider. - */ - colorPrimaryBorder: string; // 3 - - /** - * @nameZH 主色描边色悬浮态 - * @nameEN Hover state of border color of primary color - * @desc 主色梯度下的描边用色的悬浮态,Slider 、Button 等组件的描边 Hover 时会使用。 - * @descEN The hover state of the stroke color under the main color gradient, which will be used when the stroke Hover of components such as Slider and Button. - */ - colorPrimaryBorderHover: string; // 4 - - /** - * @nameZH 主色悬浮态 - * @nameEN Hover state of primary color - * @desc 主色梯度下的悬浮态。 - * @descEN Hover state under the main color gradient. - */ - colorPrimaryHover: string; // 5 - - /** - * @nameZH 主色激活态 - * @nameEN Active state of primary color - * @desc 主色梯度下的深色激活态。 - * @descEN Dark active state under the main color gradient. - */ - colorPrimaryActive: string; // 7 - - /** - * @nameZH 主色文本悬浮态 - * @nameEN Hover state of text color of primary color - * @desc 主色梯度下的文本悬浮态。 - * @descEN Hover state of text color under the main color gradient. - */ - colorPrimaryTextHover: string; // 8 - - /** - * @nameZH 主色文本 - * @nameEN Text color of primary color - * @desc 主色梯度下的文本颜色。 - * @descEN Text color under the main color gradient. - */ - colorPrimaryText: string; // 9 - - /** - * @nameZH 主色文本激活态 - * @nameEN Active state of text color of primary color - * @desc 主色梯度下的文本激活态。 - * @descEN Active state of text color under the main color gradient. - */ - colorPrimaryTextActive: string; // 10 -} - -interface ColorSuccessMapToken { - /** - * @nameZH 成功色的浅色背景颜色 - * @nameEN Light Background Color of Success Color - * @desc 成功色的浅色背景颜色,用于 Tag 和 Alert 的成功态背景色 - * @descEN Light background color of success color, used for Tag and Alert success state background color - */ - colorSuccessBg: string; // 1 - - /** - * @nameZH 成功色的浅色背景色悬浮态 - * @nameEN Hover State Color of Light Success Background - * @desc 成功色浅色背景颜色,一般用于视觉层级较弱的选中状态,不过 antd 目前没有使用到该 token - * @descEN Light background color of success color, but antd does not use this token currently - */ - colorSuccessBgHover: string; // 2 - - /** - * @nameZH 成功色的描边色 - * @nameEN Border Color of Success Color - * @desc 成功色的描边色,用于 Tag 和 Alert 的成功态描边色 - * @descEN Border color of success color, used for Tag and Alert success state border color - */ - colorSuccessBorder: string; // 3 - - /** - * @nameZH 成功色的描边色悬浮态 - * @nameEN Hover State Color of Success Border - * @desc 成功色的描边色悬浮态 - * @descEN Hover state color of success color border - */ - colorSuccessBorderHover: string; // 4 - - /** - * @nameZH 成功色的深色悬浮态 - * @nameEN Hover State Color of Dark Success - * @desc 成功色的深色悬浮态 - * @descEN Hover state color of dark success color - */ - colorSuccessHover: string; // 5 - - /** - * @nameZH 成功色 - * @nameEN Success Color - * @desc 默认的成功色,如 Result、Progress 等组件中都有使用该颜色 - * @descEN Default success color, used in components such as Result and Progress - */ - colorSuccess: string; // 6 - - /** - * @nameZH 成功色的深色激活态 - * @nameEN Active State Color of Dark Success - * @desc 成功色的深色激活态 - * @descEN Active state color of dark success color - */ - colorSuccessActive: string; // 7 - - /** - * @nameZH 成功色的文本悬浮态 - * @nameEN Hover State Color of Success Text - * @desc 成功色的文本悬浮态 - * @descEN Hover state color of success color text - */ - colorSuccessTextHover: string; // 8 - - /** - * @nameZH 成功色的文本默认态 - * @nameEN Default State Color of Success Text - * @desc 成功色的文本默认态 - * @descEN Default state color of success color text - */ - colorSuccessText: string; // 9 - - /** - * @nameZH 成功色的文本激活态 - * @nameEN Active State Color of Success Text - * @desc 成功色的文本激活态 - * @descEN Active state color of success color text - */ - colorSuccessTextActive: string; // 10 -} - -interface ColorWarningMapToken { - /** - * @nameZH 警戒色的浅色背景颜色 - * @nameEN Warning background color - * @desc 警戒色的浅色背景颜色 - * @descEN The background color of the warning state. - */ - colorWarningBg: string; // 1 - - /** - * @nameZH 警戒色的浅色背景色悬浮态 - * @nameEN Warning background color hover state - * @desc 警戒色的浅色背景色悬浮态 - * @descEN The hover state background color of the warning state. - */ - colorWarningBgHover: string; // 2 - - /** - * @nameZH 警戒色的描边色 - * @nameEN Warning border color - * @desc 警戒色的描边色 - * @descEN The border color of the warning state. - */ - colorWarningBorder: string; // 3 - - /** - * @nameZH 警戒色的描边色悬浮态 - * @nameEN Warning border color hover state - * @desc 警戒色的描边色悬浮态 - * @descEN The hover state border color of the warning state. - */ - colorWarningBorderHover: string; // 4 - - /** - * @nameZH 警戒色的深色悬浮态 - * @nameEN Warning hover color - * @desc 警戒色的深色悬浮态 - * @descEN The hover state of the warning color. - */ - colorWarningHover: string; // 5 - - /** - * @nameZH 警戒色 - * @nameEN Warning color - * @desc 最常用的警戒色,例如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该颜色 - * @descEN The most commonly used warning color, used for warning components such as Notification, Alert, or input components. - */ - colorWarning: string; // 6 - - /** - * @nameZH 警戒色的深色激活态 - * @nameEN Warning active color - * @desc 警戒色的深色激活态 - * @descEN The active state of the warning color. - */ - colorWarningActive: string; // 7 - - /** - * @nameZH 警戒色的文本悬浮态 - * @nameEN Warning text hover state - * @desc 警戒色的文本悬浮态 - * @descEN The hover state of the text in the warning color. - */ - colorWarningTextHover: string; // 8 - - /** - * @nameZH 警戒色的文本默认态 - * @nameEN Warning text default state - * @desc 警戒色的文本默认态 - * @descEN The default state of the text in the warning color. - */ - colorWarningText: string; // 9 - - /** - * @nameZH 警戒色的文本激活态 - * @nameEN Warning text active state - * @desc 警戒色的文本激活态 - * @descEN The active state of the text in the warning color. - */ - colorWarningTextActive: string; // 10 -} - -interface ColorInfoMapToken { - /** - * @nameZH 信息色的浅色背景颜色 - * @nameEN Light background color of information color - * @desc 信息色的浅色背景颜色。 - * @descEN Light background color of information color. - */ - colorInfoBg: string; // 1 - - /** - * @nameZH 信息色的浅色背景色悬浮态 - * @nameEN Hover state of light background color of information color - * @desc 信息色的浅色背景色悬浮态。 - * @descEN Hover state of light background color of information color. - */ - colorInfoBgHover: string; // 2 - - /** - * @nameZH 信息色的描边色 - * @nameEN Border color of information color - * @desc 信息色的描边色。 - * @descEN Border color of information color. - */ - colorInfoBorder: string; // 3 - - /** - * @nameZH 信息色的描边色悬浮态 - * @nameEN Hover state of border color of information color - * @desc 信息色的描边色悬浮态。 - * @descEN Hover state of border color of information color. - */ - colorInfoBorderHover: string; // 4 - - /** - * @nameZH 信息色的深色悬浮态 - * @nameEN Hover state of dark color of information color - * @desc 信息色的深色悬浮态。 - * @descEN Hover state of dark color of information color. - */ - colorInfoHover: string; // 5 - - /** - * @nameZH 信息色 - * @nameEN Information color - * @desc 信息色。 - * @descEN Information color. - */ - colorInfo: string; // 6 - - /** - * @nameZH 信息色的深色激活态 - * @nameEN Active state of dark color of information color - * @desc 信息色的深色激活态。 - * @descEN Active state of dark color of information color. - */ - colorInfoActive: string; // 7 - - /** - * @nameZH 信息色的文本悬浮态 - * @nameEN Hover state of text color of information color - * @desc 信息色的文本悬浮态。 - * @descEN Hover state of text color of information color. - */ - colorInfoTextHover: string; // 8 - - /** - * @nameZH 信息色的文本默认态 - * @nameEN Default state of text color of information color - * @desc 信息色的文本默认态。 - * @descEN Default state of text color of information color. - */ - colorInfoText: string; // 9 - - /** - * @nameZH 信息色的文本激活态 - * @nameEN Active state of text color of information color - * @desc 信息色的文本激活态。 - * @descEN Active state of text color of information color. - */ - colorInfoTextActive: string; // 10 -} - -interface ColorErrorMapToken { - /** - * @nameZH 错误色的浅色背景颜色 - * @nameEN Error background color - * @desc 错误色的浅色背景颜色 - * @descEN The background color of the error state. - */ - colorErrorBg: string; // 1 - - /** - * @nameZH 错误色的浅色背景色悬浮态 - * @nameEN Error background color hover state - * @desc 错误色的浅色背景色悬浮态 - * @descEN The hover state background color of the error state. - */ - colorErrorBgHover: string; // 2 - - /** - * @nameZH 错误色的浅色填充背景色悬浮态 - * @nameEN Wrong color fill background color suspension state - * @desc 错误色的浅色填充背景色悬浮态,目前只用在危险填充按钮的 hover 效果。 - * @descEN The wrong color fills the background color of the suspension state, which is currently only used in the hover effect of the dangerous filled button. - */ - colorErrorBgFilledHover: string; // 2.5 - - /** - * @nameZH 错误色的浅色背景色激活态 - * @nameEN Error background color active state - * @desc 错误色的浅色背景色激活态 - * @descEN The active state background color of the error state. - */ - colorErrorBgActive: string; // 3 - - /** - * @nameZH 错误色的描边色 - * @nameEN Error border color - * @desc 错误色的描边色 - * @descEN The border color of the error state. - */ - colorErrorBorder: string; // 3 - - /** - * @nameZH 错误色的描边色悬浮态 - * @nameEN Error border color hover state - * @desc 错误色的描边色悬浮态 - * @descEN The hover state border color of the error state. - */ - colorErrorBorderHover: string; // 4 - - /** - * @nameZH 错误色的深色悬浮态 - * @nameEN Error hover color - * @desc 错误色的深色悬浮态 - * @descEN The hover state of the error color. - */ - colorErrorHover: string; // 5 - - /** - * @nameZH 错误色 - * @nameEN Error color - * @desc 错误色 - * @descEN The color of the error state. - */ - colorError: string; // 6 - - /** - * @nameZH 错误色的深色激活态 - * @nameEN Error active color - * @desc 错误色的深色激活态 - * @descEN The active state of the error color. - */ - colorErrorActive: string; // 7 - - /** - * @nameZH 错误色的文本悬浮态 - * @nameEN Error text hover state - * @desc 错误色的文本悬浮态 - * @descEN The hover state of the text in the error color. - */ - colorErrorTextHover: string; // 8 - - /** - * @nameZH 错误色的文本默认态 - * @nameEN Error text default state - * @desc 错误色的文本默认态 - * @descEN The default state of the text in the error color. - */ - colorErrorText: string; // 9 - - /** - * @nameZH 错误色的文本激活态 - * @nameEN Error text active state - * @desc 错误色的文本激活态 - * @descEN The active state of the text in the error color. - */ - colorErrorTextActive: string; // 10 -} - -export interface ColorLinkMapToken { - /** - * @nameZH 超链接颜色 - * @nameEN Hyperlink color - * @desc 控制超链接的颜色。 - * @descEN Control the color of hyperlink. - */ - colorLink: string; - /** - * @nameZH 超链接悬浮颜色 - * @nameEN Hyperlink hover color - * @desc 控制超链接悬浮时的颜色。 - * @descEN Control the color of hyperlink when hovering. - */ - colorLinkHover: string; - /** - * @nameZH 超链接激活颜色 - * @nameEN Hyperlink active color - * @desc 控制超链接被点击时的颜色。 - * @descEN Control the color of hyperlink when clicked. - */ - colorLinkActive: string; -} - -export interface ColorMapToken - extends ColorNeutralMapToken, - ColorPrimaryMapToken, - ColorSuccessMapToken, - ColorWarningMapToken, - ColorErrorMapToken, - ColorInfoMapToken, - ColorLinkMapToken { - /** - * @nameZH 纯白色 - * @desc 不随主题变化的纯白色 - * @descEN Pure white color don't changed by theme - * @default #FFFFFF - */ - colorWhite: string; - - /** - * @nameZH 浮层的背景蒙层颜色 - * @nameEN Background color of the mask - * @desc 浮层的背景蒙层颜色,用于遮罩浮层下面的内容,Modal、Drawer 等组件的蒙层使用的是该 token - * @descEN The background color of the mask, used to cover the content below the mask, Modal, Drawer and other components use this token - */ - colorBgMask: string; - - /** - * @nameZH 纯黑色 - * @desc 不随主题变化的纯黑色 - * @default #0000 - */ -} diff --git a/packages/x-markdown/src/plugins/theme/interface/maps/font.ts b/packages/x-markdown/src/plugins/theme/interface/maps/font.ts deleted file mode 100644 index 40ed00716..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/maps/font.ts +++ /dev/null @@ -1,139 +0,0 @@ -export interface FontMapToken { - // Font Size - /** - * @desc 小号字体大小 - * @descEN Small font size - */ - fontSizeSM: number; - /** - * @desc 标准字体大小 - * @descEN Standard font size - */ - fontSize: number; - /** - * @desc 大号字体大小 - * @descEN Large font size - */ - fontSizeLG: number; - /** - * @desc 超大号字体大小 - * @descEN Super large font size - */ - fontSizeXL: number; - - /** - * @nameZH 一级标题字号 - * @nameEN Font size of heading level 1 - * @desc H1 标签所使用的字号 - * @descEN Font size of h1 tag. - * @default 38 - */ - fontSizeHeading1: number; - /** - * @nameZH 二级标题字号 - * @nameEN Font size of heading level 2 - * @desc h2 标签所使用的字号 - * @descEN Font size of h2 tag. - * @default 30 - */ - fontSizeHeading2: number; - /** - * @nameZH 三级标题字号 - * @nameEN Font size of heading level 3 - * @desc h3 标签使用的字号 - * @descEN Font size of h3 tag. - * @default 24 - */ - fontSizeHeading3: number; - /** - * @nameZH 四级标题字号 - * @nameEN Font size of heading level 4 - * @desc h4 标签使用的字号 - * @descEN Font size of h4 tag. - * @default 20 - */ - fontSizeHeading4: number; - /** - * @nameZH 五级标题字号 - * @nameEN Font size of heading level 5 - * @desc h5 标签使用的字号 - * @descEN Font size of h5 tag. - * @default 16 - */ - fontSizeHeading5: number; - - // LineHeight - /** - * @desc 文本行高 - * @descEN Line height of text. - */ - lineHeight: number; - /** - * @desc 大型文本行高 - * @descEN Line height of large text. - */ - lineHeightLG: number; - /** - * @desc 小型文本行高 - * @descEN Line height of small text. - */ - lineHeightSM: number; - - // TextHeight - /** - * Round of fontSize * lineHeight - * @internal - */ - fontHeight: number; - /** - * Round of fontSizeSM * lineHeightSM - * @internal - */ - fontHeightSM: number; - /** - * Round of fontSizeLG * lineHeightLG - * @internal - */ - fontHeightLG: number; - - /** - * @nameZH 一级标题行高 - * @nameEN Line height of heading level 1 - * @desc H1 标签所使用的行高 - * @descEN Line height of h1 tag. - * @default 1.4 - */ - lineHeightHeading1: number; - /** - * @nameZH 二级标题行高 - * @nameEN Line height of heading level 2 - * @desc h2 标签所使用的行高 - * @descEN Line height of h2 tag. - * @default 1.35 - */ - lineHeightHeading2: number; - /** - * @nameZH 三级标题行高 - * @nameEN Line height of heading level 3 - * @desc h3 标签所使用的行高 - * @descEN Line height of h3 tag. - * @default 1.3 - */ - lineHeightHeading3: number; - /** - * @nameZH 四级标题行高 - * @nameEN Line height of heading level 4 - * @desc h4 标签所使用的行高 - * @descEN Line height of h4 tag. - * @default 1.25 - */ - lineHeightHeading4: number; - /** - * @nameZH 五级标题行高 - * @nameEN Line height of heading level 5 - * @desc h5 标签所使用的行高 - * @descEN Line height of h5 tag. - * @default 1.2 - */ - lineHeightHeading5: number; -} diff --git a/packages/x-markdown/src/plugins/theme/interface/maps/index.ts b/packages/x-markdown/src/plugins/theme/interface/maps/index.ts deleted file mode 100644 index 29d3f53d7..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/maps/index.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { ColorPalettes, LegacyColorPalettes } from '../presetColors'; -import type { SeedToken } from '../seeds'; -import type { ColorMapToken } from './colors'; -import type { FontMapToken } from './font'; -import type { HeightMapToken, SizeMapToken } from './size'; -import type { StyleMapToken } from './style'; - -export * from './colors'; -export * from './font'; -export * from './size'; -export * from './style'; - -export interface CommonMapToken extends StyleMapToken { - // Motion - /** - * @desc 动效播放速度,快速。用于小型元素动画交互 - * @descEN Motion speed, fast speed. Used for small element animation interaction. - */ - motionDurationFast: string; - /** - * @desc 动效播放速度,中速。用于中型元素动画交互 - * @descEN Motion speed, medium speed. Used for medium element animation interaction. - */ - motionDurationMid: string; - /** - * @desc 动效播放速度,慢速。用于大型元素如面板动画交互 - * @descEN Motion speed, slow speed. Used for large element animation interaction. - */ - motionDurationSlow: string; -} - -// ====================================================================== -// == Map Token == -// ====================================================================== -// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 - -export interface MapToken - extends SeedToken, - ColorPalettes, - LegacyColorPalettes, - ColorMapToken, - SizeMapToken, - HeightMapToken, - StyleMapToken, - FontMapToken, - CommonMapToken {} diff --git a/packages/x-markdown/src/plugins/theme/interface/maps/size.ts b/packages/x-markdown/src/plugins/theme/interface/maps/size.ts deleted file mode 100644 index f69f5a927..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/maps/size.ts +++ /dev/null @@ -1,74 +0,0 @@ -export interface SizeMapToken { - /** - * @nameZH XXL - * @default 48 - */ - sizeXXL: number; - /** - * @nameZH XL - * @default 32 - */ - sizeXL: number; - /** - * @nameZH LG - * @default 24 - */ - sizeLG: number; - /** - * @nameZH MD - * @default 20 - */ - sizeMD: number; - /** Same as size by default, but could be larger in compact mode */ - sizeMS: number; - /** - * @nameZH 默认 - * @desc 默认尺寸 - * @default 16 - */ - size: number; - /** - * @nameZH SM - * @default 12 - */ - sizeSM: number; - /** - * @nameZH XS - * @default 8 - */ - sizeXS: number; - /** - * @nameZH XXS - * @default 4 - */ - sizeXXS: number; -} - -export interface HeightMapToken { - // Control - /** Only Used for control inside component like Multiple Select inner selection item */ - - /** - * @nameZH 更小的组件高度 - * @nameEN XS component height - * @desc 更小的组件高度 - * @descEN XS component height - */ - controlHeightXS: number; - - /** - * @nameZH 较小的组件高度 - * @nameEN SM component height - * @desc 较小的组件高度 - * @descEN SM component height - */ - controlHeightSM: number; - - /** - * @nameZH 较高的组件高度 - * @nameEN LG component height - * @desc 较高的组件高度 - * @descEN LG component height - */ - controlHeightLG: number; -} diff --git a/packages/x-markdown/src/plugins/theme/interface/maps/style.ts b/packages/x-markdown/src/plugins/theme/interface/maps/style.ts deleted file mode 100644 index e4faf7dac..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/maps/style.ts +++ /dev/null @@ -1,43 +0,0 @@ -export interface StyleMapToken { - /** - * @nameZH 线宽 - * @nameEN Line Width - * @desc 描边类组件的默认线宽,如 Button、Input、Select 等输入类控件。 - * @descEN The default line width of the outline class components, such as Button, Input, Select, etc. - * @default 1 - */ - lineWidthBold: number; - - /** - * @nameZH XS号圆角 - * @nameEN XS Border Radius - * @desc XS号圆角,用于组件中的一些小圆角,如 Segmented 、Arrow 等一些内部圆角的组件样式中。 - * @descEN XS size border radius, used in some small border radius components, such as Segmented, Arrow and other components with small border radius. - * @default 2 - */ - borderRadiusXS: number; - /** - * @nameZH SM号圆角 - * @nameEN SM Border Radius - * @desc SM号圆角,用于组件小尺寸下的圆角,如 Button、Input、Select 等输入类控件在 small size 下的圆角 - * @descEN SM size border radius, used in small size components, such as Button, Input, Select and other input components in small size - * @default 4 - */ - borderRadiusSM: number; - /** - * @nameZH LG号圆角 - * @nameEN LG Border Radius - * @desc LG号圆角,用于组件中的一些大圆角,如 Card、Modal 等一些组件样式。 - * @descEN LG size border radius, used in some large border radius components, such as Card, Modal and other components. - * @default 8 - */ - borderRadiusLG: number; - /** - * @nameZH 外部圆角 - * @nameEN Outer Border Radius - * @default 4 - * @desc 外部圆角 - * @descEN Outer border radius - */ - borderRadiusOuter: number; -} diff --git a/packages/x-markdown/src/plugins/theme/interface/presetColors.ts b/packages/x-markdown/src/plugins/theme/interface/presetColors.ts deleted file mode 100644 index e160935e6..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/presetColors.ts +++ /dev/null @@ -1,32 +0,0 @@ -export const PresetColors = [ - 'blue', - 'purple', - 'cyan', - 'green', - 'magenta', - 'pink', - 'red', - 'orange', - 'yellow', - 'volcano', - 'geekblue', - 'lime', - 'gold', -] as const; - -export type PresetColorKey = (typeof PresetColors)[number]; - -export type PresetColorType = Record; - -type ColorPaletteKeyIndex = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; - -export type LegacyColorPalettes = { - /** - * @deprecated - */ - [key in `${keyof PresetColorType}-${ColorPaletteKeyIndex}`]: string; -}; - -export type ColorPalettes = { - [key in `${keyof PresetColorType}${ColorPaletteKeyIndex}`]: string; -}; diff --git a/packages/x-markdown/src/plugins/theme/interface/seeds.ts b/packages/x-markdown/src/plugins/theme/interface/seeds.ts deleted file mode 100644 index 98a185ed1..000000000 --- a/packages/x-markdown/src/plugins/theme/interface/seeds.ts +++ /dev/null @@ -1,282 +0,0 @@ -import type { PresetColorType } from './presetColors'; - -// ====================================================================== -// == Seed Token == -// ====================================================================== -// 🔥🔥🔥🔥🔥🔥🔥 DO NOT MODIFY THIS. PLEASE CONTACT DESIGNER. 🔥🔥🔥🔥🔥🔥🔥 - -export interface SeedToken extends PresetColorType { - // ---------- Color ---------- // - - /** - * @nameZH 品牌主色 - * @nameEN Brand Color - * @desc 品牌色是体现产品特性和传播理念最直观的视觉元素之一。在你完成品牌主色的选取之后,我们会自动帮你生成一套完整的色板,并赋予它们有效的设计语义 - * @descEN Brand color is one of the most direct visual elements to reflect the characteristics and communication of the product. After you have selected the brand color, we will automatically generate a complete color palette and assign it effective design semantics. - */ - colorPrimary: string; - - /** - * @nameZH 成功色 - * @nameEN Success Color - * @desc 用于表示操作成功的 Token 序列,如 Result、Progress 等组件会使用该组梯度变量。 - * @descEN Used to represent the token sequence of operation success, such as Result, Progress and other components will use these map tokens. - */ - colorSuccess: string; - - /** - * @nameZH 警戒色 - * @nameEN Warning Color - * @desc 用于表示操作警告的 Token 序列,如 Notification、 Alert等警告类组件或 Input 输入类等组件会使用该组梯度变量。 - * @descEN Used to represent the warning map token, such as Notification, Alert, etc. Alert or Control component(like Input) will use these map tokens. - */ - colorWarning: string; - - /** - * @nameZH 错误色 - * @nameEN Error Color - * @desc 用于表示操作失败的 Token 序列,如失败按钮、错误状态提示(Result)组件等。 - * @descEN Used to represent the visual elements of the operation failure, such as the error Button, error Result component, etc. - */ - colorError: string; - - /** - * @nameZH 信息色 - * @nameEN Info Color - * @desc 用于表示操作信息的 Token 序列,如 Alert 、Tag、 Progress 等组件都有用到该组梯度变量。 - * @descEN Used to represent the operation information of the Token sequence, such as Alert, Tag, Progress, and other components use these map tokens. - */ - colorInfo: string; - - /** - * @nameZH 基础文本色 - * @nameEN Seed Text Color - * @desc 用于派生文本色梯度的基础变量,v5 中我们添加了一层文本色的派生算法可以产出梯度明确的文本色的梯度变量。但请不要在代码中直接使用该 Seed Token ! - * @descEN Used to derive the base variable of the text color gradient. In v5, we added a layer of text color derivation algorithm to produce gradient variables of text color gradient. But please do not use this Seed Token directly in the code! - */ - colorTextBase: string; - - /** - * @nameZH 基础背景色 - * @nameEN Seed Background Color - * @desc 用于派生背景色梯度的基础变量,v5 中我们添加了一层背景色的派生算法可以产出梯度明确的背景色的梯度变量。但请不要在代码中直接使用该 Seed Token ! - * @descEN Used to derive the base variable of the background color gradient. In v5, we added a layer of background color derivation algorithm to produce map token of background color. But PLEASE DO NOT USE this Seed Token directly in the code! - */ - colorBgBase: string; - - /** - * @nameZH 超链接颜色 - * @nameEN Hyperlink color - * @desc 控制超链接的颜色。 - * @descEN Control the color of hyperlink. - */ - colorLink: string; - - // ---------- Font ---------- // - - /** - * @nameZH 字体 - * @nameEN Font family for default text - * @desc Ant Design 的字体家族中优先使用系统默认的界面字体,同时提供了一套利于屏显的备用字体库,来维护在不同平台以及浏览器的显示下,字体始终保持良好的易读性和可读性,体现了友好、稳定和专业的特性。 - * @descEN The font family of Ant Design prioritizes the default interface font of the system, and provides a set of alternative font libraries that are suitable for screen display to maintain the readability and readability of the font under different platforms and browsers, reflecting the friendly, stable and professional characteristics. - */ - fontFamily: string; - - /** - * @nameZH 代码字体 - * @nameEN Font family for code text - * @desc 代码字体,用于 Typography 内的 code、pre 和 kbd 类型的元素 - * @descEN Code font, used for code, pre and kbd elements in Typography - */ - fontFamilyCode: string; - - /** - * @nameZH 默认字号 - * @nameEN Default Font Size - * @desc 设计系统中使用最广泛的字体大小,文本梯度也将基于该字号进行派生。 - * @descEN The most widely used font size in the design system, from which the text gradient will be derived. - * @default 14 - */ - fontSize: number; - - // ---------- Line ---------- // - - /** - * @nameZH 基础线宽 - * @nameEN Base Line Width - * @desc 用于控制组件边框、分割线等的宽度 - * @descEN Border width of base components - */ - lineWidth: number; - - /** - * @nameZH 线条样式 - * @nameEN Line Style - * @desc 用于控制组件边框、分割线等的样式,默认是实线 - * @descEN Border style of base components - */ - lineType: string; - - // ---------- BorderRadius ---------- // - - /** - * @nameZH 基础圆角 - * @nameEN Base Border Radius - * @descEN Border radius of base components - * @desc 基础组件的圆角大小,例如按钮、输入框、卡片等 - */ - borderRadius: number; - - // ---------- Size ---------- // - - /** - * @nameZH 尺寸变化单位 - * @nameEN Size Change Unit - * @desc 用于控制组件尺寸的变化单位,在 Ant Design 中我们的基础单位为 4 ,便于更加细致地控制尺寸梯度 - * @descEN The unit of size change, in Ant Design, our base unit is 4, which is more fine-grained control of the size step - * @default 4 - */ - sizeUnit: number; - - /** - * @nameZH 尺寸步长 - * @nameEN Size Base Step - * @desc 用于控制组件尺寸的基础步长,尺寸步长结合尺寸变化单位,就可以派生各种尺寸梯度。通过调整步长即可得到不同的布局模式,例如 V5 紧凑模式下的尺寸步长为 2 - * @descEN The base step of size change, the size step combined with the size change unit, can derive various size steps. By adjusting the step, you can get different layout modes, such as the size step of the compact mode of V5 is 2 - * @default 4 - */ - sizeStep: number; - - /** - * @nameZH 组件箭头尺寸 - * @desc 组件箭头的尺寸 - * @descEN The size of the component arrow - */ - sizePopupArrow: number; - - /** - * @nameZH 基础高度 - * @nameEN Base Control Height - * @desc Ant Design 中按钮和输入框等基础控件的高度 - * @descEN The height of the basic controls such as buttons and input boxes in Ant Design - * @default 32 - */ - controlHeight: number; - - // ---------- zIndex ---------- // - - /** - * @nameZH 基础 zIndex - * @nameEN Base zIndex - * @desc 所有组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 BackTop、 Affix 等 - * @descEN The base Z axis value of all components, which can be used to control the level of some floating components based on the Z axis value, such as BackTop, Affix, etc. - * - * @default 0 - */ - zIndexBase: number; - - /** - * @nameZH 浮层基础 zIndex - * @nameEN popup base zIndex - * @desc 浮层类组件的基础 Z 轴值,用于一些悬浮类的组件的可以基于该值 Z 轴控制层级,例如 FloatButton、 Affix、Modal 等 - * @descEN Base zIndex of component like FloatButton, Affix which can be cover by large popup - * @default 1000 - */ - zIndexPopupBase: number; - - // ---------- Opacity ---------- // - - /** - * @nameZH 图片不透明度 - * @nameEN Define default Image opacity. Useful when in dark-like theme - * @desc 控制图片不透明度 - * @descEN Control image opacity - */ - opacityImage: number; - - // ---------- motion ---------- // - // TODO: 缺一个懂 motion 的人来收敛 Motion 相关的 Token - - /** - * @nameZH 动画时长变化单位 - * @nameEN Animation Duration Unit - * @desc 用于控制动画时长的变化单位 - * @descEN The unit of animation duration change - * @default 100ms - */ - motionUnit: number; - - /** - * @nameZH 动画基础时长。 - * @nameEN Animation Base Duration. - */ - motionBase: number; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseOutCirc: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseInOutCirc: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseInOut: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseOutBack: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseInBack: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseInQuint: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseOutQuint: string; - - /** - * @desc 预设动效曲率 - * @descEN Preset motion curve. - */ - motionEaseOut: string; - - // ---------- Style ---------- // - - /** - * @nameZH 线框风格 - * @nameEN Wireframe Style - * @desc 用于将组件的视觉效果变为线框化,如果需要使用 V4 的效果,需要开启配置项 - * @descEN Used to change the visual effect of the component to wireframe, if you need to use the V4 effect, you need to enable the configuration item - * @default false - */ - wireframe: boolean; - - /** - * @nameZH 动画风格 - * @nameEN Motion Style - * @desc 用于配置动画效果,为 `false` 时则关闭动画 - * @descEN Used to configure the motion effect, when it is `false`, the motion is turned off - * @default true - */ - motion: boolean; -} diff --git a/packages/x-markdown/src/plugins/theme/useToken.ts b/packages/x-markdown/src/plugins/theme/useToken.ts deleted file mode 100644 index 55df3cebb..000000000 --- a/packages/x-markdown/src/plugins/theme/useToken.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type { Theme } from '@ant-design/cssinjs'; -import { createTheme, useCacheToken } from '@ant-design/cssinjs'; -import type { - FullToken as FullTokenTypeUtil, - GetDefaultToken as GetDefaultTokenTypeUtil, - GlobalToken as GlobalTokenTypeUtil, - TokenMapKey, -} from '@ant-design/cssinjs-utils'; -import { theme as antdTheme } from 'antd'; -import type { DesignTokenProviderProps } from 'antd/es/theme/context'; -import type { AliasToken, SeedToken } from 'antd/es/theme/internal'; -import { ignore, unitless } from 'antd/es/theme/useToken'; -import formatToken from 'antd/es/theme/util/alias'; -import React from 'react'; -import version from '../version'; -import { ComponentTokenMap } from './interface/components'; - -const defaultTheme: Theme = createTheme(antdTheme.defaultAlgorithm); - -export type GlobalToken = GlobalTokenTypeUtil; - -export type GetDefaultToken> = GetDefaultTokenTypeUtil< - ComponentTokenMap, - AliasToken, - C ->; - -export type FullToken> = FullTokenTypeUtil< - ComponentTokenMap, - AliasToken, - C ->; - -const preserve: { - [key in keyof AliasToken]?: boolean; -} = { - screenXS: true, - screenXSMin: true, - screenXSMax: true, - screenSM: true, - screenSMMin: true, - screenSMMax: true, - screenMD: true, - screenMDMin: true, - screenMDMax: true, - screenLG: true, - screenLGMin: true, - screenLGMax: true, - screenXL: true, - screenXLMin: true, - screenXLMax: true, - screenXXL: true, - screenXXLMin: true, -}; - -export const getComputedToken = ( - originToken: SeedToken, - overrideToken: DesignTokenProviderProps['components'] & { - override?: Partial; - }, - theme: Theme, -) => { - const derivativeToken = theme.getDerivativeToken(originToken); - - const { override, ...components } = overrideToken; - - // Merge with override - let mergedDerivativeToken = { - ...derivativeToken, - override, - }; - - // Format if needed - mergedDerivativeToken = formatToken(mergedDerivativeToken); - - if (components) { - Object.entries(components).forEach(([key, value]) => { - const { theme: componentTheme, ...componentTokens } = value; - let mergedComponentToken = componentTokens; - if (componentTheme) { - mergedComponentToken = getComputedToken( - { - ...mergedDerivativeToken, - ...componentTokens, - }, - { - override: componentTokens, - }, - componentTheme as unknown as Theme, - ); - } - mergedDerivativeToken[key] = mergedComponentToken; - }); - } - - return mergedDerivativeToken; -}; - -export function useInternalToken(): [ - theme: Theme, - token: GlobalToken, - hashId: string, - realToken: GlobalToken, - cssVar?: DesignTokenProviderProps['cssVar'], -] { - const { - token: rootDesignToken, - hashed, - theme = defaultTheme, - override, - cssVar: ctxCssVar, - } = React.useContext(antdTheme._internalContext); - - const cssVar = { - prefix: ctxCssVar?.prefix || 'ant', - key: ctxCssVar?.key || 'css-var-root', - }; - - const mergedTheme = theme || defaultTheme; - - const [token, hashId, realToken] = useCacheToken( - mergedTheme as Theme, - [antdTheme.defaultSeed, rootDesignToken], - { - salt: `${version}-${hashed || ''}`, - override, - getComputedToken, - cssVar: { - ...cssVar, - unitless, - ignore, - preserve, - }, - }, - ); - - return [theme as Theme, realToken, hashed ? hashId : '', token, cssVar]; -} diff --git a/packages/x-markdown/src/plugins/type.ts b/packages/x-markdown/src/plugins/type.ts index da242f1b3..d7af0c366 100644 --- a/packages/x-markdown/src/plugins/type.ts +++ b/packages/x-markdown/src/plugins/type.ts @@ -1,71 +1,15 @@ import type { KatexOptions } from 'katex'; import type { TokenizerAndRendererExtension } from 'marked'; -import type { ReactNode } from 'react'; -import type { SyntaxHighlighterProps } from 'react-syntax-highlighter'; export type LatexOption = { katexOptions?: KatexOptions; replaceAlignStart?: boolean; }; -type HighlightCodeType = 'root' | 'header' | 'headerTitle' | 'code'; -export type HighlightCodeProps = { - lang?: string; - children: string; - header?: ReactNode | null; - prefixCls?: string; - style?: React.CSSProperties; - className?: string; - highlightProps?: Partial; - // Semantic - classNames?: Partial>; - styles?: Partial>; -}; - -type MermaidType = 'root' | 'header' | 'graph' | 'code'; -export type MermaidProps = { - children: string; - header?: ReactNode | null; - prefixCls?: string; - style?: React.CSSProperties; - className?: string; - highlightProps?: Partial; - // Semantic - classNames?: Partial>; - styles?: Partial>; -}; - -interface BaseComponentConfig { - style: React.CSSProperties; - styles: Record; - className: string; - classNames: Record; -} - -type ComponentConfig< - CompProps extends Record, - PickType extends keyof CompProps = keyof BaseComponentConfig, -> = Pick; - -export interface MarkdownComponentsConfig { - highlightCode?: ComponentConfig; - mermaid?: ComponentConfig; -} - export type PluginsType = { /** * @desc 渲染数学公式Latex语法。 * @descEN Rendering mathematical formulas using Latex syntax. */ Latex: (options?: LatexOption) => TokenizerAndRendererExtension[]; - /** - * @desc 渲染代码高亮。 - * @descEN Highlight the rendering code. - */ - HighlightCode: (props: HighlightCodeProps) => React.ReactNode; - /** - * @desc 渲染 Mermaid 图表。 - * @descEN Rendering the Mermaid Chart. - */ - Mermaid: (props: MermaidProps) => React.ReactNode; }; diff --git a/packages/x-markdown/src/plugins/version/plugin-meta.json b/packages/x-markdown/src/plugins/version/plugin-meta.json new file mode 100644 index 000000000..eda9d9992 --- /dev/null +++ b/packages/x-markdown/src/plugins/version/plugin-meta.json @@ -0,0 +1,7 @@ +[ + { + "plugin": "Latex", + "desc": "渲染数学公式Latex语法。", + "descEn": "Rendering mathematical formulas using Latex syntax." + } +] diff --git a/packages/x-markdown/tests/dekko/dist.test.ts b/packages/x-markdown/tests/dekko/dist.test.ts index 1b1ed7605..25780f332 100644 --- a/packages/x-markdown/tests/dekko/dist.test.ts +++ b/packages/x-markdown/tests/dekko/dist.test.ts @@ -13,13 +13,7 @@ $('dist/plugins') .isDirectory() .hasFile('latex.js') .hasFile('latex.min.js') - .hasFile('latex.min.js.map') - .hasFile('mermaid.js') - .hasFile('mermaid.min.js') - .hasFile('mermaid.min.js.map') - .hasFile('code-high-light.js') - .hasFile('code-high-light.min.js') - .hasFile('code-high-light.min.js.map'); + .hasFile('latex.min.js.map'); // eslint-disable-next-line no-console console.log(chalk.green('✨ `dist/plugins` directory is valid.')); diff --git a/packages/x-markdown/tests/dekko/lib.test.ts b/packages/x-markdown/tests/dekko/lib.test.ts index 013e50fbf..80ec54b29 100644 --- a/packages/x-markdown/tests/dekko/lib.test.ts +++ b/packages/x-markdown/tests/dekko/lib.test.ts @@ -35,16 +35,12 @@ $('lib/plugins/*') (filename: string) => !filename.endsWith('type.js') && !filename.endsWith('type.d.ts') && - !filename.endsWith('hooks') && - !filename.endsWith('theme'), + !filename.endsWith('hooks'), ) .isDirectory() .hasFile('index.js') .hasFile('index.d.ts'); -// theme -$('lib/plugins/theme').isDirectory(); - // eslint-disable-next-line no-console console.log(chalk.green('✨ `lib/plugins` directory is valid.')); diff --git a/packages/x/.dumi/theme/builtins/XMarkdownComponentTokenTable/index.tsx b/packages/x/.dumi/theme/builtins/XMarkdownComponentTokenTable/index.tsx deleted file mode 100644 index c1a2f7d87..000000000 --- a/packages/x/.dumi/theme/builtins/XMarkdownComponentTokenTable/index.tsx +++ /dev/null @@ -1,253 +0,0 @@ -import { LinkOutlined, QuestionCircleOutlined, RightOutlined } from '@ant-design/icons'; -import { XProvider } from '@ant-design/x'; -import tokenData from '@ant-design/x-markdown/plugins/version/token.json'; -import tokenMeta from '@ant-design/x-markdown/plugins/version/token-meta.json'; -import { Flex, Popover, Table, Typography } from 'antd'; -import { createStyles, css, useTheme } from 'antd-style'; -import { getDesignToken } from 'antd-token-previewer'; -import React, { useMemo, useState } from 'react'; - -import useLocale from '../../../hooks/useLocale'; -import type { TokenData } from '../TokenTable'; -import { useColumns } from '../TokenTable'; - -const compare = (token1: string, token2: string) => { - const hasColor1 = token1.toLowerCase().includes('color'); - const hasColor2 = token2.toLowerCase().includes('color'); - if (hasColor1 && !hasColor2) { - return -1; - } - if (!hasColor1 && hasColor2) { - return 1; - } - return token1 < token2 ? -1 : 1; -}; - -const defaultToken: any = getDesignToken(); -const xTokenData: any = tokenData; -const xTokenMeta: any = tokenMeta; - -const locales = { - cn: { - token: 'Token 名称', - description: '描述', - type: '类型', - value: '默认值', - componentToken: '组件 Token', - globalToken: '全局 Token', - componentComment: '这里是你的组件 token', - globalComment: '这里是你的全局 token', - help: '如何定制?', - customizeTokenLink: '/docs/react/customize-theme-cn#修改主题变量', - customizeComponentTokenLink: '/docs/react/customize-theme-cn#修改组件变量', - }, - en: { - token: 'Token Name', - description: 'Description', - type: 'Type', - value: 'Default Value', - componentToken: 'Component Token', - globalToken: 'Global Token', - componentComment: 'here is your component tokens', - globalComment: 'here is your global tokens', - help: 'How to use?', - customizeTokenLink: '/docs/react/customize-theme#customize-design-token', - customizeComponentTokenLink: 'docs/react/customize-theme#customize-component-token', - }, -}; - -const useStyle = createStyles(({ token }) => ({ - tableTitle: css` - cursor: pointer; - position: relative; - display: flex; - align-items: center; - justify-content: flex-start; - line-height: 40px; - gap: ${token.marginXS}px; - `, - arrowIcon: css` - font-size: ${token.fontSizeLG}px; - & svg { - transition: all ${token.motionDurationSlow}; - } - `, - help: css` - font-size: ${token.fontSizeSM}px; - font-weight: normal; - color: #999; - a { - color: #999; - } - `, - tokenTitle: css` - font-size: ${token.fontSizeLG}px; - font-weight: bold; - `, -})); - -interface SubTokenTableProps { - defaultOpen?: boolean; - title: string; - helpText: React.ReactNode; - helpLink: string; - tokens: string[]; - component?: string; - comment?: { - componentComment?: string; - globalComment?: string; - }; -} - -const SubTokenTable: React.FC = (props) => { - const { defaultOpen, tokens, title, helpText, helpLink, component, comment } = props; - const [, lang] = useLocale(locales); - const token = useTheme(); - const columns = useColumns(); - - const [open, setOpen] = useState(defaultOpen ?? process.env.NODE_ENV !== 'production'); - - const { styles } = useStyle(); - - if (!tokens.length) { - return null; - } - - const data = tokens - .sort(component ? undefined : compare) - .map((name) => { - const meta = component - ? xTokenMeta.components[component].find((item: { token: string }) => item.token === name) - : xTokenMeta.global?.[name]; - - if (!meta) { - return null as unknown as TokenData; - } - - return { - name, - desc: lang === 'cn' ? meta.desc : meta.descEn, - type: meta.type, - value: component ? xTokenData[component].component[name] : defaultToken[name], - }; - }) - .filter(Boolean); - - const code = component - ? ` - ... -` - : ` - ... -`; - - return ( - <> -

      setOpen(!open)}> - - - {title} - -
      -                  {code}
      -                
      - - - {helpText} - - - } - > - - - {helpText} - -
      -
      -
      - {open && ( - - - size="middle" - columns={columns} - bordered - dataSource={data} - style={{ marginBottom: token.margin }} - pagination={false} - rowKey={(record) => record.name} - /> - - )} - - ); -}; - -export interface ComponentTokenTableProps { - component: string; -} - -const XMarkdownComponentTokenTable: React.FC = ({ component }) => { - const [locale] = useLocale(locales); - const [mergedGlobalTokens] = useMemo(() => { - const globalTokenSet = new Set(); - - component.split(',').forEach((comp) => { - const { global: globalTokens = [] } = xTokenData?.[comp] || {}; - - globalTokens.forEach((token: string) => { - globalTokenSet.add(token); - }); - }); - - return [Array.from(globalTokenSet)] as const; - }, [component]); - return ( - <> - {xTokenMeta?.components?.[component] && ( - item.token)} - component={component} - comment={{ - componentComment: locale.componentComment, - globalComment: locale.globalComment, - }} - /> - )} - - - ); -}; - -export default React.memo(XMarkdownComponentTokenTable); diff --git a/packages/x/.fatherrc.ts b/packages/x/.fatherrc.ts index fe3201575..1f0a50fa4 100644 --- a/packages/x/.fatherrc.ts +++ b/packages/x/.fatherrc.ts @@ -35,39 +35,50 @@ export default defineConfig({ umd: { entry: 'components/index.ts', name: 'antdx', - bundler: 'utoopack', + bundler: 'webpack', output: { path: 'dist/', filename: 'antdx', }, sourcemap: true, generateUnminified: true, - concatenateModules: true, + concatenateModules: false, rootPath: path.resolve(__dirname, '../../'), externals: { react: { root: 'React', commonjs: 'react', + commonjs2: 'react', }, 'react-dom': { root: 'ReactDOM', commonjs: 'react-dom', + commonjs2: 'react-dom', }, '@ant-design/cssinjs': { root: 'antdCssinjs', commonjs: 'antdCssinjs', + commonjs2: 'antdCssinjs', }, '@ant-design/icons': { root: 'icons', commonjs: 'icons', + commonjs2: 'icons', }, dayjs: { root: 'dayjs', commonjs: 'dayjs', + commonjs2: 'dayjs', }, antd: { root: 'antd', commonjs: 'antd', + commonjs2: 'antd', + }, + mermaid: { + root: 'mermaid', + commonjs: 'mermaid', + commonjs2: 'mermaid', }, }, transformRuntime: { @@ -86,12 +97,17 @@ export default defineConfig({ memo.plugin('circular-dependency-checker').use(CircularDependencyPlugin, [ { failOnError: true, + // mermaid + exclude: /node_modules[\\/](chevrotain|d3-.*|langium)/, }, ]); memo.plugin('duplicate-package-checker').use(DuplicatePackageCheckerPlugin, [ { verbose: true, emitError: true, + // mermaid + exclude: ({ name }) => + ['cose-base', 'layout-base', 'internmap'].includes(name) || name.startsWith('d3-'), }, ]); } diff --git a/packages/x/.jest.js b/packages/x/.jest.js index b88492da8..6bc90a3b8 100644 --- a/packages/x/.jest.js +++ b/packages/x/.jest.js @@ -5,6 +5,32 @@ const compileModules = [ '@ant-design', 'countup.js', '.pnpm', + 'react-syntax-highlighter', + 'mermaid', + 'khroma', + 'd3', + 'd3-', + 'refractor', + 'hastscript', + 'hast-util-parse-selector', + 'property-information', + 'space-separated-tokens', + 'comma-separated-tokens', + 'unist-util-visit', + 'unist-util-is', + 'bail', + 'trough', + 'vfile', + 'vfile-message', + 'parse-entities', + 'character-entities', + 'character-entities-legacy', + 'character-reference-invalid', + 'is-decimal', + 'is-hexadecimal', + 'is-alphanumerical', + 'is-alphabetical', + 'decode-named-character-reference', ]; const resolve = (p) => require.resolve(`@ant-design/tools/lib/jest/${p}`); diff --git a/packages/x/components/_util/hooks/use-x-component-config.ts b/packages/x/components/_util/hooks/use-x-component-config.ts index 662d1faa5..b2a47045a 100644 --- a/packages/x/components/_util/hooks/use-x-component-config.ts +++ b/packages/x/components/_util/hooks/use-x-component-config.ts @@ -1,7 +1,6 @@ import React from 'react'; import type { XComponentConfig, XComponentsConfig } from '../../x-provider/context'; import XProviderContext from '../../x-provider/context'; -import { MarkdownComponentsConfig as XMarkdownComponentsConfig } from '../../x-provider/XMarkdownComponents'; const defaultXComponentStyleConfig: XComponentConfig = { classNames: {}, @@ -11,7 +10,7 @@ const defaultXComponentStyleConfig: XComponentConfig = { shortcutKeys: {}, }; -type MergeXComponentsConfig = XComponentsConfig & XMarkdownComponentsConfig; +type MergeXComponentsConfig = XComponentsConfig; const useXComponentConfig = ( component: C, ): Required[C] & XComponentConfig => { diff --git a/packages/x/components/bubble/__tests__/__snapshots__/demo-extend.test.ts.snap b/packages/x/components/bubble/__tests__/__snapshots__/demo-extend.test.ts.snap index 5543b813c..3bb97ba6a 100644 --- a/packages/x/components/bubble/__tests__/__snapshots__/demo-extend.test.ts.snap +++ b/packages/x/components/bubble/__tests__/__snapshots__/demo-extend.test.ts.snap @@ -3867,8 +3867,7 @@ exports[`renders components/bubble/demo/markdown.tsx extend context correctly 1` class="ant-typography css-var-_r_d_" >

      diff --git a/packages/x-markdown/src/plugins/HighlightCode/index.tsx b/packages/x/components/code-highlighter/CodeHighlighter.tsx similarity index 66% rename from packages/x-markdown/src/plugins/HighlightCode/index.tsx rename to packages/x/components/code-highlighter/CodeHighlighter.tsx index ddc6b7cac..485d46ea4 100644 --- a/packages/x-markdown/src/plugins/HighlightCode/index.tsx +++ b/packages/x/components/code-highlighter/CodeHighlighter.tsx @@ -1,11 +1,11 @@ -import useXComponentConfig from '@ant-design/x/es/_util/hooks/use-x-component-config'; -import Actions from '@ant-design/x/es/actions'; -import useXProviderContext from '@ant-design/x/es/x-provider/hooks/use-x-provider-context'; import classnames from 'classnames'; import React from 'react'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'; -import type { HighlightCodeProps } from '../type'; +import useXComponentConfig from '../_util/hooks/use-x-component-config'; +import Actions from '../actions'; +import { useXProviderContext } from '../x-provider'; +import type { CodeHighlighterProps } from './interface'; import useStyle from './style'; const customOneLight = { @@ -16,7 +16,7 @@ const customOneLight = { }, }; -const HighlightCode: React.FC = (props) => { +const CodeHighlighter = React.forwardRef((props, ref) => { const { lang, children, @@ -25,24 +25,25 @@ const HighlightCode: React.FC = (props) => { className, classNames = {}, styles = {}, - style, + style = {}, highlightProps, + ...restProps } = props; // ============================ Prefix ============================ const { getPrefixCls, direction } = useXProviderContext(); - const prefixCls = getPrefixCls('highlightCode', customizePrefixCls); + const prefixCls = getPrefixCls('codeHighlighter', customizePrefixCls); const [hashId, cssVarCls] = useStyle(prefixCls); // ===================== Component Config ========================= - const contextConfig = useXComponentConfig('highlightCode'); + const contextConfig = useXComponentConfig('codeHighlighter'); // ============================ style ============================ const mergedCls = classnames( prefixCls, contextConfig.className, className, - contextConfig.classNames.root, + contextConfig.classNames?.root, classNames.root, hashId, cssVarCls, @@ -51,6 +52,12 @@ const HighlightCode: React.FC = (props) => { }, ); + const mergedStyle = { + ...contextConfig.style, + ...styles?.root, + ...style, + }; + // ============================ render content ============================ const renderTitle = () => { if (header === null) return null; @@ -61,18 +68,18 @@ const HighlightCode: React.FC = (props) => {

      {lang} @@ -91,10 +98,10 @@ const HighlightCode: React.FC = (props) => { } return ( -
      +
      {renderTitle()}
      = (props) => {
      ); -}; +}); + +if (process.env.NODE_ENV !== 'production') { + CodeHighlighter.displayName = 'CodeHighlighter'; +} -export default HighlightCode; +export default CodeHighlighter; diff --git a/packages/x/components/code-highlighter/__tests__/index.test.tsx b/packages/x/components/code-highlighter/__tests__/index.test.tsx new file mode 100644 index 000000000..373a5f478 --- /dev/null +++ b/packages/x/components/code-highlighter/__tests__/index.test.tsx @@ -0,0 +1,114 @@ +import { render } from '@testing-library/react'; +import React from 'react'; +import CodeHighlighter from '../index'; + +jest.mock('react', () => ({ + ...jest.requireActual('react'), + useId: () => 'mock-id-123', +})); + +// Mock mermaid to avoid Jest transform issues with ES6+ syntax +jest.mock('mermaid', () => ({ + initialize: jest.fn(), + render: jest.fn().mockResolvedValue({ svg: '' }), +})); + +// Mock the mermaid component to avoid issues +jest.mock('../../mermaid', () => ({ + __esModule: true, + default: () =>
      Mermaid Diagram
      , +})); + +describe('CodeHighlighter', () => { + it('render normal code', () => { + const { container } = render( + {`console.log("javascript");`}, + ); + expect(container.querySelector('pre')).toBeInTheDocument(); + expect(container.querySelector('code')).toBeInTheDocument(); + expect(container.textContent).toContain('console.log("javascript");'); + }); + + it('render normal code with header', () => { + const { container } = render( + {`console.log("javascript");`}, + ); + expect(container.querySelector('.ant-codeHighlighter-header')).toBeInTheDocument(); + expect(container.querySelector('.ant-codeHighlighter-header')?.textContent).toContain( + 'javascript', + ); + }); + + it('render normal code with custom header class', () => { + const { container } = render( + + {`console.log("javascript");`} + , + ); + expect(container.querySelector('.customHeader')).toBeInTheDocument(); + }); + + it('render normal code with custom header', () => { + const { container } = render( + custom header
      } + > + {`console.log("javascript");`} + , + ); + expect(container.querySelector('.myCustomClass')).toBeInTheDocument(); + expect(container.querySelector('.myCustomClass')?.textContent).toContain('custom header'); + }); + + it('render normal code with no header', () => { + const { container } = render( + + {`console.log("javascript");`} + , + ); + expect(container.querySelector('.ant-codeHighlighter-header')).toBeNull(); + }); + + it('render normal code with no children', () => { + const { container } = render({''}); + expect(container.querySelector('code')).toBeNull(); + }); + + it('mermaid code is render as text', () => { + const { container } = render( + {`graph TD; A-->B;`}, + ); + expect(container.querySelector('pre')).toBeInTheDocument(); + expect(container.textContent).toContain('graph TD; A-->B;'); + }); + + it('should handle undefined lang', () => { + const { container } = render({`plain text`}); + expect(container.querySelector('code')).toBeInTheDocument(); + expect(container.textContent).toContain('plain text'); + }); + + it('should apply custom styles', () => { + const { container } = render( + + {`console.log("test");`} + , + ); + const root = container.firstChild as HTMLElement; + expect(root.style.backgroundColor).toBe('red'); + }); + + it('should forward ref correctly', () => { + const ref = React.createRef(); + const { container } = render( + + {`console.log("test");`} + , + ); + expect(ref.current).toBe(container.firstChild); + }); +}); diff --git a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/_semantic.tsx b/packages/x/components/code-highlighter/demo/_semantic.tsx similarity index 77% rename from packages/x/docs/x-markdown/demo/supersets/HighlightCode/_semantic.tsx rename to packages/x/components/code-highlighter/demo/_semantic.tsx index 7439254dc..d5acdcbf4 100644 --- a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/_semantic.tsx +++ b/packages/x/components/code-highlighter/demo/_semantic.tsx @@ -1,7 +1,7 @@ -import HighlightCode from '@ant-design/x-markdown/plugins/HighlightCode'; +import { CodeHighlighter } from '@ant-design/x'; import React from 'react'; -import SemanticPreview from '../../../../../.dumi/components/SemanticPreview'; -import useLocale from '../../../../../.dumi/hooks/useLocale'; +import SemanticPreview from '../../../.dumi/components/SemanticPreview'; +import useLocale from '../../../.dumi/hooks/useLocale'; const locales = { cn: { @@ -38,7 +38,7 @@ const App: React.FC = () => { { name: 'code', desc: locale.code }, ]} > - {content} + {content} ); }; diff --git a/packages/x/components/code-highlighter/demo/basic.tsx b/packages/x/components/code-highlighter/demo/basic.tsx new file mode 100644 index 000000000..ff35fdbda --- /dev/null +++ b/packages/x/components/code-highlighter/demo/basic.tsx @@ -0,0 +1,47 @@ +import React from 'react'; +import CodeHighlighter from '../index'; + +const App: React.FC = () => { + const code = `import React from 'react'; +import { Button } from 'antd'; + +const App = () => ( +
      + +
      +); + +export default App;`; + + return ( +
      +

      JavaScript Code

      + {code} + +

      CSS Code

      + + {`.container { + display: flex; + justify-content: center; + align-items: center; + height: 100vh; +}`} + + +

      HTML Code

      + + {` + + + My Page + + +

      Hello World

      + +`} +
      +
      + ); +}; + +export default App; diff --git a/packages/x/components/code-highlighter/demo/custom-header.tsx b/packages/x/components/code-highlighter/demo/custom-header.tsx new file mode 100644 index 000000000..ab912745a --- /dev/null +++ b/packages/x/components/code-highlighter/demo/custom-header.tsx @@ -0,0 +1,60 @@ +import { CodeHighlighter } from '@ant-design/x'; +import { Button, Space } from 'antd'; +import React from 'react'; + +const App = () => { + const code = `import { useState } from 'react'; + +function Counter() { + const [count, setCount] = useState(0); + return ( +
      +

      当前计数:{count}

      + +
      + ); +}`; + + const customHeader = ( +
      + + React 计数器示例 + + JavaScript + + + + + + +
      + ); + + return ( + + {code} + + ); +}; + +export default App; diff --git a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/basic.tsx b/packages/x/components/code-highlighter/demo/with-xmarkdown.tsx similarity index 94% rename from packages/x/docs/x-markdown/demo/supersets/HighlightCode/basic.tsx rename to packages/x/components/code-highlighter/demo/with-xmarkdown.tsx index 09d43294f..996a3392b 100644 --- a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/basic.tsx +++ b/packages/x/components/code-highlighter/demo/with-xmarkdown.tsx @@ -1,8 +1,8 @@ import { Bubble } from '@ant-design/x'; import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown'; -import HighlightCode from '@ant-design/x-markdown/plugins/HighlightCode'; import { Button, Flex } from 'antd'; import React from 'react'; +import CodeHighlighter from '../index'; const text = ` Here's a Python code block example that demonstrates how to calculate Fibonacci numbers: @@ -50,7 +50,7 @@ const Code: React.FC = (props) => { const lang = className?.match(/language-(\w+)/)?.[1] || ''; if (typeof children !== 'string') return null; - return {children}; + return {children}; }; const App = () => { diff --git a/packages/x/components/code-highlighter/index.en-US.md b/packages/x/components/code-highlighter/index.en-US.md new file mode 100644 index 000000000..1cc48872f --- /dev/null +++ b/packages/x/components/code-highlighter/index.en-US.md @@ -0,0 +1,55 @@ +--- +category: Components +group: + title: Feedback + order: 4 +title: CodeHighlighter +description: Used to highlight code formatting. +cover: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/_KKkTrXq7wcAAAAAKuAAAAgADtFMAQFr/original +coverDark: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/c62-S4SH1tUAAAAANuAAAAgADtFMAQFr/original +demo: + cols: 1 +--- + +## When to Use + +The CodeHighlighter component is used in scenarios where you need to display code snippets with syntax highlighting. + +- Used to display code snippets with syntax highlighting, providing copy functionality and header language information. +- When used in combination with XMarkdown, it can render code blocks within Markdown content and enhance highlighting display and interactive features. + +## Code Examples + + +Basic +Custom Header +With XMarkdown + +## API + +For common properties, refer to: [Common Properties](/docs/react/common-props). + +### CodeHighlighterProps + +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| lang | Language | `string` | - | +| children | Code content | `string` | - | +| header | Header | `React.ReactNode \| null` | React.ReactNode | +| className | Style class name | `string` | | +| classNames | Style class names | `string` | - | +| highlightProps | Code highlighting configuration | [`highlightProps`](https://github.com/react-syntax-highlighter/react-syntax-highlighter?tab=readme-ov-file#props) | - | + +### CodeHighlighterRef + +| Property | Description | Type | Version | +| ------------- | ------------------ | ----------- | ------- | +| nativeElement | Get native element | HTMLElement | - | + +## Semantic DOM + + + +## Theme Variables (Design Token) + + diff --git a/packages/x/components/code-highlighter/index.tsx b/packages/x/components/code-highlighter/index.tsx new file mode 100644 index 000000000..cbb85beee --- /dev/null +++ b/packages/x/components/code-highlighter/index.tsx @@ -0,0 +1,5 @@ +import CodeHighlighter from './CodeHighlighter'; +import type { CodeHighlighterProps } from './interface'; + +export type { CodeHighlighterProps }; +export default CodeHighlighter; diff --git a/packages/x/components/code-highlighter/index.zh-CN.md b/packages/x/components/code-highlighter/index.zh-CN.md new file mode 100644 index 000000000..b2d59fe18 --- /dev/null +++ b/packages/x/components/code-highlighter/index.zh-CN.md @@ -0,0 +1,56 @@ +--- +category: Components +group: + title: 反馈 + order: 4 +title: CodeHighlighter +subtitle: 代码高亮 +description: 用于高亮代码格式。 +cover: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/_KKkTrXq7wcAAAAAKuAAAAgADtFMAQFr/original +coverDark: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/c62-S4SH1tUAAAAANuAAAAgADtFMAQFr/original +demo: + cols: 1 +--- + +## 何时使用 + +CodeHighlighter 组件用于需要展示带有语法高亮的代码片段的场景。 + +- 用于展示带语法高亮的代码片段,并提供复制功能及头部语言信息。 +- 与 XMarkdown 结合使用,可在 Markdown 内容中渲染代码块,并增强高亮显示和交互功能。 + +## 代码演示 + + +基本 +自定义 Header +配合 XMarkdown + +## API + +通用属性参考:[通用属性](/docs/react/common-props)。 + +### CodeHighlighterProps + +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| lang | 语言 | `string` | - | +| children | 代码内容 | `string` | - | +| header | 顶部 | `React.ReactNode \| null` | React.ReactNode | +| className | 样式类名 | `string` | | +| classNames | 样式类名 | `string` | - | +| highlightProps | 代码高亮配置 | [`highlightProps`](https://github.com/react-syntax-highlighter/react-syntax-highlighter?tab=readme-ov-file#props) | - | + +### CodeHighlighterRef + +| 属性 | 说明 | 类型 | 版本 | +| ------------- | ------------ | ----------- | ---- | +| nativeElement | 获取原生节点 | HTMLElement | - | + +## Semantic DOM + + + +## 主题变量(Design Token) + + diff --git a/packages/x/components/code-highlighter/interface.ts b/packages/x/components/code-highlighter/interface.ts new file mode 100644 index 000000000..f6f411974 --- /dev/null +++ b/packages/x/components/code-highlighter/interface.ts @@ -0,0 +1,48 @@ +import type React from 'react'; +import type { SyntaxHighlighterProps } from 'react-syntax-highlighter'; + +type SemanticType = 'root' | 'header' | 'headerTitle' | 'code'; + +export interface CodeHighlighterProps + extends Omit, 'children'> { + /** + * @desc 代码语言类型 + * @descEN Code language type + */ + lang?: string; + /** + * @desc 代码内容 + * @descEN Code content + */ + children: string; + /** + * @desc 头部内容,为 null 时不显示头部 + * @descEN Header content, no header displayed when null + */ + header?: React.ReactNode | null; + /** + * @desc 样式类名的前缀 + * @descEN Prefix for style classnames + */ + prefixCls?: string; + /** + * @desc 根节点样式 + * @descEN Root node style + */ + style?: React.CSSProperties; + /** + * @desc 语法高亮器的额外属性 + * @descEN Additional props for syntax highlighter + */ + highlightProps?: Partial; + /** + * @desc 语义化结构 className + * @descEN Semantic structure class names + */ + classNames?: Partial>; + /** + * @desc 语义化结构 style + * @descEN Semantic structure styles + */ + styles?: Partial>; +} diff --git a/packages/x/components/code-highlighter/style/index.ts b/packages/x/components/code-highlighter/style/index.ts new file mode 100644 index 000000000..2c3677999 --- /dev/null +++ b/packages/x/components/code-highlighter/style/index.ts @@ -0,0 +1,88 @@ +import type { CSSObject } from '@ant-design/cssinjs'; +import { mergeToken } from '@ant-design/cssinjs-utils'; +import type { FullToken, GenerateStyle, GetDefaultToken } from '../../theme/cssinjs-utils'; +import { genStyleHooks } from '../../theme/genStyleUtils'; + +export interface ComponentToken { + /** + * @desc 标题背景颜色 + * @descEN Title background color + */ + colorBgTitle: string; + /** + * @desc 标题文本颜色 + * @descEN Title text color + */ + colorTextTitle: string; + /** + * @desc 代码块边框颜色 + * @descEN Code block border color + */ + colorBorderCode: string; +} + +export interface CodeHighlighterToken extends FullToken<'CodeHighlighter'> {} + +const genCodeHighlighterStyle: GenerateStyle = ( + token: CodeHighlighterToken, +): CSSObject => { + const { componentCls } = token; + + return { + [componentCls]: { + [`${componentCls}-header`]: { + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + color: token.colorText, + background: token.colorFillContent, + padding: token.paddingSM, + borderStartStartRadius: token.borderRadius, + borderStartEndRadius: token.borderRadius, + }, + [`${componentCls}-header-title`]: { + fontSize: token.fontSize, + fontWeight: token.fontWeightStrong, + }, + [`${componentCls}-code`]: { + borderEndEndRadius: token.borderRadius, + borderEndStartRadius: token.borderRadius, + borderStartStartRadius: 0, + borderStartEndRadius: 0, + background: token.colorBgContainer, + border: `1px solid ${token.colorBorderSecondary}`, + borderTop: 'none', + overflow: 'hidden', + 'pre,code': { + whiteSpace: 'pre', + fontSize: token.fontSize, + fontFamily: token.fontFamilyCode, + lineHeight: 2, + borderRadius: 0, + border: 'none', + }, + "code[class*='language-'],pre[class*='language-']": { + background: 'none', + }, + }, + [`&${componentCls}-rtl`]: { + direction: 'rtl', + }, + }, + }; +}; + +export const prepareComponentToken: GetDefaultToken<'CodeHighlighter'> = (token) => ({ + colorBgTitle: token.colorFillContent, + colorBorderCode: token.colorBorderSecondary, + colorTextTitle: token.colorText, +}); + +export default genStyleHooks( + 'CodeHighlighter', + (token) => { + const codeHighlighterToken = mergeToken(token, {}); + return [genCodeHighlighterStyle(codeHighlighterToken)]; + }, + prepareComponentToken, +); diff --git a/packages/x/components/index.ts b/packages/x/components/index.ts index f940b9d16..782fcadb9 100644 --- a/packages/x/components/index.ts +++ b/packages/x/components/index.ts @@ -6,10 +6,14 @@ export type { AttachmentsProps } from './attachments'; export { default as Attachments } from './attachments'; export type { BubbleItemType, BubbleListProps, BubbleProps } from './bubble'; export { default as Bubble } from './bubble'; +export type { CodeHighlighterProps } from './code-highlighter'; +export { default as CodeHighlighter } from './code-highlighter'; export type { ConversationItemType, ConversationsProps } from './conversations'; export { default as Conversations } from './conversations'; export type { FileCardListProps, FileCardProps } from './file-card'; export { default as FileCard } from './file-card'; +export type { MermaidProps } from './mermaid'; +export { default as Mermaid } from './mermaid'; export type { XNotificationOpenArgs } from './notification'; export { default as notification } from './notification'; export type { PromptsItemType, PromptsProps } from './prompts'; diff --git a/packages/x/components/locale/en_US.ts b/packages/x/components/locale/en_US.ts index 973bb8ba7..5edc12b00 100644 --- a/packages/x/components/locale/en_US.ts +++ b/packages/x/components/locale/en_US.ts @@ -1,6 +1,6 @@ -import type { xLocale, xMarkdownLocale } from '.'; +import type { xLocale } from '.'; -const localeValues: Required = { +const localeValues: Required = { locale: 'en', Conversations: { create: 'New chat', @@ -22,8 +22,6 @@ const localeValues: Required = { editableCancel: 'Cancel', }, Mermaid: { - copySuccess: 'Copied', - copy: 'Copy code', zoomIn: 'Zoom in', zoomOut: 'Zoom out', zoomReset: 'Reset', @@ -31,10 +29,6 @@ const localeValues: Required = { code: 'Code', image: 'Image', }, - HighlightCode: { - copySuccess: 'Copied', - copy: 'Copy code', - }, }; export default localeValues; diff --git a/packages/x/components/locale/index.tsx b/packages/x/components/locale/index.tsx index dd6aa0952..50d5b760f 100644 --- a/packages/x/components/locale/index.tsx +++ b/packages/x/components/locale/index.tsx @@ -29,12 +29,7 @@ export interface xLocale { editableOk: string; editableCancel: string; }; -} - -export interface xMarkdownLocale { Mermaid?: { - copySuccess: string; - copy: string; zoomIn: string; zoomOut: string; zoomReset: string; @@ -42,12 +37,9 @@ export interface xMarkdownLocale { code: string; image: string; }; - HighlightCode?: { - copySuccess: string; - copy: string; - }; } -export type Locale = xLocale & antdLocale & xMarkdownLocale; + +export type Locale = xLocale & antdLocale; export interface LocaleProviderProps { locale: Locale; diff --git a/packages/x/components/locale/useLocale.ts b/packages/x/components/locale/useLocale.ts index d4272694c..93a4a432b 100644 --- a/packages/x/components/locale/useLocale.ts +++ b/packages/x/components/locale/useLocale.ts @@ -1,17 +1,13 @@ import type { LocaleComponentName as AntdLocaleContextProps } from 'antd/es/locale/useLocale'; import defaultAntdEnUS from 'antd/locale/en_US'; import * as React from 'react'; -import type { Locale, xLocale, xMarkdownLocale } from '.'; +import type { Locale, xLocale } from '.'; import type { LocaleContextProps } from './context'; import LocaleContext from './context'; import defaultLocaleData from './en_US'; type LocaleComponentName = Exclude; -type MarkdownComponentName = Exclude; -type mergeLocaleComponentName = - | LocaleComponentName - | AntdLocaleContextProps - | MarkdownComponentName; +type mergeLocaleComponentName = LocaleComponentName | AntdLocaleContextProps; const useLocale = ( componentName: C, defaultLocale?: Locale[C] | (() => Locale[C]), diff --git a/packages/x/components/locale/zh_CN.ts b/packages/x/components/locale/zh_CN.ts index 1f9b5820a..2192217d3 100644 --- a/packages/x/components/locale/zh_CN.ts +++ b/packages/x/components/locale/zh_CN.ts @@ -1,6 +1,6 @@ -import type { xLocale, xMarkdownLocale } from './index'; +import type { xLocale } from './index'; -const localeValues: Required = { +const localeValues: Required = { locale: 'zh-cn', Conversations: { create: '新对话', @@ -22,8 +22,6 @@ const localeValues: Required = { editableCancel: '取消', }, Mermaid: { - copySuccess: '复制成功', - copy: '复制代码', zoomIn: '放大', zoomOut: '缩小', zoomReset: '重置', @@ -31,10 +29,6 @@ const localeValues: Required = { code: '代码', image: '图片', }, - HighlightCode: { - copySuccess: '复制成功', - copy: '复制代码', - }, }; export default localeValues; diff --git a/packages/x-markdown/src/plugins/Mermaid/index.tsx b/packages/x/components/mermaid/Mermaid.tsx similarity index 81% rename from packages/x-markdown/src/plugins/Mermaid/index.tsx rename to packages/x/components/mermaid/Mermaid.tsx index cccc6a2e8..e2656b48a 100644 --- a/packages/x-markdown/src/plugins/Mermaid/index.tsx +++ b/packages/x/components/mermaid/Mermaid.tsx @@ -1,31 +1,37 @@ import { DownloadOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons'; -import useXComponentConfig from '@ant-design/x/es/_util/hooks/use-x-component-config'; -import Actions from '@ant-design/x/es/actions'; -import { ItemType } from '@ant-design/x/es/actions/interface'; -import useLocale from '@ant-design/x/es/locale/useLocale'; -import useXProviderContext from '@ant-design/x/es/x-provider/hooks/use-x-provider-context'; -import locale_EN from '@ant-design/x/locale/en_US'; import { Button, Segmented, Tooltip } from 'antd'; import classnames from 'classnames'; import throttle from 'lodash.throttle'; -import mermaid from 'mermaid'; import React, { useEffect, useRef, useState } from 'react'; import SyntaxHighlighter from 'react-syntax-highlighter'; -import type { MermaidProps } from '../type'; +import useXComponentConfig from '../_util/hooks/use-x-component-config'; +import Actions from '../actions'; +import type { ItemType } from '../actions/interface'; +import locale_EN from '../locale/en_US'; +import useLocale from '../locale/useLocale'; +import { useXProviderContext } from '../x-provider'; import useStyle from './style'; +export type MermaidType = 'root' | 'header' | 'graph' | 'code'; + +export interface MermaidProps { + children: string; + header?: React.ReactNode | null; + prefixCls?: string; + style?: React.CSSProperties; + className?: string; + highlightProps?: Partial>; + // Semantic + classNames?: Partial>; + styles?: Partial>; + onRenderTypeChange?: (value: RenderType) => void; +} + enum RenderType { Code = 'code', Image = 'image', } -mermaid.initialize({ - startOnLoad: false, - securityLevel: 'strict', - theme: 'default', - fontFamily: 'monospace', -}); - let uuid = 0; const Mermaid: React.FC = React.memo((props) => { @@ -38,6 +44,7 @@ const Mermaid: React.FC = React.memo((props) => { header, children, highlightProps, + onRenderTypeChange, } = props; const [renderType, setRenderType] = useState(RenderType.Image); const [scale, setScale] = useState(1); @@ -45,6 +52,7 @@ const Mermaid: React.FC = React.memo((props) => { const [isDragging, setIsDragging] = useState(false); const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 }); const containerRef = useRef(null); + const mermaidRef = useRef(null); const id = `mermaid-${uuid++}-${children?.length || 0}`; // ============================ locale ============================ @@ -62,7 +70,7 @@ const Mermaid: React.FC = React.memo((props) => { const mergedCls = classnames( prefixCls, contextConfig.className, - contextConfig.classNames.root, + contextConfig.classNames?.root, className, classNames.root, hashId, @@ -77,12 +85,23 @@ const Mermaid: React.FC = React.memo((props) => { if (!children || !containerRef.current || renderType === RenderType.Code) return; try { - const isValid = await mermaid.parse(children, { suppressErrors: true }); + if (!mermaidRef.current) { + const mermaidModule = await import('mermaid'); + mermaidRef.current = mermaidModule.default; + mermaidRef.current.initialize({ + startOnLoad: false, + securityLevel: 'strict', + theme: 'default', + fontFamily: 'monospace', + }); + } + + const isValid = await mermaidRef.current.parse(children, { suppressErrors: true }); if (!isValid) throw new Error('Invalid Mermaid syntax'); const newText = children.replace(/[`\s]+$/g, ''); - const { svg } = await mermaid.render(id, newText, containerRef.current); + const { svg } = await mermaidRef.current.render(id, newText, containerRef.current); containerRef.current.innerHTML = svg; } catch (error) { @@ -256,10 +275,10 @@ const Mermaid: React.FC = React.memo((props) => {
      = React.memo((props) => { { label: contextLocale.code, value: RenderType.Code }, ]} value={renderType} - onChange={setRenderType} + onChange={(value) => { + setRenderType(value as RenderType); + onRenderTypeChange?.(value as RenderType); + }} />
      @@ -280,11 +302,11 @@ const Mermaid: React.FC = React.memo((props) => {
      = React.memo((props) => {
      = React.memo((props) => { return (
      {renderHeader()} {renderContent()} diff --git a/packages/x-markdown/src/plugins/Mermaid/__test__/index.test.tsx b/packages/x/components/mermaid/__tests__/index.test.tsx similarity index 85% rename from packages/x-markdown/src/plugins/Mermaid/__test__/index.test.tsx rename to packages/x/components/mermaid/__tests__/index.test.tsx index da5844b6c..a32c677ed 100644 --- a/packages/x-markdown/src/plugins/Mermaid/__test__/index.test.tsx +++ b/packages/x/components/mermaid/__tests__/index.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import React from 'react'; -import Mermaid from '../index'; +import Mermaid from '../Mermaid'; // Mock mermaid jest.mock('mermaid', () => ({ @@ -55,7 +55,7 @@ jest.mock('antd', () => { const mermaidContent = 'graph TD; A-->B;'; -describe('Mermaid Plugin', () => { +describe('Mermaid Component', () => { const mockMermaid = require('mermaid'); const mockParse = mockMermaid.parse as jest.Mock; const mockRender = mockMermaid.render as jest.Mock; @@ -135,12 +135,12 @@ describe('Mermaid Plugin', () => { render({mermaidContent}); - // 切换到代码视图 + // 切换到代码模式以显示复制按钮 const codeButton = screen.getByText('Code'); fireEvent.click(codeButton); - // 查找复制按钮 - 使用 aria-label 或 role - const copyButton = screen.getByLabelText('Copy'); + // 查找复制按钮 - 使用更通用的选择器 + const copyButton = screen.getByRole('button', { name: /copy/i }); fireEvent.click(copyButton); await waitFor(() => { @@ -159,11 +159,11 @@ describe('Mermaid Plugin', () => { render({mermaidContent}); - // 切换到代码视图 + // 切换到代码模式 const codeButton = screen.getByText('Code'); fireEvent.click(codeButton); - const copyButton = screen.getByLabelText('Copy'); + const copyButton = screen.getByRole('button', { name: /copy/i }); // 确保点击不会抛出错误 expect(() => fireEvent.click(copyButton)).not.toThrow(); @@ -183,21 +183,27 @@ describe('Mermaid Plugin', () => { value: mockClipboard, }); + // Mock console.error to catch the error + const consoleSpy = jest.spyOn(console, 'error').mockImplementation(); + render({mermaidContent}); - // 切换到代码视图 + // 切换到代码模式 const codeButton = screen.getByText('Code'); fireEvent.click(codeButton); - const copyButton = screen.getByLabelText('Copy'); - - // 确保点击不会抛出错误 - expect(() => fireEvent.click(copyButton)).not.toThrow(); + const copyButton = screen.getByRole('button', { name: /copy/i }); + fireEvent.click(copyButton); - // 验证剪贴板被调用,即使失败也不会抛出错误 + // 等待异步操作完成 await waitFor(() => { expect(mockClipboard.writeText).toHaveBeenCalledWith('graph TD; A-->B;'); }); + + // 由于错误被Actions.Copy组件内部处理,我们验证剪贴板调用即可 + expect(mockClipboard.writeText).toHaveBeenCalled(); + + consoleSpy.mockRestore(); }); }); @@ -349,6 +355,66 @@ describe('Mermaid Plugin', () => { }); }); + describe('onChange Event', () => { + it('should trigger onChange when switching to code view', () => { + const onChangeMock = jest.fn(); + render({mermaidContent}); + + const codeButton = screen.getByText('Code'); + fireEvent.click(codeButton); + + expect(onChangeMock).toHaveBeenCalledTimes(1); + expect(onChangeMock).toHaveBeenCalledWith('code'); + }); + + it('should trigger onChange when switching to image view', () => { + const onChangeMock = jest.fn(); + render({mermaidContent}); + + // 先切换到代码模式 + const codeButton = screen.getByText('Code'); + fireEvent.click(codeButton); + expect(onChangeMock).toHaveBeenCalledWith('code'); + + // 再切换回图片模式 + const imageButton = screen.getByText('Image'); + fireEvent.click(imageButton); + + expect(onChangeMock).toHaveBeenCalledTimes(2); + expect(onChangeMock).toHaveBeenCalledWith('image'); + }); + + it('should not trigger onChange when onChange prop is not provided', () => { + const { container } = render({mermaidContent}); + + const codeButton = screen.getByText('Code'); + fireEvent.click(codeButton); + + // 没有 onChange prop,不应该抛出错误 + expect(container.querySelector('.ant-mermaid')).toBeInTheDocument(); + }); + + it('should handle multiple mode switches with onChange', () => { + const onChangeMock = jest.fn(); + render({mermaidContent}); + + const codeButton = screen.getByText('Code'); + const imageButton = screen.getByText('Image'); + + // 多次切换 + fireEvent.click(codeButton); + fireEvent.click(imageButton); + fireEvent.click(codeButton); + fireEvent.click(imageButton); + + expect(onChangeMock).toHaveBeenCalledTimes(4); + expect(onChangeMock).toHaveBeenNthCalledWith(1, 'code'); + expect(onChangeMock).toHaveBeenNthCalledWith(2, 'image'); + expect(onChangeMock).toHaveBeenNthCalledWith(3, 'code'); + expect(onChangeMock).toHaveBeenNthCalledWith(4, 'image'); + }); + }); + describe('Error Handling', () => { it('should handle mermaid render errors', async () => { mockRender.mockRejectedValue(new Error('Render error')); diff --git a/packages/x/docs/x-markdown/demo/supersets/Mermaid/_semantic.tsx b/packages/x/components/mermaid/demo/_semantic.tsx similarity index 62% rename from packages/x/docs/x-markdown/demo/supersets/Mermaid/_semantic.tsx rename to packages/x/components/mermaid/demo/_semantic.tsx index de550f2ec..95a1a94a3 100644 --- a/packages/x/docs/x-markdown/demo/supersets/Mermaid/_semantic.tsx +++ b/packages/x/components/mermaid/demo/_semantic.tsx @@ -1,7 +1,7 @@ -import Mermaid from '@ant-design/x-markdown/plugins/Mermaid'; -import React from 'react'; -import SemanticPreview from '../../../../../.dumi/components/SemanticPreview'; -import useLocale from '../../../../../.dumi/hooks/useLocale'; +import { Mermaid } from '@ant-design/x'; +import React, { useState } from 'react'; +import SemanticPreview from '../../../.dumi/components/SemanticPreview'; +import useLocale from '../../../.dumi/hooks/useLocale'; const locales = { cn: { @@ -18,8 +18,7 @@ const locales = { }, }; -const content = ` -graph TD +const content = `graph TD A[Start] --> B{Data Valid?} B -->|Yes| C[Process Data] B -->|No| D[Error Handling] @@ -31,6 +30,7 @@ graph TD const App: React.FC = () => { const [locale] = useLocale(locales); + const [renderType, setRenderType] = useState('image'); return ( { semantics={[ { name: 'root', desc: locale.root }, { name: 'header', desc: locale.header }, - { name: 'graph', desc: locale.graph }, - { name: 'code', desc: locale.code }, + renderType === 'image' + ? { name: 'graph', desc: locale.graph } + : { name: 'code', desc: locale.code }, ]} > - {content} + setRenderType(value)}>{content} ); }; diff --git a/packages/x/components/mermaid/demo/basic.tsx b/packages/x/components/mermaid/demo/basic.tsx new file mode 100644 index 000000000..25f02e7e0 --- /dev/null +++ b/packages/x/components/mermaid/demo/basic.tsx @@ -0,0 +1,15 @@ +import React from 'react'; +import Mermaid from '../Mermaid'; + +const App: React.FC = () => ( + + {`graph TD + A[开始] --> B{条件判断} + B -->|是| C[执行操作A] + B -->|否| D[执行操作B] + C --> E[结束] + D --> E`} + +); + +export default App; diff --git a/packages/x/components/mermaid/demo/custom-header.tsx b/packages/x/components/mermaid/demo/custom-header.tsx new file mode 100644 index 000000000..dd8263dd5 --- /dev/null +++ b/packages/x/components/mermaid/demo/custom-header.tsx @@ -0,0 +1,26 @@ +import { Button, Space } from 'antd'; +import React from 'react'; +import Mermaid from '../Mermaid'; + +const App: React.FC = () => { + const header = ( + + 流程图示例 + + + + ); + return ( + + {`flowchart LR + A[用户登录] --> B{验证身份} + B -->|成功| C[进入系统] + B -->|失败| D[显示错误] + C --> E[主界面] + D --> A`} + + ); +}; +export default App; diff --git a/packages/x/docs/x-markdown/demo/supersets/Mermaid/basic.tsx b/packages/x/components/mermaid/demo/with-xmarkdown.tsx similarity index 96% rename from packages/x/docs/x-markdown/demo/supersets/Mermaid/basic.tsx rename to packages/x/components/mermaid/demo/with-xmarkdown.tsx index c535c4181..1427aba17 100644 --- a/packages/x/docs/x-markdown/demo/supersets/Mermaid/basic.tsx +++ b/packages/x/components/mermaid/demo/with-xmarkdown.tsx @@ -1,6 +1,5 @@ -import { Bubble } from '@ant-design/x'; +import { Bubble, Mermaid } from '@ant-design/x'; import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown'; -import Mermaid from '@ant-design/x-markdown/plugins/Mermaid'; import { Button, Flex } from 'antd'; import React from 'react'; diff --git a/packages/x/components/mermaid/index.en-US.md b/packages/x/components/mermaid/index.en-US.md new file mode 100644 index 000000000..a6d841ac9 --- /dev/null +++ b/packages/x/components/mermaid/index.en-US.md @@ -0,0 +1,43 @@ +--- +category: Components +group: + title: Feedback + order: 4 +title: Mermaid +description: Used to render diagrams with Mermaid. +cover: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/yTn9SILS900AAAAAPaAAAAgADtFMAQFr/original +coverDark: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/uYcMRYLDTCMAAAAAQBAAAAgADtFMAQFr/original +demo: + cols: 1 +--- + +## When to Use + +- Used to render interactive Mermaid diagrams that support zooming, panning, and switching between image and code views in applications. +- When used together with XMarkdown, it can render Mermaid diagrams within Markdown content and enhance interactive features. + +## Code Demo + + +Basic +Custom Header +With XMarkdown + +## API + + +| Property | Description | Type | Default | +| --- | --- | --- | --- | +| children | Code content | `string` | - | +| header | Header | `React.ReactNode \| null` | React.ReactNode | +| className | Style class name | `string` | | +| classNames | Style class name | `string` | - | +| highlightProps | Code highlighting configuration | [`highlightProps`](https://github.com/react-syntax-highlighter/react-syntax-highlighter?tab=readme-ov-file#props) | - | + +## Semantic DOM + + + +## Theme Variables (Design Token) + + diff --git a/packages/x/components/mermaid/index.tsx b/packages/x/components/mermaid/index.tsx new file mode 100644 index 000000000..df9f5904f --- /dev/null +++ b/packages/x/components/mermaid/index.tsx @@ -0,0 +1,5 @@ +import Mermaid from './Mermaid'; + +export type { MermaidProps, MermaidType } from './Mermaid'; + +export default Mermaid; diff --git a/packages/x/components/mermaid/index.zh-CN.md b/packages/x/components/mermaid/index.zh-CN.md new file mode 100644 index 000000000..319ed1b20 --- /dev/null +++ b/packages/x/components/mermaid/index.zh-CN.md @@ -0,0 +1,44 @@ +--- +category: Components +group: + title: 反馈 + order: 4 +title: Mermaid +subtitle: 图表工具 +description: 用于渲染图表工具 Mermaid。 +cover: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/yTn9SILS900AAAAAPaAAAAgADtFMAQFr/original +coverDark: https://mdn.alipayobjects.com/huamei_lkxviz/afts/img/uYcMRYLDTCMAAAAAQBAAAAgADtFMAQFr/original +demo: + cols: 1 +--- + +## 何时使用 + +- 用于在应用中渲染支持缩放、平移、图像/代码双视图切换的交互式 Mermaid 图表。 +- 与 XMarkdown 结合使用,可在 Markdown 内容中渲染 Mermaid,并增强交互功能。 + +## 代码演示 + + +基本 +自定义 Header +配合 XMarkdown + +## API + + +| 属性 | 说明 | 类型 | 默认值 | +| --- | --- | --- | --- | +| children | 代码内容 | `string` | - | +| header | 顶部 | `React.ReactNode \| null` | React.ReactNode | +| className | 样式类名 | `string` | | +| classNames | 样式类名 | `string` | - | +| highlightProps | 代码高亮配置 | [`highlightProps`](https://github.com/react-syntax-highlighter/react-syntax-highlighter?tab=readme-ov-file#props) | - | + +## Semantic DOM + + + +## 主题变量(Design Token) + + diff --git a/packages/x-markdown/src/plugins/Mermaid/style/index.ts b/packages/x/components/mermaid/style/index.ts similarity index 64% rename from packages/x-markdown/src/plugins/Mermaid/style/index.ts rename to packages/x/components/mermaid/style/index.ts index bfd33f6a9..b878a3212 100644 --- a/packages/x-markdown/src/plugins/Mermaid/style/index.ts +++ b/packages/x/components/mermaid/style/index.ts @@ -1,8 +1,33 @@ import type { CSSObject } from '@ant-design/cssinjs'; import { mergeToken } from '@ant-design/cssinjs-utils'; +import type { FullToken, GenerateStyle, GetDefaultToken } from '../../theme/cssinjs-utils'; import { genStyleHooks } from '../../theme/genStyleUtils'; -import type { GenerateStyle } from '../../theme/interface'; -import type { FullToken, GetDefaultToken } from '../../theme/useToken'; + +export interface ComponentToken { + /** + * @desc 标题背景颜色 + * @descEN Title background color + */ + colorBgTitle: string; + + /** + * @desc 标题文本颜色 + * @descEN Title text color + */ + colorTextTitle: string; + + /** + * @desc 代码块边框颜色 + * @descEN Code block border color + */ + colorBorderCode: string; + + /** + * @desc 图表边框颜色 + * @descEN Graph border color + */ + colorBorderGraph: string; +} export interface MermaidToken extends FullToken<'Mermaid'> {} @@ -18,8 +43,8 @@ const genMermaidStyle: GenerateStyle = (token: MermaidToken): CSSO background: token.colorBgTitle, color: token.colorTextTitle, padding: token.paddingSM, - borderTopLeftRadius: token.borderRadius, - borderTopRightRadius: token.borderRadius, + borderStartStartRadius: token.borderRadius, + borderStartEndRadius: token.borderRadius, }, [`${componentCls}-graph`]: { display: 'flex', @@ -30,8 +55,8 @@ const genMermaidStyle: GenerateStyle = (token: MermaidToken): CSSO padding: token.paddingSM, background: token.colorBgContainer, overflow: 'auto', - borderBottomRightRadius: token.borderRadius, - borderBottomLeftRadius: token.borderRadius, + borderEndEndRadius: token.borderRadius, + borderEndStartRadius: token.borderRadius, }, [`${componentCls}-graph-hidden`]: { display: 'none', @@ -41,11 +66,11 @@ const genMermaidStyle: GenerateStyle = (token: MermaidToken): CSSO height: 'auto', }, [`${componentCls}-code`]: { - borderBottomRightRadius: token.borderRadius, - borderBottomLeftRadius: token.borderRadius, + borderEndEndRadius: token.borderRadius, + borderEndStartRadius: token.borderRadius, borderBottom: `1px solid ${token.colorBgTitle}`, - borderLeft: `1px solid ${token.colorBgTitle}`, - borderRight: `1px solid ${token.colorBgTitle}`, + borderInlineStart: `1px solid ${token.colorBgTitle}`, + borderInlineEnd: `1px solid ${token.colorBgTitle}`, background: token.colorBgContainer, paddingInline: token.paddingSM, paddingBlock: token.paddingSM, @@ -69,14 +94,12 @@ const genMermaidStyle: GenerateStyle = (token: MermaidToken): CSSO }; }; -export const prepareComponentToken: GetDefaultToken<'Mermaid'> = (token) => { - return { - colorBgTitle: token.colorFillContent, - colorBorderCode: token.colorBorderSecondary, - colorBorderGraph: token.colorBorderSecondary, - colorTextTitle: token.colorText, - }; -}; +export const prepareComponentToken: GetDefaultToken<'Mermaid'> = (token) => ({ + colorBgTitle: token.colorFillContent, + colorBorderCode: token.colorBorderSecondary, + colorBorderGraph: token.colorBorderSecondary, + colorTextTitle: token.colorText, +}); export default genStyleHooks<'Mermaid'>( 'Mermaid', diff --git a/packages/x/components/sources/index.en-US.md b/packages/x/components/sources/index.en-US.md index 484d75816..2522be649 100644 --- a/packages/x/components/sources/index.en-US.md +++ b/packages/x/components/sources/index.en-US.md @@ -1,8 +1,8 @@ --- category: Components group: - title: Confirmation - order: 3 + title: Feedback + order: 4 title: Sources description: Show the source address of the referenced data. cover: https://mdn.alipayobjects.com/huamei_b00jk5/afts/img/A*3nEPRYJbNQgAAAAAQFAAAAgAegitAQ/original diff --git a/packages/x/components/sources/index.zh-CN.md b/packages/x/components/sources/index.zh-CN.md index c80eca920..bd5cedd98 100644 --- a/packages/x/components/sources/index.zh-CN.md +++ b/packages/x/components/sources/index.zh-CN.md @@ -1,8 +1,8 @@ --- category: Sources group: - title: 确认 - order: 3 + title: 反馈 + order: 4 title: Sources subtitle: 来源引用 description: 展示引用的数据来源地址。 diff --git a/packages/x/components/theme/interface/components.ts b/packages/x/components/theme/interface/components.ts index a8c55ca5c..23d14d95c 100644 --- a/packages/x/components/theme/interface/components.ts +++ b/packages/x/components/theme/interface/components.ts @@ -1,8 +1,10 @@ import type { ComponentToken as ActionsToken } from '../../actions/style'; import type { ComponentToken as AttachmentsToken } from '../../attachments/style'; import type { ComponentToken as BubbleComponentToken } from '../../bubble/style'; +import type { ComponentToken as CodeHighlighterComponentToken } from '../../code-highlighter/style'; import type { ComponentToken as ConversationsComponentToken } from '../../conversations/style'; import type { ComponentToken as FileCardComponentToken } from '../../file-card/style'; +import type { ComponentToken as MermaidComponentToken } from '../../mermaid/style'; import type { ComponentToken as PromptsComponentToken } from '../../prompts/style'; import type { ComponentToken as SenderComponentToken } from '../../sender/style'; import type { ComponentToken as SourcesComponentToken } from '../../sources/style'; @@ -10,9 +12,8 @@ import type { ComponentToken as SuggestionComponentToken } from '../../suggestio import type { ComponentToken as ThinkComponentToken } from '../../think/style'; import type { ComponentToken as ThoughtChainComponentToken } from '../../thought-chain/style'; import type { ComponentToken as WelcomeComponentToken } from '../../welcome/style'; -import type { ComponentTokenMap as XMarkdownToken } from './XMarkdownComponents'; -export interface ComponentTokenMap extends XMarkdownToken { +export interface ComponentTokenMap { Attachments?: AttachmentsToken; Bubble?: BubbleComponentToken; Conversations?: ConversationsComponentToken; @@ -25,4 +26,6 @@ export interface ComponentTokenMap extends XMarkdownToken { Actions?: ActionsToken; FileCard?: FileCardComponentToken; Sources?: SourcesComponentToken; + CodeHighlighter?: CodeHighlighterComponentToken; + Mermaid?: MermaidComponentToken; } diff --git a/packages/x/components/x-provider/XMarkdownComponents.ts b/packages/x/components/x-provider/XMarkdownComponents.ts deleted file mode 100644 index da242f1b3..000000000 --- a/packages/x/components/x-provider/XMarkdownComponents.ts +++ /dev/null @@ -1,71 +0,0 @@ -import type { KatexOptions } from 'katex'; -import type { TokenizerAndRendererExtension } from 'marked'; -import type { ReactNode } from 'react'; -import type { SyntaxHighlighterProps } from 'react-syntax-highlighter'; - -export type LatexOption = { - katexOptions?: KatexOptions; - replaceAlignStart?: boolean; -}; - -type HighlightCodeType = 'root' | 'header' | 'headerTitle' | 'code'; -export type HighlightCodeProps = { - lang?: string; - children: string; - header?: ReactNode | null; - prefixCls?: string; - style?: React.CSSProperties; - className?: string; - highlightProps?: Partial; - // Semantic - classNames?: Partial>; - styles?: Partial>; -}; - -type MermaidType = 'root' | 'header' | 'graph' | 'code'; -export type MermaidProps = { - children: string; - header?: ReactNode | null; - prefixCls?: string; - style?: React.CSSProperties; - className?: string; - highlightProps?: Partial; - // Semantic - classNames?: Partial>; - styles?: Partial>; -}; - -interface BaseComponentConfig { - style: React.CSSProperties; - styles: Record; - className: string; - classNames: Record; -} - -type ComponentConfig< - CompProps extends Record, - PickType extends keyof CompProps = keyof BaseComponentConfig, -> = Pick; - -export interface MarkdownComponentsConfig { - highlightCode?: ComponentConfig; - mermaid?: ComponentConfig; -} - -export type PluginsType = { - /** - * @desc 渲染数学公式Latex语法。 - * @descEN Rendering mathematical formulas using Latex syntax. - */ - Latex: (options?: LatexOption) => TokenizerAndRendererExtension[]; - /** - * @desc 渲染代码高亮。 - * @descEN Highlight the rendering code. - */ - HighlightCode: (props: HighlightCodeProps) => React.ReactNode; - /** - * @desc 渲染 Mermaid 图表。 - * @descEN Rendering the Mermaid Chart. - */ - Mermaid: (props: MermaidProps) => React.ReactNode; -}; diff --git a/packages/x/components/x-provider/context.ts b/packages/x/components/x-provider/context.ts index 9194cd16f..3582b4074 100644 --- a/packages/x/components/x-provider/context.ts +++ b/packages/x/components/x-provider/context.ts @@ -5,11 +5,13 @@ import type { import React from 'react'; import type { AnyObject, ShortcutKeys } from '../_util/type'; import type { ActionsProps } from '../actions/interface'; -import { AttachmentsProps } from '../attachments'; +import type { AttachmentsProps } from '../attachments'; import type { BubbleProps } from '../bubble'; +import type { CodeHighlighterProps } from '../code-highlighter'; import type { ConversationsProps } from '../conversations'; import type { FileCardProps } from '../file-card'; import { Locale } from '../locale'; +import type { MermaidProps } from '../mermaid'; import type { PromptsProps } from '../prompts'; import type { SenderProps } from '../sender'; import type { SourcesProps } from '../sources'; @@ -19,7 +21,6 @@ import { MappingAlgorithm } from '../theme/interface'; import type { ThinkProps } from '../think'; import type { ThoughtChainProps } from '../thought-chain'; import type { WelcomeProps } from '../welcome'; -import { MarkdownComponentsConfig as XMarkdownComponentsConfig } from './XMarkdownComponents'; interface BaseComponentConfig { style: React.CSSProperties; @@ -49,6 +50,8 @@ export interface XComponentsConfig { think?: ComponentConfig; fileCard?: ComponentConfig; sources?: ComponentConfig; + codeHighlighter?: ComponentConfig; + mermaid?: ComponentConfig; } type ComponentsConfig = { @@ -59,7 +62,6 @@ type ComponentsConfig = { export interface XProviderProps extends XComponentsConfig, - XMarkdownComponentsConfig, Omit { theme?: Omit & { components?: ThemeConfig['components'] & ComponentsConfig; diff --git a/packages/x/components/x-provider/index.tsx b/packages/x/components/x-provider/index.tsx index c01410210..0e76e0208 100644 --- a/packages/x/components/x-provider/index.tsx +++ b/packages/x/components/x-provider/index.tsx @@ -22,7 +22,7 @@ const XProvider: React.FC = (props) => { locale, children, mermaid, - highlightCode, + codeHighlighter, ...antdConfProps } = props; @@ -39,7 +39,7 @@ const XProvider: React.FC = (props) => { fileCard, think, mermaid, - highlightCode, + codeHighlighter, welcome, }; }, [ @@ -55,7 +55,7 @@ const XProvider: React.FC = (props) => { mermaid, think, fileCard, - highlightCode, + codeHighlighter, ]); let childNode = children; diff --git a/packages/x/docs/x-markdown/components-codeHighlighter.en-US.md b/packages/x/docs/x-markdown/components-codeHighlighter.en-US.md new file mode 100644 index 000000000..49ad9c47d --- /dev/null +++ b/packages/x/docs/x-markdown/components-codeHighlighter.en-US.md @@ -0,0 +1,14 @@ +--- +group: + title: Components + order: 5 +title: CodeHighlighter +order: 2 +--- + +Use with [`CodeHighlighter`](../../components/code-highlighter/index.en-US.md) to highlight code. + +## Code Demo + + + diff --git a/packages/x/docs/x-markdown/components-codeHighlighter.zh-CN.md b/packages/x/docs/x-markdown/components-codeHighlighter.zh-CN.md new file mode 100644 index 000000000..48441deec --- /dev/null +++ b/packages/x/docs/x-markdown/components-codeHighlighter.zh-CN.md @@ -0,0 +1,15 @@ +--- +group: + title: 组件 + order: 5 +title: CodeHighlighter +subtitle: 代码高亮 +order: 2 +--- + +配合 [`CodeHighlighter`](../../components/code-highlighter/index.zh-CN.md) 高亮代码。 + +## 代码演示 + + + diff --git a/packages/x/docs/x-markdown/components-custom.en-US.md b/packages/x/docs/x-markdown/components-custom.en-US.md index 062f7c460..63c3fb788 100644 --- a/packages/x/docs/x-markdown/components-custom.en-US.md +++ b/packages/x/docs/x-markdown/components-custom.en-US.md @@ -3,7 +3,7 @@ group: title: Components order: 5 title: Custom Component -order: 4 +order: 7 --- XMarkdown supports a highly flexible business component rendering mechanism, allowing developers to implement customized functionality through the following approaches: diff --git a/packages/x/docs/x-markdown/components-custom.zh-CN.md b/packages/x/docs/x-markdown/components-custom.zh-CN.md index 88672b15e..f12c8ab05 100644 --- a/packages/x/docs/x-markdown/components-custom.zh-CN.md +++ b/packages/x/docs/x-markdown/components-custom.zh-CN.md @@ -4,7 +4,7 @@ group: order: 5 title: Custom subtitle: 自定义组件 -order: 4 +order: 7 --- XMarkdown 支持高度灵活的业务组件渲染机制,开发者可通过以下方式实现定制化功能: diff --git a/packages/x/docs/x-markdown/components-data.en-US.md b/packages/x/docs/x-markdown/components-data.en-US.md index 17610b23d..907b95bfc 100644 --- a/packages/x/docs/x-markdown/components-data.en-US.md +++ b/packages/x/docs/x-markdown/components-data.en-US.md @@ -3,7 +3,7 @@ group: title: Components order: 5 title: DataChart -order: 3 +order: 5 --- Works with [`GPT-VIS`](https://github.com/antvis/GPT-Vis) to display loading states during streaming and show final results after streaming completes. diff --git a/packages/x/docs/x-markdown/components-data.zh-CN.md b/packages/x/docs/x-markdown/components-data.zh-CN.md index 12223d443..8580abcbd 100644 --- a/packages/x/docs/x-markdown/components-data.zh-CN.md +++ b/packages/x/docs/x-markdown/components-data.zh-CN.md @@ -4,7 +4,7 @@ group: order: 5 title: DataChart subtitle: 数据图表 -order: 3 +order: 5 --- 配合 [`GPT-VIS`](https://github.com/antvis/GPT-Vis) 在流式过程中展示 Loading 状态,流式结束后展示最终结果。 diff --git a/packages/x/docs/x-markdown/components-mermaid.en-US.md b/packages/x/docs/x-markdown/components-mermaid.en-US.md new file mode 100644 index 000000000..3e3c994e0 --- /dev/null +++ b/packages/x/docs/x-markdown/components-mermaid.en-US.md @@ -0,0 +1,14 @@ +--- +group: + title: Components + order: 5 +title: Mermaid +order: 3 +--- + +Use with [`Mermaid`](../../components/mermaid/index.en-US.md) to render graph. + +## Code Demo + + + diff --git a/packages/x/docs/x-markdown/components-mermaid.zh-CN.md b/packages/x/docs/x-markdown/components-mermaid.zh-CN.md new file mode 100644 index 000000000..a127fad18 --- /dev/null +++ b/packages/x/docs/x-markdown/components-mermaid.zh-CN.md @@ -0,0 +1,15 @@ +--- +group: + title: 组件 + order: 5 +title: Mermaid +subtitle: 图表工具 +order: 3 +--- + +配合 [`Mermaid`](../../components/mermaid/index.zh-CN.md) 渲染图表。 + +## 代码演示 + + + diff --git a/packages/x/docs/x-markdown/components-sources.en-US.md b/packages/x/docs/x-markdown/components-sources.en-US.md index ecb9dc00e..e770c6fc2 100644 --- a/packages/x/docs/x-markdown/components-sources.en-US.md +++ b/packages/x/docs/x-markdown/components-sources.en-US.md @@ -3,7 +3,7 @@ group: title: Components order: 5 title: Sources -order: 2 +order: 6 --- Use with [`sources`](../../components/sources/index.en-US.md) to render source references. diff --git a/packages/x/docs/x-markdown/components-sources.zh-CN.md b/packages/x/docs/x-markdown/components-sources.zh-CN.md index 9a6d32e32..873f9512b 100644 --- a/packages/x/docs/x-markdown/components-sources.zh-CN.md +++ b/packages/x/docs/x-markdown/components-sources.zh-CN.md @@ -4,7 +4,7 @@ group: order: 5 title: Sources subtitle: 来源应用 -order: 2 +order: 6 --- 配合 [`sources`](../../components/sources/index.zh-CN.md) 渲染来源引用。 diff --git a/packages/x/docs/x-markdown/components-think.en-US.md b/packages/x/docs/x-markdown/components-think.en-US.md index fc4a575c9..37913dc38 100644 --- a/packages/x/docs/x-markdown/components-think.en-US.md +++ b/packages/x/docs/x-markdown/components-think.en-US.md @@ -3,7 +3,7 @@ group: title: Components order: 5 title: Think -order: 2 +order: 4 --- Works with [`Think`](../../components/think/index.en-US.md) to automatically open during streaming and automatically close after streaming ends. diff --git a/packages/x/docs/x-markdown/components-think.zh-CN.md b/packages/x/docs/x-markdown/components-think.zh-CN.md index bd73d8c99..54e43ca01 100644 --- a/packages/x/docs/x-markdown/components-think.zh-CN.md +++ b/packages/x/docs/x-markdown/components-think.zh-CN.md @@ -4,7 +4,7 @@ group: order: 5 title: Think subtitle: 思考过程 -order: 2 +order: 4 --- 配合 [`Think`](../../components/think/index.zh-CN.md) 在流式过程中自动打开,流式结束后自动关闭。 diff --git a/packages/x/docs/x-markdown/demo/codeDemo/supersets.tsx b/packages/x/docs/x-markdown/demo/codeDemo/supersets.tsx index 74e73190f..7acde2ebd 100644 --- a/packages/x/docs/x-markdown/demo/codeDemo/supersets.tsx +++ b/packages/x/docs/x-markdown/demo/codeDemo/supersets.tsx @@ -1,7 +1,6 @@ +import { CodeHighlighter, Mermaid } from '@ant-design/x'; import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown'; -import HighlightCode from '@ant-design/x-markdown/plugins/HighlightCode'; import Latex from '@ant-design/x-markdown/plugins/Latex'; -import Mermaid from '@ant-design/x-markdown/plugins/Mermaid'; import React from 'react'; import { useMarkdownTheme } from '../_utils'; import '@ant-design/x-markdown/themes/light.css'; @@ -31,7 +30,7 @@ const Code: React.FC = (props) => { if (lang === 'mermaid') { return {children}; } - return {children}; + return {children}; }; const App: React.FC = () => { diff --git a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/streaming.tsx b/packages/x/docs/x-markdown/demo/components/codeHighlighter.tsx similarity index 92% rename from packages/x/docs/x-markdown/demo/supersets/HighlightCode/streaming.tsx rename to packages/x/docs/x-markdown/demo/components/codeHighlighter.tsx index 09d43294f..5188c89c0 100644 --- a/packages/x/docs/x-markdown/demo/supersets/HighlightCode/streaming.tsx +++ b/packages/x/docs/x-markdown/demo/components/codeHighlighter.tsx @@ -1,6 +1,5 @@ -import { Bubble } from '@ant-design/x'; +import { Bubble, CodeHighlighter } from '@ant-design/x'; import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown'; -import HighlightCode from '@ant-design/x-markdown/plugins/HighlightCode'; import { Button, Flex } from 'antd'; import React from 'react'; @@ -50,7 +49,7 @@ const Code: React.FC = (props) => { const lang = className?.match(/language-(\w+)/)?.[1] || ''; if (typeof children !== 'string') return null; - return {children}; + return {children}; }; const App = () => { diff --git a/packages/x/docs/x-markdown/demo/components/compare.tsx b/packages/x/docs/x-markdown/demo/components/compare.tsx deleted file mode 100644 index ea1064fb7..000000000 --- a/packages/x/docs/x-markdown/demo/components/compare.tsx +++ /dev/null @@ -1,184 +0,0 @@ -import { Button, Card, Col, Input, Row, Typography } from 'antd'; -import React, { useEffect, useRef, useState } from 'react'; -import '@ant-design/x-markdown/themes/light.css'; -import XMarkdown, { type ComponentProps } from '@ant-design/x-markdown'; -import HighlightCode from '@ant-design/x-markdown/plugins/HighlightCode'; -import ReactMarkdown from 'react-markdown'; -import rehypeRaw from 'rehype-raw'; -import remarkGfm from 'remark-gfm'; - -const { Title, Text } = Typography; -const { TextArea } = Input; - -const Code: React.FC = (props) => { - const { className, children } = props; - const lang = className?.match(/language-(\w+)/)?.[1] || ''; - - if (typeof children !== 'string') return null; - return {children}; -}; - -const App: React.FC = () => { - const [enableStreaming, setEnableStreaming] = useState(true); - const [hasNextChunk, setHasNextChunk] = useState(false); - const [className, setClassName] = useState('x-markdown-light'); - const [inputValue, setInputValue] = useState(`#### Image - - - -### Link - -[Ant Design X](https://x.ant.design/components/overview) - -### Emphasis - -*This is emphasis text* - -### Bold - -**This is bold text** - -### Code - -\`\`\`tsx -import React from 'react'; -import XMarkdown from '@ant-design/x-markdown'; - -const App = () => ; - -export default App; -\`\`\``); - - const [reactMarkdownContent, setReactMarkdownContent] = useState(''); - const [xMarkdownContent, setXMarkdownContent] = useState(''); - const intervalRef = useRef(null); - - useEffect(() => { - if (typeof window !== 'undefined') { - const urlParams = new URLSearchParams(window.location.search); - const theme = urlParams.get('theme'); - setClassName(theme === 'dark' ? 'x-markdown-dark' : 'x-markdown-light'); - } - }, []); - - const startComparison = () => { - // 清除之前的定时器 - if (intervalRef.current) { - clearInterval(intervalRef.current); - } - - // 重置内容 - setReactMarkdownContent(''); - setXMarkdownContent(''); - setHasNextChunk(true); - - let currentContent = ''; - const fullContent = inputValue; - - intervalRef.current = setInterval(() => { - const addCount = Math.floor(Math.random() * 30) + 1; - currentContent = fullContent.slice( - 0, - Math.min(currentContent.length + addCount, fullContent.length), - ); - - setReactMarkdownContent(currentContent); - - if (enableStreaming) { - setXMarkdownContent(currentContent); - } else { - setXMarkdownContent(fullContent); - } - - if (currentContent === fullContent) { - if (intervalRef.current) { - clearInterval(intervalRef.current); - } - setHasNextChunk(false); - } - }, 100); - }; - - useEffect(() => { - return () => { - if (intervalRef.current) { - clearInterval(intervalRef.current); - } - }; - }, []); - - return ( -
      -
      - - React-Markdown vs XMarkdown 对比演示 - - - 使用相同的Markdown内容,左侧展示react-markdown渲染效果,右侧展示XMarkdown渲染效果 - -
      - - - -