• Stars
    star
    1,326
  • Rank 35,449 (Top 0.7 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A tiny library for building modular UI components using DOM diffing and ES6 tagged template literals

yo-yo.js

A tiny library for building modular UI components using DOM diffing and ES6 tagged template literals, powered by bel and morphdom and based on the "yo-yo" data binding pattern: data down, actions up.

yo-yo powers the choo framework, you should check it out if you want something higher level! or if you want lower level, see the module that powers yo-yo: bel

logo

Getting started is as easy as

var element = yo`<h1>hello world!</h1>`

Give yo-yo a spin in your browser on RequireBin.

Features

  • React-style modular UI components that can efficiently update themselves
  • Build your own framework: small modules that you can swap out to pick your own tradeoffs
  • Uses features available in browsers today instead of inventing new syntax/APIs
  • Designed for template literals, a templating feature built in to JS
  • Uses a default DOM diffing strategy based on the real DOM, not a virtual DOM
  • Compatible with vanilla DOM elements and vanilla JS data structures
  • Doesn't require hundreds of megabytes of devDependencies to build
  • 4kb minified + gzipped (6 times smaller than React), small enough for UI components to include as a dependency

About

yo-yo is a modular UI framework, meaning there isn't much code in this repository, much of the functionality comes from other modules (see index.js). The goals of yo-yo are to choose a good set of default dependencies, document how to use them all together in one place, and use small enough dependencies that you can include a copy of yo-yo in standalone UI component modules and publish them to npm.

You can start by simply doing require('yo-yo') but as your app grows will most likely want to choose different tradeoffs (add or remove dependencies), and yo-yo is designed to let you do that without rewriting all of your code due to API changes, forcing you to use certain dependencies, or making you adopt new coding conventions.

In this way yo-yo is similar to the modular frameworks mississippi, http-framework and mercury.

Installing

You can get it from npm: npm install yo-yo

To create a standalone copy run browserify --standalone yo index.js > yo-yo.js

API

The yo-yo API is very simple and only has two functions.

var yo = require('yo-yo')

Returns the yo function. There is also a method on yo called yo.update.

yo`template`

yo is a function designed to be used with tagged template literals. If your template produces a string containing an HTML element, the yo function will take it and produce a new DOM element that you can insert into the DOM.

yo.update(targetElement, newElement, [opts])

Efficiently updates the attributes and content of an element by diffing and morphing a new element onto an existing target element. The two elements + their children should have the same 'shape', as the diff between newElement will replace nodes in targetElement. targetElement will get efficiently updated with only the new DOM nodes from newElement, and newElement can be discarded afterwards.

Note that many properties of a DOM element are ignored when elements are updated. morphdom only copies the following properties:

  • node.firstChild
  • node.tagName
  • node.nextSibling
  • node.attributes
  • node.nodeType
  • node.nodeValue

In addition to these yo-yo will copy event attributes (e.g. onclick, onmousedown) that you set using DOM attributes in your template.

opts is optional and has these options:

  • events - set false to disable copying of event attributes. otherwise set to an array of strings, one for each event name you want to whitelist for copying. defaults to our default events

The opts object will also get passed to morphdom.

Examples

Here are some UI modules implemented using yo-yo:

And here are some simpler examples:

Creating a simple list

var yo = require('yo-yo')

var el = list([
  'grizzly',
  'polar',
  'brown'
])

function list (items) {
  return yo`<ul>
    ${items.map(function (item) {
      return yo`<li>${item}</li>`
    })}
  </ul>`
}

document.body.appendChild(el)

Dynamic updates

var yo = require('yo-yo')

var numbers = [] // start empty
var el = list(numbers, update)

function list (items, onclick) {
  return yo`<div>
    Random Numbers
    <ul>
      ${items.map(function (item) {
        return yo`<li>${item}</li>`
      })}
    </ul>
    <button onclick=${onclick}>Add Random Number</button>
  </div>`
}

function update () {
  // add a new random number to our list
  numbers.push(Math.random())
  
  // construct a new list and efficiently diff+morph it into the one in the DOM
  var newList = list(numbers, update)
  yo.update(el, newList)
}

document.body.appendChild(el)

Clicking the button three times results in this HTML:

<div>Random Numbers
  <ul>
    <li>0.027827488956972957</li>
    <li>0.742044786689803</li>
    <li>0.4440679911058396</li>
  </ul>
  <button>Add Random Number</button>
</div>

When the button is clicked, thanks to yo.update, only a single new <li> is inserted into the DOM.

Updating events

Event handlers starting with on that you set via attributes will get updated.

function a () { console.log('a') }
function b () { console.log('b') }

var el = yo`<button onclick=${a}>hi</button>`
el.click() // logs 'a' to console

var newEl = yo`<button onclick=${b}>hi</button>`
yo.update(el, newEl)
el.click() // logs 'b' to console

This works because we explicitly copy common event attributes. When yo.update is called above, el is still the same JavaScript Object instance before and after. The only difference is that yo.update will copy any new attributes from newEl onto el. However, if you add custom properties or events to newEl before calling yo.update, for example newEl.addEventListener('foo', handleFoo), they will not be copied onto el.

Modules that work well with yo-yo

The functionality built in to yo-yo covers the same problems as React and JSX, (DOM diffing and templating), using these dependencies of yo-yo:

  • bel - creates DOM elements from template strings
  • morphdom - efficiently morphs DOM elements (without a virtual DOM)

However you might consider these alternatives to the above built-in choices based on your use case:

There are also UI problems that yo-yo does not currently address, such as events. But it's easy to use other modules alongside yo-yo to create your own framework. We might even add some of these to yo-yo in the future:

Older Browser Compatibility / Production Performance

If you are targeting browsers that may not support template literals and would like to get a performance boost by transforming your yo-yo elements into raw document calls:

CSS

  • dom-css - inline CSS helper
  • csjs - namespaced CSS helper
  • csjs-extractify - csjs browserify transform to compile css bundles
  • csjs-injectify - csjs browserify transform that uses insert-css
  • sheetify - browserify modular css transform
  • plain css files - you don't always have to use a fancy CSS module :)

State management

In yo-yo state management is left completely up to you. The simplest approach is the "yo-yo" pattern: simply call a callback up until it reaches a parent where you want to handle updates, then yo.update() the changes down from there, which keeps the elements isolated. But since you are just working with DOM elements, you can do yo.update(document.querySelector('.some-other-element'), newelement) as well.

There are also some other approaches that introduce their own patterns for managing state:

Overview of default dependencies

bel

bel is a module that takes the output from a tagged template string and creates or updates (using DOM diffing) a DOM element tree.

Tagged template literals

Tagged template literals are a way to use template literals (AKA template strings) with functions that take the output of the template string and format them in a certain way.

Regular template literals lets you take code like this:

var multiline = 'hello\n' +
'this\n' +
'is\n' +
'multiline'

And write the same thing like this instead:

var multiline = `hello
this
is
multiline`

Tagged template literals is where you put a function name in front of the template tags, similar to calling a function with () but using the backticks ```` instead of parens.

function doesNothing () {}

doesNothing`im a string`

The above example causes the doesNothing function to get invoked (AKA called), similar to if you did doesNothing('im a string').

The difference is that tagged template strings return a specific output value.

function logArguments (a, b, c, d) {
  console.log(a, b, c, d)
}

logArguments`im a string`

Running the above produces ["im a string", raw: "im a string"] undefined undefined undefined.

If you were to just run console.log(im a string) it would produce "im a string".

However, tagged template strings return the above tagged template array output format.

The first item in the array is an array of all of the strings in your template string. In our case there is only one:

["im a string", raw: "im a string"]

The raw is a property that also contains an array, but where the values are the 'raw' values as there were entered.

If you had this template for example:

logArguments`\u9999`

It would produce this as the first argument to logArguments: ["香", raw: ["\u9999"]]

In template literals, tagged or not, you can interpolate values by embedding javascript expressions inside of ${}

var name = 'bob'
console.log(`hello ${name}!`)

The above produces "hello bob!". However, when called like this:

function logArguments (a, b, c, d) {
  console.log(a, b, c, d)
}

var name = 'bob'
logArguments`hello ${name}!`

It produces the tagged template array ["hello ", "!", raw: ["hello ", "!"]] "bob" undefined undefined

As you can see the first argument is an array of all of the strings, and the rest of the arguments are all of the interpolated values one at a time.

Using this array you can implement your own custom way to render the strings and values. For example to simply print a string you print the strings and values in 'zipped' order):

