13493: Merge branch 'master' into 13493-federation-proxy
[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_main(workflow)
430     if workflow[:"$graph"].nil?
431       return workflow
432     else
433       workflow[:"$graph"].each do |tool|
434         if tool[:id] == "#main"
435           return tool
436         end
437       end
438     end
439   end
440
441   def get_cwl_inputs(workflow)
442     get_cwl_main(workflow)[:inputs]
443   end
444
445
446   def cwl_shortname(id)
447     if id[0] == "#"
448       id = id[1..-1]
449     end
450     return id.split("/")[-1]
451   end
452
453   def cwl_input_info(input_schema)
454     required = !(input_schema[:type].include? "null")
455     if input_schema[:type].is_a? Array
456       primary_type = input_schema[:type].select { |n| n != "null" }[0]
457     elsif input_schema[:type].is_a? String
458       primary_type = input_schema[:type]
459     elsif input_schema[:type].is_a? Hash
460       primary_type = input_schema[:type]
461     end
462     param_id = cwl_shortname(input_schema[:id])
463     return required, primary_type, param_id
464   end
465
466   def cwl_input_value(object, input_schema, set_attr_path)
467     dn = ""
468     attrvalue = object
469     set_attr_path.each do |a|
470       dn += "[#{a}]"
471       attrvalue = attrvalue[a.to_sym]
472     end
473     return dn, attrvalue
474   end
475
476   def cwl_inputs_required(object, inputs_schema, set_attr_path)
477     r = 0
478     inputs_schema.each do |input|
479       required, primary_type, param_id = cwl_input_info(input)
480       dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
481       r += 1 if required and attrvalue.nil?
482     end
483     r
484   end
485
486   def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
487     required, primary_type, param_id = cwl_input_info(input_schema)
488
489     dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
490     attrvalue = if attrvalue.nil? then "" else attrvalue end
491
492     id = "#{object.uuid}-#{param_id}"
493
494     opt_empty_selection = if required then [] else [{value: "", text: ""}] end
495
496     if ["Directory", "File"].include? primary_type
497       chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
498       selection_param = object.class.to_s.underscore + dn
499       if attrvalue.is_a? Hash
500         display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
501         re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
502         if re
503           if re[4]
504             display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
505           else
506             display_value = Collection.find(re[1]).name
507           end
508         end
509       end
510       modal_path = choose_collections_path \
511       ({ title: chooser_title,
512          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
513          action_name: 'OK',
514          action_href: container_request_path(id: object.uuid),
515          action_method: 'patch',
516          preconfigured_search_str: "",
517          action_data: {
518            merge: true,
519            use_preview_selection: primary_type == 'File' ? true : nil,
520            selection_param: selection_param,
521            success: 'page-refresh'
522          }.to_json,
523         })
524
525       return content_tag('div', :class => 'input-group') do
526         html = text_field_tag(dn, display_value,
527                               :class =>
528                               "form-control #{'required' if required}")
529         html + content_tag('span', :class => 'input-group-btn') do
530           link_to('Choose',
531                   modal_path,
532                   { :class => "btn btn-primary",
533                     :remote => true,
534                     :method => 'get',
535                   })
536         end
537       end
538     elsif "boolean" == primary_type
539       return link_to attrvalue.to_s, '#', {
540                      "data-emptytext" => "none",
541                      "data-placement" => "bottom",
542                      "data-type" => "select",
543                      "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
544                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
545                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
546                      "data-name" => dn,
547                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
548                      "data-value" => attrvalue.to_s,
549                      # "clear" button interferes with form-control's up/down arrows
550                      "data-clear" => false,
551                      :class => "editable #{'required' if required} form-control",
552                      :id => id
553                    }.merge(htmloptions)
554     elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
555       return link_to attrvalue, '#', {
556                      "data-emptytext" => "none",
557                      "data-placement" => "bottom",
558                      "data-type" => "select",
559                      "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
560                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
561                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
562                      "data-name" => dn,
563                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
564                      "data-value" => attrvalue,
565                      # "clear" button interferes with form-control's up/down arrows
566                      "data-clear" => false,
567                      :class => "editable #{'required' if required} form-control",
568                      :id => id
569                    }.merge(htmloptions)
570     elsif primary_type.is_a? String
571       if ["int", "long"].include? primary_type
572         datatype = "number"
573       else
574         datatype = "text"
575       end
576
577       return link_to attrvalue, '#', {
578                      "data-emptytext" => "none",
579                      "data-placement" => "bottom",
580                      "data-type" => datatype,
581                      "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
582                      "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
583                      "data-name" => dn,
584                      "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
585                      "data-value" => attrvalue,
586                      # "clear" button interferes with form-control's up/down arrows
587                      "data-clear" => false,
588                      :class => "editable #{'required' if required} form-control",
589                      :id => id
590                      }.merge(htmloptions)
591     else
592       return "Unable to render editing control for parameter type #{primary_type}"
593     end
594   end
595
596   def render_arvados_object_list_start(list, button_text, button_href,
597                                        params={}, *rest, &block)
598     show_max = params.delete(:show_max) || 3
599     params[:class] ||= 'btn btn-xs btn-default'
600     list[0...show_max].each { |item| yield item }
601     unless list[show_max].nil?
602       link_to(h(button_text) +
603               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
604               button_href, params, *rest)
605     end
606   end
607
608   def render_controller_partial partial, opts
609     cname = opts.delete :controller_name
610     begin
611       render opts.merge(partial: "#{cname}/#{partial}")
612     rescue ActionView::MissingTemplate
613       render opts.merge(partial: "application/#{partial}")
614     end
615   end
616
617   RESOURCE_CLASS_ICONS = {
618     "Collection" => "fa-archive",
619     "ContainerRequest" => "fa-gears",
620     "Group" => "fa-users",
621     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
622     "Job" => "fa-gears",
623     "KeepDisk" => "fa-hdd-o",
624     "KeepService" => "fa-exchange",
625     "Link" => "fa-arrows-h",
626     "Node" => "fa-cloud",
627     "PipelineInstance" => "fa-gears",
628     "PipelineTemplate" => "fa-gears",
629     "Repository" => "fa-code-fork",
630     "Specimen" => "fa-flask",
631     "Trait" => "fa-clipboard",
632     "User" => "fa-user",
633     "VirtualMachine" => "fa-terminal",
634     "Workflow" => "fa-gears",
635   }
636   DEFAULT_ICON_CLASS = "fa-cube"
637
638   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
639     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
640   end
641
642   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
643     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
644   end
645
646   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
647     case class_name = object.class.to_s
648     when "Group"
649       object.group_class ? 'fa-folder' : 'fa-users'
650     else
651       RESOURCE_CLASS_ICONS.fetch(class_name, default)
652     end
653   end
654
655   def chooser_preview_url_for object, use_preview_selection=false
656     case object.class.to_s
657     when 'Collection'
658       polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
659     else
660       nil
661     end
662   end
663
664   def render_attribute_as_textile( object, attr, attrvalue, truncate )
665     if attrvalue && (is_textile? object, attr)
666       markup = render_markup attrvalue
667       markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
668       return markup
669     else
670       return attrvalue
671     end
672   end
673
674   def render_localized_date(date, opts="")
675     raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
676   end
677
678   def render_time duration, use_words, round_to_min=true
679     render_runtime duration, use_words, round_to_min
680   end
681
682   # Keep locators are expected to be of the form \"...<pdh/file_path>\"
683   JSON_KEEP_LOCATOR_REGEXP = /(.*)(([0-9a-f]{32}\+\d+)(.*)\"(.*))/
684   def keep_locator_in_json str
685     JSON_KEEP_LOCATOR_REGEXP.match str
686   end
687
688 private
689   def is_textile?( object, attr )
690     is_textile = object.textile_attributes.andand.include?(attr)
691   end
692 end