Migrate web site to use rails 2.0.1.

This commit is contained in:
Tom Hughes 2008-01-06 12:17:58 +00:00
parent dffd645c50
commit 7fc2dbecd5
18 changed files with 4298 additions and 2326 deletions

View file

@ -51,7 +51,7 @@ by the OpenStreetMap project and it's contributors.
<% zoom = h(params['zoom'] || '12') %> <% zoom = h(params['zoom'] || '12') %>
<% layers = h(params['layers']) %> <% layers = h(params['layers']) %>
<% elsif cookies.key?("location") %> <% elsif cookies.key?("location") %>
<% lon,lat,zoom,layers = cookies["location"].value.first.split(",") %> <% lon,lat,zoom,layers = cookies["location"].split(",") %>
<% elsif @user and !@user.home_lon.nil? and !@user.home_lat.nil? %> <% elsif @user and !@user.home_lon.nil? and !@user.home_lat.nil? %>
<% lon = @user.home_lon %> <% lon = @user.home_lon %>
<% lat = @user.home_lat %> <% lat = @user.home_lat %>

View file

@ -1,45 +1,108 @@
# Don't change this file. Configuration is done in config/environment.rb and config/environments/*.rb # Don't change this file!
# Configure your app in config/environment.rb and config/environments/*.rb
unless defined?(RAILS_ROOT) RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
root_path = File.join(File.dirname(__FILE__), '..')
unless RUBY_PLATFORM =~ /(:?mswin|mingw)/ module Rails
require 'pathname' class << self
root_path = Pathname.new(root_path).cleanpath(true).to_s def boot!
end unless booted?
preinitialize
RAILS_ROOT = root_path pick_boot.run
end
unless defined?(Rails::Initializer)
if File.directory?("#{RAILS_ROOT}/vendor/rails")
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
else
require 'rubygems'
environment_without_comments = IO.readlines(File.dirname(__FILE__) + '/environment.rb').reject { |l| l =~ /^#/ }.join
environment_without_comments =~ /[^#]RAILS_GEM_VERSION = '([\d.]+)'/
rails_gem_version = $1
if version = defined?(RAILS_GEM_VERSION) ? RAILS_GEM_VERSION : rails_gem_version
# Asking for 1.1.6 will give you 1.1.6.5206, if available -- makes it easier to use beta gems
rails_gem = Gem.cache.search('rails', "~>#{version}.0").sort_by { |g| g.version.version }.last
if rails_gem
gem "rails", "=#{rails_gem.version.version}"
require rails_gem.full_gem_path + '/lib/initializer'
else
STDERR.puts %(Cannot find gem for Rails ~>#{version}.0:
Install the missing gem with 'gem install -v=#{version} rails', or
change environment.rb to define RAILS_GEM_VERSION with your desired version.
)
exit 1
end end
else end
gem "rails"
require 'initializer' def booted?
defined? Rails::Initializer
end
def pick_boot
(vendor_rails? ? VendorBoot : GemBoot).new
end
def vendor_rails?
File.exist?("#{RAILS_ROOT}/vendor/rails")
end
def preinitialize
load(preinitializer_path) if File.exists?(preinitializer_path)
end
def preinitializer_path
"#{RAILS_ROOT}/config/preinitializer.rb"
end end
end end
Rails::Initializer.run(:set_load_path) class Boot
def run
load_initializer
Rails::Initializer.run(:set_load_path)
end
end
class VendorBoot < Boot
def load_initializer
require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
end
end
class GemBoot < Boot
def load_initializer
self.class.load_rubygems
load_rails_gem
require 'initializer'
end
def load_rails_gem
if version = self.class.gem_version
gem 'rails', version
else
gem 'rails'
end
rescue Gem::LoadError => load_error
$stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
exit 1
end
class << self
def rubygems_version
Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion
end
def gem_version
if defined? RAILS_GEM_VERSION
RAILS_GEM_VERSION
elsif ENV.include?('RAILS_GEM_VERSION')
ENV['RAILS_GEM_VERSION']
else
parse_gem_version(read_environment_rb)
end
end
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.)
exit 1
end
rescue LoadError
$stderr.puts %(Rails requires RubyGems >= 0.9.4. Please install RubyGems and try again: http://rubygems.rubyforge.org)
exit 1
end
def parse_gem_version(text)
$1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*'([!~<>=]*\s*[\d.]+)'/
end
private
def read_environment_rb
File.read("#{RAILS_ROOT}/config/environment.rb")
end
end
end
end end
# All that for this:
Rails.boot!

View file

@ -1,58 +1,63 @@
# Be sure to restart your web server when you modify this file. # Be sure to restart your server when you modify this file
# Limit each rails process to a 512Mb resident set size # Uncomment below to force Rails into production mode when
Process.setrlimit Process::RLIMIT_AS, 640*1024*1024, Process::RLIM_INFINITY
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way # you don't control web/app server and can't set it the proper way
ENV['RAILS_ENV'] ||= 'production' ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present # Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '1.2.3' RAILS_GEM_VERSION = '2.0.1' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration # Set the server URL
require File.join(File.dirname(__FILE__), 'boot') SERVER_URL = ENV['OSM_SERVER_URL'] || 'www.openstreetmap.org'
# Application constants needed for routes.rb - must go before Initializer call # Application constants needed for routes.rb - must go before Initializer call
API_VERSION = ENV['OSM_API_VERSION'] || '0.5' API_VERSION = ENV['OSM_API_VERSION'] || '0.5'
# Custom logger class to format messages sensibly # Set to :readonly to put the API in read-only mode or :offline to
class OSMLogger < Logger # take it completely offline
def format_message(severity, time, progname, msg) API_STATUS = :online
"[%s.%06d #%d] %s\n" % [time.strftime("%Y-%m-%d %H:%M:%S"), time.usec, $$, msg.sub(/^\n+/, "")]
end # Bootstrap the Rails environment, frameworks, and default configuration
end require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config| Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence those specified here # Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# Skip frameworks you're not going to use # -- all .rb files in that directory are automatically loaded.
# config.frameworks -= [ :action_web_service, :action_mailer ] # See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# 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 ]
# Add additional load paths for your own custom dirs # Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras ) # config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level # Force all environments to use the same logger level
# (by default production uses :info, the others :debug) # (by default production uses :info, the others :debug)
# config.log_level = :debug # config.log_level = :debug
# Use our custom logger # Your secret key for verifying cookie session data integrity.
config.logger = OSMLogger.new(config.log_path) # If you change this key, all old sessions will become invalid!
config.logger.level = Logger.const_get(config.log_level.to_s.upcase) # 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 => '_osm_session',
:secret => 'd886369b1e709c61d1f9fcb07384a2b96373c83c01bfc98c6611a9fe2b6d0b14215bb360a0154265cccadde5489513f2f9b8d9e7b384a11924f772d2872c2a1f'
}
# Use the database for sessions instead of the file system # Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create') # (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :sql_session_store config.action_controller.session_store = :sql_session_store
# Unfortunately SqlSessionStore is a plugin which has not been
# loaded yet, so we have to do things the hard way...
config.after_initialize do
ActionController::Base.session_store = :sql_session_store
SqlSessionStore.session_class = MysqlSession
end
# Use SQL instead of Active Record's schema dumper when creating the test database. # Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper, # This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types # like if you have constraints or database-specific column types
config.active_record.schema_format = :sql config.active_record.schema_format = :sql
@ -61,55 +66,4 @@ Rails::Initializer.run do |config|
# Make Active Record use UTC-base instead of local time # Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc # config.active_record.default_timezone = :utc
# See Rails::Configuration for more options
end end
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# Hack the AssetTagHelper to make asset tagging work better
module ActionView
module Helpers
module AssetTagHelper
private
alias :old_compute_public_path :compute_public_path
def compute_public_path(source, dir, ext)
path = old_compute_public_path(source, dir, ext)
if path =~ /(.+)\?(\d+)\??$/
path = "#{$1}/#{$2}"
end
path
end
end
end
end
# Set to :readonly to put the API in read-only mode or :offline to
# take it completely offline
API_STATUS = :online
# Include your application configuration below
SERVER_URL = ENV['OSM_SERVER_URL'] || 'www.openstreetmap.org'
ActionMailer::Base.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'localhost',
}
#Taming FCGI
#
COUNT = 0
MAX_COUNT = 10000

