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, {
content: "<lingo-loading></lingo-loading>",
allowHTML: true,
trigger: "manual",
interactive: true,
getReferenceClientRect: () =>
document.getSelection().getRangeAt(0).getBoundingClientRect(),
onShow: (instance) => {
instance.setContent(
`<lingo-translate toTranslate="${document
.getSelection()
.toString()}"></lingo-translate>`
);
},
});
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() {
super();
this.innerHTML = "";
@ -8,10 +41,8 @@ export class LingoLoading extends HTMLElement {
let spinner = document.createElement("div");
spinner.id = "spinner";
const style = document.createElement("link");
style.rel = "stylesheet";
style.href = spinnerCSS;
style.textContent = spinnerCSS;
const style = document.createElement("style");
style.textContent = contents;
shadow.appendChild(style);
shadow.appendChild(spinner);
}