diff --git a/.babelrc b/.babelrc deleted file mode 100644 index 89cafe3..0000000 --- a/.babelrc +++ /dev/null @@ -1,10 +0,0 @@ -{ - "presets": ["es2015-webpack", "stage-2"], - "env": { - "test": { - "plugins": [ - ["__coverage__", {"ignore": "*.+(test|stub).*"}] - ] - } - } -} diff --git a/.eslintrc b/.eslintrc index 2531b1d..50cc65d 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,5 +1,5 @@ { - "extends": ["kentcdodds/es-next"], + "extends": ["kentcdodds"], "rules": { // these are only here because I did not // want to update the entire codebase ¯\_(ツ)_/¯ @@ -9,11 +9,17 @@ "comma-dangle": 0, "valid-jsdoc": 0, "vars-on-top": 0, - "complexity": [2, 6], + "complexity": [2, 8], + "max-depth": [2, 6], + "consistent-return": 0, + // es6 stuff we technically can not do yet + "object-shorthand": 0, }, "globals": { "describe": false, "it": false, - "expect": false + "expect": false, + "$on": false, + "beforeEach": false, } } diff --git a/src/favicon.ico b/favicon.ico similarity index 100% rename from src/favicon.ico rename to favicon.ico diff --git a/src/index.html b/index.html similarity index 72% rename from src/index.html rename to index.html index 48e5cef..77dd369 100755 --- a/src/index.html +++ b/index.html @@ -3,10 +3,10 @@ VanillaJS • TodoMVC - - + + - +

todos

@@ -40,7 +40,13 @@

Ported to ES6 by Kent C. Dodds

Part of TodoMVC

- - + + + + + + + + diff --git a/karma.conf.js b/karma.conf.js index 87efb5a..17c1adf 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -1,21 +1,19 @@ -const webpackEnv = {test: true} -const webpackConfig = require('./webpack.config')(webpackEnv) -process.env.BABEL_ENV = 'test' // so we load the correct babel plugins -const testGlob = 'src/js/**/*.test.js' -const srcGlob = 'src/js/**/*!(test|stub).js' - +var preprocessors = {} +preprocessors['src/**/*.js'] = ['coverage'] module.exports = function setKarmaConfig(config) { config.set({ basePath: '', frameworks: ['mocha', 'chai'], - files: [testGlob, srcGlob], - preprocessors: { - [testGlob]: ['webpack'], - [srcGlob]: ['webpack'], - }, - webpack: webpackConfig, - webpackMiddleware: {noInfo: true}, + files: [ + 'src/**/*.js', + 'test/stub/**/*.js', + 'test/unit/**/*.js', + ], + exclude: [ + 'src/app.js', + ], reporters: ['progress', 'coverage'], + preprocessors: preprocessors, coverageReporter: { reporters: [ {type: 'lcov', dir: 'coverage/', subdir: '.'}, diff --git a/package.json b/package.json index 10eb255..4f5b9af 100644 --- a/package.json +++ b/package.json @@ -5,35 +5,23 @@ "todomvc-common": "1.0.2" }, "devDependencies": { - "babel": "6.5.2", - "babel-core": "6.8.0", "babel-eslint": "6.0.4", - "babel-loader": "6.2.4", - "babel-plugin-__coverage__": "1.11.111", - "babel-preset-es2015-webpack": "6.4.1", - "babel-preset-stage-2": "6.5.0", "chai": "3.5.0", "cpy-cli": "1.0.0", - "css-loader": "0.23.1", "eslint": "2.9.0", "eslint-config-kentcdodds": "6.2.1", - "eslint-loader": "1.3.0", "ghooks": "1.2.1", + "http-server": "0.9.0", "istanbul": "0.4.3", "karma": "0.13.22", "karma-chai": "0.1.0", "karma-chrome-launcher": "1.0.1", "karma-coverage": "1.0.0", "karma-mocha": "1.0.1", - "karma-webpack": "1.7.0", "mocha": "2.5.3", "npm-run-all": "1.8.0", "opt-cli": "1.4.2", - "rimraf": "2.5.2", - "style-loader": "0.13.1", - "webpack": "2.1.0-beta.12", - "webpack-dev-server": "2.0.0-beta", - "webpack-validator": "2.1.2" + "rimraf": "2.5.2" }, "config": { "ghooks": { @@ -42,20 +30,10 @@ }, "scripts": { "test": "karma start", - "check-coverage": "istanbul check-coverage --statements 23 --branches 5 --functions 9 --lines 24", + "check-coverage": "istanbul check-coverage --statements 22 --branches 5 --functions 0 --lines 22", "watch:test": "npm test -- --auto-watch --no-single-run", - "validate": "npm-run-all --parallel validate-webpack:* lint test --serial check-coverage", - "validate-webpack:dev": "webpack-validator webpack.config.js --env.dev", - "validate-webpack:prod": "webpack-validator webpack.config.js --env.prod", - "clean-dist": "rimraf dist", - "copy-files": "cpy src/index.html src/favicon.ico dist", - "clean-and-copy": "npm run clean-dist && npm run copy-files", - "prestart": "npm run clean-and-copy", - "start": "webpack-dev-server --env.dev --content-base dist", - "prebuild": "npm run clean-and-copy", - "prebuild:prod": "npm run clean-and-copy", - "build": "webpack --env.dev", - "build:prod": "webpack --env.prod -p", + "validate": "npm-run-all --parallel lint test --serial check-coverage", + "start": "http-server", "lint": "eslint .", "setup": "npm install && npm run validate" } diff --git a/src/app.js b/src/app.js new file mode 100644 index 0000000..da65a07 --- /dev/null +++ b/src/app.js @@ -0,0 +1,25 @@ +/* global app, $on */ +(function() { + 'use strict' + + /** + * Sets up a brand new Todo list. + * + * @param {string} name The name of your new to do list. + */ + function Todo(name) { + this.storage = new app.Store(name) + this.model = new app.Model(this.storage) + this.template = new app.Template() + this.view = new app.View(this.template) + this.controller = new app.Controller(this.model, this.view) + } + + function setView() { + var todo = new Todo('todos-vanillajs') + todo.controller.setView(document.location.hash) + } + + $on(window, 'load', setView) + $on(window, 'hashchange', setView) +})() diff --git a/src/controller.js b/src/controller.js new file mode 100644 index 0000000..134e371 --- /dev/null +++ b/src/controller.js @@ -0,0 +1,268 @@ +(function(window) { + 'use strict' + + /** + * Takes a model and view and acts as the controller between them + * + * @constructor + * @param {object} model The model instance + * @param {object} view The view instance + */ + function Controller(model, view) { + var that = this + that.model = model + that.view = view + + that.view.bind('newTodo', function(title) { + that.addItem(title) + }) + + that.view.bind('itemEdit', function(item) { + that.editItem(item.id) + }) + + that.view.bind('itemEditDone', function(item) { + that.editItemSave(item.id, item.title) + }) + + that.view.bind('itemEditCancel', function(item) { + that.editItemCancel(item.id) + }) + + that.view.bind('itemRemove', function(item) { + that.removeItem(item.id) + }) + + that.view.bind('itemToggle', function(item) { + that.toggleComplete(item.id, item.completed) + }) + + that.view.bind('removeCompleted', function() { + that.removeCompletedItems() + }) + + that.view.bind('toggleAll', function(status) { + that.toggleAll(status.completed) + }) + } + + /** + * Loads and initialises the view + * + * @param {string} '' | 'active' | 'completed' + */ + Controller.prototype.setView = function(locationHash) { + var route = locationHash.split('/')[1] + var page = route || '' + this._updateFilterState(page) + } + + /** + * An event to fire on load. Will get all items and display them in the + * todo-list + */ + Controller.prototype.showAll = function() { + var that = this + that.model.read(function(data) { + that.view.render('showEntries', data) + }) + } + + /** + * Renders all active tasks + */ + Controller.prototype.showActive = function() { + var that = this + that.model.read({completed: false}, function(data) { + that.view.render('showEntries', data) + }) + } + + /** + * Renders all completed tasks + */ + Controller.prototype.showCompleted = function() { + var that = this + that.model.read({completed: true}, function(data) { + that.view.render('showEntries', data) + }) + } + + /** + * An event to fire whenever you want to add an item. Simply pass in the event + * object and it'll handle the DOM insertion and saving of the new item. + */ + Controller.prototype.addItem = function(title) { + var that = this + + if (title.trim() === '') { + return + } + + that.model.create(title, function() { + that.view.render('clearNewTodo') + that._filter(true) + }) + } + + /* + * Triggers the item editing mode. + */ + Controller.prototype.editItem = function(id) { + var that = this + that.model.read(id, function(data) { + that.view.render('editItem', {id: id, title: data[0].title}) + }) + } + + /* + * Finishes the item editing mode successfully. + */ + Controller.prototype.editItemSave = function(id, title) { + var that = this + if (title.trim()) { + that.model.update(id, {title: title}, function() { + that.view.render('editItemDone', {id: id, title: title}) + }) + } else { + that.removeItem(id) + } + } + + /* + * Cancels the item editing mode. + */ + Controller.prototype.editItemCancel = function(id) { + var that = this + that.model.read(id, function(data) { + that.view.render('editItemDone', {id: id, title: data[0].title}) + }) + } + + /** + * By giving it an ID it'll find the DOM element matching that ID, + * remove it from the DOM and also remove it from storage. + * + * @param {number} id The ID of the item to remove from the DOM and + * storage + */ + Controller.prototype.removeItem = function(id) { + var that = this + that.model.remove(id, function() { + that.view.render('removeItem', id) + }) + + that._filter() + } + + /** + * Will remove all completed items from the DOM and storage. + */ + Controller.prototype.removeCompletedItems = function() { + var that = this + that.model.read({completed: true}, function(data) { + data.forEach(function(item) { + that.removeItem(item.id) + }) + }) + + that._filter() + } + + /** + * Give it an ID of a model and a checkbox and it will update the item + * in storage based on the checkbox's state. + * + * @param {number} id The ID of the element to complete or uncomplete + * @param {object} checkbox The checkbox to check the state of complete + * or not + * @param {boolean|undefined} silent Prevent re-filtering the todo items + */ + Controller.prototype.toggleComplete = function(id, completed, silent) { + var that = this + that.model.update(id, {completed: completed}, function() { + that.view.render('elementComplete', { + id: id, + completed: completed + }) + }) + + if (!silent) { + that._filter() + } + } + + /** + * Will toggle ALL checkboxes' on/off state and completeness of models. + * Just pass in the event object. + */ + Controller.prototype.toggleAll = function(completed) { + var that = this + that.model.read({completed: !completed}, function(data) { + data.forEach(function(item) { + that.toggleComplete(item.id, completed, true) + }) + }) + + that._filter() + } + + /** + * Updates the pieces of the page which change depending on the remaining + * number of todos. + */ + Controller.prototype._updateCount = function() { + var that = this + that.model.getCount(function(todos) { + that.view.render('updateElementCount', todos.active) + that.view.render('clearCompletedButton', { + completed: todos.completed, + visible: todos.completed > 0 + }) + + that.view.render('toggleAll', {checked: todos.completed === todos.total}) + that.view.render('contentBlockVisibility', {visible: todos.total > 0}) + }) + } + + /** + * Re-filters the todo items, based on the active route. + * @param {boolean|undefined} force forces a re-painting of todo items. + */ + Controller.prototype._filter = function(force) { + var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1) + + // Update the elements on the page, which change with each completed todo + this._updateCount() + + // If the last active route isn't "All", or we're switching routes, we + // re-create the todo item elements, calling: + // this.show[All|Active|Completed](); + if (force || this._lastActiveRoute !== 'All' || this._lastActiveRoute !== activeRoute) { + this['show' + activeRoute]() + } + + this._lastActiveRoute = activeRoute + } + + /** + * Simply updates the filter nav's selected states + */ + Controller.prototype._updateFilterState = function(currentPage) { + // Store a reference to the active route, allowing us to re-filter todo + // items as they are marked complete or incomplete. + this._activeRoute = currentPage + + if (currentPage === '') { + this._activeRoute = 'All' + } + + this._filter() + + this.view.render('setFilter', currentPage) + } + + // Export to window + window.app = window.app || {} + window.app.Controller = Controller +})(window) diff --git a/src/helpers.js b/src/helpers.js new file mode 100644 index 0000000..d5a9865 --- /dev/null +++ b/src/helpers.js @@ -0,0 +1,52 @@ +/*global NodeList */ +(function(window) { + 'use strict' + + // Get element(s) by CSS selector: + window.qs = function(selector, scope) { + return (scope || document).querySelector(selector) + } + window.qsa = function(selector, scope) { + return (scope || document).querySelectorAll(selector) + } + + // addEventListener wrapper: + window.$on = function(target, type, callback, useCapture) { + target.addEventListener(type, callback, !!useCapture) + } + + // Attach a handler to event for all elements that match the selector, + // now or in the future, based on a root element + window.$delegate = function(target, selector, type, handler) { + function dispatchEvent(event) { + var targetElement = event.target + var potentialElements = window.qsa(selector, target) + var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0 + + if (hasMatch) { + handler.call(targetElement, event) + } + } + + // https://developer.mozilla.org/en-US/docs/Web/Events/blur + var useCapture = type === 'blur' || type === 'focus' + + window.$on(target, type, dispatchEvent, useCapture) + } + + // Find the element's parent with the given tag name: + // $parent(qs('a'), 'div'); + window.$parent = function(element, tagName) { + if (!element.parentNode) { + return + } + if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) { + return element.parentNode + } + return window.$parent(element.parentNode, tagName) + } + + // Allow for looping on nodes by chaining: + // qsa('.foo').forEach(function () {}) + NodeList.prototype.forEach = Array.prototype.forEach +})(window) diff --git a/src/js/app.js b/src/js/app.js deleted file mode 100755 index 2c0012f..0000000 --- a/src/js/app.js +++ /dev/null @@ -1,35 +0,0 @@ -import 'todomvc-common/base.css' -import 'todomvc-app-css/index.css' - -import View from './view' -import {$on, qsa, removeClass} from './helpers' -import Controller from './controller' -import Model from './model' -import Store from './store' -import Template from './template' - -var todo - -/** - * Sets up a brand new Todo list. - * - * @param {string} name The name of your new to do list. - */ -function Todo(name) { - this.storage = new Store(name) - this.model = new Model(this.storage) - this.template = new Template() - this.view = new View(this.template) - this.controller = new Controller(this.model, this.view) -} - -function setView() { - todo.controller.setView(document.location.hash) -} - -$on(window, 'load', function() { - todo = new Todo('todos-vanillajs') - setView() - removeClass(qsa('.hide'), 'hide') -}) -$on(window, 'hashchange', setView) diff --git a/src/js/controller.js b/src/js/controller.js deleted file mode 100755 index c126991..0000000 --- a/src/js/controller.js +++ /dev/null @@ -1,261 +0,0 @@ -export default Controller -/** -* Takes a model and view and acts as the controller between them -* -* @constructor -* @param {object} model The model instance -* @param {object} view The view instance -*/ -function Controller(model, view) { - var that = this - that.model = model - that.view = view - - that.view.bind('newTodo', function(title) { - that.addItem(title) - }) - - that.view.bind('itemEdit', function(item) { - that.editItem(item.id) - }) - - that.view.bind('itemEditDone', function(item) { - that.editItemSave(item.id, item.title) - }) - - that.view.bind('itemEditCancel', function(item) { - that.editItemCancel(item.id) - }) - - that.view.bind('itemRemove', function(item) { - that.removeItem(item.id) - }) - - that.view.bind('itemToggle', function(item) { - that.toggleComplete(item.id, item.completed) - }) - - that.view.bind('removeCompleted', function() { - that.removeCompletedItems() - }) - - that.view.bind('toggleAll', function(status) { - that.toggleAll(status.completed) - }) -} - -/** -* Loads and initialises the view -* -* @param {string} '' | 'active' | 'completed' -*/ -Controller.prototype.setView = function(locationHash) { - var route = locationHash.split('/')[1] - var page = route || '' - this._updateFilterState(page) -} - -/** -* An event to fire on load. Will get all items and display them in the -* todo-list -*/ -Controller.prototype.showAll = function() { - var that = this - that.model.read(function(data) { - that.view.render('showEntries', data) - }) -} - -/** -* Renders all active tasks -*/ -Controller.prototype.showActive = function() { - var that = this - that.model.read({completed: false}, function(data) { - that.view.render('showEntries', data) - }) -} - -/** -* Renders all completed tasks -*/ -Controller.prototype.showCompleted = function() { - var that = this - that.model.read({completed: true}, function(data) { - that.view.render('showEntries', data) - }) -} - -/** -* An event to fire whenever you want to add an item. Simply pass in the event -* object and it'll handle the DOM insertion and saving of the new item. -*/ -Controller.prototype.addItem = function(title) { - var that = this - - if (title.trim() === '') { - return - } - - that.model.create(title, function() { - that.view.render('clearNewTodo') - that._filter(true) - }) -} - -/* -* Triggers the item editing mode. -*/ -Controller.prototype.editItem = function(id) { - var that = this - that.model.read(id, function(data) { - that.view.render('editItem', {id, title: data[0].title}) - }) -} - -/* -* Finishes the item editing mode successfully. -*/ -Controller.prototype.editItemSave = function(id, title) { - var that = this - if (title.trim()) { - that.model.update(id, {title}, function() { - that.view.render('editItemDone', {id, title}) - }) - } else { - that.removeItem(id) - } -} - -/* -* Cancels the item editing mode. -*/ -Controller.prototype.editItemCancel = function(id) { - var that = this - that.model.read(id, function(data) { - that.view.render('editItemDone', {id, title: data[0].title}) - }) -} - -/** -* By giving it an ID it'll find the DOM element matching that ID, -* remove it from the DOM and also remove it from storage. -* -* @param {number} id The ID of the item to remove from the DOM and -* storage -*/ -Controller.prototype.removeItem = function(id) { - var that = this - that.model.remove(id, function() { - that.view.render('removeItem', id) - }) - - that._filter() -} - -/** -* Will remove all completed items from the DOM and storage. -*/ -Controller.prototype.removeCompletedItems = function() { - var that = this - that.model.read({completed: true}, function(data) { - data.forEach(function(item) { - that.removeItem(item.id) - }) - }) - - that._filter() -} - -/** -* Give it an ID of a model and a checkbox and it will update the item -* in storage based on the checkbox's state. -* -* @param {number} id The ID of the element to complete or uncomplete -* @param {object} checkbox The checkbox to check the state of complete -* or not -* @param {boolean|undefined} silent Prevent re-filtering the todo items -*/ -Controller.prototype.toggleComplete = function(id, completed, silent) { - var that = this - that.model.update(id, {completed}, function() { - that.view.render('elementComplete', { - id, - completed, - }) - }) - - if (!silent) { - that._filter() - } -} - -/** -* Will toggle ALL checkboxes' on/off state and completeness of models. -* Just pass in the event object. -*/ -Controller.prototype.toggleAll = function(completed) { - var that = this - that.model.read({completed: !completed}, function(data) { - data.forEach(function(item) { - that.toggleComplete(item.id, completed, true) - }) - }) - - that._filter() -} - -/** -* Updates the pieces of the page which change depending on the remaining -* number of todos. -*/ -Controller.prototype._updateCount = function() { - var that = this - that.model.getCount(function(todos) { - that.view.render('updateElementCount', todos.active) - that.view.render('clearCompletedButton', { - completed: todos.completed, - visible: todos.completed > 0 - }) - - that.view.render('toggleAll', {checked: todos.completed === todos.total}) - that.view.render('contentBlockVisibility', {visible: todos.total > 0}) - }) -} - -/** -* Re-filters the todo items, based on the active route. -* @param {boolean|undefined} force forces a re-painting of todo items. -*/ -Controller.prototype._filter = function(force) { - var activeRoute = this._activeRoute.charAt(0).toUpperCase() + this._activeRoute.substr(1) - - // Update the elements on the page, which change with each completed todo - this._updateCount() - - // If the last active route isn't "All", or we're switching routes, we - // re-create the todo item elements, calling: - // this.show[All|Active|Completed](); - if (force || this._lastActiveRoute !== 'All' || this._lastActiveRoute !== activeRoute) { - this['show' + activeRoute]() - } - - this._lastActiveRoute = activeRoute -} - -/** -* Simply updates the filter nav's selected states -*/ -Controller.prototype._updateFilterState = function(currentPage) { - // Store a reference to the active route, allowing us to re-filter todo - // items as they are marked complete or incomplete. - this._activeRoute = currentPage - - if (currentPage === '') { - this._activeRoute = 'All' - } - - this._filter() - - this.view.render('setFilter', currentPage) -} diff --git a/src/js/controller.test.js b/src/js/controller.test.js deleted file mode 100644 index 884cafa..0000000 --- a/src/js/controller.test.js +++ /dev/null @@ -1,12 +0,0 @@ -import getModelStub from './model.stub' -import getViewStub from './view.stub' -import Controller from './controller' - -describe('controller', () => { - it('can be created', () => { - const view = getViewStub() - const model = getModelStub() - const controller = new Controller(model, view) - expect(controller).to.exist - }) -}) diff --git a/src/js/helpers.js b/src/js/helpers.js deleted file mode 100755 index 5a558c2..0000000 --- a/src/js/helpers.js +++ /dev/null @@ -1,61 +0,0 @@ -export {qs, qsa, removeClass, $on, $delegate, $parent} - -// Get element(s) by CSS selector: -function qs(selector, scope) { - return (scope || document).querySelector(selector) -} -function qsa(selector, scope) { - return (scope || document).querySelectorAll(selector) -} -function removeClass(el, className) { - if (el.length) { - for (var i = 0; i < el.length; i++) { - removeClass(el[i], className) - } - return - } - if (el.classList) { - el.classList.remove(className) - } else { - el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ') - } -} - -// addEventListener wrapper: -function $on(target, type, callback, useCapture) { - target.addEventListener(type, callback, !!useCapture) -} - -// Attach a handler to event for all elements that match the selector, -// now or in the future, based on a root element -function $delegate(target, selector, type, handler) { - // https://developer.mozilla.org/en-US/docs/Web/Events/blur - var useCapture = type === 'blur' || type === 'focus' - $on(target, type, dispatchEvent, useCapture) - - function dispatchEvent(event) { - var targetElement = event.target - var potentialElements = qsa(selector, target) - var hasMatch = Array.prototype.indexOf.call(potentialElements, targetElement) >= 0 - - if (hasMatch) { - handler.call(targetElement, event) - } - } -} - -// Find the element's parent with the given tag name: -// $parent(qs('a'), 'div'); -function $parent(element, tagName) { - if (!element.parentNode) { - return undefined - } - if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) { - return element.parentNode - } - return $parent(element.parentNode, tagName) -} - -// Allow for looping on nodes by chaining: -// qsa('.foo').forEach(function () {}) -NodeList.prototype.forEach = Array.prototype.forEach diff --git a/src/js/model.js b/src/js/model.js deleted file mode 100755 index 06fa58a..0000000 --- a/src/js/model.js +++ /dev/null @@ -1,116 +0,0 @@ -export default Model - -/** -* Creates a new Model instance and hooks up the storage. -* -* @constructor -* @param {object} storage A reference to the client side storage class -*/ -function Model(storage) { - this.storage = storage -} - -/** -* Creates a new todo model -* -* @param {string} [title] The title of the task -* @param {function} [callback] The callback to fire after the model is created -*/ -Model.prototype.create = function(title, callback) { - title = title || '' - callback = callback || function() { - } - - var newItem = { - title: title.trim(), - completed: false - } - - this.storage.save(newItem, callback) -} - -/** - * Finds and returns a model in storage. If no query is given it'll simply - * return everything. If you pass in a string or number it'll look that up as - * the ID of the model to find. Lastly, you can pass it an object to match against. - * - * @param {string|number|object} [query] A query to match models against - * @param {function} [callback] The callback to fire after the model is found - * - * @example - * model.read(1, func); // Will find the model with an ID of 1 - * model.read('1'); // Same as above - * //Below will find a model with foo equalling bar and hello equalling world. - * model.read({ foo: 'bar', hello: 'world' }); - */ -Model.prototype.read = function(query, callback) { - var queryType = typeof query - callback = callback || function() { - } - - if (queryType === 'function') { - callback = query - return this.storage.findAll(callback) - } else if (queryType === 'string' || queryType === 'number') { - query = parseInt(query, 10) - this.storage.find({id: query}, callback) - } else { - this.storage.find(query, callback) - } - return undefined -} - -/** -* Updates a model by giving it an ID, data to update, and a callback to fire when -* the update is complete. -* -* @param {number} id The id of the model to update -* @param {object} data The properties to update and their new value -* @param {function} callback The callback to fire when the update is complete. -*/ -Model.prototype.update = function(id, data, callback) { - this.storage.save(data, callback, id) -} - -/** -* Removes a model from storage -* -* @param {number} id The ID of the model to remove -* @param {function} callback The callback to fire when the removal is complete. -*/ -Model.prototype.remove = function(id, callback) { - this.storage.remove(id, callback) -} - -/** -* WARNING: Will remove ALL data from storage. -* -* @param {function} callback The callback to fire when the storage is wiped. -*/ -Model.prototype.removeAll = function(callback) { - this.storage.drop(callback) -} - -/** -* Returns a count of all todos -*/ -Model.prototype.getCount = function(callback) { - var todos = { - active: 0, - completed: 0, - total: 0 - } - - this.storage.findAll(function(data) { - data.forEach(function(todo) { - if (todo.completed) { - todos.completed++ - } else { - todos.active++ - } - - todos.total++ - }) - callback(todos) - }) -} diff --git a/src/js/model.stub.js b/src/js/model.stub.js deleted file mode 100644 index ef557af..0000000 --- a/src/js/model.stub.js +++ /dev/null @@ -1,6 +0,0 @@ -export default getModelStub - -function getModelStub() { - return { - } -} diff --git a/src/js/store.js b/src/js/store.js deleted file mode 100755 index d086f8e..0000000 --- a/src/js/store.js +++ /dev/null @@ -1,135 +0,0 @@ -export default Store -/** - * Creates a new client side storage object and will create an empty - * collection if no collection already exists. - * - * @param {string} name The name of our DB we want to use - * @param {function} callback Our fake DB uses callbacks because in - * real life you probably would be making AJAX calls - */ -function Store(name, callback) { - callback = callback || function() { - } - - this._dbName = name - - if (!localStorage[name]) { - var data = { - todos: [] - } - - localStorage[name] = JSON.stringify(data) - } - - callback.call(this, JSON.parse(localStorage[name])) -} - -/** -* Finds items based on a query given as a JS object -* -* @param {object} query The query to match against (i.e. {foo: 'bar'}) -* @param {function} callback The callback to fire when the query has -* completed running -* -* @example -* db.find({foo: 'bar', hello: 'world'}, function (data) { -* // data will return any items that have foo: bar and -* // hello: world in their properties -* }); -*/ -Store.prototype.find = function(query, callback) { - if (!callback) { - return - } - - var todos = JSON.parse(localStorage[this._dbName]).todos - - callback.call(this, todos.filter(function(todo) { - for (var q in query) { - if (query[q] !== todo[q]) { - return false - } - } - return true - })) -} - -/** -* Will retrieve all data from the collection -* -* @param {function} callback The callback to fire upon retrieving data -*/ -Store.prototype.findAll = function(callback) { - callback = callback || function() { - } - callback.call(this, JSON.parse(localStorage[this._dbName]).todos) -} - -/** -* Will save the given data to the DB. If no item exists it will create a new -* item, otherwise it'll simply update an existing item's properties -* -* @param {object} updateData The data to save back into the DB -* @param {function} callback The callback to fire after saving -* @param {number} id An optional param to enter an ID of an item to update -*/ -Store.prototype.save = function(updateData, callback, id) { - var data = JSON.parse(localStorage[this._dbName]) - var todos = data.todos - - callback = callback || function() { - } - - // If an ID was actually given, find the item and update each property - if (id) { - for (var i = 0; i < todos.length; i++) { - if (todos[i].id === id) { - for (var key in updateData) { // eslint-disable-line guard-for-in - todos[i][key] = updateData[key] - } - break - } - } - - localStorage[this._dbName] = JSON.stringify(data) - callback.call(this, JSON.parse(localStorage[this._dbName]).todos) - } else { - // Generate an ID - updateData.id = new Date().getTime() - - todos.push(updateData) - localStorage[this._dbName] = JSON.stringify(data) - callback.call(this, [updateData]) - } -} - -/** -* Will remove an item from the Store based on its ID -* -* @param {number} id The ID of the item you want to remove -* @param {function} callback The callback to fire after saving -*/ -Store.prototype.remove = function(id, callback) { - var data = JSON.parse(localStorage[this._dbName]) - var todos = data.todos - - for (var i = 0; i < todos.length; i++) { - if (todos[i].id === id) { - todos.splice(i, 1) - break - } - } - - localStorage[this._dbName] = JSON.stringify(data) - callback.call(this, JSON.parse(localStorage[this._dbName]).todos) -} - -/** -* Will drop all storage and start fresh -* -* @param {function} callback The callback to fire after dropping the data -*/ -Store.prototype.drop = function(callback) { - localStorage[this._dbName] = JSON.stringify({todos: []}) - callback.call(this, JSON.parse(localStorage[this._dbName]).todos) -} diff --git a/src/js/template.js b/src/js/template.js deleted file mode 100755 index 60c4f6f..0000000 --- a/src/js/template.js +++ /dev/null @@ -1,110 +0,0 @@ -export default Template - -var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - '\'': ''', - '`': '`' -} - -var escapeHtmlChar = function(chr) { - return htmlEscapes[chr] -} - -var reUnescapedHtml = /[&<>"'`]/g -var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source) - -var escape = function(string) { - if (string && reHasUnescapedHtml.test(string)) { - return string.replace(reUnescapedHtml, escapeHtmlChar) - } else { - return string - } -} - -/** -* Sets up defaults for all the Template methods such as a default template -* -* @constructor -*/ -function Template() { - this.defaultTemplate = ` -
  • -
    - - - -
    -
  • - ` -} - -/** - * Creates an
  • HTML string and returns it for placement in your app. - * - * NOTE: In real life you should be using a templating engine such as Mustache - * or Handlebars, however, this is a vanilla JS example. - * - * @param {object} data The object containing keys you want to find in the - * template to replace. - * @returns {string} HTML String of an
  • element - * - * @example - * view.show({ - * id: 1, - * title: "Hello World", - * completed: 0, - * }); - */ -Template.prototype.show = function(data) { - var i, l - var view = '' - - for (i = 0, l = data.length; i < l; i++) { - var template = this.defaultTemplate - var completed = '' - var checked = '' - - if (data[i].completed) { - completed = 'completed' - checked = 'checked' - } - - template = template.replace('{{id}}', data[i].id) - template = template.replace('{{title}}', escape(data[i].title)) - template = template.replace('{{completed}}', completed) - template = template.replace('{{checked}}', checked) - - view = view + template - } - - return view -} - -/** - * Displays a counter of how many to dos are left to complete - * - * @param {number} activeTodos The number of active todos. - * @returns {string} String containing the count - */ -Template.prototype.itemCounter = function(activeTodos) { - var plural = activeTodos === 1 ? '' : 's' - - return '' + activeTodos + ' item' + plural + ' left' -} - -/** - * Updates the text within the "Clear completed" button - * - * @param {[type]} completedTodos The number of completed todos. - * @returns {string} String containing the count - */ -Template.prototype.clearCompletedButton = function(completedTodos) { - if (completedTodos > 0) { - return 'Clear completed' - } else { - return '' - } -} diff --git a/src/js/view.stub.js b/src/js/view.stub.js deleted file mode 100644 index 9c7c25a..0000000 --- a/src/js/view.stub.js +++ /dev/null @@ -1,7 +0,0 @@ -export default getViewStub - -function getViewStub() { - return { - bind: function() {} - } -} diff --git a/src/model.js b/src/model.js new file mode 100644 index 0000000..ec7b934 --- /dev/null +++ b/src/model.js @@ -0,0 +1,122 @@ +(function(window) { + 'use strict' + + /** + * Creates a new Model instance and hooks up the storage. + * + * @constructor + * @param {object} storage A reference to the client side storage class + */ + function Model(storage) { + this.storage = storage + } + + /** + * Creates a new todo model + * + * @param {string} [title] The title of the task + * @param {function} [callback] The callback to fire after the model is created + */ + Model.prototype.create = function(title, callback) { + title = title || '' + callback = callback || function() { + } + + var newItem = { + title: title.trim(), + completed: false + } + + this.storage.save(newItem, callback) + } + + /** + * Finds and returns a model in storage. If no query is given it'll simply + * return everything. If you pass in a string or number it'll look that up as + * the ID of the model to find. Lastly, you can pass it an object to match + * against. + * + * @param {string|number|object} [query] A query to match models against + * @param {function} [callback] The callback to fire after the model is found + * + * @example + * model.read(1, func); // Will find the model with an ID of 1 + * model.read('1'); // Same as above + * //Below will find a model with foo equalling bar and hello equalling world. + * model.read({ foo: 'bar', hello: 'world' }); + */ + Model.prototype.read = function(query, callback) { + var queryType = typeof query + callback = callback || function() { + } + + if (queryType === 'function') { + callback = query + return this.storage.findAll(callback) + } else if (queryType === 'string' || queryType === 'number') { + query = parseInt(query, 10) + this.storage.find({id: query}, callback) + } else { + this.storage.find(query, callback) + } + } + + /** + * Updates a model by giving it an ID, data to update, and a callback to fire when + * the update is complete. + * + * @param {number} id The id of the model to update + * @param {object} data The properties to update and their new value + * @param {function} callback The callback to fire when the update is complete. + */ + Model.prototype.update = function(id, data, callback) { + this.storage.save(data, callback, id) + } + + /** + * Removes a model from storage + * + * @param {number} id The ID of the model to remove + * @param {function} callback The callback to fire when the removal is complete. + */ + Model.prototype.remove = function(id, callback) { + this.storage.remove(id, callback) + } + + /** + * WARNING: Will remove ALL data from storage. + * + * @param {function} callback The callback to fire when the storage is wiped. + */ + Model.prototype.removeAll = function(callback) { + this.storage.drop(callback) + } + + /** + * Returns a count of all todos + */ + Model.prototype.getCount = function(callback) { + var todos = { + active: 0, + completed: 0, + total: 0 + } + + this.storage.findAll(function(data) { + data.forEach(function(todo) { + if (todo.completed) { + todos.completed++ + } else { + todos.active++ + } + + todos.total++ + }) + callback(todos) + }) + } + + // Export to window + window.app = window.app || {} + window.app.Model = Model +})(window) diff --git a/src/store.js b/src/store.js new file mode 100644 index 0000000..7f09d7c --- /dev/null +++ b/src/store.js @@ -0,0 +1,144 @@ +(function(window) { + 'use strict' + + /** + * Creates a new client side storage object and will create an empty + * collection if no collection already exists. + * + * @param {string} name The name of our DB we want to use + * @param {function} callback Our fake DB uses callbacks because in + * real life you probably would be making AJAX calls + */ + function Store(name, callback) { + callback = callback || function() { + } + + this._dbName = name + + if (!localStorage[name]) { + var data = { + todos: [] + } + + localStorage[name] = JSON.stringify(data) + } + + callback.call(this, JSON.parse(localStorage[name])) + } + + /** + * Finds items based on a query given as a JS object + * + * @param {object} query The query to match against (i.e. {foo: 'bar'}) + * @param {function} callback The callback to fire when the query has + * completed running + * + * @example + * db.find({foo: 'bar', hello: 'world'}, function (data) { + * // data will return any items that have foo: bar and + * // hello: world in their properties + * }); + */ + Store.prototype.find = function(query, callback) { + if (!callback) { + return + } + + var todos = JSON.parse(localStorage[this._dbName]).todos + + callback.call(this, todos.filter(function(todo) { + for (var q in query) { + if (query[q] !== todo[q]) { + return false + } + } + return true + })) + } + + /** + * Will retrieve all data from the collection + * + * @param {function} callback The callback to fire upon retrieving data + */ + Store.prototype.findAll = function(callback) { + callback = callback || function() { + } + callback.call(this, JSON.parse(localStorage[this._dbName]).todos) + } + + /** + * Will save the given data to the DB. If no item exists it will create a new + * item, otherwise it'll simply update an existing item's properties + * + * @param {object} updateData The data to save back into the DB + * @param {function} callback The callback to fire after saving + * @param {number} id An optional param to enter an ID of an item to update + */ + Store.prototype.save = function(updateData, callback, id) { + var data = JSON.parse(localStorage[this._dbName]) + var todos = data.todos + + callback = callback || function() { + } + + // If an ID was actually given, find the item and update each property + if (id) { + for (var i = 0; i < todos.length; i++) { + if (todos[i].id === id) { + for (var key in updateData) { + if (updateData.hasOwnProperty(key)) { + todos[i][key] = updateData[key] + } + } + break + } + } + + localStorage[this._dbName] = JSON.stringify(data) + callback.call(this, JSON.parse(localStorage[this._dbName]).todos) + } else { + // Generate an ID + updateData.id = new Date().getTime() + + todos.push(updateData) + localStorage[this._dbName] = JSON.stringify(data) + callback.call(this, [updateData]) + } + } + + /** + * Will remove an item from the Store based on its ID + * + * @param {number} id The ID of the item you want to remove + * @param {function} callback The callback to fire after saving + */ + Store.prototype.remove = function(id, callback) { + var data = JSON.parse(localStorage[this._dbName]) + var todos = data.todos + + for (var i = 0; i < todos.length; i++) { + if (todos[i].id == id) { // eslint-disable-line + todos.splice(i, 1) + break + } + } + + localStorage[this._dbName] = JSON.stringify(data) + callback.call(this, JSON.parse(localStorage[this._dbName]).todos) + } + + /** + * Will drop all storage and start fresh + * + * @param {function} callback The callback to fire after dropping the data + */ + Store.prototype.drop = function(callback) { + localStorage[this._dbName] = JSON.stringify({todos: []}) + callback.call(this, JSON.parse(localStorage[this._dbName]).todos) + } + + // Export to window + window.app = window.app || {} + window.app.Store = Store +})(window) diff --git a/src/template.js b/src/template.js new file mode 100644 index 0000000..15abe7d --- /dev/null +++ b/src/template.js @@ -0,0 +1,112 @@ +(function(window) { + 'use strict' + + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + '\'': ''', + '`': '`' + } + + var escapeHtmlChar = function(chr) { + return htmlEscapes[chr] + } + + var reUnescapedHtml = /[&<>"'`]/g + var reHasUnescapedHtml = new RegExp(reUnescapedHtml.source) + + var escape = function(string) { + return (string && reHasUnescapedHtml.test(string)) ? + string.replace(reUnescapedHtml, escapeHtmlChar) : + string + } + + /** + * Sets up defaults for all the Template methods such as a default template + * + * @constructor + */ + function Template() { + this.defaultTemplate = '
  • ' + + '
    ' + + '' + + '' + + '' + + '
    ' + + '
  • ' + } + + /** + * Creates an
  • HTML string and returns it for placement in your app. + * + * NOTE: In real life you should be using a templating engine such as Mustache + * or Handlebars, however, this is a vanilla JS example. + * + * @param {object} data The object containing keys you want to find in the + * template to replace. + * @returns {string} HTML String of an
  • element + * + * @example + * view.show({ + * id: 1, + * title: "Hello World", + * completed: 0, + * }); + */ + Template.prototype.show = function(data) { + var i, l + var view = '' + + for (i = 0, l = data.length; i < l; i++) { + var template = this.defaultTemplate + var completed = '' + var checked = '' + + if (data[i].completed) { + completed = 'completed' + checked = 'checked' + } + + template = template.replace('{{id}}', data[i].id) + template = template.replace('{{title}}', escape(data[i].title)) + template = template.replace('{{completed}}', completed) + template = template.replace('{{checked}}', checked) + + view = view + template + } + + return view + } + + /** + * Displays a counter of how many to dos are left to complete + * + * @param {number} activeTodos The number of active todos. + * @returns {string} String containing the count + */ + Template.prototype.itemCounter = function(activeTodos) { + var plural = activeTodos === 1 ? '' : 's' + + return '' + activeTodos + ' item' + plural + ' left' + } + + /** + * Updates the text within the "Clear completed" button + * + * @param {[type]} completedTodos The number of completed todos. + * @returns {string} String containing the count + */ + Template.prototype.clearCompletedButton = function(completedTodos) { + if (completedTodos > 0) { + return 'Clear completed' + } else { + return '' + } + } + + // Export to window + window.app = window.app || {} + window.app.Template = Template +})(window) diff --git a/src/js/view.js b/src/view.js old mode 100755 new mode 100644 similarity index 61% rename from src/js/view.js rename to src/view.js index 315ed5c..8908adf --- a/src/js/view.js +++ b/src/view.js @@ -1,17 +1,19 @@ -/* eslint no-invalid-this: 0, complexity:[2, 9] */ -import {qs, qsa, $on, $parent, $delegate} from './helpers' +/*global qs, qsa, $on, $parent, $delegate */ +/* eslint no-invalid-this: 0 */ -/** - * View that abstracts away the browser's DOM completely. - * It has two simple entry points: - * - * - bind(eventName, handler) - * Takes a todo application event and registers the handler - * - render(command, parameterObject) - * Renders the given command with the options - */ -export default class View { - constructor(template) { +(function(window) { + 'use strict' + + /** + * View that abstracts away the browser's DOM completely. + * It has two simple entry points: + * + * - bind(eventName, handler) + * Takes a todo application event and registers the handler + * - render(command, parameterObject) + * Renders the given command with the options + */ + function View(template) { this.template = template this.ENTER_KEY = 13 @@ -26,7 +28,7 @@ export default class View { this.$newTodo = qs('.new-todo') } - _removeItem(id) { + View.prototype._removeItem = function(id) { var elem = qs('[data-id="' + id + '"]') if (elem) { @@ -34,12 +36,47 @@ export default class View { } } - _clearCompletedButton(completedCount, visible) { + View.prototype._clearCompletedButton = function(completedCount, visible) { this.$clearCompleted.innerHTML = this.template.clearCompletedButton(completedCount) this.$clearCompleted.style.display = visible ? 'block' : 'none' } - _editItemDone(id, title) { + View.prototype._setFilter = function(currentPage) { + qs('.filters .selected').className = '' + qs('.filters [href="#/' + currentPage + '"]').className = 'selected' + } + + View.prototype._elementComplete = function(id, completed) { + var listItem = qs('[data-id="' + id + '"]') + + if (!listItem) { + return + } + + listItem.className = completed ? 'completed' : '' + + // In case it was toggled from an event and not by clicking the checkbox + qs('input', listItem).checked = completed + } + + View.prototype._editItem = function(id, title) { + var listItem = qs('[data-id="' + id + '"]') + + if (!listItem) { + return + } + + listItem.className = listItem.className + ' editing' + + var input = document.createElement('input') + input.className = 'edit' + + listItem.appendChild(input) + input.focus() + input.value = title + } + + View.prototype._editItemDone = function(id, title) { var listItem = qs('[data-id="' + id + '"]') if (!listItem) { @@ -56,7 +93,7 @@ export default class View { }) } - render(viewCmd, parameter) { + View.prototype.render = function(viewCmd, parameter) { var that = this var viewCommands = { showEntries: function() { @@ -78,16 +115,16 @@ export default class View { that.$toggleAll.checked = parameter.checked }, setFilter: function() { - _setFilter(parameter) + that._setFilter(parameter) }, clearNewTodo: function() { that.$newTodo.value = '' }, elementComplete: function() { - _elementComplete(parameter.id, parameter.completed) + that._elementComplete(parameter.id, parameter.completed) }, editItem: function() { - _editItem(parameter.id, parameter.title) + that._editItem(parameter.id, parameter.title) }, editItemDone: function() { that._editItemDone(parameter.id, parameter.title) @@ -97,12 +134,17 @@ export default class View { viewCommands[viewCmd]() } - _bindItemEditDone(handler) { + View.prototype._itemId = function(element) { + var li = $parent(element, 'li') + return parseInt(li.dataset.id, 10) + } + + View.prototype._bindItemEditDone = function(handler) { var that = this $delegate(that.$todoList, 'li .edit', 'blur', function() { if (!this.dataset.iscanceled) { handler({ - id: _itemId(this), + id: that._itemId(this), title: this.value }) } @@ -117,19 +159,19 @@ export default class View { }) } - _bindItemEditCancel(handler) { + View.prototype._bindItemEditCancel = function(handler) { var that = this $delegate(that.$todoList, 'li .edit', 'keyup', function(event) { if (event.keyCode === that.ESCAPE_KEY) { this.dataset.iscanceled = true this.blur() - handler({id: _itemId(this)}) + handler({id: that._itemId(this)}) } }) } - bind(event, handler) { + View.prototype.bind = function(event, handler) { // eslint-disable-line var that = this if (event === 'newTodo') { $on(that.$newTodo, 'change', function() { @@ -148,18 +190,18 @@ export default class View { } else if (event === 'itemEdit') { $delegate(that.$todoList, 'li label', 'dblclick', function() { - handler({id: _itemId(this)}) + handler({id: that._itemId(this)}) }) } else if (event === 'itemRemove') { $delegate(that.$todoList, '.destroy', 'click', function() { - handler({id: _itemId(this)}) + handler({id: that._itemId(this)}) }) } else if (event === 'itemToggle') { $delegate(that.$todoList, '.toggle', 'click', function() { handler({ - id: _itemId(this), + id: that._itemId(this), completed: this.checked }) }) @@ -171,44 +213,8 @@ export default class View { that._bindItemEditCancel(handler) } } -} -function _setFilter(currentPage) { - qs('.filters .selected').className = '' - qs('.filters [href="#/' + currentPage + '"]').className = 'selected' -} - -function _elementComplete(id, completed) { - var listItem = qs('[data-id="' + id + '"]') - - if (!listItem) { - return - } - - listItem.className = completed ? 'completed' : '' - - // In case it was toggled from an event and not by clicking the checkbox - qs('input', listItem).checked = completed -} - -function _editItem(id, title) { - var listItem = qs('[data-id="' + id + '"]') - - if (!listItem) { - return - } - - listItem.className = listItem.className + ' editing' - - var input = document.createElement('input') - input.className = 'edit' - - listItem.appendChild(input) - input.focus() - input.value = title -} - -function _itemId(element) { - var li = $parent(element, 'li') - return parseInt(li.dataset.id, 10) -} + // Export to window + window.app = window.app || {} + window.app.View = View +})(window) diff --git a/test/stub/model.js b/test/stub/model.js new file mode 100644 index 0000000..327f25a --- /dev/null +++ b/test/stub/model.js @@ -0,0 +1,8 @@ +(function(window) { + 'use strict' + window.stubs = window.stubs || {} + window.stubs.getModelStub = function getModelStub() { + return { + } + } +})(window) diff --git a/test/stub/view.js b/test/stub/view.js new file mode 100644 index 0000000..510c12a --- /dev/null +++ b/test/stub/view.js @@ -0,0 +1,9 @@ +(function(window) { + 'use strict' + window.stubs = window.stubs || {} + window.stubs.getViewStub = function getViewStub() { + return { + bind: function() {} + } + } +})(window) diff --git a/test/unit/controller.js b/test/unit/controller.js new file mode 100644 index 0000000..1eb5d15 --- /dev/null +++ b/test/unit/controller.js @@ -0,0 +1,17 @@ +'use strict' +var Controller, getModelStub, getViewStub + +describe('controller', function() { + beforeEach(function() { + Controller = window.app.Controller + getModelStub = window.stubs.getModelStub + getViewStub = window.stubs.getViewStub + }) + + it('can be created', function() { + var view = getViewStub() + var model = getModelStub() + var controller = new Controller(model, view) + expect(controller).to.exist + }) +}) diff --git a/webpack.config.js b/webpack.config.js deleted file mode 100644 index bbcb7f3..0000000 --- a/webpack.config.js +++ /dev/null @@ -1,20 +0,0 @@ -const {resolve} = require('path') -module.exports = env => { - return { - entry: './js/app.js', - output: { - filename: 'bundle.js', - path: resolve(__dirname, 'dist'), - pathinfo: !env.prod, - }, - context: resolve(__dirname, 'src'), - devtool: env.prod ? 'source-map' : 'eval', - bail: env.prod, - module: { - loaders: [ - {test: /\.js$/, loader: 'babel!eslint', exclude: /node_modules/}, - {test: /\.css$/, loader: 'style!css'}, - ], - }, - } -}