-
Notifications
You must be signed in to change notification settings - Fork 2
/
todoitem.js
118 lines (107 loc) · 2.37 KB
/
todoitem.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
'use strict';
var dom = require('poochie/dom');
var observable = require('poochie/observable');
var prelude = require('./prelude');
var ESC_KEY = 27;
function todoItemClass(completed, readMode) {
var classes = [];
if (completed) {
classes.push('completed');
}
if (!readMode) {
classes.push('editing');
}
return classes.join(' ');
}
function readModeTodoItem(params) {
return dom.element({
name: 'div',
attributes: {className: 'view'},
handlers: {
'dblclick': function onDblClick() { params.readMode.set(false); }
},
contents: [
dom.element({
name: 'input',
attributes: {
className: 'toggle',
type: 'checkbox',
checked: params.completed
},
handlers: {
click: function(evt) { params.completed.set(evt.target.checked); }
}
}),
dom.element({
name: 'label',
contents: params.text.map(prelude.singleton)
}),
dom.element({
name: 'button',
attributes: {className: 'destroy'},
handlers: {
'click': params.handlers.remove
}
})
]
});
}
function writeModeTodoItem(params) {
function onChange(evt) {
if (params.readMode.get()) {
return;
}
var value = evt.target.value.trim();
if (value === '') {
params.handlers.remove(evt);
} else {
params.text.set(value);
}
params.readMode.set(true);
}
function onKeyUp(evt) {
if (evt.keyCode === ESC_KEY) {
evt.target.value = params.text.get();
params.readMode.set(true);
}
}
return dom.element({
name: 'input',
focus: params.readMode.map(prelude.not),
attributes: {className: 'edit', value: params.text},
handlers: {
'change': onChange,
'blur': onChange,
'keyup': onKeyUp
}
});
}
function todoItemImpl(params) {
var handlers = {};
handlers.remove = params.handlers && params.handlers.remove || function() {};
var ps = {
text: params.text,
completed: params.completed,
readMode: observable.publisher(true),
handlers: handlers
};
return dom.element({
name: 'li',
attributes: {
className: observable.subscriber([ps.completed, ps.readMode], todoItemClass)
},
contents: [
readModeTodoItem(ps),
writeModeTodoItem(ps)
]
});
}
function todoItem(params) {
var e = {text: params.text, completed: params.completed, handlers: params.handlers};
e.render = function() { return todoItemImpl(e); };
return e;
}
module.exports = {
todoItem: todoItem,
todoItemImpl: todoItemImpl
};