require 'mega/dictionary' require 'nitro/compiler/morphing' # Javascript related morphers. module Nitro #-- # A useful superclass for morphers. Provides easy access to # js/css shared buffers. #++ class SharedMorpher < Morpher # :nodoc: all include JavascriptUtils # Record javascript to be injected in the template. def record_js(code) (@compiler.shared[:js_buffer] ||= '') << code end alias_method :js, :record_js # Record css to be injected in the template. def record_css(css) (@compiler.shared[:css_buffer] ||= '') << css end alias_method :css, :record_css # Require javascript files. def require_script_file(*names) files = (@compiler.shared[:js_required_files] ||= Dictionary.new) for name in names files[name] = true end end alias_method :add_script_file, :require_script_file end # Transform a normal achor into an asynchronous request: # ... # becomes # ... class AsyncMorpher < SharedMorpher def before_start(buffer) require_script_file :prototype href = @attributes['href'] @attributes['href'] = '#' @attributes['onclick'] = "new Ajax.Request('#{href}'); return false;" @attributes.delete(@key) end end # Transform script attributes. # #
... # becomes # ... # # .. # becomes # ... class ScriptMorpher < SharedMorpher def before_start(buffer) require_script_file :prototype case @name when 'form' @attributes['onsubmit'] = "#@value(); return false" else @attributes['href'] = '#' @attributes['onclick'] = "#@value(); return false" end @attributes.delete(@key) end end # Transform client attributes. '__nc_' marks Nitro generated # javascript functions. # # ... # becomes # ... # # .. # becomes # ... class ClientMorpher < SharedMorpher def before_start(buffer) require_script_file :prototype, :effects case @name when 'form' @attributes['onsubmit'] = "__nc_#@value(); return false" else @attributes['href'] = '#' @attributes['onclick'] = "__nc_#@value(); return false" end @attributes.delete(@key) end end # Makes a DOM element draggable. class DraggableMorpher < SharedMorpher def before_start(buffer) require_script_file :prototype, :effects, :dragdrop id = @attributes['id'] || @attributes['name'] options = @attributes['drag_options'] || '' js "new Draggable('#{id}', #{hash_to_js(options)});" @attributes.delete(@key) end end # Adds auto-complete functionality to a standard input field. # # === Example # # # # You need to provide the autocomplete values by means of a # custom action: {field_id}_auto_complete. The method should # return a