feat: keep unchanged elements

This commit is contained in:
Gabe Yuan
2024-01-02 17:55:59 +08:00
parent 748f2002ab
commit 591afe08bd
8 changed files with 253 additions and 75 deletions

View File

@@ -66,6 +66,7 @@ export const matchRule = async (
}
rule.selector = rule.selector?.trim() || globalRule.selector;
rule.keepSelector = rule.keepSelector?.trim() || globalRule.keepSelector;
if (rule.textStyle === GLOBAL_KEY) {
rule.textStyle = globalRule.textStyle;
rule.bgColor = globalRule.bgColor;
@@ -112,6 +113,7 @@ export const checkRules = (rules) => {
({
pattern,
selector,
keepSelector,
translator,
fromLang,
toLang,
@@ -122,6 +124,7 @@ export const checkRules = (rules) => {
}) => ({
pattern: pattern.trim(),
selector: type(selector) === "string" ? selector : "",
keepSelector: type(keepSelector) === "string" ? keepSelector : "",
bgColor: type(bgColor) === "string" ? bgColor : "",
textDiyStyle: type(textDiyStyle) === "string" ? textDiyStyle : "",
translator: matchValue([GLOBAL_KEY, ...OPT_TRANS_ALL], translator),

View File

@@ -360,6 +360,11 @@ export class Translator {
}
}, 500);
_matchLength = (q) =>
!q ||
q.length < (this._setting.minLength ?? TRANS_MIN_LENGTH) ||
q.length > (this._setting.maxLength ?? TRANS_MAX_LENGTH);
_render = (el) => {
let traEl = el.querySelector(APP_LCNAME);
@@ -379,20 +384,41 @@ export class Translator {
traEl.remove();
}
const q = el.innerText.trim();
let q = el.innerText.trim();
this._tranNodes.set(el, q);
// 太长或太短
if (
!q ||
q.length < (this._setting.minLength ?? TRANS_MIN_LENGTH) ||
q.length > (this._setting.maxLength ?? TRANS_MAX_LENGTH)
) {
if (this._matchLength(q)) {
return;
}
// console.log("---> ", q);
const keepSelector = this._rule.keepSelector || "";
const keeps = [];
if (keepSelector.trim()) {
let text = "";
el.childNodes.forEach((child) => {
if (child.nodeType === 1 && child.matches(keepSelector)) {
text += `#${keeps.length}#`;
keeps.push(child.outerHTML);
} else {
text += child.textContent;
}
});
// 太长或太短
if (this._matchLength(text.replace(/#(\d+)#/g, "").trim())) {
return;
}
if (keeps.length > 0) {
q = text;
}
}
// console.log("---> ", q);
traEl = document.createElement(APP_LCNAME);
traEl.style.visibility = "visible";
el.appendChild(traEl);
@@ -404,6 +430,6 @@ export class Translator {
}
const root = createRoot(traEl);
root.render(<Content q={q} translator={this} />);
root.render(<Content q={q} keeps={keeps} translator={this} />);
};
}