8784: Fix test for latest firefox.
[arvados.git] / apps / workbench / app / helpers / application_helper.rb
1 module ApplicationHelper
2   def current_user
3     controller.current_user
4   end
5
6   def self.match_uuid(uuid)
7     /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
8   end
9
10   def current_api_host
11     Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,''
12   end
13
14   def render_markup(markup)
15     raw RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile) if markup
16   end
17
18   def human_readable_bytes_html(n)
19     return h(n) unless n.is_a? Fixnum
20     return "0 bytes" if (n == 0)
21
22     orders = {
23       1 => "bytes",
24       1024 => "KiB",
25       (1024*1024) => "MiB",
26       (1024*1024*1024) => "GiB",
27       (1024*1024*1024*1024) => "TiB"
28     }
29
30     orders.each do |k, v|
31       sig = (n.to_f/k)
32       if sig >=1 and sig < 1024
33         if v == 'bytes'
34           return "%i #{v}" % sig
35         else
36           return "%0.1f #{v}" % sig
37         end
38       end
39     end
40
41     return h(n)
42     #raw = n.to_s
43     #cooked = ''
44     #while raw.length > 3
45     #  cooked = ',' + raw[-3..-1] + cooked
46     #  raw = raw[0..-4]
47     #end
48     #cooked = raw + cooked
49   end
50
51   def resource_class_for_uuid(attrvalue, opts={})
52     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
53   end
54
55   # When using {remote:true}, or using {method:...} to use an HTTP
56   # method other than GET, move the target URI from href to
57   # data-remote-href. Otherwise, browsers offer features like "open in
58   # new window" and "copy link address" which bypass Rails' click
59   # handler and therefore end up at incorrect/nonexistent routes (by
60   # ignoring data-method) and expect to receive pages rather than
61   # javascript responses.
62   #
63   # See assets/javascripts/link_to_remote.js for supporting code.
64   def link_to *args, &block
65     if (args.last and args.last.is_a? Hash and
66         (args.last[:remote] or
67          (args.last[:method] and
68           args.last[:method].to_s.upcase != 'GET')))
69       if Rails.env.test?
70         # Capybara/phantomjs can't click_link without an href, even if
71         # the click handler means it never gets used.
72         raw super.gsub(' href="', ' href="#" data-remote-href="')
73       else
74         # Regular browsers work as desired: users can click A elements
75         # without hrefs, and click handlers fire; but there's no "copy
76         # link address" option in the right-click menu.
77         raw super.gsub(' href="', ' data-remote-href="')
78       end
79     else
80       super
81     end
82   end
83
84   ##
85   # Returns HTML that links to the Arvados object specified in +attrvalue+
86   # Provides various output control and styling options.
87   #
88   # +attrvalue+ an Arvados model object or uuid
89   #
90   # +opts+ a set of flags to control output:
91   #
92   # [:link_text] the link text to use (may include HTML), overrides everything else
93   #
94   # [:friendly_name] whether to use the "friendly" name in the link text (by
95   # calling #friendly_link_name on the object), otherwise use the uuid
96   #
97   # [:with_class_name] prefix the link text with the class name of the model
98   #
99   # [:no_tags] disable tags in the link text (default is to show tags).
100   # Currently tags are only shown for Collections.
101   #
102   # [:thumbnail] if the object is a collection, show an image thumbnail if the
103   # collection consists of a single image file.
104   #
105   # [:no_link] don't create a link, just return the link text
106   #
107   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
108   #
109   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
110     if (resource_class = resource_class_for_uuid(attrvalue, opts))
111       if attrvalue.is_a? ArvadosBase
112         object = attrvalue
113         link_uuid = attrvalue.uuid
114       else
115         object = nil
116         link_uuid = attrvalue
117       end
118       link_name = opts[:link_text]
119       tags = ""
120       if !link_name
121         link_name = object.andand.default_name || resource_class.default_name
122
123         if opts[:friendly_name]
124           if attrvalue.respond_to? :friendly_link_name
125             link_name = attrvalue.friendly_link_name opts[:lookup]
126           else
127             begin
128               if resource_class.name == 'Collection'
129                 if CollectionsHelper.match(link_uuid)
130                   link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
131                 else
132                   link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
133                 end
134               else
135                 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
136               end
137             rescue ArvadosApiClient::NotFoundException
138               # If that lookup failed, the link will too. So don't make one.
139               return attrvalue
140             end
141           end
142         end
143         if link_name.nil? or link_name.empty?
144           link_name = attrvalue
145         end
146         if opts[:with_class_name]
147           link_name = "#{resource_class.to_s}: #{link_name}"
148         end
149         if !opts[:no_tags] and resource_class == Collection
150           links_for_object(link_uuid).each do |tag|
151             if tag.link_class.in? ["tag", "identifier"]
152               tags += ' <span class="label label-info">'
153               tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
154               tags += '</span>'
155             end
156           end
157         end
158         if opts[:thumbnail] and resource_class == Collection
159           # add an image thumbnail if the collection consists of a single image file.
160           collections_for_object(link_uuid).each do |c|
161             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
162               link_name += " "
163               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
164             end
165           end
166         end
167       end
168       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
169       if opts[:no_link] or (resource_class == User && !current_user)
170         raw(link_name)
171       else
172         controller_class = resource_class.to_s.tableize
173         if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
174           controller_class = 'projects'
175         end
176         (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
177       end
178     else
179       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
180       if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
181         "(none)"
182       else
183         attrvalue
184       end
185     end
186   end
187
188   def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
189     resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
190     if !resource_class
191       return link_to_if_arvados_object attrvalue, opts
192     end
193
194     readable = object_readable attrvalue, resource_class
195     if readable
196       link_to_if_arvados_object attrvalue, opts
197     elsif opts[:required] and current_user # no need to show this for anonymous user
198       raw('<div><input type="text" style="border:none;width:100%;background:#ffdddd" disabled=true class="required unreadable-input" value="') + link_text_if_not_readable + raw('" ></input></div>')
199     else
200       link_text_if_not_readable
201     end
202   end
203
204   # This method takes advantage of preloaded collections and objects.
205   # Hence you can improve performance by first preloading objects
206   # related to the page context before using this method.
207   def object_readable attrvalue, resource_class=nil
208     # if it is a collection filename, check readable for the locator
209     attrvalue = attrvalue.split('/')[0] if attrvalue
210
211     resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
212     return if resource_class.nil?
213
214     return_value = nil
215     if resource_class.to_s == 'Collection'
216       if CollectionsHelper.match(attrvalue)
217         found = collection_for_pdh(attrvalue)
218         return_value = found.first if found.any?
219       else
220         found = collections_for_object(attrvalue)
221         return_value = found.first if found.any?
222       end
223     else
224       return_value = object_for_dataclass(resource_class, attrvalue)
225     end
226     return_value
227   end
228
229   # Render an editable attribute with the attrvalue of the attr.
230   # The htmloptions are added to the editable element's list of attributes.
231   # The nonhtml_options are only used to customize the display of the element.
232   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
233     attrvalue = object.send(attr) if attrvalue.nil?
234     if not object.attribute_editable?(attr)
235       if attrvalue && attrvalue.length > 0
236         return render_attribute_as_textile( object, attr, attrvalue, false )
237       else
238         return (attr == 'name' and object.andand.default_name) ||
239                 '(none)'
240       end
241     end
242
243     input_type = 'text'
244     attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
245     if attrtype == 'text' or attr == 'description'
246       input_type = 'textarea'
247     elsif attrtype == 'datetime'
248       input_type = 'date'
249     else
250       input_type = 'text'
251     end
252
253     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
254     rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
255
256     ajax_options = {
257       "data-pk" => {
258         id: object.uuid,
259         key: object.class.to_s.underscore
260       }
261     }
262     if object.uuid
263       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
264     else
265       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
266       ajax_options['data-pk'][:defaults] = object.attributes
267     end
268     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
269     @unique_id ||= (Time.now.to_f*1000000).to_i
270     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
271
272     span_tag = content_tag 'span', rendervalue, {
273       "data-emptytext" => '(none)',
274       "data-placement" => "bottom",
275       "data-type" => input_type,
276       "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
277       "data-name" => htmloptions['selection_name'] || attr,
278       "data-object-uuid" => object.uuid,
279       "data-toggle" => "manual",
280       "data-value" => htmloptions['data-value'] || attrvalue,
281       "id" => span_id,
282       :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
283     }.merge(htmloptions).merge(ajax_options)
284
285     edit_tiptitle = 'edit'
286     edit_tiptitle = 'Warning: do not use hyphens in the repository name as they will be stripped' if (object.class.to_s == 'Repository' and attr == 'name')
287
288     edit_button = raw('<a href="#" class="btn btn-xs btn-' + (nonhtml_options[:btnclass] || 'default') + ' btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (nonhtml_options[:tiptitle] || edit_tiptitle) + '"><i class="fa fa-fw fa-pencil"></i>' + (nonhtml_options[:btntext] || '') + '</a>')
289
290     if nonhtml_options[:btnplacement] == :left
291       edit_button + ' ' + span_tag
292     elsif nonhtml_options[:btnplacement] == :top
293       edit_button + raw('<br/>') + span_tag
294     else
295       span_tag + ' ' + edit_button
296     end
297   end
298
299   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
300     datatype = nil
301     required = true
302     attrvalue = value_info
303
304     if value_info.is_a? Hash
305       if value_info[:output_of]
306         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
307       end
308       if value_info[:dataclass]
309         dataclass = value_info[:dataclass]
310       end
311       if value_info[:optional] != nil
312         required = (value_info[:optional] != "true")
313       end
314       if value_info[:required] != nil
315         required = value_info[:required]
316       end
317
318       # Pick a suitable attrvalue to show as the current value (i.e.,
319       # the one that would be used if we ran the pipeline right now).
320       if value_info[:value]
321         attrvalue = value_info[:value]
322       elsif value_info[:default]
323         attrvalue = value_info[:default]
324       else
325         attrvalue = ''
326       end
327       preconfigured_search_str = value_info[:search_for]
328     end
329
330     if not object.andand.attribute_editable?(attr)
331       return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
332     end
333
334     if dataclass
335       begin
336         dataclass = dataclass.constantize
337       rescue NameError
338       end
339     else
340       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
341     end
342
343     id = "#{object.uuid}-#{subattr.join('-')}"
344     dn = "[#{attr}]"
345     subattr.each do |a|
346       dn += "[#{a}]"
347     end
348     if value_info.is_a? Hash
349       dn += '[value]'
350     end
351
352     if (dataclass == Collection) or (dataclass == File)
353       selection_param = object.class.to_s.underscore + dn
354       display_value = attrvalue
355       if value_info.is_a?(Hash)
356         if (link = Link.find? value_info[:link_uuid])
357           display_value = link.name
358         elsif value_info[:link_name]
359           display_value = value_info[:link_name]
360         elsif value_info[:selection_name]
361           display_value = value_info[:selection_name]
362         end
363       end
364       if (attr == :components) and (subattr.size > 2)
365         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
366       else
367         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
368       end
369       modal_path = choose_collections_path \
370       ({ title: chooser_title,
371          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
372          action_name: 'OK',
373          action_href: pipeline_instance_path(id: object.uuid),
374          action_method: 'patch',
375          preconfigured_search_str: (preconfigured_search_str || ""),
376          action_data: {
377            merge: true,
378            use_preview_selection: dataclass == File ? true : nil,
379            selection_param: selection_param,
380            success: 'page-refresh'
381          }.to_json,
382         })
383
384       return content_tag('div', :class => 'input-group') do
385         html = text_field_tag(dn, display_value,
386                               :class =>
387                               "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
388         html + content_tag('span', :class => 'input-group-btn') do
389           link_to('Choose',
390                   modal_path,
391                   { :class => "btn btn-primary",
392                     :remote => true,
393                     :method => 'get',
394                   })
395         end
396       end
397     end
398
399     if attrvalue.is_a? String
400       datatype = 'text'
401     elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
402       # TODO: find a way to edit with x-editable
403       return attrvalue
404     end
405
406     # When datatype is a String or Fixnum, link_to the attrvalue
407     lt = link_to attrvalue, '#', {
408       "data-emptytext" => "none",
409       "data-placement" => "bottom",
410       "data-type" => datatype,
411       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
412       "data-title" => "Set value for #{subattr[-1].to_s}",
413       "data-name" => dn,
414       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
415       "data-value" => attrvalue,
416       # "clear" button interferes with form-control's up/down arrows
417       "data-clear" => false,
418       :class => "editable #{'required' if required} form-control",
419       :id => id
420     }.merge(htmloptions)
421
422     lt
423   end
424
425   def get_cwl_inputs(workflow)
426     if workflow[:inputs]
427       return workflow[:inputs]
428     else
429       workflow[:"$graph"].each do |tool|
430         if tool[:id] == "#main"
431           return tool[:inputs]
432         end
433       end
434     end
435   end
436
437   def cwl_shortname(id)
438     if id[0] == "#"
439       id = id[1..-1]
440     end
441     return id.split("/")[-1]
442   end
443
444   def cwl_input_info(input_schema)
445     required = !(input_schema[:type].include? "null")
446     if input_schema[:type].is_a? Array
447       primary_type = input_schema[:type].select { |n| n != "null" }[0]
448     elsif input_schema[:type].is_a? String
449       primary_type = input_schema[:type]
450     elsif input_schema[:type].is_a? Hash
451       primary_type = input_schema[:type]
452     end
453     param_id = cwl_shortname(input_schema[:id])
454     return required, primary_type, param_id
455   end
456
457   def cwl_input_value(object, input_schema, set_attr_path)
458     dn = ""
459     attrvalue = object
460     set_attr_path.each do |a|
461       dn += "[#{a}]"
462       attrvalue = attrvalue[a.to_sym]
463     end
464     return dn, attrvalue
465   end
466
467   def cwl_inputs_required(object, inputs_schema, set_attr_path)
468     r = 0
469     inputs_schema.each do |input|
470       required, primary_type, param_id = cwl_input_info(input)
471       dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
472       r += 1 if required and attrvalue.nil?
473     end
474     r
475   end
476
477   def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
478     required, primary_type, param_id = cwl_input_info(input_schema)
479
480     dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
481     attrvalue = if attrvalue.nil? then "" else attrvalue end
482
483     id = "#{object.uuid}-#{param_id}"
484
485     opt_empty_selection = if required then [] else [{value: "", text: ""}] end
486
487     if ["Directory", "File"].include? primary_type
488       chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
489       selection_param = object.class.to_s.underscore + dn
490       if attrvalue.is_a? Hash
491         display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
492         re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
493         if re
494           if re[4]
495             display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
496           else
497             display_value = Collection.find(re[1]).name
498           end
499         end
500       end
501       modal_path = choose_collections_path \
502       ({ title: chooser_title,
503          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
504          action_name: 'OK',
505          action_href: container_request_path(id: object.uuid),
506          action_method: 'patch',
507          preconfigured_search_str: "",
508          action_data: {
509            merge: true,
510            use_preview_selection: primary_type == 'File' ? true : nil,
511            selection_param: selection_param,
512            success: 'page-refresh'
513          }.to_json,
514         })
515
516       return content_tag('div', :class => 'input-group') do
517         html = text_field_tag(dn, display_value,
518                               :class =>
519                               "form-control #{'required' if required}")
520         html + content_tag('span', :class => 'input-group-btn') do
521           link_to('Choose',
522                   modal_path,
523                   { :class => "btn btn-primary",
524                     :remote => true,
525                     :method => 'get',
526                   })
527         end
528       end
529     elsif "boolean" == primary_type
530       return link_to attrvalue.to_s, '#', {
531                      "data-emptytext" => "none",
532                      "data-placement" => "bottom",
533                      "data-type" => "select",
534                      "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
535                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
536                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
537                      "data-name" => dn,
538                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
539                      "data-value" => attrvalue.to_s,
540                      # "clear" button interferes with form-control's up/down arrows
541                      "data-clear" => false,
542                      :class => "editable #{'required' if required} form-control",
543                      :id => id
544                    }.merge(htmloptions)
545     elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
546       return link_to attrvalue, '#', {
547                      "data-emptytext" => "none",
548                      "data-placement" => "bottom",
549                      "data-type" => "select",
550                      "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
551                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
552                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
553                      "data-name" => dn,
554                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
555                      "data-value" => attrvalue,
556                      # "clear" button interferes with form-control's up/down arrows
557                      "data-clear" => false,
558                      :class => "editable #{'required' if required} form-control",
559                      :id => id
560                    }.merge(htmloptions)
561     elsif primary_type.is_a? String
562       if ["int", "long"].include? primary_type
563         datatype = "number"
564       else
565         datatype = "text"
566       end
567
568       return link_to attrvalue, '#', {
569                      "data-emptytext" => "none",
570                      "data-placement" => "bottom",
571                      "data-type" => datatype,
572                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
573                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
574                      "data-name" => dn,
575                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
576                      "data-value" => attrvalue,
577                      # "clear" button interferes with form-control's up/down arrows
578                      "data-clear" => false,
579                      :class => "editable #{'required' if required} form-control",
580                      :id => id
581                      }.merge(htmloptions)
582     else
583       return "Unable to render editing control for parameter type #{primary_type}"
584     end
585   end
586
587   def render_arvados_object_list_start(list, button_text, button_href,
588                                        params={}, *rest, &block)
589     show_max = params.delete(:show_max) || 3
590     params[:class] ||= 'btn btn-xs btn-default'
591     list[0...show_max].each { |item| yield item }
592     unless list[show_max].nil?
593       link_to(h(button_text) +
594               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
595               button_href, params, *rest)
596     end
597   end
598
599   def render_controller_partial partial, opts
600     cname = opts.delete :controller_name
601     begin
602       render opts.merge(partial: "#{cname}/#{partial}")
603     rescue ActionView::MissingTemplate
604       render opts.merge(partial: "application/#{partial}")
605     end
606   end
607
608   RESOURCE_CLASS_ICONS = {
609     "Collection" => "fa-archive",
610     "ContainerRequest" => "fa-gears",
611     "Group" => "fa-users",
612     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
613     "Job" => "fa-gears",
614     "KeepDisk" => "fa-hdd-o",
615     "KeepService" => "fa-exchange",
616     "Link" => "fa-arrows-h",
617     "Node" => "fa-cloud",
618     "PipelineInstance" => "fa-gears",
619     "PipelineTemplate" => "fa-gears",
620     "Repository" => "fa-code-fork",
621     "Specimen" => "fa-flask",
622     "Trait" => "fa-clipboard",
623     "User" => "fa-user",
624     "VirtualMachine" => "fa-terminal",
625     "Workflow" => "fa-gears",
626   }
627   DEFAULT_ICON_CLASS = "fa-cube"
628
629   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
630     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
631   end
632
633   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
634     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
635   end
636
637   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
638     case class_name = object.class.to_s
639     when "Group"
640       object.group_class ? 'fa-folder' : 'fa-users'
641     else
642       RESOURCE_CLASS_ICONS.fetch(class_name, default)
643     end
644   end
645
646   def chooser_preview_url_for object, use_preview_selection=false
647     case object.class.to_s
648     when 'Collection'
649       polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
650     else
651       nil
652     end
653   end
654
655   def render_attribute_as_textile( object, attr, attrvalue, truncate )
656     if attrvalue && (is_textile? object, attr)
657       markup = render_markup attrvalue
658       markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
659       return markup
660     else
661       return attrvalue
662     end
663   end
664
665   def render_localized_date(date, opts="")
666     raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
667   end
668
669   def render_time duration, use_words, round_to_min=true
670     render_runtime duration, use_words, round_to_min
671   end
672
673   # Keep locators are expected to be of the form \"...<pdh/file_path>\"
674   JSON_KEEP_LOCATOR_REGEXP = /(.*)(([0-9a-f]{32}\+\d+)(.*)\"(.*))/
675   def keep_locator_in_json str
676     JSON_KEEP_LOCATOR_REGEXP.match str
677   end
678
679 private
680   def is_textile?( object, attr )
681     is_textile = object.textile_attributes.andand.include?(attr)
682   end
683 end