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

valtio-element

v0.1.0

Published

Create reactive, declarative custom elements with valtio

Downloads

2

Readme

valtio-element

Create reactive, declarative custom elements with valtio

NPM JavaScript Style Guide Open in CodeSandbox

Install

npm install --save valtio valtio-element
yarn add valtio valtio-element

Usage

Element definition

// For handling element state
import { proxy } from 'valtio/vanilla';
// For element lifecycle
import { watch } from 'valtio/utils';
// For element definition
import { define, setRenderer } from 'valtio-element';
// For element rendering
// You can use any renderer or VDOM libraries
import { html, render } from 'lit-html';

// Define our renderer
setRenderer((root, result) => {
  render(result, root);
});

define({
  // Custom element name
  name: 'counter-button',

  // Define props to track for.
  // This is an array of prop names.
  props: [],

  // This setup is only called once.
  // All watch lifecycles inside setup are automatically managed.
  setup() {
    const count = proxy({ value: 0 });

    function increment() {
      count.value += 1;
    }

    watch((get) => {
      console.log('Current count:', get(count).value);
    });

    return (get) => (
      // This re-renders for every tracked updates
      // In this case, it re-renders when count updates.
      html`
        <button @click=${increment}>Count: ${get(count).value}</button>
      `
    );
  },
});
<counter-button></counter-button>

Features

Setup and Render

Inspired by Vue's Composition API, valtio-element has elements with setup definition, which defines the element's logic and the render method.

setup is only called once everytime the element gets connected (see customElements connectedCallback), and constructs the element's logic. The setup then must return a render callback which instructs the element how to render to its Shadow DOM.

define({
  name: 'my-element',
  setup() {
    // element logic
    return () => (
      // render
    );
  }
});

render receives a get callback which is used to track proxy updates and prompts the element to re-render its content.

Props

valtio-element uses the element's props definition for tracking element attributes. You can then access these props with setup. The props object received is wrapped with valtio/vanilla's proxy therefore they are reactive.

define({
  props: ['name'],
  setup(props) {
    watch((get) => {
      console.log('Name:', get(props).name);
    });
  },
});

Element State

valtio-element can use valtio/vanilla's proxy to construct element states.

Lifecycles

valtio-element utilizes valtio/utils's watch to handle element lifecycles and side-effects.

define({
  setup() {
    watch(() => {
      console.log('Mounted');
      return () => {
        console.log('Unmounted');
      };
    });
  },
});

You don't have to worry about managing watch lifecycles, they are automatically tracked and cleaned-up when necessary.

valtio-element also provides onConnected, onAdopted and onDisconnected hooks for handling custom element callbacks.

Functional Declaration

define not just allows objects as element definition but also just plain functions.

define(function CounterButton() {
  const count = proxy({ value: 0 });

  function increment() {
    count.value += 1;
  }

  watch((get) => {
    console.log('Current count:', get(count).value);
  });

  return (get) => (
    // This re-renders for every tracked updates
    // In this case, it re-renders when count updates.
    html`
      <button @click=${increment}>Count: ${get(count).value}</button>
    `
  );
});

Element names are automatically transformed into kebab-case. However, this does not allow explicit prop definitions.

Custom Renderer

The example above utilizes lit-html for rendering the DOM content of the element. You can use any kind of renderer (e.g. react and react-dom, vue, uhtml, etc.) and then define them once with setRenderer.

import { define, setRenderer } from 'valtio-element';
import React from 'react';
import { render } from 'react-dom';

setRenderer((root, result) => {
  render(result, root);
});

define({
  setup() {
    return () => (
      <h1>Hello World</h1>
    );
  },
});

License

MIT © lxsmnsyc