A collection of utilities I use when making vanilla js applications. A mini-framework if you will.

Overview

R2.js

A collection of utilities I use when making vanilla js applications.

Installation

Copy ./r2.js over to your project. It small. Do wtf u want with it.

Usage

HTML Templating

Ever wanted to simply write out html instead of a chain of document.createElement() and setting attributes manually? Use HTML Templating from r2.js.

import { html } from 'r2.js';

const todos = [
  { task: 'install r2.js', done: false },
  { task: 'star r2.js', done: false },
  { task: 'tell friends to star r2.js', done: false }
];

const renderTodo = (todo, i) => html`
<div class="todo">
  <input type="checkbox" id="todo-${i}" ${todo.done && 'checked'}></input>
  <label for="todo-${i}">${todo.task}</label>
</div>
`;

const app = html`
  <h1>Todos</h1>
  <p>${todos.every(t => t.done) && 'Congratulations, you did everything!'}</p>
  <div class="todos">
    ${todos.map(renderTodo)}
  </div>
`;

// mount app to the document body
document.body.appendChild(app);

State Management

I love svelte stores but, they require me to install svelte. Unfortunately, the spirit of my lord and saviour Rich Harris cannot always be with me, so I have made my own bootleg svelte store. I will consider adding derived stores to this although it isn't too bad doing derived stores manually.

We will now re-write the above todos example with useState to add reactivity.

The below example is hosted at https://r2dev2.github.io/r2.js/todo.html

import { html, useState } from 'r2.js';

const [ todos, setTodos, subTodos ] = useState([
  { task: 'install r2.js', done: false },
  { task: 'star r2.js', done: false },
  { task: 'tell friends to star r2.js', done: false }
]);

const [ allDone, setAllDone, subAllDone ] = useState(false);

// whenever todos updates, update the allDone store
// this is poor man's derived store
subTodos($todos => setAllDone($todos.every(t => t.done)));

// whenever everything is done, tell the user with an annnoying alert message
// we need a built in confetti
subAllDone($allDone => $allDone && alert('Congratulations for doing everything'));

const renderTodo = (todo, i) => html`
<div class="todo">
  <input type="checkbox" id="todo-${i}" ${todo.done && 'checked'}></input>
  <label for="todo-${i}">${todo.task}</label>
</div>
`;

const createTodo = (todo, i) => {
  const todoEl = renderTodo(todo, i);

  const checkbox = todoEl.querySelector('input[type=checkbox]');
  checkbox.addEventListener('change', () => {
    const newTodos = [...todos()];
    newTodos[i] = {...newTodos[i], done: checkbox.checked};
    setTodos(newTodos);
  });

  return todoEl;
};

// TODO this app won't change whenever allDone changes or todos changes
const app = html`
<div id="app">
  <h1>Todos</h1>
  <p class="congrats-msg" />
  <div class="todos" />
</div>
`;

subAllDone($allDone => {
  app.querySelector('.congrats-msg').textContent = $allDone
    ? 'Congratulations, you did everything!'
    : '';
});

subTodos($todos => {
  const container = app.querySelector('.todos');
  const previousChildren = [...container.children];
  $todos.map(createTodo).forEach(container.appendChild.bind(container));
  previousChildren.forEach(e => e.remove());
});

// mount app to the document body
document.body.appendChild(app);

Various JS Utilities

Imagine lodash but good.

import { compose, pipe, sortBy, suppress, sleep, clamp } from 'r2.js';

// coolFn1(x) == fn1(fn2(fn3(x)))
const coolFn1 = compose(fn1, fn2, fn3);

// coolFn2(x) = fn3(fn2(fn1(x))) kinda like the | in bash
const coolFn2 = pipe(fn1, fn2, fn3);

// basically Array.prototype.sort but with a key
// will return the array but backwards (sorted by y)
sortBy([
  { x: 0, y: 2 },
  { x: 1, y: 1 },
  { x: 2, y: 0 }
], 'y');

// returns the result of cb if it succeeded, returns error if failed
// either way, nothing will be thrown ultimately
// in this invocation, it'll remove the element if it was found otherwise
// do nothing
suppress(() => {
  document.querySelector('.something-to-remove').remove();
});

// sleeps for 100 ms
await sleep(100);

// if number is less than min, return min
// if it's greater than max, return max
// otherwise return x
// it's basically css's clamp
clamp(x, min, max);
You might also like...

A collection of functions and methods to make it easier for you to create applications.

def-helper A collection of functions and methods to make it easier for you to create applications. Install npm install --save def-helper Usage import

Oct 13, 2022

