Refactor structure to be more testable

This commit is contained in:
Keegan
2016-01-27 00:03:07 -08:00
parent b960dc19f4
commit 13b84f7e6c
19 changed files with 391 additions and 3095 deletions
+4 -4
View File
@@ -22,7 +22,7 @@ module.exports = [
},
{
"type": "input",
"app_key": "email",
"appKey": "email",
"value": "",
"label": "Email",
"attributes": {
@@ -34,13 +34,13 @@ module.exports = [
},
{
"type": "toggle",
"app_key": "like_stuff",
"appKey": "cool_stuff",
"label": "Enable Cool Stuff",
"value": false
},
{
"type": "color",
"app_key": "background",
"appKey": "background",
"value": "0xFF0000",
"label": "Background Color"
}
@@ -56,7 +56,7 @@ module.exports = [
{
"id": "flavor",
"type": "select",
"app_key": "flavor",
"appKey": "flavor",
"value": "grape",
"label": "Favorite Flavor",
"options": [
+9 -9
View File
@@ -1,15 +1,15 @@
'use strict';
module.exports = function() {
var Api = window.Clay = this;
var Clay = this;
var testHandler = function() {
console.debug('KEEGAN: this', this);
console.debug('KEEGAN: arguments', arguments);
// Api.getItemByAppKey('background').off(testHandler);
};
Clay.getItemByAppKey('cool_stuff').on('change', function() {
if (this.get()) {
Clay.getItemByAppKey('background').enable();
} else {
Clay.getItemByAppKey('background').disable();
}
});
Api.getItemByAppKey('background').on('change', testHandler);
console.debug('custom fn worked');
Clay.getSettings();
};
+8 -144
View File
@@ -1,28 +1,16 @@
'use strict';
/**
* A Clay config Item
* @typedef {object} Clay~Item
* @property {string} type
* @property {string} app_key
* @property {string} id
* @property {string} content
* @property {string|boolean} default
* @property {string} label
* @property {object} attributes
* @property {Array} options
* @property {Array} items
*/
var itemTypes = require('./lib/items');
var $ = require('./vendor/minified/minified').$;
var _ = require('./vendor/minified/minified')._;
var HTML = require('./vendor/minified/minified').HTML;
var Api = require('./lib/api');
var config = _.extend([], window.clayConfig || []);
var settings = _.extend({}, window.claySettings || {});
var returnTo = window.returnTo || 'pebblejs://close#';
var customFn = window.customFn;
var customFn = window.customFn || function() {};
var api = new Api(settings);
var $mainForm = $('#main-form');
function submit(event) {
_.each(api.itemsByAppKey, function(appKey, item) {
@@ -34,132 +22,8 @@ function submit(event) {
return false;
}
/**
*
* @param {string} key
* @param {string|boolean} defaultValue
* @return {string|boolean}
*/
function getSetting(key, defaultValue) {
return typeof settings[key] !== 'undefined' ? settings[key] : (defaultValue || '');
}
api.addItem(config, $mainForm);
// function setSetting(key, value) {
// settings[key] = value;
// }
//$mainForm.on('submit', submit);
/**
* @param {Clay~Item|Array} item
* @param {$} $parent
*/
function processConfigItem(item, $parent) {
// @todo add validation on the Item
if (Array.isArray(item)) {
item.forEach(function(item) {
processConfigItem(item, $parent);
});
} else if (item.type === 'section') {
var $container = HTML('<div class="section">');
$parent.add($container);
processConfigItem(item.items, $container);
} else {
var apiItem = {};
var itemType = itemTypes[item.type];
var templateData = {
label: '',
options: [],
attributes: {},
size: 4
};
_.extend(templateData, item);
apiItem.$element = HTML(_.formatHtml(itemType.template, templateData));
apiItem.$manipulatorTarget =
apiItem.$element.select('[data-manipulator-target]');
// this caters for situations where the manipulator target is the root element
if (!apiItem.$manipulatorTarget.length) {
apiItem.$manipulatorTarget = apiItem.$element;
}
// proxy event related methods
var eventProxies = {};
apiItem.on = function(events, handler) {
eventProxies[handler] = function() {
handler.apply(apiItem, arguments);
};
return apiItem.$manipulatorTarget.on(events, eventProxies[handler]);
};
apiItem.one = function(events, handler) {
eventProxies[handler] = function(event) {
handler.apply(apiItem, arguments);
$.off(eventProxies[handler]);
};
return apiItem.$manipulatorTarget.on(events, eventProxies[handler]);
};
apiItem.off = function(handler) {
return $.off(eventProxies[handler]);
};
apiItem.trigger =
apiItem.$manipulatorTarget.trigger.bind(apiItem.$manipulatorTarget);
// attach the manipulator methods to the apiItem
_.eachObj(itemType.manipulator, function(methodName, method) {
apiItem[methodName] = method.bind(apiItem);
});
apiItem.config = item;
// attach the initialize method to the API.
apiItem.iniialize = typeof itemType.initialize === 'function' ?
itemType.initialize :
function() {};
apiItem.iniialize.bind(apiItem);
apiItem.iniialize();
// set the value of the item via the manipulator to ensure consistency
apiItem.set(getSetting(item.app_key, item.value));
if (item.id) {
api.itemsById[item.id] = apiItem;
}
if (item.app_key) {
api.itemsByAppKey[item.app_key] = apiItem;
}
api.items.push(apiItem);
$parent.add(apiItem.$element);
}
}
var api = {
items: [],
itemsById: {},
itemsByAppKey: {}
};
var $mainForm = $('#main-form');
api.getItemByAppKey = function(key) {
return api.itemsByAppKey[key];
};
api.getItemById = function(key) {
return api.itemsById[key];
};
api.getItemsByType = function(type) {
return api.items.filter(function(item) {
return item.config.type === type;
});
};
processConfigItem(config, $mainForm);
$mainForm.on('submit', submit);
module.exports = api;
customFn.call(api);
+88
View File
@@ -0,0 +1,88 @@
'use strict';
var itemTypes = require('./items');
var $ = require('../vendor/minified/minified').$;
var _ = require('../vendor/minified/minified')._;
var HTML = require('../vendor/minified/minified').HTML;
function ApiItem(config) {
var self = this;
var eventProxies = {};
var itemType = itemTypes[config.type];
var templateData = _.extend({}, itemType.defaults, config);
var $element = HTML(_.formatHtml(itemType.template, templateData));
var $manipulatorTarget = $element.select('[data-manipulator-target]');
// this caters for situations where the manipulator target is the root element
if (!$manipulatorTarget.length) {
$manipulatorTarget = $element;
}
Object.defineProperties(self, {
id: {
value: config.id || null
},
appKey: {
value: config.appKey || null
},
config: {
value: config || null
},
$element: {
value: $element
},
$manipulatorTarget: {
value: $manipulatorTarget
},
on: {
value: function(events, handler) {
eventProxies[handler] = function() {
handler.apply(self, arguments);
};
return $manipulatorTarget.on(events, eventProxies[handler]);
}
},
one: {
value: function(events, handler) {
eventProxies[handler] = function(event) {
handler.apply(self, arguments);
$.off(eventProxies[handler]);
};
return $manipulatorTarget.on(events, eventProxies[handler]);
}
},
off: {
value: function(handler) {
return $.off(eventProxies[handler]);
}
},
trigger: {
value: $manipulatorTarget.trigger.bind($manipulatorTarget)
},
initialize: {
value: typeof itemType.initialize === 'function' ?
itemType.initialize.bind(self) :
function() {}
}
});
// attach the manipulator methods to the apiItem
_.eachObj(itemType.manipulator, function(methodName, method) {
Object.defineProperty(self, methodName, { value: method.bind(self) });
});
self.initialize();
}
module.exports = ApiItem;
+95
View File
@@ -0,0 +1,95 @@
'use strict';
/**
* A Clay config Item
* @typedef {object} Clay~Item
* @property {string} type
* @property {string} appKey
* @property {string} id
* @property {string} content
* @property {string|boolean} default
* @property {string} label
* @property {object} attributes
* @property {Array} options
* @property {Array} items
*/
var HTML = require('../vendor/minified/minified').HTML;
var _ = require('../vendor/minified/minified')._;
var ApiItem = require('./api-item');
function Api(settings) {
var self = this;
var _items = [];
var _itemsById = {};
var _itemsByAppKey = {};
var _settings = _.copyObj(settings);
Object.defineProperties(self, {
getItemByAppKey: {
value: function(key) {
return _itemsByAppKey[key];
}
},
getItemById: {
value: function(key) {
return _itemsById[key];
}
},
getItemsByType: {
value: function(type) {
return _items.filter(function(item) {
return item.config.type === type;
});
}
},
getSettings: {
value: function() {
_.eachObj(_itemsByAppKey, function(appKey, item) {
_settings[appKey] = item.get();
});
return _settings;
}
},
addItem: {
value: function(item, $container) {
if (Array.isArray(item)) {
item.forEach(function(item) {
self.addItem(item, $container);
});
} else if (item.type === 'section') {
var $wrapper = HTML('<div class="section">');
$container.add($wrapper);
self.addItem(item.items, $wrapper);
} else {
var apiItem = new ApiItem(item);
if (item.id) {
_itemsById[item.id] = apiItem;
}
if (item.appKey) {
_itemsByAppKey[item.appKey] = apiItem;
}
_items.push(apiItem);
// set the value of the item via the manipulator to ensure consistency
var value = typeof _settings[item.appKey] !== 'undefined' ?
_settings[item.appKey] :
(item.value || '');
apiItem.set(value);
$container.add(apiItem.$element);
}
}
}
});
}
module.exports = Api;
+15 -1
View File
@@ -5,6 +5,9 @@ var HTML = require('../../vendor/minified/minified').HTML;
module.exports = {
template: require('../../../templates/items/color.tpl'),
manipulator: require('../manipulators').val,
defaults: {
label: ''
},
initialize: function() {
var self = this;
@@ -72,9 +75,12 @@ module.exports = {
var $valueDisplay = $elem.select('.value');
var $picker = $elem.select('.picker-wrap');
var disabled = self.$manipulatorTarget.get('disabled');
$elem.on('click', function(ev) {
$picker.set('show');
if (!disabled) {
$picker.set('show');
}
});
self.on('|change', function() {
@@ -89,5 +95,13 @@ module.exports = {
$picker.set('-show');
});
self.on('disabled', function() {
disabled = true;
});
self.on('enabled', function() {
disabled = false;
});
}
};
+4 -1
View File
@@ -2,5 +2,8 @@
module.exports = {
template: require('../../../templates/items/footer.tpl'),
manipulator: require('../manipulators').html
manipulator: require('../manipulators').html,
defaults: {
attributes: {}
}
};
+5 -1
View File
@@ -2,5 +2,9 @@
module.exports = {
template: require('../../../templates/items/heading.tpl'),
manipulator: require('../manipulators').html
manipulator: require('../manipulators').html,
defaults: {
attributes: {},
size: 4
}
};
+5 -1
View File
@@ -2,5 +2,9 @@
module.exports = {
template: require('../../../templates/items/input.tpl'),
manipulator: require('../manipulators').val
manipulator: require('../manipulators').val,
defaults: {
label: '',
attributes: {}
}
};
+5 -1
View File
@@ -2,5 +2,9 @@
module.exports = {
template: require('../../../templates/items/radiogroup.tpl'),
manipulator: require('../manipulators').radiogroup
manipulator: require('../manipulators').radiogroup,
defaults: {
label: '',
options: []
}
};
+4
View File
@@ -3,6 +3,10 @@
module.exports = {
template: require('../../../templates/items/select.tpl'),
manipulator: require('../manipulators').val,
defaults: {
label: '',
options: []
},
initialize: function() {
var self = this;
+4 -1
View File
@@ -2,5 +2,8 @@
module.exports = {
template: require('../../../templates/items/submit.tpl'),
manipulator: require('../manipulators').val
manipulator: require('../manipulators').val,
defaults: {
attributes: {}
}
};
+4 -1
View File
@@ -2,5 +2,8 @@
module.exports = {
template: require('../../../templates/items/text.tpl'),
manipulator: require('../manipulators').html
manipulator: require('../manipulators').html,
defaults: {
attributes: {}
}
};
+4 -1
View File
@@ -2,5 +2,8 @@
module.exports = {
template: require('../../../templates/items/toggle.tpl'),
manipulator: require('../manipulators').checked
manipulator: require('../manipulators').checked,
defaults: {
attributes: {}
}
};
+4 -2
View File
@@ -19,10 +19,12 @@ module.exports = {
.trigger('change');
},
disable: function() {
return this.$manipulatorTarget.set('disabled', true);
return this.$manipulatorTarget.set('disabled', true)
.trigger('disabled');
},
enable: function() {
return this.$manipulatorTarget.set('disabled', false);
return this.$manipulatorTarget.set('disabled', false)
.trigger('enabled');
}
},
checked: {
+127 -4
View File
@@ -1,8 +1,8 @@
// minified.js config start -- use this comment to re-create a configuration in the Builder
// - Only sections add, always, amdsupport, dollardollar, each,
// - eachobj, error, extend, filter, find, format, formathtml, get, html, isobject,
// - map, mapobj, off, on, ready, request, select, set, template, trigger,
// - underscore, wait.
// - Only sections add, always, amdsupport, copyobj, dollardollar,
// - each, eachobj, error, extend, filter, filterobj, find, format, formathtml,
// - get, ht, html, isobject, keys, map, mapobj, objvalues, off, on, ready,
// - request, select, set, template, trigger, underscore, wait.
// WARNING! This file is autogenerated from minified-master.js and others.
@@ -2741,6 +2741,89 @@ define('minified', function() {
'find': find,
// @condend
/*$
* @id keys
* @group OBJECT
* @requires
* @configurable default
* @name _.keys()
* @syntax _.keys(obj)
* @module UTIL
* Creates a ##list#Minified list## containing all property names of the specified object. Only direct properies are
* included, not inherited ones. The order of the keys in the list is undefined and runtime-specific.
*
* @example Using <var>keys()</var>:
* <pre>var obj = {a: 2, b: 52};
* var keys = _.keys(obj); // keys contains ['a', 'b'] now
* </pre>
*
* @param object The object to gather keys from.
* @return A Minified list containing the property names.
*
* @see ##_.values() returns the values of an object as a list.
*/
'keys': funcArrayBind(keys),
/*$
* @id objvalues
* @group OBJECT
* @requires
* @configurable default
* @name _.values()
* @syntax _.values(obj)
* @module UTIL
* Creates a ##list#Minified list## containing all property values of the specified object. Only direct properies are
* included, not inherited ones. The order of the values in the list is undefined and runtime-specific.
*
* @example Using <var>values()</var>:
* <pre>var obj = {a: 2, b: 52};
* var values = _.values(obj); // keys contains [2, 52] now
* </pre>
*
* @param object The object to gather values from.
* @return A Minified list containing the property names.
*
* @see ##_.keys() retrieves the property names of an object as a list.
*/
'values': funcArrayBind(function(obj, keys) {
var list = [];
if (keys)
each(keys, function(value) { list.push(obj[value]); });
else
eachObj(obj, function(key, value) { list.push(value); });
return list;
}),
/*$
* @id copyobj
* @group OBJECT
* @requires
* @configurable default
* @name _.copyObj()
* @syntax _.copyObj(from)
* @syntax _.copyObj(from, to)
* @module UTIL
* Copies every property of the first object into the second object. The properties are copied as shallow-copies.
*
* @example Copying properties:
* <pre>var target = {a:3, c: 3};
* _.copyObj({a: 1, b: 2}, target); // target is now {a: 1, b: 2, c: 3}</pre>
*
* @example Inline property merge:
* <pre>var target = _.copyObj({a: 1, b: 2}, {a:3, c: 3}); // target is now {a: 1, b: 2, c: 3}</pre>
*
* @example Duplicating an object:
* <pre>var target = _.copyObj({a: 1, b: 2}); // target is now {a: 1, b: 2}</pre>
*
* @param from the object to copy from
* @param to optional the object to copy to. If not given, a new object will be created.
* @return the object that has been copied to
*
* @see ##_.extend() is very similar to <var>copyObj()</var>, but with a slightly different syntax.
* @see ##_.merge() copies a list of objects into a new object.
*/
'copyObj': copyObj,
/*$
* @id extend
* @group OBJECT
@@ -2848,6 +2931,46 @@ define('minified', function() {
return result;
},
/*$
* @id filterobj
* @group OBJECT
* @requires
* @configurable default
* @name _.filterObj()
* @syntax _.filterObj(obj, filterFunc)
* @syntax _.filterObj(obj, filterFunc, ctx)
* @module UTIL
* Creates a new object that contains only those properties of the input object that have been approved by the filter function.
*
* If the callback function returns true, the property and its value are shallow-copied in the new object, otherwise it will be removed.
*
* @example Removing all values over 10 from an object:
* <pre>
* var list = _.filterObj({a: 4, b: 22, c: 7, d: 2, e: 19}, function(key, value) {
* return value &lt;= 10;
* });
* </pre>
*
* @param obj the object to use
* @param callback The callback <code>function(key, value)</code> to invoke for each property.
* <dl><dt>key</dt><dd>The name of the current property.</dd>
* <dt>value</dt><dd>The value of the current property.</dd>
* <dt class="this">this</dt><dd>The given context. If not set, the object itself.</dd>
* <dt class="returnValue">(callback return value)</dt><dd><var>true</var> to include the property in the new object, <var>false</var> to omit it.</dd></dl>
* @param ctx optional a context to pass to the callback as 'this'.
* @return the new object
*
* @see ##_.mapObj() can be used to modify the values og an object.
*/
'filterObj': function(obj, f, ctx) {
var r = {};
eachObj(obj, function(key, value) {
if (f.call(ctx || obj, key, value))
r[key] = value;
});
return r;
},
/*$
* @id isobject
* @group TYPE
File diff suppressed because it is too large Load Diff
+5
View File
@@ -9,6 +9,11 @@
box-shadow: $box-shadow-small-components;
}
input:disabled ~ .value,
input:disabled ~ .label {
opacity: 0.25;
}
.picker-wrap {
left: 0;
top: 0;
+1 -1
View File
@@ -1,9 +1,9 @@
<label class="item item-color">
<span class="label">{{{label}}}</span>
<input
data-manipulator-target
type="hidden"
/>
<span class="label">{{{label}}}</span>
<span class="value"></span>
<div class="picker-wrap">
<div class="picker">