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 allowed_tags = Rails::Html::Sanitizer.white_list_sanitizer.allowed_tags + %w(table tbody th tr td col colgroup caption thead tfoot)
20 sanitize(raw(RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile)), tags: allowed_tags) if markup
23 def human_readable_bytes_html(n)
24 return h(n) unless n.is_a? Fixnum
25 return "0 bytes" if (n == 0)
31 (1024*1024*1024) => "GiB",
32 (1024*1024*1024*1024) => "TiB"
37 if sig >=1 and sig < 1024
39 return "%i #{v}" % sig
41 return "%0.1f #{v}" % sig
49 def resource_class_for_uuid(attrvalue, opts={})
50 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
53 # When using {remote:true}, or using {method:...} to use an HTTP
54 # method other than GET, move the target URI from href to
55 # data-remote-href. Otherwise, browsers offer features like "open in
56 # new window" and "copy link address" which bypass Rails' click
57 # handler and therefore end up at incorrect/nonexistent routes (by
58 # ignoring data-method) and expect to receive pages rather than
59 # javascript responses.
61 # See assets/javascripts/link_to_remote.js for supporting code.
62 def link_to *args, &block
63 if (args.last and args.last.is_a? Hash and
64 (args.last[:remote] or
65 (args.last[:method] and
66 args.last[:method].to_s.upcase != 'GET')))
68 # Capybara/phantomjs can't click_link without an href, even if
69 # the click handler means it never gets used.
70 raw super.gsub(' href="', ' href="#" data-remote-href="')
72 # Regular browsers work as desired: users can click A elements
73 # without hrefs, and click handlers fire; but there's no "copy
74 # link address" option in the right-click menu.
75 raw super.gsub(' href="', ' data-remote-href="')
83 # Returns HTML that links to the Arvados object specified in +attrvalue+
84 # Provides various output control and styling options.
86 # +attrvalue+ an Arvados model object or uuid
88 # +opts+ a set of flags to control output:
90 # [:link_text] the link text to use (may include HTML), overrides everything else
92 # [:friendly_name] whether to use the "friendly" name in the link text (by
93 # calling #friendly_link_name on the object), otherwise use the uuid
95 # [:with_class_name] prefix the link text with the class name of the model
97 # [:no_tags] disable tags in the link text (default is to show tags).
98 # Currently tags are only shown for Collections.
100 # [:thumbnail] if the object is a collection, show an image thumbnail if the
101 # collection consists of a single image file.
103 # [:no_link] don't create a link, just return the link text
105 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
107 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
108 if (resource_class = resource_class_for_uuid(attrvalue, opts))
109 if attrvalue.is_a? ArvadosBase
111 link_uuid = attrvalue.uuid
114 link_uuid = attrvalue
116 link_name = opts[:link_text]
119 link_name = object.andand.default_name || resource_class.default_name
121 if opts[:friendly_name]
122 if attrvalue.respond_to? :friendly_link_name
123 link_name = attrvalue.friendly_link_name opts[:lookup]
126 if resource_class.name == 'Collection'
127 if CollectionsHelper.match(link_uuid)
128 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
130 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
133 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
135 rescue ArvadosApiClient::NotFoundException
136 # If that lookup failed, the link will too. So don't make one.
141 if link_name.nil? or link_name.empty?
142 link_name = attrvalue
144 if opts[:with_class_name]
145 link_name = "#{resource_class.to_s}: #{link_name}"
147 if !opts[:no_tags] and resource_class == Collection
148 links_for_object(link_uuid).each do |tag|
149 if tag.link_class.in? ["tag", "identifier"]
150 tags += ' <span class="label label-info">'
151 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
156 if opts[:thumbnail] and resource_class == Collection
157 # add an image thumbnail if the collection consists of a single image file.
158 collections_for_object(link_uuid).each do |c|
159 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
161 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
166 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
167 if opts[:no_link] or (resource_class == User && !current_user)
170 controller_class = resource_class.to_s.tableize
171 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
172 controller_class = 'projects'
174 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
177 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
178 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
186 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
187 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
189 return link_to_if_arvados_object attrvalue, opts
192 readable = object_readable attrvalue, resource_class
194 link_to_if_arvados_object attrvalue, opts
195 elsif opts[:required] and current_user # no need to show this for anonymous user
196 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>')
198 link_text_if_not_readable
202 # This method takes advantage of preloaded collections and objects.
203 # Hence you can improve performance by first preloading objects
204 # related to the page context before using this method.
205 def object_readable attrvalue, resource_class=nil
206 # if it is a collection filename, check readable for the locator
207 attrvalue = attrvalue.split('/')[0] if attrvalue
209 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
210 return if resource_class.nil?
213 if resource_class.to_s == 'Collection'
214 if CollectionsHelper.match(attrvalue)
215 found = collection_for_pdh(attrvalue)
216 return_value = found.first if found.any?
218 found = collections_for_object(attrvalue)
219 return_value = found.first if found.any?
222 return_value = object_for_dataclass(resource_class, attrvalue)
227 # Render an editable attribute with the attrvalue of the attr.
228 # The htmloptions are added to the editable element's list of attributes.
229 # The nonhtml_options are only used to customize the display of the element.
230 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
231 attrvalue = object.send(attr) if attrvalue.nil?
232 if not object.attribute_editable?(attr)
233 if attrvalue && attrvalue.length > 0
234 return render_attribute_as_textile( object, attr, attrvalue, false )
236 return (attr == 'name' and object.andand.default_name) ||
242 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
243 if attrtype == 'text' or attr == 'description'
244 input_type = 'textarea'
245 elsif attrtype == 'datetime'
251 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
252 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
257 key: object.class.to_s.underscore
261 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
263 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
264 ajax_options['data-pk'][:defaults] = object.attributes
266 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
267 @unique_id ||= (Time.now.to_f*1000000).to_i
268 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
270 span_tag = content_tag 'span', rendervalue, {
271 "data-emptytext" => '(none)',
272 "data-placement" => "bottom",
273 "data-type" => input_type,
274 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
275 "data-name" => htmloptions['selection_name'] || attr,
276 "data-object-uuid" => object.uuid,
277 "data-toggle" => "manual",
278 "data-value" => htmloptions['data-value'] || attrvalue,
280 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
281 }.merge(htmloptions).merge(ajax_options)
283 edit_tiptitle = 'edit'
284 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')
286 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>')
288 if nonhtml_options[:btnplacement] == :left
289 edit_button + ' ' + span_tag
290 elsif nonhtml_options[:btnplacement] == :top
291 edit_button + raw('<br/>') + span_tag
293 span_tag + ' ' + edit_button
297 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
300 attrvalue = value_info
302 if value_info.is_a? Hash
303 if value_info[:output_of]
304 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
306 if value_info[:dataclass]
307 dataclass = value_info[:dataclass]
309 if value_info[:optional] != nil
310 required = (value_info[:optional] != "true")
312 if value_info[:required] != nil
313 required = value_info[:required]
316 # Pick a suitable attrvalue to show as the current value (i.e.,
317 # the one that would be used if we ran the pipeline right now).
318 if value_info[:value]
319 attrvalue = value_info[:value]
320 elsif value_info[:default]
321 attrvalue = value_info[:default]
325 preconfigured_search_str = value_info[:search_for]
328 if not object.andand.attribute_editable?(attr)
329 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
334 dataclass = dataclass.constantize
338 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
341 id = "#{object.uuid}-#{subattr.join('-')}"
346 if value_info.is_a? Hash
350 if (dataclass == Collection) or (dataclass == File)
351 selection_param = object.class.to_s.underscore + dn
352 display_value = attrvalue
353 if value_info.is_a?(Hash)
354 if (link = Link.find? value_info[:link_uuid])
355 display_value = link.name
356 elsif value_info[:link_name]
357 display_value = value_info[:link_name]
358 elsif value_info[:selection_name]
359 display_value = value_info[:selection_name]
362 if (attr == :components) and (subattr.size > 2)
363 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
365 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
367 modal_path = choose_collections_path \
368 ({ title: chooser_title,
369 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
371 action_href: pipeline_instance_path(id: object.uuid),
372 action_method: 'patch',
373 preconfigured_search_str: (preconfigured_search_str || ""),
376 use_preview_selection: dataclass == File ? true : nil,
377 selection_param: selection_param,
378 success: 'page-refresh'
382 return content_tag('div', :class => 'input-group') do
383 html = text_field_tag(dn, display_value,
385 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
386 html + content_tag('span', :class => 'input-group-btn') do
389 { :class => "btn btn-primary",
397 if attrvalue.is_a? String
399 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
400 # TODO: find a way to edit with x-editable
404 # When datatype is a String or Fixnum, link_to the attrvalue
405 lt = link_to attrvalue, '#', {
406 "data-emptytext" => "none",
407 "data-placement" => "bottom",
408 "data-type" => datatype,
409 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
410 "data-title" => "Set value for #{subattr[-1].to_s}",
412 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
413 "data-value" => attrvalue,
414 # "clear" button interferes with form-control's up/down arrows
415 "data-clear" => false,
416 :class => "editable #{'required' if required} form-control",
423 def get_cwl_main(workflow)
424 if workflow[:"$graph"].nil?
427 workflow[:"$graph"].each do |tool|
428 if tool[:id] == "#main"
435 def get_cwl_inputs(workflow)
436 get_cwl_main(workflow)[:inputs]
440 def cwl_shortname(id)
444 return id.split("/")[-1]
447 def cwl_input_info(input_schema)
448 required = !(input_schema[:type].include? "null")
449 if input_schema[:type].is_a? Array
450 primary_type = input_schema[:type].select { |n| n != "null" }[0]
451 elsif input_schema[:type].is_a? String
452 primary_type = input_schema[:type]
453 elsif input_schema[:type].is_a? Hash
454 primary_type = input_schema[:type]
456 param_id = cwl_shortname(input_schema[:id])
457 return required, primary_type, param_id
460 def cwl_input_value(object, input_schema, set_attr_path)
463 set_attr_path.each do |a|
465 attrvalue = attrvalue[a.to_sym]
470 def cwl_inputs_required(object, inputs_schema, set_attr_path)
472 inputs_schema.each do |input|
473 required, primary_type, param_id = cwl_input_info(input)
474 dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
475 r += 1 if required and attrvalue.nil?
480 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
481 required, primary_type, param_id = cwl_input_info(input_schema)
483 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
484 attrvalue = if attrvalue.nil? then "" else attrvalue end
486 id = "#{object.uuid}-#{param_id}"
488 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
490 if ["Directory", "File"].include? primary_type
491 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
492 selection_param = object.class.to_s.underscore + dn
493 if attrvalue.is_a? Hash
494 display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
495 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
498 display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
500 display_value = Collection.find(re[1]).name
504 modal_path = choose_collections_path \
505 ({ title: chooser_title,
506 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
508 action_href: container_request_path(id: object.uuid),
509 action_method: 'patch',
510 preconfigured_search_str: "",
513 use_preview_selection: primary_type == 'File' ? true : nil,
514 selection_param: selection_param,
515 success: 'page-refresh'
519 return content_tag('div', :class => 'input-group') do
520 html = text_field_tag(dn, display_value,
522 "form-control #{'required' if required}")
523 html + content_tag('span', :class => 'input-group-btn') do
526 { :class => "btn btn-primary",
532 elsif "boolean" == primary_type
533 return link_to attrvalue.to_s, '#', {
534 "data-emptytext" => "none",
535 "data-placement" => "bottom",
536 "data-type" => "select",
537 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
538 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
539 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
541 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
542 "data-value" => attrvalue.to_s,
543 # "clear" button interferes with form-control's up/down arrows
544 "data-clear" => false,
545 :class => "editable #{'required' if required} form-control",
548 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
549 return link_to attrvalue, '#', {
550 "data-emptytext" => "none",
551 "data-placement" => "bottom",
552 "data-type" => "select",
553 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
554 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
555 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
557 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
558 "data-value" => attrvalue,
559 # "clear" button interferes with form-control's up/down arrows
560 "data-clear" => false,
561 :class => "editable #{'required' if required} form-control",
564 elsif primary_type.is_a? String
565 if ["int", "long"].include? primary_type
571 return link_to attrvalue, '#', {
572 "data-emptytext" => "none",
573 "data-placement" => "bottom",
574 "data-type" => datatype,
575 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
576 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
578 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
579 "data-value" => attrvalue,
580 # "clear" button interferes with form-control's up/down arrows
581 "data-clear" => false,
582 :class => "editable #{'required' if required} form-control",
586 return "Unable to render editing control for parameter type #{primary_type}"
590 def render_arvados_object_list_start(list, button_text, button_href,
591 params={}, *rest, &block)
592 show_max = params.delete(:show_max) || 3
593 params[:class] ||= 'btn btn-xs btn-default'
594 list[0...show_max].each { |item| yield item }
595 unless list[show_max].nil?
596 link_to(h(button_text) +
597 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
598 button_href, params, *rest)
602 def render_controller_partial partial, opts
603 cname = opts.delete :controller_name
605 render opts.merge(partial: "#{cname}/#{partial}")
606 rescue ActionView::MissingTemplate
607 render opts.merge(partial: "application/#{partial}")
611 RESOURCE_CLASS_ICONS = {
612 "Collection" => "fa-archive",
613 "ContainerRequest" => "fa-gears",
614 "Group" => "fa-users",
615 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
617 "KeepDisk" => "fa-hdd-o",
618 "KeepService" => "fa-exchange",
619 "Link" => "fa-arrows-h",
620 "Node" => "fa-cloud",
621 "PipelineInstance" => "fa-gears",
622 "PipelineTemplate" => "fa-gears",
623 "Repository" => "fa-code-fork",
624 "Specimen" => "fa-flask",
625 "Trait" => "fa-clipboard",
627 "VirtualMachine" => "fa-terminal",
628 "Workflow" => "fa-gears",
630 DEFAULT_ICON_CLASS = "fa-cube"
632 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
633 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
636 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
637 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
640 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
641 case class_name = object.class.to_s
643 object.group_class ? 'fa-folder' : 'fa-users'
645 RESOURCE_CLASS_ICONS.fetch(class_name, default)
649 def chooser_preview_url_for object, use_preview_selection=false
650 case object.class.to_s
652 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
658 def render_attribute_as_textile( object, attr, attrvalue, truncate )
659 if attrvalue && (is_textile? object, attr)
660 markup = render_markup attrvalue
661 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
668 def render_localized_date(date, opts="")
669 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
672 def render_time duration, use_words, round_to_min=true
673 render_runtime duration, use_words, round_to_min
676 # Keep locators are expected to be of the form \"...<pdh/file_path>\"
677 JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*?)(?=['"]|\z|$)/
678 def keep_locator_in_json str
679 # Return a list of all matches
680 str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
684 def is_textile?( object, attr )
685 is_textile = object.textile_attributes.andand.include?(attr)