(markdown: string, filename?: string)
| 66 | } |
| 67 | |
| 68 | export async function saveMarkdownWithLocalImages(markdown: string, filename?: string) { |
| 69 | if (!markdown) return |
| 70 | |
| 71 | // 匹配 markdown 中的图片链接  |
| 72 | const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g |
| 73 | const images: { alt: string; url: string; index: number }[] = [] |
| 74 | let match |
| 75 | |
| 76 | while ((match = imageRegex.exec(markdown)) !== null) { |
| 77 | images.push({ |
| 78 | alt: match[1], |
| 79 | url: match[2], |
| 80 | index: match.index |
| 81 | }) |
| 82 | } |
| 83 | |
| 84 | if (images.length === 0) { |
| 85 | // 没有图片,直接保存 |
| 86 | saveMarkdown(markdown, filename) |
| 87 | return |
| 88 | } |
| 89 | |
| 90 | // 下载所有图片并转换为 base64 |
| 91 | const imagePromises = images.map(async (img) => { |
| 92 | try { |
| 93 | const response = await fetch(img.url) |
| 94 | const blob = await response.blob() |
| 95 | return new Promise<{ url: string; base64: string }>((resolve) => { |
| 96 | const reader = new FileReader() |
| 97 | reader.onloadend = () => { |
| 98 | resolve({ |
| 99 | url: img.url, |
| 100 | base64: reader.result as string |
| 101 | }) |
| 102 | } |
| 103 | reader.readAsDataURL(blob) |
| 104 | }) |
| 105 | } catch (error) { |
| 106 | console.error(`Failed to download image: ${img.url}`, error) |
| 107 | return { url: img.url, base64: img.url } // 失败时保持原 URL |
| 108 | } |
| 109 | }) |
| 110 | |
| 111 | const downloadedImages = await Promise.all(imagePromises) |
| 112 | |
| 113 | // 替换 markdown 中的图片 URL 为 base64 |
| 114 | let updatedMarkdown = markdown |
| 115 | downloadedImages.forEach((img) => { |
| 116 | updatedMarkdown = updatedMarkdown.replace( |
| 117 | new RegExp(`\\(${img.url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\)`, "g"), |
| 118 | `(${img.base64})` |
| 119 | ) |
| 120 | }) |
| 121 | |
| 122 | // 保存更新后的 markdown |
| 123 | const blob = new Blob([updatedMarkdown], { type: "text/markdown;charset=utf-8" }) |
| 124 | filename = filename || "CodeBox-page" |
| 125 | saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.md`) |
no test coverage detected