Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                h1.site-name To Do! Not again!
#app
              
            
!

CSS

              
                @import url(http://weloveiconfonts.com/api/?family=entypo);

@mixin tag-ui() {
  display: inline-block;
  height: 16px;
  padding: 0 8px;
  margin-right: 8px;
  border-radius: 4px;
  
  font-size: 12px;
  
  color: #999;
  background: #eee;
  cursor: pointer;
}

* {
  box-sizing: border-box;
}

body {
  min-width: 320px;
}

.site-name {
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
  padding: 24px 0;
  
  transition: padding 300ms ease-in;
  
  @media (max-width: 480px) {
    padding: 24px 12px;
  }
}

#app {
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
  
  transition: padding 300ms ease-in;
  
  @media (max-width: 480px) {
    padding: 0 12px;
  }
}

.editbox {
  display: flex;
  width: 100%;
}

.editbox__textbox {
  flex: 1 100%;
  padding: 5px;
}

.editbox__button-add {
  padding: 5px 20px;
}

.tagbox {
  width: 100%;
  padding: 8px 0;
}

.tagbox__item {
  @include tag-ui();
  
  &:before {
    content: "";
    display: inline-block;
    height: 16px;
    width: 16px;
    margin-right: 4px;
    
    text-align: center;
    vertical-align: middle;
    
    font-family: "entypo", san-serif;
    line-height: 16px;
  }
  
  &.is-checked {
    background-color: #09d;
    color: white;
  }
  
  &.is-home:before {
    content: "\2302";
  }
  
  &.is-work:before {
    content: "\e736";
  }
  
  &.is-star:before {
    content: "\2665";
  }
}
  
.todo-list {
  padding: 0px;
  list-style: lower-alpha;
  
  counter-reset: todoitems 0;
}

.todo-list__message {
  font-size: 36px;
  font-weight: bold;
  text-align: center;
}

.todo-list__item {
  display: flex;
  align-items: center;
  width: 100%;
  
  padding: 5px;
  border-bottom: 1px dashed #ccc;
  
}

.todo-item__checkmark {
  position: relative;
  
  display: block;
  height: 32px;
  width: 32px;
  outline: 1px solid #ccc;
  outline-offset: -8px;
  
  font-size: 32px;
  line-height: 32px;
  
  cursor: pointer;
  
  &:after {
    position: absolute;
    display: block;
    
    width: 32px;
    height: 32px;
  }
  
  .is-checked & {
    outline: none;
  }
  
  .is-checked &:after {
    content: "\2714";
  }
}
.todo-item__summary {
  display: block;
  flex: 1 50%;
  
  padding: 0px 5px;
  
  .is-checked & {
    color: #ccc;
    text-decoration: line-through;
  }
}
.todo-item__tags {
  flex: 1 50%;
}
.todo-item__remove {
  
}

.todo-tags {
  position: relative;
  outline: 0;
}
.todo-tags__label {
  padding: 4px;
  color: #ccc;
  font-size: 12px;

  .is-tagged & {
    color: #333;
  }
  
  .is-editing & {
    background-color: white;
  }
}
.todo-tags__value {
  @include tag-ui();
  background-color: #09d;
  color: white;
  
  &:before {
    content: "";
    display: inline-block;
    height: 16px;
    width: 16px;
    margin-right: 4px;
    
    text-align: center;
    vertical-align: middle;
    
    font-family: "entypo", san-serif;
    line-height: 16px;
  }
  
  &.is-home:before {
    content: "\2302";
  }
  
  &.is-work:before {
    content: "\e736";
  }
  
  &.is-star:before {
    content: "\2665";
  }
}
.todo-tags__dropdown {
  display: none;
  position: absolute;
  top: 100%;
  margin-top: 4px;
  width: 115px;
  z-index: 1000; // Popup layer
  
  background: white;
  padding: 0;
  
  list-style: none;
  
  .is-editing > & {
    display: block;

    box-shadow: 0 3px 4px #ccc;
  }
}

.todo-tags__item {
  padding: 4px 16px;
  
  cursor: pointer;
  
  &:hover {
    background-color: #eee;
  }
}
              
            
!

JS

              
                // Utilities
