require File.dirname(__FILE__) + '/tag_helper'
module ActionView
module Helpers
# Provides a set of helpers for calling JavaScript functions and, most importantly, to call remote methods using what has
# been labelled AJAX[http://www.adaptivepath.com/publications/essays/archives/000385.php]. This means that you can call
# actions in your controllers without reloading the page, but still update certain parts of it using injections into the
# DOM. The common use case is having a form that adds a new element to a list without reloading the page.
#
# To be able to use the JavaScript helpers, you must either call <%= define_javascript_functions %> (which returns all
# the JavaScript support functions in a '
end
# Observes the field with the DOM ID specified by +field_id+ and makes
# an AJAX call when its contents have changed.
#
# Required +options+ are:
# :url:: +url_for+-style options for the action to call
# when the field has changed.
#
# Additional options are:
# :frequency:: The frequency (in seconds) at which changes to
# this field will be detected. Set this to a value
# greater than zero to use time based observation
# instead of event based observation.
# :update:: Specifies the DOM ID of the element whose
# innerHTML should be updated with the
# XMLHttpRequest response text.
# :with:: A JavaScript expression specifying the
# parameters for the XMLHttpRequest. This defaults
# to 'value', which in the evaluated context
# refers to the new field value.
#
# Additionally, you may specify any of the options documented in
# +link_to_remote.
def observe_field(field_id, options = {})
if options[:frequency]
build_observer('Form.Element.Observer', field_id, options)
else
build_observer('Form.Element.EventObserver', field_id, options)
end
end
# Like +observe_field+, but operates on an entire form identified by the
# DOM ID +form_id+. +options+ are the same as +observe_field+, except
# the default value of the :with option evaluates to the
# serialized (request string) value of the form.
def observe_form(form_id, options = {})
if options[:frequency]
build_observer('Form.Observer', form_id, options)
else
build_observer('Form.EventObserver', form_id, options)
end
end
# Adds AJAX autocomplete functionality to the text input field with the
# DOM ID specified by +field_id+.
#
# This function expects that the called action returns a HTML
list,
# or nothing if no entries should be displayed for autocompletion.
#
# You'll probably want to turn the browser's built-in autocompletion off,
# su be sure to include a autocomplete="off" attribute with your text
# input field.
#
# Required +options+ are:
# :url:: Specifies the DOM ID of the element whose
# innerHTML should be updated with the autocomplete
# entries returned by XMLHttpRequest.
#
# Addtional +options+ are:
# :update:: Specifies the DOM ID of the element whose
# innerHTML should be updated with the autocomplete
# entries returned by the AJAX request.
# Defaults to field_id + '_auto_complete'
# :with:: A JavaScript expression specifying the
# parameters for the XMLHttpRequest. This defaults
# to 'fieldname=value'.
# :indicator:: Specifies the DOM ID of an elment which will be
# displayed while autocomplete is running.
def auto_complete_field(field_id, options = {})
function = "new Ajax.Autocompleter("
function << "'#{field_id}', "
function << "'" + (options[:update] || "#{field_id}_auto_complete") + "', "
function << "'#{url_for(options[:url])}'"
js_options = {}
js_options[:callback] = "function(element, value) { return #{options[:with]} }" if options[:with]
js_options[:indicator] = "'#{options[:indicator]}'" if options[:indicator]
function << (', ' + options_for_javascript(js_options) + ')')
javascript_tag(function)
end
# Use this method in your view to generate a return for the AJAX automplete requests.
#
# Example action:
#
# def auto_complete_for_item_title
# @items = Item.find(:all,
# :conditions => [ 'LOWER(description) LIKE ?',
# '%' + request.raw_post.downcase + '%' ])
# render :inline => '<%= auto_complete_result(@items, 'description') %>'
# end
#
# The auto_complete_result can of course also be called from a view belonging to the
# auto_complete action if you need to decorate it further.
def auto_complete_result(entries, field, phrase = nil)
return unless entries
items = entries.map { |entry| content_tag("li", phrase ? highlight(entry[field], phrase) : h(entry[field])) }
content_tag("ul", items)
end
# Wrapper for text_field with added AJAX autocompletion functionality.
#
# In your controller, you'll need to define an action called
# auto_complete_for_object_method to respond the AJAX calls,
#
# See the RDoc on ActionController::AutoComplete to learn more about this.
def text_field_with_auto_complete(object, method, tag_options = {}, completion_options = {})
(completion_options[:skip_style] ? "" : auto_complete_stylesheet) +
text_field(object, method, { :autocomplete => "off" }.merge!(tag_options)) +
content_tag("div", "", :id => "#{object}_#{method}_auto_complete", :class => "auto_complete") +
auto_complete_field("#{object}_#{method}", { :url => { :action => "auto_complete_for_#{object}_#{method}" } }.update(completion_options))
end
# Returns a JavaScript snippet to be used on the AJAX callbacks for starting
# visual effects.
#
# Example:
# <%= link_to_remote "Reload", :update => "posts",
# :url => { :action => "reload" },
# :complete => visual_effect(:highlight, "posts", :duration => 0.5 )
#
# If no element_id is given, it assumes "element" which should be a local
# variable in the generated JavaScript execution context. This can be used
# for example with drop_receiving_element:
#
# <%= drop_receving_element (...), :loading => visual_effect(:fade) %>
#
# This would fade the element that was dropped on the drop receiving element.
#
# You can change the behaviour with various options, see
# http://script.aculo.us for more documentation.
def visual_effect(name, element_id = false, js_options = {})
element = element_id ? "'#{element_id}'" : "element"
"new Effect.#{name.to_s.camelize}(#{element},#{options_for_javascript(js_options)});"
end
# Makes the element with the DOM ID specified by +element_id+ sortable
# by drag-and-drop and make an AJAX call whenever the sort order has
# changed. By default, the action called gets the serialized sortable
# element as parameters.
#
# Example:
# <%= sortable_element("my_list", :url => { :action => "order" }) %>
#
# In the example, the action gets a "my_list" array parameter
# containing the values of the ids of elements the sortable consists
# of, in the current order.
#
# You can change the behaviour with various options, see
# http://script.aculo.us for more documentation.
def sortable_element(element_id, options = {})
options[:with] ||= "Sortable.serialize('#{element_id}')"
options[:onUpdate] ||= "function(){" + remote_function(options) + "}"
options.delete_if { |key, value| AJAX_OPTIONS.include?(key) }
[:tag, :overlap, :constraint, :handle].each do |option|
options[option] = "'#{options[option]}'" if options[option]
end
if options[:containment] and options[:containment].kind_of?(Array)
options[:containment] = "['#{options[:containment].join('\',\'')}']"
elsif options[:containment]
options[:containment] = "'#{options[:containment]}'" if options[:containment]
end
javascript_tag("Sortable.create('#{element_id}', #{options_for_javascript(options)})")
end
# Makes the element with the DOM ID specified by +element_id+ draggable.
#
# Example:
# <%= draggable_element("my_image", :revert => true)
#
# You can change the behaviour with various options, see
# http://script.aculo.us for more documentation.
def draggable_element(element_id, options = {})
javascript_tag("new Draggable('#{element_id}', #{options_for_javascript(options)})")
end
# Makes the element with the DOM ID specified by +element_id+ receive
# dropped draggable elements (created by draggable_element).
# and make an AJAX call By default, the action called gets the DOM ID of the
# element as parameter.
#
# Example:
# <%= drop_receiving_element("my_cart", :url => { :controller => "cart", :action => "add" }) %>
#
# You can change the behaviour with various options, see
# http://script.aculo.us for more documentation.
def drop_receiving_element(element_id, options = {})
options[:with] ||= "'id=' + encodeURIComponent(element.id)"
options[:onDrop] ||= "function(element){" + remote_function(options) + "}"
options.delete_if { |key, value| AJAX_OPTIONS.include?(key) }
if options[:accept] and options[:accept].kind_of?(Array)
options[:accept] = "['#{options[:accept].join('\',\'')}']"
elsif options[:accept]
options[:accept] = "'#{options[:accept]}'" if options[:accept]
end
options[:hoverclass] = "'#{options[:hoverclass]}'" if options[:hoverclass]
javascript_tag("Droppables.add('#{element_id}', #{options_for_javascript(options)})")
end
# Escape carrier returns and single and double quotes for JavaScript segments.
def escape_javascript(javascript)
(javascript || '').gsub(/\r\n|\n|\r/, "\\n").gsub(/["']/) { |m| "\\#{m}" }
end
# Returns a JavaScript tag with the +content+ inside. Example:
# javascript_tag "alert('All is good')" # =>
def javascript_tag(content)
content_tag("script", content, :type => "text/javascript")
end
private
def options_for_javascript(options)
'{' + options.map {|k, v| "#{k}:#{v}"}.join(', ') + '}'
end
def options_for_ajax(options)
js_options = build_callbacks(options)
js_options['asynchronous'] = options[:type] != :synchronous
js_options['method'] = method_option_to_s(options[:method]) if options[:method]
js_options['insertion'] = "Insertion.#{options[:position].to_s.camelize}" if options[:position]
js_options['evalScripts'] = options[:script].nil? || options[:script]
if options[:form]
js_options['parameters'] = 'Form.serialize(this)'
elsif options[:with]
js_options['parameters'] = options[:with]
end
options_for_javascript(js_options)
end
def method_option_to_s(method)
(method.is_a?(String) and !method.index("'").nil?) ? method : "'#{method}'"
end
def build_observer(klass, name, options = {})
options[:with] ||= 'value' if options[:update]
callback = remote_function(options)
javascript = '"
end
def build_callbacks(options)
callbacks = {}
options.each do |callback, code|
if CALLBACKS.include?(callback)
name = 'on' + callback.to_s.capitalize
callbacks[name] = "function(request){#{code}}"
end
end
callbacks
end
def auto_complete_stylesheet
content_tag("style", <<-EOT
div.auto_complete {
width: 350px;
background: #fff;
}
div.auto_complete ul {
border:1px solid #888;
margin:0;
padding:0;
width:100%;
list-style-type:none;
}
div.auto_complete ul li {
margin:0;
padding:3px;
}
div.auto_complete ul li.selected {
background-color: #ffb;
}
div.auto_complete ul strong.highlight {
color: #800;
margin:0;
padding:0;
}
EOT
)
end
end
JavascriptHelper = JavaScriptHelper unless const_defined? :JavascriptHelper
end
end