Browse Source

Move to 2 space indentation + editorconfig

pull/36/head
Josh Johnson 5 years ago
parent
commit
d40841d8dd
  1. 9
      .editorconfig
  2. 2
      .eslintrc
  3. 88
      assets/scripts/src/actions/index.js
  4. 3753
      assets/scripts/src/choices.js
  5. 181
      assets/scripts/src/lib/polyfills.js
  6. 505
      assets/scripts/src/lib/utils.js
  7. 154
      assets/scripts/src/reducers/choices.js
  8. 24
      assets/scripts/src/reducers/groups.js
  9. 24
      assets/scripts/src/reducers/index.js
  10. 70
      assets/scripts/src/reducers/items.js
  11. 284
      assets/scripts/src/store/index.js

9
.editorconfig

@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true

2
.eslintrc

@ -10,7 +10,7 @@
"rules": {
"quotes": [2, "single"],
"strict": [2, "never"],
"indent": ["error", 4, {"SwitchCase": 1}],
"indent": ["error", 2, {"SwitchCase": 1}],
"eol-last": "off",
"arrow-body-style": "off",
"no-underscore-dangle": "off",

88
assets/scripts/src/actions/index.js

@ -1,67 +1,67 @@
export const addItem = (value, label, id, choiceId, activateOptions) => {
return {
type: 'ADD_ITEM',
value,
label,
id,
choiceId,
activateOptions,
};
return {
type: 'ADD_ITEM',
value,
label,
id,
choiceId,
activateOptions,
};
};
export const removeItem = (id, choiceId) => {
return {
type: 'REMOVE_ITEM',
id,
choiceId,
};
return {
type: 'REMOVE_ITEM',
id,
choiceId,
};
};
export const highlightItem = (id, highlighted) => {
return {
type: 'HIGHLIGHT_ITEM',
id,
highlighted,
};
return {
type: 'HIGHLIGHT_ITEM',
id,
highlighted,
};
};
export const addChoice = (value, label, id, groupId, disabled) => {
return {
type: 'ADD_CHOICE',
value,
label,
id,
groupId,
disabled,
};
return {
type: 'ADD_CHOICE',
value,
label,
id,
groupId,
disabled,
};
};
export const filterChoices = (results) => {
return {
type: 'FILTER_CHOICES',
results,
};
return {
type: 'FILTER_CHOICES',
results,
};
};
export const activateChoices = (active = true) => {
return {
type: 'ACTIVATE_CHOICES',
active,
};
return {
type: 'ACTIVATE_CHOICES',
active,
};
};
export const addGroup = (value, id, active, disabled) => {
return {
type: 'ADD_GROUP',
value,
id,
active,
disabled,
};
return {
type: 'ADD_GROUP',
value,
id,
active,
disabled,
};
};
export const clearAll = () => {
return {
type: 'CLEAR_ALL',
};
return {
type: 'CLEAR_ALL',
};
};

3753
assets/scripts/src/choices.js
File diff suppressed because it is too large
View File

181
assets/scripts/src/lib/polyfills.js

@ -1,113 +1,112 @@
/* eslint-disable */
// Production steps of ECMA-262, Edition 6, 22.1.2.1
// Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
if (!Array.from) {
Array.from = (function() {
var toStr = Object.prototype.toString;
Array.from = (function() {
var toStr = Object.prototype.toString;
var isCallable = function(fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var isCallable = function(fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function(value) {
var number = Number(value);
if (isNaN(number)) {
return 0;
}
if (number === 0 || !isFinite(number)) {
return number;
}
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var toInteger = function(value) {
var number = Number(value);
if (isNaN(number)) {
return 0;
}
if (number === 0 || !isFinite(number)) {
return number;
}
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function(value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
var toLength = function(value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike /*, mapFn, thisArg */ ) {
// 1. Let C be the this value.
var C = this;
// The length property of the from method is 1.
return function from(arrayLike /*, mapFn, thisArg */ ) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError("Array.from requires an array-like object - not null or undefined");
}
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError("Array.from requires an array-like object - not null or undefined");
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
// Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
Array.prototype.find = function(predicate) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}

505
assets/scripts/src/lib/utils.js

@ -1,14 +1,13 @@
/* eslint-disable */
/**
* Capitalises the first letter of each word in a string
* @param {String} str String to capitalise
* @return {String} Capitalised string
*/
export const capitalise = function(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
return str.replace(/\w\S*/g, function(txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
/**
@ -18,8 +17,8 @@ export const capitalise = function(str) {
* @return {Boolean}
*/
export const isType = function(type, obj) {
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
var clas = Object.prototype.toString.call(obj).slice(8, -1);
return obj !== undefined && obj !== null && clas === type;
};
/**
@ -28,10 +27,10 @@ export const isType = function(type, obj) {
* @return {Boolean}
*/
export const isNode = (o) => {
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
);
return (
typeof Node === "object" ? o instanceof Node :
o && typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName === "string"
);
};
/**
@ -40,10 +39,10 @@ export const isNode = (o) => {
* @return {Boolean}
*/
export const isElement = (o) => {
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName==="string"
);
return (
typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
o && typeof o === "object" && o !== null && o.nodeType === 1 && typeof o.nodeName === "string"
);
};
/**
@ -52,63 +51,63 @@ export const isElement = (o) => {
* @return {Object} Merged object of arguments
*/
export const extend = function() {
let extended = {};
let deep = false;
let length = arguments.length;
/**
* Merge one object into another
* @param {Object} obj Object to merge into extended object
*/
let merge = function (obj) {
for (let prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// If deep merge and property is an object, merge properties
if (deep && isType('Object', obj[prop])) {
extended[prop] = extend( true, extended[prop], obj[prop]);
} else {
extended[prop] = obj[prop];
}
}
let extended = {};
let deep = false;
let length = arguments.length;
/**
* Merge one object into another
* @param {Object} obj Object to merge into extended object
*/
let merge = function(obj) {
for (let prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// If deep merge and property is an object, merge properties
if (deep && isType('Object', obj[prop])) {
extended[prop] = extend(true, extended[prop], obj[prop]);
} else {
extended[prop] = obj[prop];
}
};
}
}
};
// Loop through each passed argument
for (let i = 0; i < length; i++) {
// store argument at position i
let obj = arguments[i];
// Loop through each passed argument
for (let i = 0; i < length; i++) {
// store argument at position i
let obj = arguments[i];
// If we are in fact dealing with an object, merge it. Otherwise throw error
if (isType('Object', obj)) {
merge(obj);
} else {
console.error('Custom options must be an object');
}
// If we are in fact dealing with an object, merge it. Otherwise throw error
if (isType('Object', obj)) {
merge(obj);
} else {
console.error('Custom options must be an object');
}
}
return extended;
return extended;
};
/**
* CSS transition end event listener
* @return
*/
export const whichTransitionEvent = function(){
var t,
export const whichTransitionEvent = function() {
var t,
el = document.createElement("fakeelement");
var transitions = {
"transition" : "transitionend",
"OTransition" : "oTransitionEnd",
"MozTransition" : "transitionend",
"WebkitTransition": "webkitTransitionEnd"
}
var transitions = {
"transition": "transitionend",
"OTransition": "oTransitionEnd",
"MozTransition": "transitionend",
"WebkitTransition": "webkitTransitionEnd"
}
for (t in transitions){
if (el.style[t] !== undefined){
return transitions[t];
}
for (t in transitions) {
if (el.style[t] !== undefined) {
return transitions[t];
}
}
};
/**
@ -116,21 +115,21 @@ export const whichTransitionEvent = function(){
* @return
*/
export const whichAnimationEvent = function() {
var t,
el = document.createElement('fakeelement');
var animations = {
'animation': 'animationend',
'OAnimation': 'oAnimationEnd',
'MozAnimation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd'
};
for (t in animations) {
if (el.style[t] !== undefined) {
return animations[t];
}
var t,
el = document.createElement('fakeelement');
var animations = {
'animation': 'animationend',
'OAnimation': 'oAnimationEnd',
'MozAnimation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd'
};
for (t in animations) {
if (el.style[t] !== undefined) {
return animations[t];
}
}
};
/**
@ -142,103 +141,103 @@ export const whichAnimationEvent = function() {
* @return {Array} Array of parent elements
*/
export const getParentsUntil = function(elem, parent, selector) {
var parents = [];
// Get matches
for (; elem && elem !== document; elem = elem.parentNode) {
// Check if parent has been reached
if (parent) {
var parentType = parent.charAt(0);
// If parent is a class
if (parentType === '.') {
if (elem.classList.contains(parent.substr(1))) {
break;
}
}
// If parent is an ID
if (parentType === '#') {
if (elem.id === parent.substr(1)) {
break;
}
}
// If parent is a data attribute
if (parentType === '[') {
if (elem.hasAttribute(parent.substr(1, parent.length - 1))) {
break;
}
}
// If parent is a tag
if (elem.tagName.toLowerCase() === parent) {
break;
}
var parents = [];
// Get matches
for (; elem && elem !== document; elem = elem.parentNode) {
// Check if parent has been reached
if (parent) {
var parentType = parent.charAt(0);
// If parent is a class
if (parentType === '.') {
if (elem.classList.contains(parent.substr(1))) {
break;
}
if (selector) {
var selectorType = selector.charAt(0);
// If selector is a class
if (selectorType === '.') {
if (elem.classList.contains(selector.substr(1))) {
parents.push(elem);
}
}
// If selector is an ID
if (selectorType === '#') {
if (elem.id === selector.substr(1)) {
parents.push(elem);
}
}
// If selector is a data attribute
if (selectorType === '[') {
if (elem.hasAttribute(selector.substr(1, selector.length - 1))) {
parents.push(elem);
}
}
// If selector is a tag
if (elem.tagName.toLowerCase() === selector) {
parents.push(elem);
}
}
} else {
parents.push(elem);
// If parent is an ID
if (parentType === '#') {
if (elem.id === parent.substr(1)) {
break;
}
}
// If parent is a data attribute
if (parentType === '[') {
if (elem.hasAttribute(parent.substr(1, parent.length - 1))) {
break;
}
}
// If parent is a tag
if (elem.tagName.toLowerCase() === parent) {
break;
}
}
if (selector) {
var selectorType = selector.charAt(0);
// If selector is a class
if (selectorType === '.') {
if (elem.classList.contains(selector.substr(1))) {
parents.push(elem);
}
}
// If selector is an ID
if (selectorType === '#') {
if (elem.id === selector.substr(1)) {
parents.push(elem);
}
}
// If selector is a data attribute
if (selectorType === '[') {
if (elem.hasAttribute(selector.substr(1, selector.length - 1))) {
parents.push(elem);
}
}
// If selector is a tag
if (elem.tagName.toLowerCase() === selector) {
parents.push(elem);
}
// Return parents if any exist
if (parents.length === 0) {
return null;
} else {
return parents;
parents.push(elem);
}
}
// Return parents if any exist
if (parents.length === 0) {
return null;
} else {
return parents;
}
};
export const wrap = function (element, wrapper) {
wrapper = wrapper || document.createElement('div');
if (element.nextSibling) {
element.parentNode.insertBefore(wrapper, element.nextSibling);
} else {
element.parentNode.appendChild(wrapper);
}
return wrapper.appendChild(element);
export const wrap = function(element, wrapper) {
wrapper = wrapper || document.createElement('div');
if (element.nextSibling) {
element.parentNode.insertBefore(wrapper, element.nextSibling);
} else {
element.parentNode.appendChild(wrapper);
}
return wrapper.appendChild(element);
};
export const getSiblings = function (elem) {
var siblings = [];
var sibling = elem.parentNode.firstChild;
for ( ; sibling; sibling = sibling.nextSibling ) {
if ( sibling.nodeType === 1 && sibling !== elem ) {
siblings.push( sibling );
}
export const getSiblings = function(elem) {
var siblings = [];
var sibling = elem.parentNode.firstChild;
for (; sibling; sibling = sibling.nextSibling) {
if (sibling.nodeType === 1 && sibling !== elem) {
siblings.push(sibling);
}
return siblings;
}
return siblings;
};
/**
@ -248,8 +247,8 @@ export const getSiblings = function (elem) {
* @return {NodeElement} Found parent element
*/
export const findAncestor = function(el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
};
/**
@ -260,19 +259,19 @@ export const findAncestor = function(el, cls) {
* @return {Function} A function will be called after it stops being called for a given delay
*/
export const debounce = function(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
/**
@ -282,14 +281,14 @@ export const debounce = function(func, wait, immediate) {
* @return {Number} Elements Distance from top of page
*/
export const getElemDistance = function(el) {
var location = 0;
if (el.offsetParent) {
do {
location += el.offsetTop;
el = el.offsetParent;
} while (el);
}
return location >= 0 ? location : 0;
var location = 0;
if (el.offsetParent) {
do {
location += el.offsetTop;
el = el.offsetParent;
} while (el);
}
return location >= 0 ? location : 0;
};
/**
@ -299,11 +298,11 @@ export const getElemDistance = function(el) {
* @return {Number} Height of element
*/
export const getElementOffset = function(el, offset) {
var elOffset = offset;
if(elOffset > 1) elOffset = 1;
if(elOffset > 0) elOffset = 0;
var elOffset = offset;
if (elOffset > 1) elOffset = 1;
if (elOffset > 0) elOffset = 0;
return Math.max(el.offsetHeight*elOffset);
return Math.max(el.offsetHeight * elOffset);
};
/**
@ -314,15 +313,15 @@ export const getElementOffset = function(el, offset) {
* @return {[HTMLElement} Found element
*/
export const getAdjacentEl = (startEl, className, direction = 1) => {
if(!startEl || !className) return;
if (!startEl || !className) return;
const parent = startEl.parentNode.parentNode;
const children = Array.from(parent.querySelectorAll(className));
const parent = startEl.parentNode.parentNode;
const children = Array.from(parent.querySelectorAll(className));
const startPos = children.indexOf(startEl);
const operatorDirection = direction > 0 ? 1 : -1;
const startPos = children.indexOf(startEl);
const operatorDirection = direction > 0 ? 1 : -1;
return children[startPos + operatorDirection];
return children[startPos + operatorDirection];
};
/**
@ -331,13 +330,13 @@ export const getAdjacentEl = (startEl, className, direction = 1) => {
* @return {String} Position of scroll
*/
export const getScrollPosition = function(position) {
if(position === 'bottom') {
// Scroll position from the bottom of the viewport
return Math.max((window.scrollY || window.pageYOffset) + (window.innerHeight || document.documentElement.clientHeight));
} else {
// Scroll position from the top of the viewport
return (window.scrollY || window.pageYOffset);
}
if (position === 'bottom') {
// Scroll position from the bottom of the viewport
return Math.max((window.scrollY || window.pageYOffset) + (window.innerHeight || document.documentElement.clientHeight));
} else {
// Scroll position from the top of the viewport
return (window.scrollY || window.pageYOffset);
}
};
/**
@ -347,8 +346,8 @@ export const getScrollPosition = function(position) {
* @return {Boolean}
*/
export const isInView = function(el, position, offset) {
// If the user has scrolled further than the distance from the element to the top of its parent
return this.getScrollPosition(position) > (this.getElemDistance(el) + this.getElementOffset(el, offset)) ? true : false;
// If the user has scrolled further than the distance from the element to the top of its parent
return this.getScrollPosition(position) > (this.getElemDistance(el) + this.getElementOffset(el, offset)) ? true : false;
};
/**
@ -359,19 +358,19 @@ export const isInView = function(el, position, offset) {
* @return {Boolean}
*/
export const isScrolledIntoView = (el, parent, direction = 1) => {
if(!el) return;
if (!el) return;
let isVisible;
let isVisible;
if(direction > 0) {
// In view from bottom
isVisible = (parent.scrollTop + parent.offsetHeight) >= (el.offsetTop + el.offsetHeight) ;
} else {
// In view from top
isVisible = el.offsetTop >= parent.scrollTop;
}
if (direction > 0) {
// In view from bottom
isVisible = (parent.scrollTop + parent.offsetHeight) >= (el.offsetTop + el.offsetHeight);
} else {
// In view from top
isVisible = el.offsetTop >= parent.scrollTop;
}
return isVisible;
return isVisible;
};
/**
@ -380,9 +379,9 @@ export const isScrolledIntoView = (el, parent, direction = 1) => {
* @return {String} Sanitised string
*/
export const stripHTML = function(html) {
let el = document.createElement("DIV");
el.innerHTML = html;
return el.textContent || el.innerText || "";
let el = document.createElement("DIV");
el.innerHTML = html;
return el.textContent || el.innerText || "";
};
/**
@ -392,15 +391,15 @@ export const stripHTML = function(html) {
* @return
*/
export const addAnimation = (el, animation) => {
let animationEvent = whichAnimationEvent();
let animationEvent = whichAnimationEvent();
let removeAnimation = () => {
el.classList.remove(animation);
el.removeEventListener(animationEvent, removeAnimation, false);
};
let removeAnimation = () => {
el.classList.remove(animation);
el.removeEventListener(animationEvent, removeAnimation, false);
};
el.classList.add(animation);
el.addEventListener(animationEvent, removeAnimation, false);
el.classList.add(animation);
el.addEventListener(animationEvent, removeAnimation, false);
};
@ -411,7 +410,7 @@ export const addAnimation = (el, animation) => {
* @return {Number} Random number
*/
export const getRandomNumber = function(min, max) {
return Math.floor(Math.random() * (max - min) + min);
return Math.floor(Math.random() * (max - min) + min);
};
/**
@ -420,18 +419,18 @@ export const getRandomNumber = function(min, max) {
* @return {HTMLElement} Converted node element
*/
export const strToEl = (function() {
var tmpEl = document.createElement('div');
return function(str) {
var r;
tmpEl.innerHTML = str;
r = tmpEl.children[0];
while (tmpEl.firstChild) {
tmpEl.removeChild(tmpEl.firstChild);
}
var tmpEl = document.createElement('div');
return function(str) {
var r;
tmpEl.innerHTML = str;
r = tmpEl.children[0];
while (tmpEl.firstChild) {
tmpEl.removeChild(tmpEl.firstChild);
}
return r;
};
return r;
};
}());
/**
@ -439,39 +438,39 @@ export const strToEl = (function() {
* @return {Number} Width of input
*/
export const getWidthOfInput = (input) => {
const value = input.value || input.placeholder;
let width = input.offsetWidth;
if(value) {
const testEl = strToEl(`<span>${ value }</span>`);
testEl.style.position = 'absolute';
testEl.style.padding = '0';
testEl.style.top = '-9999px';
testEl.style.left = '-9999px';
testEl.style.width = 'auto';
testEl.style.whiteSpace = 'pre';
document.body.appendChild(testEl);
if(value && testEl.offsetWidth !== input.offsetWidth) {
width = testEl.offsetWidth + 4;
}
document.body.removeChild(testEl);
const value = input.value || input.placeholder;
let width = input.offsetWidth;
if (value) {
const testEl = strToEl(`<span>${ value }</span>`);
testEl.style.position = 'absolute';
testEl.style.padding = '0';
testEl.style.top = '-9999px';
testEl.style.left = '-9999px';
testEl.style.width = 'auto';
testEl.style.whiteSpace = 'pre';
document.body.appendChild(testEl);
if (value && testEl.offsetWidth !== input.offsetWidth) {
width = testEl.offsetWidth + 4;
}
return `${width}px`;
document.body.removeChild(testEl);
}
return `${width}px`;
};
export const sortByAlpha = (a, b) => {
const labelA = (a.label || a.value).toLowerCase();
const labelB = (b.label || b.value).toLowerCase();
const labelA = (a.label || a.value).toLowerCase();
const labelB = (b.label || b.value).toLowerCase();
if (labelA < labelB) return -1;
if (labelA > labelB) return 1;
return 0;
if (labelA < labelB) return -1;
if (labelA > labelB) return 1;
return 0;
};
export const sortByScore = (a, b) => {
return a.score - b.score;
return a.score - b.score;
};

154
assets/scripts/src/reducers/choices.js

@ -1,93 +1,93 @@
const choices = (state = [], action) => {
switch (action.type) {
case 'ADD_CHOICE': {
/*
A disabled choice appears in the choice dropdown but cannot be selected
A selected choice has been added to the passed input's value (added as an item)
An active choice appears within the choice dropdown
*/
return [...state, {
id: action.id,
groupId: action.groupId,
value: action.value,
label: action.label,
disabled: action.disabled,
selected: false,
active: true,
score: 9999,
}];
}
switch (action.type) {
case 'ADD_CHOICE': {
/*
A disabled choice appears in the choice dropdown but cannot be selected
A selected choice has been added to the passed input's value (added as an item)
An active choice appears within the choice dropdown
*/
return [...state, {
id: action.id,
groupId: action.groupId,
value: action.value,
label: action.label,
disabled: action.disabled,
selected: false,
active: true,
score: 9999,
}];
}
case 'ADD_ITEM': {
let newState = state;
case 'ADD_ITEM': {
let newState = state;
// If all choices need to be activated
if (action.activateOptions) {
newState = state.map((choice) => {
choice.active = action.active;
return choice;
});
}
// When an item is added and it has an associated choice,
// we want to disable it so it can't be chosen again
if (action.choiceId > -1) {
newState = state.map((choice) => {
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = true;
}
return choice;
});
}
// If all choices need to be activated
if (action.activateOptions) {
newState = state.map((choice) => {
choice.active = action.active;
return choice;
});
}
// When an item is added and it has an associated choice,
// we want to disable it so it can't be chosen again
if (action.choiceId > -1) {
newState = state.map((choice) => {
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = true;
}
return choice;
});
}
return newState;
}
return newState;
}
case 'REMOVE_ITEM': {
// When an item is removed and it has an associated choice,
// we want to re-enable it so it can be chosen again
if (action.choiceId > -1) {
return state.map((choice) => {
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = false;
}
return choice;
});
}
case 'REMOVE_ITEM': {
// When an item is removed and it has an associated choice,
// we want to re-enable it so it can be chosen again
if (action.choiceId > -1) {
return state.map((choice) => {
if (choice.id === parseInt(action.choiceId, 10)) {
choice.selected = false;
}
return choice;
});
}
return state;
}
return state;
}
case 'FILTER_CHOICES': {
const filteredResults = action.results;
const filteredState = state.map((choice) => {
// Set active state based on whether choice is
// within filtered results
case 'FILTER_CHOICES': {
const filteredResults = action.results;
const filteredState = state.map((choice) => {
// Set active state based on whether choice is
// within filtered results
choice.active = filteredResults.some((result) => {
if (result.item.id === choice.id) {
choice.score = result.score;
return true;
}
return false;
});
choice.active = filteredResults.some((result) => {
if (result.item.id === choice.id) {
choice.score = result.score;
return true;
}
return false;
});
return choice;
});
return choice;
});
return filteredState;
}
return filteredState;
}
case 'ACTIVATE_CHOICES': {
return state.map((choice) => {
choice.active = action.active;
return choice;
});
}
case 'ACTIVATE_CHOICES': {
return state.map((choice) => {
choice.active = action.active;
return choice;
});
}
default: {
return state;
}
default: {
return state;
}
}
};
export default choices;

24
assets/scripts/src/reducers/groups.js

@ -1,18 +1,18 @@
const groups = (state = [], action) => {
switch (action.type) {
case 'ADD_GROUP': {
return [...state, {
id: action.id,
value: action.value,
active: action.active,
disabled: action.disabled,
}];
}
switch (action.type) {
case 'ADD_GROUP': {
return [...state, {
id: action.id,
value: action.value,
active: action.active,
disabled: action.disabled,
}];
}
default: {
return state;
}
default: {
return state;
}
}
};
export default groups;

24
assets/scripts/src/reducers/index.js

@ -4,22 +4,22 @@ import groups from './groups';
import choices from './choices';
const appReducer = combineReducers({
items,
groups,
choices,
items,
groups,
choices,
});
const rootReducer = (passedState, action) => {
let state = passedState;
// If we are clearing all items, groups and options we reassign
// state and then pass that state to our proper reducer. This isn't
// mutating our actual state
// See: http://stackoverflow.com/a/35641992
if (action.type === 'CLEAR_ALL') {
state = undefined;
}
let state = passedState;
// If we are clearing all items, groups and options we reassign
// state and then pass that state to our proper reducer. This isn't
// mutating our actual state
// See: http://stackoverflow.com/a/35641992
if (action.type === 'CLEAR_ALL') {
state = undefined;
}
return appReducer(state, action);
return appReducer(state, action);
};
export default rootReducer;

70
assets/scripts/src/reducers/items.js

@ -1,47 +1,47 @@
const items = (state = [], action) => {
switch (action.type) {
case 'ADD_ITEM': {
// Add object to items array
const newState = [...state, {
id: action.id,
choiceId: action.choiceId,
value: action.value,
label: action.label,
active: true,
highlighted: false,
}];
switch (action.type) {
case 'ADD_ITEM': {
// Add object to items array
const newState = [...state, {
id: action.id,
choiceId: action.choiceId,
value: action.value,
label: action.label,
active: true,
highlighted: false,
}];
return newState.map((item) => {
if (item.highlighted) {
item.highlighted = false;
}
return item;
});
return newState.map((item) => {
if (item.highlighted) {
item.highlighted = false;
}
return item;
});
}
case 'REMOVE_ITEM': {
// Set item to inactive
return state.map((item) => {
if (item.id === action.id) {
item.active = false;
}
return item;
});
case 'REMOVE_ITEM': {
// Set item to inactive
return state.map((item) => {
if (item.id === action.id) {
item.active = false;
}
return item;
});
}
case 'HIGHLIGHT_ITEM': {
return state.map((item) => {
if (item.id === action.id) {
item.highlighted = action.highlighted;
}
return item;
});
case 'HIGHLIGHT_ITEM': {
return state.map((item) => {
if (item.id === action.id) {
item.highlighted = action.highlighted;
}
return item;
});
}
default: {
return state;
}
default: {
return state;
}
}
};
export default items;

284
assets/scripts/src/store/index.js

@ -2,149 +2,149 @@ import { createStore } from 'redux';
import rootReducer from './../reducers/index.js';
export default class Store {
constructor() {
this.store = createStore(
rootReducer,
window.devToolsExtension ? window.devToolsExtension() : undefined
);
}
/**
* Get store object (wrapping Redux method)
* @return {Object} State
*/
getState() {
return this.store.getState();
}
/**
* Dispatch event to store (wrapped Redux method)
* @param {Function} action Action function to trigger
* @return
*/
dispatch(action) {
this.store.dispatch(action);
}
/**
* Subscribe store to function call (wrapped Redux method)
* @param {Function} onChange Function to trigger when state changes
* @return
*/
subscribe(onChange) {
this.store.subscribe(onChange);
}
/**
* Get items from store
* @return {Array} Item objects
*/
getItems() {
const state = this.store.getState();
return state.items;
}
/**
* Get active items from store
* @return {Array} Item objects
*/
getItemsFilteredByActive() {
const items = this.getItems();
const values = items.filter((item) => {
return item.active === true;
}, []);
return values;
}
/**
* Get items from store reduced to just their values
* @return {Array} Item objects
*/
getItemsReducedToValues(items = this.getItems()) {
const values = items.reduce((prev, current) => {
prev.push(current.value);
return prev;
}, []);
return values;
}
/**
* Get choices from store
* @return {Array} Option objects
*/
getChoices() {
const state = this.store.getState();
return state.choices;
}
/**
* Get active choices from store
* @return {Array} Option objects
*/
getChoicesFilteredByActive() {
const choices = this.getChoices();
const values = choices.filter((choice) => {
return choice.active === true;
}, []);
return values;
}
/**
* Get selectable choices from store
* @return {Array} Option objects
*/
getChoicesFilteredBySelectable() {
const choices = this.getChoices();
const values = choices.filter((choice) => {
return choice.disabled !== true;
}, []);
return values;
}
/**
* Get single choice by it's ID
* @return {Object} Found choice
*/
getChoiceById(id) {
if (id) {
const choices = this.getChoicesFilteredByActive();
const foundChoice = choices.find((choice) => choice.id === parseInt(id, 10));
return foundChoice;
}
return false;
}
/**
* Get groups from store
* @return {Array} Group objects
*/
getGroups() {
const state = this.store.getState();
return state.groups;
}
/**
* Get active groups from store
* @return {Array} Group objects
*/
getGroupsFilteredByActive() {
const groups = this.getGroups();
const choices = this.getChoices();
const values = groups.filter((group) => {
const isActive = group.active === true && group.disabled === false;
const hasActiveOptions = choices.some((choice) => {
return choice.active === true && choice.disabled === false;
});
return isActive && hasActiveOptions;
}, []);
return values;
constructor() {
this.store = createStore(
rootReducer
, window.devToolsExtension ? window.devToolsExtension() : undefined
);
}
/**
* Get store object (wrapping Redux method)
* @return {Object} State
*/
getState() {
return this.store.getState();
}
/**
* Dispatch event to store (wrapped Redux method)
* @param {Function} action Action function to trigger
* @return
*/
dispatch(action) {
this.store.dispatch(action);
}
/**
* Subscribe store to function call (wrapped Redux method)
* @param {Function} onChange Function to trigger when state changes
* @return
*/
subscribe(onChange) {
this.store.subscribe(onChange);
}