Repository: yoshuawuyts/nanocomponent Branch: master Commit: ea72ac8796aa Files: 15 Total size: 42.3 KB Directory structure: gitextract_m5verzkw/ ├── .gitignore ├── .npmrc ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── compare.js ├── example/ │ ├── index.js │ └── leaflet.js ├── index.js ├── package.json └── test/ ├── browser/ │ ├── blog-section.js │ ├── index.js │ └── simple.js └── node.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules/ coverage/ tmp/ npm-debug.log* .DS_Store dist .source* .vscode ================================================ FILE: .npmrc ================================================ package-lock=false ================================================ FILE: .travis.yml ================================================ dist: trusty language: node_js node_js: - 'node' sudo: false addons: apt: packages: - xvfb cache: directories: - ~/.npm install: - export DISPLAY=':99.0' - Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & - npm i script: - npm test ================================================ FILE: CHANGELOG.md ================================================ # nanocomponent Change Log All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## 6.6.0 - 2021-04-12 - You can modify makeID (https://github.com/choojs/nanocomponent/pull/96) ## 6.5.3 - 2019-11-12 - Fix `onclick` event name in readme example (https://github.com/choojs/nanocomponent/pull/82) - Add doc note about maintaining control of a component (https://github.com/choojs/nanocomponent/pull/89) - Point out the `createElement()` return value should be a single DOM node (https://github.com/choojs/nanocomponent/pull/93) ## 6.5.2 - 2018-04-20 - Allow SVGs as the root node (https://github.com/choojs/nanocomponent/pull/79) - Update deps ## 6.5.1 - 2018-02-11 - Update nanotiming@7.2.0 - Update devdeps: tap-run, dependency-check, browserify, bankai ## 6.4.6 - 2017-12-05 - Proxy elements are created matching the root node returned from the `createElement` method. (🙏@tornqvist🙏) ## 6.4.5 - 2017-12-03 - Pin `on-load` to v3.3.4 to fix node import. ## 6.4.4 - 2017-12-03 - Pin `on-load` to v3.3.3 to fix unbundled electron import. ## 6.4.3 - 2017-12-02 - Pin `on-load` to 3.3.2 to fix unbundled electron import. ## 6.4.1 - 2017-09-11 - Fixed `afterreorder` hook typo. - Update `on-load` to handle `` loading and for addded assertions. ## 6.4.0 - 2017-09-04 - **Added**: `.rerender()` method to allow re-rendering with the last rendered arguments if internal state changes. - Updated docs for `rerender`. - Add a few more pitfall pointers in the lifecycle API docs around rerendering in `beforerender`. ## 6.3.0 - 2017-08-24 - **Added**: Use [`nanoassert`](https://github.com/emilbayes/nanoassert) in the browser. ## 6.2.0 - 2017-08-18 - **Added**: `afterreorder` event which is called after your component is remounted on sibbling reorders. ## 6.1.0 - 2017-08-14 - **Added**: [nanotiming](https://github.com/choojs/nanotiming) timings. You can name component instances and it will emit timing information. See [nanocomponent/pull/47](https://github.com/choojs/nanocomponent/pull/47) ## 6.0.1 - 2017-08-09 - **Fixed**: [[`f9f7540415`](https://github.com/choojs/nanocomponent/commit/f9f7540415)] - load & unload callbacks should be passed el (timwis) ## 6.0.0 - 2017-08-09 🎉 nanocomponent and [cache-component][cc] are merged into one module: `nanocomponent@6.0.0` 🎉. Be sure to read the README so that you get an understanding of the new API, but here is a quick summary of what has changed from the perspective of both modules: ### Changes since `cache-component@5` `nanocomponent@6` is mostly the same as `cache-component@5` except a few methods are renamed and everything you interact with has had the `_` prefix removed. - **Breaking**: The `_element` [getter][getter] is renamed to `element`. - **Breaking**: `_willMount` is renamed to `beforerender` because DOM mounting can't be guaranteed from the perspective of a component. - **Breaking**: `_didMount` is removed. Consider using `load` instead now. - **Breaking**: `_update` is renamed to `update` and should always be implemented. Instead of the old default shallow compare, not implementing `update` throws. You can `require('nanocomponent/compare')` to implement the shallow compare if you want that still. See below. - **Breaking**: `_args` is removed. `arguments` in `createElement` and `update` are already "sliced", so you can simply capture a copy in `update` and `createElement` and use it for comparison at a later time. - **Breaking**: `_willUpdate` is removed. Anything you could do in `_willUpdate` you can just move to `update`. - **Changed**: `_didUpdate` is renamed to `afterupdate`. It also receives an element argument `el` e.g. `afterupdate(el)`. This makes its argument signature consistent with the other life-cycle methods. - **Added**: Added [on-load][ol] hooks `load` and `unload`. [on-load][ol] listeners only get added when one or both of the hooks are implemented on a component making the mutation observers optional. #### `cache-component@5` to `nanocomponent@6` upgrade guide: - Renamed `_render` to `createElement`. - You must implement `update` now. Rename existing `_update` method to `update`. Here is an example of doing shallow compare on components that didn't implement their own update function previously: ```js var html = require('choo/html') var Component = require('nanocomponent') var compare = require('nanocomponent/compare') class Meta extends Component { constructor () { super() this.arguments = [] } createElement (title, artist, album) { this.arguments = arguments // cache a copy of arguments return html`

