From 49b72ee736349794db201f7347c21a79f45bea03 Mon Sep 17 00:00:00 2001 From: Yuska Date: Wed, 12 Oct 2022 17:32:26 +0800 Subject: [PATCH] refactor: use CSSStyleSheet object to change the custom property of size inside shadow DOM dynamically --- src/main.ts | 25 +++++++++++-------------- src/style.css | 6 ++++++ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/src/main.ts b/src/main.ts index ccce584..ccf0835 100644 --- a/src/main.ts +++ b/src/main.ts @@ -25,13 +25,13 @@ template.innerHTML = templateContent const PLACEMENT = ['top-right', 'top-left', 'bottom-right', 'bottom-left'] -const DEFAULT_SIZE = '5rem' const DEFAULT_BANNER_COLOR = 'black' const DEFAULT_OCTOCAT_COLOR = 'white' const DEFAULT_DURATION = '0.5s' class GithubCorner extends HTMLElement { #shadowRoot: ShadowRoot + #styleSheet: CSSStyleSheet #anchor: HTMLAnchorElement #svgContainer: SVGElement @@ -46,14 +46,15 @@ class GithubCorner extends HTMLElement { constructor() { super() + this.#styleSheet = new CSSStyleSheet() + this.#styleSheet.replaceSync(cssContent) + // Create a shadow root this.#shadowRoot = this.attachShadow({ mode: 'open' }) - - const style = document.createElement('style') - style.textContent = cssContent + this.#shadowRoot.adoptedStyleSheets = [this.#styleSheet] // attach the created elements to the shadow DOM - this.#shadowRoot.append(style, template.content.cloneNode(true)) + this.#shadowRoot.append(template.content.cloneNode(true)) this.#anchor = this.#shadowRoot.querySelector('a.link') as HTMLAnchorElement this.#svgContainer = this.#shadowRoot.querySelector( @@ -91,9 +92,6 @@ class GithubCorner extends HTMLElement { } #init() { - const size = this.getAttribute('size') - this.#setSize(size ? size : DEFAULT_SIZE) - if (!this.#banner.getAttribute('fill')) { this.#banner.setAttribute('fill', DEFAULT_BANNER_COLOR) } @@ -110,11 +108,6 @@ class GithubCorner extends HTMLElement { } } - #setSize(size: string) { - this.style.width = size - this.style.height = size - } - connectedCallback() { if (this.#status === 'init') { this.#init() @@ -137,7 +130,11 @@ class GithubCorner extends HTMLElement { ) { switch (attributeName) { case 'size': - this.#setSize(newValue) + // replace size custom property + this.#styleSheet.deleteRule(0) + this.#styleSheet.insertRule( + `:host { --github-corner-size: ${newValue}; }` + ) break case 'href': diff --git a/src/style.css b/src/style.css index f9b1fe0..3b5786d 100644 --- a/src/style.css +++ b/src/style.css @@ -1,9 +1,15 @@ +:host { + --github-corner-size: 5rem; +} + :host { display: block; position: absolute; cursor: pointer; overflow: hidden; clip-path: polygon(0% 0%, 100% 0%, 100% 100%); + width: var(--github-corner-size); + height: var(--github-corner-size); } :host([placement='top-left']) {