Remix enables you to build fantastic user experiences for the web and feel happy with the code that got you there. In this workshop, we'll look at some more advanced use cases when building Remix applications.

💿 Advanced Remix Workshop Remix enables you to build fantastic user experiences for the web and feel happy with the code that got you there. In this

Dec 9, 2022

An easy-to-use JavaScript library aimed at making it easier to draw on SVG elements.

svg-pen-sketch An easy-to-use JavaScript library aimed at making it easier to draw on SVG elements when using a digital pen (such as the Surface Pen).

Jul 27, 2022

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

Phaser is a fun, free and fast 2D game framework for making HTML5 games for desktop and mobile web browsers, supporting Canvas and WebGL rendering.

Phaser - HTML5 Game Framework Phaser is a fast, free, and fun open source HTML5 game framework that offers WebGL and Canvas rendering across desktop a

Jan 7, 2023

A easy-to-use framework for building immersive decentralized applications

A easy-to-use framework for building immersive decentralized applications

Dec 27, 2022

Utilities for parsing and manipulating LaTeX ASTs with the Unified.js framework

unified-latex Monorepo for @unified-latex packages. These packages provide a JS/TypeScript interface for creating, manipulating, and printing LaTeX Ab

Dec 27, 2022

front-end framework for fast and powerful configuration of utilities and intuitive UI

front-end framework for fast and powerful configuration of utilities and intuitive UI Getting Started with Vector → Getting started A variety of optio

Jun 29, 2022

front-end framework for fast and powerful configuration of utilities and intuitive UI

front-end framework for fast and powerful configuration of utilities and intuitive UI Getting Started with Vector → Getting started A variety of optio

Jun 29, 2022

This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js

This is a vanilla Node.js rest API created to show that it is possible to create a rest API using only vanilla Node.js. But in most cases, I would recommend you to use something like Express in a production project for productivity purposes.

Jul 19, 2022
Owner
Ronak Badhe
I'm a 18 year old developer at UCLA. I play chess and do full stack and ml. • @LiveTL • arch user btw
Ronak Badhe
A collection of framework specific Cache utilities for working with Supabase.

supabase-cache-helpers A collection of framework specific Cache utilities for working with Supabase. Supabase Launch Week Hackathon 5 Submission Team

Philipp Steinrötter 91 Dec 29, 2022
A collection of Aurelia 2 example applications showcasing how to build Aurelia 2 applications and other tasks.

Aurelia 2 Examples A monorepository of a treasure trove of Aurelia 2 example applications you can use as a guide to help you build your own applicatio

aurelia 12 Dec 29, 2022
Fullstack Dynamic NFT Mini Game built using 💎 Diamond Standard [EIP 2535] 🏃‍♀️Players can use Hero NFT to battle against Thanos ⚔ Heroes can be Healed by staking their NFT 🛡

?? Fullstack Dynamic NFT Mini Game ?? ?? Using Diamond Standard Play On ?? ?? ⏩ http://diamond-dapp.vercel.app/ Project Description ?? Fullstack Dynam

Shiva Shanmuganathan 21 Dec 23, 2022
Functionless-based mini-framework for DynamoDB migrations in AWS CDK.

dynamodb-migrations This repo is heavily in progress! Readme describes desired contract and functionality. Please do not try using it yet!. I'm not ev

Rafal Wilinski 23 Dec 20, 2022
Manually curated collection of resources, plugins, utilities, and other assortments for the Sapphire Community projects.

Awesome Sapphire Manually curated collection of resources, plugins, utilities, and other assortments for the Sapphire Community projects. Has your pro

Sapphire 20 Dec 17, 2022
Collection of SEO utilities like sitemap, robots.txt, etc. for a Remix Application

Remix SEO Collection of SEO utilities like sitemap, robots.txt, etc. for a Remix Features Generate Sitemap Generate Robots.txt Installation To use it,

Balavishnu V J 128 Dec 21, 2022
A collection of opening hours-related utilities.

Opening-Hours-Utils A collection of opening hours-related utilities. tl;dr Install by executing npm install @wojtekmaj/opening-hours-utils or yarn add

Wojciech Maj 9 Jan 7, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
This plugin add a new utilities classes so you can use from 0% to 100%!

This plugin add new utilities classes so you can use from 0% to 100%!

Ehsan Akbarzadeh 2 Apr 3, 2022
A mini project that shows whom doesn't follow you back on Github

Doesn't follow you back This is a simple and basic project that shows you whom doesn't follows you back on Github, so you can challenge them to a duel

Nicolas Massardo 43 Dec 21, 2022