${title}

${artist} - ${album}

` } // Implement this to recreate cache-component@5 // behavior when update was not implemented update () { return compare(arguments, this.arguments) } } ``` - Rename components with `_willMount` to `beforerender` - Move any `_didMount` implementations into `load` or a `window.requestAnmimationFrame` inside of `beforerender`. - Move any `_willUpdate` implementations into `update`. - Rename `_didUpdate` to `afterupdate`. - Take advantage of `load` and `unload` for DOM insertion aware node interactions 🙌 ### Changes since `nanocomponent@5` `nanocomponent@6` has some subtle but important differences from `nanocompnent@5`. Be sure to read the README and check out the examples to get an understanding of the new API. - **Breaking**: The `_element` property is removed. A [getter][getter] called `element` is now used instead. Since this is now a read-only getter, you must not assign anything to this property or else bad things will happen. The `element` getter returns the component's DOM node if mounted in the page, and `undefined` otherwise. You are allowed to mutate that DOM node by hand however. Just don't reassign the property on the component instance. - **Fixed**: Components can gracefully be removed, re-ordered and remounted between views. You can even mutate the same component over individual instances. This is an improvement over `nanocomponent@5`. - **Breaking**: `_render` is renamed to `createElement` and must now return a DOM node always. In earlier versions you could get away with not returning from `_render` and assigning nodes to `_element`. No longer! Also, you should move your DOM mutations into `update`. - **Changed**: Update still works the same way: return true to run `createElement` or return false to skip a call to `createElement` when `render` is called. If you decide to mutate `element` "by hand" on updates, do that here (rather than conditional paths inside `createElement`). - **Changed**: `_load` and `_unload` renamed to `load` and `unload`. They have always been optional, but now the mutation observers are only added if at least one of these methods are implemented prior to component instantiation. - **Added**: `beforerender` lifecycle hook. Its similar to `load` but runs before the function call to `render` returns on unmounted component instances. This is where the [on-load][ol] listeners are added and is a good opportunity to add any other lifecycle hooks. - **Added**: `afterupdate` runs after `update` returns true and the results of `createElement` is mutated over the mounted component. Useful for adjusting scroll position. #### `nanocomponent@5` to `nanocomponent@6` upgrade guide: - Read through the new leaflet example to get an idea of the differences between the old and new API. 🗺 - Renamed `_render` to `createElement` and `_update` to `update`. - Move any DOM mutation code from `createElement` into `update`. - Ensure `createElement` returns a DOM node always. (You will get warnings if you don't and it probably won't work) - Rename `_load` and `_unload` to `load` and `unload`. - Consider moving any `load` actions into `beforerender` if they don't depend on the newly rendered node being mounted in a DOM tree yet. - Take advantage of `afterupdate` allowing you to interact with your component after `createElement` is called on mounted components 🙌 [ol]: https://github.com/shama/on-load [cc]: https://github.com/hypermodules/cache-component [nanohtml]: http://ghub.io/nanohtml [nm]: http://ghub.io/nanomorph [getter]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2017 Yoshua Wuyts Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # nanocomponent [![stability][0]][1] [![npm version][2]][3] [![build status][4]][5] [![downloads][8]][9] [![js-standard-style][10]][11] 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][nanohtml] and [yoyoify][yoyoify] - Combines the best of `nanocomponent@5` and [`cache-component@5`][cc]. ## Usage ```js // 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` ` } // Implement conditional rendering update (newColor) { return newColor !== this.color } } module.exports = Button ``` ```js // 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` ${button.render(state.color)} ` } 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! ```js 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: ```js 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`` } update () { return false // Never re-render } } ``` ### ES5 Syntax Nanocomponent can be written using prototypal inheritance too: ```js 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`
Color is ${color}
` } 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. ```js var Nanocomponent = require('nanocomponent') var html = require('nanohtml') class Component extends Nanocomponent { constructor () { super() this.text = '' } createElement (text) { this.text = text return html`

${text}

` } 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](https://github.com/choojs/nanocomponent/issues/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. ```js 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`
${this.button1.render(colorArray[0])} ${this.button2.render(colorArray[1])} ${this.button3.render(colorArray[2])}
` } 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](lifecycle.jpg) **Note:** `aftercreate` should actually say `afterupdate`. Shoutout to [@lrlna](https://github.com/lrlna) for the excellent diagram. ### Where does this run? Nanocomponent was written to work well with [choo][choo], but it also works well with DOM diffing engines that check `.isSameNode()` like [nanomorph][nm] and [morphdom][md]. 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][nca] 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: ```js var html = require('nanohtml') var el1 = html`
pink is the best
` var el2 = html`
blue is the best
` // let's proxy el1 var proxy = html`
` 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`][nm] 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`][nm] 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`][md] has supported `.isSameNode` since [v2.1.0][210]. ### 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) 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][onload] under the hood. ### `Nanocomponent.prototype.unload(el)` Called when the component is removed from the DOM. Uses [on-load][onload] 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 ```sh $ 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. - [yoshuawuyts/observe-resize](https://github.com/yoshuawuyts/observe-resize) - [bendrucker/document-ready](https://github.com/bendrucker/document-ready) - [yoshuawuyts/on-intersect](https://github.com/yoshuawuyts/on-intersect) - [yoshuawuyts/on-idle](https://github.com/yoshuawuyts/on-idle) ## See also - [component-box][cb] - Dynamic component instance caching - [nanomap][nanomap] - Functional mapping into keyed component instances - [choojs/choo][choo] - [choojs/nanocomponent-adapters][nca] - [choojs/nanohtml](https://github.com/choojs/nanohtml) - [shama/on-load](https://github.com/shama/on-load) ## Examples - [Bloomberg: What’s Inside All the iPhones](https://www.bloomberg.com/features/apple-iphone-guts/) (👏 [@jongacnik](https://github.com/jongacnik) 👏) - [twitter-component](https://github.com/bcomnes/twitter-component) - [youtube-component](https://github.com/bcomnes/youtube-component) - [Ara File Manager](https://ara.one/app) (Decentralized application built atop Electron) ## Similar Packages - [shama/base-element](https://github.com/shama/base-element) - [yoshuawuyts/cache-element](https://github.com/yoshuawuyts/cache-element) - [yoshuawuyts/microcomponent](https://github.com/yoshuawuyts/microcomponent) - [hypermodules/cache-component](https://github.com/hypermodules/cache-component) - [rafaelrinaldi/data-components](https://github.com/rafaelrinaldi/data-components) ## License [MIT](https://tldrlegal.com/license/mit-license) [0]: https://img.shields.io/badge/stability-experimental-orange.svg?style=flat-square [1]: https://nodejs.org/api/documentation.html#documentation_stability_index [2]: https://img.shields.io/npm/v/nanocomponent.svg?style=flat-square [3]: https://npmjs.org/package/nanocomponent [4]: https://img.shields.io/travis/choojs/nanocomponent/master.svg?style=flat-square [5]: https://travis-ci.org/choojs/nanocomponent [8]: http://img.shields.io/npm/dm/nanocomponent.svg?style=flat-square [9]: https://npmjs.org/package/nanocomponent [10]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat-square [11]: https://github.com/feross/standard [nanohtml]: https://github.com/choojs/nanohtml [yoyoify]: https://github.com/shama/yo-yoify [md]: https://github.com/patrick-steele-idem/morphdom [210]: https://github.com/patrick-steele-idem/morphdom/pull/81 [nm]: https://github.com/yoshuawuyts/nanomorph [ce]: https://github.com/yoshuawuyts/cache-element [class]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes [isSameNode]: https://github.com/choojs/nanomorph#caching-dom-elements [onload]: https://github.com/shama/on-load [choo]: https://github.com/choojs/choo [nca]: https://github.com/choojs/nanocomponent-adapters [cc]: https://github.com/hypermodules/cache-component [nanomap]: https://github.com/bcomnes/nanomap [cb]: https://github.com/jongacnik/component-box ================================================ FILE: compare.js ================================================ module.exports = compare // included for compatibility reasons only // implements a simple shallow compare for simple values in arrays function compare (array1, array2) { var length = array1.length if (length !== array2.length) return true for (var i = 0; i < length; i++) { if (array1[i] !== array2[i]) return true } return false } ================================================ FILE: example/index.js ================================================ // adapted from https://github.com/timwis/choo-leaflet-demo/blob/master/src/index.js var microbounce = require('microbounce') var html = require('choo/html') var css = require('sheetify') var log = require('choo-log') var choo = require('choo') var Leaflet = require('./leaflet.js') css('leaflet') var leaflet = new Leaflet() var app = choo() app.use(log()) app.use(store) app.route('/', mainView) app.mount('body') var debounce = microbounce(128) function mainView (state, emit) { return html`

