1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
5 module ApplicationHelper
7 controller.current_user
10 def self.match_uuid(uuid)
11 /^([0-9a-z]{5})-([0-9a-z]{5})-([0-9a-z]{15})$/.match(uuid.to_s)
15 Rails.configuration.arvados_v1_base.gsub /https?:\/\/|\/arvados\/v1/,''
18 def render_markup(markup)
19 sanitize(raw(RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile))) if markup
22 def human_readable_bytes_html(n)
23 return h(n) unless n.is_a? Fixnum
24 return "0 bytes" if (n == 0)
30 (1024*1024*1024) => "GiB",
31 (1024*1024*1024*1024) => "TiB"
36 if sig >=1 and sig < 1024
38 return "%i #{v}" % sig
40 return "%0.1f #{v}" % sig
48 def resource_class_for_uuid(attrvalue, opts={})
49 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
52 # When using {remote:true}, or using {method:...} to use an HTTP
53 # method other than GET, move the target URI from href to
54 # data-remote-href. Otherwise, browsers offer features like "open in
55 # new window" and "copy link address" which bypass Rails' click
56 # handler and therefore end up at incorrect/nonexistent routes (by
57 # ignoring data-method) and expect to receive pages rather than
58 # javascript responses.
60 # See assets/javascripts/link_to_remote.js for supporting code.
61 def link_to *args, &block
62 if (args.last and args.last.is_a? Hash and
63 (args.last[:remote] or
64 (args.last[:method] and
65 args.last[:method].to_s.upcase != 'GET')))
67 # Capybara/phantomjs can't click_link without an href, even if
68 # the click handler means it never gets used.
69 raw super.gsub(' href="', ' href="#" data-remote-href="')
71 # Regular browsers work as desired: users can click A elements
72 # without hrefs, and click handlers fire; but there's no "copy
73 # link address" option in the right-click menu.
74 raw super.gsub(' href="', ' data-remote-href="')
82 # Returns HTML that links to the Arvados object specified in +attrvalue+
83 # Provides various output control and styling options.
85 # +attrvalue+ an Arvados model object or uuid
87 # +opts+ a set of flags to control output:
89 # [:link_text] the link text to use (may include HTML), overrides everything else
91 # [:friendly_name] whether to use the "friendly" name in the link text (by
92 # calling #friendly_link_name on the object), otherwise use the uuid
94 # [:with_class_name] prefix the link text with the class name of the model
96 # [:no_tags] disable tags in the link text (default is to show tags).
97 # Currently tags are only shown for Collections.
99 # [:thumbnail] if the object is a collection, show an image thumbnail if the
100 # collection consists of a single image file.
102 # [:no_link] don't create a link, just return the link text
104 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
106 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
107 if (resource_class = resource_class_for_uuid(attrvalue, opts))
108 if attrvalue.is_a? ArvadosBase
110 link_uuid = attrvalue.uuid
113 link_uuid = attrvalue
115 link_name = opts[:link_text]
118 link_name = object.andand.default_name || resource_class.default_name
120 if opts[:friendly_name]
121 if attrvalue.respond_to? :friendly_link_name
122 link_name = attrvalue.friendly_link_name opts[:lookup]
125 if resource_class.name == 'Collection'
126 if CollectionsHelper.match(link_uuid)
127 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
129 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
132 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
134 rescue ArvadosApiClient::NotFoundException
135 # If that lookup failed, the link will too. So don't make one.
140 if link_name.nil? or link_name.empty?
141 link_name = attrvalue
143 if opts[:with_class_name]
144 link_name = "#{resource_class.to_s}: #{link_name}"
146 if !opts[:no_tags] and resource_class == Collection
147 links_for_object(link_uuid).each do |tag|
148 if tag.link_class.in? ["tag", "identifier"]
149 tags += ' <span class="label label-info">'
150 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
155 if opts[:thumbnail] and resource_class == Collection
156 # add an image thumbnail if the collection consists of a single image file.
157 collections_for_object(link_uuid).each do |c|
158 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
160 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
165 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
166 if opts[:no_link] or (resource_class == User && !current_user)
169 controller_class = resource_class.to_s.tableize
170 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
171 controller_class = 'projects'
173 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
176 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
177 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
185 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
186 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
188 return link_to_if_arvados_object attrvalue, opts
191 readable = object_readable attrvalue, resource_class
193 link_to_if_arvados_object attrvalue, opts
194 elsif opts[:required] and current_user # no need to show this for anonymous user
195 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>')
197 link_text_if_not_readable
201 # This method takes advantage of preloaded collections and objects.
202 # Hence you can improve performance by first preloading objects
203 # related to the page context before using this method.
204 def object_readable attrvalue, resource_class=nil
205 # if it is a collection filename, check readable for the locator
206 attrvalue = attrvalue.split('/')[0] if attrvalue
208 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
209 return if resource_class.nil?
212 if resource_class.to_s == 'Collection'
213 if CollectionsHelper.match(attrvalue)
214 found = collection_for_pdh(attrvalue)
215 return_value = found.first if found.any?
217 found = collections_for_object(attrvalue)
218 return_value = found.first if found.any?
221 return_value = object_for_dataclass(resource_class, attrvalue)
226 # Render an editable attribute with the attrvalue of the attr.
227 # The htmloptions are added to the editable element's list of attributes.
228 # The nonhtml_options are only used to customize the display of the element.
229 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
230 attrvalue = object.send(attr) if attrvalue.nil?
231 if not object.attribute_editable?(attr)
232 if attrvalue && attrvalue.length > 0
233 return render_attribute_as_textile( object, attr, attrvalue, false )
235 return (attr == 'name' and object.andand.default_name) ||
241 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
242 if attrtype == 'text' or attr == 'description'
243 input_type = 'textarea'
244 elsif attrtype == 'datetime'
250 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
251 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
256 key: object.class.to_s.underscore
260 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
262 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
263 ajax_options['data-pk'][:defaults] = object.attributes
265 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
266 @unique_id ||= (Time.now.to_f*1000000).to_i
267 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
269 span_tag = content_tag 'span', rendervalue, {
270 "data-emptytext" => '(none)',
271 "data-placement" => "bottom",
272 "data-type" => input_type,
273 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
274 "data-name" => htmloptions['selection_name'] || attr,
275 "data-object-uuid" => object.uuid,
276 "data-toggle" => "manual",
277 "data-value" => htmloptions['data-value'] || attrvalue,
279 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
280 }.merge(htmloptions).merge(ajax_options)
282 edit_tiptitle = 'edit'
283 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')
285 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>')
287 if nonhtml_options[:btnplacement] == :left
288 edit_button + ' ' + span_tag
289 elsif nonhtml_options[:btnplacement] == :top
290 edit_button + raw('<br/>') + span_tag
292 span_tag + ' ' + edit_button
296 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
299 attrvalue = value_info
301 if value_info.is_a? Hash
302 if value_info[:output_of]
303 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
305 if value_info[:dataclass]
306 dataclass = value_info[:dataclass]
308 if value_info[:optional] != nil
309 required = (value_info[:optional] != "true")
311 if value_info[:required] != nil
312 required = value_info[:required]
315 # Pick a suitable attrvalue to show as the current value (i.e.,
316 # the one that would be used if we ran the pipeline right now).
317 if value_info[:value]
318 attrvalue = value_info[:value]
319 elsif value_info[:default]
320 attrvalue = value_info[:default]
324 preconfigured_search_str = value_info[:search_for]
327 if not object.andand.attribute_editable?(attr)
328 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
333 dataclass = dataclass.constantize
337 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
340 id = "#{object.uuid}-#{subattr.join('-')}"
345 if value_info.is_a? Hash
349 if (dataclass == Collection) or (dataclass == File)
350 selection_param = object.class.to_s.underscore + dn
351 display_value = attrvalue
352 if value_info.is_a?(Hash)
353 if (link = Link.find? value_info[:link_uuid])
354 display_value = link.name
355 elsif value_info[:link_name]
356 display_value = value_info[:link_name]
357 elsif value_info[:selection_name]
358 display_value = value_info[:selection_name]
361 if (attr == :components) and (subattr.size > 2)
362 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
364 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
366 modal_path = choose_collections_path \
367 ({ title: chooser_title,
368 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
370 action_href: pipeline_instance_path(id: object.uuid),
371 action_method: 'patch',
372 preconfigured_search_str: (preconfigured_search_str || ""),
375 use_preview_selection: dataclass == File ? true : nil,
376 selection_param: selection_param,
377 success: 'page-refresh'
381 return content_tag('div', :class => 'input-group') do
382 html = text_field_tag(dn, display_value,
384 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
385 html + content_tag('span', :class => 'input-group-btn') do
388 { :class => "btn btn-primary",
396 if attrvalue.is_a? String
398 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
399 # TODO: find a way to edit with x-editable
403 # When datatype is a String or Fixnum, link_to the attrvalue
404 lt = link_to attrvalue, '#', {
405 "data-emptytext" => "none",
406 "data-placement" => "bottom",
407 "data-type" => datatype,
408 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
409 "data-title" => "Set value for #{subattr[-1].to_s}",
411 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
412 "data-value" => attrvalue,
413 # "clear" button interferes with form-control's up/down arrows
414 "data-clear" => false,
415 :class => "editable #{'required' if required} form-control",
422 def get_cwl_main(workflow)
423 if workflow[:"$graph"].nil?
426 workflow[:"$graph"].each do |tool|
427 if tool[:id] == "#main"
434 def get_cwl_inputs(workflow)
435 get_cwl_main(workflow)[:inputs]
439 def cwl_shortname(id)
443 return id.split("/")[-1]
446 def cwl_input_info(input_schema)
447 required = !(input_schema[:type].include? "null")
448 if input_schema[:type].is_a? Array
449 primary_type = input_schema[:type].select { |n| n != "null" }[0]
450 elsif input_schema[:type].is_a? String
451 primary_type = input_schema[:type]
452 elsif input_schema[:type].is_a? Hash
453 primary_type = input_schema[:type]
455 param_id = cwl_shortname(input_schema[:id])
456 return required, primary_type, param_id
459 def cwl_input_value(object, input_schema, set_attr_path)
462 set_attr_path.each do |a|
464 attrvalue = attrvalue[a.to_sym]
469 def cwl_inputs_required(object, inputs_schema, set_attr_path)
471 inputs_schema.each do |input|
472 required, primary_type, param_id = cwl_input_info(input)
473 dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
474 r += 1 if required and attrvalue.nil?
479 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
480 required, primary_type, param_id = cwl_input_info(input_schema)
482 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
483 attrvalue = if attrvalue.nil? then "" else attrvalue end
485 id = "#{object.uuid}-#{param_id}"
487 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
489 if ["Directory", "File"].include? primary_type
490 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
491 selection_param = object.class.to_s.underscore + dn
492 if attrvalue.is_a? Hash
493 display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
494 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
497 display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
499 display_value = Collection.find(re[1]).name
503 modal_path = choose_collections_path \
504 ({ title: chooser_title,
505 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
507 action_href: container_request_path(id: object.uuid),
508 action_method: 'patch',
509 preconfigured_search_str: "",
512 use_preview_selection: primary_type == 'File' ? true : nil,
513 selection_param: selection_param,
514 success: 'page-refresh'
518 return content_tag('div', :class => 'input-group') do
519 html = text_field_tag(dn, display_value,
521 "form-control #{'required' if required}")
522 html + content_tag('span', :class => 'input-group-btn') do
525 { :class => "btn btn-primary",
531 elsif "boolean" == primary_type
532 return link_to attrvalue.to_s, '#', {
533 "data-emptytext" => "none",
534 "data-placement" => "bottom",
535 "data-type" => "select",
536 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
537 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
538 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
540 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
541 "data-value" => attrvalue.to_s,
542 # "clear" button interferes with form-control's up/down arrows
543 "data-clear" => false,
544 :class => "editable #{'required' if required} form-control",
547 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
548 return link_to attrvalue, '#', {
549 "data-emptytext" => "none",
550 "data-placement" => "bottom",
551 "data-type" => "select",
552 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
553 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
554 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
556 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
557 "data-value" => attrvalue,
558 # "clear" button interferes with form-control's up/down arrows
559 "data-clear" => false,
560 :class => "editable #{'required' if required} form-control",
563 elsif primary_type.is_a? String
564 if ["int", "long"].include? primary_type
570 return link_to attrvalue, '#', {
571 "data-emptytext" => "none",
572 "data-placement" => "bottom",
573 "data-type" => datatype,
574 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
575 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
577 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
578 "data-value" => attrvalue,
579 # "clear" button interferes with form-control's up/down arrows
580 "data-clear" => false,
581 :class => "editable #{'required' if required} form-control",
585 return "Unable to render editing control for parameter type #{primary_type}"
589 def render_arvados_object_list_start(list, button_text, button_href,
590 params={}, *rest, &block)
591 show_max = params.delete(:show_max) || 3
592 params[:class] ||= 'btn btn-xs btn-default'
593 list[0...show_max].each { |item| yield item }
594 unless list[show_max].nil?
595 link_to(h(button_text) +
596 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
597 button_href, params, *rest)
601 def render_controller_partial partial, opts
602 cname = opts.delete :controller_name
604 render opts.merge(partial: "#{cname}/#{partial}")
605 rescue ActionView::MissingTemplate
606 render opts.merge(partial: "application/#{partial}")
610 RESOURCE_CLASS_ICONS = {
611 "Collection" => "fa-archive",
612 "ContainerRequest" => "fa-gears",
613 "Group" => "fa-users",
614 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
616 "KeepDisk" => "fa-hdd-o",
617 "KeepService" => "fa-exchange",
618 "Link" => "fa-arrows-h",
619 "Node" => "fa-cloud",
620 "PipelineInstance" => "fa-gears",
621 "PipelineTemplate" => "fa-gears",
622 "Repository" => "fa-code-fork",
623 "Specimen" => "fa-flask",
624 "Trait" => "fa-clipboard",
626 "VirtualMachine" => "fa-terminal",
627 "Workflow" => "fa-gears",
629 DEFAULT_ICON_CLASS = "fa-cube"
631 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
632 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
635 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
636 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
639 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
640 case class_name = object.class.to_s
642 object.group_class ? 'fa-folder' : 'fa-users'
644 RESOURCE_CLASS_ICONS.fetch(class_name, default)
648 def chooser_preview_url_for object, use_preview_selection=false
649 case object.class.to_s
651 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
657 def render_attribute_as_textile( object, attr, attrvalue, truncate )
658 if attrvalue && (is_textile? object, attr)
659 markup = render_markup attrvalue
660 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
667 def render_localized_date(date, opts="")
668 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
671 def render_time duration, use_words, round_to_min=true
672 render_runtime duration, use_words, round_to_min
675 # Keep locators are expected to be of the form \"...<pdh/file_path>\"
676 JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*?)(?=['"]|\z|$)/
677 def keep_locator_in_json str
678 # Return a list of all matches
679 str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
683 def is_textile?( object, attr )
684 is_textile = object.textile_attributes.andand.include?(attr)