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

bloc-utils

v0.0.4

Published

Utilities for building applications with the BLoC pattern

Downloads

18

Readme

Business Logic Component Utilities

Tools for building simple business logic component

docs

Example: Todo App

TodoBloc.jsx
import { protectBloc, Behavior } from "bloc-utils";

/**
 * @param {Todo[]} initialTodos
 */
export default function createTodoBloc(initialTodos = []) {
  const $todos = new Behavior(initialTodos);
  const $todoInput = new Behavior("");

  return protectBloc({
    $todos,
    $todoInput,
    toggleTodo(id) {
      $todos.next(
        $todos.value.map(todo => {
          if (todo.id === id) {
            return {
              ...todo,
              done: !todo.done
            };
          } else {
            return todo;
          }
        })
      );
    },
    deleteTodo(id) {
      $todos.next(
        $todos.value.filter(todo => {
          if (todo.id === id) {
            return false;
          } else {
            return true;
          }
        })
      );
    },
    addTodo() {
      if ($todoInput.value) {
        $todos.next([
          ...$todos.value,
          { id: Math.random(), done: false, title: $todoInput.value }
        ]);
        $todoInput.next("");
      }
    },
    updateNewTodoInput(value) {
      $todoInput.next(value);
    }
  });
}
TodoApp.jsx
import React, { useContext } from "react";
import { Observer } from "bloc-utils/react";

import { createTodo } from "../helpers";
import { changeValue, preventDefaultThen } from "../react-helpers";

import createTodoBloc from "./TodoBloc";
import { TodoItem } from "./TodoItem";

/** @type {Todo[]} */
const todos = [
  createTodo("Build UI for TodoApp", true),
  createTodo("Toggling a Todo"),
  createTodo("Deleting a Todo"),
  createTodo("Adding a Todo")
];

export const TodoBloc = React.createContext(createTodoBloc(todos));

export default function AppRoot() {
  return <TodoApp></TodoApp>;
}

function TodoApp() {
  const bloc = useContext(TodoBloc);

  return (
    <div className="container">
      <h1>Todos</h1>
      <ul className="list-group">
        <Observer
          of={bloc.$todos}
          next={todos =>
            todos.map(todo => <TodoItem key={todo.id} todo={todo} />)
          }
        />
      </ul>
      <br />
      <form className="form-group" onSubmit={preventDefaultThen(bloc.addTodo)}>
        <label htmlFor="todo-title">New Todo Title</label>
        <div className="input-group">
          <Observer
            of={bloc.$todoInput}
            next={value => (
              <input
                id="todo-title"
                type="text"
                className="form-control"
                value={value}
                onChange={changeValue(bloc.updateNewTodoInput)}
                placeholder="What do you want to get done?"
              />
            )}
          />
          <button className="btn btn-primary">Add</button>
        </div>
      </form>
    </div>
  );
}
TodoItem.jsx
import React, { useContext } from "react";
import { TodoBloc } from "./TodoApp";
import { onEnterOrClick } from "../react-helpers";

/**
 * TodoItem appears within the TodoApp
 * @param {{ todo: Todo }} props
 */
export function TodoItem({ todo }) {
  const todos = useContext(TodoBloc);

  return (
    <li
      className="list-group-item"
      {...onEnterOrClick(() => {
        todos.toggleTodo(todo.id);
      })}
    >
      <span style={{ textDecoration: todo.done ? "line-through" : "none" }}>
        {todo.title}
      </span>
      <button
        className="btn btn-sm btn-default float-right"
        aria-label={`Delete "${todo.title}"`}
        {...onEnterOrClick(() => {
          todos.deleteTodo(todo.id);
        })}
      >
        🗑
      </button>
    </li>
  );
}

Bloc Testing (jest)

bloc-utils comes with jest wrappers right out of the box to help with your unit testing needs.

By wrapping a bloc in the spyOnBloc helper, every Observable is now enabled to be tested against either the .nextValue (returns a Promise resolved with the nextValue) and the .latestValue property which holds the last value emitted by the observable.

TodoBloc.test.js
import { spyOnBloc } from "bloc-utils/jest";
import { createTodo } from "../helpers";
import createTodoBloc from "./TodoBloc";

function createMockTodos() {
  return [createTodo("Todo 0"), createTodo("Todo 1"), createTodo("Todo 2")];
}

jest.useFakeTimers();

test("todos / update input", async () => {
  const bloc = spyOnBloc(createTodoBloc([]));

  bloc.updateNewTodoInput("abc");

  expect(bloc.$todoInput.latestValue).toBe("abc");
  expect(bloc.$todoInput.nextValue).resolves.toBe("");

  bloc.updateNewTodoInput("");
});

test("todos / add todo", async () => {
  const bloc = spyOnBloc(createTodoBloc([]));

  bloc.updateNewTodoInput("new todo");
  bloc.addTodo();

  const updatedTodos = bloc.$todos.latestValue;

  expect(updatedTodos).toHaveLength(1);

  const [addedTodo] = updatedTodos;

  expect(addedTodo.title).toBe("new todo");
  expect(addedTodo.done).toBe(false);

  expect(bloc.$todoInput.latestValue).toBe("");
});

test("todos / toggle todo", async () => {
  const bloc = spyOnBloc(
    createTodoBloc([{ done: false, id: 1, title: "Todo 1" }])
  );

  // sanity check existing data
  const originalTodos = bloc.$todos.latestValue;

  expect(originalTodos).toHaveLength(1);
  const [originalTodo] = originalTodos;
  expect(originalTodo.done).toBe(false);

  bloc.toggleTodo(1);

  expect(bloc.$todos.latestValue).toHaveLength(1);
  const [updatedTodo] = bloc.$todos.latestValue;
  expect(updatedTodo.done).toBe(true);
});

test("todos / delete todo", async () => {
  const TITLE = "to be deleted";
  const bloc = spyOnBloc(
    createTodoBloc([
      ...createMockTodos(),
      { id: 1, done: false, title: TITLE },
      ...createMockTodos()
    ])
  );

  // sanity check existing data
  const originalTodos = bloc.$todos.latestValue;

  const originalTodosLength = originalTodos.length;
  expect(originalTodos.find(todo => todo.title === TITLE)).toBeDefined();

  bloc.deleteTodo(1);

  const updated = bloc.$todos.latestValue;
  expect(updated).toHaveLength(originalTodosLength - 1);
  expect(updated.find(todo => todo.title === TITLE)).toBeUndefined();
});