Browse files

Initial attempts to use ExtendedDocument

  • Loading branch information...
1 parent d6ffcc5 commit 696f138ab2ec13d2cc211816932e2199c2ed1843 @topfunky committed Apr 19, 2009
Showing with 16,742 additions and 724 deletions.
  1. +0 −6 app/controllers/application.rb
  2. +16 −0 app/controllers/application_controller.rb
  3. +10 −10 app/controllers/notes_controller.rb
  4. +1 −1 app/helpers/notes_helper.rb
  5. +103 −10 app/models/note.rb
  6. +5 −5 app/views/notes/_form.html.erb
  7. +6 −4 app/views/notes/index.html.erb
  8. +4 −4 app/views/notes/show.html.erb
  9. +5 −5 config/boot.rb
  10. +14 −6 config/environment.rb
  11. +3 −1 config/environments/development.rb
  12. +165 −0 lib/tasks/rspec.rake
  13. +72 −72 public/javascripts/controls.js
  14. +165 −164 public/javascripts/dragdrop.js
  15. +173 −165 public/javascripts/effects.js
  16. +362 −267 public/javascripts/prototype.js
  17. +6 −0 script/autospec
  18. +10 −0 script/spec
  19. +9 −0 script/spec_server
  20. +10 −0 spec/controllers/notes_controller_spec.rb
  21. +11 −0 spec/helpers/notes_helper_spec.rb
  22. +2 −0 spec/rcov.opts
  23. +4 −0 spec/spec.opts
  24. +47 −0 spec/spec_helper.rb
  25. +1 −4 test/functional/notes_controller_test.rb
  26. +200 −0 vendor/gems/couchrest-0.23/.specification
  27. +176 −0 vendor/gems/couchrest-0.23/LICENSE
  28. +93 −0 vendor/gems/couchrest-0.23/README.md
  29. +75 −0 vendor/gems/couchrest-0.23/Rakefile
  30. +18 −0 vendor/gems/couchrest-0.23/THANKS.md
  31. +144 −0 vendor/gems/couchrest-0.23/examples/model/example.rb
  32. +38 −0 vendor/gems/couchrest-0.23/examples/word_count/markov
  33. +3 −0 vendor/gems/couchrest-0.23/examples/word_count/views/books/chunked-map.js
  34. +1 −0 vendor/gems/couchrest-0.23/examples/word_count/views/books/united-map.js
  35. +6 −0 vendor/gems/couchrest-0.23/examples/word_count/views/markov/chain-map.js
  36. +7 −0 vendor/gems/couchrest-0.23/examples/word_count/views/markov/chain-reduce.js
  37. +6 −0 vendor/gems/couchrest-0.23/examples/word_count/views/word_count/count-map.js
  38. +3 −0 vendor/gems/couchrest-0.23/examples/word_count/views/word_count/count-reduce.js
  39. +46 −0 vendor/gems/couchrest-0.23/examples/word_count/word_count.rb
  40. +40 −0 vendor/gems/couchrest-0.23/examples/word_count/word_count_query.rb
  41. +26 −0 vendor/gems/couchrest-0.23/examples/word_count/word_count_views.rb
  42. +198 −0 vendor/gems/couchrest-0.23/lib/couchrest.rb
  43. +71 −0 vendor/gems/couchrest-0.23/lib/couchrest/commands/generate.rb
  44. +103 −0 vendor/gems/couchrest-0.23/lib/couchrest/commands/push.rb
  45. +298 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/database.rb
  46. +79 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/design.rb
  47. +87 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/document.rb
  48. +16 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/response.rb
  49. +88 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/server.rb
  50. +4 −0 vendor/gems/couchrest-0.23/lib/couchrest/core/view.rb
  51. +103 −0 vendor/gems/couchrest-0.23/lib/couchrest/helper/pager.rb
  52. +44 −0 vendor/gems/couchrest-0.23/lib/couchrest/helper/streamer.rb
  53. +51 −0 vendor/gems/couchrest-0.23/lib/couchrest/helper/upgrade.rb
  54. +4 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins.rb
  55. +31 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/attachments.rb
  56. +483 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/callbacks.rb
  57. +108 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/class_proxy.rb
  58. +90 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/design_doc.rb
  59. +44 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/document_queries.rb
  60. +68 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/extended_attachments.rb
  61. +7 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/extended_document_mixins.rb
  62. +129 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/properties.rb
  63. +242 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/validation.rb
  64. +169 −0 vendor/gems/couchrest-0.23/lib/couchrest/mixins/views.rb
  65. +113 −0 vendor/gems/couchrest-0.23/lib/couchrest/monkeypatches.rb
  66. +28 −0 vendor/gems/couchrest-0.23/lib/couchrest/more/casted_model.rb
  67. +215 −0 vendor/gems/couchrest-0.23/lib/couchrest/more/extended_document.rb
  68. +40 −0 vendor/gems/couchrest-0.23/lib/couchrest/more/property.rb
  69. +42 −0 vendor/gems/couchrest-0.23/lib/couchrest/support/blank.rb
  70. +176 −0 vendor/gems/couchrest-0.23/lib/couchrest/support/class.rb
  71. +163 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/auto_validate.rb
  72. +78 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/contextual_validators.rb
  73. +118 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validation_errors.rb
  74. +74 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/absent_field_validator.rb
  75. +99 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/confirmation_validator.rb
  76. +117 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/format_validator.rb
  77. +66 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/formats/email.rb
  78. +43 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/formats/url.rb
  79. +120 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/generic_validator.rb
  80. +134 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/length_validator.rb
  81. +89 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/method_validator.rb
  82. +104 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/numeric_validator.rb
  83. +109 −0 vendor/gems/couchrest-0.23/lib/couchrest/validation/validators/required_field_validator.rb
  84. +201 −0 vendor/gems/couchrest-0.23/spec/couchrest/core/couchrest_spec.rb
  85. +694 −0 vendor/gems/couchrest-0.23/spec/couchrest/core/database_spec.rb
  86. +138 −0 vendor/gems/couchrest-0.23/spec/couchrest/core/design_spec.rb
  87. +267 −0 vendor/gems/couchrest-0.23/spec/couchrest/core/document_spec.rb
  88. +35 −0 vendor/gems/couchrest-0.23/spec/couchrest/core/server_spec.rb
  89. +122 −0 vendor/gems/couchrest-0.23/spec/couchrest/helpers/pager_spec.rb
  90. +23 −0 vendor/gems/couchrest-0.23/spec/couchrest/helpers/streamer_spec.rb
  91. +40 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/casted_extended_doc_spec.rb
  92. +98 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/casted_model_spec.rb
  93. +130 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/extended_doc_attachment_spec.rb
  94. +509 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/extended_doc_spec.rb
  95. +98 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/extended_doc_subclass_spec.rb
  96. +355 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/extended_doc_view_spec.rb
  97. +136 −0 vendor/gems/couchrest-0.23/spec/couchrest/more/property_spec.rb
  98. +3 −0 vendor/gems/couchrest-0.23/spec/fixtures/attachments/README
  99. BIN vendor/gems/couchrest-0.23/spec/fixtures/attachments/couchdb.png
  100. +11 −0 vendor/gems/couchrest-0.23/spec/fixtures/attachments/test.html
  101. +34 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/article.rb
  102. +20 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/card.rb
  103. +14 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/course.rb
  104. +6 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/event.rb
  105. +17 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/invoice.rb
  106. +8 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/person.rb
  107. +6 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/question.rb
  108. +12 −0 vendor/gems/couchrest-0.23/spec/fixtures/more/service.rb
  109. +3 −0 vendor/gems/couchrest-0.23/spec/fixtures/views/lib.js
  110. +3 −0 vendor/gems/couchrest-0.23/spec/fixtures/views/test_view/lib.js
  111. +4 −0 vendor/gems/couchrest-0.23/spec/fixtures/views/test_view/only-map.js
  112. +3 −0 vendor/gems/couchrest-0.23/spec/fixtures/views/test_view/test-map.js
  113. +3 −0 vendor/gems/couchrest-0.23/spec/fixtures/views/test_view/test-reduce.js
  114. +6 −0 vendor/gems/couchrest-0.23/spec/spec.opts
  115. +26 −0 vendor/gems/couchrest-0.23/spec/spec_helper.rb
  116. +27 −0 vendor/gems/couchrest-0.23/utils/remap.rb
  117. +30 −0 vendor/gems/couchrest-0.23/utils/subset.rb
  118. +69 −0 vendor/gems/mime-types-1.15/.specification
  119. +101 −0 vendor/gems/mime-types-1.15/ChangeLog
  120. +16 −0 vendor/gems/mime-types-1.15/Install
  121. +18 −0 vendor/gems/mime-types-1.15/LICENCE
  122. +30 −0 vendor/gems/mime-types-1.15/README
  123. +208 −0 vendor/gems/mime-types-1.15/Rakefile
  124. +1,558 −0 vendor/gems/mime-types-1.15/lib/mime/types.rb
  125. +46 −0 vendor/gems/mime-types-1.15/pre-setup.rb
  126. +1,366 −0 vendor/gems/mime-types-1.15/setup.rb
  127. +275 −0 vendor/gems/mime-types-1.15/tests/tc_mime_type.rb
  128. +77 −0 vendor/gems/mime-types-1.15/tests/tc_mime_types.rb
  129. +18 −0 vendor/gems/mime-types-1.15/tests/testall.rb
  130. +61 −0 vendor/gems/rest-client-0.6/.specification
  131. +84 −0 vendor/gems/rest-client-0.6/Rakefile
  132. +65 −0 vendor/gems/rest-client-0.6/bin/restclient
  133. +75 −0 vendor/gems/rest-client-0.6/lib/request_errors.rb
  134. +103 −0 vendor/gems/rest-client-0.6/lib/resource.rb
  135. +146 −0 vendor/gems/rest-client-0.6/lib/rest_client.rb
  136. +4 −0 vendor/gems/rest-client-0.6/spec/base.rb
  137. +44 −0 vendor/gems/rest-client-0.6/spec/request_errors_spec.rb
  138. +52 −0 vendor/gems/rest-client-0.6/spec/resource_spec.rb
  139. +213 −0 vendor/gems/rest-client-0.6/spec/rest_client_spec.rb
  140. +4 −0 vendor/gems/rspec-1.1.12/.autotest
  141. +466 −0 vendor/gems/rspec-1.1.12/.specification
  142. +1,253 −0 vendor/gems/rspec-1.1.12/History.txt
  143. +22 −0 vendor/gems/rspec-1.1.12/License.txt
  144. +383 −0 vendor/gems/rspec-1.1.12/Manifest.txt
  145. +57 −0 vendor/gems/rspec-1.1.12/README.txt
  146. +89 −0 vendor/gems/rspec-1.1.12/Rakefile
  147. +18 −0 vendor/gems/rspec-1.1.12/TODO.txt
  148. +4 −0 vendor/gems/rspec-1.1.12/bin/autospec
  149. +4 −0 vendor/gems/rspec-1.1.12/bin/spec
  150. +7 −0 vendor/gems/rspec-1.1.12/examples/failing/README.txt
  151. +36 −0 vendor/gems/rspec-1.1.12/examples/failing/diffing_spec.rb
  152. +19 −0 vendor/gems/rspec-1.1.12/examples/failing/failing_autogenerated_docstrings_example.rb
  153. +10 −0 vendor/gems/rspec-1.1.12/examples/failing/failure_in_after.rb
  154. +10 −0 vendor/gems/rspec-1.1.12/examples/failing/failure_in_before.rb
  155. +40 −0 vendor/gems/rspec-1.1.12/examples/failing/mocking_example.rb
  156. +26 −0 vendor/gems/rspec-1.1.12/examples/failing/mocking_with_flexmock.rb
  157. +25 −0 vendor/gems/rspec-1.1.12/examples/failing/mocking_with_mocha.rb
  158. +27 −0 vendor/gems/rspec-1.1.12/examples/failing/mocking_with_rr.rb
