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 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
49 # cooked = ',' + raw[-3..-1] + cooked
52 #cooked = raw + cooked
55 def resource_class_for_uuid(attrvalue, opts={})
56 ArvadosBase::resource_class_for_uuid(attrvalue, opts)
59 # When using {remote:true}, or using {method:...} to use an HTTP
60 # method other than GET, move the target URI from href to
61 # data-remote-href. Otherwise, browsers offer features like "open in
62 # new window" and "copy link address" which bypass Rails' click
63 # handler and therefore end up at incorrect/nonexistent routes (by
64 # ignoring data-method) and expect to receive pages rather than
65 # javascript responses.
67 # See assets/javascripts/link_to_remote.js for supporting code.
68 def link_to *args, &block
69 if (args.last and args.last.is_a? Hash and
70 (args.last[:remote] or
71 (args.last[:method] and
72 args.last[:method].to_s.upcase != 'GET')))
74 # Capybara/phantomjs can't click_link without an href, even if
75 # the click handler means it never gets used.
76 raw super.gsub(' href="', ' href="#" data-remote-href="')
78 # Regular browsers work as desired: users can click A elements
79 # without hrefs, and click handlers fire; but there's no "copy
80 # link address" option in the right-click menu.
81 raw super.gsub(' href="', ' data-remote-href="')
89 # Returns HTML that links to the Arvados object specified in +attrvalue+
90 # Provides various output control and styling options.
92 # +attrvalue+ an Arvados model object or uuid
94 # +opts+ a set of flags to control output:
96 # [:link_text] the link text to use (may include HTML), overrides everything else
98 # [:friendly_name] whether to use the "friendly" name in the link text (by
99 # calling #friendly_link_name on the object), otherwise use the uuid
101 # [:with_class_name] prefix the link text with the class name of the model
103 # [:no_tags] disable tags in the link text (default is to show tags).
104 # Currently tags are only shown for Collections.
106 # [:thumbnail] if the object is a collection, show an image thumbnail if the
107 # collection consists of a single image file.
109 # [:no_link] don't create a link, just return the link text
111 # +style_opts+ additional HTML properties for the anchor tag, passed to link_to
113 def link_to_if_arvados_object(attrvalue, opts={}, style_opts={})
114 if (resource_class = resource_class_for_uuid(attrvalue, opts))
115 if attrvalue.is_a? ArvadosBase
117 link_uuid = attrvalue.uuid
120 link_uuid = attrvalue
122 link_name = opts[:link_text]
125 link_name = object.andand.default_name || resource_class.default_name
127 if opts[:friendly_name]
128 if attrvalue.respond_to? :friendly_link_name
129 link_name = attrvalue.friendly_link_name opts[:lookup]
132 if resource_class.name == 'Collection'
133 if CollectionsHelper.match(link_uuid)
134 link_name = collection_for_pdh(link_uuid).andand.first.andand.portable_data_hash
136 link_name = collections_for_object(link_uuid).andand.first.andand.friendly_link_name
139 link_name = object_for_dataclass(resource_class, link_uuid).andand.friendly_link_name
141 rescue ArvadosApiClient::NotFoundException
142 # If that lookup failed, the link will too. So don't make one.
147 if link_name.nil? or link_name.empty?
148 link_name = attrvalue
150 if opts[:with_class_name]
151 link_name = "#{resource_class.to_s}: #{link_name}"
153 if !opts[:no_tags] and resource_class == Collection
154 links_for_object(link_uuid).each do |tag|
155 if tag.link_class.in? ["tag", "identifier"]
156 tags += ' <span class="label label-info">'
157 tags += link_to tag.name, controller: "links", filters: [["link_class", "=", "tag"], ["name", "=", tag.name]].to_json
162 if opts[:thumbnail] and resource_class == Collection
163 # add an image thumbnail if the collection consists of a single image file.
164 collections_for_object(link_uuid).each do |c|
165 if c.files.length == 1 and CollectionsHelper::is_image c.files.first[1]
167 link_name += image_tag "#{url_for c}/#{CollectionsHelper::file_path c.files.first}", style: "height: 4em; width: auto"
172 style_opts[:class] = (style_opts[:class] || '') + ' nowrap'
173 if opts[:no_link] or (resource_class == User && !current_user)
176 controller_class = resource_class.to_s.tableize
177 if controller_class.eql?('groups') and object.andand.group_class.eql?('project')
178 controller_class = 'projects'
180 (link_to raw(link_name), { controller: controller_class, action: 'show', id: ((opts[:name_link].andand.uuid) || link_uuid) }, style_opts) + raw(tags)
183 # just return attrvalue if it is not recognizable as an Arvados object or uuid.
184 if attrvalue.nil? or (attrvalue.is_a? String and attrvalue.empty?)
192 def link_to_arvados_object_if_readable(attrvalue, link_text_if_not_readable, opts={})
193 resource_class = resource_class_for_uuid(attrvalue.split('/')[0]) if attrvalue.is_a?(String)
195 return link_to_if_arvados_object attrvalue, opts
198 readable = object_readable attrvalue, resource_class
200 link_to_if_arvados_object attrvalue, opts
201 elsif opts[:required] and current_user # no need to show this for anonymous user
202 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>')
204 link_text_if_not_readable
208 # This method takes advantage of preloaded collections and objects.
209 # Hence you can improve performance by first preloading objects
210 # related to the page context before using this method.
211 def object_readable attrvalue, resource_class=nil
212 # if it is a collection filename, check readable for the locator
213 attrvalue = attrvalue.split('/')[0] if attrvalue
215 resource_class = resource_class_for_uuid(attrvalue) if resource_class.nil?
216 return if resource_class.nil?
219 if resource_class.to_s == 'Collection'
220 if CollectionsHelper.match(attrvalue)
221 found = collection_for_pdh(attrvalue)
222 return_value = found.first if found.any?
224 found = collections_for_object(attrvalue)
225 return_value = found.first if found.any?
228 return_value = object_for_dataclass(resource_class, attrvalue)
233 # Render an editable attribute with the attrvalue of the attr.
234 # The htmloptions are added to the editable element's list of attributes.
235 # The nonhtml_options are only used to customize the display of the element.
236 def render_editable_attribute(object, attr, attrvalue=nil, htmloptions={}, nonhtml_options={})
237 attrvalue = object.send(attr) if attrvalue.nil?
238 if not object.attribute_editable?(attr)
239 if attrvalue && attrvalue.length > 0
240 return render_attribute_as_textile( object, attr, attrvalue, false )
242 return (attr == 'name' and object.andand.default_name) ||
248 attrtype = object.class.attribute_info[attr.to_sym].andand[:type]
249 if attrtype == 'text' or attr == 'description'
250 input_type = 'textarea'
251 elsif attrtype == 'datetime'
257 attrvalue = attrvalue.to_json if attrvalue.is_a? Hash or attrvalue.is_a? Array
258 rendervalue = render_attribute_as_textile( object, attr, attrvalue, false )
263 key: object.class.to_s.underscore
267 ajax_options['data-url'] = url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore)
269 ajax_options['data-url'] = url_for(action: "create", controller: object.class.to_s.pluralize.underscore)
270 ajax_options['data-pk'][:defaults] = object.attributes
272 ajax_options['data-pk'] = ajax_options['data-pk'].to_json
273 @unique_id ||= (Time.now.to_f*1000000).to_i
274 span_id = object.uuid.to_s + '-' + attr.to_s + '-' + (@unique_id += 1).to_s
276 span_tag = content_tag 'span', rendervalue, {
277 "data-emptytext" => '(none)',
278 "data-placement" => "bottom",
279 "data-type" => input_type,
280 "data-title" => "Edit #{attr.to_s.gsub '_', ' '}",
281 "data-name" => htmloptions['selection_name'] || attr,
282 "data-object-uuid" => object.uuid,
283 "data-toggle" => "manual",
284 "data-value" => htmloptions['data-value'] || attrvalue,
286 :class => "editable #{is_textile?( object, attr ) ? 'editable-textile' : ''}"
287 }.merge(htmloptions).merge(ajax_options)
289 edit_tiptitle = 'edit'
290 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')
292 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>')
294 if nonhtml_options[:btnplacement] == :left
295 edit_button + ' ' + span_tag
296 elsif nonhtml_options[:btnplacement] == :top
297 edit_button + raw('<br/>') + span_tag
299 span_tag + ' ' + edit_button
303 def render_pipeline_component_attribute(object, attr, subattr, value_info, htmloptions={})
306 attrvalue = value_info
308 if value_info.is_a? Hash
309 if value_info[:output_of]
310 return raw("<span class='label label-default'>#{value_info[:output_of]}</span>")
312 if value_info[:dataclass]
313 dataclass = value_info[:dataclass]
315 if value_info[:optional] != nil
316 required = (value_info[:optional] != "true")
318 if value_info[:required] != nil
319 required = value_info[:required]
322 # Pick a suitable attrvalue to show as the current value (i.e.,
323 # the one that would be used if we ran the pipeline right now).
324 if value_info[:value]
325 attrvalue = value_info[:value]
326 elsif value_info[:default]
327 attrvalue = value_info[:default]
331 preconfigured_search_str = value_info[:search_for]
334 if not object.andand.attribute_editable?(attr)
335 return link_to_arvados_object_if_readable(attrvalue, attrvalue, {friendly_name: true, required: required})
340 dataclass = dataclass.constantize
344 dataclass = ArvadosBase.resource_class_for_uuid(attrvalue)
347 id = "#{object.uuid}-#{subattr.join('-')}"
352 if value_info.is_a? Hash
356 if (dataclass == Collection) or (dataclass == File)
357 selection_param = object.class.to_s.underscore + dn
358 display_value = attrvalue
359 if value_info.is_a?(Hash)
360 if (link = Link.find? value_info[:link_uuid])
361 display_value = link.name
362 elsif value_info[:link_name]
363 display_value = value_info[:link_name]
364 elsif value_info[:selection_name]
365 display_value = value_info[:selection_name]
368 if (attr == :components) and (subattr.size > 2)
369 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'} for #{object.component_input_title(subattr[0], subattr[2])}:"
371 chooser_title = "Choose a #{dataclass == Collection ? 'dataset' : 'file'}:"
373 modal_path = choose_collections_path \
374 ({ title: chooser_title,
375 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
377 action_href: pipeline_instance_path(id: object.uuid),
378 action_method: 'patch',
379 preconfigured_search_str: (preconfigured_search_str || ""),
382 use_preview_selection: dataclass == File ? true : nil,
383 selection_param: selection_param,
384 success: 'page-refresh'
388 return content_tag('div', :class => 'input-group') do
389 html = text_field_tag(dn, display_value,
391 "form-control #{'required' if required} #{'unreadable-input' if attrvalue.present? and !object_readable(attrvalue, Collection)}")
392 html + content_tag('span', :class => 'input-group-btn') do
395 { :class => "btn btn-primary",
403 if attrvalue.is_a? String
405 elsif attrvalue.is_a?(Array) or dataclass.andand.is_a?(Class)
406 # TODO: find a way to edit with x-editable
410 # When datatype is a String or Fixnum, link_to the attrvalue
411 lt = link_to attrvalue, '#', {
412 "data-emptytext" => "none",
413 "data-placement" => "bottom",
414 "data-type" => datatype,
415 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
416 "data-title" => "Set value for #{subattr[-1].to_s}",
418 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
419 "data-value" => attrvalue,
420 # "clear" button interferes with form-control's up/down arrows
421 "data-clear" => false,
422 :class => "editable #{'required' if required} form-control",
429 def get_cwl_inputs(workflow)
431 return workflow[:inputs]
433 workflow[:"$graph"].each do |tool|
434 if tool[:id] == "#main"
441 def cwl_shortname(id)
445 return id.split("/")[-1]
448 def cwl_input_info(input_schema)
449 required = !(input_schema[:type].include? "null")
450 if input_schema[:type].is_a? Array
451 primary_type = input_schema[:type].select { |n| n != "null" }[0]
452 elsif input_schema[:type].is_a? String
453 primary_type = input_schema[:type]
454 elsif input_schema[:type].is_a? Hash
455 primary_type = input_schema[:type]
457 param_id = cwl_shortname(input_schema[:id])
458 return required, primary_type, param_id
461 def cwl_input_value(object, input_schema, set_attr_path)
464 set_attr_path.each do |a|
466 attrvalue = attrvalue[a.to_sym]
471 def cwl_inputs_required(object, inputs_schema, set_attr_path)
473 inputs_schema.each do |input|
474 required, primary_type, param_id = cwl_input_info(input)
475 dn, attrvalue = cwl_input_value(object, input, set_attr_path + [param_id])
476 r += 1 if required and attrvalue.nil?
481 def render_cwl_input(object, input_schema, set_attr_path, htmloptions={})
482 required, primary_type, param_id = cwl_input_info(input_schema)
484 dn, attrvalue = cwl_input_value(object, input_schema, set_attr_path + [param_id])
485 attrvalue = if attrvalue.nil? then "" else attrvalue end
487 id = "#{object.uuid}-#{param_id}"
489 opt_empty_selection = if required then [] else [{value: "", text: ""}] end
491 if ["Directory", "File"].include? primary_type
492 chooser_title = "Choose a #{primary_type == 'Directory' ? 'dataset' : 'file'}:"
493 selection_param = object.class.to_s.underscore + dn
494 if attrvalue.is_a? Hash
495 display_value = attrvalue[:"arv:collection"] || attrvalue[:location]
496 re = CollectionsHelper.match_uuid_with_optional_filepath(display_value)
499 display_value = "#{Collection.find(re[1]).name} / #{re[4][1..-1]}"
501 display_value = Collection.find(re[1]).name
505 modal_path = choose_collections_path \
506 ({ title: chooser_title,
507 filters: [['owner_uuid', '=', object.owner_uuid]].to_json,
509 action_href: container_request_path(id: object.uuid),
510 action_method: 'patch',
511 preconfigured_search_str: "",
514 use_preview_selection: primary_type == 'File' ? true : nil,
515 selection_param: selection_param,
516 success: 'page-refresh'
520 return content_tag('div', :class => 'input-group') do
521 html = text_field_tag(dn, display_value,
523 "form-control #{'required' if required}")
524 html + content_tag('span', :class => 'input-group-btn') do
527 { :class => "btn btn-primary",
533 elsif "boolean" == primary_type
534 return link_to attrvalue.to_s, '#', {
535 "data-emptytext" => "none",
536 "data-placement" => "bottom",
537 "data-type" => "select",
538 "data-source" => (opt_empty_selection + [{value: "true", text: "true"}, {value: "false", text: "false"}]).to_json,
539 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
540 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
542 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
543 "data-value" => attrvalue.to_s,
544 # "clear" button interferes with form-control's up/down arrows
545 "data-clear" => false,
546 :class => "editable #{'required' if required} form-control",
549 elsif primary_type.is_a? Hash and primary_type[:type] == "enum"
550 return link_to attrvalue, '#', {
551 "data-emptytext" => "none",
552 "data-placement" => "bottom",
553 "data-type" => "select",
554 "data-source" => (opt_empty_selection + primary_type[:symbols].map {|i| {:value => i, :text => i} }).to_json,
555 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
556 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
558 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
559 "data-value" => attrvalue,
560 # "clear" button interferes with form-control's up/down arrows
561 "data-clear" => false,
562 :class => "editable #{'required' if required} form-control",
565 elsif primary_type.is_a? String
566 if ["int", "long"].include? primary_type
572 return link_to attrvalue, '#', {
573 "data-emptytext" => "none",
574 "data-placement" => "bottom",
575 "data-type" => datatype,
576 "data-url" => url_for(action: "update", id: object.uuid, controller: object.class.to_s.pluralize.underscore, merge: true),
577 "data-title" => "Set value for #{cwl_shortname(input_schema[:id])}",
579 "data-pk" => "{id: \"#{object.uuid}\", key: \"#{object.class.to_s.underscore}\"}",
580 "data-value" => attrvalue,
581 # "clear" button interferes with form-control's up/down arrows
582 "data-clear" => false,
583 :class => "editable #{'required' if required} form-control",
587 return "Unable to render editing control for parameter type #{primary_type}"
591 def render_arvados_object_list_start(list, button_text, button_href,
592 params={}, *rest, &block)
593 show_max = params.delete(:show_max) || 3
594 params[:class] ||= 'btn btn-xs btn-default'
595 list[0...show_max].each { |item| yield item }
596 unless list[show_max].nil?
597 link_to(h(button_text) +
598 raw(' <i class="fa fa-fw fa-arrow-circle-right"></i>'),
599 button_href, params, *rest)
603 def render_controller_partial partial, opts
604 cname = opts.delete :controller_name
606 render opts.merge(partial: "#{cname}/#{partial}")
607 rescue ActionView::MissingTemplate
608 render opts.merge(partial: "application/#{partial}")
612 RESOURCE_CLASS_ICONS = {
613 "Collection" => "fa-archive",
614 "ContainerRequest" => "fa-gears",
615 "Group" => "fa-users",
616 "Human" => "fa-male", # FIXME: Use a more inclusive icon.
618 "KeepDisk" => "fa-hdd-o",
619 "KeepService" => "fa-exchange",
620 "Link" => "fa-arrows-h",
621 "Node" => "fa-cloud",
622 "PipelineInstance" => "fa-gears",
623 "PipelineTemplate" => "fa-gears",
624 "Repository" => "fa-code-fork",
625 "Specimen" => "fa-flask",
626 "Trait" => "fa-clipboard",
628 "VirtualMachine" => "fa-terminal",
629 "Workflow" => "fa-gears",
631 DEFAULT_ICON_CLASS = "fa-cube"
633 def fa_icon_class_for_class(resource_class, default=DEFAULT_ICON_CLASS)
634 RESOURCE_CLASS_ICONS.fetch(resource_class.to_s, default)
637 def fa_icon_class_for_uuid(uuid, default=DEFAULT_ICON_CLASS)
638 fa_icon_class_for_class(resource_class_for_uuid(uuid), default)
641 def fa_icon_class_for_object(object, default=DEFAULT_ICON_CLASS)
642 case class_name = object.class.to_s
644 object.group_class ? 'fa-folder' : 'fa-users'
646 RESOURCE_CLASS_ICONS.fetch(class_name, default)
650 def chooser_preview_url_for object, use_preview_selection=false
651 case object.class.to_s
653 polymorphic_path(object, tab_pane: 'chooser_preview', use_preview_selection: use_preview_selection)
659 def render_attribute_as_textile( object, attr, attrvalue, truncate )
660 if attrvalue && (is_textile? object, attr)
661 markup = render_markup attrvalue
662 markup = markup[0,markup.index('</p>')+4] if (truncate && markup.index('</p>'))
669 def render_localized_date(date, opts="")
670 raw("<span class='utc-date' data-utc-date='#{date}' data-utc-date-opts='noseconds'>#{date}</span>")
673 def render_time duration, use_words, round_to_min=true
674 render_runtime duration, use_words, round_to_min
677 # Keep locators are expected to be of the form \"...<pdh/file_path>\"
678 JSON_KEEP_LOCATOR_REGEXP = /(.*)(([0-9a-f]{32}\+\d+)(.*)\"(.*))/
679 def keep_locator_in_json str
680 JSON_KEEP_LOCATOR_REGEXP.match str
684 def is_textile?( object, attr )
685 is_textile = object.textile_attributes.andand.include?(attr)