(
onProgress?: (current: number, total: number) => void
)
| 284 | } |
| 285 | |
| 286 | async function downloadMarkdownWithImages( |
| 287 | onProgress?: (current: number, total: number) => void |
| 288 | ) { |
| 289 | await scrollToLoadImages() |
| 290 | |
| 291 | const html = document.querySelector("#img-content") |
| 292 | if (!html) return |
| 293 | |
| 294 | let markdown = turndownService.turndown(html) |
| 295 | const mdImageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g |
| 296 | const imageEntries: { alt: string; url: string }[] = [] |
| 297 | let match |
| 298 | while ((match = mdImageRegex.exec(markdown)) !== null) { |
| 299 | const url = match[2] |
| 300 | if (url && !url.startsWith("./images/")) { |
| 301 | imageEntries.push({ alt: match[1], url }) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | const zip = new JSZip() |
| 306 | const title = articleTitle || document.title.trim() |
| 307 | const total = imageEntries.length + 1 |
| 308 | |
| 309 | const getExt = (url: string) => { |
| 310 | const fmt = url.match(/wx_fmt=(\w+)/)?.[1] || "" |
| 311 | if (fmt === "gif") return ".gif" |
| 312 | if (fmt === "png" || fmt === "webp") return ".png" |
| 313 | if (fmt === "bmp") return ".bmp" |
| 314 | if (url.includes("mmbiz_gif")) return ".gif" |
| 315 | if (url.includes("mmbiz_png") || url.includes("mmbiz_webp")) return ".png" |
| 316 | return ".jpg" |
| 317 | } |
| 318 | |
| 319 | // 下载图片并替换 markdown 中的 URL |
| 320 | for (let i = 0; i < imageEntries.length; i++) { |
| 321 | const { url } = imageEntries[i] |
| 322 | try { |
| 323 | const response = await fetch(url) |
| 324 | const blob = await response.blob() |
| 325 | const ext = getExt(url) |
| 326 | const localPath = `./images/${i}${ext}` |
| 327 | |
| 328 | zip.file(`images/${i}${ext}`, blob) |
| 329 | markdown = markdown.replace(url, localPath) |
| 330 | |
| 331 | if (onProgress) { |
| 332 | onProgress(i + 1, total) |
| 333 | } |
| 334 | } catch (error) { |
| 335 | console.error(`Failed to download image ${i}:`, error) |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | // 添加 markdown 文件到 zip |
| 340 | zip.file(`${title}.md`, markdown) |
| 341 | |
| 342 | if (onProgress) { |
| 343 | onProgress(total, total) |
no test coverage detected