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