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

alfama

v1.3.24

Published

Fine-grained reactive library with no compiler, no magic, and no virtual DOM

Downloads

249

Readme

alfama

⚡ Fine grained reactive UI Library.

Version License: MIT Build Status Badge size

npm: npm i alfama

cdn: https://cdn.jsdelivr.net/npm/alfama/+esm


Features

  • Rich and Complete: From support for SVG to popular patterns like dangerouslySetInnerHTML, ref to <Fragment> and <Portal /> alfama has you covered.
  • Small: Fully featured at ~9kB gzip.
  • Truly reactive and fine grained: Unlike VDOM libraries which use diffing to compute changes, it uses fine grained updates to target only the DOM which needs to update.
  • No Magic: Explicit subscriptions obviate the need of sample/untrack methods found in other fine grained reactive libraries like solid/sinuous. Importantly, many feel that this also makes your code easy to reason about.
  • Signals and Stores: Signals for primitives and Stores for deeply nested objects/arrays.
  • First class HMR: Preserves Signals/Stores across HMR loads for a truly stable HMR experience.
  • DevEx: no compile step needed if you want: choose your view syntax: h for plain javascript or <JSX/> for babel/typescript.

Backers & Sponsors

Ecosystem

Example

Counter - Codesandbox

/** @jsx h **/
import { component, h, render } from "alfama";

// 1) The signal/wire/store functions are passed as a param to
// component definition
const Page = component("HomePage", (props, { signal, wire }) => {
  // 2) Named signals for stable HMR
  const [count, setCount] = signal("count", 0);
  // or $count = signal("count", 0) and then $count.get/$count.set

  // 3) Most importantly: wire reactivity to signals
  // with explicit subscription using the $ token param
  // NB: also makes code easy to reason about and prevents those pesky untrack/sample related errors
  const $doubleCount = wire(($) => count($) * 2);

  return (
    <div id="home">
      <p>Hey, {props.name}</p>
      <button onClick={() => setCount(count() + 1)}>
        Increment / {wire(count)})
      </button>
      <p>Double count = {$doubleCount}</p>
    </div>
  );
});

render(<Page name="John Doe" />, document.body);

Motivation

This library is at its core inspired by haptic that in particular it also favours manual subscription model instead of automatic subscriptions model. This oblivates the need of sample/untrack found in almost all other reactive libraries.

Also it borrows the nomenclature of aptly named Signal and Wire from haptic.

It's also influenced by Sinuous, Solid, & S.js

API

Core

export const HomePage = component<{ name: string }>(
  "HomePage",
  (props, { signal, wire }) => {
    const [count, setCount] = signal("count", 0);
    //.. rest of component
  }
);
<div id="home">
  <button
    onclick={() => {
      setCount(count() + 1);
    }}
  >
    Increment to {wire(($) => $(count))}
  </button>
</div>
export const Todos = component("Todos", (props, { signal, wire, store }) => {
  const $todos = store("todos", {
    items: [{ task: "Do Something" }, { task: "Do Something else" }],
  });
  return (
    <ul>
      <Each
        cursor={$todos.items}
        renderItem={(cursor) => {
          return <li>{cursor().task}</li>;
        }}
      ></Each>
    </ul>
  );
});
export const RouterContext = defineContext<RouterObject>("RouterObject");
const BrowserRouter = component("Router", (props, { setContext, signal }) => {
  setContext(
    RouterContext,
    signal("router", createRouter(window.history, window.location))
  );
  return props.children;
});
const Link = component("Link", (props: any, { signal, wire, getContext }) => {
  const router = getContext(RouterContext);
  //... rest of component
});
export const Prosemirror = component("Prosemirror", (props, { onMount }) => {
  onMount(() => {
    console.log("component mounted");
  });
  // ...
});
export const Prosemirror = component("Prosemirror", (props, { onUnmount }) => {
  onUnmount(() => {
    console.log("component unmounted");
  });
  // ...
});

Helper Components

<When
  condition={($) => count($) > 5}
  views={{
    true: () => {
      return <div key="true">"TRUE"</div>;
    },
    false: () => {
      return <div key="false">"FALSE"</div>;
    },
  }}
></When>
<Each
  cursor={$todos.items}
  renderItem={(cursor) => {
    return <li>{wire(cursor().task)}</li>;
  }}
></Each>
export const PortalExample = component("PortalExample", (props, utils) => {
  const [active, setActive] = utils.signal("active", false);
  return (
    <div>
      <button
        onClick={(e) => {
          setActive(!active());
        }}
      >
        toggle modal
      </button>
      <When
        condition={($) => active($)}
        views={{
          true: () => {
            return (
              <Portal mount={document.body}>
                <div style="position: fixed; max-width: 400px; max-height: 50vh; background: white; padding: 7px; width: 100%; border: 1px solid #000;top: 0;">
                  <h1>Portal</h1>
                </div>
              </Portal>
            );
          },
          false: () => {
            return "";
          },
        }}
      ></When>
    </div>
  );
});

Reciepes

/** @jsx h **/
import { h, render } from "alfama";
import { Layout } from "./index";

const renderApp = ({ Layout }: { Layout: typeof Layout }) =>
  render(<Layout />, document.getElementById("app")!);

window.addEventListener("load", () => renderApp({ Layout }));

if (import.meta.hot) {
  import.meta.hot.accept("./index", (newModule) => {
    if (newModule) renderApp(newModule as unknown as { Layout: typeof Layout });
  });
}
/** @jsx h **/

export const Prosemirror = component("Prosemirror", (props, { onUnmount }) => {
  let container: Element | undefined = undefined;
  let prosemirror: EditorView | undefined = undefined;
  onUnmount(() => {
    if (prosemirror) {
      prosemirror.destroy();
    }
  });
  return (
    <div
      style="
    height: 100%;    position: absolute; width: 100%;"
      ref={(el) => {
        container = el;
        if (container) {
          prosemirror = setupProsemirror(container);
        }
      }}
    ></div>
  );
});
/** @jsx h **/
<div dangerouslySetInnerHTML={{ __html: `<!-- any HTML you want -->` }} />

Concepts

Signals

These are reactive read/write variables who notify subscribers when they've been written to. They act as dispatchers in the reactive system.

const [count, setCount] = signal("count", 0);

count(); // Passive read (read-pass)
setCount(1); // Write

// also possible to use get/set on signal instead of tuples
const $count = signal("count", 0);
$count.get();
$count.set(5);

The subscribers to signals are wires, which will be introduced later. They subscribe by read-subscribing the signal.

Stores

Stores are for storing nested arrays/objects and also act as dispatchers in the reactive system. And like signals, stores can also be read subsribed by wires. Outside of wires, they can be read via reify function. Writes can be done via produce function immer style.

const val = { name: "Jane", friends: [{ id: "1", name: "John" }] };
const $profile = store("profile", val);

// Passive read (read-pass)
const friends = reify($profile.friends);
console.log(friends.length);
// Write
produce($profile.friends, (friends) => {
  friends.push({ id: "2", name: "John Doe 2" });
});

Wires

These are task runners who subscribe to signals/stores and react to writes. They hold a function (the task) and manage its subscriptions, nested wires, run count, and other metadata. The wire provides a $ token to the function call that, at your discretion as the developer, can use to read-subscribe to signals.

wire(($) => {
  // Explicitly subscribe to count signal getter using the subtoken "$"
  const countValue = $(count);

  // also possible to subscribe to a stores using "$" subtoken
  const friendsCount = $($profile.friends);
  return countValue + friendsCount;
});