Ryddet kode

This commit is contained in:
Børge Antonsen 2018-10-19 17:23:42 +02:00
parent a4bc8585b7
commit 6af365f425
12 changed files with 291 additions and 452 deletions

View File

@ -1,20 +0,0 @@
.toggle-graph {
float: left;
margin-left: 16px;
cursor: pointer;
position: relative;
z-index: 1;
}
.toggle-graph svg {
height: 20px;
width: 20px;
}
.toggle-graph svg path {
fill: #777;
}
.toggle-graph.active svg path,
.toggle-graph:hover svg path,
.toggle-graph:focus svg path {
fill: black;
}

View File

@ -7,23 +7,21 @@ var Model = require('./model')
var Store = require('./store')
var Template = require('./template')
import {$on} from './helpers'
import {updateTodo} from './todo'
import toggleGraph from './graph'
/**
* 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)
}
export function onLoad() { // eslint-disable-line import/prefer-default-export
updateTodo()
const toggleGraphButton = document.querySelector('.toggle-graph')
$on(
toggleGraphButton,
'click',
() => {
const active = toggleGraph()
if (active) {
toggleGraphButton.classList.add('active')
} else {
toggleGraphButton.classList.remove('active')
}
},
)
module.exports.onLoad = function onLoad() {
var todo = new Todo('todos-vanillajs')
todo.controller.setView(document.location.hash)
helpers.log('view set')
}

View File

@ -1,4 +1,4 @@
export default Controller
module.exports = Controller
/**
* Takes a model and view and acts as the controller between them
@ -110,7 +110,7 @@ Controller.prototype.addItem = function(title) {
Controller.prototype.editItem = function(id) {
var that = this
that.model.read(id, function(data) {
that.view.render('editItem', {id, title: data[0].title})
that.view.render('editItem', {id: id, title: data[0].title})
})
}
@ -120,8 +120,8 @@ Controller.prototype.editItem = function(id) {
Controller.prototype.editItemSave = function(id, title) {
var that = this
if (title.trim()) {
that.model.update(id, {title}, function() {
that.view.render('editItemDone', {id, title})
that.model.update(id, {title: title}, function() {
that.view.render('editItemDone', {id: id, title: title})
})
} else {
that.removeItem(id)
@ -134,7 +134,7 @@ Controller.prototype.editItemSave = function(id, title) {
Controller.prototype.editItemCancel = function(id) {
var that = this
that.model.read(id, function(data) {
that.view.render('editItemDone', {id, title: data[0].title})
that.view.render('editItemDone', {id: id, title: data[0].title})
})
}
@ -179,10 +179,10 @@ Controller.prototype.removeCompletedItems = function() {
*/
Controller.prototype.toggleComplete = function(id, completed, silent) {
var that = this
that.model.update(id, {completed}, function() {
that.model.update(id, {completed: completed}, function() {
that.view.render('elementComplete', {
id,
completed,
id: id,
completed: completed
})
})
@ -230,7 +230,6 @@ Controller.prototype._updateCount = function() {
*/
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()
@ -250,7 +249,6 @@ Controller.prototype._filter = function(force) {
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.
currentPage = currentPage.split('?')[0]
this._activeRoute = currentPage
if (currentPage === '') {

View File

@ -1,53 +0,0 @@
import {subscribe, getTodo} from '../todo'
let graphArea
const unsubscribe = {
store: null,
todo: null,
}
export default toggleGraph
function toggleGraph() {
if (graphArea) {
graphArea.remove()
graphArea = null
unsubscribe.store()
unsubscribe.todo()
return false
} else {
graphArea = document.createElement('div')
document.body.querySelector('.graph-area-container').appendChild(graphArea)
const {storage} = getTodo()
loadAndRenderGraph(graphArea, storage)
updateTodoSubscription()
updateStoreSubscription(storage)
return true
}
}
function updateTodoSubscription() {
if (unsubscribe.todo) {
unsubscribe.todo()
}
unsubscribe.todo = subscribe(function onTodoUpdate() {
const {storage} = getTodo()
updateStoreSubscription(storage)
loadAndRenderGraph(graphArea, storage)
})
}
function updateStoreSubscription(store) {
if (unsubscribe.store) {
unsubscribe.store()
}
unsubscribe.store = store.subscribe(function onStoreUpdate() {
loadAndRenderGraph(graphArea, store)
})
}
function loadAndRenderGraph(node, store) {
System.import('./render').then(({default: renderGraph}) => {
renderGraph(node, store)
})
}

View File

@ -1,44 +0,0 @@
import React from 'react'
import ReactDOM from 'react-dom'
import {PieChart} from 'rd3'
import {chain} from 'lodash'
export default updateGraph
function updateGraph(node, store) {
store.findAll(todos => {
ReactDOM.render(
<Graph todos={todos} />,
node,
)
})
}
function Graph({todos}) {
const data = chain(todos)
.groupBy('completed')
.map((group, complete) => ({
label: complete === 'true' ? 'Complete' : 'Incomplete',
value: Math.round(group.length / todos.length * 10000) / 100
}))
.value()
return (
<div>
There are {todos.length} total todos
<div>
<PieChart
data={data}
width={450}
height={310}
radius={110}
innerRadius={20}
sectorBorderColor="white"
title="Todo Data"
/>
</div>
</div>
)
}
Graph.propTypes = {
todos: React.PropTypes.array,
}

View File

@ -1,4 +1,4 @@
export {qs, qsa, $on, $delegate, $parent, remove}
module.exports = {qs, qsa, log, $on, $delegate, $parent, remove, leftPad}
// Get element(s) by CSS selector:
function qs(selector, scope) {
@ -9,6 +9,12 @@ function qsa(selector, scope) {
return (scope || document).querySelectorAll(selector)
}
function log() {
if (window.console && window.console.log) {
window.console.log.apply(window.console, arguments) // eslint-disable-line
}
}
// addEventListener wrapper:
function $on(target, type, callback, useCapture) {
target.addEventListener(type, callback, !!useCapture)
@ -17,10 +23,6 @@ function $on(target, 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)
@ -30,13 +32,18 @@ function $delegate(target, selector, type, handler) {
handler.call(targetElement, event)
}
}
// https://developer.mozilla.org/en-US/docs/Web/Events/blur
var useCapture = type === 'blur' || type === 'focus'
$on(target, type, dispatchEvent, useCapture)
}
// Find the element's parent with the given tag name:
// $parent(qs('a'), 'div');
function $parent(element, tagName) {
if (!element.parentNode) {
return undefined
return
}
if (element.parentNode.tagName.toLowerCase() === tagName.toLowerCase()) {
return element.parentNode
@ -56,6 +63,16 @@ function remove(array, thing) {
array.splice(index, 1)
}
// pad the left of the given string by the given size with the given character
// leftPad('10', 3, '0') -> 010
function leftPad(str, size, padWith) {
if (size <= str.length) {
return str
} else {
return Array(size - str.length + 1).join(padWith || '0') + str
}
}
// Allow for looping on nodes by chaining:
// qsa('.foo').forEach(function () {})
NodeList.prototype.forEach = Array.prototype.forEach

6
src/index.html Normal file → Executable file
View File

@ -18,11 +18,6 @@
</section>
<footer class="footer">
<span class="todo-count"></span>
<button class="toggle-graph">
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 32 32">
<path d="M14 18v-14c-7.732 0-14 6.268-14 14s6.268 14 14 14 14-6.268 14-14c0-2.251-0.532-4.378-1.476-6.262l-12.524 6.262zM28.524 7.738c-2.299-4.588-7.043-7.738-12.524-7.738v14l12.524-6.262z"></path>
</svg>
</button>
<ul class="filters">
<li>
<a href="#/" class="selected">All</a>
@ -37,7 +32,6 @@
<button class="clear-completed">Clear completed</button>
</footer>
</section>
<section class="graph-area-container"></section>
<footer class="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://twitter.com/oscargodson">Oscar Godson</a></p>

View File

@ -1,4 +1,4 @@
export default Model
module.exports = Model
/**
* Creates a new Model instance and hooks up the storage.
@ -32,7 +32,8 @@ Model.prototype.create = function(title, 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.
* 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
@ -57,7 +58,6 @@ Model.prototype.read = function(query, callback) {
} else {
this.storage.find(query, callback)
}
return undefined
}
/**

View File

@ -1,5 +1,4 @@
import {remove} from './helpers'
export default Store
module.exports = Store
/**
* Creates a new client side storage object and will create an empty
@ -24,16 +23,6 @@ function Store(name, callback) {
}
callback.call(this, JSON.parse(localStorage[name]))
this.subscribers = []
}
Store.prototype.subscribe = function(subscriber) {
this.subscribers.push(subscriber)
return () => remove(this.subscribers, subscriber)
}
Store.prototype._notify = function() {
this.subscribers.forEach(s => s())
}
/**
@ -96,9 +85,11 @@ Store.prototype.save = function(updateData, callback, id) {
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
for (var key in updateData) {
if (updateData.hasOwnProperty(key)) {
todos[i][key] = updateData[key]
}
}
break
}
}
@ -113,7 +104,6 @@ Store.prototype.save = function(updateData, callback, id) {
localStorage[this._dbName] = JSON.stringify(data)
callback.call(this, [updateData])
}
this._notify()
}
/**
@ -127,7 +117,7 @@ Store.prototype.remove = function(id, callback) {
var todos = data.todos
for (var i = 0; i < todos.length; i++) {
if (todos[i].id === id) {
if (todos[i].id == id) { // eslint-disable-line
todos.splice(i, 1)
break
}
@ -135,7 +125,6 @@ Store.prototype.remove = function(id, callback) {
localStorage[this._dbName] = JSON.stringify(data)
callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
this._notify()
}
/**
@ -146,5 +135,4 @@ Store.prototype.remove = function(id, callback) {
Store.prototype.drop = function(callback) {
localStorage[this._dbName] = JSON.stringify({todos: []})
callback.call(this, JSON.parse(localStorage[this._dbName]).todos)
this._notify()
}

View File

@ -1,4 +1,4 @@
export default Template
module.exports = Template
var htmlEscapes = {
'&': '&amp;',
@ -17,11 +17,9 @@ 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
}
return (string && reHasUnescapedHtml.test(string)) ?
string.replace(reUnescapedHtml, escapeHtmlChar) :
string
}
/**
@ -30,15 +28,13 @@ var escape = function(string) {
* @constructor
*/
function Template() {
this.defaultTemplate = `
<li data-id="{{id}}" class="{{completed}}">
<div class="view">
<input class="toggle" type="checkbox" {{checked}} />
<label>{{title}}</label>
<button class="destroy"></button>
</div>
</li>
`
this.defaultTemplate = '<li data-id="{{id}}" class="{{completed}}">' +
'<div class="view">' +
'<input class="toggle" type="checkbox" {{checked}}>' +
'<label>{{title}}</label>' +
'<button class="destroy"></button>' +
'</div>' +
'</li>'
}
/**

View File

@ -1,41 +0,0 @@
import View from './view'
import Controller from './controller'
import Model from './model'
import Store from './store'
import Template from './template'
import {remove} from './helpers'
export {updateTodo, getTodo, subscribe}
let todo
const subscribers = []
/**
* 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 updateTodo() {
todo = new Todo('todos-vanillajs')
todo.controller.setView(document.location.hash)
subscribers.forEach(s => s())
}
function getTodo() {
return todo
}
function subscribe(cb) {
subscribers.push(cb)
return function unsubscribe() {
remove(subscribers, cb)
}
}

View File

@ -1,5 +1,13 @@
/* eslint no-invalid-this: 0, complexity:[2, 9] */
import {qs, qsa, $on, $parent, $delegate} from './helpers'
/* eslint no-invalid-this: 0 */
var helpers = require('./helpers')
var qs = helpers.qs
var qsa = helpers.qsa
var $on = helpers.$on
var $parent = helpers.$parent
var $delegate = helpers.$delegate
module.exports = View
/**
* View that abstracts away the browser's DOM completely.
@ -10,8 +18,7 @@ import {qs, qsa, $on, $parent, $delegate} from './helpers'
* - render(command, parameterObject)
* Renders the given command with the options
*/
export default class View {
constructor(template) {
function View(template) {
this.template = template
this.ENTER_KEY = 13
@ -26,7 +33,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 +41,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 +98,7 @@ export default class View {
})
}
render(viewCmd, parameter) {
View.prototype.render = function(viewCmd, parameter) {
var that = this
var viewCommands = {
showEntries: function() {
@ -78,16 +120,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 +139,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 +164,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 +195,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 +218,3 @@ 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)
}