Solve the problem of multi-layer shadowroot selector and input box translation

This commit is contained in:
Gabe Yuan
2023-09-22 15:33:02 +08:00
parent 5306d81284
commit 87f099dd7f

View File

@@ -91,8 +91,8 @@ function addLoading(node, loadingId) {
node.offsetParent?.appendChild(div); node.offsetParent?.appendChild(div);
} }
function removeLoading(loadingId) { function removeLoading(node, loadingId) {
const div = document.getElementById(loadingId); const div = node.offsetParent.querySelector(`#${loadingId}`);
if (div) { if (div) {
div.remove(); div.remove();
} }
@@ -259,6 +259,22 @@ export class Translator {
); );
}; };
_queryShadowNodes = (selector, rootNode) => {
this._rootNodes.add(rootNode);
this._queryFilter(selector, rootNode).forEach((item) => {
if (!this._tranNodes.has(item)) {
this._tranNodes.set(item, "");
}
});
Array.from(rootNode.querySelectorAll("*"))
.map((item) => item.shadowRoot)
.filter(Boolean)
.forEach((item) => {
this._queryShadowNodes(selector, item);
});
};
_queryNodes = (rootNode = document) => { _queryNodes = (rootNode = document) => {
// const childRoots = Array.from(rootNode.querySelectorAll("*")) // const childRoots = Array.from(rootNode.querySelectorAll("*"))
// .map((item) => item.shadowRoot) // .map((item) => item.shadowRoot)
@@ -281,14 +297,15 @@ export class Translator {
const outNodes = this._querySelectorAll(outSelector, rootNode); const outNodes = this._querySelectorAll(outSelector, rootNode);
outNodes.forEach((outNode) => { outNodes.forEach((outNode) => {
if (outNode.shadowRoot) { if (outNode.shadowRoot) {
this._rootNodes.add(outNode.shadowRoot); // this._rootNodes.add(outNode.shadowRoot);
this._queryFilter(inSelector, outNode.shadowRoot).forEach( // this._queryFilter(inSelector, outNode.shadowRoot).forEach(
(item) => { // (item) => {
if (!this._tranNodes.has(item)) { // if (!this._tranNodes.has(item)) {
this._tranNodes.set(item, ""); // this._tranNodes.set(item, "");
} // }
} // }
); // );
this._queryShadowNodes(inSelector, outNode.shadowRoot);
} }
}); });
} }
@@ -357,8 +374,17 @@ export class Translator {
stepShortcutRegister( stepShortcutRegister(
triggerShortcut, triggerShortcut,
async () => { async () => {
const node = document.activeElement; let node = document.activeElement;
if (!node || !(isInputNode(node) || isEditAbleNode(node))) {
if (!node) {
return;
}
while (node.shadowRoot) {
node = node.shadowRoot.activeElement;
}
if (!isInputNode(node) && !isEditAbleNode(node)) {
return; return;
} }
@@ -435,7 +461,7 @@ export class Translator {
} catch (err) { } catch (err) {
console.log("[translate input]", err.message); console.log("[translate input]", err.message);
} finally { } finally {
removeLoading(loadingId); removeLoading(node, loadingId);
} }
}, },
triggerCount, triggerCount,