Skip to content

Instantly share code, notes, and snippets.

@ul
Created June 11, 2015 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ul/e2a4152959eeb3fcba04 to your computer and use it in GitHub Desktop.
Save ul/e2a4152959eeb3fcba04 to your computer and use it in GitHub Desktop.
Responsive wrapper for Facebook's Fixed-Data-Table grids, adapted for Om
var now = function() {};
var isObject = function (value) {};
var isFunction = function (value) {};
var debounce = function (func, wait, options) {};
var now = Date.now;
/**
* Checks if `value` is the language type of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return type == 'function' || (value && type == 'object') || false;
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// Avoid a Chakra JIT bug in compatibility modes of IE 11.
// See https://github.com/jashkenas/underscore/issues/1621 for more details.
return typeof value == 'function' || false;
}
// Fallback for environments that return incorrect `typeof` operator results.
if (isFunction(/x/) || (Uint8Array && !isFunction(Uint8Array))) {
isFunction = function(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return objToString.call(value) == funcTag;
};
}
/**
* Creates a function that delays invoking `func` until after `wait` milliseconds
* have elapsed since the last time it was invoked. The created function comes
* with a `cancel` method to cancel delayed invocations. Provide an options
* object to indicate that `func` should be invoked on the leading and/or
* trailing edge of the `wait` timeout. Subsequent calls to the debounced
* function return the result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it is invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (!isFunction(func)) {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : wait;
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
var isCalled = trailingCall;
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
if (timeoutId) {
clearTimeout(timeoutId);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (trailing || (maxWait !== wait)) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
}
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = null;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
(defproject foo "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [...
[cljsjs/fixed-data-table "0.2.0-0" :exclusions [cljsjs/react]]
[cljsjs/react-with-addons "0.12.2-8"]
[org.omcljs/om "0.8.8" :exclusions [cljsjs/react]]]
:plugins [[lein-cljsbuild "1.0.6"]]
:cljsbuild {:builds {:app {:compiler {...
;; FIXME submit to cljsjs
:foreign-libs [{:file "resources/lib/responsive-fixed-data-table.js"
:requires ["cljsjs.fixed-data-table" "lowdash.debounce"]
:provides ["cljsjs.responsive-fixed-data-table"]}
{:file "resources/lib/debounce.js"
:provides ["lowdash.debounce"]}]
:externs ["resources/ext/responsive-fixed-data-table.ext.js"
"resources/ext/debounce.ext.js"]}}}})
var ResponsiveFixedDataTable = {Table: {}};
/*
The MIT License (MIT)
Copyright (c) 2015 Viky Guerra
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.
*/
// NOTE when submit to cljsjs make sure that package depends on react-with-addons
'use-strict';
var PureRenderMixin = React.addons.PureRenderMixin;
var Table = FixedDataTable.Table;
var ResponsiveFixedDataTable = React.createClass({
mixins: [ PureRenderMixin ],
propTypes: {
refreshRate: React.PropTypes.number
},
getDefaultProps: function() {
return {
refreshRate: 250, // ms
wrapperStyle: { width: '100%', height: '100%' }
};
},
getInitialState: function() {
return {
gridWidth: 100,
gridHeight: 100
};
},
componentDidMount: function() {
this._setDimensionsOnState();
},
componentWillMount: function() {
this._setDimensionsOnState = debounce(this._setDimensionsOnState, this.props.refreshRate, true);
this._attachResizeEvent();
},
componentWillUnmount: function() {
window.removeEventListener('resize');
},
_attachResizeEvent: function() {
var win = window;
if (win.addEventListener) {
win.addEventListener('resize', this._setDimensionsOnState, false);
} else if (win.attachEvent) {
win.attachEvent('resize', this._setDimensionsOnState);
} else {
win.onresize = this._setDimensionsOnState;
}
},
_setDimensionsOnState: function() {
if (this.isMounted()) {
var tableWrapperNode = this.getDOMNode();
this.setState({
gridWidth: tableWrapperNode.offsetWidth,
gridHeight: tableWrapperNode.offsetHeight
});
}
},
/**
* @return {ReactDOMNode}
*/
render: function() {
return (
React.createElement(
"div",
{style: this.props.wrapperStyle},
React.createElement(
Table,
React.__spread(
{},
this.props,
{ref: "table",
width: this.state.gridWidth,
height: this.state.gridHeight}))));
}
});
(ns foo.views
(:require [cljsjs.responsive-fixed-data-table] ...))
;;; drop-in responsive replacement for js/FixedDataTable.Table
(def Table (js/React.createFactory js/ResponsiveFixedDataTable))
(def Column (js/React.createFactory js/FixedDataTable.Column))
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment