Repository: wilsonpage/fastdom Branch: master Commit: 01524d7b9078 Files: 23 Total size: 76.2 KB Directory structure: gitextract_gaqz58xe/ ├── .gitignore ├── .jshintignore ├── .jshintrc ├── .npmignore ├── .travis.yml ├── README.md ├── bower.json ├── examples/ │ ├── animation.html │ └── aspect-ratio.html ├── extensions/ │ ├── fastdom-promised.d.ts │ ├── fastdom-promised.js │ └── fastdom-sandbox.js ├── fastdom-strict.js ├── fastdom.d.ts ├── fastdom.js ├── package.json ├── src/ │ └── fastdom-strict.js ├── test/ │ ├── fastdom-promised-test.js │ ├── fastdom-sandbox-test.js │ ├── fastdom-strict-test.js │ ├── fastdom-test.js │ └── karma.conf.js └── webpack.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules .DS_Store npm-debug.log test/coverage ================================================ FILE: .jshintignore ================================================ node_modules fastdom.js strict.js ================================================ FILE: .jshintrc ================================================ { "camelcase": false, "forin": false, "latedef": "nofunc", "newcap": false, "noarg": true, "node": true, "nonew": true, "quotmark": "single", "undef": true, "unused": "vars", "trailing": true, "maxlen": 80, "laxbreak": true, "sub": true, "eqnull": true, "expr": true, "maxerr": 1000, "regexdash": true, "laxcomma": true, "proto": true, "boss": true, "esnext": true, "browser": true, "devel": true, "nonstandard": true, "worker": true, "-W078": true, "predef": [ "define" ] } ================================================ FILE: .npmignore ================================================ **/*. bower.json webpack.config.js node_modules examples test ================================================ FILE: .travis.yml ================================================ sudo: required dist: trusty language: node_js node_js: - 5.1.0 addons: firefox: latest apt: sources: - google-chrome packages: - google-chrome-stable before_script: - export CHROME_BIN=$(which google-chrome-stable) - export DISPLAY=:99.0 - sh -e /etc/init.d/xvfb start after_script: - npm run coveralls ================================================ FILE: README.md ================================================ # fastdom [![Twitter Follow](https://img.shields.io/twitter/follow/wilsonpage?style=social)](https://twitter.com/wilsonpage) [![Build Status](https://travis-ci.org/wilsonpage/fastdom.svg?branch=master)](https://travis-ci.org/wilsonpage/fastdom) [![NPM version](https://badge.fury.io/js/fastdom.svg)](http://badge.fury.io/js/fastdom) [![npm](https://img.shields.io/npm/dm/fastdom.svg?maxAge=2592000)]() [![Coverage Status](https://coveralls.io/repos/wilsonpage/fastdom/badge.svg?branch=master&service=github)](https://coveralls.io/github/wilsonpage/fastdom?branch=master) ![gzip size](http://img.badgesize.io/https://unpkg.com/fastdom/fastdom.min.js?compression=gzip) Eliminates layout thrashing by batching DOM read/write operations (~600 bytes minified gzipped). ```js fastdom.measure(() => { console.log('measure'); }); fastdom.mutate(() => { console.log('mutate'); }); fastdom.measure(() => { console.log('measure'); }); fastdom.mutate(() => { console.log('mutate'); }); ``` Outputs: ``` measure measure mutate mutate ``` ## Examples - [Animation example](http://wilsonpage.github.io/fastdom/examples/animation.html) - [Aspect ratio example](http://wilsonpage.github.io/fastdom/examples/aspect-ratio.html) ## Installation FastDom is CommonJS and AMD compatible, you can install it in one of the following ways: ```sh $ npm install fastdom --save ``` or [download](http://github.com/wilsonpage/fastdom/raw/master/fastdom.js). ## How it works FastDom works as a regulatory layer between your app/library and the DOM. By batching DOM access we **avoid unnecessary document reflows** and dramatically **speed up layout performance**. Each measure/mutate job is added to a corresponding measure/mutate queue. The queues are emptied (reads, then writes) at the turn of the next frame using [`window.requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame). FastDom aims to behave like a singleton across *all* modules in your app. When any module requires `'fastdom'` they get the same instance back, meaning FastDom can harmonize DOM access app-wide. Potentially a third-party library could depend on FastDom, and better integrate within an app that itself uses it. ## API ### FastDom#measure(callback[, context]) Schedules a job for the 'measure' queue. Returns a unique ID that can be used to clear the scheduled job. ```js fastdom.measure(() => { const width = element.clientWidth; }); ``` ### FastDom#mutate(callback[, context]) Schedules a job for the 'mutate' queue. Returns a unique ID that can be used to clear the scheduled job. ```js fastdom.mutate(() => { element.style.width = width + 'px'; }); ``` ### FastDom#clear(id) Clears **any** scheduled job. ```js const read = fastdom.measure(() => {}); const write = fastdom.mutate(() => {}); fastdom.clear(read); fastdom.clear(write); ``` ## Strict mode It's very important that all DOM mutations or measurements go through `fastdom` to ensure good performance; to help you with this we wrote `fastdom-strict`. When `fastdom-strict.js` is loaded, it will throw errors when sensitive DOM APIs are called at the wrong time. This is useful when working with a large team who might not all be aware of `fastdom` or its benefits. It can also prove useful for catching 'un-fastdom-ed' code when migrating an app to `fastdom`. ```html ``` ```js element.clientWidth; // throws fastdom.mutate(function() { element.clientWidth; }); // throws fastdom.measure(function() { element.clientWidth; }); // does not throw ``` ```js "Error: Can only get .clientWidth during 'measure' phase" ``` - `fastdom-strict` will not throw if nodes are not attached to the document. - You should use `fastdom-strict` in development to catch rendering performance issues before they hit production. - It is not advisable to use `fastdom-strict` in production. ## Exceptions FastDom is async, this can therefore mean that when a job comes around to being executed, the node you were working with may no longer be there. These errors are usually not critical, but they can cripple your app. FastDom allows you to register a `catch` handler. If `fastdom.catch` has been registered, FastDom will catch any errors that occur in your jobs, and run the handler instead. ```js fastdom.catch = (error) => { // Do something if you want }; ``` ## Extensions The core `fastdom` library is designed to be as light as possible. Additional functionality can be bolted on in the form of 'extensions'. It's worth noting that `fastdom` is a 'singleton' by design, so all tasks (even those scheduled by extensions) will reach the same global task queue. **Fastdom ships with some extensions:** - [`fastdom-promised`](extensions/fastdom-promised.js) - Adds Promise based API - [`fastdom-sandbox`](extensions/fastdom-sandbox.js) - Adds task grouping concepts ### Using an extension Use the `.extend()` method to extend the current `fastdom` to create a new object. ```html ``` ```js // extend fastdom const myFastdom = fastdom.extend(fastdomPromised); // use new api myFastdom.mutate(...).then(...); ``` Extensions can be chained to construct a fully customised `fastdom`. ```js const myFastdom = fastdom .extend(fastdomPromised) .extend(fastdomSandbox); ``` ### Writing an extension ```js const myFastdom = fastdom.extend({ measure(fn, ctx) { // do custom stuff ... // then call the parent method return this.fastdom.measure(fn, ctx); }, mutate: ... }); ``` You'll notice `this.fastdom` references the parent `fastdom`. If you're extending a core API and aren't calling the parent method, you're doing something wrong. When distributing an extension only export a plain object to allow users to compose their own `fastdom`. ```js module.exports = { measure: ..., mutate: ..., clear: ... }; ``` ## Tests ```sh $ npm install $ npm test ``` ## Author - **Wilson Page** - [@wilsonpage](http://twitter.com/wilsonpage) ## Contributors - **Wilson Page** - [@wilsonpage](http://twitter.com/wilsonpage) - **Paul Irish** - [@paulirish](http://github.com/paulirish) - **Kornel Lesinski** - [@pornel](http://github.com/pornel) - **George Crawford** - [@georgecrawford](http://github.com/georgecrawford) ## License (The MIT License) Copyright (c) 2016 Wilson Page 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: bower.json ================================================ { "name": "fastdom", "description": "Eliminates layout thrashing by batching DOM read/write operations", "main": "fastdom.js", "scripts": [ "fastdom.js" ], "ignore": [ "**/*.", "webpack.config.js", "examples/", "test/", "README.md" ], "license": "MIT", "_source": "git@github.com/wilsonpage/fastdom.git" } ================================================ FILE: examples/animation.html ================================================ FastDom: Animation Example
An adaptation of the demo from the Google Developers article Diagnosing forced synchronous layouts. In the article, forced synchronous layouts are fixed by simply not doing any reads at all. Rather than this extreme solution, which will not be appropriate for many use cases, we instead use fastdom to intelligently defer and batch the DOM reads and writes, and get similar performance gains as a result.
================================================ FILE: examples/aspect-ratio.html ================================================ FastDom: Aspect Ratio Example
================================================ FILE: extensions/fastdom-promised.d.ts ================================================ declare namespace FastdomPromised { export function clear>(task: T): void; export function initialize(): void; export function measure void>(task: T, context?: any): Promise>; export function mutate void>(task: T, context?: any): Promise>; } export = FastdomPromised; ================================================ FILE: extensions/fastdom-promised.js ================================================ !(function() { /** * Wraps fastdom in a Promise API * for improved control-flow. * * @example * * // returning a result * fastdom.measure(() => el.clientWidth) * .then(result => ...); * * // returning promises from tasks * fastdom.measure(() => { * var w = el1.clientWidth; * return fastdom.mutate(() => el2.style.width = w + 'px'); * }).then(() => console.log('all done')); * * // clearing pending tasks * var promise = fastdom.measure(...) * fastdom.clear(promise); * * @type {Object} */ var exports = { initialize: function() { this._tasks = new Map(); }, mutate: function(fn, ctx) { return create(this, 'mutate', fn, ctx); }, measure: function(fn, ctx) { return create(this, 'measure', fn, ctx); }, clear: function(promise) { var tasks = this._tasks; var task = tasks.get(promise); this.fastdom.clear(task); tasks.delete(promise); } }; /** * Create a fastdom task wrapped in * a 'cancellable' Promise. * * @param {FastDom} fastdom * @param {String} type - 'measure'|'mutate' * @param {Function} fn * @return {Promise} */ function create(promised, type, fn, ctx) { var tasks = promised._tasks; var fastdom = promised.fastdom; var task; var promise = new Promise(function(resolve, reject) { task = fastdom[type](function() { tasks.delete(promise); try { resolve(ctx ? fn.call(ctx) : fn()); } catch (e) { reject(e); } }, ctx); }); tasks.set(promise, task); return promise; } // Expose to CJS, AMD or global if ((typeof define)[0] == 'f') define(function() { return exports; }); else if ((typeof module)[0] == 'o') module.exports = exports; else window.fastdomPromised = exports; })(); ================================================ FILE: extensions/fastdom-sandbox.js ================================================ (function(exports) { /** * Mini logger * * @return {Function} */ var debug = 0 ? console.log.bind(console, '[fastdom-sandbox]') : function() {}; /** * Exports */ /** * Create a new `Sandbox`. * * Scheduling tasks via a sandbox is * useful because you can clear all * sandboxed tasks in one go. * * This is handy when working with view * components. You can create one sandbox * per component and call `.clear()` when * tearing down. * * @example * * var sandbox = fastdom.sandbox(); * * sandbox.measure(function() { console.log(1); }); * sandbox.measure(function() { console.log(2); }); * * fastdom.measure(function() { console.log(3); }); * fastdom.measure(function() { console.log(4); }); * * sandbox.clear(); * * // => 3 * // => 4 * * @return {Sandbox} * @public */ exports.sandbox = function() { return new Sandbox(this.fastdom); }; /** * Initialize a new `Sandbox` * * @param {FastDom} fastdom */ function Sandbox(fastdom) { this.fastdom = fastdom; this.tasks = []; debug('initialized'); } /** * Schedule a 'measure' task. * * @param {Function} fn * @param {Object} ctx * @return {Object} can be passed to .clear() */ Sandbox.prototype.measure = function(fn, ctx) { var tasks = this.tasks; var task = this.fastdom.measure(function() { tasks.splice(tasks.indexOf(task)); return fn.call(ctx); }); tasks.push(task); return task; }; /** * Schedule a 'mutate' task. * * @param {Function} fn * @param {Object} ctx * @return {Object} can be passed to .clear() */ Sandbox.prototype.mutate = function(fn, ctx) { var tasks = this.tasks; var task = this.fastdom.mutate(function() { tasks.splice(tasks.indexOf(task)); return fn.call(ctx); }); this.tasks.push(task); return task; }; /** * Clear a single task or is no task is * passsed, all tasks in the `Sandbox`. * * @param {Object} task (optional) */ Sandbox.prototype.clear = function(task) { if (!arguments.length) clearAll(this.fastdom, this.tasks); remove(this.tasks, task); return this.fastdom.clear(task); }; /** * Clears all the given tasks from * the given `FastDom`. * * @param {FastDom} fastdom * @param {Array} tasks * @private */ function clearAll(fastdom, tasks) { debug('clear all', fastdom, tasks); var i = tasks.length; while (i--) { fastdom.clear(tasks[i]); tasks.splice(i, 1); } } /** * Remove an item from an Array. * * @param {Array} array * @param {*} item * @return {Boolean} */ function remove(array, item) { var index = array.indexOf(item); return !!~index && !!array.splice(index, 1); } /** * Expose */ if ((typeof define)[0] == 'f') define(function() { return exports; }); else if ((typeof module)[0] == 'o') module.exports = exports; else window.fastdomSandbox = exports; })({}); ================================================ FILE: fastdom-strict.js ================================================ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("fastdom")); else if(typeof define === 'function' && define.amd) define(["fastdom"], factory); else if(typeof exports === 'object') exports["fastdom"] = factory(require("fastdom")); else root["fastdom"] = factory(root["fastdom"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; var strictdom = __webpack_require__(1); var fastdom = __webpack_require__(2); /** * Mini logger * * @return {Function} */ var debug = 0 ? console.log.bind(console, '[fastdom-strict]') : function() {}; /** * Enabled state * * @type {Boolean} */ var enabled = false; window.fastdom = module.exports = fastdom.extend({ measure: function(fn, ctx) { debug('measure'); var task = !ctx ? fn : fn.bind(ctx); return this.fastdom.measure(function() { if (!enabled) return task(); return strictdom.phase('measure', task); }, ctx); }, mutate: function(fn, ctx) { debug('mutate'); var task = !ctx ? fn : fn.bind(ctx); return this.fastdom.mutate(function() { if (!enabled) return task(); return strictdom.phase('mutate', task); }, ctx); }, strict: function(value) { if (value) { enabled = true; strictdom.enable(); } else { enabled = false; strictdom.disable(); } } }); // turn on strict-mode window.fastdom.strict(true); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;!(function() { 'use strict'; var debug = 0 ? console.log.bind(console, '[strictdom]') : function() {}; /** * Crude webkit test. * * @type {Boolean} */ // var isWebkit = !!window.webkitURL; /** * List of properties observed. * * @type {Object} */ var properties = { prototype: { Document: { execCommand: Mutate, elementFromPoint: Measure, elementsFromPoint: Measure, scrollingElement: Measure }, Node: { appendChild: { type: Mutate, test: function(dom, parent, args) { var attached = isAttached(parent) || isAttached(args[0]); if (attached && dom.not('mutate')) throw error(3, this.name); } }, insertBefore: { type: Mutate, test: function(dom, parent, args) { var attached = isAttached(parent) || isAttached(args[0]); if (attached && dom.not('mutate')) throw error(3, this.name); } }, removeChild: { type: Mutate, test: function(dom, parent, args) { var attached = isAttached(parent) || isAttached(args[0]); if (attached && dom.not('mutate')) throw error(3, this.name); } }, textContent: Mutate }, Element: { scrollIntoView: Mutate, scrollBy: Mutate, scrollTo: Mutate, getClientRects: Measure, getBoundingClientRect: Measure, clientLeft: Measure, clientWidth: Measure, clientHeight: Measure, scrollLeft: Accessor, scrollTop: Accessor, scrollWidth: Measure, scrollHeight: Measure, innerHTML: Mutate, outerHTML: Mutate, insertAdjacentHTML: Mutate, remove: Mutate, setAttribute: Mutate, removeAttribute: Mutate, className: Mutate, classList: ClassList }, HTMLElement: { offsetLeft: Measure, offsetTop: Measure, offsetWidth: Measure, offsetHeight: Measure, offsetParent: Measure, innerText: Accessor, outerText: Accessor, focus: Measure, blur: Measure, style: Style, // `element.dataset` is hard to wrap. // We could use `Proxy` but it's not // supported in Chrome yet. Not too // concerned as `data-` attributes are // not often associated with render. // dataset: DATASET }, CharacterData: { remove: Mutate, data: Mutate }, Range: { getClientRects: Measure, getBoundingClientRect: Measure }, MouseEvent: { layerX: Measure, layerY: Measure, offsetX: Measure, offsetY: Measure }, HTMLButtonElement: { reportValidity: Measure }, HTMLDialogElement: { showModal: Mutate }, HTMLFieldSetElement: { reportValidity: Measure }, HTMLImageElement: { width: Accessor, height: Accessor, x: Measure, y: Measure }, HTMLInputElement: { reportValidity: Measure }, HTMLKeygenElement: { reportValidity: Measure }, SVGSVGElement: { currentScale: Accessor } }, instance: { window: { getComputedStyle: { type: Measure, /** * Throws when the Element is in attached * and strictdom is not in the 'measure' phase. * * @param {StrictDom} strictdom * @param {Window} win * @param {Object} args */ test: function(strictdom, win, args) { if (isAttached(args[0]) && strictdom.not('measure')) { throw error(2, 'getComputedStyle'); } } }, // innerWidth: { // type: isWebkit ? Value : Measure, // // /** // * Throws when the window is nested (in