2760: Replace dashboard tables with news feed. More ability to link via names rather...
[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_time_html t
19     begin
20       t = Time.parse(t) unless t.is_a? Time
21     rescue
22       return ''
23     end
24     now = Time.now
25     delta = (now - t).abs
26     if delta < 12.hours
27       t.strftime('%I:%M%P').downcase.sub(/^0/,'')
28     elsif (delta < 2.months and now>t) or t.strftime('%Y')==now.strftime('%Y')
29       # recent, or this year (hopefully unambiguous in context)
30       t.strftime('%b %d').sub(/ 0/,' ')
31     else
32       t.strftime('%b %d, %Y').sub(/ 0/,' ')
33     end
34   end
35
36   def human_readable_bytes_html(n)
37     return h(n) unless n.is_a? Fixnum
38
39     orders = {
40       1 => "bytes",
41       1024 => "KiB",
42       (1024*1024) => "MiB",
43       (1024*1024*1024) => "GiB",
44       (1024*1024*1024*1024) => "TiB"
45     }
46
47     orders.each do |k, v|
48       sig = (n.to_f/k)
49       if sig >=1 and sig < 1024
50         if v == 'bytes'
51           return "%i #{v}" % sig
52         else
53           return "%0.1f #{v}" % sig
54         end
55       end
56     end
57
58     return h(n)
59     #raw = n.to_s
60     #cooked = ''
61     #while raw.length > 3
62     #  cooked = ',' + raw[-3..-1] + cooked
63     #  raw = raw[0..-4]
64     #end
65     #cooked = raw + cooked
66   end
67
68   def resource_class_for_uuid(attrvalue, opts={})
69     ArvadosBase::resource_class_for_uuid(attrvalue, opts)
70   end
71
72   ##
73   # Returns HTML that links to the Arvados object specified in +attrvalue+
74   # Provides various output control and styling options.
75   #
76   # +attrvalue+ an Arvados model object or uuid
77   #
78   # +opts+ a set of flags to control output:
79   #
80   # [:link_text] the link text to use (may include HTML), overrides everything else
81   #
82   # [:friendly_name] whether to use the "friendly" name in the link text (by
83   # calling #friendly_link_name on the object), otherwise use the uuid
84   #
85   # [:with_class_name] prefix the link text with the class name of the model
86   #
87   # [:no_tags] disable tags in the link text (default is to show tags).
88   # Currently tags are only shown for Collections.
89   #
90   # [:thumbnail] if the object is a collection, show an image thumbnail if the
91   # collection consists of a single image file.
92   #
93   # [:no_link] don't create a link, just return the link text
94   #
95   # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
96   #
97   def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
98     if (resource_class = resource_class_for_uuid(attrvalue, opts))
99       link_uuid = attrvalue.is_a?(ArvadosBase) ? attrvalue.uuid : attrvalue
100       link_name = opts[:link_text]
101       if !link_name
102         link_name = link_uuid
103
104         if opts[:name_link]
105           link_name = opts[:name_link].name
106         elsif opts[:friendly_name]
107           if attrvalue.respond_to? :friendly_link_name
108             link_name = attrvalue.friendly_link_name
109           else
110             begin
111               link_name = resource_class.find(link_uuid).friendly_link_name
112             rescue RuntimeError
113               # If that lookup failed, the link will too. So don't make one.
114               return attrvalue
115             end
116           end
117         end
118         if opts[:with_class_name]
119           link_name = "#{resource_class.to_s}: #{link_name}"
120         end
121         if !opts[:name_link] and
122             !opts[:no_tags] and
123             resource_class == Collection
124           Link.where(head_uuid: link_uuid, link_class: ["tag", "identifier"]).each do |tag|
125             link_name += ' <span class="label label-info">' + html_escape(tag.name) + '</span>'
126           end
127         end
128         if opts[:thumbnail] and resource_class == Collection
129           # add an image thumbnail if the collection consists of a single image file.
130           Collection.where(uuid: link_uuid).each do |c|
131             if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
132               link_name += " "
133               link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
134             end
135           end
136         end
137       end
138       style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
139       if opts[:no_link]
140         raw(link_name)
141       else
142         link_to raw(link_name), { controller: resource_class.to_s.tableize, action: 'show', id: link_uuid }, style_opts
143       end
144     else
145       # just return attrvalue if it is not recognizable as an Arvados object or uuid.
146       attrvalue
147     end
148   end
149
150   def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={})
151     attrvalue = object.send(attr) if attrvalue.nil?
152     return attrvalue if !object.attribute_editable? attr
153
154     input_type = 'text'
155     case object.class.attribute_info[attr.to_sym].andand[:type]
156     when 'text'
157       input_type = 'textarea'
158     when 'datetime'
159       input_type = 'date'
160     else
161       input_type = 'text'
162     end
163
164     attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
165
166     ajax_options = {
167       "data-pk" => {
168         id: object.uuid,
169         key: object.class.to_s.underscore
170       }
171     }
172     if object.uuid
173       ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
174     else
175       ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
176       ajax_options['data-pk'][:defaults] = object.attributes
177     end
178     ajax_options['data-pk'] = ajax_options['data-pk'].to_json
179
180     content_tag 'span', attrvalue.to_s, {
181       "data-emptytext" => "none",
182       "data-placement" => "bottom",
183       "data-type" => input_type,
184       "data-title" => "Update #{attr.gsub '_', ' '}",
185       "data-name" => attr,
186       "data-object-uuid" => object.uuid,
187       :class => "editable"
188     }.merge(htmloptions).merge(ajax_options)
189   end
190
191   def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
192     datatype = nil
193     required = true
194     attrvalue = value_info
195
196     if value_info.is_a? Hash
197       if value_info[:output_of]
198         return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
199       end
200       if value_info[:dataclass]
201         dataclass = value_info[:dataclass]
202       end
203       if value_info[:optional] != nil
204         required = (value_info[:optional] != "true")
205       end
206       if value_info[:required] != nil
207         required = value_info[:required]
208       end
209
210       # Pick a suitable attrvalue to show as the current value (i.e.,
211       # the one that would be used if we ran the pipeline right now).
212       if value_info[:value]
213         attrvalue = value_info[:value]
214       elsif value_info[:default]
215         attrvalue = value_info[:default]
216       else
217         attrvalue = ''
218       end
219     end
220
221     unless object.andand.attribute_editable? attr
222       return link_to_if_arvados_object attrvalue
223     end
224
225     if dataclass
226       begin
227         dataclass = dataclass.constantize
228       rescue NameError
229       end
230     else
231       dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
232     end
233
234     if dataclass.andand.is_a?(Class)
235       datatype = 'select'
236     elsif dataclass == 'number'
237       datatype = 'number'
238     elsif attrvalue.is_a? Array
239       # TODO: find a way to edit arrays with x-editable
240       return attrvalue
241     elsif attrvalue.is_a? Fixnum or attrvalue.is_a? Float
242       datatype = 'number'
243     elsif attrvalue.is_a? String
244       datatype = 'text'
245     end
246
247     id = "#{object.uuid}-#{subattr.join('-')}"
248     dn = "[#{attr}]"
249     subattr.each do |a|
250       dn += "[#{a}]"
251     end
252     if value_info.is_a? Hash
253       dn += '[value]'
254     end
255
256     selectables = []
257     attrtext = attrvalue
258     if dataclass and dataclass.is_a? Class
259       if attrvalue and !attrvalue.empty?
260         Link.where(head_uuid: attrvalue, link_class: ["tag", "identifier"]).each do |tag|
261           attrtext += " [#{tag.name}]"
262         end
263         selectables.append({name: attrtext, uuid: attrvalue, type: dataclass.to_s})
264       end
265       #dataclass.where(uuid: attrvalue).each do |item|
266       #  selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
267       #end
268       itemuuids = []
269       dataclass.limit(10).each do |item|
270         itemuuids << item.uuid
271         selectables.append({name: item.uuid, uuid: item.uuid, type: dataclass.to_s})
272       end
273       Link.where(head_uuid: itemuuids, link_class: ["tag", "identifier"]).each do |tag|
274         selectables.each do |selectable|
275           if selectable['uuid'] == tag.head_uuid
276             selectable['name'] += ' [' + tag.name + ']'
277           end
278         end
279       end
280     end
281
282     lt = link_to attrtext, '#', {
283       "data-emptytext" => "none",
284       "data-placement" => "bottom",
285       "data-type" => datatype,
286       "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
287       "data-title" => "Set value for #{subattr[-1].to_s}",
288       "data-name" => dn,
289       "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
290       "data-showbuttons" => "false",
291       "data-value" => attrvalue,
292       :class => "editable #{'required' if required}",
293       :id => id
294     }.merge(htmloptions)
295
296     lt += raw("\n<script>")
297
298     if selectables.any?
299       lt += raw("add_form_selection_sources(#{selectables.to_json});\n")
300     end
301
302     lt += raw("$('##{id}').editable({source: function() { return select_form_sources('#{dataclass}'); } });\n")
303
304     lt += raw("</script>")
305
306     lt
307   end
308 end