From 9cb02bdffad29c9854d03fa5599718e4f42b6fb0 Mon Sep 17 00:00:00 2001 From: vrugtehagel Date: Tue, 11 Feb 2025 08:00:28 +0100 Subject: [PATCH] Add register.style for registering global component styles --- src/index.js | 2 +- src/mods/{05-template.js => 04-template.js} | 2 +- src/register.js | 19 ++++++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) rename src/mods/{05-template.js => 04-template.js} (96%) diff --git a/src/index.js b/src/index.js index a0db255..7e1bd7e 100644 --- a/src/index.js +++ b/src/index.js @@ -11,7 +11,7 @@ import './mods/00-title.js' import './mods/01-meta.js' import './mods/02-hooks.js' import './mods/03-transforms.js' -import './mods/05-template.js' +import './mods/04-template.js' import './mods/07-query.js' import './mods/08-style.js' import './mods/10-script.js' diff --git a/src/mods/05-template.js b/src/mods/04-template.js similarity index 96% rename from src/mods/05-template.js rename to src/mods/04-template.js index 72f9f0e..dbdbafa 100644 --- a/src/mods/05-template.js +++ b/src/mods/04-template.js @@ -2,7 +2,7 @@ import { define } from '../define.js' import { warn } from '../help.js' // -define.register(5, 'template', (context, [args]) => { +define.register(4, 'template', (context, [args]) => { if(!args){ return { constructor: function(meta){ diff --git a/src/register.js b/src/register.js index 5436b2c..dac68a7 100644 --- a/src/register.js +++ b/src/register.js @@ -64,7 +64,7 @@ register.auto = finder => { // We sneakily define another mod here, to define custom elements in the // template - define.register(6, Symbol(), context => { + define.register(5, Symbol(), context => { if(context.__template) from(context.__template) return {} }) @@ -79,3 +79,20 @@ register.auto = finder => { from(document) } } + +register.style = url => { + const sheet = new CSSStyleSheet + define.register(6, Symbol(), context => { + return { + connectedCallback: function(meta){ + const root = meta.root.mode ? meta.root : this.getRootNode() + const sheets = root.adoptedStyleSheets + if(sheets.includes(sheet)) return + root.adoptedStyleSheets = [...sheets, sheet] + } + } + }) + return fetch(url) + .then(response => response.text()) + .then(styles => sheet.replace(styles)) +}