• Stars
    star
    366
  • Rank 116,547 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 8 years ago
  • Updated over 3 years ago

Reviews

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

Repository Details

๐Ÿšƒ - create performant HTML components

nanocomponent stability

npm version build status downloads js-standard-style

Native DOM components that pair nicely with DOM diffing algorithms.

Features

  • Isolate native DOM libraries from DOM diffing algorithms
  • Makes rendering elements very fastโ„ข by avoiding unnecessary rendering
  • Component nesting and state update passthrough
  • Implemented in only a few lines
  • Only uses native DOM methods
  • Class based components offering a familiar component structure
  • Works well with nanohtml and yoyoify
  • Combines the best of nanocomponent@5 and cache-component@5.

Usage

// button.js
var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')

class Button extends Nanocomponent {
  constructor () {
    super()
    this.color = null
  }

  createElement (color) {
    this.color = color
    return html`
      <button style="background-color: ${color}">
        Click Me
      </button>
    `
  }

  // Implement conditional rendering
  update (newColor) {
    return newColor !== this.color
  }
}

module.exports = Button
// index.js
var choo = require('choo')
var html = require('nanohtml')

var Button = require('./button.js')
var button = new Button()

var app = choo()
app.route('/', mainView)
app.mount('body')

function mainView (state, emit) {
  return html`
    <body>
      ${button.render(state.color)}
    </body>
  `
}

app.use(function (state, emitter) {
  state.color = 'green'
})

Patterns

These are some common patterns you might encounter when writing components.

Standalone

Nanocomponent is part of the choo ecosystem, but works great standalone!

var Button = require('./button.js')
var button = new Button()

// Attach to DOM
document.body.appendChild(button.render('green'))

// Update mounted component
button.render('green')
button.render('red')

// Log a reference to the mounted dom node
console.log(button.element)

Binding event handlers as component methods

Sometimes it's useful to pass around prototype methods into other functions. This can be done by binding the method that's going to be passed around:

var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')

class Component extends Nanocomponent {
  constructor () {
    super()

    // Bind the method so it can be passed around
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick (event) {
    console.log('element is', this.element)
  }

  createElement () {
    return html`<button onclick=${this.handleClick}>
      My component
    </button>`
  }

  update () {
    return false // Never re-render
  }
}

ES5 Syntax

Nanocomponent can be written using prototypal inheritance too:

var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')

function Component () {
  if (!(this instanceof Component)) return new Component()
  Nanocomponent.call(this)
  this.color = null
}

Component.prototype = Object.create(Nanocomponent.prototype)

Component.prototype.createElement = function (color) {
  this.color = color
  return html`
    <div style="background-color: ${color}">
      Color is ${color}
    </div>
  `
}

Component.prototype.update = function (newColor) {
  return newColor !== this.color
}

Mutating the components instead of re-rendering

Sometimes you might want to mutate the element that's currently mounted, rather than performing DOM diffing. Think cases like third party widgets that manage themselves.

var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')

class Component extends Nanocomponent {
  constructor () {
    super()
    this.text = ''
  }

  createElement (text) {
    this.text = text
    return html`<h1>${text}</h1>`
  }

  update (text) {
    if (text !== this.text) {
      this.text = text
      this.element.innerText = this.text   // Directly update the element
    }
    return false                           // Don't call createElement again
  }

  unload (text) {
    console.log('No longer mounted on the DOM!')
  }
}

Please note that if you remove a component from the DOM, it will be unloaded, and when reinserted into the DOM, createElement will be fired again. If you want to maintain control of a component's rendering, it has to stay mounted! See issue #88 for a more detailed discussion.

Nested components and component containers

Components nest and can skip renders at intermediary levels. Components can also act as containers that shape app data flowing into view specific components.

var Nanocomponent = require('nanocomponent')
var html = require('nanohtml')
var Button = require('./button.js')

class Component extends Nanocomponent {
  constructor () {
    super()
    this.button1 = new Button()
    this.button2 = new Button()
    this.button3 = new Button()
  }

  createElement (state) {
    var colorArray = shapeData(state)
    return html`
      <div>
        ${this.button1.render(colorArray[0])}
        ${this.button2.render(colorArray[1])}
        ${this.button3.render(colorArray[2])}
      </div>
    `
  }

