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