function printString(strings, valueA, valueB, valueC) {
  console.log(strings[0] + valueA + strings[1] + valueB + strings[2] + valueC)
}

You could also imagine writing the above function in a more general way using loops etc. Or do something entirely different:

hyperx

yo-yo uses a module called bel which in turn uses hyperx to turn tagged template arrays into DOM builder data.

For example:

var hyperx = require('hyperx')

var convertTaggedTemplateOutputToDomBuilder = hyperx(function (tagName, attrs, children) {
  console.log(tagName, attrs, children)
})

convertTaggedTemplateOutputToDomBuilder`<h1>hello world</h1>`

Running this produces h1 {} [ 'hello world' ], which aren't yet DOM elements but have all the data you need to build your own DOM elements however you like. These three arguments, tagName, attrs, children are a sort of pseudo-standard used by various DOM building libraries such as virtual-dom, hyperscript and react, and now hyperx and bel.

You can also use DOM elements not created using hyperx and bel:

var yo = require('yo-yo')
var vanillaElement = document.createElement('h3')
vanillaElement.textContent = 'Hello'

var app = yo`<div class="app">${vanillaElement} World</div>`

Running the above sets app to an element with this HTML:

<div class="app"><h3>Hello</h3> World</div>

morphdom

yo-yo lets you do two basic things: create an element and update it. When you create an element it simply creates a new DOM element tree using hyperx and its own custom code that uses document.createElement.

