forked from 027xiguapi/code-box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom.tsx
77 lines (66 loc) · 2.01 KB
/
custom.tsx
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
import { Readability } from "@mozilla/readability"
import { useEffect, useState } from "react"
import { useMessage } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/hook"
import { addCss, saveTxt, setIcon } from "~tools"
const documentClone = document.cloneNode(true)
const article = new Readability(documentClone as Document, {}).parse()
setIcon(false)
export default function Custom() {
const [runCss] = useStorage<boolean>("custom-runCss")
const [cssCode] = useStorage<string>("custom-cssCode")
const [closeLog] = useStorage("config-closeLog", true)
const [codes, setCodes] = useState([])
useEffect(() => {
runCss && runCssFunc()
}, [runCss])
useMessage(async (req, res) => {
if (req.name == "custom-isShow") {
res.send({ isShow: true })
}
if (req.name == "getCodes") {
res.send({ codes: getCodes() })
}
if (req.name == "scrollIntoViewCode") {
scrollIntoViewCode(req.body)
}
if (req.name == "downloadCode") {
downloadCode(req.body)
}
})
/* 插入自定义css代码 */
function runCssFunc() {
closeLog || console.log("插入自定义css代码", cssCode)
addCss(cssCode)
}
function getCodes() {
let codes = []
let codesTxt = []
const _codes = document.querySelectorAll("pre")
_codes.forEach((code) => {
let codeTxt = code.innerText
if (code.querySelector("code")) {
codeTxt = code.querySelector("code").innerText
}
codeTxt = codeTxt.replace(/\n/g, "")
if (codeTxt.length > 8) {
codes.push(code)
codesTxt.push(codeTxt)
}
})
setCodes(codes)
return codesTxt
}
function scrollIntoViewCode(data) {
const code = codes[data.index]
code && code.scrollIntoView()
}
function downloadCode(data) {
let code = codes[data.index]
if (code && code.querySelector("code")) {
code = code.querySelector("code")
}
code && saveTxt(code.innerText, article.title)
}
return <div style={{ display: "none" }}></div>
}