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

推荐订阅源

N
News and Events Feed by Topic
GbyAI
GbyAI
博客园 - Franky
宝玉的分享
宝玉的分享
Blog — PlanetScale
Blog — PlanetScale
Google DeepMind News
Google DeepMind News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
人人都是产品经理
人人都是产品经理
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
腾讯CDC
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
I
InfoQ
The Cloudflare Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Engineering at Meta
Engineering at Meta
MongoDB | Blog
MongoDB | Blog
有赞技术团队
有赞技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
F
Full Disclosure
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Vercel News
Vercel News
博客园 - 【当耐特】
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Schneier on Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Project Zero
Project Zero
量子位
M
MIT News - Artificial intelligence
Stack Overflow Blog
Stack Overflow Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
美团技术团队
Attack and Defense Labs
Attack and Defense Labs
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
P
Proofpoint News Feed
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
S
SegmentFault 最新的问题
L
LINUX DO - 最新话题
Simon Willison's Weblog
Simon Willison's Weblog
爱范儿
爱范儿
博客园 - 聂微东
A
About on SuperTechFans
PCI Perspectives
PCI Perspectives
D
Docker

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.