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

sinuous-lifecycle

v2.1.0

Published

Sinuous onAttach/onDetach DOM lifecycles

Downloads

22

Readme

Sinuous onAttach/onDetach DOM lifecycles

badge:min+gzip badge:min badge:npm-v badge:npm-license badge:npm-types

Write lifecycles in Sinuous.

/components/YourComponent.tsx:

import { h, observable } from 'sinuous';
import { hooks } from '../index.js'; // Optional shorthand notation

const YourComponent = () => {
  const windowSize = observable('');
  const onWindowResize = () =>
    windowSize(`${window.innerWidth}px × ${window.innerHeight}px`);

  hooks.onAttach(() => {
    onWindowResize();
    window.addEventListener('resize', onWindowResize);
  });
  hooks.onDetach(() => {
    window.removeEventListener('resize', onWindowResize);
  });
  return <p>The window's size is <span>{windowSize}</span></p>;
};

/index.tsx:

import { h, api } from 'sinuous';
import { trace } from 'sinuous-trace';
import { lifecycle } from 'sinuous-lifecycle';

trace(api);
lifecycle(api, trace);

const hooks = {
  onAttach(fn: () => void) { lifecycle.set('onAttach', fn); },
  onDetach(fn: () => void) { lifecycle.set('onDetach', fn); },
};

const Page = () =>
  <main>
    <YourComponent/>
  </main>

api.add(document.body, <Page/>);

export { hooks };

UI libraries that work with the DOM instead of a virtual DOM often don't have a centralized render loop to know when a component isConnected. Instead, often a MutationObserver is used for these events as seen in packages like disconnected and disco; written for hyperHTML and Sinuous, respectively.

This works, but has very questionable performance and the API isn't personally as intuitive as say, React's componentWillMount. Even without knowing the browser's implementation, it sounds expensive to ask to observe all document changes. Instead, this package does the bookkeeping necessary to provide lifecycles without a MutationObserver.

In sinuous-trace, Sinuous API calls are wrapped to capture component element creation, adoption, and removal. This is stored in a WeakMap tree to hold all component relations. This means sinuous-lifecycle can plug into those events and check whether the parent/child will change their connection to the DOM, providing the onAttach/onDetach lifecycles.

Install

npm install sinuous-trace sinuous-lifecycle

Alternatively, in your HTML:

<!-- ESM -->
<script type="module" src="https://unpkg.com/sinuous-trace?module"></script>
<script type="module" src="https://unpkg.com/sinuous-lifecycle?module"></script>
<!-- IIFE (For older browsers) -->
<script src="https://unpkg.com/sinuous-trace/index.min.js"></script>
<script src="https://unpkg.com/sinuous-lifecycle/index.min.js"></script>

Setup

You extend the Sinuous API yourself when initializing your application. This is explained in the Sinuous internal API documentation.

Here's how to setup Sinuous for tracing and lifecycles. Run this before using any Sinuous calls:

import { api } from 'sinuous';
import { trace } from 'sinuous-trace';
import { lifecycle } from 'sinuous-lifecycle';

// These functions must be run at initialization before Sinuous is called
trace(api);
// This wires up onAttach/onDetach to run automatically
lifecycle(api, trace);

// Optional: Export lifecycle setters however you like
// Alternatively write directly to the Sinuous API as `api.hooks = {...}`
const hooks = {
  onAttach(fn: () => void) { lifecycle.set('onAttach', fn); },
  onDetach(fn: () => void) { lifecycle.set('onDetach', fn); },
  // Any of your custom lifecycles...
};

Note that only onAttach/onDetach run automatically - any custom lifecycles will need lifecycle.callTree() to run. If you write in Typescript, use declaration merging (module augmentation) to extend the module's Lifecycle interface.

Hot Module Reloading

If you're using HMR you must be sure to only run trace and lifecycle once, or you'll receive "Too much recursion" or "Maximum call stack size exceeded" because the function will call itself instead of Sinuous' API.

// In using Parcel/Webpack HMR (or a CodeSandbox)
if (!window.sinuousSetup) {
  window.sinuousSetup = true;
  trace(api);
  lifecycle(api, trace);
}

Just mark that you've done the operation so it's not done again. I use window as an example but it doesn't matter where you store the marker as long as it's outside of the module to being hot reloaded.

Limitations

This works through bookkeeping. The internal Sinuous API has its execution traced to determine what action to take. This means you have to use Sinuous. In MutationObserver, you can run DOM APIs directly (i.e appendChild()) or mix and match libraries like using jQuery now and then.

This won't work in this library. You must use the Sinuous API. If you use Sinuous for all of your UI you'll be fine. If you ever need to use a DOM API for adding or removing nodes, use api.add() or api.rm() instead.

For instance, Sinuous documentation uses document.appendChild() as an example of how to attach your root app to the DOM. Doing this won't cause lifecycles to run. Instead, either:

Call lifecycle tree manually:

const renderedApp = <App/>
document.appendChild(document.querySelector('#root'), renderedApp)
lifecycle.callTree('onAttach', renderedApp);

Use api.add()

api.add(document.querySelector('#root'), <App/>)

Logging / Debugging

badge:min+gzip badge:min

This package includes an optional log package at sinuous-lifecycle/log. Here's an example to setup the browser console logging, extending the above example.

import { api } from 'sinuous';
import { trace } from 'sinuous-trace';
// Optional: Try `logTrace` from sinuous-trace/log too if you'd like both
import { logLifecycle } from 'sinuous-lifecycle/log';

trace(api);
lifecycle(api, trace);
// logTrace(...)
logLifecycle(trace, lifecycle /*, options: LogLifecycleOptions */);

If using HMR you have to make sure this only runs once. This is documented in above in the setup section.

Options: (Defaults shown)

const options: LogLifecycleOptions = {
  consoleStyle: {
    onAttach: 'background: #A6E2B3', // Green
    onDetach: 'background: #F4A89A', // Red
  },
};

There's a notable performance hit when the browser console is open, but does show all lifecycle calls including the root tree element and the total call count.