View file

@ -8,14 +8,11 @@ config.cache_classes = false
# Log error messages when you accidentally call methods on nil. # Log error messages when you accidentally call methods on nil.
config.whiny_nils = true config.whiny_nils = true
# Enable the breakpoint server that script/breakpointer connects to
config.breakpoint_server = true
# Show full error reports and disable caching # Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false config.action_controller.perform_caching = false
config.action_view.cache_template_extensions = false config.action_view.cache_template_extensions = false
config.action_view.debug_rjs = true
# Don't care if the mailer can't send # Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false config.action_mailer.raise_delivery_errors = false

View file

@ -14,5 +14,5 @@ config.action_controller.perform_caching = true
# Enable serving of images, stylesheets, and javascripts from an asset server # Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com" # config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors if you bad email addresses should just be ignored # Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false # config.action_mailer.raise_delivery_errors = false

View file

@ -13,7 +13,10 @@ config.whiny_nils = true
config.action_controller.consider_all_requests_local = true config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false config.action_controller.perform_caching = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell ActionMailer not to deliver emails to the real world. # Tell ActionMailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the # The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array. # ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test config.action_mailer.delivery_method = :test

View file

@ -0,0 +1,6 @@
# Configure ActionMailer
ActionMailer::Base.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'localhost',
}

View file

