/** @jsx React.DOM */ 'use strict'; var React = require('react'); var ContentEditableLabel = React.createClass({ propTypes: { tag: React.PropTypes.func, className: React.PropTypes.string, onChange: React.PropTypes.func, onComplete: React.PropTypes.func, initialText: React.PropTypes.string, autofocus: React.PropTypes.bool }, getDefaultProps: function() { return { autofocus: true, tag: React.DOM.span }; }, componentDidMount:function() { if(this.props.autofocus) { this.clearAndFocus(); } this.cancelled = false; }, shouldComponentUpdate: function(nextProps){ return nextProps.initialText !== this.getText(); }, clearAndFocus: function() { var elem = this.refs.element.getDOMNode(); elem.focus(); elem.textContent = ''; }, getText: function() { if(this.cancelled) return ''; return this.refs.element.getDOMNode().textContent; }, handleClick: function() { if(!this.props.autofocus) { this.clearAndFocus(); } }, handleChange: function(){ var text = this.getText(); if(this.props.onChange && text !== this.previousText) { this.props.onChange(text); } this.previousText = text; }, handleKeyUp: function(e) { if(e.which === 13 || e.which === 27) { this.cancelled = (e.which === 27); this.refs.element.getDOMNode().blur(); } }, handleBlur: function() { this.props.onComplete(this.getText()); this.cancelled = false; }, render: function(){ return (this.props.tag({ ref: 'element', className: this.props.className, onClick: this.handleClick, onInput: this.handleChange, onKeyUp: this.handleKeyUp, onBlur: this.handleBlur, contentEditable: 'true' }, this.props.initialText)); } }); module.exports = ContentEditableLabel;