function cx(classNames) {
  var names = '';

  if (typeof classNames == 'object') {
    for (var name in classNames) {
      if (!classNames.hasOwnProperty(name) || !classNames[name]) {
        continue;
      }
      names += name + ' ';
    }
  } else {
    for (var i = 0; i < arguments.length; i++) {
      // We should technically exclude 0 too, but for the sake of backward
      // compat we'll keep it (for now)
      if (arguments[i] == null) {
        continue;
      }
      names += arguments[i] + ' ';
    }
  }

  return names.trim();
}
var TODO_ID = Date.now();
// Data Model
var ToDo = Immutable.Record({ id: 0, summary: '', status: 'open', tags: []});
function newToDo (summary) {
  return new ToDo({ id: TODO_ID++, summary: summary });
};

// Actions and Store
var actionAdd = Reflux.createAction();
var actionRemove = Reflux.createAction();
var actionCheck = Reflux.createAction();
var actionUncheck = Reflux.createAction();
var actionTag = Reflux.createAction();
var actionFilter = Reflux.createAction();

var storeTodos = Reflux.createStore({
  init () {
    this.filteringTags = Immutable.fromJS([]);
    this.items = [];
    this.filtered = this.items;
    
    console.log('Opening a new database');
    var request = indexedDB.open('todos', 2);
    request.onsuccess = (e)=> {
      this.db = e.target.result;
      
      console.log('TODOs database has been created under the name "todos".');
      
      var objectStore = this.db.transaction('todos').objectStore('todos');
      objectStore.openCursor().onsuccess = this.onCursor;
    };
    request.onerror = (e) => {
      console.error('An error has occurred. ERR: ' + e.message);
    };
    request.onupgradeneeded = (e) => {
      var db = e.target.result;
      console.log('Creating object store "todos"');

      var objectStore = db.createObjectStore('todos', { keyPath: 'id' });
      objectStore.transaction.oncomplete = ()=>{
        console.info('Object store has been created');
      };
    };
        
    this.listenTo(actionAdd, this.onActionAdd);
    this.listenTo(actionRemove, this.onActionRemove);
    this.listenTo(actionCheck, this.onActionCheck);
    this.listenTo(actionUncheck, this.onActionUncheck);
    this.listenTo(actionTag, this.onActionTag);
    
    this.listenTo(actionFilter, this.onActionFilter);
  },
  onCursor (e) {
    var cursor = e.target.result;
    
    if (!cursor) {
      // We have no more data
      console.info('No more items');
      this.trigger(this.items);
      
      return;
    }
    
    var todo = cursor.value;
    console.log('Loading item: ', todo.summary);
    this.items.push(Immutable.fromJS(todo));
    
    cursor.continue();
  },
  onActionAdd (data) {
    var todo = data;
    console.log('Action is being handled: %s', todo.summary);
    
    var tx = this.db.transaction(['todos'], 'readwrite');
    var request = tx.objectStore('todos').add(todo.toJS());
    request.onsuccess = (e) => {
      var newID = e.target.result;
      console.info('Done added new todo record %s', newID);
      
      this.items.unshift(todo);
      
      console.log('Synchronizing UI...');
      this.triggerAsync(this.filtered);
    };
  },
  onActionRemove (data) {
    var todo = data;
    console.assert(this.items, 'onActionRemove (data)');
    
    var index = this.items.indexOf(todo);
    console.log('Removing todo item "%s" at index %s', todo.summary, index);
    
    var request = this.db.transaction(['todos'], "readwrite")
                .objectStore('todos')
                .delete(todo.get('id'));
    request.onsuccess = (e) => {
      this.items.splice(index,1);
      this.triggerAsync(this.filtered);
    };
  },
  onActionCheck (data) {
    var todo = data;

    console.log('Store: Checking item as "done": %s = %s', todo.get('id'), todo.get('summary'));
    var objectStore = this.db.transaction(['todos'], "readwrite")
        .objectStore('todos');
    
    var updatedToDo = todo.update('status', status=>'done');
    var request = objectStore.put(updatedToDo.toJS());
    
    request.onsuccess = (e) => {
      console.log('Store: Backend has been updated.');
      var index = this.items.indexOf(todo);
      
      this.items.splice(index, 1, updatedToDo);
      this.trigger(this.filtered);
    };
  },
  onActionUncheck (data) {
    var todo = data;
    
    console.log('Store: Checking item as "open": %s = %s', todo.get('id'), todo.get('summary'));
    var objectStore = this.db.transaction(['todos'], "readwrite")
        .objectStore('todos');
    
    var updatedToDo = todo.update('status', status=>'open');
    var request = objectStore.put(updatedToDo.toJS());
    
    request.onsuccess = (e) => {
      console.log('Store: Backend has been updated.');
      var index = this.items.indexOf(todo);
      
      this.items.splice(index, 1, updatedToDo);
      this.trigger(this.filtered);
    };
  },
  onActionTag (todo, tags) {
    console.log('Store: Updating item\'s tags as "%o" for %s', tags, todo.get('id'));
    var objectStore = this.db.transaction(['todos'], "readwrite")
        .objectStore('todos');
    
    var updatedToDo = todo.update('tags', value=>tags);
    console.log('Updated: ', updatedToDo.toJS());
    var request = objectStore.put(updatedToDo.toJS());
    
    request.onsuccess = (e) => {
      console.log('Store: Backend has been updated.');
      var index = this.items.indexOf(todo);
      
      this.items[index] = updatedToDo;
      console.log('Item\'s new tags: ', tags);
      
      var shouldKeepInFiltered = false;
      if (this.filteringTags.size===0) {  // There is no filtering
        shouldKeepInFiltered = true;  // No effect here! Leave here for clarity
      }
      else {
        for (let tag of tags) {
          if (this.filteringTags.includes(tag)) {
            shouldKeepInFiltered = true;
            break;
          }  
        }  
        // TODO Improve this iteration
        if (!shouldKeepInFiltered) {
          var filtered = this.items.filter((item) => {
            for (let tag of this.filteringTags) {
              if (item.get('tags').indexOf(tag)!==-1) {
                return true;
              }
            }

            return false;
          });

          this.filtered = filtered;
          this.triggerAsync(this.filtered);
        }
      }
    };
  },
  onActionFilter (data) {
    console.log('Store: Filtering by tags: %o', data);
    
    var tags = data;
    if (!tags.length) {
      this.filtered = this.items;
      this.triggerAsync(this.filtered);
      return;
    }
    this.filteringTags = Immutable.fromJS(tags);
    console.log('Updated filtering tags: ', this.filteringTags);
    
    var filtered = this.items.filter((item) => {
      for (let tag of tags) {
        if (item.get('tags').indexOf(tag)!==-1) {
          return true;
        }
      }
      
      return false;
    });

    this.filtered = filtered;
    this.triggerAsync(this.filtered);
  }
});
// Views
var EditBox = React.createClass({
  getInitialState () {
    return {
      text: ''
    }
  },
  handleChange (event) {
    this.setState({
      text: event.target.value
    });
  },
  render () {
    return (
      <div className='editbox'>
        <input ref='taskSummary' placeholder='Default value' value={this.state.text} onChange={this.handleChange} className='editbox__textbox' onKeyUp={this.onTextKeyup} />
        <button className='editbox__button-add' onClick={this.onAddClicked}>Add</button>
      </div>
    )
  },
  doAdd () {
    var taskSummary = this.refs.taskSummary.getDOMNode().value;
    if (!taskSummary) {
      return;
    }
    
    var todo = newToDo(taskSummary);
    actionAdd(todo);
    
    this.refs.taskSummary.getDOMNode().value = null;
  },
  onTextKeyup (e) {
    if (e.keyCode !== 13) return;
    
    this.doAdd();
  },
  onAddClicked () {
    this.doAdd();
  }
});

