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