Permalink
Browse files

Add TweetForm to validate tweet length.

  • Loading branch information...
1 parent e54de1f commit bddc08aaf66f0a645855748dc8fb518c59a0850a @dgraham committed Jun 25, 2012
View
59 app/assets/javascripts/main.js.coffee
@@ -1,13 +1,48 @@
-# Place all the behaviors and hooks related to the matching controller here.
-# All this logic will automatically be available in application.js.
-# You can use CoffeeScript in this file: http://jashkenas.github.com/coffee-script/
+# Monitors the state of the tweet form while the user is typing into it. The
+# form counts down the number of characters remaining. If the user types more
+# than 140 characters, the form displays a warning and disables the submit
+# button.
+class TweetForm
+ MAX = 140
+
+ # Create a new form and start watching the tweet input box for changes.
+ constructor: ->
+ @form = $ '#tweet-form'
+ @input = $ '#tweet-form textarea'
+ @count = $ '#tweet-form .count'
+ @submit = $ '#tweet-form input[type="submit"]'
+ @input.keyup @validate.bind this
+
+ # Returns the number of characters remaining in the composed tweet.
+ remaining: ->
+ MAX - @input.val().length
+
+ # Updates the state of the form with warning indicators and/or disabling the
+ # submit button.
+ #
+ # options - The options Hash of state changes:
+ # :warn - Displays the character counter in red if true.
+ # :disable - Disables the submit button if true.
+ #
+ # Returns nothing.
+ state: (options) ->
+ @count.toggleClass 'warn', options.warn
+ @submit.prop 'disabled', options.disable
+
+ # Changes the state of the form based on the length of the tweet. This should
+ # be called each time the user changes the tweet input.
+ #
+ # Returns nothing.
+ validate: ->
+ left = @remaining()
+ @count.text left
+ if left == MAX
+ @state warn: false, disable: true
+ else if left >= 0
+ @state warn: false, disable: false
+ else if left < 0
+ @state warn: true, disable: true
+
$ ->
- input = $('#tweet-form textarea')
- count = $('#tweet-form .count')
- input.keyup ->
- left = 140 - input.val().length
- if left < 0
- count.addClass 'warn'
- else
- count.removeClass 'warn'
- count.text left
+ # Start watching the form when the page loads.
+ new TweetForm()
View
4 app/assets/stylesheets/main.css.scss
@@ -204,6 +204,10 @@ li.user {
.count.warn {
color: #AC1F23;
}
+
+ :disabled {
+ opacity: 0.35;
+ }
}
#tweet-content {
View
2 app/templates/welcome/index.mustache
@@ -3,7 +3,7 @@
<input type="hidden" name="authenticity_token" value="{{ form_authenticity_token }}"/>
<textarea id="status-text" name="status" placeholder="Compose new Tweet..."></textarea>
<span class="count">140</span>
- <input type="submit" value="Tweet"/>
+ <input disabled type="submit" value="Tweet"/>
</form>
<ul class="tweets">
{{#tweets}}

0 comments on commit bddc08a

Please sign in to comment.