2871: add helper method to get "n" number of objects of specific dataclass
[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_content_from_database(markup)
15     raw RedCloth.new(markup).to_html
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       link_uuid = attrvalue.is_a?(ArvadosBase) ? attrvalue.uuid : attrvalue
83       link_name = opts[:link_text]
84       if !link_name
85         link_name = link_uuid
86
87         if opts[:friendly_name]
88           if attrvalue.respond_to? :friendly_link_name
89             link_name = attrvalue.friendly_link_name
90           else
91             begin
92               link_name = resource_class.find(link_uuid).friendly_link_name
93             rescue RuntimeError
94               # If that lookup failed, the link will too. So don't make one.
95               return attrvalue
96             end
97           end
98         end
99         if opts[:with_class_name]
100           link_name = "#{resource_class.to_s}: #{link_name}"
101         end
102         if !opts[:no_tags] and resource_class == Collection
103           Link.where(head_uuid: link_uuid, link_class: ["tag", "identifier"]).each do |tag|
104             link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
105           end
106         end
107         if opts[:thumbnail] and resource_class == Collection
108           # add an image thumbnail if the collection consists of a single image file.
109           Collection.where(uuid: link_uuid).each do |c|
110             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
111               link_name += " "
112               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
113             end
114           end
115         end
116       end
117       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
118       if opts[:no_link]
119         raw(link_name)
120       else
121         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: link_uuid }, style_opts
122       end
123     else
124       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
125       attrvalue
126     end
127   end
128
129   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
130     attrvalue = object.send(attr) if attrvalue.nil?
131     if !object.attribute_editable?(attr, :ever) or
132         (!object.editable? and
133          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
134       return attrvalue 
135     end
136
137     input_type = 'text'
138     case object.class.attribute_info[attr.to_sym].andand[:type]
139     when 'text'
140       input_type = 'textarea'
141     when 'datetime'
142       input_type = 'date'
143     else
144       input_type = 'text'
145     end
146
147     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
148
149     ajax_options = {
150       "data-pk" => {
151         id: object.uuid,
152         key: object.class.to_s.underscore
153       }
154     }
155     if object.uuid
156       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
157     else
158       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
159       ajax_options['data-pk'][:defaults] = object.attributes
160     end
161     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
162
163     content_tag 'span', attrvalue.to_s, {
164       "data-emptytext" => "none",
165       "data-placement" => "bottom",
166       "data-type" => input_type,
167       "data-title" => "Update #{attr.gsub '_', ' '}",
168       "data-name" => attr,
169       "data-object-uuid" => object.uuid,
170       :class => "editable"
171     }.merge(htmloptions).merge(ajax_options)
172   end
173
174   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
175     datatype = nil
176     required = true
177     attrvalue = value_info
178
179     if value_info.is_a? Hash
180       if value_info[:output_of]
181         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
182       end
183       if value_info[:dataclass]
184         dataclass = value_info[:dataclass]
185       end
186       if value_info[:optional] != nil
187         required = (value_info[:optional] != "true")
188       end
189       if value_info[:required] != nil
190         required = value_info[:required]
191       end
192
193       # Pick a suitable attrvalue to show as the current value (i.e.,
194       # the one that would be used if we ran the pipeline right now).
195       if value_info[:value]
196         attrvalue = value_info[:value]
197       elsif value_info[:default]
198         attrvalue = value_info[:default]
199       else
200         attrvalue = ''
201       end
202     end
203
204     if !object or
205         !object.attribute_editable?(attr, :ever) or
206         (!object.editable? and
207          !object.owner_uuid.in?(my_folders.collect(&:uuid)))
208       return link_to_if_arvados_object attrvalue
209     end
210
211     if dataclass
212       begin
213         dataclass = dataclass.constantize
214       rescue NameError
215       end
216     else
217       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
218     end
219
220     if dataclass.andand.is_a?(Class)
221       datatype = 'select'
222     elsif dataclass == 'number'
223       datatype = 'number'
224     elsif attrvalue.is_a? Array
225       # TODO: find a way to edit arrays with x-editable
226       return attrvalue
227     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
228       datatype = 'number'
229     elsif attrvalue.is_a? String
230       datatype = 'text'
231     end
232
233     id = "#{object.uuid}-#{subattr.join('-')}"
234     dn = "[#{attr}]"
235     subattr.each do |a|
236       dn += "[#{a}]"
237     end
238     if value_info.is_a? Hash
239       dn += '[value]'
240     end
241
242     preload_uuids = [attrvalue]
243     items = []
244     selectables = []
245
246     attrtext = attrvalue
247     if dataclass and dataclass.is_a? Class
248       objects = get_objects_of_type dataclass, 10
249       objects.each do |item|
250         items << item
251         preload_uuids << item.uuid
252       end
253       if attrvalue and !attrvalue.empty?
254         preload_uuids << attrvalue
255       end
256       preload_links_for_objects preload_uuids
257
258       if attrvalue and !attrvalue.empty?
259         links_for_object(attrvalue).each do |link|
260           if link.link_class.in? ["tag", "identifier"]
261             attrtext += " [#{tag.name}]"
262           end
263         end
264         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
265       end
266       itemuuids = []
267       items.each do |item|
268         itemuuids << item.uuid
269         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
270       end
271       
272       itemuuids.each do |itemuuid|
273         links_for_object(itemuuid).each do |link|
274           if link.link_class.in? ["tag", "identifier"]
275             selectables.each do |selectable|
276               if selectable['uuid'] == tag.head_uuid
277                 selectable['name'] += ' [' + tag.name + ']'
278               end
279             end
280           end
281         end
282       end
283     end
284
285     lt = link_to attrtext, '#', {
286       "data-emptytext" => "none",
287       "data-placement" => "bottom",
288       "data-type" => datatype,
289       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
290       "data-title" => "Set value for #{subattr[-1].to_s}",
291       "data-name" => dn,
292       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
293       "data-showbuttons" => "false",
294       "data-value" => attrvalue,
295       :class => "editable #{'required' if required} form-control",
296       :id => id
297     }.merge(htmloptions)
298
299     lt += raw("\n<script>")
300
301     if selectables.any?
302       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
303     end
304
305     lt += raw("$('[data-name=\"#{dn}\"]').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
306
307     lt += raw("</script>")
308
309     lt
310   end
311
312   def render_arvados_object_list_start(list, button_text, button_href,
313                                        params={}, *rest, &block)
314     show_max = params.delete(:show_max) || 3
315     params[:class] ||= 'btn btn-xs btn-default'
316     list[0...show_max].each { |item| yield item }
317     unless list[show_max].nil?
318       link_to(h(button_text) +
319               raw(' &nbsp; <i class="fa fa-fw fa-arrow-circle-right"></i>'),
320               button_href, params, *rest)
321     end
322   end
323 end