However, when you update an element using yo.update() it actually uses a module called morphdom to transform the existing DOM tree to match the new DOM tree while minimizing the number of changes to the existing DOM tree. This is a really similar approach to what react and virtual-dom do, except morphdom does not use a virtual DOM, it simply uses the actual DOM.

Benchmarks

You can find benchmarks at https://github.com/shama/yo-yo-perf

More Repositories

1

art-of-node

❄️ a short introduction to node.js
JavaScript
9,640
star
2

menubar

➖ high level way to create menubar desktop applications with electron
TypeScript
6,673
star
3

screencat

🐈 webrtc screensharing electron app for mac os (Alpha)
CSS
3,014
star
4

cool-ascii-faces

ᕙ༼ຈل͜ຈ༽ᕗ
JavaScript
1,753
star
5

voxel-engine

3D HTML5 voxel game engine
JavaScript
1,269
star
6

monu

menubar process monitor mac app [ALPHA]
CSS
1,111
star
7

mississippi

A collection of useful stream utility modules for writing better code using streams
JavaScript
1,084
star
8

callback-hell

information about async javascript programming
JavaScript
815
star
9

javascript-for-cats

an introduction to the javascript programming language. intended audience: cats
JavaScript
775
star
10

websocket-stream

websockets with the node stream API
JavaScript
665
star
11

torrent

download torrents with node from the CLI
JavaScript
637
star
12

concat-stream

writable stream that concatenates strings or data and calls a callback with the result
JavaScript
570
star
13

hexbin

community curated list of hexagon logos
JavaScript
526
star
14

linux

run Linux on Yosemite easily from the CLI
JavaScript
457
star
15

geojson-js-utils

JavaScript helper functions for manipulating GeoJSON
JavaScript
403
star
16

requirebin

write browser JavaScript programs using modules from NPM
JavaScript
391
star
17

extract-zip

Zip extraction written in pure JavaScript. Extracts a zip into a directory.
JavaScript
391
star
18

maintenance-modules

a list of modules that are useful for maintaining or developing modules
348
star
19

tabby

a browser with almost no UI
JavaScript
345
star
20

ndjson

