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