- 脏标记行尾归一(含裸\r),CRLF 文件打开不再误报未保存 - 防抖回灌校验发起文件+flushEmit,杜绝串文件与丢尾 - F5/tab淘汰/读失败/草稿/重命名/保存刷新六处状态一致性修复 - GBK 文件按原编码回写(接口零改动),保存不再悄悄转 UTF-8 - .sh 系高亮根修(StreamLanguage 导入源错),面包屑长名截断 - CSV 大文件门豁免+表头贴顶;空标题滤除与 iframe 边距去除 - BGM 播放器增强收编(拖拽seek/音量/连播/快捷键/路径导航折叠) - 版本 0.5.3,CHANGELOG 同步
321 lines
11 KiB
TypeScript
321 lines
11 KiB
TypeScript
import { getHljsLanguage } from './languageMap'
|
||
|
||
let mermaidInstance: typeof import('mermaid').default | null = null
|
||
let mermaidTheme: string | null = null
|
||
|
||
// languageMap.ts(commonLangNames 直出 + 扩展名映射值)能产出的 hljs 语言全集。
|
||
// 用 lib/core + 逐语言异步 import 替代全量包(全量 ~190 种语言严重拖大首包);
|
||
// shell/cmd/html 是 bash/dos/xml 模块自带的别名,plaintext 为 hljs 内建,无需单独注册
|
||
const HLJS_LANGUAGES: Record<string, () => Promise<{ default: unknown }>> = {
|
||
javascript: () => import('highlight.js/lib/languages/javascript'),
|
||
typescript: () => import('highlight.js/lib/languages/typescript'),
|
||
python: () => import('highlight.js/lib/languages/python'),
|
||
java: () => import('highlight.js/lib/languages/java'),
|
||
go: () => import('highlight.js/lib/languages/go'),
|
||
rust: () => import('highlight.js/lib/languages/rust'),
|
||
c: () => import('highlight.js/lib/languages/c'),
|
||
cpp: () => import('highlight.js/lib/languages/cpp'),
|
||
csharp: () => import('highlight.js/lib/languages/csharp'),
|
||
php: () => import('highlight.js/lib/languages/php'),
|
||
ruby: () => import('highlight.js/lib/languages/ruby'),
|
||
swift: () => import('highlight.js/lib/languages/swift'),
|
||
kotlin: () => import('highlight.js/lib/languages/kotlin'),
|
||
scala: () => import('highlight.js/lib/languages/scala'),
|
||
dart: () => import('highlight.js/lib/languages/dart'),
|
||
lua: () => import('highlight.js/lib/languages/lua'),
|
||
r: () => import('highlight.js/lib/languages/r'),
|
||
bash: () => import('highlight.js/lib/languages/bash'),
|
||
powershell: () => import('highlight.js/lib/languages/powershell'),
|
||
dos: () => import('highlight.js/lib/languages/dos'),
|
||
sql: () => import('highlight.js/lib/languages/sql'),
|
||
yaml: () => import('highlight.js/lib/languages/yaml'),
|
||
json: () => import('highlight.js/lib/languages/json'),
|
||
xml: () => import('highlight.js/lib/languages/xml'),
|
||
markdown: () => import('highlight.js/lib/languages/markdown'),
|
||
css: () => import('highlight.js/lib/languages/css'),
|
||
scss: () => import('highlight.js/lib/languages/scss'),
|
||
less: () => import('highlight.js/lib/languages/less'),
|
||
ini: () => import('highlight.js/lib/languages/ini'),
|
||
makefile: () => import('highlight.js/lib/languages/makefile'),
|
||
dockerfile: () => import('highlight.js/lib/languages/dockerfile'),
|
||
cmake: () => import('highlight.js/lib/languages/cmake'),
|
||
latex: () => import('highlight.js/lib/languages/latex'),
|
||
objectivec: () => import('highlight.js/lib/languages/objectivec'),
|
||
autohotkey: () => import('highlight.js/lib/languages/autohotkey'),
|
||
diff: () => import('highlight.js/lib/languages/diff'),
|
||
graphql: () => import('highlight.js/lib/languages/graphql'),
|
||
nginx: () => import('highlight.js/lib/languages/nginx'),
|
||
perl: () => import('highlight.js/lib/languages/perl'),
|
||
haskell: () => import('highlight.js/lib/languages/haskell'),
|
||
elixir: () => import('highlight.js/lib/languages/elixir'),
|
||
erlang: () => import('highlight.js/lib/languages/erlang'),
|
||
clojure: () => import('highlight.js/lib/languages/clojure'),
|
||
ocaml: () => import('highlight.js/lib/languages/ocaml'),
|
||
vbnet: () => import('highlight.js/lib/languages/vbnet'),
|
||
wasm: () => import('highlight.js/lib/languages/wasm'),
|
||
fsharp: () => import('highlight.js/lib/languages/fsharp'),
|
||
groovy: () => import('highlight.js/lib/languages/groovy'),
|
||
julia: () => import('highlight.js/lib/languages/julia'),
|
||
matlab: () => import('highlight.js/lib/languages/matlab'),
|
||
}
|
||
|
||
// 懒加载 marked + hljs,首次调用时才初始化
|
||
let _marked: typeof import('marked').marked | null = null
|
||
let _initPromise: Promise<typeof import('marked').marked> | null = null
|
||
|
||
async function ensureMarked(): Promise<typeof import('marked').marked> {
|
||
if (_marked) return _marked
|
||
if (_initPromise) return _initPromise
|
||
|
||
_initPromise = (async () => {
|
||
const [markedModule, hljs, ...langModules] = await Promise.all([
|
||
import('marked'),
|
||
import('highlight.js/lib/core'),
|
||
...Object.values(HLJS_LANGUAGES).map(load => load()),
|
||
])
|
||
// 注册语言到 hljs core(Promise.all 保序,键序与模块序一一对应)
|
||
const hljsCore = hljs.default
|
||
const langNames = Object.keys(HLJS_LANGUAGES)
|
||
langNames.forEach((name, i) => {
|
||
hljsCore.registerLanguage(name, (langModules[i] as any).default)
|
||
})
|
||
|
||
const marked = markedModule.marked
|
||
const renderer = new marked.Renderer()
|
||
|
||
renderer.code = function(token: any) {
|
||
if (token.lang === 'mermaid') {
|
||
return `<pre class="mermaid">${token.text}</pre>`
|
||
}
|
||
|
||
const lang = getHljsLanguage(token.lang)
|
||
|
||
let highlighted: string
|
||
try {
|
||
highlighted = hljs.default.highlight(token.text, { language: lang }).value
|
||
} catch {
|
||
highlighted = token.text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||
}
|
||
return `<pre><code class="hljs language-${lang}" data-theme="auto">${highlighted}</code></pre>`
|
||
}
|
||
|
||
renderer.heading = function(token: any) {
|
||
const raw = token.raw || ''
|
||
const depth = token.depth || 1
|
||
const text = token.text || ''
|
||
|
||
const id = raw
|
||
.toLowerCase()
|
||
.replace(/[^一-龥a-z0-9\s-]/g, '')
|
||
.trim()
|
||
.replace(/\s+/g, '-')
|
||
.replace(/-+/g, '-')
|
||
.replace(/^-+|-+$/g, '') || `heading-${Math.random().toString(36).slice(2, 11)}`
|
||
|
||
return `<h${depth} id="${id}" class="heading">
|
||
${text}<a href="#${id}" class="heading-anchor" aria-hidden="true" title="跳转到此标题">#</a>
|
||
</h${depth}>`
|
||
}
|
||
|
||
// 图片/链接渲染器
|
||
renderer.image = createImageRenderer()
|
||
renderer.link = createLinkRenderer()
|
||
|
||
marked.use({ renderer, breaks: true, gfm: true, async: false })
|
||
|
||
_marked = marked
|
||
return marked
|
||
})()
|
||
|
||
return _initPromise
|
||
}
|
||
|
||
// ========== 图片相对路径转换支持 ==========
|
||
let _currentFileDir: string = ''
|
||
let _fileServerBase: string = 'http://localhost:2652/localfs'
|
||
|
||
export function setCurrentFileDir(dir: string): void {
|
||
_currentFileDir = dir
|
||
}
|
||
|
||
export function getCurrentFileDir(): string {
|
||
return _currentFileDir
|
||
}
|
||
|
||
export function setFileServerBase(base: string): void {
|
||
_fileServerBase = base
|
||
}
|
||
|
||
function resolveImageUrl(src: string, fileServerBase: string): string {
|
||
if (!src) return src
|
||
if (/^(?:[a-zA-Z]:[/\\]|\/(?:[^/]|$)|https?:|ftp:|data:|#)/i.test(src)) return src
|
||
|
||
const dir = _currentFileDir || '/'
|
||
const sep = dir.includes('\\') ? '\\' : '/'
|
||
let resolved = normalizeRelativePath(dir, src, sep)
|
||
|
||
const encoded = encodeURIComponent(resolved).replace(/%2F/gi, '/').replace(/%5C/gi, '\\')
|
||
return `${fileServerBase}/${encoded}`
|
||
}
|
||
|
||
function normalizeRelativePath(base: string, relative: string, sep: string): string {
|
||
let baseNormalized = base.replace(/[\\/]+$/, '')
|
||
if (!baseNormalized) baseNormalized = sep === '/' ? '/' : 'C:\\'
|
||
|
||
const baseParts = baseNormalized.split(sep).filter(Boolean)
|
||
const relParts = relative.split(/[\\/]/).filter(Boolean)
|
||
|
||
for (const part of relParts) {
|
||
if (part === '..') {
|
||
baseParts.pop()
|
||
} else if (part !== '.') {
|
||
baseParts.push(part)
|
||
}
|
||
}
|
||
|
||
if (/^[a-zA-Z]:$/i.test(baseNormalized.split(sep)[0] || '')) {
|
||
return baseParts.join(sep)
|
||
}
|
||
return sep + baseParts.join(sep)
|
||
}
|
||
|
||
const isLocalFileLink = (href: string): boolean => {
|
||
if (!href) return false
|
||
if (/^(https?|ftp|mailto|tel|data):/i.test(href)) return false
|
||
if (href.startsWith('#')) return false
|
||
return true
|
||
}
|
||
|
||
function createImageRenderer() {
|
||
return function(token: any) {
|
||
const src = token.href || ''
|
||
const title = token.title || ''
|
||
const alt = token.text || ''
|
||
const titleAttr = title ? ` title="${title}"` : ''
|
||
|
||
if (_currentFileDir && !/^(?:[a-zA-Z]:[/\\]|\/(?:[^/]|$)|https?:|ftp:|data:|#)/i.test(src)) {
|
||
const resolvedSrc = resolveImageUrl(src, _fileServerBase)
|
||
return `<img src="${resolvedSrc}" alt="${alt}"${titleAttr}>`
|
||
}
|
||
|
||
return `<img src="${src}" alt="${alt}"${titleAttr}>`
|
||
}
|
||
}
|
||
|
||
function createLinkRenderer() {
|
||
return function(this: any, token: any) {
|
||
const href = token.href || ''
|
||
const text = this.parser.parseInline(token.tokens) || token.text || ''
|
||
const title = token.title || ''
|
||
const titleAttr = title ? ` title="${title}"` : ''
|
||
|
||
if (href.startsWith('#')) {
|
||
return `<a href="${href}${titleAttr}">${text}</a>`
|
||
}
|
||
|
||
if (isLocalFileLink(href)) {
|
||
return `<a href="javascript:void(0)" data-local-link="${href}" class="local-file-link"${titleAttr}>${text}</a>`
|
||
}
|
||
|
||
return `<a href="${href}" target="_blank" rel="noopener noreferrer"${titleAttr}>${text}</a>`
|
||
}
|
||
}
|
||
|
||
// 检测当前是否为暗色主题
|
||
function isDarkTheme(): boolean {
|
||
if (typeof document === 'undefined') return false
|
||
return document.body.getAttribute('arco-theme')?.includes('dark') ?? false
|
||
}
|
||
|
||
async function loadMermaid() {
|
||
const currentTheme = isDarkTheme() ? 'dark' : 'default'
|
||
|
||
if (mermaidInstance && mermaidTheme === currentTheme) {
|
||
return mermaidInstance
|
||
}
|
||
|
||
if (!mermaidInstance) {
|
||
const m = await import('mermaid')
|
||
mermaidInstance = m.default
|
||
}
|
||
mermaidInstance.initialize({
|
||
startOnLoad: false,
|
||
theme: currentTheme,
|
||
securityLevel: 'strict',
|
||
themeVariables: Object.assign({
|
||
primaryColor: '#165DFF',
|
||
primaryTextColor: '#ffffff',
|
||
primaryBorderColor: '#4080FF'
|
||
}, currentTheme === 'dark' ? {
|
||
lineColor: '#4E5969',
|
||
secondaryColor: '#0E42D2',
|
||
tertiaryColor: '#0FC6C2',
|
||
mainBkg: '#17171A',
|
||
nodeBorder: '#165DFF',
|
||
clusterBkg: '#232324',
|
||
titleColor: '#FFFFFF',
|
||
edgeLabelBackground: '#232324'
|
||
} : {
|
||
lineColor: '#86909C',
|
||
secondaryColor: '#E8F3FF',
|
||
tertiaryColor: '#722ED1',
|
||
mainBkg: '#F2F3F5',
|
||
nodeBorder: '#165DFF',
|
||
clusterBkg: '#F7F8FA',
|
||
titleColor: '#1D2129',
|
||
edgeLabelBackground: '#F2F3F5'
|
||
})
|
||
})
|
||
mermaidTheme = currentTheme
|
||
return mermaidInstance
|
||
}
|
||
|
||
/** 同步渲染 Markdown(需先调用 ensureMarked 初始化) */
|
||
export async function renderMarkdown(content: string): Promise<string> {
|
||
const marked = await ensureMarked()
|
||
return marked.parse(content) as string
|
||
}
|
||
|
||
/** 检查 marked 是否已初始化(同步渲染用) */
|
||
export function isMarkedReady(): boolean {
|
||
return _marked !== null
|
||
}
|
||
|
||
/** 同步渲染(仅当已初始化时可用) */
|
||
export function parseMarkdown(content: string): string {
|
||
if (!_marked) return ''
|
||
const html = _marked.parse(content) as string
|
||
// 兜底:过滤空一级标题块(首行 `#`/`# ` 无文字产生的 <h1></h1> 空白条)
|
||
return html.replace(/<h1(?:\s[^>]*)?>(?:\s| )*<\/h1>/g, '')
|
||
}
|
||
|
||
/** 触发懒加载(可在空闲时调用) */
|
||
export function preloadMarked(): void {
|
||
ensureMarked().catch(() => {})
|
||
}
|
||
|
||
export async function renderMermaidDiagrams() {
|
||
const mermaid = await loadMermaid()
|
||
if (mermaid) {
|
||
document.querySelectorAll('.mermaid:not([data-mermaid-src])').forEach(pre => {
|
||
;(pre as HTMLElement).setAttribute('data-mermaid-src', pre.textContent || '')
|
||
})
|
||
await mermaid.run()
|
||
}
|
||
}
|
||
|
||
export async function rerenderMermaidDiagrams(container?: HTMLElement | null) {
|
||
mermaidInstance = null
|
||
mermaidTheme = null
|
||
|
||
const target = container || document
|
||
target.querySelectorAll('.mermaid').forEach(pre => {
|
||
const el = pre as HTMLElement
|
||
if (el.getAttribute('data-processed')) {
|
||
el.innerHTML = el.getAttribute('data-mermaid-src') || ''
|
||
el.removeAttribute('data-processed')
|
||
}
|
||
})
|
||
await renderMermaidDiagrams()
|
||
}
|