@ -0,0 +1,10 @@
module ActionView
module Helpers
module AssetTagHelper
def rewrite_asset_path!(source)
asset_id = rails_asset_id(source)
source << "/#{asset_id}" if !asset_id.blank?
end
end
end
end

View file

@ -0,0 +1,14 @@
# Hack BufferedLogger to add timestamps to messages
module ActiveSupport
class BufferedLogger
alias_method :old_add, :add
def add(severity, message = nil, progname = nil, &block)
return if @level > severity
message = (message || (block && block.call) || progname).to_s
time = Time.now
message = "[%s.%06d #%d] %s\n" % [time.strftime("%Y-%m-%d %H:%M:%S"), time.usec, $$, message.sub(/^\n+/, "")]
old_add(severity, message)
end
end
end

View file

@ -0,0 +1,10 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end

View file

@ -0,0 +1,6 @@
# Limit each rails process to a 512Mb resident set size
Process.setrlimit Process::RLIMIT_AS, 640*1024*1024, Process::RLIM_INFINITY
# Force a restart after every 10000 requests
COUNT = 0
MAX_COUNT = 10000

View file

@ -0,0 +1,5 @@
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

View file

@ -0,0 +1,2 @@
# Use the MySQL interface for SqlSessionStore
SqlSessionStore.session_class = MysqlSession

View file

@ -55,5 +55,5 @@ while(true) do
exit if terminated exit if terminated
end end
sleep 5.minutes sleep 5.minutes.value
end end

File diff suppressed because it is too large Load diff

View file

