refactor(CodeBlock): support more file extensions for code downloading (#7192)

This commit is contained in:
one
2025-06-19 15:09:01 +08:00
committed by GitHub
parent 26cb37c9be
commit 28b58d8e49
6 changed files with 137 additions and 10 deletions
@@ -4,7 +4,7 @@ import { CodeTool, CodeToolbar, TOOL_SPECS, useCodeTool } from '@renderer/compon
import { useSettings } from '@renderer/hooks/useSettings'
import { pyodideService } from '@renderer/services/PyodideService'
import { extractTitle } from '@renderer/utils/formats'
import { isValidPlantUML } from '@renderer/utils/markdown'
import { getExtensionByLanguage, isValidPlantUML } from '@renderer/utils/markdown'
import dayjs from 'dayjs'
import { CirclePlay, CodeXml, Copy, Download, Eye, Square, SquarePen, SquareSplitHorizontal } from 'lucide-react'
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react'
@@ -67,23 +67,21 @@ const CodeBlockView: React.FC<Props> = ({ children, language, onSave }) => {
window.message.success({ content: t('code_block.copy.success'), key: 'copy-code' })
}, [children, t])
const handleDownloadSource = useCallback(() => {
const handleDownloadSource = useCallback(async () => {
let fileName = ''
// 尝试提取标题
// 尝试提取 HTML 标题
if (language === 'html' && children.includes('</html>')) {
const title = extractTitle(children)
if (title) {
fileName = `${title}.html`
}
fileName = extractTitle(children) || ''
}
// 默认使用日期格式命名
if (!fileName) {
fileName = `${dayjs().format('YYYYMMDDHHmm')}.${language}`
fileName = `${dayjs().format('YYYYMMDDHHmm')}`
}
window.api.file.save(fileName, children)
const ext = await getExtensionByLanguage(language)
window.api.file.save(`${fileName}${ext}`, children)
}, [children, language])
const handleRunScript = useCallback(() => {
@@ -7,6 +7,7 @@ import {
convertMathFormula,
findCitationInChildren,
getCodeBlockId,
getExtensionByLanguage,
markdownToPlainText,
removeTrailingDoubleSpaces,
updateCodeBlock
@@ -143,6 +144,67 @@ describe('markdown', () => {
})
})
describe('getExtensionByLanguage', () => {
// 批量测试语言名称到扩展名的映射
const testLanguageExtensions = async (testCases: Record<string, string>) => {
for (const [language, expectedExtension] of Object.entries(testCases)) {
const result = await getExtensionByLanguage(language)
expect(result).toBe(expectedExtension)
}
}
it('should return extension for exact language name match', async () => {
await testLanguageExtensions({
'4D': '.4dm',
'C#': '.cs',
JavaScript: '.js',
TypeScript: '.ts',
'Objective-C++': '.mm',
Python: '.py',
SVG: '.svg',
'Visual Basic .NET': '.vb'
})
})
it('should return extension for case-insensitive language name match', async () => {
await testLanguageExtensions({
'4d': '.4dm',
'c#': '.cs',
javascript: '.js',
typescript: '.ts',
'objective-c++': '.mm',
python: '.py',
svg: '.svg',
'visual basic .net': '.vb'
})
})
it('should return extension for language aliases', async () => {
await testLanguageExtensions({
js: '.js',
node: '.js',
'obj-c++': '.mm',
'objc++': '.mm',
'objectivec++': '.mm',
py: '.py',
'visual basic': '.vb'
})
})
it('should return fallback extension for unknown languages', async () => {
await testLanguageExtensions({
'unknown-language': '.unknown-language',
custom: '.custom'
})
})
it('should handle empty string input', async () => {
await testLanguageExtensions({
'': '.'
})
})
})
describe('getCodeBlockId', () => {
it('should generate ID from position information', () => {
// 从位置信息生成ID
+54
View File
@@ -54,6 +54,60 @@ export function removeTrailingDoubleSpaces(markdown: string): string {
return markdown.replace(/ {2}$/gm, '')
}
const predefinedExtensionMap: Record<string, string> = {
html: '.html',
javascript: '.js',
typescript: '.ts',
python: '.py',
json: '.json',
markdown: '.md',
text: '.txt'
}
/**
* 根据语言名称获取文件扩展名
* - 先精确匹配,再忽略大小写,最后匹配别名
* - 返回第一个扩展名
* @param language 语言名称
* @returns 文件扩展名
*/
export async function getExtensionByLanguage(language: string): Promise<string> {
const lowerLanguage = language.toLowerCase()
// 常用的扩展名
const predefined = predefinedExtensionMap[lowerLanguage]
if (predefined) {
return predefined
}
const languages = await import('linguist-languages')
// 精确匹配语言名称
const directMatch = languages[language as keyof typeof languages] as any
if (directMatch?.extensions?.[0]) {
return directMatch.extensions[0]
}
// 大小写不敏感的语言名称匹配
for (const [langName, data] of Object.entries(languages)) {
const languageData = data as any
if (langName.toLowerCase() === lowerLanguage && languageData.extensions?.[0]) {
return languageData.extensions[0]
}
}
// 通过别名匹配
for (const [, data] of Object.entries(languages)) {
const languageData = data as any
if (languageData.aliases?.includes(lowerLanguage)) {
return languageData.extensions?.[0] || `.${language}`
}
}
// 回退到语言名称
return `.${language}`
}
/**
* 根据代码块节点的起始位置生成 ID
* @param start 代码块节点的起始位置