streaming line delimited json parser + serializer
JavaScript
294
star
21

abstract-blob-store

A test suite and interface you can use to implement streaming file (blob) storage modules for various storage backends and platforms
JavaScript
266
star
22

standard-format

converts your code into Standard JavaScript Format
JavaScript
265
star
23

wzrd

Super minimal browserify development server
JavaScript
248
star
24

elementary-electron

NodeSchool workshop for learning Electron
JavaScript
228
star
25

gh-pages-template

free hosting on github! fork this to get a repo with only a gh-pages branch that is easy to edit
CSS
221
star
26

taco

a modular deployment system for unix
215
star
27

toiletdb

flushes an object to a JSON file. lets you do simple CRUD with async safely with the backend being a flat JSON file
JavaScript
215
star
28

bytewiser

a nodeschool workshop that teaches you the fundamentals of working with binary data in node.js and HTML5 browsers
HTML
208
star
29

csv-write-stream

A CSV encoder stream that produces properly escaped CSVs
JavaScript
204
star
30

electron-spawn

easy way to run code inside of a headless electron window from the CLI
JavaScript
198
star
31

voxel

tools to work with voxel generation and meshing in javascript
JavaScript
186
star
32

monocles

[NOT MAINTAINED] diaspora... as a couchapp! in pure javascript and fully OStatus compliant (almost)
JavaScript
180
star
33

simplify-geojson

apply the ramer-douglas-peucker line simplification to geojson features or feature collections in JS or on the CLI
JavaScript
170
star
34

nugget

minimalist wget clone written in node. HTTP GET files and downloads them into the current directory
JavaScript
162
star
35

electron-microscope

use electron-microscope to inspect websites and extract data
JavaScript
157
star
36

domnode

node style streams for HTML5 APIs
JavaScript
154
star
37

voxel-builder

build stuff with blocks in the browser, export for papercraft or 3d printing
CSS
149
star
38

multiplex

A binary stream multiplexer
JavaScript
141
star
39

gifify-docker

docker container for the gifify utility
135
star
40

csv-spectrum

A variety of CSV files to serve as an acid test for CSV parsing libraries
JavaScript
134
star
41

async-team

Documentation about how to run an async team (e.g. a remote team in different places)
132
star
42

node-repl

run a node program but also attach a repl to the same context that your code runs in so you can inspect + mess with stuff as your program is running. node 0.12/iojs and above only
JavaScript
129
star
43

datacouch

[ON HIATUS] distributed, collaborative dataset sharing
JavaScript
122
star
44

HyperOS

A 50MB linux distribution that has dat-container for booting live containers on mac OS
Shell
119
star
45

couchpubtato

use Node.js to make CouchDB eat feeds like potato chips
JavaScript
116
star
46

voxel-mesh

generate a three.js mesh from voxel data
JavaScript
109
star
47

browser-locale

normalizes weird cross browser issues and tries to return the users selected language in 100% client side JS by looking at various properties on the `window.navigator` object
JavaScript
106
star
48

binary-csv

A fast, streaming CSV binary parser written in javascript
JavaScript
105
star
49

cats

BSD licensed cat photos that I've taken
103
star
50

filereader-stream

Read an HTML5 File object (from e.g. HTML5 drag and drops) as a stream.
JavaScript
102
star
51

nets

nothing but nets. http client that works in node and browsers
JavaScript
101
star
52

javascript-editor

codemirror + esprima powered html5 javascript editor component
JavaScript
99
star
53

adventure-time

a web based environment for doing nodeschool adventures
JavaScript
97
star
54

workerstream

use HTML5 web workers with the node stream API
JavaScript
92
star
55

tree-view

tree viewer UI widget made with react
JavaScript
91
star
56

packify

packs up browserify apps by inlining all assets into one html file
JavaScript
89
star
57

ViewKit

UI library designed for WebKit/Mobile Safari/Android WebViews
JavaScript
87
star
58

gut

hosted open data filet knives
JavaScript
86
star
59

conversationThreading-js

javascript port of JWZ email conversation threading
JavaScript
83
star
60

