Skip to content

Commit

Permalink
修复条目奇偶阴影开启部分插件失效
Browse files Browse the repository at this point in the history
  • Loading branch information
MuiseDestiny committed Feb 21, 2023
1 parent d4fafae commit 2c57a97
Show file tree
Hide file tree
Showing 6 changed files with 216 additions and 111 deletions.
Empty file removed addon/chrome/content/style.css
Empty file.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "zotero-style",
"version": "2.2.1",
"version": "2.2.2",
"description": "让你的Zotero看起来更有趣",
"config": {
"addonName": "Zotero Style",
Expand Down Expand Up @@ -37,6 +37,7 @@
"pixi": "^0.3.1",
"raphael": "^2.3.0",
"runes": "^0.4.3",
"sentence-extractor": "^1.0.7",
"three": "^0.148.0",
"zotero-plugin-toolkit": "^2.0.3"
},
Expand Down
4 changes: 2 additions & 2 deletions src/modules/item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default class AddonItem {
// @ts-ignore
item = new Zotero.Item('computerProgram');
item.setField('title', this.title);
await item.saveTx()
await item.saveTx({ skipSelect : true})
log("From new")
}
Zotero.Prefs.set(this.prefKey, item.key)
Expand All @@ -58,7 +58,7 @@ export default class AddonItem {
let noteData = this.getNoteData(noteItem)
noteData[key] = data
noteItem.setNote(`${item.key}\n${JSON.stringify(noteData)}`)
await noteItem.saveTx()
await noteItem.saveTx({ skipSelect: true })
}

/**
Expand Down
314 changes: 209 additions & 105 deletions src/modules/views.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ export default class Views {
properties: {
innerHTML: `
[id^=item-tree-main-default-row]:nth-child(odd) {
background-color: ${Zotero.Prefs.get(`${config.addonRef}.titleColumn.odd`) as string};
background-color: ${Zotero.Prefs.get(`${config.addonRef}.titleColumn.odd`) as string} !important;
}
[id^=item-tree-main-default-row]:nth-child(even) {
background-color: ${Zotero.Prefs.get(`${config.addonRef}.titleColumn.even`) as string};
background-color: ${Zotero.Prefs.get(`${config.addonRef}.titleColumn.even`) as string} !important;
}
.tag-box .tag-swatch {
position: absolute;
Expand Down Expand Up @@ -1614,7 +1614,6 @@ export default class Views {
let h = 0;
const mouseDownHandler = function (e: any) {
frame.style.display = "none"

// Get the current mouse position
y = e.clientY;
h = container.getBoundingClientRect().height;
Expand Down Expand Up @@ -1985,108 +1984,213 @@ export default class Views {
/**
* 逐句翻译对照
*/
ztoolkit.Prompt.register([{
name: "逐句对照翻译",
label: "Translate",
when: () => {
const selection = ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
ztoolkit.log(selection)
return selection.length > 0 && Zotero.PDFTranslate
},
callback: (prompt) => {
const selection = ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
const container = prompt.createCommandsContainer() as HTMLDivElement
container.style = `
padding: .5em;
display: flex;
flex-direction: row;
justify-content: space-between;
`
const queue = Zotero.PDFTranslate.data.translate.queue
const task = queue.find((i: any) => i.raw == selection) || queue.slice(-1)[0]
if (!task) {
prompt.showTip("Task is Null.")
}
const rawText = task.raw, resultText = task.result;
const props = {
styles: {
width: "49%",
height: "20em",
border: "1px solid #eee",
textAlign: "justify",
padding: ".5em",
fontSize: "1em",
lineHeight: "1.5em",
overflowY: "auto",
},
}
// TODO: 首选项自行配置,不同语言分隔符,比如英文点,中文句号,这里默认英文中文翻译
let addSentences = (node: HTMLElement, text: string, sep: string) => {
let sentences = text.match(new RegExp(`.+?${sep}\\s*`, "g"))! as string[]
console.log(sentences)
// 把错误断开的连接起来Fig. Table.等,只针对英文,其它分隔符以下代码将无效
let i = 0
while (i < sentences.length - 1) {
if (
// Fig. 5形式
/(table|fig|figure)\.\s*$/i.test(sentences[i]) ||
// 2.33形式
(/\d\.$/i.test(sentences[i]) && /^\d/i.test(sentences[i+1]))
) {
console.log(sentences[i], "-", sentences[i + 1])
sentences[i] = sentences[i] + sentences[i + 1]
sentences.splice(i+1, 1)
} else {
i += 1
}
}
sentences = sentences.filter(s => s.length > 0)
console.log(sentences)
for (let i = 0; i < sentences.length; i++) {
console.log(sentences[i])
node.appendChild(ztoolkit.UI.createElement(document, "span", {
id: `sentence-${i}`,
properties: {
innerHTML: sentences[i]
},
listeners: [
{
type: "mousemove",
listener: function () {
const hightlightColor = "#fee972"
// @ts-ignore
const span = this as HTMLSpanElement
const parentNode = span.parentNode as HTMLDivElement
parentNode?.querySelectorAll("span").forEach(e => e.style.backgroundColor="")
span.style.backgroundColor = hightlightColor
const siblingNode = (parentNode?.previousSibling || parentNode?.nextSibling) as HTMLDivElement
siblingNode?.querySelectorAll("span").forEach(e => e.style.backgroundColor = "");
const twinSpan = siblingNode.querySelector(`span[id=sentence-${i}]`) as HTMLSpanElement
twinSpan.style.backgroundColor = hightlightColor;
// 滚轮滚动,让译文/原文在中间显示
siblingNode.scrollTo(0, twinSpan.offsetTop - siblingNode.offsetHeight * .5);
}
}
]
}))
}
}
// 原文
const rawDiv = ztoolkit.UI.createElement(document, "div", {
...props
})
addSentences(rawDiv, rawText, "[\\.;]")
const resultDiv = ztoolkit.UI.createElement(document, "div", {
...props,
})
addSentences(resultDiv, resultText, "[。;;]")
container.append(rawDiv, resultDiv)
}
}])
// let getSelection = () => {
// return ztoolkit.Reader.getSelectedText(
// Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
// );
// }
// ztoolkit.Prompt.register([{
// name: "Translate Sentences",
// label: config.addonInstance,
// when: () => {
// const selection = getSelection();
// const sl = Zotero.Prefs.get("ZoteroPDFTranslate.sourceLanguage") as string
// const tl = Zotero.Prefs.get("ZoteroPDFTranslate.targetLanguage") as string
// return selection.length > 0 && Zotero?.PDFTranslate && sl.startsWith("en") && tl.startsWith("zh")
// },
// callback: async (prompt) => {
// const selection = getSelection();
// const queue = Zotero.PDFTranslate.data.translate.queue
// let task = queue.find((task: any) => task.raw == selection && task.result.length > 0)
// task = null
// if (!task) {
// prompt.showTip("Loading...")
// task = await Zotero.PDFTranslate.api.translate(selection)
// Zotero.PDFTranslate.data.translate.queue.push(task)
// // @ts-ignore
// prompt.exit()
// }
// prompt.inputNode.placeholder = task.service
// const rawText = task.raw, resultText = task.result;