  update (state) {
    var colorArray = shapeData(state) // process app specific data in a container
    this.button1.render(colorArray[0]) // pass processed data to owned children components
    this.button2.render(colorArray[1])
    this.button3.render(colorArray[2])
    return false // always return false when mounted
  }
}

// Some arbitrary data shaping function
function shapeData (state) {
  return [state.colors.color1, state.colors.color2, state.colors.color3]
}

FAQ

What order do lifecycle events run in?

Lifecycle diagram

Note: aftercreate should actually say afterupdate.

Shoutout to @lrlna for the excellent diagram.

Where does this run?

Nanocomponent was written to work well with choo, but it also works well with DOM diffing engines that check .isSameNode() like nanomorph and morphdom. It is designed and documented in isolation however, so it also works well on it's own if you are careful. You can even embed it in other SPA frameworks like React or Preact with the use of nanocomponent-adapters which enable framework-free components! ๐Ÿ˜Ž

What's a proxy node?

It's a node that overloads Node.isSameNode() to compare it to another node. This is needed because a given DOM node can only exist in one DOM tree at the time, so we need a way to reference mounted nodes in the tree without actually using them. Hence the proxy pattern, and the recently added support for it in certain diffing engines:

var html = require('nanohtml')

var el1 = html`<div>pink is the best</div>`
var el2 = html`<div>blue is the best</div>`

// let's proxy el1
var proxy = html`<div></div>`
proxy.isSameNode = function (targetNode) {
  return (targetNode === el1)
}

el1.isSameNode(el1)   // true
el1.isSameNode(el2)   // false
proxy.isSameNode(el1) // true
proxy.isSameNode(el2) // false

How does it work?

nanomorph is a diffing engine that diffs real DOM trees. It runs a series of checks between nodes to see if they should either be replaced, removed, updated or reordered. This is done using a series of property checks on the nodes.

nanomorph runs Node.isSameNode(otherNode) when diffing two DOM trees. This allows us to override the function and replace it with a custom function that proxies an existing node. Check out the code to see how it works. The result is that if every element in our tree uses nanocomponent, only elements that have changed will be recomputed and re-rendered making things very fast.

nanomorph, which saw first use in choo 5, has supported isSameNode since its conception. morphdom has supported .isSameNode since v2.1.0.

Is this basically react-create-class?

nanocomponent is very similar to react-create-class, but it leaves more decisions up to you. For example, there is no built in props or state abstraction in nanocomponent but you can do something similar with arguments (perhaps passing a single props object to .render e.g. .render({ foo, bar }) and assigning internal state to this however you want (perhaps this.state = { fizz: buzz }).

API

component = Nanocomponent([name])

Create a new Nanocomponent instance. Additional methods can be set on the prototype. Takes an optional name which is used when emitting timings.

component.render([argumentsโ€ฆ])

Render the component. Returns a proxy node if already mounted on the DOM. Proxy nodes make it so DOM diffing algorithms leave the element alone when diffing. Call this when arguments have changed.

component.rerender()

Re-run .render using the last arguments that were passed to the render call. Useful for triggering component renders if internal state has changed. Arguments are automatically cached under this._arguments (๐Ÿ– hands off, buster! ๐Ÿ–). The update method is bypassed on re-render.

component.element

A getter property that returns the component's DOM node if its mounted in the page and null when its not.

DOMNode = Nanocomponent.prototype.createElement([argumentsโ€ฆ])

Must be implemented. Component specific render function. Optionally cache argument values here. Run anything here that needs to run along side node rendering. Must return a DOMNode. Use beforerender to run code after createElement when the component is unmounted. Previously named _render. Arguments passed to render are passed to createElement. Elements returned from createElement must always return the same root node type.

Boolean = Nanocomponent.prototype.update([argumentsโ€ฆ])

Must be implemented. Return a boolean to determine if prototype.createElement() should be called. The update method is analogous to React's shouldComponentUpdate. Called only when the component is mounted in the DOM tree. Arguments passed to render are passed to update.

Nanocomponent.prototype.beforerender(el)

A function called right after createElement returns with el, but before the fully rendered element is returned to the render caller. Run any first render hooks here. The load and unload hooks are added at this stage. Do not attempt to rerender in beforerender as the component may not be in the DOM yet.

Nanocomponent.prototype.load(el)

Called when the component is mounted on the DOM. Uses on-load under the hood.

Nanocomponent.prototype.unload(el)

Called when the component is removed from the DOM. Uses on-load under the hood.

Nanocomponent.prototype.afterupdate(el)

Called after a mounted component updates (e.g. update returns true). You can use this hook to call element.scrollIntoView or other dom methods on the mounted component.

Nanocomponent.prototype.afterreorder(el)

Called after a component is re-ordered. This method is rarely needed, but is handy when you have a component that is sensitive to temorary removals from the DOM, such as externally controlled iframes or embeds (e.g. embedded tweets).

Installation

$ npm install nanocomponent

Optional lifecycle events

You can add even more lifecycle events to your components by attatching the following modules in the beforerender hook.

See also

Examples

Similar Packages

License

MIT

More Repositories

1

choo

๐Ÿš‚๐Ÿš‹ - sturdy 4kb frontend framework
JavaScript
6,776
star
2

bankai

๐Ÿš‰ - friendly web compiler
JavaScript
1,088
star
3

hyperx

๐Ÿท - tagged template string virtual dom builder
JavaScript
1,010
star
4

nanomorph

๐Ÿš… - Hyper fast diffing algorithm for real DOM nodes
JavaScript
726
star
5

nanohtml

๐Ÿ‰ HTML template strings for the Browser with support for Server Side Rendering in Node.
JavaScript
687
star
6

nanographql

Tiny graphQL client library
JavaScript
421
star
7

wayfarer

๐Ÿ‘“ composable trie based router
JavaScript
332
star
8

choo-handbook

๐Ÿš‚โœ‹๐Ÿ“– - Learn the choo framework through a set of exercises
HTML
268
star
9

nanobus

๐ŸšŽ - Tiny message bus
JavaScript
225
star
10

awesome-choo

๐ŸŒ… Awesome things related with choo framework
197
star
11

create-choo-app

๐Ÿšž - create a fresh choo application
JavaScript
181
star
12

nanostate

๐Ÿšฆ- Small Finite State Machines
JavaScript
170
star
13

nanorouter

๐Ÿ›ค - Small frontend router
JavaScript
116
star
14

nanocomponent-adapters

๐Ÿ”Œ - Convert a nanocomponent to a component for your favourite API or library (web components, (p)react, angular)
JavaScript
96
star
15

choop

๐Ÿš‚โš›๏ธ - choo architecture for preact
JavaScript
93
star
16

on-idle

๐Ÿ˜ด - Detect when the browser is idle
JavaScript
82
star
17

nanologger

๐Ÿ“œ - Cute browser logs
JavaScript
80
star
18

nanoanimation

๐Ÿ‘จโ€๐ŸŽจ - Safety wrapper around the Web Animation API
JavaScript
72
star
19

nanoraf

๐ŸŽž - Only call RAF when needed
JavaScript
71
star
20

choo-devtools

๐Ÿ’ผ - Expose a choo instance on the window
JavaScript
53
star
21

nanoquery

๐Ÿ“‡ - Tiny querystring module
JavaScript
49
star
22

nanotask

Microtask queue scheduler for the browser
JavaScript
47
star
23

choo-log

๐Ÿ“ƒ - Development logger for choo
JavaScript
47
star
24

nanoscheduler

Schedule work to be completed when the user agent is idle.
JavaScript
46
star
25

website

๐Ÿš‡ - Hyper Train Transfer Protocol (HTTP)
JavaScript
46
star
26

nanohref

โ›“ - Tiny href click handler library
JavaScript
41
star
27

nanotick

process.nextTick() batching utility
JavaScript
37
star
28

choo-store

Lightweight state structure for choo apps.
JavaScript
37
star
29

nanotiming

โฒ - Small timing library
JavaScript
35
star
30

create-choo-electron

:electron: - Create a fresh Choo Electron application
JavaScript
29
star
31

object-change-callsite

Determine the callsite of an object change using Proxies
JavaScript
27
star
32

choo-reload

โ›ฝ๏ธ - Livereloading package for choo
JavaScript
27
star
33

on-performance

Listen for performance timeline events
JavaScript
26
star
34

nanobeacon

Small navigator.sendBeacon wrapper
JavaScript
25
star
35

choo-service-worker

๐Ÿ‘ท - Service worker loader for choo
JavaScript
24
star
36

choo-scaffold

๐Ÿ— - Scaffold out files for a Choo project
JavaScript
24
star
37

choo-notification

Web Notification plugin for Choo
JavaScript
22
star
38

nanobounce

Smol debounce package
JavaScript
19
star
39

choo-choo

๐ŸŽ“ learn choo from the command line!
JavaScript
19
star
40

nanomount

Mount a DOM tree on a target node
JavaScript
19
star
41

choo-redirect

๐ŸŽฌ - Redirect a view to another view
JavaScript
19
star
42

persist-storage

๐Ÿ—„ - Enable persistent storage in the browser
JavaScript
19
star
43

nanohistory

Small browser history library
JavaScript
14
star
44

choo-hooks

๐ŸŽฃ - Hook into Choo's events and timings
JavaScript
12
star
45

nanolocation

๐Ÿ“- Small window.location library
JavaScript
10
star
46

discuss

๐ŸŽญ โ€“ Discuss project organization, initiatives, and anything else!
8
star
47

nanocache

Cache Nanocomponents.
JavaScript
7
star
48

bankai-website

JavaScript
6
star
49

choo-umd

๐Ÿ™ˆ - umd build for choo framework
HTML
3
star