npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

query-assigned-element-content

v0.0.2

Published

Decorator to query the content of elements assigned to a slot

Downloads

1

Readme

queryAssignedElementContent

A class accessor decorator that converts a class property into a getter which lets you query the content of elements assigned to a <slot>. Use it to simplify the selection of slot content in your web component.

The decorator supports the latest (stage: 3) TC39 proposal - which is not yet implemented by browser vendors. However with TypeScript 5 we can use those already.

Some notes:

  • using both experimentalDecorators and stage 3 decorators in the same file is not possible. In the same project for separate files this could work, but that needs some work and several tsconfig files.
  • Some libraries do not yet support the latest decorator proposal
  • Even if it is not an experimentalDecorators (😅) decorator, it is experimental and therefore to be used with that in mind

Feel free to contribute and giving feedback

Usage

Let's just say we are developing a web component which takes in content using the slot-attribute:

<deco-element>
  <ul slot="list">
    <li>Tethys</li> 
    <li>Mimas</li>
  </ul>
</deco-element>

The assigned element in this example is a <ul> which contains some <li> elements. We want to select those list items from within the component and toggle a class when clicked. That could look like this:

import { queryAssignedElementContent } from './query-assigned-element-content.js';

class DecoElement extends HTMLElement {
  @queryAssignedElementContent({ selector: 'li', slot: 'list' })
  private accessor _listElements!: Array<HTMLLIElement>;

  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot!.innerHTML = `<slot name="list"></slot>`;
   
    this._listElements.forEach(listElement =>
      listElement.addEventListener('click', e => {
        (e.target as HTMLLIElement).classList.toggle('active');
      })
    );
  }
}

customElements.define('deco-element', DecoElement);

Motivation

I use the Lit library fairly frequently and developed a component a while ago. It highlights links in a table of contents when their corresponding headings appear in your device's viewport. These links come pre-rendered on my personal website from an SSG and must be added using a slot (see my post about it).

Using Lit's @queryAssignedElements^1 decorator that could look like this (simplified):

@customElement('toc-observer')
export class TocObserver extends LitElement {
  // ...

  @queryAssignedElements({slot: 'toc'})
  private _tocList?: Array<HTMLUListElement>;

  private get _tocListItems(): HTMLAnchorElement[] | null {
    return this._tocList?.length
      ? [...this._tocList[0].querySelectorAll<HTMLAnchorElement>('[href^="#"]')]
      : null;
  }
}

With my decorator this would become:

@customElement('toc-observer')
export class TocObserver extends LitElement {
  // ...

  @queryAssignedElementContent({
    selector: '[href^="#"]',
    slot: 'toc',
  })
  private accessor _tocListItems!: Array<HTMLLIElement>;
}

Currently it's not supported by Lit to use both types of decorators but it's something that is being worked on. My motivation was mainly to simplify my own use case and to familiarize myself with a technical specification about a topic for which has not been written much about it yet.

Installation

npm i query-assigned-element-content

Development

Install project dependencies

npm i

Run the next two commands in parallel:

# Build with TS:
npm run build:watch
# Start a webserver:
npm run wds:serve

Inspiration & other useful resources