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

@tdreyno/fizz

v5.2.0

Published

[![Test Coverage](https://api.codeclimate.com/v1/badges/bade509a61c126d7f488/test_coverage)](https://codeclimate.com/github/tdreyno/fizz/test_coverage) [![npm latest version](https://img.shields.io/npm/v/@tdreyno/fizz/latest.svg)](https://www.npmjs.com/pa

Downloads

131

Readme

Fizz

Test Coverage npm latest version Minified Size

Fizz is a small library for building state machines that can effectively manage complex sequences of events. Learn more about state machines (and charts).

Install

npm install --save @tdreyno/fizz

Let's play pong

This example shows how we would model something like a game of Pong.

import {
  state,
  createAction,
  ActionCreatorType,
  onFrame,
  OnFrame,
  Enter,
} from "@tdreyno/fizz"

export const start = createAction("Start")
export type Start = ActionCreatorType<typeof start>

export const onPaddleInput = createAction("OnPaddleInput")
export type OnPaddleInput = ActionCreatorType<typeof onPaddleInput>

type Data = {
  ballPosition: [x: number, y: number]
  ballVector: [x: number, y: number]
  leftPaddle: number
  rightPaddle: number
}

const Welcome = state<Start, Data>({
  Start: () =>
    Playing({
      ballPosition: [0, 0],
      ballVector: [1, 1],
      leftPaddle: 0,
      rightPaddle: 0,
    }),
})

const Playing = state<Enter | OnPaddleInput | OnFrame, Data>({
  Enter: onFrame,

  OnPaddleInput: (data, { whichPaddle, direction }, { update }) => {
    data[whichPaddle] = data[whichPaddle] + direction

    return update(data)
  },

  OnFrame: (data, _, { update }) => {
    // Handle bouncing off things.
    if (doesIntersectPaddle(data) || doesTopOrBottom(data)) {
      data.ballVector = [data.ballVector[0] * -1, data.ballVector[1] * -1]

      return [update(data), onFrame()]
    }

    // Handle scoring
    if (isOffscreen(data)) {
      return Victory(ballPosition < 0 ? "Left" : "Right")
    }

    // Otherwise run physics
    data.ballPosition = [
      data.ballPosition[0] + data.ballVector[0],
      data.ballPosition[1] + data.ballVector[1],
    ]

    return [update(data), onFrame()]
  },
})

const Victory = state<Enter, string>({
  Enter: winner => log(`Winner is ${winner}`),
})

onFrame is an action that is called via requestAnimationFrame. Assume doesIntersectPaddle, doesTopOrBottom and isOffscreen are doing bounding boxes checks.

Our renderer can now check the current state each frame and decide whether to render the Welcome screen, the Victory screen or the game of Pong.

Pure Javascript Runtime

The Runtime is what connects the states together, runs actions and allows state change over time.

Runtimes use a Context to hold historical information about states. To setup a Runtime, first create a context with the initial state as the only item in the first parameter (history).

import {
  createInitialContext,
  createRuntime,
  noop,
  Enter,
  enter,
} from "@tdreyno/fizz"

const Start = state<Enter>({
  Enter: noop,
})

const context = createInitialContext([Start()])

const runtime = createRuntime(context)

You can now send actions to the runtime. To kick things off, let's enter the initial state:

const result = await runtime.run(enter())

assert(isState(runtime.currentState(), Start))

You can continue to run actions on the runtime and await their resulting new state.

React Runtime

If you are using React, you can create a machine provider and access the current state with hooks.

import { createFizzContext, useMachine, Enter, ActionCreatorType, createAction } from "@tdreyno/fizz"

const finished = createAction<"Finished", string>("Finished")
type Finished = ActionCreatorType<typeof finished>

const Start = state<Enter | Finished>({
  Enter: noop,
  Finished: () => End()
})

const End = state<Enter>({
  Enter: noop,
})

const Machine = createFizzContext({
  Start,
  End,
}, {
  finish
})

const ShowState = () => {
  const { currentState, actions: { finished } } = useMachine(Machine)

  return <div role="name">
    <h1>{currentState.name}</h1>
    <button onClick={() => finished()}>
  </div>
}

const App = () => (
  <Machine.Provider initialState={States.Start()}>
    {({ currentState, actions }) => <ShowState />}
  </Machine.Provider>
)

Svelte Runtime

If you are using Svelte, you can create a machine provider and access the current state with a store.

import { createMachine } from "@tdreyno/fizz/svelte"

const machine = createMachine(states, actions, initialState)

$: {
  console.log($machine.currentState)
}

Design

Fizz attempts to provide an API that is "Just Javascript" and operates in a pure and functional manner[^1].

States are mappings of actions to future states. The action type is the same format as a Redux action.

States return one or more side-effects (or a Promise of one or more side-effects), which are simply functions which will be called in the order they were generated at the end of the state transition.

States can be entered by sending the Enter action. Here is an example of a simple state which logs a message upon entering.

import { state, Enter } from "@tdreyno/fizz"

const MyState = state<Enter>({
  Enter: () => log("Entered state MyState."),
})

In this case, log is a side-effect which will log to the console. It is implemented like so:

// The side-effect generating function.
function log(msg) {
  // A representation of the effect, but not the execution.
  return effect(
    // An effect name. Helps when writing tests and middleware.
    "log",

    // The data associated with the effect. Also good for tests and middleware.
    msg,

    // Finally, the method which will execute the effect
    () => console.log(msg),
  )
}

This level of indirection, returning a function that will cause an action, rather than immediately executing the action, gives us some interesting abilities.

First, all of our states are pure functions, even if they will eventually communicate with external systems. This allows for very easy testing of state logic.

Second, external middleware can see the requested side-effects and modify them if necessary. Say you can one side-effect to update a user's first name via an HTTP POST to the server and you had a second side-effect to update their last name. Because we can modify the list (and implementations) of the effects before they run, we could write middleware to combine those two effects into 1-single HTTP POST.

It is the opinion of this library that "original Redux was right." Simple functions, reducers and switch statements make reasoning about code easy. In the years since Redux was released, folks have many to DRY-up the boilerplate and have only complicated what was a very simple system. We are not interesting in replacing switch statements with more complex alternatives. If this causes an additional level of nesting, so be it.

Technical details

Fizz is implemented in TypeScript and is distributed with .d.ts files.

[^1]: Internally there is some data mutation, but this can be replaced by a more immutable approach if necessary without modifying the external API.