// let addSentences = (node: HTMLElement, text: string, dividers: string[]) => {
// let i = 0
// let sentences: string[] = []
// let sentence = ""
// // https://www.npmjs.com/package/sentence-extractor?activeTab=explore
// const abbrs = ["a.m.", "p.m.", "etc.", "vol.", "inc.", "jr.", "dr.", "tex.", "co.", "prof.", "rev.", "revd.", "hon.", "v.s.", "ie.",
// "eg.", "e.g.", "et al.", "st.", "ph.d.", "capt.", "mr.", "mrs.", "ms."]
// let getWord = (i: number) => {
// let before, after;
// before = text.slice(0, i).match(/[\.a-zA-Z]+$/)
// after = text.slice(i + 1).match(/^[\.a-zA-Z]+/)
// let word = ([before, ["."], after].filter(i => i) as string[][])
// .map((i: string[]) => i[0]).join("")
// return word
// }
// let isAbbr = (i: number) => {
// const word = getWord(i)
// return abbrs.find((abbr: string) => {
// return word.toLowerCase() == abbr.toLowerCase()
// })
// }
// let isNumber = (i: number) => {
// return i - 1 >= 0 && /\d/.test(text[i - 1]) && i + 1 < text.length && /\d/.test(text[i + 1])
// }
// let isPotentialAbbr = (i: number) => {
// const word = getWord(i)
// let parts = word.split(".").filter(i => i)
// return parts.length > 2 && parts.every(part => part.length <= 2)
// }
// while (i < text.length) {
// let char = text[i]
// sentence += char
// if (dividers.indexOf(char) != -1) {
// if (char == ".") {
// if (isAbbr(i) || isNumber(i) || isPotentialAbbr(i)) {
// i += 1
// continue
// }
// }
// const blank = " "
// i += 1
// while (text[i] == blank) {
// sentence += blank
// i += 1
// }
// sentences.push(sentence)
// sentence = ""
// continue
// }
// i += 1
// }
// for (let i = 0; i < sentences.length; i++) {
// ztoolkit.UI.appendElement(
// {
// tag: "span",
// id: `sentence-${i}`,
// properties: {
// innerText: sentences[i]
// },
// styles: {
// borderRadius: "3px"
// },
// listeners: [
// {
// type: "mousemove",
// listener: function () {
// const highlightColor = "#fee972"
// // @ts-ignore
// const span = this as HTMLSpanElement
// const parentNode = span.parentNode as HTMLDivElement
// parentNode?.querySelectorAll("span").forEach(e => e.style.backgroundColor = "")
// span.style.backgroundColor = highlightColor
// const siblingNode = (parentNode?.previousSibling?.previousSibling || parentNode?.nextSibling?.nextSibling) as HTMLDivElement
// siblingNode?.querySelectorAll("span").forEach(e => e.style.backgroundColor = "");
// const twinSpan = siblingNode.querySelector(`span[id=sentence-${i}]`) as HTMLSpanElement
// twinSpan.style.backgroundColor = highlightColor;
// if (direction == "column" && siblingNode.classList.contains("result")) {
// siblingNode.scrollTo(0, twinSpan.offsetTop - siblingNode.offsetHeight * .5 - parentNode.offsetHeight);
// } else {
// siblingNode.scrollTo(0, twinSpan.offsetTop - siblingNode.offsetHeight * .5);
// }
// }
// }
// ]
// },
// node
// )
// }
// }
// const container = prompt.createCommandsContainer() as HTMLDivElement
// // TODO: prefs: direction
// const directions = ["row", "column"]
// const direction = directions[1]
// container.setAttribute("style", `
// display: flex;
// flex-direction: ${direction};
// padding: .5em 1em;
// margin-left: 0px;
// width: 100%;
// height: 25em;
// `)
// const props = {
// styles: {
// height: "100%",
// width: "100%",
// minWidth: "10em",
// minHeight: "5em",
// border: "1px solid #eee",
// textAlign: "justify",
// padding: ".5em",
// fontSize: "1em",
// lineHeight: "1.5em",
// overflowY: "auto"
// },
// }
// const rawDiv = ztoolkit.UI.createElement(document, "div", {
// ...props,
// classList: ["raw"]
// })