@ -1,10 +1,10 @@
// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) // (c) 2005-2007 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. // 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/ // For details, see the script.aculo.us web site: http://script.aculo.us/
if(typeof Effect == 'undefined') if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library"); throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = { var Droppables = {
@ -20,14 +20,13 @@ var Droppables = {
greedy: true, greedy: true,
hoverclass: null, hoverclass: null,
tree: false tree: false
}, arguments[1] || {}); }, arguments[1] || { });
// cache containers // cache containers
if(options.containment) { if(options.containment) {
options._containers = []; options._containers = [];
var containment = options.containment; var containment = options.containment;
if((typeof containment == 'object') && if(Object.isArray(containment)) {
(containment.constructor == Array)) {
containment.each( function(c) { options._containers.push($(c)) }); containment.each( function(c) { options._containers.push($(c)) });
} else { } else {
options._containers.push($(containment)); options._containers.push($(containment));
@ -87,21 +86,23 @@ var Droppables = {
show: function(point, element) { show: function(point, element) {
if(!this.drops.length) return; if(!this.drops.length) return;
var affected = []; var drop, affected = [];
if(this.last_active) this.deactivate(this.last_active);
this.drops.each( function(drop) { this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop)) if(Droppables.isAffected(point, element, drop))
affected.push(drop); affected.push(drop);
}); });
if(affected.length>0) { if(affected.length>0)
drop = Droppables.findDeepestChild(affected); drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]); Position.within(drop.element, point[0], point[1]);
if(drop.onHover) if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
Droppables.activate(drop); if (drop != this.last_active) Droppables.activate(drop);
} }
}, },
@ -110,8 +111,10 @@ var Droppables = {
Position.prepare(); Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event); this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
}, },
reset: function() { reset: function() {
@ -219,10 +222,7 @@ var Draggables = {
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/
var Draggable = Class.create(); var Draggable = Class.create({
Draggable._dragging = {};
Draggable.prototype = {
initialize: function(element) { initialize: function(element) {
var defaults = { var defaults = {
handle: false, handle: false,
@ -233,7 +233,7 @@ Draggable.prototype = {
}); });
}, },
endeffect: function(element) { endeffect: function(element) {
var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0; 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'}, queue: {scope:'_draggable', position:'end'},
afterFinish: function(){ afterFinish: function(){
@ -243,6 +243,7 @@ Draggable.prototype = {
}, },
zindex: 1000, zindex: 1000,
revert: false, revert: false,
quiet: false,
scroll: false, scroll: false,
scrollSensitivity: 20, scrollSensitivity: 20,
scrollSpeed: 15, scrollSpeed: 15,
@ -250,7 +251,7 @@ Draggable.prototype = {
delay: 0 delay: 0
}; };
if(!arguments[1] || typeof arguments[1].endeffect == 'undefined') if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, { Object.extend(defaults, {
starteffect: function(element) { starteffect: function(element) {
element._opacity = Element.getOpacity(element); element._opacity = Element.getOpacity(element);
@ -259,11 +260,11 @@ Draggable.prototype = {
} }
}); });
var options = Object.extend(defaults, arguments[1] || {}); var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element); this.element = $(element);
if(options.handle && (typeof options.handle == 'string')) if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0); this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle); if(!this.handle) this.handle = $(options.handle);
@ -276,7 +277,6 @@ Draggable.prototype = {
Element.makePositioned(this.element); // fix IE Element.makePositioned(this.element); // fix IE
this.delta = this.currentDelta();
this.options = options; this.options = options;
this.dragging = false; this.dragging = false;
@ -298,17 +298,17 @@ Draggable.prototype = {
}, },
initDrag: function(event) { initDrag: function(event) {
if(typeof Draggable._dragging[this.element] != 'undefined' && if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return; Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) { if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue // abort on form elements, fixes a Firefox issue
var src = Event.element(event); var src = Event.element(event);
if(src.tagName && ( if((tag_name = src.tagName.toUpperCase()) && (
src.tagName=='INPUT' || tag_name=='INPUT' ||
src.tagName=='SELECT' || tag_name=='SELECT' ||
src.tagName=='OPTION' || tag_name=='OPTION' ||
src.tagName=='BUTTON' || tag_name=='BUTTON' ||
src.tagName=='TEXTAREA')) return; tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)]; var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = Position.cumulativeOffset(this.element); var pos = Position.cumulativeOffset(this.element);
@ -321,6 +321,8 @@ Draggable.prototype = {
startDrag: function(event) { startDrag: function(event) {
this.dragging = true; this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) { if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
@ -329,7 +331,9 @@ Draggable.prototype = {
if(this.options.ghosting) { if(this.options.ghosting) {
this._clone = this.element.cloneNode(true); this._clone = this.element.cloneNode(true);
Position.absolutize(this.element); this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this.element._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element); this.element.parentNode.insertBefore(this._clone, this.element);
} }
@ -351,8 +355,12 @@ Draggable.prototype = {
updateDrag: function(event, pointer) { updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event); if(!this.dragging) this.startDrag(event);
Position.prepare();
Droppables.show(pointer, this.element); if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event); Draggables.notify('onDrag', this, event);
this.draw(pointer); this.draw(pointer);
@ -380,30 +388,44 @@ Draggable.prototype = {
} }
// fix AppleWebKit rendering // fix AppleWebKit rendering
if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event); Event.stop(event);
}, },
finishDrag: function(event, success) { finishDrag: function(event, success) {
this.dragging = false; 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.options.ghosting) {
Position.relativize(this.element); if (!this.element._originallyAbsolute)
Position.relativize(this.element);
delete this.element._originallyAbsolute;
Element.remove(this._clone); Element.remove(this._clone);
this._clone = null; this._clone = null;
} }
if(success) Droppables.fire(event, this.element); 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); Draggables.notify('onEnd', this, event);
var revert = this.options.revert; var revert = this.options.revert;
if(revert && typeof revert == 'function') revert = revert(this.element); if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta(); var d = this.currentDelta();
if(revert && this.options.reverteffect) { if(revert && this.options.reverteffect) {
this.options.reverteffect(this.element, if (dropped == 0 || revert != 'failure')
d[1]-this.delta[1], d[0]-this.delta[0]); this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else { } else {
this.delta = d; this.delta = d;
} }
@ -451,15 +473,15 @@ Draggable.prototype = {
}.bind(this)); }.bind(this));
if(this.options.snap) { if(this.options.snap) {
if(typeof this.options.snap == 'function') { if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this); p = this.options.snap(p[0],p[1],this);
} else { } else {
if(this.options.snap instanceof Array) { if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) { p = p.map( function(v, i) {
return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this)) return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this))
} else { } else {
p = p.map( function(v) { p = p.map( function(v) {
return Math.round(v/this.options.snap)*this.options.snap }.bind(this)) return (v/this.options.snap).round()*this.options.snap }.bind(this))
} }
}} }}
@ -543,12 +565,13 @@ Draggable.prototype = {
} }
return { top: T, left: L, width: W, height: H }; return { top: T, left: L, width: W, height: H };
} }
} });
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/
var SortableObserver = Class.create(); var SortableObserver = Class.create({
SortableObserver.prototype = {
initialize: function(element, observer) { initialize: function(element, observer) {
this.element = $(element); this.element = $(element);
this.observer = observer; this.observer = observer;
@ -564,15 +587,15 @@ SortableObserver.prototype = {
if(this.lastValue != Sortable.serialize(this.element)) if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element) this.observer(this.element)
} }
} });
var Sortable = { var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: {}, sortables: { },
_findRootElement: function(element) { _findRootElement: function(element) {
while (element.tagName != "BODY") { while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element; if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode; element = element.parentNode;
} }
@ -612,13 +635,20 @@ var Sortable = {
delay: 0, delay: 0,
hoverclass: null, hoverclass: null,
ghosting: false, ghosting: false,
quiet: false,
scroll: false, scroll: false,
scrollSensitivity: 20, scrollSensitivity: 20,
scrollSpeed: 15, scrollSpeed: 15,
format: this.SERIALIZE_RULE, format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction, onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction onUpdate: Prototype.emptyFunction
}, arguments[1] || {}); }, arguments[1] || { });
// clear any old sortable with same element // clear any old sortable with same element
this.destroy(element); this.destroy(element);
@ -626,6 +656,7 @@ var Sortable = {
// build options for the draggables // build options for the draggables
var options_for_draggable = { var options_for_draggable = {
revert: true, revert: true,
quiet: options.quiet,
scroll: options.scroll, scroll: options.scroll,
scrollSpeed: options.scrollSpeed, scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity, scrollSensitivity: options.scrollSensitivity,
@ -679,10 +710,9 @@ var Sortable = {
options.droppables.push(element); options.droppables.push(element);
} }
(this.findElements(element, options) || []).each( function(e) { (options.elements || this.findElements(element, options) || []).each( function(e,i) {
// handles are per-draggable var handle = options.handles ? $(options.handles[i]) :
var handle = options.handle ? (options.handle ? $(e).select('.' + options.handle)[0] : e);
$(e).down('.'+options.handle,0) : e;
options.draggables.push( options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable); Droppables.add(e, options_for_droppable);
@ -842,7 +872,7 @@ var Sortable = {
only: sortableOptions.only, only: sortableOptions.only,
name: element.id, name: element.id,
format: sortableOptions.format format: sortableOptions.format
}, arguments[1] || {}); }, arguments[1] || { });
var root = { var root = {
id: null, id: null,
@ -866,7 +896,7 @@ var Sortable = {
sequence: function(element) { sequence: function(element) {
element = $(element); element = $(element);
var options = Object.extend(this.options(element), arguments[1] || {}); var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) { return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
@ -875,9 +905,9 @@ var Sortable = {
setSequence: function(element, new_sequence) { setSequence: function(element, new_sequence) {
element = $(element); element = $(element);
var options = Object.extend(this.options(element), arguments[2] || {}); var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = {}; var nodeMap = { };
this.findElements(element, options).each( function(n) { this.findElements(element, options).each( function(n) {
if (n.id.match(options.format)) if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
@ -895,7 +925,7 @@ var Sortable = {
serialize: function(element) { serialize: function(element) {
element = $(element); element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || {}); var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent( var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id); (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
@ -919,7 +949,7 @@ Element.isParent = function(child, element) {
return Element.isParent(child.parentNode, element); return Element.isParent(child.parentNode, element);
} }
Element.findChildren = function(element, only, recursive, tagName) { Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null; if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase(); tagName = tagName.toUpperCase();
if(only) only = [only].flatten(); if(only) only = [only].flatten();

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff