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.Services.Controller.ExternalURL.hostname}:#{Rails.configuration.Services.Controller.ExternalURL.port}"
18 def current_uuid_prefix
19 Rails.configuration.ClusterID
22 def render_markup(markup)
23 allowed_tags = Rails::Html::Sanitizer.white_list_sanitizer.allowed_tags + %w(table tbody th tr td col colgroup caption thead tfoot)
24 sanitize(raw(RedCloth.new(markup.to_s).to_html(:refs_arvados, :textile)), tags: allowed_tags) if markup
27 def human_readable_bytes_html(n)
28 return h(n) unless n.is_a? Integer
29 return "0 bytes" if (n == 0)
35 (1024*1024*1024) => "GiB",
36 (1024*1024*1024*1024) => "TiB"
41 if sig >=1 and sig < 1024
43 return "%i #{v}" % sig
45 return "%0.1f #{v}" % sig
53 def resource_class_for_uuid(attrvalue, opts={})
54 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
57 # When using {remote:true}, or using {method:...} to use an HTTP
58 # method other than GET, move the target URI from href to
59 # data-remote-href. Otherwise, browsers offer features like "open in
60 # new window" and "copy link address" which bypass Rails' click
61 # handler and therefore end up at incorrect/nonexistent routes (by
62 # ignoring data-method) and expect to receive pages rather than
63 # javascript responses.
65 # See assets/javascripts/link_to_remote.js for supporting code.
66 def link_to *args, &block
67 if (args.last and args.last.is_a? Hash and
68 (args.last[:remote] or
69 (args.last[:method] and
70 args.last[:method].to_s.upcase != 'GET')))
72 # Capybara/phantomjs can't click_link without an href, even if
73 # the click handler means it never gets used.
74 raw super.gsub(' href="', ' href="#" data-remote-href="')
76 # Regular browsers work as desired: users can click A elements
77 # without hrefs, and click handlers fire; but there's no "copy
78 # link address" option in the right-click menu.
79 raw super.gsub(' href="', ' data-remote-href="')
87 # Returns HTML that links to the Arvados object specified in +attrvalue+
88 # Provides various output control and styling options.
90 # +attrvalue+ an Arvados model object or uuid
92 # +opts+ a set of flags to control output:
94 # [:link_text] the link text to use (may include HTML), overrides everything else
96 # [:friendly_name] whether to use the "friendly" name in the link text (by
97 # calling #friendly_link_name on the object), otherwise use the uuid
99 # [:with_class_name] prefix the link text with the class name of the model
101 # [:no_tags] disable tags in the link text (default is to show tags).
102 # Currently tags are only shown for Collections.
104 # [:thumbnail] if the object is a collection, show an image thumbnail if the
105 # collection consists of a single image file.
107 # [:no_link] don't create a link, just return the link text
109 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
111 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
112 if (resource_class = resource_class_for_uuid(attrvalue, opts))
113 if attrvalue.is_a? ArvadosBase
115 link_uuid = attrvalue.uuid
118 link_uuid = attrvalue
120 link_name = opts[:link_text]
123 link_name = object.andand.default_name || resource_class.default_name
125 if opts[:friendly_name]
126 if attrvalue.respond_to? :friendly_link_name
127 link_name = attrvalue.friendly_link_name opts[:lookup]
130 if resource_class.name == 'Collection'
131 if CollectionsHelper.match(link_uuid)
132 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
134 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
137 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
139 rescue ArvadosApiClient::NotFoundException
140 # If that lookup failed, the link will too. So don't make one.
145 if link_name.nil? or link_name.empty?
146 link_name = attrvalue
148 if opts[:with_class_name]
149 link_name = "#{resource_class.to_s}: #{link_name}"
151 if !opts[:no_tags] and resource_class == Collection
152 links_for_object(link_uuid).each do |tag|
153 if tag.link_class.in? ["tag", "identifier"]
154 tags += ' <span class="label label-info">'
155 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
160 if opts[:thumbnail] and resource_class == Collection
161 # add an image thumbnail if the collection consists of a single image file.
162 collections_for_object(link_uuid).each do |c|
163 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
165 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
170 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
171 if opts[:no_link] or (resource_class == User && !current_user)
174 controller_class = resource_class.to_s.tableize
175 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
176 controller_class = 'projects'
178 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
181 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
182 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
190 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
191 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
193 return link_to_if_arvados_object attrvalue, opts
196 readable = object_readable attrvalue, resource_class
198 link_to_if_arvados_object attrvalue, opts
199 elsif opts[:required] and current_user # no need to show this for anonymous user
200 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>')
202 link_text_if_not_readable
206 # This method takes advantage of preloaded collections and objects.
207 # Hence you can improve performance by first preloading objects
208 # related to the page context before using this method.
209 def object_readable attrvalue, resource_class=nil
210 # if it is a collection filename, check readable for the locator
211 attrvalue = attrvalue.split('/')[0] if attrvalue
213 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
214 return if resource_class.nil?
217 if resource_class.to_s == 'Collection'
218 if CollectionsHelper.match(attrvalue)
219 found = collection_for_pdh(attrvalue)
220 return_value = found.first if found.any?
222 found = collections_for_object(attrvalue)
223 return_value = found.first if found.any?
226 return_value = object_for_dataclass(resource_class, attrvalue)
231 # Render an editable attribute with the attrvalue of the attr.
232 # The htmloptions are added to the editable element's list of attributes.
233 # The nonhtml_options are only used to customize the display of the element.
234 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
235 attrvalue = object.send(attr) if attrvalue.nil?
236 if not object.attribute_editable?(attr)
237 if attrvalue && attrvalue.length > 0
238 return render_attribute_as_textile( object, attr, attrvalue, false )
240 return (attr == 'name' and object.andand.default_name) ||
246 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
247 if attrtype == 'text' or attr == 'description'
248 input_type = 'textarea'
249 elsif attrtype == 'datetime'
255 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
256 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
261 key: object.class.to_s.underscore
265 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
267 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
268 ajax_options['data-pk'][:defaults] = object.attributes
270 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
271 @unique_id ||= (Time.now.to_f*1000000).to_i
272 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
274 span_tag = content_tag 'span', rendervalue, {
275 "data-emptytext" => '(none)',
276 "data-placement" => "bottom",
277 "data-type" => input_type,
278 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
279 "data-name" => htmloptions['selection_name'] || attr,
280 "data-object-uuid" => object.uuid,
281 "data-toggle" => "manual",
282 "data-value" => htmloptions['data-value'] || attrvalue,
284 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
285 }.merge(htmloptions).merge(ajax_options)
287 edit_tiptitle = 'edit'
288 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')
290 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>')
292 if nonhtml_options[:btnplacement] == :left
293 edit_button + ' ' + span_tag
294 elsif nonhtml_options[:btnplacement] == :top
295 edit_button + raw('<br/>') + span_tag
297 span_tag + ' ' + edit_button
301 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
304 attrvalue = value_info
306 if value_info.is_a? Hash
307 if value_info[:output_of]
308 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
310 if value_info[:dataclass]
311 dataclass = value_info[:dataclass]
313 if value_info[:optional] != nil
314 required = (value_info[:optional] != "true")
316 if value_info[:required] != nil
317 required = value_info[:required]
320 # Pick a suitable attrvalue to show as the current value (i.e.,
321 # the one that would be used if we ran the pipeline right now).
322 if value_info[:value]
323 attrvalue = value_info[:value]
324 elsif value_info[:default]
325 attrvalue = value_info[:default]
329 preconfigured_search_str = value_info[:search_for]
332 if not object.andand.attribute_editable?(attr)
333 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
338 dataclass = dataclass.constantize
342 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
345 id = "#{object.uuid}-#{subattr.join('-')}"
350 if value_info.is_a? Hash
354 if (dataclass == Collection) or (dataclass == File)
355 selection_param = object.class.to_s.underscore + dn
356 display_value = attrvalue
357 if value_info.is_a?(Hash)
358 if (link = Link.find? value_info[:link_uuid])
359 display_value = link.name
360 elsif value_info[:link_name]
361 display_value = value_info[:link_name]
362 elsif (sn = value_info[:selection_name]) && sn != ""
366 if (attr == :components) and (subattr.size > 2)
367 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
369 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
371 modal_path = choose_collections_path \
372 ({ title: chooser_title,
373 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
375 action_href: pipeline_instance_path(id: object.uuid),
376 action_method: 'patch',
377 preconfigured_search_str: (preconfigured_search_str || ""),
380 use_preview_selection: dataclass == File ? true : nil,
381 selection_param: selection_param,
382 success: 'page-refresh'
386 return content_tag('div', :class => 'input-group') do
387 html = text_field_tag(dn, display_value,
389 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
390 html + content_tag('span', :class => 'input-group-btn') do
393 { :class => "btn btn-primary",
401 if attrvalue.is_a? String
403 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
404 # TODO: find a way to edit with x-editable
408 # When datatype is a String or Fixnum, link_to the attrvalue
409 lt = link_to attrvalue, '#', {
410 "data-emptytext" => "none",
411 "data-placement" => "bottom",
412 "data-type" => datatype,
413 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
414 "data-title" => "Set value for #{subattr[-1].to_s}",
416 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
417 "data-value" => attrvalue,
418 # "clear" button interferes with form-control's up/down arrows
419 "data-clear" => false,
420 :class => "editable #{'required' if required} form-control",
427 def get_cwl_main(workflow)
428 if workflow[:"$graph"].nil?
431 workflow[:"$graph"].each do |tool|
432 if tool[:id] == "#main"
439 def get_cwl_inputs(workflow)
440 get_cwl_main(workflow)[:inputs]
444 def cwl_shortname(id)
448 return id.split("/")[-1]
451 def cwl_input_info(input_schema)
452 required = !(input_schema[:type].include? "null")
453 if input_schema[:type].is_a? Array
454 primary_type = input_schema[:type].select { |n| n != "null" }[0]
455 elsif input_schema[:type].is_a? String
456 primary_type = input_schema[:type]
457 elsif input_schema[:type].is_a? Hash
458 primary_type = input_schema[:type]
460 param_id = cwl_shortname(input_schema[:id])
461 return required, primary_type, param_id
464 def cwl_input_value(object, input_schema, set_attr_path)
467 set_attr_path.each do |a|
469 attrvalue = attrvalue[a.to_sym]
474 def cwl_inputs_required(object, inputs_schema, set_attr_path)
476 inputs_schema.each do |input|
477 required, _, param_id = cwl_input_info(input)
478 _, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
479 r += 1 if required and attrvalue.nil?
484 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
485 required, primary_type, param_id = cwl_input_info(input_schema)
487 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
488 attrvalue = if attrvalue.nil? then "" else attrvalue end
490 id = "#{object.uuid}-#{param_id}"
492 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
494 if ["Directory", "File"].include? primary_type
495 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
496 selection_param = object.class.to_s.underscore + dn
497 if attrvalue.is_a? Hash
498 display_value = attrvalue[:"http://arvados.org/cwl#collectionUUID"] || attrvalue[:"arv:collection"] || attrvalue[:location]
499 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
500 locationre = CollectionsHelper.match(attrvalue[:location][5..-1])
502 if locationre and locationre[4]
503 display_value = "#{Collection.find(re[1]).name} / #{locationre[4][1..-1]}"
505 display_value = Collection.find(re[1]).name
509 modal_path = choose_collections_path \
510 ({ title: chooser_title,
511 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
513 action_href: container_request_path(id: object.uuid),
514 action_method: 'patch',
515 preconfigured_search_str: "",
518 use_preview_selection: primary_type == 'File' ? true : nil,
519 selection_param: selection_param,
520 success: 'page-refresh'
524 return content_tag('div', :class => 'input-group') do
525 html = text_field_tag(dn, display_value,
527 "form-control #{'required' if required}")
528 html + content_tag('span', :class => 'input-group-btn') do
531 { :class => "btn btn-primary",
537 elsif "boolean" == primary_type
538 return link_to attrvalue.to_s, '#', {
539 "data-emptytext" => "none",
540 "data-placement" => "bottom",
541 "data-type" => "select",
542 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
543 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
544 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
546 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
547 "data-value" => attrvalue.to_s,
548 # "clear" button interferes with form-control's up/down arrows
549 "data-clear" => false,
550 :class => "editable #{'required' if required} form-control",
553 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
554 return link_to attrvalue, '#', {
555 "data-emptytext" => "none",
556 "data-placement" => "bottom",
557 "data-type" => "select",
558 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
559 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
560 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
562 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
563 "data-value" => attrvalue,
564 # "clear" button interferes with form-control's up/down arrows
565 "data-clear" => false,
566 :class => "editable #{'required' if required} form-control",
569 elsif primary_type.is_a? String
570 if ["int", "long"].include? primary_type
576 return link_to attrvalue, '#', {
577 "data-emptytext" => "none",
578 "data-placement" => "bottom",
579 "data-type" => datatype,
580 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
581 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
583 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
584 "data-value" => attrvalue,
585 # "clear" button interferes with form-control's up/down arrows
586 "data-clear" => false,
587 :class => "editable #{'required' if required} form-control",
591 return "Unable to render editing control for parameter type #{primary_type}"
595 def render_arvados_object_list_start(list, button_text, button_href,
596 params={}, *rest, &block)
597 show_max = params.delete(:show_max) || 3
598 params[:class] ||= 'btn btn-xs btn-default'
599 list[0...show_max].each { |item| yield item }
600 unless list[show_max].nil?
601 link_to(h(button_text) +
602 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
603 button_href, params, *rest)
607 def render_controller_partial partial, opts
608 cname = opts.delete :controller_name
610 render opts.merge(partial: "#{cname}/#{partial}")
611 rescue ActionView::MissingTemplate
612 render opts.merge(partial: "application/#{partial}")
616 RESOURCE_CLASS_ICONS = {
617 "Collection" => "fa-archive",
618 "ContainerRequest" => "fa-gears",
619 "Group" => "fa-users",
620 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
622 "KeepDisk" => "fa-hdd-o",
623 "KeepService" => "fa-exchange",
624 "Link" => "fa-arrows-h",
625 "Node" => "fa-cloud",
626 "PipelineInstance" => "fa-gears",
627 "PipelineTemplate" => "fa-gears",
628 "Repository" => "fa-code-fork",
629 "Specimen" => "fa-flask",
630 "Trait" => "fa-clipboard",
632 "VirtualMachine" => "fa-terminal",
633 "Workflow" => "fa-gears",
635 DEFAULT_ICON_CLASS = "fa-cube"
637 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
638 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
641 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
642 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
645 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
646 case class_name = object.class.to_s
648 object.group_class ? 'fa-folder' : 'fa-users'
650 RESOURCE_CLASS_ICONS.fetch(class_name, default)
654 def chooser_preview_url_for object, use_preview_selection=false
655 case object.class.to_s
657 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
663 def render_attribute_as_textile( object, attr, attrvalue, truncate )
664 if attrvalue && (is_textile? object, attr)
665 markup = render_markup attrvalue
666 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
673 def render_localized_date(date, opts="")
674 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
677 def render_time duration, use_words, round_to_min=true
678 render_runtime duration, use_words, round_to_min
681 # Keep locators are expected to be of the form \"...<pdh/file_path>\" or \"...<uuid/file_path>\"
682 JSON_KEEP_LOCATOR_REGEXP = /([0-9a-f]{32}\+\d+[^'"]*|[a-z0-9]{5}-4zz18-[a-z0-9]{15}[^'"]*)(?=['"]|\z|$)/
683 def keep_locator_in_json str
684 # Return a list of all matches
685 str.scan(JSON_KEEP_LOCATOR_REGEXP).flatten
689 def is_textile?( object, attr )
690 object.textile_attributes.andand.include?(attr)