Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

root/plugins/upload_progress/lib/upload_progress_helper.rb

Revision 3424, 16.8 kB (checked in by madrobby, 3 years ago)

Added upload_progress as a plugin

Line 
1 module UploadProgress
2   # Provides a set of methods to be used in your views to help with the
3   # rendering of Ajax enabled status updating during a multipart upload.
4   #
5   # The basic mechanism for upload progress is that the form will post to a
6   # hidden <iframe> element, then poll a status action that will replace the
7   # contents of a status container.  Client Javascript hooks are provided for
8   # +begin+ and +finish+ of the update.
9   #
10   # If you wish to have a DTD that will validate this page, use XHTML
11   # Transitional because this DTD supports the <iframe> element.
12   #
13   # == Typical usage
14   #
15   # In your upload view:
16   #
17   #   <%= form_tag_with_upload_progress({ :action => 'create' }) %>
18   #     <%= file_field "document", "file" %>
19   #     <%= submit_tag "Upload" %>
20   #     <%= upload_status_tag %>
21   #   <%= end_form_tag %>
22   #
23   # In your controller:
24   #
25   #   class DocumentController < ApplicationController   
26   #     upload_status_for  :create
27   #     
28   #     def create
29   #       # ... Your document creation action
30   #     end
31   #   end
32   #   
33   # == Javascript callback on begin and finished
34   #
35   # In your upload view:
36   #
37   #   <%= form_tag_with_upload_progress({ :action => 'create' }, {
38   #       :begin => "alert('upload beginning'),
39   #       :finish => "alert('upload finished')}) %>
40   #     <%= file_field "document", "file" %>
41   #     <%= submit_tag "Upload" %>
42   #     <%= upload_status_tag %>
43   #   <%= end_form_tag %>
44   #
45   #
46   # == CSS Styling of the status text and progress bar
47   #
48   # See +upload_status_text_tag+ and +upload_status_progress_bar_tag+ for references
49   # of the IDs and CSS classes used.
50   #
51   # Default styling is included with the scaffolding CSS.
52   module UploadProgressHelper
53     unless const_defined? :FREQUENCY
54       # Default number of seconds between client updates
55       FREQUENCY = 2.0
56
57       # Factor to decrease the frequency when the +upload_status+ action returns the same results
58       # To disable update decay, set this constant to +false+
59       FREQUENCY_DECAY = 1.8
60     end
61    
62     # Contains a hash of status messages used for localization of
63     # +upload_progress_status+ and +upload_progress_text+.  Each string is
64     # evaluated in the helper method context so you can include your own
65     # calculations and string iterpolations.
66     #
67     # The following keys are defined:
68     #
69     # <tt>:begin</tt>::      Displayed before the first byte is received on the server
70     # <tt>:update</tt>::     Contains a human representation of the upload progress
71     # <tt>:finish</tt>::     Displayed when the file upload is complete, before the action has completed.  If you are performing extra activity in your action such as processing of the upload, then inform the user of what you are doing by setting +upload_progress.message+
72     #
73     @@default_messages = {
74       :begin => '"Upload starting..."',
75       :update => '"#{human_size(upload_progress.received_bytes)} of #{human_size(upload_progress.total_bytes)} at #{human_size(upload_progress.bitrate)}/s; #{distance_of_time_in_words(0,upload_progress.remaining_seconds,true)} remaining"',
76       :finish => 'upload_progress.message.blank? ? "Upload finished." : upload_progress.message',
77     }
78
79
80     # Creates a form tag and hidden <iframe> necessary for the upload progress
81     # status messages to be displayed in a designated +div+ on your page.
82     #
83     # == Initializations
84     #
85     # When the upload starts, the content created by +upload_status_tag+ will be filled out with
86     # "Upload starting...".  When the upload is finished, "Upload finished." will be used.  Every
87     # update inbetween the begin and finish events will be determined by the server +upload_status+
88     # action.  Doing this automatically means that the user can use the same form to upload multiple
89     # files without refreshing page while still displaying a reasonable progress.
90     #
91     # == Upload IDs
92     #
93     # For the view and the controller to know about the same upload they must share
94     # a common +upload_id+.  +form_tag_with_upload_progress+ prepares the next available
95     # +upload_id+ when called.  There are other methods which use the +upload_id+ so the
96     # order in which you include your content is important.  Any content that depends on the
97     # +upload_id+ will use the one defined +form_tag_with_upload_progress+
98     # otherwise you will need to explicitly declare the +upload_id+ shared among
99     # your progress elements.
100     #
101     # Status container after the form:
102     #
103     #   <%= form_tag_with_upload_progress %>
104     #   <%= end_form_tag %>
105     #
106     #   <%= upload_status_tag %>
107     #
108     # Status container before form:
109     #
110     #   <% my_upload_id = next_upload_id %>
111     #
112     #   <%= upload_status_tag %>
113     #
114     #   <%= form_tag_with_upload_progress :upload_id => my_upload_id %>
115     #   <%= end_form_tag %>
116     #
117     # It is recommended that the helpers manage the +upload_id+ parameter.
118     #
119     # == Options
120     #
121     # +form_tag_with_upload_progress+ uses similar options as +form_tag+
122     # yet accepts another hash for the options used for the +upload_status+ action.
123     #
124     # <tt>url_for_options</tt>:: The same options used by +form_tag+ including:
125     # <tt>:upload_id</tt>:: the upload id used to uniquely identify this upload
126     #
127     # <tt>options</tt>:: similar options to +form_tag+ including:
128     # <tt>:begin</tt>::   Javascript code that executes before the first status update occurs.
129     # <tt>:finish</tt>::  Javascript code that executes after the action that receives the post returns.
130     # <tt>:frequency</tt>:: number of seconds between polls to the upload status action.
131     #
132     # <tt>status_url_for_options</tt>:: options passed to +url_for+ to build the url
133     # for the upload status action.
134     # <tt>:controller</tt>::  defines the controller to be used for a custom update status action
135     # <tt>:action</tt>::      defines the action to be used for a custom update status action
136     #
137     # Parameters passed to the action defined by status_url_for_options
138     #
139     # <tt>:upload_id</tt>::   the upload_id automatically generated by +form_tag_with_upload_progress+ or the user defined id passed to this method.
140     #   
141     def form_tag_with_upload_progress(url_for_options = {}, options = {}, status_url_for_options = {}, *parameters_for_url_method)
142      
143       ## Setup the action URL and the server-side upload_status action for
144       ## polling of status during the upload
145
146       options = options.dup
147
148       upload_id = url_for_options.delete(:upload_id) || next_upload_id
149       upload_action_url = url_for(url_for_options)
150
151       if status_url_for_options.is_a? Hash
152         status_url_for_options = status_url_for_options.merge({
153           :action => 'upload_status',
154           :upload_id => upload_id})
155       end
156
157       status_url = url_for(status_url_for_options)
158      
159       ## Prepare the form options.  Dynamically change the target and URL to enable the status
160       ## updating only if javascript is enabled, otherwise perform the form submission in the same
161       ## frame.
162      
163       upload_target = options[:target] || upload_target_id
164       upload_id_param = "#{upload_action_url.include?('?') ? '&' : '?'}upload_id=#{upload_id}"
165      
166       ## Externally :begin and :finish are the entry and exit points
167       ## Internally, :finish is called :complete
168
169       js_options = {
170         :decay => options[:decay] || FREQUENCY_DECAY,
171         :frequency => options[:frequency] || FREQUENCY,
172       }
173
174       updater_options = '{' + js_options.map {|k, v| "#{k}:#{v}"}.sort.join(',') + '}'
175
176       ## Finish off the updating by forcing the progress bar to 100% and status text because the
177       ## results of the post may load and finish in the IFRAME before the last status update
178       ## is loaded.
179
180       options[:complete] = "$('#{status_tag_id}').innerHTML='#{escape_javascript upload_progress_text(:finish)}';"
181       options[:complete] << "#{upload_progress_update_bar_js(100)};"
182       options[:complete] << "#{upload_update_object} = null"
183       options[:complete] = "#{options[:complete]}; #{options[:finish]}" if options[:finish]
184
185       options[:script] = true
186
187       ## Prepare the periodic updater, clearing any previous updater
188
189       updater = "if (#{upload_update_object}) { #{upload_update_object}.stop(); }"
190       updater << "#{upload_update_object} = new Ajax.PeriodicalUpdater('#{status_tag_id}',"
191       updater << "'#{status_url}', Object.extend(#{options_for_ajax(options)},#{updater_options}))"
192
193       updater = "#{options[:begin]}; #{updater}" if options[:begin]
194       updater = "#{upload_progress_update_bar_js(0)}; #{updater}"
195       updater = "$('#{status_tag_id}').innerHTML='#{escape_javascript upload_progress_text(:begin)}'; #{updater}"
196      
197       ## Touch up the form action and target to use the given target instead of the
198       ## default one. Then start the updater
199
200       options[:onsubmit] = "if (this.action.indexOf('upload_id') < 0){ this.action += '#{escape_javascript upload_id_param}'; }"
201       options[:onsubmit] << "this.target = '#{escape_javascript upload_target}';"
202       options[:onsubmit] << "#{updater}; return true"
203       options[:multipart] = true
204
205       [:begin, :finish, :complete, :frequency, :decay, :script].each { |sym| options.delete(sym) }
206
207       ## Create the tags
208       ## If a target for the form is given then avoid creating the hidden IFRAME
209
210       tag = form_tag(upload_action_url, options, *parameters_for_url_method)
211
212       unless options[:target]
213         tag << content_tag('iframe', '', {
214           :id => upload_target,
215           :name => upload_target,
216           :src => '',
217           :style => 'width:0px;height:0px;border:0'
218         })
219       end
220
221       tag
222     end
223
224     # This method must be called by the action that receives the form post
225     # with the +upload_progress+.  By default this method is rendered when
226     # the controller declares that the action is the receiver of a
227     # +form_tag_with_upload_progress+ posting.
228     #
229     # This template will do a javascript redirect to the URL specified in +redirect_to+
230     # if this method is called anywhere in the controller action.  When the action
231     # performs a redirect, the +finish+ handler will not be called.
232     #
233     # If there are errors in the action then you should set the controller
234     # instance variable +@errors+.  The +@errors+ object will be
235     # converted to a javascript array from +@errors.full_messages+ and
236     # passed to the +finish+ handler of +form_tag_with_upload_progress+
237     #
238     # If no errors have occured, the parameter to the +finish+ handler will
239     # be +undefined+.
240     #
241     # == Example (in view)
242     #
243     #  <script>
244     #   function do_finish(errors) {
245     #     if (errors) {
246     #       alert(errors);
247     #     }
248     #   }
249     #  </script>
250     #
251     #  <%= form_tag_with_upload_progress {:action => 'create'}, {finish => 'do_finish(arguments[0])'} %>
252     #
253     def finish_upload_status(options = {})
254       # Always trigger the stop/finish callback
255       js = "parent.#{upload_update_object}.stop(#{options[:client_js_argument]});\n"
256
257       # Redirect if redirect_to was called in controller
258       js << "parent.location.replace('#{escape_javascript options[:redirect_to]}');\n" unless options[:redirect_to].blank?
259
260       # Guard against multiple triggers/redirects on back
261       js = "if (parent.#{upload_update_object}) { #{js} }\n"
262      
263       content_tag("html",
264         content_tag("head",
265           content_tag("script", "function finish() { #{js} }",
266             {:type => "text/javascript", :language => "javascript"})) +
267         content_tag("body", '', :onload => 'finish()'))
268     end
269
270     # Renders the HTML to contain the upload progress bar above the
271     # default messages
272     #
273     # Use this method to display the upload status after your +form_tag_with_upload_progress+
274     def upload_status_tag(content='', options={})
275       upload_status_progress_bar_tag + upload_status_text_tag(content, options)
276     end
277
278     # Content helper that will create a +div+ with the proper ID and class that
279     # will contain the contents returned by the +upload_status+ action.  The container
280     # is defined as
281     #
282     #   <div id="#{status_tag_id}" class="uploadStatus"> </div>
283     #
284     # Style this container by selecting the +.uploadStatus+ +CSS+ class.
285     #
286     # The +content+ parameter will be included in the inner most +div+ when
287     # rendered.
288     #
289     # The +options+ will create attributes on the outer most div.  To use a different
290     # +CSS+ class, pass a different class option.
291     #
292     # Example +CSS+:
293     #   .uploadStatus { font-size: 10px; color: grey; }
294     #
295     def upload_status_text_tag(content=nil, options={})
296       content_tag("div", content, {:id => status_tag_id, :class => 'uploadStatus'}.merge(options))
297     end
298
299     # Content helper that will create the element tree that can be easily styled
300     # with +CSS+ to create a progress bar effect.  The containers are defined as:
301     #
302     #   <div class="progressBar" id="#{progress_bar_id}">
303     #     <div class="border">
304     #       <div class="background">
305     #         <div class="content"> </div>
306     #       </div>
307     #     </div>
308     #   </div>
309     #
310     # The +content+ parameter will be included in the inner most +div+ when
311     # rendered.
312     #
313     # The +options+ will create attributes on the outer most div.  To use a different
314     # +CSS+ class, pass a different class option.
315     #
316     # Example:
317     #   <%= upload_status_progress_bar_tag('', {:class => 'progress'}) %>
318     #
319     # Example +CSS+:
320     #
321     #   div.progressBar {
322     #     margin: 5px;
323     #   }
324     #
325     #   div.progressBar div.border {
326     #     background-color: #fff;
327     #     border: 1px solid grey;
328     #     width: 100%;
329     #   }
330     #
331     #   div.progressBar div.background {
332     #     background-color: #333;
333     #     height: 18px;
334     #     width: 0%;
335     #   }
336     #
337     def upload_status_progress_bar_tag(content='', options={})
338       css = [options[:class], 'progressBar'].compact.join(' ')
339
340       content_tag("div",
341         content_tag("div",
342           content_tag("div",
343             content_tag("div", content, :class => 'foreground'),
344           :class => 'background'),
345         :class => 'border'),
346       {:id => progress_bar_id}.merge(options).merge({:class => css}))
347     end
348
349     # The text and Javascript returned by the default +upload_status+ controller
350     # action which will replace the contents of the div created by +upload_status_text_tag+
351     # and grow the progress bar background to the appropriate width.
352     #
353     # See +upload_progress_text+ and +upload_progress_update_bar_js+
354     def upload_progress_status
355       "#{upload_progress_text}<script>#{upload_progress_update_bar_js}</script>"
356     end
357    
358     # Javascript helper that will create a script that will change the width
359     # of the background progress bar container.  Include this in the script
360     # portion of your view rendered by your +upload_status+ action to
361     # automatically find and update the progress bar.
362     #
363     # Example (in controller):
364     #
365     #   def upload_status
366     #     render :inline => "<script><%= update_upload_progress_bar_js %></script>", :layout => false
367     #   end
368     #
369     #
370     def upload_progress_update_bar_js(percent=nil)
371       progress = upload_progress
372       percent ||= case
373         when progress.nil? || !progress.started? then 0
374         when progress.finished? then 100
375         else progress.completed_percent
376       end.to_i
377
378       # TODO do animation instead of jumping
379       "if($('#{progress_bar_id}')){$('#{progress_bar_id}').firstChild.firstChild.style.width='#{percent}%'}"
380     end
381    
382     # Generates a nicely formatted string of current upload progress for
383     # +UploadProgress::Progress+ object +progress+.  Addtionally, it
384     # will return "Upload starting..." if progress has not been initialized,
385     # "Receiving data..." if there is no received data yet, and "Upload
386     # finished" when all data has been sent.
387     #
388     # You can overload this method to add you own output to the
389     #
390     # Example return: 223.5 KB of 1.5 MB at 321.2 KB/s; less than 10 seconds
391     # remaining
392     def upload_progress_text(state=nil)
393       eval case
394         when state then @@default_messages[state.to_sym]
395         when upload_progress.nil? || !upload_progress.started? then @@default_messages[:begin]
396         when upload_progress.finished? then @@default_messages[:finish]
397         else @@default_messages[:update]
398       end
399     end
400
401     protected
402     # Javascript object used to contain the polling methods and keep track of
403     # the finished state
404     def upload_update_object
405       "document.uploadStatus#{current_upload_id}"
406     end
407
408     # Element ID of the progress bar
409     def progress_bar_id
410       "UploadProgressBar#{current_upload_id}"
411     end
412
413     # Element ID of the progress status container
414     def status_tag_id
415       "UploadStatus#{current_upload_id}"
416     end
417
418     # Element ID of the target <iframe> used as the target of the form
419     def upload_target_id
420       "UploadTarget#{current_upload_id}"
421     end
422
423   end
424 end
Note: See TracBrowser for help on using the browser.