-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathindex.ts
More file actions
400 lines (351 loc) · 11.2 KB
/
index.ts
File metadata and controls
400 lines (351 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { markedAlert, MDKatex } from '@md/core'
import { prefix } from '@md/shared/configs'
// 直接导入供本文件内部使用
import {
checkImage,
createTable,
downloadFile,
formatDoc,
removeLeft,
sanitizeTitle,
toBase64,
} from '@md/shared/utils'
import juice from 'juice'
import { Marked } from 'marked'
export {
LocalStorageEngine as LocalEngine,
RestfulStorageEngine as RestfulEngine,
type StorageEngine,
} from './storage'
// 重新导出供外部使用
export {
checkImage,
createTable,
downloadFile,
formatDoc,
removeLeft,
sanitizeTitle,
toBase64,
}
// 导出新主题系统需要的函数
export {
modifyHtmlContent,
postProcessHtml,
renderMarkdown,
} from '@md/core/utils'
export function addPrefix(str: string) {
return `${prefix}__${str}`
}
/**
* 导出原始 Markdown 文档
* @param {string} doc - 文档内容
* @param {string} title - 文档标题
*/
export function downloadMD(doc: string, title: string = `untitled`) {
const safeTitle = sanitizeTitle(title)
downloadFile(doc, `${safeTitle}.md`, `text/markdown;charset=utf-8`)
}
/**
* 批量导出多篇文章为 ZIP
* @param posts - 文章列表(含 title 和 content)
*/
export async function exportPostsAsZip(posts: Array<{ title: string, content: string }>) {
const JSZip = (await import(`jszip`)).default
const zip = new JSZip()
posts.forEach(({ title, content }) => {
const safeTitle = sanitizeTitle(title)
zip.file(`${safeTitle}.md`, content)
})
const blob = await zip.generateAsync({ type: `blob` })
const date = new Date().toISOString().slice(0, 10)
const url = URL.createObjectURL(blob)
const a = document.createElement(`a`)
a.href = url
a.download = `posts-${date}.zip`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
URL.revokeObjectURL(url)
}
/**
* 获取 HTML 内容
* @returns {string} HTML 字符串
*/
export function getHtmlContent(): string {
const element = document.querySelector(`#output`)!
// Clone to avoid mutating the live DOM, then strip injected UI overlays
// (e.g. diagram download bars) that must not appear in exported content.
const clone = element.cloneNode(true) as HTMLElement
clone.querySelectorAll(`.diagram-download-bar`).forEach(el => el.remove())
return clone.innerHTML
}
/**
* 导出 HTML 生成内容
*/
export async function exportHTML(title: string = `untitled`) {
const htmlStr = getHtmlContent()
const stylesToAdd = await getStylesToAdd()
const fullHtml = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>${sanitizeTitle(title)}</title>
${stylesToAdd}
</head>
<body>
<div style="width: 750px; margin: auto; padding: 20px;">
${htmlStr}
</div>
</body>
</html>`
downloadFile(fullHtml, `${sanitizeTitle(title)}.html`, `text/html`)
}
/**
* 生成无样式 HTML
* @param raw - 原始 Markdown 内容
* @returns string
*/
export async function generatePureHTML(raw: string): Promise<string> {
const markedInstance = new Marked()
markedInstance.use(markedAlert({ withoutStyle: true }))
markedInstance.use(
MDKatex({ nonStandard: true }, false),
)
const pureHtml = await markedInstance.parse(raw)
return pureHtml
}
/**
* 导出无样式 HTML 文件
* @param raw - 原始 Markdown 内容
* @param title - 文档标题
*/
export async function exportPureHTML(raw: string, title: string = `untitled`) {
const safeTitle = sanitizeTitle(title)
const pureHtml = await generatePureHTML(raw)
downloadFile(pureHtml, `${safeTitle}.html`, `text/html`)
}
/**
* 导出 PDF 文档(新主题系统)
* @param {string} title - 文档标题
*/
export async function exportPDF(title: string = `untitled`) {
const htmlStr = getHtmlContent()
const stylesToAdd = await getStylesToAdd()
const safeTitle = sanitizeTitle(title)
const printHtml = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>${safeTitle}</title>
${stylesToAdd}
<style>
/* 强制打印背景颜色和图片 */
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
color-adjust: exact !important;
}
/* 打印页面设置 */
@page {
@top-center {
content: "${safeTitle}";
font-size: 12px;
color: #666;
}
@bottom-left {
content: "https://md.doocs.org";
font-size: 10px;
color: #999;
}
@bottom-right {
content: "第 " counter(page) " 页,共 " counter(pages) " 页";
font-size: 10px;
color: #999;
}
}
@media print {
body { margin: 0; }
}
</style>
</head>
<body>
<div style="width: 100%; max-width: 750px; margin: auto;">
${htmlStr}
</div>
</body>
</html>`
const iframe = document.createElement(`iframe`)
iframe.style.cssText = `position:fixed;width:0;height:0;top:-9999px;left:-9999px;border:none;`
iframe.srcdoc = printHtml
document.body.appendChild(iframe)
iframe.onload = () => {
iframe.contentWindow?.focus()
iframe.contentWindow?.print()
// 延迟移除,确保打印完成
setTimeout(() => {
document.body.removeChild(iframe)
}, 500)
}
}
export function solveWeChatImage() {
const clipboardDiv = document.getElementById(`output`)!
const images = clipboardDiv.getElementsByTagName(`img`)
Array.from(images).forEach((image) => {
const width = image.getAttribute(`width`)
const height = image.getAttribute(`height`)
if (width) {
image.removeAttribute(`width`)
// 如果是纯数字,添加 px 单位;否则保持原值
image.style.width = /^\d+$/.test(width) ? `${width}px` : width
}
if (height) {
image.removeAttribute(`height`)
// 如果是纯数字,添加 px 单位;否则保持原值
image.style.height = /^\d+$/.test(height) ? `${height}px` : height
}
})
}
async function getHljsStyles(): Promise<string> {
const hljsLink = document.querySelector(`#hljs`) as HTMLLinkElement
if (!hljsLink)
return ``
try {
const response = await fetch(hljsLink.href)
const cssText = await response.text()
return `<style>${cssText}</style>`
}
catch (error) {
console.warn(`Failed to fetch highlight.js styles:`, error)
return ``
}
}
function getThemeStyles(): string {
const themeStyle = document.querySelector(`#md-theme`) as HTMLStyleElement
if (!themeStyle || !themeStyle.textContent) {
console.warn('[getThemeStyles] 未找到主题样式')
return ``
}
// 移除 #output 作用域前缀,因为复制后的 HTML 不在 #output 容器中
let cssContent = themeStyle.textContent
// 处理 #output {} 为 body {},避免出现 {} 无效样式
cssContent = cssContent.replace(/#output\s*\{/g, 'body {')
// 将 "#output h1" 替换为 "h1","#output .class" 替换为 ".class" 等
// 同时处理换行和多个空格的情况
cssContent = cssContent.replace(/#output\s+/g, '')
// 处理选择器开头的 #output(如果没有后续内容)
cssContent = cssContent.replace(/^#output\s*/gm, '')
const styleContent = `<style>${cssContent}</style>`
return styleContent
}
function mergeCss(html: string): string {
return juice(html, {
inlinePseudoElements: true,
preserveImportant: true,
// 禁用 CSS 变量解析,避免 juice 处理时的错误
// 新主题系统已通过 postcss 处理 CSS 变量
resolveCSSVariables: false,
})
}
function modifyHtmlStructure(htmlString: string): string {
const tempDiv = document.createElement(`div`)
tempDiv.innerHTML = htmlString
// 移动 `li > ul` 和 `li > ol` 到 `li` 后面
tempDiv.querySelectorAll(`li > ul, li > ol`).forEach((originalItem) => {
originalItem.parentElement!.insertAdjacentElement(`afterend`, originalItem)
})
return tempDiv.innerHTML
}
function createEmptyNode(): HTMLElement {
const node = document.createElement(`p`)
node.style.fontSize = `0`
node.style.lineHeight = `0`
node.style.margin = `0`
node.innerHTML = ` `
return node
}
/**
* 获取需要添加的样式
* @returns {Promise<string>} 样式字符串
*/
async function getStylesToAdd(): Promise<string> {
const themeStyles = getThemeStyles()
const hljsStyles = await getHljsStyles()
return [themeStyles, hljsStyles].filter(Boolean).join(``)
}
export async function processClipboardContent(primaryColor: string) {
const clipboardDiv = document.getElementById(`output`)!
const stylesToAdd = await getStylesToAdd()
if (stylesToAdd) {
clipboardDiv.innerHTML = stylesToAdd + clipboardDiv.innerHTML
}
// 先合并 CSS 和修改 HTML 结构
clipboardDiv.innerHTML = modifyHtmlStructure(mergeCss(clipboardDiv.innerHTML))
// 处理样式和颜色变量
clipboardDiv.innerHTML = clipboardDiv.innerHTML
.replace(/([^-])top:(.*?)em/g, `$1transform: translateY($2em)`)
.replace(/hsl\(var\(--foreground\)\)/g, `#3f3f3f`)
.replace(/var\(--blockquote-background\)/g, `#f7f7f7`)
.replace(/var\(--md-primary-color\)/g, primaryColor)
.replace(/--md-primary-color:.+?;/g, ``)
.replace(/--md-font-family:.+?;/g, ``)
.replace(/--md-font-size:.+?;/g, ``)
.replace(
/<span class="nodeLabel"([^>]*)><p[^>]*>(.*?)<\/p><\/span>/g,
`<span class="nodeLabel"$1>$2</span>`,
)
.replace(
/<span class="edgeLabel"([^>]*)><p[^>]*>(.*?)<\/p><\/span>/g,
`<span class="edgeLabel"$1>$2</span>`,
)
// 处理图片大小
solveWeChatImage()
// 添加空白节点用于兼容 SVG 复制
const beforeNode = createEmptyNode()
const afterNode = createEmptyNode()
clipboardDiv.insertBefore(beforeNode, clipboardDiv.firstChild)
clipboardDiv.appendChild(afterNode)
// 兼容 Mermaid
const nodes = clipboardDiv.querySelectorAll(`.nodeLabel`)
nodes.forEach((node) => {
const parent = node.parentElement!
const xmlns = parent.getAttribute(`xmlns`)!
const style = parent.getAttribute(`style`)!
const section = document.createElement(`section`)
section.setAttribute(`xmlns`, xmlns)
section.setAttribute(`style`, style)
section.innerHTML = parent.innerHTML
const grand = parent.parentElement!
// 清空父元素
grand.innerHTML = ``
grand.appendChild(section)
})
// fix: mermaid 部分文本颜色被 stroke 覆盖
clipboardDiv.innerHTML = clipboardDiv.innerHTML
.replace(
/<tspan([^>]*)>/g,
`<tspan$1 style="fill: #333333 !important; color: #333333 !important; stroke: none !important;">`,
)
// fix: antv infographic 复制到微信公众平台时 <text></text> 被自动转为 <text><tspan></tspan></text> 导致在 Safari 浏览器中文字异常的问题
clipboardDiv.querySelectorAll('.infographic-diagram').forEach((diagram) => {
diagram.querySelectorAll('text').forEach((textElem) => {
// 如果有 dominant-baseline 属性,替换为 dy
const dominantBaseline = textElem.getAttribute('dominant-baseline')
const variantMap = {
'alphabetic': '',
'central': '0.35em',
'middle': '0.35em',
'hanging': '-0.55em',
'ideographic': '0.18em',
'text-before-edge': '-0.85em',
'text-after-edge': '0.15em',
}
if (dominantBaseline) {
textElem.removeAttribute('dominant-baseline')
const dy = variantMap[dominantBaseline as keyof typeof variantMap]
if (dy) {
textElem.setAttribute('dy', dy)
}
}
})
})
}