Add translation to the content script

This commit is contained in:
a 2020-08-04 00:40:22 +02:00
parent 41f0a7e01d
commit 5cffa7772a
2 changed files with 44 additions and 7 deletions

View file

@ -31,12 +31,18 @@ declare global {
}); });
const tippyInstance = tippy(document.body, { const tippyInstance = tippy(document.body, {
content: "<lingo-loading></lingo-loading>",
allowHTML: true, allowHTML: true,
trigger: "manual", trigger: "manual",
interactive: true, interactive: true,
getReferenceClientRect: () => getReferenceClientRect: () =>
document.getSelection().getRangeAt(0).getBoundingClientRect(), document.getSelection().getRangeAt(0).getBoundingClientRect(),
onShow: (instance) => {
instance.setContent(
`<lingo-translate toTranslate="${document
.getSelection()
.toString()}"></lingo-translate>`
);
},
}); });
let timeoutID: number; let timeoutID: number;

View file

@ -1,6 +1,39 @@
import spinnerCSS from "./spinner.scss?file"; import { browser } from "webextension-polyfill-ts";
import contents from "./spinner.scss?raw";
export class LingoLoading extends HTMLElement { class LingoTranslate extends HTMLElement {
shadow: ShadowRoot;
constructor() {
super();
this.shadow = this.attachShadow({ mode: "open" });
this.render();
}
render = () => {
this.shadow.innerHTML = "<lingo-loading></lingo-loading>";
const toTranslate = this.getAttribute("toTranslate");
const translation = browser.runtime.sendMessage({
commandKind: commands.translate,
toTranslate: toTranslate,
});
translation.then((t) => (this.shadow.textContent = t.result));
};
attributeChangedCallback = (
attributeName: string,
oldValue: string,
newValue: string
) => {
if (attributeName === "toTranslate" && oldValue != newValue) this.render();
};
static get observedAttributes() {
return ["toTranslate"];
}
}
customElements.define("lingo-translate", LingoTranslate);
class LingoLoading extends HTMLElement {
constructor() { constructor() {
super(); super();
this.innerHTML = ""; this.innerHTML = "";
@ -8,10 +41,8 @@ export class LingoLoading extends HTMLElement {
let spinner = document.createElement("div"); let spinner = document.createElement("div");
spinner.id = "spinner"; spinner.id = "spinner";
const style = document.createElement("link"); const style = document.createElement("style");
style.rel = "stylesheet"; style.textContent = contents;
style.href = spinnerCSS;
style.textContent = spinnerCSS;
shadow.appendChild(style); shadow.appendChild(style);
shadow.appendChild(spinner); shadow.appendChild(spinner);
} }