// addSentences(rawDiv, rawText, [".", ";", "?", "!"])
// const resultDiv = ztoolkit.UI.createElement(document, "div", {
// ...props,
// classList: ["result"]
// })
// addSentences(resultDiv, resultText, [";", "?", "!", "!", ";", "。", "?"])
// const size = 5
// const resizer = ztoolkit.UI.createElement(document, "div", {
// styles: {
// height: (direction == "row" ? "100%" : `${size}px`),
// width: (direction == "column" ? "100%" : `${size}px`),
// backgroundColor: "#f0f0f0",
// cursor: direction == "column" ? "ns-resize" : "ew-resize",
// },
// })
// // 可调
// let y = 0, x = 0;
// let h = 0, w = 0;
// const rect = container.getBoundingClientRect();
// const H = rect.height;
// const W = rect.width;
// const mouseDownHandler = function (e: MouseEvent) {
// // hide
// [rawDiv, resultDiv].forEach(div => {
// div.querySelectorAll("span").forEach((e: HTMLSpanElement) => e.style.display = "none")
// })
// y = e.clientY;
// x = e.clientX;
// const rect = resultDiv.getBoundingClientRect()
// h = rect.height;
// w = rect.width;
// document.addEventListener('mousemove', mouseMoveHandler);
// document.addEventListener('mouseup', mouseUpHandler);
// };
// const mouseMoveHandler = function (e: MouseEvent) {
// const dy = e.clientY - y;
// const dx = e.clientX - x;
// if (direction == "column") {
// resultDiv.style.height = `${h - dy}px`;
// rawDiv.style.height = `${H - (h - dy) - size}px`;
// }
// if (direction == "row") {
// resultDiv.style.width = `${w - dx}px`;
// rawDiv.style.width = `${W - (w - dx) - size}px`;
// }
// };
// const mouseUpHandler = function () {
// // show
// [rawDiv, resultDiv].forEach(div => {
// div.querySelectorAll("span").forEach((e: HTMLSpanElement) => e.style.display = "")
// })
// document.removeEventListener('mousemove', mouseMoveHandler);
// document.removeEventListener('mouseup', mouseUpHandler);
// };
// resizer.addEventListener('mousedown', mouseDownHandler);
// container.append(rawDiv, resizer, resultDiv)
// }
// }])
// Prompt
// 旧版数据迁移
let getItem = () => {
Expand Down
4 changes: 2 additions & 2 deletions update.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"[email protected]": {
"updates": [
{
"version": "2.2.1",
"version": "2.2.2",
"update_link": "https://github.com/muisedestiny/zotero-style/releases/latest/download/zotero-style.xpi",
"applications": {
"gecko": {
Expand All @@ -12,7 +12,7 @@
}
},
{
"version": "2.2.1",
"version": "2.2.2",
"update_link": "https://github.com/muisedestiny/zotero-style/releases/latest/download/zotero-style.xpi",
"applications": {
"zotero": {
Expand Down
2 changes: 1 addition & 1 deletion update.rdf
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<rdf:Seq>
<rdf:li>
<rdf:Description>
<em:version>2.2.1</em:version>
<em:version>2.2.2</em:version>
<em:targetApplication>
<rdf:Description>
<em:id>[email protected]</em:id>
Expand Down

0 comments on commit 2c57a97

Please sign in to comment.