var TagBox = React.createClass({
  statics: {
    tags: [
      { value: 'home', label: 'Home' },
      { value: 'work', label: 'Work' },
      { value: 'star', label: 'Star' }
    ]
  },
  getInitialState () {
    return {
      tags: []
    };
  },
  render () {
    var selectedTags = this.state.tags;
    
    var tagList = TagBox.tags.map((tag) => {
      var classes = cx({
        'tagbox__item': true,
        'is-checked': selectedTags.indexOf(tag.value) !== -1,
        ['is-' + tag.value]: true
      });
      return (
        <span className={classes} 
              onClick={this.toggleFilter.bind(null, tag.value)}
              key={tag.value}>
          {tag.label}
        </span>
      );
    });
    
    return (
      <div className="tagbox">
        {tagList}
      </div>
    );
  },
  toggleFilter (tag) {
    console.log('Adding more tag to the filter: %s', tag);
    
    var tags = this.state.tags;
    var index = tags.indexOf(tag);
    
    if (index === -1) {
      tags.push(tag);
    } else {
      tags.splice(index, 1);
    }
    
    console.log('Filtering by tags: %o', tags);
    this.setState({
      tags: tags
    });
    
    actionFilter(tags);
  }
});

var Tags = React.createClass({
  statics: {
    tags: [
      { value: 'home', label: 'Home' },
      { value: 'work', label: 'Work' },
      { value: 'star', label: 'Star' }
    ]
  },
  getInitialState () {
    return {
      tags: Immutable.fromJS(this.props.tags || []),
      editing: false
    };
  },
  render () {
    var classes = cx({
      'todo-tags': true,
      [this.props.className]: true,
      'is-editing': this.state.editing,
      'is-tagged': this.state.tags.size > 0
    });
    
    var dropdown;
    
    if (this.state.editing) {
      dropdown = (
        <ul className="todo-tags__dropdown">
        {Tags.tags.map(tag => <li key={tag.value} className="todo-tags__item" onClick={this.toggleTag.bind(this, tag.value)}>{tag.label}</li>)}
        </ul>
      );  
    }
    
    return (
      <div className={classes} onClick={this.toggleEdit} onBlur={this.endEdit} tabIndex="0">
        <span className="todo-tags__label">
          {this.state.tags.size===0?'tags':this.state.tags.map(tag => {
            var classes = cx({
              'todo-tags__value': true,
              ['is-' + tag]: true
            });

            return (<span className={classes}>{tag}</span>);
          })}
        </span>
        {dropdown}
      </div>
    );
  },
  toggleEdit (e) {
    e.stopPropagation();

    if (this.state.editing) {
      this.endEdit();
    } else {
      this.beginEdit();
    }
  },
  beginEdit () {
    if (this.state.editing) {
      return;
    }
    
    this.setState({'editing': true});
    Tags.activeID = null; //this.getID();
  },
  endEdit () {
    console.log('Ending edit...');
    
    if (Tags.active && Tags.active === this) {
      Tags.active = null;
    }
    
    this.setState({'editing': false});
  },
  toggleTag (tag, e) {
    e.stopPropagation();
    
    var tags = this.state.tags;
    if (!tags) {
      console.assert(!tags, 'Tags is expected');
      return;
    }
    
    var index = tags.indexOf(tag);
    if (index === -1) {
      tags = tags.push(tag);
    } else {
      tags = tags.delete(index);
    }
    
    this.setState({
      tags: tags
    });
    
    var onToggleTag = this.props.onToggleTag;
    if (!onToggleTag) {
      console.info('No handler for onToggleTag');
      return;
    }
    
    onToggleTag(tags);
    this.endEdit();
  }
})

