惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
L
LINUX DO - 热门话题
酷 壳 – CoolShell
酷 壳 – CoolShell
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Martin Fowler
Martin Fowler
G
GRAHAM CLULEY
Simon Willison's Weblog
Simon Willison's Weblog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
V
Vulnerabilities – Threatpost
云风的 BLOG
云风的 BLOG
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
I
Intezer
Scott Helme
Scott Helme
A
About on SuperTechFans
博客园 - 司徒正美
Hacker News: Ask HN
Hacker News: Ask HN
The GitHub Blog
The GitHub Blog
Forbes - Security
Forbes - Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
博客园 - 聂微东
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
T
Tailwind CSS Blog
S
Security Affairs
宝玉的分享
宝玉的分享

Ben Frain

So, you want a React modal that uses the <dialog> element and transitions in AND out? Scroll indicators on tables with background colours using animation-timeline Review: SoundPEATS Clip1 Open ear clip-on headphones VS Code – highlight just the active indent guide Review: MoErgo Go60, a split ergonomic and fully programmable keyboard Review: Kinesis mWave mechanical ergonomic and programmable keyboard iOS26 Safari theme-color/tab-tinting with fixed position elements is a mess New Book: Responsive Web Design with HTML5 and CSS, 5th Edition Use @supports with a proxy feature/value for features you can’t test for (@starting-style) First adventures in View Transitions Review: Benq Screenbar Pro and Halo lightbars. The kit you never knew you needed! Center items in a container, and make then left aligned when they overflow A single element CSS donut timer/countdown timer, that can sit on any background Review: Open Ear Headphones – Bose Open Ultra v Huawei FreeClip In search of the perfect autocomplete for CSS Managing multiple versions of node, without NVM or additional tools Review: Keychron Q14 Max Alice 96 Key mechanical keyboard NEW VIDEO COURSE: Responsive Web Design with HTML5 and CSS Is CSS Grid really slower than Flexbox? Review: Advantage360 Pro Signature Edition 2024 mechanical ergonomic keyboard More Keys or Fewer Keys for mechanical keyboards Yes! You can use position: sticky and overflow together Neovim – how to do project-wide find and replace? Review: Keyboardio Model 100, split, wooden, mechanical keyboard Struggling to learn SwiftUI How to create rounded gradient borders with any background in CSS How to get equal size icons in the cmp completion menu of Neovim with Kitty terminal Review: Dygma Defy, split, mechanical, programmable ergonomic keyboard What’s the best way to reset WAAPI chained animations? Using CSS @property inside shadowRoot (web components) workaround Dynamically create a ref for items when iterating over them in lit.dev templates Selecting and pausing running animations in Lit Web Components New Web APIs — a popover on top of a dialog element can’t be interacted with? Review: ZSA Voyager, split, mechanical keyboard Russel Brand, narcissism, and a sadly common pattern… When it comes to text editors, I feel like Goldilocks Simple settings for writing and converting markdown with Sublime Text Review: The ZSA Platform tenting kit for the Moonlander keyboard Logitech MX Master 3/3s scroll wheel fix Building a line graph with CSS clip-mask Review: Dell 6K 32″ Monitor U3224KBA I broke my keyboard! Swapping the key switches in the Kinesis Advantage360 Pro HUGE macOS Productivity boost: Set-up simple, keyboard only, instant App switching and arrangement Adding to $PATH for a central location for Neovim/NPM tools Neovim Power Tips: Volume 2 Review: MoErgo Glove80, split, wireless, columnar ergonomic keyboard with RGB Review: Kinesis Advantage 360 Pro — split ergo mechanical keyboard Review: Dactyl Manuform – an ergonomic, custom built mechanical keyboard How to animate along an SVG path at the same time the path animates?
Getting the context of Web Components (lit)
Ben Frain · 2022-11-10 · via Ben Frain

The default nature of Web Components and one of their main selling points, is that they are closed off. However, there are occasions when it is very useful to have the context of your component. When styling for example.

There may be subtle variations depending on where your component lives. A different background if in the sidebar area than the main content, for example.

This can be surprisingly long-winded to deal with, but what follows is what I have found to be an effective way.

Passing context down

My context here is Lit. If you want to pass context, or any other properties down, in the absence of the new context package you would typically do this with a property that gets passed down through the tree of components. The outermost relevant component sends in .context=${"sidebar"} and then each subsequest child component recieves and passes on this context, <other-element .context=${this.context}></other-element> and this goes on and on down the chain. Forget a link in the chain and you won’t get any context.

Turns out you can also reach from within a component up.

Reaching up for context

There is a method of the Node interface called getRootNode() and we can use that to get the tag name of the next parent element like this:

this.getRootNode()?.host?.tagName

We have the optional chaining operator (?) in there just to stop it erroring if it fails to find something.

And that will return you a string something like SIDE-BAR, always in uppercase. So you may want to massage that a little more, maybe lower-casing it:

this.getRootNode()?.host?.tagName.toLowerCase()

Multiple levels

Although it doesn’t look particularly elegant, you can walk up the tree of hosts like this (for two hosts up):

this.getRootNode()?.host?.getRootNode()?.host?.toLowerCase()

And chain it on as many times as you like.

TypeScript

The double-edged sword of TypeScript may whinge at you that it doesn’t know what host is. You may need to add something like this to the bottom of your component:

declare global {
    interface Node {
        host: any;
    }
}

A wrapping utility function

My first inclination was to try and build a function up with a loop. But I think this could only be achieved with ultimately using either new Function() or eval() on a string made to be a function. That seemed like a particularly bad idea.

Thanks to Shiv in the comments, here is a lovely and elegant solution:

function getAncestorHost(component: Element, level: number = 1) {
    let host = component;
    let current = level;

    while (current-- > 0) {
        const h = (host.getRootNode() as ShadowRoot | undefined)?.host;

        if (h === undefined) {
            console.warn(`Could not find host (level ${current + 1}/${level})`);
            return host;
        }

        host = h;
    }

    return host.tagName.toLowerCase();
}

Now you can write getAncestorHost(this, 5), rather than writing:

this.getRootNode()?.host?
.getRootNode()?.host?
.getRootNode()?.host?
.getRootNode()?.host?
.getRootNode()?.host?
.tagName.toLowerCase()

The odd time you need to.

Summary

Whichever method you choose, there is a convenient(ish) way to get the context of your web component for styling. For my case I typically add the context as an attribute:

<my-component data-context="${getAncestorHost(this," 2)}></my-component>

Which then let’s me style it like this:

:host([data-context="whatever-the-context-is"]) {
  /* styles */
}

Which is usually preferable to using the method of passing properties down the chain (which I have subsequently heard described at ‘prop drilling’). Until the Context Protocol is established at least.