mirror of
https://github.com/github/rails.git
synced 2026-04-04 03:00:58 -04:00
Merge branch 'master' of git@github.com:rails/rails
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
*2.3.0/3.0*
|
||||
*2.3.0 [Edge]*
|
||||
|
||||
* Fixed that no body charset would be set when there are attachments present #740 [Paweł Kondzior]
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.rubyforge_project = "actionmailer"
|
||||
s.homepage = "http://www.rubyonrails.org"
|
||||
|
||||
s.add_dependency('actionpack', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('actionpack', '= 2.3.0' + PKG_BUILD)
|
||||
|
||||
s.has_rdoc = true
|
||||
s.requirements << 'none'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActionMailer
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -1,4 +1,24 @@
|
||||
*2.3.0/3.0*
|
||||
*2.3.0 [Edge]*
|
||||
|
||||
* Remove deprecated ActionController::Base#assign_default_content_type_and_charset
|
||||
|
||||
* Changed the default of ActionView#render to assume partials instead of files when not given an options hash [DHH]. Examples:
|
||||
|
||||
# Instead of <%= render :partial => "account" %>
|
||||
<%= render "account" %>
|
||||
|
||||
# Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
|
||||
<%= render "account", :account => @buyer %>
|
||||
|
||||
# @account is an Account instance, so it uses the RecordIdentifier to replace
|
||||
# <%= render :partial => "accounts/account", :locals => { :account => @account } %>
|
||||
<%= render(@account) %>
|
||||
|
||||
# @posts is an array of Post instances, so it uses the RecordIdentifier to replace
|
||||
# <%= render :partial => "posts/post", :collection => @posts %>
|
||||
<%= render(@posts) %>
|
||||
|
||||
* Remove deprecated render_component. Please use the plugin from http://github.com/rails/render_component/tree/master [Pratik]
|
||||
|
||||
* Fixed RedCloth and BlueCloth shouldn't preload. Instead just assume that they're available if you want to use textilize and markdown and let autoload require them [DHH]
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.has_rdoc = true
|
||||
s.requirements << 'none'
|
||||
|
||||
s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
|
||||
|
||||
s.require_path = 'lib'
|
||||
s.autorequire = 'action_controller'
|
||||
|
||||
@@ -49,7 +49,6 @@ require 'action_controller/verification'
|
||||
require 'action_controller/streaming'
|
||||
require 'action_controller/session_management'
|
||||
require 'action_controller/http_authentication'
|
||||
require 'action_controller/components'
|
||||
require 'action_controller/rack_process'
|
||||
require 'action_controller/record_identifier'
|
||||
require 'action_controller/request_forgery_protection'
|
||||
@@ -72,7 +71,6 @@ ActionController::Base.class_eval do
|
||||
include ActionController::Streaming
|
||||
include ActionController::SessionManagement
|
||||
include ActionController::HttpAuthentication::Basic::ControllerMethods
|
||||
include ActionController::Components
|
||||
include ActionController::RecordIdentifier
|
||||
include ActionController::RequestForgeryProtection
|
||||
include ActionController::Translation
|
||||
|
||||
@@ -529,7 +529,7 @@ module ActionController #:nodoc:
|
||||
end
|
||||
|
||||
def send_response
|
||||
response.prepare! unless component_request?
|
||||
response.prepare!
|
||||
response
|
||||
end
|
||||
|
||||
@@ -1270,11 +1270,6 @@ module ActionController #:nodoc:
|
||||
@action_name = (params['action'] || 'index')
|
||||
end
|
||||
|
||||
def assign_default_content_type_and_charset
|
||||
response.assign_default_content_type_and_charset!
|
||||
end
|
||||
deprecate :assign_default_content_type_and_charset => :'response.assign_default_content_type_and_charset!'
|
||||
|
||||
def action_methods
|
||||
self.class.action_methods
|
||||
end
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
module ActionController #:nodoc:
|
||||
# Components allow you to call other actions for their rendered response while executing another action. You can either delegate
|
||||
# the entire response rendering or you can mix a partial response in with your other content.
|
||||
#
|
||||
# class WeblogController < ActionController::Base
|
||||
# # Performs a method and then lets hello_world output its render
|
||||
# def delegate_action
|
||||
# do_other_stuff_before_hello_world
|
||||
# render_component :controller => "greeter", :action => "hello_world", :params => { :person => "david" }
|
||||
# end
|
||||
# end
|
||||
#
|
||||
# class GreeterController < ActionController::Base
|
||||
# def hello_world
|
||||
# render :text => "#{params[:person]} says, Hello World!"
|
||||
# end
|
||||
# end
|
||||
#
|
||||
# The same can be done in a view to do a partial rendering:
|
||||
#
|
||||
# Let's see a greeting:
|
||||
# <%= render_component :controller => "greeter", :action => "hello_world" %>
|
||||
#
|
||||
# It is also possible to specify the controller as a class constant, bypassing the inflector
|
||||
# code to compute the controller class at runtime:
|
||||
#
|
||||
# <%= render_component :controller => GreeterController, :action => "hello_world" %>
|
||||
#
|
||||
# == When to use components
|
||||
#
|
||||
# Components should be used with care. They're significantly slower than simply splitting reusable parts into partials and
|
||||
# conceptually more complicated. Don't use components as a way of separating concerns inside a single application. Instead,
|
||||
# reserve components to those rare cases where you truly have reusable view and controller elements that can be employed
|
||||
# across many applications at once.
|
||||
#
|
||||
# So to repeat: Components are a special-purpose approach that can often be replaced with better use of partials and filters.
|
||||
module Components
|
||||
def self.included(base) #:nodoc:
|
||||
base.class_eval do
|
||||
include InstanceMethods
|
||||
include ActiveSupport::Deprecation
|
||||
extend ClassMethods
|
||||
helper HelperMethods
|
||||
|
||||
# If this controller was instantiated to process a component request,
|
||||
# +parent_controller+ points to the instantiator of this controller.
|
||||
attr_accessor :parent_controller
|
||||
|
||||
alias_method_chain :process_cleanup, :components
|
||||
alias_method_chain :set_session_options, :components
|
||||
alias_method_chain :flash, :components
|
||||
|
||||
alias_method :component_request?, :parent_controller
|
||||
end
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
# Track parent controller to identify component requests
|
||||
def process_with_components(request, response, parent_controller = nil) #:nodoc:
|
||||
controller = new
|
||||
controller.parent_controller = parent_controller
|
||||
controller.process(request, response)
|
||||
end
|
||||
end
|
||||
|
||||
module HelperMethods
|
||||
def render_component(options)
|
||||
@controller.__send__(:render_component_as_string, options)
|
||||
end
|
||||
end
|
||||
|
||||
module InstanceMethods
|
||||
# Extracts the action_name from the request parameters and performs that action.
|
||||
def process_with_components(request, response, method = :perform_action, *arguments) #:nodoc:
|
||||
flash.discard if component_request?
|
||||
process_without_components(request, response, method, *arguments)
|
||||
end
|
||||
|
||||
protected
|
||||
# Renders the component specified as the response for the current method
|
||||
def render_component(options) #:doc:
|
||||
component_logging(options) do
|
||||
render_for_text(component_response(options, true).body, response.headers["Status"])
|
||||
end
|
||||
end
|
||||
deprecate :render_component => "Please install render_component plugin from http://github.com/rails/render_component/tree/master"
|
||||
|
||||
# Returns the component response as a string
|
||||
def render_component_as_string(options) #:doc:
|
||||
component_logging(options) do
|
||||
response = component_response(options, false)
|
||||
|
||||
if redirected = response.redirected_to
|
||||
render_component_as_string(redirected)
|
||||
else
|
||||
response.body
|
||||
end
|
||||
end
|
||||
end
|
||||
deprecate :render_component_as_string => "Please install render_component plugin from http://github.com/rails/render_component/tree/master"
|
||||
|
||||
def flash_with_components(refresh = false) #:nodoc:
|
||||
if !defined?(@_flash) || refresh
|
||||
@_flash =
|
||||
if defined?(@parent_controller)
|
||||
@parent_controller.flash
|
||||
else
|
||||
flash_without_components
|
||||
end
|
||||
end
|
||||
@_flash
|
||||
end
|
||||
|
||||
private
|
||||
def component_response(options, reuse_response)
|
||||
klass = component_class(options)
|
||||
request = request_for_component(klass.controller_name, options)
|
||||
new_response = reuse_response ? response : response.dup
|
||||
|
||||
klass.process_with_components(request, new_response, self)
|
||||
end
|
||||
|
||||
# determine the controller class for the component request
|
||||
def component_class(options)
|
||||
if controller = options[:controller]
|
||||
controller.is_a?(Class) ? controller : "#{controller.camelize}Controller".constantize
|
||||
else
|
||||
self.class
|
||||
end
|
||||
end
|
||||
|
||||
# Create a new request object based on the current request.
|
||||
# The new request inherits the session from the current request,
|
||||
# bypassing any session options set for the component controller's class
|
||||
def request_for_component(controller_name, options)
|
||||
new_request = request.dup
|
||||
new_request.session = request.session
|
||||
|
||||
new_request.instance_variable_set(
|
||||
:@parameters,
|
||||
(options[:params] || {}).with_indifferent_access.update(
|
||||
"controller" => controller_name, "action" => options[:action], "id" => options[:id]
|
||||
)
|
||||
)
|
||||
|
||||
new_request
|
||||
end
|
||||
|
||||
def component_logging(options)
|
||||
if logger
|
||||
logger.info "Start rendering component (#{options.inspect}): "
|
||||
result = yield
|
||||
logger.info "\n\nEnd of component rendering"
|
||||
result
|
||||
else
|
||||
yield
|
||||
end
|
||||
end
|
||||
|
||||
def set_session_options_with_components(request)
|
||||
set_session_options_without_components(request) unless component_request?
|
||||
end
|
||||
|
||||
def process_cleanup_with_components
|
||||
process_cleanup_without_components unless component_request?
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -165,7 +165,7 @@ module ActionController #:nodoc:
|
||||
def assign_shortcuts_with_flash(request, response) #:nodoc:
|
||||
assign_shortcuts_without_flash(request, response)
|
||||
flash(:refresh)
|
||||
flash.sweep if @_session && !component_request?
|
||||
flash.sweep if @_session
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -74,6 +74,7 @@ module ActionController
|
||||
def polymorphic_url(record_or_hash_or_array, options = {})
|
||||
if record_or_hash_or_array.kind_of?(Array)
|
||||
record_or_hash_or_array = record_or_hash_or_array.compact
|
||||
record_or_hash_or_array = record_or_hash_or_array[0] if record_or_hash_or_array.size == 1
|
||||
end
|
||||
|
||||
record = extract_record(record_or_hash_or_array)
|
||||
|
||||
@@ -106,12 +106,8 @@ module ActionController
|
||||
# argument
|
||||
class PositionalArgumentsWithAdditionalParams < PositionalArguments
|
||||
def guard_conditions
|
||||
[
|
||||
"args.size == #{route.segment_keys.size + 1}",
|
||||
"!args.last.has_key?(:anchor)",
|
||||
"!args.last.has_key?(:port)",
|
||||
"!args.last.has_key?(:host)"
|
||||
]
|
||||
["args.size == #{route.segment_keys.size + 1}"] +
|
||||
UrlRewriter::RESERVED_OPTIONS.collect{ |key| "!args.last.has_key?(:#{key})" }
|
||||
end
|
||||
|
||||
# This case uses almost the same code as positional arguments,
|
||||
|
||||
@@ -168,6 +168,7 @@ module ActionController
|
||||
#
|
||||
@module.module_eval <<-end_eval # We use module_eval to avoid leaks
|
||||
def #{selector}(*args)
|
||||
|
||||
#{generate_optimisation_block(route, kind)}
|
||||
|
||||
opts = if args.empty? || Hash === args.first
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActionPack #:nodoc:
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -234,16 +234,21 @@ module ActionView #:nodoc:
|
||||
@view_paths = self.class.process_view_paths(paths)
|
||||
end
|
||||
|
||||
# Renders the template present at <tt>template_path</tt> (relative to the view_paths array).
|
||||
# The hash in <tt>local_assigns</tt> is made available as local variables.
|
||||
# Returns the result of a render that's dictated by the options hash. The primary options are:
|
||||
#
|
||||
# * <tt>:partial</tt> - See ActionView::Partials.
|
||||
# * <tt>:update</tt> - Calls update_page with the block given.
|
||||
# * <tt>:file</tt> - Renders an explicit template file (this used to be the old default), add :locals to pass in those.
|
||||
# * <tt>:inline</tt> - Renders an inline template similar to how it's done in the controller.
|
||||
# * <tt>:text</tt> - Renders the text passed in out.
|
||||
#
|
||||
# If no options hash is passed or :update specified, the default is to render a partial and use the second parameter
|
||||
# as the locals hash.
|
||||
def render(options = {}, local_assigns = {}, &block) #:nodoc:
|
||||
local_assigns ||= {}
|
||||
|
||||
if options.is_a?(String)
|
||||
render(:file => options, :locals => local_assigns)
|
||||
elsif options == :update
|
||||
update_page(&block)
|
||||
elsif options.is_a?(Hash)
|
||||
case options
|
||||
when Hash
|
||||
options = options.reverse_merge(:locals => {})
|
||||
if options[:layout]
|
||||
_render_with_layout(options, local_assigns, &block)
|
||||
@@ -256,6 +261,10 @@ module ActionView #:nodoc:
|
||||
elsif options[:text]
|
||||
options[:text]
|
||||
end
|
||||
when :update
|
||||
update_page(&block)
|
||||
else
|
||||
render_partial(:partial => options, :locals => local_assigns)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -317,7 +326,8 @@ module ActionView #:nodoc:
|
||||
template
|
||||
elsif template = self.view_paths[template_file_name]
|
||||
template
|
||||
elsif @_render_stack.first && template = self.view_paths["#{template_file_name}.#{@_render_stack.first.format_and_extension}"]
|
||||
elsif (first_render = @_render_stack.first) && first_render.respond_to?(:format_and_extension) &&
|
||||
(template = self.view_paths["#{template_file_name}.#{first_render.format_and_extension}"])
|
||||
template
|
||||
elsif template_format == :js && template = self.view_paths["#{template_file_name}.html"]
|
||||
@template_format = :html
|
||||
|
||||
@@ -151,7 +151,7 @@ module ActionView
|
||||
# javascript_path "http://www.railsapplication.com/js/xmlhr" # => http://www.railsapplication.com/js/xmlhr.js
|
||||
# javascript_path "http://www.railsapplication.com/js/xmlhr.js" # => http://www.railsapplication.com/js/xmlhr.js
|
||||
def javascript_path(source)
|
||||
JavaScriptTag.create(self, @controller, source).public_path
|
||||
JavaScriptTag.new(self, @controller, source).public_path
|
||||
end
|
||||
alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route
|
||||
|
||||
@@ -314,7 +314,7 @@ module ActionView
|
||||
# stylesheet_path "http://www.railsapplication.com/css/style" # => http://www.railsapplication.com/css/style.css
|
||||
# stylesheet_path "http://www.railsapplication.com/css/style.js" # => http://www.railsapplication.com/css/style.css
|
||||
def stylesheet_path(source)
|
||||
StylesheetTag.create(self, @controller, source).public_path
|
||||
StylesheetTag.new(self, @controller, source).public_path
|
||||
end
|
||||
alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route
|
||||
|
||||
@@ -411,7 +411,7 @@ module ActionView
|
||||
# image_path("/icons/edit.png") # => /icons/edit.png
|
||||
# image_path("http://www.railsapplication.com/img/edit.png") # => http://www.railsapplication.com/img/edit.png
|
||||
def image_path(source)
|
||||
ImageTag.create(self, @controller, source).public_path
|
||||
ImageTag.new(self, @controller, source).public_path
|
||||
end
|
||||
alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route
|
||||
|
||||
@@ -527,20 +527,6 @@ module ActionView
|
||||
Cache = {}
|
||||
CacheGuard = Mutex.new
|
||||
|
||||
def self.create(template, controller, source, include_host = true)
|
||||
CacheGuard.synchronize do
|
||||
key = if controller.respond_to?(:request)
|
||||
[self, controller.request.protocol,
|
||||
ActionController::Base.asset_host,
|
||||
ActionController::Base.relative_url_root,
|
||||
source, include_host]
|
||||
else
|
||||
[self, ActionController::Base.asset_host, source, include_host]
|
||||
end
|
||||
Cache[key] ||= new(template, controller, source, include_host).freeze
|
||||
end
|
||||
end
|
||||
|
||||
ProtocolRegexp = %r{^[-a-z]+://}.freeze
|
||||
|
||||
def initialize(template, controller, source, include_host = true)
|
||||
@@ -551,8 +537,16 @@ module ActionView
|
||||
@controller = controller
|
||||
@source = source
|
||||
@include_host = include_host
|
||||
@cache_key = if controller.respond_to?(:request)
|
||||
[self.class.name,controller.request.protocol,
|
||||
ActionController::Base.asset_host,
|
||||
ActionController::Base.relative_url_root,
|
||||
source, include_host]
|
||||
else
|
||||
[self.class.name,ActionController::Base.asset_host, source, include_host]
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def public_path
|
||||
compute_public_path(@source)
|
||||
end
|
||||
@@ -585,20 +579,32 @@ module ActionView
|
||||
# roots. Rewrite the asset path for cache-busting asset ids. Include
|
||||
# asset host, if configured, with the correct request protocol.
|
||||
def compute_public_path(source)
|
||||
source += ".#{extension}" if missing_extension?(source)
|
||||
unless source =~ ProtocolRegexp
|
||||
source = "/#{directory}/#{source}" unless source[0] == ?/
|
||||
source = rewrite_asset_path(source)
|
||||
source = prepend_relative_url_root(source)
|
||||
if source =~ ProtocolRegexp
|
||||
source += ".#{extension}" if missing_extension?(source)
|
||||
source = prepend_asset_host(source)
|
||||
source
|
||||
else
|
||||
CacheGuard.synchronize do
|
||||
Cache[@cache_key] ||= begin
|
||||
source += ".#{extension}" if missing_extension?(source) || file_exists_with_extension?(source)
|
||||
source = "/#{directory}/#{source}" unless source[0] == ?/
|
||||
source = rewrite_asset_path(source)
|
||||
source = prepend_relative_url_root(source)
|
||||
source = prepend_asset_host(source)
|
||||
source
|
||||
end
|
||||
end
|
||||
end
|
||||
source = prepend_asset_host(source)
|
||||
source
|
||||
end
|
||||
|
||||
|
||||
def missing_extension?(source)
|
||||
extension && (File.extname(source).blank? || File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}")))
|
||||
extension && File.extname(source).blank?
|
||||
end
|
||||
|
||||
|
||||
def file_exists_with_extension?(source)
|
||||
extension && File.exist?(File.join(ASSETS_DIR, directory, "#{source}.#{extension}"))
|
||||
end
|
||||
|
||||
def prepend_relative_url_root(source)
|
||||
relative_url_root = ActionController::Base.relative_url_root
|
||||
if request? && @include_host && source !~ %r{^#{relative_url_root}/}
|
||||
@@ -735,7 +741,7 @@ module ActionView
|
||||
end
|
||||
|
||||
def tag_sources
|
||||
expand_sources.collect { |source| tag_class.create(@template, @controller, source, false) }
|
||||
expand_sources.collect { |source| tag_class.new(@template, @controller, source, false) }
|
||||
end
|
||||
|
||||
def joined_contents
|
||||
|
||||
@@ -31,9 +31,6 @@ module ActionView
|
||||
# to use all basic AJAX functionality. For the Scriptaculous-based
|
||||
# JavaScript helpers, like visual effects, autocompletion, drag and drop
|
||||
# and so on, you should use the method described above.
|
||||
# * Use <tt><%= define_javascript_functions %></tt>: this will copy all the
|
||||
# JavaScript support functions within a single script block. Not
|
||||
# recommended.
|
||||
#
|
||||
# For documentation on +javascript_include_tag+ see
|
||||
# ActionView::Helpers::AssetTagHelper.
|
||||
|
||||
@@ -1,963 +0,0 @@
|
||||
// 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)
|
||||
// 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
|
||||
// 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,
|
||||
// a getUpdatedChoices function that will be invoked every time
|
||||
// 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
|
||||
// autocompletion. Specific auto-completion logic (AJAX, etc)
|
||||
// belongs in getUpdatedChoices.
|
||||
//
|
||||
// Tokenized incremental autocompletion is enabled automatically
|
||||
// when an autocompleter is instantiated with the 'tokens' option
|
||||
// in the options parameter, e.g.:
|
||||
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
|
||||
// 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
|
||||
// allows smart autocompletion after linebreaks.
|
||||
|
||||
if(typeof Effect == 'undefined')
|
||||
throw("controls.js requires including script.aculo.us' effects.js library");
|
||||
|
||||
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;
|
||||
this.entryCount = 0;
|
||||
this.oldElementValue = this.element.value;
|
||||
|
||||
if(this.setOptions)
|
||||
this.setOptions(options);
|
||||
else
|
||||
this.options = options || { };
|
||||
|
||||
this.options.paramName = this.options.paramName || this.element.name;
|
||||
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){
|
||||
if(!update.style.position || update.style.position=='absolute') {
|
||||
update.style.position = 'absolute';
|
||||
Position.clone(element, update, {
|
||||
setHeight: false,
|
||||
offsetTop: element.offsetHeight
|
||||
});
|
||||
}
|
||||
Effect.Appear(update,{duration:0.15});
|
||||
};
|
||||
this.options.onHide = this.options.onHide ||
|
||||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
|
||||
|
||||
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);
|
||||
|
||||
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
|
||||
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
|
||||
},
|
||||
|
||||
show: function() {
|
||||
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
|
||||
if(!this.iefix &&
|
||||
(Prototype.Browser.IE) &&
|
||||
(Element.getStyle(this.update, 'position')=='absolute')) {
|
||||
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;
|
||||
this.update.style.zIndex = 2;
|
||||
Element.show(this.iefix);
|
||||
},
|
||||
|
||||
hide: function() {
|
||||
this.stopIndicator();
|
||||
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
|
||||
if(this.iefix) Element.hide(this.iefix);
|
||||
},
|
||||
|
||||
startIndicator: function() {
|
||||
if(this.options.indicator) Element.show(this.options.indicator);
|
||||
},
|
||||
|
||||
stopIndicator: function() {
|
||||
if(this.options.indicator) Element.hide(this.options.indicator);
|
||||
},
|
||||
|
||||
onKeyPress: function(event) {
|
||||
if(this.active)
|
||||
switch(event.keyCode) {
|
||||
case Event.KEY_TAB:
|
||||
case Event.KEY_RETURN:
|
||||
this.selectEntry();
|
||||
Event.stop(event);
|
||||
case Event.KEY_ESC:
|
||||
this.hide();
|
||||
this.active = false;
|
||||
Event.stop(event);
|
||||
return;
|
||||
case Event.KEY_LEFT:
|
||||
case Event.KEY_RIGHT:
|
||||
return;
|
||||
case Event.KEY_UP:
|
||||
this.markPrevious();
|
||||
this.render();
|
||||
Event.stop(event);
|
||||
return;
|
||||
case Event.KEY_DOWN:
|
||||
this.markNext();
|
||||
this.render();
|
||||
Event.stop(event);
|
||||
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 =
|
||||
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
|
||||
},
|
||||
|
||||
activate: function() {
|
||||
this.changed = false;
|
||||
this.hasFocus = true;
|
||||
this.getUpdatedChoices();
|
||||
},
|
||||
|
||||
onHover: function(event) {
|
||||
var element = Event.findElement(event, 'LI');
|
||||
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;
|
||||
},
|
||||
|
||||
render: function() {
|
||||
if(this.entryCount > 0) {
|
||||
for (var i = 0; i < this.entryCount; i++)
|
||||
this.index==i ?
|
||||
Element.addClassName(this.getEntry(i),"selected") :
|
||||
Element.removeClassName(this.getEntry(i),"selected");
|
||||
if(this.hasFocus) {
|
||||
this.show();
|
||||
this.active = true;
|
||||
}
|
||||
} else {
|
||||
this.active = false;
|
||||
this.hide();
|
||||
}
|
||||
},
|
||||
|
||||
markPrevious: function() {
|
||||
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++
|
||||
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());
|
||||
},
|
||||
|
||||
updateElement: function(selectedElement) {
|
||||
if (this.options.updateElement) {
|
||||
this.options.updateElement(selectedElement);
|
||||
return;
|
||||
}
|
||||
var value = '';
|
||||
if (this.options.select) {
|
||||
var nodes = $(selectedElement).select('.' + this.options.select) || [];
|
||||
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]);
|
||||
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
|
||||
if (whitespace)
|
||||
newValue += whitespace[0];
|
||||
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
|
||||
} else {
|
||||
this.element.value = value;
|
||||
}
|
||||
this.oldElementValue = this.element.value;
|
||||
this.element.focus();
|
||||
|
||||
if (this.options.afterUpdateElement)
|
||||
this.options.afterUpdateElement(this.element, selectedElement);
|
||||
},
|
||||
|
||||
updateChoices: function(choices) {
|
||||
if(!this.changed && this.hasFocus) {
|
||||
this.update.innerHTML = choices;
|
||||
Element.cleanWhitespace(this.update);
|
||||
Element.cleanWhitespace(this.update.down());
|
||||
|
||||
if(this.update.firstChild && this.update.down().childNodes) {
|
||||
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 {
|
||||
this.entryCount = 0;
|
||||
}
|
||||
|
||||
this.stopIndicator();
|
||||
this.index = 0;
|
||||
|
||||
if(this.entryCount==1 && this.options.autoSelect) {
|
||||
this.selectEntry();
|
||||
this.hide();
|
||||
} else {
|
||||
this.render();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
addObservers: function(element) {
|
||||
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
|
||||
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
|
||||
},
|
||||
|
||||
onObserverEvent: function() {
|
||||
this.changed = false;
|
||||
this.tokenBounds = null;
|
||||
if(this.getToken().length>=this.options.minChars) {
|
||||
this.getUpdatedChoices();
|
||||
} else {
|
||||
this.active = false;
|
||||
this.hide();
|
||||
}
|
||||
this.oldElementValue = this.element.value;
|
||||
},
|
||||
|
||||
getToken: function() {
|
||||
var bounds = this.getTokenBounds();
|
||||
return this.element.value.substring(bounds[0], bounds[1]).strip();
|
||||
},
|
||||
|
||||
getTokenBounds: function() {
|
||||
if (null != this.tokenBounds) return this.tokenBounds;
|
||||
var value = this.element.value;
|
||||
if (value.strip().empty()) return [-1, 0];
|
||||
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
|
||||
var offset = (diff == this.oldElementValue.length ? 1 : 0);
|
||||
var prevTokenPos = -1, nextTokenPos = value.length;
|
||||
var tp;
|
||||
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
|
||||
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
|
||||
if (tp > prevTokenPos) prevTokenPos = tp;
|
||||
tp = value.indexOf(this.options.tokens[index], diff + offset);
|
||||
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
|
||||
}
|
||||
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
|
||||
}
|
||||
});
|
||||
|
||||
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
|
||||
var boundary = Math.min(newS.length, oldS.length);
|
||||
for (var index = 0; index < boundary; ++index)
|
||||
if (newS[index] != oldS[index])
|
||||
return index;
|
||||
return boundary;
|
||||
};
|
||||
|
||||
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
|
||||
initialize: function(element, update, url, options) {
|
||||
this.baseInitialize(element, update, options);
|
||||
this.options.asynchronous = true;
|
||||
this.options.onComplete = this.onComplete.bind(this);
|
||||
this.options.defaultParams = this.options.parameters || null;
|
||||
this.url = url;
|
||||
},
|
||||
|
||||
getUpdatedChoices: function() {
|
||||
this.startIndicator();
|
||||
|
||||
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)
|
||||
this.options.parameters += '&' + this.options.defaultParams;
|
||||
|
||||
new Ajax.Request(this.url, this.options);
|
||||
},
|
||||
|
||||
onComplete: function(request) {
|
||||
this.updateChoices(request.responseText);
|
||||
}
|
||||
});
|
||||
|
||||
// The local array autocompleter. Used when you'd prefer to
|
||||
// inject an array of autocompletion options into the page, rather
|
||||
// than sending out Ajax queries, which can be quite slow sometimes.
|
||||
//
|
||||
// The constructor takes four parameters. The first two are, as usual,
|
||||
// the id of the monitored textbox, and id of the autocompletion menu.
|
||||
// The third is the array you want to autocomplete from, and the fourth
|
||||
// is the options block.
|
||||
//
|
||||
// Extra local autocompletion options:
|
||||
// - choices - How many autocompletion choices to offer
|
||||
//
|
||||
// - partialSearch - If false, the autocompleter will match entered
|
||||
// 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
|
||||
// search anywhere in the string, additionally set
|
||||
// the option fullSearch to true (default: off).
|
||||
//
|
||||
// - fullSsearch - Search anywhere in autocomplete array strings.
|
||||
//
|
||||
// - partialChars - How many characters to enter before triggering
|
||||
// a partial match (unlike minChars, which defines
|
||||
// how many characters are required to do any match
|
||||
// at all). Defaults to 2.
|
||||
//
|
||||
// - ignoreCase - Whether to ignore case when autocompleting.
|
||||
// Defaults to true.
|
||||
//
|
||||
// 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.
|
||||
|
||||
Autocompleter.Local = Class.create(Autocompleter.Base, {
|
||||
initialize: function(element, update, array, options) {
|
||||
this.baseInitialize(element, update, options);
|
||||
this.options.array = array;
|
||||
},
|
||||
|
||||
getUpdatedChoices: function() {
|
||||
this.updateChoices(this.options.selector(this));
|
||||
},
|
||||
|
||||
setOptions: function(options) {
|
||||
this.options = Object.extend({
|
||||
choices: 10,
|
||||
partialSearch: true,
|
||||
partialChars: 2,
|
||||
ignoreCase: true,
|
||||
fullSearch: false,
|
||||
selector: function(instance) {
|
||||
var ret = []; // Beginning matches
|
||||
var partial = []; // Inside matches
|
||||
var entry = instance.getToken();
|
||||
var count = 0;
|
||||
|
||||
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()) :
|
||||
elem.indexOf(entry);
|
||||
|
||||
while (foundPos != -1) {
|
||||
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 &&
|
||||
instance.options.partialSearch && foundPos != -1) {
|
||||
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
|
||||
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
|
||||
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
|
||||
foundPos + entry.length) + "</li>");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
return "<ul>" + ret.join('') + "</ul>";
|
||||
}
|
||||
}, options || { });
|
||||
}
|
||||
});
|
||||
|
||||
// AJAX in-place editor and collection editor
|
||||
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
|
||||
|
||||
// Use this if you notice weird scrolling problems on some browsers,
|
||||
// the DOM might be a bit confused when this gets called so do this
|
||||
// waits 1 ms (with setTimeout) until it does the activation
|
||||
Field.scrollFreeActivate = function(field) {
|
||||
setTimeout(function() {
|
||||
Field.activate(field);
|
||||
}, 1);
|
||||
}
|
||||
|
||||
Ajax.InPlaceEditor = Class.create({
|
||||
initialize: function(element, url, options) {
|
||||
this.url = url;
|
||||
this.element = element = $(element);
|
||||
this.prepareOptions();
|
||||
this._controls = { };
|
||||
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
|
||||
Object.extend(this.options, options || { });
|
||||
if (!this.options.formId && this.element.id) {
|
||||
this.options.formId = this.element.id + '-inplaceeditor';
|
||||
if ($(this.options.formId))
|
||||
this.options.formId = '';
|
||||
}
|
||||
if (this.options.externalControl)
|
||||
this.options.externalControl = $(this.options.externalControl);
|
||||
if (!this.options.externalControl)
|
||||
this.options.externalControlOnly = false;
|
||||
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
|
||||
this.element.title = this.options.clickToEditText;
|
||||
this._boundCancelHandler = this.handleFormCancellation.bind(this);
|
||||
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
|
||||
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
|
||||
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
|
||||
this._boundWrapperHandler = this.wrapUp.bind(this);
|
||||
this.registerListeners();
|
||||
},
|
||||
checkForEscapeOrReturn: function(e) {
|
||||
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
|
||||
if (Event.KEY_ESC == e.keyCode)
|
||||
this.handleFormCancellation(e);
|
||||
else if (Event.KEY_RETURN == e.keyCode)
|
||||
this.handleFormSubmission(e);
|
||||
},
|
||||
createControl: function(mode, handler, extraClasses) {
|
||||
var control = this.options[mode + 'Control'];
|
||||
var text = this.options[mode + 'Text'];
|
||||
if ('button' == control) {
|
||||
var btn = document.createElement('input');
|
||||
btn.type = 'submit';
|
||||
btn.value = text;
|
||||
btn.className = 'editor_' + mode + '_button';
|
||||
if ('cancel' == mode)
|
||||
btn.onclick = this._boundCancelHandler;
|
||||
this._form.appendChild(btn);
|
||||
this._controls[mode] = btn;
|
||||
} else if ('link' == control) {
|
||||
var link = document.createElement('a');
|
||||
link.href = '#';
|
||||
link.appendChild(document.createTextNode(text));
|
||||
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
|
||||
link.className = 'editor_' + mode + '_link';
|
||||
if (extraClasses)
|
||||
link.className += ' ' + extraClasses;
|
||||
this._form.appendChild(link);
|
||||
this._controls[mode] = link;
|
||||
}
|
||||
},
|
||||
createEditField: function() {
|
||||
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
|
||||
var fld;
|
||||
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
|
||||
fld = document.createElement('input');
|
||||
fld.type = 'text';
|
||||
var size = this.options.size || this.options.cols || 0;
|
||||
if (0 < size) fld.size = size;
|
||||
} else {
|
||||
fld = document.createElement('textarea');
|
||||
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
|
||||
fld.cols = this.options.cols || 40;
|
||||
}
|
||||
fld.name = this.options.paramName;
|
||||
fld.value = text; // No HTML breaks conversion anymore
|
||||
fld.className = 'editor_field';
|
||||
if (this.options.submitOnBlur)
|
||||
fld.onblur = this._boundSubmitHandler;
|
||||
this._controls.editor = fld;
|
||||
if (this.options.loadTextURL)
|
||||
this.loadExternalText();
|
||||
this._form.appendChild(this._controls.editor);
|
||||
},
|
||||
createForm: function() {
|
||||
var ipe = this;
|
||||
function addText(mode, condition) {
|
||||
var text = ipe.options['text' + mode + 'Controls'];
|
||||
if (!text || condition === false) return;
|
||||
ipe._form.appendChild(document.createTextNode(text));
|
||||
};
|
||||
this._form = $(document.createElement('form'));
|
||||
this._form.id = this.options.formId;
|
||||
this._form.addClassName(this.options.formClassName);
|
||||
this._form.onsubmit = this._boundSubmitHandler;
|
||||
this.createEditField();
|
||||
if ('textarea' == this._controls.editor.tagName.toLowerCase())
|
||||
this._form.appendChild(document.createElement('br'));
|
||||
if (this.options.onFormCustomization)
|
||||
this.options.onFormCustomization(this, this._form);
|
||||
addText('Before', this.options.okControl || this.options.cancelControl);
|
||||
this.createControl('ok', this._boundSubmitHandler);
|
||||
addText('Between', this.options.okControl && this.options.cancelControl);
|
||||
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
|
||||
addText('After', this.options.okControl || this.options.cancelControl);
|
||||
},
|
||||
destroy: function() {
|
||||
if (this._oldInnerHTML)
|
||||
this.element.innerHTML = this._oldInnerHTML;
|
||||
this.leaveEditMode();
|
||||
this.unregisterListeners();
|
||||
},
|
||||
enterEditMode: function(e) {
|
||||
if (this._saving || this._editing) return;
|
||||
this._editing = true;
|
||||
this.triggerCallback('onEnterEditMode');
|
||||
if (this.options.externalControl)
|
||||
this.options.externalControl.hide();
|
||||
this.element.hide();
|
||||
this.createForm();
|
||||
this.element.parentNode.insertBefore(this._form, this.element);
|
||||
if (!this.options.loadTextURL)
|
||||
this.postProcessEditField();
|
||||
if (e) Event.stop(e);
|
||||
},
|
||||
enterHover: function(e) {
|
||||
if (this.options.hoverClassName)
|
||||
this.element.addClassName(this.options.hoverClassName);
|
||||
if (this._saving) return;
|
||||
this.triggerCallback('onEnterHover');
|
||||
},
|
||||
getText: function() {
|
||||
return this.element.innerHTML;
|
||||
},
|
||||
handleAJAXFailure: function(transport) {
|
||||
this.triggerCallback('onFailure', transport);
|
||||
if (this._oldInnerHTML) {
|
||||
this.element.innerHTML = this._oldInnerHTML;
|
||||
this._oldInnerHTML = null;
|
||||
}
|
||||
},
|
||||
handleFormCancellation: function(e) {
|
||||
this.wrapUp();
|
||||
if (e) Event.stop(e);
|
||||
},
|
||||
handleFormSubmission: function(e) {
|
||||
var form = this._form;
|
||||
var value = $F(this._controls.editor);
|
||||
this.prepareSubmission();
|
||||
var params = this.options.callback(form, value) || '';
|
||||
if (Object.isString(params))
|
||||
params = params.toQueryParams();
|
||||
params.editorId = this.element.id;
|
||||
if (this.options.htmlResponse) {
|
||||
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
|
||||
Object.extend(options, {
|
||||
parameters: params,
|
||||
onComplete: this._boundWrapperHandler,
|
||||
onFailure: this._boundFailureHandler
|
||||
});
|
||||
new Ajax.Updater({ success: this.element }, this.url, options);
|
||||
} else {
|
||||
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
|
||||
Object.extend(options, {
|
||||
parameters: params,
|
||||
onComplete: this._boundWrapperHandler,
|
||||
onFailure: this._boundFailureHandler
|
||||
});
|
||||
new Ajax.Request(this.url, options);
|
||||
}
|
||||
if (e) Event.stop(e);
|
||||
},
|
||||
leaveEditMode: function() {
|
||||
this.element.removeClassName(this.options.savingClassName);
|
||||
this.removeForm();
|
||||
this.leaveHover();
|
||||
this.element.style.backgroundColor = this._originalBackground;
|
||||
this.element.show();
|
||||
if (this.options.externalControl)
|
||||
this.options.externalControl.show();
|
||||
this._saving = false;
|
||||
this._editing = false;
|
||||
this._oldInnerHTML = null;
|
||||
this.triggerCallback('onLeaveEditMode');
|
||||
},
|
||||
leaveHover: function(e) {
|
||||
if (this.options.hoverClassName)
|
||||
this.element.removeClassName(this.options.hoverClassName);
|
||||
if (this._saving) return;
|
||||
this.triggerCallback('onLeaveHover');
|
||||
},
|
||||
loadExternalText: function() {
|
||||
this._form.addClassName(this.options.loadingClassName);
|
||||
this._controls.editor.disabled = true;
|
||||
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
|
||||
Object.extend(options, {
|
||||
parameters: 'editorId=' + encodeURIComponent(this.element.id),
|
||||
onComplete: Prototype.emptyFunction,
|
||||
onSuccess: function(transport) {
|
||||
this._form.removeClassName(this.options.loadingClassName);
|
||||
var text = transport.responseText;
|
||||
if (this.options.stripLoadedTextTags)
|
||||
text = text.stripTags();
|
||||
this._controls.editor.value = text;
|
||||
this._controls.editor.disabled = false;
|
||||
this.postProcessEditField();
|
||||
}.bind(this),
|
||||
onFailure: this._boundFailureHandler
|
||||
});
|
||||
new Ajax.Request(this.options.loadTextURL, options);
|
||||
},
|
||||
postProcessEditField: function() {
|
||||
var fpc = this.options.fieldPostCreation;
|
||||
if (fpc)
|
||||
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
|
||||
},
|
||||
prepareOptions: function() {
|
||||
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
|
||||
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
|
||||
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
|
||||
Object.extend(this.options, defs);
|
||||
}.bind(this));
|
||||
},
|
||||
prepareSubmission: function() {
|
||||
this._saving = true;
|
||||
this.removeForm();
|
||||
this.leaveHover();
|
||||
this.showSaving();
|
||||
},
|
||||
registerListeners: function() {
|
||||
this._listeners = { };
|
||||
var listener;
|
||||
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
|
||||
listener = this[pair.value].bind(this);
|
||||
this._listeners[pair.key] = listener;
|
||||
if (!this.options.externalControlOnly)
|
||||
this.element.observe(pair.key, listener);
|
||||
if (this.options.externalControl)
|
||||
this.options.externalControl.observe(pair.key, listener);
|
||||
}.bind(this));
|
||||
},
|
||||
removeForm: function() {
|
||||
if (!this._form) return;
|
||||
this._form.remove();
|
||||
this._form = null;
|
||||
this._controls = { };
|
||||
},
|
||||
showSaving: function() {
|
||||
this._oldInnerHTML = this.element.innerHTML;
|
||||
this.element.innerHTML = this.options.savingText;
|
||||
this.element.addClassName(this.options.savingClassName);
|
||||
this.element.style.backgroundColor = this._originalBackground;
|
||||
this.element.show();
|
||||
},
|
||||
triggerCallback: function(cbName, arg) {
|
||||
if ('function' == typeof this.options[cbName]) {
|
||||
this.options[cbName](this, arg);
|
||||
}
|
||||
},
|
||||
unregisterListeners: function() {
|
||||
$H(this._listeners).each(function(pair) {
|
||||
if (!this.options.externalControlOnly)
|
||||
this.element.stopObserving(pair.key, pair.value);
|
||||
if (this.options.externalControl)
|
||||
this.options.externalControl.stopObserving(pair.key, pair.value);
|
||||
}.bind(this));
|
||||
},
|
||||
wrapUp: function(transport) {
|
||||
this.leaveEditMode();
|
||||
// Can't use triggerCallback due to backward compatibility: requires
|
||||
// binding + direct element
|
||||
this._boundComplete(transport, this.element);
|
||||
}
|
||||
});
|
||||
|
||||
Object.extend(Ajax.InPlaceEditor.prototype, {
|
||||
dispose: Ajax.InPlaceEditor.prototype.destroy
|
||||
});
|
||||
|
||||
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
|
||||
initialize: function($super, element, url, options) {
|
||||
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
|
||||
$super(element, url, options);
|
||||
},
|
||||
|
||||
createEditField: function() {
|
||||
var list = document.createElement('select');
|
||||
list.name = this.options.paramName;
|
||||
list.size = 1;
|
||||
this._controls.editor = list;
|
||||
this._collection = this.options.collection || [];
|
||||
if (this.options.loadCollectionURL)
|
||||
this.loadCollection();
|
||||
else
|
||||
this.checkForExternalText();
|
||||
this._form.appendChild(this._controls.editor);
|
||||
},
|
||||
|
||||
loadCollection: function() {
|
||||
this._form.addClassName(this.options.loadingClassName);
|
||||
this.showLoadingText(this.options.loadingCollectionText);
|
||||
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
|
||||
Object.extend(options, {
|
||||
parameters: 'editorId=' + encodeURIComponent(this.element.id),
|
||||
onComplete: Prototype.emptyFunction,
|
||||
onSuccess: function(transport) {
|
||||
var js = transport.responseText.strip();
|
||||
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
|
||||
throw 'Server returned an invalid collection representation.';
|
||||
this._collection = eval(js);
|
||||
this.checkForExternalText();
|
||||
}.bind(this),
|
||||
onFailure: this.onFailure
|
||||
});
|
||||
new Ajax.Request(this.options.loadCollectionURL, options);
|
||||
},
|
||||
|
||||
showLoadingText: function(text) {
|
||||
this._controls.editor.disabled = true;
|
||||
var tempOption = this._controls.editor.firstChild;
|
||||
if (!tempOption) {
|
||||
tempOption = document.createElement('option');
|
||||
tempOption.value = '';
|
||||
this._controls.editor.appendChild(tempOption);
|
||||
tempOption.selected = true;
|
||||
}
|
||||
tempOption.update((text || '').stripScripts().stripTags());
|
||||
},
|
||||
|
||||
checkForExternalText: function() {
|
||||
this._text = this.getText();
|
||||
if (this.options.loadTextURL)
|
||||
this.loadExternalText();
|
||||
else
|
||||
this.buildOptionList();
|
||||
},
|
||||
|
||||
loadExternalText: function() {
|
||||
this.showLoadingText(this.options.loadingText);
|
||||
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
|
||||
Object.extend(options, {
|
||||
parameters: 'editorId=' + encodeURIComponent(this.element.id),
|
||||
onComplete: Prototype.emptyFunction,
|
||||
onSuccess: function(transport) {
|
||||
this._text = transport.responseText.strip();
|
||||
this.buildOptionList();
|
||||
}.bind(this),
|
||||
onFailure: this.onFailure
|
||||
});
|
||||
new Ajax.Request(this.options.loadTextURL, options);
|
||||
},
|
||||
|
||||
buildOptionList: function() {
|
||||
this._form.removeClassName(this.options.loadingClassName);
|
||||
this._collection = this._collection.map(function(entry) {
|
||||
return 2 === entry.length ? entry : [entry, entry].flatten();
|
||||
});
|
||||
var marker = ('value' in this.options) ? this.options.value : this._text;
|
||||
var textFound = this._collection.any(function(entry) {
|
||||
return entry[0] == marker;
|
||||
}.bind(this));
|
||||
this._controls.editor.update('');
|
||||
var option;
|
||||
this._collection.each(function(entry, index) {
|
||||
option = document.createElement('option');
|
||||
option.value = entry[0];
|
||||
option.selected = textFound ? entry[0] == marker : 0 == index;
|
||||
option.appendChild(document.createTextNode(entry[1]));
|
||||
this._controls.editor.appendChild(option);
|
||||
}.bind(this));
|
||||
this._controls.editor.disabled = false;
|
||||
Field.scrollFreeActivate(this._controls.editor);
|
||||
}
|
||||
});
|
||||
|
||||
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
|
||||
//**** This only exists for a while, in order to let ****
|
||||
//**** users adapt to the new API. Read up on the new ****
|
||||
//**** API and convert your code to it ASAP! ****
|
||||
|
||||
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
|
||||
if (!options) return;
|
||||
function fallback(name, expr) {
|
||||
if (name in options || expr === undefined) return;
|
||||
options[name] = expr;
|
||||
};
|
||||
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
|
||||
options.cancelLink == options.cancelButton == false ? false : undefined)));
|
||||
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
|
||||
options.okLink == options.okButton == false ? false : undefined)));
|
||||
fallback('highlightColor', options.highlightcolor);
|
||||
fallback('highlightEndColor', options.highlightendcolor);
|
||||
};
|
||||
|
||||
Object.extend(Ajax.InPlaceEditor, {
|
||||
DefaultOptions: {
|
||||
ajaxOptions: { },
|
||||
autoRows: 3, // Use when multi-line w/ rows == 1
|
||||
cancelControl: 'link', // 'link'|'button'|false
|
||||
cancelText: 'cancel',
|
||||
clickToEditText: 'Click to edit',
|
||||
externalControl: null, // id|elt
|
||||
externalControlOnly: false,
|
||||
fieldPostCreation: 'activate', // 'activate'|'focus'|false
|
||||
formClassName: 'inplaceeditor-form',
|
||||
formId: null, // id|elt
|
||||
highlightColor: '#ffff99',
|
||||
highlightEndColor: '#ffffff',
|
||||
hoverClassName: '',
|
||||
htmlResponse: true,
|
||||
loadingClassName: 'inplaceeditor-loading',
|
||||
loadingText: 'Loading...',
|
||||
okControl: 'button', // 'link'|'button'|false
|
||||
okText: 'ok',
|
||||
paramName: 'value',
|
||||
rows: 1, // If 1 and multi-line, uses autoRows
|
||||
savingClassName: 'inplaceeditor-saving',
|
||||
savingText: 'Saving...',
|
||||
size: 0,
|
||||
stripLoadedTextTags: false,
|
||||
submitOnBlur: false,
|
||||
textAfterControls: '',
|
||||
textBeforeControls: '',
|
||||
textBetweenControls: ''
|
||||
},
|
||||
DefaultCallbacks: {
|
||||
callback: function(form) {
|
||||
return Form.serialize(form);
|
||||
},
|
||||
onComplete: function(transport, element) {
|
||||
// For backward compatibility, this one is bound to the IPE, and passes
|
||||
// the element directly. It was too often customized, so we don't break it.
|
||||
new Effect.Highlight(element, {
|
||||
startcolor: this.options.highlightColor, keepBackgroundImage: true });
|
||||
},
|
||||
onEnterEditMode: null,
|
||||
onEnterHover: function(ipe) {
|
||||
ipe.element.style.backgroundColor = ipe.options.highlightColor;
|
||||
if (ipe._effect)
|
||||
ipe._effect.cancel();
|
||||
},
|
||||
onFailure: function(transport, ipe) {
|
||||
alert('Error communication with the server: ' + transport.responseText.stripTags());
|
||||
},
|
||||
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
|
||||
onLeaveEditMode: null,
|
||||
onLeaveHover: function(ipe) {
|
||||
ipe._effect = new Effect.Highlight(ipe.element, {
|
||||
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
|
||||
restorecolor: ipe._originalBackground, keepBackgroundImage: true
|
||||
});
|
||||
}
|
||||
},
|
||||
Listeners: {
|
||||
click: 'enterEditMode',
|
||||
keydown: 'checkForEscapeOrReturn',
|
||||
mouseover: 'enterHover',
|
||||
mouseout: 'leaveHover'
|
||||
}
|
||||
});
|
||||
|
||||
Ajax.InPlaceCollectionEditor.DefaultOptions = {
|
||||
loadingCollectionText: 'Loading options...'
|
||||
};
|
||||
|
||||
// Delayed observer, like Form.Element.Observer,
|
||||
// but waits for delay after last key input
|
||||
// Ideal for live-search fields
|
||||
|
||||
Form.Element.DelayedObserver = Class.create({
|
||||
initialize: function(element, delay, callback) {
|
||||
this.delay = delay || 0.5;
|
||||
this.element = $(element);
|
||||
this.callback = callback;
|
||||
this.timer = null;
|
||||
this.lastValue = $F(this.element);
|
||||
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
|
||||
},
|
||||
delayedListener: function(event) {
|
||||
if(this.lastValue == $F(this.element)) return;
|
||||
if(this.timer) clearTimeout(this.timer);
|
||||
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
|
||||
this.lastValue = $F(this.element);
|
||||
},
|
||||
onTimerEvent: function() {
|
||||
this.timer = null;
|
||||
this.callback(this.element, $F(this.element));
|
||||
}
|
||||
});
|
||||
@@ -1,972 +0,0 @@
|
||||
// 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)
|
||||
//
|
||||
// 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/
|
||||
|
||||
if(Object.isUndefined(Effect))
|
||||
throw("dragdrop.js requires including script.aculo.us' effects.js library");
|
||||
|
||||
var Droppables = {
|
||||
drops: [],
|
||||
|
||||
remove: function(element) {
|
||||
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
|
||||
},
|
||||
|
||||
add: function(element) {
|
||||
element = $(element);
|
||||
var options = Object.extend({
|
||||
greedy: true,
|
||||
hoverclass: null,
|
||||
tree: false
|
||||
}, arguments[1] || { });
|
||||
|
||||
// cache containers
|
||||
if(options.containment) {
|
||||
options._containers = [];
|
||||
var containment = options.containment;
|
||||
if(Object.isArray(containment)) {
|
||||
containment.each( function(c) { options._containers.push($(c)) });
|
||||
} else {
|
||||
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;
|
||||
} 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(
|
||||
function(v) { return drop.accept.include(v) } ) )) &&
|
||||
Position.within(drop.element, point[0], point[1]) );
|
||||
},
|
||||
|
||||
deactivate: function(drop) {
|
||||
if(drop.hoverclass)
|
||||
Element.removeClassName(drop.element, drop.hoverclass);
|
||||
this.last_active = null;
|
||||
},
|
||||
|
||||
activate: function(drop) {
|
||||
if(drop.hoverclass)
|
||||
Element.addClassName(drop.element, drop.hoverclass);
|
||||
this.last_active = drop;
|
||||
},
|
||||
|
||||
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);
|
||||
|
||||
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
|
||||
if (drop) {
|
||||
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);
|
||||
}
|
||||
},
|
||||
|
||||
fire: function(event, element) {
|
||||
if(!this.last_active) return;
|
||||
Position.prepare();
|
||||
|
||||
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;
|
||||
}
|
||||
},
|
||||
|
||||
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) {
|
||||
Event.stopObserving(document, "mouseup", this.eventMouseUp);
|
||||
Event.stopObserving(document, "mousemove", this.eventMouseMove);
|
||||
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);
|
||||
} 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.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;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
var Draggable = Class.create({
|
||||
initialize: function(element) {
|
||||
var defaults = {
|
||||
handle: false,
|
||||
reverteffect: function(element, top_offset, left_offset) {
|
||||
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
|
||||
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
|
||||
queue: {scope:'_draggable', position:'end'}
|
||||
});
|
||||
},
|
||||
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,
|
||||
queue: {scope:'_draggable', position:'end'},
|
||||
afterFinish: function(){
|
||||
Draggable._dragging[element] = false
|
||||
}
|
||||
});
|
||||
},
|
||||
zindex: 1000,
|
||||
revert: false,
|
||||
quiet: false,
|
||||
scroll: false,
|
||||
scrollSensitivity: 20,
|
||||
scrollSpeed: 15,
|
||||
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});
|
||||
}
|
||||
});
|
||||
|
||||
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
|
||||
|
||||
this.options = options;
|
||||
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)) {
|
||||
// abort on form elements, fixes a Firefox issue
|
||||
var src = Event.element(event);
|
||||
if((tag_name = src.tagName.toUpperCase()) && (
|
||||
tag_name=='INPUT' ||
|
||||
tag_name=='SELECT' ||
|
||||
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)
|
||||
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);
|
||||
this.originalScrollLeft = where.left;
|
||||
this.originalScrollTop = where.top;
|
||||
} else {
|
||||
this.originalScrollLeft = this.options.scroll.scrollLeft;
|
||||
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 ]; }
|
||||
} else {
|
||||
p = Position.page(this.options.scroll);
|
||||
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
|
||||
p[1] += this.options.scroll.scrollTop + Position.deltaY;
|
||||
p.push(p[0]+this.options.scroll.offsetWidth);
|
||||
p.push(p[1]+this.options.scroll.offsetHeight);
|
||||
}
|
||||
var speed = [0,0];
|
||||
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
|
||||
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
|
||||
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
|
||||
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)
|
||||
Position.relativize(this.element);
|
||||
delete this.element._originallyAbsolute;
|
||||
Element.remove(this._clone);
|
||||
this._clone = null;
|
||||
}
|
||||
|
||||
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')
|
||||
this.options.reverteffect(this.element,
|
||||
d[1]-this.delta[1], d[0]-this.delta[0]);
|
||||
} else {
|
||||
this.delta = d;
|
||||
}
|
||||
|
||||
if(this.options.zindex)
|
||||
this.element.style.zIndex = this.originalZ;
|
||||
|
||||
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])
|
||||
}.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))
|
||||
} else {
|
||||
p = p.map( function(v) {
|
||||
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;
|
||||
this.lastScrolled = current;
|
||||
if(this.options.scroll == window) {
|
||||
with (this._getWindowScroll(this.options.scroll)) {
|
||||
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
|
||||
var d = delta / 1000;
|
||||
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
|
||||
}
|
||||
}
|
||||
} else {
|
||||
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);
|
||||
if (this._isScrollChild) {
|
||||
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
|
||||
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
|
||||
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
|
||||
if (Draggables._lastScrollPointer[0] < 0)
|
||||
Draggables._lastScrollPointer[0] = 0;
|
||||
if (Draggables._lastScrollPointer[1] < 0)
|
||||
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) {
|
||||
if (w.document.documentElement && documentElement.scrollTop) {
|
||||
T = documentElement.scrollTop;
|
||||
L = documentElement.scrollLeft;
|
||||
} else if (w.document.body) {
|
||||
T = body.scrollTop;
|
||||
L = body.scrollLeft;
|
||||
}
|
||||
if (w.innerWidth) {
|
||||
W = w.innerWidth;
|
||||
H = w.innerHeight;
|
||||
} else if (w.document.documentElement && documentElement.clientWidth) {
|
||||
W = documentElement.clientWidth;
|
||||
H = documentElement.clientHeight;
|
||||
} else {
|
||||
W = body.offsetWidth;
|
||||
H = body.offsetHeight
|
||||
}
|
||||
}
|
||||
return { top: T, left: L, width: W, height: H };
|
||||
}
|
||||
});
|
||||
|
||||
Draggable._dragging = { };
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
var SortableObserver = Class.create({
|
||||
initialize: function(element, observer) {
|
||||
this.element = $(element);
|
||||
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))
|
||||
this.observer(this.element)
|
||||
}
|
||||
});
|
||||
|
||||
var Sortable = {
|
||||
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
|
||||
|
||||
sortables: { },
|
||||
|
||||
_findRootElement: function(element) {
|
||||
while (element.tagName.toUpperCase() != "BODY") {
|
||||
if(element.id && Sortable.sortables[element.id]) return element;
|
||||
element = element.parentNode;
|
||||
}
|
||||
},
|
||||
|
||||
options: function(element) {
|
||||
element = Sortable._findRootElement($(element));
|
||||
if(!element) return;
|
||||
return Sortable.sortables[element.id];
|
||||
},
|
||||
|
||||
destroy: function(element){
|
||||
var s = Sortable.options(element);
|
||||
|
||||
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({
|
||||
element: element,
|
||||
tag: 'li', // assumes li children, override with tag: 'tagname'
|
||||
dropOnEmpty: false,
|
||||
tree: false,
|
||||
treeTag: 'ul',
|
||||
overlap: 'vertical', // one of 'vertical', 'horizontal'
|
||||
constraint: 'vertical', // one of 'vertical', 'horizontal', false
|
||||
containment: element, // also takes array of elements (or id's); or false
|
||||
handle: false, // or a CSS class
|
||||
only: false,
|
||||
delay: 0,
|
||||
hoverclass: null,
|
||||
ghosting: false,
|
||||
quiet: false,
|
||||
scroll: false,
|
||||
scrollSensitivity: 20,
|
||||
scrollSpeed: 15,
|
||||
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,
|
||||
onUpdate: Prototype.emptyFunction
|
||||
}, arguments[1] || { });
|
||||
|
||||
// clear any old sortable with same element
|
||||
this.destroy(element);
|
||||
|
||||
// build options for the draggables
|
||||
var options_for_draggable = {
|
||||
revert: true,
|
||||
quiet: options.quiet,
|
||||
scroll: options.scroll,
|
||||
scrollSpeed: options.scrollSpeed,
|
||||
scrollSensitivity: options.scrollSensitivity,
|
||||
delay: options.delay,
|
||||
ghosting: options.ghosting,
|
||||
constraint: options.constraint,
|
||||
handle: options.handle };
|
||||
|
||||
if(options.starteffect)
|
||||
options_for_draggable.starteffect = options.starteffect;
|
||||
|
||||
if(options.reverteffect)
|
||||
options_for_draggable.reverteffect = options.reverteffect;
|
||||
else
|
||||
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
|
||||
element.style.top = 0;
|
||||
element.style.left = 0;
|
||||
};
|
||||
|
||||
if(options.endeffect)
|
||||
options_for_draggable.endeffect = options.endeffect;
|
||||
|
||||
if(options.zindex)
|
||||
options_for_draggable.zindex = options.zindex;
|
||||
|
||||
// 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);
|
||||
|
||||
options.draggables = [];
|
||||
options.droppables = [];
|
||||
|
||||
// drop on empty handling
|
||||
if(options.dropOnEmpty || options.tree) {
|
||||
Droppables.add(element, options_for_tree);
|
||||
options.droppables.push(element);
|
||||
}
|
||||
|
||||
(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.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);
|
||||
});
|
||||
|
||||
if(options.tree) {
|
||||
(Sortable.findTreeElements(element, options) || []).each( function(e) {
|
||||
Droppables.add(e, options_for_tree);
|
||||
e.treeNode = element;
|
||||
options.droppables.push(e);
|
||||
});
|
||||
}
|
||||
|
||||
// keep reference
|
||||
this.sortables[element.id] = options;
|
||||
|
||||
// for onupdate
|
||||
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
|
||||
|
||||
},
|
||||
|
||||
// return all suitable-for-sortable elements in a guaranteed order
|
||||
findElements: function(element, options) {
|
||||
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);
|
||||
},
|
||||
|
||||
onHover: function(element, dropon, overlap) {
|
||||
if(Element.isParent(dropon, element)) return;
|
||||
|
||||
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
|
||||
return;
|
||||
} else if(overlap>0.5) {
|
||||
Sortable.mark(dropon, 'before');
|
||||
if(dropon.previousSibling != element) {
|
||||
var oldParentNode = element.parentNode;
|
||||
element.style.visibility = "hidden"; // fix gecko rendering
|
||||
dropon.parentNode.insertBefore(element, dropon);
|
||||
if(dropon.parentNode!=oldParentNode)
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
Sortable.options(dropon.parentNode).onChange(element);
|
||||
}
|
||||
} else {
|
||||
Sortable.mark(dropon, 'after');
|
||||
var nextElement = dropon.nextSibling || null;
|
||||
if(nextElement != element) {
|
||||
var oldParentNode = element.parentNode;
|
||||
element.style.visibility = "hidden"; // fix gecko rendering
|
||||
dropon.parentNode.insertBefore(element, nextElement);
|
||||
if(dropon.parentNode!=oldParentNode)
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
Sortable.options(dropon.parentNode).onChange(element);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
onEmptyHover: function(element, dropon, overlap) {
|
||||
var oldParentNode = element.parentNode;
|
||||
var droponOptions = Sortable.options(dropon);
|
||||
|
||||
if(!Element.isParent(dropon, element)) {
|
||||
var index;
|
||||
|
||||
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
|
||||
var child = null;
|
||||
|
||||
if(children) {
|
||||
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
|
||||
|
||||
for (index = 0; index < children.length; index += 1) {
|
||||
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
|
||||
offset -= Element.offsetSize (children[index], droponOptions.overlap);
|
||||
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
|
||||
child = index + 1 < children.length ? children[index + 1] : null;
|
||||
break;
|
||||
} else {
|
||||
child = children[index];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
dropon.insertBefore(element, child);
|
||||
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
droponOptions.onChange(element);
|
||||
}
|
||||
},
|
||||
|
||||
unmark: function() {
|
||||
if(Sortable._marker) Sortable._marker.hide();
|
||||
},
|
||||
|
||||
mark: function(dropon, position) {
|
||||
// mark on ghosting only
|
||||
var sortable = Sortable.options(dropon.parentNode);
|
||||
if(sortable && !sortable.ghosting) return;
|
||||
|
||||
if(!Sortable._marker) {
|
||||
Sortable._marker =
|
||||
($('dropmarker') || Element.extend(document.createElement('DIV'))).
|
||||
hide().addClassName('dropmarker').setStyle({position:'absolute'});
|
||||
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
|
||||
}
|
||||
var offsets = Position.cumulativeOffset(dropon);
|
||||
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
|
||||
|
||||
if(position=='after')
|
||||
if(sortable.overlap == 'horizontal')
|
||||
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
|
||||
else
|
||||
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
|
||||
|
||||
Sortable._marker.show();
|
||||
},
|
||||
|
||||
_tree: function(element, options, parent) {
|
||||
var children = Sortable.findElements(element, options) || [];
|
||||
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
var match = children[i].id.match(options.format);
|
||||
|
||||
if (!match) continue;
|
||||
|
||||
var child = {
|
||||
id: encodeURIComponent(match ? match[1] : null),
|
||||
element: element,
|
||||
parent: parent,
|
||||
children: [],
|
||||
position: parent.children.length,
|
||||
container: $(children[i]).down(options.treeTag)
|
||||
}
|
||||
|
||||
/* Get the element containing the children and recurse over it */
|
||||
if (child.container)
|
||||
this._tree(child.container, options, child)
|
||||
|
||||
parent.children.push (child);
|
||||
}
|
||||
|
||||
return parent;
|
||||
},
|
||||
|
||||
tree: function(element) {
|
||||
element = $(element);
|
||||
var sortableOptions = this.options(element);
|
||||
var options = Object.extend({
|
||||
tag: sortableOptions.tag,
|
||||
treeTag: sortableOptions.treeTag,
|
||||
only: sortableOptions.only,
|
||||
name: element.id,
|
||||
format: sortableOptions.format
|
||||
}, arguments[1] || { });
|
||||
|
||||
var root = {
|
||||
id: null,
|
||||
parent: null,
|
||||
children: [],
|
||||
container: element,
|
||||
position: 0
|
||||
}
|
||||
|
||||
return Sortable._tree(element, options, root);
|
||||
},
|
||||
|
||||
/* Construct a [i] index for a particular node */
|
||||
_constructIndex: function(node) {
|
||||
var index = '';
|
||||
do {
|
||||
if (node.id) index = '[' + node.position + ']' + index;
|
||||
} while ((node = node.parent) != null);
|
||||
return index;
|
||||
},
|
||||
|
||||
sequence: function(element) {
|
||||
element = $(element);
|
||||
var options = Object.extend(this.options(element), arguments[1] || { });
|
||||
|
||||
return $(this.findElements(element, options) || []).map( function(item) {
|
||||
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
|
||||
});
|
||||
},
|
||||
|
||||
setSequence: function(element, new_sequence) {
|
||||
element = $(element);
|
||||
var options = Object.extend(this.options(element), arguments[2] || { });
|
||||
|
||||
var nodeMap = { };
|
||||
this.findElements(element, options).each( function(n) {
|
||||
if (n.id.match(options.format))
|
||||
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
|
||||
n.parentNode.removeChild(n);
|
||||
});
|
||||
|
||||
new_sequence.each(function(ident) {
|
||||
var n = nodeMap[ident];
|
||||
if (n) {
|
||||
n[1].appendChild(n[0]);
|
||||
delete nodeMap[ident];
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
serialize: function(element) {
|
||||
element = $(element);
|
||||
var options = Object.extend(Sortable.options(element), arguments[1] || { });
|
||||
var name = encodeURIComponent(
|
||||
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
|
||||
|
||||
if (options.tree) {
|
||||
return Sortable.tree(element, arguments[1]).children.map( function (item) {
|
||||
return [name + Sortable._constructIndex(item) + "[id]=" +
|
||||
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
|
||||
}).flatten().join('&');
|
||||
} else {
|
||||
return Sortable.sequence(element, arguments[1]).map( function(item) {
|
||||
return name + "[]=" + encodeURIComponent(item);
|
||||
}).join('&');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Returns true if child is contained within element
|
||||
Element.isParent = function(child, element) {
|
||||
if (!child.parentNode || child == element) return false;
|
||||
if (child.parentNode == element) return true;
|
||||
return Element.isParent(child.parentNode, element);
|
||||
}
|
||||
|
||||
Element.findChildren = function(element, only, recursive, tagName) {
|
||||
if(!element.hasChildNodes()) return null;
|
||||
tagName = tagName.toUpperCase();
|
||||
if(only) only = [only].flatten();
|
||||
var elements = [];
|
||||
$A(element.childNodes).each( function(e) {
|
||||
if(e.tagName && e.tagName.toUpperCase()==tagName &&
|
||||
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
|
||||
elements.push(e);
|
||||
if(recursive) {
|
||||
var grandchildren = Element.findChildren(e, only, recursive, tagName);
|
||||
if(grandchildren) elements.push(grandchildren);
|
||||
}
|
||||
});
|
||||
|
||||
return (elements.length>0 ? elements.flatten() : []);
|
||||
}
|
||||
|
||||
Element.offsetSize = function (element, type) {
|
||||
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,7 @@ module ActionView
|
||||
module TagHelper
|
||||
include ERB::Util
|
||||
|
||||
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple).to_set
|
||||
BOOLEAN_ATTRIBUTES = %w(disabled readonly multiple checked).to_set
|
||||
BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym))
|
||||
|
||||
# Returns an empty HTML tag of type +name+ which by default is XHTML
|
||||
|
||||
@@ -46,6 +46,38 @@ module ActionView
|
||||
#
|
||||
# This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
|
||||
#
|
||||
# == Rendering objects with the RecordIdentifier
|
||||
#
|
||||
# Instead of explicitly naming the location of a partial, you can also let the RecordIdentifier do the work if
|
||||
# you're following its conventions for RecordIdentifier#partial_path. Examples:
|
||||
#
|
||||
# # @account is an Account instance, so it uses the RecordIdentifier to replace
|
||||
# # <%= render :partial => "accounts/account", :locals => { :account => @buyer } %>
|
||||
# <%= render :partial => @account %>
|
||||
#
|
||||
# # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
|
||||
# # <%= render :partial => "posts/post", :collection => @posts %>
|
||||
# <%= render :partial => @posts %>
|
||||
#
|
||||
# == Rendering the default case
|
||||
#
|
||||
# If you're not going to be using any of the options like collections or layouts, you can also use the short-hand
|
||||
# defaults of render to render partials. Examples:
|
||||
#
|
||||
# # Instead of <%= render :partial => "account" %>
|
||||
# <%= render "account" %>
|
||||
#
|
||||
# # Instead of <%= render :partial => "account", :locals => { :account => @buyer } %>
|
||||
# <%= render "account", :account => @buyer %>
|
||||
#
|
||||
# # @account is an Account instance, so it uses the RecordIdentifier to replace
|
||||
# # <%= render :partial => "accounts/account", :locals => { :account => @account } %>
|
||||
# <%= render(@account) %>
|
||||
#
|
||||
# # @posts is an array of Post instances, so it uses the RecordIdentifier to replace
|
||||
# # <%= render :partial => "posts/post", :collection => @posts %>
|
||||
# <%= render(@posts) %>
|
||||
#
|
||||
# == Rendering partials with layouts
|
||||
#
|
||||
# Partials can have their own layouts applied to them. These layouts are different than the ones that are
|
||||
|
||||
@@ -2,20 +2,26 @@ $:.unshift(File.dirname(__FILE__) + '/../lib')
|
||||
$:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
|
||||
$:.unshift(File.dirname(__FILE__) + '/fixtures/helpers')
|
||||
|
||||
require 'rubygems'
|
||||
require 'yaml'
|
||||
require 'stringio'
|
||||
require 'test/unit'
|
||||
|
||||
gem 'mocha', '>= 0.9.0'
|
||||
require 'mocha'
|
||||
|
||||
begin
|
||||
require 'ruby-debug'
|
||||
Debugger.start
|
||||
rescue LoadError
|
||||
# Debugging disabled. `gem install ruby-debug` to enable.
|
||||
end
|
||||
|
||||
require 'action_controller'
|
||||
require 'action_controller/cgi_ext'
|
||||
require 'action_controller/test_process'
|
||||
require 'action_view/test_case'
|
||||
|
||||
begin
|
||||
require 'ruby-debug'
|
||||
rescue LoadError
|
||||
# Debugging disabled. `gem install ruby-debug` to enable.
|
||||
end
|
||||
|
||||
# Show backtraces for deprecated behavior for quicker cleanup.
|
||||
ActiveSupport::Deprecation.debug = true
|
||||
|
||||
@@ -26,14 +32,6 @@ FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures')
|
||||
ActionView::PathSet::Path.eager_load_templates!
|
||||
ActionController::Base.view_paths = FIXTURE_LOAD_PATH
|
||||
|
||||
# Wrap tests that use Mocha and skip if unavailable.
|
||||
def uses_mocha(test_name)
|
||||
unless Object.const_defined?(:Mocha)
|
||||
require 'mocha'
|
||||
require 'stubba'
|
||||
end
|
||||
yield
|
||||
rescue LoadError => load_error
|
||||
raise unless load_error.message =~ /mocha/i
|
||||
$stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again."
|
||||
end
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
require 'abstract_unit'
|
||||
|
||||
class CallerController < ActionController::Base
|
||||
def calling_from_controller
|
||||
render_component(:controller => "callee", :action => "being_called")
|
||||
end
|
||||
|
||||
def calling_from_controller_with_params
|
||||
render_component(:controller => "callee", :action => "being_called", :params => { "name" => "David" })
|
||||
end
|
||||
|
||||
def calling_from_controller_with_different_status_code
|
||||
render_component(:controller => "callee", :action => "blowing_up")
|
||||
end
|
||||
|
||||
def calling_from_template
|
||||
render :inline => "Ring, ring: <%= render_component(:controller => 'callee', :action => 'being_called') %>"
|
||||
end
|
||||
|
||||
def internal_caller
|
||||
render :inline => "Are you there? <%= render_component(:action => 'internal_callee') %>"
|
||||
end
|
||||
|
||||
def internal_callee
|
||||
render :text => "Yes, ma'am"
|
||||
end
|
||||
|
||||
def set_flash
|
||||
render_component(:controller => "callee", :action => "set_flash")
|
||||
end
|
||||
|
||||
def use_flash
|
||||
render_component(:controller => "callee", :action => "use_flash")
|
||||
end
|
||||
|
||||
def calling_redirected
|
||||
render_component(:controller => "callee", :action => "redirected")
|
||||
end
|
||||
|
||||
def calling_redirected_as_string
|
||||
render :inline => "<%= render_component(:controller => 'callee', :action => 'redirected') %>"
|
||||
end
|
||||
|
||||
def rescue_action(e) raise end
|
||||
end
|
||||
|
||||
class CalleeController < ActionController::Base
|
||||
def being_called
|
||||
render :text => "#{params[:name] || "Lady"} of the House, speaking"
|
||||
end
|
||||
|
||||
def blowing_up
|
||||
render :text => "It's game over, man, just game over, man!", :status => 500
|
||||
end
|
||||
|
||||
def set_flash
|
||||
flash[:notice] = 'My stoney baby'
|
||||
render :text => 'flash is set'
|
||||
end
|
||||
|
||||
def use_flash
|
||||
render :text => flash[:notice] || 'no flash'
|
||||
end
|
||||
|
||||
def redirected
|
||||
redirect_to :controller => "callee", :action => "being_called"
|
||||
end
|
||||
|
||||
def rescue_action(e) raise end
|
||||
end
|
||||
|
||||
class ComponentsTest < ActionController::TestCase
|
||||
tests CallerController
|
||||
|
||||
def test_calling_from_controller
|
||||
assert_deprecated do
|
||||
get :calling_from_controller
|
||||
assert_equal "Lady of the House, speaking", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_calling_from_controller_with_params
|
||||
assert_deprecated do
|
||||
get :calling_from_controller_with_params
|
||||
assert_equal "David of the House, speaking", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_calling_from_controller_with_different_status_code
|
||||
assert_deprecated do
|
||||
get :calling_from_controller_with_different_status_code
|
||||
assert_equal 500, @response.response_code
|
||||
end
|
||||
end
|
||||
|
||||
def test_calling_from_template
|
||||
assert_deprecated do
|
||||
get :calling_from_template
|
||||
assert_equal "Ring, ring: Lady of the House, speaking", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_etag_is_set_for_parent_template_when_calling_from_template
|
||||
assert_deprecated do
|
||||
get :calling_from_template
|
||||
expected_etag = etag_for("Ring, ring: Lady of the House, speaking")
|
||||
assert_equal expected_etag, @response.headers['ETag']
|
||||
end
|
||||
end
|
||||
|
||||
def test_internal_calling
|
||||
assert_deprecated do
|
||||
get :internal_caller
|
||||
assert_equal "Are you there? Yes, ma'am", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_flash
|
||||
assert_deprecated do
|
||||
get :set_flash
|
||||
assert_equal 'My stoney baby', flash[:notice]
|
||||
get :use_flash
|
||||
assert_equal 'My stoney baby', @response.body
|
||||
get :use_flash
|
||||
assert_equal 'no flash', @response.body
|
||||
end
|
||||
end
|
||||
|
||||
def test_component_redirect_redirects
|
||||
assert_deprecated do
|
||||
get :calling_redirected
|
||||
assert_redirected_to :controller=>"callee", :action => "being_called"
|
||||
end
|
||||
end
|
||||
|
||||
def test_component_multiple_redirect_redirects
|
||||
test_component_redirect_redirects
|
||||
test_internal_calling
|
||||
end
|
||||
|
||||
def test_component_as_string_redirect_renders_redirected_action
|
||||
assert_deprecated do
|
||||
get :calling_redirected_as_string
|
||||
assert_equal "Lady of the House, speaking", @response.body
|
||||
end
|
||||
end
|
||||
|
||||
protected
|
||||
def etag_for(text)
|
||||
%("#{Digest::MD5.hexdigest(text)}")
|
||||
end
|
||||
end
|
||||
@@ -179,6 +179,12 @@ uses_mocha 'polymorphic URL helpers' do
|
||||
polymorphic_url([nil, @article])
|
||||
end
|
||||
|
||||
def test_with_array_containing_single_name
|
||||
@article.save
|
||||
expects(:articles_url)
|
||||
polymorphic_url([:articles])
|
||||
end
|
||||
|
||||
# TODO: Needs to be updated to correctly know about whether the object is in a hash or not
|
||||
def xtest_with_hash
|
||||
expects(:article_url).with(@article)
|
||||
|
||||
@@ -246,6 +246,15 @@ class TestController < ActionController::Base
|
||||
:locals => { :local_name => name }
|
||||
end
|
||||
|
||||
def helper_method_to_render_to_string(*args)
|
||||
render_to_string(*args)
|
||||
end
|
||||
helper_method :helper_method_to_render_to_string
|
||||
|
||||
def render_html_only_partial_within_inline
|
||||
render :inline => "Hello world <%= helper_method_to_render_to_string :partial => 'test/partial_with_only_html_version' %>"
|
||||
end
|
||||
|
||||
def formatted_html_erb
|
||||
end
|
||||
|
||||
@@ -932,6 +941,11 @@ class RenderTest < ActionController::TestCase
|
||||
assert_equal "Goodbye, Local David", @response.body
|
||||
end
|
||||
|
||||
def test_rendering_html_only_partial_within_inline_with_js
|
||||
get :render_html_only_partial_within_inline, :format => :js
|
||||
assert_equal "Hello world partial with only html version", @response.body
|
||||
end
|
||||
|
||||
def test_should_render_formatted_template
|
||||
get :formatted_html_erb
|
||||
assert_equal 'formatted html erb', @response.body
|
||||
|
||||
@@ -706,12 +706,13 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
|
||||
port = options.delete(:port) || 80
|
||||
port_string = port == 80 ? '' : ":#{port}"
|
||||
|
||||
host = options.delete(:host) || "named.route.test"
|
||||
anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
|
||||
protocol = options.delete(:protocol) || "http"
|
||||
host = options.delete(:host) || "named.route.test"
|
||||
anchor = "##{options.delete(:anchor)}" if options.key?(:anchor)
|
||||
|
||||
path = routes.generate(options)
|
||||
|
||||
only_path ? "#{path}#{anchor}" : "http://#{host}#{port_string}#{path}#{anchor}"
|
||||
only_path ? "#{path}#{anchor}" : "#{protocol}://#{host}#{port_string}#{path}#{anchor}"
|
||||
end
|
||||
|
||||
def request
|
||||
@@ -1726,6 +1727,11 @@ uses_mocha 'LegacyRouteSet, Route, RouteSet and RouteLoading' do
|
||||
assert_equal "http://some.example.com/people/5", controller.send(:show_url, 5, :host=>"some.example.com")
|
||||
end
|
||||
|
||||
def test_named_route_url_method_with_protocol
|
||||
controller = setup_named_route_test
|
||||
assert_equal "https://named.route.test/people/5", controller.send(:show_url, 5, :protocol => "https")
|
||||
end
|
||||
|
||||
def test_named_route_url_method_with_ordered_parameters
|
||||
controller = setup_named_route_test
|
||||
assert_equal "http://named.route.test/people/go/7/hello/joe/5",
|
||||
|
||||
1
actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
vendored
Normal file
1
actionpack/test/fixtures/test/_partial_with_only_html_version.html.erb
vendored
Normal file
@@ -0,0 +1 @@
|
||||
partial with only html version
|
||||
2
actionpack/test/fixtures/test/hello.builder
vendored
2
actionpack/test/fixtures/test/hello.builder
vendored
@@ -1,4 +1,4 @@
|
||||
xml.html do
|
||||
xml.p "Hello #{@name}"
|
||||
xml << render("test/greeting")
|
||||
xml << render(:file => "test/greeting")
|
||||
end
|
||||
@@ -648,4 +648,10 @@ class AssetTagHelperNonVhostTest < ActionView::TestCase
|
||||
ensure
|
||||
ActionController::Base.asset_host = nil
|
||||
end
|
||||
|
||||
def test_assert_css_and_js_of_the_same_name_return_correct_extension
|
||||
assert_dom_equal(%(/collaboration/hieraki/javascripts/foo.js), javascript_path("foo"))
|
||||
assert_dom_equal(%(/collaboration/hieraki/stylesheets/foo.css), stylesheet_path("foo"))
|
||||
|
||||
end
|
||||
end
|
||||
|
||||
@@ -12,30 +12,30 @@ uses_mocha 'TestTemplateRecompilation' do
|
||||
|
||||
def test_template_gets_compiled
|
||||
assert_equal 0, @compiled_templates.instance_methods.size
|
||||
assert_equal "Hello world!", render("test/hello_world.erb")
|
||||
assert_equal "Hello world!", render(:file => "test/hello_world.erb")
|
||||
assert_equal 1, @compiled_templates.instance_methods.size
|
||||
end
|
||||
|
||||
def test_template_gets_recompiled_when_using_different_keys_in_local_assigns
|
||||
assert_equal 0, @compiled_templates.instance_methods.size
|
||||
assert_equal "Hello world!", render("test/hello_world.erb")
|
||||
assert_equal "Hello world!", render("test/hello_world.erb", {:foo => "bar"})
|
||||
assert_equal "Hello world!", render(:file => "test/hello_world.erb")
|
||||
assert_equal "Hello world!", render(:file => "test/hello_world.erb", :locals => {:foo => "bar"})
|
||||
assert_equal 2, @compiled_templates.instance_methods.size
|
||||
end
|
||||
|
||||
def test_compiled_template_will_not_be_recompiled_when_rendered_with_identical_local_assigns
|
||||
assert_equal 0, @compiled_templates.instance_methods.size
|
||||
assert_equal "Hello world!", render("test/hello_world.erb")
|
||||
assert_equal "Hello world!", render(:file => "test/hello_world.erb")
|
||||
ActionView::Template.any_instance.expects(:compile!).never
|
||||
assert_equal "Hello world!", render("test/hello_world.erb")
|
||||
assert_equal "Hello world!", render(:file => "test/hello_world.erb")
|
||||
end
|
||||
|
||||
def test_compiled_template_will_always_be_recompiled_when_eager_loaded_templates_is_off
|
||||
ActionView::PathSet::Path.expects(:eager_load_templates?).times(4).returns(false)
|
||||
assert_equal 0, @compiled_templates.instance_methods.size
|
||||
assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
|
||||
assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb")
|
||||
ActionView::Template.any_instance.expects(:compile!).times(3)
|
||||
3.times { assert_equal "Hello world!", render("#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
|
||||
3.times { assert_equal "Hello world!", render(:file => "#{FIXTURE_LOAD_PATH}/test/hello_world.erb") }
|
||||
assert_equal 1, @compiled_templates.instance_methods.size
|
||||
end
|
||||
|
||||
|
||||
@@ -238,6 +238,7 @@ class FormTagHelperTest < ActionView::TestCase
|
||||
def test_boolean_options
|
||||
assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
|
||||
assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
|
||||
assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
|
||||
assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => true)
|
||||
assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>", :multiple => true)
|
||||
assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>", :multiple => nil)
|
||||
|
||||
@@ -8,7 +8,7 @@ class ViewRenderTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_render_file
|
||||
assert_equal "Hello world!", @view.render("test/hello_world.erb")
|
||||
assert_equal "Hello world!", @view.render(:file => "test/hello_world.erb")
|
||||
end
|
||||
|
||||
def test_render_file_not_using_full_path
|
||||
@@ -16,11 +16,11 @@ class ViewRenderTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_render_file_without_specific_extension
|
||||
assert_equal "Hello world!", @view.render("test/hello_world")
|
||||
assert_equal "Hello world!", @view.render(:file => "test/hello_world")
|
||||
end
|
||||
|
||||
def test_render_file_at_top_level
|
||||
assert_equal 'Elastica', @view.render('/shared')
|
||||
assert_equal 'Elastica', @view.render(:file => '/shared')
|
||||
end
|
||||
|
||||
def test_render_file_with_full_path
|
||||
@@ -29,20 +29,20 @@ class ViewRenderTest < Test::Unit::TestCase
|
||||
end
|
||||
|
||||
def test_render_file_with_instance_variables
|
||||
assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_ivar.erb")
|
||||
assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_ivar.erb")
|
||||
end
|
||||
|
||||
def test_render_file_with_locals
|
||||
locals = { :secret => 'in the sauce' }
|
||||
assert_equal "The secret is in the sauce\n", @view.render("test/render_file_with_locals.erb", locals)
|
||||
assert_equal "The secret is in the sauce\n", @view.render(:file => "test/render_file_with_locals.erb", :locals => locals)
|
||||
end
|
||||
|
||||
def test_render_file_not_using_full_path_with_dot_in_path
|
||||
assert_equal "The secret is in the sauce\n", @view.render("test/dot.directory/render_file_with_ivar")
|
||||
assert_equal "The secret is in the sauce\n", @view.render(:file => "test/dot.directory/render_file_with_ivar")
|
||||
end
|
||||
|
||||
def test_render_has_access_current_template
|
||||
assert_equal "test/template.erb", @view.render("test/template.erb")
|
||||
assert_equal "test/template.erb", @view.render(:file => "test/template.erb")
|
||||
end
|
||||
|
||||
def test_render_update
|
||||
@@ -51,6 +51,10 @@ class ViewRenderTest < Test::Unit::TestCase
|
||||
assert_equal 'alert("Hello, World!");', @view.render(:update) { |page| page.alert('Hello, World!') }
|
||||
end
|
||||
|
||||
def test_render_partial_from_default
|
||||
assert_equal "only partial", @view.render("test/partial_only")
|
||||
end
|
||||
|
||||
def test_render_partial
|
||||
assert_equal "only partial", @view.render(:partial => "test/partial_only")
|
||||
end
|
||||
@@ -73,6 +77,10 @@ class ViewRenderTest < Test::Unit::TestCase
|
||||
assert_equal "5", @view.render(:partial => "test/counter", :locals => { :counter_counter => 5 })
|
||||
end
|
||||
|
||||
def test_render_partial_with_locals_from_default
|
||||
assert_equal "only partial", @view.render("test/partial_only", :counter_counter => 5)
|
||||
end
|
||||
|
||||
def test_render_partial_with_errors
|
||||
@view.render(:partial => "test/raise")
|
||||
flunk "Render did not raise TemplateError"
|
||||
|
||||
@@ -4,7 +4,8 @@ require 'active_model/state_machine/event'
|
||||
module ActiveModel
|
||||
module StateMachine
|
||||
class Machine
|
||||
attr_accessor :initial_state, :states, :events, :state_index
|
||||
attr_writer :initial_state
|
||||
attr_accessor :states, :events, :state_index
|
||||
attr_reader :klass, :name
|
||||
|
||||
def initialize(klass, name, options = {}, &block)
|
||||
|
||||
@@ -40,24 +40,22 @@ class ObservingTest < ActiveModel::TestCase
|
||||
assert ObservedModel.observers.include?(:bar), ":bar not in #{ObservedModel.observers.inspect}"
|
||||
end
|
||||
|
||||
uses_mocha "observer instantiation" do
|
||||
test "instantiates observer names passed as strings" do
|
||||
ObservedModel.observers << 'foo_observer'
|
||||
FooObserver.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
|
||||
test "instantiates observer names passed as symbols" do
|
||||
ObservedModel.observers << :foo_observer
|
||||
FooObserver.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
|
||||
test "instantiates observer classes" do
|
||||
ObservedModel.observers << ObservedModel::Observer
|
||||
ObservedModel::Observer.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
test "instantiates observer names passed as strings" do
|
||||
ObservedModel.observers << 'foo_observer'
|
||||
FooObserver.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
|
||||
test "instantiates observer names passed as symbols" do
|
||||
ObservedModel.observers << :foo_observer
|
||||
FooObserver.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
|
||||
test "instantiates observer classes" do
|
||||
ObservedModel.observers << ObservedModel::Observer
|
||||
ObservedModel::Observer.expects(:instance)
|
||||
ObservedModel.instantiate_observers
|
||||
end
|
||||
|
||||
test "passes observers to subclasses" do
|
||||
|
||||
@@ -20,12 +20,10 @@ class EventTest < ActiveModel::TestCase
|
||||
assert_equal @success, new_event.success
|
||||
end
|
||||
|
||||
uses_mocha 'StateTransition creation' do
|
||||
test 'should create StateTransitions' do
|
||||
ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :open)
|
||||
ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :received)
|
||||
new_event
|
||||
end
|
||||
test 'should create StateTransitions' do
|
||||
ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :open)
|
||||
ActiveModel::StateMachine::StateTransition.expects(:new).with(:to => :closed, :from => :received)
|
||||
new_event
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
@@ -43,32 +43,30 @@ class StateTest < ActiveModel::TestCase
|
||||
assert_equal new_state, new_state
|
||||
end
|
||||
|
||||
uses_mocha 'state actions' do
|
||||
test 'should send a message to the record for an action if the action is present as a symbol' do
|
||||
state = new_state(:entering => :foo)
|
||||
test 'should send a message to the record for an action if the action is present as a symbol' do
|
||||
state = new_state(:entering => :foo)
|
||||
|
||||
record = stub
|
||||
record.expects(:foo)
|
||||
record = stub
|
||||
record.expects(:foo)
|
||||
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
|
||||
test 'should send a message to the record for an action if the action is present as a string' do
|
||||
state = new_state(:entering => 'foo')
|
||||
test 'should send a message to the record for an action if the action is present as a string' do
|
||||
state = new_state(:entering => 'foo')
|
||||
|
||||
record = stub
|
||||
record.expects(:foo)
|
||||
record = stub
|
||||
record.expects(:foo)
|
||||
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
|
||||
test 'should call a proc, passing in the record for an action if the action is present' do
|
||||
state = new_state(:entering => Proc.new {|r| r.foobar})
|
||||
test 'should call a proc, passing in the record for an action if the action is present' do
|
||||
state = new_state(:entering => Proc.new {|r| r.foobar})
|
||||
|
||||
record = stub
|
||||
record.expects(:foobar)
|
||||
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
record = stub
|
||||
record.expects(:foobar)
|
||||
|
||||
state.call_action(:entering, record)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -10,39 +10,37 @@ class StateTransitionTest < ActiveModel::TestCase
|
||||
assert_equal opts, st.options
|
||||
end
|
||||
|
||||
uses_mocha 'checking ActiveModel StateMachine transitions' do
|
||||
test 'should pass equality check if from and to are the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
test 'should pass equality check if from and to are the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.stubs(:from).returns(opts[:from])
|
||||
obj.stubs(:to).returns(opts[:to])
|
||||
obj = stub
|
||||
obj.stubs(:from).returns(opts[:from])
|
||||
obj.stubs(:to).returns(opts[:to])
|
||||
|
||||
assert_equal st, obj
|
||||
end
|
||||
assert_equal st, obj
|
||||
end
|
||||
|
||||
test 'should fail equality check if from are not the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
test 'should fail equality check if from are not the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.stubs(:from).returns('blah')
|
||||
obj.stubs(:to).returns(opts[:to])
|
||||
obj = stub
|
||||
obj.stubs(:from).returns('blah')
|
||||
obj.stubs(:to).returns(opts[:to])
|
||||
|
||||
assert_not_equal st, obj
|
||||
end
|
||||
|
||||
test 'should fail equality check if to are not the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
assert_not_equal st, obj
|
||||
end
|
||||
|
||||
obj = stub
|
||||
obj.stubs(:from).returns(opts[:from])
|
||||
obj.stubs(:to).returns('blah')
|
||||
test 'should fail equality check if to are not the same' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'g'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
assert_not_equal st, obj
|
||||
end
|
||||
obj = stub
|
||||
obj.stubs(:from).returns(opts[:from])
|
||||
obj.stubs(:to).returns('blah')
|
||||
|
||||
assert_not_equal st, obj
|
||||
end
|
||||
end
|
||||
|
||||
@@ -54,35 +52,33 @@ class StateTransitionGuardCheckTest < ActiveModel::TestCase
|
||||
assert st.perform(nil)
|
||||
end
|
||||
|
||||
uses_mocha 'checking ActiveModel StateMachine transition guard checks' do
|
||||
test 'should call the method on the object if guard is a symbol' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => :test_guard}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
test 'should call the method on the object if guard is a symbol' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => :test_guard}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
st.perform(obj)
|
||||
end
|
||||
st.perform(obj)
|
||||
end
|
||||
|
||||
test 'should call the method on the object if guard is a string' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'test_guard'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
test 'should call the method on the object if guard is a string' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => 'test_guard'}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
st.perform(obj)
|
||||
end
|
||||
|
||||
test 'should call the proc passing the object if the guard is a proc' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => Proc.new {|o| o.test_guard}}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
st.perform(obj)
|
||||
end
|
||||
st.perform(obj)
|
||||
end
|
||||
|
||||
test 'should call the proc passing the object if the guard is a proc' do
|
||||
opts = {:from => 'foo', :to => 'bar', :guard => Proc.new {|o| o.test_guard}}
|
||||
st = ActiveModel::StateMachine::StateTransition.new(opts)
|
||||
|
||||
obj = stub
|
||||
obj.expects(:test_guard)
|
||||
|
||||
st.perform(obj)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -122,24 +122,22 @@ class StateMachineEventFiringWithPersistenceTest < ActiveModel::TestCase
|
||||
assert_equal :closed, @subj.current_state
|
||||
end
|
||||
|
||||
uses_mocha "StateMachineEventFiringWithPersistenceTest with callbacks" do
|
||||
test 'fires the Event' do
|
||||
@subj.class.state_machine.events[:close].expects(:fire).with(@subj)
|
||||
@subj.close!
|
||||
test 'fires the Event' do
|
||||
@subj.class.state_machine.events[:close].expects(:fire).with(@subj)
|
||||
@subj.close!
|
||||
end
|
||||
|
||||
test 'calls the success callback if one was provided' do
|
||||
@subj.expects(:success_callback)
|
||||
@subj.close!
|
||||
end
|
||||
|
||||
test 'attempts to persist if write_state is defined' do
|
||||
def @subj.write_state
|
||||
end
|
||||
|
||||
test 'calls the success callback if one was provided' do
|
||||
@subj.expects(:success_callback)
|
||||
@subj.close!
|
||||
end
|
||||
|
||||
test 'attempts to persist if write_state is defined' do
|
||||
def @subj.write_state
|
||||
end
|
||||
|
||||
@subj.expects(:write_state)
|
||||
@subj.close!
|
||||
end
|
||||
@subj.expects(:write_state)
|
||||
@subj.close!
|
||||
end
|
||||
end
|
||||
|
||||
@@ -151,98 +149,90 @@ class StateMachineEventFiringWithoutPersistence < ActiveModel::TestCase
|
||||
assert_equal :closed, subj.current_state
|
||||
end
|
||||
|
||||
uses_mocha 'StateMachineEventFiringWithoutPersistence' do
|
||||
test 'fires the Event' do
|
||||
subj = StateMachineSubject.new
|
||||
test 'fires the Event' do
|
||||
subj = StateMachineSubject.new
|
||||
|
||||
StateMachineSubject.state_machine.events[:close].expects(:fire).with(subj)
|
||||
subj.close
|
||||
StateMachineSubject.state_machine.events[:close].expects(:fire).with(subj)
|
||||
subj.close
|
||||
end
|
||||
|
||||
test 'attempts to persist if write_state is defined' do
|
||||
subj = StateMachineSubject.new
|
||||
|
||||
def subj.write_state
|
||||
end
|
||||
|
||||
test 'attempts to persist if write_state is defined' do
|
||||
subj = StateMachineSubject.new
|
||||
subj.expects(:write_state_without_persistence)
|
||||
|
||||
def subj.write_state
|
||||
end
|
||||
|
||||
subj.expects(:write_state_without_persistence)
|
||||
|
||||
subj.close
|
||||
end
|
||||
subj.close
|
||||
end
|
||||
end
|
||||
|
||||
uses_mocha 'StateMachinePersistenceTest' do
|
||||
class StateMachinePersistenceTest < ActiveModel::TestCase
|
||||
test 'reads the state if it has not been set and read_state is defined' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.read_state
|
||||
end
|
||||
|
||||
subj.expects(:read_state).with(StateMachineSubject.state_machine)
|
||||
|
||||
subj.current_state
|
||||
class StateMachinePersistenceTest < ActiveModel::TestCase
|
||||
test 'reads the state if it has not been set and read_state is defined' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.read_state
|
||||
end
|
||||
|
||||
subj.expects(:read_state).with(StateMachineSubject.state_machine)
|
||||
|
||||
subj.current_state
|
||||
end
|
||||
end
|
||||
|
||||
uses_mocha 'StateMachineEventCallbacksTest' do
|
||||
class StateMachineEventCallbacksTest < ActiveModel::TestCase
|
||||
test 'should call aasm_event_fired if defined and successful for bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_fired(from, to)
|
||||
end
|
||||
|
||||
subj.expects(:event_fired)
|
||||
|
||||
subj.close!
|
||||
class StateMachineEventCallbacksTest < ActiveModel::TestCase
|
||||
test 'should call aasm_event_fired if defined and successful for bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_fired(from, to)
|
||||
end
|
||||
|
||||
test 'should call aasm_event_fired if defined and successful for non-bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_fired(from, to)
|
||||
end
|
||||
subj.expects(:event_fired)
|
||||
|
||||
subj.expects(:event_fired)
|
||||
subj.close!
|
||||
end
|
||||
|
||||
subj.close
|
||||
test 'should call aasm_event_fired if defined and successful for non-bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_fired(from, to)
|
||||
end
|
||||
|
||||
test 'should call aasm_event_failed if defined and transition failed for bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.event_failed(event)
|
||||
end
|
||||
subj.expects(:event_fired)
|
||||
|
||||
subj.expects(:event_failed)
|
||||
subj.close
|
||||
end
|
||||
|
||||
subj.null!
|
||||
test 'should call aasm_event_failed if defined and transition failed for bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.event_failed(event)
|
||||
end
|
||||
|
||||
test 'should call aasm_event_failed if defined and transition failed for non-bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_failed(event)
|
||||
end
|
||||
subj.expects(:event_failed)
|
||||
|
||||
subj.expects(:event_failed)
|
||||
subj.null!
|
||||
end
|
||||
|
||||
subj.null
|
||||
test 'should call aasm_event_failed if defined and transition failed for non-bang fire' do
|
||||
subj = StateMachineSubject.new
|
||||
def subj.aasm_event_failed(event)
|
||||
end
|
||||
|
||||
subj.expects(:event_failed)
|
||||
|
||||
subj.null
|
||||
end
|
||||
end
|
||||
|
||||
uses_mocha 'StateMachineStateActionsTest' do
|
||||
class StateMachineStateActionsTest < ActiveModel::TestCase
|
||||
test "calls enter when entering state" do
|
||||
subj = StateMachineSubject.new
|
||||
subj.expects(:enter)
|
||||
subj.close
|
||||
end
|
||||
class StateMachineStateActionsTest < ActiveModel::TestCase
|
||||
test "calls enter when entering state" do
|
||||
subj = StateMachineSubject.new
|
||||
subj.expects(:enter)
|
||||
subj.close
|
||||
end
|
||||
|
||||
test "calls exit when exiting state" do
|
||||
subj = StateMachineSubject.new
|
||||
subj.expects(:exit)
|
||||
subj.close
|
||||
end
|
||||
test "calls exit when exiting state" do
|
||||
subj = StateMachineSubject.new
|
||||
subj.expects(:exit)
|
||||
subj.close
|
||||
end
|
||||
end
|
||||
|
||||
@@ -306,19 +296,17 @@ class StateMachineWithComplexTransitionsTest < ActiveModel::TestCase
|
||||
assert_equal :working, @subj.current_state(:chetan_patil)
|
||||
end
|
||||
|
||||
uses_mocha "StateMachineWithComplexTransitionsTest on_transition tests" do
|
||||
test 'calls on_transition method with args' do
|
||||
@subj.wakeup! :showering
|
||||
|
||||
@subj.expects(:wear_clothes).with('blue', 'jeans')
|
||||
@subj.dress! :working, 'blue', 'jeans'
|
||||
end
|
||||
|
||||
test 'calls on_transition proc' do
|
||||
@subj.wakeup! :showering
|
||||
|
||||
@subj.expects(:wear_clothes).with('purple', 'slacks')
|
||||
@subj.dress!(:dating, 'purple', 'slacks')
|
||||
end
|
||||
test 'calls on_transition method with args' do
|
||||
@subj.wakeup! :showering
|
||||
|
||||
@subj.expects(:wear_clothes).with('blue', 'jeans')
|
||||
@subj.dress! :working, 'blue', 'jeans'
|
||||
end
|
||||
|
||||
test 'calls on_transition proc' do
|
||||
@subj.wakeup! :showering
|
||||
|
||||
@subj.expects(:wear_clothes).with('purple', 'slacks')
|
||||
@subj.dress!(:dating, 'purple', 'slacks')
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,30 +1,18 @@
|
||||
require 'rubygems'
|
||||
require 'test/unit'
|
||||
|
||||
gem 'mocha', '>= 0.5.5'
|
||||
require 'mocha'
|
||||
|
||||
require 'active_model'
|
||||
require 'active_model/state_machine'
|
||||
require 'active_support/test_case'
|
||||
|
||||
def uses_gem(gem_name, test_name, version = '> 0')
|
||||
require 'rubygems'
|
||||
gem gem_name.to_s, version
|
||||
require gem_name.to_s
|
||||
yield
|
||||
rescue LoadError
|
||||
$stderr.puts "Skipping #{test_name} tests. `gem install #{gem_name}` and try again."
|
||||
end
|
||||
|
||||
# Wrap tests that use Mocha and skip if unavailable.
|
||||
unless defined? uses_mocha
|
||||
def uses_mocha(test_name, &block)
|
||||
uses_gem('mocha', test_name, '>= 0.5.5', &block)
|
||||
end
|
||||
class ActiveModel::TestCase < ActiveSupport::TestCase
|
||||
end
|
||||
|
||||
begin
|
||||
require 'rubygems'
|
||||
require 'ruby-debug'
|
||||
Debugger.start
|
||||
rescue LoadError
|
||||
end
|
||||
|
||||
class ActiveModel::TestCase < ActiveSupport::TestCase
|
||||
end
|
||||
|
||||
@@ -171,7 +171,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
|
||||
end
|
||||
|
||||
s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
|
||||
|
||||
s.files.delete FIXTURES_ROOT + "/fixture_database.sqlite"
|
||||
s.files.delete FIXTURES_ROOT + "/fixture_database_2.sqlite"
|
||||
|
||||
@@ -31,7 +31,7 @@ module ActiveRecord
|
||||
include QueryCache
|
||||
include ActiveSupport::Callbacks
|
||||
define_callbacks :checkout, :checkin
|
||||
checkout :reset!
|
||||
|
||||
@@row_even = true
|
||||
|
||||
def initialize(connection, logger = nil) #:nodoc:
|
||||
|
||||
@@ -3,11 +3,9 @@ require "active_support/test_case"
|
||||
module ActiveRecord
|
||||
class TestCase < ActiveSupport::TestCase #:nodoc:
|
||||
def assert_date_from_db(expected, actual, message = nil)
|
||||
# SQL Server doesn't have a separate column type just for dates,
|
||||
# SybaseAdapter doesn't have a separate column type just for dates,
|
||||
# so the time is in the string and incorrectly formatted
|
||||
if current_adapter?(:SQLServerAdapter)
|
||||
assert_equal expected.strftime("%Y/%m/%d 00:00:00"), actual.strftime("%Y/%m/%d 00:00:00")
|
||||
elsif current_adapter?(:SybaseAdapter)
|
||||
if current_adapter?(:SybaseAdapter)
|
||||
assert_equal expected.to_s, actual.to_date.to_s, message
|
||||
else
|
||||
assert_equal expected.to_s, actual.to_s, message
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActiveRecord
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
require "cases/helper"
|
||||
require 'models/default'
|
||||
require 'models/post'
|
||||
require 'models/task'
|
||||
|
||||
class SqlServerAdapterTest < ActiveRecord::TestCase
|
||||
class TableWithRealColumn < ActiveRecord::Base; end
|
||||
|
||||
fixtures :posts, :tasks
|
||||
|
||||
def setup
|
||||
@connection = ActiveRecord::Base.connection
|
||||
end
|
||||
|
||||
def teardown
|
||||
@connection.execute("SET LANGUAGE us_english") rescue nil
|
||||
end
|
||||
|
||||
def test_real_column_has_float_type
|
||||
assert_equal :float, TableWithRealColumn.columns_hash["real_number"].type
|
||||
end
|
||||
|
||||
# SQL Server 2000 has a bug where some unambiguous date formats are not
|
||||
# correctly identified if the session language is set to german
|
||||
def test_date_insertion_when_language_is_german
|
||||
@connection.execute("SET LANGUAGE deutsch")
|
||||
|
||||
assert_nothing_raised do
|
||||
Task.create(:starting => Time.utc(2000, 1, 31, 5, 42, 0), :ending => Date.new(2006, 12, 31))
|
||||
end
|
||||
end
|
||||
|
||||
def test_indexes_with_descending_order
|
||||
# Make sure we have an index with descending order
|
||||
@connection.execute "CREATE INDEX idx_credit_limit ON accounts (credit_limit DESC)" rescue nil
|
||||
assert_equal ["credit_limit"], @connection.indexes('accounts').first.columns
|
||||
ensure
|
||||
@connection.execute "DROP INDEX accounts.idx_credit_limit"
|
||||
end
|
||||
|
||||
def test_execute_without_block_closes_statement
|
||||
assert_all_statements_used_are_closed do
|
||||
@connection.execute("SELECT 1")
|
||||
end
|
||||
end
|
||||
|
||||
def test_execute_with_block_closes_statement
|
||||
assert_all_statements_used_are_closed do
|
||||
@connection.execute("SELECT 1") do |sth|
|
||||
assert !sth.finished?, "Statement should still be alive within block"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def test_insert_with_identity_closes_statement
|
||||
assert_all_statements_used_are_closed do
|
||||
@connection.insert("INSERT INTO accounts ([id], [firm_id],[credit_limit]) values (999, 1, 50)")
|
||||
end
|
||||
end
|
||||
|
||||
def test_insert_without_identity_closes_statement
|
||||
assert_all_statements_used_are_closed do
|
||||
@connection.insert("INSERT INTO accounts ([firm_id],[credit_limit]) values (1, 50)")
|
||||
end
|
||||
end
|
||||
|
||||
def test_active_closes_statement
|
||||
assert_all_statements_used_are_closed do
|
||||
@connection.active?
|
||||
end
|
||||
end
|
||||
|
||||
def assert_all_statements_used_are_closed(&block)
|
||||
existing_handles = []
|
||||
ObjectSpace.each_object(DBI::StatementHandle) {|handle| existing_handles << handle}
|
||||
GC.disable
|
||||
|
||||
yield
|
||||
|
||||
used_handles = []
|
||||
ObjectSpace.each_object(DBI::StatementHandle) {|handle| used_handles << handle unless existing_handles.include? handle}
|
||||
|
||||
assert_block "No statements were used within given block" do
|
||||
used_handles.size > 0
|
||||
end
|
||||
|
||||
ObjectSpace.each_object(DBI::StatementHandle) do |handle|
|
||||
assert_block "Statement should have been closed within given block" do
|
||||
handle.finished?
|
||||
end
|
||||
end
|
||||
ensure
|
||||
GC.enable
|
||||
end
|
||||
end
|
||||
@@ -667,7 +667,7 @@ class EagerAssociationTest < ActiveRecord::TestCase
|
||||
end
|
||||
|
||||
def test_count_with_include
|
||||
if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
|
||||
if current_adapter?(:SybaseAdapter)
|
||||
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "len(comments.body) > 15")
|
||||
elsif current_adapter?(:OpenBaseAdapter)
|
||||
assert_equal 3, authors(:david).posts_with_comments.count(:conditions => "length(FETCHBLOB(comments.body)) > 15")
|
||||
|
||||
@@ -428,9 +428,6 @@ class BasicsTest < ActiveRecord::TestCase
|
||||
end
|
||||
|
||||
def test_preserving_date_objects
|
||||
# SQL Server doesn't have a separate column type just for dates, so all are returned as time
|
||||
return true if current_adapter?(:SQLServerAdapter)
|
||||
|
||||
if current_adapter?(:SybaseAdapter, :OracleAdapter)
|
||||
# Sybase ctlib does not (yet?) support the date type; use datetime instead.
|
||||
# Oracle treats all dates/times as Time.
|
||||
@@ -777,8 +774,8 @@ class BasicsTest < ActiveRecord::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
# Oracle, SQLServer, and Sybase do not have a TIME datatype.
|
||||
unless current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
|
||||
# Oracle, and Sybase do not have a TIME datatype.
|
||||
unless current_adapter?(:OracleAdapter, :SybaseAdapter)
|
||||
def test_utc_as_time_zone
|
||||
Topic.default_timezone = :utc
|
||||
attributes = { "bonus_time" => "5:42:00AM" }
|
||||
@@ -1157,8 +1154,8 @@ class BasicsTest < ActiveRecord::TestCase
|
||||
end
|
||||
|
||||
def test_attributes_on_dummy_time
|
||||
# Oracle, SQL Server, and Sybase do not have a TIME datatype.
|
||||
return true if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
|
||||
# Oracle, and Sybase do not have a TIME datatype.
|
||||
return true if current_adapter?(:OracleAdapter, :SybaseAdapter)
|
||||
|
||||
attributes = {
|
||||
"bonus_time" => "5:42:00AM"
|
||||
@@ -1874,7 +1871,7 @@ class BasicsTest < ActiveRecord::TestCase
|
||||
assert_equal "integer", xml.elements["//parent-id"].attributes['type']
|
||||
assert_equal "true", xml.elements["//parent-id"].attributes['nil']
|
||||
|
||||
if current_adapter?(:SybaseAdapter, :SQLServerAdapter, :OracleAdapter)
|
||||
if current_adapter?(:SybaseAdapter, :OracleAdapter)
|
||||
assert_equal last_read_in_current_timezone, xml.elements["//last-read"].text
|
||||
assert_equal "datetime" , xml.elements["//last-read"].attributes['type']
|
||||
else
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
require "cases/helper"
|
||||
|
||||
# Without using prepared statements, it makes no sense to test
|
||||
# BLOB data with SQL Server, because the length of a statement is
|
||||
# limited to 8KB.
|
||||
#
|
||||
# Without using prepared statements, it makes no sense to test
|
||||
# BLOB data with DB2 or Firebird, because the length of a statement
|
||||
# is limited to 32KB.
|
||||
unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
|
||||
unless current_adapter?(:SybaseAdapter, :DB2Adapter, :FirebirdAdapter)
|
||||
require 'models/binary'
|
||||
|
||||
class BinaryTest < ActiveRecord::TestCase
|
||||
|
||||
@@ -78,7 +78,7 @@ class DefaultTest < ActiveRecord::TestCase
|
||||
end
|
||||
end
|
||||
|
||||
if current_adapter?(:PostgreSQLAdapter, :SQLServerAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
|
||||
if current_adapter?(:PostgreSQLAdapter, :FirebirdAdapter, :OpenBaseAdapter, :OracleAdapter)
|
||||
def test_default_integers
|
||||
default = Default.new
|
||||
assert_instance_of Fixnum, default.positive_integer
|
||||
|
||||
@@ -59,13 +59,13 @@ class InheritanceTest < ActiveRecord::TestCase
|
||||
|
||||
def test_a_bad_type_column
|
||||
#SQLServer need to turn Identity Insert On before manually inserting into the Identity column
|
||||
if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
|
||||
if current_adapter?(:SybaseAdapter)
|
||||
Company.connection.execute "SET IDENTITY_INSERT companies ON"
|
||||
end
|
||||
Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"
|
||||
|
||||
#We then need to turn it back Off before continuing.
|
||||
if current_adapter?(:SQLServerAdapter, :SybaseAdapter)
|
||||
if current_adapter?(:SybaseAdapter)
|
||||
Company.connection.execute "SET IDENTITY_INSERT companies OFF"
|
||||
end
|
||||
assert_raises(ActiveRecord::SubclassNotFound) { Company.find(100) }
|
||||
|
||||
@@ -200,9 +200,9 @@ end
|
||||
# blocks, so separate script called by Kernel#system is needed.
|
||||
# (See exec vs. async_exec in the PostgreSQL adapter.)
|
||||
|
||||
# TODO: The SQL Server, Sybase, and OpenBase adapters currently have no support for pessimistic locking
|
||||
# TODO: The Sybase, and OpenBase adapters currently have no support for pessimistic locking
|
||||
|
||||
unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :OpenBaseAdapter)
|
||||
unless current_adapter?(:SybaseAdapter, :OpenBaseAdapter)
|
||||
class PessimisticLockingTest < ActiveRecord::TestCase
|
||||
self.use_transactional_fixtures = false
|
||||
fixtures :people, :readers
|
||||
|
||||
@@ -271,9 +271,9 @@ if ActiveRecord::Base.connection.supports_migrations?
|
||||
Person.connection.drop_table table_name rescue nil
|
||||
end
|
||||
|
||||
# SQL Server, Sybase, and SQLite3 will not allow you to add a NOT NULL
|
||||
# Sybase, and SQLite3 will not allow you to add a NOT NULL
|
||||
# column to a table without a default value.
|
||||
unless current_adapter?(:SQLServerAdapter, :SybaseAdapter, :SQLiteAdapter)
|
||||
unless current_adapter?(:SybaseAdapter, :SQLiteAdapter)
|
||||
def test_add_column_not_null_without_default
|
||||
Person.connection.create_table :testings do |t|
|
||||
t.column :foo, :string
|
||||
@@ -410,7 +410,7 @@ if ActiveRecord::Base.connection.supports_migrations?
|
||||
assert_equal Fixnum, bob.age.class
|
||||
assert_equal Time, bob.birthday.class
|
||||
|
||||
if current_adapter?(:SQLServerAdapter, :OracleAdapter, :SybaseAdapter)
|
||||
if current_adapter?(:OracleAdapter, :SybaseAdapter)
|
||||
# Sybase, and Oracle don't differentiate between date/time
|
||||
assert_equal Time, bob.favorite_day.class
|
||||
else
|
||||
@@ -851,10 +851,6 @@ if ActiveRecord::Base.connection.supports_migrations?
|
||||
# - SQLite3 stores a float, in violation of SQL
|
||||
assert_kind_of BigDecimal, b.value_of_e
|
||||
assert_equal BigDecimal("2.71828182845905"), b.value_of_e
|
||||
elsif current_adapter?(:SQLServer)
|
||||
# - SQL Server rounds instead of truncating
|
||||
assert_kind_of Fixnum, b.value_of_e
|
||||
assert_equal 3, b.value_of_e
|
||||
else
|
||||
# - SQL standard is an integer
|
||||
assert_kind_of Fixnum, b.value_of_e
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
require "cases/helper"
|
||||
require 'active_record/schema'
|
||||
|
||||
if ActiveRecord::Base.connection.supports_migrations?
|
||||
class Order < ActiveRecord::Base
|
||||
self.table_name = '[order]'
|
||||
end
|
||||
|
||||
class TableNameTest < ActiveRecord::TestCase
|
||||
self.use_transactional_fixtures = false
|
||||
|
||||
# Ensures Model.columns works when using SQLServer escape characters.
|
||||
# Enables legacy schemas using SQL reserved words as table names.
|
||||
# Should work with table names with spaces as well ('table name').
|
||||
def test_escaped_table_name
|
||||
assert_nothing_raised do
|
||||
ActiveRecord::Base.connection.select_all 'SELECT * FROM [order]'
|
||||
end
|
||||
assert_equal '[order]', Order.table_name
|
||||
assert_equal 5, Order.columns.length
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,5 +0,0 @@
|
||||
ActiveRecord::Schema.define do
|
||||
create_table :table_with_real_columns, :force => true do |t|
|
||||
t.column :real_number, :real
|
||||
end
|
||||
end
|
||||
@@ -65,7 +65,7 @@ spec = Gem::Specification.new do |s|
|
||||
s.files = s.files + Dir.glob( "#{dir}/**/*" ).delete_if { |item| item.include?( "\.svn" ) }
|
||||
end
|
||||
|
||||
s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
|
||||
|
||||
s.require_path = 'lib'
|
||||
s.autorequire = 'active_resource'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActiveResource
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
*2.3.0/3.0*
|
||||
*2.3.0 [Edge]*
|
||||
|
||||
* Added Object#try. ( Taken from http://ozmm.org/posts/try.html ) [Chris Wanstrath]
|
||||
|
||||
* Added Enumerable#none? to check that none of the elements match the block #1408 [Damian Janowski]
|
||||
|
||||
* TimeZone offset tests: use current_period, to ensure TimeZone#utc_offset is up-to-date [Geoff Buesing]
|
||||
|
||||
* Update bundled TZInfo to 0.3.12 [Geoff Buesing]
|
||||
|
||||
|
||||
@@ -104,4 +104,13 @@ module Enumerable
|
||||
size = block_given? ? select(&block).size : self.size
|
||||
size > 1
|
||||
end
|
||||
|
||||
# Returns true if none of the elements match the given block.
|
||||
#
|
||||
# success = responses.none? {|r| r.status / 100 == 5 }
|
||||
#
|
||||
# This is a builtin method in Ruby 1.8.7 and later.
|
||||
def none?(&block)
|
||||
!any?(&block)
|
||||
end unless [].respond_to?(:none?)
|
||||
end
|
||||
|
||||
@@ -71,4 +71,17 @@ class Object
|
||||
def acts_like?(duck)
|
||||
respond_to? "acts_like_#{duck}?"
|
||||
end
|
||||
|
||||
# Tries to send the method only if object responds to it. Return +nil+ otherwise.
|
||||
#
|
||||
# ==== Example :
|
||||
#
|
||||
# # Without try
|
||||
# @person ? @person.name : nil
|
||||
#
|
||||
# With try
|
||||
# @person.try(:name)
|
||||
def try(method)
|
||||
send(method) if respond_to?(method, true)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
module ActiveSupport
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -79,4 +79,15 @@ class EnumerableTests < Test::Unit::TestCase
|
||||
assert ![ 1, 2 ].many? {|x| x > 1 }
|
||||
assert [ 1, 2, 2 ].many? {|x| x > 1 }
|
||||
end
|
||||
|
||||
def test_none
|
||||
assert [].none?
|
||||
assert [nil, false].none?
|
||||
assert ![1].none?
|
||||
|
||||
assert [].none? {|x| x > 1 }
|
||||
assert ![ 2 ].none? {|x| x > 1 }
|
||||
assert ![ 1, 2 ].none? {|x| x > 1 }
|
||||
assert [ 1, 1 ].none? {|x| x > 1 }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -247,3 +247,28 @@ class ObjectInstanceVariableTest < Test::Unit::TestCase
|
||||
[arg] + instance_exec('bar') { |v| [reverse, v] } }
|
||||
end
|
||||
end
|
||||
|
||||
class ObjectTryTest < Test::Unit::TestCase
|
||||
def setup
|
||||
@string = "Hello"
|
||||
end
|
||||
|
||||
def test_nonexisting_method
|
||||
method = :undefined_method
|
||||
assert !@string.respond_to?(method)
|
||||
assert_nil @string.try(method)
|
||||
end
|
||||
|
||||
def test_valid_method
|
||||
assert_equal 5, @string.try(:size)
|
||||
end
|
||||
|
||||
def test_valid_private_method
|
||||
class << @string
|
||||
private :size
|
||||
end
|
||||
|
||||
assert_equal 5, @string.try(:size)
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
@@ -51,7 +51,7 @@ class TimeZoneTest < Test::Unit::TestCase
|
||||
|
||||
define_method("test_utc_offset_for_#{name}") do
|
||||
silence_warnings do # silence warnings raised by tzinfo gem
|
||||
period = zone.tzinfo.period_for_utc(Time.utc(2009,1,1,0,0,0))
|
||||
period = zone.tzinfo.current_period
|
||||
assert_equal period.utc_offset, zone.utc_offset
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Project.configure do |project|
|
||||
project.build_command = 'ruby ci/ci_build.rb'
|
||||
project.email_notifier.emails = ['thewoolleyman@gmail.com','michael@koziarski.com']
|
||||
project.email_notifier.emails = ['thewoolleyman@gmail.com','michael@koziarski.com', 'david@loudthinking.com', 'jeremy@bitsweat.net', 'josh@joshpeek.com', 'pratiknaik@gmail.com']
|
||||
project.email_notifier.from = 'thewoolleyman+railsci@gmail.com'
|
||||
end
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
*2.3.0/3.0*
|
||||
*2.3.0 [Edge]*
|
||||
|
||||
* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH]
|
||||
|
||||
|
||||
@@ -361,11 +361,11 @@ spec = Gem::Specification.new do |s|
|
||||
EOF
|
||||
|
||||
s.add_dependency('rake', '>= 0.8.3')
|
||||
s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activerecord', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('actionpack', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('actionmailer', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activeresource', '= 2.2.1' + PKG_BUILD)
|
||||
s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD)
|
||||
s.add_dependency('activerecord', '= 2.3.0' + PKG_BUILD)
|
||||
s.add_dependency('actionpack', '= 2.3.0' + PKG_BUILD)
|
||||
s.add_dependency('actionmailer', '= 2.3.0' + PKG_BUILD)
|
||||
s.add_dependency('activeresource', '= 2.3.0' + PKG_BUILD)
|
||||
|
||||
s.rdoc_options << '--exclude' << '.'
|
||||
s.has_rdoc = false
|
||||
|
||||
@@ -22,7 +22,7 @@ Rails::Initializer.run do |config|
|
||||
|
||||
# Specify gems that this application depends on.
|
||||
# They can then be installed with "rake gems:install" on new installations.
|
||||
# You have to specify the <tt>:lib</tt> option for libraries, where the Gem name (<em>sqlite3-ruby</em>) differs from the file itself (_sqlite3_)
|
||||
# You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3)
|
||||
# config.gem "bj"
|
||||
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
|
||||
# config.gem "sqlite3-ruby", :lib => "sqlite3"
|
||||
|
||||
144
railties/html/javascripts/controls.js
vendored
144
railties/html/javascripts/controls.js
vendored
@@ -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,10 +91,10 @@ 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>');
|
||||
@@ -102,7 +102,7 @@ Autocompleter.Base = Class.create({
|
||||
}
|
||||
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));
|
||||
}
|
||||
});
|
||||
});
|
||||
329
railties/html/javascripts/dragdrop.js
vendored
329
railties/html/javascripts/dragdrop.js
vendored
@@ -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,7 +32,7 @@ var Droppables = {
|
||||
options._containers.push($(containment));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(options.accept) options.accept = [options.accept].flatten();
|
||||
|
||||
Element.makePositioned(element); // fix IE
|
||||
@@ -40,34 +40,34 @@ var Droppables = {
|
||||
|
||||
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,8 +112,8 @@ 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;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -121,25 +121,25 @@ var Droppables = {
|
||||
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,24 +148,24 @@ 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)];
|
||||
@@ -173,36 +173,36 @@ var Draggables = {
|
||||
// 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) {
|
||||
@@ -210,7 +210,7 @@ var Draggables = {
|
||||
});
|
||||
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
|
||||
},
|
||||
|
||||
|
||||
_cacheObserverCallbacks: function() {
|
||||
['onStart','onEnd','onDrag'].each( function(eventName) {
|
||||
Draggables[eventName+'Count'] = Draggables.observers.select(
|
||||
@@ -218,7 +218,7 @@ var Draggables = {
|
||||
).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,16 +386,16 @@ 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)];
|
||||
@@ -403,24 +403,24 @@ var Draggable = Class.create({
|
||||
}
|
||||
|
||||
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,67 +433,67 @@ 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);
|
||||
@@ -501,14 +501,14 @@ var Draggable = Class.create({
|
||||
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(dropon.parentNode!=oldParentNode)
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
Sortable.options(dropon.parentNode).onChange(element);
|
||||
}
|
||||
@@ -769,26 +770,26 @@ var Sortable = {
|
||||
var oldParentNode = element.parentNode;
|
||||
element.style.visibility = "hidden"; // fix gecko rendering
|
||||
dropon.parentNode.insertBefore(element, nextElement);
|
||||
if(dropon.parentNode!=oldParentNode)
|
||||
if(dropon.parentNode!=oldParentNode)
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
Sortable.options(dropon.parentNode).onChange(element);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
onEmptyHover: function(element, dropon, overlap) {
|
||||
var oldParentNode = element.parentNode;
|
||||
var droponOptions = Sortable.options(dropon);
|
||||
|
||||
|
||||
if(!Element.isParent(dropon, element)) {
|
||||
var index;
|
||||
|
||||
|
||||
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
|
||||
var child = null;
|
||||
|
||||
|
||||
if(children) {
|
||||
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
|
||||
|
||||
|
||||
for (index = 0; index < children.length; index += 1) {
|
||||
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
|
||||
offset -= Element.offsetSize (children[index], droponOptions.overlap);
|
||||
@@ -801,9 +802,9 @@ var Sortable = {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
dropon.insertBefore(element, child);
|
||||
|
||||
|
||||
Sortable.options(oldParentNode).onChange(element);
|
||||
droponOptions.onChange(element);
|
||||
}
|
||||
@@ -816,34 +817,34 @@ var Sortable = {
|
||||
mark: function(dropon, position) {
|
||||
// mark on ghosting only
|
||||
var sortable = Sortable.options(dropon.parentNode);
|
||||
if(sortable && !sortable.ghosting) return;
|
||||
if(sortable && !sortable.ghosting) return;
|
||||
|
||||
if(!Sortable._marker) {
|
||||
Sortable._marker =
|
||||
Sortable._marker =
|
||||
($('dropmarker') || Element.extend(document.createElement('DIV'))).
|
||||
hide().addClassName('dropmarker').setStyle({position:'absolute'});
|
||||
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
|
||||
}
|
||||
}
|
||||
var offsets = Position.cumulativeOffset(dropon);
|
||||
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
|
||||
|
||||
|
||||
if(position=='after')
|
||||
if(sortable.overlap == 'horizontal')
|
||||
if(sortable.overlap == 'horizontal')
|
||||
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
|
||||
else
|
||||
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
|
||||
|
||||
|
||||
Sortable._marker.show();
|
||||
},
|
||||
|
||||
|
||||
_tree: function(element, options, parent) {
|
||||
var children = Sortable.findElements(element, options) || [];
|
||||
|
||||
|
||||
for (var i = 0; i < children.length; ++i) {
|
||||
var match = children[i].id.match(options.format);
|
||||
|
||||
if (!match) continue;
|
||||
|
||||
|
||||
var child = {
|
||||
id: encodeURIComponent(match ? match[1] : null),
|
||||
element: element,
|
||||
@@ -851,16 +852,16 @@ var Sortable = {
|
||||
children: [],
|
||||
position: parent.children.length,
|
||||
container: $(children[i]).down(options.treeTag)
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
/* Get the element containing the children and recurse over it */
|
||||
if (child.container)
|
||||
this._tree(child.container, options, child)
|
||||
|
||||
this._tree(child.container, options, child);
|
||||
|
||||
parent.children.push (child);
|
||||
}
|
||||
|
||||
return parent;
|
||||
return parent;
|
||||
},
|
||||
|
||||
tree: function(element) {
|
||||
@@ -873,15 +874,15 @@ var Sortable = {
|
||||
name: element.id,
|
||||
format: sortableOptions.format
|
||||
}, arguments[1] || { });
|
||||
|
||||
|
||||
var root = {
|
||||
id: null,
|
||||
parent: null,
|
||||
children: [],
|
||||
container: element,
|
||||
position: 0
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return Sortable._tree(element, options, root);
|
||||
},
|
||||
|
||||
@@ -897,7 +898,7 @@ var Sortable = {
|
||||
sequence: function(element) {
|
||||
element = $(element);
|
||||
var options = Object.extend(this.options(element), arguments[1] || { });
|
||||
|
||||
|
||||
return $(this.findElements(element, options) || []).map( function(item) {
|
||||
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
|
||||
});
|
||||
@@ -906,14 +907,14 @@ var Sortable = {
|
||||
setSequence: function(element, new_sequence) {
|
||||
element = $(element);
|
||||
var options = Object.extend(this.options(element), arguments[2] || { });
|
||||
|
||||
|
||||
var nodeMap = { };
|
||||
this.findElements(element, options).each( function(n) {
|
||||
if (n.id.match(options.format))
|
||||
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
|
||||
n.parentNode.removeChild(n);
|
||||
});
|
||||
|
||||
|
||||
new_sequence.each(function(ident) {
|
||||
var n = nodeMap[ident];
|
||||
if (n) {
|
||||
@@ -922,16 +923,16 @@ var Sortable = {
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
serialize: function(element) {
|
||||
element = $(element);
|
||||
var options = Object.extend(Sortable.options(element), arguments[1] || { });
|
||||
var name = encodeURIComponent(
|
||||
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
|
||||
|
||||
|
||||
if (options.tree) {
|
||||
return Sortable.tree(element, arguments[1]).children.map( function (item) {
|
||||
return [name + Sortable._constructIndex(item) + "[id]=" +
|
||||
return [name + Sortable._constructIndex(item) + "[id]=" +
|
||||
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
|
||||
}).flatten().join('&');
|
||||
} else {
|
||||
@@ -940,16 +941,16 @@ var Sortable = {
|
||||
}).join('&');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Returns true if child is contained within element
|
||||
Element.isParent = function(child, element) {
|
||||
if (!child.parentNode || child == element) return false;
|
||||
if (child.parentNode == element) return true;
|
||||
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;
|
||||
tagName = tagName.toUpperCase();
|
||||
if(only) only = [only].flatten();
|
||||
@@ -965,8 +966,8 @@ Element.findChildren = function(element, only, recursive, tagName) {
|
||||
});
|
||||
|
||||
return (elements.length>0 ? elements.flatten() : []);
|
||||
}
|
||||
};
|
||||
|
||||
Element.offsetSize = function (element, type) {
|
||||
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
|
||||
}
|
||||
};
|
||||
338
railties/html/javascripts/effects.js
vendored
338
railties/html/javascripts/effects.js
vendored
@@ -3,46 +3,46 @@
|
||||
// Justin Palmer (http://encytemedia.com/)
|
||||
// Mark Pilgrim (http://diveintomark.org/)
|
||||
// Martin Bialasinki
|
||||
//
|
||||
//
|
||||
// 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/
|
||||
|
||||
// converts rgb() and #xxx to #xxxxxx format,
|
||||
// returns self (or first argument) if not convertable
|
||||
String.prototype.parseColor = function() {
|
||||
// converts rgb() and #xxx to #xxxxxx format,
|
||||
// returns self (or first argument) if not convertable
|
||||
String.prototype.parseColor = function() {
|
||||
var color = '#';
|
||||
if (this.slice(0,4) == 'rgb(') {
|
||||
var cols = this.slice(4,this.length-1).split(',');
|
||||
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
|
||||
} else {
|
||||
if (this.slice(0,1) == '#') {
|
||||
if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
|
||||
if (this.length==7) color = this.toLowerCase();
|
||||
}
|
||||
}
|
||||
return (color.length==7 ? color : (arguments[0] || this));
|
||||
if (this.slice(0,4) == 'rgb(') {
|
||||
var cols = this.slice(4,this.length-1).split(',');
|
||||
var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);
|
||||
} else {
|
||||
if (this.slice(0,1) == '#') {
|
||||
if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();
|
||||
if (this.length==7) color = this.toLowerCase();
|
||||
}
|
||||
}
|
||||
return (color.length==7 ? color : (arguments[0] || this));
|
||||
};
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Element.collectTextNodes = function(element) {
|
||||
Element.collectTextNodes = function(element) {
|
||||
return $A($(element).childNodes).collect( function(node) {
|
||||
return (node.nodeType==3 ? node.nodeValue :
|
||||
return (node.nodeType==3 ? node.nodeValue :
|
||||
(node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
|
||||
}).flatten().join('');
|
||||
};
|
||||
|
||||
Element.collectTextNodesIgnoreClass = function(element, className) {
|
||||
Element.collectTextNodesIgnoreClass = function(element, className) {
|
||||
return $A($(element).childNodes).collect( function(node) {
|
||||
return (node.nodeType==3 ? node.nodeValue :
|
||||
((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
|
||||
return (node.nodeType==3 ? node.nodeValue :
|
||||
((node.hasChildNodes() && !Element.hasClassName(node,className)) ?
|
||||
Element.collectTextNodesIgnoreClass(node, className) : ''));
|
||||
}).flatten().join('');
|
||||
};
|
||||
|
||||
Element.setContentZoom = function(element, percent) {
|
||||
element = $(element);
|
||||
element.setStyle({fontSize: (percent/100) + 'em'});
|
||||
element = $(element);
|
||||
element.setStyle({fontSize: (percent/100) + 'em'});
|
||||
if (Prototype.Browser.WebKit) window.scrollBy(0,0);
|
||||
return element;
|
||||
};
|
||||
@@ -70,28 +70,23 @@ var Effect = {
|
||||
Transitions: {
|
||||
linear: Prototype.K,
|
||||
sinoidal: function(pos) {
|
||||
return (-Math.cos(pos*Math.PI)/2) + 0.5;
|
||||
return (-Math.cos(pos*Math.PI)/2) + .5;
|
||||
},
|
||||
reverse: function(pos) {
|
||||
return 1-pos;
|
||||
},
|
||||
flicker: function(pos) {
|
||||
var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
|
||||
var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4;
|
||||
return pos > 1 ? 1 : pos;
|
||||
},
|
||||
wobble: function(pos) {
|
||||
return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
|
||||
return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5;
|
||||
},
|
||||
pulse: function(pos, pulses) {
|
||||
pulses = pulses || 5;
|
||||
return (
|
||||
((pos % (1/pulses)) * pulses).round() == 0 ?
|
||||
((pos * pulses * 2) - (pos * pulses * 2).floor()) :
|
||||
1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
|
||||
);
|
||||
pulse: function(pos, pulses) {
|
||||
return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5;
|
||||
},
|
||||
spring: function(pos) {
|
||||
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
|
||||
spring: function(pos) {
|
||||
return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6));
|
||||
},
|
||||
none: function(pos) {
|
||||
return 0;
|
||||
@@ -112,14 +107,14 @@ var Effect = {
|
||||
tagifyText: function(element) {
|
||||
var tagifyStyle = 'position:relative';
|
||||
if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
|
||||
|
||||
|
||||
element = $(element);
|
||||
$A(element.childNodes).each( function(child) {
|
||||
if (child.nodeType==3) {
|
||||
child.nodeValue.toArray().each( function(character) {
|
||||
element.insertBefore(
|
||||
new Element('span', {style: tagifyStyle}).update(
|
||||
character == ' ' ? String.fromCharCode(160) : character),
|
||||
character == ' ' ? String.fromCharCode(160) : character),
|
||||
child);
|
||||
});
|
||||
Element.remove(child);
|
||||
@@ -128,13 +123,13 @@ var Effect = {
|
||||
},
|
||||
multiple: function(element, effect) {
|
||||
var elements;
|
||||
if (((typeof element == 'object') ||
|
||||
Object.isFunction(element)) &&
|
||||
if (((typeof element == 'object') ||
|
||||
Object.isFunction(element)) &&
|
||||
(element.length))
|
||||
elements = element;
|
||||
else
|
||||
elements = $(element).childNodes;
|
||||
|
||||
|
||||
var options = Object.extend({
|
||||
speed: 0.1,
|
||||
delay: 0.0
|
||||
@@ -156,7 +151,7 @@ var Effect = {
|
||||
var options = Object.extend({
|
||||
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
|
||||
}, arguments[2] || { });
|
||||
Effect[element.visible() ?
|
||||
Effect[element.visible() ?
|
||||
Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
|
||||
}
|
||||
};
|
||||
@@ -168,20 +163,20 @@ Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;
|
||||
Effect.ScopedQueue = Class.create(Enumerable, {
|
||||
initialize: function() {
|
||||
this.effects = [];
|
||||
this.interval = null;
|
||||
this.interval = null;
|
||||
},
|
||||
_each: function(iterator) {
|
||||
this.effects._each(iterator);
|
||||
},
|
||||
add: function(effect) {
|
||||
var timestamp = new Date().getTime();
|
||||
|
||||
var position = Object.isString(effect.options.queue) ?
|
||||
|
||||
var position = Object.isString(effect.options.queue) ?
|
||||
effect.options.queue : effect.options.queue.position;
|
||||
|
||||
|
||||
switch(position) {
|
||||
case 'front':
|
||||
// move unstarted effects after this effect
|
||||
// move unstarted effects after this effect
|
||||
this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
|
||||
e.startOn += effect.finishOn;
|
||||
e.finishOn += effect.finishOn;
|
||||
@@ -195,13 +190,13 @@ Effect.ScopedQueue = Class.create(Enumerable, {
|
||||
timestamp = this.effects.pluck('finishOn').max() || timestamp;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
effect.startOn += timestamp;
|
||||
effect.finishOn += timestamp;
|
||||
|
||||
if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
|
||||
this.effects.push(effect);
|
||||
|
||||
|
||||
if (!this.interval)
|
||||
this.interval = setInterval(this.loop.bind(this), 15);
|
||||
},
|
||||
@@ -214,7 +209,7 @@ Effect.ScopedQueue = Class.create(Enumerable, {
|
||||
},
|
||||
loop: function() {
|
||||
var timePos = new Date().getTime();
|
||||
for(var i=0, len=this.effects.length;i<len;i++)
|
||||
for(var i=0, len=this.effects.length;i<len;i++)
|
||||
this.effects[i] && this.effects[i].loop(timePos);
|
||||
}
|
||||
});
|
||||
@@ -223,7 +218,7 @@ Effect.Queues = {
|
||||
instances: $H(),
|
||||
get: function(queueName) {
|
||||
if (!Object.isString(queueName)) return queueName;
|
||||
|
||||
|
||||
return this.instances.get(queueName) ||
|
||||
this.instances.set(queueName, new Effect.ScopedQueue());
|
||||
}
|
||||
@@ -248,23 +243,35 @@ Effect.Base = Class.create({
|
||||
this.fromToDelta = this.options.to-this.options.from;
|
||||
this.totalTime = this.finishOn-this.startOn;
|
||||
this.totalFrames = this.options.fps*this.options.duration;
|
||||
|
||||
eval('this.render = function(pos){ '+
|
||||
'if (this.state=="idle"){this.state="running";'+
|
||||
codeForEvent(this.options,'beforeSetup')+
|
||||
(this.setup ? 'this.setup();':'')+
|
||||
codeForEvent(this.options,'afterSetup')+
|
||||
'};if (this.state=="running"){'+
|
||||
'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
|
||||
'this.position=pos;'+
|
||||
codeForEvent(this.options,'beforeUpdate')+
|
||||
(this.update ? 'this.update(pos);':'')+
|
||||
codeForEvent(this.options,'afterUpdate')+
|
||||
'}}');
|
||||
|
||||
|
||||
this.render = (function() {
|
||||
function dispatch(effect, eventName) {
|
||||
if (effect.options[eventName + 'Internal'])
|
||||
effect.options[eventName + 'Internal'](effect);
|
||||
if (effect.options[eventName])
|
||||
effect.options[eventName](effect);
|
||||
}
|
||||
|
||||
return function(pos) {
|
||||
if (this.state === "idle") {
|
||||
this.state = "running";
|
||||
dispatch(this, 'beforeSetup');
|
||||
if (this.setup) this.setup();
|
||||
dispatch(this, 'afterSetup');
|
||||
}
|
||||
if (this.state === "running") {
|
||||
pos = (this.options.transition(pos) * this.fromToDelta) + this.options.from;
|
||||
this.position = pos;
|
||||
dispatch(this, 'beforeUpdate');
|
||||
if (this.update) this.update(pos);
|
||||
dispatch(this, 'afterUpdate');
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
this.event('beforeStart');
|
||||
if (!this.options.sync)
|
||||
Effect.Queues.get(Object.isString(this.options.queue) ?
|
||||
Effect.Queues.get(Object.isString(this.options.queue) ?
|
||||
'global' : this.options.queue.scope).add(this);
|
||||
},
|
||||
loop: function(timePos) {
|
||||
@@ -273,9 +280,9 @@ Effect.Base = Class.create({
|
||||
this.render(1.0);
|
||||
this.cancel();
|
||||
this.event('beforeFinish');
|
||||
if (this.finish) this.finish();
|
||||
if (this.finish) this.finish();
|
||||
this.event('afterFinish');
|
||||
return;
|
||||
return;
|
||||
}
|
||||
var pos = (timePos - this.startOn) / this.totalTime,
|
||||
frame = (pos * this.totalFrames).round();
|
||||
@@ -287,7 +294,7 @@ Effect.Base = Class.create({
|
||||
},
|
||||
cancel: function() {
|
||||
if (!this.options.sync)
|
||||
Effect.Queues.get(Object.isString(this.options.queue) ?
|
||||
Effect.Queues.get(Object.isString(this.options.queue) ?
|
||||
'global' : this.options.queue.scope).remove(this);
|
||||
this.state = 'finished';
|
||||
},
|
||||
@@ -325,10 +332,10 @@ Effect.Parallel = Class.create(Effect.Base, {
|
||||
Effect.Tween = Class.create(Effect.Base, {
|
||||
initialize: function(object, from, to) {
|
||||
object = Object.isString(object) ? $(object) : object;
|
||||
var args = $A(arguments), method = args.last(),
|
||||
var args = $A(arguments), method = args.last(),
|
||||
options = args.length == 5 ? args[3] : null;
|
||||
this.method = Object.isFunction(method) ? method.bind(object) :
|
||||
Object.isFunction(object[method]) ? object[method].bind(object) :
|
||||
Object.isFunction(object[method]) ? object[method].bind(object) :
|
||||
function(value) { object[method] = value };
|
||||
this.start(Object.extend({ from: from, to: to }, options || { }));
|
||||
},
|
||||
@@ -392,7 +399,7 @@ Effect.Move = Class.create(Effect.Base, {
|
||||
|
||||
// for backwards compatibility
|
||||
Effect.MoveBy = function(element, toTop, toLeft) {
|
||||
return new Effect.Move(element,
|
||||
return new Effect.Move(element,
|
||||
Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
|
||||
};
|
||||
|
||||
@@ -414,15 +421,15 @@ Effect.Scale = Class.create(Effect.Base, {
|
||||
setup: function() {
|
||||
this.restoreAfterFinish = this.options.restoreAfterFinish || false;
|
||||
this.elementPositioning = this.element.getStyle('position');
|
||||
|
||||
|
||||
this.originalStyle = { };
|
||||
['top','left','width','height','fontSize'].each( function(k) {
|
||||
this.originalStyle[k] = this.element.style[k];
|
||||
}.bind(this));
|
||||
|
||||
|
||||
this.originalTop = this.element.offsetTop;
|
||||
this.originalLeft = this.element.offsetLeft;
|
||||
|
||||
|
||||
var fontSize = this.element.getStyle('font-size') || '100%';
|
||||
['em','px','%','pt'].each( function(fontSizeType) {
|
||||
if (fontSize.indexOf(fontSizeType)>0) {
|
||||
@@ -430,9 +437,9 @@ Effect.Scale = Class.create(Effect.Base, {
|
||||
this.fontSizeType = fontSizeType;
|
||||
}
|
||||
}.bind(this));
|
||||
|
||||
|
||||
this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
|
||||
|
||||
|
||||
this.dims = null;
|
||||
if (this.options.scaleMode=='box')
|
||||
this.dims = [this.element.offsetHeight, this.element.offsetWidth];
|
||||
@@ -507,17 +514,16 @@ Effect.Highlight = Class.create(Effect.Base, {
|
||||
|
||||
Effect.ScrollTo = function(element) {
|
||||
var options = arguments[1] || { },
|
||||
scrollOffsets = document.viewport.getScrollOffsets(),
|
||||
elementOffsets = $(element).cumulativeOffset(),
|
||||
max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();
|
||||
scrollOffsets = document.viewport.getScrollOffsets(),
|
||||
elementOffsets = $(element).cumulativeOffset();
|
||||
|
||||
if (options.offset) elementOffsets[1] += options.offset;
|
||||
|
||||
return new Effect.Tween(null,
|
||||
scrollOffsets.top,
|
||||
elementOffsets[1] > max ? max : elementOffsets[1],
|
||||
elementOffsets[1],
|
||||
options,
|
||||
function(p){ scrollTo(scrollOffsets.left, p.round()) }
|
||||
function(p){ scrollTo(scrollOffsets.left, p.round()); }
|
||||
);
|
||||
};
|
||||
|
||||
@@ -529,9 +535,9 @@ Effect.Fade = function(element) {
|
||||
var options = Object.extend({
|
||||
from: element.getOpacity() || 1.0,
|
||||
to: 0.0,
|
||||
afterFinishInternal: function(effect) {
|
||||
afterFinishInternal: function(effect) {
|
||||
if (effect.options.to!=0) return;
|
||||
effect.element.hide().setStyle({opacity: oldOpacity});
|
||||
effect.element.hide().setStyle({opacity: oldOpacity});
|
||||
}
|
||||
}, arguments[1] || { });
|
||||
return new Effect.Opacity(element,options);
|
||||
@@ -547,15 +553,15 @@ Effect.Appear = function(element) {
|
||||
effect.element.forceRerendering();
|
||||
},
|
||||
beforeSetup: function(effect) {
|
||||
effect.element.setOpacity(effect.options.from).show();
|
||||
effect.element.setOpacity(effect.options.from).show();
|
||||
}}, arguments[1] || { });
|
||||
return new Effect.Opacity(element,options);
|
||||
};
|
||||
|
||||
Effect.Puff = function(element) {
|
||||
element = $(element);
|
||||
var oldStyle = {
|
||||
opacity: element.getInlineOpacity(),
|
||||
var oldStyle = {
|
||||
opacity: element.getInlineOpacity(),
|
||||
position: element.getStyle('position'),
|
||||
top: element.style.top,
|
||||
left: element.style.left,
|
||||
@@ -563,12 +569,12 @@ Effect.Puff = function(element) {
|
||||
height: element.style.height
|
||||
};
|
||||
return new Effect.Parallel(
|
||||
[ new Effect.Scale(element, 200,
|
||||
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
|
||||
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
|
||||
Object.extend({ duration: 1.0,
|
||||
[ new Effect.Scale(element, 200,
|
||||
{ sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }),
|
||||
new Effect.Opacity(element, { sync: true, to: 0.0 } ) ],
|
||||
Object.extend({ duration: 1.0,
|
||||
beforeSetupInternal: function(effect) {
|
||||
Position.absolutize(effect.effects[0].element)
|
||||
Position.absolutize(effect.effects[0].element);
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.effects[0].element.hide().setStyle(oldStyle); }
|
||||
@@ -580,12 +586,12 @@ Effect.BlindUp = function(element) {
|
||||
element = $(element);
|
||||
element.makeClipping();
|
||||
return new Effect.Scale(element, 0,
|
||||
Object.extend({ scaleContent: false,
|
||||
scaleX: false,
|
||||
Object.extend({ scaleContent: false,
|
||||
scaleX: false,
|
||||
restoreAfterFinish: true,
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.hide().undoClipping();
|
||||
}
|
||||
}
|
||||
}, arguments[1] || { })
|
||||
);
|
||||
};
|
||||
@@ -593,15 +599,15 @@ Effect.BlindUp = function(element) {
|
||||
Effect.BlindDown = function(element) {
|
||||
element = $(element);
|
||||
var elementDimensions = element.getDimensions();
|
||||
return new Effect.Scale(element, 100, Object.extend({
|
||||
scaleContent: false,
|
||||
return new Effect.Scale(element, 100, Object.extend({
|
||||
scaleContent: false,
|
||||
scaleX: false,
|
||||
scaleFrom: 0,
|
||||
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
|
||||
restoreAfterFinish: true,
|
||||
afterSetup: function(effect) {
|
||||
effect.element.makeClipping().setStyle({height: '0px'}).show();
|
||||
},
|
||||
effect.element.makeClipping().setStyle({height: '0px'}).show();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.undoClipping();
|
||||
}
|
||||
@@ -616,16 +622,16 @@ Effect.SwitchOff = function(element) {
|
||||
from: 0,
|
||||
transition: Effect.Transitions.flicker,
|
||||
afterFinishInternal: function(effect) {
|
||||
new Effect.Scale(effect.element, 1, {
|
||||
new Effect.Scale(effect.element, 1, {
|
||||
duration: 0.3, scaleFromCenter: true,
|
||||
scaleX: false, scaleContent: false, restoreAfterFinish: true,
|
||||
beforeSetup: function(effect) {
|
||||
beforeSetup: function(effect) {
|
||||
effect.element.makePositioned().makeClipping();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}, arguments[1] || { }));
|
||||
};
|
||||
@@ -637,16 +643,16 @@ Effect.DropOut = function(element) {
|
||||
left: element.getStyle('left'),
|
||||
opacity: element.getInlineOpacity() };
|
||||
return new Effect.Parallel(
|
||||
[ new Effect.Move(element, {x: 0, y: 100, sync: true }),
|
||||
[ new Effect.Move(element, {x: 0, y: 100, sync: true }),
|
||||
new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
|
||||
Object.extend(
|
||||
{ duration: 0.5,
|
||||
beforeSetup: function(effect) {
|
||||
effect.effects[0].element.makePositioned();
|
||||
effect.effects[0].element.makePositioned();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
|
||||
}
|
||||
}
|
||||
}, arguments[1] || { }));
|
||||
};
|
||||
|
||||
@@ -674,7 +680,7 @@ Effect.Shake = function(element) {
|
||||
new Effect.Move(effect.element,
|
||||
{ x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
|
||||
effect.element.undoPositioned().setStyle(oldStyle);
|
||||
}}) }}) }}) }}) }}) }});
|
||||
}}); }}); }}); }}); }}); }});
|
||||
};
|
||||
|
||||
Effect.SlideDown = function(element) {
|
||||
@@ -682,9 +688,9 @@ Effect.SlideDown = function(element) {
|
||||
// SlideDown need to have the content of the element wrapped in a container element with fixed height!
|
||||
var oldInnerBottom = element.down().getStyle('bottom');
|
||||
var elementDimensions = element.getDimensions();
|
||||
return new Effect.Scale(element, 100, Object.extend({
|
||||
scaleContent: false,
|
||||
scaleX: false,
|
||||
return new Effect.Scale(element, 100, Object.extend({
|
||||
scaleContent: false,
|
||||
scaleX: false,
|
||||
scaleFrom: window.opera ? 0 : 1,
|
||||
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
|
||||
restoreAfterFinish: true,
|
||||
@@ -692,11 +698,11 @@ Effect.SlideDown = function(element) {
|
||||
effect.element.makePositioned();
|
||||
effect.element.down().makePositioned();
|
||||
if (window.opera) effect.element.setStyle({top: ''});
|
||||
effect.element.makeClipping().setStyle({height: '0px'}).show();
|
||||
effect.element.makeClipping().setStyle({height: '0px'}).show();
|
||||
},
|
||||
afterUpdateInternal: function(effect) {
|
||||
effect.element.down().setStyle({bottom:
|
||||
(effect.dims[0] - effect.element.clientHeight) + 'px' });
|
||||
(effect.dims[0] - effect.element.clientHeight) + 'px' });
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.undoClipping().undoPositioned();
|
||||
@@ -710,8 +716,8 @@ Effect.SlideUp = function(element) {
|
||||
var oldInnerBottom = element.down().getStyle('bottom');
|
||||
var elementDimensions = element.getDimensions();
|
||||
return new Effect.Scale(element, window.opera ? 0 : 1,
|
||||
Object.extend({ scaleContent: false,
|
||||
scaleX: false,
|
||||
Object.extend({ scaleContent: false,
|
||||
scaleX: false,
|
||||
scaleMode: 'box',
|
||||
scaleFrom: 100,
|
||||
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
|
||||
@@ -721,7 +727,7 @@ Effect.SlideUp = function(element) {
|
||||
effect.element.down().makePositioned();
|
||||
if (window.opera) effect.element.setStyle({top: ''});
|
||||
effect.element.makeClipping().show();
|
||||
},
|
||||
},
|
||||
afterUpdateInternal: function(effect) {
|
||||
effect.element.down().setStyle({bottom:
|
||||
(effect.dims[0] - effect.element.clientHeight) + 'px' });
|
||||
@@ -734,15 +740,15 @@ Effect.SlideUp = function(element) {
|
||||
);
|
||||
};
|
||||
|
||||
// Bug in opera makes the TD containing this element expand for a instance after finish
|
||||
// Bug in opera makes the TD containing this element expand for a instance after finish
|
||||
Effect.Squish = function(element) {
|
||||
return new Effect.Scale(element, window.opera ? 1 : 0, {
|
||||
return new Effect.Scale(element, window.opera ? 1 : 0, {
|
||||
restoreAfterFinish: true,
|
||||
beforeSetup: function(effect) {
|
||||
effect.element.makeClipping();
|
||||
},
|
||||
effect.element.makeClipping();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.hide().undoClipping();
|
||||
effect.element.hide().undoClipping();
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -762,13 +768,13 @@ Effect.Grow = function(element) {
|
||||
width: element.style.width,
|
||||
opacity: element.getInlineOpacity() };
|
||||
|
||||
var dims = element.getDimensions();
|
||||
var dims = element.getDimensions();
|
||||
var initialMoveX, initialMoveY;
|
||||
var moveX, moveY;
|
||||
|
||||
|
||||
switch (options.direction) {
|
||||
case 'top-left':
|
||||
initialMoveX = initialMoveY = moveX = moveY = 0;
|
||||
initialMoveX = initialMoveY = moveX = moveY = 0;
|
||||
break;
|
||||
case 'top-right':
|
||||
initialMoveX = dims.width;
|
||||
@@ -793,11 +799,11 @@ Effect.Grow = function(element) {
|
||||
moveY = -dims.height / 2;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
return new Effect.Move(element, {
|
||||
x: initialMoveX,
|
||||
y: initialMoveY,
|
||||
duration: 0.01,
|
||||
duration: 0.01,
|
||||
beforeSetup: function(effect) {
|
||||
effect.element.hide().makeClipping().makePositioned();
|
||||
},
|
||||
@@ -806,17 +812,17 @@ Effect.Grow = function(element) {
|
||||
[ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
|
||||
new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
|
||||
new Effect.Scale(effect.element, 100, {
|
||||
scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
|
||||
scaleMode: { originalHeight: dims.height, originalWidth: dims.width },
|
||||
sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
|
||||
], Object.extend({
|
||||
beforeSetup: function(effect) {
|
||||
effect.effects[0].element.setStyle({height: '0px'}).show();
|
||||
effect.effects[0].element.setStyle({height: '0px'}).show();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
|
||||
effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
|
||||
}
|
||||
}, options)
|
||||
)
|
||||
);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -838,7 +844,7 @@ Effect.Shrink = function(element) {
|
||||
|
||||
var dims = element.getDimensions();
|
||||
var moveX, moveY;
|
||||
|
||||
|
||||
switch (options.direction) {
|
||||
case 'top-left':
|
||||
moveX = moveY = 0;
|
||||
@@ -855,19 +861,19 @@ Effect.Shrink = function(element) {
|
||||
moveX = dims.width;
|
||||
moveY = dims.height;
|
||||
break;
|
||||
case 'center':
|
||||
case 'center':
|
||||
moveX = dims.width / 2;
|
||||
moveY = dims.height / 2;
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
return new Effect.Parallel(
|
||||
[ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
|
||||
new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
|
||||
new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
|
||||
], Object.extend({
|
||||
], Object.extend({
|
||||
beforeStartInternal: function(effect) {
|
||||
effect.effects[0].element.makePositioned().makeClipping();
|
||||
effect.effects[0].element.makePositioned().makeClipping();
|
||||
},
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
|
||||
@@ -877,12 +883,14 @@ Effect.Shrink = function(element) {
|
||||
|
||||
Effect.Pulsate = function(element) {
|
||||
element = $(element);
|
||||
var options = arguments[1] || { };
|
||||
var oldOpacity = element.getInlineOpacity();
|
||||
var transition = options.transition || Effect.Transitions.sinoidal;
|
||||
var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
|
||||
reverser.bind(transition);
|
||||
return new Effect.Opacity(element,
|
||||
var options = arguments[1] || { },
|
||||
oldOpacity = element.getInlineOpacity(),
|
||||
transition = options.transition || Effect.Transitions.linear,
|
||||
reverser = function(pos){
|
||||
return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5);
|
||||
};
|
||||
|
||||
return new Effect.Opacity(element,
|
||||
Object.extend(Object.extend({ duration: 2.0, from: 0,
|
||||
afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
|
||||
}, options), {transition: reverser}));
|
||||
@@ -896,12 +904,12 @@ Effect.Fold = function(element) {
|
||||
width: element.style.width,
|
||||
height: element.style.height };
|
||||
element.makeClipping();
|
||||
return new Effect.Scale(element, 5, Object.extend({
|
||||
return new Effect.Scale(element, 5, Object.extend({
|
||||
scaleContent: false,
|
||||
scaleX: false,
|
||||
afterFinishInternal: function(effect) {
|
||||
new Effect.Scale(element, 1, {
|
||||
scaleContent: false,
|
||||
new Effect.Scale(element, 1, {
|
||||
scaleContent: false,
|
||||
scaleY: false,
|
||||
afterFinishInternal: function(effect) {
|
||||
effect.element.hide().undoClipping().setStyle(oldStyle);
|
||||
@@ -916,7 +924,7 @@ Effect.Morph = Class.create(Effect.Base, {
|
||||
var options = Object.extend({
|
||||
style: { }
|
||||
}, arguments[1] || { });
|
||||
|
||||
|
||||
if (!Object.isString(options.style)) this.style = $H(options.style);
|
||||
else {
|
||||
if (options.style.include(':'))
|
||||
@@ -934,18 +942,18 @@ Effect.Morph = Class.create(Effect.Base, {
|
||||
effect.transforms.each(function(transform) {
|
||||
effect.element.style[transform.style] = '';
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
this.start(options);
|
||||
},
|
||||
|
||||
|
||||
setup: function(){
|
||||
function parseColor(color){
|
||||
if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
|
||||
color = color.parseColor();
|
||||
return $R(0,2).map(function(i){
|
||||
return parseInt( color.slice(i*2+1,i*2+3), 16 )
|
||||
return parseInt( color.slice(i*2+1,i*2+3), 16 );
|
||||
});
|
||||
}
|
||||
this.transforms = this.style.map(function(pair){
|
||||
@@ -965,9 +973,9 @@ Effect.Morph = Class.create(Effect.Base, {
|
||||
}
|
||||
|
||||
var originalValue = this.element.getStyle(property);
|
||||
return {
|
||||
style: property.camelize(),
|
||||
originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
|
||||
return {
|
||||
style: property.camelize(),
|
||||
originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
|
||||
targetValue: unit=='color' ? parseColor(value) : value,
|
||||
unit: unit
|
||||
};
|
||||
@@ -978,13 +986,13 @@ Effect.Morph = Class.create(Effect.Base, {
|
||||
transform.unit != 'color' &&
|
||||
(isNaN(transform.originalValue) || isNaN(transform.targetValue))
|
||||
)
|
||||
)
|
||||
);
|
||||
});
|
||||
},
|
||||
update: function(position) {
|
||||
var style = { }, transform, i = this.transforms.length;
|
||||
while(i--)
|
||||
style[(transform = this.transforms[i]).style] =
|
||||
style[(transform = this.transforms[i]).style] =
|
||||
transform.unit=='color' ? '#'+
|
||||
(Math.round(transform.originalValue[0]+
|
||||
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
|
||||
@@ -993,7 +1001,7 @@ Effect.Morph = Class.create(Effect.Base, {
|
||||
(Math.round(transform.originalValue[2]+
|
||||
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
|
||||
(transform.originalValue +
|
||||
(transform.targetValue - transform.originalValue) * position).toFixed(3) +
|
||||
(transform.targetValue - transform.originalValue) * position).toFixed(3) +
|
||||
(transform.unit === null ? '' : transform.unit);
|
||||
this.element.setStyle(style, true);
|
||||
}
|
||||
@@ -1030,7 +1038,7 @@ Effect.Transform = Class.create({
|
||||
});
|
||||
|
||||
Element.CSS_PROPERTIES = $w(
|
||||
'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
|
||||
'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
|
||||
'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
|
||||
'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
|
||||
'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
|
||||
@@ -1039,7 +1047,7 @@ Element.CSS_PROPERTIES = $w(
|
||||
'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
|
||||
'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
|
||||
'right textIndent top width wordSpacing zIndex');
|
||||
|
||||
|
||||
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
|
||||
|
||||
String.__parseStyleElement = document.createElement('div');
|
||||
@@ -1051,11 +1059,11 @@ String.prototype.parseStyle = function(){
|
||||
String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
|
||||
style = String.__parseStyleElement.childNodes[0].style;
|
||||
}
|
||||
|
||||
|
||||
Element.CSS_PROPERTIES.each(function(property){
|
||||
if (style[property]) styleRules.set(property, style[property]);
|
||||
if (style[property]) styleRules.set(property, style[property]);
|
||||
});
|
||||
|
||||
|
||||
if (Prototype.Browser.IE && this.include('opacity'))
|
||||
styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);
|
||||
|
||||
@@ -1074,14 +1082,14 @@ if (document.defaultView && document.defaultView.getComputedStyle) {
|
||||
Element.getStyles = function(element) {
|
||||
element = $(element);
|
||||
var css = element.currentStyle, styles;
|
||||
styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) {
|
||||
hash.set(property, css[property]);
|
||||
return hash;
|
||||
styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
|
||||
results[property] = css[property];
|
||||
return results;
|
||||
});
|
||||
if (!styles.opacity) styles.set('opacity', element.getOpacity());
|
||||
if (!styles.opacity) styles.opacity = element.getOpacity();
|
||||
return styles;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
Effect.Methods = {
|
||||
morph: function(element, style) {
|
||||
@@ -1090,7 +1098,7 @@ Effect.Methods = {
|
||||
return element;
|
||||
},
|
||||
visualEffect: function(element, effect, options) {
|
||||
element = $(element)
|
||||
element = $(element);
|
||||
var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
|
||||
new Effect[klass](element, options);
|
||||
return element;
|
||||
@@ -1104,17 +1112,17 @@ Effect.Methods = {
|
||||
|
||||
$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
|
||||
'pulsate shake puff squish switchOff dropOut').each(
|
||||
function(effect) {
|
||||
function(effect) {
|
||||
Effect.Methods[effect] = function(element, options){
|
||||
element = $(element);
|
||||
Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
|
||||
return element;
|
||||
}
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
|
||||
$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each(
|
||||
function(f) { Effect.Methods[f] = Element[f]; }
|
||||
);
|
||||
|
||||
Element.addMethods(Effect.Methods);
|
||||
Element.addMethods(Effect.Methods);
|
||||
@@ -1,8 +1,8 @@
|
||||
module Rails
|
||||
module VERSION #:nodoc:
|
||||
MAJOR = 2
|
||||
MINOR = 2
|
||||
TINY = 1
|
||||
MINOR = 3
|
||||
TINY = 0
|
||||
|
||||
STRING = [MAJOR, MINOR, TINY].join('.')
|
||||
end
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require 'rbconfig'
|
||||
require 'digest/md5'
|
||||
require 'active_support/secure_random'
|
||||
|
||||
class AppGenerator < Rails::Generator::Base
|
||||
DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'],
|
||||
|
||||
@@ -293,8 +293,8 @@ uses_mocha 'i18n settings' do
|
||||
|
||||
Rails::Initializer.run(:initialize_i18n, config)
|
||||
assert_equal [
|
||||
"./test/../../activesupport/lib/active_support/locale/en-US.yml",
|
||||
"./test/../../actionpack/lib/action_view/locale/en-US.yml",
|
||||
File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"),
|
||||
File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"),
|
||||
"my/test/locale.yml",
|
||||
"my/other/locale.yml" ], I18n.load_path
|
||||
end
|
||||
@@ -306,4 +306,4 @@ uses_mocha 'i18n settings' do
|
||||
assert_equal :de, I18n.default_locale
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user