Sorry, we could not display the entire diff because too many files (2,216) changed.
View
6 app/controllers/application.rb
@@ -13,10 +13,4 @@ class ApplicationController < ActionController::Base
# from your application log (in this case, all fields with names like "password").
# filter_parameter_logging :password
- protected
-
- def database_name
- ["notes", "topfunky", Rails.env].join("_")
- end
-
end
View
16 app/controllers/application_controller.rb
@@ -0,0 +1,16 @@
+# Filters added to this controller apply to all controllers in the application.
+# Likewise, all the methods added will be available for all controllers.
+
+class ApplicationController < ActionController::Base
+ helper :all # include all helpers, all the time
+
+ # See ActionController::RequestForgeryProtection for details
+ # Uncomment the :secret if you're not using the cookie session store
+ protect_from_forgery # :secret => '1473d82c87ff75589db6723e090f26ac'
+
+ # See ActionController::Base for details
+ # Uncomment this to filter the contents of submitted sensitive data parameters
+ # from your application log (in this case, all fields with names like "password").
+ # filter_parameter_logging :password
+
+end
View
20 app/controllers/notes_controller.rb
@@ -1,20 +1,20 @@
class NotesController < ApplicationController
def index
- @notes = Note.view(database_name, "notes/by_title-map")
+ @notes = Note.by_title #(database_name, "notes/by_title-map")
respond_to do |wants|
wants.html
wants.json { render :json => @notes.rows.to_json }
end
end
def show
- @note = Note.find(database_name, params[:id])
+ @note = Note.get(params[:id])
# Attachment
if params[:filename]
- metadata = @note._attachments[params[:filename]]
- data = Note.db(database_name).fetch_attachment(@note.id, params[:filename])
+ metadata = @note['_attachments'][params[:filename]]
+ data = @note.fetch_attachment(params[:filename])
send_data(data, {
:filename => params[:filename],
:type => metadata['content_type'],
@@ -30,24 +30,24 @@ def show
end
def new
- @note = Note.new(database_name)
+ @note = Note.new
end
def create
- note = Note.new(database_name)
- note.save(params[:note])
+ note = Note.new(params[:note])
+ note.save
respond_to do |wants|
wants.html { redirect_to note_url(note) }
end
end
def edit
- @note = Note.find(database_name, params[:id])
+ @note = Note.get(params[:id])
end
def update
- @note = Note.find(database_name, params[:id])
- @note.save(params[:note])
+ @note = Note.get(params[:id])
+ @note.update_attributes(params[:note])
respond_to do |wants|
wants.html { redirect_to note_url(@note) }
end
View
2 app/helpers/notes_helper.rb
@@ -2,7 +2,7 @@ module NotesHelper
def couchdb_rev_field(form, record)
unless record.new_record?
- form.hidden_field("_rev")
+ form.hidden_field("rev")
end
end
View
113 app/models/note.rb
@@ -1,13 +1,13 @@
-class Note < BasicModel
-
- def default_attributes
- {
- "title" => nil,
- "description" => nil,
- "tags" => [],
- "visited_on" => Time.now.strftime('%Y/%m/%d')
- }
- end
+class Note < CouchRest::ExtendedDocument
+
+# def default_attributes
+# {
+# "title" => nil,
+# "description" => nil,
+# "tags" => [],
+# "visited_on" => Time.now.strftime('%Y/%m/%d')
+# }
+# end
##
# Coerce fields into the proper types of objects.
@@ -18,4 +18,97 @@ def on_update
end
end
+
+
+ use_database SERVER.default_database
+
+ property :title
+ property :description
+ property :tags, :default => []
+ property :visited_on, :default => lambda { Time.now.strftime('%Y/%m/%d') }
+
+ timestamps!
+
+ view_by :title, {
+ :map =>
+ "function(doc) {
+ if (doc['couchrest-type'] == 'Note') {
+ emit(doc.title, doc);
+ }
+ }"
+ }
+ # :reduce =>
+ # "function(keys, values, rereduce) {
+ # return sum(values);
+ # }"
+
+ view_by :tag, {
+ :map =>
+ "function(doc) {
+ if (doc['couchrest-type'] == 'Note' && doc.tags) {
+ doc.tags.map(function(tag) {
+ emit(tag, doc);
+ });
+ }
+ }",
+ :reduce =>
+ "function(key, values, combine) {
+ return {'tag':key[0][0], 'count':values.length};
+ }"
+ }
+
+ view_by :updated_at, {
+ :map =>
+ "function(doc) {
+ if (doc['couchrest-type'] == 'Note') {
+ emit(Date.parse(doc.updated_at.data), doc);
+ }
+ }"
+ }
+
+ view_by :visited_on, {
+ :map =>
+ "function(doc) {
+ if (doc['couchrest-type'] == 'Note' && doc.visited_on) {
+ emit(Util.dateAsArray(doc.visited_on), doc);
+ }
+ }"
+ }
+
+ ###############
+
+
+# unique_id :slug
+
+# view_by :date, :descending => true
+# view_by :user_id, :date
+
+# view_by :tags, {
+# :map =>
+# "function(doc) {
+# if (doc['couchrest-type'] == 'Article' && doc.tags) {
+# doc.tags.forEach(function(tag){
+# emit(tag, 1);
+# });
+# }
+# }",
+# :reduce =>
+# "function(keys, values, rereduce) {
+# return sum(values);
+# }"
+# }
+
+# property :date
+# property :slug, :read_only => true
+# property :title
+# property :tags
+
+# timestamps!
+
+# save_callback :before, :generate_slug_from_title
+
+# def generate_slug_from_title
+# self['slug'] = title.downcase.gsub(/[^a-z0-9]/,'-').squeeze('-').gsub(/^\-|\-$/,'') if new_document?
+# end
+
end
View
10 app/views/notes/_form.html.erb
@@ -1,6 +1,6 @@
-<% form_for @note, :html => {:multipart => true} do |f| %>
+<% form_for @note, :url => (@note.new_record? ? notes_path : note_path(@note.id)), :html => {:multipart => true} do |f| %>
- <%= couchdb_rev_field f, @note %>
+ <%# couchdb_rev_field f, @note %>
<%= f.label "Title" %>
<%= f.text_field :title %>
@@ -14,9 +14,9 @@
<%= f.label "Visited On" %>
<%= f.text_field "visited_on", :id => "date" %>
- <%= f.label "Attachment" %>
- <%= f.file_field "attachment" %>
+ <%# f.label "Attachment" %>
+ <%# f.file_field "attachment" %>
<%= f.submit "Save" %>
-<% end %>
+<% end %>
View
10 app/views/notes/index.html.erb
@@ -1,8 +1,10 @@
<h1>Your Notes</h1>
-<% @notes.rows.each do |note| %>
- <h2><%= link_to note.title, note_path(note) %></h2>
+<% @notes.each do |note| %>
+ <h2><%= link_to note.title, note_path(note.id) %></h2>
<p><%= note.description %></p>
- <small><em>Tags:</em> <%= note.tags.join(", ") %></small>
- <p><%= link_to "Edit", edit_note_path(note) %></p>
+ <% if note.tags.is_a?(Array) -%>
+ <small><em>Tags:</em> <%= note.tags.join(", ") %></small>
+ <% end -%>
+ <p><%= link_to "Edit", edit_note_path(note.id) %></p>
<% end %>
View
8 app/views/notes/show.html.erb
@@ -4,11 +4,11 @@
<p><%= @note.description %></p>
-<% if @note._attachments %>
+<% if @note['_attachments'] %>
<ul>
- <% @note._attachments.each do |attachment_name, attachment_attributes| %>
+ <% @note['_attachments'].each do |attachment_name, attachment_attributes| %>
<li>
- <%= link_to attachment_name, note_path(:id => @note, :filename => attachment_name) %>
+ <%= link_to attachment_name, note_path(:id => @note.id, :filename => attachment_name) %>
<%= number_to_human_size(attachment_attributes['length']) %>
</li>
<% end %>
@@ -17,4 +17,4 @@
<small><em>Tags:</em> <%= @note.tags.join(", ") %></small>
-<p><%= link_to "Edit", edit_note_path(@note) %></p>
+<p><%= link_to "Edit", edit_note_path(@note.id) %></p>
View
10 config/boot.rb
@@ -67,7 +67,7 @@ def load_rails_gem
class << self
def rubygems_version
- Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
+ Gem::RubyGemsVersion rescue nil
end
def gem_version
@@ -82,14 +82,14 @@ def gem_version
def load_rubygems
require 'rubygems'
-
- unless rubygems_version >= '0.9.4'
- $stderr.puts %(Rails requires RubyGems >= 0.9.4 (you have #{rubygems_version}). Please `gem update --system` and try again.)
+ min_version = '1.3.1'
+ unless rubygems_version >= min_version
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
exit 1
end
rescue LoadError
- $stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org)
+ $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
View
20 config/environment.rb
@@ -5,7 +5,7 @@
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
-RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION
+#RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
@@ -20,14 +20,18 @@
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
- # Specify gems that this application depends on.
+ # Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
- config.gem "jchris-couchrest", :lib => "couchrest"
- config.gem "json"
+ config.gem "couchrest"
+ config.gem "json", :version => "= 1.1.3"
+
+ config.gem "rspec", :lib => false, :version => ">= 1.2.0"
+ config.gem "rspec-rails", :lib => false, :version => ">= 1.2.0"
+
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "aws-s3", :lib => "aws/s3"
- # Only load the plugins named here, in the order given. By default, all plugins
+ # Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
@@ -46,7 +50,7 @@
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
- # Make sure the secret is at least 30 characters and all random,
+ # Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_travel_app_session',
@@ -71,3 +75,7 @@
require 'json/add/rails'
ENV['TZ'] = 'UTC'
+
+SERVER = CouchRest.new
+SERVER.default_database = ["notes", Rails.env].join("_")
+
View
4 config/environments/development.rb
@@ -14,4 +14,6 @@
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
-config.action_mailer.raise_delivery_errors = false
+config.action_mailer.raise_delivery_errors = false
+
+config.middleware.use "Rack::Bug"
View
165 lib/tasks/rspec.rake
@@ -0,0 +1,165 @@
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+
+# Don't load rspec if running "rake gems:*"
+unless ARGV.any? {|a| a =~ /^gems/}
+
+begin
+ require 'spec/rake/spectask'
+rescue MissingSourceFile
+ module Spec
+ module Rake
+ class SpecTask
+ def initialize(name)
+ task name do
+ # if rspec-rails is a configured gem, this will output helpful material and exit ...
+ require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
+
+ # ... otherwise, do this:
+ raise <<-MSG
+
+#{"*" * 80}
+* You are trying to run an rspec rake task defined in
+* #{__FILE__},
+* but rspec can not be found in vendor/gems, vendor/plugins or system gems.
+#{"*" * 80}
+MSG
+ end
+ end
+ end
+ end
+ end
+end
+
+Rake.application.instance_variable_get('@tasks').delete('default')
+
+spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
+task :noop do
+end
+
+task :default => :spec
+task :stats => "spec:statsetup"
+
+desc "Run all specs in spec directory (excluding plugin specs)"
+Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*/*_spec.rb']
+end
+
+namespace :spec do
+ desc "Run all specs in spec directory with RCov (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:rcov) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*/*_spec.rb']
+ t.rcov = true
+ t.rcov_opts = lambda do
+ IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
+ end
+ end
+
+ desc "Print Specdoc for all specs (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['spec/**/*/*_spec.rb']
+ end
+
+ desc "Print Specdoc for all plugin examples"
+ Spec::Rake::SpecTask.new(:plugin_doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*/*_spec.rb'].exclude('vendor/plugins/rspec/*')
+ end
+
+ [:models, :controllers, :views, :helpers, :lib].each do |sub|
+ desc "Run the code examples in spec/#{sub}"
+ Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
+ end
+ end
+
+ desc "Run the code examples in vendor/plugins (except RSpec's own)"
+ Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*")
+ end
+
+ namespace :plugins do
+ desc "Runs the examples for rspec_on_rails"
+ Spec::Rake::SpecTask.new(:rspec_on_rails) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*/*_spec.rb']
+ end
+ end
+
+ # Setup specs for stats
+ task :statsetup do
+ require 'code_statistics'
+ ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models')
+ ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views')
+ ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers')
+ ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers')
+ ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib')
+ ::STATS_DIRECTORIES << %w(Routing\ specs spec/lib) if File.exist?('spec/routing')
+ ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models')
+ ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views')
+ ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers')
+ ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers')
+ ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib')
+ ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?('spec/routing')
+ end
+
+ namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z."
+ task :load => :environment do
+ ActiveRecord::Base.establish_connection(Rails.env)
+ base_dir = File.join(Rails.root, 'spec', 'fixtures')
+ fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
+
+ require 'active_record/fixtures'
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
+ Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
+ end
+ end
+ end
+ end
+
+ namespace :server do
+ daemonized_server_pid = File.expand_path("#{RAILS_ROOT}/tmp/pids/spec_server.pid")
+
+ desc "start spec_server."
+ task :start do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts "spec_server is already running."
+ else
+ $stderr.puts %Q{Starting up spec_server ...}
+ FileUtils.mkdir_p('tmp/pids') unless test ?d, 'tmp/pids'
+ system("ruby", "script/spec_server", "--daemon", "--pid", daemonized_server_pid)
+ end
+ end
+
+ desc "stop spec_server."
+ task :stop do
+ unless File.exist?(daemonized_server_pid)
+ $stderr.puts "No server running."
+ else
+ $stderr.puts "Shutting down spec_server ..."
+ system("kill", "-s", "TERM", File.read(daemonized_server_pid).strip) &&
+ File.delete(daemonized_server_pid)
+ end
+ end
+
+ desc "restart spec_server."
+ task :restart => [:stop, :start]
+
+ desc "check if spec server is running"
+ task :status do
+ if File.exist?(daemonized_server_pid)
+ $stderr.puts %Q{spec_server is running (PID: #{File.read(daemonized_server_pid).gsub("\n","")})}
+ else
+ $stderr.puts "No server running."
+ end
+ end
+ end
+end
+
+end
View
144 public/javascripts/controls.js
@@ -1,22 +1,22 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com)
+// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
-//
+//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
-// Autocompleter.Base handles all the autocompletion functionality
+// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
-// Specific autocompleters need to provide, at the very least,
+// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
-// the text inside the monitored textbox changes. This method
+// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
@@ -30,23 +30,23 @@
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
-// enables autocompletion on multiple tokens. This is most
-// useful when one of the tokens is \n (a newline), as it
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
-var Autocompleter = { }
+var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
- element = $(element)
- this.element = element;
- this.update = $(update);
- this.hasFocus = false;
- this.changed = false;
- this.active = false;
- this.index = 0;
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
@@ -59,28 +59,28 @@ Autocompleter.Base = Class.create({
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
- this.options.onShow = this.options.onShow ||
- function(element, update){
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
- setHeight: false,
+ setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
- this.options.onHide = this.options.onHide ||
+ this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
- if(typeof(this.options.tokens) == 'string')
+ if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
-
+
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
@@ -91,18 +91,18 @@ Autocompleter.Base = Class.create({
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
- if(!this.iefix &&
+ if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
- new Insertion.After(this.update,
+ new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
-
+
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
@@ -150,15 +150,15 @@ Autocompleter.Base = Class.create({
Event.stop(event);
return;
}
- else
- if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
- this.observer =
+ this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
@@ -170,35 +170,35 @@ Autocompleter.Base = Class.create({
onHover: function(event) {
var element = Event.findElement(event, 'LI');
- if(this.index != element.autocompleteIndex)
+ if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
-
+
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
-
+
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
- this.active = false;
- },
-
+ this.active = false;
+ },
+
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
- this.index==i ?
- Element.addClassName(this.getEntry(i),"selected") :
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
- if(this.hasFocus) {
+ if(this.hasFocus) {
this.show();
this.active = true;
}
@@ -207,27 +207,27 @@ Autocompleter.Base = Class.create({
this.hide();
}
},
-
+
markPrevious: function() {
- if(this.index > 0) this.index--
+ if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
-
+
markNext: function() {
- if(this.index < this.entryCount-1) this.index++
+ if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
-
+
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
-
+
getCurrentEntry: function() {
return this.getEntry(this.index);
},
-
+
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
@@ -244,7 +244,7 @@ Autocompleter.Base = Class.create({
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
-
+
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
@@ -257,7 +257,7 @@ Autocompleter.Base = Class.create({
}
this.oldElementValue = this.element.value;
this.element.focus();
-
+
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
@@ -269,20 +269,20 @@ Autocompleter.Base = Class.create({
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
- this.entryCount =
+ this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
- } else {
+ } else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
-
+
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
@@ -298,7 +298,7 @@ Autocompleter.Base = Class.create({
},
onObserverEvent: function() {
- this.changed = false;
+ this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
@@ -351,16 +351,16 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
getUpdatedChoices: function() {
this.startIndicator();
-
- var entry = encodeURIComponent(this.options.paramName) + '=' +
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
- if(this.options.defaultParams)
+ if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
-
+
new Ajax.Request(this.url, this.options);
},
@@ -382,7 +382,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
-// text only at the beginning of strings in the
+// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
@@ -399,7 +399,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, {
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
-// It's possible to pass in a custom function as the 'selector'
+// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
@@ -427,20 +427,20 @@ Autocompleter.Local = Class.create(Autocompleter.Base, {
var entry = instance.getToken();
var count = 0;
- for (var i = 0; i < instance.options.array.length &&
- ret.length < instance.options.choices ; i++) {
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
- var foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
- if (foundPos == 0 && elem.length != entry.length) {
- ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
- } else if (entry.length >= instance.options.partialChars &&
+ } else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
@@ -450,14 +450,14 @@ Autocompleter.Local = Class.create(Autocompleter.Base, {
}
}
- foundPos = instance.options.ignoreCase ?
- elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
- ret = ret.concat(partial.slice(0, instance.options.choices - ret.length))
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
@@ -474,7 +474,7 @@ Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
-}
+};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
@@ -604,7 +604,7 @@ Ajax.InPlaceEditor = Class.create({
this.triggerCallback('onEnterHover');
},
getText: function() {
- return this.element.innerHTML;
+ return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
@@ -780,7 +780,7 @@ Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
- throw 'Server returned an invalid collection representation.';
+ throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
@@ -937,7 +937,7 @@ Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
-// Delayed observer, like Form.Element.Observer,
+// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
@@ -947,7 +947,7 @@ Form.Element.DelayedObserver = Class.create({
this.element = $(element);
this.callback = callback;
this.timer = null;
- this.lastValue = $F(this.element);
+ this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
@@ -960,4 +960,4 @@ Form.Element.DelayedObserver = Class.create({
this.timer = null;
this.callback(this.element, $F(this.element));
}
-});
+});
View
329 public/javascripts/dragdrop.js
@@ -1,6 +1,6 @@
// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
-//
+// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
+//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
@@ -32,42 +32,42 @@ var Droppables = {
options._containers.push($(containment));
}
}
-
+
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
-
+
findDeepestChild: function(drops) {
deepest = drops[0];
-
+
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
-
+
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
- containmentNode = element.treeNode;
+ containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
-
+
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
- (Element.classNames(element).detect(
+ (Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
@@ -87,12 +87,12 @@ var Droppables = {
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
-
+
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
-
+
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
@@ -101,7 +101,7 @@ var Droppables = {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
-
+
if (drop != this.last_active) Droppables.activate(drop);
}
},
@@ -112,34 +112,34 @@ var Droppables = {
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
- this.last_active.onDrop(element, this.last_active.element, event);
- return true;
+ this.last_active.onDrop(element, this.last_active.element, event);
+ return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
-}
+};
var Draggables = {
drags: [],
observers: [],
-
+
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
-
+
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
-
+
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
@@ -148,77 +148,77 @@ var Draggables = {
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
-
+
activate: function(draggable) {
- if(draggable.options.delay) {
- this._timeout = setTimeout(function() {
- Draggables._timeout = null;
- window.focus();
- Draggables.activeDraggable = draggable;
- }.bind(this), draggable.options.delay);
+ if(draggable.options.delay) {
+ this._timeout = setTimeout(function() {
+ Draggables._timeout = null;
+ window.focus();
+ Draggables.activeDraggable = draggable;
+ }.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
-
+
deactivate: function() {
this.activeDraggable = null;
},
-
+
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
-
+
this.activeDraggable.updateDrag(event, pointer);
},
-
+
endDrag: function(event) {
- if(this._timeout) {
- clearTimeout(this._timeout);
- this._timeout = null;
+ if(this._timeout) {
+ clearTimeout(this._timeout);
+ this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
-
+
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
-
+
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
-
+
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
-
+
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
-
+
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
-}
+};
/*--------------------------------------------------------------------------*/
@@ -234,12 +234,12 @@ var Draggable = Class.create({
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
- new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
+ new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
- afterFinish: function(){
- Draggable._dragging[element] = false
+ afterFinish: function(){
+ Draggable._dragging[element] = false
}
- });
+ });
},
zindex: 1000,
revert: false,
@@ -250,57 +250,57 @@ var Draggable = Class.create({
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
-
+
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
- new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
+ new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
-
+
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
-
+
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
-
+
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
-
+
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
- Element.makePositioned(this.element); // fix IE
+ Element.makePositioned(this.element); // fix IE
this.options = options;
- this.dragging = false;
+ this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
-
+
Draggables.register(this);
},
-
+
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
-
+
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
-
+
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
- if(Event.isLeftClick(event)) {
+ if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
@@ -309,34 +309,34 @@ var Draggable = Class.create({
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
-
+
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element);
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
-
+
Draggables.activate(this);
Event.stop(event);
}
},
-
+
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
-
+
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
-
+
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
- this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
- if (!this.element._originallyAbsolute)
+ this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
+ if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
-
+
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
@@ -347,28 +347,28 @@ var Draggable = Class.create({
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
-
+
Draggables.notify('onStart', this, event);
-
+
if(this.options.starteffect) this.options.starteffect(this.element);
},
-
+
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
-
+
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
-
+
Draggables.notify('onDrag', this, event);
-
+
this.draw(pointer);
if(this.options.change) this.options.change(this);
-
+
if(this.options.scroll) {
this.stopScrolling();
-
+
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
@@ -386,41 +386,41 @@ var Draggable = Class.create({
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
-
+
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
-
+
Event.stop(event);
},
-
+
finishDrag: function(event, success) {
this.dragging = false;
-
+
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
- if (!this.element._originallyAbsolute)
+ if (!this._originallyAbsolute)
Position.relativize(this.element);
- delete this.element._originallyAbsolute;
+ delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
- var dropped = false;
- if(success) {
- dropped = Droppables.fire(event, this.element);
- if (!dropped) dropped = false;
+ var dropped = false;
+ if(success) {
+ dropped = Droppables.fire(event, this.element);
+ if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
-
+
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
@@ -433,82 +433,82 @@ var Draggable = Class.create({
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
- if(this.options.endeffect)
+ if(this.options.endeffect)
this.options.endeffect(this.element);
-
+
Draggables.deactivate(this);
Droppables.reset();
},
-
+
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
-
+
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
-
+
draw: function(point) {
var pos = Position.cumulativeOffset(this.element);
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
-
+
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
-
+
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
-
- var p = [0,1].map(function(i){
- return (point[i]-pos[i]-this.offset[i])
+
+ var p = [0,1].map(function(i){
+ return (point[i]-pos[i]-this.offset[i])
}.bind(this));
-
+
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
- return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
+ return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
- return (v/this.options.snap).round()*this.options.snap }.bind(this))
+ return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
-
+
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
-
+
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
-
+
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
-
+
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
-
+
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
@@ -524,7 +524,7 @@ var Draggable = Class.create({
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
-
+
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
@@ -538,10 +538,10 @@ var Draggable = Class.create({
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
-
+
if(this.options.change) this.options.change(this);
},
-
+
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
@@ -560,7 +560,7 @@ var Draggable = Class.create({
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
- H = body.offsetHeight
+ H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
@@ -577,11 +577,11 @@ var SortableObserver = Class.create({
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
-
+
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
-
+
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
@@ -591,11 +591,11 @@ var SortableObserver = Class.create({
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
-
+
sortables: { },
-
+
_findRootElement: function(element) {
- while (element.tagName.toUpperCase() != "BODY") {
+ while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
@@ -606,22 +606,23 @@ var Sortable = {
if(!element) return;
return Sortable.sortables[element.id];
},
-
+
destroy: function(element){
- var s = Sortable.options(element);
-
+ element = $(element);
+ var s = Sortable.sortables[element.id];
+
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
-
+
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
- var options = Object.extend({
+ var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
@@ -635,17 +636,17 @@ var Sortable = {
delay: 0,
hoverclass: null,
ghosting: false,
- quiet: false,
+ quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
-
- // these take arrays of elements or ids and can be
+
+ // these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
-
+
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
@@ -682,24 +683,24 @@ var Sortable = {
if(options.zindex)
options_for_draggable.zindex = options.zindex;
- // build options for the droppables
+ // build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
- }
-
+ };
+
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
- }
+ };
// fix for gecko engine
- Element.cleanWhitespace(element);
+ Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
@@ -712,14 +713,14 @@ var Sortable = {
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
- (options.handle ? $(e).select('.' + options.handle)[0] : e);
+ (options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
- options.droppables.push(e);
+ options.droppables.push(e);
});
-
+
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
@@ -741,7 +742,7 @@ var Sortable = {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
-
+
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
@@ -758,7 +759,7 @@ var Sortable = {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
- if(dropon.parentNode!=oldParentNode)
+ if