From 5cffa7772ae76eba22ce0cdf574948fa6201fb71 Mon Sep 17 00:00:00 2001 From: a Date: Tue, 4 Aug 2020 00:40:22 +0200 Subject: [PATCH] Add translation to the content script --- src/content_script/content_script.ts | 8 ++++- src/content_script/custom_elements.ts | 43 +++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/content_script/content_script.ts b/src/content_script/content_script.ts index f279867..5c47e92 100644 --- a/src/content_script/content_script.ts +++ b/src/content_script/content_script.ts @@ -31,12 +31,18 @@ declare global { }); const tippyInstance = tippy(document.body, { - content: "", allowHTML: true, trigger: "manual", interactive: true, getReferenceClientRect: () => document.getSelection().getRangeAt(0).getBoundingClientRect(), + onShow: (instance) => { + instance.setContent( + `` + ); + }, }); let timeoutID: number; diff --git a/src/content_script/custom_elements.ts b/src/content_script/custom_elements.ts index e8f4024..4e81e34 100644 --- a/src/content_script/custom_elements.ts +++ b/src/content_script/custom_elements.ts @@ -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 = ""; + 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); }