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

snabbmitt

v0.0.16

Published

Stateful components in Snabbdom using Mitt

Downloads

6

Readme

snabbmitt

Stateful components in Snabbdom using Mitt and a subtree patching algorithm implementation

What is the idea?

As you may know, Snabbdom is a really nice virtual DOM library, indeed, is enough mature and extensible to create more complex structures like Stateful Components with a composable, clear and fractal approach.

On the other hand, a stateful component needs a way to manage their internal state and redraw. So, in that case, I think we can use simple event emitters and that's why Mitt is the best choice.

You can try the particles example

It's better to understand with an example. Let's go to create a clock app.

Creating the view for our app

const { snabbmitt } = require('snabbmitt');
const { run } = snabbmitt();
const h = require('snabbdom/h').default;

function App() {
    function view() {
        return h('h1', [
            h('span.hours', '00'),
            ':',
            h('span.minutes', '00'),
            ':',
            h('span.seconds', '00')
        ]);
    }

    return view;
}

run(document.getElementById('app'), App);

DEMO

  1. We got the snabbmitt module
  2. Then we created an instance of the snabbdom patch that returns a run function to mount our app in the DOM.
  3. I always prefer hyperscript over other alternatives like JSX so in these examples, I'm going to use the h snabbdom module.
  4. What about the application? Well, it's only a named function that acts as a function factory for our component and returns a view function. So, the App function is our first component.

Creating a state to keep tracking the hours, minutes and seconds

function App() {
    function store() {
        const state = {
            hours: 0,
            minutes: 0,
            seconds: 0
        };

        return state;
    }

    function displayDigit(digit) {
        if (digit < 10) {
            return `0${digit}`;
        }
        return digit;
    }

    function view({ state }) {
        return h('h1', [
            h('span.hours', displayDigit(state.hours)),
            ':',
            h('span.minutes', displayDigit(state.minutes)),
            ':',
            h('span.seconds', displayDigit(state.seconds))
        ]);
    }

    return {
        view,
        store
    };
}

DEMO

  1. We defined a new function inside our component called store. This function is in charge of creating the state and each behavior related with their mutable updates (like reducers in redux but different, here we are talking about mutable updates).
  2. Now our view function can use the state as a destructuring object argument.
  3. Notice too that our App return an object { view, store } instead of only the view function as before.

Creating the behaviors for our state and how to update it. We are going to use event emitters :)

function App({ emitter }) {
    function store() {
        const state = {
            hours: 0,
            minutes: 0,
            seconds: 0
        };

        emitter.on('clock:update', () => {
            state.seconds++;

            if (state.seconds === 60) {
                state.minutes++;
                state.seconds = 0;
            }

            if (state.minutes === 60) {
                state.hours++;
                state.minutes = 0;
            }

            if (state.hours === 24) {
                state.hours = 0;
            }

            emitter.emit('render');
        });

        return state;
    }

    let interval;
    const hook = {
        create() {
            interval = setInterval(() => emitter.emit('clock:update'), 1000);
        },
        destroy(vnode, removeCallback) {
            clearInterval(interval);
            removeCallback();
        }
    };

    function displayDigit(digit) {
        if (digit < 10) {
            return `0${digit}`;
        }
        return digit;
    }

    function view({ state }) {
        return h('h1', { hook }, [
            h('span.hours', displayDigit(state.hours)),
            ':',
            h('span.minutes', displayDigit(state.minutes)),
            ':',
            h('span.seconds', displayDigit(state.seconds))
        ]);
    }

    return {
        view,
        store
    };
}

DEMO

  1. Each component has their own emitter and is passed as a destructuring argument for the component.
  2. In the store function, we define the event handlers that can do mutable updates to our state.
  3. There is no magic in snabbmitt, update your state doesn't mean that the component will be rendered again, you must force the render explicit using: emitter.emit('render')
  4. The hook implementation of snabbdom is great and we use it to start/stop the timer of each component.

and that's it!

Making the clock app a fractal component for an App of clocks?

Well, I say that the App function is a component, why don't we called Clock? and then...

function Clock({ emitter, props }) {
    function store() {
        const state = {
            hours: props.time ? props.time[0] : 0,
            minutes: props.time ? props.time[1] : 0,
            seconds: props.time ? props.time[2] : 0
        };

        emitter.on('clock:update', () => {
            state.seconds++;

            if (state.seconds === 60) {
                state.minutes++;
                state.seconds = 0;
            }

            if (state.minutes === 60) {
                state.hours++;
                state.minutes = 0;
            }

            if (state.hours === 24) {
                state.hours = 0;
            }

            emitter.emit('render');
        });

        return state;
    }

    let interval;
    const hook = {
        create() {
            interval = setInterval(() => emitter.emit('clock:update'), 1000);
        },
        destroy(vnode, removeCallback) {
            clearInterval(interval);
            removeCallback();
        }
    };

    function displayDigit(digit) {
        if (digit < 10) {
            return `0${digit}`;
        }
        return digit;
    }

    function view({ state, props }) {
        return h('h1', { hook }, [
            props.name,
            ' => ',
            h('span.hours', displayDigit(state.hours)),
            ':',
            h('span.minutes', displayDigit(state.minutes)),
            ':',
            h('span.seconds', displayDigit(state.seconds))
        ]);
    }

    return {
        view,
        store
    };
}

function App() {
    function view() {
        return h('div', [
            component(Clock, { name: 'Clock 1' }),
            component(Clock, { name: 'Clock 2', time: [5 ,20, 16] }),
            component(Clock, { name: 'Clock 3', time: [23, 59, 40] })
        ]);
    }

    return view;
}

DEMO

  1. The snabbmitt instance returns a component function factory too. With this function, you can create stateful components in your app.
  2. Your component can receive a props argument object from his parent and use it either when the component is creating or the view runs.