${state.title}

${leaflet.render(state.coords)}
` function updateTitle (evt) { var value = evt.target.value debounce(function () { emit('update-title', value) }) } function toPhiladelphia () { emit('set-coords', [39.9526, -75.1652]) } function toSeattle () { emit('set-coords', [47.6062, -122.3321]) } } function store (state, emitter) { state.coords = [39.9526, -75.1652] state.title = 'Hello, World' emitter.on('DOMContentLoaded', function () { emitter.on('set-coords', setCoords) emitter.on('update-title', updateTitle) }) function setCoords (newCoords) { state.coords = newCoords emitter.emit('render') } function updateTitle (newTitle) { state.title = newTitle emitter.emit('render') } } ================================================ FILE: example/leaflet.js ================================================ // // adapted from https://github.com/timwis/choo-leaflet-demo/blob/master/src/map.js var Nanocomponent = require('../') var nanologger = require('nanologger') var leaflet = require('leaflet') var onIdle = require('on-idle') var html = require('nanohtml') module.exports = Leaflet function Leaflet () { if (!(this instanceof Leaflet)) return new Leaflet() Nanocomponent.call(this) this._log = nanologger('leaflet') this.map = null // capture leaflet this.coords = [0, 0] // null island } Leaflet.prototype = Object.create(Nanocomponent.prototype) Leaflet.prototype.createElement = function (coords) { this.coords = coords return html`
` } Leaflet.prototype.update = function (coords) { if (!this.map) return this._log.warn('missing map', 'failed to update') if (coords[0] !== this.coords[0] || coords[1] !== this.coords[1]) { var self = this onIdle(function () { self.coords = coords self._log.info('update-map', coords) self.map.setView(coords, 12) }) } return false } Leaflet.prototype.beforerender = function (el) { var coords = this.coords this._log.info('create-map', coords) var map = leaflet.map(el).setView(coords, 12) leaflet.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.{ext}', { attribution: 'Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap', subdomains: 'abcd', minZoom: 0, maxZoom: 20, ext: 'png' }).addTo(map) this.map = map } Leaflet.prototype.load = function () { this._log.info('load') this.map.invalidateSize() } Leaflet.prototype.unload = function () { this._log.info('unload') this.map.remove() this.map = null this.coords = [0, 0] } ================================================ FILE: index.js ================================================ const document = require('global/document') const nanotiming = require('nanotiming') const morph = require('nanomorph') const onload = require('on-load') const assert = require('assert') const OL_KEY_ID = onload.KEY_ID const OL_ATTR_ID = onload.KEY_ATTR module.exports = Nanocomponent function makeID () { return 'ncid-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) } Nanocomponent.makeID = makeID function Nanocomponent (name) { this._hasWindow = typeof window !== 'undefined' this._id = null // represents the id of the root node this._ncID = null // internal nanocomponent id this._olID = null this._proxy = null this._loaded = false // Used to debounce on-load when child-reordering this._rootNodeName = null this._name = name || 'nanocomponent' this._rerender = false this._handleLoad = this._handleLoad.bind(this) this._handleUnload = this._handleUnload.bind(this) this._arguments = [] const self = this Object.defineProperty(this, 'element', { get: function () { const el = document.getElementById(self._id) if (el) return el.dataset.nanocomponent === self._ncID ? el : undefined } }) } Nanocomponent.prototype.render = function () { const renderTiming = nanotiming(this._name + '.render') const self = this const args = new Array(arguments.length) let el for (let i = 0; i < arguments.length; i++) args[i] = arguments[i] if (!this._hasWindow) { const createTiming = nanotiming(this._name + '.create') el = this.createElement.apply(this, args) createTiming() renderTiming() return el } else if (this.element) { el = this.element // retain reference, as the ID might change on render const updateTiming = nanotiming(this._name + '.update') const shouldUpdate = this._rerender || this.update.apply(this, args) updateTiming() if (this._rerender) this._rerender = false if (shouldUpdate) { const desiredHtml = this._handleRender(args) const morphTiming = nanotiming(this._name + '.morph') morph(el, desiredHtml) morphTiming() if (this.afterupdate) this.afterupdate(el) } if (!this._proxy) { this._proxy = this._createProxy() } renderTiming() return this._proxy } else { this._reset() el = this._handleRender(args) if (this.beforerender) this.beforerender(el) if (this.load || this.unload || this.afterreorder) { onload(el, self._handleLoad, self._handleUnload, self._ncID) this._olID = el.dataset[OL_KEY_ID] } renderTiming() return el } } Nanocomponent.prototype.rerender = function () { assert(this.element, 'nanocomponent: cant rerender on an unmounted dom node') this._rerender = true this.render.apply(this, this._arguments) } Nanocomponent.prototype._handleRender = function (args) { const createElementTiming = nanotiming(this._name + '.createElement') const el = this.createElement.apply(this, args) createElementTiming() if (!this._rootNodeName) this._rootNodeName = el.nodeName assert(el instanceof window.Element, 'nanocomponent: createElement should return a single DOM node') assert(this._rootNodeName === el.nodeName, 'nanocomponent: root node types cannot differ between re-renders') this._arguments = args return this._brandNode(this._ensureID(el)) } Nanocomponent.prototype._createProxy = function () { const proxy = document.createElement(this._rootNodeName) const self = this this._brandNode(proxy) proxy.id = this._id proxy.setAttribute('data-proxy', '') proxy.isSameNode = function (el) { return (el && el.dataset.nanocomponent === self._ncID) } return proxy } Nanocomponent.prototype._reset = function () { this._ncID = Nanocomponent.makeID() this._olID = null this._id = null this._proxy = null this._rootNodeName = null } Nanocomponent.prototype._brandNode = function (node) { node.setAttribute('data-nanocomponent', this._ncID) if (this._olID) node.setAttribute(OL_ATTR_ID, this._olID) return node } Nanocomponent.prototype._ensureID = function (node) { if (node.id) this._id = node.id else node.id = this._id = this._ncID // Update proxy node ID if it changed if (this._proxy && this._proxy.id !== this._id) this._proxy.id = this._id return node } Nanocomponent.prototype._handleLoad = function (el) { if (this._loaded) { if (this.afterreorder) this.afterreorder(el) return // Debounce child-reorders } this._loaded = true if (this.load) this.load(el) } Nanocomponent.prototype._handleUnload = function (el) { if (this.element) return // Debounce child-reorders this._loaded = false if (this.unload) this.unload(el) } Nanocomponent.prototype.createElement = function () { throw new Error('nanocomponent: createElement should be implemented!') } Nanocomponent.prototype.update = function () { throw new Error('nanocomponent: update should be implemented!') } ================================================ FILE: package.json ================================================ { "name": "nanocomponent", "version": "6.6.0", "description": "Native DOM components that pair nicely with DOM diffing algorithms", "main": "index.js", "browser": { "assert": "nanoassert" }, "scripts": { "test": "run-s test:*", "test:deps": "dependency-check . --no-dev -i nanoassert", "test:node": "NODE_ENV=test node test/node.js | tap-format-spec", "test:browser": "browserify test/browser/index.js | tape-run --render='tap-format-spec'", "test:lint": "standard *.js", "start": "bankai start example", "build": "rm -rf example/dist && rm -rf dist && bankai build example && mv example/dist ." }, "repository": { "type": "git", "url": "git+https://github.com/choojs/nanocomponent.git" }, "keywords": [ "nanohtml", "bel", "choo", "element", "thunk", "cache", "perf", "nanomorph", "morphdom", "nanocomponent", "cache-component" ], "author": "Trainspotters", "contributors": [ "Bret Comnes (http://bret.io)" ], "license": "MIT", "bugs": { "url": "https://github.com/choojs/nanocomponent/issues" }, "homepage": "https://github.com/choojs/nanocomponent#readme", "dependencies": { "global": "^4.3.1", "nanoassert": "^2.0.0", "nanomorph": "^5.1.2", "nanotiming": "^7.2.0", "on-load": "^4.0.2" }, "devDependencies": { "@tap-format/spec": "^0.2.0", "bankai": "^9.5.1", "browserify": "^16.0.0", "choo": "^7.1.0", "choo-log": "^8.0.0", "dependency-check": "^4.1.0", "envify": "^4.0.0", "leaflet": "^1.1.0", "microbounce": "^1.0.0", "nanobus": "^4.2.0", "nanohtml": "^1.2.3", "nanologger": "^2.0.0", "npm-run-all": "^4.0.2", "on-idle": "^3.1.0", "standard": "^14.3.4", "tape": "^5.0.0", "tape-run": "^7.0.0" } } ================================================ FILE: test/browser/blog-section.js ================================================ var Nanocomponent = require('../../') var html = require('nanohtml') class BlogSection extends Nanocomponent { constructor (name = 'BlogSection') { super(name) this.entries = null } createElement (entries) { this.entries = entries return html`
${entries && entries.length > 0 ? entries.map(e => html`

${e}

`) : 'No entries'}
` } update (entries) { if (entries !== this.entries || this.entries.some((e, i) => e !== entries[i])) return true return false } } module.exports = BlogSection ================================================ FILE: test/browser/index.js ================================================ var test = require('tape') var SimpleComponent = require('./simple') var BlogSection = require('./blog-section') var Nanocomponent = require('../../') var html = require('nanohtml') var compare = require('../../compare') var nanobus = require('nanobus') function makeID () { return 'testid-' + Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) } function createTestElement () { var testRoot = document.createElement('div') testRoot.id = makeID() document.body.appendChild(testRoot) return testRoot } test('can create a simple component', function (t) { var testRoot = createTestElement() // Create instance and mount var comp = new SimpleComponent('yosh') testRoot.appendChild(comp.render('green')) t.ok(comp.element, 'component created and mounted in page') t.equal(comp.element.querySelector('.name').innerText, 'yosh', 'instance options correctly rendered') t.equal(comp.element.querySelector('.color').innerText, 'green', 'arguments correctly rendered') t.equal(comp.element.dataset.proxy, undefined, 'not a proxy element') // Update mounted component and inspect proxy var proxy = comp.render('red') t.ok(proxy.dataset.proxy != null, 'proxy is returned on mounted component') t.equal(proxy.dataset.nanocomponent, comp._ncID, 'proxy is tagged with the correct ncID') t.equal(proxy.nodeName, comp.element.nodeName, 'proxy is of same type') t.ok(proxy.isSameNode(comp.element), 'isSameNode works') t.ok(comp.element, 'component is still mounted in page') t.equal(comp.element.querySelector('.color').innerText, 'red', 'arguments correctly rendered') t.equal(comp.element.dataset.proxy, undefined, 'mounted node isn\'t a proxy') comp.render('red') t.ok(comp.element, 'component is still mounted in page') t.equal(comp.element.querySelector('.color').innerText, 'red', 'arguments correctly rendered') t.equal(comp.element.dataset.proxy, undefined, 'mounted node isn\'t a proxy') comp.name = 'lrlna' // Update internal state comp.rerender() t.ok(comp.element, 'component is still mounted in page') t.equal(comp.element.querySelector('.name').innerText, 'lrlna', 'instance options correctly rerendered') t.equal(comp.element.querySelector('.color').innerText, 'red', 'internal state reflected in rerender') t.equal(comp.element.dataset.proxy, undefined, 'mounted node isn\'t a proxy') t.end() }) test('proxy node types match the root node returned from createElement', function (t) { var testRoot = createTestElement() var comp = new BlogSection() testRoot.appendChild(comp.render(['hey', 'hi', 'howdy'])) t.ok(comp.element, 'component created and mounted in page') t.equal(comp.element.nodeName, 'SECTION', 'correctly rendered') t.equal(comp.element.dataset.proxy, undefined, 'not a proxy element') var proxy = comp.render(['by', 'bye', 'cya']) t.equal(proxy.nodeName, comp.element.nodeName, 'proxy is of same type as the root node of createElement') t.end() }) test('missing createElement', function (t) { function Missing () { if (!(this instanceof Missing)) return new Missing() Nanocomponent.call(this) } Missing.prototype = Object.create(Nanocomponent.prototype) var badMissing = new Missing() t.throws(badMissing.render.bind(badMissing), new RegExp(/createElement should be implemented/), 'call to render throws if createElement is missing') t.end() }) test('missing update', function (t) { function Missing () { if (!(this instanceof Missing)) return new Missing() Nanocomponent.call(this) } Missing.prototype = Object.create(Nanocomponent.prototype) Missing.prototype.createElement = function () { return html`
hey
` } var badMissing = new Missing() var testRoot = createTestElement() testRoot.appendChild(badMissing.render()) t.throws(badMissing.render.bind(badMissing), new RegExp(/update should be implemented/), 'call to update throws if update is missing') t.end() }) test('lifecycle tests', function (t) { var testRoot = createTestElement() class LifeCycleComp extends Nanocomponent { constructor () { super() this.bus = nanobus() this.testState = { 'create-element': 0, update: 0, beforerender: 0, afterupdate: 0, load: 0, unload: 0 } } createElement (text) { this.arguments = arguments this.testState['create-element']++ return html`
${text}
` } update (text) { var shouldUpdate = compare(this.arguments, arguments) this.testState.update++ return shouldUpdate } beforerender () { this.testState.beforerender++ } afterupdate () { this.testState.afterupdate++ } load () { this.testState.load++ this.bus.emit('load') } unload () { this.testState.unload++ this.bus.emit('unload') } } var comp = new LifeCycleComp() comp.bus.on('load', () => window.requestAnimationFrame(onLoad)) comp.bus.on('unload', () => window.requestAnimationFrame(onUnload)) t.deepEqual(comp.testState, { 'create-element': 0, update: 0, beforerender: 0, afterupdate: 0, load: 0, unload: 0 }, 'no lifecycle methods run on instantiation') var el = comp.render('hey') t.deepEqual(comp.testState, { 'create-element': 1, update: 0, beforerender: 1, afterupdate: 0, load: 0, unload: 0 }, 'create-element and beforerender is run on first render') testRoot.appendChild(el) function onLoad () { t.deepEqual(comp.testState, { 'create-element': 1, update: 0, beforerender: 1, afterupdate: 0, load: 1, unload: 0 }, 'component loaded') comp.render('hi') t.deepEqual(comp.testState, { 'create-element': 2, update: 1, beforerender: 1, afterupdate: 1, load: 1, unload: 0 }, 'component re-rendered') comp.render('hi') t.deepEqual(comp.testState, { 'create-element': 2, update: 2, beforerender: 1, afterupdate: 1, load: 1, unload: 0 }, 'component cache hit') testRoot.removeChild(comp.element) } function onUnload () { t.equal(comp.element, undefined, 'component unmounted') t.end() } }) ================================================ FILE: test/browser/simple.js ================================================ var Nanocomponent = require('../../') var html = require('nanohtml') module.exports = SimpleComponent function SimpleComponent (name) { if (!(this instanceof SimpleComponent)) return new SimpleComponent(name) this.name = name this.color = null Nanocomponent.call(this) } SimpleComponent.prototype = Object.create(Nanocomponent.prototype) SimpleComponent.prototype.createElement = function (color) { this.color = color || 'blue' return html`

${this.name}

${this.color}

` } SimpleComponent.prototype.update = function (color) { return this.color !== color } ================================================ FILE: test/node.js ================================================ var Nanocomponent = require('../') var test = require('tape') var html = require('nanohtml') test('should validate input types', (t) => { t.plan(1) var comp = new Nanocomponent() t.throws(comp.render.bind(comp), /createElement should be implemented/) }) test('should render elements', (t) => { t.plan(2) function MyComp () { if (!(this instanceof MyComp)) return new MyComp() Nanocomponent.call(this) } MyComp.prototype = Object.create(Nanocomponent.prototype) MyComp.prototype.createElement = function (name) { return html`
${name}
` } MyComp.prototype.update = function (name) { return false } var myComp = new MyComp() var el1 = myComp.render('mittens') t.equal(String(el1), '
mittens
', 'init render success') var el3 = myComp.render('scruffles') t.equal(String(el3), '
scruffles
', 're-render success') })