4523: updated render_editable_attribute to use textarea for descriptions.
[arvados.git] / apps / workbench / app / helpers / application_helper.rb
1 module ApplicationHelper
2   def current_user
3     controller.current_user
4   end
5
6   def self.match_uuid(uuid)
7     /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
8   end
9
10   def current_api_host
11     Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,''
12   end
13
14   def render_markup(markup)
15     raw RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile) if markup
16   end
17
18   def human_readable_bytes_html(n)
19     return h(n) unless n.is_a? Fixnum
20     return "0 bytes" if (n == 0)
21
22     orders = {
23       1 => "bytes",
24       1024 => "KiB",
25       (1024*1024) => "MiB",
26       (1024*1024*1024) => "GiB",
27       (1024*1024*1024*1024) => "TiB"
28     }
29
30     orders.each do |k, v|
31       sig = (n.to_f/k)
32       if sig >=1 and sig < 1024
33         if v == 'bytes'
34           return "%i #{v}" % sig
35         else
36           return "%0.1f #{v}" % sig
37         end
38       end
39     end
40
41     return h(n)
42     #raw = n.to_s
43     #cooked = ''
44     #while raw.length > 3
45     #  cooked = ',' + raw[-3..-1] + cooked
46     #  raw = raw[0..-4]
47     #end
48     #cooked = raw + cooked
49   end
50
51   def resource_class_for_uuid(attrvalue, opts={})
52     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
53   end
54
55   ##
56   # Returns HTML that links to the Arvados object specified in +attrvalue+
57   # Provides various output control and styling options.
58   #
59   # +attrvalue+ an Arvados model object or uuid
60   #
61   # +opts+ a set of flags to control output:
62   #
63   # [:link_text] the link text to use (may include HTML), overrides everything else
64   #
65   # [:friendly_name] whether to use the "friendly" name in the link text (by
66   # calling #friendly_link_name on the object), otherwise use the uuid
67   #
68   # [:with_class_name] prefix the link text with the class name of the model
69   #
70   # [:no_tags] disable tags in the link text (default is to show tags).
71   # Currently tags are only shown for Collections.
72   #
73   # [:thumbnail] if the object is a collection, show an image thumbnail if the
74   # collection consists of a single image file.
75   #
76   # [:no_link] don't create a link, just return the link text
77   #
78   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
79   #
80   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
81     if (resource_class = resource_class_for_uuid(attrvalue, opts))
82       if attrvalue.is_a? ArvadosBase
83         object = attrvalue
84         link_uuid = attrvalue.uuid
85       else
86         object = nil
87         link_uuid = attrvalue
88       end
89       link_name = opts[:link_text]
90       tags = ""
91       if !link_name
92         link_name = object.andand.default_name || resource_class.default_name
93
94         if opts[:friendly_name]
95           if attrvalue.respond_to? :friendly_link_name
96             link_name = attrvalue.friendly_link_name opts[:lookup]
97           else
98             begin
99               if resource_class.name == 'Collection'
100                 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
101               else
102                 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
103               end
104             rescue ArvadosApiClient::NotFoundException
105               # If that lookup failed, the link will too. So don't make one.
106               return attrvalue
107             end
108           end
109         end
110         if link_name.nil? or link_name.empty?
111           link_name = attrvalue
112         end
113         if opts[:with_class_name]
114           link_name = "#{resource_class.to_s}: #{link_name}"
115         end
116         if !opts[:no_tags] and resource_class == Collection
117           links_for_object(link_uuid).each do |tag|
118             if tag.link_class.in? ["tag", "identifier"]
119               tags += ' <span class="label label-info">'
120               tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
121               tags += '</span>'
122             end
123           end
124         end
125         if opts[:thumbnail] and resource_class == Collection
126           # add an image thumbnail if the collection consists of a single image file.
127           collections_for_object(link_uuid).each do |c|
128             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
129               link_name += " "
130               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
131             end
132           end
133         end
134       end
135       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
136       if opts[:no_link]
137         raw(link_name)
138       else
139         (link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
140       end
141     else
142       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
143       if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
144         "(none)"
145       else
146         attrvalue
147       end
148     end
149   end
150
151   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
152     attrvalue = object.send(attr) if attrvalue.nil?
153     if not object.attribute_editable?(attr)
154       if attrvalue && attrvalue.length > 0
155         return render_attribute_as_textile( object, attr, attrvalue, false )
156       else
157         return (attr == 'name' and object.andand.default_name) ||
158                 '(none)'
159       end
160     end
161
162     input_type = 'text'
163     case object.class.attribute_info[attr.to_sym].andand[:type]
164     when 'text'
165       input_type = 'textarea'
166     when 'datetime'
167       input_type = 'date'
168     else
169       input_type = 'text'
170     end
171
172     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
173     rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
174
175     ajax_options = {
176       "data-pk" => {
177         id: object.uuid,
178         key: object.class.to_s.underscore
179       }
180     }
181     if object.uuid
182       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
183     else
184       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
185       ajax_options['data-pk'][:defaults] = object.attributes
186     end
187     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
188     @unique_id ||= (Time.now.to_f*1000000).to_i
189     span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
190
191     if attr == 'description'
192       input_type = 'textarea'
193     end
194     span_tag = content_tag 'span', rendervalue, {
195       "data-emptytext" => '(none)',
196       "data-placement" => "bottom",
197       "data-type" => input_type,
198       "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
199       "data-name" => attr,
200       "data-object-uuid" => object.uuid,
201       "data-toggle" => "manual",
202       "data-value" => attrvalue,
203       "id" => span_id,
204       :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
205     }.merge(htmloptions).merge(ajax_options)
206     edit_button = raw('<a href="#" class="btn btn-xs btn-default btn-nodecorate" data-toggle="x-editable tooltip" data-toggle-selector="#' + span_id + '" data-placement="top" title="' + (htmloptions[:tiptitle] || 'edit') + '"><i class="fa fa-fw fa-pencil"></i></a>')
207     if htmloptions[:btnplacement] == :left
208       edit_button + ' ' + span_tag
209     else
210       span_tag + ' ' + edit_button
211     end
212   end
213
214   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
215     datatype = nil
216     required = true
217     attrvalue = value_info
218
219     if value_info.is_a? Hash
220       if value_info[:output_of]
221         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
222       end
223       if value_info[:dataclass]
224         dataclass = value_info[:dataclass]
225       end
226       if value_info[:optional] != nil
227         required = (value_info[:optional] != "true")
228       end
229       if value_info[:required] != nil
230         required = value_info[:required]
231       end
232
233       # Pick a suitable attrvalue to show as the current value (i.e.,
234       # the one that would be used if we ran the pipeline right now).
235       if value_info[:value]
236         attrvalue = value_info[:value]
237       elsif value_info[:default]
238         attrvalue = value_info[:default]
239       else
240         attrvalue = ''
241       end
242       preconfigured_search_str = value_info[:search_for]
243     end
244
245     if not object.andand.attribute_editable?(attr)
246       return link_to_if_arvados_object attrvalue
247     end
248
249     if dataclass
250       begin
251         dataclass = dataclass.constantize
252       rescue NameError
253       end
254     else
255       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
256     end
257
258     id = "#{object.uuid}-#{subattr.join('-')}"
259     dn = "[#{attr}]"
260     subattr.each do |a|
261       dn += "[#{a}]"
262     end
263     if value_info.is_a? Hash
264       dn += '[value]'
265     end
266
267     if (dataclass == Collection) or (dataclass == File)
268       selection_param = object.class.to_s.underscore + dn
269       display_value = attrvalue
270       if value_info.is_a?(Hash)
271         if (link = Link.find? value_info[:link_uuid])
272           display_value = link.name
273         elsif value_info[:link_name]
274           display_value = value_info[:link_name]
275         elsif value_info[:selection_name]
276           display_value = value_info[:selection_name]
277         end
278       end
279       if (attr == :components) and (subattr.size > 2)
280         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
281       else
282         chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
283       end
284       modal_path = choose_collections_path \
285       ({ title: chooser_title,
286          filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
287          action_name: 'OK',
288          action_href: pipeline_instance_path(id: object.uuid),
289          action_method: 'patch',
290          preconfigured_search_str: (preconfigured_search_str || ""),
291          action_data: {
292            merge: true,
293            use_preview_selection: dataclass == File ? true : nil,
294            selection_param: selection_param,
295            success: 'page-refresh'
296          }.to_json,
297         })
298       return content_tag('div', :class => 'input-group') do
299         html = text_field_tag(dn, display_value,
300                               :class =>
301                               "form-control #{'required' if required}")
302         html + content_tag('span', :class => 'input-group-btn') do
303           link_to('Choose',
304                   modal_path,
305                   { :class => "btn btn-primary",
306                     :remote => true,
307                     :method => 'get',
308                   })
309         end
310       end
311     end
312
313     if dataclass == 'number' or attrvalue.is_a? Fixnum or attrvalue.is_a? Float
314       datatype = 'number'
315     elsif attrvalue.is_a? String
316       datatype = 'text'
317     elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
318       # TODO: find a way to edit with x-editable
319       return attrvalue
320     end
321
322     # When datatype is a String or Fixnum, link_to the attrvalue
323     lt = link_to attrvalue, '#', {
324       "data-emptytext" => "none",
325       "data-placement" => "bottom",
326       "data-type" => datatype,
327       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
328       "data-title" => "Set value for #{subattr[-1].to_s}",
329       "data-name" => dn,
330       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
331       "data-value" => attrvalue,
332       # "clear" button interferes with form-control's up/down arrows
333       "data-clear" => false,
334       :class => "editable #{'required' if required} form-control",
335       :id => id
336     }.merge(htmloptions)
337
338     lt
339   end
340
341   def render_arvados_object_list_start(list, button_text, button_href,
342                                        params={}, *rest, &block)
343     show_max = params.delete(:show_max) || 3
344     params[:class] ||= 'btn btn-xs btn-default'
345     list[0...show_max].each { |item| yield item }
346     unless list[show_max].nil?
347       link_to(h(button_text) +
348               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
349               button_href, params, *rest)
350     end
351   end
352
353   def render_controller_partial partial, opts
354     cname = opts.delete :controller_name
355     begin
356       render opts.merge(partial: "#{cname}/#{partial}")
357     rescue ActionView::MissingTemplate
358       render opts.merge(partial: "application/#{partial}")
359     end
360   end
361
362   RESOURCE_CLASS_ICONS = {
363     "Collection" => "fa-archive",
364     "Group" => "fa-users",
365     "Human" => "fa-male",  # FIXME: Use a more inclusive icon.
366     "Job" => "fa-gears",
367     "KeepDisk" => "fa-hdd-o",
368     "KeepService" => "fa-exchange",
369     "Link" => "fa-arrows-h",
370     "Node" => "fa-cloud",
371     "PipelineInstance" => "fa-gears",
372     "PipelineTemplate" => "fa-gears",
373     "Repository" => "fa-code-fork",
374     "Specimen" => "fa-flask",
375     "Trait" => "fa-clipboard",
376     "User" => "fa-user",
377     "VirtualMachine" => "fa-terminal",
378   }
379   DEFAULT_ICON_CLASS = "fa-cube"
380
381   def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
382     RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
383   end
384
385   def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
386     fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
387   end
388
389   def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
390     case class_name = object.class.to_s
391     when "Group"
392       object.group_class ? 'fa-folder' : 'fa-users'
393     else
394       RESOURCE_CLASS_ICONS.fetch(class_name, default)
395     end
396   end
397
398   def chooser_preview_url_for object, use_preview_selection=false
399     case object.class.to_s
400     when 'Collection'
401       polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
402     else
403       nil
404     end
405   end
406
407   def render_attribute_as_textile( object, attr, attrvalue, truncate )
408     if attrvalue && (is_textile? object, attr)
409       markup = render_markup attrvalue
410       markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
411       return markup
412     else
413       return attrvalue
414     end
415   end
416
417   def render_localized_date(date, opts="")
418     raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
419   end
420
421 private
422   def is_textile?( object, attr )
423     is_textile = object.textile_attributes.andand.include?(attr)
424   end
425 end