refine-python

Python client library for controlling Google Refine
Python
83
star
61

require-times

find out how long require calls take in your program. this is a debugging tool for figuring out why apps load slowly
JavaScript
77
star
62

binary-split

a fast newline (or any delimiter) splitter stream - like require('split') but specific for binary data
JavaScript
77
star
63

commonjs-html-prettyprinter

easy HTML pretty printing in commonJS
JavaScript
76
star
64

voxel-server

multiplayer server for voxel-engine
JavaScript
74
star
65

nginx-vhosts

Programmatically add or remove vhosts to a running Nginx instance
JavaScript
71
star
66

github-oauth

simple node.js functions for doing oauth login with github
JavaScript
71
star
67

get-dat

A command line tutorial to learn dat
HTML
69
star
68

docker-stream

CLI tool for automating the use of docker containers in streaming data processing pipelines. Works on Windows, Mac and Linux.
JavaScript
68
star
69

ogmail

minimalist gmail cli client
JavaScript
63
star
70

dhtkv

CLI for storing arbitrary key/value data in the bittorrent mainline DHT
JavaScript
63
star
71

voxel-hello-world

a template voxel game repo you can use to build your own voxel games
JavaScript
62
star
72

browser-module-sandbox

browser editor for code that gets 'compiled' on the server with node and run on the client
JavaScript
61
star
73

minecraft-skin

load minecraft skins as meshes in three.js applications
JavaScript
58
star
74

atomic-queue

a crash friendly queue that persists queue state and can restart. uses a worker pool and has configurable concurrency
JavaScript
57
star
75

PDXAPI

JSON API for CivicApps.org datasets for Portland, OR
JavaScript
53
star
76

googleauth

Create and load persistent Google authentication tokens for command-line apps
JavaScript
52
star
77

joinopenwifi

automatically join open and internet connect wireless networks on linux
JavaScript
51
star
78

superlevel

a minimalist cli utility for leveldb databases
JavaScript
51
star
79

ble-stream

experimental duplex stream api over bluetooth low energy connections (BLE)
JavaScript
50
star
80

json-merge

given two streams of newline delimited JSON data perform a merge/extend on each object in the stream
JavaScript
49
star
81

haraka-couchdb

a real time email server using nodejs, haraka and couchdb
JavaScript
49
star
82

multirepo

a power tool for batch processing multiple github repositories
JavaScript
49
star
83

mount-url

mount a http file as if it was a local file using fuse
JavaScript
48
star
84

dat-editor

web app console/dashboard/spreadsheet thingy for dat
CSS
47
star
85

csv2html

CSV to HTML command line utility
JavaScript
47
star
86

collaborator

easily add new collaborators to your github repos from the CLI
JavaScript
46
star
87

subcommand

Create CLI tools with subcommands. A minimalist CLI router
JavaScript
44
star
88

blockplot

[alpha] explore minecraft worlds in your browser
JavaScript
44
star
89

refine-ruby

Ruby client library for controlling Google Refine
Ruby
43
star
90

element-class

exactly like .addClass and .removeClass from jquery but without dependencies
JavaScript
42
star
91

biofabric

a client side module for generating biofabric graphs in svg using d3
JavaScript
42
star
92

dat-core

low level implementation of the dat data version graph
JavaScript
42
star
93

kawaii

kawaii face detection
JavaScript
41
star
94

doorknob

convenience module for adding Mozilla Persona user login + LevelDB based session storage to node web apps
JavaScript
38
star
95

stl-obj-viewer

super simple viewer for .stl or .obj files powered by three.js
JavaScript
38
star
96

ftpfs

an ftp client that expose the node fs API
JavaScript
38
star
97

xml-json

convert xml to json on the command line. not streaming, pure javascript
JavaScript
37
star
98

ndarray-stl

convert voxels into 3D printable .stl files
JavaScript
37
star
99

masseuse.js

a (now deprecated) library for fast taps on mobile browsers
JavaScript
37
star
100

current-location

Get your current location (latitude, longitude) on the command line as JSON
JavaScript
37
star