-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathtools.ts
More file actions
150 lines (128 loc) · 4.1 KB
/
tools.ts
File metadata and controls
150 lines (128 loc) · 4.1 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
import dayjs from "dayjs"
import { saveAs } from "file-saver"
import { sendToBackground } from "@plasmohq/messaging"
export function scrollToTop(element) {
window.scrollTo({
top: element.offsetTop - 50,
behavior: "smooth" // 可选,平滑滚动
})
}
export function addCss(code, id?) {
const style = document.createElement("style")
const css = document.createTextNode(code)
style.setAttribute("data-id", id || "codebox-css")
style.appendChild(css)
document.head.appendChild(style)
}
export function removeCss(id) {
var style = document.querySelector(`[data-id="${id}"]`)
style && style.remove()
}
export function addJs(code) {
const script = document.createElement("script")
// const js = document.createTextNode(`(()=>{${code}})()`)
const js = document.createTextNode(code)
script.appendChild(js)
document.head.appendChild(script)
}
export function setIcon(active: boolean) {
sendToBackground({
name: "icon",
body: {
active: active
}
})
}
export function saveTxt(txt: string, filename?: string) {
if (txt) {
const blob = new Blob([txt], { type: "text/plain;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.txt`)
}
}
export function saveHtml(dom: Element, filename?: string) {
if (dom) {
const htmlContent = dom.outerHTML
const blob = new Blob([htmlContent], { type: "text/html;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.html`)
}
}
export function saveMarkdown(markdown: string, filename?: string) {
if (markdown) {
const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.md`)
}
}
export async function saveMarkdownWithLocalImages(markdown: string, filename?: string) {
if (!markdown) return
// 匹配 markdown 中的图片链接 
const imageRegex = /!\[([^\]]*)\]\(([^)]+)\)/g
const images: { alt: string; url: string; index: number }[] = []
let match
while ((match = imageRegex.exec(markdown)) !== null) {
images.push({
alt: match[1],
url: match[2],
index: match.index
})
}
if (images.length === 0) {
// 没有图片,直接保存
saveMarkdown(markdown, filename)
return
}
// 下载所有图片并转换为 base64
const imagePromises = images.map(async (img) => {
try {
const response = await fetch(img.url)
const blob = await response.blob()
return new Promise<{ url: string; base64: string }>((resolve) => {
const reader = new FileReader()
reader.onloadend = () => {
resolve({
url: img.url,
base64: reader.result as string
})
}
reader.readAsDataURL(blob)
})
} catch (error) {
console.error(`Failed to download image: ${img.url}`, error)
return { url: img.url, base64: img.url } // 失败时保持原 URL
}
})
const downloadedImages = await Promise.all(imagePromises)
// 替换 markdown 中的图片 URL 为 base64
let updatedMarkdown = markdown
downloadedImages.forEach((img) => {
updatedMarkdown = updatedMarkdown.replace(
new RegExp(`\\(${img.url.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\)`, "g"),
`(${img.base64})`
)
})
// 保存更新后的 markdown
const blob = new Blob([updatedMarkdown], { type: "text/markdown;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.md`)
}
export function i18n(key: string) {
return chrome.i18n.getMessage(key)
}
export function getMetaContentByProperty(metaProperty: string) {
const metas = document.getElementsByTagName("meta")
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("property") === metaProperty) {
return metas[i].getAttribute("content")
}
}
return ""
}
export function isValidUrl(urlString: string) {
try {
return Boolean(new URL(urlString))
} catch (e) {
return false
}
}