var ToDoList = React.createClass({
  getInitialState () {
    return {
      items: Immutable.fromJS(storeTodos.items)
    };
  },
  componentDidMount () {
    this.stopListening = storeTodos.listen((data)=>{
      this.setState({
        items: Immutable.fromJS(data) // Freeze the object state
      })
    });
  },
  componentWillUnmount () {
    this.stopListening();
  },
  render () {
    var content;
    if (!this.state.items.size) {
      content = (
        <div className='todo-list'>
          <p className="todo-list__message">
            You have nothing to do!
          </p>
        </div>
      );
    } 
    else {
      let items = (this.state.items.map((item)=>{
        var boundRemovedClicked = this.onRemovedDelegate.bind(this, item);
        var boundItemClicked = item.get('status')==='done'?this.onUncheckDelegate.bind(this, item):this.onCheckDelegate.bind(this, item);
        var boundItemTag = this.onTagDelegate.bind(this, item);

        var classes = cx({
          'todo-list__item todo-item': true,
          'is-checked': item.get('status')==='done'
        });

        return (
          <li className={classes} key={item.get('id')}>
            <span className='todo-item__checkmark' onClick={boundItemClicked}></span>
            <span className='todo-item__summary'>{item.get('summary')}</span>
            <Tags className='todo-item__tags' tags={item.get('tags')} editable='true' onToggleTag={boundItemTag} />
            <button className='todo-item__remove' onClick={boundRemovedClicked}>&#10008;</button>
          </li>
        );
      }));
      //*/
      content = (
        <ul className='todo-list'>
        {items}
        </ul>
      );
    }

    return content;
  },
  onCheckDelegate (item) {
    actionCheck(item);
  },
  onUncheckDelegate (item) {
    actionUncheck(item);
  },
  onRemovedDelegate (item) {
    actionRemove(item);
  },
  onTagDelegate (item, tags) {
    console.log('Tags applied to item %s: %o', item.get('summary'), tags);
    actionTag(item, tags);
  }
});

React.render(
  <div>
    <EditBox />
    <TagBox />
    <ToDoList />
  </div>, 
  document.querySelector('#app'));
              
            
!
999px

Console