diff --git a/.ci/flake8_lint_include_list.txt b/.ci/flake8_lint_include_list.txt index 05a81fcdd66..c59a8c9da66 100644 --- a/.ci/flake8_lint_include_list.txt +++ b/.ci/flake8_lint_include_list.txt @@ -79,9 +79,7 @@ lib/galaxy/visualization/__init__.py lib/galaxy/visualization/plugins/__init__.py lib/galaxy/visualization/plugins/utils.py lib/galaxy/visualization/tracks/ -lib/galaxy/web/base/controllers/__init__.py -lib/galaxy/web/base/__init__.py -lib/galaxy/web/base/interactive_environments.py +lib/galaxy/web/base/ lib/galaxy/web/buildapp.py lib/galaxy/web/formatting.py lib/galaxy/web/framework/base.py diff --git a/.ci/py3_sources.txt b/.ci/py3_sources.txt index 676a2225f6c..dae37277b5b 100644 --- a/.ci/py3_sources.txt +++ b/.ci/py3_sources.txt @@ -27,6 +27,7 @@ lib/galaxy/tools/ lib/galaxy/tours/ lib/galaxy/util/ lib/galaxy/visualization/ +lib/galaxy/web/base/ lib/galaxy/web/buildapp.py lib/galaxy/web/framework/base.py lib/galaxy/web/framework/decorators.py diff --git a/client/galaxy/scripts/apps/analysis.js b/client/galaxy/scripts/apps/analysis.js index 8bdd36cadde..833e85a765c 100644 --- a/client/galaxy/scripts/apps/analysis.js +++ b/client/galaxy/scripts/apps/analysis.js @@ -17,6 +17,7 @@ var jQuery = require( 'jquery' ), ToolFormComposite = require( 'mvc/tool/tool-form-composite' ), Utils = require( 'utils/utils' ), Ui = require( 'mvc/ui/ui-misc' ), + DatasetError = require( 'mvc/dataset/dataset-error' ), DatasetEditAttributes = require('mvc/dataset/dataset-edit-attributes'); /** define the 'Analyze Data'/analysis/main/home page for Galaxy @@ -51,7 +52,8 @@ window.app = function app( options, bootstrapped ){ '(/)datasets(/)list(/)' : 'show_datasets', '(/)workflow/import_workflow' : 'show_import_workflow', '(/)custom_builds' : 'show_custom_builds', - '(/)datasets/edit': 'show_dataset_edit_attributes' + '(/)datasets/edit': 'show_dataset_edit_attributes', + '(/)datasets/error': 'show_dataset_error' }, require_login: [ @@ -127,6 +129,10 @@ window.app = function app( options, bootstrapped ){ this.page.display( new DatasetEditAttributes.View() ); }, + show_dataset_error : function() { + this.page.display( new DatasetError.View() ); + }, + /** */ home : function( params ){ // TODO: to router, remove Globals diff --git a/client/galaxy/scripts/mvc/dataset/dataset-error.js b/client/galaxy/scripts/mvc/dataset/dataset-error.js new file mode 100644 index 00000000000..e6394023c39 --- /dev/null +++ b/client/galaxy/scripts/mvc/dataset/dataset-error.js @@ -0,0 +1,176 @@ +define( [ 'utils/utils', 'mvc/ui/ui-misc', 'mvc/form/form-view' ], function( Utils, Ui, Form ) { + + /** Dataset edit attributes view */ + var View = Backbone.View.extend({ + initialize: function() { + this.setElement( '
' ); + this.model = new Backbone.Model( { 'dataset_id': Galaxy.params.dataset_id } ); + this.render(); + }, + + // Fetch data for the selected dataset and + render: function() { + var data_url = Galaxy.root + 'api/datasets/' + this.model.get( 'dataset_id' ), + self = this; + + Utils.get({ + url : data_url, + success : function( dataset ) { + var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True'; + Utils.get({ + url : job_url, + success : function( job ) { + var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True'; + self.render_error_page( self, dataset, job ); + }, + error : function( response ) { + var error_response = { + 'status': 'error', + 'message': 'Error occured while loading the job.', + 'persistent': true, + 'cls': 'errormessage' + }; + self.display_message( error_response, self.$( '.response-message' ) ); + } + }); + }, + error : function( response ) { + var error_response = { + 'status': 'error', + 'message': 'Error occured while loading the dataset.', + 'persistent': true, + 'cls': 'errormessage' + }; + self.display_message( error_response, self.$( '.response-message' ) ); + } + }); + }, + + /** Render the view */ + render_error_page: function( self, dataset, job ) { + self.$el.empty().append( self._templateHeader() ); + self.$el.append('

Dataset Error

'); + self.$el.append('

An error occured while running the tool ' + job.tool_id + '.

'); + self.$el.append('

Tool execution generated the following messages:

'); + self.$el.append('
' + job.stderr + '
'); + self.$el.append('

Report This Error'); + self.$el.append('

Usually the local Galaxy administrators regularly review errors that occur on the server. However, if you would like to provide additional information (such as what you were trying to do when the error occurred) and a contact e-mail address, we will be better able to investigate your problem and get back to you.

'); + self.$el.append(self._getBugFormTemplate(dataset, job)); + }, + + /** Display actions messages */ + display_message: function( response, $el, doNotClear, safe ) { + if(!safe){ + if(doNotClear) { + $el.append( new Ui.Message( response ).$el ); + } else { + $el.empty().html( new Ui.Message( response ).$el ); + } + } else { + if(doNotClear) { + $el.append( new Ui.UnescapedMessage( response ).$el ); + } else { + $el.empty().html( new Ui.UnescapedMessage( response ).$el ); + } + } + }, + + /** Main template */ + _templateHeader: function() { + return '
' + + '
' + + '
'; + }, + + /** Convert tab template */ + _getBugFormTemplate: function(dataset, job) { + var self = this; + var inputs = [ + { + "help": "Your email address", + "options": [], + "type": "text", + "name": "email", + "label": "Your email", + "value": Galaxy.user.get('email') + }, + { + "help": "Any additional comments you can provide regarding what you were doing at the time of the bug.", + "options": [], + "type": "text", + "area": true, + "name": "message", + "label": "Message" + } + ]; + + // TODO + if(false && response.any_public){ + inputs.push({ + "name": "public_consent", + "label": "Public Disclosure Consent", + "help": "This Galaxy is configured to report to one or more error reporting backends that public to the world. By selecting 'yes', you acknowledge that this bug report will be made public.", + "value": String( Boolean( false ) ), + "options": [], + "type": "boolean", + }) + } + + var form = new Form({ + title : 'Error Report', + inputs : inputs, + buttons : { + save : new Ui.Button({ + icon : 'fa-bug', + title : 'Report', + cls : 'ui-button btn btn-primary', + floating : 'clear', + onclick : function() { + var form_data = form.data.create(); + var url = Galaxy.root + 'api/jobs/' + job.id + '/error' + form_data.dataset_id = dataset.id; + self.submit(form_data, url) + } + }) + }, + }); + return form.$el; + }, + + /** Make ajax request */ + submit : function(form_data, url){ + var self = this; + // Some required metadata + $.ajax({ + type: "POST", + url: url, + data: form_data, + success: function( response ) { + // Clear out the div + self.$el.empty().append( self._templateHeader() ); + // And display the messages. + response.messages.forEach(function(message){ + self.display_message( { + 'status': message[1], + 'message': message[0], + 'persistent': true, + }, self.$( '.response-message' ), true, true ); + }); + }, + error : function( response ) { + var error_response = { + 'status': 'error', + 'message': 'Error occured while saving. Please fill all the required fields and try again.', + 'persistent': true, + 'cls': 'errormessage' + }; + self.display_message( error_response, self.$( '.response-message' ) ); + } + }); + } + }); + + return { + View : View + }; +}); diff --git a/client/galaxy/scripts/mvc/dataset/dataset-li-edit.js b/client/galaxy/scripts/mvc/dataset/dataset-li-edit.js index 081047c9e4b..6041d6467c9 100644 --- a/client/galaxy/scripts/mvc/dataset/dataset-li-edit.js +++ b/client/galaxy/scripts/mvc/dataset/dataset-li-edit.js @@ -197,9 +197,8 @@ var DatasetListItemEdit = _super.extend( _renderErrButton : function(){ return faIconButton({ title : _l( 'View or report this error' ), - href : this.model.urls.report_error, + href : Galaxy.root + 'datasets/error?dataset_id=' + this.model.attributes.id, classes : 'report-error-btn', - target : this.linkTarget, faIcon : 'fa-bug' }); }, diff --git a/client/galaxy/scripts/mvc/job/job-params.js b/client/galaxy/scripts/mvc/job/job-params.js new file mode 100644 index 00000000000..f45b8da79a2 --- /dev/null +++ b/client/galaxy/scripts/mvc/job/job-params.js @@ -0,0 +1,63 @@ +/** Workflow view */ +define( [ 'utils/utils' ], function( Utils ) { + + /** Build messages after user action */ + function build_messages( self ) { + var $el_message = self.$el.find( '.response-message' ), + status = Utils.getQueryString( 'status' ), + message = Utils.getQueryString( 'message' ); + + if( message && message !== null && message !== "" ) { + $el_message.addClass( status + 'message' ); + $el_message.html( '

' + _.escape( message ) + '

' ); + } + else { + $el_message.html(""); + } + } + + /** View of the main workflow list page */ + var View = Backbone.View.extend({ + + initialize: function( options ) { + var self = this; + this.options = options; + this.setElement( '
' ); + this.render(); + }, + + render: function() { + console.log('HI'); + var self = this; + self.$el.empty().append( '

Testing

' ); + //var self = this, + //min_query_length = 3; + //$.getJSON( Galaxy.root + 'api/workflows/', function( workflows ) { + //var $el_workflow = null; + //// Add workflow header + //// Add user actions message if any + //build_messages( self ); + //$el_workflow = self.$el.find( '.user-workflows' ); + //// Add the actions buttons + //$el_workflow.append( self._templateActionButtons() ); + //if( workflows.length > 0) { + //$el_workflow.append( self._templateWorkflowTable( self, workflows) ); + //self.adjust_actiondropdown( $el_workflow ); + //// Register delete and run workflow events + //_.each( workflows, function( wf ) { + //self.confirm_delete( self, wf ); + //}); + //// Register search workflow event + //self.search_workflow( self, self.$el.find( '.search-wf' ), self.$el.find( '.workflow-search tr' ), min_query_length ); + //} + //else { + //$el_workflow.append( self._templateNoWorkflow() ); + //} + //}); + } + }); + + return { + View : View + }; +}); diff --git a/client/galaxy/scripts/mvc/library/library-dataset-view.js b/client/galaxy/scripts/mvc/library/library-dataset-view.js index dfa7dab4e7e..751f862c18f 100644 --- a/client/galaxy/scripts/mvc/library/library-dataset-view.js +++ b/client/galaxy/scripts/mvc/library/library-dataset-view.js @@ -721,6 +721,12 @@ var LibraryDatasetView = Backbone.View.extend({ '<%= _.escape(item.get("misc_info")) %>', '', '<% } %>', + '<% if (item.get("tags")) { %>', + '', + 'Tags', + '<%= _.escape(item.get("tags")) %>', + '', + '<% } %>', '', '
', @@ -850,6 +856,12 @@ var LibraryDatasetView = Backbone.View.extend({ '<%= _.escape(ldda.get("misc_info")) %>', '', '<% } %>', + '<% if (item.get("tags")) { %>', + '', + 'Tags', + '<%= _.escape(item.get("tags")) %>', + '', + '<% } %>', '', '
', '
',
@@ -951,6 +963,13 @@ var LibraryDatasetView = Backbone.View.extend({
             'Miscellaneous blurb',
             '<%= _.escape(item.get("misc_blurb")) %>',
           '',
+          //TODO: add functionality to modify tags here
+          '<% if (item.get("tags")) { %>',
+            '',
+              'Tags',
+              '<%= _.escape(item.get("tags")) %>',
+            '',
+          '<% } %>',
         '',
         '
', '
',
diff --git a/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js b/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js
index d6a13549869..3532e30987d 100644
--- a/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js
+++ b/client/galaxy/scripts/mvc/library/library-foldertoolbar-view.js
@@ -675,6 +675,7 @@ var FolderToolbarView = Backbone.View.extend({
     var link_data = this.modal.$el.find( '.link-checkbox' ).is( ':checked' );
     var file_type = this.select_extension.value();
     var dbkey = this.select_genome.value();
+    var tag_using_filenames = this.modal.$el.find( '.tag-files' ).is( ':checked' );
     var selection_type = selected_nodes[0].type;
     var paths = [];
     if ( selected_nodes.length < 1 ){
@@ -694,13 +695,15 @@ var FolderToolbarView = Backbone.View.extend({
                                           link_data: link_data,
                                           source: full_source,
                                           file_type: file_type,
-                                          dbkey: dbkey } );
+                                          dbkey: dbkey,
+                                          tag_using_filenames: tag_using_filenames } );
       } else if ( selection_type === 'file' ){
         var full_source = options.source + '_file';
         this.chainCallImportingUserdirFiles( { paths : paths,
                                                file_type: file_type,
                                                dbkey: dbkey,
-                                               source: full_source } );
+                                               source: full_source,
+                                               tag_using_filenames: tag_using_filenames } );
       }
     }
   },
@@ -794,9 +797,10 @@ var FolderToolbarView = Backbone.View.extend({
   },
 
   /**
-   * Take the array of paths and createa request for each of them
+   * Take the array of paths and create a request for each of them
    * calling them in chain. Update the progress bar in between each.
-   * @param  {array} paths           paths relative to user folder on Galaxy
+   * @param  {array} paths                    paths relative to user folder on Galaxy
+   * @param  {boolean} tag_using_filenames    add tags to datasets using names of files
    */
   chainCallImportingUserdirFiles: function( options ){
 
@@ -815,7 +819,8 @@ var FolderToolbarView = Backbone.View.extend({
                                                        '&source=' + options.source +
                                                        '&path=' + popped_item +
                                                        '&file_type=' + options.file_type +
-                                                       '&dbkey=' + options.dbkey ) )
+                                                       '&dbkey=' + options.dbkey +
+                                                       '&tag_using_filenames=' + options.tag_using_filenames ) )
     promise.done( function( response ){
               that.updateProgress();
               that.chainCallImportingUserdirFiles( options );
@@ -830,11 +835,12 @@ var FolderToolbarView = Backbone.View.extend({
   /**
    * Take the array of paths and createa request for each of them
    * calling them in chain. Update the progress bar in between each.
-   * @param  {array} paths           paths relative to Galaxy root folder
-   * @param  {boolean} preserve_dirs indicates whether to preserve folder structure
-   * @param  {boolean} link_data     copy files to Galaxy or link instead
-   * @param  {str} source            string representing what type of folder
-   *                                 is the source of import
+   * @param  {array} paths                    paths relative to Galaxy root folder
+   * @param  {boolean} preserve_dirs          indicates whether to preserve folder structure
+   * @param  {boolean} link_data              copy files to Galaxy or link instead
+   * @param  {str} source                     string representing what type of folder
+   *                                          is the source of import
+   * @param  {boolean} tag_using_filenames    add tags to datasets using names of files
    */
   chainCallImportingFolders: function( options ){
     // TODO need to check which paths to call
@@ -856,7 +862,8 @@ var FolderToolbarView = Backbone.View.extend({
                                                           '&preserve_dirs=' + options.preserve_dirs +
                                                           '&link_data=' + options.link_data +
                                                           '&file_type=' + options.file_type +
-                                                          '&dbkey=' + options.dbkey ) )
+                                                          '&dbkey=' + options.dbkey +
+                                                          '&tag_using_filenames=' + options.tag_using_filenames ) )
     promise.done(function(response){
               that.updateProgress();
               that.chainCallImportingFolders( options );
@@ -1341,7 +1348,13 @@ var FolderToolbarView = Backbone.View.extend({
       '
', 'Type: ', 'Genome: ', - '
', + '
', + '
', + '', + '
', '
' ].join('')); }, diff --git a/client/galaxy/style/less/galaxy_bootstrap/overrides.less b/client/galaxy/style/less/galaxy_bootstrap/overrides.less index 1d4ac947707..4b81980b31e 100644 --- a/client/galaxy/style/less/galaxy_bootstrap/overrides.less +++ b/client/galaxy/style/less/galaxy_bootstrap/overrides.less @@ -94,3 +94,11 @@ div.ui-form-help { } } } + +// pre styling +pre.code { + white-space: pre-wrap; + background: #1d1f21; + color: white; + padding: 1em; +} diff --git a/config/datatypes_conf.xml.sample b/config/datatypes_conf.xml.sample index 84c3ec9a89d..982f1810ae5 100644 --- a/config/datatypes_conf.xml.sample +++ b/config/datatypes_conf.xml.sample @@ -242,6 +242,8 @@ + + @@ -323,7 +325,7 @@ - + diff --git a/config/error_report.yml.sample b/config/error_report.yml.sample new file mode 100644 index 00000000000..a6b4b8640fd --- /dev/null +++ b/config/error_report.yml.sample @@ -0,0 +1,42 @@ +# Each element in this file corresponds to a destination for an error +# report. + +# If you supply the parameter ``user_submission``, and set it to True, +# this error plugin will only be activated when the user uses the bug +# report submission interface. Otherwise, it will be triggered without +# any user interaction (e.g. historical behaviour of sentry plugin) + +# If your plugin is ``user_submission=True``, then supplying +# ``verbose=True`` will cause the plugin to display a message to the end +# user. E.g. the email plugin simply states "Your error report has been +# sent", or the JSON plugin informs the user "Wrote error report to ..." + +# The plugins below are listed with their default values of +# verbose/user_submission, but those are not necessary to provide. + +# The default Email bug reporter. By default, the standard +# configuration is taken from your galaxy.ini +- type: email + verbose: true + user_submission: true + +# Example JSON bug reporter implementation. This just writes the bug +# report as a JSON file to a specified directory and serves as an +# example for others to extend. +# - type: json +# verbose: true +# user_submission: true +# directory: /tmp/reports/ + +# Submit error reports to sentry. If a sentry_dsn is configured in your +# galaxy.ini, then Galaxy will submit the job error to Sentry. +- type: sentry + user_submission: false + +# Allow users to submit error reports to biostars. This requires that the +# biostars integration is configured. This *only* makes sense when +# user_submission is true, as it only generates the link for the user to click +# on and submit the bug report, it does not actually submit the bug report on +# their behalf. +# - type: biostars +# user_submission: true diff --git a/config/tool_conf.xml.sample b/config/tool_conf.xml.sample index b8b98a82d77..2232fe2b3e2 100644 --- a/config/tool_conf.xml.sample +++ b/config/tool_conf.xml.sample @@ -38,6 +38,7 @@ +
diff --git a/config/user_preferences_extra_conf.yml.sample b/config/user_preferences_extra_conf.yml.sample new file mode 100644 index 00000000000..8f8ef07670a --- /dev/null +++ b/config/user_preferences_extra_conf.yml.sample @@ -0,0 +1,41 @@ +preferences: + # the key you can refer to + apollo_url_01: + # description that is displayed to the user + description: The URL to your personal Apollo instance + inputs: + # the content can be accessed by apollo_url_01.apollo_url + - name: apollo_url + label: Apollo URL + # type of input field that will be displayed to the user + # can be string or password + type: text + # by defaul all inputs are required + required: True + - name: apollo_text + label: Apollo Text + # type of input field that will be displayed to the user + # can be string or password + type: text + # by defaul all inputs are required + required: True + + openstack_account: + description: Your own Open Stack account + inputs: + - name: username + label: Username + type: text + required: False + - name: url + label: Open Stack URL + type: text + required: True + + webhook_overlay_search: + description: Configuration option for your search results + inputs: + - name: max_search_results + label: Maximum number of search results + type: text + required: False diff --git a/doc/source/admin/special_topics/bug_reports.rst b/doc/source/admin/special_topics/bug_reports.rst new file mode 100644 index 00000000000..f2a6f79fe78 --- /dev/null +++ b/doc/source/admin/special_topics/bug_reports.rst @@ -0,0 +1,72 @@ +Bug Reports +=========== + +In 17.09, bug reports were refactored to a plugin-type infrastructure. This +gives the administrator more control over how and when bug reports are +generated. In the past, email reports would be generated when the user clicks +the button and only then. Sentry reports would be generated for every failing +tool, as soon as the tool failed. This disparate behaviour was unified under a +single configuration file, ``config/error_report.xml.sample``. + +Let's look at that briefly: + +.. code-block:: xml + + + + + + + + +The actual configuration file contains more documentation which has been +stripped out here for the sake of brevity. As you can see, there are a couple of +different plugins that already exist. Additionally, there are some options that +are common to all plugins: + +``user_submission`` + When true, this action is triggered only when the user is on the job error + page and clicks "submit bug report". + + When false, this action is triggered *any* time a job errors, without user + involvement + +``verbose`` + When ``user_submission=True``, and ``verbose=True``, this indicates that a + message is to be displayed to the end user. For example, the email plugin will + inform the user that a mail has been sent. Or the JSON plugin will inform the + user that a file has been written to a specific directory. + +Email +----- + +This is the classic bug-report mechanism that we are all familiar with. It +generates an email to the admin and the submitting user containing detailed +information about the job and links to the precise locations within Galaxy. + +As a plugin, nothing has changed to this functionality, though future updates +may add features. It currently takes all of its configuration from your +``$GALAXY/config/galaxy.ini``, e.g. the variables ``error_email_to`` and +``email_from``. + +JSON +---- + +This is a demo-plugin that writes the contents of the error report to a file in +your temp directory. This just serves as a full-featured reference +implementation that others can use to build their own bug reporting plugins. + +When ``verbose="true" user_submission="true"``, the plugin will inform the user +that a report has been written to ``/tmp/``. + +Sentry +------ + +This refactors the existing on-failure submit-to-sentry behaviour into a bug +reporting plugin. Now, for example, you are able to disable the automatic +submission to sentry and only run that whenever the user reports it. + +When ``verbose="true" user_submission="true"``, the plugin will inform the user +that ``Submitted bug report to Sentry. Your guru meditation number is +dc907d44ce294f78b267a56f68e5cd1a``, using the same phrasing that is common to +users from Galaxy internal server errors. diff --git a/doc/source/admin/special_topics/index.rst b/doc/source/admin/special_topics/index.rst index b3cf8f7aa9a..0abc9e283f5 100644 --- a/doc/source/admin/special_topics/index.rst +++ b/doc/source/admin/special_topics/index.rst @@ -11,3 +11,4 @@ Special Topics chat webhooks performance_tracking + bug_reports diff --git a/lib/galaxy/app.py b/lib/galaxy/app.py index b735e8de8ba..74505ed2c18 100644 --- a/lib/galaxy/app.py +++ b/lib/galaxy/app.py @@ -27,6 +27,7 @@ from galaxy.tools.cache import ( ToolShedRepositoryCache ) from galaxy.jobs import metrics as job_metrics +from galaxy.tools.error_reports import ErrorReports from galaxy.web.proxy import ProxyManager from galaxy.web.stack import application_stack_instance from galaxy.queue_worker import GalaxyQueueWorker @@ -102,6 +103,9 @@ class UniverseApplication( object, config.ConfiguresGalaxyMixin ): # config so per-destination modifications can be made. self.job_metrics = job_metrics.JobMetrics( self.config.job_metrics_config_file, app=self ) + # Initialize error report plugins. + self.error_reports = ErrorReports( self.config.error_report_file, app=self ) + # Initialize the job management configuration self.job_config = jobs.JobConfiguration(self) diff --git a/lib/galaxy/config.py b/lib/galaxy/config.py index 672fc662188..221ddcf0b6d 100644 --- a/lib/galaxy/config.py +++ b/lib/galaxy/config.py @@ -43,6 +43,7 @@ PATH_DEFAULTS = dict( job_config_file=['config/job_conf.xml', 'job_conf.xml'], tool_destinations_config_file=['config/tool_destinations.yml', 'config/tool_destinations.yml.sample'], job_metrics_config_file=['config/job_metrics_conf.xml', 'job_metrics_conf.xml', 'config/job_metrics_conf.xml.sample'], + error_report_file=['config/error_report.yml', 'config/error_report.yml.sample'], dependency_resolvers_config_file=['config/dependency_resolvers_conf.xml', 'dependency_resolvers_conf.xml'], job_resource_params_file=['config/job_resource_params_conf.xml', 'job_resource_params_conf.xml'], migrated_tools_config=['migrated_tools_conf.xml', 'config/migrated_tools_conf.xml'], @@ -54,6 +55,7 @@ PATH_DEFAULTS = dict( workflow_schedulers_config_file=['config/workflow_schedulers_conf.xml', 'config/workflow_schedulers_conf.xml.sample'], modules_mapping_files=['config/environment_modules_mapping.yml', 'config/environment_modules_mapping.yml.sample'], local_conda_mapping_file=['config/local_conda_mapping.yml', 'config/local_conda_mapping.yml.sample'], + user_preferences_extra_config_file=[ 'config/user_preferences_extra_conf.yml' ], containers_config_file=['config/containers_conf.yml'], ) diff --git a/lib/galaxy/datatypes/interval.py b/lib/galaxy/datatypes/interval.py index 658d767af3a..5b67e9ea0fe 100644 --- a/lib/galaxy/datatypes/interval.py +++ b/lib/galaxy/datatypes/interval.py @@ -13,7 +13,10 @@ from six.moves.urllib.parse import quote_plus from galaxy import util from galaxy.datatypes import metadata from galaxy.datatypes.metadata import MetadataElement -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import ( + get_headers, + iter_headers +) from galaxy.datatypes.tabular import Tabular from galaxy.datatypes.util.gff_util import parse_gff3_attributes, parse_gff_attributes from galaxy.web import url_for @@ -313,12 +316,12 @@ class Interval( Tabular ): >>> Interval().sniff( fname ) True """ - headers = get_headers( filename, '\t', comment_designator='#' ) try: """ If we got here, we already know the file is_column_based and is not bed, so we'll just look for some valid data. """ + headers = iter_headers( filename, '\t', comment_designator='#' ) for hdr in headers: if hdr: if len(hdr) < 3: @@ -489,10 +492,10 @@ class Bed( Interval ): >>> Bed().sniff( fname ) True """ - headers = get_headers( filename, '\t', comment_designator='#' ) + if not get_headers( filename, '\t', comment_designator='#', count=1 ): + return False try: - if not headers: - return False + headers = iter_headers( filename, '\t', comment_designator='#' ) for hdr in headers: if hdr[0] == '': continue @@ -832,10 +835,10 @@ class Gff( Tabular, _RemoteCallMixin ): >>> Gff().sniff( fname ) True """ - headers = get_headers( filename, '\t' ) + if len(get_headers( filename, '\t', count=2 )) < 2: + return False try: - if len(headers) < 2: - return False + headers = iter_headers( filename, '\t' ) for hdr in headers: if hdr and hdr[0].startswith( '##gff-version' ) and hdr[0].find( '2' ) < 0: return False @@ -964,10 +967,10 @@ class Gff3( Gff ): >>> Gff3().sniff( fname ) True """ - headers = get_headers( filename, '\t' ) + if len(get_headers( filename, '\t', count=2 )) < 2: + return False try: - if len(headers) < 2: - return False + headers = iter_headers( filename, '\t' ) for hdr in headers: if hdr and hdr[0].startswith( '##gff-version' ) and hdr[0].find( '3' ) >= 0: return True @@ -1039,10 +1042,10 @@ class Gtf( Gff ): >>> Gtf().sniff( fname ) True """ - headers = get_headers( filename, '\t' ) + if len(get_headers( filename, '\t', count=2 )) < 2: + return False try: - if len(headers) < 2: - return False + headers = iter_headers( filename, '\t' ) for hdr in headers: if hdr and hdr[0].startswith( '##gff-version' ) and hdr[0].find( '2' ) < 0: return False @@ -1235,8 +1238,8 @@ class Wiggle( Tabular, _RemoteCallMixin ): >>> Wiggle().sniff( fname ) True """ - headers = get_headers( filename, None ) try: + headers = iter_headers( filename, None ) for hdr in headers: if len(hdr) > 1 and hdr[0] == 'track' and hdr[1].startswith('type=wiggle'): return True @@ -1371,7 +1374,7 @@ class CustomTrack ( Tabular ): >>> CustomTrack().sniff( fname ) True """ - headers = get_headers( filename, None ) + headers = iter_headers( filename, None ) first_line = True for hdr in headers: if first_line: diff --git a/lib/galaxy/datatypes/molecules.py b/lib/galaxy/datatypes/molecules.py index 703e143e6c8..bfacad3c169 100644 --- a/lib/galaxy/datatypes/molecules.py +++ b/lib/galaxy/datatypes/molecules.py @@ -10,7 +10,10 @@ from galaxy.datatypes import ( from galaxy.datatypes.binary import Binary from galaxy.datatypes.data import get_file_peek from galaxy.datatypes.metadata import MetadataElement -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import ( + get_headers, + iter_headers +) from galaxy.datatypes.tabular import Tabular from galaxy.datatypes.xml import GenericXml @@ -461,7 +464,7 @@ class PDB(GenericMolFile): >>> PDB().sniff(fname) False """ - headers = get_headers(filename, sep=' ', count=300) + headers = iter_headers(filename, sep=' ', count=300) h = t = c = s = k = e = False for line in headers: section_name = line[0].strip() @@ -514,7 +517,7 @@ class PDBQT(GenericMolFile): >>> PDBQT().sniff(fname) False """ - headers = get_headers(filename, sep=' ', count=300) + headers = iter_headers(filename, sep=' ', count=300) h = t = c = s = k = False for line in headers: section_name = line[0].strip() @@ -607,7 +610,7 @@ class InChI(Tabular): >>> InChI().sniff(fname) False """ - inchi_lines = get_headers(filename, sep=' ', count=10) + inchi_lines = iter_headers(filename, sep=' ', count=10) for inchi in inchi_lines: if not inchi[0].startswith('InChI='): return False diff --git a/lib/galaxy/datatypes/mothur.py b/lib/galaxy/datatypes/mothur.py index c6a6ce44cb1..75bb29be8c2 100644 --- a/lib/galaxy/datatypes/mothur.py +++ b/lib/galaxy/datatypes/mothur.py @@ -7,7 +7,10 @@ import sys from galaxy.datatypes.data import Text from galaxy.datatypes.metadata import MetadataElement -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import ( + get_headers, + iter_headers +) from galaxy.datatypes.tabular import Tabular log = logging.getLogger(__name__) @@ -32,10 +35,11 @@ class Otu(Text): data_lines = 0 comment_lines = 0 - headers = get_headers(dataset.file_name, sep='\t', count=-1) + headers = iter_headers(dataset.file_name, sep='\t', count=-1) + first_line = get_headers(dataset.file_name, sep='\t', count=1) # set otulabels - if len(headers[0]) > 2: - otulabel_names = headers[0][2:] + if len(first_line) > 2: + otulabel_names = first_line[2:] # set label names and number of lines for line in headers: if len(line) >= 2 and not line[0].startswith('@'): @@ -64,7 +68,7 @@ class Otu(Text): >>> Otu().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@'): @@ -109,7 +113,7 @@ class Sabund(Otu): >>> Sabund().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@'): @@ -151,7 +155,7 @@ class GroupAbund(Otu): comment_lines = 0 ncols = 0 - headers = get_headers(dataset.file_name, sep='\t', count=-1) + headers = iter_headers(dataset.file_name, sep='\t', count=-1) for line in headers: if line[0] == 'label' and line[1] == 'Group': skip = 1 @@ -187,7 +191,7 @@ class GroupAbund(Otu): >>> GroupAbund().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@'): @@ -234,7 +238,7 @@ class SecondaryStructureMap(Tabular): >>> SecondaryStructureMap().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') line_num = 0 rowidxmap = {} for line in headers: @@ -302,7 +306,7 @@ class DistanceMatrix(Text): def set_meta(self, dataset, overwrite=True, skip=0, **kwd): super(DistanceMatrix, self).set_meta(dataset, overwrite=overwrite, skip=skip, **kwd) - headers = get_headers(dataset.file_name, sep='\t') + headers = iter_headers(dataset.file_name, sep='\t') for line in headers: if not line[0].startswith('@'): try: @@ -344,7 +348,7 @@ class LowerTriangleDistanceMatrix(DistanceMatrix): False """ numlines = 300 - headers = get_headers(filename, sep='\t', count=numlines) + headers = iter_headers(filename, sep='\t', count=numlines) line_num = 0 for line in headers: if not line[0].startswith('@'): @@ -405,7 +409,7 @@ class SquareDistanceMatrix(DistanceMatrix): False """ numlines = 300 - headers = get_headers(filename, sep='\t', count=numlines) + headers = iter_headers(filename, sep='\t', count=numlines) line_num = 0 for line in headers: if not line[0].startswith('@'): @@ -461,7 +465,7 @@ class PairwiseDistanceMatrix(DistanceMatrix, Tabular): >>> PairwiseDistanceMatrix().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@'): @@ -525,7 +529,7 @@ class Group(Tabular): super(Group, self).set_meta(dataset, overwrite, skip, max_data_lines) group_names = set() - headers = get_headers(dataset.file_name, sep='\t', count=-1) + headers = iter_headers(dataset.file_name, sep='\t', count=-1) for line in headers: if len(line) > 1: group_names.add(line[1]) @@ -558,7 +562,7 @@ class Oligos(Text): >>> Oligos().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@') and not line[0].startswith('#'): @@ -602,7 +606,7 @@ class Frequency(Tabular): >>> Frequency().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@'): @@ -653,7 +657,7 @@ class Quantile(Tabular): >>> Quantile().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 for line in headers: if not line[0].startswith('@') and not line[0].startswith('#'): @@ -691,7 +695,7 @@ class LaneMask(Text): >>> LaneMask().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = get_headers(filename, sep='\t', count=2) if len(headers) != 1 or len(headers[0]) != 1: return False @@ -774,7 +778,7 @@ class RefTaxonomy(Tabular): >>> RefTaxonomy().sniff( fname ) False """ - headers = get_headers(filename, sep='\t', count=300) + headers = iter_headers(filename, sep='\t', count=300) count = 0 pat_prog = re.compile('^([^ \t\n\r\x0c\x0b;]+([(]\\d+[)])?(;[^ \t\n\r\x0c\x0b;]+([(]\\d+[)])?)*(;)?)$') found_semicolons = False @@ -849,7 +853,7 @@ class Axes(Tabular): >>> Axes().sniff( fname ) False """ - headers = get_headers(filename, sep='\t') + headers = iter_headers(filename, sep='\t') count = 0 col_cnt = None all_integers = True diff --git a/lib/galaxy/datatypes/sequence.py b/lib/galaxy/datatypes/sequence.py index b3c4f65f2ba..ee0a646cc73 100644 --- a/lib/galaxy/datatypes/sequence.py +++ b/lib/galaxy/datatypes/sequence.py @@ -9,6 +9,7 @@ import re import string import sys from cgi import escape +from itertools import islice import bx.align.maf @@ -16,7 +17,10 @@ from galaxy import util from galaxy.datatypes import metadata from galaxy.datatypes.binary import Binary from galaxy.datatypes.metadata import MetadataElement -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import ( + get_headers, + iter_headers +) from galaxy.util import ( compression_utils, nice_size @@ -611,7 +615,7 @@ class BaseFastq ( Sequence ): compressed = is_gzip(filename) or is_bz2(filename) if compressed and not isinstance(self, Binary): return False - headers = get_headers( filename, None, count=1000 ) + headers = iter_headers( filename, None, count=1000 ) # If this is a FastqSanger-derived class, then check to see if the base qualities match if isinstance(self, FastqSanger) or isinstance(self, FastqSangerGz) or isinstance(self, FastqSangerBz2): @@ -621,7 +625,8 @@ class BaseFastq ( Sequence ): bases_regexp = re.compile( "^[NGTAC]*" ) # check that first block looks like a fastq block try: - if len( headers ) >= 4 and headers[0][0] and headers[0][0][0] == "@" and headers[2][0] and headers[2][0][0] == "+" and headers[1][0]: + headers = get_headers( filename, None, count=4 ) + if len( headers ) == 4 and headers[0][0] and headers[0][0][0] == "@" and headers[2][0] and headers[2][0][0] == "+" and headers[1][0]: # Check the sequence line, make sure it contains only G/C/A/T/N if not bases_regexp.match( headers[1][0] ): return False @@ -695,7 +700,7 @@ class BaseFastq ( Sequence ): @staticmethod def sangerQualities( lines ): """Presuming lines are lines from a fastq file, return True if the qualities are compatible with sanger encoding""" - for line in lines[3::4]: + for line in islice(lines, 3, None, 4): if not all(_ >= '!' and _ <= 'M' for _ in line[0]): return False return True diff --git a/lib/galaxy/datatypes/sniff.py b/lib/galaxy/datatypes/sniff.py index 4e1aa31b223..f2e0ea6e07a 100644 --- a/lib/galaxy/datatypes/sniff.py +++ b/lib/galaxy/datatypes/sniff.py @@ -200,19 +200,7 @@ def convert_newlines_sep2tabs( fname, in_place=True, patt="\\s+", tmp_dir=None, return ( i + 1, temp_name ) -def get_headers( fname, sep, count=60, is_multi_byte=False, comment_designator=None ): - """ - Returns a list with the first 'count' lines split by 'sep', ignoring lines - starting with 'comment_designator' - - >>> fname = get_test_fname('complete.bed') - >>> get_headers(fname,'\\t') - [['chr7', '127475281', '127491632', 'NM_000230', '0', '+', '127486022', '127488767', '0', '3', '29,172,3225,', '0,10713,13126,'], ['chr7', '127486011', '127488900', 'D49487', '0', '+', '127486022', '127488767', '0', '2', '155,490,', '0,2399']] - >>> fname = get_test_fname('test.gff') - >>> get_headers(fname, '\\t', count=5, comment_designator='#') - [[''], ['chr7', 'bed2gff', 'AR', '26731313', '26731437', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731491', '26731536', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731541', '26731649', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731659', '26731841', '.', '+', '.', 'score']] - """ - headers = [] +def iter_headers( fname, sep, count=60, is_multi_byte=False, comment_designator=None ): with compression_utils.get_fileobj(fname) as in_file: idx = 0 for line in in_file: @@ -225,11 +213,25 @@ def get_headers( fname, sep, count=60, is_multi_byte=False, comment_designator=N comment_designator = comment_designator.encode( 'utf-8' ) if comment_designator is not None and comment_designator != '' and line.startswith( comment_designator ): continue - headers.append( line.split(sep) ) + yield line.split(sep) idx += 1 if idx == count: break - return headers + + +def get_headers( fname, sep, count=60, is_multi_byte=False, comment_designator=None ): + """ + Returns a list with the first 'count' lines split by 'sep', ignoring lines + starting with 'comment_designator' + + >>> fname = get_test_fname('complete.bed') + >>> get_headers(fname,'\\t') + [['chr7', '127475281', '127491632', 'NM_000230', '0', '+', '127486022', '127488767', '0', '3', '29,172,3225,', '0,10713,13126,'], ['chr7', '127486011', '127488900', 'D49487', '0', '+', '127486022', '127488767', '0', '2', '155,490,', '0,2399']] + >>> fname = get_test_fname('test.gff') + >>> get_headers(fname, '\\t', count=5, comment_designator='#') + [[''], ['chr7', 'bed2gff', 'AR', '26731313', '26731437', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731491', '26731536', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731541', '26731649', '.', '+', '.', 'score'], ['chr7', 'bed2gff', 'AR', '26731659', '26731841', '.', '+', '.', 'score']] + """ + return list(iter_headers(fname=fname, sep=sep, count=count, is_multi_byte=is_multi_byte, comment_designator=comment_designator)) def is_column_based( fname, sep='\t', skip=0, is_multi_byte=False ): diff --git a/lib/galaxy/datatypes/tabular.py b/lib/galaxy/datatypes/tabular.py index fbcba2b43a9..5b8e568b0b4 100644 --- a/lib/galaxy/datatypes/tabular.py +++ b/lib/galaxy/datatypes/tabular.py @@ -8,6 +8,7 @@ import csv import logging import os import re +import shutil import subprocess import sys import tempfile @@ -15,9 +16,12 @@ from cgi import escape from json import dumps from galaxy import util -from galaxy.datatypes import data, metadata +from galaxy.datatypes import binary, data, metadata from galaxy.datatypes.metadata import MetadataElement -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import ( + get_headers, + iter_headers +) from galaxy.util import compression_utils from . import dataproviders @@ -62,7 +66,7 @@ class TabularData( data.Text ): return False def get_chunk(self, trans, dataset, offset=0, ck_size=None): - with open(dataset.file_name) as f: + with compression_utils.get_fileobj(dataset.file_name) as f: f.seek(offset) ck_data = f.read(ck_size or trans.app.config.display_chunk_size) if ck_data and ck_data[-1] != '\n': @@ -325,49 +329,48 @@ class Tabular( TabularData ): first_line_column_types = [default_column_type] # default value is one column of type str if dataset.has_data(): # NOTE: if skip > num_check_lines, we won't detect any metadata, and will use default - dataset_fh = open( dataset.file_name ) - i = 0 - while True: - line = dataset_fh.readline() - if not line: - break - line = line.rstrip( '\r\n' ) - if i < skip or not line or line.startswith( '#' ): - # We'll call blank lines comments - comment_lines += 1 - else: - data_lines += 1 - if max_guess_type_data_lines is None or data_lines <= max_guess_type_data_lines: - fields = line.split( '\t' ) - for field_count, field in enumerate( fields ): - if field_count >= len( column_types ): # found a previously unknown column, we append None - column_types.append( None ) - column_type = guess_column_type( field ) - if type_overrules_type( column_type, column_types[field_count] ): - column_types[field_count] = column_type - if i == 0 and requested_skip is None: - # This is our first line, people seem to like to upload files that have a header line, but do not - # start with '#' (i.e. all column types would then most likely be detected as str). We will assume - # that the first line is always a header (this was previous behavior - it was always skipped). When - # the requested skip is None, we only use the data from the first line if we have no other data for - # a column. This is far from perfect, as - # 1,2,3 1.1 2.2 qwerty - # 0 0 1,2,3 - # will be detected as - # "column_types": ["int", "int", "float", "list"] - # instead of - # "column_types": ["list", "float", "float", "str"] *** would seem to be the 'Truth' by manual - # observation that the first line should be included as data. The old method would have detected as - # "column_types": ["int", "int", "str", "list"] - first_line_column_types = column_types - column_types = [ None for col in first_line_column_types ] - if max_data_lines is not None and data_lines >= max_data_lines: - if dataset_fh.tell() != dataset.get_size(): - data_lines = None # Clear optional data_lines metadata value - comment_lines = None # Clear optional comment_lines metadata value; additional comment lines could appear below this point - break - i += 1 - dataset_fh.close() + with compression_utils.get_fileobj(dataset.file_name) as dataset_fh: + i = 0 + while True: + line = dataset_fh.readline() + if not line: + break + line = line.rstrip( '\r\n' ) + if i < skip or not line or line.startswith( '#' ): + # We'll call blank lines comments + comment_lines += 1 + else: + data_lines += 1 + if max_guess_type_data_lines is None or data_lines <= max_guess_type_data_lines: + fields = line.split( '\t' ) + for field_count, field in enumerate( fields ): + if field_count >= len( column_types ): # found a previously unknown column, we append None + column_types.append( None ) + column_type = guess_column_type( field ) + if type_overrules_type( column_type, column_types[field_count] ): + column_types[field_count] = column_type + if i == 0 and requested_skip is None: + # This is our first line, people seem to like to upload files that have a header line, but do not + # start with '#' (i.e. all column types would then most likely be detected as str). We will assume + # that the first line is always a header (this was previous behavior - it was always skipped). When + # the requested skip is None, we only use the data from the first line if we have no other data for + # a column. This is far from perfect, as + # 1,2,3 1.1 2.2 qwerty + # 0 0 1,2,3 + # will be detected as + # "column_types": ["int", "int", "float", "list"] + # instead of + # "column_types": ["list", "float", "float", "str"] *** would seem to be the 'Truth' by manual + # observation that the first line should be included as data. The old method would have detected as + # "column_types": ["int", "int", "str", "list"] + first_line_column_types = column_types + column_types = [ None for col in first_line_column_types ] + if max_data_lines is not None and data_lines >= max_data_lines: + if dataset_fh.tell() != dataset.get_size(): + data_lines = None # Clear optional data_lines metadata value + comment_lines = None # Clear optional comment_lines metadata value; additional comment lines could appear below this point + break + i += 1 # we error on the larger number of columns # first we pad our column_types by using data from first line @@ -638,7 +641,7 @@ class Pileup( Tabular ): >>> Pileup().sniff( fname ) True """ - headers = get_headers( filename, '\t' ) + headers = iter_headers( filename, '\t' ) try: for hdr in headers: if hdr and not hdr[0].startswith( '#' ): @@ -670,7 +673,7 @@ class Pileup( Tabular ): @dataproviders.decorators.has_dataproviders -class Vcf( Tabular ): +class BaseVcf( Tabular ): """ Variant Call Format for describing SNPs and other simple genome variations. """ edam_format = "format_3016" track_type = "VariantTrack" @@ -693,7 +696,7 @@ class Vcf( Tabular ): return self.make_html_table( dataset, column_names=self.column_names ) def set_meta( self, dataset, **kwd ): - super( Vcf, self ).set_meta( dataset, **kwd ) + super( BaseVcf, self ).set_meta( dataset, **kwd ) source = open( dataset.file_name ) # Skip comments. @@ -732,6 +735,46 @@ class Vcf( Tabular ): return self.genomic_region_dataprovider( dataset, **settings ) +class Vcf ( BaseVcf ): + extension = 'vcf' + + +class VcfGz( BaseVcf, binary.Binary): + extension = 'vcf.gz' + compressed = True + + MetadataElement( name="tabix_index", desc="Vcf Index File", param=metadata.FileParameter, file_ext="tbi", readonly=True, no_value=None, visible=False, optional=True ) + + def set_meta( self, dataset, **kwd ): + super(BaseVcf, self).set_meta(dataset, **kwd) + """ Creates the index for the VCF file. """ + # These metadata values are not accessible by users, always overwrite + index_file = dataset.metadata.bcf_index + if not index_file: + index_file = dataset.metadata.spec['tabix_index'].param.new_file( dataset=dataset ) + # Create the bcf index + # $ bcftools index + # Usage: bcftools index + + dataset_symlink = os.path.join( os.path.dirname( index_file.file_name ), + '__dataset_%d_%s' % ( dataset.id, os.path.basename( index_file.file_name ) ) ) + ".vcf.gz" + os.symlink( dataset.file_name, dataset_symlink ) + + stderr_name = tempfile.NamedTemporaryFile( prefix="bcf_index_stderr" ).name + command = [ 'bcftools', 'index', '-t', dataset_symlink ] + try: + subprocess.check_call( args=command, stderr=open( stderr_name, 'wb' ) ) + shutil.move( dataset_symlink + '.tbi', index_file.file_name ) # this will fail if bcftools < 1.0 is used, because it creates a .bci index file instead of .csi + except Exception as e: + stderr = open( stderr_name ).read().strip() + raise Exception('Error setting BCF metadata: %s' % (stderr or str(e))) + finally: + # Remove temp file and symlink + os.remove( stderr_name ) + os.remove( dataset_symlink ) + dataset.metadata.tabix_index = index_file + + class Eland( Tabular ): """Support for the export.txt.gz file used by Illumina's ELANDv2e aligner""" file_ext = '_export.txt.gz' diff --git a/lib/galaxy/datatypes/text.py b/lib/galaxy/datatypes/text.py index bffb3ad24bc..22b8ca8db11 100644 --- a/lib/galaxy/datatypes/text.py +++ b/lib/galaxy/datatypes/text.py @@ -12,7 +12,7 @@ import tempfile from galaxy.datatypes.data import get_file_peek, Text from galaxy.datatypes.metadata import MetadataElement, MetadataParameter -from galaxy.datatypes.sniff import get_headers +from galaxy.datatypes.sniff import iter_headers from galaxy.util import nice_size, string_as_bool log = logging.getLogger(__name__) @@ -47,7 +47,7 @@ class Html( Text ): >>> Html().sniff( fname ) True """ - headers = get_headers( filename, None ) + headers = iter_headers( filename, None ) try: for i, hdr in enumerate(headers): if hdr and hdr[0].lower().find( '' ) >= 0: diff --git a/lib/galaxy/jobs/__init__.py b/lib/galaxy/jobs/__init__.py index a29244ec283..f3fb280d3a0 100644 --- a/lib/galaxy/jobs/__init__.py +++ b/lib/galaxy/jobs/__init__.py @@ -1028,7 +1028,7 @@ class JobWrapper( object, HasResourceParameters ): # the partial files to the object store regardless of whether job.state == DELETED self.__update_output(job, dataset, clean_only=True) - self._report_error_to_sentry() + self._report_error() # Perform email action even on failure. for pja in [pjaa.post_job_action for pjaa in job.post_job_actions if pjaa.post_job_action.action_type == "EmailAction"]: ActionBox.execute(self.app, self.sa_session, pja, job) @@ -1437,7 +1437,7 @@ class JobWrapper( object, HasResourceParameters ): self.sa_session.flush() log.debug( 'job %d ended (finish() executed in %s)' % (self.job_id, finish_timer) ) if job.state == job.states.ERROR: - self._report_error_to_sentry() + self._report_error() cleanup_job = self.cleanup_job delete_files = cleanup_job == 'always' or ( job.state == job.states.OK and cleanup_job == 'onsuccess' ) self.cleanup( delete_files=delete_files ) @@ -1809,27 +1809,11 @@ class JobWrapper( object, HasResourceParameters ): return self.tool.requires_setting_metadata return False - def _report_error_to_sentry( self ): + def _report_error( self ): job = self.get_job() tool = self.app.toolbox.get_tool(job.tool_id, tool_version=job.tool_version) or None - if self.app.sentry_client and job.state == job.states.ERROR: - self.app.sentry_client.capture( - 'raven.events.Message', - message="Galaxy Job Error: %s v.%s" % (job.tool_id, job.tool_version), - extra={ - 'info' : job.info, - 'id' : job.id, - 'command_line' : job.command_line, - 'stderr' : job.stderr, - 'traceback': job.traceback, - 'exit_code': job.exit_code, - 'stdout': job.stdout, - 'handler': job.handler, - 'user': self.user, - 'tool_version': job.tool_version, - 'tool_xml': tool.config_file if tool else None - } - ) + for dataset in job.output_datasets: + self.app.error_reports.default_error_plugin.submit_report(dataset, job, tool, user_submission=False) class TaskWrapper(JobWrapper): diff --git a/lib/galaxy/jobs/command_factory.py b/lib/galaxy/jobs/command_factory.py index 89646105984..24bb50e78bf 100644 --- a/lib/galaxy/jobs/command_factory.py +++ b/lib/galaxy/jobs/command_factory.py @@ -66,8 +66,13 @@ def build_command( if not commands_builder.commands: return None + # Version, dependency resolution, and task splitting are prepended to the + # command - so they need to appear in the following order to ensure that + # the underlying application used by version command is available in the + # environment after dependency resolution, but the task splitting command + # is still executed in Galaxy's Python environment. + __handle_version_command(commands_builder, job_wrapper) - __handle_task_splitting(commands_builder, job_wrapper) # One could imagine also allowing dependencies inside of the container but # that is too sophisticated for a first crack at this - build your @@ -75,6 +80,8 @@ def build_command( if not container or container.resolve_dependencies: __handle_dependency_resolution(commands_builder, job_wrapper, remote_command_params) + __handle_task_splitting(commands_builder, job_wrapper) + if (container and modify_command_for_container) or job_wrapper.commands_in_new_shell: if container and modify_command_for_container: # Many Docker containers do not have /bin/bash. diff --git a/lib/galaxy/managers/tags.py b/lib/galaxy/managers/tags.py index 989f5185ffd..6ac8d852863 100644 --- a/lib/galaxy/managers/tags.py +++ b/lib/galaxy/managers/tags.py @@ -324,6 +324,10 @@ class GalaxyTagManager( TagManager ): ItemTagAssocInfo( model.HistoryDatasetCollectionAssociation, model.HistoryDatasetCollectionTagAssociation, model.HistoryDatasetCollectionTagAssociation.table.c.history_dataset_collection_id ) + self.item_tag_assoc_info["LibraryDatasetDatasetAssociation"] = \ + ItemTagAssocInfo( model.LibraryDatasetDatasetAssociation, + model.LibraryDatasetDatasetAssociationTagAssociation, + model.LibraryDatasetDatasetAssociationTagAssociation.table.c.library_dataset_dataset_association_id ) self.item_tag_assoc_info["Page"] = ItemTagAssocInfo( model.Page, model.PageTagAssociation, model.PageTagAssociation.table.c.page_id ) diff --git a/lib/galaxy/managers/workflows.py b/lib/galaxy/managers/workflows.py index 0339ec882ae..fa280f1be87 100644 --- a/lib/galaxy/managers/workflows.py +++ b/lib/galaxy/managers/workflows.py @@ -373,7 +373,7 @@ class WorkflowContentsManager(UsesAnnotations): step_model = None if step.type == 'tool': incoming = {} - tool = trans.app.toolbox.get_tool( step.tool_id ) + tool = trans.app.toolbox.get_tool( step.tool_id, tool_version=step.tool_version ) params_to_incoming( incoming, tool.inputs, step.state.inputs, trans.app ) step_model = tool.to_json( trans, incoming, workflow_building_mode=workflow_building_modes.USE_HISTORY ) step_model[ 'post_job_actions' ] = [{ diff --git a/lib/galaxy/model/__init__.py b/lib/galaxy/model/__init__.py index 56a70f6306c..a49d1a6d9ed 100644 --- a/lib/galaxy/model/__init__.py +++ b/lib/galaxy/model/__init__.py @@ -28,6 +28,8 @@ import galaxy.model.metadata import galaxy.model.orm.now import galaxy.security.passwords import galaxy.util + +from galaxy.managers import tags from galaxy.model.item_attrs import UsesAnnotations from galaxy.model.util import pgcalc from galaxy.security import get_permitted_actions @@ -2470,6 +2472,7 @@ class HistoryDatasetAssociation( DatasetInstance, HasTags, Dictifiable, UsesAnno trans.sa_session.flush() # Must set metadata after ldda flushed, as MetadataFiles require ldda.id ldda.metadata = self.metadata + # TODO: copy #tags from history if ldda_message: ldda.message = ldda_message if not replace_dataset: @@ -2934,6 +2937,11 @@ class LibraryDatasetDatasetAssociation( DatasetInstance, HasName ): parent_id=parent_id, copied_from_library_dataset_dataset_association=self, history=target_history ) + + tag_manager = tags.GalaxyTagManager( sa_session ) + src_ldda_tags = tag_manager.get_tags_str(self.tags) + tag_manager.apply_item_tags( user=self.user, item=hda, tags_str=src_ldda_tags ) + sa_session.add( hda ) sa_session.flush() hda.metadata = self.metadata # need to set after flushed, as MetadataFiles require dataset.id @@ -2961,6 +2969,11 @@ class LibraryDatasetDatasetAssociation( DatasetInstance, HasName ): parent_id=parent_id, copied_from_library_dataset_dataset_association=self, folder=target_folder ) + + tag_manager = tags.GalaxyTagManager( sa_session ) + src_ldda_tags = tag_manager.get_tags_str(self.tags) + tag_manager.apply_item_tags( user=self.user, item=ldda, tags_str=src_ldda_tags ) + sa_session.add( ldda ) sa_session.flush() # Need to set after flushed, as MetadataFiles require dataset.id @@ -3009,6 +3022,7 @@ class LibraryDatasetDatasetAssociation( DatasetInstance, HasName ): except OSError: file_size = 0 + # TODO: render tags here rval = dict( id=ldda.id, hda_ldda='ldda', model_class=self.__class__.__name__, @@ -5143,6 +5157,10 @@ class HistoryDatasetAssociationTagAssociation ( ItemTagAssociation ): pass +class LibraryDatasetDatasetAssociationTagAssociation ( ItemTagAssociation ): + pass + + class PageTagAssociation ( ItemTagAssociation ): pass diff --git a/lib/galaxy/model/mapping.py b/lib/galaxy/model/mapping.py index 5388fc6524c..864441eb405 100644 --- a/lib/galaxy/model/mapping.py +++ b/lib/galaxy/model/mapping.py @@ -1213,6 +1213,16 @@ model.HistoryDatasetAssociationTagAssociation.table = Table( Column( "value", TrimmedString( 255 ), index=True ), Column( "user_value", TrimmedString( 255 ), index=True ) ) +model.LibraryDatasetDatasetAssociationTagAssociation.table = Table( + "library_dataset_dataset_association_tag_association", metadata, + Column( "id", Integer, primary_key=True ), + Column( "library_dataset_dataset_association_id", Integer, ForeignKey( "library_dataset_dataset_association.id" ), index=True ), + Column( "tag_id", Integer, ForeignKey( "tag.id" ), index=True ), + Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True ), + Column( "user_tname", TrimmedString(255), index=True ), + Column( "value", TrimmedString(255), index=True ), + Column( "user_value", TrimmedString(255), index=True ) ) + model.StoredWorkflowTagAssociation.table = Table( "stored_workflow_tag_association", metadata, Column( "id", Integer, primary_key=True ), @@ -1990,6 +2000,9 @@ mapper( model.LibraryDatasetDatasetAssociation, model.LibraryDatasetDatasetAssoc ( model.LibraryDatasetDatasetAssociation.table.c.visible == true() ) ), remote_side=[model.LibraryDatasetDatasetAssociation.table.c.id] ), + tags=relation(model.LibraryDatasetDatasetAssociationTagAssociation, + order_by=model.LibraryDatasetDatasetAssociationTagAssociation.table.c.id, + backref='history_tag_associations'), extended_metadata=relation( model.ExtendedMetadata, primaryjoin=( ( model.LibraryDatasetDatasetAssociation.table.c.extended_metadata_id == model.ExtendedMetadata.table.c.id ) ) ), @@ -2448,6 +2461,7 @@ def tag_mapping( tag_association_class, backref_name ): tag_mapping( model.HistoryTagAssociation, "tagged_histories" ) tag_mapping( model.DatasetTagAssociation, "tagged_datasets" ) tag_mapping( model.HistoryDatasetAssociationTagAssociation, "tagged_history_dataset_associations" ) +tag_mapping( model.LibraryDatasetDatasetAssociationTagAssociation, "tagged_library_dataset_dataset_associations" ) tag_mapping( model.PageTagAssociation, "tagged_pages" ) tag_mapping( model.StoredWorkflowTagAssociation, "tagged_workflows" ) tag_mapping( model.WorkflowStepTagAssociation, "tagged_workflow_steps" ) diff --git a/lib/galaxy/model/migrate/versions/0135_add_library_tags.py b/lib/galaxy/model/migrate/versions/0135_add_library_tags.py new file mode 100644 index 00000000000..21c015a8fae --- /dev/null +++ b/lib/galaxy/model/migrate/versions/0135_add_library_tags.py @@ -0,0 +1,47 @@ +""" +This migration script adds support for storing tags in the context of a dataset in a library +""" +from __future__ import print_function + +import logging + +from sqlalchemy import Column, ForeignKey, Integer, MetaData, Table + +# Need our custom types, but don't import anything else from model +from galaxy.model.custom_types import TrimmedString + +log = logging.getLogger( __name__ ) +metadata = MetaData() + + +LibraryDatasetDatasetAssociationTagAssociation_table = Table( + "library_dataset_dataset_association_tag_association", metadata, + Column("id", Integer, primary_key=True), + Column( "library_dataset_dataset_association_id", Integer, ForeignKey( "library_dataset_dataset_association.id" ), index=True ), + Column( "tag_id", Integer, ForeignKey( "tag.id" ), index=True ), + Column( "user_tname", TrimmedString(255), index=True), + Column( "value", TrimmedString(255), index=True), + Column( "user_value", TrimmedString(255), index=True), + Column( "user_id", Integer, ForeignKey( "galaxy_user.id" ), index=True ) +) + + +def upgrade(migrate_engine): + metadata.bind = migrate_engine + print(__doc__) + metadata.reflect() + + try: + LibraryDatasetDatasetAssociationTagAssociation_table.create() + except Exception: + log.exception("Creating library_dataset_association_tag_association table failed.") + + +def downgrade(migrate_engine): + metadata.bind = migrate_engine + metadata.reflect() + + try: + LibraryDatasetDatasetAssociationTagAssociation_table.drop() + except Exception: + log.exception("Dropping library_dataset_association_tag_association table failed.") diff --git a/lib/galaxy/tools/__init__.py b/lib/galaxy/tools/__init__.py index 2a42690cd41..664d1c443c1 100755 --- a/lib/galaxy/tools/__init__.py +++ b/lib/galaxy/tools/__init__.py @@ -2510,6 +2510,30 @@ class FlattenTool( DatabaseOperationTool ): ) +class SortTool( DatabaseOperationTool ): + tool_type = 'sort_collection' + + def produce_outputs( self, trans, out_data, output_collections, incoming, history ): + hdca = incoming[ "input" ] + sorttype = incoming["sort_type"] + new_elements = odict() + elements = hdca.collection.elements + if sorttype == 'alpha': + presort_elements = [(dce.element_identifier, dce) for dce in elements] + elif sorttype == 'numeric': + presort_elements = [(int(re.sub('[^0-9]', '', dce.element_identifier)), dce) for dce in elements] + sorted_elements = [x[1] for x in sorted(presort_elements, key=lambda x: x[0])] + + for dce in sorted_elements: + dce_object = dce.element_object + copied_dataset = dce_object.copy() + history.add_dataset(copied_dataset, set_hid=False) + new_elements[dce.element_identifier] = copied_dataset + output_collections.create_collection( + next(iter(self.outputs.values())), "output", elements=new_elements + ) + + class RelabelFromFileTool(DatabaseOperationTool): tool_type = 'relabel_from_file' diff --git a/lib/galaxy/tools/actions/upload_common.py b/lib/galaxy/tools/actions/upload_common.py index 857acbcc216..f6cbe3d45b0 100644 --- a/lib/galaxy/tools/actions/upload_common.py +++ b/lib/galaxy/tools/actions/upload_common.py @@ -11,6 +11,7 @@ from sqlalchemy.orm import eagerload_all from galaxy import datatypes, util from galaxy.exceptions import ObjectInvalid +from galaxy.managers import tags from galaxy.util.odict import odict log = logging.getLogger( __name__ ) @@ -178,6 +179,11 @@ def __new_library_upload( trans, cntrller, uploaded_dataset, library_bunch, stat user=trans.user, create_dataset=True, sa_session=trans.sa_session ) + if uploaded_dataset.get( 'tag_using_filenames', False ): + tag_from_filename = os.path.splitext( os.path.basename( uploaded_dataset.name ))[0] + tag_manager = tags.GalaxyTagManager( trans.sa_session ) + tag_manager.apply_item_tag( item=ldda, user=trans.user, name='name', value=tag_from_filename ) + trans.sa_session.add( ldda ) if state: ldda.state = state diff --git a/lib/galaxy/tools/error_reports/__init__.py b/lib/galaxy/tools/error_reports/__init__.py new file mode 100644 index 00000000000..8fc4e447398 --- /dev/null +++ b/lib/galaxy/tools/error_reports/__init__.py @@ -0,0 +1,74 @@ +"""This module defines the error reporting framework for Galaxy jobs. +""" +import collections +import logging +import os + +from galaxy.util import plugin_config + +log = logging.getLogger(__name__) + + +class ErrorReports(object): + """Load and store a collection of :class:`ErrorPlugin` objects.""" + + def __init__(self, conf_file=None, **kwargs): + """Load :class:`ErrorPlugin` objects from specified configuration file.""" + self.plugin_classes = self.__plugins_dict() + self.default_error_plugin = ErrorPlugin.from_file(self.plugin_classes, conf_file, **kwargs) + self.error_plugin = collections.defaultdict(lambda: self.default_error_plugin) + + def __plugins_dict(self): + import galaxy.tools.error_reports.plugins + return plugin_config.plugins_dict(galaxy.tools.error_reports.plugins, 'plugin_type') + + +class NullErrorPlugin(object): + + def submit_report(self, dataset, job, tool, **kwargs): + return "Submitted Bug Report" + + +NULL_ERROR_PLUGIN = NullErrorPlugin() + + +class ErrorPlugin(object): + + def __init__(self, plugin_classes, plugins_source, **kwargs): + self.extra_kwargs = kwargs + self.app = kwargs['app'] + self.plugin_classes = plugin_classes + self.plugins = self.__plugins_from_source(plugins_source) + + def _can_access_dataset(self, dataset, user): + if user: + roles = user.all_roles() + else: + roles = [] + return self.app.security_agent.can_access_dataset(roles, dataset.dataset) + + def submit_report(self, dataset, job, tool, user=None, user_submission=False, **kwargs): + if user_submission: + assert self._can_access_dataset(dataset, user), Exception("You are not allowed to access this dataset.") + + responses = [] + for plugin in self.plugins: + if user_submission == plugin.user_submission: + try: + response = plugin.submit_report(dataset, job, tool, **kwargs) + log.debug("Bug report plugin %s generated response %s", plugin, response) + if plugin.verbose and response: + responses.append(response) + except Exception: + log.exception("Failed to generate submit_report commands for plugin %s", plugin) + return responses + + def __plugins_from_source(self, plugins_source): + return plugin_config.load_plugins(self.plugin_classes, plugins_source, self.extra_kwargs) + + @staticmethod + def from_file(plugin_classes, conf_file, **kwargs): + if not conf_file or not os.path.exists(conf_file): + return NULL_ERROR_PLUGIN + plugins_source = plugin_config.plugin_source_from_path(conf_file) + return ErrorPlugin(plugin_classes, plugins_source, **kwargs) diff --git a/lib/galaxy/tools/error_reports/plugins/__init__.py b/lib/galaxy/tools/error_reports/plugins/__init__.py new file mode 100644 index 00000000000..9dd6ac66a0a --- /dev/null +++ b/lib/galaxy/tools/error_reports/plugins/__init__.py @@ -0,0 +1,25 @@ +"""This module describes the abstract interface for :class:`InstrumentPlugin`. + +These are responsible for collecting and formatting a coherent set of metrics. +""" +from abc import ( + ABCMeta, + abstractmethod +) + +import six + + +@six.add_metaclass(ABCMeta) +class ErrorPlugin( object ): + """Describes how to send bug reports to various locations.""" + + @property + @abstractmethod + def plugin_type( self ): + """Short string providing labelling this plugin """ + + def submit_report( self, dataset, job, tool, user_submission=False, **kwargs ): + """Submit the bug report and render a string to be displayed to the user. + """ + return None diff --git a/lib/galaxy/tools/error_reports/plugins/biostars.py b/lib/galaxy/tools/error_reports/plugins/biostars.py new file mode 100644 index 00000000000..dfade933615 --- /dev/null +++ b/lib/galaxy/tools/error_reports/plugins/biostars.py @@ -0,0 +1,42 @@ +"""The module describes the ``biostars`` error plugin.""" +from __future__ import absolute_import + +import logging + +from galaxy.util import biostar +from galaxy.util import string_as_bool +from galaxy.web.base.controller import url_for + +from ..plugins import ErrorPlugin + +log = logging.getLogger( __name__ ) + + +class BiostarsPlugin( ErrorPlugin ): + """Send error report as an issue on Biostars + """ + plugin_type = "biostars" + + def __init__( self, **kwargs ): + self.app = kwargs['app'] + self.verbose = string_as_bool(kwargs.get('verbose', True)) + self.user_submission = string_as_bool(kwargs.get('user_submission', True)) + + def submit_report( self, dataset, job, tool, **kwargs ): + """Doesn't do anything, just shows a link to submit on biostars. + """ + try: + assert biostar.biostar_enabled( self.app ), ValueError( "Biostar is not configured for this galaxy instance" ) + assert self.app.config.biostar_enable_bug_reports, ValueError( "Biostar is not configured to allow bug reporting for this galaxy instance" ) + print(kwargs) + + url = url_for(controller='biostar', + action='biostar_tool_bug_report', + hda=self.app.security.encode_id(dataset.id), + email=kwargs['email'], message=kwargs['message']) + return ( 'Click here to submit to BioStars' % url, 'success' ) + except Exception as e: + return ( "An error occurred submitting the report to biostars: %s" % str( e ), "danger" ) + + +__all__ = ( 'BiostarsPlugin', ) diff --git a/lib/galaxy/tools/error_reports/plugins/email.py b/lib/galaxy/tools/error_reports/plugins/email.py new file mode 100644 index 00000000000..bb68b8b8763 --- /dev/null +++ b/lib/galaxy/tools/error_reports/plugins/email.py @@ -0,0 +1,35 @@ +"""The module describes the ``email`` error plugin.""" +from __future__ import absolute_import + +import logging + +from galaxy.tools.errors import EmailErrorReporter +from galaxy.util import string_as_bool + +from ..plugins import ErrorPlugin + +log = logging.getLogger( __name__ ) + + +class EmailPlugin( ErrorPlugin ): + """Send error report as an email + """ + plugin_type = "email" + + def __init__( self, **kwargs ): + self.app = kwargs['app'] + self.verbose = string_as_bool(kwargs.get('verbose', True)) + self.user_submission = string_as_bool(kwargs.get('user_submission', True)) + + def submit_report( self, dataset, job, tool, **kwargs ): + """Send report as an email + """ + try: + error_reporter = EmailErrorReporter( dataset.id, self.app ) + error_reporter.send_report( user=job.get_user(), email=kwargs.get('email', None), message=kwargs.get('message', None) ) + return ( "Your error report has been sent", "success" ) + except Exception as e: + return ( "An error occurred sending the report by email: %s" % str( e ), "danger" ) + + +__all__ = ( 'EmailPlugin', ) diff --git a/lib/galaxy/tools/error_reports/plugins/json.py b/lib/galaxy/tools/error_reports/plugins/json.py new file mode 100644 index 00000000000..4a523616529 --- /dev/null +++ b/lib/galaxy/tools/error_reports/plugins/json.py @@ -0,0 +1,57 @@ +"""The module describes the ``json`` error plugin.""" +from __future__ import absolute_import + +import json +import logging +import os +import tempfile + +from galaxy.util import string_as_bool + +from ..plugins import ErrorPlugin + +log = logging.getLogger( __name__ ) + + +class JsonPlugin( ErrorPlugin ): + """Write error report to a JSON file. + """ + plugin_type = "json" + + def __init__( self, **kwargs ): + self.app = kwargs['app'] + self.verbose = string_as_bool(kwargs.get('verbose', False)) + self.user_submission = string_as_bool(kwargs.get('user_submission', False)) + self.report_directory = kwargs.get( "directory", tempfile.gettempdir() ) + if not os.path.exists(self.report_directory): + os.makedirs(self.report_directory) + + def submit_report( self, dataset, job, tool, **kwargs ): + """Write the report to a json file. + """ + path = os.path.join( self.report_directory, str(dataset.id)) + with open( path, 'w' ) as handle: + data = { + 'info' : job.info, + 'id' : job.id, + 'command_line' : job.command_line, + 'stderr' : job.stderr, + 'traceback': job.traceback, + 'exit_code': job.exit_code, + 'stdout': job.stdout, + 'handler': job.handler, + 'user': job.get_user().to_dict(), + 'tool_version': job.tool_version, + 'tool_xml': str(tool.config_file) if tool else None + } + if 'email' in kwargs: + data['email'] = kwargs['email'] + + if 'message' in kwargs: + data['message'] = kwargs['message'] + + json.dump(data, handle, indent=2) + return ( 'Wrote error report to %s' % path, 'success' ) + + +__all__ = ( 'JsonPlugin', ) diff --git a/lib/galaxy/tools/error_reports/plugins/sentry.py b/lib/galaxy/tools/error_reports/plugins/sentry.py new file mode 100644 index 00000000000..ae1b232d864 --- /dev/null +++ b/lib/galaxy/tools/error_reports/plugins/sentry.py @@ -0,0 +1,52 @@ +"""The module describes the ``sentry`` error plugin plugin.""" +import logging + +from galaxy.util import string_as_bool + +from ..plugins import ErrorPlugin + +log = logging.getLogger( __name__ ) + + +class SentryPlugin( ErrorPlugin ): + """Send error report to Sentry. + """ + plugin_type = "sentry" + + def __init__( self, **kwargs ): + self.app = kwargs['app'] + self.verbose = string_as_bool(kwargs.get('verbose', False)) + self.user_submission = string_as_bool(kwargs.get('user_submission', False)) + + def submit_report( self, dataset, job, tool, **kwargs ): + """Submit the error report to sentry + """ + if self.app.sentry_client: + extra = { + 'info' : job.info, + 'id' : job.id, + 'command_line' : job.command_line, + 'stderr' : job.stderr, + 'traceback': job.traceback, + 'exit_code': job.exit_code, + 'stdout': job.stdout, + 'handler': job.handler, + 'user': job.get_user(), + 'tool_version': job.tool_version, + 'tool_xml': tool.config_file if tool else None + } + if 'email' in kwargs: + extra['email'] = kwargs['email'] + + if 'message' in kwargs: + extra['message'] = kwargs['message'] + + response = self.app.sentry_client.capture( + 'raven.events.Message', + message="Galaxy Job Error: %s v.%s" % (job.tool_id, job.tool_version), + extra=extra, + ) + return ( 'Submitted bug report to Sentry. Your guru meditation number is %s' % response, 'success' ) + + +__all__ = ( 'SentryPlugin', ) diff --git a/lib/galaxy/tools/errors.py b/lib/galaxy/tools/errors.py index 5223a07c77f..4314d3672db 100644 --- a/lib/galaxy/tools/errors.py +++ b/lib/galaxy/tools/errors.py @@ -67,7 +67,7 @@ error_report_template_html = """

Error Localization

- + @@ -84,7 +84,7 @@ ${message}

Detailed Job Information

-Job environment and execution information is available at the job Info Page. +Job environment and execution information is available at the job info page.
Dataset${dataset_id} (${dataset_id_encoded})
Dataset${dataset_id} (${dataset_id_encoded})
History${history_id} (${history_id_encoded})
Failed Job${hid}: ${history_item_name} (${hda_id_encoded})
diff --git a/lib/galaxy/tools/parameters/grouping.py b/lib/galaxy/tools/parameters/grouping.py index f83d6649050..12df0c5db53 100644 --- a/lib/galaxy/tools/parameters/grouping.py +++ b/lib/galaxy/tools/parameters/grouping.py @@ -452,6 +452,7 @@ class UploadDataset( Group ): file_type = self.get_file_type( context ) d_type = self.get_datatype( trans, context ) dbkey = context.get( 'dbkey', None ) + tag_using_filenames = context.get('tag_using_filenames', False) writable_files = d_type.writable_files writable_files_offset = 0 groups_incoming = [ None for _ in writable_files ] @@ -470,6 +471,7 @@ class UploadDataset( Group ): dataset.metadata = {} dataset.composite_files = {} dataset.uuid = None + dataset.tag_using_filenames = None # load metadata files_metadata = context.get( self.metadata_ref, {} ) metadata_name_substition_default_dict = dict( ( composite_file.substitute_name_with_metadata, d_type.metadata_spec[ composite_file.substitute_name_with_metadata ].default ) for composite_file in d_type.composite_files.values() if composite_file.substitute_name_with_metadata ) @@ -520,6 +522,7 @@ class UploadDataset( Group ): dataset.datatype = d_type dataset.ext = self.get_datatype_ext( trans, context ) dataset.dbkey = dbkey + dataset.tag_using_filenames = tag_using_filenames rval.append( dataset ) return rval diff --git a/lib/galaxy/tools/parser/interface.py b/lib/galaxy/tools/parser/interface.py index b16f807ae7e..c048e8cb7a8 100644 --- a/lib/galaxy/tools/parser/interface.py +++ b/lib/galaxy/tools/parser/interface.py @@ -8,8 +8,8 @@ import six NOT_IMPLEMENTED_MESSAGE = "Galaxy tool format does not yet support this tool feature." -@six.add_metaclass(ABCMeta) @six.python_2_unicode_compatible +@six.add_metaclass(ABCMeta) class ToolSource(object): """ This interface represents an abstract source to parse tool information from. diff --git a/lib/galaxy/tools/parser/output_objects.py b/lib/galaxy/tools/parser/output_objects.py index 32421f288fc..91f08e19133 100644 --- a/lib/galaxy/tools/parser/output_objects.py +++ b/lib/galaxy/tools/parser/output_objects.py @@ -118,11 +118,7 @@ class ToolOutputCollection( ToolOutputBase ): if len( self.outputs ) > 1: output_parts = [ToolOutputCollectionPart(self, k, v) for k, v in self.outputs.items()] else: - # either must have specified structured_like or something worse - if self.structure.structured_like: - collection_prototype = inputs[ self.structure.structured_like ].collection - else: - collection_prototype = type_registry.prototype( self.structure.collection_type ) + collection_prototype = self.structure.collection_prototype( inputs, type_registry ) def prototype_dataset_element_to_output( element, parent_ids=[] ): name = element.element_identifier @@ -178,9 +174,9 @@ class ToolOutputCollectionStructure( object ): def __init__( self, collection_type, - collection_type_source, - structured_like, - dataset_collector_descriptions, + collection_type_source=None, + structured_like=None, + dataset_collector_descriptions=None, ): self.collection_type = collection_type self.collection_type_source = collection_type_source @@ -194,6 +190,14 @@ class ToolOutputCollectionStructure( object ): raise ValueError( "Cannot specify dynamic structure (discovered_datasets) and structured_like attribute." ) self.dynamic = dataset_collector_descriptions is not None + def collection_prototype( self, inputs, type_registry ): + # either must have specified structured_like or something worse + if self.structured_like: + collection_prototype = inputs[ self.structured_like ].collection + else: + collection_prototype = type_registry.prototype( self.collection_type ) + return collection_prototype + class ToolOutputCollectionPart( object ): diff --git a/lib/galaxy/tools/sort_collection_list.xml b/lib/galaxy/tools/sort_collection_list.xml new file mode 100644 index 00000000000..f884b0392db --- /dev/null +++ b/lib/galaxy/tools/sort_collection_list.xml @@ -0,0 +1,73 @@ + + of list of datasets + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/galaxy/tools/toolbox/base.py b/lib/galaxy/tools/toolbox/base.py index b3e63e168aa..4ed9f93df22 100644 --- a/lib/galaxy/tools/toolbox/base.py +++ b/lib/galaxy/tools/toolbox/base.py @@ -454,7 +454,10 @@ class AbstractToolBox( Dictifiable, ManagesIntegratedToolPanelMixin, object ): # We now likely have a Toolshed guid passed in, but no supporting database entries # If the tool exists by exact id and is loaded then provide exact match within a list if tool_id in self._tools_by_id: - return[ self._tools_by_id[ tool_id ] ] + if get_all_versions: + return [ self._tools_by_id[ tool_id ] ] + else: + return self._tools_by_id[ tool_id ] return None def has_tool( self, tool_id, tool_version=None, exact=False ): diff --git a/lib/galaxy/util/biostar.py b/lib/galaxy/util/biostar.py index 278e9491cf4..4a93db15031 100644 --- a/lib/galaxy/util/biostar.py +++ b/lib/galaxy/util/biostar.py @@ -169,7 +169,20 @@ class BiostarErrorReporter( ErrorReporter ): assert self._can_access_dataset( user ), Exception( "You are not allowed to access this dataset." ) tool_version_select_field, tools, tool = \ self.app.toolbox.get_tool_components( self.tool_id, tool_version=None, get_loaded_tools_by_lineage=False, set_selected=True ) - payload = { 'title': 'Bug report on "%s" tool' % ( tool.name ), 'content': self.report.replace( '\n', '
' ).replace( '\r', '' ), 'tag_val': slugify( 'bug report' ) } + + # Strip out unwanted HTML characters + html_remove = ['', '', '', '', '\n', '\r'] + report = self.html_report + for tag in html_remove: + report = report.replace(tag, '') + # Must lstrip spaces or it isn't recognised as HTML + report = report.lstrip() + + payload = { + 'title': 'Bug report on "%s" tool' % ( tool.name ), + 'content': report, + 'tag_val': slugify( 'bug report' ) + } # Get footer for email from here payload2 = populate_tool_payload( tool=tool ) if 'content' in payload2: diff --git a/lib/galaxy/util/plugin_config.py b/lib/galaxy/util/plugin_config.py index d9deab5bdd3..e89749bf36a 100644 --- a/lib/galaxy/util/plugin_config.py +++ b/lib/galaxy/util/plugin_config.py @@ -72,7 +72,7 @@ def __load_plugins_from_dicts(plugins_dict, configs, extra_kwds): def plugin_source_from_path(path): - if path.endswith(".yaml") or path.endswith(".yml"): + if path.endswith(".yaml") or path.endswith(".yml") or path.endswith(".yaml.sample") or path.endswith(".yml.sample"): return ('dict', __read_yaml(path)) else: return ('xml', ElementTree.parse( path ).getroot()) diff --git a/lib/galaxy/web/base/controller.py b/lib/galaxy/web/base/controller.py index 578f90db42d..0cb680c9c15 100644 --- a/lib/galaxy/web/base/controller.py +++ b/lib/galaxy/web/base/controller.py @@ -2,40 +2,63 @@ Contains functionality needed in every web interface """ import logging -import operator import re -from six import string_types, text_type +from paste.httpexceptions import ( + HTTPBadRequest, + HTTPInternalServerError, + HTTPNotImplemented, + HTTPRequestRangeNotSatisfiable +) +from six import ( + string_types, + text_type +) from sqlalchemy import true -from paste.httpexceptions import HTTPBadRequest, HTTPInternalServerError -from paste.httpexceptions import HTTPNotImplemented, HTTPRequestRangeNotSatisfiable -from galaxy import exceptions -from galaxy import web -from galaxy import model -from galaxy import security -from galaxy import util - -from galaxy.web import error, url_for -from galaxy.web.form_builder import AddressField, CheckboxField, SelectField, TextArea, TextField -from galaxy.web.form_builder import build_select_field, HistoryField, PasswordField, WorkflowField, WorkflowMappingField -from galaxy.workflow.modules import WorkflowModuleInjector -from galaxy.security.validate_user_input import validate_publicname -from galaxy.util.sanitize_html import sanitize_html -from galaxy.model.item_attrs import UsesAnnotations -from galaxy.util.dictifiable import Dictifiable - +from galaxy import ( + exceptions, + model, + security, + util, + web +) from galaxy.datatypes.interval import ChromatinInteractions - -from galaxy.model import ExtendedMetadata, ExtendedMetadataIndex, LibraryDatasetDatasetAssociation, HistoryDatasetAssociation - -from galaxy.managers import api_keys -from galaxy.managers import tags -from galaxy.managers import workflows -from galaxy.managers import base as managers_base -from galaxy.managers import users -from galaxy.managers import configuration - +from galaxy.managers import ( + api_keys, + base as managers_base, + configuration, + tags, + users, + workflows +) +from galaxy.model import ( + ExtendedMetadata, + ExtendedMetadataIndex, + HistoryDatasetAssociation, + LibraryDatasetDatasetAssociation +) +from galaxy.model.item_attrs import UsesAnnotations +from galaxy.security.validate_user_input import validate_publicname +from galaxy.util.dictifiable import Dictifiable +from galaxy.util.sanitize_html import sanitize_html +from galaxy.web import ( + error, + url_for +) +from galaxy.web.form_builder import ( + AddressField, + build_select_field, + CheckboxField, + HistoryField, + PasswordField, + SelectField, + TextArea, + TextField, + WorkflowField, + WorkflowMappingField +) +from galaxy.workflow.modules import WorkflowModuleInjector log = logging.getLogger( __name__ ) @@ -132,7 +155,7 @@ class BaseController( object ): values = [ values ] # TODO: it may be more helpful to the consumer if we error on incomplete 3-tuples # (instead of relying on zip to shorten) - return zip( attrs, ops, values ) + return list(zip( attrs, ops, values )) def parse_limit_offset( self, qdict ): """ @@ -211,8 +234,8 @@ class BaseAPIController( BaseController ): msg = "The following value(s) for associated users and/or groups could not be parsed: %s." % ', '.join( invalid ) msg += " Valid values are email addresses of users, names of groups, or IDs of both." raise Exception( msg ) - payload['in_users'] = map( str, new_in_users ) - payload['in_groups'] = map( str, new_in_groups ) + payload['in_users'] = list(map( str, new_in_users )) + payload['in_groups'] = list(map( str, new_in_groups )) def not_implemented( self, trans, **kwd ): raise HTTPNotImplemented() @@ -903,7 +926,7 @@ class UsesVisualizationMixin( UsesLibraryMixinItems ): if not job: return None - tool = trans.app.toolbox.get_tool( job.tool_id ) + tool = trans.app.toolbox.get_tool( job.tool_id, tool_version=job.tool_version ) if not tool: return None @@ -2176,7 +2199,6 @@ class UsesTagsMixin( SharableItemSecurityMixin ): return self.get_tag_handler( trans )._get_item_tag_assoc( user, tagged_item, tag_name ) def set_tags_from_list( self, trans, item, new_tags_list, user=None ): - # Method deprecated - try to use TagsHandler instead. tags_manager = tags.GalaxyTagManager( trans.app.model.context ) return tags_manager.set_tags_from_list( user, item, new_tags_list ) @@ -2322,6 +2344,6 @@ def sort_by_attr( seq, attr ): # (seq[i].attr, i, seq[i]) and sort it. The second item of tuple is needed not # only to provide stable sorting, but mainly to eliminate comparison of objects # (which can be expensive or prohibited) in case of equal attribute values. - intermed = map( None, map( getattr, seq, ( attr, ) * len( seq ) ), xrange( len( seq ) ), seq ) + intermed = [(getattr(v, attr), i, v) for i, v in enumerate(seq)] intermed.sort() - return map( operator.getitem, intermed, ( -1, ) * len( intermed ) ) + return [_[-1] for _ in intermed] diff --git a/lib/galaxy/web/base/interactive_environments.py b/lib/galaxy/web/base/interactive_environments.py index 7beee84b52a..00dd3197b0a 100644 --- a/lib/galaxy/web/base/interactive_environments.py +++ b/lib/galaxy/web/base/interactive_environments.py @@ -1,4 +1,3 @@ -import ConfigParser import json import logging import os @@ -6,11 +5,11 @@ import random import stat import tempfile import uuid - from subprocess import PIPE, Popen from sys import platform as _platform import yaml +from six.moves import configparser from galaxy import model, web from galaxy.containers import build_container_interfaces @@ -121,7 +120,7 @@ class InteractiveEnvironmentRequest(object): def load_deploy_config(self, default_dict={}): # For backwards compat, any new variables added to the base .ini file - # will need to be recorded here. The ConfigParser doesn't provide a + # will need to be recorded here. The configparser doesn't provide a # .get() that will ignore missing sections, so we must make use of # their defaults dictionary instead. default_dict = { @@ -133,7 +132,7 @@ class InteractiveEnvironmentRequest(object): 'docker_galaxy_temp_dir': None, 'docker_connect_port': None, } - viz_config = ConfigParser.SafeConfigParser(default_dict) + viz_config = configparser.SafeConfigParser(default_dict) conf_path = os.path.join( self.attr.our_config_dir, self.attr.viz_id + ".ini" ) if not os.path.exists( conf_path ): conf_path = "%s.sample" % conf_path @@ -253,7 +252,7 @@ class InteractiveEnvironmentRequest(object): env_override = {} conf = self.get_conf_dict() conf.update(env_override) - return dict([(key.upper(), item) for key, item in conf.items()]) + return dict((key.upper(), item) for key, item in conf.items()) def _get_import_volume_for_run(self): if self.use_volumes and self.attr.import_volume: @@ -271,8 +270,8 @@ class InteractiveEnvironmentRequest(object): volumes = [] env = self._get_env_for_run(env_override) import_volume_def = self._get_import_volume_for_run() - env_str = ' '.join(['-e "%s=%s"' % (key, item) for key, item in env.items()]) - volume_str = ' '.join(['-v "%s"' % volume for volume in volumes]) if self.use_volumes else '' + env_str = ' '.join('-e "%s=%s"' % (key, item) for key, item in env.items()) + volume_str = ' '.join('-v "%s"' % volume for volume in volumes) if self.use_volumes else '' import_volume_str = '-v "{import_volume}"'.format(import_volume=import_volume_def) if import_volume_def else '' name = None # This is the basic docker command such as "sudo -u docker docker {docker_args}" diff --git a/lib/galaxy/web/base/pluginframework.py b/lib/galaxy/web/base/pluginframework.py index 704830716eb..eb85d3047e1 100644 --- a/lib/galaxy/web/base/pluginframework.py +++ b/lib/galaxy/web/base/pluginframework.py @@ -7,17 +7,19 @@ and base class for plugins that: * serve templated html * have some configuration at startup """ - +import imp +import logging import os.path import sys -import imp - -from galaxy import util -from galaxy.util import odict -from galaxy.util import bunch import mako.lookup -import logging + +from galaxy import util +from galaxy.util import ( + bunch, + odict +) + log = logging.getLogger( __name__ ) diff --git a/lib/galaxy/webapps/galaxy/api/jobs.py b/lib/galaxy/webapps/galaxy/api/jobs.py index 42d4008f855..c2efdb19117 100644 --- a/lib/galaxy/webapps/galaxy/api/jobs.py +++ b/lib/galaxy/webapps/galaxy/api/jobs.py @@ -352,3 +352,34 @@ class JobController( BaseAPIController, UsesLibraryMixinItems ): if all( list( a.dataset.deleted is False for a in job.output_datasets ) ): out.append( self.encode_all_ids( trans, job.to_dict( 'element' ), True ) ) return out + + @expose_api + def error( self, trans, id, **kwd ): + """ + error( trans, id ) + * POST /api/jobs/{id}/error + submits a bug report via the API. + + :type id: string + :param id: Encoded job id + + :rtype: dictionary + :returns: dictionary containing information regarding where the error report was sent. + """ + # Get dataset on which this error was triggered + try: + decoded_dataset_id = self.decode_id( kwd['dataset_id'] ) + except Exception: + raise exceptions.MalformedId() + dataset = trans.sa_session.query( trans.app.model.HistoryDatasetAssociation ).get( decoded_dataset_id ) + + # Get job + job = self.__get_job( trans, id ) + tool = trans.app.toolbox.get_tool( job.tool_id, tool_version=job.tool_version ) or None + messages = trans.app.error_reports.default_error_plugin.submit_report( + dataset, job, tool, user_submission=True, user=trans.user, + email=kwd.get('email', trans.user.email), + message=kwd.get('message', None) + ) + + return { 'messages': messages } diff --git a/lib/galaxy/webapps/galaxy/api/lda_datasets.py b/lib/galaxy/webapps/galaxy/api/lda_datasets.py index c1d5a1581f6..909f6d88294 100644 --- a/lib/galaxy/webapps/galaxy/api/lda_datasets.py +++ b/lib/galaxy/webapps/galaxy/api/lda_datasets.py @@ -16,7 +16,7 @@ from galaxy import exceptions from galaxy import util from galaxy import web from galaxy.exceptions import ObjectNotFound -from galaxy.managers import folders, roles +from galaxy.managers import folders, roles, tags from galaxy.tools.actions import upload_common from galaxy.tools.parameters import populate_state from galaxy.util.streamball import StreamBall @@ -56,6 +56,8 @@ class LibraryDatasetsController( BaseAPIController, UsesVisualizationMixin ): current_user_roles = trans.get_current_user_roles() + tag_manager = tags.GalaxyTagManager( trans.sa_session ) + # Build the full path for breadcrumb purposes. full_path = self._build_path( trans, library_dataset.folder ) dataset_item = ( trans.security.encode_id( library_dataset.id ), library_dataset.name ) @@ -78,6 +80,7 @@ class LibraryDatasetsController( BaseAPIController, UsesVisualizationMixin ): rval[ 'date_uploaded' ] = library_dataset.library_dataset_dataset_association.create_time.strftime( "%Y-%m-%d %I:%M %p" ) rval[ 'can_user_modify' ] = trans.app.security_agent.can_modify_library_item( current_user_roles, library_dataset) or trans.user_is_admin() rval[ 'is_unrestricted' ] = trans.app.security_agent.dataset_is_public( library_dataset.library_dataset_dataset_association.dataset ) + rval[ 'tags' ] = tag_manager.get_tags_str(library_dataset.library_dataset_dataset_association.tags) # Manage dataset permission is always attached to the dataset itself, not the the ld or ldda to maintain consistency rval[ 'can_user_manage' ] = trans.app.security_agent.can_manage_dataset( current_user_roles, library_dataset.library_dataset_dataset_association.dataset) or trans.user_is_admin() @@ -396,6 +399,8 @@ class LibraryDatasetsController( BaseAPIController, UsesVisualizationMixin ): :type file_type: str :param dbkey: dbkey of the loaded genome, defaults to '?' (unknown) :type dbkey: str + :param tag_using_filenames: flag whether to generate dataset tags from filenames + :type tag_using_filenames: bool :type dictionary :returns: dict containing information about the created upload job :rtype: dictionary @@ -408,7 +413,8 @@ class LibraryDatasetsController( BaseAPIController, UsesVisualizationMixin ): kwd[ 'to_posix_lines' ] = True kwd[ 'dbkey' ] = kwd.get( 'dbkey', '?' ) kwd[ 'file_type' ] = kwd.get( 'file_type', 'auto' ) - kwd[ 'link_data_only' ] = 'link_to_files' if util.asbool( kwd.get( 'link_data', False ) ) else 'copy_files' + kwd['link_data_only'] = 'link_to_files' if util.string_as_bool( kwd.get( 'link_data', False ) ) else 'copy_files' + kwd[ 'tag_using_filenames' ] = util.string_as_bool( kwd.get( 'tag_using_filenames', None ) ) encoded_folder_id = kwd.get( 'encoded_folder_id', None ) if encoded_folder_id is not None: folder_id = self.folder_manager.cut_and_decode( trans, encoded_folder_id ) diff --git a/lib/galaxy/webapps/galaxy/api/library_contents.py b/lib/galaxy/webapps/galaxy/api/library_contents.py index 7416406f062..b8c50b08ed9 100644 --- a/lib/galaxy/webapps/galaxy/api/library_contents.py +++ b/lib/galaxy/webapps/galaxy/api/library_contents.py @@ -182,6 +182,8 @@ class LibraryContentsController( BaseAPIController, UsesLibraryMixin, UsesLibrar folder to create * description: (optional, only if create_type is 'folder') description of the folder to create + * tag_using_filename: (optional) + create tags on datasets using the file's original name :returns: a dictionary describing the new item unless ``from_hdca_id`` is supplied, in that case a list of such dictionaries is returned. diff --git a/lib/galaxy/webapps/galaxy/api/users.py b/lib/galaxy/webapps/galaxy/api/users.py index eae0ef3d08c..51a5a2e773c 100644 --- a/lib/galaxy/webapps/galaxy/api/users.py +++ b/lib/galaxy/webapps/galaxy/api/users.py @@ -11,6 +11,8 @@ from datetime import datetime from markupsafe import escape from sqlalchemy import false, true, and_, or_ +import yaml + from galaxy import exceptions, util, web from galaxy.exceptions import MessageException, ObjectInvalid from galaxy.managers import users @@ -250,6 +252,46 @@ class UserAPIController( BaseAPIController, UsesTagsMixin, CreatesUsersMixin, Cr 'nice_total_disk_usage': util.nice_size( usage ), 'quota_percent': percent} + def _get_extra_user_preferences(self, trans): + """ + Reads the file user_preferences_extra_conf.yml to display + admin defined user informations + """ + path = trans.app.config.user_preferences_extra_config_file + try: + with open(path, 'r') as stream: + config = yaml.load(stream) + except: + log.warn('Config file (%s) could not be found or is malformed.' % path) + return {} + + return config['preferences'] if config else {} + + def _build_extra_user_pref_inputs(self, preferences, user): + """ + Build extra user preferences inputs list. + Add values to the fields if present + """ + if not preferences: + return [] + data = [] + # Get data if present + data_key = "extra_user_preferences" + if data_key in user.preferences: + data = json.loads(user.preferences[data_key]) + extra_pref_inputs = list() + # Build sections for different categories of inputs + for item, value in preferences.items(): + if value is not None: + for input in value["inputs"]: + input['help'] = 'Required' if input['required'] else '' + field = item + '|' + input['name'] + for data_item in data: + if field in data_item: + input['value'] = data[data_item] + extra_pref_inputs.append({'type': 'section', 'title': value['description'], 'name': item, 'expanded': True, 'inputs': value['inputs']}) + return extra_pref_inputs + @expose_api def get_information(self, trans, id, **kwd): """ @@ -302,6 +344,7 @@ class UserAPIController( BaseAPIController, UsesTagsMixin, CreatesUsersMixin, Cr info_field['test_param']['data'].append({'label': info_form['name'], 'value': info_form['id']}) info_field['cases'].append({'value': info_form['id'], 'inputs': info_form['inputs']}) inputs.append(info_field) + address_inputs = [{'type': 'hidden', 'name': 'id', 'hidden': True}] for field in AddressField.fields(): address_inputs.append({'type': 'text', 'name': field[0], 'label': field[1], 'help': field[2]}) @@ -315,6 +358,11 @@ class UserAPIController( BaseAPIController, UsesTagsMixin, CreatesUsersMixin, Cr address_cache.append(input_copy) address_repeat['cache'].append(address_cache) inputs.append(address_repeat) + + # Build input sections for extra user preferences + extra_user_pref = self._build_extra_user_pref_inputs( self._get_extra_user_preferences( trans ), user ) + for item in extra_user_pref: + inputs.append(item) else: if user.active_repositories: inputs.append(dict(id='name_input', name='username', label='Public name:', type='hidden', value=username, help='You cannot change your public name after you have created a repository in this tool shed.')) @@ -382,6 +430,26 @@ class UserAPIController( BaseAPIController, UsesTagsMixin, CreatesUsersMixin, Cr form_values = trans.model.FormValues(user_info_form, user_info_values) trans.sa_session.add(form_values) user.values = form_values + + # Update values for extra user preference items + extra_user_pref_data = dict() + get_extra_pref_keys = self._get_extra_user_preferences( trans ) + if get_extra_pref_keys is not None: + for key in get_extra_pref_keys: + key_prefix = key + '|' + for item in payload: + if item.startswith( key_prefix ): + # Show error message if the required field is empty + if payload[item] == "": + # Raise an exception when a required field is empty while saving the form + keys = item.split("|") + section = get_extra_pref_keys[keys[0]] + for input in section['inputs']: + if input['name'] == keys[1] and input['required']: + raise MessageException("Please fill the required field") + extra_user_pref_data[ item ] = payload[ item ] + user.preferences[ "extra_user_preferences" ] = json.dumps( extra_user_pref_data ) + # Update user addresses address_dicts = {} address_count = 0 diff --git a/lib/galaxy/webapps/galaxy/buildapp.py b/lib/galaxy/webapps/galaxy/buildapp.py index fbfb02e5f97..162be3570ba 100644 --- a/lib/galaxy/webapps/galaxy/buildapp.py +++ b/lib/galaxy/webapps/galaxy/buildapp.py @@ -122,6 +122,7 @@ def paste_app_factory( global_conf, **kwargs ): webapp.add_client_route( '/histories/list_shared' ) webapp.add_client_route( '/datasets/list' ) webapp.add_client_route( '/datasets/edit' ) + webapp.add_client_route( '/datasets/error' ) webapp.add_client_route( '/workflow/run' ) webapp.add_client_route( '/workflow/import_workflow' ) webapp.add_client_route( '/custom_builds' ) @@ -761,6 +762,7 @@ def populate_api_routes( webapp, app ): webapp.mapper.connect( 'job_inputs', '/api/jobs/{id}/inputs', controller='jobs', action='inputs', conditions=dict( method=['GET'] ) ) webapp.mapper.connect( 'job_outputs', '/api/jobs/{id}/outputs', controller='jobs', action='outputs', conditions=dict( method=['GET'] ) ) webapp.mapper.connect( 'build_for_rerun', '/api/jobs/{id}/build_for_rerun', controller='jobs', action='build_for_rerun', conditions=dict( method=['GET'] ) ) + webapp.mapper.connect( 'job_error', '/api/jobs/{id}/error', controller='jobs', action='error', conditions=dict( method=['POST'] ) ) # Job files controllers. Only for consumption by remote job runners. webapp.mapper.resource( 'file', diff --git a/lib/galaxy/webapps/galaxy/controllers/admin.py b/lib/galaxy/webapps/galaxy/controllers/admin.py index af48a200bb9..2d766b68be9 100644 --- a/lib/galaxy/webapps/galaxy/controllers/admin.py +++ b/lib/galaxy/webapps/galaxy/controllers/admin.py @@ -1017,14 +1017,13 @@ class AdminGalaxy( controller.JSAppLauncher, AdminActions, UsesQuotaMixin, Quota 'inputs' : [{ 'name' : 'name', 'label' : 'Name' - },{ + }, { 'name' : 'description', 'label' : 'Description' }, build_select_input( 'groups', 'Groups', all_groups, [] ), - build_select_input( 'users', 'Users', all_users, [] ), - { - 'name' : 'auto_create', + build_select_input( 'users', 'Users', all_users, [] ), { + 'name' : 'create_group_for_role', 'label' : 'Create a new role of the same name for this group:', 'type' : 'boolean' } ] } @@ -1080,7 +1079,11 @@ class AdminGalaxy( controller.JSAppLauncher, AdminActions, UsesQuotaMixin, Quota 'name' : 'name', 'label' : 'Name', 'value' : role.name +<<<<<<< HEAD },{ +======= + }, { +>>>>>>> admin_grid_roles 'name' : 'description', 'label' : 'Description', 'value' : role.description diff --git a/lib/galaxy/webapps/galaxy/controllers/dataset.py b/lib/galaxy/webapps/galaxy/controllers/dataset.py index 41d34889b6d..37052e64b61 100644 --- a/lib/galaxy/webapps/galaxy/controllers/dataset.py +++ b/lib/galaxy/webapps/galaxy/controllers/dataset.py @@ -18,7 +18,6 @@ from galaxy.util.sanitize_html import sanitize_html from galaxy.web import form_builder from galaxy.web.base.controller import BaseUIController, ERROR, SUCCESS, url_for, UsesExtendedMetadataMixin from galaxy.web.framework.helpers import grids, iff, time_ago, to_unicode -from galaxy.tools.errors import EmailErrorReporter log = logging.getLogger( __name__ ) @@ -160,18 +159,6 @@ class DatasetInterface( BaseUIController, UsesAnnotations, UsesItemRatings, Uses exit_code = "Invalid dataset ID or you are not allowed to access this dataset" return exit_code - @web.expose - def report_error( self, trans, id, email='', message="", **kwd ): - biostar_report = 'biostar' in str( kwd.get( 'submit_error_report') ).lower() - if biostar_report: - return trans.response.send_redirect( url_for( controller='biostar', action='biostar_tool_bug_report', hda=id, email=email, message=message ) ) - try: - error_reporter = EmailErrorReporter( id, trans.app ) - error_reporter.send_report( user=trans.user, email=email, message=message ) - return trans.show_ok_message( "Your error report has been sent" ) - except Exception as e: - return trans.show_error_message( "An error occurred sending the report by email: %s" % str( e ) ) - @web.expose def default(self, trans, dataset_id=None, **kwd): return 'This link may not be followed from within Galaxy.' diff --git a/lib/galaxy/webapps/galaxy/controllers/library_common.py b/lib/galaxy/webapps/galaxy/controllers/library_common.py index 41890760daa..36b195dea6f 100644 --- a/lib/galaxy/webapps/galaxy/controllers/library_common.py +++ b/lib/galaxy/webapps/galaxy/controllers/library_common.py @@ -1151,6 +1151,7 @@ class LibraryCommon( BaseUIController, UsesFormDefinitionsMixin, UsesExtendedMet uploaded_dataset.dbkey = params.get( 'dbkey', None ) uploaded_dataset.to_posix_lines = params.get('to_posix_lines', None) uploaded_dataset.space_to_tab = params.get( 'space_to_tab', None ) + uploaded_dataset.tag_using_filenames = params.get( 'tag_using_filenames', True ) if in_folder: uploaded_dataset.in_folder = in_folder uploaded_dataset.data = upload_common.new_upload( trans, cntrller, uploaded_dataset, library_bunch ) diff --git a/lib/galaxy/workflow/extract.py b/lib/galaxy/workflow/extract.py index 8bf16245826..aec7e3336c3 100644 --- a/lib/galaxy/workflow/extract.py +++ b/lib/galaxy/workflow/extract.py @@ -305,7 +305,7 @@ class WorkflowSummary( object ): def step_inputs( trans, job ): - tool = trans.app.toolbox.get_tool( job.tool_id ) + tool = trans.app.toolbox.get_tool( job.tool_id, tool_version=job.tool_version ) param_values = job.get_param_values( trans.app, ignore_errors=True ) # If a tool was updated and e.g. had a text value changed to an integer, we don't want a traceback here associations = __cleanup_param_values( tool.inputs, param_values ) tool_inputs = tool.params_to_strings( param_values, trans.app ) diff --git a/lib/tool_shed/metadata/metadata_generator.py b/lib/tool_shed/metadata/metadata_generator.py index c32fc9f8973..87a3ced6599 100644 --- a/lib/tool_shed/metadata/metadata_generator.py +++ b/lib/tool_shed/metadata/metadata_generator.py @@ -680,6 +680,7 @@ class MetadataGenerator( object ): guid=guid, name=tool.name, version=tool.version, + profile=tool.profile, description=tool.description, version_string_cmd=tool.version_string_cmd, tool_config=tool_config, diff --git a/lib/tool_shed/util/workflow_util.py b/lib/tool_shed/util/workflow_util.py index 1222eece3ed..66a9e0173ce 100644 --- a/lib/tool_shed/util/workflow_util.py +++ b/lib/tool_shed/util/workflow_util.py @@ -49,7 +49,7 @@ class RepoToolModule( ToolModule ): break else: # We're in Galaxy. - self.tool = trans.app.toolbox.get_tool( self.tool_id ) + self.tool = trans.app.toolbox.get_tool( self.tool_id, tool_version=self.tool_version ) if self.tool is None: self.errors = 'unavailable' self.post_job_actions = {} diff --git a/lib/tool_shed/utility_containers/utility_container_manager.py b/lib/tool_shed/utility_containers/utility_container_manager.py index 0000b9792d3..d9961c8ed4b 100644 --- a/lib/tool_shed/utility_containers/utility_container_manager.py +++ b/lib/tool_shed/utility_containers/utility_container_manager.py @@ -136,7 +136,7 @@ class RepositoryDependency( object ): class Tool( object ): """Tool object""" - def __init__( self, id=None, tool_config=None, tool_id=None, name=None, description=None, version=None, requirements=None, + def __init__( self, id=None, tool_config=None, tool_id=None, name=None, description=None, version=None, profile=None, requirements=None, repository_id=None, changeset_revision=None, repository_installation_status=None ): self.id = id self.tool_config = tool_config @@ -144,6 +144,7 @@ class Tool( object ): self.name = name self.description = description self.version = version + self.profile = profile self.requirements = requirements self.repository_id = repository_id self.changeset_revision = changeset_revision @@ -438,6 +439,7 @@ class UtilityContainerManager( object ): name='Name', description='Description', version='Version', + profile='Minimum Galaxy Version', requirements='', repository_id='', changeset_revision='' ) @@ -479,6 +481,7 @@ class UtilityContainerManager( object ): name = str( tool_dict.get( 'name', 'unknown' ) ) description = str( tool_dict.get( 'description', '' ) ) version = str( tool_dict.get( 'version', 'unknown' ) ) + profile = str( tool_dict.get('profile', 'any')) except Exception as e: tool_config = str( e ) tool_id = 'unknown' @@ -491,6 +494,7 @@ class UtilityContainerManager( object ): name=name, description=description, version=version, + profile=profile, requirements=requirements_str, repository_id=repository_id, changeset_revision=changeset_revision, diff --git a/scripts/grt/export.py b/scripts/grt/export.py index 53cace28415..4619c6929c6 100644 --- a/scripts/grt/export.py +++ b/scripts/grt/export.py @@ -16,7 +16,7 @@ import logging from collections import defaultdict -sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'lib'))) +sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'lib'))) from galaxy.util.properties import load_app_properties import galaxy @@ -32,7 +32,7 @@ def _init(config, need_app=False): if config.startswith('/'): config_file = os.path.abspath(config) else: - config_file = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, config)) + config_file = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, config)) properties = load_app_properties(ini_file=config_file) config = galaxy.config.Configuration(**properties) @@ -292,6 +292,9 @@ def main(argv): .filter(model.JobMetricNumeric.job_id > offset_start) \ .filter(model.JobMetricNumeric.job_id <= min(end_job_id, offset_start + args.batch_size)) \ .all(): + # No associated job + if metric[0] not in job_tool_map: + continue # If the tool is blacklisted, exclude everywhere if job_tool_map[metric[0]] in blacklisted_tools: continue @@ -316,6 +319,9 @@ def main(argv): .filter(model.JobParameter.job_id > offset_start) \ .filter(model.JobParameter.job_id <= min(end_job_id, offset_start + args.batch_size)) \ .all(): + # No associated job + if param[0] not in job_tool_map: + continue # If the tool is blacklisted, exclude everywhere if job_tool_map[param[0]] in blacklisted_tools: continue diff --git a/scripts/grt/upload.py b/scripts/grt/upload.py index bc3513337b7..332cbe89e6d 100644 --- a/scripts/grt/upload.py +++ b/scripts/grt/upload.py @@ -3,8 +3,6 @@ See doc/source/admin/grt.rst for more detailed usage information. """ -from __future__ import print_function - import argparse import os import sys @@ -37,7 +35,7 @@ def main(argv): config = yaml.load(handle) REPORT_DIR = args.report_directory - GRT_URL = config['grt']['url'] + GRT_URL = config['grt']['url'].rstrip('/') + '/' GRT_INSTANCE_ID = config['grt']['instance_id'] GRT_API_KEY = config['grt']['api_key'] @@ -55,8 +53,8 @@ def main(argv): if report_id not in remote_reports: logging.info("Uploading %s", report_id) files = { - 'meta': open(os.path.join(sys.argv[1], report_id + '.json'), 'rb'), - 'data': open(os.path.join(sys.argv[1], report_id + '.tsv.gz'), 'rb') + 'meta': open(os.path.join(REPORT_DIR, report_id + '.json'), 'rb'), + 'data': open(os.path.join(REPORT_DIR, report_id + '.tar.gz'), 'rb') } data = { 'identifier': report_id diff --git a/static/maps/mvc/dataset/dataset-error.js.map b/static/maps/mvc/dataset/dataset-error.js.map new file mode 100644 index 00000000000..02d7d5db6d9 --- /dev/null +++ b/static/maps/mvc/dataset/dataset-error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dataset-error.js","sources":["../../../src/mvc/dataset/dataset-error.js"],"names":["define","Utils","Ui","Form","View","Backbone","extend","initialize","this","setElement","model","Model","dataset_id","Galaxy","params","render","data_url","root","get","self","url","success","dataset","job_url","creating_job","job","render_error_page","error","error_response","status","message","persistent","cls","display_message","$","$el","empty","append","_templateHeader","tool_id","stderr","_getBugFormTemplate","response","doNotClear","safe","UnescapedMessage","html","Message","inputs","help","options","type","name","label","value","user","area","form","title","buttons","save","Button","icon","floating","onclick","form_data","data","create","id","submit","ajax","messages","forEach"],"mappings":"AAAAA,QAAU,cAAe,iBAAkB,sBAAwB,SAAUC,EAAOC,EAAIC,GAGpF,GAAIC,GAAOC,SAASD,KAAKE,QACrBC,WAAY,WACRC,KAAKC,WAAY,UACjBD,KAAKE,MAAQ,GAAIL,UAASM,OAASC,WAAcC,OAAOC,OAAOF,aAC/DJ,KAAKO,UAITA,OAAQ,WACJ,GAAIC,GAAWH,OAAOI,KAAO,gBAAkBT,KAAKE,MAAMQ,IAAK,cAC3DC,EAAOX,IAEXP,GAAMiB,KACFE,IAAUJ,EACVK,QAAU,SAAUC,GAChB,GAAIC,GAAUV,OAAOI,KAAO,YAAcK,EAAQE,aAAe,YACjEvB,GAAMiB,KACFE,IAAUG,EACVF,QAAU,SAAUI,GACFZ,OAAOI,KAAO,YAAcK,EAAQE,aAAe,YACjEL,GAAKO,kBAAmBP,EAAMG,EAASG,IAE3CE,MAAU,WACN,GAAIC,IACAC,OAAU,QACVC,QAAW,uCACXC,YAAc,EACdC,IAAO,eAEXb,GAAKc,gBAAiBL,EAAgBT,EAAKe,EAAG,0BAI1DP,MAAU,WACN,GAAIC,IACAC,OAAU,QACVC,QAAW,2CACXC,YAAc,EACdC,IAAO,eAEXb,GAAKc,gBAAiBL,EAAgBT,EAAKe,EAAG,0BAM1DR,kBAAmB,SAAUP,EAAMG,EAASG,GACxCN,EAAKgB,IAAIC,QAAQC,OAAQlB,EAAKmB,mBAC9BnB,EAAKgB,IAAIE,OAAO,0BAChBlB,EAAKgB,IAAIE,OAAO,iDAAmDZ,EAAIc,QAAU,aACjFpB,EAAKgB,IAAIE,OAAO,2DAChBlB,EAAKgB,IAAIE,OAAO,qBAAuBZ,EAAIe,OAAS,UACpDrB,EAAKgB,IAAIE,OAAO,+BAChBlB,EAAKgB,IAAIE,OAAO,oUAChBlB,EAAKgB,IAAIE,OAAOlB,EAAKsB,oBAAoBnB,EAASG,KAItDQ,gBAAiB,SAAUS,EAAUP,EAAKQ,EAAYC,GAC9CA,EAOGD,EACCR,EAAIE,OAAQ,GAAInC,GAAG2C,iBAAkBH,GAAWP,KAEhDA,EAAIC,QAAQU,KAAM,GAAI5C,GAAG2C,iBAAkBH,GAAWP,KATvDQ,EACCR,EAAIE,OAAQ,GAAInC,GAAG6C,QAASL,GAAWP,KAEvCA,EAAIC,QAAQU,KAAM,GAAI5C,GAAG6C,QAASL,GAAWP,MAYzDG,gBAAiB,WACb,MAAO,oFAMXG,oBAAqB,SAASnB,EAASG,GACnC,GAAIN,GAAOX,KACPwC,IAEIC,KAAQ,qBACRC,WACAC,KAAQ,OACRC,KAAQ,QACRC,MAAS,aACTC,MAASzC,OAAO0C,KAAKrC,IAAI,WAGzB+B,KAAQ,gGACRC,WACAC,KAAQ,OACRK,MAAQ,EACRJ,KAAQ,UACRC,MAAS,YAgBbI,EAAO,GAAItD,IACXuD,MAAS,eACTV,OAASA,EACTW,SACIC,KAAU,GAAI1D,GAAG2D,QACbC,KAAW,SACXJ,MAAW,SACX1B,IAAW,4BACX+B,SAAW,QACXC,QAAW,WACP,GAAIC,GAAYR,EAAKS,KAAKC,SACtB/C,EAAMP,OAAOI,KAAO,YAAcQ,EAAI2C,GAAK,QAC/CH,GAAUrD,WAAaU,EAAQ8C,GAC/BjD,EAAKkD,OAAOJ,EAAW7C,QAKvC,OAAOqC,GAAKtB,KAIhBkC,OAAS,SAASJ,EAAW7C,GACzB,GAAID,GAAOX,IAEX0B,GAAEoC,MACEnB,KAAM,OACN/B,IAAKA,EACL8C,KAAMD,EACN5C,QAAS,SAAUqB,GAEfvB,EAAKgB,IAAIC,QAAQC,OAAQlB,EAAKmB,mBAE9BI,EAAS6B,SAASC,QAAQ,SAAS1C,GAC/BX,EAAKc,iBACDJ,OAAUC,EAAQ,GAClBA,QAAWA,EAAQ,GACnBC,YAAc,GACfZ,EAAKe,EAAG,sBAAuB,GAAM,MAGhDP,MAAU,WACN,GAAIC,IACAC,OAAU,QACVC,QAAW,iFACXC,YAAc,EACdC,IAAO,eAEXb,GAAKc,gBAAiBL,EAAgBT,EAAKe,EAAG,2BAM9D,QACI9B,KAAQA"} \ No newline at end of file diff --git a/static/maps/mvc/dataset/dataset-li-edit.js.map b/static/maps/mvc/dataset/dataset-li-edit.js.map index ad95871b3f7..64371b3ba7c 100644 --- a/static/maps/mvc/dataset/dataset-li-edit.js.map +++ b/static/maps/mvc/dataset/dataset-li-edit.js.map @@ -1 +1 @@ -{"version":3,"file":"dataset-li-edit.js","sources":["../../../src/mvc/dataset/dataset-li-edit.js"],"names":["define","STATES","DATASET_LI","TAGS","ANNOTATIONS","faIconButton","BASE_MVC","_l","_super","DatasetListItemView","DatasetListItemEdit","extend","initialize","attributes","prototype","call","this","hasUser","purgeAllowed","tagsEditorShown","annotationEditorShown","_renderPrimaryActions","actions","model","get","NOT_VIEWABLE","concat","_renderEditButton","_renderDeleteButton","DISCARDED","purged","deleted","editBtnData","title","href","Galaxy","root","id","faIcon","classes","disabled","_","contains","UPLOAD","NEW","self","deletedAlready","isDeletedOrPurged","onclick","$el","find","trigger","_renderDetails","$details","state","OK","FAILED_METADATA","_renderTags","_renderAnnotation","_makeDbkeyEditLink","_setUpBehaviors","_renderToolHelpButton","datasetID","dataset_id","jobID","creating_job","parseToolBuild","data","helpString","name","help","append","$","parseHTML","parseToolID","ajax","url","tool_id","done","fail","user","length","toggle","console","log","_renderSecondaryActions","ERROR","unshift","_renderErrButton","_renderRerunButton","_renderVisualizationsButton","urls","report_error","target","linkTarget","rerun","ev","preventDefault","router","push","job_id","visualizations","hasData","isEmpty","isObject","warn","$visualizations","templates","attr","_addScratchBookFn","addBack","$links","click","frame","active","add","stopPropagation","$where","view","tagsEditor","TagsEditor","el","onshowFirstTime","render","onshow","onhide","$activator","appendTo","annotationEditor","AnnotationEditor","editableDbkey","edit","replaceWith","events","clone","click .undelete-link","click .purge-link","click .edit-btn","click .delete-btn","click .rerun-btn","click .report-err-btn","click .visualization-btn","click .dbkey a","_clickUndeleteLink","undelete","_clickPurgeLink","confirm","purge","toString","modelString","warnings","failed_metadata","wrapTemplate","visualizationsTemplate"],"mappings":"AAAAA,QACI,qBACA,yBACA,UACA,iBACA,oBACA,eACA,sBACD,SAAUC,EAAQC,EAAYC,EAAMC,EAAaC,EAAcC,EAAUC,GAE5E,YAEA,IAAIC,GAASN,EAAWO,oBAGpBC,EAAsBF,EAAOG,QAI7BC,WAAc,SAAUC,GACpBL,EAAOM,UAAUF,WAAWG,KAAMC,KAAMH,GACxCG,KAAKC,QAAUJ,EAAWI,QAG1BD,KAAKE,aAAeL,EAAWK,eAAgB,EAI/CF,KAAKG,gBAAyBN,EAAWM,kBAAmB,EAE5DH,KAAKI,sBAAyBP,EAAWO,wBAAyB,GAKtEC,sBAAwB,WACpB,GAAIC,GAAUd,EAAOM,UAAUO,sBAAsBN,KAAMC,KAC3D,OAAIA,MAAKO,MAAMC,IAAK,WAAcvB,EAAOwB,aAC9BH,EAGJd,EAAOM,UAAUO,sBAAsBN,KAAMC,MAAOU,QACvDV,KAAKW,oBACLX,KAAKY,yBAObD,kBAAoB,WAGhB,GAAMX,KAAKO,MAAMC,IAAK,WAAcvB,EAAO4B,YACpCb,KAAKO,MAAMC,IAAK,cACnB,MAAO,KAGX,IAAIM,GAASd,KAAKO,MAAMC,IAAK,UACzBO,EAAUf,KAAKO,MAAMC,IAAK,WAC1BQ,GACIC,MAAc1B,EAAI,mBAClB2B,KAAcC,OAAOC,KAAO,4BAA8BpB,KAAKO,MAAMV,WAAWwB,GAChFC,OAAc,YACdC,QAAc,WAgBtB,OAbIR,IAAWD,GACXE,EAAYQ,UAAW,EACnBV,EACAE,EAAYC,MAAQ1B,EAAI,wDACjBwB,IACPC,EAAYC,MAAQ1B,EAAI,yCAIrBkC,EAAEC,UAAYzC,EAAO0C,OAAQ1C,EAAO2C,KAAO5B,KAAKO,MAAMC,IAAK,YAClEQ,EAAYQ,UAAW,EACvBR,EAAYC,MAAQ1B,EAAI,qCAErBF,EAAc2B,IAIzBJ,oBAAsB,WAElB,IAAOZ,KAAKO,MAAMC,IAAK,cACnB,MAAO,KAGX,IAAIqB,GAAO7B,KACP8B,EAAiB9B,KAAKO,MAAMwB,mBAChC,OAAO1C,IACC4B,MAAgD1B,EAAjCuC,EAAqC,6BAAjB,UACnCN,SAAcM,EACdR,OAAc,WACdC,QAAc,aACdS,QAAc,WAEVH,EAAKI,IAAIC,KAAM,wBAAyBC,QAAS,YACjDN,EAAKtB,MAAgB,aAOrC6B,eAAiB,WAEb,GAAIC,GAAW7C,EAAOM,UAAUsC,eAAerC,KAAMC,MACjDsC,EAAQtC,KAAKO,MAAMC,IAAK,QAS5B,QAPKR,KAAKO,MAAMwB,qBAAuBN,EAAEC,UAAWzC,EAAOsD,GAAItD,EAAOuD,iBAAmBF,KACrFtC,KAAKyC,YAAaJ,GAClBrC,KAAK0C,kBAAmBL,GACxBrC,KAAK2C,mBAAoBN,IAG7BrC,KAAK4C,gBAAiBP,GACfA,GAOXQ,sBAAwB,WACpB,GAAIC,GAAY9C,KAAKO,MAAMV,WAAWkD,WAClCC,EAAQhD,KAAKO,MAAMV,WAAWoD,aAC9BpB,EAAO7B,KAEPkD,EAAiB,SAASC,GAC1B,GAAIC,GAAa,kBAAoBN,EAAY,qBAC7CK,GAAKE,MAAQF,EAAKG,MAClBF,GAAc,yBAA2BD,EAAKE,KAAO,iBACrDD,GAAcD,EAAKG,MAEnBF,GAAc,mEAElBA,GAAc,SACdvB,EAAKI,IAAIC,KAAM,YAAaqB,OAAOC,EAAEC,UAAUL,KAE/CM,EAAc,SAASP,GACvBK,EAAEG,MACEC,IAAKzC,OAAOC,KAAO,aAAe+B,EAAKU,QAAU,WAClDC,KAAK,SAASX,GACbD,EAAeC,KAChBY,KAAK,WACJb,QAGR,OAAuB,QAAnB/B,OAAO6C,KAAK3C,GACL,KAEJhC,GACH4B,MAAO1B,EAAG,aACVgC,QAAS,WACTL,KAAM,IACNI,OAAQ,cACRU,QAAS,WAEDH,EAAKI,IAAIC,KAAK,aAAa+B,OAAS,EACpCpC,EAAKI,IAAIC,KAAK,aAAagC,SAE3BV,EAAEG,MACEC,IAAKzC,OAAOC,KAAO,YAAc4B,IAClCc,KAAK,SAASX,GACbO,EAAYP,KACbY,KAAK,WACLI,QAAQC,IAAI,yEAA2EpB,EAAQ,YASlHqB,wBAA0B,WACtB,GAAI/D,GAAUd,EAAOM,UAAUuE,wBAAwBtE,KAAMC,KAC7D,QAAQA,KAAKO,MAAMC,IAAK,UACpB,IAAKvB,GAAO0C,OACZ,IAAK1C,GAAOwB,aACR,MAAOH,EACX,KAAKrB,GAAOqF,MAGR,MADAhE,GAAQiE,QAASvE,KAAKwE,oBACflE,EAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK6C,yBAC5D,KAAK5D,GAAOsD,GACZ,IAAKtD,GAAOuD,gBACR,MAAOlC,GAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK0E,8BAA+B1E,KAAK6C,0BAEpG,MAAOvC,GAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK6C,2BAI5D2B,iBAAmB,WACf,MAAOnF,IACH4B,MAAc1B,EAAI,6BAClB2B,KAAclB,KAAKO,MAAMoE,KAAKC,aAC9BrD,QAAc,mBACdsD,OAAc7E,KAAK8E,WACnBxD,OAAc,YAKtBmD,mBAAqB,WACjB,GAAIxB,GAAejD,KAAKO,MAAMC,IAAK,eACnC,OAAIR,MAAKO,MAAMC,IAAK,cACTnB,GACH4B,MAAc1B,EAAI,sBAClB2B,KAAclB,KAAKO,MAAMoE,KAAKI,MAC9BxD,QAAc,YACdsD,OAAc7E,KAAK8E,WACnBxD,OAAc,aACdU,QAAc,SAAUgD,GACpBA,EAAGC,iBACH9D,OAAO+D,OAAOC,KAAM,KAAOC,OAASnC,OAThD,QAgBJyB,4BAA8B,WAE1B,GAAIW,GAAiBrF,KAAKO,MAAMC,IAAK,iBACrC,IAAMR,KAAKO,MAAMwB,sBACV/B,KAAKC,UACLD,KAAKO,MAAM+E,WACZ7D,EAAE8D,QAASF,GACb,MAAO,KAEX,KAAK5D,EAAE+D,SAAUH,EAAe,IAE5B,MADArF,MAAKyF,KAAM,yCACJ,IAGX,IAAIC,GAAkBlC,EAAGxD,KAAK2F,UAAUN,eAAgBA,EAAgBrF,MAKxE,OAHA0F,GAAgBxD,KAAM,0BAA0B0D,KAAM,SAAU5F,KAAK8E,YAErE9E,KAAK6F,kBAAmBH,EAAgBxD,KAAM,uBAAwB4D,QAAS,wBACxEJ,GAIXG,kBAAoB,SAAUE,GAE1BA,EAAOC,MAAO,SAAUhB,GAChB7D,OAAO8E,OAAS9E,OAAO8E,MAAMC,SAC7B/E,OAAO8E,MAAME,KACTlF,MAAc,gBACd2C,IAAcJ,EAAGxD,MAAO4F,KAAM,UAElCZ,EAAGC,iBACHD,EAAGoB,sBAOf3D,YAAc,SAAU4D,GACpB,GAAKrG,KAAKC,QAAV,CACA,GAAIqG,GAAOtG,IACXA,MAAKuG,WAAa,GAAIpH,GAAKqH,YACvBjG,MAAkBP,KAAKO,MACvBkG,GAAkBJ,EAAOnE,KAAM,iBAC/BwE,gBAAkB,WAAY1G,KAAK2G,UAEnCC,OAAkB,WAAYN,EAAKnG,iBAAkB,GACrD0G,OAAkB,WAAYP,EAAKnG,iBAAkB,GACrD2G,WAAkBzH,GACd4B,MAAU1B,EAAI,qBACdgC,QAAU,UACVD,OAAU,YACXyF,SAAUV,EAAOnE,KAAM,sBAE1BlC,KAAKG,iBAAmBH,KAAKuG,WAAWrC,QAAQ,KAIxDxB,kBAAoB,SAAU2D,GAC1B,GAAKrG,KAAKC,QAAV,CACA,GAAIqG,GAAOtG,IACXA,MAAKgH,iBAAmB,GAAI5H,GAAY6H,kBACpC1G,MAAkBP,KAAKO,MACvBkG,GAAkBJ,EAAOnE,KAAM,uBAC/BwE,gBAAkB,WAAY1G,KAAK2G,UAEnCC,OAAkB,WAAYN,EAAKlG,uBAAwB,GAC3DyG,OAAkB,WAAYP,EAAKlG,uBAAwB,GAC3D0G,WAAkBzH,GACd4B,MAAU1B,EAAI,2BACdgC,QAAU,eACVD,OAAU,eACXyF,SAAUV,EAAOnE,KAAM,sBAE1BlC,KAAKI,uBAAyBJ,KAAKgH,iBAAiB9C,QAAQ,KAIpEvB,mBAAqB,SAAUN,GAE3B,GAA2C,MAAvCrC,KAAKO,MAAMC,IAAK,oBACfR,KAAKO,MAAMwB,oBAAqB,CACjC,GAAImF,GAAgB1D,EAAG,0BAClBoC,KAAM,OAAQ5F,KAAKO,MAAMoE,KAAKwC,MAC9BvB,KAAM,SAAU5F,KAAK8E,WAC1BzC,GAASH,KAAM,iBAAkBkF,YAAaF,KAMtDG,OAAS5F,EAAE9B,OAAQ8B,EAAE6F,MAAO9H,EAAOM,UAAUuH,SACzCE,uBAA0B,qBAC1BC,oBAA0B,kBAE1BC,kBAA0B,SAAUzC,GAAMhF,KAAKmC,QAAS,OAAQnC,KAAMgF,IACtE0C,oBAA0B,SAAU1C,GAAMhF,KAAKmC,QAAS,SAAUnC,KAAMgF,IACxE2C,mBAA0B,SAAU3C,GAAMhF,KAAKmC,QAAS,QAASnC,KAAMgF,IACvE4C,wBAA0B,SAAU5C,GAAMhF,KAAKmC,QAAS,aAAcnC,KAAMgF,IAC5E6C,2BAA6B,SAAU7C,GAAMhF,KAAKmC,QAAS,YAAanC,KAAMgF,IAC9E8C,iBAA0B,SAAU9C,GAAMhF,KAAKmC,QAAS,OAAQnC,KAAMgF,MAI1E+C,mBAAqB,WAEjB,MADA/H,MAAKO,MAAMyH,YACJ,GAIXC,gBAAkB,WAId,MAHIC,SAAS3I,EAAI,0EACbS,KAAKO,MAAM4H,SAER,GAKXC,SAAW,WACP,GAAIC,GAAgBrI,KAAW,MAAIA,KAAKO,MAAQ,GAAK,YACrD,OAAO,eAAiB8H,EAAc,MAwE1C,OAjEJ3I,GAAoBI,UAAU6F,UAAa,WAEvC,GAAI2C,GAAW7G,EAAE9B,UAAYH,EAAOM,UAAU6F,UAAU2C,UACpDC,gBAAkBjJ,EAASkJ,cAEvB,mDACI,4DACIjJ,EAAI,2DACJ,4EACIA,EAAI,2CACR,OACJ,SACJ,WACD,WAEHwB,QAAUzB,EAASkJ,cAEf,kDAEI,gDACIjJ,EAAI,iCACJ,6DAA8DA,EAAI,eAAiB,OACnF,iCACI,0DACIA,EAAI,mCACR,OACJ,UACJ,SACJ,WACD,aAGHkJ,EAAyBnJ,EAASkJ,cAClC,2CACI,8EACQ,oDAAqDjJ,EAAI,gBACzD,mCACJ,0CACJ,OAEJ,iBACI,0DACI,oCAAqCA,EAAI,aAAe,KACpD,0CACJ,OACA,yCACI,2DACI,qEACQ,yCACJ,4BACJ,YACJ,YACJ,QACJ,SACJ,WACD,iBAEH,OAAOkC,GAAE9B,UAAYH,EAAOM,UAAU6F,WAClC2C,SAAWA,EACXjD,eAAiBoD,QAOjB/I,oBAAsBA"} \ No newline at end of file +{"version":3,"file":"dataset-li-edit.js","sources":["../../../src/mvc/dataset/dataset-li-edit.js"],"names":["define","STATES","DATASET_LI","TAGS","ANNOTATIONS","faIconButton","BASE_MVC","_l","_super","DatasetListItemView","DatasetListItemEdit","extend","initialize","attributes","prototype","call","this","hasUser","purgeAllowed","tagsEditorShown","annotationEditorShown","_renderPrimaryActions","actions","model","get","NOT_VIEWABLE","concat","_renderEditButton","_renderDeleteButton","DISCARDED","purged","deleted","editBtnData","title","href","Galaxy","root","id","faIcon","classes","disabled","_","contains","UPLOAD","NEW","self","deletedAlready","isDeletedOrPurged","onclick","$el","find","trigger","_renderDetails","$details","state","OK","FAILED_METADATA","_renderTags","_renderAnnotation","_makeDbkeyEditLink","_setUpBehaviors","_renderToolHelpButton","datasetID","dataset_id","jobID","creating_job","parseToolBuild","data","helpString","name","help","append","$","parseHTML","parseToolID","ajax","url","tool_id","done","fail","user","length","toggle","console","log","_renderSecondaryActions","ERROR","unshift","_renderErrButton","_renderRerunButton","_renderVisualizationsButton","urls","rerun","target","linkTarget","ev","preventDefault","router","push","job_id","visualizations","hasData","isEmpty","isObject","warn","$visualizations","templates","attr","_addScratchBookFn","addBack","$links","click","frame","active","add","stopPropagation","$where","view","tagsEditor","TagsEditor","el","onshowFirstTime","render","onshow","onhide","$activator","appendTo","annotationEditor","AnnotationEditor","editableDbkey","edit","replaceWith","events","clone","click .undelete-link","click .purge-link","click .edit-btn","click .delete-btn","click .rerun-btn","click .report-err-btn","click .visualization-btn","click .dbkey a","_clickUndeleteLink","undelete","_clickPurgeLink","confirm","purge","toString","modelString","warnings","failed_metadata","wrapTemplate","visualizationsTemplate"],"mappings":"AAAAA,QACI,qBACA,yBACA,UACA,iBACA,oBACA,eACA,sBACD,SAAUC,EAAQC,EAAYC,EAAMC,EAAaC,EAAcC,EAAUC,GAE5E,YAEA,IAAIC,GAASN,EAAWO,oBAGpBC,EAAsBF,EAAOG,QAI7BC,WAAc,SAAUC,GACpBL,EAAOM,UAAUF,WAAWG,KAAMC,KAAMH,GACxCG,KAAKC,QAAUJ,EAAWI,QAG1BD,KAAKE,aAAeL,EAAWK,eAAgB,EAI/CF,KAAKG,gBAAyBN,EAAWM,kBAAmB,EAE5DH,KAAKI,sBAAyBP,EAAWO,wBAAyB,GAKtEC,sBAAwB,WACpB,GAAIC,GAAUd,EAAOM,UAAUO,sBAAsBN,KAAMC,KAC3D,OAAIA,MAAKO,MAAMC,IAAK,WAAcvB,EAAOwB,aAC9BH,EAGJd,EAAOM,UAAUO,sBAAsBN,KAAMC,MAAOU,QACvDV,KAAKW,oBACLX,KAAKY,yBAObD,kBAAoB,WAGhB,GAAMX,KAAKO,MAAMC,IAAK,WAAcvB,EAAO4B,YACpCb,KAAKO,MAAMC,IAAK,cACnB,MAAO,KAGX,IAAIM,GAASd,KAAKO,MAAMC,IAAK,UACzBO,EAAUf,KAAKO,MAAMC,IAAK,WAC1BQ,GACIC,MAAc1B,EAAI,mBAClB2B,KAAcC,OAAOC,KAAO,4BAA8BpB,KAAKO,MAAMV,WAAWwB,GAChFC,OAAc,YACdC,QAAc,WAgBtB,OAbIR,IAAWD,GACXE,EAAYQ,UAAW,EACnBV,EACAE,EAAYC,MAAQ1B,EAAI,wDACjBwB,IACPC,EAAYC,MAAQ1B,EAAI,yCAIrBkC,EAAEC,UAAYzC,EAAO0C,OAAQ1C,EAAO2C,KAAO5B,KAAKO,MAAMC,IAAK,YAClEQ,EAAYQ,UAAW,EACvBR,EAAYC,MAAQ1B,EAAI,qCAErBF,EAAc2B,IAIzBJ,oBAAsB,WAElB,IAAOZ,KAAKO,MAAMC,IAAK,cACnB,MAAO,KAGX,IAAIqB,GAAO7B,KACP8B,EAAiB9B,KAAKO,MAAMwB,mBAChC,OAAO1C,IACC4B,MAAgD1B,EAAjCuC,EAAqC,6BAAjB,UACnCN,SAAcM,EACdR,OAAc,WACdC,QAAc,aACdS,QAAc,WAEVH,EAAKI,IAAIC,KAAM,wBAAyBC,QAAS,YACjDN,EAAKtB,MAAgB,aAOrC6B,eAAiB,WAEb,GAAIC,GAAW7C,EAAOM,UAAUsC,eAAerC,KAAMC,MACjDsC,EAAQtC,KAAKO,MAAMC,IAAK,QAS5B,QAPKR,KAAKO,MAAMwB,qBAAuBN,EAAEC,UAAWzC,EAAOsD,GAAItD,EAAOuD,iBAAmBF,KACrFtC,KAAKyC,YAAaJ,GAClBrC,KAAK0C,kBAAmBL,GACxBrC,KAAK2C,mBAAoBN,IAG7BrC,KAAK4C,gBAAiBP,GACfA,GAOXQ,sBAAwB,WACpB,GAAIC,GAAY9C,KAAKO,MAAMV,WAAWkD,WAClCC,EAAQhD,KAAKO,MAAMV,WAAWoD,aAC9BpB,EAAO7B,KAEPkD,EAAiB,SAASC,GAC1B,GAAIC,GAAa,kBAAoBN,EAAY,qBAC7CK,GAAKE,MAAQF,EAAKG,MAClBF,GAAc,yBAA2BD,EAAKE,KAAO,iBACrDD,GAAcD,EAAKG,MAEnBF,GAAc,mEAElBA,GAAc,SACdvB,EAAKI,IAAIC,KAAM,YAAaqB,OAAOC,EAAEC,UAAUL,KAE/CM,EAAc,SAASP,GACvBK,EAAEG,MACEC,IAAKzC,OAAOC,KAAO,aAAe+B,EAAKU,QAAU,WAClDC,KAAK,SAASX,GACbD,EAAeC,KAChBY,KAAK,WACJb,QAGR,OAAuB,QAAnB/B,OAAO6C,KAAK3C,GACL,KAEJhC,GACH4B,MAAO1B,EAAG,aACVgC,QAAS,WACTL,KAAM,IACNI,OAAQ,cACRU,QAAS,WAEDH,EAAKI,IAAIC,KAAK,aAAa+B,OAAS,EACpCpC,EAAKI,IAAIC,KAAK,aAAagC,SAE3BV,EAAEG,MACEC,IAAKzC,OAAOC,KAAO,YAAc4B,IAClCc,KAAK,SAASX,GACbO,EAAYP,KACbY,KAAK,WACLI,QAAQC,IAAI,yEAA2EpB,EAAQ,YASlHqB,wBAA0B,WACtB,GAAI/D,GAAUd,EAAOM,UAAUuE,wBAAwBtE,KAAMC,KAC7D,QAAQA,KAAKO,MAAMC,IAAK,UACpB,IAAKvB,GAAO0C,OACZ,IAAK1C,GAAOwB,aACR,MAAOH,EACX,KAAKrB,GAAOqF,MAGR,MADAhE,GAAQiE,QAASvE,KAAKwE,oBACflE,EAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK6C,yBAC5D,KAAK5D,GAAOsD,GACZ,IAAKtD,GAAOuD,gBACR,MAAOlC,GAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK0E,8BAA+B1E,KAAK6C,0BAEpG,MAAOvC,GAAQI,QAASV,KAAKyE,qBAAsBzE,KAAK6C,2BAI5D2B,iBAAmB,WACf,MAAOnF,IACH4B,MAAc1B,EAAI,6BAClB2B,KAAcC,OAAOC,KAAO,6BAA+BpB,KAAKO,MAAMV,WAAWwB,GACjFE,QAAc,mBACdD,OAAc,YAKtBmD,mBAAqB,WACjB,GAAIxB,GAAejD,KAAKO,MAAMC,IAAK,eACnC,OAAIR,MAAKO,MAAMC,IAAK,cACTnB,GACH4B,MAAc1B,EAAI,sBAClB2B,KAAclB,KAAKO,MAAMoE,KAAKC,MAC9BrD,QAAc,YACdsD,OAAc7E,KAAK8E,WACnBxD,OAAc,aACdU,QAAc,SAAU+C,GACpBA,EAAGC,iBACH7D,OAAO8D,OAAOC,KAAM,KAAOC,OAASlC,OAThD,QAgBJyB,4BAA8B,WAE1B,GAAIU,GAAiBpF,KAAKO,MAAMC,IAAK,iBACrC,IAAMR,KAAKO,MAAMwB,sBACV/B,KAAKC,UACLD,KAAKO,MAAM8E,WACZ5D,EAAE6D,QAASF,GACb,MAAO,KAEX,KAAK3D,EAAE8D,SAAUH,EAAe,IAE5B,MADApF,MAAKwF,KAAM,yCACJ,IAGX,IAAIC,GAAkBjC,EAAGxD,KAAK0F,UAAUN,eAAgBA,EAAgBpF,MAKxE,OAHAyF,GAAgBvD,KAAM,0BAA0ByD,KAAM,SAAU3F,KAAK8E,YAErE9E,KAAK4F,kBAAmBH,EAAgBvD,KAAM,uBAAwB2D,QAAS,wBACxEJ,GAIXG,kBAAoB,SAAUE,GAE1BA,EAAOC,MAAO,SAAUhB,GAChB5D,OAAO6E,OAAS7E,OAAO6E,MAAMC,SAC7B9E,OAAO6E,MAAME,KACTjF,MAAc,gBACd2C,IAAcJ,EAAGxD,MAAO2F,KAAM,UAElCZ,EAAGC,iBACHD,EAAGoB,sBAOf1D,YAAc,SAAU2D,GACpB,GAAKpG,KAAKC,QAAV,CACA,GAAIoG,GAAOrG,IACXA,MAAKsG,WAAa,GAAInH,GAAKoH,YACvBhG,MAAkBP,KAAKO,MACvBiG,GAAkBJ,EAAOlE,KAAM,iBAC/BuE,gBAAkB,WAAYzG,KAAK0G,UAEnCC,OAAkB,WAAYN,EAAKlG,iBAAkB,GACrDyG,OAAkB,WAAYP,EAAKlG,iBAAkB,GACrD0G,WAAkBxH,GACd4B,MAAU1B,EAAI,qBACdgC,QAAU,UACVD,OAAU,YACXwF,SAAUV,EAAOlE,KAAM,sBAE1BlC,KAAKG,iBAAmBH,KAAKsG,WAAWpC,QAAQ,KAIxDxB,kBAAoB,SAAU0D,GAC1B,GAAKpG,KAAKC,QAAV,CACA,GAAIoG,GAAOrG,IACXA,MAAK+G,iBAAmB,GAAI3H,GAAY4H,kBACpCzG,MAAkBP,KAAKO,MACvBiG,GAAkBJ,EAAOlE,KAAM,uBAC/BuE,gBAAkB,WAAYzG,KAAK0G,UAEnCC,OAAkB,WAAYN,EAAKjG,uBAAwB,GAC3DwG,OAAkB,WAAYP,EAAKjG,uBAAwB,GAC3DyG,WAAkBxH,GACd4B,MAAU1B,EAAI,2BACdgC,QAAU,eACVD,OAAU,eACXwF,SAAUV,EAAOlE,KAAM,sBAE1BlC,KAAKI,uBAAyBJ,KAAK+G,iBAAiB7C,QAAQ,KAIpEvB,mBAAqB,SAAUN,GAE3B,GAA2C,MAAvCrC,KAAKO,MAAMC,IAAK,oBACfR,KAAKO,MAAMwB,oBAAqB,CACjC,GAAIkF,GAAgBzD,EAAG,0BAClBmC,KAAM,OAAQ3F,KAAKO,MAAMoE,KAAKuC,MAC9BvB,KAAM,SAAU3F,KAAK8E,WAC1BzC,GAASH,KAAM,iBAAkBiF,YAAaF,KAMtDG,OAAS3F,EAAE9B,OAAQ8B,EAAE4F,MAAO7H,EAAOM,UAAUsH,SACzCE,uBAA0B,qBAC1BC,oBAA0B,kBAE1BC,kBAA0B,SAAUzC,GAAM/E,KAAKmC,QAAS,OAAQnC,KAAM+E,IACtE0C,oBAA0B,SAAU1C,GAAM/E,KAAKmC,QAAS,SAAUnC,KAAM+E,IACxE2C,mBAA0B,SAAU3C,GAAM/E,KAAKmC,QAAS,QAASnC,KAAM+E,IACvE4C,wBAA0B,SAAU5C,GAAM/E,KAAKmC,QAAS,aAAcnC,KAAM+E,IAC5E6C,2BAA6B,SAAU7C,GAAM/E,KAAKmC,QAAS,YAAanC,KAAM+E,IAC9E8C,iBAA0B,SAAU9C,GAAM/E,KAAKmC,QAAS,OAAQnC,KAAM+E,MAI1E+C,mBAAqB,WAEjB,MADA9H,MAAKO,MAAMwH,YACJ,GAIXC,gBAAkB,WAId,MAHIC,SAAS1I,EAAI,0EACbS,KAAKO,MAAM2H,SAER,GAKXC,SAAW,WACP,GAAIC,GAAgBpI,KAAW,MAAIA,KAAKO,MAAQ,GAAK,YACrD,OAAO,eAAiB6H,EAAc,MAwE1C,OAjEJ1I,GAAoBI,UAAU4F,UAAa,WAEvC,GAAI2C,GAAW5G,EAAE9B,UAAYH,EAAOM,UAAU4F,UAAU2C,UACpDC,gBAAkBhJ,EAASiJ,cAEvB,mDACI,4DACIhJ,EAAI,2DACJ,4EACIA,EAAI,2CACR,OACJ,SACJ,WACD,WAEHwB,QAAUzB,EAASiJ,cAEf,kDAEI,gDACIhJ,EAAI,iCACJ,6DAA8DA,EAAI,eAAiB,OACnF,iCACI,0DACIA,EAAI,mCACR,OACJ,UACJ,SACJ,WACD,aAGHiJ,EAAyBlJ,EAASiJ,cAClC,2CACI,8EACQ,oDAAqDhJ,EAAI,gBACzD,mCACJ,0CACJ,OAEJ,iBACI,0DACI,oCAAqCA,EAAI,aAAe,KACpD,0CACJ,OACA,yCACI,2DACI,qEACQ,yCACJ,4BACJ,YACJ,YACJ,QACJ,SACJ,WACD,iBAEH,OAAOkC,GAAE9B,UAAYH,EAAOM,UAAU4F,WAClC2C,SAAWA,EACXjD,eAAiBoD,QAOjB9I,oBAAsBA"} \ No newline at end of file diff --git a/static/maps/mvc/job/job-params.js.map b/static/maps/mvc/job/job-params.js.map new file mode 100644 index 00000000000..81e802d565e --- /dev/null +++ b/static/maps/mvc/job/job-params.js.map @@ -0,0 +1 @@ +{"version":3,"file":"job-params.js","sources":["../../../src/mvc/job/job-params.js"],"names":["define","Utils","View","Backbone","extend","initialize","options","this","setElement","render","console","log","self","$el","empty","append"],"mappings":"AACAA,QAAU,eAAiB,SAAUC,GAkBjC,GAAIC,GAAOC,SAASD,KAAKE,QAErBC,WAAY,SAAUC,GAElBC,KAAKD,QAAUA,EACfC,KAAKC,WAAY,UACjBD,KAAKE,UAGTA,OAAQ,WACJC,QAAQC,IAAI,KACZ,IAAIC,GAAOL,IACXK,GAAKC,IAAIC,QAAQC,OAAQ,sBA4BjC,QACIb,KAAQA"} \ No newline at end of file diff --git a/static/maps/mvc/library/library-dataset-view.js.map b/static/maps/mvc/library/library-dataset-view.js.map index cecbc1ce870..ae9e24144b2 100644 --- a/static/maps/mvc/library/library-dataset-view.js.map +++ b/static/maps/mvc/library/library-dataset-view.js.map @@ -1 +1 @@ -{"version":3,"file":"library-dataset-view.js","sources":["../../../src/mvc/library/library-dataset-view.js"],"names":["define","mod_toastr","mod_library_model","mod_utils","mod_select","LibraryDatasetView","Backbone","View","extend","el","model","options","events","click .toolbtn_modify_dataset","click .toolbtn_cancel_modifications","click .toolbtn-download-dataset","click .toolbtn-import-dataset","click .toolbtn-share-dataset","click .btn-copy-link-to-clipboard","click .btn-make-private","click .btn-remove-restrictions","click .toolbtn_save_permissions","click .toolbtn_save_modifications","select_genome","select_extension","list_extensions","auto","id","text","description","list_genomes","initialize","this","_","fetchExtAndGenomes","fetchDataset","Item","that","fetch","success","show_permissions","showPermissions","show_version","fetchVersion","render","error","response","responseJSON","err_msg","onclick","Galaxy","libraries","library_router","back","$","remove","template","templateDataset","$el","html","item","get","tooltip","ldda_id","ldda","Ldda","url","urlRoot","renderVersion","templateVersion","enableModification","templateModifyDataset","renderSelectBoxes","genome_build","file_ext","downloadDataset","root","data","ld_ids","processDownload","method","param","inputs","each","split","pair","appendTo","submit","info","importIntoHistory","refreshUserHistoriesList","self","templateBulkImportInModal","modal","show","closing_events","title","body","histories","models","buttons","Import","importCurrentIntoHistory","Close","hide","callback","GalaxyHistories","length","warning","window","location","disableButton","new_history_name","val","post","name","done","new_history","processImportToHistory","fail","always","enableButton","history_id","find","historyItem","HistoryItem","jQuery","getJSON","save","content","source","shareDataset","goBack","undefined","fetched_permissions","set","access_dataset_roles","is_unrestricted","is_admin","user","isAdmin","templateDatasetPermissions","prepareSelectBoxes","css","_serializeRoles","role_list","selected_roles","i","push","selected_access_dataset_roles","selected_modify_item_roles","selected_manage_dataset_roles","modify_item_roles","manage_dataset_roles","access_select_options","minimumInputLength","multiple","placeholder","container","ajax","dataType","quietMillis","term","page","q","page_limit","results","more","total","roles","formatResult","role","type","formatSelection","initSelection","element","initialData","join","dropdownCssClass","modify_select_options","manage_select_options","accessSelectObject","modifySelectObject","manageSelectObject","templateAccessSelect","select2","comingSoon","copyToClipboard","href","history","lastIndexOf","substr","prompt","makeDatasetPrivate","removeDatasetRestrictions","_extractIds","roles_list","ids_list","savePermissions","access_ids","manage_ids","modify_ids","access_ids[]","manage_ids[]","modify_ids[]","datatypes","key","extension","description_url","sort","a","b","unshift","genomes","current_genome","current_ext","value"],"mappings":"AAAAA,QACE,cACA,4BACA,cACA,oBAEF,SACQC,EACAC,EACAC,EACAC,GAGR,GAAIC,GAAqBC,SAASC,KAAKC,QACrCC,GAAI,UAEJC,MAAO,KAEPC,WAIAC,QACEC,gCAA0C,qBAC1CC,sCAA0C,SAC1CC,kCAA0C,kBAC1CC,gCAA0C,oBAC1CC,+BAA0C,eAC1CC,oCAA0C,kBAC1CC,0BAA0C,qBAC1CC,iCAA0C,4BAC1CC,kCAA0C,kBAC1CC,oCAA0C,cAK5CC,cAAgB,KAGhBC,iBAAmB,KAGnBC,mBAGAC,MACIC,GAAc,OACdC,KAAc,cACdC,YAAc,sZASlBC,gBAEAC,WAAY,SAASpB,GACnBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtCqB,KAAKE,qBACDF,KAAKrB,QAAQgB,IACfK,KAAKG,gBAITA,aAAc,SAASxB,GACrBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtCqB,KAAKtB,MAAQ,GAAIR,GAAkBkC,MAAMT,GAAIK,KAAKrB,QAAQgB,IAC1D,IAAIU,GAAOL,IACXA,MAAKtB,MAAM4B,OACTC,QAAS,WACHF,EAAK1B,QAAQ6B,iBACbH,EAAKI,kBACEJ,EAAK1B,QAAQ+B,aACpBL,EAAKM,eAELN,EAAKO,UAGXC,MAAO,SAASnC,EAAOoC,GACgB,mBAA1BA,GAASC,aAClB9C,EAAW4C,MAAMC,EAASC,aAAaC,QAAU,0BAA2B,IAAKC,QAAS,WAAYC,OAAOC,UAAUC,eAAeC,UAEtIpD,EAAW4C,MAAM,2CAA4C,IAAKI,QAAS,WAAYC,OAAOC,UAAUC,eAAeC,cAM/HT,OAAQ,SAASjC,GACfqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC2C,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKyB,iBACpBzB,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,SACnC4C,EAAE,SAASK,KAAK3B,KAAKtB,MAAMmD,IAAI,SAC/BP,EAAE,yBAAyBQ,WAG7BnB,aAAc,SAAShC,GACrBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC0B,KAAOL,KACFA,KAAKrB,QAAQoD,SAIhB/B,KAAKgC,KAAO,GAAI9D,GAAkB+D,MAAMtC,GAAIK,KAAKrB,QAAQoD,UACzD/B,KAAKgC,KAAKE,IAAMlC,KAAKgC,KAAKG,QAAUnC,KAAKtB,MAAMiB,GAAK,aAAeK,KAAKgC,KAAKrC,GAC7EK,KAAKgC,KAAK1B,OACRC,QAAS,WACPF,KAAK+B,iBAEPvB,MAAO,SAASnC,EAAOoC,GAEnB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACDD,EAASC,aAAaC,QAEtB,0BAbvBhB,KAAKY,SACL3C,EAAW4C,MAAM,2DAmBrBuB,cAAe,WACbd,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKqC,iBACpBrC,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,MAAOsD,KAAMhC,KAAKgC,QACrDV,EAAE,SAASK,KAAK3B,KAAKgC,KAAKH,IAAI,UAGhCS,mBAAoB,WAClBhB,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKuC,uBACpBvC,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,SACnCsB,KAAKwC,mBAAmBC,aAAczC,KAAKtB,MAAMmD,IAAI,gBAAiBa,SAAU1C,KAAKtB,MAAMmD,IAAI,cAC/FP,EAAE,SAASK,KAAK3B,KAAKtB,MAAMmD,IAAI,SAC/BP,EAAE,yBAAyBQ,WAG7Ba,gBAAiB,WACf,GAAIT,GAAMhB,OAAO0B,KAAO,+CACpBC,GAAQC,OAAU9C,KAAKL,GAC3BK,MAAK+C,gBAAgBb,EAAKW,IAG5BE,gBAAiB,SAASb,EAAKW,EAAMG,GAE/B,GAAId,GAAOW,EAAM,CAEfA,EAAsB,gBAARA,GAAmBA,EAAOvB,EAAE2B,MAAMJ,EAEhD,IAAIK,GAAS,EACb5B,GAAE6B,KAAKN,EAAKO,MAAM,KAAM,WACtB,GAAIC,GAAOrD,KAAKoD,MAAM,IACtBF,IAAQ,8BAA+BG,EAAK,GAAI,YAAaA,EAAK,GAAI,SAGxE/B,EAAE,iBAAkBY,EAAK,cAAec,GAAQ,QAAS,KAAKE,EAAO,WACpEI,SAAS,QAAQC,SAAShC,SAE3BtD,EAAWuF,KAAK,oCAIxBC,kBAAmB,WACjBzD,KAAK0D,yBAAyB,SAASC,GAC/B,GAAInC,GAAWmC,EAAKC,2BACpBD,GAAKE,MAAQ3C,OAAO2C,MACpBF,EAAKE,MAAMC,MACPC,gBAAkB,EAClBC,MAAkB,sBAClBC,KAAkBzC,GAAU0C,UAAYP,EAAKO,UAAUC,SACvDC,SACIC,OAAc,WAAYV,EAAKW,4BAC/BC,MAAc,WAAYrD,OAAO2C,MAAMW,cAM1Dd,yBAA0B,SAASe,GAChC,GAAId,GAAO3D,IACXA,MAAKkE,UAAY,GAAIhG,GAAkBwG,gBACvC1E,KAAKkE,UAAU5D,OACbC,QAAS,SAAU2D,GACQ,IAArBA,EAAUS,OACZ1G,EAAW2G,QAAQ,yDAA0D,IAAK3D,QAAS,WAAY4D,OAAOC,SAAS5D,OAAO0B,QAE9H6B,EAASd,IAGb9C,MAAO,SAASnC,EAAOoC,GAEnB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBAMzBsD,yBAA0B,WACxBtE,KAAK6D,MAAMkB,cAAc,SACzB,IAAIC,GAAmBhF,KAAK6D,MAAMvC,EAAE,4BAA4B2D,MAC5D5E,EAAOL,IACX,IAAyB,KAArBgF,EACF1D,EAAE4D,KAAMhE,OAAO0B,KAAO,iBAAkBuC,KAAMH,IAC3CI,KAAK,SAAUC,GACdhF,EAAKiF,uBAAuBD,EAAY1F,MAEzC4F,KAAK,WACJtH,EAAW4C,MAAM,uBAElB2E,OAAO,WACNnF,EAAKwD,MAAM4B,aAAa,gBAEvB,CACL,GAAIC,GAAapE,EAAEtB,KAAK6D,MAAMnC,KAAKiE,KAAK,sDAAsDV,KAC9FjF,MAAKsF,uBAAuBI,GAC5B1F,KAAK6D,MAAM4B,aAAa,YAI5BH,uBAAwB,SAAUI,GAChC,GAAIE,GAAc,GAAI1H,GAAkB2H,WACxCD,GAAY1D,IAAM0D,EAAYzD,QAAUuD,EAAa,YAGrDI,OAAOC,QAAS7E,OAAO0B,KAAO,6BAA+B8C,GAE7DE,EAAYI,MAAOC,QAAUjG,KAAKL,GAAIuG,OAAS,YAC7C3F,QAAU,WACRW,OAAO2C,MAAMW,OACbvG,EAAWsC,QAAQ,sDAAuD,IAAKU,QAAS,WAAY4D,OAAOC,SAAS5D,OAAO0B,SAE7H/B,MAAQ,SAASnC,EAAOoC,GAEpB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACD,yBAA2BD,EAASC,aAAaC,QAEjD,iEAMzBmF,aAAc,WACZlI,EAAWuF,KAAK,yBAGlB4C,OAAQ,WACNlF,OAAOC,UAAUC,eAAeC,QAGlCZ,gBAAiB,SAAS9B,GACxBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC2C,EAAE,YAAYC,SAC2B8E,SAArCrG,KAAKrB,QAAQ2H,qBAEbtG,KAAKtB,MAAM6H,IADwD,IAAjEvG,KAAKrB,QAAQ2H,oBAAoBE,qBAAqB7B,QACxC8B,iBAAgB,IAEhBA,iBAAgB,GAIpC,IAAIC,IAAW,CACXxF,QAAOyF,OACTD,EAAWxF,OAAOyF,KAAKC,UAEzB,IAAIpF,GAAWxB,KAAK6G,4BACpB7G,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,MAAOgI,SAAUA,IACpD,IAAI/C,GAAO3D,IACXsB,GAAEO,IAAKX,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,8BAA8ByF,KAAK,SAASkB,GACrG3C,EAAKmD,oBAAoBR,oBAAqBA,EAAqBI,SAAUA,MAC5EnB,KAAK,WACJtH,EAAW4C,MAAM,sEAErBS,EAAE,yBAAyBQ,UAC3BR,EAAE,WAAWyF,IAAI,WAAW,SAG9BC,gBAAkB,SAASC,GAEzB,IAAK,GADDC,MACKC,EAAI,EAAGA,EAAIF,EAAUtC,OAAQwC,IACpCD,EAAeE,KAAKH,EAAUE,GAAG,GAAK,IAAMF,EAAUE,GAAG,GAE3D,OAAOD,IAGTJ,mBAAoB,SAASnI,GAC3BqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,EACtC,IAAI2H,GAAsBtG,KAAKrB,QAAQ2H,oBACnCI,EAAW1G,KAAKrB,QAAQ+H,SACxB/C,EAAO3D,KACPqH,KACAC,KACAC,IAKJ,IAJAF,EAAgCrH,KAAKgH,gBAAgBV,EAAoBE,sBACzEc,EAA6BtH,KAAKgH,gBAAgBV,EAAoBkB,mBACtED,EAAgCvH,KAAKgH,gBAAgBV,EAAoBmB,sBAErEf,EAAS,CACT,GAAIgB,IACFC,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAa3B,EAA8B4B,KAAK,KAChDC,iBAAkB,WAEhBC,GACFxB,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAa1B,EAA2B2B,KAAK,KAC7CC,iBAAkB,WAEhBE,GACFzB,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAazB,EAA8B0B,KAAK,KAChDC,iBAAkB,UAGpBvF,GAAK0F,mBAAqB,GAAIjL,GAAWG,KAAKmJ,GAC9C/D,EAAK2F,mBAAqB,GAAIlL,GAAWG,KAAK4K,GAC9CxF,EAAK4F,mBAAqB,GAAInL,GAAWG,KAAK6K,OAC3C,CACH,GAAI5H,GAAWmC,EAAK6F,sBACpBlI,GAAEO,IAAKX,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BAAgC,SAAUkD,GACjGvB,EAAE,gBAAgBK,KAAKH,GAAU7C,QAASkE,EAAK4F,SAC/C9E,EAAK0F,mBAAqB/H,EAAE,kBAAkBmI,YAC/ClE,KAAK,WACJtH,EAAW4C,MAAM,wEAK3B6I,WAAY,WACVzL,EAAW2G,QAAQ,yBAGrB+E,gBAAiB,WACf,GAAIC,GAAOtL,SAASuL,QAAQ/E,SAAS8E,IACI,MAArCA,EAAKE,YAAY,kBACnBF,EAAOA,EAAKG,OAAO,EAAGH,EAAKE,YAAY,kBAEzCjF,OAAOmF,OAAO,mCAAoCJ,IAGpDK,mBAAoB,WAClB,GAAItG,GAAO3D,IACXsB,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,oCAAoCyF,KAAK,SAASkB,GAC5G3C,EAAKjF,MAAM6H,KAAKE,iBAAiB,IACjC9C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,wCAClBgF,KAAK,WACNtH,EAAW4C,MAAM,kEAIrBqJ,0BAA2B,WACzB,GAAIvG,GAAO3D,IACXsB,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,2CAC3DyF,KAAK,SAASkB,GACb3C,EAAKjF,MAAM6H,KAAKE,iBAAiB,IACjC9C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,iDAEpBgF,KAAK,WACJtH,EAAW4C,MAAM,uEAOrBsJ,YAAa,SAASC,GACpBC,WACA,KAAK,GAAIlD,GAAIiD,EAAWzF,OAAS,EAAGwC,GAAK,EAAGA,IAC1CkD,SAASjD,KAAKgD,EAAWjD,GAAGxH,GAE9B,OAAO0K,WAMTC,gBAAiB,WACf,GAAI3G,GAAO3D,KACPuK,EAAavK,KAAKmK,YAAYnK,KAAKqJ,mBAAmB3H,IAAI+H,QAAQ,SAClEe,EAAaxK,KAAKmK,YAAYnK,KAAKuJ,mBAAmB7H,IAAI+H,QAAQ,SAClEgB,EAAazK,KAAKmK,YAAYnK,KAAKsJ,mBAAmB5H,IAAI+H,QAAQ,QACtEnI,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,uCAAyC+K,eAAgBH,EAAYI,eAAgBH,EAAYI,eAAgBH,IAC5KrF,KAAK,SAASkB,GACb3C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,wBAEpBgF,KAAK,WACJtH,EAAW4C,MAAM,qEAQrBX,mBAAoB,WAClB,GAAIG,GAAOL,IACX7B,GAAU0D,KACNK,IAAYhB,OAAO0B,KAAO,qCAC1BrC,QAAY,SAAUsK,GACN,IAAKC,MAAOD,GACRxK,EAAKZ,gBAAgB2H,MACjBzH,GAAkBkL,EAAUC,KAAKC,UACjCnL,KAAkBiL,EAAUC,KAAKC,UACjClL,YAAkBgL,EAAUC,KAAKjL,YACjCmL,gBAAkBH,EAAUC,KAAKE,iBAGzC3K,GAAKZ,gBAAgBwL,KAAK,SAASC,EAAGC,GAClC,MAAOD,GAAEvL,GAAKwL,EAAExL,GAAK,EAAIuL,EAAEvL,GAAKwL,EAAExL,GAAK,GAAK,IAEhDU,EAAKZ,gBAAgB2L,QAAQ/K,EAAKX,SAGtDvB,EAAU0D,KACNK,IAAahB,OAAO0B,KAAO,cAC3BrC,QAAU,SAAU8K,GACR,IAAMP,MAAOO,GACThL,EAAKP,aAAasH,MACdzH,GAAU0L,EAAQP,KAAK,GACvBlL,KAAUyL,EAAQP,KAAK,IAG/BzK,GAAKP,aAAamL,KAAK,SAASC,EAAGC,GAC/B,MAAOD,GAAEvL,GAAKwL,EAAExL,GAAK,EAAIuL,EAAEvL,GAAKwL,EAAExL,GAAK,GAAK,QAMlE6C,kBAAmB,SAAS7D,GAK1B,GAAI2M,GAAiB,IACjBC,EAAc,MACK,oBAAZ5M,KAC2B,mBAAzBA,GAAQ8D,eACjB6I,EAAiB3M,EAAQ8D,cAEK,mBAArB9D,GAAQ+D,WACjB6I,EAAc5M,EAAQ+D,UAG1B,IAAIrC,GAAOL,IACXA,MAAKT,cAAgB,GAAInB,GAAWG,MAChCwI,IAAK,wBACLlE,KAAMxC,EAAKP,aACXgI,UAAWzH,EAAKqB,IAAIiE,KAAM,0BAC1B6F,MAAOF,IAEXtL,KAAKR,iBAAmB,GAAIpB,GAAWG,MACrCwI,IAAK,2BACLlE,KAAMxC,EAAKZ,gBACXqI,UAAWzH,EAAKqB,IAAIiE,KAAM,6BAC1B6F,MAAOD,KAIX9J,gBAAkB,WAChB,MAAOxB,GAAEuB,UAET,wCACE,6BACE,0KACE,uCACA,iBACF,YACA,mLACE,mCACA,mBACF,YACA,2CACE,2KACE,qCACA,eACF,YACF,UACA,2CACE,uFACE,8KACE,oCACA,oBACF,YACF,OACF,UACF,SAGF,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,2CACE,iCACE,6FACA,gKACE,wCACA,qBACF,aACF,SACF,UAGA,8BACE,2DACE,OACE,oHACA,6CACF,QACA,oCACE,OACE,iCACA,iDACF,QACF,UACA,wCACE,OACE,oCACA,qDACF,QACF,UACA,qCACE,OACE,4BACA,kDACF,QACF,UACA,yCACE,OACE,2CACA,sDACF,QACF,UACA,uCACE,OACE,mCACA,oDACF,QACF,UACA,+CACE,OACE,kCACA,wEACF,QACF,UACA,kDACE,OACE,qCACA,2EACF,QACF,UACA,4CACE,OACE,yCACA,qEACF,QACF,UACA,iDACE,OACE,oCACA,0EACF,QACF,UACA,mCACE,OACE,+BACA,4DACF,QACF,UACA,sCACE,OACE,2CACA,+DACF,QACF,UACA,qCACE,OACE,iDACA,8DACF,QACF,UACF,WAEF,QACE,qBACA,SACF,SAEA,wCACE,QACE,6BACA,OACE,iEACE,wKACF,WACF,OACF,SACF,UAEA,SAEA,UACEyH,KAAK,MAGT5G,gBAAkB,WAChB,MAAOpC,GAAEuB,UAET,wCACE,6BACE,2EACE,qJACE,+CACA,uBACF,YACF,MACF,SAGA,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,8HAEA,8BACE,2DACE,OACE,2EACA,6CACF,QACA,oCACE,OACE,iCACA,iDACF,QACF,UACA,wCACE,OACE,oCACA,qDACF,QACF,UACA,qCACE,OACE,4BACA,kDACF,QACF,UACA,yCACE,OACE,2CACA,sDACF,QACF,UACA,uCACE,OACE,mCACA,oDACF,QACF,UACA,+CACE,OACE,kCACA,wEACF,QACF,UACA,kDACE,OACE,qCACA,2EACF,QACF,UACA,4CACE,OACE,yCACA,qEACF,QACF,UACA,iDACE,OACE,oCACA,0EACF,QACF,UACA,mCACE,OACE,+BACA,4DACF,QACF,UACA,sCACE,OACE,2CACA,+DACF,QACF,UACA,qCACE,OACE,iDACA,8DACF,QACF,UACF,WACA,QACE,qBACA,SACF,SAEF,SAEF,UACEyH,KAAK,MAGT1G,sBAAwB,WACtB,MAAOtC,GAAEuB,UAET,wCACE,6BACE,kLACE,oCACA,eACF,YACA,8KACE,uCACA,aACF,YACF,SAGA,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,8BACE,wGACA,2DACE,OACE,oHACA,oIACF,QACA,OACE,iCACA,OACE,0EACF,QACF,QACA,OACE,oCACA,OACE,oEACF,QACF,QACA,OACE,4BACA,kDACF,QACA,OACE,2CACA,sDACF,QACA,OACE,mCACA,oDACF,QACA,mBACE,kCACA,wEACF,QACE,qCACA,yDACE,2EACF,iBACE,+BACF,UACF,QACA,OACE,yCACA,qEACF,QACA,OACE,oCACA,0EACF,QACA,OACE,+BACA,4DACF,QACA,OACE,iDACA,8DACF,QACA,OACE,2CACA,+DACF,QACF,WACA,QACE,qBACA,SACF,SACF,SAEF,UACEyH,KAAK,MAGTpC,2BAA6B,WAC3B,MAAO5G,GAAEuB,UAET,wCACE,6BACE,mDACE,6JACE,4CACA,0BACF,YACF,OACA,2EACE,mJACE,qCACA,wBACF,YACF,MACF,SAGA,0BACE,6EACE,4DACE,uCACE,2GACF,iBACE,gFACF,UACJ,YACF,QAEA,sDACA,oCACE,wBACE,yKACF,iBACE,+IACF,UACF,SACA,8BACE,uCACA,kDACA,mEACA,8KACA,QACA,uCACA,+LACA,4CACE,8DACE,yLACE,oCACA,4BACF,YACF,OACF,iBACE,4FACA,gKACE,wCACA,qBACA,YACF,gDACE,iLACE,kCACA,qBACF,YACF,OACF,UACA,6CACA,mEACA,iDACE,qFACA,mGACA,mGACF,SACA,4DACA,mEACA,iDACE,uLACF,SACA,iLACE,uCACA,aACF,YACF,SAEF,UACEyH,KAAK,MAGTrF,0BAA2B,WACzB,MAAO3D,GAAEuB,UACT,QACE,mCACE,mBACA,qHACE,8CACE,mGACF,YACF,YACF,SACA,mCACE,kBACA,4GACA,WACF,SACF,UACEyH,KAAK,MAITO,qBAAsB,WACpB,MAAOvJ,GAAEuB,UACT,uCACE,2CACE,iEACF,YACF,aACEyH,KAAK,OAKX,QACI5K,mBAAoBA"} \ No newline at end of file +{"version":3,"file":"library-dataset-view.js","sources":["../../../src/mvc/library/library-dataset-view.js"],"names":["define","mod_toastr","mod_library_model","mod_utils","mod_select","LibraryDatasetView","Backbone","View","extend","el","model","options","events","click .toolbtn_modify_dataset","click .toolbtn_cancel_modifications","click .toolbtn-download-dataset","click .toolbtn-import-dataset","click .toolbtn-share-dataset","click .btn-copy-link-to-clipboard","click .btn-make-private","click .btn-remove-restrictions","click .toolbtn_save_permissions","click .toolbtn_save_modifications","select_genome","select_extension","list_extensions","auto","id","text","description","list_genomes","initialize","this","_","fetchExtAndGenomes","fetchDataset","Item","that","fetch","success","show_permissions","showPermissions","show_version","fetchVersion","render","error","response","responseJSON","err_msg","onclick","Galaxy","libraries","library_router","back","$","remove","template","templateDataset","$el","html","item","get","tooltip","ldda_id","ldda","Ldda","url","urlRoot","renderVersion","templateVersion","enableModification","templateModifyDataset","renderSelectBoxes","genome_build","file_ext","downloadDataset","root","data","ld_ids","processDownload","method","param","inputs","each","split","pair","appendTo","submit","info","importIntoHistory","refreshUserHistoriesList","self","templateBulkImportInModal","modal","show","closing_events","title","body","histories","models","buttons","Import","importCurrentIntoHistory","Close","hide","callback","GalaxyHistories","length","warning","window","location","disableButton","new_history_name","val","post","name","done","new_history","processImportToHistory","fail","always","enableButton","history_id","find","historyItem","HistoryItem","jQuery","getJSON","save","content","source","shareDataset","goBack","undefined","fetched_permissions","set","access_dataset_roles","is_unrestricted","is_admin","user","isAdmin","templateDatasetPermissions","prepareSelectBoxes","css","_serializeRoles","role_list","selected_roles","i","push","selected_access_dataset_roles","selected_modify_item_roles","selected_manage_dataset_roles","modify_item_roles","manage_dataset_roles","access_select_options","minimumInputLength","multiple","placeholder","container","ajax","dataType","quietMillis","term","page","q","page_limit","results","more","total","roles","formatResult","role","type","formatSelection","initSelection","element","initialData","join","dropdownCssClass","modify_select_options","manage_select_options","accessSelectObject","modifySelectObject","manageSelectObject","templateAccessSelect","select2","comingSoon","copyToClipboard","href","history","lastIndexOf","substr","prompt","makeDatasetPrivate","removeDatasetRestrictions","_extractIds","roles_list","ids_list","savePermissions","access_ids","manage_ids","modify_ids","access_ids[]","manage_ids[]","modify_ids[]","datatypes","key","extension","description_url","sort","a","b","unshift","genomes","current_genome","current_ext","value"],"mappings":"AAAAA,QACE,cACA,4BACA,cACA,oBAEF,SACQC,EACAC,EACAC,EACAC,GAGR,GAAIC,GAAqBC,SAASC,KAAKC,QACrCC,GAAI,UAEJC,MAAO,KAEPC,WAIAC,QACEC,gCAA0C,qBAC1CC,sCAA0C,SAC1CC,kCAA0C,kBAC1CC,gCAA0C,oBAC1CC,+BAA0C,eAC1CC,oCAA0C,kBAC1CC,0BAA0C,qBAC1CC,iCAA0C,4BAC1CC,kCAA0C,kBAC1CC,oCAA0C,cAK5CC,cAAgB,KAGhBC,iBAAmB,KAGnBC,mBAGAC,MACIC,GAAc,OACdC,KAAc,cACdC,YAAc,sZASlBC,gBAEAC,WAAY,SAASpB,GACnBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtCqB,KAAKE,qBACDF,KAAKrB,QAAQgB,IACfK,KAAKG,gBAITA,aAAc,SAASxB,GACrBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtCqB,KAAKtB,MAAQ,GAAIR,GAAkBkC,MAAMT,GAAIK,KAAKrB,QAAQgB,IAC1D,IAAIU,GAAOL,IACXA,MAAKtB,MAAM4B,OACTC,QAAS,WACHF,EAAK1B,QAAQ6B,iBACbH,EAAKI,kBACEJ,EAAK1B,QAAQ+B,aACpBL,EAAKM,eAELN,EAAKO,UAGXC,MAAO,SAASnC,EAAOoC,GACgB,mBAA1BA,GAASC,aAClB9C,EAAW4C,MAAMC,EAASC,aAAaC,QAAU,0BAA2B,IAAKC,QAAS,WAAYC,OAAOC,UAAUC,eAAeC,UAEtIpD,EAAW4C,MAAM,2CAA4C,IAAKI,QAAS,WAAYC,OAAOC,UAAUC,eAAeC,cAM/HT,OAAQ,SAASjC,GACfqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC2C,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKyB,iBACpBzB,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,SACnC4C,EAAE,SAASK,KAAK3B,KAAKtB,MAAMmD,IAAI,SAC/BP,EAAE,yBAAyBQ,WAG7BnB,aAAc,SAAShC,GACrBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC0B,KAAOL,KACFA,KAAKrB,QAAQoD,SAIhB/B,KAAKgC,KAAO,GAAI9D,GAAkB+D,MAAMtC,GAAIK,KAAKrB,QAAQoD,UACzD/B,KAAKgC,KAAKE,IAAMlC,KAAKgC,KAAKG,QAAUnC,KAAKtB,MAAMiB,GAAK,aAAeK,KAAKgC,KAAKrC,GAC7EK,KAAKgC,KAAK1B,OACRC,QAAS,WACPF,KAAK+B,iBAEPvB,MAAO,SAASnC,EAAOoC,GAEnB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACDD,EAASC,aAAaC,QAEtB,0BAbvBhB,KAAKY,SACL3C,EAAW4C,MAAM,2DAmBrBuB,cAAe,WACbd,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKqC,iBACpBrC,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,MAAOsD,KAAMhC,KAAKgC,QACrDV,EAAE,SAASK,KAAK3B,KAAKgC,KAAKH,IAAI,UAGhCS,mBAAoB,WAClBhB,EAAE,YAAYC,QACd,IAAIC,GAAWxB,KAAKuC,uBACpBvC,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,SACnCsB,KAAKwC,mBAAmBC,aAAczC,KAAKtB,MAAMmD,IAAI,gBAAiBa,SAAU1C,KAAKtB,MAAMmD,IAAI,cAC/FP,EAAE,SAASK,KAAK3B,KAAKtB,MAAMmD,IAAI,SAC/BP,EAAE,yBAAyBQ,WAG7Ba,gBAAiB,WACf,GAAIT,GAAMhB,OAAO0B,KAAO,+CACpBC,GAAQC,OAAU9C,KAAKL,GAC3BK,MAAK+C,gBAAgBb,EAAKW,IAG5BE,gBAAiB,SAASb,EAAKW,EAAMG,GAE/B,GAAId,GAAOW,EAAM,CAEfA,EAAsB,gBAARA,GAAmBA,EAAOvB,EAAE2B,MAAMJ,EAEhD,IAAIK,GAAS,EACb5B,GAAE6B,KAAKN,EAAKO,MAAM,KAAM,WACtB,GAAIC,GAAOrD,KAAKoD,MAAM,IACtBF,IAAQ,8BAA+BG,EAAK,GAAI,YAAaA,EAAK,GAAI,SAGxE/B,EAAE,iBAAkBY,EAAK,cAAec,GAAQ,QAAS,KAAKE,EAAO,WACpEI,SAAS,QAAQC,SAAShC,SAE3BtD,EAAWuF,KAAK,oCAIxBC,kBAAmB,WACjBzD,KAAK0D,yBAAyB,SAASC,GAC/B,GAAInC,GAAWmC,EAAKC,2BACpBD,GAAKE,MAAQ3C,OAAO2C,MACpBF,EAAKE,MAAMC,MACPC,gBAAkB,EAClBC,MAAkB,sBAClBC,KAAkBzC,GAAU0C,UAAYP,EAAKO,UAAUC,SACvDC,SACIC,OAAc,WAAYV,EAAKW,4BAC/BC,MAAc,WAAYrD,OAAO2C,MAAMW,cAM1Dd,yBAA0B,SAASe,GAChC,GAAId,GAAO3D,IACXA,MAAKkE,UAAY,GAAIhG,GAAkBwG,gBACvC1E,KAAKkE,UAAU5D,OACbC,QAAS,SAAU2D,GACQ,IAArBA,EAAUS,OACZ1G,EAAW2G,QAAQ,yDAA0D,IAAK3D,QAAS,WAAY4D,OAAOC,SAAS5D,OAAO0B,QAE9H6B,EAASd,IAGb9C,MAAO,SAASnC,EAAOoC,GAEnB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBAMzBsD,yBAA0B,WACxBtE,KAAK6D,MAAMkB,cAAc,SACzB,IAAIC,GAAmBhF,KAAK6D,MAAMvC,EAAE,4BAA4B2D,MAC5D5E,EAAOL,IACX,IAAyB,KAArBgF,EACF1D,EAAE4D,KAAMhE,OAAO0B,KAAO,iBAAkBuC,KAAMH,IAC3CI,KAAK,SAAUC,GACdhF,EAAKiF,uBAAuBD,EAAY1F,MAEzC4F,KAAK,WACJtH,EAAW4C,MAAM,uBAElB2E,OAAO,WACNnF,EAAKwD,MAAM4B,aAAa,gBAEvB,CACL,GAAIC,GAAapE,EAAEtB,KAAK6D,MAAMnC,KAAKiE,KAAK,sDAAsDV,KAC9FjF,MAAKsF,uBAAuBI,GAC5B1F,KAAK6D,MAAM4B,aAAa,YAI5BH,uBAAwB,SAAUI,GAChC,GAAIE,GAAc,GAAI1H,GAAkB2H,WACxCD,GAAY1D,IAAM0D,EAAYzD,QAAUuD,EAAa,YAGrDI,OAAOC,QAAS7E,OAAO0B,KAAO,6BAA+B8C,GAE7DE,EAAYI,MAAOC,QAAUjG,KAAKL,GAAIuG,OAAS,YAC7C3F,QAAU,WACRW,OAAO2C,MAAMW,OACbvG,EAAWsC,QAAQ,sDAAuD,IAAKU,QAAS,WAAY4D,OAAOC,SAAS5D,OAAO0B,SAE7H/B,MAAQ,SAASnC,EAAOoC,GAEpB7C,EAAW4C,MADwB,mBAA1BC,GAASC,aACD,yBAA2BD,EAASC,aAAaC,QAEjD,iEAMzBmF,aAAc,WACZlI,EAAWuF,KAAK,yBAGlB4C,OAAQ,WACNlF,OAAOC,UAAUC,eAAeC,QAGlCZ,gBAAiB,SAAS9B,GACxBqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,GACtC2C,EAAE,YAAYC,SAC2B8E,SAArCrG,KAAKrB,QAAQ2H,qBAEbtG,KAAKtB,MAAM6H,IADwD,IAAjEvG,KAAKrB,QAAQ2H,oBAAoBE,qBAAqB7B,QACxC8B,iBAAgB,IAEhBA,iBAAgB,GAIpC,IAAIC,IAAW,CACXxF,QAAOyF,OACTD,EAAWxF,OAAOyF,KAAKC,UAEzB,IAAIpF,GAAWxB,KAAK6G,4BACpB7G,MAAK0B,IAAIC,KAAKH,GAAUI,KAAM5B,KAAKtB,MAAOgI,SAAUA,IACpD,IAAI/C,GAAO3D,IACXsB,GAAEO,IAAKX,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,8BAA8ByF,KAAK,SAASkB,GACrG3C,EAAKmD,oBAAoBR,oBAAqBA,EAAqBI,SAAUA,MAC5EnB,KAAK,WACJtH,EAAW4C,MAAM,sEAErBS,EAAE,yBAAyBQ,UAC3BR,EAAE,WAAWyF,IAAI,WAAW,SAG9BC,gBAAkB,SAASC,GAEzB,IAAK,GADDC,MACKC,EAAI,EAAGA,EAAIF,EAAUtC,OAAQwC,IACpCD,EAAeE,KAAKH,EAAUE,GAAG,GAAK,IAAMF,EAAUE,GAAG,GAE3D,OAAOD,IAGTJ,mBAAoB,SAASnI,GAC3BqB,KAAKrB,QAAUsB,EAAEzB,OAAOwB,KAAKrB,QAASA,EACtC,IAAI2H,GAAsBtG,KAAKrB,QAAQ2H,oBACnCI,EAAW1G,KAAKrB,QAAQ+H,SACxB/C,EAAO3D,KACPqH,KACAC,KACAC,IAKJ,IAJAF,EAAgCrH,KAAKgH,gBAAgBV,EAAoBE,sBACzEc,EAA6BtH,KAAKgH,gBAAgBV,EAAoBkB,mBACtED,EAAgCvH,KAAKgH,gBAAgBV,EAAoBmB,sBAErEf,EAAS,CACT,GAAIgB,IACFC,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAa3B,EAA8B4B,KAAK,KAChDC,iBAAkB,WAEhBC,GACFxB,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAa1B,EAA2B2B,KAAK,KAC7CC,iBAAkB,WAEhBE,GACFzB,mBAAoB,EACpBZ,IAAK,cACLa,UAAS,EACTC,YAAa,yBACbC,UAAWnE,EAAKjC,IAAIiE,KAAK,gBACzBoC,MACI7F,IAAKhB,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BACzDqI,SAAU,OACVC,YAAa,IACbpF,KAAM,SAAUqF,EAAMC,GAClB,OACIC,EAAGF,EACHG,WAAY,GACZF,KAAMA,IAGdG,QAAS,SAAUzF,EAAMsF,GACrB,GAAII,GAAe,GAAPJ,EAAatF,EAAK2F,KAE9B,QAAQF,QAASzF,EAAK4F,MAAOF,KAAMA,KAG3CG,aAAe,SAA0BC,GACrC,MAAOA,GAAKxD,KAAO,UAAYwD,EAAKC,MAGxCC,gBAAiB,SAA6BF,GAC1C,MAAOA,GAAKxD,MAEhB2D,cAAe,SAASC,EAAStE,GAI7B,GAAI5B,KACJvB,GAAEyH,EAAQ9D,MAAM7B,MAAM,MAAMD,KAAK,WAC7B,GAAIvB,GAAO5B,KAAKoD,MAAM,IACtBP,GAAKuE,MACDzH,GAAIiC,EAAK,GACTuD,KAAMvD,EAAK,OAGnB6C,EAAS5B,IAEbmG,YAAazB,EAA8B0B,KAAK,KAChDC,iBAAkB,UAGpBvF,GAAK0F,mBAAqB,GAAIjL,GAAWG,KAAKmJ,GAC9C/D,EAAK2F,mBAAqB,GAAIlL,GAAWG,KAAK4K,GAC9CxF,EAAK4F,mBAAqB,GAAInL,GAAWG,KAAK6K,OAC3C,CACH,GAAI5H,GAAWmC,EAAK6F,sBACpBlI,GAAEO,IAAKX,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,+BAAgC,SAAUkD,GACjGvB,EAAE,gBAAgBK,KAAKH,GAAU7C,QAASkE,EAAK4F,SAC/C9E,EAAK0F,mBAAqB/H,EAAE,kBAAkBmI,YAC/ClE,KAAK,WACJtH,EAAW4C,MAAM,wEAK3B6I,WAAY,WACVzL,EAAW2G,QAAQ,yBAGrB+E,gBAAiB,WACf,GAAIC,GAAOtL,SAASuL,QAAQ/E,SAAS8E,IACI,MAArCA,EAAKE,YAAY,kBACnBF,EAAOA,EAAKG,OAAO,EAAGH,EAAKE,YAAY,kBAEzCjF,OAAOmF,OAAO,mCAAoCJ,IAGpDK,mBAAoB,WAClB,GAAItG,GAAO3D,IACXsB,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,oCAAoCyF,KAAK,SAASkB,GAC5G3C,EAAKjF,MAAM6H,KAAKE,iBAAiB,IACjC9C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,wCAClBgF,KAAK,WACNtH,EAAW4C,MAAM,kEAIrBqJ,0BAA2B,WACzB,GAAIvG,GAAO3D,IACXsB,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,2CAC3DyF,KAAK,SAASkB,GACb3C,EAAKjF,MAAM6H,KAAKE,iBAAiB,IACjC9C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,iDAEpBgF,KAAK,WACJtH,EAAW4C,MAAM,uEAOrBsJ,YAAa,SAASC,GACpBC,WACA,KAAK,GAAIlD,GAAIiD,EAAWzF,OAAS,EAAGwC,GAAK,EAAGA,IAC1CkD,SAASjD,KAAKgD,EAAWjD,GAAGxH,GAE9B,OAAO0K,WAMTC,gBAAiB,WACf,GAAI3G,GAAO3D,KACPuK,EAAavK,KAAKmK,YAAYnK,KAAKqJ,mBAAmB3H,IAAI+H,QAAQ,SAClEe,EAAaxK,KAAKmK,YAAYnK,KAAKuJ,mBAAmB7H,IAAI+H,QAAQ,SAClEgB,EAAazK,KAAKmK,YAAYnK,KAAKsJ,mBAAmB5H,IAAI+H,QAAQ,QACtEnI,GAAE4D,KAAMhE,OAAO0B,KAAO,0BAA4Be,EAAKhE,GAAK,uCAAyC+K,eAAgBH,EAAYI,eAAgBH,EAAYI,eAAgBH,IAC5KrF,KAAK,SAASkB,GACb3C,EAAKlD,iBAAiB6F,oBAAqBA,IAC3CrI,EAAWsC,QAAQ,wBAEpBgF,KAAK,WACJtH,EAAW4C,MAAM,qEAQrBX,mBAAoB,WAClB,GAAIG,GAAOL,IACX7B,GAAU0D,KACNK,IAAYhB,OAAO0B,KAAO,qCAC1BrC,QAAY,SAAUsK,GACN,IAAKC,MAAOD,GACRxK,EAAKZ,gBAAgB2H,MACjBzH,GAAkBkL,EAAUC,KAAKC,UACjCnL,KAAkBiL,EAAUC,KAAKC,UACjClL,YAAkBgL,EAAUC,KAAKjL,YACjCmL,gBAAkBH,EAAUC,KAAKE,iBAGzC3K,GAAKZ,gBAAgBwL,KAAK,SAASC,EAAGC,GAClC,MAAOD,GAAEvL,GAAKwL,EAAExL,GAAK,EAAIuL,EAAEvL,GAAKwL,EAAExL,GAAK,GAAK,IAEhDU,EAAKZ,gBAAgB2L,QAAQ/K,EAAKX,SAGtDvB,EAAU0D,KACNK,IAAahB,OAAO0B,KAAO,cAC3BrC,QAAU,SAAU8K,GACR,IAAMP,MAAOO,GACThL,EAAKP,aAAasH,MACdzH,GAAU0L,EAAQP,KAAK,GACvBlL,KAAUyL,EAAQP,KAAK,IAG/BzK,GAAKP,aAAamL,KAAK,SAASC,EAAGC,GAC/B,MAAOD,GAAEvL,GAAKwL,EAAExL,GAAK,EAAIuL,EAAEvL,GAAKwL,EAAExL,GAAK,GAAK,QAMlE6C,kBAAmB,SAAS7D,GAK1B,GAAI2M,GAAiB,IACjBC,EAAc,MACK,oBAAZ5M,KAC2B,mBAAzBA,GAAQ8D,eACjB6I,EAAiB3M,EAAQ8D,cAEK,mBAArB9D,GAAQ+D,WACjB6I,EAAc5M,EAAQ+D,UAG1B,IAAIrC,GAAOL,IACXA,MAAKT,cAAgB,GAAInB,GAAWG,MAChCwI,IAAK,wBACLlE,KAAMxC,EAAKP,aACXgI,UAAWzH,EAAKqB,IAAIiE,KAAM,0BAC1B6F,MAAOF,IAEXtL,KAAKR,iBAAmB,GAAIpB,GAAWG,MACrCwI,IAAK,2BACLlE,KAAMxC,EAAKZ,gBACXqI,UAAWzH,EAAKqB,IAAIiE,KAAM,6BAC1B6F,MAAOD,KAIX9J,gBAAkB,WAChB,MAAOxB,GAAEuB,UAET,wCACE,6BACE,0KACE,uCACA,iBACF,YACA,mLACE,mCACA,mBACF,YACA,2CACE,2KACE,qCACA,eACF,YACF,UACA,2CACE,uFACE,8KACE,oCACA,oBACF,YACF,OACF,UACF,SAGF,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,2CACE,iCACE,6FACA,gKACE,wCACA,qBACF,aACF,SACF,UAGA,8BACE,2DACE,OACE,oHACA,6CACF,QACA,oCACE,OACE,iCACA,iDACF,QACF,UACA,wCACE,OACE,oCACA,qDACF,QACF,UACA,qCACE,OACE,4BACA,kDACF,QACF,UACA,yCACE,OACE,2CACA,sDACF,QACF,UACA,uCACE,OACE,mCACA,oDACF,QACF,UACA,+CACE,OACE,kCACA,wEACF,QACF,UACA,kDACE,OACE,qCACA,2EACF,QACF,UACA,4CACE,OACE,yCACA,qEACF,QACF,UACA,iDACE,OACE,oCACA,0EACF,QACF,UACA,mCACE,OACE,+BACA,4DACF,QACF,UACA,sCACE,OACE,2CACA,+DACF,QACF,UACA,qCACE,OACE,iDACA,8DACF,QACF,UACA,gCACE,OACE,4BACA,yDACF,QACF,UACF,WAEF,QACE,qBACA,SACF,SAEA,wCACE,QACE,6BACA,OACE,iEACE,wKACF,WACF,OACF,SACF,UAEA,SAEA,UACEyH,KAAK,MAGT5G,gBAAkB,WAChB,MAAOpC,GAAEuB,UAET,wCACE,6BACE,2EACE,qJACE,+CACA,uBACF,YACF,MACF,SAGA,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,8HAEA,8BACE,2DACE,OACE,2EACA,6CACF,QACA,oCACE,OACE,iCACA,iDACF,QACF,UACA,wCACE,OACE,oCACA,qDACF,QACF,UACA,qCACE,OACE,4BACA,kDACF,QACF,UACA,yCACE,OACE,2CACA,sDACF,QACF,UACA,uCACE,OACE,mCACA,oDACF,QACF,UACA,+CACE,OACE,kCACA,wEACF,QACF,UACA,kDACE,OACE,qCACA,2EACF,QACF,UACA,4CACE,OACE,yCACA,qEACF,QACF,UACA,iDACE,OACE,oCACA,0EACF,QACF,UACA,mCACE,OACE,+BACA,4DACF,QACF,UACA,sCACE,OACE,2CACA,+DACF,QACF,UACA,qCACE,OACE,iDACA,8DACF,QACF,UACA,gCACE,OACE,4BACA,yDACF,QACF,UACF,WACA,QACE,qBACA,SACF,SAEF,SAEF,UACEyH,KAAK,MAGT1G,sBAAwB,WACtB,MAAOtC,GAAEuB,UAET,wCACE,6BACE,kLACE,oCACA,eACF,YACA,8KACE,uCACA,aACF,YACF,SAGA,0BACE,6EACA,4DACE,uCACE,2GACF,iBACE,gFACF,UACF,YACF,QAEA,8BACE,wGACA,2DACE,OACE,oHACA,oIACF,QACA,OACE,iCACA,OACE,0EACF,QACF,QACA,OACE,oCACA,OACE,oEACF,QACF,QACA,OACE,4BACA,kDACF,QACA,OACE,2CACA,sDACF,QACA,OACE,mCACA,oDACF,QACA,mBACE,kCACA,wEACF,QACE,qCACA,yDACE,2EACF,iBACE,+BACF,UACF,QACA,OACE,yCACA,qEACF,QACA,OACE,oCACA,0EACF,QACA,OACE,+BACA,4DACF,QACA,OACE,iDACA,8DACF,QACA,OACE,2CACA,+DACF,QAEA,gCACE,OACE,4BACA,yDACF,QACF,UACF,WACA,QACE,qBACA,SACF,SACF,SAEF,UACEyH,KAAK,MAGTpC,2BAA6B,WAC3B,MAAO5G,GAAEuB,UAET,wCACE,6BACE,mDACE,6JACE,4CACA,0BACF,YACF,OACA,2EACE,mJACE,qCACA,wBACF,YACF,MACF,SAGA,0BACE,6EACE,4DACE,uCACE,2GACF,iBACE,gFACF,UACJ,YACF,QAEA,sDACA,oCACE,wBACE,yKACF,iBACE,+IACF,UACF,SACA,8BACE,uCACA,kDACA,mEACA,8KACA,QACA,uCACA,+LACA,4CACE,8DACE,yLACE,oCACA,4BACF,YACF,OACF,iBACE,4FACA,gKACE,wCACA,qBACA,YACF,gDACE,iLACE,kCACA,qBACF,YACF,OACF,UACA,6CACA,mEACA,iDACE,qFACA,mGACA,mGACF,SACA,4DACA,mEACA,iDACE,uLACF,SACA,iLACE,uCACA,aACF,YACF,SAEF,UACEyH,KAAK,MAGTrF,0BAA2B,WACzB,MAAO3D,GAAEuB,UACT,QACE,mCACE,mBACA,qHACE,8CACE,mGACF,YACF,YACF,SACA,mCACE,kBACA,4GACA,WACF,SACF,UACEyH,KAAK,MAITO,qBAAsB,WACpB,MAAOvJ,GAAEuB,UACT,uCACE,2CACE,iEACF,YACF,aACEyH,KAAK,OAKX,QACI5K,mBAAoBA"} \ No newline at end of file diff --git a/static/maps/mvc/library/library-foldertoolbar-view.js.map b/static/maps/mvc/library/library-foldertoolbar-view.js.map index 2294cf31586..d35d6d4952b 100644 --- a/static/maps/mvc/library/library-foldertoolbar-view.js.map +++ b/static/maps/mvc/library/library-foldertoolbar-view.js.map @@ -1 +1 @@ -{"version":3,"file":"library-foldertoolbar-view.js","sources":["../../../src/mvc/library/library-foldertoolbar-view.js"],"names":["define","mod_masthead","mod_utils","mod_toastr","mod_library_model","mod_select","FolderToolbarView","Backbone","View","extend","el","events","click #toolbtn_create_folder","click #toolbtn_bulk_import","click #include_deleted_datasets_chk","click #toolbtn_bulk_delete","click .toolbtn-show-locinfo","click .page_size_prompt","defaults","can_add_library_item","contains_file_or_folder","chain_call_control","total_number","failed_number","disabled_jstree_element","modal","jstree","histories","select_genome","select_extension","list_extensions","auto","id","text","description","list_genomes","initialize","options","this","_","fetchExtAndGenomes","render","toolbar_template","templateToolBar","template_defaults","is_admin","is_anonym","mutiple_add_dataset_options","Galaxy","user","isAdmin","isAnonymous","config","user_library_import_dir","allow_library_path_paste","library_import_dir","$el","html","renderPaginator","paginator_template","templatePaginator","$","find","show_page","parseInt","page_count","total_items_count","items_shown","configureElements","show","hide","tooltip","createFolderFromModal","event","preventDefault","stopPropagation","self","template","templateNewFolderInModal","closing_events","title","body","buttons","Create","create_new_folder_event","Close","folderDetails","serialize_new_folder","validate_new_folder","folder","FolderAsModel","url_items","history","fragment","split","current_folder_id","length","url","urlRoot","save","success","set","type","libraries","folderListView","collection","add","error","model","response","responseJSON","err_msg","name","val","modalBulkImport","checkedValues","info","refreshUserHistoriesList","that","templateBulkImportInModal","models","Import","importAllIntoHistory","callback","GalaxyHistories","fetch","disableButton","new_history_name","post","root","done","new_history","last_used_history_id","processImportToHistory","fail","always","enableButton","history_id","history_name","dataset_ids","folder_ids","each","parentElement","data","classList","contains","push","datasets_to_import","i","library_dataset_id","historyItem","HistoryItem","content","source","library_folder_id","initChainCallControl","action","jQuery","getJSON","chainCallImportingIntoHistory","updateProgress","progress","progressStep","width","Math","round","txt_representation","download","folder_id","format","ld_ids","processDownload","method","param","inputs","pair","appendTo","submit","remove","addFilesFromHistoryModal","template_modal","templateAddFilesFromHistory","folder_name","full_path","Add","addAllDatasetsFromHistory","closing_callback","library_router","back","fetchAndDisplayHistoryContents","change","target","value","importFilesFromPathModal","templateImportPathModal","importFromPathsClicked","navigate","trigger","renderSelectBoxes","get","datatypes","key","extension","description_url","sort","a","b","unshift","cache","genomes","css","container","importFilesFromGalaxyFolderModal","templateBrowserModal","importFromJstreePath","bind","renderJstree","Jstree","require","core","plugins","types","icon","file","checkbox","three_state","err_code","warning","preserve_dirs","is","link_data","file_type","dbkey","paths","valid_paths","trimmed","trim","chainCallImportingFolders","templateAddingDatasetsProgressBar","templateDeletingItemsProgressBar","templateImportIntoHistoryProgressBar","emit","all_nodes","get_selected","selected_nodes","filter","node","state","disabled","selection_type","undefined","li_attr","full_source","chainCallImportingUserdirFiles","history_contents","HistoryContents","history_contents_template","templateHistoryContents","contents","reverse","checked_hdas","history_item_ids","history_item_types","items_to_add","hid","item_type","history_item_id","folder_item","Item","from_hdca_id","from_hda_id","chainCallAddingHdas","history_item_set","popped_item","pop","onclick","window","location","promise","when","hdas_set","added_hdas","Folder","chainCallDeletingItems","items_to_delete","deleted_items","destroy","item","include_deleted","updated_item","model_class","checkIncludeDeleted","fetchFolder","checked","deleteSelectedItems","substring","items_total","dataset","showLocInfo","library","libraryListView","parent_library_id","showLocInfoModal","Library","templateLocInfoInModal","showImportModal","showPageSizePrompt","folder_page_size","prompt","preferences","join"],"mappings":"AAAAA,QACI,kBACA,cACA,cACA,4BACA,oBAEJ,SAAUC,EACAC,EACAC,EACAC,EACAC,GAGV,GAAIC,GAAoBC,SAASC,KAAKC,QACpCC,GAAI,UAEJC,QACEC,+BAAwC,wBACxCC,6BAAwC,kBACxCC,sCAAwC,sBACxCC,6BAAwC,sBACxCC,8BAAwC,cACxCC,0BAAwC,sBAI1CC,UACEC,sBAA4B,EAC5BC,yBAA4B,EAC5BC,oBAC4BC,aAAkB,EAClBC,cAAkB,GAE9CC,wBAA4B,WAG9BC,MAAQ,KAGRC,OAAQ,KAGRC,UAAY,KAGZC,cAAgB,KAGhBC,iBAAmB,KAGnBC,mBAGAC,MACIC,GAAc,OACdC,KAAc,cACdC,YAAc,sZASlBC,gBAEAC,WAAY,SAASC,GACnBC,KAAKD,QAAUE,EAAErB,SAAUmB,MAAeC,KAAKpB,UAC/CoB,KAAKE,qBACLF,KAAKG,UAGPA,OAAQ,SAASJ,GACfC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAIK,GAAmBJ,KAAKK,kBACxBC,GACAZ,GAAIM,KAAKD,QAAQL,GACjBa,UAAU,EACVC,WAAW,EACXC,6BAA6B,EAE7BC,QAAOC,OACTL,EAAkBC,SAAWG,OAAOC,KAAKC,UACzCN,EAAkBE,UAAYE,OAAOC,KAAKE,eACK,OAA1CH,OAAOI,OAAOC,yBAAoCL,OAAOI,OAAOE,4BAA6B,GAA8C,OAArCN,OAAOI,OAAOG,sBACvHX,EAAkBG,6BAA8B,IAGpDT,KAAKkB,IAAIC,KAAKf,EAAiBE,KAOjCc,gBAAiB,SAAUrB,GACvBC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAIsB,GAAqBrB,KAAKsB,mBAC9BC,GAAE,QAAQC,KAAM,qBAAsBL,KAAME,GACxC3B,GAAIM,KAAKD,QAAQL,GACjB+B,UAAWC,SAAU1B,KAAKD,QAAQ0B,WAClCE,WAAYD,SAAU1B,KAAKD,QAAQ4B,YACnCC,kBAAmB5B,KAAKD,QAAQ6B,kBAChCC,YAAa7B,KAAKD,QAAQ8B,gBAIlCC,kBAAmB,SAAS/B,GAC1BC,KAAKD,QAAUE,EAAE9B,OAAO6B,KAAKD,QAASA,GAElCC,KAAKD,QAAQlB,wBAAyB,EACxC0C,EAAE,sBAAsBQ,OAExBR,EAAE,sBAAsBS,OAEtBhC,KAAKD,QAAQjB,2BAA4B,GACvC4B,OAAOC,KACJD,OAAOC,KAAKE,eAIfU,EAAE,yBAAyBQ,OAC3BR,EAAE,gCAAgCS,SAJlCT,EAAE,gCAAgCQ,OAClCR,EAAE,yBAAyBQ,SAU/BR,EAAE,gCAAgCS,OAClCT,EAAE,yBAAyBS,QAE7BhC,KAAKkB,IAAIM,KAAK,iBAAiBS,WAIjCC,sBAAuB,SAAUC,GAC/BA,EAAMC,iBACND,EAAME,iBAGN,IAAIC,GAAOtC,KACPuC,EAAWvC,KAAKwC,0BACpBxC,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,oBAClBC,KAAkBJ,IAClBK,SACIC,OAAc,WAAYP,EAAKQ,2BAC/BC,MAAc,WAAYrC,OAAOvB,MAAM6C,YAMjDc,wBAAyB,WACrB,GAAIE,GAAgBhD,KAAKiD,sBACzB,IAAIjD,KAAKkD,oBAAoBF,GAAe,CACxC,GAAIG,GAAS,GAAIrF,GAAkBsF,aACnCC,WAAYpF,SAASqF,QAAQC,SAASC,MAAM,KAC5CC,kBAAoBJ,UAAUA,UAAUK,OAAO,GAC/CP,EAAOQ,IAAMR,EAAOS,QAAUH,kBAE9BN,EAAOU,KAAKb,GACVc,QAAS,SAAUX,GACjBzC,OAAOvB,MAAM6C,OACbnE,EAAWiG,QAAQ,mBACnBX,EAAOY,KAAKC,KAAS,WACrBtD,OAAOuD,UAAUC,eAAeC,WAAWC,IAAIjB,IAEjDkB,MAAO,SAASC,EAAOC,GACrB7D,OAAOvB,MAAM6C,OAEXnE,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,4BAKvB5G,GAAWwG,MAAM,4BAErB,QAAO,GAIXpB,qBAAuB,WACnB,OACIyB,KAAMnD,EAAE,sBAAsBoD,MAC9B/E,YAAa2B,EAAE,6BAA6BoD,QAKpDzB,oBAAqB,SAASF,GAC1B,MAA8B,KAAvBA,EAAc0B,MAKzBE,gBAAkB,WACd,GAAIC,GAAgBtD,EAAE,iBAAiBC,KAAK,WAChB,KAAzBqD,EAAcnB,OACb7F,EAAWiH,KAAK,wCAEhB9E,KAAK+E,yBAAyB,SAASC,GACrC,GAAIzC,GAAWyC,EAAKC,2BACpBD,GAAK7F,MAAQuB,OAAOvB,MACpB6F,EAAK7F,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,sBAClBC,KAAkBJ,GAAUlD,UAAY2F,EAAK3F,UAAU6F,SACvDtC,SACIuC,OAAc,WAAYH,EAAKI,wBAC/BrC,MAAc,WAAYrC,OAAOvB,MAAM6C,cAOzD+C,yBAA0B,SAASM,GACjC,GAAIL,GAAOhF,IACXA,MAAKX,UAAY,GAAIvB,GAAkBwH,gBACvCtF,KAAKX,UAAUkG,OACbzB,QAAS,WACPuB,EAASL,IAEXX,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBASzBW,qBAAuB,WACrBpF,KAAKb,MAAMqG,cAAc,SACzB,IAAIC,GAAmBzF,KAAKb,MAAMoC,EAAE,4BAA4BoD,MAC5DK,EAAOhF,IACX,IAAyB,KAArByF,EACFlE,EAAEmE,KAAMhF,OAAOiF,KAAO,iBAAkBjB,KAAMe,IAC3CG,KAAK,SAAUC,GACdb,EAAKjF,QAAQ+F,qBAAuBD,EAAYnG,GAChDsF,EAAKe,uBAAuBF,EAAYnG,GAAImG,EAAYnB,QAEzDsB,KAAK,WACJnI,EAAWwG,MAAM,uBAElB4B,OAAO,WACNjB,EAAK7F,MAAM+G,aAAa,gBAEvB,CACL,GAAIC,GAAa5E,EAAE,oDAAoDoD,KACvE3E,MAAKD,QAAQ+F,qBAAuBK,CACpC,IAAIC,GAAe7E,EAAE,oDAAoD5B,MACzEK,MAAK+F,uBAAuBI,EAAYC,GACxCpG,KAAKb,MAAM+G,aAAa,YAI5BH,uBAAwB,SAAUI,EAAYC,GAC5C,GAAIC,MACAC,IACJ/E,GAAE,iBAAiBC,KAAK,YAAY+E,KAAK,WACkB,KAAnDhF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eAC7GN,EAAYO,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OACA,KAAnDlF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eACpHL,EAAWM,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAKjE,KAAK,GADDI,MACKC,EAAIT,EAAY3C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC9C,GAAIC,GAAqBV,EAAYS,GACjCE,EAAc,GAAIlJ,GAAkBmJ,WACxCD,GAAYrD,IAAMqD,EAAYpD,QAAUuC,EAAa,YACrDa,EAAYE,QAAUH,EACtBC,EAAYG,OAAS,UACrBN,EAAmBD,KAAKI,GAK5B,IAAK,GAAIF,GAAIR,EAAW5C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC7C,GAAIM,GAAoBd,EAAWQ,GAC/BE,EAAc,GAAIlJ,GAAkBmJ,WACxCD,GAAYrD,IAAMqD,EAAYpD,QAAUuC,EAAa,YACrDa,EAAYE,QAAUE,EACtBJ,EAAYG,OAAS,iBACrBN,EAAmBD,KAAKI,GAG5BhH,KAAKqH,sBAAwB3D,OAAQmD,EAAmBnD,OAAQ4D,OAAQ,aAAclB,aAAcA,IAGpGmB,OAAOC,QAAS9G,OAAOiF,KAAO,6BAA+BQ,GAC7DnG,KAAKyH,8BAA+BZ,EAAoBT,IAM1DsB,eAAgB,WACZ1H,KAAK2H,UAAY3H,KAAK4H,aACtBrG,EAAG,wBAAyBsG,MAAOC,KAAKC,MAAO/H,KAAK2H,UAAa,KACjEK,mBAAqBF,KAAKC,MAAO/H,KAAK2H,UAAa,aACnDpG,EAAG,oBAAqB5B,KAAMqI,qBAQlCC,SAAW,SAAUC,EAAWC,GAC9B,GAAI9B,MACAC,IACA/E,GAAG,iBAAkBC,KAAM,YAAa+E,KAAM,WACc,KAAnDhF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eAC9GN,EAAYO,KAAMrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OACA,KAAnDlF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eACrHL,EAAWM,KAAMrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAGtE,IAAI9C,GAAMjD,OAAOiF,KAAO,mCAAqCwC,EACzD1B,GAAS2B,OAAW/B,EAAaC,WAAeA,EACpDtG,MAAKqI,gBAAiB1E,EAAK8C,EAAM,QAUnC4B,gBAAiB,SAAU1E,EAAK8C,EAAM6B,GACpC,GAAK3E,GAAO8C,EAAM,CAEhBA,EAAuB,gBAATA,GAAoBA,EAAOlF,EAAEgH,MAAO9B,EAElD,IAAI+B,GAAS,EACbjH,GAAEgF,KAAME,EAAKjD,MAAO,KAAO,WACnB,GAAIiF,GAAOzI,KAAKwD,MAAO,IACvBgF,IAAQ,8BAA+BC,EAAK,GAAI,YAAaA,EAAK,GAAI,SAG9ElH,EAAE,iBAAkBoC,EAAK,cAAe2E,GAAQ,QAAS,KAAKE,EAAO,WACpEE,SAAU,QAASC,SAASC,SAC7B/K,EAAWiH,KAAM,sCAEjBjH,GAAWwG,MAAO,uBAItBwE,yBAA0B,WACxB7I,KAAK+E,yBAA0B,SAAUzC,GACvCA,EAAKnD,MAAQuB,OAAOvB,KACpB,IAAI2J,GAAiBxG,EAAKyG,8BACtBC,EAAc1G,EAAKvC,QAAQkJ,UAAU3G,EAAKvC,QAAQkJ,UAAUvF,OAAS,GAAG,EAC5EpB,GAAKnD,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,+CAAiDsG,EACnErG,KAAkBmG,GAAgBzJ,UAAWiD,EAAKjD,UAAU6F,SAC5DtC,SACIsG,IAAc,WAAY5G,EAAK6G,6BAC/BpG,MAAc,WAAYrC,OAAOvB,MAAM6C,SAE3CoH,iBAAkB,WAChB1I,OAAOuD,UAAUoF,eAAeC,UAKlChH,EAAKjD,UAAU6F,OAAOxB,OAAS,GACjCpB,EAAKiH,+BAA+BjH,EAAKjD,UAAU6F,OAAO,GAAGxF,IAC7D6B,EAAG,qBAAsBiI,OAAO,SAASrH,GACvCG,EAAKiH,+BAA+BpH,EAAMsH,OAAOC,UAGnD7L,EAAWwG,MAAO,wBASxBsF,yBAA0B,WACxB,GAAI3E,GAAOhF,IACXA,MAAKb,MAAQuB,OAAOvB,KACpB,IAAI2J,GAAiB9I,KAAK4J,yBAC1B5J,MAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,+BAClBC,KAAkBmG,MAClBlG,SACIuC,OAAc,WAAaH,EAAK6E,uBAAuB7E,IACvDjC,MAAc,WAAarC,OAAOvB,MAAM6C,SAE5CoH,iBAAkB,WAEhB1I,OAAOuD,UAAUoF,eAAeS,SAAU,WAAa9E,EAAKtF,IAAMqK,SAAS,OAGjF/J,KAAKgK,qBAOP9J,mBAAoB,WAClB,GAAI8E,GAAOhF,IACXpC,GAAUqM,KACNtG,IAAYjD,OAAOiF,KAAO,qCAC1B7B,QAAY,SAAUoG,GACNlF,EAAKxF,kBACL,KAAK2K,MAAOD,GACRlF,EAAKxF,gBAAgBoH,MACjBlH,GAAkBwK,EAAUC,KAAKC,UACjCzK,KAAkBuK,EAAUC,KAAKC,UACjCxK,YAAkBsK,EAAUC,KAAKvK,YACjCyK,gBAAkBH,EAAUC,KAAKE,iBAGzCrF,GAAKxF,gBAAgB8K,KAAK,SAASC,EAAGC,GAClC,MAAOD,GAAE7K,GAAK8K,EAAE9K,GAAK,EAAI6K,EAAE7K,GAAK8K,EAAE9K,GAAK,GAAK,IAEhDsF,EAAKxF,gBAAgBiL,QAAQzF,EAAKvF,OAElDiL,OAAW,IAEf9M,EAAUqM,KACNtG,IAAajD,OAAOiF,KAAO,cAC3B7B,QAAU,SAAU6G,GACR3F,EAAKnF,eACL,KAAMsK,MAAOQ,GACT3F,EAAKnF,aAAa+G,MACdlH,GAAUiL,EAAQR,KAAK,GACvBxK,KAAUgL,EAAQR,KAAK,IAG/BnF,GAAKnF,aAAayK,KAAK,SAASC,EAAGC,GAC/B,MAAOD,GAAE7K,GAAK8K,EAAE9K,GAAK,EAAI6K,EAAE7K,GAAK8K,EAAE9K,GAAK,GAAK,KAG5DgL,OAAU,KAIhBV,kBAAmB,WAKjB,GAAIhF,GAAOhF,IACXA,MAAKV,cAAgB,GAAIvB,GAAWG,MAChC0M,IAAK,wBACLnE,KAAMzB,EAAKnF,aACXgL,UAAWnK,OAAOvB,MAAM+B,IAAIM,KAAM,0BAClCkI,MAAO,MAEX1J,KAAKT,iBAAmB,GAAIxB,GAAWG,MACrC0M,IAAK,2BACLnE,KAAMzB,EAAKxF,gBACXqL,UAAWnK,OAAOvB,MAAM+B,IAAIM,KAAM,6BAClCkI,MAAO,UAQXoB,iCAAkC,SAAU/K,GAC1C,GAAIiF,GAAOhF,KACP8I,EAAiB9I,KAAK+K,sBAC1B/K,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACTU,gBAAkB,EAClBC,MAAkB,iCAClBC,KAAkBmG,MAClBlG,SACIuC,OAAc,WACZH,EAAKgG,qBAAsBhG,EAAMjF,IAEnCgD,MAAc,WACZrC,OAAOvB,MAAM6C,SAGnBoH,iBAAkB,WAEhB1I,OAAOuD,UAAUoF,eAAeS,SAAS,WAAa9E,EAAKtF,IAAKqK,SAAS,OAI7ExI,EAAE,yBAAyB0J,KAAK,QAAS,WACvC1J,EAAE,mBAAmBnC,OAAO,eAE9BmC,EAAE,0BAA0B0J,KAAK,QAAS,WACxC1J,EAAE,mBAAmBnC,OAAO,iBAG9BY,KAAKgK,oBACLjK,EAAQb,wBAA0B,UAClCc,KAAKkL,aAAcnL,GAEnBwB,EAAG,qBAAsBiI,OAAQ,SAAUrH,GACb,2BAAtBA,EAAMsH,OAAOC,OACf3J,EAAQb,wBAA0B,UAClC8F,EAAKkG,aAAcnL,GACnBwB,EAAE,2BAA2BS,OAC7BT,EAAE,8BAA8BS,OAChCT,EAAE,sBAAsBS,OACxBT,EAAE,yBAAyBQ,QACK,yBAAtBI,EAAMsH,OAAOC,QACvBnI,EAAE,yBAAyBS,OAC3BT,EAAE,2BAA2BQ,OAC7BR,EAAE,sBAAsBQ,OACxBR,EAAE,8BAA8BQ,OAChChC,EAAQb,wBAA0B,QAClC8F,EAAKkG,aAAcnL,OAY3BmL,aAAc,SAAUnL,GAEtBC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAI0J,GAAS1J,EAAQoH,QAAU,UAC3BjI,EAA0Bc,KAAKD,QAAQb,uBAC3Cc,MAAKZ,OAAS,GAAItB,GAAkBqN,OACpCnL,KAAKZ,OAAOuE,IAAM3D,KAAKZ,OAAOwE,QACV,WAAa6F,EACb,0BACcvK,EAClCc,KAAKZ,OAAOmG,OACVzB,QAAS,SAASQ,GAEhB5G,OAAQ,SAAU,WAAY,MAAO6J,UAErC6D,SAAU,sBAAwB,WAChC7J,EAAE,mBAAmBnC,OAAO,WAC5BmC,EAAE,mBAAmBnC,QACnBiM,MACE5E,KAAQnC,GAEVgH,SAAY,QAAS,YACrBC,OACEpI,QACEqI,KAAQ,iBAEVC,MACED,KAAQ,gBAGZE,UACEC,aAAa,QAKrBtH,MAAO,SAASC,EAAOC,GACgB,mBAA1BA,GAASC,aACqB,SAAnCD,EAASC,aAAaoH,SACxB/N,EAAWgO,QAAQtH,EAASC,aAAaC,SAEzC5G,EAAWwG,MAAME,EAASC,aAAaC,SAGzC5G,EAAWwG,MAAM,yBAWzBwF,uBAAwB,WACtB,GAAIiC,GAAgB9L,KAAKb,MAAM+B,IAAIM,KAAK,sBAAsBuK,GAAG,YAC7DC,EAAYhM,KAAKb,MAAM+B,IAAIM,KAAK,kBAAkBuK,GAAG,YACrDE,EAAYjM,KAAKT,iBAAiBmK,QAClCwC,EAAQlM,KAAKV,cAAcoK,QAC3ByC,EAAQ5K,EAAE,yBAAyBoD,MACnCyH,IACJ,IAAKD,EAEE,CACLnM,KAAKb,MAAMqG,cAAc,UACzB2G,EAAQA,EAAM3I,MAAM,KACpB,KAAK,GAAIsD,GAAIqF,EAAMzI,OAAS,EAAGoD,GAAK,EAAGA,IACrCuF,QAAUF,EAAMrF,GAAGwF,OACE,IAAjBD,QAAQ3I,QACV0I,EAAYxF,KAAKyF,QAGrBrM,MAAKqH,sBAAwB3D,OAAQ0I,EAAY1I,OAAQ4D,OAAQ,oBACjEtH,KAAKuM,2BAA6BJ,MAAOC,EACPN,cAAeA,EACfE,UAAWA,EACX7E,OAAQ,aACR8E,UAAWA,EACXC,MAAOA,QAhBzCrO,GAAWiH,KAAK,iDAyBpBuC,qBAAsB,SAAUtH,GAC9B,GAAIwC,EACJ,QAAQxC,EAAQuH,QACd,IAAK,kBACH/E,EAAWvC,KAAKwM,oCAChBxM,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,GAAYyG,YAAchJ,KAAKD,QAAQiJ,cAClF,MACF,KAAK,oBACHzG,EAAWvC,KAAKyM,mCAChBzM,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,IAC3C,MACF,KAAK,aACHA,EAAWvC,KAAK0M,uCAChB1M,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,GAAY6D,aAAerG,EAAQqG,eAC9E,MACF,SACE1F,OAAOiM,KAAKtI,MAAO,0BAA2B,YAMlDrE,KAAK2H,SAAW,EAChB3H,KAAK4H,aAAe,IAAM7H,EAAQ2D,OAClC1D,KAAKD,QAAQhB,mBAAmBC,aAAee,EAAQ2D,OACvD1D,KAAKD,QAAQhB,mBAAmBE,cAAgB,GAWlD+L,qBAAsB,SAAWhG,EAAMjF,GACrC,GAAI6M,GAAYrL,EAAG,mBAAoBnC,SAASyN,cAAc,EAE9DC,gBAAiB7M,EAAE8M,OAAOH,EAAW,SAASI,GAAO,MAA8B,IAAvBA,EAAKC,MAAMC,UACvE,IAAIpB,GAAgB9L,KAAKb,MAAM+B,IAAIM,KAAM,sBAAuBuK,GAAI,YAChEC,EAAYhM,KAAKb,MAAM+B,IAAIM,KAAM,kBAAmBuK,GAAI,YACxDE,EAAYjM,KAAKT,iBAAiBmK,QAClCwC,EAAQlM,KAAKV,cAAcoK,QAC3ByD,EAAiBL,eAAe,GAAG9I,KACnCmI,IACJ,IAAKW,eAAepJ,OAAS,EAC3B7F,EAAWiH,KAAM,uCACZ,CACL9E,KAAKb,MAAMqG,cAAe,SAC1B,KAAM,GAAIsB,GAAIgG,eAAepJ,OAAS,EAAGoD,GAAK,EAAGA,IACFsG,SAAxCN,eAAehG,GAAGuG,QAAQpE,WAC7BkD,EAAMvF,KAAMkG,eAAehG,GAAGuG,QAAQpE,UAI1C,IADAjJ,KAAKqH,sBAAwB3D,OAAQyI,EAAMzI,OAAQ4D,OAAQ,oBACnC,WAAnB6F,EAA6B,CAChC,GAAIG,GAAcvN,EAAQoH,OAAS,SACnCnH,MAAKuM,2BAA6BJ,MAAOA,EACPL,cAAeA,EACfE,UAAWA,EACX7E,OAAQmG,EACRrB,UAAWA,EACXC,MAAOA,QACpC,IAAwB,SAAnBiB,EAA2B,CACrC,GAAIG,GAAcvN,EAAQoH,OAAS,OACnCnH,MAAKuN,gCAAkCpB,MAAQA,EACRF,UAAWA,EACXC,MAAOA,EACP/E,OAAQmG,OAKrD/D,+BAAgC,SAASpD,GACvC,GAAIqH,GAAmB,GAAI1P,GAAkB2P,iBAAiB/N,GAAGyG,IAC7D7D,EAAOtC,IACXwN,GAAiBjI,OACfzB,QAAS,SAAS0J,GAChB,GAAIE,GAA4BpL,EAAKqL,yBACrCrL,GAAKjD,UAAU4K,IAAI9D,GAAYpC,KAAK6J,SAAaJ,IACjDlL,EAAKnD,MAAM+B,IAAIM,KAAK,6BAA6BL,KAAKuM,GAA2BF,iBAAkBA,EAAiBtI,OAAO2I,cAE7HxJ,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBASzB0E,0BAA4B,WAC1B,GAAI2E,GAAe9N,KAAKb,MAAM+B,IAAIM,KAAM,6BAA8BA,KAAM,YACxEuM,KACAC,KACAC,IACJ,IAAKH,EAAapK,OAAS,EACzB7F,EAAWiH,KAAM,4CACZ,CACL9E,KAAKb,MAAMqG,cAAe,OAC1BsI,EAAavH,KAAK,WAChB,GAAI2H,GAAM3M,EAAGvB,KAAKwG,eAAgBC,KAAM,KACxC,IAAKyH,EAAM,CACT,GAAIC,GAAY5M,EAAGvB,KAAKwG,eAAgBC,KAAM,OAC9CsH,GAAiBnH,KAAMsH,GACvBF,EAAmBpH,KAAMuH,KAG7B,KAAM,GAAIrH,GAAIiH,EAAiBrK,OAAS,EAAGoD,GAAK,EAAGA,IAAM,CACvDsH,gBAAkBL,EAAiBjH,EACnC,IAAIuH,GAAc,GAAIvQ,GAAkBwQ,IACxCD,GAAY1K,IAAMjD,OAAOiF,KAAO,eAAiB3F,KAAKD,QAAQL,GAAK,YAEjE2O,EAAYtK,IADgB,eAA1BiK,EAAmBlH,IACJyH,aAAgBH,kBAEhBI,YAAeJ,kBAElCH,EAAarH,KAAKyH,GAEpBrO,KAAKqH,sBAAwB3D,OAAQuK,EAAavK,OAAQ4D,OAAQ,oBAClEtH,KAAKyO,oBAAqBR,KAU9BxG,8BAA+B,SAAUiH,EAAkBtI,GACzD,GAAI9D,GAAOtC,KACP2O,EAAcD,EAAiBE,KACnC,IAA2B,mBAAfD,GASV,MARuD,KAAlD3O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,6EAA8E,IAAM+K,QAAS,WAAaC,OAAOC,SAASrO,OAAOiF,QAC3I3F,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,kEACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,gGAAiG,IAAMgD,QAAS,WAAaC,OAAOC,SAASrO,OAAOiF,QAE1KjF,OAAOvB,MAAM6C,QACN,CAET,IAAIgN,GAAUzN,EAAE0N,KAAMN,EAAY9K,MAAQqD,QAASyH,EAAYzH,QAASC,OAAQwH,EAAYxH,SAE5F6H,GAAQpJ,KAAM,WACJtD,EAAKoF,iBACLpF,EAAKmF,8BAA+BiH,EAAkBtI,KAEvDJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAKmF,8BAA+BiH,EAAkBtI,MASlEmH,+BAAgC,SAAUxN,GAExC,GAAIiF,GAAOhF,KACP2O,EAAc5O,EAAQoM,MAAMyC,KAChC,IAA4B,mBAAhBD,GAOV,MANuD,KAAlD3O,KAAKD,QAAQhB,mBAAmBE,eACnCpB,EAAWiG,QAAS,mDACpBpD,OAAOvB,MAAM6C,QAEbnE,EAAWwG,MAAO,sBAEb,CAET,IAAI2K,GAAUzN,EAAE0N,KAAM1N,EAAEmE,KAAMhF,OAAOiF,KAAO,4CAA8CX,EAAKtF,GAC5C,WAAaK,EAAQoH,OACrB,SAAWwH,EACX,cAAgB5O,EAAQkM,UACxB,UAAYlM,EAAQmM,OACvE8C,GAAQpJ,KAAM,WACJZ,EAAK0C,iBACL1C,EAAKuI,+BAAgCxN,KAEtCiG,KAAM,WACLhB,EAAKjF,QAAQhB,mBAAmBE,eAAiB,EACjD+F,EAAK0C,iBACL1C,EAAKuI,+BAAgCxN,MAajDwM,0BAA2B,SAAUxM,GAEnC,GAAIiF,GAAOhF,KACP2O,EAAc5O,EAAQoM,MAAMyC,KAChC,IAA0B,mBAAfD,GAQT,MAPsD,KAAlD3O,KAAKD,QAAQhB,mBAAmBE,eAClCpB,EAAWiG,QAAQ,yEACnBpD,OAAOvB,MAAM6C,QAGbnE,EAAWwG,MAAM,sBAEZ,CAET,IAAI2K,GAAUzN,EAAE0N,KAAM1N,EAAEmE,KAAMhF,OAAOiF,KAAO,4CAA8CX,EAAKtF,GACzC,WAAaK,EAAQoH,OACrB,SAAWwH,EACX,kBAAoB5O,EAAQ+L,cAC5B,cAAgB/L,EAAQiM,UACxB,cAAgBjM,EAAQkM,UACxB,UAAYlM,EAAQmM,OAC1E8C,GAAQpJ,KAAK,WACHZ,EAAK0C,iBACL1C,EAAKuH,0BAA2BxM,KAEjCiG,KAAK,WACJhB,EAAKjF,QAAQhB,mBAAmBE,eAAiB,EACjD+F,EAAK0C,iBACL1C,EAAKuH,0BAA2BxM,MAS5C0O,oBAAqB,SAAUS,GAC7B,GAAI5M,GAAOtC,IACXA,MAAKmP,WAAa,GAAIrR,GAAkBsR,MACxC,IAAIT,GAAcO,EAASN,KAC3B,IAA2B,mBAAfD,GASV,MARuD,KAAlD3O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,sDACV9D,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,gEACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,yDAEtBnL,OAAOvB,MAAM6C,OACNhC,KAAKmP,UAEd,IAAIH,GAAUzN,EAAE0N,KAAMN,EAAY9K,MAAQ2K,YAAaG,EAAY1E,IAAK,iBAExE+E,GAAQpJ,KAAM,SAAUtB,GACd5D,OAAOuD,UAAUC,eAAeC,WAAWC,IAAKE,GAChDhC,EAAKoF,iBACLpF,EAAKmM,oBAAqBS,KAE3BlJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAKmM,oBAAqBS,MAStCG,uBAAwB,SAAUC,GAClC,GAAIhN,GAAOtC,IACXA,MAAKuP,cAAgB,GAAIzR,GAAkBsR,MAC3C,IAAIT,GAAcW,EAAgBV,KAClC,IAA4B,mBAAhBD,GASV,MARuD,KAAlD3O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,gCACV9D,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,mGACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,6FAEtBnL,OAAOvB,MAAM6C,OACNhC,KAAKuP,aAEd,IAAIP,GAAUzN,EAAE0N,KAAMN,EAAYa,UAElCR,GAAQpJ,KAAM,SAAU6J,GAId,GAHA/O,OAAOuD,UAAUC,eAAeC,WAAWyE,OAAQ+F,EAAYjP,IAC/D4C,EAAKoF,iBAEAhH,OAAOuD,UAAUC,eAAenE,QAAQ2P,gBAAiB,CAC5D,GAAIC,GAAe,IACD,YAAdF,EAAKzL,MAA0C,kBAArByL,EAAKG,YACjCD,EAAe,GAAI7R,GAAkBsF,cAAeqM,GAC7B,SAAdA,EAAKzL,MAAwC,mBAArByL,EAAKG,YACtCD,EAAe,GAAI7R,GAAkBwQ,KAAMmB,IAE3C/O,OAAOiM,KAAKtI,MAAM,mCAAoC,YACtD3D,OAAOiM,KAAKtI,MAAMoL,EAAKzL,MAAQyL,EAAKG,YAAa,aAEnDlP,OAAOuD,UAAUC,eAAeC,WAAWC,IAAKuL,GAElDrN,EAAK+M,uBAAwBC,KAE9BtJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAK+M,uBAAwBC,MAOvCO,oBAAqB,SAAS1N,GAE1BzB,OAAOuD,UAAUC,eAAe4L,YAD9B3N,EAAMsH,OAAOsG,SAC8BL,iBAAiB,IAEjBA,iBAAiB,KAOlEM,oBAAqB,WACnB,GAAInL,GAAgBtD,EAAE,iBAAiBC,KAAK,WAC5C,IAA4B,IAAzBqD,EAAcnB,OACb7F,EAAWiH,KAAK,uDACb,CACL,GAAIvC,GAAWvC,KAAKyM,kCACpBzM,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,0BAClBC,KAAkBJ,MAClBK,SACIG,MAAc,WAAYrC,OAAOvB,MAAM6C,WAI/ChC,KAAKD,QAAQhB,mBAAmBC,aAAe,EAC/CgB,KAAKD,QAAQhB,mBAAmBE,cAAgB,CAEhD,IAAIoH,MACAC,IACJzB,GAAc0B,KAAK,WACwC6G,SAAnD7L,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAC4B,KAAjElF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,MAAMwJ,UAAU,EAAE,GAC7D3J,EAAWM,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAEzDJ,EAAYO,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,SAKpE,IAAIyJ,GAAc7J,EAAY3C,OAAS4C,EAAW5C,MAClD1D,MAAK4H,aAAe,IAAMsI,EAC1BlQ,KAAK2H,SAAW,CAIhB,KAAK,GADD2H,MACKxI,EAAIT,EAAY3C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC9C,GAAIqJ,GAAU,GAAIrS,GAAkBwQ,MAAM5O,GAAG2G,EAAYS,IACzDwI,GAAgB1I,KAAKuJ,GAEzB,IAAK,GAAIrJ,GAAIR,EAAW5C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC7C,GAAI3D,GAAS,GAAIrF,GAAkBsF,eAAe1D,GAAG4G,EAAWQ,IAChEwI,GAAgB1I,KAAKzD,GAGzBnD,KAAKD,QAAQhB,mBAAmBC,aAAekR,EAAYxM,OAE3D1D,KAAKqP,uBAAuBC,KAKhCc,YAAa,WACX,GAAIC,GAAU,KACVrL,EAAOhF,IAC8B,QAArCU,OAAOuD,UAAUqM,iBACnBD,EAAU3P,OAAOuD,UAAUqM,gBAAgBnM,WAAW8F,IAAIjK,KAAKD,QAAQwQ,mBACvEvQ,KAAKwQ,iBAAiBH,KAEtBA,EAAU,GAAIvS,GAAkB2S,SAAS/Q,GAAIM,KAAKD,QAAQwQ,oBAC1DF,EAAQ9K,OACNzB,QAAS,WACPkB,EAAKwL,iBAAiBH,IAExBhM,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,0BAO3B+L,iBAAkB,SAASH,GACzB,GAAIrL,GAAOhF,KACPuC,EAAWvC,KAAK0Q,wBACpB1Q,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,mBAClBC,KAAkBJ,GAAU8N,QAASA,EAAStQ,QAASiF,EAAKjF,UAC5D6C,SACIG,MAAc,WAAYrC,OAAOvB,MAAM6C,YAKjD2O,gBAAiB,SAAS5Q,GACxB,OAAOA,EAAQoH,QACb,IAAK,UACHnH,KAAK6I,0BACL,MACF,KAAK,YACH7I,KAAK8K,kCAAoC3D,OAAQ,aACjD,MACF,KAAK,OACHnH,KAAK2J,0BACL,MACF,KAAK,UACH3J,KAAK8K,kCAAoC3D,OAAQ,WACjD,MACF,SACEzG,OAAOuD,UAAUoF,eAAeC,OAChCzL,EAAWwG,MAAM,4BAQvBuM,mBAAoB,WAClB,GAAIC,GAAmBC,OAAQ,8CAA+CpQ,OAAOuD,UAAU8M,YAAY9G,IAAK,oBACrF,OAApB4G,GAAgCA,GAAoBnP,SAAUmP,KACjEnQ,OAAOuD,UAAU8M,YAAYhN,KAAO8M,iBAAoBnP,SAAUmP,KAClEnQ,OAAOuD,UAAUC,eAAe/D,QAAUT,GAAIM,KAAKD,QAAQL,GAAI+B,UAAW,MAIhFpB,gBAAiB,WACf,MAAOJ,GAAEsC,UAET,wCAEE,6BACE,yCACE,+CAEA,2DACA,sGACE,UACE,mFACF,WACF,SACA,qNACE,qEACF,YACA,0CACA,kEACE,oIACE,8FACF,YACA,yCACE,yEACA,6DACE,gFACF,UACA,qDACE,4BACA,+CACA,wDACE,mFACF,UACA,qDACE,kEACF,UACF,UACF,QACF,SACA,iBACE,0LACE,mEACF,OACF,UACA,iOACE,mCACA,mBACF,YACA,0FACE,kIACE,4EACF,YACA,yCACE,kEACA,kEACA,+DACF,QACF,SACE,+NACA,oDACA,8LACE,0CACA,gBACF,YACA,qGACE,8FACE,gDACE,8CACA,aACF,YACF,OACF,UACF,SACF,UAEF,kCACA,SAEA,wDAEF,UACEyO,KAAK,MAGTN,uBAAwB,WACtB,MAAOzQ,GAAEsC,UACP,QACE,6CACE,UACE,uCACA,YACF,WACA,UACE,OACE,gBACA,sCACF,QACA,gDACE,OACE,uBACA,6CACF,QACF,UACA,6CACE,OACE,oBACA,0CACF,QACF,UACA,uDACE,OACE,mBACA,2GACF,QACF,UACA,OACE,cACA,oCACF,QACF,WACF,WACA,6CACE,UACE,sCACA,YACF,WACA,UACE,OACE,gBACA,sCACF,QACA,gDACE,OACE,uBACA,6CACF,QACF,UACA,OACE,cACA,6BACF,QACA,WACJ,WACJ,UACEyO,KAAK,MAGTxO,yBAA0B,WACxB,MAAOvC,GAAEsC,UACT,8BACE,SACE,wEACA,4EACF,UACF,UACEyO,KAAK,MAIT/L,0BAA4B,WAC1B,MAAOhF,GAAEsC,UACT,QACE,mCACE,mBACA,iHACE,8CACE,mGACF,YACF,YACF,SACA,mCACE,kBACA,4GACA,WACF,SACF,UACEyO,KAAK,MAGTtE,qCAAuC,WACrC,MAAOzM,GAAEsC,UACT,4BACE,2EACF,SACA,yBACE,gJACE,mDACF,SACF,UACEyO,KAAK,MAGTxE,kCAAmC,WACjC,MAAOvM,GAAEsC,UACT,4BACE,iFACF,SACA,yBACE,gJACE,mDACF,SACF,UACEyO,KAAK,MAGTvE,iCAAkC,WAChC,MAAOxM,GAAEsC,UACT,4BACA,SACA,yBACE,gJACE,mDACF,SACF,UACEyO,KAAK,MAGTjG,qBAAsB,WACpB,MAAO9K,GAAEsC,UACT,gCACE,0JACA,wLACA,mCACE,oFACE,yGACF,WACA,sFACA,uFACA,WACF,SACA,mCACE,kFACE,yFACA,+BACF,WACA,0EACE,mEACA,gCACF,WACF,SACA,qGACE,aACF,YACA,qGACE,cACF,YACA,SAEA,4BACA,SACA,SACA,kFACA,QACE,gFACA,4EACA,SACJ,UACEyO,KAAK,MAGTpH,wBAAyB,WACvB,MAAO3J,GAAEsC,UACT,gCACE,+JACA,sCACE,4DACE,yFACA,+BACF,WACA,oDACE,mEACA,gCACF,WACF,SACA,uKACA,SACA,kFACA,QACE,gFACA,4EACF,SACF,UACEyO,KAAK,MAGTjI,4BAA6B,WAC3B,MAAO9I,GAAEsC,UACT,6BACE,QACE,oBACA,8EACE,8CACE,mGACF,YACF,YACF,SACA,QACA,sCACA,SACF,UACEyO,KAAK;;EAGTrD,wBAAyB,WACvB,MAAO1N,GAAEsC,UACT,kDACA,OACE,0DACE,oDACE,yDACI,kEACA,0CACE,+GACE,sJACF,QACD,iBACE,6FACG,2GACE,oKACF,UACF,QACF,UACN,iGACI,+GACE,iIACF,QACJ,UACF,UACF,YACF,SACEyO,KAAK,MAGT1P,kBAAmB,WACjB,MAAOrB,GAAEsC,UACT,wCACE,uCACE,gDACE,iGACA,wHACF,iBACE,iGACA,2GACF,UACF,iBACE,kHACA,wHACF,UACA,sBACE,0FACF,QACA,4CACE,2GACA,0HACF,iBACE,yHACA,2IACF,UACF,QACA,SACE,sBACA,8HACE,qBACF,OACA,0CACF,WACEyO,KAAK,OAKX,QACIhT,kBAAmBA"} \ No newline at end of file +{"version":3,"file":"library-foldertoolbar-view.js","sources":["../../../src/mvc/library/library-foldertoolbar-view.js"],"names":["define","mod_masthead","mod_utils","mod_toastr","mod_library_model","mod_select","FolderToolbarView","Backbone","View","extend","el","events","click #toolbtn_create_folder","click #toolbtn_bulk_import","click #include_deleted_datasets_chk","click #toolbtn_bulk_delete","click .toolbtn-show-locinfo","click .page_size_prompt","defaults","can_add_library_item","contains_file_or_folder","chain_call_control","total_number","failed_number","disabled_jstree_element","modal","jstree","histories","select_genome","select_extension","list_extensions","auto","id","text","description","list_genomes","initialize","options","this","_","fetchExtAndGenomes","render","toolbar_template","templateToolBar","template_defaults","is_admin","is_anonym","mutiple_add_dataset_options","Galaxy","user","isAdmin","isAnonymous","config","user_library_import_dir","allow_library_path_paste","library_import_dir","$el","html","renderPaginator","paginator_template","templatePaginator","$","find","show_page","parseInt","page_count","total_items_count","items_shown","configureElements","show","hide","tooltip","createFolderFromModal","event","preventDefault","stopPropagation","self","template","templateNewFolderInModal","closing_events","title","body","buttons","Create","create_new_folder_event","Close","folderDetails","serialize_new_folder","validate_new_folder","folder","FolderAsModel","url_items","history","fragment","split","current_folder_id","length","url","urlRoot","save","success","set","type","libraries","folderListView","collection","add","error","model","response","responseJSON","err_msg","name","val","modalBulkImport","checkedValues","info","refreshUserHistoriesList","that","templateBulkImportInModal","models","Import","importAllIntoHistory","callback","GalaxyHistories","fetch","disableButton","new_history_name","post","root","done","new_history","last_used_history_id","processImportToHistory","fail","always","enableButton","history_id","history_name","dataset_ids","folder_ids","each","parentElement","data","classList","contains","push","datasets_to_import","i","library_dataset_id","historyItem","HistoryItem","content","source","library_folder_id","initChainCallControl","action","jQuery","getJSON","chainCallImportingIntoHistory","updateProgress","progress","progressStep","width","Math","round","txt_representation","download","folder_id","format","ld_ids","processDownload","method","param","inputs","pair","appendTo","submit","remove","addFilesFromHistoryModal","template_modal","templateAddFilesFromHistory","folder_name","full_path","Add","addAllDatasetsFromHistory","closing_callback","library_router","back","fetchAndDisplayHistoryContents","change","target","value","importFilesFromPathModal","templateImportPathModal","importFromPathsClicked","navigate","trigger","renderSelectBoxes","get","datatypes","key","extension","description_url","sort","a","b","unshift","cache","genomes","css","container","importFilesFromGalaxyFolderModal","templateBrowserModal","importFromJstreePath","bind","renderJstree","Jstree","require","core","plugins","types","icon","file","checkbox","three_state","err_code","warning","preserve_dirs","is","link_data","file_type","dbkey","paths","valid_paths","trimmed","trim","chainCallImportingFolders","templateAddingDatasetsProgressBar","templateDeletingItemsProgressBar","templateImportIntoHistoryProgressBar","emit","all_nodes","get_selected","selected_nodes","filter","node","state","disabled","tag_using_filenames","selection_type","undefined","li_attr","full_source","chainCallImportingUserdirFiles","history_contents","HistoryContents","history_contents_template","templateHistoryContents","contents","reverse","checked_hdas","history_item_ids","history_item_types","items_to_add","hid","item_type","history_item_id","folder_item","Item","from_hdca_id","from_hda_id","chainCallAddingHdas","history_item_set","popped_item","pop","onclick","window","location","promise","when","hdas_set","added_hdas","Folder","chainCallDeletingItems","items_to_delete","deleted_items","destroy","item","include_deleted","updated_item","model_class","checkIncludeDeleted","fetchFolder","checked","deleteSelectedItems","substring","items_total","dataset","showLocInfo","library","libraryListView","parent_library_id","showLocInfoModal","Library","templateLocInfoInModal","showImportModal","showPageSizePrompt","folder_page_size","prompt","preferences","join"],"mappings":"AAAAA,QACI,kBACA,cACA,cACA,4BACA,oBAEJ,SAAUC,EACAC,EACAC,EACAC,EACAC,GAGV,GAAIC,GAAoBC,SAASC,KAAKC,QACpCC,GAAI,UAEJC,QACEC,+BAAwC,wBACxCC,6BAAwC,kBACxCC,sCAAwC,sBACxCC,6BAAwC,sBACxCC,8BAAwC,cACxCC,0BAAwC,sBAI1CC,UACEC,sBAA4B,EAC5BC,yBAA4B,EAC5BC,oBAC4BC,aAAkB,EAClBC,cAAkB,GAE9CC,wBAA4B,WAG9BC,MAAQ,KAGRC,OAAQ,KAGRC,UAAY,KAGZC,cAAgB,KAGhBC,iBAAmB,KAGnBC,mBAGAC,MACIC,GAAc,OACdC,KAAc,cACdC,YAAc,sZASlBC,gBAEAC,WAAY,SAASC,GACnBC,KAAKD,QAAUE,EAAErB,SAAUmB,MAAeC,KAAKpB,UAC/CoB,KAAKE,qBACLF,KAAKG,UAGPA,OAAQ,SAASJ,GACfC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAIK,GAAmBJ,KAAKK,kBACxBC,GACAZ,GAAIM,KAAKD,QAAQL,GACjBa,UAAU,EACVC,WAAW,EACXC,6BAA6B,EAE7BC,QAAOC,OACTL,EAAkBC,SAAWG,OAAOC,KAAKC,UACzCN,EAAkBE,UAAYE,OAAOC,KAAKE,eACK,OAA1CH,OAAOI,OAAOC,yBAAoCL,OAAOI,OAAOE,4BAA6B,GAA8C,OAArCN,OAAOI,OAAOG,sBACvHX,EAAkBG,6BAA8B,IAGpDT,KAAKkB,IAAIC,KAAKf,EAAiBE,KAOjCc,gBAAiB,SAAUrB,GACvBC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAIsB,GAAqBrB,KAAKsB,mBAC9BC,GAAE,QAAQC,KAAM,qBAAsBL,KAAME,GACxC3B,GAAIM,KAAKD,QAAQL,GACjB+B,UAAWC,SAAU1B,KAAKD,QAAQ0B,WAClCE,WAAYD,SAAU1B,KAAKD,QAAQ4B,YACnCC,kBAAmB5B,KAAKD,QAAQ6B,kBAChCC,YAAa7B,KAAKD,QAAQ8B,gBAIlCC,kBAAmB,SAAS/B,GAC1BC,KAAKD,QAAUE,EAAE9B,OAAO6B,KAAKD,QAASA,GAElCC,KAAKD,QAAQlB,wBAAyB,EACxC0C,EAAE,sBAAsBQ,OAExBR,EAAE,sBAAsBS,OAEtBhC,KAAKD,QAAQjB,2BAA4B,GACvC4B,OAAOC,KACJD,OAAOC,KAAKE,eAIfU,EAAE,yBAAyBQ,OAC3BR,EAAE,gCAAgCS,SAJlCT,EAAE,gCAAgCQ,OAClCR,EAAE,yBAAyBQ,SAU/BR,EAAE,gCAAgCS,OAClCT,EAAE,yBAAyBS,QAE7BhC,KAAKkB,IAAIM,KAAK,iBAAiBS,WAIjCC,sBAAuB,SAAUC,GAC/BA,EAAMC,iBACND,EAAME,iBAGN,IAAIC,GAAOtC,KACPuC,EAAWvC,KAAKwC,0BACpBxC,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,oBAClBC,KAAkBJ,IAClBK,SACIC,OAAc,WAAYP,EAAKQ,2BAC/BC,MAAc,WAAYrC,OAAOvB,MAAM6C,YAMjDc,wBAAyB,WACrB,GAAIE,GAAgBhD,KAAKiD,sBACzB,IAAIjD,KAAKkD,oBAAoBF,GAAe,CACxC,GAAIG,GAAS,GAAIrF,GAAkBsF,aACnCC,WAAYpF,SAASqF,QAAQC,SAASC,MAAM,KAC5CC,kBAAoBJ,UAAUA,UAAUK,OAAO,GAC/CP,EAAOQ,IAAMR,EAAOS,QAAUH,kBAE9BN,EAAOU,KAAKb,GACVc,QAAS,SAAUX,GACjBzC,OAAOvB,MAAM6C,OACbnE,EAAWiG,QAAQ,mBACnBX,EAAOY,KAAKC,KAAS,WACrBtD,OAAOuD,UAAUC,eAAeC,WAAWC,IAAIjB,IAEjDkB,MAAO,SAASC,EAAOC,GACrB7D,OAAOvB,MAAM6C,OAEXnE,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,4BAKvB5G,GAAWwG,MAAM,4BAErB,QAAO,GAIXpB,qBAAuB,WACnB,OACIyB,KAAMnD,EAAE,sBAAsBoD,MAC9B/E,YAAa2B,EAAE,6BAA6BoD,QAKpDzB,oBAAqB,SAASF,GAC1B,MAA8B,KAAvBA,EAAc0B,MAKzBE,gBAAkB,WACd,GAAIC,GAAgBtD,EAAE,iBAAiBC,KAAK,WAChB,KAAzBqD,EAAcnB,OACb7F,EAAWiH,KAAK,wCAEhB9E,KAAK+E,yBAAyB,SAASC,GACrC,GAAIzC,GAAWyC,EAAKC,2BACpBD,GAAK7F,MAAQuB,OAAOvB,MACpB6F,EAAK7F,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,sBAClBC,KAAkBJ,GAAUlD,UAAY2F,EAAK3F,UAAU6F,SACvDtC,SACIuC,OAAc,WAAYH,EAAKI,wBAC/BrC,MAAc,WAAYrC,OAAOvB,MAAM6C,cAOzD+C,yBAA0B,SAASM,GACjC,GAAIL,GAAOhF,IACXA,MAAKX,UAAY,GAAIvB,GAAkBwH,gBACvCtF,KAAKX,UAAUkG,OACbzB,QAAS,WACPuB,EAASL,IAEXX,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBASzBW,qBAAuB,WACrBpF,KAAKb,MAAMqG,cAAc,SACzB,IAAIC,GAAmBzF,KAAKb,MAAMoC,EAAE,4BAA4BoD,MAC5DK,EAAOhF,IACX,IAAyB,KAArByF,EACFlE,EAAEmE,KAAMhF,OAAOiF,KAAO,iBAAkBjB,KAAMe,IAC3CG,KAAK,SAAUC,GACdb,EAAKjF,QAAQ+F,qBAAuBD,EAAYnG,GAChDsF,EAAKe,uBAAuBF,EAAYnG,GAAImG,EAAYnB,QAEzDsB,KAAK,WACJnI,EAAWwG,MAAM,uBAElB4B,OAAO,WACNjB,EAAK7F,MAAM+G,aAAa,gBAEvB,CACL,GAAIC,GAAa5E,EAAE,oDAAoDoD,KACvE3E,MAAKD,QAAQ+F,qBAAuBK,CACpC,IAAIC,GAAe7E,EAAE,oDAAoD5B,MACzEK,MAAK+F,uBAAuBI,EAAYC,GACxCpG,KAAKb,MAAM+G,aAAa,YAI5BH,uBAAwB,SAAUI,EAAYC,GAC5C,GAAIC,MACAC,IACJ/E,GAAE,iBAAiBC,KAAK,YAAY+E,KAAK,WACkB,KAAnDhF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eAC7GN,EAAYO,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OACA,KAAnDlF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eACpHL,EAAWM,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAKjE,KAAK,GADDI,MACKC,EAAIT,EAAY3C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC9C,GAAIC,GAAqBV,EAAYS,GACjCE,EAAc,GAAIlJ,GAAkBmJ,WACxCD,GAAYrD,IAAMqD,EAAYpD,QAAUuC,EAAa,YACrDa,EAAYE,QAAUH,EACtBC,EAAYG,OAAS,UACrBN,EAAmBD,KAAKI,GAK5B,IAAK,GAAIF,GAAIR,EAAW5C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC7C,GAAIM,GAAoBd,EAAWQ,GAC/BE,EAAc,GAAIlJ,GAAkBmJ,WACxCD,GAAYrD,IAAMqD,EAAYpD,QAAUuC,EAAa,YACrDa,EAAYE,QAAUE,EACtBJ,EAAYG,OAAS,iBACrBN,EAAmBD,KAAKI,GAG5BhH,KAAKqH,sBAAwB3D,OAAQmD,EAAmBnD,OAAQ4D,OAAQ,aAAclB,aAAcA,IAGpGmB,OAAOC,QAAS9G,OAAOiF,KAAO,6BAA+BQ,GAC7DnG,KAAKyH,8BAA+BZ,EAAoBT,IAM1DsB,eAAgB,WACZ1H,KAAK2H,UAAY3H,KAAK4H,aACtBrG,EAAG,wBAAyBsG,MAAOC,KAAKC,MAAO/H,KAAK2H,UAAa,KACjEK,mBAAqBF,KAAKC,MAAO/H,KAAK2H,UAAa,aACnDpG,EAAG,oBAAqB5B,KAAMqI,qBAQlCC,SAAW,SAAUC,EAAWC,GAC9B,GAAI9B,MACAC,IACA/E,GAAG,iBAAkBC,KAAM,YAAa+E,KAAM,WACc,KAAnDhF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eAC9GN,EAAYO,KAAMrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OACA,KAAnDlF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAAgBzG,KAAKwG,cAAcA,cAAcE,UAAUC,SAAS,eACrHL,EAAWM,KAAMrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAGtE,IAAI9C,GAAMjD,OAAOiF,KAAO,mCAAqCwC,EACzD1B,GAAS2B,OAAW/B,EAAaC,WAAeA,EACpDtG,MAAKqI,gBAAiB1E,EAAK8C,EAAM,QAUnC4B,gBAAiB,SAAU1E,EAAK8C,EAAM6B,GACpC,GAAK3E,GAAO8C,EAAM,CAEhBA,EAAuB,gBAATA,GAAoBA,EAAOlF,EAAEgH,MAAO9B,EAElD,IAAI+B,GAAS,EACbjH,GAAEgF,KAAME,EAAKjD,MAAO,KAAO,WACnB,GAAIiF,GAAOzI,KAAKwD,MAAO,IACvBgF,IAAQ,8BAA+BC,EAAK,GAAI,YAAaA,EAAK,GAAI,SAG9ElH,EAAE,iBAAkBoC,EAAK,cAAe2E,GAAQ,QAAS,KAAKE,EAAO,WACpEE,SAAU,QAASC,SAASC,SAC7B/K,EAAWiH,KAAM,sCAEjBjH,GAAWwG,MAAO,uBAItBwE,yBAA0B,WACxB7I,KAAK+E,yBAA0B,SAAUzC,GACvCA,EAAKnD,MAAQuB,OAAOvB,KACpB,IAAI2J,GAAiBxG,EAAKyG,8BACtBC,EAAc1G,EAAKvC,QAAQkJ,UAAU3G,EAAKvC,QAAQkJ,UAAUvF,OAAS,GAAG,EAC5EpB,GAAKnD,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,+CAAiDsG,EACnErG,KAAkBmG,GAAgBzJ,UAAWiD,EAAKjD,UAAU6F,SAC5DtC,SACIsG,IAAc,WAAY5G,EAAK6G,6BAC/BpG,MAAc,WAAYrC,OAAOvB,MAAM6C,SAE3CoH,iBAAkB,WAChB1I,OAAOuD,UAAUoF,eAAeC,UAKlChH,EAAKjD,UAAU6F,OAAOxB,OAAS,GACjCpB,EAAKiH,+BAA+BjH,EAAKjD,UAAU6F,OAAO,GAAGxF,IAC7D6B,EAAG,qBAAsBiI,OAAO,SAASrH,GACvCG,EAAKiH,+BAA+BpH,EAAMsH,OAAOC,UAGnD7L,EAAWwG,MAAO,wBASxBsF,yBAA0B,WACxB,GAAI3E,GAAOhF,IACXA,MAAKb,MAAQuB,OAAOvB,KACpB,IAAI2J,GAAiB9I,KAAK4J,yBAC1B5J,MAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,+BAClBC,KAAkBmG,MAClBlG,SACIuC,OAAc,WAAaH,EAAK6E,uBAAuB7E,IACvDjC,MAAc,WAAarC,OAAOvB,MAAM6C,SAE5CoH,iBAAkB,WAEhB1I,OAAOuD,UAAUoF,eAAeS,SAAU,WAAa9E,EAAKtF,IAAMqK,SAAS,OAGjF/J,KAAKgK,qBAOP9J,mBAAoB,WAClB,GAAI8E,GAAOhF,IACXpC,GAAUqM,KACNtG,IAAYjD,OAAOiF,KAAO,qCAC1B7B,QAAY,SAAUoG,GACNlF,EAAKxF,kBACL,KAAK2K,MAAOD,GACRlF,EAAKxF,gBAAgBoH,MACjBlH,GAAkBwK,EAAUC,KAAKC,UACjCzK,KAAkBuK,EAAUC,KAAKC,UACjCxK,YAAkBsK,EAAUC,KAAKvK,YACjCyK,gBAAkBH,EAAUC,KAAKE,iBAGzCrF,GAAKxF,gBAAgB8K,KAAK,SAASC,EAAGC,GAClC,MAAOD,GAAE7K,GAAK8K,EAAE9K,GAAK,EAAI6K,EAAE7K,GAAK8K,EAAE9K,GAAK,GAAK,IAEhDsF,EAAKxF,gBAAgBiL,QAAQzF,EAAKvF,OAElDiL,OAAW,IAEf9M,EAAUqM,KACNtG,IAAajD,OAAOiF,KAAO,cAC3B7B,QAAU,SAAU6G,GACR3F,EAAKnF,eACL,KAAMsK,MAAOQ,GACT3F,EAAKnF,aAAa+G,MACdlH,GAAUiL,EAAQR,KAAK,GACvBxK,KAAUgL,EAAQR,KAAK,IAG/BnF,GAAKnF,aAAayK,KAAK,SAASC,EAAGC,GAC/B,MAAOD,GAAE7K,GAAK8K,EAAE9K,GAAK,EAAI6K,EAAE7K,GAAK8K,EAAE9K,GAAK,GAAK,KAG5DgL,OAAU,KAIhBV,kBAAmB,WAKjB,GAAIhF,GAAOhF,IACXA,MAAKV,cAAgB,GAAIvB,GAAWG,MAChC0M,IAAK,wBACLnE,KAAMzB,EAAKnF,aACXgL,UAAWnK,OAAOvB,MAAM+B,IAAIM,KAAM,0BAClCkI,MAAO,MAEX1J,KAAKT,iBAAmB,GAAIxB,GAAWG,MACrC0M,IAAK,2BACLnE,KAAMzB,EAAKxF,gBACXqL,UAAWnK,OAAOvB,MAAM+B,IAAIM,KAAM,6BAClCkI,MAAO,UAQXoB,iCAAkC,SAAU/K,GAC1C,GAAIiF,GAAOhF,KACP8I,EAAiB9I,KAAK+K,sBAC1B/K,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACTU,gBAAkB,EAClBC,MAAkB,iCAClBC,KAAkBmG,MAClBlG,SACIuC,OAAc,WACZH,EAAKgG,qBAAsBhG,EAAMjF,IAEnCgD,MAAc,WACZrC,OAAOvB,MAAM6C,SAGnBoH,iBAAkB,WAEhB1I,OAAOuD,UAAUoF,eAAeS,SAAS,WAAa9E,EAAKtF,IAAKqK,SAAS,OAI7ExI,EAAE,yBAAyB0J,KAAK,QAAS,WACvC1J,EAAE,mBAAmBnC,OAAO,eAE9BmC,EAAE,0BAA0B0J,KAAK,QAAS,WACxC1J,EAAE,mBAAmBnC,OAAO,iBAG9BY,KAAKgK,oBACLjK,EAAQb,wBAA0B,UAClCc,KAAKkL,aAAcnL,GAEnBwB,EAAG,qBAAsBiI,OAAQ,SAAUrH,GACb,2BAAtBA,EAAMsH,OAAOC,OACf3J,EAAQb,wBAA0B,UAClC8F,EAAKkG,aAAcnL,GACnBwB,EAAE,2BAA2BS,OAC7BT,EAAE,8BAA8BS,OAChCT,EAAE,sBAAsBS,OACxBT,EAAE,yBAAyBQ,QACK,yBAAtBI,EAAMsH,OAAOC,QACvBnI,EAAE,yBAAyBS,OAC3BT,EAAE,2BAA2BQ,OAC7BR,EAAE,sBAAsBQ,OACxBR,EAAE,8BAA8BQ,OAChChC,EAAQb,wBAA0B,QAClC8F,EAAKkG,aAAcnL,OAY3BmL,aAAc,SAAUnL,GAEtBC,KAAKD,QAAUE,EAAE9B,OAAQ6B,KAAKD,QAASA,EACvC,IAAI0J,GAAS1J,EAAQoH,QAAU,UAC3BjI,EAA0Bc,KAAKD,QAAQb,uBAC3Cc,MAAKZ,OAAS,GAAItB,GAAkBqN,OACpCnL,KAAKZ,OAAOuE,IAAM3D,KAAKZ,OAAOwE,QACV,WAAa6F,EACb,0BACcvK,EAClCc,KAAKZ,OAAOmG,OACVzB,QAAS,SAASQ,GAEhB5G,OAAQ,SAAU,WAAY,MAAO6J,UAErC6D,SAAU,sBAAwB,WAChC7J,EAAE,mBAAmBnC,OAAO,WAC5BmC,EAAE,mBAAmBnC,QACnBiM,MACE5E,KAAQnC,GAEVgH,SAAY,QAAS,YACrBC,OACEpI,QACEqI,KAAQ,iBAEVC,MACED,KAAQ,gBAGZE,UACEC,aAAa,QAKrBtH,MAAO,SAASC,EAAOC,GACgB,mBAA1BA,GAASC,aACqB,SAAnCD,EAASC,aAAaoH,SACxB/N,EAAWgO,QAAQtH,EAASC,aAAaC,SAEzC5G,EAAWwG,MAAME,EAASC,aAAaC,SAGzC5G,EAAWwG,MAAM,yBAWzBwF,uBAAwB,WACtB,GAAIiC,GAAgB9L,KAAKb,MAAM+B,IAAIM,KAAK,sBAAsBuK,GAAG,YAC7DC,EAAYhM,KAAKb,MAAM+B,IAAIM,KAAK,kBAAkBuK,GAAG,YACrDE,EAAYjM,KAAKT,iBAAiBmK,QAClCwC,EAAQlM,KAAKV,cAAcoK,QAC3ByC,EAAQ5K,EAAE,yBAAyBoD,MACnCyH,IACJ,IAAKD,EAEE,CACLnM,KAAKb,MAAMqG,cAAc,UACzB2G,EAAQA,EAAM3I,MAAM,KACpB,KAAK,GAAIsD,GAAIqF,EAAMzI,OAAS,EAAGoD,GAAK,EAAGA,IACrCuF,QAAUF,EAAMrF,GAAGwF,OACE,IAAjBD,QAAQ3I,QACV0I,EAAYxF,KAAKyF,QAGrBrM,MAAKqH,sBAAwB3D,OAAQ0I,EAAY1I,OAAQ4D,OAAQ,oBACjEtH,KAAKuM,2BAA6BJ,MAAOC,EACPN,cAAeA,EACfE,UAAWA,EACX7E,OAAQ,aACR8E,UAAWA,EACXC,MAAOA,QAhBzCrO,GAAWiH,KAAK,iDAyBpBuC,qBAAsB,SAAUtH,GAC9B,GAAIwC,EACJ,QAAQxC,EAAQuH,QACd,IAAK,kBACH/E,EAAWvC,KAAKwM,oCAChBxM,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,GAAYyG,YAAchJ,KAAKD,QAAQiJ,cAClF,MACF,KAAK,oBACHzG,EAAWvC,KAAKyM,mCAChBzM,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,IAC3C,MACF,KAAK,aACHA,EAAWvC,KAAK0M,uCAChB1M,KAAKb,MAAM+B,IAAIM,KAAM,eAAgBL,KAAMoB,GAAY6D,aAAerG,EAAQqG,eAC9E,MACF,SACE1F,OAAOiM,KAAKtI,MAAO,0BAA2B,YAMlDrE,KAAK2H,SAAW,EAChB3H,KAAK4H,aAAe,IAAM7H,EAAQ2D,OAClC1D,KAAKD,QAAQhB,mBAAmBC,aAAee,EAAQ2D,OACvD1D,KAAKD,QAAQhB,mBAAmBE,cAAgB,GAWlD+L,qBAAsB,SAAWhG,EAAMjF,GACrC,GAAI6M,GAAYrL,EAAG,mBAAoBnC,SAASyN,cAAc,EAE9DC,gBAAiB7M,EAAE8M,OAAOH,EAAW,SAASI,GAAO,MAA8B,IAAvBA,EAAKC,MAAMC,UACvE,IAAIpB,GAAgB9L,KAAKb,MAAM+B,IAAIM,KAAM,sBAAuBuK,GAAI,YAChEC,EAAYhM,KAAKb,MAAM+B,IAAIM,KAAM,kBAAmBuK,GAAI,YACxDE,EAAYjM,KAAKT,iBAAiBmK,QAClCwC,EAAQlM,KAAKV,cAAcoK,QAC3ByD,EAAsBnN,KAAKb,MAAM+B,IAAIM,KAAM,cAAeuK,GAAI,YAC9DqB,EAAiBN,eAAe,GAAG9I,KACnCmI,IACJ,IAAKW,eAAepJ,OAAS,EAC3B7F,EAAWiH,KAAM,uCACZ,CACL9E,KAAKb,MAAMqG,cAAe,SAC1B,KAAM,GAAIsB,GAAIgG,eAAepJ,OAAS,EAAGoD,GAAK,EAAGA,IACFuG,SAAxCP,eAAehG,GAAGwG,QAAQrE,WAC7BkD,EAAMvF,KAAMkG,eAAehG,GAAGwG,QAAQrE,UAI1C,IADAjJ,KAAKqH,sBAAwB3D,OAAQyI,EAAMzI,OAAQ4D,OAAQ,oBACnC,WAAnB8F,EAA6B,CAChC,GAAIG,GAAcxN,EAAQoH,OAAS,SACnCnH,MAAKuM,2BAA6BJ,MAAOA,EACPL,cAAeA,EACfE,UAAWA,EACX7E,OAAQoG,EACRtB,UAAWA,EACXC,MAAOA,EACPiB,oBAAqBA,QAClD,IAAwB,SAAnBC,EAA2B,CACrC,GAAIG,GAAcxN,EAAQoH,OAAS,OACnCnH,MAAKwN,gCAAkCrB,MAAQA,EACRF,UAAWA,EACXC,MAAOA,EACP/E,OAAQoG,EACRJ,oBAAqBA,OAKlE5D,+BAAgC,SAASpD,GACvC,GAAIsH,GAAmB,GAAI3P,GAAkB4P,iBAAiBhO,GAAGyG,IAC7D7D,EAAOtC,IACXyN,GAAiBlI,OACfzB,QAAS,SAAS2J,GAChB,GAAIE,GAA4BrL,EAAKsL,yBACrCtL,GAAKjD,UAAU4K,IAAI9D,GAAYpC,KAAK8J,SAAaJ,IACjDnL,EAAKnD,MAAM+B,IAAIM,KAAK,6BAA6BL,KAAKwM,GAA2BF,iBAAkBA,EAAiBvI,OAAO4I,cAE7HzJ,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,yBASzB0E,0BAA4B,WAC1B,GAAI4E,GAAe/N,KAAKb,MAAM+B,IAAIM,KAAM,6BAA8BA,KAAM,YACxEwM,KACAC,KACAC,IACJ,IAAKH,EAAarK,OAAS,EACzB7F,EAAWiH,KAAM,4CACZ,CACL9E,KAAKb,MAAMqG,cAAe,OAC1BuI,EAAaxH,KAAK,WAChB,GAAI4H,GAAM5M,EAAGvB,KAAKwG,eAAgBC,KAAM,KACxC,IAAK0H,EAAM,CACT,GAAIC,GAAY7M,EAAGvB,KAAKwG,eAAgBC,KAAM,OAC9CuH,GAAiBpH,KAAMuH,GACvBF,EAAmBrH,KAAMwH,KAG7B,KAAM,GAAItH,GAAIkH,EAAiBtK,OAAS,EAAGoD,GAAK,EAAGA,IAAM,CACvDuH,gBAAkBL,EAAiBlH,EACnC,IAAIwH,GAAc,GAAIxQ,GAAkByQ,IACxCD,GAAY3K,IAAMjD,OAAOiF,KAAO,eAAiB3F,KAAKD,QAAQL,GAAK,YAEjE4O,EAAYvK,IADgB,eAA1BkK,EAAmBnH,IACJ0H,aAAgBH,kBAEhBI,YAAeJ,kBAElCH,EAAatH,KAAK0H,GAEpBtO,KAAKqH,sBAAwB3D,OAAQwK,EAAaxK,OAAQ4D,OAAQ,oBAClEtH,KAAK0O,oBAAqBR,KAU9BzG,8BAA+B,SAAUkH,EAAkBvI,GACzD,GAAI9D,GAAOtC,KACP4O,EAAcD,EAAiBE,KACnC,IAA2B,mBAAfD,GASV,MARuD,KAAlD5O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,6EAA8E,IAAMgL,QAAS,WAAaC,OAAOC,SAAStO,OAAOiF,QAC3I3F,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,kEACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,gGAAiG,IAAMiD,QAAS,WAAaC,OAAOC,SAAStO,OAAOiF,QAE1KjF,OAAOvB,MAAM6C,QACN,CAET,IAAIiN,GAAU1N,EAAE2N,KAAMN,EAAY/K,MAAQqD,QAAS0H,EAAY1H,QAASC,OAAQyH,EAAYzH,SAE5F8H,GAAQrJ,KAAM,WACJtD,EAAKoF,iBACLpF,EAAKmF,8BAA+BkH,EAAkBvI,KAEvDJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAKmF,8BAA+BkH,EAAkBvI,MAUlEoH,+BAAgC,SAAUzN,GAExC,GAAIiF,GAAOhF,KACP4O,EAAc7O,EAAQoM,MAAM0C,KAChC,IAA4B,mBAAhBD,GAOV,MANuD,KAAlD5O,KAAKD,QAAQhB,mBAAmBE,eACnCpB,EAAWiG,QAAS,mDACpBpD,OAAOvB,MAAM6C,QAEbnE,EAAWwG,MAAO,sBAEb,CAET,IAAI4K,GAAU1N,EAAE2N,KAAM3N,EAAEmE,KAAMhF,OAAOiF,KAAO,4CAA8CX,EAAKtF,GAC5C,WAAaK,EAAQoH,OACrB,SAAWyH,EACX,cAAgB7O,EAAQkM,UACxB,UAAYlM,EAAQmM,MACpB,wBAA0BnM,EAAQoN,qBACrF8B,GAAQrJ,KAAM,WACJZ,EAAK0C,iBACL1C,EAAKwI,+BAAgCzN,KAEtCiG,KAAM,WACLhB,EAAKjF,QAAQhB,mBAAmBE,eAAiB,EACjD+F,EAAK0C,iBACL1C,EAAKwI,+BAAgCzN,MAcjDwM,0BAA2B,SAAUxM,GAEnC,GAAIiF,GAAOhF,KACP4O,EAAc7O,EAAQoM,MAAM0C,KAChC,IAA0B,mBAAfD,GAQT,MAPsD,KAAlD5O,KAAKD,QAAQhB,mBAAmBE,eAClCpB,EAAWiG,QAAQ,yEACnBpD,OAAOvB,MAAM6C,QAGbnE,EAAWwG,MAAM,sBAEZ,CAET,IAAI4K,GAAU1N,EAAE2N,KAAM3N,EAAEmE,KAAMhF,OAAOiF,KAAO,4CAA8CX,EAAKtF,GACzC,WAAaK,EAAQoH,OACrB,SAAWyH,EACX,kBAAoB7O,EAAQ+L,cAC5B,cAAgB/L,EAAQiM,UACxB,cAAgBjM,EAAQkM,UACxB,UAAYlM,EAAQmM,MACpB,wBAA0BnM,EAAQoN,qBACxF8B,GAAQrJ,KAAK,WACHZ,EAAK0C,iBACL1C,EAAKuH,0BAA2BxM,KAEjCiG,KAAK,WACJhB,EAAKjF,QAAQhB,mBAAmBE,eAAiB,EACjD+F,EAAK0C,iBACL1C,EAAKuH,0BAA2BxM,MAS5C2O,oBAAqB,SAAUS,GAC7B,GAAI7M,GAAOtC,IACXA,MAAKoP,WAAa,GAAItR,GAAkBuR,MACxC,IAAIT,GAAcO,EAASN,KAC3B,IAA2B,mBAAfD,GASV,MARuD,KAAlD5O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,sDACV9D,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,gEACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,yDAEtBnL,OAAOvB,MAAM6C,OACNhC,KAAKoP,UAEd,IAAIH,GAAU1N,EAAE2N,KAAMN,EAAY/K,MAAQ4K,YAAaG,EAAY3E,IAAK,iBAExEgF,GAAQrJ,KAAM,SAAUtB,GACd5D,OAAOuD,UAAUC,eAAeC,WAAWC,IAAKE,GAChDhC,EAAKoF,iBACLpF,EAAKoM,oBAAqBS,KAE3BnJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAKoM,oBAAqBS,MAStCG,uBAAwB,SAAUC,GAClC,GAAIjN,GAAOtC,IACXA,MAAKwP,cAAgB,GAAI1R,GAAkBuR,MAC3C,IAAIT,GAAcW,EAAgBV,KAClC,IAA4B,mBAAhBD,GASV,MARuD,KAAlD5O,KAAKD,QAAQhB,mBAAmBE,cACnCpB,EAAWiG,QAAS,gCACV9D,KAAKD,QAAQhB,mBAAmBE,gBAAkBe,KAAKD,QAAQhB,mBAAmBC,aAC5FnB,EAAWwG,MAAO,mGACRrE,KAAKD,QAAQhB,mBAAmBE,cAAgBe,KAAKD,QAAQhB,mBAAmBC,cAC1FnB,EAAWgO,QAAS,6FAEtBnL,OAAOvB,MAAM6C,OACNhC,KAAKwP,aAEd,IAAIP,GAAU1N,EAAE2N,KAAMN,EAAYa,UAElCR,GAAQrJ,KAAM,SAAU8J,GAId,GAHAhP,OAAOuD,UAAUC,eAAeC,WAAWyE,OAAQgG,EAAYlP,IAC/D4C,EAAKoF,iBAEAhH,OAAOuD,UAAUC,eAAenE,QAAQ4P,gBAAiB,CAC5D,GAAIC,GAAe,IACD,YAAdF,EAAK1L,MAA0C,kBAArB0L,EAAKG,YACjCD,EAAe,GAAI9R,GAAkBsF,cAAesM,GAC7B,SAAdA,EAAK1L,MAAwC,mBAArB0L,EAAKG,YACtCD,EAAe,GAAI9R,GAAkByQ,KAAMmB,IAE3ChP,OAAOiM,KAAKtI,MAAM,mCAAoC,YACtD3D,OAAOiM,KAAKtI,MAAMqL,EAAK1L,MAAQ0L,EAAKG,YAAa,aAEnDnP,OAAOuD,UAAUC,eAAeC,WAAWC,IAAKwL,GAElDtN,EAAKgN,uBAAwBC,KAE9BvJ,KAAM,WACL1D,EAAKvC,QAAQhB,mBAAmBE,eAAiB,EACjDqD,EAAKoF,iBACLpF,EAAKgN,uBAAwBC,MAOvCO,oBAAqB,SAAS3N,GAE1BzB,OAAOuD,UAAUC,eAAe6L,YAD9B5N,EAAMsH,OAAOuG,SAC8BL,iBAAiB,IAEjBA,iBAAiB,KAOlEM,oBAAqB,WACnB,GAAIpL,GAAgBtD,EAAE,iBAAiBC,KAAK,WAC5C,IAA4B,IAAzBqD,EAAcnB,OACb7F,EAAWiH,KAAK,uDACb,CACL,GAAIvC,GAAWvC,KAAKyM,kCACpBzM,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,0BAClBC,KAAkBJ,MAClBK,SACIG,MAAc,WAAYrC,OAAOvB,MAAM6C,WAI/ChC,KAAKD,QAAQhB,mBAAmBC,aAAe,EAC/CgB,KAAKD,QAAQhB,mBAAmBE,cAAgB,CAEhD,IAAIoH,MACAC,IACJzB,GAAc0B,KAAK,WACwC8G,SAAnD9L,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,QAC4B,KAAjElF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,MAAMyJ,UAAU,EAAE,GAC7D5J,EAAWM,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,OAEzDJ,EAAYO,KAAKrF,EAAEvB,KAAKwG,cAAcA,eAAeC,KAAK,SAKpE,IAAI0J,GAAc9J,EAAY3C,OAAS4C,EAAW5C,MAClD1D,MAAK4H,aAAe,IAAMuI,EAC1BnQ,KAAK2H,SAAW,CAIhB,KAAK,GADD4H,MACKzI,EAAIT,EAAY3C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC9C,GAAIsJ,GAAU,GAAItS,GAAkByQ,MAAM7O,GAAG2G,EAAYS,IACzDyI,GAAgB3I,KAAKwJ,GAEzB,IAAK,GAAItJ,GAAIR,EAAW5C,OAAS,EAAGoD,GAAK,EAAGA,IAAK,CAC7C,GAAI3D,GAAS,GAAIrF,GAAkBsF,eAAe1D,GAAG4G,EAAWQ,IAChEyI,GAAgB3I,KAAKzD,GAGzBnD,KAAKD,QAAQhB,mBAAmBC,aAAemR,EAAYzM,OAE3D1D,KAAKsP,uBAAuBC,KAKhCc,YAAa,WACX,GAAIC,GAAU,KACVtL,EAAOhF,IAC8B,QAArCU,OAAOuD,UAAUsM,iBACnBD,EAAU5P,OAAOuD,UAAUsM,gBAAgBpM,WAAW8F,IAAIjK,KAAKD,QAAQyQ,mBACvExQ,KAAKyQ,iBAAiBH,KAEtBA,EAAU,GAAIxS,GAAkB4S,SAAShR,GAAIM,KAAKD,QAAQyQ,oBAC1DF,EAAQ/K,OACNzB,QAAS,WACPkB,EAAKyL,iBAAiBH,IAExBjM,MAAO,SAASC,EAAOC,GAEnB1G,EAAWwG,MADwB,mBAA1BE,GAASC,aACDD,EAASC,aAAaC,QAEtB,0BAO3BgM,iBAAkB,SAASH,GACzB,GAAItL,GAAOhF,KACPuC,EAAWvC,KAAK2Q,wBACpB3Q,MAAKb,MAAQuB,OAAOvB,MACpBa,KAAKb,MAAM4C,MACPU,gBAAkB,EAClBC,MAAkB,mBAClBC,KAAkBJ,GAAU+N,QAASA,EAASvQ,QAASiF,EAAKjF,UAC5D6C,SACIG,MAAc,WAAYrC,OAAOvB,MAAM6C,YAKjD4O,gBAAiB,SAAS7Q,GACxB,OAAOA,EAAQoH,QACb,IAAK,UACHnH,KAAK6I,0BACL,MACF,KAAK,YACH7I,KAAK8K,kCAAoC3D,OAAQ,aACjD,MACF,KAAK,OACHnH,KAAK2J,0BACL,MACF,KAAK,UACH3J,KAAK8K,kCAAoC3D,OAAQ,WACjD,MACF,SACEzG,OAAOuD,UAAUoF,eAAeC,OAChCzL,EAAWwG,MAAM,4BAQvBwM,mBAAoB,WAClB,GAAIC,GAAmBC,OAAQ,8CAA+CrQ,OAAOuD,UAAU+M,YAAY/G,IAAK,oBACrF,OAApB6G,GAAgCA,GAAoBpP,SAAUoP,KACjEpQ,OAAOuD,UAAU+M,YAAYjN,KAAO+M,iBAAoBpP,SAAUoP,KAClEpQ,OAAOuD,UAAUC,eAAe/D,QAAUT,GAAIM,KAAKD,QAAQL,GAAI+B,UAAW,MAIhFpB,gBAAiB,WACf,MAAOJ,GAAEsC,UAET,wCAEE,6BACE,yCACE,+CAEA,2DACA,sGACE,UACE,mFACF,WACF,SACA,qNACE,qEACF,YACA,0CACA,kEACE,oIACE,8FACF,YACA,yCACE,yEACA,6DACE,gFACF,UACA,qDACE,4BACA,+CACA,wDACE,mFACF,UACA,qDACE,kEACF,UACF,UACF,QACF,SACA,iBACE,0LACE,mEACF,OACF,UACA,iOACE,mCACA,mBACF,YACA,0FACE,kIACE,4EACF,YACA,yCACE,kEACA,kEACA,+DACF,QACF,SACE,+NACA,oDACA,8LACE,0CACA,gBACF,YACA,qGACE,8FACE,gDACE,8CACA,aACF,YACF,OACF,UACF,SACF,UAEF,kCACA,SAEA,wDAEF,UACE0O,KAAK,MAGTN,uBAAwB,WACtB,MAAO1Q,GAAEsC,UACP,QACE,6CACE,UACE,uCACA,YACF,WACA,UACE,OACE,gBACA,sCACF,QACA,gDACE,OACE,uBACA,6CACF,QACF,UACA,6CACE,OACE,oBACA,0CACF,QACF,UACA,uDACE,OACE,mBACA,2GACF,QACF,UACA,OACE,cACA,oCACF,QACF,WACF,WACA,6CACE,UACE,sCACA,YACF,WACA,UACE,OACE,gBACA,sCACF,QACA,gDACE,OACE,uBACA,6CACF,QACF,UACA,OACE,cACA,6BACF,QACA,WACJ,WACJ,UACE0O,KAAK,MAGTzO,yBAA0B,WACxB,MAAOvC,GAAEsC,UACT,8BACE,SACE,wEACA,4EACF,UACF,UACE0O,KAAK,MAIThM,0BAA4B,WAC1B,MAAOhF,GAAEsC,UACT,QACE,mCACE,mBACA,iHACE,8CACE,mGACF,YACF,YACF,SACA,mCACE,kBACA,4GACA,WACF,SACF,UACE0O,KAAK,MAGTvE,qCAAuC,WACrC,MAAOzM,GAAEsC,UACT,4BACE,2EACF,SACA,yBACE,gJACE,mDACF,SACF,UACE0O,KAAK,MAGTzE,kCAAmC,WACjC,MAAOvM,GAAEsC,UACT,4BACE,iFACF,SACA,yBACE,gJACE,mDACF,SACF,UACE0O,KAAK,MAGTxE,iCAAkC,WAChC,MAAOxM,GAAEsC,UACT,4BACA,SACA,yBACE,gJACE,mDACF,SACF,UACE0O,KAAK,MAGTlG,qBAAsB,WACpB,MAAO9K,GAAEsC,UACT,gCACE,0JACA,wLACA,mCACE,oFACE,yGACF,WACA,sFACA,uFACA,WACF,SACA,mCACE,kFACE,yFACA,+BACF,WACA,0EACE,mEACA,gCACF,WACF,SACA,qGACE,aACF,YACA,qGACE,cACF,YACA,SAEA,4BACA,SACA,SACA,kFACA,QACE,gFACA,4EACF,SACA,QACG,4CACG,oCACA,0FACH,WACH,SACF,UACE0O,KAAK,MAGTrH,wBAAyB,WACvB,MAAO3J,GAAEsC,UACT,gCACE,+JACA,sCACE,4DACE,yFACA,+BACF,WACA,oDACE,mEACA,gCACF,WACF,SACA,uKACA,SACA,kFACA,QACE,gFACA,4EACF,SACF,UACE0O,KAAK;;EAGTlI,4BAA6B,WAC3B,MAAO9I,GAAEsC,UACT,6BACE,QACE,oBACA,8EACE,8CACE,mGACF,YACF,YACF,SACA,QACA,sCACA,SACF,UACE0O,KAAK,MAGTrD,wBAAyB,WACvB,MAAO3N,GAAEsC,UACT,kDACA,OACE,0DACE,oDACE,yDACI,kEACA,0CACE,+GACE,sJACF,QACD,iBACE,6FACG,2GACE,oKACF,UACF,QACF,UACN,iGACI,+GACE,iIACF,QACJ,UACF,UACF,YACF,SACE0O,KAAK,MAGT3P,kBAAmB,WACjB,MAAOrB,GAAEsC,UACT,wCACE,uCACE,gDACE,iGACA,wHACF,iBACE,iGACA,2GACF,UACF,iBACE,kHACA,wHACF,UACA,sBACE,0FACF,QACA,4CACE,2GACA,0HACF,iBACE,yHACA,2IACF,UACF,QACA,SACE,sBACA,8HACE,qBACF,OACA,0CACF,WACE0O,KAAK,OAKX,QACIjT,kBAAmBA"} \ No newline at end of file diff --git a/static/scripts/bundled/admin.bundled.js b/static/scripts/bundled/admin.bundled.js index 7d7deee2796..3e5ba4640bb 100644 --- a/static/scripts/bundled/admin.bundled.js +++ b/static/scripts/bundled/admin.bundled.js @@ -1,4 +1,4 @@ -webpackJsonp([4],[function(t,e,i){(function(t){var e=i(1),a=e,s=i(49).GalaxyApp,n=i(100),l=i(59),o=i(12),r=(i(5),i(26)),d=i(52),c=i(50);window.app=function(e,i){window.Galaxy=new s(e,i),Galaxy.debug("admin app");var h=d.extend({routes:{"(/)admin(/)users":"show_users","(/)admin(/)roles":"show_roles","(/)admin(/)groups":"show_groups","(/)admin(/)forms(/)(:form_id)":"show_forms"},authenticate:function(t,e){return Galaxy.user&&Galaxy.user.id&&Galaxy.user.get("is_admin")},show_users:function(){this.page.display(new o({url_base:Galaxy.root+"admin/users_list",url_data:Galaxy.params,dict_format:!0}))},show_roles:function(){this.page.display(new o({url_base:Galaxy.root+"admin/roles_list",url_data:Galaxy.params,dict_format:!0}))},show_groups:function(){this.page.display(new o({url_base:Galaxy.root+"admin/groups_list",url_data:Galaxy.params,dict_format:!0}))},show_forms:function(t){var e={reset_user_password:{title:"Reset passwords",url:"admin/reset_user_password?id="+r.get("id"),icon:"fa-user",submit_title:"Save new password",redirect:"admin/users"},manage_roles_and_groups_for_user:{url:"admin/manage_roles_and_groups_for_user?id="+r.get("id"),icon:"fa-users",redirect:"admin/users"},manage_users_and_groups_for_role:{url:"admin/manage_users_and_groups_for_role?id="+r.get("id"),redirect:"admin/roles"},manage_users_and_roles_for_group:{url:"admin/manage_users_and_roles_for_group?id="+r.get("id"),redirect:"admin/groups"},create_role:{url:"admin/create_role?id="+r.get("id"),redirect:"admin/roles"},create_group:{url:"admin/create_group?id="+r.get("id"),redirect:"admin/groups"},rename_role:{url:"admin/rename_role?id="+r.get("id"),redirect:"admin/roles"},rename_group:{url:"admin/rename_group?id="+r.get("id"),redirect:"admin/groups"}};this.page.display(new l.View(e[t]))}});a(function(){t.extend(e.config,{active_view:"admin"}),Galaxy.page=new c.View(t.extend(e,{Left:n,Router:h}))})}}).call(e,i(3))},,,,,function(t,e,i){var a,s;(function(n,l,o){a=[i(4),i(15),i(40),i(14),i(36),i(10),i(8)],s=function(t,e,i,a,s,r,d){var c=n.View.extend({tagName:"label",initialize:function(t){this.model=t&&t.model||new n.Model(t),this.tagName=t.tagName||this.tagName,this.setElement(l("<"+this.tagName+"/>")),this.listenTo(this.model,"change",this.render,this),this.render()},title:function(t){this.model.set("title",t)},value:function(){return this.model.get("title")},render:function(){return this.$el.removeClass().addClass("ui-label").addClass(this.model.get("cls")).html(this.model.get("title")),this}}),h=n.View.extend({initialize:function(t){this.model=t&&t.model||new n.Model({message:null,status:"info",cls:"",persistent:!1,fade:!0}).set(t),this.listenTo(this.model,"change",this.render,this),this.render()},update:function(t){this.model.set(t)},render:function(){this.$el.removeClass().addClass("ui-message").addClass(this.model.get("cls"));var t=this.model.get("status");if(this.model.get("large")?this.$el.addClass(("success"==t&&"done"||"danger"==t&&"error"||t)+"messagelarge"):this.$el.addClass("alert").addClass("alert-"+t),this.model.get("message")){if(this.$el.html(this.messageForDisplay()),this.$el[this.model.get("fade")?"fadeIn":"show"](),this.timeout&&window.clearTimeout(this.timeout),!this.model.get("persistent")){var e=this;this.timeout=window.setTimeout(function(){e.model.set("message","")},3e3)}}else this.$el.fadeOut();return this},messageForDisplay:function(){return o.escape(this.model.get("message"))}}),u=h.extend({messageForDisplay:function(){return this.model.get("message")}}),p=n.View.extend({initialize:function(t){this.model=t&&t.model||new n.Model({type:"text",placeholder:"",disabled:!1,readonly:!1,visible:!0,cls:"",area:!1,color:null,style:null}).set(t),this.tagName=this.model.get("area")?"textarea":"input",this.setElement(l("<"+this.tagName+"/>")),this.listenTo(this.model,"change",this.render,this),this.render()},events:{input:"_onchange"},value:function(t){return void 0!==t&&this.model.set("value","string"==typeof t?t:""),this.model.get("value")},render:function(){var t=this;this.$el.removeClass().addClass("ui-"+this.tagName).addClass(this.model.get("cls")).addClass(this.model.get("style")).attr("id",this.model.id).attr("type",this.model.get("type")).attr("placeholder",this.model.get("placeholder")).css("color",this.model.get("color")||"").css("border-color",this.model.get("color")||"");var e=this.model.get("datalist");return l.isArray(e)&&e.length>0&&this.$el.autocomplete({source:function(e,i){i(t.model.get("datalist"))},change:function(){t._onchange()}}),this.model.get("value")!==this.$el.val()&&this.$el.val(this.model.get("value")),o.each(["readonly","disabled"],function(e){t.model.get(e)?t.$el.attr(e,!0):t.$el.removeAttr(e)}),this.$el[this.model.get("visible")?"show":"hide"](),this},_onchange:function(){this.value(this.$el.val()),this.model.get("onchange")&&this.model.get("onchange")(this.model.get("value"))}}),f=n.View.extend({initialize:function(t){this.model=t&&t.model||new n.Model(t),this.setElement(l("
").append(this.$info=l("
")).append(this.$hidden=l("
"))),this.listenTo(this.model,"change",this.render,this),this.render()},value:function(t){return void 0!==t&&this.model.set("value",t),this.model.get("value")},render:function(){return this.$el.attr("id",this.model.id),this.$hidden.val(this.model.get("value")),this.model.get("info")?this.$info.show().text(this.model.get("info")):this.$info.hide(),this}}),m=n.View.extend({initialize:function(t){var e=this;this.model=t&&t.model||new n.Model(t),this.setElement(l("
").append(this.$info=l("
")).append(this.$file=l("").attr("type","file").addClass("ui-margin-bottom")).append(this.$text=l("',"
","
"].join("")}});return{CitationView:n,CitationListView:s}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2))},function(e,t,i){var n,s;(function(a,o,r){n=[i(64),i(58),i(7),i(6)],s=function(e,t,i,n){"use strict";var s=e.FoldoutListItemView,l=e.ListItemView,d=s.extend({className:s.prototype.className+" dataset-collection",id:function(){return["dataset_collection",this.model.get("id")].join("-")},initialize:function(e){this.linkTarget=e.linkTarget||"_blank",this.hasUser=e.hasUser,s.prototype.initialize.call(this,e)},_setUpListeners:function(){s.prototype._setUpListeners.call(this),this.listenTo(this.model,"change",function(e,t){a.has(e.changed,"deleted")?this.render():a.has(e.changed,"element_count")&&this.$("> .title-bar .subtitle").replaceWith(this._renderSubtitle())})},_renderSubtitle:function(){return o(this.templates.subtitle(this.model.toJSON(),this))},_getFoldoutPanelOptions:function(){var e=s.prototype._getFoldoutPanelOptions.call(this);return a.extend(e,{linkTarget:this.linkTarget,hasUser:this.hasUser})},$selector:function(){return this.$("> .selector")},toString:function(){var e=this.model?this.model+"":"(no model)";return"DCListItemView("+e+")"}});d.prototype.templates=function(){var e=a.extend({},s.prototype.templates.warnings,{error:i.wrapTemplate(["<% if( model.error ){ %>",'
',n("There was an error getting the data for this collection"),": <%- model.error %>","
","<% } %>"]),purged:i.wrapTemplate(["<% if( model.purged ){ %>",'
',n("This collection has been deleted and removed from disk"),"
","<% } %>"]),deleted:i.wrapTemplate(["<% if( model.deleted && !model.purged ){ %>",'
',n("This collection has been deleted"),"
","<% } %>"])}),t=i.wrapTemplate(['
','
','<%- collection.element_identifier || collection.name %>',"
",'
',"
"],"collection"),o=i.wrapTemplate(['
','<% var countText = collection.element_count? ( collection.element_count + " " ) : ""; %>','<% if( collection.collection_type === "list" ){ %>',n("a list of <%- countText %>datasets"),'<% } else if( collection.collection_type === "paired" ){ %>',n("a pair of datasets"),'<% } else if( collection.collection_type === "list:paired" ){ %>',n("a list of <%- countText %>dataset pairs"),'<% } else if( collection.collection_type === "list:list" ){ %>',n("a list of <%- countText %>dataset lists"),"<% } %>","
"],"collection");return a.extend({},s.prototype.templates,{warnings:e,titleBar:t,subtitle:o})}();var c=l.extend({className:l.prototype.className+" dataset-collection-element",initialize:function(e){e.logger&&(this.logger=this.model.logger=e.logger),this.log("DCEListItemView.initialize:",e),l.prototype.initialize.call(this,e)},toString:function(){var e=this.model?this.model+"":"(no model)";return"DCEListItemView("+e+")"}});c.prototype.templates=function(){var e=i.wrapTemplate(['
','
','<%- element.element_identifier %>',"
",'
',"
"],"element");return a.extend({},l.prototype.templates,{titleBar:e})}();var h=t.DatasetListItemView.extend({className:t.DatasetListItemView.prototype.className+" dataset-collection-element",initialize:function(e){e.logger&&(this.logger=this.model.logger=e.logger),this.log("DatasetDCEListItemView.initialize:",e),t.DatasetListItemView.prototype.initialize.call(this,e)},_fetchModelDetails:function(){var e=this;return e.model.inReadyState()&&!e.model.hasDetails()?e.model.fetch({silent:!0}):r.when()},toString:function(){var e=this.model?this.model+"":"(no model)";return"DatasetDCEListItemView("+e+")"}});h.prototype.templates=function(){var e=i.wrapTemplate(['
','','
','<%- element.element_identifier %>',"
","
"],"element");return a.extend({},t.DatasetListItemView.prototype.templates,{titleBar:e})}();var u=d.extend({className:d.prototype.className+" dataset-collection-element",_swapNewRender:function(e){d.prototype._swapNewRender.call(this,e);var t=this.model.get("state")||"ok";return this.$el.addClass("state-"+t),this.$el},toString:function(){var e=this.model?this.model+"":"(no model)";return"NestedDCDCEListItemView("+e+")"}});return{DCListItemView:d,DCEListItemView:c,DatasetDCEListItemView:h,NestedDCDCEListItemView:u}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(83),i(7),i(6)],s=function(e,t,i){"use strict";var n={defaults:{model_class:"DatasetCollectionElement",element_identifier:null,element_index:null,element_type:null},_mergeObject:function(e){return a.extend(e,e.object,{element_id:e.id}),delete e.object,e},constructor:function(e,t){e=this._mergeObject(e),this.idAttribute="element_id",o.Model.apply(this,arguments)},parse:function(e,t){var i=e;return i=this._mergeObject(i)}},s=o.Model.extend(t.LoggableMixin).extend(n).extend({_logNamespace:"collections"}),l=o.Collection.extend(t.LoggableMixin).extend({_logNamespace:"collections",model:s,toString:function(){return["DatasetCollectionElementCollection(",this.length,")"].join("")}}),d=e.DatasetAssociation.extend(t.mixin(n,{url:function(){return this.has("history_id")?Galaxy.root+"api/histories/"+this.get("history_id")+"/contents/"+this.get("id"):(console.warn("no endpoint for non-hdas within a collection yet"),Galaxy.root+"api/datasets")},defaults:a.extend({},e.DatasetAssociation.prototype.defaults,n.defaults),_downloadQueryParameters:function(){return"?to_ext="+this.get("file_ext")+"&hdca_id="+this.get("parent_hdca_id")+"&element_identifier="+this.get("element_identifier")},constructor:function(e,t){this.debug("\t DatasetDCE.constructor:",e,t),n.constructor.call(this,e,t)},hasDetails:function(){return this.elements&&this.elements.length},toString:function(){var e=this.get("element_identifier");return["DatasetDCE(",e,")"].join("")}})),c=l.extend({model:d,toString:function(){return["DatasetDCECollection(",this.length,")"].join("")}}),h=o.Model.extend(t.LoggableMixin).extend(t.SearchableModelMixin).extend({_logNamespace:"collections",defaults:{collection_type:null,deleted:!1},collectionClass:l,initialize:function(e,t){this.debug(this+"(DatasetCollection).initialize:",e,t,this),this.elements=this._createElementsModel(),this.on("change:elements",function(){this.log("change:elements"),this.elements=this._createElementsModel()})},_createElementsModel:function(){this.debug(this+"._createElementsModel",this.collectionClass,this.get("elements"),this.elements);var e=this.get("elements")||[];this.unset("elements",{silent:!0});var t=this;return a.each(e,function(e,i){a.extend(e,{parent_hdca_id:t.get("id")})}),this.elements=new this.collectionClass(e),this.elements},toJSON:function(){var e=o.Model.prototype.toJSON.call(this);return this.elements&&(e.elements=this.elements.toJSON()),e},inReadyState:function(){var e=this.get("populated");return this.isDeletedOrPurged()||e},hasDetails:function(){return 0!==this.elements.length},getVisibleContents:function(e){return this.elements},parse:function(e,t){var i=o.Model.prototype.parse.call(this,e,t);return i.create_time&&(i.create_time=new Date(i.create_time)),i.update_time&&(i.update_time=new Date(i.update_time)),i},delete:function(e){return this.get("deleted")?r.when():this.save({deleted:!0},e)},undelete:function(e){return!this.get("deleted")||this.get("purged")?r.when():this.save({deleted:!1},e)},isDeletedOrPurged:function(){return this.get("deleted")||this.get("purged")},searchAttributes:["name","tags"],toString:function(){var e=[this.get("id"),this.get("name")||this.get("element_identifier")];return"DatasetCollection("+e.join(",")+")"}}),u=h.extend({collectionClass:c,toString:function(){return"List"+h.prototype.toString.call(this)}}),p=u.extend({toString:function(){return"Pair"+h.prototype.toString.call(this)}}),f=h.extend(t.mixin(n,{constructor:function(e,t){this.debug("\t NestedDCDCE.constructor:",e,t),n.constructor.call(this,e,t)},toString:function(){var e=this.object?""+this.object:this.get("element_identifier");return["NestedDCDCE(",e,")"].join("")}})),g=l.extend({model:f,toString:function(){return["NestedDCDCECollection(",this.length,")"].join("")}}),m=p.extend(t.mixin(n,{constructor:function(e,t){this.debug("\t NestedPairDCDCE.constructor:",e,t),n.constructor.call(this,e,t)},toString:function(){var e=this.object?""+this.object:this.get("element_identifier");return["NestedPairDCDCE(",e,")"].join("")}})),v=g.extend({model:m,toString:function(){return["NestedPairDCDCECollection(",this.length,")"].join("")}}),_=h.extend({collectionClass:v,toString:function(){return["ListPairedDatasetCollection(",this.get("name"),")"].join("")}}),y=u.extend(t.mixin(n,{constructor:function(e,t){this.debug("\t NestedListDCDCE.constructor:",e,t),n.constructor.call(this,e,t)},toString:function(){var e=this.object?""+this.object:this.get("element_identifier");return["NestedListDCDCE(",e,")"].join("")}})),w=g.extend({model:y,toString:function(){return["NestedListDCDCECollection(",this.length,")"].join("")}}),b=h.extend({collectionClass:w,toString:function(){return["ListOfListsDatasetCollection(",this.get("name"),")"].join("")}});return{ListDatasetCollection:u,PairDatasetCollection:p,ListPairedDatasetCollection:_,ListOfListsDatasetCollection:b}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(2),i(1))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(60),i(17),i(7),i(80),i(8),i(98),i(6),i(95)],s=function(e,t,i,n,s,d,c){"use strict";function h(e,t){var i=e.toJSON(),n=m(i,{defaultHideSourceItems:t,creationFn:function(t,i,n){return t=t.map(function(e){return{id:e.id,name:e.name,src:"dataset"===e.history_content_type?"hda":"hdca"}}),e.createHDCA(t,"list",i,n)}});return n}var u="collections",p=a.View.extend(i.LoggableMixin).extend({_logNamespace:u,tagName:"li",className:"collection-element",initialize:function(e){this.element=e.element||{},this.selected=e.selected||!1},render:function(){return this.$el.attr("data-element-id",this.element.id).attr("draggable",!0).html(this.template({element:this.element})),this.selected&&this.$el.addClass("selected"),this},template:o.template(['',"<%- element.name %>","",'"].join("")),select:function(e){this.$el.toggleClass("selected",e),this.trigger("select",{source:this,selected:this.$el.hasClass("selected")})},discard:function(){var e=this,t=this.$el.parent().width();this.$el.animate({"margin-right":t},"fast",function(){e.trigger("discard",{source:e}),e.destroy()})},destroy:function(){this.off(),this.$el.remove()},events:{click:"_click","click .name":"_clickName","click .discard":"_clickDiscard",dragstart:"_dragstart",dragend:"_dragend",dragover:"_sendToParent",drop:"_sendToParent"},_click:function(e){e.stopPropagation(),this.select(e)},_clickName:function(e){e.stopPropagation(),e.preventDefault();var t=([c("Enter a new name for the element"),":\n(",c("Note that changing the name here will not rename the dataset"),")"].join(""),prompt(c("Enter a new name for the element")+":",this.element.name));t&&(this.element.name=t,this.render())},_clickDiscard:function(e){e.stopPropagation(),this.discard()},_dragstart:function(e){e.originalEvent&&(e=e.originalEvent),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",JSON.stringify(this.element)),this.$el.addClass("dragging"),this.$el.parent().trigger("collection-element.dragstart",[this])},_dragend:function(e){this.$el.removeClass("dragging"),this.$el.parent().trigger("collection-element.dragend",[this])},_sendToParent:function(e){this.$el.parent().trigger(e)},toString:function(){return"DatasetCollectionElementView()"}}),f=a.View.extend(i.LoggableMixin).extend(n.CollectionCreatorMixin).extend({_logNamespace:u,elementViewClass:p,collectionClass:e.HistoryListDatasetCollection,className:"list-collection-creator collection-creator flex-row-container",minElements:1,defaultAttributes:{creationFn:function(){throw new TypeError("no creation fn for creator")},oncreate:function(){},oncancel:function(){},autoscrollDist:24,highlightClr:"rgba( 64, 255, 255, 1.0 )"},footerSettings:{".hide-originals":"hideOriginals"},initialize:function(e){this.metric("ListCollectionCreator.initialize",e);var t=this;o.each(this.defaultAttributes,function(i,n){i=e[n]||i,t[n]=i}),t.initialElements=e.elements||[],this._setUpCommonSettings(e),this._instanceSetUp(),this._elementsSetUp(),this._setUpBehaviors()},_instanceSetUp:function(){this.selectedIds={},this.$dragging=null,this.blocking=!1},_elementsSetUp:function(){this.invalidElements=[],this.workingElements=[],this.elementViews=[],this.workingElements=this.initialElements.slice(0),this._ensureElementIds(),this._validateElements(),this._mangleDuplicateNames(),this._sortElements()},_ensureElementIds:function(){return this.workingElements.forEach(function(e){e.hasOwnProperty("id")||(e.id=o.uniqueId())}),this.workingElements},_validateElements:function(){var e=this;return e.invalidElements=[],this.workingElements=this.workingElements.filter(function(t){var i=e._isElementInvalid(t);return i&&e.invalidElements.push({element:t,text:i}),!i}),this.workingElements},_isElementInvalid:function(e){if("dataset"!==e.history_content_type)return c("is not a dataset");var i=e.state===t.OK||o.contains(t.NOT_READY_STATES,e.state);return i?e.deleted||e.purged?c("has been deleted or purged"):null:c("has errored, is paused, or is not accessible")},_mangleDuplicateNames:function(){var e=900,t=1,i={};this.workingElements.forEach(function(n){for(var s=n.name;i.hasOwnProperty(s);)if(s=n.name+" ("+t+")",t+=1,t>=e)throw new Error("Safety hit in while loop - thats impressive");n.name=s,i[n.name]=!0})},_sortElements:function(e){},render:function(e,t){return this.workingElements.length .clear-selected").show():this.$(".collection-elements-controls > .clear-selected").hide()},_renderList:function(e,t){var i=this,n=l("
"),s=i.$list();o.each(this.elementViews,function(e){e.destroy(),i.removeElementView(e)}),i.workingElements.forEach(function(e){var t=i._createElementView(e);n.append(t.$el)}),i._renderClearSelected(),s.empty().append(n.children()),o.invoke(i.elementViews,"render"),s.height()>s.css("max-height")?s.css("border-width","1px 0px 1px 0px"):s.css("border-width","0px")},_createElementView:function(e){var t=new this.elementViewClass({element:e,selected:o.has(this.selectedIds,e.id)});return this.elementViews.push(t),this._listenToElementView(t),t},_listenToElementView:function(e){var t=this;t.listenTo(e,{select:function(e){var i=e.source.element;e.selected?t.selectedIds[i.id]=!0:delete t.selectedIds[i.id],t.trigger("elements:select",e)},discard:function(e){t.trigger("elements:discard",e)}})},addElementView:function(e){},removeElementView:function(e){delete this.selectedIds[e.element.id],this._renderClearSelected(),this.elementViews=o.without(this.elementViews,e),this.stopListening(e)},_renderNoElementsLeft:function(){this._disableNameAndCreate(!0),this.$(".collection-elements").append(this.templates.noElementsLeft())},_elementToJSON:function(e){return e},createList:function(e){if(!this.workingElements.length){var t=c("No valid elements for final list")+". ";return t+=''+c("Cancel")+" ",t+=c("or"),t+=' '+c("start over")+".",void this._showAlert(t)}var i=this,n=this.workingElements.map(function(e){return i._elementToJSON(e)});return i.blocking=!0,i.creationFn(n,e,i.hideOriginals).always(function(){i.blocking=!1}).fail(function(e,t,n){i.trigger("error",{xhr:e,status:t,message:c("An error occurred while creating this collection")})}).done(function(e,t,n){i.trigger("collection:created",e,t,n),i.metric("collection:created",e),"function"==typeof i.oncreate&&i.oncreate.call(this,e,t,n)})},_setUpBehaviors:function(){return this.on("error",this._errorHandler),this.once("rendered",function(){this.trigger("rendered:initial",this)}),this.on("elements:select",function(e){this._renderClearSelected()}),this.on("elements:discard",function(e){var t=e.source.element;this.removeElementView(e.source),this.workingElements=o.without(this.workingElements,t),this.workingElements.length||this._renderNoElementsLeft()}),this},_errorHandler:function(e){this.error(e);var t=this;if(content=e.message||c("An error occurred"),e.xhr){var i=e.xhr,n=e.message;0===i.readyState&&0===i.status?content+=": "+c("Galaxy could not be reached and may be updating.")+c(" Try again in a few minutes."):i.responseJSON?content+=":
"+JSON.stringify(i.responseJSON)+"
":content+=": "+n}t._showAlert(content,"alert-danger")},events:{"click .more-help":"_clickMoreHelp","click .less-help":"_clickLessHelp","click .main-help":"_toggleHelp","click .header .alert button":"_hideAlert","click .reset":"reset","click .clear-selected":"clearSelectedElements","click .collection-elements":"clearSelectedElements","dragover .collection-elements":"_dragoverElements","drop .collection-elements":"_dropElements","collection-element.dragstart .collection-elements":"_elementDragstart","collection-element.dragend .collection-elements":"_elementDragend","change .collection-name":"_changeName","keydown .collection-name":"_nameCheckForEnter","change .hide-originals":"_changeHideOriginals","click .cancel-create":"_cancelCreate","click .create-collection":"_clickCreate"},reset:function(){this._instanceSetUp(),this._elementsSetUp(),this.render()},clearSelectedElements:function(e){this.$(".collection-elements .collection-element").removeClass("selected"),this.$(".collection-elements-controls > .clear-selected").hide()},_dragoverElements:function(e){e.preventDefault();var t=this.$list();this._checkForAutoscroll(t,e.originalEvent.clientY);var i=this._getNearestElement(e.originalEvent.clientY);this.$(".element-drop-placeholder").remove();var n=r('
');i.length?i.before(n):t.append(n)},_checkForAutoscroll:function(e,t){var i=2,n=e.offset(),s=e.scrollTop(),a=t-n.top,o=n.top+e.outerHeight()-t;a>=0&&a=0&&oe&&a-o','',c("More help"),"",'","
",'
','','',"
"].join("")),middle:o.template(['",'
',"
"].join("")),footer:o.template(['
','
','","
",'
','','
',c("Name"),":
","
","
",'
','
','",'
','",'","
","
",'
','","
","
"].join("")),helpContent:o.template(["

",c(["Collections of datasets are permanent, ordered lists of datasets that can be passed to tools and ","workflows in order to have analyses done on each member of the entire group. This interface allows ","you to create a collection and re-order the final collection."].join("")),"

","
    ","
  • ",c(["Rename elements in the list by clicking on ",'the existing name.'].join("")),"
  • ","
  • ",c(["Discard elements from the final created list by clicking on the ",'"Discard" button.'].join("")),"
  • ","
  • ",c(["Reorder the list by clicking and dragging elements. Select multiple elements by clicking on ",'them and you can then move those selected by dragging the ',"entire group. Deselect them by clicking them again or by clicking the ",'the "Clear selected" link.'].join("")),"
  • ","
  • ",c(['Click the "Start over" link to begin again as if you had just opened ',"the interface."].join("")),"
  • ","
  • ",c(['Click the "Cancel" button to exit the interface.'].join("")),"
  • ","

","

",c(['Once your collection is complete, enter a name and ','click "Create list".'].join("")),"

"].join("")),invalidElements:o.template([c("The following selections could not be included due to problems:"),"
    <% _.each( problems, function( problem ){ %>","
  • <%- problem.element.name %>: <%- problem.text %>
  • ","<% }); %>
"].join("")),noElementsLeft:o.template(['
  • ',c("No elements left! "),c("Would you like to "),'',c("start over"),"?","
  • "].join("")),invalidInitial:o.template(['
    ','
    ','',"<% if( _.size( problems ) ){ %>",c("The following selections could not be included due to problems"),":","
      <% _.each( problems, function( problem ){ %>","
    • <%- problem.element.name %>: <%- problem.text %>
    • ","<% }); %>
    ","<% } else if( _.size( elements ) < 1 ){ %>",c("No datasets were selected"),".","<% } %>","
    ",c("At least one element is needed for the collection"),". ",c("You may need to "),'',c("cancel")," ",c("and reselect new elements"),".","
    ","
    ","
    ",'"].join(""))}),toString:function(){return"ListCollectionCreator"}}),g=function(e,t,i){var n,a=l.Deferred(),r=Galaxy.modal||new s.View;return t=o.defaults(t||{},{elements:e,oncancel:function(){r.hide(),a.reject("cancelled")},oncreate:function(e,t){r.hide(),a.resolve(t)}}),n=new i(t),r.show({title:t.title||c("Create a collection"),body:n.$el,width:"80%",height:"100%",closing_events:!0}),n.render(),window._collectionCreator=n,a},m=function(e,t){return t=t||{},t.title=c("Create a collection from a list of datasets"),g(e,t,f)};return{DatasetCollectionElementView:p,ListCollectionCreator:f,collectionCreatorModal:g,listCollectionCreatorModal:m,createListCollection:h}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3),i(1),i(1))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(64),i(17),i(25),i(7),i(6)],s=function(e,t,i,n,s){"use strict";var d="dataset",c=e.ListItemView,h=c.extend({_logNamespace:d,className:c.prototype.className+" dataset",id:function(){return["dataset",this.model.get("id")].join("-")},initialize:function(e){e.logger&&(this.logger=this.model.logger=e.logger),this.log(this+".initialize:",e),c.prototype.initialize.call(this,e),this.linkTarget=e.linkTarget||"_blank"},_setUpListeners:function(){c.prototype._setUpListeners.call(this);var e=this;return e.listenTo(e.model,{change:function(t){e.model.changedAttributes().state&&e.model.inReadyState()&&e.expanded&&!e.model.hasDetails()?e.model.fetch({silent:!0}).done(function(){e.render()}):a.has(t.changed,"tags")&&1===a.keys(t.changed).length?e.$(".nametags").html(e._renderNametags()):e.render()}})},_fetchModelDetails:function(){var e=this;return e.model.inReadyState()&&!e.model.hasDetails()?e.model.fetch({silent:!0}):o.when()},remove:function(e,t){var i=this;e=e||this.fxSpeed,this.$el.fadeOut(e,function(){r.View.prototype.remove.call(i),t&&t.call(i)})},_swapNewRender:function(e){return c.prototype._swapNewRender.call(this,e),this.model.has("state")&&this.$el.addClass("state-"+this.model.get("state")), -this.$el},_renderPrimaryActions:function(){return[this._renderDisplayButton()]},_renderDisplayButton:function(){var e=this.model.get("state");if(e===t.NOT_VIEWABLE||e===t.DISCARDED||!this.model.get("accessible"))return null;var n={target:this.linkTarget,classes:"display-btn"};if(this.model.get("purged"))n.disabled=!0,n.title=s("Cannot display datasets removed from disk");else if(e===t.UPLOAD)n.disabled=!0,n.title=s("This dataset must finish uploading before it can be viewed");else if(e===t.NEW)n.disabled=!0,n.title=s("This dataset is not yet viewable");else{n.title=s("View data"),n.href=this.model.urls.display;var a=this;n.onclick=function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.addDataset(a.model.get("id")),e.preventDefault())}}return n.faIcon="fa-eye",i(n)},_renderDetails:function(){if(this.model.get("state")===t.NOT_VIEWABLE)return l(this.templates.noAccess(this.model.toJSON(),this));var e=c.prototype._renderDetails.call(this);return e.find(".actions .left").empty().append(this._renderSecondaryActions()),e.find(".summary").html(this._renderSummary()).prepend(this._renderDetailMessages()),e.find(".display-applications").html(this._renderDisplayApplications()),this._setUpBehaviors(e),e},_renderSummary:function(){var e=this.model.toJSON(),t=this.templates.summaries[e.state];return(t=t||this.templates.summaries.unknown)(e,this)},_renderDetailMessages:function(){var e=this,t=l('
    '),i=e.model.toJSON();return a.each(e.templates.detailMessages,function(n){t.append(l(n(i,e)))}),t},_renderDisplayApplications:function(){return this.model.isDeletedOrPurged()?"":[this.templates.displayApplications(this.model.get("display_apps"),this),this.templates.displayApplications(this.model.get("display_types"),this)].join("")},_renderSecondaryActions:function(){switch(this.debug("_renderSecondaryActions"),this.model.get("state")){case t.NOT_VIEWABLE:return[];case t.OK:case t.FAILED_METADATA:case t.ERROR:return[this._renderDownloadButton(),this._renderShowParamsButton()]}return[this._renderShowParamsButton()]},_renderShowParamsButton:function(){return i({title:s("View details"),classes:"params-btn",href:this.model.urls.show_params,target:this.linkTarget,faIcon:"fa-info-circle",onclick:function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.add({title:"Dataset details",url:this.href}),e.preventDefault(),e.stopPropagation())}})},_renderDownloadButton:function(){return this.model.get("purged")||!this.model.hasData()?null:a.isEmpty(this.model.get("meta_files"))?l(['','',""].join("")):this._renderMetaFileDownloadButton()},_renderMetaFileDownloadButton:function(){var e=this.model.urls;return l(['"].join("\n"))},_renderNametags:function(){var e=a.template(["<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>",'<% if (tag.indexOf("name:") == 0){ %>','<%- tag.slice(5) %>',"<% } %>","<% }); %>"].join(""));return e({tags:this.model.get("tags")})},events:a.extend(a.clone(c.prototype.events),{"click .display-btn":function(e){this.trigger("display",this,e)},"click .params-btn":function(e){this.trigger("params",this,e)},"click .download-btn":function(e){this.trigger("download",this,e)}}),toString:function(){var e=this.model?this.model+"":"(no model)";return"DatasetListItemView("+e+")"}});return h.prototype.templates=function(){var e=a.extend({},c.prototype.templates.warnings,{failed_metadata:n.wrapTemplate(['<% if( model.state === "failed_metadata" ){ %>','
    ',s("An error occurred setting the metadata for this dataset"),"
    ","<% } %>"]),error:n.wrapTemplate(["<% if( model.error ){ %>",'
    ',s("There was an error getting the data for this dataset"),": <%- model.error %>","
    ","<% } %>"]),purged:n.wrapTemplate(["<% if( model.purged ){ %>",'
    ',s("This dataset has been deleted and removed from disk"),"
    ","<% } %>"]),deleted:n.wrapTemplate(["<% if( model.deleted && !model.purged ){ %>",'
    ',s("This dataset has been deleted"),"
    ","<% } %>"])}),i=n.wrapTemplate(['
    ','
    ','
    ','
    ','
    ',"
    ","<% if( !dataset.deleted && !dataset.purged ){ %>",'
    ','
    ','
    ',"<% if( dataset.peek ){ %>",'
    <%= dataset.peek %>
    ',"<% } %>","<% } %>","
    "],"dataset"),o=n.wrapTemplate(['
    ','
    ',s("You do not have permission to view this dataset"),"
    ","
    "],"dataset"),r={};r[t.OK]=r[t.FAILED_METADATA]=n.wrapTemplate(["<% if( dataset.misc_blurb ){ %>",'
    ','<%- dataset.misc_blurb %>',"
    ","<% } %>","<% if( dataset.file_ext ){ %>",'
    ','",'<%- dataset.file_ext %>',"
    ","<% } %>","<% if( dataset.metadata_dbkey ){ %>",'
    ','",'',"<%- dataset.metadata_dbkey %>","","
    ","<% } %>","<% if( dataset.misc_info ){ %>",'
    ','<%- dataset.misc_info %>',"
    ","<% } %>"],"dataset"),r[t.NEW]=n.wrapTemplate(["
    ",s("This is a new dataset and not all of its data are available yet"),"
    "],"dataset"),r[t.NOT_VIEWABLE]=n.wrapTemplate(["
    ",s("You do not have permission to view this dataset"),"
    "],"dataset"),r[t.DISCARDED]=n.wrapTemplate(["
    ",s("The job creating this dataset was cancelled before completion"),"
    "],"dataset"),r[t.QUEUED]=n.wrapTemplate(["
    ",s("This job is waiting to run"),"
    "],"dataset"),r[t.RUNNING]=n.wrapTemplate(["
    ",s("This job is currently running"),"
    "],"dataset"),r[t.UPLOAD]=n.wrapTemplate(["
    ",s("This dataset is currently uploading"),"
    "],"dataset"),r[t.SETTING_METADATA]=n.wrapTemplate(["
    ",s("Metadata is being auto-detected"),"
    "],"dataset"),r[t.PAUSED]=n.wrapTemplate(["
    ",s('This job is paused. Use the "Resume Paused Jobs" in the history menu to resume'),"
    "],"dataset"),r[t.ERROR]=n.wrapTemplate(["<% if( !dataset.purged ){ %>","
    <%- dataset.misc_blurb %>
    ","<% } %>",'',s("An error occurred with this dataset"),":",'
    <%- dataset.misc_info %>
    '],"dataset"),r[t.EMPTY]=n.wrapTemplate(["
    ",s("No data"),": <%- dataset.misc_blurb %>
    "],"dataset"),r.unknown=n.wrapTemplate(['
    Error: unknown dataset state: "<%- dataset.state %>"
    '],"dataset");var l={resubmitted:n.wrapTemplate(["<% if( model.resubmitted ){ %>",'
    ',s("The job creating this dataset has been resubmitted"),"
    ","<% } %>"])},d=n.wrapTemplate(["<% _.each( apps, function( app ){ %>",'
    ','<%- app.label %> ','',"<% _.each( app.links, function( link ){ %>",'',"<% print( _l( link.text ) ); %>"," ","<% }); %>","","
    ","<% }); %>"],"apps");return a.extend({},c.prototype.templates,{warnings:e,details:i,noAccess:o,summaries:r,detailMessages:l,displayApplications:d})}(),{DatasetListItemView:h}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(2),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(11),i(5)],s=function(e,t){var i=a.View.extend({initialize:function(e){this.model=new a.Model(e),this.url=this.model.get("url"),this.redirect=this.model.get("redirect"),this.setElement("
    "),this.render()},render:function(){var i=this;o.ajax({url:Galaxy.root+this.url,type:"GET"}).done(function(n){var s=o.extend({},i.model.attributes,n),a=new e({title:s.title,message:s.message,status:s.status||"warning",icon:s.icon,inputs:s.inputs,buttons:{submit:new t.Button({tooltip:s.submit_tooltip,title:s.submit_title||"Save settings",icon:s.submit_icon||"fa-save",cls:"btn btn-primary ui-clear-float",onclick:function(){i._submit(a)}})}});i.$el.empty().append(a.$el)}).fail(function(e){i.$el.empty().append(new t.Message({message:"Failed to load resource "+i.url+".",status:"danger",persistent:!0}).$el)})},_submit:function(e){var t=this;o.ajax({url:Galaxy.root+t.url,data:JSON.stringify(e.data.create()),type:"PUT",contentType:"application/json"}).done(function(i){var n={message:i.message,status:"success",persistent:!1};t.redirect?window.location=Galaxy.root+t.redirect+"?"+o.param(n):(e.data.matchModel(i,function(t,i){e.field_list[i].value(t.value)}),t._showMessage(e,n))}).fail(function(i){t._showMessage(e,{message:i.responseJSON.err_msg,status:"danger",persistent:!1})})},_showMessage:function(e,t){var i=e.$el.parents().filter(function(){return["auto","scroll"].indexOf(o(this).css("overflow"))!=-1}).first();i.animate({scrollTop:0},500),e.message.update(t)}});return{View:i}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1))},function(e,t,i){var n,s;(function(a){n=[i(56),i(88),i(6)],s=function(e,t,i){"use strict";function n(e){return function(t,i){return this.isNew()&&(i=i||{},i.url=this.urlRoot+this.get("history_id")+"/contents",t=t||{},t.type="dataset_collection"),e.call(this,t,i)}}var s=t.HistoryContentMixin,o=e.ListDatasetCollection,r=e.PairDatasetCollection,l=e.ListPairedDatasetCollection,d=e.ListOfListsDatasetCollection,c=o.extend(s).extend({defaults:a.extend(a.clone(o.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list",model_class:"HistoryDatasetCollectionAssociation"}),save:n(o.prototype.save),toString:function(){return"History"+o.prototype.toString.call(this)}}),h=r.extend(s).extend({defaults:a.extend(a.clone(r.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"paired",model_class:"HistoryDatasetCollectionAssociation"}),save:n(r.prototype.save),toString:function(){return"History"+r.prototype.toString.call(this)}}),u=l.extend(s).extend({defaults:a.extend(a.clone(l.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list:paired",model_class:"HistoryDatasetCollectionAssociation"}),save:n(l.prototype.save),toString:function(){return"History"+l.prototype.toString.call(this)}}),p=d.extend(s).extend({defaults:a.extend(a.clone(d.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list:list",model_class:"HistoryDatasetCollectionAssociation"}),save:n(d.prototype.save),toString:function(){return["HistoryListOfListsDatasetCollection(",this.get("name"),")"].join("")}});return{HistoryListDatasetCollection:c,HistoryPairDatasetCollection:h,HistoryListPairedDatasetCollection:u,HistoryListOfListsDatasetCollection:p}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o,r){n=[i(79),i(86),i(60),i(63),i(7),i(149)],s=function(e,t,i,n,s,l){"use strict";var d=e.PaginatedCollection,c=d.extend(s.LoggableMixin).extend({_logNamespace:"history",model:function(e,n){if("dataset"===e.history_content_type)return new t.HistoryDatasetAssociation(e,n);if("dataset_collection"===e.history_content_type){switch(e.collection_type){case"list":return new i.HistoryListDatasetCollection(e,n);case"paired":return new i.HistoryPairDatasetCollection(e,n);case"list:paired":return new i.HistoryListPairedDatasetCollection(e,n);case"list:list":return new i.HistoryListOfListsDatasetCollection(e,n)}var s="Unknown collection_type: "+e.collection_type;return console.warn(s,e),{validationError:s}}return{validationError:"Unknown history_content_type: "+e.history_content_type}},limitPerPage:500,limitPerProgressiveFetch:500,order:"hid",urlRoot:Galaxy.root+"api/histories",url:function(){return this.urlRoot+"/"+this.historyId+"/contents"},initialize:function(e,t){t=t||{},d.prototype.initialize.call(this,e,t),this.history=t.history||null,this.setHistoryId(t.historyId||null),this.includeDeleted=t.includeDeleted||this.includeDeleted,this.includeHidden=t.includeHidden||this.includeHidden,this.model.prototype.idAttribute="type_id"},setHistoryId:function(e){this.historyId=e,this._setUpWebStorage()},_setUpWebStorage:function(e){if(this.historyId)return this.storage=new n.HistoryPrefs({id:n.HistoryPrefs.historyStorageKey(this.historyId)}),this.trigger("new-storage",this.storage,this),this.on({"include-deleted":function(e){this.storage.includeDeleted(e)},"include-hidden":function(e){this.storage.includeHidden(e)}}),this.includeDeleted=this.storage.includeDeleted()||!1,this.includeHidden=this.storage.includeHidden()||!1,this},comparators:a.extend(a.clone(d.prototype.comparators),{name:s.buildComparator("name",{ascending:!0}),"name-dsc":s.buildComparator("name",{ascending:!1}),hid:s.buildComparator("hid",{ascending:!1}),"hid-asc":s.buildComparator("hid",{ascending:!0})}),running:function(){return this.filter(function(e){return!e.inReadyState()})},runningAndActive:function(){return this.filter(function(e){return!e.inReadyState()&&e.get("visible")&&!e.get("deleted")})},getByHid:function(e){return this.findWhere({hid:e})},haveDetails:function(){return this.all(function(e){return e.hasDetails()})},hidden:function(){return this.filter(function(e){return e.hidden()})},deleted:function(){return this.filter(function(e){return e.get("deleted")})},visibleAndUndeleted:function(){return this.filter(function(e){return e.get("visible")&&!e.get("deleted")})},setIncludeDeleted:function(e,t){if(a.isBoolean(e)&&e!==this.includeDeleted){if(this.includeDeleted=e,a.result(t,"silent"))return;this.trigger("include-deleted",e,this)}},setIncludeHidden:function(e,t){if(a.isBoolean(e)&&e!==this.includeHidden){if(this.includeHidden=e,t=t||{},a.result(t,"silent"))return;this.trigger("include-hidden",e,this)}},fetch:function(e){if(e=e||{},this.historyId&&!e.details){var t=n.HistoryPrefs.get(this.historyId).toJSON();a.isEmpty(t.expandedIds)||(e.details=a.values(t.expandedIds).join(","))}return d.prototype.fetch.call(this,e)},_buildFetchData:function(e){return a.extend(d.prototype._buildFetchData.call(this,e),{v:"dev"})},_fetchParams:d.prototype._fetchParams.concat(["v","details"]),_buildFetchFilters:function(e){var t=d.prototype._buildFetchFilters.call(this,e)||{},i={};return this.includeDeleted||(i.deleted=!1,i.purged=!1),this.includeHidden||(i.visible=!0),a.defaults(t,i)},getTotalItemCount:function(){return this.history.contentsShown()},fetchUpdated:function(e,t){return e&&(t=t||{filters:{}},t.remove=!1,t.filters={"update_time-ge":e.toISOString(),visible:""}),this.fetch(t)},fetchDeleted:function(e){e=e||{};var t=this;return e.filters=a.extend(e.filters,{deleted:!0,purged:void 0}),e.remove=!1,t.trigger("fetching-deleted",t),t.fetch(e).always(function(){t.trigger("fetching-deleted-done",t)})},fetchHidden:function(e){e=e||{};var t=this;return e.filters=a.extend(e.filters,{visible:!1}),e.remove=!1,t.trigger("fetching-hidden",t),t.fetch(e).always(function(){t.trigger("fetching-hidden-done",t)})},fetchAllDetails:function(e){e=e||{};var t={details:"all"};return e.data=a.extend(e.data||{},t),this.fetch(e)},fetchCollectionCounts:function(e){return e=e||{},e.keys=["type_id","element_count"].join(","),e.filters=a.extend(e.filters||{},{history_content_type:"dataset_collection"}),e.remove=!1,this.fetch(e)},_filterAndUpdate:function(e,t){var i=this,n=i.model.prototype.idAttribute,s=[t];return i.fetch({filters:e,remove:!1}).then(function(e){return e=e.reduce(function(e,t,s){var a=i.get(t[n]);return a?e.concat(a):e},[]),i.ajaxQueue("save",s,e)})},ajaxQueue:function(e,t,i){return i=i||this.models,new l.AjaxQueue(i.slice().reverse().map(function(i,n){var s=a.isString(e)?i[e]:e;return function(){return s.apply(i,t)}})).deferred},progressivelyFetchDetails:function(e){function i(t){t=t||0;var o=a.extend(a.clone(e),{view:"summary",keys:d,limit:r,offset:t,reset:0===t,remove:!1});a.defer(function(){s.fetch.call(s,o).fail(n.reject).done(function(e){n.notify(e,r,t),e.length!==r?(s.allFetched=!0,n.resolve(e,r,t)):i(t+r)})})}e=e||{};var n=o.Deferred(),s=this,r=e.limitPerCall||s.limitPerProgressiveFetch,l=t.HistoryDatasetAssociation.prototype.searchAttributes,d=l.join(",");return i(),n},isCopyable:function(e){var t=["HistoryDatasetAssociation","HistoryDatasetCollectionAssociation"];return a.isObject(e)&&e.id&&a.contains(t,e.model_class)},copy:function(e){var t,i,n;a.isString(e)?(t=e,n="hda",i="dataset"):(t=e.id,n={HistoryDatasetAssociation:"hda",LibraryDatasetDatasetAssociation:"ldda",HistoryDatasetCollectionAssociation:"hdca"}[e.model_class]||"hda",i="hdca"===n?"dataset_collection":"dataset");var s=this,r=o.ajax(this.url(),{method:"POST",contentType:"application/json",data:JSON.stringify({content:t,source:n,type:i})}).done(function(e){s.add([e],{parse:!0})}).fail(function(e,a,o){s.trigger("error",s,r,{},"Error copying contents",{type:i,id:t,source:n})});return r},createHDCA:function(e,t,i,n,s){var a=this.model({history_content_type:"dataset_collection",collection_type:t,history_id:this.historyId,name:i,hide_source_items:n||!1,element_identifiers:e});return a.save(s)},haveSearchDetails:function(){return this.allFetched&&this.all(function(e){return a.has(e.attributes,"annotation")})},matches:function(e){return this.filter(function(t){return t.matches(e)})},clone:function(){var e=r.Collection.prototype.clone.call(this);return e.historyId=this.historyId,e},toString:function(){return["HistoryContents(",[this.historyId,this.length].join(),")"].join("")}});return{HistoryContents:c}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(2))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(61),i(63),i(79),i(4),i(7),i(6)],s=function(e,t,i,n,s,d){"use strict";var c=a.Model.extend(s.LoggableMixin).extend(s.mixin(s.SearchableModelMixin,{_logNamespace:"history",UPDATE_DELAY:4e3,defaults:{model_class:"History",id:null,name:"Unnamed History",state:"new",deleted:!1,contents_active:{},contents_states:{}},urlRoot:Galaxy.root+"api/histories",contentsClass:e.HistoryContents,searchAttributes:["name","annotation","tags"],searchAliases:{title:"name",tag:"tags"},initialize:function(e,t){t=t||{},this.logger=t.logger||null,this.log(this+".initialize:",e,t),this.contents=new this.contentsClass([],{history:this,historyId:this.get("id"),order:t.order}),this._setUpListeners(),this._setUpCollectionListeners(),this.updateTimeoutId=null},_setUpListeners:function(){return this.on({error:function(e,t,i,n,s){this.clearUpdateTimeout()},"change:id":function(e,t){this.contents&&(this.contents.historyId=t)}})},_setUpCollectionListeners:function(){return this.contents?this.listenTo(this.contents,{error:function(){this.trigger.apply(this,o.makeArray(arguments))}}):this},contentsShown:function(){var e=this.get("contents_active"),t=e.active||0;return t+=this.contents.includeDeleted?e.deleted:0,t+=this.contents.includeHidden?e.hidden:0},nice_size:function(){var e=this.get("size");return e?n.bytesToString(e,!0,2):d("(empty)")},toJSON:function(){return r.extend(a.Model.prototype.toJSON.call(this),{nice_size:this.nice_size()})},get:function(e){return"nice_size"===e?this.nice_size():a.Model.prototype.get.apply(this,arguments)},ownedByCurrUser:function(){return!(!Galaxy||!Galaxy.user)&&(!Galaxy.user.isAnonymous()&&Galaxy.user.id===this.get("user_id"))},numOfUnfinishedJobs:function(){var e=this.get("non_ready_jobs");return e?e.length:0},numOfUnfinishedShownContents:function(){return this.contents.runningAndActive().length||0},_fetchContentRelatedAttributes:function(){var e=["size","non_ready_jobs","contents_active","hid_counter"];return this.fetch({data:l.param({keys:e.join(",")})})},refresh:function(e){e=e||{};var t=this,i=t.lastUpdateTime;this.contents.allFetched=!1;var n=0!==t.contents.currentPage?function(){return t.contents.fetchPage(t.contents.currentPage)}:function(){return t.contents.fetchUpdated(i)};return n().done(function(i,n,s){var a;try{a=new Date(s.getResponseHeader("Date"))}catch(e){}t.lastUpdateTime=a||new Date,t.checkForUpdates(e)})},checkForUpdates:function(e){function t(){n.clearUpdateTimeout(),n.updateTimeoutId=setTimeout(function(){n.refresh(e)},i)}e=e||{};var i=this.UPDATE_DELAY,n=this;if(n.id){var s=this.numOfUnfinishedShownContents();s>0?t():n._fetchContentRelatedAttributes().done(function(e){n.numOfUnfinishedJobs()>0?t():n.trigger("ready")})}},clearUpdateTimeout:function(){this.updateTimeoutId&&(clearTimeout(this.updateTimeoutId),this.updateTimeoutId=null)},parse:function(e,t){var i=a.Model.prototype.parse.call(this,e,t);return i.create_time&&(i.create_time=new Date(i.create_time)),i.update_time&&(i.update_time=new Date(i.update_time)),i},fetchWithContents:function(e,t){e=e||{};var i=this;return e.view="dev-detailed",this.fetch(e).then(function(e){return i.contents.history=i,i.contents.setHistoryId(e.id),i.fetchContents(t)})},fetchContents:function(e){e=e||{};var t=this;return t.lastUpdateTime=new Date,t.contents.fetchCurrentPage(e)},_delete:function(e){return this.get("deleted")?o.when():this.save({deleted:!0},e)},purge:function(e){return this.get("purged")?o.when():this.save({deleted:!0,purged:!0},e)},undelete:function(e){return this.get("deleted")?this.save({deleted:!1},e):o.when()},copy:function(e,t,i){if(e=void 0===e||e,!this.id)throw new Error("You must set the history ID before copying it.");var n={history_id:this.id};e&&(n.current=!0),t&&(n.name=t),i||(n.all_datasets=!1),n.view="dev-detailed";var s=this,a=o.post(this.urlRoot,n);return e?a.then(function(e){var t=new c(e);return t.setAsCurrent().done(function(){s.trigger("copied",s,e)})}):a.done(function(e){s.trigger("copied",s,e)})},setAsCurrent:function(){var e=this,t=o.getJSON(Galaxy.root+"history/set_as_current?id="+this.id);return t.done(function(){e.trigger("set-as-current",e)}),t},toString:function(){return"History("+this.get("id")+","+this.get("name")+")"}})),h=i.InfinitelyScrollingCollection,u=h.extend(s.LoggableMixin).extend({_logNamespace:"history",model:c,order:"update_time",limitOnFirstFetch:10,limitPerFetch:10,initialize:function(e,t){t=t||{},this.log("HistoryCollection.initialize",e,t),h.prototype.initialize.call(this,e,t),this.includeDeleted=t.includeDeleted||!1,this.currentHistoryId=t.currentHistoryId,this.setUpListeners()},urlRoot:Galaxy.root+"api/histories",url:function(){return this.urlRoot},setUpListeners:function(){return this.on({"change:deleted":function(e){this.debug("change:deleted",this.includeDeleted,e.get("deleted")),!this.includeDeleted&&e.get("deleted")&&this.remove(e)},copied:function(e,t){this.setCurrent(new c(t,[]))},"set-as-current":function(e){var t=this.currentHistoryId;this.trigger("no-longer-current",t),this.currentHistoryId=e.id}})},_buildFetchData:function(e){return r.extend(h.prototype._buildFetchData.call(this,e),{view:"dev-detailed"})},_buildFetchFilters:function(e){var t=h.prototype._buildFetchFilters.call(this,e)||{},i={};return this.includeDeleted?i.deleted=null:(i.deleted=!1,i.purged=!1),r.defaults(t,i)},fetchFirst:function(e){var t=this,i=l.when();return this.currentHistoryId&&(i=h.prototype.fetchFirst.call(t,{silent:!0,limit:1,filters:{purged:"",deleted:"","encoded_id-in":this.currentHistoryId}})),i.then(function(){return e=e||{},e.offset=0,t.fetchMore(e)})},comparators:r.extend(r.clone(h.prototype.comparators),{name:s.buildComparator("name",{ascending:!0}),"name-dsc":s.buildComparator("name",{ascending:!1}),size:s.buildComparator("size",{ascending:!1}),"size-asc":s.buildComparator("size",{ascending:!0})}),sort:function(e){e=e||{};var t=e.silent,i=this.remove(this.get(this.currentHistoryId));return h.prototype.sort.call(this,r.defaults({silent:!0},e)),this.unshift(i,{silent:!0}),t||this.trigger("sort",this,e),this},create:function(e,t,i,n){var s=this,a=o.getJSON(Galaxy.root+"history/create_new_current");return a.done(function(e){s.setCurrent(new c(e,[],i||{}))})},setCurrent:function(e,t){return t=t||{},this.unshift(e,t),this.currentHistoryId=e.get("id"),t.silent||this.trigger("new-current",e,this),this},toString:function(){return"HistoryCollection("+this.length+",current:"+this.currentHistoryId+")"}});return{History:c,HistoryCollection:u}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3),i(1))},function(e,t,i){var n,s;(function(a){n=[i(7)],s=function(e){"use strict";var t=e.SessionStorageModel.extend({defaults:{expandedIds:{},show_deleted:!1,show_hidden:!1},addExpanded:function(e){var t=this.get("expandedIds");t[e.id]=e.get("id"),this.save("expandedIds",t)},removeExpanded:function(e){var t=this.get("expandedIds");delete t[e.id],this.save("expandedIds",t)},isExpanded:function(e){return a.result(this.get("expandedIds"),e,!1)},allExpanded:function(){return a.values(this.get("expandedIds"))},clearExpanded:function(){this.set("expandedIds",{})},includeDeleted:function(e){return a.isUndefined(e)||this.set("show_deleted",e),this.get("show_deleted")},includeHidden:function(e){return a.isUndefined(e)||this.set("show_hidden",e),this.get("show_hidden")},toString:function(){return"HistoryPrefs("+this.id+")"}},{storageKeyPrefix:"history:",historyStorageKey:function(e){if(!e)throw new Error("HistoryPrefs.historyStorageKey needs valid id: "+e);return t.storageKeyPrefix+e},get:function(e){return new t({id:t.historyStorageKey(e)})},clearAll:function(e){for(var i in sessionStorage)0===i.indexOf(t.storageKeyPrefix)&&sessionStorage.removeItem(i)}});return{HistoryPrefs:t}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(7),i(6)],s=function(e,t){"use strict";var i="list",n=a.View.extend(e.LoggableMixin).extend({_logNamespace:i,initialize:function(e){this.expanded=e.expanded||!1,this.log("\t expanded:",this.expanded),this.fxSpeed=void 0!==e.fxSpeed?e.fxSpeed:this.fxSpeed},fxSpeed:"fast",render:function(e){var t=this._buildNewRender();return this._setUpBehaviors(t),this._queueNewRender(t,e),this},_buildNewRender:function(){var e=o(this.templates.el(this.model.toJSON(),this));return this.expanded&&this.$details(e).replaceWith(this._renderDetails().show()),e},_queueNewRender:function(e,t){t=void 0===t?this.fxSpeed:t;var i=this;0===t?(i._swapNewRender(e),i.trigger("rendered",i)):o(i).queue("fx",[function(e){i.$el.fadeOut(t,e)},function(t){i._swapNewRender(e),t()},function(e){i.$el.fadeIn(t,e)},function(e){i.trigger("rendered",i),e()}])},_swapNewRender:function(e){return this.$el.empty().attr("class",r.isFunction(this.className)?this.className():this.className).append(e.children())},_setUpBehaviors:function(e){e=e||this.$el,e.find("[title]").tooltip({placement:"bottom"})},$details:function(e){return e=e||this.$el,e.find("> .details")},_renderDetails:function(){var e=o(this.templates.details(this.model.toJSON(),this));return this._setUpBehaviors(e),e},toggleExpanded:function(e){return e=void 0===e?!this.expanded:e,e?this.expand():this.collapse(),this},expand:function(){var e=this;return e._fetchModelDetails().always(function(){e._expand()})},_fetchModelDetails:function(){return this.model.hasDetails()?l.when():this.model.fetch()},_expand:function(){var e=this,t=e._renderDetails();e.$details().replaceWith(t),e.expanded=!0,e.$details().slideDown(e.fxSpeed,function(){e.trigger("expanded",e)})},collapse:function(){this.debug(this+"(ExpandableView).collapse");var e=this;e.expanded=!1,this.$details().slideUp(e.fxSpeed,function(){e.trigger("collapsed",e)})}}),s=n.extend(e.mixin(e.SelectableViewMixin,e.DraggableViewMixin,{tagName:"div",className:"list-item",initialize:function(t){n.prototype.initialize.call(this,t),e.SelectableViewMixin.initialize.call(this,t),e.DraggableViewMixin.initialize.call(this,t),this._setUpListeners()},_setUpListeners:function(){return this.on("selectable",function(e){e?this.$(".primary-actions").hide():this.$(".primary-actions").show()},this),this},_buildNewRender:function(){var e=n.prototype._buildNewRender.call(this);return e.children(".warnings").replaceWith(this._renderWarnings()),e.children(".title-bar").replaceWith(this._renderTitleBar()),e.children(".primary-actions").append(this._renderPrimaryActions()),e.find("> .title-bar .subtitle").replaceWith(this._renderSubtitle()),e},_swapNewRender:function(e){return n.prototype._swapNewRender.call(this,e),this.selectable&&this.showSelector(0),this.draggable&&this.draggableOn(),this.$el},_renderWarnings:function(){var e=this,t=o('
    '),i=e.model.toJSON();return r.each(e.templates.warnings,function(n){t.append(o(n(i,e)))}),t},_renderTitleBar:function(){return o(this.templates.titleBar(this.model.toJSON(),this))},_renderPrimaryActions:function(){return[]},_renderSubtitle:function(){return o(this.templates.subtitle(this.model.toJSON(),this))},events:{"click .title-bar":"_clickTitleBar","keydown .title-bar":"_keyDownTitleBar","click .selector":"toggleSelect"},_clickTitleBar:function(e){e.stopPropagation(),e.altKey?(this.toggleSelect(e),this.selectable||this.showSelector()):this.toggleExpanded()},_keyDownTitleBar:function(e){var t=32,i=13;return!e||"keydown"!==e.type||e.keyCode!==t&&e.keyCode!==i||(this.toggleExpanded(),e.stopPropagation(),!1)},toString:function(){var e=this.model?this.model+"":"(no model)";return"ListItemView("+e+")"}}));s.prototype.templates=function(){var t=e.wrapTemplate(['
    ','
    ','
    ','',"
    ",'
    ','
    ','
    ',"
    "]),i={},n=e.wrapTemplate(['
    ','','
    ','<%- element.name %>',"
    ",'
    ',"
    "],"element"),s=e.wrapTemplate(['
    ']),a=e.wrapTemplate(['
    ']);return{el:t,warnings:i,titleBar:n,subtitle:s,details:a}}();var d=s.extend({foldoutStyle:"foldout",foldoutPanelClass:null,initialize:function(e){"drilldown"===this.foldoutStyle&&(this.expanded=!1),this.foldoutStyle=e.foldoutStyle||this.foldoutStyle,this.foldoutPanelClass=e.foldoutPanelClass||this.foldoutPanelClass,s.prototype.initialize.call(this,e),this.foldout=this._createFoldoutPanel()},_renderDetails:function(){if("drilldown"===this.foldoutStyle)return o();var e=s.prototype._renderDetails.call(this);return this._attachFoldout(this.foldout,e)},_createFoldoutPanel:function(){var e=this.model,t=this._getFoldoutPanelClass(e),i=this._getFoldoutPanelOptions(e),n=new t(r.extend(i,{model:e}));return n},_getFoldoutPanelClass:function(){return this.foldoutPanelClass},_getFoldoutPanelOptions:function(){return{foldoutStyle:this.foldoutStyle,fxSpeed:this.fxSpeed}},_attachFoldout:function(e,t){return t=t||this.$("> .details"),this.foldout=e.render(0),e.$("> .controls").hide(),t.append(e.$el)},expand:function(){var e=this;return e._fetchModelDetails().always(function(){"foldout"===e.foldoutStyle?e._expand():"drilldown"===e.foldoutStyle&&e._expandByDrilldown()})},_expandByDrilldown:function(){var e=this;e.listenTo(e.foldout,"close",function(){e.trigger("collapsed:drilldown",e,e.foldout)}),e.trigger("expanded:drilldown",e,e.foldout)}});return d.prototype.templates=function(){var t=e.wrapTemplate(['
    ',"
    "],"collection"); +this.$el},_renderPrimaryActions:function(){return[this._renderDisplayButton()]},_renderDisplayButton:function(){var e=this.model.get("state");if(e===t.NOT_VIEWABLE||e===t.DISCARDED||!this.model.get("accessible"))return null;var n={target:this.linkTarget,classes:"display-btn"};if(this.model.get("purged"))n.disabled=!0,n.title=s("Cannot display datasets removed from disk");else if(e===t.UPLOAD)n.disabled=!0,n.title=s("This dataset must finish uploading before it can be viewed");else if(e===t.NEW)n.disabled=!0,n.title=s("This dataset is not yet viewable");else{n.title=s("View data"),n.href=this.model.urls.display;var a=this;n.onclick=function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.addDataset(a.model.get("id")),e.preventDefault())}}return n.faIcon="fa-eye",i(n)},_renderDetails:function(){if(this.model.get("state")===t.NOT_VIEWABLE)return l(this.templates.noAccess(this.model.toJSON(),this));var e=c.prototype._renderDetails.call(this);return e.find(".actions .left").empty().append(this._renderSecondaryActions()),e.find(".summary").html(this._renderSummary()).prepend(this._renderDetailMessages()),e.find(".display-applications").html(this._renderDisplayApplications()),this._setUpBehaviors(e),e},_renderSummary:function(){var e=this.model.toJSON(),t=this.templates.summaries[e.state];return(t=t||this.templates.summaries.unknown)(e,this)},_renderDetailMessages:function(){var e=this,t=l('
    '),i=e.model.toJSON();return a.each(e.templates.detailMessages,function(n){t.append(l(n(i,e)))}),t},_renderDisplayApplications:function(){return this.model.isDeletedOrPurged()?"":[this.templates.displayApplications(this.model.get("display_apps"),this),this.templates.displayApplications(this.model.get("display_types"),this)].join("")},_renderSecondaryActions:function(){switch(this.debug("_renderSecondaryActions"),this.model.get("state")){case t.NOT_VIEWABLE:return[];case t.OK:case t.FAILED_METADATA:case t.ERROR:return[this._renderDownloadButton(),this._renderShowParamsButton()]}return[this._renderShowParamsButton()]},_renderShowParamsButton:function(){return i({title:s("View details"),classes:"params-btn",href:this.model.urls.show_params,target:this.linkTarget,faIcon:"fa-info-circle",onclick:function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.add({title:"Dataset details",url:this.href}),e.preventDefault(),e.stopPropagation())}})},_renderDownloadButton:function(){return this.model.get("purged")||!this.model.hasData()?null:a.isEmpty(this.model.get("meta_files"))?l(['','',""].join("")):this._renderMetaFileDownloadButton()},_renderMetaFileDownloadButton:function(){var e=this.model.urls;return l(['"].join("\n"))},_renderNametags:function(){var e=a.template(["<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>",'<% if (tag.indexOf("name:") == 0){ %>','<%- tag.slice(5) %>',"<% } %>","<% }); %>"].join(""));return e({tags:this.model.get("tags")})},events:a.extend(a.clone(c.prototype.events),{"click .display-btn":function(e){this.trigger("display",this,e)},"click .params-btn":function(e){this.trigger("params",this,e)},"click .download-btn":function(e){this.trigger("download",this,e)}}),toString:function(){var e=this.model?this.model+"":"(no model)";return"DatasetListItemView("+e+")"}});return h.prototype.templates=function(){var e=a.extend({},c.prototype.templates.warnings,{failed_metadata:n.wrapTemplate(['<% if( model.state === "failed_metadata" ){ %>','
    ',s("An error occurred setting the metadata for this dataset"),"
    ","<% } %>"]),error:n.wrapTemplate(["<% if( model.error ){ %>",'
    ',s("There was an error getting the data for this dataset"),": <%- model.error %>","
    ","<% } %>"]),purged:n.wrapTemplate(["<% if( model.purged ){ %>",'
    ',s("This dataset has been deleted and removed from disk"),"
    ","<% } %>"]),deleted:n.wrapTemplate(["<% if( model.deleted && !model.purged ){ %>",'
    ',s("This dataset has been deleted"),"
    ","<% } %>"])}),i=n.wrapTemplate(['
    ','
    ','
    ','
    ','
    ',"
    ","<% if( !dataset.deleted && !dataset.purged ){ %>",'
    ','
    ','
    ',"<% if( dataset.peek ){ %>",'
    <%= dataset.peek %>
    ',"<% } %>","<% } %>","
    "],"dataset"),o=n.wrapTemplate(['
    ','
    ',s("You do not have permission to view this dataset"),"
    ","
    "],"dataset"),r={};r[t.OK]=r[t.FAILED_METADATA]=n.wrapTemplate(["<% if( dataset.misc_blurb ){ %>",'
    ','<%- dataset.misc_blurb %>',"
    ","<% } %>","<% if( dataset.file_ext ){ %>",'
    ','",'<%- dataset.file_ext %>',"
    ","<% } %>","<% if( dataset.metadata_dbkey ){ %>",'
    ','",'',"<%- dataset.metadata_dbkey %>","","
    ","<% } %>","<% if( dataset.misc_info ){ %>",'
    ','<%- dataset.misc_info %>',"
    ","<% } %>"],"dataset"),r[t.NEW]=n.wrapTemplate(["
    ",s("This is a new dataset and not all of its data are available yet"),"
    "],"dataset"),r[t.NOT_VIEWABLE]=n.wrapTemplate(["
    ",s("You do not have permission to view this dataset"),"
    "],"dataset"),r[t.DISCARDED]=n.wrapTemplate(["
    ",s("The job creating this dataset was cancelled before completion"),"
    "],"dataset"),r[t.QUEUED]=n.wrapTemplate(["
    ",s("This job is waiting to run"),"
    "],"dataset"),r[t.RUNNING]=n.wrapTemplate(["
    ",s("This job is currently running"),"
    "],"dataset"),r[t.UPLOAD]=n.wrapTemplate(["
    ",s("This dataset is currently uploading"),"
    "],"dataset"),r[t.SETTING_METADATA]=n.wrapTemplate(["
    ",s("Metadata is being auto-detected"),"
    "],"dataset"),r[t.PAUSED]=n.wrapTemplate(["
    ",s('This job is paused. Use the "Resume Paused Jobs" in the history menu to resume'),"
    "],"dataset"),r[t.ERROR]=n.wrapTemplate(["<% if( !dataset.purged ){ %>","
    <%- dataset.misc_blurb %>
    ","<% } %>",'',s("An error occurred with this dataset"),":",'
    <%- dataset.misc_info %>
    '],"dataset"),r[t.EMPTY]=n.wrapTemplate(["
    ",s("No data"),": <%- dataset.misc_blurb %>
    "],"dataset"),r.unknown=n.wrapTemplate(['
    Error: unknown dataset state: "<%- dataset.state %>"
    '],"dataset");var l={resubmitted:n.wrapTemplate(["<% if( model.resubmitted ){ %>",'
    ',s("The job creating this dataset has been resubmitted"),"
    ","<% } %>"])},d=n.wrapTemplate(["<% _.each( apps, function( app ){ %>",'
    ','<%- app.label %> ','',"<% _.each( app.links, function( link ){ %>",'',"<% print( _l( link.text ) ); %>"," ","<% }); %>","","
    ","<% }); %>"],"apps");return a.extend({},c.prototype.templates,{warnings:e,details:i,noAccess:o,summaries:r,detailMessages:l,displayApplications:d})}(),{DatasetListItemView:h}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(2),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(10),i(5)],s=function(e,t){var i=a.View.extend({initialize:function(e){this.model=new a.Model(e),this.url=this.model.get("url"),this.redirect=this.model.get("redirect"),this.setElement("
    "),this.render()},render:function(){var i=this;o.ajax({url:Galaxy.root+this.url,type:"GET"}).done(function(n){var s=o.extend({},i.model.attributes,n),a=new e({title:s.title,message:s.message,status:s.status||"warning",icon:s.icon,inputs:s.inputs,buttons:{submit:new t.Button({tooltip:s.submit_tooltip,title:s.submit_title||"Save settings",icon:s.submit_icon||"fa-save",cls:"btn btn-primary ui-clear-float",onclick:function(){i._submit(a)}})}});i.$el.empty().append(a.$el)}).fail(function(e){i.$el.empty().append(new t.Message({message:"Failed to load resource "+i.url+".",status:"danger",persistent:!0}).$el)})},_submit:function(e){var t=this;o.ajax({url:Galaxy.root+t.url,data:JSON.stringify(e.data.create()),type:"PUT",contentType:"application/json"}).done(function(i){var n={message:i.message,status:"success",persistent:!1};t.redirect?window.location=Galaxy.root+t.redirect+"?"+o.param(n):(e.data.matchModel(i,function(t,i){e.field_list[i].value(t.value)}),t._showMessage(e,n))}).fail(function(i){t._showMessage(e,{message:i.responseJSON.err_msg,status:"danger",persistent:!1})})},_showMessage:function(e,t){var i=e.$el.parents().filter(function(){return["auto","scroll"].indexOf(o(this).css("overflow"))!=-1}).first();i.animate({scrollTop:0},500),e.message.update(t)}});return{View:i}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1))},function(e,t,i){var n,s;(function(a){n=[i(56),i(88),i(6)],s=function(e,t,i){"use strict";function n(e){return function(t,i){return this.isNew()&&(i=i||{},i.url=this.urlRoot+this.get("history_id")+"/contents",t=t||{},t.type="dataset_collection"),e.call(this,t,i)}}var s=t.HistoryContentMixin,o=e.ListDatasetCollection,r=e.PairDatasetCollection,l=e.ListPairedDatasetCollection,d=e.ListOfListsDatasetCollection,c=o.extend(s).extend({defaults:a.extend(a.clone(o.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list",model_class:"HistoryDatasetCollectionAssociation"}),save:n(o.prototype.save),toString:function(){return"History"+o.prototype.toString.call(this)}}),h=r.extend(s).extend({defaults:a.extend(a.clone(r.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"paired",model_class:"HistoryDatasetCollectionAssociation"}),save:n(r.prototype.save),toString:function(){return"History"+r.prototype.toString.call(this)}}),u=l.extend(s).extend({defaults:a.extend(a.clone(l.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list:paired",model_class:"HistoryDatasetCollectionAssociation"}),save:n(l.prototype.save),toString:function(){return"History"+l.prototype.toString.call(this)}}),p=d.extend(s).extend({defaults:a.extend(a.clone(d.prototype.defaults),{history_content_type:"dataset_collection",collection_type:"list:list",model_class:"HistoryDatasetCollectionAssociation"}),save:n(d.prototype.save),toString:function(){return["HistoryListOfListsDatasetCollection(",this.get("name"),")"].join("")}});return{HistoryListDatasetCollection:c,HistoryPairDatasetCollection:h,HistoryListPairedDatasetCollection:u,HistoryListOfListsDatasetCollection:p}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o,r){n=[i(79),i(86),i(60),i(63),i(7),i(150)],s=function(e,t,i,n,s,l){"use strict";var d=e.PaginatedCollection,c=d.extend(s.LoggableMixin).extend({_logNamespace:"history",model:function(e,n){if("dataset"===e.history_content_type)return new t.HistoryDatasetAssociation(e,n);if("dataset_collection"===e.history_content_type){switch(e.collection_type){case"list":return new i.HistoryListDatasetCollection(e,n);case"paired":return new i.HistoryPairDatasetCollection(e,n);case"list:paired":return new i.HistoryListPairedDatasetCollection(e,n);case"list:list":return new i.HistoryListOfListsDatasetCollection(e,n)}var s="Unknown collection_type: "+e.collection_type;return console.warn(s,e),{validationError:s}}return{validationError:"Unknown history_content_type: "+e.history_content_type}},limitPerPage:500,limitPerProgressiveFetch:500,order:"hid",urlRoot:Galaxy.root+"api/histories",url:function(){return this.urlRoot+"/"+this.historyId+"/contents"},initialize:function(e,t){t=t||{},d.prototype.initialize.call(this,e,t),this.history=t.history||null,this.setHistoryId(t.historyId||null),this.includeDeleted=t.includeDeleted||this.includeDeleted,this.includeHidden=t.includeHidden||this.includeHidden,this.model.prototype.idAttribute="type_id"},setHistoryId:function(e){this.historyId=e,this._setUpWebStorage()},_setUpWebStorage:function(e){if(this.historyId)return this.storage=new n.HistoryPrefs({id:n.HistoryPrefs.historyStorageKey(this.historyId)}),this.trigger("new-storage",this.storage,this),this.on({"include-deleted":function(e){this.storage.includeDeleted(e)},"include-hidden":function(e){this.storage.includeHidden(e)}}),this.includeDeleted=this.storage.includeDeleted()||!1,this.includeHidden=this.storage.includeHidden()||!1,this},comparators:a.extend(a.clone(d.prototype.comparators),{name:s.buildComparator("name",{ascending:!0}),"name-dsc":s.buildComparator("name",{ascending:!1}),hid:s.buildComparator("hid",{ascending:!1}),"hid-asc":s.buildComparator("hid",{ascending:!0})}),running:function(){return this.filter(function(e){return!e.inReadyState()})},runningAndActive:function(){return this.filter(function(e){return!e.inReadyState()&&e.get("visible")&&!e.get("deleted")})},getByHid:function(e){return this.findWhere({hid:e})},haveDetails:function(){return this.all(function(e){return e.hasDetails()})},hidden:function(){return this.filter(function(e){return e.hidden()})},deleted:function(){return this.filter(function(e){return e.get("deleted")})},visibleAndUndeleted:function(){return this.filter(function(e){return e.get("visible")&&!e.get("deleted")})},setIncludeDeleted:function(e,t){if(a.isBoolean(e)&&e!==this.includeDeleted){if(this.includeDeleted=e,a.result(t,"silent"))return;this.trigger("include-deleted",e,this)}},setIncludeHidden:function(e,t){if(a.isBoolean(e)&&e!==this.includeHidden){if(this.includeHidden=e,t=t||{},a.result(t,"silent"))return;this.trigger("include-hidden",e,this)}},fetch:function(e){if(e=e||{},this.historyId&&!e.details){var t=n.HistoryPrefs.get(this.historyId).toJSON();a.isEmpty(t.expandedIds)||(e.details=a.values(t.expandedIds).join(","))}return d.prototype.fetch.call(this,e)},_buildFetchData:function(e){return a.extend(d.prototype._buildFetchData.call(this,e),{v:"dev"})},_fetchParams:d.prototype._fetchParams.concat(["v","details"]),_buildFetchFilters:function(e){var t=d.prototype._buildFetchFilters.call(this,e)||{},i={};return this.includeDeleted||(i.deleted=!1,i.purged=!1),this.includeHidden||(i.visible=!0),a.defaults(t,i)},getTotalItemCount:function(){return this.history.contentsShown()},fetchUpdated:function(e,t){return e&&(t=t||{filters:{}},t.remove=!1,t.filters={"update_time-ge":e.toISOString(),visible:""}),this.fetch(t)},fetchDeleted:function(e){e=e||{};var t=this;return e.filters=a.extend(e.filters,{deleted:!0,purged:void 0}),e.remove=!1,t.trigger("fetching-deleted",t),t.fetch(e).always(function(){t.trigger("fetching-deleted-done",t)})},fetchHidden:function(e){e=e||{};var t=this;return e.filters=a.extend(e.filters,{visible:!1}),e.remove=!1,t.trigger("fetching-hidden",t),t.fetch(e).always(function(){t.trigger("fetching-hidden-done",t)})},fetchAllDetails:function(e){e=e||{};var t={details:"all"};return e.data=a.extend(e.data||{},t),this.fetch(e)},fetchCollectionCounts:function(e){return e=e||{},e.keys=["type_id","element_count"].join(","),e.filters=a.extend(e.filters||{},{history_content_type:"dataset_collection"}),e.remove=!1,this.fetch(e)},_filterAndUpdate:function(e,t){var i=this,n=i.model.prototype.idAttribute,s=[t];return i.fetch({filters:e,remove:!1}).then(function(e){return e=e.reduce(function(e,t,s){var a=i.get(t[n]);return a?e.concat(a):e},[]),i.ajaxQueue("save",s,e)})},ajaxQueue:function(e,t,i){return i=i||this.models,new l.AjaxQueue(i.slice().reverse().map(function(i,n){var s=a.isString(e)?i[e]:e;return function(){return s.apply(i,t)}})).deferred},progressivelyFetchDetails:function(e){function i(t){t=t||0;var o=a.extend(a.clone(e),{view:"summary",keys:d,limit:r,offset:t,reset:0===t,remove:!1});a.defer(function(){s.fetch.call(s,o).fail(n.reject).done(function(e){n.notify(e,r,t),e.length!==r?(s.allFetched=!0,n.resolve(e,r,t)):i(t+r)})})}e=e||{};var n=o.Deferred(),s=this,r=e.limitPerCall||s.limitPerProgressiveFetch,l=t.HistoryDatasetAssociation.prototype.searchAttributes,d=l.join(",");return i(),n},isCopyable:function(e){var t=["HistoryDatasetAssociation","HistoryDatasetCollectionAssociation"];return a.isObject(e)&&e.id&&a.contains(t,e.model_class)},copy:function(e){var t,i,n;a.isString(e)?(t=e,n="hda",i="dataset"):(t=e.id,n={HistoryDatasetAssociation:"hda",LibraryDatasetDatasetAssociation:"ldda",HistoryDatasetCollectionAssociation:"hdca"}[e.model_class]||"hda",i="hdca"===n?"dataset_collection":"dataset");var s=this,r=o.ajax(this.url(),{method:"POST",contentType:"application/json",data:JSON.stringify({content:t,source:n,type:i})}).done(function(e){s.add([e],{parse:!0})}).fail(function(e,a,o){s.trigger("error",s,r,{},"Error copying contents",{type:i,id:t,source:n})});return r},createHDCA:function(e,t,i,n,s){var a=this.model({history_content_type:"dataset_collection",collection_type:t,history_id:this.historyId,name:i,hide_source_items:n||!1,element_identifiers:e});return a.save(s)},haveSearchDetails:function(){return this.allFetched&&this.all(function(e){return a.has(e.attributes,"annotation")})},matches:function(e){return this.filter(function(t){return t.matches(e)})},clone:function(){var e=r.Collection.prototype.clone.call(this);return e.historyId=this.historyId,e},toString:function(){return["HistoryContents(",[this.historyId,this.length].join(),")"].join("")}});return{HistoryContents:c}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(2))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(61),i(63),i(79),i(4),i(7),i(6)],s=function(e,t,i,n,s,d){"use strict";var c=a.Model.extend(s.LoggableMixin).extend(s.mixin(s.SearchableModelMixin,{_logNamespace:"history",UPDATE_DELAY:4e3,defaults:{model_class:"History",id:null,name:"Unnamed History",state:"new",deleted:!1,contents_active:{},contents_states:{}},urlRoot:Galaxy.root+"api/histories",contentsClass:e.HistoryContents,searchAttributes:["name","annotation","tags"],searchAliases:{title:"name",tag:"tags"},initialize:function(e,t){t=t||{},this.logger=t.logger||null,this.log(this+".initialize:",e,t),this.contents=new this.contentsClass([],{history:this,historyId:this.get("id"),order:t.order}),this._setUpListeners(),this._setUpCollectionListeners(),this.updateTimeoutId=null},_setUpListeners:function(){return this.on({error:function(e,t,i,n,s){this.clearUpdateTimeout()},"change:id":function(e,t){this.contents&&(this.contents.historyId=t)}})},_setUpCollectionListeners:function(){return this.contents?this.listenTo(this.contents,{error:function(){this.trigger.apply(this,o.makeArray(arguments))}}):this},contentsShown:function(){var e=this.get("contents_active"),t=e.active||0;return t+=this.contents.includeDeleted?e.deleted:0,t+=this.contents.includeHidden?e.hidden:0},nice_size:function(){var e=this.get("size");return e?n.bytesToString(e,!0,2):d("(empty)")},toJSON:function(){return r.extend(a.Model.prototype.toJSON.call(this),{nice_size:this.nice_size()})},get:function(e){return"nice_size"===e?this.nice_size():a.Model.prototype.get.apply(this,arguments)},ownedByCurrUser:function(){return!(!Galaxy||!Galaxy.user)&&(!Galaxy.user.isAnonymous()&&Galaxy.user.id===this.get("user_id"))},numOfUnfinishedJobs:function(){var e=this.get("non_ready_jobs");return e?e.length:0},numOfUnfinishedShownContents:function(){return this.contents.runningAndActive().length||0},_fetchContentRelatedAttributes:function(){var e=["size","non_ready_jobs","contents_active","hid_counter"];return this.fetch({data:l.param({keys:e.join(",")})})},refresh:function(e){e=e||{};var t=this,i=t.lastUpdateTime;this.contents.allFetched=!1;var n=0!==t.contents.currentPage?function(){return t.contents.fetchPage(t.contents.currentPage)}:function(){return t.contents.fetchUpdated(i)};return n().done(function(i,n,s){var a;try{a=new Date(s.getResponseHeader("Date"))}catch(e){}t.lastUpdateTime=a||new Date,t.checkForUpdates(e)})},checkForUpdates:function(e){function t(){n.clearUpdateTimeout(),n.updateTimeoutId=setTimeout(function(){n.refresh(e)},i)}e=e||{};var i=this.UPDATE_DELAY,n=this;if(n.id){var s=this.numOfUnfinishedShownContents();s>0?t():n._fetchContentRelatedAttributes().done(function(e){n.numOfUnfinishedJobs()>0?t():n.trigger("ready")})}},clearUpdateTimeout:function(){this.updateTimeoutId&&(clearTimeout(this.updateTimeoutId),this.updateTimeoutId=null)},parse:function(e,t){var i=a.Model.prototype.parse.call(this,e,t);return i.create_time&&(i.create_time=new Date(i.create_time)),i.update_time&&(i.update_time=new Date(i.update_time)),i},fetchWithContents:function(e,t){e=e||{};var i=this;return e.view="dev-detailed",this.fetch(e).then(function(e){return i.contents.history=i,i.contents.setHistoryId(e.id),i.fetchContents(t)})},fetchContents:function(e){e=e||{};var t=this;return t.lastUpdateTime=new Date,t.contents.fetchCurrentPage(e)},_delete:function(e){return this.get("deleted")?o.when():this.save({deleted:!0},e)},purge:function(e){return this.get("purged")?o.when():this.save({deleted:!0,purged:!0},e)},undelete:function(e){return this.get("deleted")?this.save({deleted:!1},e):o.when()},copy:function(e,t,i){if(e=void 0===e||e,!this.id)throw new Error("You must set the history ID before copying it.");var n={history_id:this.id};e&&(n.current=!0),t&&(n.name=t),i||(n.all_datasets=!1),n.view="dev-detailed";var s=this,a=o.post(this.urlRoot,n);return e?a.then(function(e){var t=new c(e);return t.setAsCurrent().done(function(){s.trigger("copied",s,e)})}):a.done(function(e){s.trigger("copied",s,e)})},setAsCurrent:function(){var e=this,t=o.getJSON(Galaxy.root+"history/set_as_current?id="+this.id);return t.done(function(){e.trigger("set-as-current",e)}),t},toString:function(){return"History("+this.get("id")+","+this.get("name")+")"}})),h=i.InfinitelyScrollingCollection,u=h.extend(s.LoggableMixin).extend({_logNamespace:"history",model:c,order:"update_time",limitOnFirstFetch:10,limitPerFetch:10,initialize:function(e,t){t=t||{},this.log("HistoryCollection.initialize",e,t),h.prototype.initialize.call(this,e,t),this.includeDeleted=t.includeDeleted||!1,this.currentHistoryId=t.currentHistoryId,this.setUpListeners()},urlRoot:Galaxy.root+"api/histories",url:function(){return this.urlRoot},setUpListeners:function(){return this.on({"change:deleted":function(e){this.debug("change:deleted",this.includeDeleted,e.get("deleted")),!this.includeDeleted&&e.get("deleted")&&this.remove(e)},copied:function(e,t){this.setCurrent(new c(t,[]))},"set-as-current":function(e){var t=this.currentHistoryId;this.trigger("no-longer-current",t),this.currentHistoryId=e.id}})},_buildFetchData:function(e){return r.extend(h.prototype._buildFetchData.call(this,e),{view:"dev-detailed"})},_buildFetchFilters:function(e){var t=h.prototype._buildFetchFilters.call(this,e)||{},i={};return this.includeDeleted?i.deleted=null:(i.deleted=!1,i.purged=!1),r.defaults(t,i)},fetchFirst:function(e){var t=this,i=l.when();return this.currentHistoryId&&(i=h.prototype.fetchFirst.call(t,{silent:!0,limit:1,filters:{purged:"",deleted:"","encoded_id-in":this.currentHistoryId}})),i.then(function(){return e=e||{},e.offset=0,t.fetchMore(e)})},comparators:r.extend(r.clone(h.prototype.comparators),{name:s.buildComparator("name",{ascending:!0}),"name-dsc":s.buildComparator("name",{ascending:!1}),size:s.buildComparator("size",{ascending:!1}),"size-asc":s.buildComparator("size",{ascending:!0})}),sort:function(e){e=e||{};var t=e.silent,i=this.remove(this.get(this.currentHistoryId));return h.prototype.sort.call(this,r.defaults({silent:!0},e)),this.unshift(i,{silent:!0}),t||this.trigger("sort",this,e),this},create:function(e,t,i,n){var s=this,a=o.getJSON(Galaxy.root+"history/create_new_current");return a.done(function(e){s.setCurrent(new c(e,[],i||{}))})},setCurrent:function(e,t){return t=t||{},this.unshift(e,t),this.currentHistoryId=e.get("id"),t.silent||this.trigger("new-current",e,this),this},toString:function(){return"HistoryCollection("+this.length+",current:"+this.currentHistoryId+")"}});return{History:c,HistoryCollection:u}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3),i(1))},function(e,t,i){var n,s;(function(a){n=[i(7)],s=function(e){"use strict";var t=e.SessionStorageModel.extend({defaults:{expandedIds:{},show_deleted:!1,show_hidden:!1},addExpanded:function(e){var t=this.get("expandedIds");t[e.id]=e.get("id"),this.save("expandedIds",t)},removeExpanded:function(e){var t=this.get("expandedIds");delete t[e.id],this.save("expandedIds",t)},isExpanded:function(e){return a.result(this.get("expandedIds"),e,!1)},allExpanded:function(){return a.values(this.get("expandedIds"))},clearExpanded:function(){this.set("expandedIds",{})},includeDeleted:function(e){return a.isUndefined(e)||this.set("show_deleted",e),this.get("show_deleted")},includeHidden:function(e){return a.isUndefined(e)||this.set("show_hidden",e),this.get("show_hidden")},toString:function(){return"HistoryPrefs("+this.id+")"}},{storageKeyPrefix:"history:",historyStorageKey:function(e){if(!e)throw new Error("HistoryPrefs.historyStorageKey needs valid id: "+e);return t.storageKeyPrefix+e},get:function(e){return new t({id:t.historyStorageKey(e)})},clearAll:function(e){for(var i in sessionStorage)0===i.indexOf(t.storageKeyPrefix)&&sessionStorage.removeItem(i)}});return{HistoryPrefs:t}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(7),i(6)],s=function(e,t){"use strict";var i="list",n=a.View.extend(e.LoggableMixin).extend({_logNamespace:i,initialize:function(e){this.expanded=e.expanded||!1,this.log("\t expanded:",this.expanded),this.fxSpeed=void 0!==e.fxSpeed?e.fxSpeed:this.fxSpeed},fxSpeed:"fast",render:function(e){var t=this._buildNewRender();return this._setUpBehaviors(t),this._queueNewRender(t,e),this},_buildNewRender:function(){var e=o(this.templates.el(this.model.toJSON(),this));return this.expanded&&this.$details(e).replaceWith(this._renderDetails().show()),e},_queueNewRender:function(e,t){t=void 0===t?this.fxSpeed:t;var i=this;0===t?(i._swapNewRender(e),i.trigger("rendered",i)):o(i).queue("fx",[function(e){i.$el.fadeOut(t,e)},function(t){i._swapNewRender(e),t()},function(e){i.$el.fadeIn(t,e)},function(e){i.trigger("rendered",i),e()}])},_swapNewRender:function(e){return this.$el.empty().attr("class",r.isFunction(this.className)?this.className():this.className).append(e.children())},_setUpBehaviors:function(e){e=e||this.$el,e.find("[title]").tooltip({placement:"bottom"})},$details:function(e){return e=e||this.$el,e.find("> .details")},_renderDetails:function(){var e=o(this.templates.details(this.model.toJSON(),this));return this._setUpBehaviors(e),e},toggleExpanded:function(e){return e=void 0===e?!this.expanded:e,e?this.expand():this.collapse(),this},expand:function(){var e=this;return e._fetchModelDetails().always(function(){e._expand()})},_fetchModelDetails:function(){return this.model.hasDetails()?l.when():this.model.fetch()},_expand:function(){var e=this,t=e._renderDetails();e.$details().replaceWith(t),e.expanded=!0,e.$details().slideDown(e.fxSpeed,function(){e.trigger("expanded",e)})},collapse:function(){this.debug(this+"(ExpandableView).collapse");var e=this;e.expanded=!1,this.$details().slideUp(e.fxSpeed,function(){e.trigger("collapsed",e)})}}),s=n.extend(e.mixin(e.SelectableViewMixin,e.DraggableViewMixin,{tagName:"div",className:"list-item",initialize:function(t){n.prototype.initialize.call(this,t),e.SelectableViewMixin.initialize.call(this,t),e.DraggableViewMixin.initialize.call(this,t),this._setUpListeners()},_setUpListeners:function(){return this.on("selectable",function(e){e?this.$(".primary-actions").hide():this.$(".primary-actions").show()},this),this},_buildNewRender:function(){var e=n.prototype._buildNewRender.call(this);return e.children(".warnings").replaceWith(this._renderWarnings()),e.children(".title-bar").replaceWith(this._renderTitleBar()),e.children(".primary-actions").append(this._renderPrimaryActions()),e.find("> .title-bar .subtitle").replaceWith(this._renderSubtitle()),e},_swapNewRender:function(e){return n.prototype._swapNewRender.call(this,e),this.selectable&&this.showSelector(0),this.draggable&&this.draggableOn(),this.$el},_renderWarnings:function(){var e=this,t=o('
    '),i=e.model.toJSON();return r.each(e.templates.warnings,function(n){t.append(o(n(i,e)))}),t},_renderTitleBar:function(){return o(this.templates.titleBar(this.model.toJSON(),this))},_renderPrimaryActions:function(){return[]},_renderSubtitle:function(){return o(this.templates.subtitle(this.model.toJSON(),this))},events:{"click .title-bar":"_clickTitleBar","keydown .title-bar":"_keyDownTitleBar","click .selector":"toggleSelect"},_clickTitleBar:function(e){e.stopPropagation(),e.altKey?(this.toggleSelect(e),this.selectable||this.showSelector()):this.toggleExpanded()},_keyDownTitleBar:function(e){var t=32,i=13;return!e||"keydown"!==e.type||e.keyCode!==t&&e.keyCode!==i||(this.toggleExpanded(),e.stopPropagation(),!1)},toString:function(){var e=this.model?this.model+"":"(no model)";return"ListItemView("+e+")"}}));s.prototype.templates=function(){var t=e.wrapTemplate(['
    ','
    ','
    ','',"
    ",'
    ','
    ','
    ',"
    "]),i={},n=e.wrapTemplate(['
    ','','
    ','<%- element.name %>',"
    ",'
    ',"
    "],"element"),s=e.wrapTemplate(['
    ']),a=e.wrapTemplate(['
    ']);return{el:t,warnings:i,titleBar:n,subtitle:s,details:a}}();var d=s.extend({foldoutStyle:"foldout",foldoutPanelClass:null,initialize:function(e){"drilldown"===this.foldoutStyle&&(this.expanded=!1),this.foldoutStyle=e.foldoutStyle||this.foldoutStyle,this.foldoutPanelClass=e.foldoutPanelClass||this.foldoutPanelClass,s.prototype.initialize.call(this,e),this.foldout=this._createFoldoutPanel()},_renderDetails:function(){if("drilldown"===this.foldoutStyle)return o();var e=s.prototype._renderDetails.call(this);return this._attachFoldout(this.foldout,e)},_createFoldoutPanel:function(){var e=this.model,t=this._getFoldoutPanelClass(e),i=this._getFoldoutPanelOptions(e),n=new t(r.extend(i,{model:e}));return n},_getFoldoutPanelClass:function(){return this.foldoutPanelClass},_getFoldoutPanelOptions:function(){return{foldoutStyle:this.foldoutStyle,fxSpeed:this.fxSpeed}},_attachFoldout:function(e,t){return t=t||this.$("> .details"),this.foldout=e.render(0),e.$("> .controls").hide(),t.append(e.$el)},expand:function(){var e=this;return e._fetchModelDetails().always(function(){"foldout"===e.foldoutStyle?e._expand():"drilldown"===e.foldoutStyle&&e._expandByDrilldown()})},_expandByDrilldown:function(){var e=this;e.listenTo(e.foldout,"close",function(){e.trigger("collapsed:drilldown",e,e.foldout)}),e.trigger("expanded:drilldown",e,e.foldout)}});return d.prototype.templates=function(){var t=e.wrapTemplate(['
    ',"
    "],"collection"); return r.extend({},s.prototype.templates,{details:t})}(),{ExpandableView:n,ListItemView:s,FoldoutListItemView:d}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(7),i(6)],s=function(e,t){var i=a.View.extend(e.LoggableMixin).extend(e.HiddenUntilActivatedViewMixin).extend({tagName:"div",className:"tags-display",initialize:function(e){e.usePrompt===!1?this.label="":this.label='",this.hiddenUntilActivated(e.$activator,e)},render:function(){var e=this;return this.$el.html(this._template()),this.$input().select2({placeholder:"Add tags",width:"100%",tags:function(){return e._getTagsUsed()}}),this._setUpBehaviors(),this},_hashToName:function(e){return e.startsWith("#")?"name:"+e.slice(1):e},_nameToHash:function(e){return e.startsWith("name:")&&(e="#"+e.slice(5)),e},_template:function(){return[this.label,''].join("")},tagsToCSV:function(){var e=this,t=this.model.get("tags");return!o.isArray(t)||o.isEmpty(t)?"":t.map(function(t){return o.escape(e._nameToHash(t))}).sort().join(",")},$input:function(){return this.$el.find("input.tags-input")},_getTagsUsed:function(){var e=this;return o.map(Galaxy.user.get("tags_used"),e._nameToHash)},_setUpBehaviors:function(){var e=this;this.$input().on("change",function(t){t.val=o.map(t.val,e._hashToName),e.model.save({tags:t.val}),t.added&&e._addNewTagToTagsUsed(t.added.text+"")})},_addNewTagToTagsUsed:function(e){var t=Galaxy.user.get("tags_used");o.contains(t,e)||(t.push(e),t.sort(),Galaxy.user.set("tags_used",t))},remove:function(){this.$input.off(),this.stopListening(this.model),a.View.prototype.remove.call(this)},toString:function(){return["TagsEditor(",this.model+"",")"].join("")}});return{TagsEditor:i}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3))},function(e,t,i){var n,s;(function(a,o){n=[i(3),i(27),i(16),i(44)],s=function(e,t,i,n){"use strict";var s={hidden:!1,show:function(){this.set("hidden",!1)},hide:function(){this.set("hidden",!0)},toggle:function(){this.set("hidden",!this.get("hidden"))},is_visible:function(){return!this.attributes.hidden}},r=a.Model.extend({defaults:{name:null,label:null,type:null,value:null,html:null,num_samples:5},initialize:function(e){this.attributes.html=unescape(this.attributes.html)},copy:function(){return new r(this.toJSON())},set_value:function(e){this.set("value",e||"")}}),l=a.Collection.extend({model:r}),d=r.extend({}),c=r.extend({set_value:function(e){this.set("value",parseInt(e,10))},get_samples:function(){return d3.scale.linear().domain([this.get("min"),this.get("max")]).ticks(this.get("num_samples"))}}),h=c.extend({set_value:function(e){this.set("value",parseFloat(e))}}),u=r.extend({get_samples:function(){return e.map(this.get("options"),function(e){return e[0]})}});r.subModelTypes={integer:c,float:h,data:d,select:u};var p=a.Model.extend({defaults:{id:null,name:null,description:null,target:null,inputs:[],outputs:[]},urlRoot:Galaxy.root+"api/tools",initialize:function(t){this.set("inputs",new l(e.map(t.inputs,function(e){var t=r.subModelTypes[e.type]||r;return new t(e)})))},toJSON:function(){var e=a.Model.prototype.toJSON.call(this);return e.inputs=this.get("inputs").map(function(e){return e.toJSON()}),e},remove_inputs:function(e){var t=this,i=t.get("inputs").filter(function(t){return e.indexOf(t.get("type"))!==-1});t.get("inputs").remove(i)},copy:function(e){var t=new p(this.toJSON());if(e){var i=new a.Collection;t.get("inputs").each(function(e){e.get_samples()&&i.push(e)}),t.set("inputs",i)}return t},apply_search_results:function(t){return e.indexOf(t,this.attributes.id)!==-1?this.show():this.hide(),this.is_visible()},set_input_value:function(e,t){this.get("inputs").find(function(t){return t.get("name")===e}).set("value",t)},set_input_values:function(t){var i=this;e.each(e.keys(t),function(e){i.set_input_value(e,t[e])})},run:function(){return this._run()},rerun:function(e,t){return this._run({action:"rerun",target_dataset_id:e.id,regions:t})},get_inputs_dict:function(){var e={};return this.get("inputs").each(function(t){e[t.get("name")]=t.get("value")}),e},_run:function(n){var s=e.extend({tool_id:this.id,inputs:this.get_inputs_dict()},n),a=o.Deferred(),r=new t.ServerStateDeferred({ajax_settings:{url:this.urlRoot,data:JSON.stringify(s),dataType:"json",contentType:"application/json",type:"POST"},interval:2e3,success_fn:function(e){return"pending"!==e}});return o.when(r.go()).then(function(e){a.resolve(new i.DatasetCollection(e))}),a}});e.extend(p.prototype,s);var f=(a.View.extend({}),a.Collection.extend({model:p})),g=a.Model.extend(s),m=a.Model.extend({defaults:{elems:[],open:!1},clear_search_results:function(){e.each(this.attributes.elems,function(e){e.show()}),this.show(),this.set("open",!1)},apply_search_results:function(t){var i,n=!0;e.each(this.attributes.elems,function(e){e instanceof g?(i=e,i.hide()):e instanceof p&&e.apply_search_results(t)&&(n=!1,i&&i.show())}),n?this.hide():(this.show(),this.set("open",!0))}});e.extend(m.prototype,s);var v=a.Model.extend({defaults:{search_hint_string:"search tools",min_chars_for_search:3,clear_btn_url:"",visible:!0,query:"",results:null,clear_key:27},urlRoot:Galaxy.root+"api/tools",initialize:function(){this.on("change:query",this.do_search)},do_search:function(){var e=this.attributes.query;if(e.length");e.append(E.tool_link(this.model.toJSON()));var t=this.model.get("form_style",null);if("upload1"===this.model.id)e.find("a").on("click",function(e){e.preventDefault(),Galaxy.upload.show()});else if("regular"===t){var i=this;e.find("a").on("click",function(e){e.preventDefault(),Galaxy.router.push("/",{tool_id:i.model.id,version:i.model.get("version")})})}return this.$el.append(e),this}}),b=y.extend({tagName:"div",className:"toolPanelLabel",render:function(){return this.$el.append(o("").text(this.model.attributes.text)),this}}),x=y.extend({tagName:"div",className:"toolSectionWrapper",initialize:function(){y.prototype.initialize.call(this),this.model.on("change:open",this.update_open,this)},render:function(){this.$el.append(E.panel_section(this.model.toJSON()));var t=this.$el.find(".toolSectionBody");return e.each(this.model.attributes.elems,function(e){if(e instanceof p){var i=new w({model:e,className:"toolTitle"});i.render(),t.append(i.$el)}else if(e instanceof g){var n=new b({model:e});n.render(),t.append(n.$el)}}),this},events:{"click .toolSectionTitle > a":"toggle"},toggle:function(){this.model.set("open",!this.model.attributes.open)},update_open:function(){this.model.attributes.open?this.$el.children(".toolSectionBody").slideDown("fast"):this.$el.children(".toolSectionBody").slideUp("fast")}}),C=a.View.extend({tagName:"div",id:"tool-search",className:"bar",events:{click:"focus_and_select","keyup :input":"query_changed","change :input":"query_changed","click #search-clear-btn":"clear"},render:function(){return this.$el.append(E.tool_search(this.model.toJSON())),this.model.is_visible()||this.$el.hide(),o("#messagebox").is(":visible")&&this.$el.css("top","95px"),this.$el.find("[title]").tooltip(),this},focus_and_select:function(){this.$el.find(":input").focus().select()},clear:function(){return this.model.clear_search(),this.$el.find(":input").val(""),this.focus_and_select(),!1},query_changed:function(e){return this.model.attributes.clear_key&&this.model.attributes.clear_key===e.which?(this.clear(),!1):void this.model.set("query",this.$el.find(":input").val())}}),$=a.View.extend({tagName:"div",className:"toolMenu",initialize:function(){this.model.get("tool_search").on("change:results",this.handle_search_results,this)},render:function(){var e=this,t=new C({model:this.model.get("tool_search")});return t.render(),e.$el.append(t.$el),this.model.get("layout").each(function(t){if(t instanceof m){var i=new x({model:t});i.render(),e.$el.append(i.$el)}else if(t instanceof p){var n=new w({model:t,className:"toolTitleNoSection"});n.render(),e.$el.append(n.$el)}else if(t instanceof g){var s=new b({model:t});s.render(),e.$el.append(s.$el)}}),e.$el.find("a.tool-link").click(function(t){var i=o(this).attr("class").split(/\s+/)[0],n=e.model.get("tools").get(i);e.trigger("tool_link_click",t,n)}),this},handle_search_results:function(){var e=this.model.get("tool_search").get("results");e&&0===e.length?o("#search-no-results").show():o("#search-no-results").hide()}}),k=a.View.extend({className:"toolForm",render:function(){this.$el.children().remove(),this.$el.append(E.tool_form(this.model.toJSON()))}}),E=(a.View.extend({className:"toolMenuAndView",initialize:function(){this.tool_panel_view=new $({collection:this.collection}),this.tool_form_view=new k},render:function(){this.tool_panel_view.render(),this.tool_panel_view.$el.css("float","left"),this.$el.append(this.tool_panel_view.$el),this.tool_form_view.$el.hide(),this.$el.append(this.tool_form_view.$el);var e=this;this.tool_panel_view.on("tool_link_click",function(t,i){t.preventDefault(),e.show_tool(i)})},show_tool:function(e){var t=this;e.fetch().done(function(){t.tool_form_view.model=e,t.tool_form_view.render(),t.tool_form_view.$el.show(),o("#left").width("650px")})}}),{tool_search:e.template(['',' ',''].join("")),panel_section:e.template(['",'
    "},_templateTable:function(){return'Available files:   
    '+r.escape(t.path)+''+e.bytesToString(t.size)+''+t.ctime+"
    NameSizeCreated
    '},_templateInfo:function(){return'
    Your FTP directory does not contain any files.
    '},_template:function(){return'
    This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at '+this.options.ftp_upload_site+' using your Galaxy credentials (email address and password).
    '}})}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3))},function(e,t,i){var n,s;(function(a,o,r){n=[i(4)],s=function(e){return a.View.extend({options:{class_check:"fa-check-square-o",class_uncheck:"fa-square-o",parameters:[{id:"space_to_tab",title:"Convert spaces to tabs"},{id:"to_posix_lines",title:"Use POSIX standard"}]},initialize:function(e){this.model=e.model,this.setElement(o("
    ").addClass("upload-settings")),this.$el.append(o("
    ").addClass("upload-settings-cover")),this.$el.append(o("").addClass("upload-settings-table ui-table-striped").append("")),this.$cover=this.$(".upload-settings-cover"),this.$table=this.$(".upload-settings-table > tbody"),this.listenTo(this.model,"change",this.render,this),this.model.trigger("change")},render:function(){var e=this;this.$table.empty(),r.each(this.options.parameters,function(t){var i=o("
    ").addClass("upload-"+t.id+" upload-icon-button fa").addClass(e.model.get(t.id)&&e.options.class_check||e.options.class_uncheck).on("click",function(){e.model.get("enabled")&&e.model.set(t.id,!e.model.get(t.id))});e.$table.append(o("
    ").append(o("")}),t.append(n)}else t.append("No "+this.model.get("plural").toLowerCase()+" have been shared with you.");return t}});return{View:t}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3))},function(e,t,i){var n,s;(function(a,o){n=[i(82),i(85),i(7),i(6)],s=function(e,t,i,n){"use strict";var s=e.DatasetListItemEdit,r=s.extend({className:s.prototype.className+" history-content",_fetchModelDetails:function(){var e=this;return e.model.inReadyState()&&!e.model.hasDetails()?e.model.fetch({silent:!0}):e.model.has("rerunnable")?a.when():e.model.fetch({silent:!0,data:{keys:["rerunnable","creating_job"].join(",")}})},events:o.extend(o.clone(s.prototype.events),{"click .unhide-link":function(e){return this.model.unhide(),!1}}),toString:function(){var e=this.model?this.model+"":"(no model)";return"HDAListItemEdit("+e+")"}});return r.prototype.templates=function(){var e=o.extend({},s.prototype.templates.warnings,{hidden:i.wrapTemplate(["<% if( !dataset.visible ){ %>",'
    ',n("This dataset has been hidden"),'
    ',n("Unhide it"),"","
    ","<% } %>"],"dataset")});return o.extend({},s.prototype.templates,{titleBar:t.HDAListItemView.prototype.templates.titleBar,warnings:e})}(),{HDAListItemEdit:r}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1),i(3))},function(e,t,i){var n,s;n=[i(87),i(120),i(25),i(6)],s=function(e,t,i,n){"use strict";var s=e.HDCAListItemView,a=s.extend({_getFoldoutPanelClass:function(){switch(this.model.get("collection_type")){case"list":return t.ListCollectionViewEdit;case"paired":return t.PairCollectionViewEdit;case"list:paired":return t.ListOfPairsCollectionViewEdit;case"list:list":return t.ListOfListsCollectionViewEdit}throw new TypeError("Uknown collection_type: "+this.model.get("collection_type"))},_renderPrimaryActions:function(){return this.log(this+"._renderPrimaryActions"),s.prototype._renderPrimaryActions.call(this).concat([this._renderDeleteButton()])},_renderDeleteButton:function(){var e=this,t=this.model.get("deleted");return i({title:n(t?"Dataset collection is already deleted":"Delete"),classes:"delete-btn",faIcon:"fa-times",disabled:t,onclick:function(){e.$el.find(".icon-btn.delete-btn").trigger("mouseout"),e.model.delete()}})},toString:function(){var e=this.model?this.model+"":"(no model)";return"HDCAListItemEdit("+e+")"}});return{HDCAListItemEdit:a}}.apply(t,n),!(void 0!==s&&(e.exports=s))},function(e,t,i){var n,s;(function(a,o,r){n=[i(4),i(12),i(62),i(84)],s=function(e,t,i,n){var s=a.View.extend({initialize:function(t){var i=this;this.setElement(o("
    ")),this.model=new a.Model,e.get({url:Galaxy.root+"history/"+t.action_id,success:function(e){e.dict_format=!0,r.each(e.operations,function(e){"Copy"==e.label&&(e.onclick=function(e){i._showCopyDialog(e)})}),i.model.set(e),i.render()}})},render:function(){var e=new t(this.model.attributes);this.$el.empty().append(e.$el)},_showCopyDialog:function(e){var t=new i.History({id:e});t.fetch().fail(function(){alert("History could not be fetched. Please contact an administrator")}).done(function(){n(t,{}).done(function(){window.parent&&window.parent.Galaxy&&window.parent.Galaxy.currHistoryPanel&&window.parent.Galaxy.currHistoryPanel.loadCurrentHistory(),window.location.reload(!0)})})}});return{View:s}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3))},function(e,t,i){var n,s;(function(a,o,r){n=[i(62),i(129),i(7),i(6)],s=function(e,t,i,n){"use strict";var s=i.SessionStorageModel.extend({defaults:{tagsEditorShown:!1,annotationEditorShown:!1,scrollPosition:0},toString:function(){return"HistoryViewPrefs("+JSON.stringify(this.toJSON())+")"}});s.storageKey=function(){return"history-panel"};var l=t.HistoryViewEdit,d=l.extend({className:l.prototype.className+" current-history-panel",HDCAViewClass:l.prototype.HDCAViewClass.extend({foldoutStyle:"drilldown"}),emptyMsg:[n("This history is empty"),". ",n("You can "),'',n("load your own data"),"",n(" or "),'',n("get data from an external source"),""].join(""),initialize:function(e){e=e||{},this.preferences=new s(a.extend({id:s.storageKey()},a.pick(e,a.keys(s.prototype.defaults)))),l.prototype.initialize.call(this,e),this.panelStack=[],this.currentContentId=e.currentContentId||null},_setUpListeners:function(){l.prototype._setUpListeners.call(this);var e=this;this.on("new-model",function(){e.preferences.set("scrollPosition",0)})},loadCurrentHistory:function(){return this.loadHistory(null,{url:Galaxy.root+"history/current_history_json"})},switchToHistory:function(e,t){return Galaxy.user.isAnonymous()?(this.trigger("error",n("You must be logged in to switch histories"),n("Anonymous user")),o.when()):this.loadHistory(e,{url:Galaxy.root+"history/set_as_current?id="+e})},createNewHistory:function(e){return Galaxy.user.isAnonymous()?(this.trigger("error",n("You must be logged in to create histories"),n("Anonymous user")),o.when()):this.loadHistory(null,{url:Galaxy.root+"history/create_new_current"})},setModel:function(e,t,i){return l.prototype.setModel.call(this,e,t,i),this.model&&this.model.id&&(this.log("checking for updates"),this.model.checkForUpdates()),this},_setUpModelListeners:function(){return l.prototype._setUpModelListeners.call(this), -this.listenTo(this.model,{"change:nice_size change:size":function(){this.trigger("history-size-change",this,this.model,arguments)},"change:id":function(){this.once("loading-done",function(){this.model.checkForUpdates()})}})},_setUpCollectionListeners:function(){l.prototype._setUpCollectionListeners.call(this),this.listenTo(this.collection,"state:ready",function(e,t,i){e.get("visible")||this.collection.storage.includeHidden()||this.removeItemView(e)})},_setUpBehaviors:function(e){e=e||this.$el;var t=this;return l.prototype._setUpBehaviors.call(t,e),this._debouncedScrollCaptureHandler||(this._debouncedScrollCaptureHandler=a.debounce(function(){t.$el.is(":visible")&&t.preferences.set("scrollPosition",o(this).scrollTop())},40)),t.$scrollContainer(e).off("scroll",this._debouncedScrollCaptureHandler).on("scroll",this._debouncedScrollCaptureHandler),t},_buildNewRender:function(){if(!this.model)return o();var e=l.prototype._buildNewRender.call(this);return e.find(".search").prependTo(e.find("> .controls")),this._renderQuotaMessage(e),e},_renderQuotaMessage:function(e){return e=e||this.$el,o(this.templates.quotaMsg({},this)).prependTo(e.find(".messages"))},_renderTags:function(e){var t=this;l.prototype._renderTags.call(t,e),t.preferences.get("tagsEditorShown")&&t.tagsEditor.toggle(!0),t.listenTo(t.tagsEditor,"hiddenUntilActivated:shown hiddenUntilActivated:hidden",function(e){t.preferences.set("tagsEditorShown",e.hidden)})},_renderAnnotation:function(e){var t=this;l.prototype._renderAnnotation.call(t,e),t.preferences.get("annotationEditorShown")&&t.annotationEditor.toggle(!0),t.listenTo(t.annotationEditor,"hiddenUntilActivated:shown hiddenUntilActivated:hidden",function(e){t.preferences.set("annotationEditorShown",e.hidden)})},_swapNewRender:function(e){l.prototype._swapNewRender.call(this,e);var t=this;return a.delay(function(){var e=t.preferences.get("scrollPosition");e&&t.scrollTo(e,0)},10),this},_attachItems:function(e){l.prototype._attachItems.call(this,e);var t=this;return t.currentContentId&&t._setCurrentContentById(t.currentContentId),this},addItemView:function(e,t,i){var n=l.prototype.addItemView.call(this,e,t,i);return n&&this.panelStack.length?this._collapseDrilldownPanel():n},_setUpItemViewListeners:function(e){var t=this;return l.prototype._setUpItemViewListeners.call(t,e),t.listenTo(e,{"expanded:drilldown":function(e,t){this._expandDrilldownPanel(t)},"collapsed:drilldown":function(e,t){this._collapseDrilldownPanel(t)}})},setCurrentContent:function(e){this.$(".history-content.current-content").removeClass("current-content"),e?(e.$el.addClass("current-content"),this.currentContentId=e.model.id):this.currentContentId=null},_setCurrentContentById:function(e){var t=this.viewFromModelId(e)||null;this.setCurrentContent(t)},_expandDrilldownPanel:function(e){this.panelStack.push(e),this.$controls().add(this.$list()).hide(),e.parentName=this.model.get("name"),e.delegateEvents().render().$el.appendTo(this.$el)},_collapseDrilldownPanel:function(e){this.panelStack.pop(),this.$controls().add(this.$list()).show()},events:a.extend(a.clone(l.prototype.events),{"click .uploader-link":function(e){Galaxy.upload.show(e)},"click .get-data-link":function(e){var t=o(".toolMenuContainer");t.parent().scrollTop(0),t.find('span:contains("Get Data")').click()}}),listenToGalaxy:function(e){this.listenTo(e,{"center-frame:load":function(e){var t=e.fullpath,i=null,n={display:/datasets\/([a-f0-9]+)\/display/,edit:/datasets\/([a-f0-9]+)\/edit/,report_error:/dataset\/errors\?id=([a-f0-9]+)/,rerun:/tool_runner\/rerun\?id=([a-f0-9]+)/,show_params:/datasets\/([a-f0-9]+)\/show_params/};a.find(n,function(e,n){return i=a.result(t.match(e),1)}),this._setCurrentContentById(i?"dataset-"+i:null)},"center-panel:load":function(e){this._setCurrentContentById()}})},connectToQuotaMeter:function(e){return e?(this.listenTo(e,"quota:over",this.showQuotaMessage),this.listenTo(e,"quota:under",this.hideQuotaMessage),this.on("rendered rendered:initial",function(){e&&e.isOverQuota()&&this.showQuotaMessage()}),this):this},clearMessages:function(e){var t=a.isUndefined(e)?this.$messages().children('[class$="message"]'):o(e.currentTarget);return t=t.not(".quota-message"),t.fadeOut(this.fxSpeed,function(){o(this).remove()}),this},showQuotaMessage:function(){var e=this.$(".quota-message");e.is(":hidden")&&e.slideDown(this.fxSpeed)},hideQuotaMessage:function(){var e=this.$(".quota-message");e.is(":hidden")||e.slideUp(this.fxSpeed)},unhideHidden:function(){var e=this;return confirm(n("Really unhide all hidden datasets?"))?e.model.contents._filterAndUpdate({visible:!1,deleted:"",purged:""},{visible:!0}).done(function(){e.model.contents.includeHidden||e.renderItems()}):r.when()},deleteHidden:function(){var e=this;return confirm(n("Really delete all hidden datasets?"))?e.model.contents._filterAndUpdate({visible:!1,deleted:"",purged:""},{deleted:!0,visible:!0}):r.when()},toString:function(){return"CurrentHistoryView("+(this.model?this.model.get("name"):"")+")"}});return d.prototype.templates=function(){var e=i.wrapTemplate(['
    ',n("You are over your disk quota"),". ",n("Tool execution is on hold until your disk usage drops below your allocated quota"),".","
    "],"history");return a.extend(a.clone(l.prototype.templates),{quotaMsg:e})}(),{CurrentHistoryView:d}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(130),i(61),i(17),i(86),i(125),i(126),i(65),i(78),i(57),i(122),i(121),i(25),i(18),i(7),i(6),i(24)],s=function(e,t,i,n,s,l,d,c,h,u,p,f,g,m,v){"use strict";var _=e.HistoryView,y=_.extend({HDAViewClass:s.HDAListItemEdit,HDCAViewClass:l.HDCAListItemEdit,initialize:function(e){e=e||{},_.prototype.initialize.call(this,e),this.tagsEditor=null,this.dragItems=!0,this.annotationEditor=null,this.purgeAllowed=e.purgeAllowed||!1,this.annotationEditorShown=e.annotationEditorShown||!1,this.tagsEditorShown=e.tagsEditorShown||!1},_setUpListeners:function(){return _.prototype._setUpListeners.call(this),this.on({"droptarget:drop":function(e,t){this.dataDropped(t),this.dropTargetOff()},"view:attached view:removed":function(){this._renderCounts()},"search:loading-progress":this._renderSearchProgress,"search:searching":this._renderSearchFindings})},_setUpModelListeners:function(){return _.prototype._setUpModelListeners.call(this),this.listenTo(this.model,"change:size",this.updateHistoryDiskSize),this},_setUpCollectionListeners:function(){return _.prototype._setUpCollectionListeners.call(this),this.listenTo(this.collection,{"change:deleted":this._handleItemDeletedChange,"change:visible":this._handleItemVisibleChange,"change:purged":function(e){this.model.fetch()},"fetching-deleted":function(e){this.$("> .controls .deleted-count").html(""+v("loading...")+"")},"fetching-hidden":function(e){this.$("> .controls .hidden-count").html(""+v("loading...")+"")},"fetching-deleted-done fetching-hidden-done":this._renderCounts}),this},_buildNewRender:function(){var e=_.prototype._buildNewRender.call(this);return this.model?(Galaxy&&Galaxy.user&&Galaxy.user.id&&Galaxy.user.id===this.model.get("user_id")&&(this._renderTags(e),this._renderAnnotation(e)),e):e},updateHistoryDiskSize:function(){this.$(".history-size").text(this.model.get("nice_size"))},renderItems:function(e){var t=_.prototype.renderItems.call(this,e);return this.searchFor||this._renderCounts(e),t},_renderCounts:function(e){e=e instanceof a?e:this.$el;var t=this.templates.counts(this.model.toJSON(),this);return e.find("> .controls .subtitle").html(t)},_renderTags:function(e){var t=this;this.tagsEditor=new d.TagsEditor({model:this.model,el:e.find(".controls .tags-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.toggleHDATagEditors(!0,t.fxSpeed)},onhide:function(){t.toggleHDATagEditors(!1,t.fxSpeed)},$activator:f({title:v("Edit history tags"),classes:"history-tag-btn",faIcon:"fa-tags"}).appendTo(e.find(".controls .actions"))})},_renderAnnotation:function(e){var t=this;this.annotationEditor=new c.AnnotationEditor({model:this.model,el:e.find(".controls .annotation-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.toggleHDAAnnotationEditors(!0,t.fxSpeed)},onhide:function(){t.toggleHDAAnnotationEditors(!1,t.fxSpeed)},$activator:f({title:v("Edit history annotation"),classes:"history-annotate-btn",faIcon:"fa-comment"}).appendTo(e.find(".controls .actions"))})},_setUpBehaviors:function(e){if(e=e||this.$el,_.prototype._setUpBehaviors.call(this,e),this.model&&Galaxy.user&&!Galaxy.user.isAnonymous()&&Galaxy.user.id===this.model.get("user_id")){var t=this,i="> .controls .name";e.find(i).attr("title",v("Click to rename history")).tooltip({placement:"bottom"}).make_text_editable({on_finish:function(e){var n=t.model.get("name");e&&e!==n?(t.$el.find(i).text(e),t.model.save({name:e}).fail(function(){t.$el.find(i).text(t.model.previous("name"))})):t.$el.find(i).text(n)}})}},multiselectActions:function(){var e=this,t=[{html:v("Hide datasets"),func:function(){var t=n.HistoryDatasetAssociation.prototype.hide;e.getSelectedModels().ajaxQueue(t)}},{html:v("Unhide datasets"),func:function(){var t=n.HistoryDatasetAssociation.prototype.unhide;e.getSelectedModels().ajaxQueue(t)}},{html:v("Delete datasets"),func:function(){var t=n.HistoryDatasetAssociation.prototype.delete;e.getSelectedModels().ajaxQueue(t)}},{html:v("Undelete datasets"),func:function(){var t=n.HistoryDatasetAssociation.prototype.undelete;e.getSelectedModels().ajaxQueue(t)}}];return e.purgeAllowed&&t.push({html:v("Permanently delete datasets"),func:function(){if(confirm(v("This will permanently remove the data in your datasets. Are you sure?"))){var t=n.HistoryDatasetAssociation.prototype.purge;e.getSelectedModels().ajaxQueue(t)}}}),t=t.concat(e._collectionActions())},_collectionActions:function(){var e=this;return[{html:v("Build Dataset List"),func:function(){e.buildCollection("list")}},{html:v("Build Dataset Pair"),func:function(){e.buildCollection("paired")}},{html:v("Build List of Dataset Pairs"),func:function(){e.buildCollection("list:paired")}}]},buildCollection:function(e,t,i){var n,s=this,t=t||s.getSelectedModels(),i=i||!1;"list"==e?n=h.createListCollection:"paired"==e?n=u.createPairCollection:"list:paired"==e?n=p.createListOfPairsCollection:console.warn("Unknown collectionType encountered "+e),n(t,i).done(function(){s.model.refresh()})},_getItemViewOptions:function(e){var t=_.prototype._getItemViewOptions.call(this,e);return o.extend(t,{purgeAllowed:this.purgeAllowed,tagsEditorShown:this.tagsEditor&&!this.tagsEditor.hidden,annotationEditorShown:this.annotationEditor&&!this.annotationEditor.hidden}),t},_handleItemDeletedChange:function(e){e.get("deleted")?this._handleItemDeletion(e):this._handleItemUndeletion(e),this._renderCounts()},_handleItemDeletion:function(e){var t=this.model.get("contents_active");t.deleted+=1,t.active-=1,this.model.contents.includeDeleted||this.removeItemView(e),this.model.set("contents_active",t)},_handleItemUndeletion:function(e){var t=this.model.get("contents_active");t.deleted-=1,this.model.contents.includeDeleted||(t.active-=1),this.model.set("contents_active",t)},_handleItemVisibleChange:function(e){e.hidden()?this._handleItemHidden(e):this._handleItemUnhidden(e),this._renderCounts()},_handleItemHidden:function(e){var t=this.model.get("contents_active");t.hidden+=1,t.active-=1,this.model.contents.includeHidden||this.removeItemView(e),this.model.set("contents_active",t)},_handleItemUnhidden:function(e){var t=this.model.get("contents_active");t.hidden-=1,this.model.contents.includeHidden||(t.active-=1),this.model.set("contents_active",t)},toggleHDATagEditors:function(e,t){o.each(this.views,function(i){i.tagsEditor&&i.tagsEditor.toggle(e,t)})},toggleHDAAnnotationEditors:function(e,t){o.each(this.views,function(i){i.annotationEditor&&i.annotationEditor.toggle(e,t)})},events:o.extend(o.clone(_.prototype.events),{"click .show-selectors-btn":"toggleSelectors","click .toggle-deleted-link":function(e){this.toggleShowDeleted()},"click .toggle-hidden-link":function(e){this.toggleShowHidden()}}),_renderSearchProgress:function(e,t){var i=e+t;return this.$("> .controls .subtitle").html(["",v("Searching "),i,"/",this.model.contentsShown(),""].join(""))},_renderSearchFindings:function(){return this.$("> .controls .subtitle").html([v("Found"),this.views.length].join(" ")),this},dropTargetOn:function(){if(this.dropTarget)return this;this.dropTarget=!0;var e={dragenter:o.bind(this.dragenter,this),dragover:o.bind(this.dragover,this),dragleave:o.bind(this.dragleave,this),drop:o.bind(this.drop,this)},t=this._renderDropTarget();this.$list().before([this._renderDropTargetHelp(),t]);for(var i in e)e.hasOwnProperty(i)&&t.on(i,e[i]);return this},_renderDropTarget:function(){return this.$(".history-drop-target").remove(),r("
    ").addClass("history-drop-target")},_renderDropTargetHelp:function(){return this.$(".history-drop-target-help").remove(),r("
    ").addClass("history-drop-target-help").text(v("Drag datasets here to copy them to the current history"))},dropTargetOff:function(){if(!this.dropTarget)return this;this.dropTarget=!1;var e=this.$(".history-drop-target").get(0);for(var t in this._dropHandlers)this._dropHandlers.hasOwnProperty(t)&&e.off(t,this._dropHandlers[t]);return this.$(".history-drop-target").remove(),this.$(".history-drop-target-help").remove(),this},dropTargetToggle:function(){return this.dropTarget?this.dropTargetOff():this.dropTargetOn(),this},dragenter:function(e){e.preventDefault(),e.stopPropagation(),this.$(".history-drop-target").css("border","2px solid black")},dragover:function(e){e.preventDefault(),e.stopPropagation()},dragleave:function(e){e.preventDefault(),e.stopPropagation(),this.$(".history-drop-target").css("border","1px dashed black")},drop:function(e){e.preventDefault();var t=this,i=e.originalEvent.dataTransfer,n=i.getData("text");i.dropEffect="move";try{n=JSON.parse(n)}catch(e){t.warn("error parsing JSON from drop:",n)}return t.trigger("droptarget:drop",e,n,t),!1},dataDropped:function(e){var t=this;return o.isObject(e)&&"HistoryDatasetAssociation"===e.model_class&&e.id?0!==t.contents.currentPage?t.contents.fetchPage(0).then(function(){return t.model.contents.copy(e.id)}):t.model.contents.copy(e.id):a.when()},toString:function(){return"HistoryViewEdit("+(this.model?this.model.get("name"):"")+")"}});return y.prototype.templates=function(){var e=m.wrapTemplate(["<% var shown = Math.max( view.views.length, history.contents_active.active ) %>","<% if( shown ){ %>",'',"<%- shown %> ",v("shown"),"","<% } %>","<% if( history.contents_active.deleted ){ %>",'',"<% if( view.model.contents.includeDeleted ){ %>",'',v("hide deleted"),"","<% } else { %>","<%- history.contents_active.deleted %> ",'',v("deleted"),"","<% } %>","","<% } %>","<% if( history.contents_active.hidden ){ %>",'',"<% if( view.model.contents.includeHidden ){ %>",'',v("hide hidden"),"","<% } else { %>","<%- history.contents_active.hidden %> ",'',v("hidden"),"","<% } %>","","<% } %>"],"history");return o.extend(o.clone(_.prototype.templates),{counts:e})}(),{HistoryViewEdit:y}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1),i(3),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(89),i(62),i(61),i(63),i(85),i(87),i(93),i(92),i(25),i(7),i(6),i(96)],s=function(e,t,i,n,s,r,l,d,c,h,u){"use strict";var p=e.ModelListPanel,f=p.extend({_logNamespace:"history",HDAViewClass:s.HDAListItemView,HDCAViewClass:r.HDCAListItemView,collectionClass:i.HistoryContents,modelCollectionKey:"contents",tagName:"div",className:p.prototype.className+" history-panel",emptyMsg:u("This history is empty"),noneFoundMsg:u("No matching datasets found"),searchPlaceholder:u("search datasets"),FETCH_COLLECTION_COUNTS_DELAY:2e3,initialize:function(e){p.prototype.initialize.call(this,e),this.linkTarget=e.linkTarget||"_blank"},_createDefaultCollection:function(){return new this.collectionClass([],{history:this.model})},freeModel:function(){return p.prototype.freeModel.call(this),this.model&&this.model.clearUpdateTimeout(),this},_setUpListeners:function(){p.prototype._setUpListeners.call(this),this.on({error:function(e,t,i,n,s){this.errorHandler(e,t,i,n,s)},"loading-done":function(){var e=this;a.delay(function(){e.model.contents.fetchCollectionCounts()},e.FETCH_COLLECTION_COUNTS_DELAY)},"views:ready view:attached view:removed":function(e){this._renderSelectButton()},"view:attached":function(e){this.scrollTo(0)}})},loadHistory:function(e,i,n){n=a.extend(n||{silent:!0}),this.info("loadHistory:",e,i,n);var s=this;return s.setModel(new t.History({id:e})),n.silent=!0,s.trigger("loading"),s.model.fetchWithContents(i,n).always(function(){s.render(),s.trigger("loading-done")})},refreshContents:function(e){return this.model?this.model.refresh(e):o.when()},_setUpCollectionListeners:function(){return p.prototype._setUpCollectionListeners.call(this),this.listenTo(this.collection,{"fetching-more":function(){this._toggleContentsLoadingIndicator(!0),this.$emptyMessage().hide()},"fetching-more-done":function(){this._toggleContentsLoadingIndicator(!1)}})},_showLoadingIndicator:function(e,t,i){var n=o('
    ');this.$el.html(n.text(e).slideDown(a.isUndefined(t)?this.fxSpeed:t))},_hideLoadingIndicator:function(e){this.$(".loading-indicator").slideUp(a.isUndefined(e)?this.fxSpeed+200:e,function(){o(this).remove()})},_buildNewRender:function(){var e=p.prototype._buildNewRender.call(this);return this._renderSelectButton(e),e},_renderSelectButton:function(e){if(e=e||this.$el,!this.multiselectActions().length)return null;if(!this.views.length)return this.hideSelectors(),e.find(".controls .actions .show-selectors-btn").remove(),null;var t=e.find(".controls .actions .show-selectors-btn");return t.length?t:c({title:u("Operations on multiple datasets"),classes:"show-selectors-btn",faIcon:"fa-check-square-o"}).prependTo(e.find(".controls .actions"))},_renderEmptyMessage:function(e){var t=this,i=t.$emptyMessage(e),n=t.model.get("contents_active").active<=0;return n?i.empty().append(t.emptyMsg).show():t.searchFor&&t.model.contents.haveSearchDetails()&&!t.views.length?i.empty().append(t.noneFoundMsg).show():(i.hide(),o())},$scrollContainer:function(e){return this.$list(e)},_toggleContentsLoadingIndicator:function(e){e?this.$list().html('
    '):this.$list().find(".contents-loading-indicator").remove()},renderItems:function(e){e=e||this.$el;var t=this,i=t.$list(e);o(".tooltip").remove(),i.empty(),t.views=[];var n=t._filterCollection();return n.length?(t._renderPagination(e),t.views=t._renderSomeItems(n,i)):e.find("> .controls .list-pagination").empty(),t._renderEmptyMessage(e).toggle(!n.length),t.trigger("views:ready",t.views),t.views},_renderPagination:function(e){var t=e.find("> .controls .list-pagination");return this.searchFor||!this.model.contents.shouldPaginate()?t.empty():(t.html(this.templates.pagination({current:this.model.contents.currentPage+1,last:this.model.contents.getLastPage()+1},this)),t.find("select.pages").tooltip(),t)},_renderSomeItems:function(e,t){var i=this,n=[];return t.append(e.map(function(e){var t=i._createItemView(e);return n.push(t),i._renderItemView$el(t)})),n},_filterItem:function(e){var t=this,i=t.model.contents;return(i.includeHidden||!e.hidden())&&(i.includeDeleted||!e.isDeletedOrPurged())&&p.prototype._filterItem.call(t,e)},_getItemViewClass:function(e){var t=e.get("history_content_type");switch(t){case"dataset":return this.HDAViewClass;case"dataset_collection":return this.HDCAViewClass}throw new TypeError("Unknown history_content_type: "+t)},_getItemViewOptions:function(e){var t=p.prototype._getItemViewOptions.call(this,e);return a.extend(t,{linkTarget:this.linkTarget,expanded:this.model.contents.storage.isExpanded(e.id),hasUser:this.model.ownedByCurrUser()})},_setUpItemViewListeners:function(e){var t=this;return p.prototype._setUpItemViewListeners.call(t,e),t.listenTo(e,{expanded:function(e){t.model.contents.storage.addExpanded(e.model)},collapsed:function(e){t.model.contents.storage.removeExpanded(e.model)}})},collapseAll:function(){this.model.contents.storage.clearExpanded(),p.prototype.collapseAll.call(this)},getSelectedModels:function(){var e=p.prototype.getSelectedModels.call(this);return e.historyId=this.collection.historyId,e},events:a.extend(a.clone(p.prototype.events),{"click .show-selectors-btn":"toggleSelectors","click > .controls .prev":"_clickPrevPage","click > .controls .next":"_clickNextPage","change > .controls .pages":"_changePageSelect","click .messages [class$=message]":"clearMessages"}),_clickPrevPage:function(e){this.model.clearUpdateTimeout(),this.model.contents.fetchPrevPage()},_clickNextPage:function(e){this.model.clearUpdateTimeout(),this.model.contents.fetchNextPage()},_changePageSelect:function(e){this.model.clearUpdateTimeout();var t=o(e.currentTarget).val();this.model.contents.fetchPage(t)},toggleShowDeleted:function(e,t){e=void 0!==e?e:!this.model.contents.includeDeleted;var i=this,n=i.model.contents;return n.setIncludeDeleted(e,t),i.trigger("show-deleted",e),n.fetchCurrentPage({renderAll:!0}),e},toggleShowHidden:function(e,t,i){e=void 0!==e?e:!this.model.contents.includeHidden;var n=this,s=n.model.contents;return s.setIncludeHidden(e,i),n.trigger("show-hidden",e),s.fetchCurrentPage({renderAll:!0}),e},_firstSearch:function(e){var t=this,i="> .controls .search-input";if(this.log("onFirstSearch",e),t.model.contents.haveSearchDetails())return void t.searchItems(e);t.$(i).searchInput("toggle-loading"),t.searchFor=e;t.model.contents.progressivelyFetchDetails({silent:!0}).progress(function(e,i,n){t.renderItems(),t.trigger("search:loading-progress",i,n)}).always(function(){t.$el.find(i).searchInput("toggle-loading")}).done(function(){t.searchItems(e,"force")})},clearSearch:function(e){var t=this;return t.searchFor?(t.searchFor="",t.trigger("search:clear",t),t.$("> .controls .search-query").val(""),t.model.contents.fetchCurrentPage({silent:!0}).done(function(){t.renderItems()}),t):t},errorHandler:function(e,t,i){if(!t||0!==t.status||0!==t.readyState){if(this.error(e,t,i),a.isString(e)&&a.isString(t)){var n=e,s=t;return d.errorModal(n,s,i)}return t&&502===t.status?d.badGatewayErrorModal():d.ajaxErrorModal(e,t,i)}},clearMessages:function(e){var t=a.isUndefined(e)?this.$messages().children('[class$="message"]'):o(e.currentTarget);return t.fadeOut(this.fxSpeed,function(){o(this).remove()}),this},scrollToHid:function(e){return this.scrollToItem(a.first(this.viewsWhereModel({hid:e})))},ordinalIndicator:function(e){var t=e+"";switch(t.charAt(t.length-1)){case"1":return t+"st";case"2":return t+"nd";case"3":return t+"rd";default:return t+"th"}},toString:function(){return"HistoryView("+(this.model?this.model.get("name"):"")+")"}});return f.prototype.templates=function(){var e=h.wrapTemplate(["
    ",'
    ','
      ','
      ',"
      "]),t=h.wrapTemplate(['
      ','
      ','
      <%- history.name %>
      ',"
      ",'
      ','
      <%- history.nice_size %>
      ','
      ','
      ',"<% if( history.deleted && history.purged ){ %>",'
      ',u("This history has been purged and deleted"),"
      ","<% } else if( history.deleted ){ %>",'
      ',u("This history has been deleted"),"
      ","<% } else if( history.purged ){ %>",'
      ',u("This history has been purged"),"
      ","<% } %>","<% if( history.message ){ %>",'
      messagesmall">',"<%= history.message.text %>","
      ","<% } %>","
      ",'
      ','
      ','",'
      ','
      ','",'","
      ",'
      ',"
      ","
      ",'
      ',"
      "],"history"),i=h.wrapTemplate(['','",''],"pages");return a.extend(a.clone(p.prototype.templates),{el:e,controls:t,pagination:i})}(),{HistoryView:f}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(18),i(84),i(7),i(6),i(42)],s=function(e,t,i,n,s){"use strict";function r(e,t,i){return o.clone(l).filter(function(n){return!(e&&!n.anon)&&(!(!t&&n.purge)&&(n.href&&(n.href=i+n.href,n.target=n.target||"galaxy_main"),n.confirm&&(n.func=function(){confirm(n.confirm)&&(galaxy_main.location=n.href)}),!0))})}var l=[{html:n("History Lists"),header:!0},{html:n("Saved Histories"),href:"histories/list",target:"_top"},{html:n("Histories Shared with Me"),href:"histories/list_shared",target:"_top"},{html:n("Current History"),header:!0,anon:!0},{html:n("Create New"),func:function(){Galaxy&&Galaxy.currHistoryPanel&&Galaxy.currHistoryPanel.createNewHistory()}},{html:n("Copy History"),func:function(){t(Galaxy.currHistoryPanel.model).done(function(){Galaxy.currHistoryPanel.loadCurrentHistory()})}},{html:n("Share or Publish"),href:"history/sharing"},{html:n("Show Structure"),href:"history/display_structured",anon:!0},{html:n("Extract Workflow"),href:"workflow/build_from_current_history"},{html:n("Delete"),anon:!0,func:function(){Galaxy&&Galaxy.currHistoryPanel&&confirm(n("Really delete the current history?"))&&(galaxy_main.window.location.href="history/delete?id="+Galaxy.currHistoryPanel.model.id)}},{html:n("Delete Permanently"),purge:!0,anon:!0,func:function(){Galaxy&&Galaxy.currHistoryPanel&&confirm(n("Really delete the current history permanently? This cannot be undone."))&&(galaxy_main.window.location.href="history/delete?purge=True&id="+Galaxy.currHistoryPanel.model.id)}},{html:n("Dataset Actions"),header:!0,anon:!0},{html:n("Copy Datasets"),href:"dataset/copy_datasets"},{html:n("Dataset Security"),href:"root/history_set_default_permissions"},{html:n("Resume Paused Jobs"),href:"history/resume_paused_jobs?current=True",anon:!0},{html:n("Collapse Expanded Datasets"),func:function(){Galaxy&&Galaxy.currHistoryPanel&&Galaxy.currHistoryPanel.collapseAll()}},{html:n("Unhide Hidden Datasets"),anon:!0,func:function(){Galaxy&&Galaxy.currHistoryPanel&&confirm(n("Really unhide all hidden datasets?"))&&a.post(Galaxy.root+"history/adjust_hidden",{user_action:"unhide"},function(){Galaxy.currHistoryPanel.loadCurrentHistory()})}},{html:n("Delete Hidden Datasets"),anon:!0,func:function(){Galaxy&&Galaxy.currHistoryPanel&&confirm(n("Really delete all hidden datasets?"))&&a.post(Galaxy.root+"history/adjust_hidden",{user_action:"delete"},function(){Galaxy.currHistoryPanel.loadCurrentHistory()})}},{html:n("Purge Deleted Datasets"),confirm:n("Really delete all deleted datasets permanently? This cannot be undone."),href:"history/purge_deleted_datasets",purge:!0,anon:!0},{html:n("Downloads"),header:!0},{html:n("Export Tool Citations"),href:"history/citations",anon:!0},{html:n("Export History to File"),href:"history/export_archive?preview=True",anon:!0},{html:n("Other Actions"),header:!0},{html:n("Import from File"),href:"history/import_archive"}];s.add({url:"api/webhooks/history-menu/all",async:!1,callback:function(e){var t=[];a.each(e.models,function(e,i){var s=i.toJSON();s.activate&&t.push({html:n(s.config.title),anon:!0})}),t.length>0&&(t.unshift({html:n("Webhooks"),header:!0}),a.merge(l,t))}});var d=function(t,i){i=i||{};var n=void 0===i.anonymous||i.anonymous,s=i.purgeAllowed||!1,a=r(n,s,Galaxy.root);return new e(t,a)};return d}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1),i(3))},function(e,t,i){var n,s;(function(a,o,r){n=[i(4),i(41),i(68),i(21),i(22)],s=function(e,t,i,n,s){return a.View.extend({status_classes:{init:"upload-icon-button fa fa-trash-o",queued:"upload-icon fa fa-spinner fa-spin",running:"upload-icon fa fa-spinner fa-spin",success:"upload-icon-button fa fa-check",error:"upload-icon-button fa fa-exclamation-triangle"},initialize:function(e,t){var i=this;this.app=e,this.model=t.model,this.setElement(this._template(t.model)),this.$mode=this.$(".upload-mode"),this.$title=this.$(".upload-title-extended"),this.$text=this.$(".upload-text"),this.$size=this.$(".upload-size"),this.$info_text=this.$(".upload-info-text"),this.$info_progress=this.$(".upload-info-progress"),this.$text_content=this.$(".upload-text-content"),this.$symbol=this.$(".upload-symbol"),this.$progress_bar=this.$(".upload-progress-bar"),this.$percentage=this.$(".upload-percentage"),this.settings=new n.View({title:"Upload configuration",container:this.$(".upload-settings"),placement:"bottom"});this.app.select_genome.value(),this.app.select_extension.value();this.$symbol.on("click",function(){i._removeRow()}),this.$text_content.on("change input",function(e){i.model.set({url_paste:o(e.target).val(),file_size:o(e.target).val().length})}),this.listenTo(this.model,"change:percentage",function(){i._refreshPercentage()}),this.listenTo(this.model,"change:status",function(){i._refreshStatus()}),this.listenTo(this.model,"change:info",function(){i._refreshInfo()}),this.listenTo(this.model,"change:file_size",function(){i._refreshFileSize()}),this.listenTo(this.model,"remove",function(){i.remove()}),this.app.collection.on("reset",function(){i.remove()})},render:function(){var t=this.model.attributes;this.$title.html(r.escape(t.file_name)),this.$size.html(e.bytesToString(t.file_size)),this.$mode.removeClass().addClass("upload-mode").addClass("text-primary"),"new"==t.file_mode?(this.$text.css({width:this.$el.width()-16+"px",top:this.$el.height()-8+"px"}).show(),this.$el.height(this.$el.height()-8+this.$text.height()+16),this.$mode.addClass("fa fa-edit")):"local"==t.file_mode?this.$mode.addClass("fa fa-laptop"):"ftp"==t.file_mode&&this.$mode.addClass("fa fa-folder-open-o")},_refreshInfo:function(){var e=this.model.get("info");e?this.$info_text.html("Failed: "+e).show():this.$info_text.hide()},_refreshPercentage:function(){var e=parseInt(this.model.get("percentage"));this.$progress_bar.css({width:e+"%"}),this.$percentage.html(100!=e?e+"%":"Adding to history...")},_refreshStatus:function(){var e=this.model.get("status");this.$symbol.removeClass().addClass("upload-symbol").addClass(this.status_classes[e]),this.model.set("enabled","init"==e);var t=this.model.get("enabled");this.$text_content.attr("disabled",!t),"success"==e&&(this.$el.addClass("success"),this.$percentage.html("100%")),"error"==e&&(this.$el.addClass("danger"),this.$info_progress.hide())},_refreshFileSize:function(){this.$size.html(e.bytesToString(this.model.get("file_size")))},_removeRow:function(){["init","success","error"].indexOf(this.model.get("status"))!==-1&&this.app.collection.remove(this.model)},_showSettings:function(){this.settings.visible?this.settings.hide():(this.settings.empty(), -this.settings.append(new i(this).$el),this.settings.show())},_template:function(e){return'
      ' + '' + '' + '' + '' + '';\n\t },\n\t\n\t /** Template of table */\n\t _templateTable: function () {\n\t return 'Available files: ' + '' + '' + '  ' + '' + '' + '' + '
      ").append(i)).append(o("").append(t.title)))}),this.$cover[this.model.get("enabled")&&"hide"||"show"]()}})}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3))},,function(e,t,i){(function(e,t){!function(i){e.event.props.push("dataTransfer"),i.uploadpost=function(t){var n=i.extend({},{data:{},success:function(){},error:function(){},progress:function(){},url:null,maxfilesize:2048,error_filesize:"File exceeds 2GB. Please use a FTP client.",error_default:"Please make sure the file is available.",error_server:"Upload request failed.",error_login:"Uploads require you to log in."},t),s=n.data;if(s.error_message)return void n.error(s.error_message);var a=new FormData;for(var o in s.payload)a.append(o,s.payload[o]);var r=0;for(var o in s.files){var l=s.files[o];a.append(l.name,l.file,l.file.name),r+=l.file.size}return r>1048576*n.maxfilesize?void n.error(n.error_filesize):(xhr=new XMLHttpRequest,xhr.open("POST",n.url,!0),xhr.setRequestHeader("Accept","application/json"),xhr.setRequestHeader("Cache-Control","no-cache"),xhr.setRequestHeader("X-Requested-With","XMLHttpRequest"),xhr.onreadystatechange=function(){if(xhr.readyState==xhr.DONE){var t=null;if(xhr.responseText)try{t=e.parseJSON(xhr.responseText)}catch(e){t=xhr.responseText}if(xhr.status<200||xhr.status>299){var i=xhr.statusText;403==xhr.status?i=n.error_login:0==xhr.status?i=n.error_server:i||(i=n.error_default),n.error(i+" ("+xhr.status+")")}else n.success(t)}},xhr.upload.addEventListener("progress",function(e){e.lengthComputable&&n.progress(Math.round(100*e.loaded/e.total))},!1),Galaxy.emit.debug("uploadbox::uploadpost()","Posting following data.",n),void xhr.send(a))},i.fn.uploadinput=function(e){var t=this,n=i.extend({},{ondragover:function(){},ondragleave:function(){},onchange:function(){},multiple:!1},e),s=i('");return t.append(s.change(function(e){n.onchange(e.target.files),i(this).val("")})),t.on("drop",function(e){n.ondragleave(e),e.dataTransfer&&(n.onchange(e.dataTransfer.files),e.preventDefault())}),t.on("dragover",function(e){e.preventDefault(),n.ondragover(e)}),t.on("dragleave",function(e){e.stopPropagation(),n.ondragleave(e)}),{dialog:function(){s.trigger("click")}}},i.fn.uploadbox=function(e){function n(e){if(e&&e.length&&!m){var i=f;return t.each(e,function(e,i){"new"!==e.mode&&t.filter(p,function(t){return t.name===e.name&&t.size===e.size}).length&&(e.duplicate=!0)}),t.each(e,function(e){if(!e.duplicate){var t=String(f++);p[t]=e,u.announce(t,p[t]),g++}}),i}}function s(e){p[e]&&(delete p[e],g--)}function a(){if(0==g||v)return v=!1,m=!1,void u.complete();m=!0;var e=-1;for(var t in p){e=t;break}p[e];s(e),i.uploadpost({url:u.url,data:u.initialize(e),success:function(t){u.success(e,t),a()},error:function(t){u.error(e,t),a()},progress:function(t){u.progress(e,t)}})}function o(){_.dialog()}function r(e){for(e in p)s(e)}function l(){m||(m=!0,a())}function d(){v=!0}function c(e){return u=i.extend({},u,e)}function h(){return window.File&&window.FormData&&window.XMLHttpRequest&&window.FileList}var u=i.extend({},{dragover:function(){},dragleave:function(){},announce:function(e){},initialize:function(e){},progress:function(e,t){},success:function(e,t){},error:function(e,t){alert(t)},complete:function(){}},e),p={},f=0,g=0,m=!1,v=!1,_=i(this).uploadinput({multiple:!0,onchange:function(e){n(e)},ondragover:e.ondragover,ondragleave:e.ondragleave});return{select:o,add:n,remove:s,start:l,stop:d,reset:r,configure:c,compatible:h}}}(e)}).call(t,i(1),i(3))},,,,,,,,function(e,t,i){var n,s;(function(a,o){n=[i(7),i(6),i(24)],s=function(e,t){var i=a.View.extend(e.LoggableMixin).extend(e.HiddenUntilActivatedViewMixin).extend({tagName:"div",className:"annotation-display",initialize:function(e){e=e||{},this.tooltipConfig=e.tooltipConfig||{placement:"bottom"},this.listenTo(this.model,"change:annotation",function(){this.render()}),this.hiddenUntilActivated(e.$activator,e)},render:function(){var e=this;return this.$el.html(this._template()),this.$annotation().make_text_editable({use_textarea:!0,on_finish:function(t){e.$annotation().text(t),e.model.save({annotation:t},{silent:!0}).fail(function(){e.$annotation().text(e.model.previous("annotation"))})}}),this},_template:function(){var e=this.model.get("annotation");return['",'
      ',o.escape(e),"
      "].join("")},$annotation:function(){return this.$el.find(".annotation")},remove:function(){this.$annotation.off(),this.stopListening(this.model),a.View.prototype.remove.call(this)},toString:function(){return["AnnotationEditor(",this.model+"",")"].join("")}});return{AnnotationEditor:i}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3))},function(e,t,i){var n,s;(function(a){n=[i(3),i(2),i(7)],s=function(e,t,i){"use strict";var n=t.Collection.extend({initialize:function(e,i){t.Collection.prototype.initialize.call(this,e,i),this.setOrder(i.order||this.order,{silent:!0})},_setUpListeners:function(){return this.on({"changed-order":this.sort})},fetch:function(e){return e=this._buildFetchOptions(e),t.Collection.prototype.fetch.call(this,e)},_buildFetchOptions:function(t){t=e.clone(t)||{};var i=this;t.traditional=!0,t.data=t.data||i._buildFetchData(t);var n=this._buildFetchFilters(t);return e.isEmpty(n)||e.extend(t.data,this._fetchFiltersToAjaxData(n)),t},_buildFetchData:function(t){var i={};return this.order&&(i.order=this.order),e.defaults(e.pick(t,this._fetchParams),i)},_fetchParams:["order","limit","offset","view","keys"],_buildFetchFilters:function(t){return e.clone(t.filters||{})},_fetchFiltersToAjaxData:function(t){var i={q:[],qv:[]};return e.each(t,function(e,t){void 0!==e&&""!==e&&(e===!0&&(e="True"),e===!1&&(e="False"),null===e&&(e="None"),i.q.push(t),i.qv.push(e))}),i},reset:function(e,i){return this.allFetched=!1,t.Collection.prototype.reset.call(this,e,i)},order:null,comparators:{update_time:i.buildComparator("update_time",{ascending:!1}),"update_time-asc":i.buildComparator("update_time",{ascending:!0}),create_time:i.buildComparator("create_time",{ascending:!1}),"create_time-asc":i.buildComparator("create_time",{ascending:!0})},setOrder:function(t,i){i=i||{};var n=this,s=n.comparators[t];if(e.isUndefined(s))throw new Error("unknown order: "+t);if(s!==n.comparator){n.order;return n.order=t,n.comparator=s,i.silent||n.trigger("changed-order",i),n}}}),s=n.extend({limitPerPage:500,initialize:function(e,t){n.prototype.initialize.call(this,e,t),this.currentPage=t.currentPage||0},getTotalItemCount:function(){return this.length},shouldPaginate:function(){return this.getTotalItemCount()>=this.limitPerPage},getLastPage:function(){return Math.floor(this.getTotalItemCount()/this.limitPerPage)},getPageCount:function(){return this.getLastPage()+1},getPageLimitOffset:function(e){return e=this.constrainPageNum(e),{limit:this.limitPerPage,offset:e*this.limitPerPage}},constrainPageNum:function(e){return Math.max(0,Math.min(e,this.getLastPage()))},fetchPage:function(t,i){var n=this;return t=n.constrainPageNum(t),n.currentPage=t,i=e.defaults(i||{},n.getPageLimitOffset(t)),n.trigger("fetching-more"),n.fetch(i).always(function(){n.trigger("fetching-more-done")})},fetchCurrentPage:function(e){return this.fetchPage(this.currentPage,e)},fetchPrevPage:function(e){return this.fetchPage(this.currentPage-1,e)},fetchNextPage:function(e){return this.fetchPage(this.currentPage+1,e)}}),o=n.extend({limitOnFirstFetch:null,limitPerFetch:100,initialize:function(e,t){n.prototype.initialize.call(this,e,t),this.limitOnFirstFetch=t.limitOnFirstFetch||this.limitOnFirstFetch,this.limitPerFetch=t.limitPerFetch||this.limitPerFetch,this.allFetched=!1,this.lastFetched=t.lastFetched||0},_buildFetchOptions:function(e){return e.remove=e.remove||!1,n.prototype._buildFetchOptions.call(this,e)},fetchFirst:function(t){return t=t?e.clone(t):{},this.allFetched=!1,this.lastFetched=0,this.fetchMore(e.defaults(t,{reset:!0,limit:this.limitOnFirstFetch}))},fetchMore:function(t){t=e.clone(t||{});var i=this;if(!t.reset&&i.allFetched)return a.when();t.offset=t.reset?0:t.offset||i.lastFetched;var n=t.limit=t.limit||i.limitPerFetch||null;return i.trigger("fetching-more"),i.fetch(t).always(function(){i.trigger("fetching-more-done")}).done(function(t){var s=e.isArray(t)?t.length:0;i.lastFetched+=s,(!n||s','
      ',''].join(""))}};return{CollectionCreatorMixin:e}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a){n=[i(89),i(56),i(55),i(7),i(6)],s=function(e,t,i,n,s){"use strict";var o="collections",r=e.ModelListPanel,l=r.extend({_logNamespace:o,className:r.prototype.className+" dataset-collection-panel",DatasetDCEViewClass:i.DatasetDCEListItemView,NestedDCDCEViewClass:i.NestedDCDCEListItemView,modelCollectionKey:"elements",initialize:function(e){r.prototype.initialize.call(this,e),this.linkTarget=e.linkTarget||"_blank",this.hasUser=e.hasUser,this.panelStack=[],this.parentName=e.parentName,this.foldoutStyle=e.foldoutStyle||"foldout",this.downloadUrl=this.model.attributes.url+"/download"},_queueNewRender:function(e,t){t=void 0===t?this.fxSpeed:t;var i=this;i.log("_queueNewRender:",e,t),i._swapNewRender(e),i.trigger("rendered",i)},_filterCollection:function(){return this.model.getVisibleContents()},_getItemViewClass:function(e){switch(e.get("element_type")){case"hda":return this.DatasetDCEViewClass;case"dataset_collection":return this.NestedDCDCEViewClass}throw new TypeError("Unknown element type:",e.get("element_type"))},_getItemViewOptions:function(e){var t=r.prototype._getItemViewOptions.call(this,e);return a.extend(t,{linkTarget:this.linkTarget,hasUser:this.hasUser,foldoutStyle:this.foldoutStyle})},_setUpItemViewListeners:function(e){var t=this;return r.prototype._setUpItemViewListeners.call(t,e),t.listenTo(e,{"expanded:drilldown":function(e,t){this._expandDrilldownPanel(t)},"collapsed:drilldown":function(e,t){this._collapseDrilldownPanel(t)}}),this},_expandDrilldownPanel:function(e){this.panelStack.push(e),this.$("> .controls").add(this.$list()).hide(),e.parentName=this.model.get("name"),this.$el.append(e.render().$el)},_collapseDrilldownPanel:function(e){this.panelStack.pop(),this.render()},events:{"click .navigation .back":"close"},close:function(e){this.remove(),this.trigger("close")},toString:function(){return"CollectionView("+(this.model?this.model.get("name"):"")+")"}});l.prototype.templates=function(){var e=n.wrapTemplate(['
      ','",'
      ','
      <%- collection.name || collection.element_identifier %>
      ','
      ','<% if( collection.collection_type === "list" ){ %>',s("a list of datasets"),'<% } else if( collection.collection_type === "paired" ){ %>',s("a pair of datasets"),'<% } else if( collection.collection_type === "list:paired" ){ %>',s("a list of paired datasets"),'<% } else if( collection.collection_type === "list:list" ){ %>',s("a list of dataset lists"),"<% } %>","
      ","
      ",'
      ','
      ','','',"","
      ","
      "],"collection");return a.extend(a.clone(r.prototype.templates),{controls:e})}();var d=l.extend({DatasetDCEViewClass:i.DatasetDCEListItemView,toString:function(){return"ListCollectionView("+(this.model?this.model.get("name"):"")+")"}}),c=d.extend({toString:function(){return"PairCollectionView("+(this.model?this.model.get("name"):"")+")"}}),h=l.extend({NestedDCDCEViewClass:i.NestedDCDCEListItemView.extend({foldoutPanelClass:c}),toString:function(){return"ListOfPairsCollectionView("+(this.model?this.model.get("name"):"")+")"}}),u=l.extend({NestedDCDCEViewClass:i.NestedDCDCEListItemView.extend({foldoutPanelClass:c}),toString:function(){return"ListOfListsCollectionView("+(this.model?this.model.get("name"):"")+")"}});return{CollectionView:l,ListCollectionView:d,PairCollectionView:c,ListOfPairsCollectionView:h,ListOfListsCollectionView:u}}.apply(t,n), -!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o){n=[i(17),i(58),i(65),i(78),i(25),i(7),i(6)],s=function(e,t,i,n,s,r,l){"use strict";var d=t.DatasetListItemView,c=d.extend({initialize:function(e){d.prototype.initialize.call(this,e),this.hasUser=e.hasUser,this.purgeAllowed=e.purgeAllowed||!1,this.tagsEditorShown=e.tagsEditorShown||!1,this.annotationEditorShown=e.annotationEditorShown||!1},_renderPrimaryActions:function(){var t=d.prototype._renderPrimaryActions.call(this);return this.model.get("state")===e.NOT_VIEWABLE?t:d.prototype._renderPrimaryActions.call(this).concat([this._renderEditButton(),this._renderDeleteButton()])},_renderEditButton:function(){if(this.model.get("state")===e.DISCARDED||!this.model.get("accessible"))return null;var t=this.model.get("purged"),i=this.model.get("deleted"),n={title:l("Edit attributes"),href:Galaxy.root+"datasets/edit?dataset_id="+this.model.attributes.id,faIcon:"fa-pencil",classes:"edit-btn"};return i||t?(n.disabled=!0,t?n.title=l("Cannot edit attributes of datasets removed from disk"):i&&(n.title=l("Undelete dataset to edit attributes"))):a.contains([e.UPLOAD,e.NEW],this.model.get("state"))&&(n.disabled=!0,n.title=l("This dataset is not yet editable")),s(n)},_renderDeleteButton:function(){if(!this.model.get("accessible"))return null;var e=this,t=this.model.isDeletedOrPurged();return s({title:l(t?"Dataset is already deleted":"Delete"),disabled:t,faIcon:"fa-times",classes:"delete-btn",onclick:function(){e.$el.find(".icon-btn.delete-btn").trigger("mouseout"),e.model.delete()}})},_renderDetails:function(){var t=d.prototype._renderDetails.call(this),i=this.model.get("state");return!this.model.isDeletedOrPurged()&&a.contains([e.OK,e.FAILED_METADATA],i)&&(this._renderTags(t),this._renderAnnotation(t),this._makeDbkeyEditLink(t)),this._setUpBehaviors(t),t},_renderToolHelpButton:function(){var e=this.model.attributes.dataset_id,t=this.model.attributes.creating_job,i=this,n=function(t){var n='
      ';t.name&&t.help?(n+="Tool help for "+t.name+"
      ",n+=t.help):n+="Tool help is unavailable for this dataset.
      ",n+="
      ",i.$el.find(".details").append(o.parseHTML(n))},a=function(e){o.ajax({url:Galaxy.root+"api/tools/"+e.tool_id+"/build"}).done(function(e){n(e)}).fail(function(){n({})})};return null===Galaxy.user.id?null:s({title:l("Tool Help"),classes:"icon-btn",href:"#",faIcon:"fa-question",onclick:function(){i.$el.find(".toolhelp").length>0?i.$el.find(".toolhelp").toggle():o.ajax({url:Galaxy.root+"api/jobs/"+t}).done(function(e){a(e)}).fail(function(){console.log('Failed at recovering job information from the Galaxy API for job id "'+t+'".')})}})},_renderSecondaryActions:function(){var t=d.prototype._renderSecondaryActions.call(this);switch(this.model.get("state")){case e.UPLOAD:case e.NOT_VIEWABLE:return t;case e.ERROR:return t.unshift(this._renderErrButton()),t.concat([this._renderRerunButton(),this._renderToolHelpButton()]);case e.OK:case e.FAILED_METADATA:return t.concat([this._renderRerunButton(),this._renderVisualizationsButton(),this._renderToolHelpButton()])}return t.concat([this._renderRerunButton(),this._renderToolHelpButton()])},_renderErrButton:function(){return s({title:l("View or report this error"),href:this.model.urls.report_error,classes:"report-error-btn",target:this.linkTarget,faIcon:"fa-bug"})},_renderRerunButton:function(){var e=this.model.get("creating_job");if(this.model.get("rerunnable"))return s({title:l("Run this job again"),href:this.model.urls.rerun,classes:"rerun-btn",target:this.linkTarget,faIcon:"fa-refresh",onclick:function(t){t.preventDefault(),Galaxy.router.push("/",{job_id:e})}})},_renderVisualizationsButton:function(){var e=this.model.get("visualizations");if(this.model.isDeletedOrPurged()||!this.hasUser||!this.model.hasData()||a.isEmpty(e))return null;if(!a.isObject(e[0]))return this.warn("Visualizations have been switched off"),null;var t=o(this.templates.visualizations(e,this));return t.find('[target="galaxy_main"]').attr("target",this.linkTarget),this._addScratchBookFn(t.find(".visualization-link").addBack(".visualization-link")),t},_addScratchBookFn:function(e){e.click(function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.add({title:"Visualization",url:o(this).attr("href")}),e.preventDefault(),e.stopPropagation())})},_renderTags:function(e){if(this.hasUser){var t=this;this.tagsEditor=new i.TagsEditor({model:this.model,el:e.find(".tags-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.tagsEditorShown=!0},onhide:function(){t.tagsEditorShown=!1},$activator:s({title:l("Edit dataset tags"),classes:"tag-btn",faIcon:"fa-tags"}).appendTo(e.find(".actions .right"))}),this.tagsEditorShown&&this.tagsEditor.toggle(!0)}},_renderAnnotation:function(e){if(this.hasUser){var t=this;this.annotationEditor=new n.AnnotationEditor({model:this.model,el:e.find(".annotation-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.annotationEditorShown=!0},onhide:function(){t.annotationEditorShown=!1},$activator:s({title:l("Edit dataset annotation"),classes:"annotate-btn",faIcon:"fa-comment"}).appendTo(e.find(".actions .right"))}),this.annotationEditorShown&&this.annotationEditor.toggle(!0)}},_makeDbkeyEditLink:function(e){if("?"===this.model.get("metadata_dbkey")&&!this.model.isDeletedOrPurged()){var t=o('?').attr("href",this.model.urls.edit).attr("target",this.linkTarget);e.find(".dbkey .value").replaceWith(t)}},events:a.extend(a.clone(d.prototype.events),{"click .undelete-link":"_clickUndeleteLink","click .purge-link":"_clickPurgeLink","click .edit-btn":function(e){this.trigger("edit",this,e)},"click .delete-btn":function(e){this.trigger("delete",this,e)},"click .rerun-btn":function(e){this.trigger("rerun",this,e)},"click .report-err-btn":function(e){this.trigger("report-err",this,e)},"click .visualization-btn":function(e){this.trigger("visualize",this,e)},"click .dbkey a":function(e){this.trigger("edit",this,e)}}),_clickUndeleteLink:function(e){return this.model.undelete(),!1},_clickPurgeLink:function(e){return confirm(l("This will permanently remove the data in your dataset. Are you sure?"))&&this.model.purge(),!1},toString:function(){var e=this.model?this.model+"":"(no model)";return"HDAEditView("+e+")"}});return c.prototype.templates=function(){var e=a.extend({},d.prototype.templates.warnings,{failed_metadata:r.wrapTemplate(['<% if( dataset.state === "failed_metadata" ){ %>','","<% } %>"],"dataset"),deleted:r.wrapTemplate(["<% if( dataset.deleted && !dataset.purged ){ %>",'
      ',l("This dataset has been deleted"),'
      ',l("Undelete it"),"","<% if( view.purgeAllowed ){ %>",'
      ',l("Permanently remove it from disk"),"","<% } %>","
      ","<% } %>"],"dataset")}),t=r.wrapTemplate(["<% if( visualizations.length === 1 ){ %>",'">','',"","<% } else { %>",'","<% } %>"],"visualizations");return a.extend({},d.prototype.templates,{warnings:e,visualizations:t})}(),{DatasetListItemEdit:c}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(17),i(7),i(6)],s=function(e,t,i){"use strict";var n="dataset",s=t.SearchableModelMixin,l=a.Model.extend(t.LoggableMixin).extend(t.mixin(s,{_logNamespace:n,defaults:{state:e.NEW,deleted:!1,purged:!1,name:"(unnamed dataset)",accessible:!0,data_type:"",file_ext:"",file_size:0,meta_files:[],misc_blurb:"",misc_info:"",tags:[]},initialize:function(t,i){this.debug(this+"(Dataset).initialize",t,i), +!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a,o){n=[i(17),i(58),i(65),i(78),i(25),i(7),i(6)],s=function(e,t,i,n,s,r,l){"use strict";var d=t.DatasetListItemView,c=d.extend({initialize:function(e){d.prototype.initialize.call(this,e),this.hasUser=e.hasUser,this.purgeAllowed=e.purgeAllowed||!1,this.tagsEditorShown=e.tagsEditorShown||!1,this.annotationEditorShown=e.annotationEditorShown||!1},_renderPrimaryActions:function(){var t=d.prototype._renderPrimaryActions.call(this);return this.model.get("state")===e.NOT_VIEWABLE?t:d.prototype._renderPrimaryActions.call(this).concat([this._renderEditButton(),this._renderDeleteButton()])},_renderEditButton:function(){if(this.model.get("state")===e.DISCARDED||!this.model.get("accessible"))return null;var t=this.model.get("purged"),i=this.model.get("deleted"),n={title:l("Edit attributes"),href:Galaxy.root+"datasets/edit?dataset_id="+this.model.attributes.id,faIcon:"fa-pencil",classes:"edit-btn"};return i||t?(n.disabled=!0,t?n.title=l("Cannot edit attributes of datasets removed from disk"):i&&(n.title=l("Undelete dataset to edit attributes"))):a.contains([e.UPLOAD,e.NEW],this.model.get("state"))&&(n.disabled=!0,n.title=l("This dataset is not yet editable")),s(n)},_renderDeleteButton:function(){if(!this.model.get("accessible"))return null;var e=this,t=this.model.isDeletedOrPurged();return s({title:l(t?"Dataset is already deleted":"Delete"),disabled:t,faIcon:"fa-times",classes:"delete-btn",onclick:function(){e.$el.find(".icon-btn.delete-btn").trigger("mouseout"),e.model.delete()}})},_renderDetails:function(){var t=d.prototype._renderDetails.call(this),i=this.model.get("state");return!this.model.isDeletedOrPurged()&&a.contains([e.OK,e.FAILED_METADATA],i)&&(this._renderTags(t),this._renderAnnotation(t),this._makeDbkeyEditLink(t)),this._setUpBehaviors(t),t},_renderToolHelpButton:function(){var e=this.model.attributes.dataset_id,t=this.model.attributes.creating_job,i=this,n=function(t){var n='
      ';t.name&&t.help?(n+="Tool help for "+t.name+"
      ",n+=t.help):n+="Tool help is unavailable for this dataset.
      ",n+="
      ",i.$el.find(".details").append(o.parseHTML(n))},a=function(e){o.ajax({url:Galaxy.root+"api/tools/"+e.tool_id+"/build"}).done(function(e){n(e)}).fail(function(){n({})})};return null===Galaxy.user.id?null:s({title:l("Tool Help"),classes:"icon-btn",href:"#",faIcon:"fa-question",onclick:function(){i.$el.find(".toolhelp").length>0?i.$el.find(".toolhelp").toggle():o.ajax({url:Galaxy.root+"api/jobs/"+t}).done(function(e){a(e)}).fail(function(){console.log('Failed at recovering job information from the Galaxy API for job id "'+t+'".')})}})},_renderSecondaryActions:function(){var t=d.prototype._renderSecondaryActions.call(this);switch(this.model.get("state")){case e.UPLOAD:case e.NOT_VIEWABLE:return t;case e.ERROR:return t.unshift(this._renderErrButton()),t.concat([this._renderRerunButton(),this._renderToolHelpButton()]);case e.OK:case e.FAILED_METADATA:return t.concat([this._renderRerunButton(),this._renderVisualizationsButton(),this._renderToolHelpButton()])}return t.concat([this._renderRerunButton(),this._renderToolHelpButton()])},_renderErrButton:function(){return s({title:l("View or report this error"),href:Galaxy.root+"datasets/error?dataset_id="+this.model.attributes.id,classes:"report-error-btn",faIcon:"fa-bug"})},_renderRerunButton:function(){var e=this.model.get("creating_job");if(this.model.get("rerunnable"))return s({title:l("Run this job again"),href:this.model.urls.rerun,classes:"rerun-btn",target:this.linkTarget,faIcon:"fa-refresh",onclick:function(t){t.preventDefault(),Galaxy.router.push("/",{job_id:e})}})},_renderVisualizationsButton:function(){var e=this.model.get("visualizations");if(this.model.isDeletedOrPurged()||!this.hasUser||!this.model.hasData()||a.isEmpty(e))return null;if(!a.isObject(e[0]))return this.warn("Visualizations have been switched off"),null;var t=o(this.templates.visualizations(e,this));return t.find('[target="galaxy_main"]').attr("target",this.linkTarget),this._addScratchBookFn(t.find(".visualization-link").addBack(".visualization-link")),t},_addScratchBookFn:function(e){e.click(function(e){Galaxy.frame&&Galaxy.frame.active&&(Galaxy.frame.add({title:"Visualization",url:o(this).attr("href")}),e.preventDefault(),e.stopPropagation())})},_renderTags:function(e){if(this.hasUser){var t=this;this.tagsEditor=new i.TagsEditor({model:this.model,el:e.find(".tags-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.tagsEditorShown=!0},onhide:function(){t.tagsEditorShown=!1},$activator:s({title:l("Edit dataset tags"),classes:"tag-btn",faIcon:"fa-tags"}).appendTo(e.find(".actions .right"))}),this.tagsEditorShown&&this.tagsEditor.toggle(!0)}},_renderAnnotation:function(e){if(this.hasUser){var t=this;this.annotationEditor=new n.AnnotationEditor({model:this.model,el:e.find(".annotation-display"),onshowFirstTime:function(){this.render()},onshow:function(){t.annotationEditorShown=!0},onhide:function(){t.annotationEditorShown=!1},$activator:s({title:l("Edit dataset annotation"),classes:"annotate-btn",faIcon:"fa-comment"}).appendTo(e.find(".actions .right"))}),this.annotationEditorShown&&this.annotationEditor.toggle(!0)}},_makeDbkeyEditLink:function(e){if("?"===this.model.get("metadata_dbkey")&&!this.model.isDeletedOrPurged()){var t=o('?').attr("href",this.model.urls.edit).attr("target",this.linkTarget);e.find(".dbkey .value").replaceWith(t)}},events:a.extend(a.clone(d.prototype.events),{"click .undelete-link":"_clickUndeleteLink","click .purge-link":"_clickPurgeLink","click .edit-btn":function(e){this.trigger("edit",this,e)},"click .delete-btn":function(e){this.trigger("delete",this,e)},"click .rerun-btn":function(e){this.trigger("rerun",this,e)},"click .report-err-btn":function(e){this.trigger("report-err",this,e)},"click .visualization-btn":function(e){this.trigger("visualize",this,e)},"click .dbkey a":function(e){this.trigger("edit",this,e)}}),_clickUndeleteLink:function(e){return this.model.undelete(),!1},_clickPurgeLink:function(e){return confirm(l("This will permanently remove the data in your dataset. Are you sure?"))&&this.model.purge(),!1},toString:function(){var e=this.model?this.model+"":"(no model)";return"HDAEditView("+e+")"}});return c.prototype.templates=function(){var e=a.extend({},d.prototype.templates.warnings,{failed_metadata:r.wrapTemplate(['<% if( dataset.state === "failed_metadata" ){ %>','","<% } %>"],"dataset"),deleted:r.wrapTemplate(["<% if( dataset.deleted && !dataset.purged ){ %>",'
      ',l("This dataset has been deleted"),'
      ',l("Undelete it"),"","<% if( view.purgeAllowed ){ %>",'
      ',l("Permanently remove it from disk"),"","<% } %>","
      ","<% } %>"],"dataset")}),t=r.wrapTemplate(["<% if( visualizations.length === 1 ){ %>",'">','',"","<% } else { %>",'","<% } %>"],"visualizations");return a.extend({},d.prototype.templates,{warnings:e,visualizations:t})}(),{DatasetListItemEdit:c}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(17),i(7),i(6)],s=function(e,t,i){"use strict";var n="dataset",s=t.SearchableModelMixin,l=a.Model.extend(t.LoggableMixin).extend(t.mixin(s,{_logNamespace:n,defaults:{state:e.NEW,deleted:!1,purged:!1,name:"(unnamed dataset)",accessible:!0,data_type:"",file_ext:"",file_size:0,meta_files:[],misc_blurb:"",misc_info:"",tags:[]},initialize:function(t,i){this.debug(this+"(Dataset).initialize",t,i), //!! this state is not in trans.app.model.Dataset.states - set it here - -this.get("accessible")||this.set("state",e.NOT_VIEWABLE),this.urls=this._generateUrls(),this._setUpListeners()},_generateUrls:function(){var e=this.get("id");if(!e)return{};var t={purge:"datasets/"+e+"/purge_async",display:"datasets/"+e+"/display/?preview=True",edit:"datasets/"+e+"/edit",download:"datasets/"+e+"/display"+this._downloadQueryParameters(),report_error:"dataset/errors?id="+e,rerun:"tool_runner/rerun?id="+e,show_params:"datasets/"+e+"/show_params",visualization:"visualization",meta_download:"dataset/get_metadata_file?hda_id="+e+"&metadata_name="};return o.each(t,function(e,i){t[i]=Galaxy.root+e}),this.urls=t,t},_downloadQueryParameters:function(){return"?to_ext="+this.get("file_ext")},_setUpListeners:function(){this.on("change:state",function(e,t){this.log(this+" has changed state:",e,t),this.inReadyState()&&this.trigger("state:ready",e,t,this.previous("state"))}),this.on("change:id change:file_ext",function(e){this._generateUrls()})},toJSON:function(){var e=a.Model.prototype.toJSON.call(this);return o.extend(e,{urls:this.urls})},isDeletedOrPurged:function(){return this.get("deleted")||this.get("purged")},inReadyState:function(){var t=o.contains(e.READY_STATES,this.get("state"));return this.isDeletedOrPurged()||t},hasDetails:function(){return!this.get("accessible")||this.has("annotation")},hasData:function(){return this.get("file_size")>0},fetch:function(e){var t=this;return a.Model.prototype.fetch.call(this,e).always(function(){t._generateUrls()})},parse:function(e,t){var i=a.Model.prototype.parse.call(this,e,t);return i.create_time&&(i.create_time=new Date(i.create_time)),i.update_time&&(i.update_time=new Date(i.update_time)),i},save:function(e,t){return t=t||{},t.wait=!!o.isUndefined(t.wait)||t.wait,a.Model.prototype.save.call(this,e,t)},delete:function(e){return this.get("deleted")?r.when():this.save({deleted:!0},e)},undelete:function(e){return!this.get("deleted")||this.get("purged")?r.when():this.save({deleted:!1},e)},purge:function(e){if(this.get("purged"))return r.when();e=e||{},e.url=this.urls.purge;var t=this,n=r.ajax(e);return n.done(function(e,i,n){t.set({deleted:!0,purged:!0})}),n.fail(function(n,s,a){var o=i("Unable to purge dataset"),r="Removal of datasets by users is not allowed in this Galaxy instance";n.responseJSON&&n.responseJSON.error?o=n.responseJSON.error:n.responseText.indexOf(r)!==-1&&(o=r),n.responseText=o,t.trigger("error",t,n,e,i(o),{error:o})}),n},searchAttributes:["name","file_ext","genome_build","misc_blurb","misc_info","annotation","tags"],searchAliases:{title:"name",format:"file_ext",database:"genome_build",blurb:"misc_blurb",description:"misc_blurb",info:"misc_info",tag:"tags"},toString:function(){var e=this.get("id")||"";return this.get("name")&&(e='"'+this.get("name")+'",'+e),"Dataset("+e+")"}})),d=a.Collection.extend(t.LoggableMixin).extend({_logNamespace:n,model:l,urlRoot:Galaxy.root+"api/datasets",url:function(){return this.urlRoot},ids:function(){return this.map(function(e){return e.get("id")})},notReady:function(){return this.filter(function(e){return!e.inReadyState()})},haveDetails:function(){return this.all(function(e){return e.hasDetails()})},ajaxQueue:function(e,t){var i=r.Deferred(),n=this.length,s=[];if(!n)return i.resolve([]),i;var a=this.chain().reverse().map(function(o,r){return function(){var l=e.call(o,t);l.done(function(e){i.notify({curr:r,total:n,response:e,model:o})}),l.always(function(e){s.push(e),a.length?a.shift()():i.resolve(s)})}}).value();return a.shift()(),i},matches:function(e){return this.filter(function(t){return t.matches(e)})},toString:function(){return["DatasetAssociationCollection(",this.length,")"].join("")}});return{DatasetAssociation:l,DatasetAssociationCollection:d}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(8),i(92),i(6)],s=function(e,t,i){"use strict";var n={defaultName:a.template("Copy of '<%- name %>'"),title:a.template(i("Copying history")+' "<%- name %>"'),submitLabel:i("Copy"),errorMessage:i("History could not be copied."),progressive:i("Copying history"),activeLabel:i("Copy only the active, non-deleted datasets"),allLabel:i("Copy all datasets including deleted ones"),anonWarning:i("As an anonymous user, unless you login or register, you will lose your current history ")+i("after copying this history. "),_template:a.template(["<% if( isAnon ){ %>",'
      ',"<%- anonWarning %>",i("You can"),' ',i("login here")," ",i("or")," ",' ',i("register here"),".","
      ","<% } %>","
      ",'
      ",'','","<% if( allowAll ){ %>","
      ","

      ",i("Choose which datasets from the original history to include:"),"

      ",'/>','',"
      ",'/>','',"<% } %>","
      "].join("")),_showAjaxIndicator:function(){var e='

      '+this.progressive+"...

      ";this.modal.$(".modal-body").empty().append(e).css({"margin-top":"8px"})},dialog:function(e,n,s){function l(){var i=e.$("#copy-modal-title").val();if(!i)return void e.$(".invalid-title").show();var s="copy-all"===e.$('input[name="copy-what"]:checked').val();e.$("button").prop("disabled",!0),d._showAjaxIndicator(),n.copy(!0,i,s).done(function(e){c.resolve(e)}).fail(function(e,a,o){var r={name:i,copyAllDatasets:s};t.ajaxErrorModal(n,e,r,d.errorMessage),c.rejectWith(c,arguments)}).done(function(){g&&e.hide()})}s=s||{};var d=this,c=o.Deferred(),h=s.nameFn||this.defaultName,u=h({name:n.get("name")}),p=s.allDatasets?"copy-all":"copy-non-deleted",f=!!a.isUndefined(s.allowAll)||s.allowAll,g=!!a.isUndefined(s.autoClose)||s.autoClose;this.modal=e;var m=s.closing_callback;return e.show(a.extend(s,{title:this.title({name:n.get("name")}),body:r(d._template({name:u,isAnon:Galaxy.user.isAnonymous(),allowAll:f,copyWhat:p,activeLabel:this.activeLabel,allLabel:this.allLabel,anonWarning:this.anonWarning})),buttons:a.object([[i("Cancel"),function(){e.hide()}],[this.submitLabel,l]]),height:"auto",closing_events:!0,closing_callback:function(e){e&&c.reject({cancelled:!0}),m&&m(e)}})),e.$("#copy-modal-title").focus().select(),e.$("#copy-modal-title").on("keydown",function(e){13===e.keyCode&&(e.preventDefault(),l())}),c}},s=a.extend({},n,{defaultName:a.template("imported: <%- name %>"),title:a.template(i("Importing history")+' "<%- name %>"'),submitLabel:i("Import"),errorMessage:i("History could not be imported."),progressive:i("Importing history"),activeLabel:i("Import only the active, non-deleted datasets"),allLabel:i("Import all datasets including deleted ones"),anonWarning:i("As an anonymous user, unless you login or register, you will lose your current history ")+i("after importing this history. ")}),l=function(t,i){i=i||{};var a=window.parent.Galaxy.modal||new e.View({});return i.useImport?s.dialog(a,t,i):n.dialog(a,t,i)};return l}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3),i(1),i(1))},function(e,t,i){var n,s;(function(a){n=[i(58),i(7),i(6)],s=function(e,t,i){"use strict";var n=e.DatasetListItemView,s=n.extend({className:n.prototype.className+" history-content",initialize:function(e,t){n.prototype.initialize.call(this,e,t)},toString:function(){var e=this.model?this.model+"":"(no model)";return"HDAListItemView("+e+")"}});return s.prototype.templates=function(){var e=t.wrapTemplate(['
      ','','
      ','<%- dataset.hid %> ','<%- dataset.name %>',"
      ","
      ",'',"<% _.each(_.sortBy(_.uniq(dataset.tags), function(x) { return x }), function(tag){ %>",'<% if (tag.indexOf("name:") == 0){ %>','<%- tag.slice(5) %>',"<% } %>","<% }); %>","","
      "],"dataset"),s=a.extend({},n.prototype.templates.warnings,{hidden:t.wrapTemplate(["<% if( !dataset.visible ){ %>",'
      ',i("This dataset has been hidden"),"
      ","<% } %>"],"dataset")});return a.extend({},n.prototype.templates,{titleBar:e,warnings:s})}(),{HDAListItemView:s}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a){n=[i(83),i(88),i(7),i(6)],s=function(e,t,i,n){"use strict";var s=e.DatasetAssociation,o=t.HistoryContentMixin,r=s.extend(i.mixin(o,{defaults:a.extend({},s.prototype.defaults,o.defaults,{history_content_type:"dataset",model_class:"HistoryDatasetAssociation"})}));return{HistoryDatasetAssociation:r}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a){n=[i(17),i(55),i(81),i(7),i(6)],s=function(e,t,i,n,s){"use strict";var o=t.DCListItemView,r=o.extend({className:o.prototype.className+" history-content",_setUpListeners:function(){o.prototype._setUpListeners.call(this),this.listenTo(this.model,{"change:tags change:populated change:visible":function(e,t){this.render()}})},_getFoldoutPanelClass:function(){switch(this.model.get("collection_type")){case"list":return i.ListCollectionView;case"paired":return i.PairCollectionView;case"list:paired":return i.ListOfPairsCollectionView;case"list:list":return i.ListOfListsCollectionView}throw new TypeError("Uknown collection_type: "+this.model.get("collection_type"))},_swapNewRender:function(t){o.prototype._swapNewRender.call(this,t);var i=this.model.get("populated")?e.OK:e.RUNNING;return this.$el.addClass("state-"+i),this.$el},toString:function(){var e=this.model?this.model+"":"(no model)";return"HDCAListItemView("+e+")"}});return r.prototype.templates=function(){var e=a.extend({},o.prototype.templates.warnings,{hidden:n.wrapTemplate(["<% if( !collection.visible ){ %>",'
      ',s("This collection has been hidden"),"
      ","<% } %>"],"collection")}),t=n.wrapTemplate(['
      ','','
      ','<%- collection.hid %> ','<%- collection.name %>',"
      ",'
      ','',"<% _.each(_.sortBy(_.uniq(collection.tags), function(x) { return x }), function(tag){ %>",'<% if (tag.indexOf("name:") == 0){ %>','<%- tag.slice(5) %>',"<% } %>","<% }); %>","","
      "],"collection");return a.extend({},o.prototype.templates,{warnings:e,titleBar:t})}(),{HDCAListItemView:r}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(3))},function(e,t,i){var n,s;(function(a){n=[i(17),i(7),i(6)],s=function(e,t,i){"use strict";var n={defaults:{history_id:null,history_content_type:null,hid:null,visible:!0},idAttribute:"type_id",hidden:function(){return!this.get("visible")},isVisible:function(e,t){var i=!0;return e||!this.get("deleted")&&!this.get("purged")||(i=!1),t||this.get("visible")||(i=!1),i},urlRoot:Galaxy.root+"api/histories/",url:function(){var e=this.urlRoot+this.get("history_id")+"/contents/"+this.get("history_content_type")+"s/"+this.get("id");return e},hide:function(e){return this.get("visible")?this.save({visible:!1},e):a.when()},unhide:function(e){return this.get("visible")?a.when():this.save({visible:!0},e)},toString:function(){return[this.get("type_id"),this.get("hid"),this.get("name")].join(":")}};return{HistoryContentMixin:n}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(64),i(147),i(7),i(6),i(96)],s=function(e,t,i,n){"use strict";var s="list",l=a.View.extend(i.LoggableMixin).extend({_logNamespace:s,viewClass:e.ListItemView,collectionClass:a.Collection,tagName:"div",className:"list-panel",fxSpeed:"fast",emptyMsg:n("This list is empty"),noneFoundMsg:n("No matching items found"),searchPlaceholder:n("search"),initialize:function(e,t){e=e||{},e.logger&&(this.logger=e.logger),this.log(this+".initialize:",e),this.fxSpeed=o.has(e,"fxSpeed")?e.fxSpeed:this.fxSpeed,this.filters=[],this.searchFor=e.searchFor||"",this.selecting=void 0===e.selecting||e.selecting,this.selected=e.selected||[],this.lastSelected=null,this.dragItems=e.dragItems||!1,this.viewClass=e.viewClass||this.viewClass,this.views=[],this.collection=e.collection||this._createDefaultCollection(),this.filters=e.filters||[],this.$scrollContainer=e.$scrollContainer||this.$scrollContainer,this.title=e.title||"",this.subtitle=e.subtitle||"",this._setUpListeners()},_setUpListeners:function(){return this.off(),this.on({error:function(e,t,i,n,s){console.error(e,t,i,n,s)},loading:function(){this._showLoadingIndicator("loading...",40)},"loading-done":function(){this._hideLoadingIndicator(40)}}),this.once("rendered",function(){this.trigger("rendered:initial",this)}),this._setUpCollectionListeners(),this._setUpViewListeners(),this},_createDefaultCollection:function(){return new this.collectionClass([])},_setUpCollectionListeners:function(){return this.log(this+"._setUpCollectionListeners",this.collection),this.stopListening(this.collection),this.listenTo(this.collection,{error:function(e,t,i,n,s){this.trigger("error",e,t,i,n,s)},update:function(e,t){var i=t.changes;return t.renderAll||i.added.length+i.removed.length>1?this.renderItems():1===i.added.length?this.addItemView(o.first(i.added),e,t):1===i.removed.length?this.removeItemView(o.first(i.removed),e,t):void 0}}),this},_setUpViewListeners:function(){this.log(this+"._setUpViewListeners"),this.on({"view:selected":function(e,t){if(t&&t.shiftKey&&this.lastSelected){var i=this.viewFromModelId(this.lastSelected);i&&this.selectRange(e,i)}else t&&t.altKey&&!this.selecting&&this.showSelectors();this.selected.push(e.model.id),this.lastSelected=e.model.id},"view:de-selected":function(e,t){this.selected=o.without(this.selected,e.model.id)}})},render:function(e){this.log(this+".render",e);var t=this._buildNewRender();return this._setUpBehaviors(t),this._queueNewRender(t,e),this},_buildNewRender:function(){this.debug(this+"(ListPanel)._buildNewRender");var e=r(this.templates.el({},this));return this._renderControls(e),this._renderTitle(e),this._renderSubtitle(e),this._renderSearch(e),this.renderItems(e),e},_renderControls:function(e){this.debug(this+"(ListPanel)._renderControls");var t=r(this.templates.controls({},this));return e.find(".controls").replaceWith(t),t},_renderTitle:function(e){},_renderSubtitle:function(e){},_queueNewRender:function(e,t){t=void 0===t?this.fxSpeed:t;var i=this;i.log("_queueNewRender:",e,t),r(i).queue("fx",[function(e){i.$el.fadeOut(t,e)},function(t){i._swapNewRender(e),t()},function(e){i.$el.fadeIn(t,e)},function(e){i.trigger("rendered",i),e()}])},_swapNewRender:function(e){return this.$el.empty().attr("class",this.className).append(e.children()),this.selecting&&this.showSelectors(0),this},_setUpBehaviors:function(e){return e=e||this.$el,this.$controls(e).find("[title]").tooltip(),this._renderMultiselectActionMenu(e),this},_renderMultiselectActionMenu:function(e){e=e||this.$el;var t=e.find(".list-action-menu"),i=this.multiselectActions();if(!i.length)return t.empty();var s=r(['
      ','",'","
      "].join("")),a=i.map(function(e){var t=['
    • ',e.html,"
    • "].join("");return r(t).click(function(t){return t.preventDefault(),e.func(t)})});return s.find("ul").append(a),t.replaceWith(s),s},multiselectActions:function(){return[]},$scrollContainer:function(e){return(e||this.$el).parent().parent()},$controls:function(e){return(e||this.$el).find("> .controls")},$list:function(e){return(e||this.$el).find("> .list-items")},$messages:function(e){return(e||this.$el).find("> .controls .messages")},$emptyMessage:function(e){return(e||this.$el).find("> .empty-message")},renderItems:function(e){e=e||this.$el;var t=this;t.log(this+".renderItems",e);var i=t.$list(e);t.freeViews();var n=t._filterCollection();return t.views=n.map(function(e){var i=t._createItemView(e);return i}),i.empty(),t.views.length&&t._attachItems(e),t._renderEmptyMessage(e).toggle(!t.views.length),t.trigger("views:ready",t.views),t.views},_filterCollection:function(){var e=this;return e.collection.filter(o.bind(e._filterItem,e))},_filterItem:function(e){var t=this;return o.every(t.filters.map(function(t){return t.call(e)}))&&(!t.searchFor||e.matchesAll(t.searchFor))},_createItemView:function(e){var t=this._getItemViewClass(e),i=o.extend(this._getItemViewOptions(e),{model:e}),n=new t(i);return this._setUpItemViewListeners(n),n},_destroyItemView:function(e){this.stopListening(e),this.views=o.without(this.views,e)},_destroyItemViews:function(e){var t=this;return t.views.forEach(function(e){t.stopListening(e)}),t.views=[],t},freeViews:function(){return this._destroyItemViews()},_getItemViewClass:function(e){return this.viewClass},_getItemViewOptions:function(e){return{fxSpeed:this.fxSpeed,expanded:!1,selectable:this.selecting,selected:o.contains(this.selected,e.id),draggable:this.dragItems}},_setUpItemViewListeners:function(e){var t=this;return this.listenTo(e,"all",function(){var e=Array.prototype.slice.call(arguments,0);e[0]="view:"+e[0],t.trigger.apply(t,e)}),this.listenTo(e,"draggable:dragstart",function(e,t){var i={},n=this.getSelectedModels();i=n.length?n.toJSON():[t.model.toJSON()],e.dataTransfer.setData("text",JSON.stringify(i))},this),t},_attachItems:function(e){var t=this;return this.$list(e).append(this.views.map(function(e){return t._renderItemView$el(e)})),this},_renderItemView$el:function(e){return e.render(0).$el},_renderEmptyMessage:function(e){this.debug("_renderEmptyMessage",e,this.searchFor);var t=this.searchFor?this.noneFoundMsg:this.emptyMsg;return this.$emptyMessage(e).text(t)},expandAll:function(){o.each(this.views,function(e){e.expand()})},collapseAll:function(){o.each(this.views,function(e){e.collapse()})},addItemView:function(e,t,i){var n=this,s=n._filterCollection().indexOf(e);if(s!==-1){var a=n._createItemView(e);return r(a).queue("fx",[function(e){n.$emptyMessage().is(":visible")?n.$emptyMessage().fadeOut(n.fxSpeed,e):e()},function(e){n._attachView(a,s),e()}]),a}},_attachView:function(e,t,i){i=!!o.isUndefined(i)||i,t=t||0;var n=this;return n.views.splice(t,0,e),n._insertIntoListAt(t,n._renderItemView$el(e).hide()),n.trigger("view:attached",e),i?e.$el.slideDown(n.fxSpeed,function(){n.trigger("view:attached:rendered")}):(e.$el.show(),n.trigger("view:attached:rendered")),e},_insertIntoListAt:function(e,t){var i=this.$list();return 0===e?i.prepend(t):i.children().eq(e-1).after(t),t},removeItemView:function(e,t,i){var n=this,s=o.find(n.views,function(t){return t.model===e});if(s)return n.views=o.without(n.views,s),n.trigger("view:removed",s),r({}).queue("fx",[function(e){s.$el.fadeOut(n.fxSpeed,e)},function(e){s.remove(),n.trigger("view:removed:rendered"),n.views.length?e():n._renderEmptyMessage().fadeIn(n.fxSpeed,e)}]),s},viewFromModelId:function(e){return o.find(this.views,function(t){return t.model.id===e})},viewFromModel:function(e){return e?this.viewFromModelId(e.id):void 0},viewsWhereModel:function(e){return this.views.filter(function(t){return o.isMatch(t.model.attributes,e)})},viewRange:function(e,t){if(e===t)return e?[e]:[];var i=this.views.indexOf(e),n=this.views.indexOf(t);return i===-1||n===-1?i===n?[]:i===-1?[t]:[e]:i .controls .search-query");return i.val()!==e&&i.val(e),this},clearSearch:function(e){return this.searchFor="",this.trigger("search:clear",this),this.$("> .controls .search-query").val(""),this.renderItems(),this},THROTTLE_SELECTOR_FX_AT:20,showSelectors:function(e){e=void 0!==e?e:this.fxSpeed,this.selecting=!0,this.$(".list-actions").slideDown(e),e=this.views.length>=this.THROTTLE_SELECTOR_FX_AT?0:e,o.each(this.views,function(t){t.showSelector(e)})},hideSelectors:function(e){e=void 0!==e?e:this.fxSpeed,this.selecting=!1,this.$(".list-actions").slideUp(e),e=this.views.length>=this.THROTTLE_SELECTOR_FX_AT?0:e,o.each(this.views,function(t){t.hideSelector(e)}),this.selected=[],this.lastSelected=null},toggleSelectors:function(){this.selecting?this.hideSelectors():this.showSelectors()},selectAll:function(e){o.each(this.views,function(t){t.select(e)})},deselectAll:function(e){this.lastSelected=null,o.each(this.views,function(t){t.deselect(e)})},selectRange:function(e,t){var i=this.viewRange(e,t);return o.each(i,function(e){e.select()}),i},getSelectedViews:function(){return o.filter(this.views,function(e){return e.selected})},getSelectedModels:function(){return new this.collection.constructor(o.map(this.getSelectedViews(),function(e){return e.model}))},_showLoadingIndicator:function(e,i,n){this.debug("_showLoadingIndicator",this.indicator,e,i,n),i=void 0!==i?i:this.fxSpeed,this.indicator||(this.indicator=new t(this.$el),this.debug("\t created",this.indicator)),this.$el.is(":visible")?(this.$el.fadeOut(i),this.indicator.show(e,i,n)):this.indicator.show(0,n)},_hideLoadingIndicator:function(e,t){this.debug("_hideLoadingIndicator",this.indicator,e,t),e=void 0!==e?e:this.fxSpeed,this.indicator&&this.indicator.hide(e,t)},scrollPosition:function(){return this.$scrollContainer().scrollTop()},scrollTo:function(e,t){return t=t||0,this.$scrollContainer().animate({scrollTop:e},t),this},scrollToTop:function(e){return this.scrollTo(0,e)},scrollToItem:function(e,t){return e?this:this},scrollToId:function(e,t){return this.scrollToItem(this.viewFromModelId(e),t)},events:{"click .select-all":"selectAll","click .deselect-all":"deselectAll"},toString:function(){return"ListPanel("+this.collection+")"}});l.prototype.templates=function(){var e=i.wrapTemplate(["
      ",'
      ','
      ','
      ',"
      "]),t=i.wrapTemplate(['
      ','
      ','
      <%- view.title %>
      ',"
      ",'
      <%- view.subtitle %>
      ','
      ','
      ','",'
      ','
      ','",'","
      ",'
      ',"
      ","
      ","
      "]);return{el:e,controls:t}}();var d=l.extend({modelCollectionKey:"contents",initialize:function(e){l.prototype.initialize.call(this,e),this.selecting=void 0!==e.selecting&&e.selecting,this.setModel(this.model,e)},setModel:function(e,t){if(t=t||{},this.debug(this+".setModel:",e,t),this.freeModel(),this.freeViews(),e){var i=this.model?this.model.get("id"):null;this.model=e,this.logger&&(this.model.logger=this.logger),this._setUpModelListeners(),this.stopListening(this.collection),this.collection=this.model[this.modelCollectionKey]||t.collection||this._createDefaultCollection(),this._setUpCollectionListeners(),i&&e.get("id")!==i&&this.trigger("new-model",this)}return this},freeModel:function(){return this.model&&this.stopListening(this.model),this},_setUpModelListeners:function(){return this.log(this+"._setUpModelListeners",this.model),this.listenTo(this.model,"error",function(){var e=Array.prototype.slice.call(arguments,0);e.unshift("error"),this.trigger.apply(this,e)},this),this.logger&&this.listenTo(this.model,"all",function(e){this.info(this+"(model)",e,arguments)}),this},_renderControls:function(e){this.debug(this+"(ModelListPanel)._renderControls");var t=this.model?this.model.toJSON():{},i=r(this.templates.controls(t,this));return e.find(".controls").replaceWith(i),i},toString:function(){return"ModelListPanel("+this.model+")"}});return d.prototype.templates=function(){var e=i.wrapTemplate(['
      ','
      ','
      <%- model.name %>
      ',"
      ",'
      <%- view.subtitle %>
      ','
      ','
      ','",'
      ','
      ','",'","
      ",'
      ',"
      ","
      ","
      "]);return o.extend(o.clone(l.prototype.templates),{controls:e})}(),{ListPanel:l,ModelListPanel:d}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(4),i(47),i(5),i(11),i(19),i(43),i(8),i(42),i(143)],s=function(e,t,i,n,s,l,d,c,h){var u=a.View.extend({initialize:function(e){var i=this;this.modal=parent.Galaxy.modal||new d.View,this.model=e&&e.model||new a.Model(e),this.deferred=new t,this.setElement(o("
      ").addClass("ui-form-composite").append(this.$message=o("
      ")).append(this.$header=o("
      ")).append(this.$steps=o("
      "))),o("body").append(this.$el),this._configure(),this.render(),o(window).resize(function(){i._refresh()})},_refresh:function(e){var t=r.reduce(this.$el.children(),function(e,t){return e+o(t).outerHeight()},0)-this.$steps.height()+90;this.$steps.css("height",o(window).height()-t)},_configure:function(){function t(e,t){for(var s=/\$\{(.+?)\}/g;match=s.exec(String(e));){var a=match[1];t(i.wp_inputs[a]=i.wp_inputs[a]||{label:a,name:a,type:"text",color:"hsl( "+100*++n+", 70%, 30% )",style:"ui-form-wp-source",links:[]})}}var i=this;this.forms=[],this.steps=[],this.links=[],this.parms=[],r.each(this.model.get("steps"),function(t,n){Galaxy.emit.debug("tool-form-composite::initialize()",n+" : Preparing workflow step.");var s=h[t.step_type],a=parseInt(n+1)+": "+(t.step_label||t.step_name);t.annotation&&(a+=" - "+t.annotation),t.step_version&&(a+=" (Galaxy Version "+t.step_version+")"),t=e.merge({index:n,title:r.escape(a),icon:s||"",help:null,citations:null,collapsible:!0,collapsed:n>0&&!i._isDataStep(t),sustain_version:!0,sustain_repeats:!0,sustain_conditionals:!0,narrow:!0,text_enable:"Edit",text_disable:"Undo",cls_enable:"fa fa-edit",cls_disable:"fa fa-undo",errors:t.messages,initial_errors:!0,cls:"ui-portlet-narrow",hide_operations:!0,needs_refresh:!1,always_refresh:"tool"!=t.step_type},t),i.steps[n]=t,i.links[n]=[],i.parms[n]={}}),r.each(this.steps,function(e,t){s.visitInputs(e.inputs,function(e,n){i.parms[t][n]=e})}),r.each(this.steps,function(e,t){r.each(e.output_connections,function(e){r.each(i.steps,function(n,s){n.step_index===e.input_step_index&&i.links[t].push(n)})})}),r.each(this.steps,function(e,t){r.each(i.steps,function(n,s){var a={};r.each(e.output_connections,function(e){n.step_index===e.input_step_index&&(a[e.input_name]=e)}),r.each(i.parms[s],function(i,n){var s=a[n];s&&(i.type="hidden",i.help=i.step_linked?i.help+", ":"",i.help+="Output dataset '"+s.output_name+"' from step "+(parseInt(t)+1),i.step_linked=i.step_linked||[],i.step_linked.push(e))})})});var n=0;this.wp_inputs={},r.each(this.steps,function(e,n){r.each(i.parms[n],function(i,n){t(i.value,function(t){t.links.push(e),i.wp_linked=!0,i.type="text",i.backdrop=!0,i.style="ui-form-wp-target"})}),r.each(e.post_job_actions,function(e){r.each(e.action_arguments,function(e){t(e,function(){})})})}),r.each(this.steps,function(t,n){if("tool"==t.step_type){var a=!0;s.visitInputs(t.inputs,function(n,s,o){var r=n.value&&"RuntimeValue"==n.value.__class__,l=["data","data_collection"].indexOf(n.type)!=-1,d=o[n.data_ref];n.step_linked&&!i._isDataStep(n.step_linked)&&(a=!1),n.options&&(0==n.options.length&&!a||n.wp_linked)&&(n.is_workflow=!0),d&&(n.is_workflow=d.step_linked&&!i._isDataStep(d.step_linked)||n.wp_linked),(l||n.value&&"RuntimeValue"==n.value.__class__&&!n.step_linked)&&(t.collapsed=!1),r&&(n.value=n.default_value),n.flavor="workflow",r||l||"hidden"===n.type||n.wp_linked||(n.optional||!e.isEmpty(n.value)&&""!==n.value)&&(n.collapsible_value=n.value,n.collapsible_preview=!0)})}})},render:function(){var e=this;this.deferred.reset(),this._renderHeader(),this._renderMessage(),this._renderParameters(),this._renderHistory(),r.each(this.steps,function(t){e._renderStep(t)})},_renderHeader:function(){var e=this;this.execute_btn=new i.Button({icon:"fa-check",title:"Run workflow",cls:"btn btn-primary",onclick:function(){e._execute()}}),this.$header.addClass("ui-form-header").empty().append(new i.Label({title:"Workflow: "+this.model.get("name")}).$el).append(this.execute_btn.$el)},_renderMessage:function(){this.$message.empty(),this.model.get("has_upgrade_messages")&&this.$message.append(new i.Message({message:"Some tools in this workflow may have changed since it was last saved or some errors were found. The workflow may still run, but any new options will have default values. Please review the messages below to make a decision about whether the changes will affect your analysis.",status:"warning",persistent:!0,fade:!1}).$el);var e=this.model.get("step_version_changes");e&&e.length>0&&this.$message.append(new i.Message({message:"Some tools are being executed with different versions compared to those available when this workflow was last saved because the other versions are not or no longer available on this Galaxy instance. To upgrade your workflow and dismiss this message simply edit the workflow and re-save it.",status:"warning",persistent:!0,fade:!1}).$el)},_renderParameters:function(){var e=this;this.wp_form=null,r.isEmpty(this.wp_inputs)||(this.wp_form=new n({title:"Workflow Parameters",inputs:this.wp_inputs,cls:"ui-portlet-narrow",onchange:function(){r.each(e.wp_form.input_list,function(t,i){r.each(t.links,function(t){e._refreshStep(t)})})}}),this._append(this.$steps.empty(),this.wp_form.$el))},_renderHistory:function(){this.history_form=new n({cls:"ui-portlet-narrow",title:"History Options",inputs:[{type:"conditional",name:"new_history",test_param:{name:"check",label:"Send results to a new history",type:"boolean",value:"false",help:""},cases:[{value:"true",inputs:[{name:"name",label:"History name",type:"text",value:this.model.get("name")}]}]}]}),this._append(this.$steps,this.history_form.$el)},_renderStep:function(t){var i=this,s=null;this.deferred.execute(function(a){if(i.$steps.addClass("ui-steps"),"tool"==t.step_type)t.postchange=function(i,n){var s={tool_id:t.id,tool_version:t.version,inputs:o.extend(!0,{},n.data.create())};n.wait(!0),Galaxy.emit.debug("tool-form-composite::postchange()","Sending current state.",s),e.request({type:"POST",url:Galaxy.root+"api/tools/"+t.id+"/build",data:s,success:function(e){n.update(e),n.wait(!1),Galaxy.emit.debug("tool-form-composite::postchange()","Received new model.",e),i.resolve()},error:function(e){Galaxy.emit.debug("tool-form-composite::postchange()","Refresh request failed.",e), -i.reject()}})},s=new l(t),t.post_job_actions&&t.post_job_actions.length&&s.portlet.append(o("
      ").addClass("ui-form-element-disabled").append(o("
      ").addClass("ui-form-title").html("Job Post Actions")).append(o("
      ").addClass("ui-form-preview").html(r.reduce(t.post_job_actions,function(e,t){return e+" "+t.short_str},""))));else{var d=["data_input","data_collection_input"].indexOf(t.step_type)!=-1;r.each(t.inputs,function(e){e.flavor="module",e.hide_label=d}),s=new n(e.merge({title:t.title,onchange:function(){r.each(i.links[t.index],function(e){i._refreshStep(e)})},inputs:t.inputs&&t.inputs.length>0?t.inputs:[{type:"hidden",name:"No options available.",ignore:null}]},t))}i.forms[t.index]=s,i._append(i.$steps,s.$el),i._refresh(),t.needs_refresh&&i._refreshStep(t),s.portlet[i.show_progress?"disable":"enable"](),i.show_progress&&i.execute_btn.model.set({wait:!0,wait_text:"Preparing...",percentage:100*(t.index+1)/i.steps.length}),Galaxy.emit.debug("tool-form-composite::initialize()",t.index+" : Workflow step state ready.",t),setTimeout(function(){a.resolve()},0)})},_refreshStep:function(e){var t=this,i=this.forms[e.index];i?(r.each(t.parms[e.index],function(e,n){if(e.step_linked||e.wp_linked){var s=i.field_list[i.data.match(n)];if(s){var a=void 0;if(e.step_linked)a={values:[]},r.each(e.step_linked,function(e){t._isDataStep(e)&&(value=t.forms[e.index].data.create().input,value&&r.each(value.values,function(e){a.values.push(e)}))}),!e.multiple&&a.values.length>0&&(a={values:[a.values[0]]});else if(e.wp_linked){a=e.value;for(var o=/\$\{(.+?)\}/g;match=o.exec(e.value);){var l=t.wp_form.field_list[t.wp_form.data.match(match[1])],d=l&&l.value();d&&(a=a.split(match[0]).join(d))}}void 0!==a&&s.value(a)}}}),i.trigger("change")):e.needs_refresh=!0},_refreshHistory:function(){var e=this,t=parent.Galaxy&&parent.Galaxy.currHistoryPanel&&parent.Galaxy.currHistoryPanel.model;this._refresh_history&&clearTimeout(this._refresh_history),t&&t.refresh().success(function(){0===t.numOfUnfinishedShownContents()&&(e._refresh_history=setTimeout(function(){e._refreshHistory()},t.UPDATE_DELAY))})},_execute:function(){var e=this;this.show_progress=!0,this._enabled(!1),this.deferred.execute(function(t){setTimeout(function(){t.resolve(),e._submit()},0)})},_submit:function(){var t=this,i=this.history_form.data.create(),n={new_history_name:i["new_history|name"]?i["new_history|name"]:null,history_id:i["new_history|name"]?null:this.model.get("history_id"),replacement_params:this.wp_form?this.wp_form.data.create():{},parameters:{},parameters_normalized:!0,batch:!0},s=!0;for(var a in this.forms){var r=this.forms[a],l=r.data.create(),d=t.steps[a],h=d.step_index;r.trigger("reset");for(var u in l){var p=l[u],f=r.data.match(u),g=(r.field_list[f],r.input_list[f]);if(!g.step_linked){if(s=this._isDataStep(d)?p&&p.values&&p.values.length>0:g.optional||g.is_workflow&&""!==p||!g.is_workflow&&null!==p,!s){r.highlight(f);break}n.parameters[h]=n.parameters[h]||{},n.parameters[h][u]=l[u]}}if(!s)break}s?(Galaxy.emit.debug("tool-form-composite::submit()","Validation complete.",n),e.request({type:"POST",url:Galaxy.root+"api/workflows/"+this.model.id+"/invocations",data:n,success:function(e){if(Galaxy.emit.debug("tool-form-composite::submit","Submission successful.",e),t.$el.children().hide(),t.$el.append(t._templateSuccess(e)),o.isArray(e)&&e.length>0){t.$el.append(o("
      ",{id:"webhook-view"}));new c.WebhookView({urlRoot:Galaxy.root+"api/webhooks/workflow",toolId:n.tool_id,toolVersion:n.tool_version})}t._refreshHistory()},error:function(e){Galaxy.emit.debug("tool-form-composite::submit","Submission failed.",e);var i=!1;if(e&&e.err_data)for(var s in t.forms){var a=t.forms[s],o=e.err_data[a.model.get("step_index")];if(o){var r=a.data.matchResponse(o);for(var l in r){a.highlight(l,r[l]),i=!0;break}}}i||t.modal.show({title:"Workflow submission failed",body:t._templateError(n,e&&e.err_msg),buttons:{Close:function(){t.modal.hide()}}})},complete:function(){t._enabled(!0)}})):(t._enabled(!0),Galaxy.emit.debug("tool-form-composite::submit()","Validation failed.",n))},_append:function(e,t){e.append("

      ").append(t)},_enabled:function(e){this.execute_btn.model.set({wait:!e,wait_text:"Sending...",percentage:-1}),this.wp_form&&this.wp_form.portlet[e?"enable":"disable"](),this.history_form&&this.history_form.portlet[e?"enable":"disable"](),r.each(this.forms,function(t){t&&t.portlet[e?"enable":"disable"]()})},_isDataStep:function(e){lst=o.isArray(e)?e:[e];for(var t=0;t0?o("

      ").addClass("donemessagelarge").append(o("

      ").html("Successfully invoked workflow "+e.sanitize(this.model.get("name"))+""+(t.length>1?" "+t.length+" times":"")+".")).append(o("

      ").append("").text("You can check the status of queued jobs and view the resulting data by refreshing the History pane. When the job has been run the status will change from 'running' to 'finished' if completed successfully or 'error' if problems were encountered.")):this._templateError(t,"Invalid success response. No invocations found.")},_templateError:function(e,t){return o("

      ").addClass("errormessagelarge").append(o("

      ").text("The server could not complete the request. Please contact the Galaxy Team if this error persists. "+(JSON.stringify(t)||""))).append(o("

      ").text(JSON.stringify(e,null,4)))}});return{View:u}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1),i(3))},,function(e,t,i){var n,s;(function(a,o){n=[i(6)],s=function(e){"use strict";function t(t,i,n){return Galaxy.modal.show({title:i,body:t,closing_events:!0,buttons:{Ok:function(){Galaxy.modal.hide()}}}),Galaxy.modal.$el.addClass("error-modal"),n&&(Galaxy.modal.$(".error-details").add(Galaxy.modal.$('button:contains("Details")')).remove(),a("
      ").addClass("error-details").hide().appendTo(Galaxy.modal.$(".modal-content")).append([a("

      ").text(h),a("

      ").text(JSON.stringify(n,null,"  "))]),a('").appendTo(Galaxy.modal.$(".buttons")).click(function(){Galaxy.modal.$(".error-details").toggle()})),Galaxy.modal}function i(i,n,s){if(i){if(i=e(i),n=e(n)||e("Error:"),window.Galaxy&&Galaxy.modal)return t(i,n,s);alert(n+"\n\n"+i),console.log("error details:",JSON.stringify(s))}}function n(){return i(e("You appear to be offline. Please check your connection and try again."),e("Offline?"))}function s(){return i(e("Galaxy is currently unreachable. Please try again in a few minutes.")+" "+d,e("Cannot connect to Galaxy"))}function r(t,n,s,a,o){a=a||c,a+=" "+d,o=o||e("An error occurred");var r=l(t,n,s);return i(a,o,r)}function l(e,t,i){return{raven:o.result(window.Raven,"lastEventId"),userAgent:navigator.userAgent,onLine:navigator.onLine,version:o.result(Galaxy.config,"version_major"),xhr:o.omit(t,o.functions(t)),options:o.omit(i,"xhr"),url:o.result(Galaxy.lastAjax,"url"),data:o.result(Galaxy.lastAjax,"data"),model:o.result(e,"toJSON",e+""),user:o.omit(o.result(Galaxy.user,"toJSON"),"email")}}var d=e("Please contact a Galaxy administrator if the problem persists."),c=e("An error occurred while updating information with the server."),h=e("The following information can assist the developers in finding the source of the error:");return{errorModal:i,offlineErrorModal:n,badGatewayErrorModal:s,ajaxErrorModal:r}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1),i(3))},,,function(e,t,i){var n,s,a;(function(i,o){!function(i){s=[],n=i,a="function"==typeof n?n.apply(t,s):n,!(void 0!==a&&(e.exports=a))}(function(){i.fn.extend({hoverhighlight:function(e,t){return e=e||"body",this.length?(o(this).each(function(){var i=o(this),n=i.data("target");n&&i.mouseover(function(i){o(n,e).css({background:t})}).mouseout(function(e){o(n).css({background:""})})}),this):this}})})}).call(t,i(1),i(1))},function(e,t,i){var n,s,a;(function(i,o){!function(i){s=[],n=i,a="function"==typeof n?n.apply(t,s):n,!(void 0!==a&&(e.exports=a))}(function(){function e(e,n){function s(e){var t=i(this).parent().children("input");t.val("").trigger("searchInput.clear").blur(),n.onclear()}function a(e,t){return t?(i(this).trigger("search.search",t),void("function"==typeof n.onfirstsearch&&g?(g=!1,n.onfirstsearch(t)):n.onsearch(t))):s()}function r(){return['"].join("")}function l(){return i(r()).focus(function(e){i(this).select()}).keyup(function(e){if(e.preventDefault(),e.stopPropagation(),e.which===u&&n.escWillClear)s.call(this,e);else{var t=i(this).val();(e.which===p||n.minSearchLen&&t.length>=n.minSearchLen)&&a.call(this,e,t)}}).val(n.initialVal)}function d(){return i([''].join("")).tooltip({placement:"bottom"}).click(function(e){s.call(this,e)})}function c(){return i([''].join("")).hide().tooltip({placement:"bottom"})}function h(){f.find(".search-loading").toggle(),f.find(".search-clear").toggle()}var u=27,p=13,f=i(e),g=!0,m={initialVal:"",name:"search",placeholder:"search",classes:"",onclear:function(){},onfirstsearch:null,onsearch:function(e){},minSearchLen:0,escWillClear:!0,oninit:function(){}};return"string"===o.type(n)?("toggle-loading"===n&&h(),f):("object"===o.type(n)&&(n=o.extend(!0,{},m,n)),f.addClass("search-input").prepend([l(),d(),c()]))}var t=window._l||function(e){return e};o.fn.extend({searchInput:function(t){return this.each(function(){return e(this,t)})}})})}).call(t,i(1),i(1))},,function(e,t,i){var n,s;n=[],s=function(){function e(e,t){var i=/(-?[0-9\.]+)/g,n=e.toString().toLowerCase()||"",s=t.toString().toLowerCase()||"",a=String.fromCharCode(0),o=n.replace(i,a+"$1"+a).split(a),r=s.replace(i,a+"$1"+a).split(a),l=new Date(n).getTime(),d=l?new Date(s).getTime():null;if(d){if(ld)return 1}for(var c,h,u=0,p=Math.max(o.length,r.length);uh)return 1}return 0}return e}.apply(t,n),!(void 0!==s&&(e.exports=s))},,,function(e,t,i){(function(t){var n=i(5),s=i(131);CurrentHistoryView=i(128).CurrentHistoryView,_l=i(6);var a=t.View.extend({initialize:function(e,i){var s=this;this.userIsAnonymous=Galaxy.user.isAnonymous(),this.allow_user_dataset_purge=i.config.allow_user_dataset_purge,this.root=i.root,this.historyView=new CurrentHistoryView({className:CurrentHistoryView.prototype.className+" middle",purgeAllowed:this.allow_user_dataset_purge,linkTarget:"galaxy_main"}),Galaxy.currHistoryPanel=this.historyView,Galaxy.currHistoryPanel.listenToGalaxy(Galaxy),this.buttonRefresh=new n.ButtonLink({id:"history-refresh-button",title:"Refresh history",cls:"panel-header-button",icon:"fa fa-refresh",onclick:function(){s.historyView.loadCurrentHistory()}}),this.buttonOptions=new n.ButtonLink({id:"history-options-button",title:"History options",cls:"panel-header-button",target:"galaxy_main",icon:"fa fa-cog",href:this.root+"root/history_options"}),this.buttonViewMulti=new n.ButtonLink({id:"history-view-multi-button",title:"View all histories",cls:"panel-header-button",icon:"fa fa-columns",href:this.root+"history/view_multiple"}),this.model=new t.Model({cls:"history-right-panel",title:_l("History"),buttons:[this.buttonRefresh,this.buttonOptions,this.buttonViewMulti]}),this.setElement(this._template()),this.historyView.setElement(this.$el),this.historyView.connectToQuotaMeter(Galaxy.quotaMeter),this.historyView.loadCurrentHistory(),Galaxy.listenTo(this.historyView,"history-size-change",function(){Galaxy.user.fetch({url:Galaxy.user.urlRoot()+"/"+(Galaxy.user.id||"current")})})},render:function(){this.optionsMenu=s(this.buttonOptions.$el,{anonymous:this.userIsAnonymous,purgeAllowed:this.allow_user_dataset_purge,root:this.root}),this.buttonViewMulti.$el[this.userIsAnonymous?"hide":"show"]()},_template:function(e){return['
      '].join("")},toString:function(){return"historyPanel"}});e.exports=a}).call(t,i(2))},function(e,t,i){(function(t,n){var s=i(66),a=i(139),o=i(6),r=(i(90),t.View.extend({initialize:function(e,i){var n=i.config;this.root=i.root,this.stored_workflow_menu_entries=n.stored_workflow_menu_entries||[];var r=new s.ToolSearch({hidden:!1}),l=new s.ToolCollection(n.toolbox);this.tool_panel=new s.ToolPanel({tool_search:r,tools:l,layout:n.toolbox_in_panel}),this.tool_panel_view=new s.ToolPanelView({model:this.tool_panel}),this.upload_button=new a({nginx_upload_path:n.nginx_upload_path,ftp_upload_site:n.ftp_upload_site,default_genome:n.default_genome,default_extension:n.default_extension}),Galaxy.upload=this.upload_button,this.model=new t.Model({title:o("Tools"),buttons:[this.upload_button]}),this.setElement(this._template())},render:function(){var e=this;this.tool_panel.get("layout").size()>0&&(this.$el.prepend(this.tool_panel_view.$el),this.tool_panel_view.render()),e.$("#internal-workflows").append(e._templateAllWorkflow({title:o("All workflows"),href:"workflow"})),n.each(this.stored_workflow_menu_entries,function(t){e.$("#internal-workflows").append(e._templateWorkflowLink({title:t.stored_workflow.name,href:"workflow/run?id="+t.encoded_stored_workflow_id}))})},_templateTool:function(e){return['"].join("")},_templateAllWorkflow:function(e){return['"].join("")},_templateWorkflowLink:function(e){return['"].join("")},_template:function(){return['
      ','",'
      ','
      ','
      ',"",o("Workflows"),"","
      ",'
      ','
      ',"
      ","
      "].join("")},toString:function(){return"toolPanel"}}));e.exports=r}).call(t,i(2),i(3))},,,,,,,,,,,,,,,,,function(e,t,i){var n,s;(function(a,o){n=[i(55),i(82),i(7),i(6)],s=function(e,t,i,n){"use strict";var s=e.DCListItemView,r=s.extend({initialize:function(e){s.prototype.initialize.call(this,e)},toString:function(){var e=this.model?this.model+"":"(no model)";return"DCListItemEdit("+e+")"}}),l=e.DCEListItemView,d=l.extend({initialize:function(e){l.prototype.initialize.call(this,e)},toString:function(){var e=this.model?this.model+"":"(no model)";return"DCEListItemEdit("+e+")"}}),c=t.DatasetListItemEdit.extend({initialize:function(e){t.DatasetListItemEdit.prototype.initialize.call(this,e)},_fetchModelDetails:function(){var e=this;return e.model.inReadyState()&&!e.model.hasDetails()?e.model.fetch({silent:!0}):a.when()},_renderDeleteButton:function(){return null},toString:function(){var e=this.model?this.model+"":"(no model)";return"DatasetDCEListItemEdit("+e+")"}});c.prototype.templates=function(){return o.extend({},t.DatasetListItemEdit.prototype.templates,{titleBar:e.DatasetDCEListItemView.prototype.templates.titleBar})}();var h=e.NestedDCDCEListItemView.extend({toString:function(){var e=this.model?this.model+"":"(no model)";return"NestedDCDCEListItemEdit("+e+")"}});return{DCListItemEdit:r,DCEListItemEdit:d,DatasetDCEListItemEdit:c,NestedDCDCEListItemEdit:h}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(1),i(3))},function(e,t,i){var n,s;n=[i(81),i(56),i(119),i(7),i(65),i(25),i(6),i(24)],s=function(e,t,i,n,s,a,o){"use strict";var r=e.CollectionView,l=r.extend({DatasetDCEViewClass:i.DatasetDCEListItemEdit,NestedDCDCEViewClass:i.NestedDCDCEListItemEdit,initialize:function(e){r.prototype.initialize.call(this,e)},_setUpBehaviors:function(e){if(e=e||this.$el,r.prototype._setUpBehaviors.call(this,e),this.model&&Galaxy.user&&!Galaxy.user.isAnonymous()){this.tagsEditorShown=!0;var t=this,i="> .controls .name";e.find(i).attr("title",o("Click to rename collection")).tooltip({placement:"bottom"}).make_text_editable({on_finish:function(e){var n=t.model.get("name");e&&e!==n?(t.$el.find(i).text(e),t.model.save({name:e}).fail(function(){t.$el.find(i).text(t.model.previous("name"))})):t.$el.find(i).text(n)}}),this.tagsEditor=new s.TagsEditor({model:this.model,el:e.find(".tags-display"),onshowFirstTime:function(){this.render()},usePrompt:!1}),this.tagsEditor.toggle(!0)}},toString:function(){return"CollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}}),d=l.extend({DatasetDCEViewClass:i.DatasetDCEListItemEdit,toString:function(){return"ListCollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}}),c=d.extend({toString:function(){return"PairCollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}}),h=c.extend({_setUpBehaviors:function(e){r.prototype._setUpBehaviors.call(this,e)},toString:function(){return"NestedPairCollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}}),u=l.extend({NestedDCDCEViewClass:i.NestedDCDCEListItemEdit.extend({foldoutPanelClass:h}),toString:function(){return"ListOfPairsCollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}}),p=l.extend({NestedDCDCEViewClass:i.NestedDCDCEListItemEdit.extend({foldoutPanelClass:h}),toString:function(){return"ListOfListsCollectionViewEdit("+(this.model?this.model.get("name"):"")+")"}});return{CollectionViewEdit:l,ListCollectionViewEdit:d,PairCollectionViewEdit:c,ListOfPairsCollectionViewEdit:u,ListOfListsCollectionViewEdit:p}}.apply(t,n),!(void 0!==s&&(e.exports=s))},function(e,t,i){var n,s;(function(a,o,r,l){n=[i(151),i(98),i(80),i(7),i(6),i(95)],s=function(e,t,i,n,s){"use strict";function d(e){function t(){return i.length||(i=[new RegExp(this.filters[0]),new RegExp(this.filters[1])]),i}e=e||{},e.createPair=e.createPair||function(e){e=e||{};var t=e.listA.splice(e.indexA,1)[0],i=e.listB.splice(e.indexB,1)[0],n=e.listB.indexOf(t),s=e.listA.indexOf(i);return n!==-1&&e.listB.splice(n,1),s!==-1&&e.listA.splice(s,1),this._pair(t,i,{silent:!0})};var i=[];return e.preprocessMatch=e.preprocessMatch||function(e){var i=t.call(this);return o.extend(e,{matchTo:e.matchTo.name.replace(i[0],""),possible:e.possible.name.replace(i[1],"")})},function(t){this.debug("autopair _strategy ---------------------------"),t=t||{};var i,n=t.listA,s=t.listB,a=0,o={score:0,index:null},r=[];for(this.debug("starting list lens:",n.length,s.length),this.debug("bestMatch (starting):",JSON.stringify(o,null," "));a=c?r.push(e.createPair.call(this,{listA:n,indexA:a,listB:s,indexB:o.index})):a+=1,!n.length||!s.length)return r}return this.debug("paired:",JSON.stringify(r,null," ")),this.debug("autopair _strategy ---------------------------"),r}}function c(e,t){var i=e.toJSON();return f(i,{historyId:e.historyId,defaultHideSourceItems:t})}var h="collections",u=a.View.extend(n.LoggableMixin).extend({_logNamespace:h,tagName:"li",className:"dataset paired",initialize:function(e){this.pair=e.pair||{}},template:o.template(['<%- pair.forward.name %>','','<%- pair.name %>',"",'<%- pair.reverse.name %>'].join("")),render:function(){return this.$el.attr("draggable",!0).data("pair",this.pair).html(this.template({pair:this.pair})).addClass("flex-column-container"),this},events:{dragstart:"_dragstart",dragend:"_dragend",dragover:"_sendToParent",drop:"_sendToParent"},_dragstart:function(e){e.currentTarget.style.opacity="0.4",e.originalEvent&&(e=e.originalEvent),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",JSON.stringify(this.pair)),this.$el.parent().trigger("pair.dragstart",[this])},_dragend:function(e){e.currentTarget.style.opacity="1.0",this.$el.parent().trigger("pair.dragend",[this])},_sendToParent:function(e){this.$el.parent().trigger(e)},toString:function(){return"PairView("+this.pair.name+")"}}),p=a.View.extend(n.LoggableMixin).extend(i.CollectionCreatorMixin).extend({_logNamespace:h,className:"list-of-pairs-collection-creator collection-creator flex-row-container",initialize:function(e){this.metric("PairedCollectionCreator.initialize",e),e=o.defaults(e,{datasets:[],filters:this.DEFAULT_FILTERS,automaticallyPair:!0,strategy:"lcs",matchPercentage:.9,twoPassAutopairing:!0}),this.initialList=e.datasets,this.historyId=e.historyId,this.filters=this.commonFilters[e.filters]||this.commonFilters[this.DEFAULT_FILTERS],o.isArray(e.filters)&&(this.filters=e.filters),this.automaticallyPair=e.automaticallyPair,this.strategy=this.strategies[e.strategy]||this.strategies[this.DEFAULT_STRATEGY],o.isFunction(e.strategy)&&(this.strategy=e.strategy),this.matchPercentage=e.matchPercentage,this.twoPassAutopairing=e.twoPassAutopairing,this.removeExtensions=!0,this.oncancel=e.oncancel,this.oncreate=e.oncreate,this.autoscrollDist=e.autoscrollDist||24,this.unpairedPanelHidden=!1,this.pairedPanelHidden=!1,this.$dragging=null,this.blocking=!1,this._setUpCommonSettings(e),this._setUpBehaviors(),this._dataSetUp()},commonFilters:{illumina:["_1","_2"],Rs:["_R1","_R2"]},DEFAULT_FILTERS:"illumina",strategies:{simple:"autopairSimple",lcs:"autopairLCS",levenshtein:"autopairLevenshtein"},DEFAULT_STRATEGY:"lcs",_dataSetUp:function(){this.paired=[],this.unpaired=[],this.selectedIds=[],this._sortInitialList(),this._ensureIds(),this.unpaired=this.initialList.slice(0),this.automaticallyPair&&(this.autoPair(),this.once("rendered:initial",function(){this.trigger("autopair")}))},_sortInitialList:function(){this._sortDatasetList(this.initialList)},_sortDatasetList:function(e){return e.sort(function(e,i){return t(e.name,i.name)}),e},_ensureIds:function(){return this.initialList.forEach(function(e){e.hasOwnProperty("id")||(e.id=o.uniqueId())}),this.initialList},_splitByFilters:function(){function e(e,t){return t.test(e.name)}var t=this.filters.map(function(e){return new RegExp(e)}),i=[[],[]];return this.unpaired.forEach(function(n){t.forEach(function(t,s){e(n,t)&&i[s].push(n)})}),i},_addToUnpaired:function(e){var i=function(n,s){if(n===s)return n;var a=Math.floor((s-n)/2)+n,o=t(e.name,this.unpaired[a].name);if(o<0)return i(n,a);if(o>0)return i(a+1,s);for(;this.unpaired[a]&&this.unpaired[a].name===e.name;)a++;return a}.bind(this);this.unpaired.splice(i(0,this.unpaired.length),0,e)},autoPair:function(e){var t=this._splitByFilters(),i=[];return this.twoPassAutopairing&&(i=this.autopairSimple({listA:t[0],listB:t[1]}),t=this._splitByFilters()),e=e||this.strategy,t=this._splitByFilters(),i=i.concat(this[e].call(this,{listA:t[0],listB:t[1]}))},autopairSimple:d({scoreThreshold:function(){return 1},match:function(e){return e=e||{},e.matchTo===e.possible?{index:e.index,score:1}:e.bestMatch}}),autopairLevenshtein:d({scoreThreshold:function(){return this.matchPercentage},match:function(t){t=t||{};var i=e(t.matchTo,t.possible),n=1-i/Math.max(t.matchTo.length,t.possible.length);return n>t.bestMatch.score?{index:t.index,score:n}:t.bestMatch}}),autopairLCS:d({scoreThreshold:function(){return this.matchPercentage},match:function(e){e=e||{};var t=this._naiveStartingAndEndingLCS(e.matchTo,e.possible).length,i=t/Math.max(e.matchTo.length,e.possible.length);return i>e.bestMatch.score?{index:e.index,score:i}:e.bestMatch}}),_naiveStartingAndEndingLCS:function(e,t){for(var i="",n="",s=0,a=0;s=0&&a>=0&&e[s]===t[a];)n=[e[s],n].join(""),s-=1,a-=1;return i+n},_pair:function(e,t,i){i=i||{},this.debug("_pair:",e,t);var n=this._createPair(e,t,i.name);return this.paired.push(n),this.unpaired=o.without(this.unpaired,e,t),i.silent||this.trigger("pair:new",n),n},_createPair:function(e,t,i){if(!e||!t||e===t)throw new Error("Bad pairing: "+[JSON.stringify(e),JSON.stringify(t)]);return i=i||this._guessNameForPair(e,t),{forward:e,name:i,reverse:t}},_guessNameForPair:function(e,t,i){i=void 0!==i?i:this.removeExtensions;var n=e.name,s=t.name,a=this._naiveStartingAndEndingLCS(n.replace(new RegExp(this.filters[0]),""),s.replace(new RegExp(this.filters[1]),""));if(i){var o=a.lastIndexOf(".");if(o>0){var r=a.slice(o,a.length);a=a.replace(r,""),n=n.replace(r,""),s=s.replace(r,"")}}return a||n+" & "+s},_unpair:function(e,t){if(t=t||{},!e)throw new Error("Bad pair: "+JSON.stringify(e));return this.paired=o.without(this.paired,e),this._addToUnpaired(e.forward),this._addToUnpaired(e.reverse),t.silent||this.trigger("pair:unpair",[e]),e},unpairAll:function(){for(var e=[];this.paired.length;)e.push(this._unpair(this.paired[0],{silent:!0}));this.trigger("pair:unpair",e)},_pairToJSON:function(e,t){return t=t||"hda",{collection_type:"paired",src:"new_collection",name:e.name,element_identifiers:[{name:"forward",id:e.forward.id,src:t},{name:"reverse",id:e.reverse.id,src:t}]}},createList:function(e){var t=this,i=Galaxy.root+"api/histories/"+this.historyId+"/contents/dataset_collections",n={type:"dataset_collection",collection_type:"list:paired",hide_source_items:t.hideOriginals||!1,name:o.escape(e||t.$(".collection-name").val()),element_identifiers:t.paired.map(function(e){return t._pairToJSON(e)})};return t.blocking=!0,r.ajax(i,{type:"POST",contentType:"application/json",dataType:"json",data:JSON.stringify(n)}).always(function(){t.blocking=!1}).fail(function(e,i,n){t._ajaxErrHandler(e,i,n)}).done(function(e,i,n){t.trigger("collection:created",e,i,n),t.metric("collection:created",e),"function"==typeof t.oncreate&&t.oncreate.call(this,e,i,n)})},_ajaxErrHandler:function(e,t,i){this.error(e,t,i);var n=s("An error occurred while creating this collection");e&&(n+=0===e.readyState&&0===e.status?": "+s("Galaxy could not be reached and may be updating.")+s(" Try again in a few minutes."):e.responseJSON?"
      "+JSON.stringify(e.responseJSON)+"
      ":": "+i),creator._showAlert(n,"alert-danger")},render:function(e,t){return this.$el.empty().html(this.templates.main()),this._renderHeader(e),this._renderMiddle(e),this._renderFooter(e),this._addPluginComponents(),this.trigger("rendered",this),this},_renderHeader:function(e,t){var i=this.$(".header").empty().html(this.templates.header()).find(".help-content").prepend(l(this.templates.helpContent()));return this._renderFilters(),i},_renderFilters:function(){return this.$(".forward-column .column-header input").val(this.filters[0]).add(this.$(".reverse-column .column-header input").val(this.filters[1]))},_renderMiddle:function(e,t){var i=this.$(".middle").empty().html(this.templates.middle());return this.unpairedPanelHidden?this.$(".unpaired-columns").hide():this.pairedPanelHidden&&this.$(".paired-columns").hide(),this._renderUnpaired(),this._renderPaired(),i},_renderUnpaired:function(e,t){var i,n,a=this,o=[],r=this._splitByFilters();return this.$(".forward-column .title").text([r[0].length,s("unpaired forward")].join(" ")),this.$(".forward-column .unpaired-info").text(this._renderUnpairedDisplayStr(this.unpaired.length-r[0].length)),this.$(".reverse-column .title").text([r[1].length,s("unpaired reverse")].join(" ")),this.$(".reverse-column .unpaired-info").text(this._renderUnpairedDisplayStr(this.unpaired.length-r[1].length)),this.$(".unpaired-columns .column-datasets").empty(),this.$(".autopair-link").toggle(0!==this.unpaired.length),0===this.unpaired.length?void this._renderUnpairedEmpty():(n=r[1].map(function(e,t){return void 0!==r[0][t]&&r[0][t]!==e&&o.push(a._renderPairButton()),a._renderUnpairedDataset(e)}),i=r[0].map(function(e){return a._renderUnpairedDataset(e)}),i.length||n.length?(this.$(".unpaired-columns .forward-column .column-datasets").append(i).add(this.$(".unpaired-columns .paired-column .column-datasets").append(o)).add(this.$(".unpaired-columns .reverse-column .column-datasets").append(n)),void this._adjUnpairedOnScrollbar()):void this._renderUnpairedNotShown())},_renderUnpairedDisplayStr:function(e){return["(",e," ",s("filtered out"),")"].join("")},_renderUnpairedDataset:function(e){return l("
    • ").attr("id","dataset-"+e.id).addClass("dataset unpaired").attr("draggable",!0).addClass(e.selected?"selected":"").append(l("").addClass("dataset-name").text(e.name)).data("dataset",e)},_renderPairButton:function(){return l("
    • ").addClass("dataset unpaired").append(l("").addClass("dataset-name").text(s("Pair these datasets")))},_renderUnpairedEmpty:function(){var e=l('
      ').text("("+s("no remaining unpaired datasets")+")");return this.$(".unpaired-columns .paired-column .column-datasets").empty().prepend(e),e},_renderUnpairedNotShown:function(){var e=l('
      ').text("("+s("no datasets were found matching the current filters")+")");return this.$(".unpaired-columns .paired-column .column-datasets").empty().prepend(e),e},_adjUnpairedOnScrollbar:function(){var e=this.$(".unpaired-columns").last(),t=this.$(".unpaired-columns .reverse-column .dataset").first();if(t.length){var i=e.offset().left+e.outerWidth(),n=t.offset().left+t.outerWidth(),s=Math.floor(i)-Math.floor(n);this.$(".unpaired-columns .forward-column").css("margin-left",s>0?s:0)}},_renderPaired:function(e,t){if(this.$(".paired-column-title .title").text([this.paired.length,s("paired")].join(" ")),this.$(".unpair-all-link").toggle(0!==this.paired.length),0===this.paired.length)return void this._renderPairedEmpty();this.$(".remove-extensions-link").show(),this.$(".paired-columns .column-datasets").empty();var i=this;this.paired.forEach(function(e,t){var n=new u({pair:e});i.$(".paired-columns .column-datasets").append(n.render().$el).append(['"].join(""))})},_renderPairedEmpty:function(){var e=l('
      ').text("("+s("no paired datasets yet")+")");return this.$(".paired-columns .column-datasets").empty().prepend(e),e},footerSettings:{".hide-originals":"hideOriginals",".remove-extensions":"removeExtensions"},_addPluginComponents:function(){this._chooseFiltersPopover(".choose-filters-link"),this.$(".help-content i").hoverhighlight(".collection-creator","rgba( 64, 255, 255, 1.0 )")},_chooseFiltersPopover:function(e){function t(e,t){return['"].join("")}var i=l(o.template(['
      ','
      ',s("Choose from the following filters to change which unpaired reads are shown in the display"),":
      ",o.values(this.commonFilters).map(function(e){return t(e[0],e[1])}).join(""),"
      "].join(""))({}));return this.$(e).popover({container:".collection-creator",placement:"bottom",html:!0,content:i})},_validationWarning:function(e,t){var i="validation-warning";"name"===e&&(e=this.$(".collection-name").add(this.$(".collection-name-prompt")),this.$(".collection-name").focus().select()),t?(e=e||this.$("."+i),e.removeClass(i)):e.addClass(i)},_setUpBehaviors:function(){return this.once("rendered",function(){this.trigger("rendered:initial",this)}),this.on("pair:new",function(){ -this._renderUnpaired(),this._renderPaired(),this.$(".paired-columns").scrollTop(8e6)}),this.on("pair:unpair",function(e){this._renderUnpaired(),this._renderPaired(),this.splitView()}),this.on("filter-change",function(){this.filters=[this.$(".forward-unpaired-filter input").val(),this.$(".reverse-unpaired-filter input").val()],this.metric("filter-change",this.filters),this._renderFilters(),this._renderUnpaired()}),this.on("autopair",function(){this._renderUnpaired(),this._renderPaired();var e,t=null;this.paired.length?(t="alert-success",e=this.paired.length+" "+s("pairs created"),this.unpaired.length||(e+=": "+s("all datasets have been successfully paired"),this.hideUnpaired(),this.$(".collection-name").focus())):e=s(["Could not automatically create any pairs from the given dataset names.","You may want to choose or enter different filters and try auto-pairing again.","Close this message using the X on the right to view more help."].join(" ")),this._showAlert(e,t)}),this},events:{"click .more-help":"_clickMoreHelp","click .less-help":"_clickLessHelp","click .main-help":"_toggleHelp","click .header .alert button":"_hideAlert","click .forward-column .column-title":"_clickShowOnlyUnpaired","click .reverse-column .column-title":"_clickShowOnlyUnpaired","click .unpair-all-link":"_clickUnpairAll","change .forward-unpaired-filter input":function(e){this.trigger("filter-change")},"focus .forward-unpaired-filter input":function(e){l(e.currentTarget).select()},"click .autopair-link":"_clickAutopair","click .choose-filters .filter-choice":"_clickFilterChoice","click .clear-filters-link":"_clearFilters","change .reverse-unpaired-filter input":function(e){this.trigger("filter-change")},"focus .reverse-unpaired-filter input":function(e){l(e.currentTarget).select()},"click .forward-column .dataset.unpaired":"_clickUnpairedDataset","click .reverse-column .dataset.unpaired":"_clickUnpairedDataset","click .paired-column .dataset.unpaired":"_clickPairRow","click .unpaired-columns":"clearSelectedUnpaired","mousedown .unpaired-columns .dataset":"_mousedownUnpaired","click .paired-column-title":"_clickShowOnlyPaired","mousedown .flexible-partition-drag":"_startPartitionDrag","click .paired-columns .dataset.paired":"selectPair","click .paired-columns":"clearSelectedPaired","click .paired-columns .pair-name":"_clickPairName","click .unpair-btn":"_clickUnpair","dragover .paired-columns .column-datasets":"_dragoverPairedColumns","drop .paired-columns .column-datasets":"_dropPairedColumns","pair.dragstart .paired-columns .column-datasets":"_pairDragstart","pair.dragend .paired-columns .column-datasets":"_pairDragend","change .remove-extensions":function(e){this.toggleExtensions()},"change .collection-name":"_changeName","keydown .collection-name":"_nameCheckForEnter","change .hide-originals":"_changeHideOriginals","click .cancel-create":"_cancelCreate","click .create-collection":"_clickCreate"},_clickShowOnlyUnpaired:function(e){this.$(".paired-columns").is(":visible")?this.hidePaired():this.splitView()},_clickShowOnlyPaired:function(e){this.$(".unpaired-columns").is(":visible")?this.hideUnpaired():this.splitView()},hideUnpaired:function(e,t){this.unpairedPanelHidden=!0,this.pairedPanelHidden=!1,this._renderMiddle(e,t)},hidePaired:function(e,t){this.unpairedPanelHidden=!1,this.pairedPanelHidden=!0,this._renderMiddle(e,t)},splitView:function(e,t){return this.unpairedPanelHidden=this.pairedPanelHidden=!1,this._renderMiddle(e,t),this},_clickUnpairAll:function(e){this.metric("unpairAll"),this.unpairAll()},_clickAutopair:function(e){var t=this.autoPair();this.metric("autopair",t.length,this.unpaired.length),this.trigger("autopair")},_clickFilterChoice:function(e){var t=l(e.currentTarget);this.$(".forward-unpaired-filter input").val(t.data("forward")),this.$(".reverse-unpaired-filter input").val(t.data("reverse")),this._hideChooseFilters(),this.trigger("filter-change")},_hideChooseFilters:function(){this.$(".choose-filters-link").popover("hide"),this.$(".popover").css("display","none")},_clearFilters:function(e){this.$(".forward-unpaired-filter input").val(""),this.$(".reverse-unpaired-filter input").val(""),this.trigger("filter-change")},_clickUnpairedDataset:function(e){return e.stopPropagation(),this.toggleSelectUnpaired(l(e.currentTarget))},toggleSelectUnpaired:function(e,t){t=t||{};var i=e.data("dataset"),n=void 0!==t.force?t.force:!e.hasClass("selected");return e.length&&void 0!==i?(n?(e.addClass("selected"),t.waitToPair||this.pairAllSelected()):e.removeClass("selected"),e):e},pairAllSelected:function(e){e=e||{};var t=this,i=[],n=[],s=[];return t.$(".unpaired-columns .forward-column .dataset.selected").each(function(){i.push(l(this).data("dataset"))}),t.$(".unpaired-columns .reverse-column .dataset.selected").each(function(){n.push(l(this).data("dataset"))}),i.length=n.length=Math.min(i.length,n.length),i.forEach(function(e,i){try{s.push(t._pair(e,n[i],{silent:!0}))}catch(e){t.error(e)}}),s.length&&!e.silent&&this.trigger("pair:new",s),s},clearSelectedUnpaired:function(){this.$(".unpaired-columns .dataset.selected").removeClass("selected")},_mousedownUnpaired:function(e){if(e.shiftKey){var t=this,i=l(e.target).addClass("selected"),n=function(e){t.$(e.target).filter(".dataset").addClass("selected")};i.parent().on("mousemove",n),l(document).one("mouseup",function(e){i.parent().off("mousemove",n),t.pairAllSelected()})}},_clickPairRow:function(e){var t=l(e.currentTarget).index(),i=l(".unpaired-columns .forward-column .dataset").eq(t).data("dataset"),n=l(".unpaired-columns .reverse-column .dataset").eq(t).data("dataset");this._pair(i,n)},_startPartitionDrag:function(e){function t(e){n.$(".flexible-partition-drag").css("color",""),l("body").css("cursor","").unbind("mousemove",i)}function i(e){var t=e.pageY-s;n.adjPartition(t)||l("body").trigger("mouseup"),n._adjUnpairedOnScrollbar(),s+=t}var n=this,s=e.pageY;l("body").css("cursor","ns-resize"),n.$(".flexible-partition-drag").css("color","black"),l("body").mousemove(i),l("body").one("mouseup",t)},adjPartition:function(e){var t=this.$(".unpaired-columns"),i=this.$(".paired-columns"),n=parseInt(t.css("height"),10),s=parseInt(i.css("height"),10);n=Math.max(10,n+e),s-=e;var a=e<0;if(a){if(this.unpairedPanelHidden)return!1;if(n<=10)return this.hideUnpaired(),!1}else this.unpairedPanelHidden&&(t.show(),this.unpairedPanelHidden=!1);if(a)this.pairedPanelHidden&&(i.show(),this.pairedPanelHidden=!1);else{if(this.pairedPanelHidden)return!1;if(s<=15)return this.hidePaired(),!1}return t.css({height:n+"px",flex:"0 0 auto"}),!0},selectPair:function(e){e.stopPropagation(),l(e.currentTarget).toggleClass("selected")},clearSelectedPaired:function(e){this.$(".paired-columns .dataset.selected").removeClass("selected")},_clickPairName:function(e){e.stopPropagation();var t=l(e.currentTarget),i=t.parent().parent(),n=i.index(".dataset.paired"),s=this.paired[n],a=prompt("Enter a new name for the pair:",s.name);a&&(s.name=a,s.customizedName=!0,t.text(s.name))},_clickUnpair:function(e){var t=Math.floor(l(e.currentTarget).index(".unpair-btn"));this._unpair(this.paired[t])},_dragoverPairedColumns:function(e){e.preventDefault();var t=this.$(".paired-columns .column-datasets");this._checkForAutoscroll(t,e.originalEvent.clientY);var i=this._getNearestPairedDatasetLi(e.originalEvent.clientY);l(".element-drop-placeholder").remove();var n=l('
      ');i.length?i.before(n):t.append(n)},_checkForAutoscroll:function(e,t){var i=2,n=e.offset(),s=e.scrollTop(),a=t-n.top,o=n.top+e.outerHeight()-t;a>=0&&a=0&&oe&&a-o",e.name)},toString:function(){return"PairedCollectionCreator"},templates:o.extend({},i.CollectionCreatorMixin._creatorTemplates,{header:o.template(['",'
      ','','',"
      ",'
      ','
      ','
      ','
      ','',s("Unpaired forward"),"",'',"
      ",'
      ','',"
      ","
      ","
      ",'",'
      ','
      ','
      ','',s("Unpaired reverse"),"",'',"
      ",'
      ','',"
      ","
      ","
      ","
      "].join("")),middle:o.template(['
      ','
      ','
        ',"
        ",'
        ','
          ',"
          ",'
          ','
            ',"
            ","
            ",'
            ','
            ','
            ','
            ','',"
            ",'',s("Unpair all"),"","
            ","
            ",'
            ','
              ',"
              "].join("")),footer:o.template(['
              ','
              ','",'","
              ",'
              ','','
              ',s("Name"),":
              ","
              ","
              ",'
              ','
              ','",'
              ','",'","
              ","
              ",'
              ','","
              ","
              "].join("")),helpContent:o.template(["

              ",s(["Collections of paired datasets are ordered lists of dataset pairs (often forward and reverse reads). ","These collections can be passed to tools and workflows in order to have analyses done on each member of ","the entire group. This interface allows you to create a collection, choose which datasets are paired, ","and re-order the final collection."].join("")),"

              ","

              ",s(['Unpaired datasets are shown in the unpaired section ',"(hover over the underlined words to highlight below). ",'Paired datasets are shown in the paired section.',"

                To pair datasets, you can:","
              • Click a dataset in the ",'forward column ',"to select it then click a dataset in the ",'reverse column.',"
              • ",'
              • Click one of the "Pair these datasets" buttons in the ','middle column ',"to pair the datasets in a particular row.","
              • ",'
              • Click "Auto-pair" ',"to have your datasets automatically paired based on name.","
              • ","
              "].join("")),"

              ","

              ",s(["

                You can filter what is shown in the unpaired sections by:","
              • Entering partial dataset names in either the ",'forward filter or ','reverse filter.',"
              • ","
              • Choosing from a list of preset filters by clicking the ",'"Choose filters" link.',"
              • ","
              • Entering regular expressions to match dataset names. See: ",'MDN\'s JavaScript Regular Expression Tutorial. ',"Note: forward slashes (\\) are not needed.","
              • ","
              • Clearing the filters by clicking the ",'"Clear filters" link.',"
              • ","
              "].join("")),"

              ","

              ",s(["To unpair individual dataset pairs, click the ",'unpair buttons ( ). ','Click the "Unpair all" link to unpair all pairs.'].join("")),"

              ","

              ",s(['You can include or remove the file extensions (e.g. ".fastq") from your pair names by toggling the ','"Remove file extensions from pair names?" control.'].join("")),"

              ","

              ",s(['Once your collection is complete, enter a name and ','click "Create list". ',"(Note: you do not have to pair all unpaired datasets to finish.)"].join("")),"

              "].join(""))})}),f=function(e,t){var i,n=r.Deferred();if(t=o.defaults(t||{},{datasets:e,oncancel:function(){Galaxy.modal.hide(),n.reject("cancelled")},oncreate:function(e,t){Galaxy.modal.hide(),n.resolve(t)}}),!window.Galaxy||!Galaxy.modal)throw new Error("Galaxy or Galaxy.modal not found");return i=new p(t),Galaxy.modal.show({title:"Create a collection of paired datasets",body:i.$el,width:"80%",height:"800px",closing_events:!0}),i.render(),window.creator=i,n};return{PairedCollectionCreator:p,pairedCollectionCreatorModal:f,createListOfPairsCollection:c}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3),i(1),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(57),i(60),i(7),i(6)],s=function(e,t,i,n){"use strict";function s(e,t){var i=e.toJSON(),n=u(i,{defaultHideSourceItems:t,creationFn:function(t,i,n){return t=[{name:"forward",src:"hda",id:t[0].id},{name:"reverse",src:"hda",id:t[1].id}],e.createHDCA(t,"paired",i,n)}});return n}var l="collections",d=a.View.extend(i.LoggableMixin).extend({_logNamespace:l,tagName:"li",className:"collection-element",initialize:function(e){this.element=e.element||{},this.identifier=e.identifier},render:function(){return this.$el.attr("data-element-id",this.element.id).html(this.template({identifier:this.identifier,element:this.element})),this},template:o.template(['<%- identifier %>','<%- element.name %>'].join("")),destroy:function(){this.off(),this.$el.remove()},toString:function(){return"DatasetCollectionElementView()"}}),c=e.ListCollectionCreator,h=c.extend({elementViewClass:d,collectionClass:t.HistoryPairDatasetCollection,className:"pair-collection-creator collection-creator flex-row-container",_mangleDuplicateNames:function(){},render:function(e,t){return 2===this.workingElements.length?c.prototype.render.call(this,e,t):this._renderInvalid(e,t)},_renderList:function(e,t){var i=this,n=r("
              "),s=i.$list();o.each(this.elementViews,function(e){e.destroy(),i.removeElementView(e)}),n.append(i._createForwardElementView().$el),n.append(i._createReverseElementView().$el),s.empty().append(n.children()),o.invoke(i.elementViews,"render")},_createForwardElementView:function(){return this._createElementView(this.workingElements[0],{identifier:"forward"})},_createReverseElementView:function(){return this._createElementView(this.workingElements[1],{identifier:"reverse"})},_createElementView:function(e,t){var i=new this.elementViewClass(o.extend(t,{element:e}));return this.elementViews.push(i),i},swap:function(){this.workingElements=[this.workingElements[1],this.workingElements[0]],this._renderList()},events:o.extend(o.clone(c.prototype.events),{"click .swap":"swap"}),templates:o.extend(o.clone(c.prototype.templates),{middle:o.template(['",'
              ',"
              "].join("")),helpContent:o.template(["

              ",n(["Pair collections are permanent collections containing two datasets: one forward and one reverse. ","Often these are forward and reverse reads. The pair collections can be passed to tools and ","workflows in order to have analyses done on both datasets. This interface allows ","you to create a pair, name it, and swap which is forward and which reverse."].join("")),"

              ","
                ","
              • ",n(['Click the "Swap" link to make your forward dataset the reverse ',"and the reverse dataset forward."].join("")),"
              • ","
              • ",n(['Click the "Cancel" button to exit the interface.'].join("")),"
              • ","

              ","

              ",n(['Once your collection is complete, enter a name and ','click "Create list".'].join("")),"

              "].join("")),invalidInitial:o.template(['
              ','
              ','',"<% if( _.size( problems ) ){ %>",n("The following selections could not be included due to problems"),"
                <% _.each( problems, function( problem ){ %>","
              • <%- problem.element.name %>: <%- problem.text %>
              • ","<% }); %>
              ","<% } else if( _.size( elements ) === 0 ){ %>",n("No datasets were selected"),".","<% } else if( _.size( elements ) === 1 ){ %>",n("Only one dataset was selected"),": <%- elements[0].name %>","<% } else if( _.size( elements ) > 2 ){ %>",n("Too many datasets were selected"),': <%- _.pluck( elements, "name" ).join( ", ") %>',"<% } %>","
              ",n("Two (and only two) elements are needed for the pair"),". ",n("You may need to "),'',n("cancel")," ",n("and reselect new elements"),".","
              ","
              ","
              ",'"].join(""))}),toString:function(){return"PairCollectionCreator"}}),u=function(t,i){return i=i||{},i.title=n("Create a collection from a pair of datasets"),e.collectionCreatorModal(t,i,h)};return{PairCollectionCreator:h,pairCollectionCreatorModal:u,createPairCollection:s}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(3),i(1))},function(e,t,i){var n,s;(function(a,o){n=[i(4),i(46),i(5),i(11)],s=function(e,t,i,n){var s=a.View.extend({initialize:function(){this.setElement("
              "),this.model=new a.Model({dataset_id:Galaxy.params.dataset_id}),this.render()},render:function(){var t=Galaxy.root+"dataset/edit",i=this;e.get({url:t,data:{dataset_id:i.model.get("dataset_id")},success:function(e){i.render_attribute_page(i,e)},error:function(e){var t={status:"error",message:"Error occured while loading the dataset.",persistent:!0,cls:"errormessage"};i.display_message(t,i.$(".response-message"))}})},render_attribute_page:function(e,t){var i={message:t.message,status:t.status,persistent:!0,cls:t.status+"message"};e.$el.empty().append(e._templateHeader()),e.display_message(i,e.$(".response-message")),e.create_tabs(t,e.$(".edit-attr"))},call_ajax:function(e,t,i){var n=Galaxy.root+"dataset/edit";o.ajax({type:"PUT",url:n,data:t,success:function(t){e.render_attribute_page(e,t),e.reload_history()},error:function(t){var i={status:"error",message:"Error occured while saving. Please fill all the required fields and try again.",persistent:!0,cls:"errormessage"};e.display_message(i,e.$(".response-message"))}})},display_message:function(e,t){t.empty().html(new i.Message(e).$el)},create_tabs:function(e,i){var n=this;n.tabs=new t.View,n.tabs.add({id:"attributes",title:"Attributes",icon:"fa fa-bars",tooltip:"Edit dataset attributes",$el:n._getAttributesFormTemplate(e)}),n.tabs.add({id:"convert",title:"Convert",icon:"fa-gear",tooltip:"Convert to new format",$el:n._getConvertFormTemplate(e)}),n.tabs.add({id:"datatype",title:"Datatypes",icon:"fa-database",tooltip:"Change data type",$el:n._getChangeDataTypeFormTemplate(e)}),n.tabs.add({id:"permissions",title:"Permissions",icon:"fa-user",tooltip:"Permissions",$el:n._getPermissionsFormTemplate(e)}),i.append(n.tabs.$el),n.tabs.showTab("attributes")},_templateHeader:function(){return'

              Edit Dataset Attributes

              '},_getAttributesFormTemplate:function(e){var t=this,s=new n({title:"Edit attributes",inputs:e.edit_attributes_inputs,operations:{submit_editattr:new i.ButtonIcon({tooltip:"Save attributes of the dataset.",icon:"fa-floppy-o ",title:"Save attributes",onclick:function(){t._submit(t,s,e,"edit_attributes")}}),submit_autocorrect:new i.ButtonIcon({tooltip:"This will inspect the dataset and attempt to correct the values of fields if they are not accurate.",icon:"fa-undo ",title:"Auto-detect",onclick:function(){t._submit(t,s,e,"auto-detect")}})}});return s.$el},_getConvertFormTemplate:function(e){var t=this,s=new n({title:"Convert to new format",inputs:e.convert_inputs,operations:{submit:new i.ButtonIcon({tooltip:"Convert the datatype to a new format.",title:"Convert datatype",icon:"fa-exchange ",onclick:function(){t._submit(t,s,e,"convert")}})}});return s.$el},_getChangeDataTypeFormTemplate:function(e){var t=this,s=new n({title:"Change datatype",inputs:e.convert_datatype_inputs,operations:{submit:new i.ButtonIcon({tooltip:"Change the datatype to a new type.",title:"Change datatype",icon:"fa-exchange ",onclick:function(){t._submit(t,s,e,"change")}})}});return s.$el},_getPermissionsFormTemplate:function(e){var t=this;if(e.can_manage_dataset){var s=new n({title:"Manage dataset permissions on "+e.display_name,inputs:e.permission_inputs,operations:{submit:new i.ButtonIcon({tooltip:"Save permissions.",title:"Save permissions",icon:"fa-floppy-o ",onclick:function(){t._submit(t,s,e,"permissions")}})}});return s.$el}var s=new n({title:"View permissions",inputs:e.permission_inputs});return s.$el},_submit:function(e,t,i,n){var s=t.data.create();switch(s.dataset_id=i.dataset_id,n){case"edit_attributes":s.save="Save";break;case"auto-detect":s.detect="Auto-detect";break;case"convert":null!==s.target_type&&s.target_type&&(s.dataset_id=i.dataset_id,s.convert_data="Convert");break;case"change":s.change="Save";break;case"permissions":var a={};a.permissions=JSON.stringify(s),a.update_roles_button="Save",a.dataset_id=i.dataset_id,s=a}e.call_ajax(e,s)},reload_history:function(){window.Galaxy&&window.Galaxy.currHistoryPanel.loadCurrentHistory()}});return{View:s}}.apply(t,n),!(void 0!==s&&(e.exports=s))}).call(t,i(2),i(1))},function(e,t,i){var n,s;(function(a,o,r){n=[i(12)],s=function(e){var t=a.View.extend({initialize:function(e){var t=this;this.setElement(o("
              ")),this.model=new a.Model(e),this.item=this.model.get("item"),o.ajax({url:Galaxy.root+this.item+"/"+this.model.get("action_id"),success:function(e){e.dict_format=!0,t.model.set(e),t.render()}})},render:function(){var t=new e(this.model.attributes);this.$el.empty().append(t.$el),this.$el.append(this._templateShared())},_templateShared:function(){var e=this,t=o("

              "+this.model.get("plural")+" shared with you by others

              "),i=this.model.attributes;if(i.shared_by_others&&i.shared_by_others.length>0){var n=o('
              TitleOwner
              ');r.each(i.shared_by_others,function(t,i){var s=Galaxy.root+e.item+"/display_by_username_and_slug?username="+t.username+"&slug="+t.slug;n.append('
            1. '+r.escape(t.title)+""+r.escape(t.username)+"
              You can tell Galaxy to download data from web by entering URL in this box (one per line). You can also directly paste the contents of a file.
              ', '
              ', '
              '].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CitationView: CitationView,\n\t CitationListView: CitationListView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))\n\n/***/ },\n/* 55 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(58), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, DATASET_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var FoldoutListItemView = LIST_ITEM.FoldoutListItemView,\n\t ListItemView = LIST_ITEM.ListItemView;\n\t /** @class Read only view for DatasetCollection.\n\t */\n\t var DCListItemView = FoldoutListItemView.extend(\n\t /** @lends DCListItemView.prototype */{\n\t\n\t className: FoldoutListItemView.prototype.className + \" dataset-collection\",\n\t id: function () {\n\t return ['dataset_collection', this.model.get('id')].join('-');\n\t },\n\t\n\t /** override to add linkTarget */\n\t initialize: function (attributes) {\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t this.hasUser = attributes.hasUser;\n\t FoldoutListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t FoldoutListItemView.prototype._setUpListeners.call(this);\n\t this.listenTo(this.model, 'change', function (model, options) {\n\t // if the model has changed deletion status render it entirely\n\t if (_.has(model.changed, 'deleted')) {\n\t this.render();\n\t\n\t // if the model has been decorated after the fact with the element count,\n\t // render the subtitle where the count is displayed\n\t } else if (_.has(model.changed, 'element_count')) {\n\t this.$('> .title-bar .subtitle').replaceWith(this._renderSubtitle());\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... rendering\n\t /** render a subtitle to show the user what sort of collection this is */\n\t _renderSubtitle: function () {\n\t return $(this.templates.subtitle(this.model.toJSON(), this));\n\t },\n\t\n\t // ......................................................................... foldout\n\t /** override to add linktarget to sub-panel */\n\t _getFoldoutPanelOptions: function () {\n\t var options = FoldoutListItemView.prototype._getFoldoutPanelOptions.call(this);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t hasUser: this.hasUser\n\t });\n\t },\n\t\n\t /** override to not catch sub-panel selectors */\n\t $selector: function () {\n\t return this.$('> .selector');\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DCListItemView.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, FoldoutListItemView.prototype.templates.warnings, {\n\t error: BASE_MVC.wrapTemplate([\n\t // error during index fetch - show error on dataset\n\t '<% if( model.error ){ %>', '
              ', _l('There was an error getting the data for this collection'), ': <%- model.error %>', '
              ', '<% } %>']),\n\t purged: BASE_MVC.wrapTemplate(['<% if( model.purged ){ %>', '
              ', _l('This collection has been deleted and removed from disk'), '
              ', '<% } %>']),\n\t deleted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.deleted && !model.purged ){ %>', '
              ', _l('This collection has been deleted'), '
              ', '<% } %>'])\n\t });\n\t\n\t // use element identifier\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
              ', '
              ', '<%- collection.element_identifier || collection.name %>', '
              ', '
              ', '
              '], 'collection');\n\t\n\t // use element identifier\n\t var subtitleTemplate = BASE_MVC.wrapTemplate(['
              ', '<% var countText = collection.element_count? ( collection.element_count + \" \" ) : \"\"; %>', '<% if( collection.collection_type === \"list\" ){ %>', _l('a list of <%- countText %>datasets'), '<% } else if( collection.collection_type === \"paired\" ){ %>', _l('a pair of datasets'), '<% } else if( collection.collection_type === \"list:paired\" ){ %>', _l('a list of <%- countText %>dataset pairs'), '<% } else if( collection.collection_type === \"list:list\" ){ %>', _l('a list of <%- countText %>dataset lists'), '<% } %>', '
              '], 'collection');\n\t\n\t return _.extend({}, FoldoutListItemView.prototype.templates, {\n\t warnings: warnings,\n\t titleBar: titleBarTemplate,\n\t subtitle: subtitleTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for DatasetCollectionElement.\n\t */\n\t var DCEListItemView = ListItemView.extend(\n\t /** @lends DCEListItemView.prototype */{\n\t\n\t /** add the DCE class to the list item */\n\t className: ListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log('DCEListItemView.initialize:', attributes);\n\t ListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DCEListItemView.prototype.templates = function () {\n\t\n\t // use the element identifier here - since that will persist and the user will need it\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
              ', '
              ', '<%- element.element_identifier %>', '
              ', '
              ', '
              '], 'element');\n\t\n\t return _.extend({}, ListItemView.prototype.templates, {\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also an DatasetAssociation\n\t * (a dataset contained in a dataset collection).\n\t */\n\t var DatasetDCEListItemView = DATASET_LI.DatasetListItemView.extend(\n\t /** @lends DatasetDCEListItemView.prototype */{\n\t\n\t className: DATASET_LI.DatasetListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log('DatasetDCEListItemView.initialize:', attributes);\n\t DATASET_LI.DatasetListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** In this override, only get details if in the ready state.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetDCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetDCEListItemView.prototype.templates = function () {\n\t\n\t // use the element identifier here and not the dataset name\n\t //TODO:?? can we steal the DCE titlebar?\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
              ', '', '
              ', '<%- element.element_identifier %>', '
              ', '
              '], 'element');\n\t\n\t return _.extend({}, DATASET_LI.DatasetListItemView.prototype.templates, {\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested DC).\n\t */\n\t var NestedDCDCEListItemView = DCListItemView.extend(\n\t /** @lends NestedDCDCEListItemView.prototype */{\n\t\n\t className: DCListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** In this override, add the state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t DCListItemView.prototype._swapNewRender.call(this, $newRender);\n\t var state = this.model.get('state') || 'ok';\n\t this.$el.addClass('state-' + state);\n\t return this.$el;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'NestedDCDCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DCListItemView: DCListItemView,\n\t DCEListItemView: DCEListItemView,\n\t DatasetDCEListItemView: DatasetDCEListItemView,\n\t NestedDCDCEListItemView: NestedDCDCEListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 56 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, Backbone, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(83), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_MODEL, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /*\n\t Notes:\n\t \n\t Terminology:\n\t DatasetCollection/DC : a container of datasets or nested DatasetCollections\n\t Element/DatasetCollectionElement/DCE : an item contained in a DatasetCollection\n\t HistoryDatasetCollectionAssociation/HDCA: a DatasetCollection contained in a history\n\t \n\t \n\t This all seems too complex unfortunately:\n\t \n\t - Terminology collision between DatasetCollections (DCs) and Backbone Collections.\n\t - In the DatasetCollections API JSON, DC Elements use a 'Has A' stucture to *contain*\n\t either a dataset or a nested DC. This would make the hierarchy much taller. I've\n\t decided to merge the contained JSON with the DC element json - making the 'has a'\n\t relation into an 'is a' relation. This seems simpler to me and allowed a lot of\n\t DRY in both models and views, but may make tracking or tracing within these models\n\t more difficult (since DatasetCollectionElements are now *also* DatasetAssociations\n\t or DatasetCollections (nested)). This also violates the rule of thumb about\n\t favoring aggregation over inheritance.\n\t - Currently, there are three DatasetCollection subclasses: List, Pair, and ListPaired.\n\t These each should a) be usable on their own, b) be usable in the context of\n\t nesting within a collection model (at least in the case of ListPaired), and\n\t c) be usable within the context of other container models (like History or\n\t LibraryFolder, etc.). I've tried to separate/extract classes in order to\n\t handle those three situations, but it's proven difficult to do in a simple,\n\t readable manner.\n\t - Ideally, histories and libraries would inherit from the same server models as\n\t dataset collections do since they are (in essence) dataset collections themselves -\n\t making the whole nested structure simpler. This would be a large, error-prone\n\t refactoring and migration.\n\t \n\t Many of the classes and heirarchy are meant as extension points so, while the\n\t relations and flow may be difficult to understand initially, they'll allow us to\n\t handle the growth or flux dataset collection in the future (w/o actually implementing\n\t any YAGNI).\n\t \n\t */\n\t //_________________________________________________________________________________________________ ELEMENTS\n\t /** @class mixin for Dataset collection elements.\n\t * When collection elements are passed from the API, the underlying element is\n\t * in a sub-object 'object' (IOW, a DCE representing an HDA will have HDA json in element.object).\n\t * This mixin uses the constructor and parse methods to merge that JSON with the DCE attribtues\n\t * effectively changing a DCE from a container to a subclass (has a --> is a).\n\t */\n\t\n\t var DatasetCollectionElementMixin = {\n\t\n\t /** default attributes used by elements in a dataset collection */\n\t defaults: {\n\t model_class: 'DatasetCollectionElement',\n\t element_identifier: null,\n\t element_index: null,\n\t element_type: null\n\t },\n\t\n\t /** merge the attributes of the sub-object 'object' into this model */\n\t _mergeObject: function (attributes) {\n\t // if we don't preserve and correct ids here, the element id becomes the object id\n\t // and collision in backbone's _byId will occur and only\n\t _.extend(attributes, attributes.object, { element_id: attributes.id });\n\t delete attributes.object;\n\t return attributes;\n\t },\n\t\n\t /** override to merge this.object into this */\n\t constructor: function (attributes, options) {\n\t // console.debug( '\\t DatasetCollectionElement.constructor:', attributes, options );\n\t attributes = this._mergeObject(attributes);\n\t this.idAttribute = 'element_id';\n\t Backbone.Model.apply(this, arguments);\n\t },\n\t\n\t /** when the model is fetched, merge this.object into this */\n\t parse: function (response, options) {\n\t var attributes = response;\n\t attributes = this._mergeObject(attributes);\n\t return attributes;\n\t }\n\t };\n\t\n\t /** @class Concrete class of Generic DatasetCollectionElement */\n\t var DatasetCollectionElement = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(DatasetCollectionElementMixin).extend({ _logNamespace: 'collections' });\n\t\n\t //==============================================================================\n\t /** @class Base/Abstract Backbone collection for Generic DCEs. */\n\t var DCECollection = Backbone.Collection.extend(BASE_MVC.LoggableMixin).extend(\n\t /** @lends DCECollection.prototype */{\n\t _logNamespace: 'collections',\n\t\n\t model: DatasetCollectionElement,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetCollectionElementCollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a dataset collection element that is a dataset (HDA).\n\t */\n\t var DatasetDCE = DATASET_MODEL.DatasetAssociation.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends DatasetDCE.prototype */{\n\t\n\t /** url fn */\n\t url: function () {\n\t // won't always be an hda\n\t if (!this.has('history_id')) {\n\t console.warn('no endpoint for non-hdas within a collection yet');\n\t // (a little silly since this api endpoint *also* points at hdas)\n\t return Galaxy.root + 'api/datasets';\n\t }\n\t return Galaxy.root + 'api/histories/' + this.get('history_id') + '/contents/' + this.get('id');\n\t },\n\t\n\t defaults: _.extend({}, DATASET_MODEL.DatasetAssociation.prototype.defaults, DatasetCollectionElementMixin.defaults),\n\t\n\t _downloadQueryParameters: function () {\n\t return '?to_ext=' + this.get('file_ext') + '&hdca_id=' + this.get('parent_hdca_id') + '&element_identifier=' + this.get('element_identifier');\n\t },\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually for now\n\t /** call the mixin constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t DatasetDCE.constructor:', attributes, options);\n\t //DATASET_MODEL.DatasetAssociation.prototype.constructor.call( this, attributes, options );\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** Does this model already contain detailed data (as opposed to just summary level data)? */\n\t hasDetails: function () {\n\t return this.elements && this.elements.length;\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.get('element_identifier');\n\t return ['DatasetDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class DCECollection of DatasetDCE's (a list of datasets, a pair of datasets).\n\t */\n\t var DatasetDCECollection = DCECollection.extend(\n\t /** @lends DatasetDCECollection.prototype */{\n\t model: DatasetDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //_________________________________________________________________________________________________ COLLECTIONS\n\t /** @class Backbone model for Dataset Collections.\n\t * The DC API returns an array of JSON objects under the attribute elements.\n\t * This model:\n\t * - removes that array/attribute ('elements') from the model,\n\t * - creates a bbone collection (of the class defined in the 'collectionClass' attribute),\n\t * - passes that json onto the bbone collection\n\t * - caches the bbone collection in this.elements\n\t */\n\t var DatasetCollection = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.SearchableModelMixin).extend( /** @lends DatasetCollection.prototype */{\n\t _logNamespace: 'collections',\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t /* 'list', 'paired', or 'list:paired' */\n\t collection_type: null,\n\t //??\n\t deleted: false\n\t },\n\t\n\t /** Which class to use for elements */\n\t collectionClass: DCECollection,\n\t\n\t /** set up: create elements instance var and (on changes to elements) update them */\n\t initialize: function (model, options) {\n\t this.debug(this + '(DatasetCollection).initialize:', model, options, this);\n\t this.elements = this._createElementsModel();\n\t this.on('change:elements', function () {\n\t this.log('change:elements');\n\t //TODO: prob. better to update the collection instead of re-creating it\n\t this.elements = this._createElementsModel();\n\t });\n\t },\n\t\n\t /** move elements model attribute to full collection */\n\t _createElementsModel: function () {\n\t this.debug(this + '._createElementsModel', this.collectionClass, this.get('elements'), this.elements);\n\t //TODO: same patterns as DatasetCollectionElement _createObjectModel - refactor to BASE_MVC.hasSubModel?\n\t var elements = this.get('elements') || [];\n\t this.unset('elements', { silent: true });\n\t var self = this;\n\t _.each(elements, function (element, index) {\n\t _.extend(element, { \"parent_hdca_id\": self.get(\"id\") });\n\t });\n\t this.elements = new this.collectionClass(elements);\n\t //this.debug( 'collectionClass:', this.collectionClass + '', this.elements );\n\t return this.elements;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** pass the elements back within the model json when this is serialized */\n\t toJSON: function () {\n\t var json = Backbone.Model.prototype.toJSON.call(this);\n\t if (this.elements) {\n\t json.elements = this.elements.toJSON();\n\t }\n\t return json;\n\t },\n\t\n\t /** Is this collection in a 'ready' state no processing (for the collection) is left\n\t * to do on the server.\n\t */\n\t inReadyState: function () {\n\t var populated = this.get('populated');\n\t return this.isDeletedOrPurged() || populated;\n\t },\n\t\n\t //TODO:?? the following are the same interface as DatasetAssociation - can we combine?\n\t /** Does the DC contain any elements yet? Is a fetch() required? */\n\t hasDetails: function () {\n\t return this.elements.length !== 0;\n\t },\n\t\n\t /** Given the filters, what models in this.elements would be returned? */\n\t getVisibleContents: function (filters) {\n\t // filters unused for now\n\t return this.elements;\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** save this dataset, _Mark_ing it as deleted (just a flag) */\n\t 'delete': function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** save this dataset, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted') || this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** Is this collection deleted or purged? */\n\t isDeletedOrPurged: function () {\n\t return this.get('deleted') || this.get('purged');\n\t },\n\t\n\t // ........................................................................ searchable\n\t /** searchable attributes for collections */\n\t searchAttributes: ['name', 'tags'],\n\t\n\t // ........................................................................ misc\n\t /** String representation */\n\t toString: function () {\n\t var idAndName = [this.get('id'), this.get('name') || this.get('element_identifier')];\n\t return 'DatasetCollection(' + idAndName.join(',') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** Model for a DatasetCollection containing datasets (non-nested).\n\t */\n\t var ListDatasetCollection = DatasetCollection.extend(\n\t /** @lends ListDatasetCollection.prototype */{\n\t\n\t /** override since we know the collection will only contain datasets */\n\t collectionClass: DatasetDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'List' + DatasetCollection.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** Model for a DatasetCollection containing fwd/rev datasets (a list of 2).\n\t */\n\t var PairDatasetCollection = ListDatasetCollection.extend(\n\t /** @lends PairDatasetCollection.prototype */{\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'Pair' + DatasetCollection.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //_________________________________________________________________________________________________ NESTED COLLECTIONS\n\t // this is where things get weird, man. Weird.\n\t //TODO: it might be possible to compact all the following...I think.\n\t //==============================================================================\n\t /** @class Backbone model for a Generic DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested collection). Currently only list:paired.\n\t */\n\t var NestedDCDCE = DatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedDCDCE.prototype */{\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually it now\n\t /** call the mixin constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedDCDCE.constructor:', attributes, options);\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection containing Generic NestedDCDCE's (nested dataset collections).\n\t */\n\t var NestedDCDCECollection = DCECollection.extend(\n\t /** @lends NestedDCDCECollection.prototype */{\n\t\n\t /** This is a collection of nested collections */\n\t model: NestedDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a paired dataset collection within a list:paired dataset collection.\n\t */\n\t var NestedPairDCDCE = PairDatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedPairDCDCE.prototype */{\n\t //TODO:?? possibly rename to NestedDatasetCollection?\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually it now\n\t /** This is both a collection and a collection element - call the constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedPairDCDCE.constructor:', attributes, options);\n\t //DatasetCollection.constructor.call( this, attributes, options );\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedPairDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection for a backbone collection containing paired dataset collections.\n\t */\n\t var NestedPairDCDCECollection = NestedDCDCECollection.extend(\n\t /** @lends PairDCDCECollection.prototype */{\n\t\n\t /** We know this collection is composed of only nested pair collections */\n\t model: NestedPairDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedPairDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone Model for a DatasetCollection (list) that contains DatasetCollections (pairs).\n\t */\n\t var ListPairedDatasetCollection = DatasetCollection.extend(\n\t /** @lends ListPairedDatasetCollection.prototype */{\n\t\n\t /** list:paired is the only collection that itself contains collections */\n\t collectionClass: NestedPairDCDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['ListPairedDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a list dataset collection within a list:list dataset collection. */\n\t var NestedListDCDCE = ListDatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedListDCDCE.prototype */{\n\t\n\t /** This is both a collection and a collection element - call the constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedListDCDCE.constructor:', attributes, options);\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedListDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection containing list dataset collections. */\n\t var NestedListDCDCECollection = NestedDCDCECollection.extend({\n\t\n\t /** We know this collection is composed of only nested pair collections */\n\t model: NestedListDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedListDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone Model for a DatasetCollection (list) that contains other lists. */\n\t var ListOfListsDatasetCollection = DatasetCollection.extend({\n\t\n\t /** list:paired is the only collection that itself contains collections */\n\t collectionClass: NestedListDCDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['ListOfListsDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t ListDatasetCollection: ListDatasetCollection,\n\t PairDatasetCollection: PairDatasetCollection,\n\t ListPairedDatasetCollection: ListPairedDatasetCollection,\n\t ListOfListsDatasetCollection: ListOfListsDatasetCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 57 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, $, jQuery) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(60), __webpack_require__(17), __webpack_require__(7), __webpack_require__(80), __webpack_require__(8), __webpack_require__(98), __webpack_require__(6), __webpack_require__(95)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HDCA, STATES, BASE_MVC, baseCreator, UI_MODAL, naturalSort, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t\n\t /*==============================================================================\n\t TODO:\n\t use proper Element model and not just json\n\t straighten out createFn, collection.createHDCA\n\t possibly stop using modals for this\n\t It would be neat to do a drag and drop\n\t \n\t ==============================================================================*/\n\t /** A view for both DatasetDCEs and NestedDCDCEs\n\t * (things that implement collection-model:DatasetCollectionElementMixin)\n\t */\n\t var DatasetCollectionElementView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n\t tagName: 'li',\n\t className: 'collection-element',\n\t\n\t initialize: function (attributes) {\n\t this.element = attributes.element || {};\n\t this.selected = attributes.selected || false;\n\t },\n\t\n\t render: function () {\n\t this.$el.attr('data-element-id', this.element.id).attr('draggable', true).html(this.template({ element: this.element }));\n\t if (this.selected) {\n\t this.$el.addClass('selected');\n\t }\n\t return this;\n\t },\n\t\n\t //TODO: lots of unused space in the element - possibly load details and display them horiz.\n\t template: _.template(['', '<%- element.name %>', '', ''].join('')),\n\t\n\t /** select this element and pub */\n\t select: function (toggle) {\n\t this.$el.toggleClass('selected', toggle);\n\t this.trigger('select', {\n\t source: this,\n\t selected: this.$el.hasClass('selected')\n\t });\n\t },\n\t\n\t /** animate the removal of this element and pub */\n\t discard: function () {\n\t var view = this,\n\t parentWidth = this.$el.parent().width();\n\t this.$el.animate({ 'margin-right': parentWidth }, 'fast', function () {\n\t view.trigger('discard', {\n\t source: view\n\t });\n\t view.destroy();\n\t });\n\t },\n\t\n\t /** remove the DOM and any listeners */\n\t destroy: function () {\n\t this.off();\n\t this.$el.remove();\n\t },\n\t\n\t events: {\n\t 'click': '_click',\n\t 'click .name': '_clickName',\n\t 'click .discard': '_clickDiscard',\n\t\n\t 'dragstart': '_dragstart',\n\t 'dragend': '_dragend',\n\t 'dragover': '_sendToParent',\n\t 'drop': '_sendToParent'\n\t },\n\t\n\t /** select when the li is clicked */\n\t _click: function (ev) {\n\t ev.stopPropagation();\n\t this.select(ev);\n\t },\n\t\n\t /** rename a pair when the name is clicked */\n\t _clickName: function (ev) {\n\t ev.stopPropagation();\n\t ev.preventDefault();\n\t var promptString = [_l('Enter a new name for the element'), ':\\n(', _l('Note that changing the name here will not rename the dataset'), ')'].join(''),\n\t response = prompt(_l('Enter a new name for the element') + ':', this.element.name);\n\t if (response) {\n\t this.element.name = response;\n\t this.render();\n\t }\n\t //TODO: cancelling with ESC leads to closure of the creator...\n\t },\n\t\n\t /** discard when the discard button is clicked */\n\t _clickDiscard: function (ev) {\n\t ev.stopPropagation();\n\t this.discard();\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragstart: function (ev) {\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t ev.dataTransfer.effectAllowed = 'move';\n\t ev.dataTransfer.setData('text/plain', JSON.stringify(this.element));\n\t\n\t this.$el.addClass('dragging');\n\t this.$el.parent().trigger('collection-element.dragstart', [this]);\n\t },\n\t\n\t /** dragging for re-ordering */\n\t _dragend: function (ev) {\n\t this.$el.removeClass('dragging');\n\t this.$el.parent().trigger('collection-element.dragend', [this]);\n\t },\n\t\n\t /** manually bubble up an event to the parent/container */\n\t _sendToParent: function (ev) {\n\t this.$el.parent().trigger(ev);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'DatasetCollectionElementView()';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t /** An interface for building collections.\n\t */\n\t var ListCollectionCreator = Backbone.View.extend(BASE_MVC.LoggableMixin).extend(baseCreator.CollectionCreatorMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t /** the class used to display individual elements */\n\t elementViewClass: DatasetCollectionElementView,\n\t /** the class this creator will create and save */\n\t collectionClass: HDCA.HistoryListDatasetCollection,\n\t className: 'list-collection-creator collection-creator flex-row-container',\n\t\n\t /** minimum number of valid elements to start with in order to build a collection of this type */\n\t minElements: 1,\n\t\n\t defaultAttributes: {\n\t //TODO: remove - use new collectionClass().save()\n\t /** takes elements and creates the proper collection - returns a promise */\n\t creationFn: function () {\n\t throw new TypeError('no creation fn for creator');\n\t },\n\t /** fn to call when the collection is created (scoped to this) */\n\t oncreate: function () {},\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t oncancel: function () {},\n\t /** distance from list edge to begin autoscrolling list */\n\t autoscrollDist: 24,\n\t /** Color passed to hoverhighlight */\n\t highlightClr: 'rgba( 64, 255, 255, 1.0 )'\n\t },\n\t\n\t footerSettings: {\n\t '.hide-originals': 'hideOriginals'\n\t },\n\t\n\t /** set up initial options, instance vars, behaviors */\n\t initialize: function (attributes) {\n\t this.metric('ListCollectionCreator.initialize', attributes);\n\t var creator = this;\n\t _.each(this.defaultAttributes, function (value, key) {\n\t value = attributes[key] || value;\n\t creator[key] = value;\n\t });\n\t\n\t /** unordered, original list - cache to allow reversal */\n\t creator.initialElements = attributes.elements || [];\n\t\n\t this._setUpCommonSettings(attributes);\n\t this._instanceSetUp();\n\t this._elementsSetUp();\n\t this._setUpBehaviors();\n\t },\n\t\n\t /** set up instance vars */\n\t _instanceSetUp: function () {\n\t /** Ids of elements that have been selected by the user - to preserve over renders */\n\t this.selectedIds = {};\n\t /** DOM elements currently being dragged */\n\t this.$dragging = null;\n\t /** Used for blocking UI events during ajax/operations (don't post twice) */\n\t this.blocking = false;\n\t },\n\t\n\t // ------------------------------------------------------------------------ process raw list\n\t /** set up main data */\n\t _elementsSetUp: function () {\n\t //this.debug( '-- _dataSetUp' );\n\t /** a list of invalid elements and the reasons they aren't valid */\n\t this.invalidElements = [];\n\t //TODO: handle fundamental problem of syncing DOM, views, and list here\n\t /** data for list in progress */\n\t this.workingElements = [];\n\t /** views for workingElements */\n\t this.elementViews = [];\n\t\n\t // copy initial list, sort, add ids if needed\n\t this.workingElements = this.initialElements.slice(0);\n\t this._ensureElementIds();\n\t this._validateElements();\n\t this._mangleDuplicateNames();\n\t this._sortElements();\n\t },\n\t\n\t /** add ids to dataset objs in initial list if none */\n\t _ensureElementIds: function () {\n\t this.workingElements.forEach(function (element) {\n\t if (!element.hasOwnProperty('id')) {\n\t element.id = _.uniqueId();\n\t }\n\t });\n\t return this.workingElements;\n\t },\n\t\n\t /** separate working list into valid and invalid elements for this collection */\n\t _validateElements: function () {\n\t var creator = this,\n\t existingNames = {};\n\t creator.invalidElements = [];\n\t\n\t this.workingElements = this.workingElements.filter(function (element) {\n\t var problem = creator._isElementInvalid(element);\n\t if (problem) {\n\t creator.invalidElements.push({\n\t element: element,\n\t text: problem\n\t });\n\t }\n\t return !problem;\n\t });\n\t return this.workingElements;\n\t },\n\t\n\t /** describe what is wrong with a particular element if anything */\n\t _isElementInvalid: function (element) {\n\t if (element.history_content_type !== 'dataset') {\n\t return _l(\"is not a dataset\");\n\t }\n\t var validState = element.state === STATES.OK || _.contains(STATES.NOT_READY_STATES, element.state);\n\t if (!validState) {\n\t return _l(\"has errored, is paused, or is not accessible\");\n\t }\n\t if (element.deleted || element.purged) {\n\t return _l(\"has been deleted or purged\");\n\t }\n\t return null;\n\t },\n\t\n\t /** mangle duplicate names using a mac-like '(counter)' addition to any duplicates */\n\t _mangleDuplicateNames: function () {\n\t var SAFETY = 900,\n\t counter = 1,\n\t existingNames = {};\n\t this.workingElements.forEach(function (element) {\n\t var currName = element.name;\n\t while (existingNames.hasOwnProperty(currName)) {\n\t currName = element.name + ' (' + counter + ')';\n\t counter += 1;\n\t if (counter >= SAFETY) {\n\t throw new Error('Safety hit in while loop - thats impressive');\n\t }\n\t }\n\t element.name = currName;\n\t existingNames[element.name] = true;\n\t });\n\t },\n\t\n\t /** sort a list of elements */\n\t _sortElements: function (list) {\n\t // // currently only natural sort by name\n\t // this.workingElements.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n\t // return this.workingElements;\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t // templates : ListCollectionCreator.templates,\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t if (this.workingElements.length < this.minElements) {\n\t return this._renderInvalid(speed, callback);\n\t }\n\t\n\t this.$el.empty().html(this.templates.main());\n\t this._renderHeader(speed);\n\t this._renderMiddle(speed);\n\t this._renderFooter(speed);\n\t this._addPluginComponents();\n\t this.$('.collection-name').focus();\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render a simplified interface aimed at telling the user why they can't move forward */\n\t _renderInvalid: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t this.$el.empty().html(this.templates.invalidInitial({\n\t problems: this.invalidElements,\n\t elements: this.workingElements\n\t }));\n\t if (typeof this.oncancel === 'function') {\n\t this.$('.cancel-create.btn').show();\n\t }\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render the header section */\n\t _renderHeader: function (speed, callback) {\n\t var $header = this.$('.header').empty().html(this.templates.header()).find('.help-content').prepend($(this.templates.helpContent()));\n\t //TODO: should only show once despite calling _renderHeader again\n\t if (this.invalidElements.length) {\n\t this._invalidElementsAlert();\n\t }\n\t return $header;\n\t },\n\t\n\t /** render the middle including the elements */\n\t _renderMiddle: function (speed, callback) {\n\t var $middle = this.$('.middle').empty().html(this.templates.middle());\n\t this._renderList(speed);\n\t return $middle;\n\t },\n\t\n\t /** add any jQuery/bootstrap/custom plugins to elements rendered */\n\t _addPluginComponents: function () {\n\t this.$('.help-content i').hoverhighlight('.collection-creator', this.highlightClr);\n\t },\n\t\n\t /** build and show an alert describing any elements that could not be included due to problems */\n\t _invalidElementsAlert: function () {\n\t this._showAlert(this.templates.invalidElements({ problems: this.invalidElements }), 'alert-warning');\n\t },\n\t\n\t _disableNameAndCreate: function (disable) {\n\t disable = !_.isUndefined(disable) ? disable : true;\n\t if (disable) {\n\t this.$('.collection-name').prop('disabled', true);\n\t this.$('.create-collection').toggleClass('disabled', true);\n\t // } else {\n\t // this.$( '.collection-name' ).prop( 'disabled', false );\n\t // this.$( '.create-collection' ).removeClass( 'disable' );\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering elements\n\t /** conv. to the main list display DOM */\n\t $list: function () {\n\t return this.$('.collection-elements');\n\t },\n\t\n\t /** show or hide the clear selected control based on the num of selected elements */\n\t _renderClearSelected: function () {\n\t if (_.size(this.selectedIds)) {\n\t this.$('.collection-elements-controls > .clear-selected').show();\n\t } else {\n\t this.$('.collection-elements-controls > .clear-selected').hide();\n\t }\n\t },\n\t\n\t /** render the elements in order (or a warning if no elements found) */\n\t _renderList: function (speed, callback) {\n\t //this.debug( '-- _renderList' );\n\t var creator = this,\n\t $tmp = jQuery('
              '),\n\t $list = creator.$list();\n\t\n\t _.each(this.elementViews, function (view) {\n\t view.destroy();\n\t creator.removeElementView(view);\n\t });\n\t\n\t // if( !this.workingElements.length ){\n\t // this._renderNoValidElements();\n\t // return;\n\t // }\n\t\n\t creator.workingElements.forEach(function (element) {\n\t var elementView = creator._createElementView(element);\n\t $tmp.append(elementView.$el);\n\t });\n\t\n\t creator._renderClearSelected();\n\t $list.empty().append($tmp.children());\n\t _.invoke(creator.elementViews, 'render');\n\t\n\t if ($list.height() > $list.css('max-height')) {\n\t $list.css('border-width', '1px 0px 1px 0px');\n\t } else {\n\t $list.css('border-width', '0px');\n\t }\n\t },\n\t\n\t /** create an element view, cache in elementViews, set up listeners, and return */\n\t _createElementView: function (element) {\n\t var elementView = new this.elementViewClass({\n\t //TODO: use non-generic class or not all\n\t // model : COLLECTION.DatasetDCE( element )\n\t element: element,\n\t selected: _.has(this.selectedIds, element.id)\n\t });\n\t this.elementViews.push(elementView);\n\t this._listenToElementView(elementView);\n\t return elementView;\n\t },\n\t\n\t /** listen to any element events */\n\t _listenToElementView: function (view) {\n\t var creator = this;\n\t creator.listenTo(view, {\n\t select: function (data) {\n\t var element = data.source.element;\n\t if (data.selected) {\n\t creator.selectedIds[element.id] = true;\n\t } else {\n\t delete creator.selectedIds[element.id];\n\t }\n\t creator.trigger('elements:select', data);\n\t },\n\t discard: function (data) {\n\t creator.trigger('elements:discard', data);\n\t }\n\t });\n\t },\n\t\n\t /** add a new element view based on the json in element */\n\t addElementView: function (element) {\n\t //TODO: workingElements is sorted, add element in appropo index\n\t // add element, sort elements, find element index\n\t // var view = this._createElementView( element );\n\t // return view;\n\t },\n\t\n\t /** stop listening to view and remove from caches */\n\t removeElementView: function (view) {\n\t delete this.selectedIds[view.element.id];\n\t this._renderClearSelected();\n\t\n\t this.elementViews = _.without(this.elementViews, view);\n\t this.stopListening(view);\n\t },\n\t\n\t /** render a message in the list that no elements remain to create a collection */\n\t _renderNoElementsLeft: function () {\n\t this._disableNameAndCreate(true);\n\t this.$('.collection-elements').append(this.templates.noElementsLeft());\n\t },\n\t\n\t // /** render a message in the list that no valid elements were found to create a collection */\n\t // _renderNoValidElements : function(){\n\t // this._disableNameAndCreate( true );\n\t // this.$( '.collection-elements' ).append( this.templates.noValidElements() );\n\t // },\n\t\n\t // ------------------------------------------------------------------------ API\n\t /** convert element into JSON compatible with the collections API */\n\t _elementToJSON: function (element) {\n\t // return element.toJSON();\n\t return element;\n\t },\n\t\n\t /** create the collection via the API\n\t * @returns {jQuery.xhr Object} the jquery ajax request\n\t */\n\t createList: function (name) {\n\t if (!this.workingElements.length) {\n\t var message = _l('No valid elements for final list') + '. ';\n\t message += '' + _l('Cancel') + ' ';\n\t message += _l('or');\n\t message += ' ' + _l('start over') + '.';\n\t this._showAlert(message);\n\t return;\n\t }\n\t\n\t var creator = this,\n\t elements = this.workingElements.map(function (element) {\n\t return creator._elementToJSON(element);\n\t });\n\t\n\t creator.blocking = true;\n\t return creator.creationFn(elements, name, creator.hideOriginals).always(function () {\n\t creator.blocking = false;\n\t }).fail(function (xhr, status, message) {\n\t creator.trigger('error', {\n\t xhr: xhr,\n\t status: status,\n\t message: _l('An error occurred while creating this collection')\n\t });\n\t }).done(function (response, message, xhr) {\n\t creator.trigger('collection:created', response, message, xhr);\n\t creator.metric('collection:created', response);\n\t if (typeof creator.oncreate === 'function') {\n\t creator.oncreate.call(this, response, message, xhr);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ events\n\t /** set up event handlers on self */\n\t _setUpBehaviors: function () {\n\t this.on('error', this._errorHandler);\n\t\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this.on('elements:select', function (data) {\n\t this._renderClearSelected();\n\t });\n\t\n\t this.on('elements:discard', function (data) {\n\t var element = data.source.element;\n\t this.removeElementView(data.source);\n\t\n\t this.workingElements = _.without(this.workingElements, element);\n\t if (!this.workingElements.length) {\n\t this._renderNoElementsLeft();\n\t }\n\t });\n\t\n\t //this.on( 'all', function(){\n\t // this.info( arguments );\n\t //});\n\t return this;\n\t },\n\t\n\t /** handle errors with feedback and details to the user (if available) */\n\t _errorHandler: function (data) {\n\t this.error(data);\n\t\n\t var creator = this;\n\t content = data.message || _l('An error occurred');\n\t if (data.xhr) {\n\t var xhr = data.xhr,\n\t message = data.message;\n\t if (xhr.readyState === 0 && xhr.status === 0) {\n\t content += ': ' + _l('Galaxy could not be reached and may be updating.') + _l(' Try again in a few minutes.');\n\t } else if (xhr.responseJSON) {\n\t content += ':
              ' + JSON.stringify(xhr.responseJSON) + '
              ';\n\t } else {\n\t content += ': ' + message;\n\t }\n\t }\n\t creator._showAlert(content, 'alert-danger');\n\t },\n\t\n\t events: {\n\t // header\n\t 'click .more-help': '_clickMoreHelp',\n\t 'click .less-help': '_clickLessHelp',\n\t 'click .main-help': '_toggleHelp',\n\t 'click .header .alert button': '_hideAlert',\n\t\n\t 'click .reset': 'reset',\n\t 'click .clear-selected': 'clearSelectedElements',\n\t\n\t // elements - selection\n\t 'click .collection-elements': 'clearSelectedElements',\n\t\n\t // elements - drop target\n\t // 'dragenter .collection-elements': '_dragenterElements',\n\t // 'dragleave .collection-elements': '_dragleaveElements',\n\t 'dragover .collection-elements': '_dragoverElements',\n\t 'drop .collection-elements': '_dropElements',\n\t\n\t // these bubble up from the elements as custom events\n\t 'collection-element.dragstart .collection-elements': '_elementDragstart',\n\t 'collection-element.dragend .collection-elements': '_elementDragend',\n\t\n\t // footer\n\t 'change .collection-name': '_changeName',\n\t 'keydown .collection-name': '_nameCheckForEnter',\n\t 'change .hide-originals': '_changeHideOriginals',\n\t 'click .cancel-create': '_cancelCreate',\n\t 'click .create-collection': '_clickCreate' //,\n\t },\n\t\n\t // ........................................................................ elements\n\t /** reset all data to the initial state */\n\t reset: function () {\n\t this._instanceSetUp();\n\t this._elementsSetUp();\n\t this.render();\n\t },\n\t\n\t /** deselect all elements */\n\t clearSelectedElements: function (ev) {\n\t this.$('.collection-elements .collection-element').removeClass('selected');\n\t this.$('.collection-elements-controls > .clear-selected').hide();\n\t },\n\t\n\t //_dragenterElements : function( ev ){\n\t // //this.debug( '_dragenterElements:', ev );\n\t //},\n\t //TODO: if selected are dragged out of the list area - remove the placeholder - cuz it won't work anyway\n\t // _dragleaveElements : function( ev ){\n\t // //this.debug( '_dragleaveElements:', ev );\n\t // },\n\t\n\t /** track the mouse drag over the list adding a placeholder to show where the drop would occur */\n\t _dragoverElements: function (ev) {\n\t //this.debug( '_dragoverElements:', ev );\n\t ev.preventDefault();\n\t\n\t var $list = this.$list();\n\t this._checkForAutoscroll($list, ev.originalEvent.clientY);\n\t var $nearest = this._getNearestElement(ev.originalEvent.clientY);\n\t\n\t //TODO: no need to re-create - move instead\n\t this.$('.element-drop-placeholder').remove();\n\t var $placeholder = $('
              ');\n\t if (!$nearest.length) {\n\t $list.append($placeholder);\n\t } else {\n\t $nearest.before($placeholder);\n\t }\n\t },\n\t\n\t /** If the mouse is near enough to the list's top or bottom, scroll the list */\n\t _checkForAutoscroll: function ($element, y) {\n\t var AUTOSCROLL_SPEED = 2,\n\t offset = $element.offset(),\n\t scrollTop = $element.scrollTop(),\n\t upperDist = y - offset.top,\n\t lowerDist = offset.top + $element.outerHeight() - y;\n\t if (upperDist >= 0 && upperDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop - AUTOSCROLL_SPEED);\n\t } else if (lowerDist >= 0 && lowerDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop + AUTOSCROLL_SPEED);\n\t }\n\t },\n\t\n\t /** get the nearest element based on the mouse's Y coordinate.\n\t * If the y is at the end of the list, return an empty jQuery object.\n\t */\n\t _getNearestElement: function (y) {\n\t var WIGGLE = 4,\n\t lis = this.$('.collection-elements li.collection-element').toArray();\n\t for (var i = 0; i < lis.length; i++) {\n\t var $li = $(lis[i]),\n\t top = $li.offset().top,\n\t halfHeight = Math.floor($li.outerHeight() / 2) + WIGGLE;\n\t if (top + halfHeight > y && top - halfHeight < y) {\n\t return $li;\n\t }\n\t }\n\t return $();\n\t },\n\t\n\t /** drop (dragged/selected elements) onto the list, re-ordering the internal list */\n\t _dropElements: function (ev) {\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t // both required for firefox\n\t ev.preventDefault();\n\t ev.dataTransfer.dropEffect = 'move';\n\t\n\t // insert before the nearest element or after the last.\n\t var $nearest = this._getNearestElement(ev.clientY);\n\t if ($nearest.length) {\n\t this.$dragging.insertBefore($nearest);\n\t } else {\n\t // no nearest before - insert after last element\n\t this.$dragging.insertAfter(this.$('.collection-elements .collection-element').last());\n\t }\n\t // resync the creator's list based on the new DOM order\n\t this._syncOrderToDom();\n\t return false;\n\t },\n\t\n\t /** resync the creator's list of elements based on the DOM order */\n\t _syncOrderToDom: function () {\n\t var creator = this,\n\t newElements = [];\n\t //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n\t this.$('.collection-elements .collection-element').each(function () {\n\t var id = $(this).attr('data-element-id'),\n\t element = _.findWhere(creator.workingElements, { id: id });\n\t if (element) {\n\t newElements.push(element);\n\t } else {\n\t console.error('missing element: ', id);\n\t }\n\t });\n\t this.workingElements = newElements;\n\t this._renderList();\n\t },\n\t\n\t /** drag communication with element sub-views: dragstart */\n\t _elementDragstart: function (ev, element) {\n\t // auto select the element causing the event and move all selected\n\t element.select(true);\n\t this.$dragging = this.$('.collection-elements .collection-element.selected');\n\t },\n\t\n\t /** drag communication with element sub-views: dragend - remove the placeholder */\n\t _elementDragend: function (ev, element) {\n\t $('.element-drop-placeholder').remove();\n\t this.$dragging = null;\n\t },\n\t\n\t // ------------------------------------------------------------------------ templates\n\t //TODO: move to require text plugin and load these as text\n\t //TODO: underscore currently unnecc. bc no vars are used\n\t //TODO: better way of localizing text-nodes in long strings\n\t /** underscore template fns attached to class */\n\t templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\t\n\t /** the header (not including help text) */\n\t header: _.template(['', '
              ', '', '', '
              '].join('')),\n\t\n\t /** the middle: element list */\n\t middle: _.template(['', '
              ', '
              '].join('')),\n\t\n\t /** creation and cancel controls */\n\t footer: _.template(['
              ', '
              ', '', '
              ', '
              ', '', '
              ', _l('Name'), ':
              ', '
              ', '
              ', '
              ', '
              ', '', '
              ', '', '', '
              ', '
              ', '
              ', '', '
              ', '
              '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

              ', _l(['Collections of datasets are permanent, ordered lists of datasets that can be passed to tools and ', 'workflows in order to have analyses done on each member of the entire group. This interface allows ', 'you to create a collection and re-order the final collection.'].join('')), '

              ', '
                ', '
              • ', _l(['Rename elements in the list by clicking on ', 'the existing name.'].join('')), '
              • ', '
              • ', _l(['Discard elements from the final created list by clicking on the ', '\"Discard\" button.'].join('')), '
              • ', '
              • ', _l(['Reorder the list by clicking and dragging elements. Select multiple elements by clicking on ', 'them and you can then move those selected by dragging the ', 'entire group. Deselect them by clicking them again or by clicking the ', 'the \"Clear selected\" link.'].join('')), '
              • ', '
              • ', _l(['Click the \"Start over\" link to begin again as if you had just opened ', 'the interface.'].join('')), '
              • ', '
              • ', _l(['Click the \"Cancel\" button to exit the interface.'].join('')), '
              • ', '

              ', '

              ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\".'].join('')), '

              '].join('')),\n\t\n\t /** shown in list when all elements are discarded */\n\t invalidElements: _.template([_l('The following selections could not be included due to problems:'), '
                <% _.each( problems, function( problem ){ %>', '
              • <%- problem.element.name %>: <%- problem.text %>
              • ', '<% }); %>
              '].join('')),\n\t\n\t /** shown in list when all elements are discarded */\n\t noElementsLeft: _.template(['
            2. ', _l('No elements left! '), _l('Would you like to '), '', _l('start over'), '?', '
            3. '].join('')),\n\t\n\t /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n\t invalidInitial: _.template(['
              ', '
              ', '', '<% if( _.size( problems ) ){ %>', _l('The following selections could not be included due to problems'), ':', '
                <% _.each( problems, function( problem ){ %>', '
              • <%- problem.element.name %>: <%- problem.text %>
              • ', '<% }); %>
              ', '<% } else if( _.size( elements ) < 1 ){ %>', _l('No datasets were selected'), '.', '<% } %>', '
              ', _l('At least one element is needed for the collection'), '. ', _l('You may need to '), '', _l('cancel'), ' ', _l('and reselect new elements'), '.', '
              ', '
              ', '
              ', '
              ', '
              ', '
              ', '',\n\t // _l( 'Create a different kind of collection' ),\n\t '
              ', '
              ', '
              '].join(''))\n\t }),\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionCreator';\n\t }\n\t });\n\t\n\t //=============================================================================\n\t /** Create a modal and load its body with the given CreatorClass creator type\n\t * @returns {Deferred} resolved when creator has built a collection.\n\t */\n\t var collectionCreatorModal = function _collectionCreatorModal(elements, options, CreatorClass) {\n\t\n\t var deferred = jQuery.Deferred(),\n\t modal = Galaxy.modal || new UI_MODAL.View(),\n\t creator;\n\t\n\t options = _.defaults(options || {}, {\n\t elements: elements,\n\t oncancel: function () {\n\t modal.hide();\n\t deferred.reject('cancelled');\n\t },\n\t oncreate: function (creator, response) {\n\t modal.hide();\n\t deferred.resolve(response);\n\t }\n\t });\n\t\n\t creator = new CreatorClass(options);\n\t modal.show({\n\t title: options.title || _l('Create a collection'),\n\t body: creator.$el,\n\t width: '80%',\n\t height: '100%',\n\t closing_events: true\n\t });\n\t creator.render();\n\t window._collectionCreator = creator;\n\t\n\t //TODO: remove modal header\n\t return deferred;\n\t };\n\t\n\t /** List collection flavor of collectionCreatorModal. */\n\t var listCollectionCreatorModal = function _listCollectionCreatorModal(elements, options) {\n\t options = options || {};\n\t options.title = _l('Create a collection from a list of datasets');\n\t return collectionCreatorModal(elements, options, ListCollectionCreator);\n\t };\n\t\n\t //==============================================================================\n\t /** Use a modal to create a list collection, then add it to the given history contents.\n\t * @returns {Deferred} resolved when the collection is added to the history.\n\t */\n\t function createListCollection(contents, defaultHideSourceItems) {\n\t var elements = contents.toJSON(),\n\t promise = listCollectionCreatorModal(elements, {\n\t defaultHideSourceItems: defaultHideSourceItems,\n\t creationFn: function (elements, name, hideSourceItems) {\n\t elements = elements.map(function (element) {\n\t return {\n\t id: element.id,\n\t name: element.name,\n\t //TODO: this allows for list:list even if the filter above does not - reconcile\n\t src: element.history_content_type === 'dataset' ? 'hda' : 'hdca'\n\t };\n\t });\n\t return contents.createHDCA(elements, 'list', name, hideSourceItems);\n\t }\n\t });\n\t return promise;\n\t }\n\t\n\t //==============================================================================\n\t return {\n\t DatasetCollectionElementView: DatasetCollectionElementView,\n\t ListCollectionCreator: ListCollectionCreator,\n\t\n\t collectionCreatorModal: collectionCreatorModal,\n\t listCollectionCreatorModal: listCollectionCreatorModal,\n\t createListCollection: createListCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 58 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, Backbone, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(17), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, STATES, faIconButton, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t var logNamespace = 'dataset';\n\t /*==============================================================================\n\t TODO:\n\t straighten out state rendering and templates used\n\t inaccessible/STATES.NOT_VIEWABLE is a special case\n\t simplify button rendering\n\t \n\t ==============================================================================*/\n\t var _super = LIST_ITEM.ListItemView;\n\t /** @class Read only list view for either LDDAs, HDAs, or HDADCEs.\n\t * Roughly, any DatasetInstance (and not a raw Dataset).\n\t */\n\t var DatasetListItemView = _super.extend(\n\t /** @lends DatasetListItemView.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t className: _super.prototype.className + \" dataset\",\n\t //TODO:?? doesn't exactly match an hda's type_id\n\t id: function () {\n\t return ['dataset', this.model.get('id')].join('-');\n\t },\n\t\n\t /** Set up: instance vars, options, and event handlers */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log(this + '.initialize:', attributes);\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t /** where should pages from links be displayed? (default to new tab/window) */\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t var self = this;\n\t\n\t // re-rendering on any model changes\n\t return self.listenTo(self.model, {\n\t 'change': function (model) {\n\t // if the model moved into the ready state and is expanded without details, fetch those details now\n\t if (self.model.changedAttributes().state && self.model.inReadyState() && self.expanded && !self.model.hasDetails()) {\n\t // normally, will render automatically (due to fetch -> change),\n\t // but! setting_metadata sometimes doesn't cause any other changes besides state\n\t // so, not rendering causes it to seem frozen in setting_metadata state\n\t self.model.fetch({ silent: true }).done(function () {\n\t self.render();\n\t });\n\t } else {\n\t if (_.has(model.changed, 'tags') && _.keys(model.changed).length === 1) {\n\t // If only the tags have changed, rerender specifically\n\t // the titlebar region. Otherwise default to the full\n\t // render.\n\t self.$('.nametags').html(self._renderNametags());\n\t } else {\n\t self.render();\n\t }\n\t }\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... expandable\n\t /** In this override, only get details if in the ready state, get rerunnable if in other states.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ......................................................................... removal\n\t /** Remove this view's html from the DOM and remove all event listeners.\n\t * @param {Number or String} speed jq effect speed\n\t * @param {Function} callback an optional function called when removal is done (scoped to this view)\n\t */\n\t remove: function (speed, callback) {\n\t var view = this;\n\t speed = speed || this.fxSpeed;\n\t this.$el.fadeOut(speed, function () {\n\t Backbone.View.prototype.remove.call(view);\n\t if (callback) {\n\t callback.call(view);\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... rendering\n\t /* TODO:\n\t dataset states are the issue primarily making dataset rendering complex\n\t each state should have it's own way of displaying/set of details\n\t often with different actions that can be applied\n\t throw in deleted/purged/visible and things get complicated easily\n\t I've considered (a couple of times) - creating a view for each state\n\t - but recreating the view during an update...seems wrong\n\t */\n\t /** In this override, add the dataset state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t if (this.model.has('state')) {\n\t this.$el.addClass('state-' + this.model.get('state'));\n\t }\n\t return this.$el;\n\t },\n\t\n\t // ................................................................................ titlebar\n\t /** In this override, add the dataset display button. */\n\t _renderPrimaryActions: function () {\n\t // render just the display for read-only\n\t return [this._renderDisplayButton()];\n\t },\n\t\n\t /** Render icon-button to display dataset data */\n\t _renderDisplayButton: function () {\n\t // don't show display if not viewable or not accessible\n\t var state = this.model.get('state');\n\t if (state === STATES.NOT_VIEWABLE || state === STATES.DISCARDED || !this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var displayBtnData = {\n\t target: this.linkTarget,\n\t classes: 'display-btn'\n\t };\n\t\n\t // show a disabled display if the data's been purged\n\t if (this.model.get('purged')) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('Cannot display datasets removed from disk');\n\t\n\t // disable if still uploading\n\t } else if (state === STATES.UPLOAD) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('This dataset must finish uploading before it can be viewed');\n\t\n\t // disable if still new\n\t } else if (state === STATES.NEW) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('This dataset is not yet viewable');\n\t } else {\n\t displayBtnData.title = _l('View data');\n\t\n\t // default link for dataset\n\t displayBtnData.href = this.model.urls.display;\n\t\n\t // add frame manager option onclick event\n\t var self = this;\n\t displayBtnData.onclick = function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t // Add dataset to frames.\n\t Galaxy.frame.addDataset(self.model.get('id'));\n\t ev.preventDefault();\n\t }\n\t };\n\t }\n\t displayBtnData.faIcon = 'fa-eye';\n\t return faIconButton(displayBtnData);\n\t },\n\t\n\t // ......................................................................... rendering details\n\t /** Render the enclosing div of the hda body and, if expanded, the html in the body\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderDetails: function () {\n\t //TODO: generalize to be allow different details for each state\n\t\n\t // no access - render nothing but a message\n\t if (this.model.get('state') === STATES.NOT_VIEWABLE) {\n\t return $(this.templates.noAccess(this.model.toJSON(), this));\n\t }\n\t\n\t var $details = _super.prototype._renderDetails.call(this);\n\t $details.find('.actions .left').empty().append(this._renderSecondaryActions());\n\t $details.find('.summary').html(this._renderSummary()).prepend(this._renderDetailMessages());\n\t $details.find('.display-applications').html(this._renderDisplayApplications());\n\t\n\t this._setUpBehaviors($details);\n\t return $details;\n\t },\n\t\n\t /** Defer to the appropo summary rendering fn based on state */\n\t _renderSummary: function () {\n\t var json = this.model.toJSON(),\n\t summaryRenderFn = this.templates.summaries[json.state];\n\t summaryRenderFn = summaryRenderFn || this.templates.summaries.unknown;\n\t return summaryRenderFn(json, this);\n\t },\n\t\n\t /** Render messages to be displayed only when the details are shown */\n\t _renderDetailMessages: function () {\n\t var view = this,\n\t $warnings = $('
              '),\n\t json = view.model.toJSON();\n\t //TODO:! unordered (map)\n\t _.each(view.templates.detailMessages, function (templateFn) {\n\t $warnings.append($(templateFn(json, view)));\n\t });\n\t return $warnings;\n\t },\n\t\n\t /** Render the external display application links */\n\t _renderDisplayApplications: function () {\n\t if (this.model.isDeletedOrPurged()) {\n\t return '';\n\t }\n\t // render both old and new display apps using the same template\n\t return [this.templates.displayApplications(this.model.get('display_apps'), this), this.templates.displayApplications(this.model.get('display_types'), this)].join('');\n\t },\n\t\n\t // ......................................................................... secondary/details actions\n\t /** A series of links/buttons for less commonly used actions: re-run, info, etc. */\n\t _renderSecondaryActions: function () {\n\t this.debug('_renderSecondaryActions');\n\t switch (this.model.get('state')) {\n\t case STATES.NOT_VIEWABLE:\n\t return [];\n\t case STATES.OK:\n\t case STATES.FAILED_METADATA:\n\t case STATES.ERROR:\n\t return [this._renderDownloadButton(), this._renderShowParamsButton()];\n\t }\n\t return [this._renderShowParamsButton()];\n\t },\n\t\n\t /** Render icon-button to show the input and output (stdout/err) for the job that created this.\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderShowParamsButton: function () {\n\t // gen. safe to show in all cases\n\t return faIconButton({\n\t title: _l('View details'),\n\t classes: 'params-btn',\n\t href: this.model.urls.show_params,\n\t target: this.linkTarget,\n\t faIcon: 'fa-info-circle',\n\t onclick: function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t Galaxy.frame.add({ title: 'Dataset details', url: this.href });\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** Render icon-button/popupmenu to download the data (and/or the associated meta files (bai, etc.)) for this.\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderDownloadButton: function () {\n\t // don't show anything if the data's been purged\n\t if (this.model.get('purged') || !this.model.hasData()) {\n\t return null;\n\t }\n\t\n\t // return either: a popupmenu with links to download assoc. meta files (if there are meta files)\n\t // or a single download icon-button (if there are no meta files)\n\t if (!_.isEmpty(this.model.get('meta_files'))) {\n\t return this._renderMetaFileDownloadButton();\n\t }\n\t\n\t return $(['', '', ''].join(''));\n\t },\n\t\n\t /** Render the download button which opens a dropdown with links to download assoc. meta files (indeces, etc.) */\n\t _renderMetaFileDownloadButton: function () {\n\t var urls = this.model.urls;\n\t return $(['
              ', '', '', '', '', '
              '].join('\\n'));\n\t },\n\t\n\t _renderNametags: function () {\n\t var tpl = _.template(['<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>'].join(''));\n\t return tpl({ tags: this.model.get('tags') });\n\t },\n\t\n\t // ......................................................................... misc\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .display-btn': function (ev) {\n\t this.trigger('display', this, ev);\n\t },\n\t 'click .params-btn': function (ev) {\n\t this.trigger('params', this, ev);\n\t },\n\t 'click .download-btn': function (ev) {\n\t this.trigger('download', this, ev);\n\t }\n\t }),\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetListItemView.prototype.templates = function () {\n\t //TODO: move to require text! plugin\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t failed_metadata: BASE_MVC.wrapTemplate([\n\t // failed metadata is rendered as a warning on an otherwise ok dataset view\n\t '<% if( model.state === \"failed_metadata\" ){ %>', '
              ', _l('An error occurred setting the metadata for this dataset'), '
              ', '<% } %>']),\n\t error: BASE_MVC.wrapTemplate([\n\t // error during index fetch - show error on dataset\n\t '<% if( model.error ){ %>', '
              ', _l('There was an error getting the data for this dataset'), ': <%- model.error %>', '
              ', '<% } %>']),\n\t purged: BASE_MVC.wrapTemplate(['<% if( model.purged ){ %>', '
              ', _l('This dataset has been deleted and removed from disk'), '
              ', '<% } %>']),\n\t deleted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.deleted && !model.purged ){ %>', '
              ', _l('This dataset has been deleted'), '
              ', '<% } %>'])\n\t\n\t //NOTE: hidden warning is only needed for HDAs\n\t });\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate(['
              ', '
              ', '
              ', '
              ', '
              ', '
              ',\n\t\n\t // do not display tags, annotation, display apps, or peek when deleted\n\t '<% if( !dataset.deleted && !dataset.purged ){ %>', '
              ', '
              ', '
              ', '<% if( dataset.peek ){ %>', '
              <%= dataset.peek %>
              ', '<% } %>', '<% } %>', '
              '], 'dataset');\n\t\n\t var noAccessTemplate = BASE_MVC.wrapTemplate(['
              ', '
              ', _l('You do not have permission to view this dataset'), '
              ', '
              '], 'dataset');\n\t\n\t //TODO: still toooooooooooooo complex - rework\n\t var summaryTemplates = {};\n\t summaryTemplates[STATES.OK] = summaryTemplates[STATES.FAILED_METADATA] = BASE_MVC.wrapTemplate(['<% if( dataset.misc_blurb ){ %>', '
              ', '<%- dataset.misc_blurb %>', '
              ', '<% } %>', '<% if( dataset.file_ext ){ %>', '
              ', '', '<%- dataset.file_ext %>', '
              ', '<% } %>', '<% if( dataset.metadata_dbkey ){ %>', '
              ', '', '', '<%- dataset.metadata_dbkey %>', '', '
              ', '<% } %>', '<% if( dataset.misc_info ){ %>', '
              ', '<%- dataset.misc_info %>', '
              ', '<% } %>'], 'dataset');\n\t summaryTemplates[STATES.NEW] = BASE_MVC.wrapTemplate(['
              ', _l('This is a new dataset and not all of its data are available yet'), '
              '], 'dataset');\n\t summaryTemplates[STATES.NOT_VIEWABLE] = BASE_MVC.wrapTemplate(['
              ', _l('You do not have permission to view this dataset'), '
              '], 'dataset');\n\t summaryTemplates[STATES.DISCARDED] = BASE_MVC.wrapTemplate(['
              ', _l('The job creating this dataset was cancelled before completion'), '
              '], 'dataset');\n\t summaryTemplates[STATES.QUEUED] = BASE_MVC.wrapTemplate(['
              ', _l('This job is waiting to run'), '
              '], 'dataset');\n\t summaryTemplates[STATES.RUNNING] = BASE_MVC.wrapTemplate(['
              ', _l('This job is currently running'), '
              '], 'dataset');\n\t summaryTemplates[STATES.UPLOAD] = BASE_MVC.wrapTemplate(['
              ', _l('This dataset is currently uploading'), '
              '], 'dataset');\n\t summaryTemplates[STATES.SETTING_METADATA] = BASE_MVC.wrapTemplate(['
              ', _l('Metadata is being auto-detected'), '
              '], 'dataset');\n\t summaryTemplates[STATES.PAUSED] = BASE_MVC.wrapTemplate(['
              ', _l('This job is paused. Use the \"Resume Paused Jobs\" in the history menu to resume'), '
              '], 'dataset');\n\t summaryTemplates[STATES.ERROR] = BASE_MVC.wrapTemplate(['<% if( !dataset.purged ){ %>', '
              <%- dataset.misc_blurb %>
              ', '<% } %>', '', _l('An error occurred with this dataset'), ':', '
              <%- dataset.misc_info %>
              '], 'dataset');\n\t summaryTemplates[STATES.EMPTY] = BASE_MVC.wrapTemplate(['
              ', _l('No data'), ': <%- dataset.misc_blurb %>
              '], 'dataset');\n\t summaryTemplates.unknown = BASE_MVC.wrapTemplate(['
              Error: unknown dataset state: \"<%- dataset.state %>\"
              '], 'dataset');\n\t\n\t // messages to be displayed only within the details section ('below the fold')\n\t var detailMessageTemplates = {\n\t resubmitted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.resubmitted ){ %>', '
              ', _l('The job creating this dataset has been resubmitted'), '
              ', '<% } %>'])\n\t };\n\t\n\t // this is applied to both old and new style display apps\n\t var displayApplicationsTemplate = BASE_MVC.wrapTemplate(['<% _.each( apps, function( app ){ %>', '
              ', '<%- app.label %> ', '', '<% _.each( app.links, function( link ){ %>', '\" href=\"<%- link.href %>\">', '<% print( _l( link.text ) ); %>', ' ', '<% }); %>', '', '
              ', '<% }); %>'], 'apps');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t details: detailsTemplate,\n\t noAccess: noAccessTemplate,\n\t summaries: summaryTemplates,\n\t detailMessages: detailMessageTemplates,\n\t displayApplications: displayApplicationsTemplate\n\t });\n\t }();\n\t\n\t // ============================================================================\n\t return {\n\t DatasetListItemView: DatasetListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 59 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {/** Generic form view */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(11), __webpack_require__(5)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Form, Ui) {\n\t\n\t var View = Backbone.View.extend({\n\t\n\t initialize: function (options) {\n\t this.model = new Backbone.Model(options);\n\t this.url = this.model.get('url');\n\t this.redirect = this.model.get('redirect');\n\t this.setElement('
              ');\n\t this.render();\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t $.ajax({\n\t url: Galaxy.root + this.url,\n\t type: 'GET'\n\t }).done(function (response) {\n\t var options = $.extend({}, self.model.attributes, response);\n\t var form = new Form({\n\t title: options.title,\n\t message: options.message,\n\t status: options.status || 'warning',\n\t icon: options.icon,\n\t inputs: options.inputs,\n\t buttons: {\n\t 'submit': new Ui.Button({\n\t tooltip: options.submit_tooltip,\n\t title: options.submit_title || 'Save settings',\n\t icon: options.submit_icon || 'fa-save',\n\t cls: 'btn btn-primary ui-clear-float',\n\t onclick: function () {\n\t self._submit(form);\n\t }\n\t })\n\t }\n\t });\n\t self.$el.empty().append(form.$el);\n\t }).fail(function (response) {\n\t self.$el.empty().append(new Ui.Message({\n\t message: 'Failed to load resource ' + self.url + '.',\n\t status: 'danger',\n\t persistent: true\n\t }).$el);\n\t });\n\t },\n\t\n\t _submit: function (form) {\n\t var self = this;\n\t $.ajax({\n\t url: Galaxy.root + self.url,\n\t data: JSON.stringify(form.data.create()),\n\t type: 'PUT',\n\t contentType: 'application/json'\n\t }).done(function (response) {\n\t var success_message = { message: response.message, status: 'success', persistent: false };\n\t if (self.redirect) {\n\t window.location = Galaxy.root + self.redirect + '?' + $.param(success_message);\n\t } else {\n\t form.data.matchModel(response, function (input, input_id) {\n\t form.field_list[input_id].value(input.value);\n\t });\n\t self._showMessage(form, success_message);\n\t }\n\t }).fail(function (response) {\n\t self._showMessage(form, { message: response.responseJSON.err_msg, status: 'danger', persistent: false });\n\t });\n\t },\n\t\n\t _showMessage: function (form, options) {\n\t var $panel = form.$el.parents().filter(function () {\n\t return ['auto', 'scroll'].indexOf($(this).css('overflow')) != -1;\n\t }).first();\n\t $panel.animate({ scrollTop: 0 }, 500);\n\t form.message.update(options);\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 60 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(56), __webpack_require__(88), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_MODEL, HISTORY_CONTENT, _l) {\n\t\n\t 'use strict';\n\t\n\t /*==============================================================================\n\t \n\t Models for DatasetCollections contained within a history.\n\t \n\t TODO:\n\t these might be compactable to one class if some duplication with\n\t collection-model is used.\n\t \n\t ==============================================================================*/\n\t\n\t var hcontentMixin = HISTORY_CONTENT.HistoryContentMixin,\n\t ListDC = DC_MODEL.ListDatasetCollection,\n\t PairDC = DC_MODEL.PairDatasetCollection,\n\t ListPairedDC = DC_MODEL.ListPairedDatasetCollection,\n\t ListOfListsDC = DC_MODEL.ListOfListsDatasetCollection;\n\t\n\t //==============================================================================\n\t /** Override to post to contents route w/o id. */\n\t function buildHDCASave(_super) {\n\t return function _save(attributes, options) {\n\t if (this.isNew()) {\n\t options = options || {};\n\t options.url = this.urlRoot + this.get('history_id') + '/contents';\n\t attributes = attributes || {};\n\t attributes.type = 'dataset_collection';\n\t }\n\t return _super.call(this, attributes, options);\n\t };\n\t }\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List Dataset Collection within a History.\n\t */\n\t var HistoryListDatasetCollection = ListDC.extend(hcontentMixin).extend(\n\t /** @lends HistoryListDatasetCollection.prototype */{\n\t\n\t defaults: _.extend(_.clone(ListDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + ListDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for Pair Dataset Collection within a History.\n\t * @constructs\n\t */\n\t var HistoryPairDatasetCollection = PairDC.extend(hcontentMixin).extend(\n\t /** @lends HistoryPairDatasetCollection.prototype */{\n\t\n\t defaults: _.extend(_.clone(PairDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'paired',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(PairDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + PairDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List of Pairs Dataset Collection within a History. */\n\t var HistoryListPairedDatasetCollection = ListPairedDC.extend(hcontentMixin).extend({\n\t\n\t defaults: _.extend(_.clone(ListPairedDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list:paired',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListPairedDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + ListPairedDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List of Lists Dataset Collection within a History. */\n\t var HistoryListOfListsDatasetCollection = ListOfListsDC.extend(hcontentMixin).extend({\n\t\n\t defaults: _.extend(_.clone(ListOfListsDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list:list',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListOfListsDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['HistoryListOfListsDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryListDatasetCollection: HistoryListDatasetCollection,\n\t HistoryPairDatasetCollection: HistoryPairDatasetCollection,\n\t HistoryListPairedDatasetCollection: HistoryListPairedDatasetCollection,\n\t HistoryListOfListsDatasetCollection: HistoryListOfListsDatasetCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 61 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, Backbone) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(79), __webpack_require__(86), __webpack_require__(60), __webpack_require__(63), __webpack_require__(7), __webpack_require__(149)], __WEBPACK_AMD_DEFINE_RESULT__ = function (CONTROLLED_FETCH_COLLECTION, HDA_MODEL, HDCA_MODEL, HISTORY_PREFS, BASE_MVC, AJAX_QUEUE) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = CONTROLLED_FETCH_COLLECTION.PaginatedCollection;\n\t /** @class Backbone collection for history content.\n\t * NOTE: history content seems like a dataset collection, but differs in that it is mixed:\n\t * each element can be either an HDA (dataset) or a DatasetCollection and co-exist on\n\t * the same level.\n\t * Dataset collections on the other hand are not mixed and (so far) can only contain either\n\t * HDAs or child dataset collections on one level.\n\t * This is why this does not inherit from any of the DatasetCollections (currently).\n\t */\n\t var HistoryContents = _super.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: 'history',\n\t\n\t // ........................................................................ composite collection\n\t /** since history content is a mix, override model fn into a factory, creating based on history_content_type */\n\t model: function (attrs, options) {\n\t if (attrs.history_content_type === \"dataset\") {\n\t return new HDA_MODEL.HistoryDatasetAssociation(attrs, options);\n\t } else if (attrs.history_content_type === \"dataset_collection\") {\n\t switch (attrs.collection_type) {\n\t case 'list':\n\t return new HDCA_MODEL.HistoryListDatasetCollection(attrs, options);\n\t case 'paired':\n\t return new HDCA_MODEL.HistoryPairDatasetCollection(attrs, options);\n\t case 'list:paired':\n\t return new HDCA_MODEL.HistoryListPairedDatasetCollection(attrs, options);\n\t case 'list:list':\n\t return new HDCA_MODEL.HistoryListOfListsDatasetCollection(attrs, options);\n\t }\n\t // This is a hack inside a hack:\n\t // Raise a plain object with validationError to fake a model.validationError\n\t // (since we don't have a model to use validate with)\n\t // (the outer hack being the mixed content/model function in this collection)\n\t var msg = 'Unknown collection_type: ' + attrs.collection_type;\n\t console.warn(msg, attrs);\n\t return { validationError: msg };\n\t }\n\t return { validationError: 'Unknown history_content_type: ' + attrs.history_content_type };\n\t },\n\t\n\t // ........................................................................ set up\n\t limitPerPage: 500,\n\t\n\t /** @type {Integer} how many contents per call to fetch when using progressivelyFetchDetails */\n\t limitPerProgressiveFetch: 500,\n\t\n\t /** @type {String} order used here and when fetching from server */\n\t order: 'hid',\n\t\n\t /** root api url */\n\t urlRoot: Galaxy.root + 'api/histories',\n\t\n\t /** complete api url */\n\t url: function () {\n\t return this.urlRoot + '/' + this.historyId + '/contents';\n\t },\n\t\n\t /** Set up */\n\t initialize: function (models, options) {\n\t options = options || {};\n\t _super.prototype.initialize.call(this, models, options);\n\t\n\t this.history = options.history || null;\n\t this.setHistoryId(options.historyId || null);\n\t /** @type {Boolean} does this collection contain and fetch deleted elements */\n\t this.includeDeleted = options.includeDeleted || this.includeDeleted;\n\t /** @type {Boolean} does this collection contain and fetch non-visible elements */\n\t this.includeHidden = options.includeHidden || this.includeHidden;\n\t\n\t // backbonejs uses collection.model.prototype.idAttribute to determine if a model is *already* in a collection\n\t // and either merged or replaced. In this case, our 'model' is a function so we need to add idAttribute\n\t // manually here - if we don't, contents will not merge but be replaced/swapped.\n\t this.model.prototype.idAttribute = 'type_id';\n\t },\n\t\n\t setHistoryId: function (newId) {\n\t this.historyId = newId;\n\t this._setUpWebStorage();\n\t },\n\t\n\t /** Set up client side storage. Currently PersistanStorage keyed under 'history:' */\n\t _setUpWebStorage: function (initialSettings) {\n\t // TODO: use initialSettings\n\t if (!this.historyId) {\n\t return;\n\t }\n\t this.storage = new HISTORY_PREFS.HistoryPrefs({\n\t id: HISTORY_PREFS.HistoryPrefs.historyStorageKey(this.historyId)\n\t });\n\t this.trigger('new-storage', this.storage, this);\n\t\n\t this.on({\n\t 'include-deleted': function (newVal) {\n\t this.storage.includeDeleted(newVal);\n\t },\n\t 'include-hidden': function (newVal) {\n\t this.storage.includeHidden(newVal);\n\t }\n\t });\n\t\n\t this.includeDeleted = this.storage.includeDeleted() || false;\n\t this.includeHidden = this.storage.includeHidden() || false;\n\t return this;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: _.extend(_.clone(_super.prototype.comparators), {\n\t 'name': BASE_MVC.buildComparator('name', { ascending: true }),\n\t 'name-dsc': BASE_MVC.buildComparator('name', { ascending: false }),\n\t 'hid': BASE_MVC.buildComparator('hid', { ascending: false }),\n\t 'hid-asc': BASE_MVC.buildComparator('hid', { ascending: true })\n\t }),\n\t\n\t /** Get every model in this collection not in a 'ready' state (running). */\n\t running: function () {\n\t return this.filter(function (c) {\n\t return !c.inReadyState();\n\t });\n\t },\n\t\n\t /** return contents that are not ready and not deleted/hidden */\n\t runningAndActive: function () {\n\t return this.filter(function (c) {\n\t return !c.inReadyState() && c.get('visible')\n\t // TODO: deletedOrPurged?\n\t && !c.get('deleted');\n\t });\n\t },\n\t\n\t /** Get the model with the given hid\n\t * @param {Int} hid the hid to search for\n\t * @returns {HistoryDatasetAssociation} the model with the given hid or undefined if not found\n\t */\n\t getByHid: function (hid) {\n\t // note: there *can* be more than one content with a given hid, this finds the first based on order\n\t return this.findWhere({ hid: hid });\n\t },\n\t\n\t /** return true if all contents have details */\n\t haveDetails: function () {\n\t return this.all(function (c) {\n\t return c.hasDetails();\n\t });\n\t },\n\t\n\t // ........................................................................ hidden / deleted\n\t /** return a new contents collection of only hidden items */\n\t hidden: function () {\n\t return this.filter(function (c) {\n\t return c.hidden();\n\t });\n\t },\n\t\n\t /** return a new contents collection of only hidden items */\n\t deleted: function () {\n\t return this.filter(function (c) {\n\t return c.get('deleted');\n\t });\n\t },\n\t\n\t /** return a new contents collection of only hidden items */\n\t visibleAndUndeleted: function () {\n\t return this.filter(function (c) {\n\t return c.get('visible') &&\n\t // TODO: deletedOrPurged?\n\t !c.get('deleted');\n\t });\n\t },\n\t\n\t /** create a setter in order to publish the change */\n\t setIncludeDeleted: function (setting, options) {\n\t if (_.isBoolean(setting) && setting !== this.includeDeleted) {\n\t this.includeDeleted = setting;\n\t if (_.result(options, 'silent')) {\n\t return;\n\t }\n\t this.trigger('include-deleted', setting, this);\n\t }\n\t },\n\t\n\t /** create a setter in order to publish the change */\n\t setIncludeHidden: function (setting, options) {\n\t if (_.isBoolean(setting) && setting !== this.includeHidden) {\n\t this.includeHidden = setting;\n\t options = options || {};\n\t if (_.result(options, 'silent')) {\n\t return;\n\t }\n\t this.trigger('include-hidden', setting, this);\n\t }\n\t },\n\t\n\t // ........................................................................ ajax\n\t // ............ controlled fetch collection\n\t /** override to get expanded ids from sessionStorage and pass to API as details */\n\t fetch: function (options) {\n\t options = options || {};\n\t if (this.historyId && !options.details) {\n\t var prefs = HISTORY_PREFS.HistoryPrefs.get(this.historyId).toJSON();\n\t if (!_.isEmpty(prefs.expandedIds)) {\n\t options.details = _.values(prefs.expandedIds).join(',');\n\t }\n\t }\n\t return _super.prototype.fetch.call(this, options);\n\t },\n\t\n\t // ............. ControlledFetch stuff\n\t /** override to include the API versioning flag */\n\t _buildFetchData: function (options) {\n\t return _.extend(_super.prototype._buildFetchData.call(this, options), {\n\t v: 'dev'\n\t });\n\t },\n\t\n\t /** Extend to include details and version */\n\t _fetchParams: _super.prototype._fetchParams.concat([\n\t // TODO: remove (the need for) both\n\t /** version */\n\t 'v',\n\t /** dataset ids to get full details of */\n\t 'details']),\n\t\n\t /** override to add deleted/hidden filters */\n\t _buildFetchFilters: function (options) {\n\t var superFilters = _super.prototype._buildFetchFilters.call(this, options) || {};\n\t var filters = {};\n\t if (!this.includeDeleted) {\n\t filters.deleted = false;\n\t filters.purged = false;\n\t }\n\t if (!this.includeHidden) {\n\t filters.visible = true;\n\t }\n\t return _.defaults(superFilters, filters);\n\t },\n\t\n\t // ............ paginated collection\n\t getTotalItemCount: function () {\n\t return this.history.contentsShown();\n\t },\n\t\n\t // ............ history contents specific ajax\n\t /** override to filter requested contents to those updated after the Date 'since' */\n\t fetchUpdated: function (since, options) {\n\t if (since) {\n\t options = options || { filters: {} };\n\t options.remove = false;\n\t options.filters = {\n\t 'update_time-ge': since.toISOString(),\n\t // workflows will produce hidden datasets (non-output datasets) that still\n\t // need to be updated in the collection or they'll update forever\n\t // we can remove the default visible filter by using an 'empty' value\n\t visible: ''\n\t };\n\t }\n\t return this.fetch(options);\n\t },\n\t\n\t /** fetch all the deleted==true contents of this collection */\n\t fetchDeleted: function (options) {\n\t options = options || {};\n\t var self = this;\n\t options.filters = _.extend(options.filters, {\n\t // all deleted, purged or not\n\t deleted: true,\n\t purged: undefined\n\t });\n\t options.remove = false;\n\t\n\t self.trigger('fetching-deleted', self);\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-deleted-done', self);\n\t });\n\t },\n\t\n\t /** fetch all the visible==false contents of this collection */\n\t fetchHidden: function (options) {\n\t options = options || {};\n\t var self = this;\n\t options.filters = _.extend(options.filters, {\n\t visible: false\n\t });\n\t options.remove = false;\n\t\n\t self.trigger('fetching-hidden', self);\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-hidden-done', self);\n\t });\n\t },\n\t\n\t /** fetch detailed model data for all contents in this collection */\n\t fetchAllDetails: function (options) {\n\t options = options || {};\n\t var detailsFlag = { details: 'all' };\n\t options.data = _.extend(options.data || {}, detailsFlag);\n\t return this.fetch(options);\n\t },\n\t\n\t /** specialty fetch method for retrieving the element_counts of all hdcas in the history */\n\t fetchCollectionCounts: function (options) {\n\t options = options || {};\n\t options.keys = ['type_id', 'element_count'].join(',');\n\t options.filters = _.extend(options.filters || {}, {\n\t history_content_type: 'dataset_collection'\n\t });\n\t options.remove = false;\n\t return this.fetch(options);\n\t },\n\t\n\t // ............. quasi-batch ops\n\t // TODO: to batch\n\t /** helper that fetches using filterParams then calls save on each fetched using updateWhat as the save params */\n\t _filterAndUpdate: function (filterParams, updateWhat) {\n\t var self = this;\n\t var idAttribute = self.model.prototype.idAttribute;\n\t var updateArgs = [updateWhat];\n\t\n\t return self.fetch({ filters: filterParams, remove: false }).then(function (fetched) {\n\t // convert filtered json array to model array\n\t fetched = fetched.reduce(function (modelArray, currJson, i) {\n\t var model = self.get(currJson[idAttribute]);\n\t return model ? modelArray.concat(model) : modelArray;\n\t }, []);\n\t return self.ajaxQueue('save', updateArgs, fetched);\n\t });\n\t },\n\t\n\t /** using a queue, perform ajaxFn on each of the models in this collection */\n\t ajaxQueue: function (ajaxFn, args, collection) {\n\t collection = collection || this.models;\n\t return new AJAX_QUEUE.AjaxQueue(collection.slice().reverse().map(function (content, i) {\n\t var fn = _.isString(ajaxFn) ? content[ajaxFn] : ajaxFn;\n\t return function () {\n\t return fn.apply(content, args);\n\t };\n\t })).deferred;\n\t },\n\t\n\t /** fetch contents' details in batches of limitPerCall - note: only get searchable details here */\n\t progressivelyFetchDetails: function (options) {\n\t options = options || {};\n\t var deferred = jQuery.Deferred();\n\t var self = this;\n\t var limit = options.limitPerCall || self.limitPerProgressiveFetch;\n\t // TODO: only fetch tags and annotations if specifically requested\n\t var searchAttributes = HDA_MODEL.HistoryDatasetAssociation.prototype.searchAttributes;\n\t var detailKeys = searchAttributes.join(',');\n\t\n\t function _recursivelyFetch(offset) {\n\t offset = offset || 0;\n\t var _options = _.extend(_.clone(options), {\n\t view: 'summary',\n\t keys: detailKeys,\n\t limit: limit,\n\t offset: offset,\n\t reset: offset === 0,\n\t remove: false\n\t });\n\t\n\t _.defer(function () {\n\t self.fetch.call(self, _options).fail(deferred.reject).done(function (response) {\n\t deferred.notify(response, limit, offset);\n\t if (response.length !== limit) {\n\t self.allFetched = true;\n\t deferred.resolve(response, limit, offset);\n\t } else {\n\t _recursivelyFetch(offset + limit);\n\t }\n\t });\n\t });\n\t }\n\t _recursivelyFetch();\n\t return deferred;\n\t },\n\t\n\t /** does some bit of JSON represent something that can be copied into this contents collection */\n\t isCopyable: function (contentsJSON) {\n\t var copyableModelClasses = ['HistoryDatasetAssociation', 'HistoryDatasetCollectionAssociation'];\n\t return _.isObject(contentsJSON) && contentsJSON.id && _.contains(copyableModelClasses, contentsJSON.model_class);\n\t },\n\t\n\t /** copy an existing, accessible hda into this collection */\n\t copy: function (json) {\n\t // TODO: somehow showhorn all this into 'save'\n\t var id, type, contentType;\n\t if (_.isString(json)) {\n\t id = json;\n\t contentType = 'hda';\n\t type = 'dataset';\n\t } else {\n\t id = json.id;\n\t contentType = {\n\t 'HistoryDatasetAssociation': 'hda',\n\t 'LibraryDatasetDatasetAssociation': 'ldda',\n\t 'HistoryDatasetCollectionAssociation': 'hdca'\n\t }[json.model_class] || 'hda';\n\t type = contentType === 'hdca' ? 'dataset_collection' : 'dataset';\n\t }\n\t var collection = this,\n\t xhr = jQuery.ajax(this.url(), {\n\t method: 'POST',\n\t contentType: 'application/json',\n\t data: JSON.stringify({\n\t content: id,\n\t source: contentType,\n\t type: type\n\t })\n\t }).done(function (response) {\n\t collection.add([response], { parse: true });\n\t }).fail(function (error, status, message) {\n\t collection.trigger('error', collection, xhr, {}, 'Error copying contents', { type: type, id: id, source: contentType });\n\t });\n\t return xhr;\n\t },\n\t\n\t /** create a new HDCA in this collection */\n\t createHDCA: function (elementIdentifiers, collectionType, name, hideSourceItems, options) {\n\t // normally collection.create returns the new model, but we need the promise from the ajax, so we fake create\n\t //precondition: elementIdentifiers is an array of plain js objects\n\t // in the proper form to create the collectionType\n\t var hdca = this.model({\n\t history_content_type: 'dataset_collection',\n\t collection_type: collectionType,\n\t history_id: this.historyId,\n\t name: name,\n\t hide_source_items: hideSourceItems || false,\n\t // should probably be able to just send in a bunch of json here and restruct per class\n\t // note: element_identifiers is now (incorrectly) an attribute\n\t element_identifiers: elementIdentifiers\n\t // do not create the model on the client until the ajax returns\n\t });\n\t return hdca.save(options);\n\t },\n\t\n\t // ........................................................................ searching\n\t /** return true if all contents have the searchable attributes */\n\t haveSearchDetails: function () {\n\t return this.allFetched && this.all(function (content) {\n\t // null (which is a valid returned annotation value)\n\t // will return false when using content.has( 'annotation' )\n\t //TODO: a bit hacky - formalize\n\t return _.has(content.attributes, 'annotation');\n\t });\n\t },\n\t\n\t /** return a new collection of contents whose attributes contain the substring matchesWhat */\n\t matches: function (matchesWhat) {\n\t return this.filter(function (content) {\n\t return content.matches(matchesWhat);\n\t });\n\t },\n\t\n\t // ........................................................................ misc\n\t /** In this override, copy the historyId to the clone */\n\t clone: function () {\n\t var clone = Backbone.Collection.prototype.clone.call(this);\n\t clone.historyId = this.historyId;\n\t return clone;\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['HistoryContents(', [this.historyId, this.length].join(), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryContents: HistoryContents\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(2)))\n\n/***/ },\n/* 62 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, jQuery, _, $) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(61), __webpack_require__(63), __webpack_require__(79), __webpack_require__(4), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_CONTENTS, HISTORY_PREFS, CONTROLLED_FETCH_COLLECTION, UTILS, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /** @class Model for a Galaxy history resource - both a record of user\n\t * tool use and a collection of the datasets those tools produced.\n\t * @name History\n\t * @augments Backbone.Model\n\t */\n\t\n\t var History = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.mixin(BASE_MVC.SearchableModelMixin, /** @lends History.prototype */{\n\t _logNamespace: 'history',\n\t\n\t /** ms between fetches when checking running jobs/datasets for updates */\n\t UPDATE_DELAY: 4000,\n\t\n\t // values from api (may need more)\n\t defaults: {\n\t model_class: 'History',\n\t id: null,\n\t name: 'Unnamed History',\n\t state: 'new',\n\t\n\t deleted: false,\n\t contents_active: {},\n\t contents_states: {}\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/histories',\n\t\n\t contentsClass: HISTORY_CONTENTS.HistoryContents,\n\t\n\t /** What model fields to search with */\n\t searchAttributes: ['name', 'annotation', 'tags'],\n\t\n\t /** Adding title and singular tag */\n\t searchAliases: {\n\t title: 'name',\n\t tag: 'tags'\n\t },\n\t\n\t // ........................................................................ set up/tear down\n\t /** Set up the model\n\t * @param {Object} historyJSON model data for this History\n\t * @param {Object} options any extra settings including logger\n\t */\n\t initialize: function (historyJSON, options) {\n\t options = options || {};\n\t this.logger = options.logger || null;\n\t this.log(this + \".initialize:\", historyJSON, options);\n\t\n\t /** HistoryContents collection of the HDAs contained in this history. */\n\t this.contents = new this.contentsClass([], {\n\t history: this,\n\t historyId: this.get('id'),\n\t order: options.order\n\t });\n\t\n\t this._setUpListeners();\n\t this._setUpCollectionListeners();\n\t\n\t /** cached timeout id for the dataset updater */\n\t this.updateTimeoutId = null;\n\t },\n\t\n\t /** set up any event listeners for this history including those to the contained HDAs\n\t * events: error:contents if an error occurred with the contents collection\n\t */\n\t _setUpListeners: function () {\n\t // if the model's id changes ('current' or null -> an actual id), update the contents history_id\n\t return this.on({\n\t 'error': function (model, xhr, options, msg, details) {\n\t this.clearUpdateTimeout();\n\t },\n\t 'change:id': function (model, newId) {\n\t if (this.contents) {\n\t this.contents.historyId = newId;\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** event handlers for the contents submodels */\n\t _setUpCollectionListeners: function () {\n\t if (!this.contents) {\n\t return this;\n\t }\n\t // bubble up errors\n\t return this.listenTo(this.contents, {\n\t 'error': function () {\n\t this.trigger.apply(this, jQuery.makeArray(arguments));\n\t }\n\t });\n\t },\n\t\n\t // ........................................................................ derived attributes\n\t /** */\n\t contentsShown: function () {\n\t var contentsActive = this.get('contents_active');\n\t var shown = contentsActive.active || 0;\n\t shown += this.contents.includeDeleted ? contentsActive.deleted : 0;\n\t shown += this.contents.includeHidden ? contentsActive.hidden : 0;\n\t return shown;\n\t },\n\t\n\t /** convert size in bytes to a more human readable version */\n\t nice_size: function () {\n\t var size = this.get('size');\n\t return size ? UTILS.bytesToString(size, true, 2) : _l('(empty)');\n\t },\n\t\n\t /** override to add nice_size */\n\t toJSON: function () {\n\t return _.extend(Backbone.Model.prototype.toJSON.call(this), {\n\t nice_size: this.nice_size()\n\t });\n\t },\n\t\n\t /** override to allow getting nice_size */\n\t get: function (key) {\n\t if (key === 'nice_size') {\n\t return this.nice_size();\n\t }\n\t return Backbone.Model.prototype.get.apply(this, arguments);\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** T/F is this history owned by the current user (Galaxy.user)\n\t * Note: that this will return false for an anon user even if the history is theirs.\n\t */\n\t ownedByCurrUser: function () {\n\t // no currUser\n\t if (!Galaxy || !Galaxy.user) {\n\t return false;\n\t }\n\t // user is anon or history isn't owned\n\t if (Galaxy.user.isAnonymous() || Galaxy.user.id !== this.get('user_id')) {\n\t return false;\n\t }\n\t return true;\n\t },\n\t\n\t /** Return the number of running jobs assoc with this history (note: unknown === 0) */\n\t numOfUnfinishedJobs: function () {\n\t var unfinishedJobIds = this.get('non_ready_jobs');\n\t return unfinishedJobIds ? unfinishedJobIds.length : 0;\n\t },\n\t\n\t /** Return the number of running hda/hdcas in this history (note: unknown === 0) */\n\t numOfUnfinishedShownContents: function () {\n\t return this.contents.runningAndActive().length || 0;\n\t },\n\t\n\t // ........................................................................ updates\n\t _fetchContentRelatedAttributes: function () {\n\t var contentRelatedAttrs = ['size', 'non_ready_jobs', 'contents_active', 'hid_counter'];\n\t return this.fetch({ data: $.param({ keys: contentRelatedAttrs.join(',') }) });\n\t },\n\t\n\t /** check for any changes since the last time we updated (or fetch all if ) */\n\t refresh: function (options) {\n\t // console.log( this + '.refresh' );\n\t options = options || {};\n\t var self = this;\n\t\n\t // note if there was no previous update time, all summary contents will be fetched\n\t var lastUpdateTime = self.lastUpdateTime;\n\t // if we don't flip this, then a fully-fetched list will not be re-checked via fetch\n\t this.contents.allFetched = false;\n\t var fetchFn = self.contents.currentPage !== 0 ? function () {\n\t return self.contents.fetchPage(self.contents.currentPage);\n\t } : function () {\n\t return self.contents.fetchUpdated(lastUpdateTime);\n\t };\n\t // note: if there was no previous update time, all summary contents will be fetched\n\t return fetchFn().done(function (response, status, xhr) {\n\t var serverResponseDatetime;\n\t try {\n\t serverResponseDatetime = new Date(xhr.getResponseHeader('Date'));\n\t } catch (err) {}\n\t self.lastUpdateTime = serverResponseDatetime || new Date();\n\t self.checkForUpdates(options);\n\t });\n\t },\n\t\n\t /** continuously fetch updated contents every UPDATE_DELAY ms if this history's datasets or jobs are unfinished */\n\t checkForUpdates: function (options) {\n\t // console.log( this + '.checkForUpdates' );\n\t options = options || {};\n\t var delay = this.UPDATE_DELAY;\n\t var self = this;\n\t if (!self.id) {\n\t return;\n\t }\n\t\n\t function _delayThenUpdate() {\n\t // prevent buildup of updater timeouts by clearing previous if any, then set new and cache id\n\t self.clearUpdateTimeout();\n\t self.updateTimeoutId = setTimeout(function () {\n\t self.refresh(options);\n\t }, delay);\n\t }\n\t\n\t // if there are still datasets in the non-ready state, recurse into this function with the new time\n\t var nonReadyContentCount = this.numOfUnfinishedShownContents();\n\t // console.log( 'nonReadyContentCount:', nonReadyContentCount );\n\t if (nonReadyContentCount > 0) {\n\t _delayThenUpdate();\n\t } else {\n\t // no datasets are running, but currently runnning jobs may still produce new datasets\n\t // see if the history has any running jobs and continue to update if so\n\t // (also update the size for the user in either case)\n\t self._fetchContentRelatedAttributes().done(function (historyData) {\n\t // console.log( 'non_ready_jobs:', historyData.non_ready_jobs );\n\t if (self.numOfUnfinishedJobs() > 0) {\n\t _delayThenUpdate();\n\t } else {\n\t // otherwise, let listeners know that all updates have stopped\n\t self.trigger('ready');\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** clear the timeout and the cached timeout id */\n\t clearUpdateTimeout: function () {\n\t if (this.updateTimeoutId) {\n\t clearTimeout(this.updateTimeoutId);\n\t this.updateTimeoutId = null;\n\t }\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** fetch this histories data (using options) then it's contents (using contentsOptions) */\n\t fetchWithContents: function (options, contentsOptions) {\n\t options = options || {};\n\t var self = this;\n\t\n\t // console.log( this + '.fetchWithContents' );\n\t // TODO: push down to a base class\n\t options.view = 'dev-detailed';\n\t\n\t // fetch history then use history data to fetch (paginated) contents\n\t return this.fetch(options).then(function getContents(history) {\n\t self.contents.history = self;\n\t self.contents.setHistoryId(history.id);\n\t return self.fetchContents(contentsOptions);\n\t });\n\t },\n\t\n\t /** fetch this histories contents, adjusting options based on the stored history preferences */\n\t fetchContents: function (options) {\n\t options = options || {};\n\t var self = this;\n\t\n\t // we're updating, reset the update time\n\t self.lastUpdateTime = new Date();\n\t return self.contents.fetchCurrentPage(options);\n\t },\n\t\n\t /** save this history, _Mark_ing it as deleted (just a flag) */\n\t _delete: function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** purge this history, _Mark_ing it as purged and removing all dataset data from the server */\n\t purge: function (options) {\n\t if (this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true, purged: true }, options);\n\t },\n\t /** save this history, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** Make a copy of this history on the server\n\t * @param {Boolean} current if true, set the copy as the new current history (default: true)\n\t * @param {String} name name of new history (default: none - server sets to: Copy of )\n\t * @fires copied passed this history and the response JSON from the copy\n\t * @returns {xhr}\n\t */\n\t copy: function (current, name, allDatasets) {\n\t current = current !== undefined ? current : true;\n\t if (!this.id) {\n\t throw new Error('You must set the history ID before copying it.');\n\t }\n\t\n\t var postData = { history_id: this.id };\n\t if (current) {\n\t postData.current = true;\n\t }\n\t if (name) {\n\t postData.name = name;\n\t }\n\t if (!allDatasets) {\n\t postData.all_datasets = false;\n\t }\n\t postData.view = 'dev-detailed';\n\t\n\t var history = this;\n\t var copy = jQuery.post(this.urlRoot, postData);\n\t // if current - queue to setAsCurrent before firing 'copied'\n\t if (current) {\n\t return copy.then(function (response) {\n\t var newHistory = new History(response);\n\t return newHistory.setAsCurrent().done(function () {\n\t history.trigger('copied', history, response);\n\t });\n\t });\n\t }\n\t return copy.done(function (response) {\n\t history.trigger('copied', history, response);\n\t });\n\t },\n\t\n\t setAsCurrent: function () {\n\t var history = this,\n\t xhr = jQuery.getJSON(Galaxy.root + 'history/set_as_current?id=' + this.id);\n\t\n\t xhr.done(function () {\n\t history.trigger('set-as-current', history);\n\t });\n\t return xhr;\n\t },\n\t\n\t // ........................................................................ misc\n\t toString: function () {\n\t return 'History(' + this.get('id') + ',' + this.get('name') + ')';\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t var _collectionSuper = CONTROLLED_FETCH_COLLECTION.InfinitelyScrollingCollection;\n\t /** @class A collection of histories (per user)\n\t * that maintains the current history as the first in the collection.\n\t * New or copied histories become the current history.\n\t */\n\t var HistoryCollection = _collectionSuper.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: 'history',\n\t\n\t model: History,\n\t /** @type {String} initial order used by collection */\n\t order: 'update_time',\n\t /** @type {Number} limit used for the first fetch (or a reset) */\n\t limitOnFirstFetch: 10,\n\t /** @type {Number} limit used for each subsequent fetch */\n\t limitPerFetch: 10,\n\t\n\t initialize: function (models, options) {\n\t options = options || {};\n\t this.log('HistoryCollection.initialize', models, options);\n\t _collectionSuper.prototype.initialize.call(this, models, options);\n\t\n\t /** @type {boolean} should deleted histories be included */\n\t this.includeDeleted = options.includeDeleted || false;\n\t\n\t /** @type {String} encoded id of the history that's current */\n\t this.currentHistoryId = options.currentHistoryId;\n\t\n\t this.setUpListeners();\n\t // note: models are sent to reset *after* this fn ends; up to this point\n\t // the collection *is empty*\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/histories',\n\t url: function () {\n\t return this.urlRoot;\n\t },\n\t\n\t /** set up reflexive event handlers */\n\t setUpListeners: function setUpListeners() {\n\t return this.on({\n\t // when a history is deleted, remove it from the collection (if optionally set to do so)\n\t 'change:deleted': function (history) {\n\t // TODO: this becomes complicated when more filters are used\n\t this.debug('change:deleted', this.includeDeleted, history.get('deleted'));\n\t if (!this.includeDeleted && history.get('deleted')) {\n\t this.remove(history);\n\t }\n\t },\n\t // listen for a history copy, setting it to current\n\t 'copied': function (original, newData) {\n\t this.setCurrent(new History(newData, []));\n\t },\n\t // when a history is made current, track the id in the collection\n\t 'set-as-current': function (history) {\n\t var oldCurrentId = this.currentHistoryId;\n\t this.trigger('no-longer-current', oldCurrentId);\n\t this.currentHistoryId = history.id;\n\t }\n\t });\n\t },\n\t\n\t /** override to change view */\n\t _buildFetchData: function (options) {\n\t return _.extend(_collectionSuper.prototype._buildFetchData.call(this, options), {\n\t view: 'dev-detailed'\n\t });\n\t },\n\t\n\t /** override to filter out deleted and purged */\n\t _buildFetchFilters: function (options) {\n\t var superFilters = _collectionSuper.prototype._buildFetchFilters.call(this, options) || {};\n\t var filters = {};\n\t if (!this.includeDeleted) {\n\t filters.deleted = false;\n\t filters.purged = false;\n\t } else {\n\t // force API to return both deleted and non\n\t //TODO: when the API is updated, remove this\n\t filters.deleted = null;\n\t }\n\t return _.defaults(superFilters, filters);\n\t },\n\t\n\t /** override to fetch current as well (as it may be outside the first 10, etc.) */\n\t fetchFirst: function (options) {\n\t var self = this;\n\t // TODO: batch?\n\t var xhr = $.when();\n\t if (this.currentHistoryId) {\n\t xhr = _collectionSuper.prototype.fetchFirst.call(self, {\n\t silent: true,\n\t limit: 1,\n\t filters: {\n\t // without these a deleted current history will return [] here and block the other xhr\n\t 'purged': '',\n\t 'deleted': '',\n\t 'encoded_id-in': this.currentHistoryId\n\t }\n\t });\n\t }\n\t return xhr.then(function () {\n\t options = options || {};\n\t options.offset = 0;\n\t return self.fetchMore(options);\n\t });\n\t },\n\t\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: _.extend(_.clone(_collectionSuper.prototype.comparators), {\n\t 'name': BASE_MVC.buildComparator('name', { ascending: true }),\n\t 'name-dsc': BASE_MVC.buildComparator('name', { ascending: false }),\n\t 'size': BASE_MVC.buildComparator('size', { ascending: false }),\n\t 'size-asc': BASE_MVC.buildComparator('size', { ascending: true })\n\t }),\n\t\n\t /** override to always have the current history first */\n\t sort: function (options) {\n\t options = options || {};\n\t var silent = options.silent;\n\t var currentHistory = this.remove(this.get(this.currentHistoryId));\n\t _collectionSuper.prototype.sort.call(this, _.defaults({ silent: true }, options));\n\t this.unshift(currentHistory, { silent: true });\n\t if (!silent) {\n\t this.trigger('sort', this, options);\n\t }\n\t return this;\n\t },\n\t\n\t /** create a new history and by default set it to be the current history */\n\t create: function create(data, hdas, historyOptions, xhrOptions) {\n\t //TODO: .create is actually a collection function that's overridden here\n\t var collection = this,\n\t xhr = jQuery.getJSON(Galaxy.root + 'history/create_new_current');\n\t return xhr.done(function (newData) {\n\t collection.setCurrent(new History(newData, [], historyOptions || {}));\n\t });\n\t },\n\t\n\t /** set the current history to the given history, placing it first in the collection.\n\t * Pass standard bbone options for use in unshift.\n\t * @triggers new-current passed history and this collection\n\t */\n\t setCurrent: function (history, options) {\n\t options = options || {};\n\t // new histories go in the front\n\t this.unshift(history, options);\n\t this.currentHistoryId = history.get('id');\n\t if (!options.silent) {\n\t this.trigger('new-current', history, this);\n\t }\n\t return this;\n\t },\n\t\n\t toString: function toString() {\n\t return 'HistoryCollection(' + this.length + ',current:' + this.currentHistoryId + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t History: History,\n\t HistoryCollection: HistoryCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 63 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7)], __WEBPACK_AMD_DEFINE_RESULT__ = function (BASE_MVC) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'history';\n\t\n\t // ============================================================================\n\t /** session storage for individual history preferences */\n\t var HistoryPrefs = BASE_MVC.SessionStorageModel.extend(\n\t /** @lends HistoryPrefs.prototype */{\n\t //TODO:?? move to user prefs?\n\t defaults: {\n\t //TODO:?? expandedIds to array?\n\t expandedIds: {},\n\t show_deleted: false,\n\t show_hidden: false\n\t },\n\t\n\t /** add an hda id to the hash of expanded hdas */\n\t addExpanded: function (model) {\n\t //TODO: use type_id and not model\n\t var current = this.get('expandedIds');\n\t current[model.id] = model.get('id');\n\t this.save('expandedIds', current);\n\t },\n\t\n\t /** remove an hda id from the hash of expanded hdas */\n\t removeExpanded: function (model) {\n\t var current = this.get('expandedIds');\n\t delete current[model.id];\n\t this.save('expandedIds', current);\n\t },\n\t\n\t isExpanded: function (contentId) {\n\t return _.result(this.get('expandedIds'), contentId, false);\n\t },\n\t\n\t allExpanded: function () {\n\t return _.values(this.get('expandedIds'));\n\t },\n\t\n\t clearExpanded: function () {\n\t this.set('expandedIds', {});\n\t },\n\t\n\t includeDeleted: function (val) {\n\t // moving the invocation here so other components don't need to know the key\n\t // TODO: change this key later\n\t if (!_.isUndefined(val)) {\n\t this.set('show_deleted', val);\n\t }\n\t return this.get('show_deleted');\n\t },\n\t\n\t includeHidden: function (val) {\n\t // TODO: change this key later\n\t if (!_.isUndefined(val)) {\n\t this.set('show_hidden', val);\n\t }\n\t return this.get('show_hidden');\n\t },\n\t\n\t toString: function () {\n\t return 'HistoryPrefs(' + this.id + ')';\n\t }\n\t\n\t }, {\n\t // ........................................................................ class vars\n\t // class lvl for access w/o instantiation\n\t storageKeyPrefix: 'history:',\n\t\n\t /** key string to store each histories settings under */\n\t historyStorageKey: function historyStorageKey(historyId) {\n\t if (!historyId) {\n\t throw new Error('HistoryPrefs.historyStorageKey needs valid id: ' + historyId);\n\t }\n\t // single point of change\n\t return HistoryPrefs.storageKeyPrefix + historyId;\n\t },\n\t\n\t /** return the existing storage for the history with the given id (or create one if it doesn't exist) */\n\t get: function get(historyId) {\n\t return new HistoryPrefs({ id: HistoryPrefs.historyStorageKey(historyId) });\n\t },\n\t\n\t /** clear all history related items in sessionStorage */\n\t clearAll: function clearAll(historyId) {\n\t for (var key in sessionStorage) {\n\t if (key.indexOf(HistoryPrefs.storageKeyPrefix) === 0) {\n\t sessionStorage.removeItem(key);\n\t }\n\t }\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryPrefs: HistoryPrefs\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 64 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'list';\n\t //==============================================================================\n\t /** A view which, when first rendered, shows only summary data/attributes, but\n\t * can be expanded to show further details (and optionally fetch those\n\t * details from the server).\n\t */\n\t var ExpandableView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: Although the reasoning behind them is different, this shares a lot with HiddenUntilActivated above: combine them\n\t //PRECONDITION: model must have method hasDetails\n\t //PRECONDITION: subclasses must have templates.el and templates.details\n\t\n\t initialize: function (attributes) {\n\t /** are the details of this view expanded/shown or not? */\n\t this.expanded = attributes.expanded || false;\n\t this.log('\\t expanded:', this.expanded);\n\t this.fxSpeed = attributes.fxSpeed !== undefined ? attributes.fxSpeed : this.fxSpeed;\n\t },\n\t\n\t // ........................................................................ render main\n\t /** jq fx speed */\n\t fxSpeed: 'fast',\n\t\n\t /** Render this content, set up ui.\n\t * @param {Number or String} speed the speed of the render\n\t */\n\t render: function (speed) {\n\t var $newRender = this._buildNewRender();\n\t this._setUpBehaviors($newRender);\n\t this._queueNewRender($newRender, speed);\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el.\n\t * If the view is already expanded, build the details as well.\n\t */\n\t _buildNewRender: function () {\n\t // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n\t var $newRender = $(this.templates.el(this.model.toJSON(), this));\n\t if (this.expanded) {\n\t this.$details($newRender).replaceWith(this._renderDetails().show());\n\t }\n\t return $newRender;\n\t },\n\t\n\t /** Fade out the old el, swap in the new contents, then fade in.\n\t * @param {Number or String} speed jq speed to use for rendering effects\n\t * @fires rendered when rendered\n\t */\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var view = this;\n\t\n\t if (speed === 0) {\n\t view._swapNewRender($newRender);\n\t view.trigger('rendered', view);\n\t } else {\n\t $(view).queue('fx', [function (next) {\n\t view.$el.fadeOut(speed, next);\n\t }, function (next) {\n\t view._swapNewRender($newRender);\n\t next();\n\t }, function (next) {\n\t view.$el.fadeIn(speed, next);\n\t }, function (next) {\n\t view.trigger('rendered', view);\n\t next();\n\t }]);\n\t }\n\t },\n\t\n\t /** empty out the current el, move the $newRender's children in */\n\t _swapNewRender: function ($newRender) {\n\t return this.$el.empty().attr('class', _.isFunction(this.className) ? this.className() : this.className).append($newRender.children());\n\t },\n\t\n\t /** set up js behaviors, event handlers for elements within the given container\n\t * @param {jQuery} $container jq object that contains the elements to process (defaults to this.$el)\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t // set up canned behavior on children (bootstrap, popupmenus, editable_text, etc.)\n\t //make_popup_menus( $where );\n\t $where.find('[title]').tooltip({ placement: 'bottom' });\n\t },\n\t\n\t // ......................................................................... details\n\t /** shortcut to details DOM (as jQ) */\n\t $details: function ($where) {\n\t $where = $where || this.$el;\n\t return $where.find('> .details');\n\t },\n\t\n\t /** build the DOM for the details and set up behaviors on it */\n\t _renderDetails: function () {\n\t var $newDetails = $(this.templates.details(this.model.toJSON(), this));\n\t this._setUpBehaviors($newDetails);\n\t return $newDetails;\n\t },\n\t\n\t // ......................................................................... expansion/details\n\t /** Show or hide the details\n\t * @param {Boolean} expand if true, expand; if false, collapse\n\t */\n\t toggleExpanded: function (expand) {\n\t expand = expand === undefined ? !this.expanded : expand;\n\t if (expand) {\n\t this.expand();\n\t } else {\n\t this.collapse();\n\t }\n\t return this;\n\t },\n\t\n\t /** Render and show the full, detailed body of this view including extra data and controls.\n\t * note: if the model does not have detailed data, fetch that data before showing the body\n\t * @fires expanded when a body has been expanded\n\t */\n\t expand: function () {\n\t var view = this;\n\t return view._fetchModelDetails().always(function () {\n\t view._expand();\n\t });\n\t },\n\t\n\t /** Check for model details and, if none, fetch them.\n\t * @returns {jQuery.promise} the model.fetch.xhr if details are being fetched, an empty promise if not\n\t */\n\t _fetchModelDetails: function () {\n\t if (!this.model.hasDetails()) {\n\t return this.model.fetch();\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Inner fn called when expand (public) has fetched the details */\n\t _expand: function () {\n\t var view = this,\n\t $newDetails = view._renderDetails();\n\t view.$details().replaceWith($newDetails);\n\t // needs to be set after the above or the slide will not show\n\t view.expanded = true;\n\t view.$details().slideDown(view.fxSpeed, function () {\n\t view.trigger('expanded', view);\n\t });\n\t },\n\t\n\t /** Hide the body/details of an HDA.\n\t * @fires collapsed when a body has been collapsed\n\t */\n\t collapse: function () {\n\t this.debug(this + '(ExpandableView).collapse');\n\t var view = this;\n\t view.expanded = false;\n\t this.$details().slideUp(view.fxSpeed, function () {\n\t view.trigger('collapsed', view);\n\t });\n\t }\n\t\n\t });\n\t\n\t //==============================================================================\n\t /** A view that is displayed in some larger list/grid/collection.\n\t * Inherits from Expandable, Selectable, Draggable.\n\t * The DOM contains warnings, a title bar, and a series of primary action controls.\n\t * Primary actions are meant to be easily accessible item functions (such as delete)\n\t * that are rendered in the title bar.\n\t *\n\t * Details are rendered when the user clicks the title bar or presses enter/space when\n\t * the title bar is in focus.\n\t *\n\t * Designed as a base class for history panel contents - but usable elsewhere (I hope).\n\t */\n\t var ListItemView = ExpandableView.extend(BASE_MVC.mixin(BASE_MVC.SelectableViewMixin, BASE_MVC.DraggableViewMixin, {\n\t\n\t tagName: 'div',\n\t className: 'list-item',\n\t\n\t /** Set up the base class and all mixins */\n\t initialize: function (attributes) {\n\t ExpandableView.prototype.initialize.call(this, attributes);\n\t BASE_MVC.SelectableViewMixin.initialize.call(this, attributes);\n\t BASE_MVC.DraggableViewMixin.initialize.call(this, attributes);\n\t this._setUpListeners();\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t // hide the primary actions in the title bar when selectable and narrow\n\t this.on('selectable', function (isSelectable) {\n\t if (isSelectable) {\n\t this.$('.primary-actions').hide();\n\t } else {\n\t this.$('.primary-actions').show();\n\t }\n\t }, this);\n\t return this;\n\t },\n\t\n\t // ........................................................................ rendering\n\t /** In this override, call methods to build warnings, titlebar and primary actions */\n\t _buildNewRender: function () {\n\t var $newRender = ExpandableView.prototype._buildNewRender.call(this);\n\t $newRender.children('.warnings').replaceWith(this._renderWarnings());\n\t $newRender.children('.title-bar').replaceWith(this._renderTitleBar());\n\t $newRender.children('.primary-actions').append(this._renderPrimaryActions());\n\t $newRender.find('> .title-bar .subtitle').replaceWith(this._renderSubtitle());\n\t return $newRender;\n\t },\n\t\n\t /** In this override, render the selector controls and set up dragging before the swap */\n\t _swapNewRender: function ($newRender) {\n\t ExpandableView.prototype._swapNewRender.call(this, $newRender);\n\t if (this.selectable) {\n\t this.showSelector(0);\n\t }\n\t if (this.draggable) {\n\t this.draggableOn();\n\t }\n\t return this.$el;\n\t },\n\t\n\t /** Render any warnings the item may need to show (e.g. \"I'm deleted\") */\n\t _renderWarnings: function () {\n\t var view = this,\n\t $warnings = $('
              '),\n\t json = view.model.toJSON();\n\t //TODO:! unordered (map)\n\t _.each(view.templates.warnings, function (templateFn) {\n\t $warnings.append($(templateFn(json, view)));\n\t });\n\t return $warnings;\n\t },\n\t\n\t /** Render the title bar (the main/exposed SUMMARY dom element) */\n\t _renderTitleBar: function () {\n\t return $(this.templates.titleBar(this.model.toJSON(), this));\n\t },\n\t\n\t /** Return an array of jQ objects containing common/easily-accessible item controls */\n\t _renderPrimaryActions: function () {\n\t // override this\n\t return [];\n\t },\n\t\n\t /** Render the title bar (the main/exposed SUMMARY dom element) */\n\t _renderSubtitle: function () {\n\t return $(this.templates.subtitle(this.model.toJSON(), this));\n\t },\n\t\n\t // ......................................................................... events\n\t /** event map */\n\t events: {\n\t // expand the body when the title is clicked or when in focus and space or enter is pressed\n\t 'click .title-bar': '_clickTitleBar',\n\t 'keydown .title-bar': '_keyDownTitleBar',\n\t 'click .selector': 'toggleSelect'\n\t },\n\t\n\t /** expand when the title bar is clicked */\n\t _clickTitleBar: function (event) {\n\t event.stopPropagation();\n\t if (event.altKey) {\n\t this.toggleSelect(event);\n\t if (!this.selectable) {\n\t this.showSelector();\n\t }\n\t } else {\n\t this.toggleExpanded();\n\t }\n\t },\n\t\n\t /** expand when the title bar is in focus and enter or space is pressed */\n\t _keyDownTitleBar: function (event) {\n\t // bail (with propagation) if keydown and not space or enter\n\t var KEYCODE_SPACE = 32,\n\t KEYCODE_RETURN = 13;\n\t if (event && event.type === 'keydown' && (event.keyCode === KEYCODE_SPACE || event.keyCode === KEYCODE_RETURN)) {\n\t this.toggleExpanded();\n\t event.stopPropagation();\n\t return false;\n\t }\n\t return true;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'ListItemView(' + modelString + ')';\n\t }\n\t }));\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ListItemView.prototype.templates = function () {\n\t\n\t var elTemplato = BASE_MVC.wrapTemplate(['
              ',\n\t // errors, messages, etc.\n\t '
              ',\n\t\n\t // multi-select checkbox\n\t '
              ', '', '
              ',\n\t // space for title bar buttons - gen. floated to the right\n\t '
              ', '
              ',\n\t\n\t // expandable area for more details\n\t '
              ', '
              ']);\n\t\n\t var warnings = {};\n\t\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding a tabindex here allows focusing the title bar and the use of keydown to expand the dataset display\n\t '
              ',\n\t //TODO: prob. belongs in dataset-list-item\n\t '', '
              ', '<%- element.name %>', '
              ', '
              ', '
              '], 'element');\n\t\n\t var subtitleTemplate = BASE_MVC.wrapTemplate([\n\t // override this\n\t '
              ']);\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate([\n\t // override this\n\t '
              ']);\n\t\n\t return {\n\t el: elTemplato,\n\t warnings: warnings,\n\t titleBar: titleBarTemplate,\n\t subtitle: subtitleTemplate,\n\t details: detailsTemplate\n\t };\n\t }();\n\t\n\t //==============================================================================\n\t /** A view that is displayed in some larger list/grid/collection.\n\t * *AND* can display some sub-list of it's own when expanded (e.g. dataset collections).\n\t * This list will 'foldout' when the item is expanded depending on this.foldoutStyle:\n\t * If 'foldout': will expand vertically to show the nested list\n\t * If 'drilldown': will overlay the parent list\n\t *\n\t * Inherits from ListItemView.\n\t *\n\t * _renderDetails does the work of creating this.details: a sub-view that shows the nested list\n\t */\n\t var FoldoutListItemView = ListItemView.extend({\n\t\n\t /** If 'foldout': show the sub-panel inside the expanded item\n\t * If 'drilldown': only fire events and handle by pub-sub\n\t * (allow the panel containing this item to attach it, hide itself, etc.)\n\t */\n\t foldoutStyle: 'foldout',\n\t /** Panel view class to instantiate for the sub-panel */\n\t foldoutPanelClass: null,\n\t\n\t /** override to:\n\t * add attributes foldoutStyle and foldoutPanelClass for config poly\n\t * disrespect attributes.expanded if drilldown\n\t */\n\t initialize: function (attributes) {\n\t if (this.foldoutStyle === 'drilldown') {\n\t this.expanded = false;\n\t }\n\t this.foldoutStyle = attributes.foldoutStyle || this.foldoutStyle;\n\t this.foldoutPanelClass = attributes.foldoutPanelClass || this.foldoutPanelClass;\n\t\n\t ListItemView.prototype.initialize.call(this, attributes);\n\t this.foldout = this._createFoldoutPanel();\n\t },\n\t\n\t /** in this override, attach the foldout panel when rendering details */\n\t _renderDetails: function () {\n\t if (this.foldoutStyle === 'drilldown') {\n\t return $();\n\t }\n\t var $newDetails = ListItemView.prototype._renderDetails.call(this);\n\t return this._attachFoldout(this.foldout, $newDetails);\n\t },\n\t\n\t /** In this override, handle collection expansion. */\n\t _createFoldoutPanel: function () {\n\t var model = this.model;\n\t var FoldoutClass = this._getFoldoutPanelClass(model),\n\t options = this._getFoldoutPanelOptions(model),\n\t foldout = new FoldoutClass(_.extend(options, {\n\t model: model\n\t }));\n\t return foldout;\n\t },\n\t\n\t /** Stub to return proper foldout panel class */\n\t _getFoldoutPanelClass: function () {\n\t // override\n\t return this.foldoutPanelClass;\n\t },\n\t\n\t /** Stub to return proper foldout panel options */\n\t _getFoldoutPanelOptions: function () {\n\t return {\n\t // propagate foldout style down\n\t foldoutStyle: this.foldoutStyle,\n\t fxSpeed: this.fxSpeed\n\t };\n\t },\n\t\n\t /** Render the foldout panel inside the view, hiding controls */\n\t _attachFoldout: function (foldout, $whereTo) {\n\t $whereTo = $whereTo || this.$('> .details');\n\t this.foldout = foldout.render(0);\n\t foldout.$('> .controls').hide();\n\t return $whereTo.append(foldout.$el);\n\t },\n\t\n\t /** In this override, branch on foldoutStyle to show expanded */\n\t expand: function () {\n\t var view = this;\n\t return view._fetchModelDetails().always(function () {\n\t if (view.foldoutStyle === 'foldout') {\n\t view._expand();\n\t } else if (view.foldoutStyle === 'drilldown') {\n\t view._expandByDrilldown();\n\t }\n\t });\n\t },\n\t\n\t /** For drilldown, set up close handler and fire expanded:drilldown\n\t * containing views can listen to this and handle other things\n\t * (like hiding themselves) by listening for expanded/collapsed:drilldown\n\t */\n\t _expandByDrilldown: function () {\n\t var view = this;\n\t // attachment and rendering done by listener\n\t view.listenTo(view.foldout, 'close', function () {\n\t view.trigger('collapsed:drilldown', view, view.foldout);\n\t });\n\t view.trigger('expanded:drilldown', view, view.foldout);\n\t }\n\t\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t FoldoutListItemView.prototype.templates = function () {\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate(['
              ',\n\t // override with more info (that goes above the panel)\n\t '
              '], 'collection');\n\t\n\t return _.extend({}, ListItemView.prototype.templates, {\n\t details: detailsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t ExpandableView: ExpandableView,\n\t ListItemView: ListItemView,\n\t FoldoutListItemView: FoldoutListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 65 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (baseMVC, _l) {\n\t // =============================================================================\n\t /** A view on any model that has a 'tags' attribute (a list of tag strings)\n\t * Incorporates the select2 jQuery plugin for tags display/editing:\n\t * http://ivaynberg.github.io/select2/\n\t */\n\t var TagsEditor = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseMVC.HiddenUntilActivatedViewMixin).extend({\n\t\n\t tagName: 'div',\n\t className: 'tags-display',\n\t\n\t /** Set up listeners, parse options */\n\t initialize: function (options) {\n\t //console.debug( this, options );\n\t // only listen to the model only for changes to tags - re-render\n\t if (options.usePrompt === false) {\n\t this.label = '';\n\t } else {\n\t this.label = '';\n\t }\n\t this.hiddenUntilActivated(options.$activator, options);\n\t },\n\t\n\t /** Build the DOM elements, call select to on the created input, and set up behaviors */\n\t render: function () {\n\t var self = this;\n\t this.$el.html(this._template());\n\t\n\t this.$input().select2({\n\t placeholder: 'Add tags',\n\t width: '100%',\n\t tags: function () {\n\t // initialize possible tags in the dropdown based on all the tags the user has used so far\n\t return self._getTagsUsed();\n\t }\n\t });\n\t\n\t this._setUpBehaviors();\n\t return this;\n\t },\n\t\n\t _hashToName: function (tag) {\n\t if (tag.startsWith('#')) {\n\t return 'name:' + tag.slice(1);\n\t }\n\t return tag;\n\t },\n\t\n\t _nameToHash: function (tag) {\n\t if (tag.startsWith('name:')) {\n\t tag = '#' + tag.slice(5);\n\t }\n\t return tag;\n\t },\n\t\n\t /** @returns {String} the html text used to build the view's DOM */\n\t _template: function () {\n\t return [this.label,\n\t // set up initial tags by adding as CSV to input vals (necc. to init select2)\n\t ''].join('');\n\t },\n\t\n\t /** @returns {String} the sorted, comma-separated tags from the model */\n\t tagsToCSV: function () {\n\t var self = this;\n\t var tagsArray = this.model.get('tags');\n\t if (!_.isArray(tagsArray) || _.isEmpty(tagsArray)) {\n\t return '';\n\t }\n\t return tagsArray.map(function (tag) {\n\t return _.escape(self._nameToHash(tag));\n\t }).sort().join(',');\n\t },\n\t\n\t /** @returns {jQuery} the input for this view */\n\t $input: function () {\n\t return this.$el.find('input.tags-input');\n\t },\n\t\n\t /** @returns {String[]} all tags used by the current user */\n\t _getTagsUsed: function () {\n\t //TODO: global\n\t var self = this;\n\t return _.map(Galaxy.user.get('tags_used'), self._nameToHash);\n\t },\n\t\n\t /** set up any event listeners on the view's DOM (mostly handled by select2) */\n\t _setUpBehaviors: function () {\n\t var self = this;\n\t this.$input().on('change', function (event) {\n\t // Modify any 'hashtag' 'nametags'\n\t event.val = _.map(event.val, self._hashToName);\n\t // save the model's tags in either remove or added event\n\t self.model.save({ tags: event.val });\n\t // if it's new, add the tag to the users tags\n\t if (event.added) {\n\t //??: solve weird behavior in FF on test.galaxyproject.org where\n\t // event.added.text is string object: 'String{ 0=\"o\", 1=\"n\", 2=\"e\" }'\n\t self._addNewTagToTagsUsed(event.added.text + '');\n\t }\n\t });\n\t },\n\t\n\t /** add a new tag (if not already there) to the list of all tags used by the user\n\t * @param {String} newTag the tag to add to the list of used\n\t */\n\t _addNewTagToTagsUsed: function (newTag) {\n\t //TODO: global\n\t var tagsUsed = Galaxy.user.get('tags_used');\n\t if (!_.contains(tagsUsed, newTag)) {\n\t tagsUsed.push(newTag);\n\t tagsUsed.sort();\n\t Galaxy.user.set('tags_used', tagsUsed);\n\t }\n\t },\n\t\n\t /** shut down event listeners and remove this view's DOM */\n\t remove: function () {\n\t this.$input.off();\n\t this.stopListening(this.model);\n\t Backbone.View.prototype.remove.call(this);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return ['TagsEditor(', this.model + '', ')'].join('');\n\t }\n\t });\n\t\n\t // =============================================================================\n\t return {\n\t TagsEditor: TagsEditor\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 66 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {/**\n\t * Model, view, and controller objects for Galaxy tools and tool panel.\n\t */\n\t\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(27), __webpack_require__(16), __webpack_require__(44)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, util, data, ToolForm) {\n\t 'use strict';\n\t\n\t /**\n\t * Mixin for tracking model visibility.\n\t */\n\t\n\t var VisibilityMixin = {\n\t hidden: false,\n\t\n\t show: function () {\n\t this.set(\"hidden\", false);\n\t },\n\t\n\t hide: function () {\n\t this.set(\"hidden\", true);\n\t },\n\t\n\t toggle: function () {\n\t this.set(\"hidden\", !this.get(\"hidden\"));\n\t },\n\t\n\t is_visible: function () {\n\t return !this.attributes.hidden;\n\t }\n\t\n\t };\n\t\n\t /**\n\t * A tool parameter.\n\t */\n\t var ToolParameter = Backbone.Model.extend({\n\t defaults: {\n\t name: null,\n\t label: null,\n\t type: null,\n\t value: null,\n\t html: null,\n\t num_samples: 5\n\t },\n\t\n\t initialize: function (options) {\n\t this.attributes.html = unescape(this.attributes.html);\n\t },\n\t\n\t copy: function () {\n\t return new ToolParameter(this.toJSON());\n\t },\n\t\n\t set_value: function (value) {\n\t this.set('value', value || '');\n\t }\n\t });\n\t\n\t var ToolParameterCollection = Backbone.Collection.extend({\n\t model: ToolParameter\n\t });\n\t\n\t /**\n\t * A data tool parameter.\n\t */\n\t var DataToolParameter = ToolParameter.extend({});\n\t\n\t /**\n\t * An integer tool parameter.\n\t */\n\t var IntegerToolParameter = ToolParameter.extend({\n\t set_value: function (value) {\n\t this.set('value', parseInt(value, 10));\n\t },\n\t\n\t /**\n\t * Returns samples from a tool input.\n\t */\n\t get_samples: function () {\n\t return d3.scale.linear().domain([this.get('min'), this.get('max')]).ticks(this.get('num_samples'));\n\t }\n\t });\n\t\n\t var FloatToolParameter = IntegerToolParameter.extend({\n\t set_value: function (value) {\n\t this.set('value', parseFloat(value));\n\t }\n\t });\n\t\n\t /**\n\t * A select tool parameter.\n\t */\n\t var SelectToolParameter = ToolParameter.extend({\n\t /**\n\t * Returns tool options.\n\t */\n\t get_samples: function () {\n\t return _.map(this.get('options'), function (option) {\n\t return option[0];\n\t });\n\t }\n\t });\n\t\n\t // Set up dictionary of parameter types.\n\t ToolParameter.subModelTypes = {\n\t 'integer': IntegerToolParameter,\n\t 'float': FloatToolParameter,\n\t 'data': DataToolParameter,\n\t 'select': SelectToolParameter\n\t };\n\t\n\t /**\n\t * A Galaxy tool.\n\t */\n\t var Tool = Backbone.Model.extend({\n\t // Default attributes.\n\t defaults: {\n\t id: null,\n\t name: null,\n\t description: null,\n\t target: null,\n\t inputs: [],\n\t outputs: []\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/tools',\n\t\n\t initialize: function (options) {\n\t\n\t // Set parameters.\n\t this.set('inputs', new ToolParameterCollection(_.map(options.inputs, function (p) {\n\t var p_class = ToolParameter.subModelTypes[p.type] || ToolParameter;\n\t return new p_class(p);\n\t })));\n\t },\n\t\n\t /**\n\t *\n\t */\n\t toJSON: function () {\n\t var rval = Backbone.Model.prototype.toJSON.call(this);\n\t\n\t // Convert inputs to JSON manually.\n\t rval.inputs = this.get('inputs').map(function (i) {\n\t return i.toJSON();\n\t });\n\t return rval;\n\t },\n\t\n\t /**\n\t * Removes inputs of a particular type; this is useful because not all inputs can be handled by\n\t * client and server yet.\n\t */\n\t remove_inputs: function (types) {\n\t var tool = this,\n\t incompatible_inputs = tool.get('inputs').filter(function (input) {\n\t return types.indexOf(input.get('type')) !== -1;\n\t });\n\t tool.get('inputs').remove(incompatible_inputs);\n\t },\n\t\n\t /**\n\t * Returns object copy, optionally including only inputs that can be sampled.\n\t */\n\t copy: function (only_samplable_inputs) {\n\t var copy = new Tool(this.toJSON());\n\t\n\t // Return only samplable inputs if flag is set.\n\t if (only_samplable_inputs) {\n\t var valid_inputs = new Backbone.Collection();\n\t copy.get('inputs').each(function (input) {\n\t if (input.get_samples()) {\n\t valid_inputs.push(input);\n\t }\n\t });\n\t copy.set('inputs', valid_inputs);\n\t }\n\t\n\t return copy;\n\t },\n\t\n\t apply_search_results: function (results) {\n\t _.indexOf(results, this.attributes.id) !== -1 ? this.show() : this.hide();\n\t return this.is_visible();\n\t },\n\t\n\t /**\n\t * Set a tool input's value.\n\t */\n\t set_input_value: function (name, value) {\n\t this.get('inputs').find(function (input) {\n\t return input.get('name') === name;\n\t }).set('value', value);\n\t },\n\t\n\t /**\n\t * Set many input values at once.\n\t */\n\t set_input_values: function (inputs_dict) {\n\t var self = this;\n\t _.each(_.keys(inputs_dict), function (input_name) {\n\t self.set_input_value(input_name, inputs_dict[input_name]);\n\t });\n\t },\n\t\n\t /**\n\t * Run tool; returns a Deferred that resolves to the tool's output(s).\n\t */\n\t run: function () {\n\t return this._run();\n\t },\n\t\n\t /**\n\t * Rerun tool using regions and a target dataset.\n\t */\n\t rerun: function (target_dataset, regions) {\n\t return this._run({\n\t action: 'rerun',\n\t target_dataset_id: target_dataset.id,\n\t regions: regions\n\t });\n\t },\n\t\n\t /**\n\t * Returns input dict for tool's inputs.\n\t */\n\t get_inputs_dict: function () {\n\t var input_dict = {};\n\t this.get('inputs').each(function (input) {\n\t input_dict[input.get('name')] = input.get('value');\n\t });\n\t return input_dict;\n\t },\n\t\n\t /**\n\t * Run tool; returns a Deferred that resolves to the tool's output(s).\n\t * NOTE: this method is a helper method and should not be called directly.\n\t */\n\t _run: function (additional_params) {\n\t // Create payload.\n\t var payload = _.extend({\n\t tool_id: this.id,\n\t inputs: this.get_inputs_dict()\n\t }, additional_params);\n\t\n\t // Because job may require indexing datasets, use server-side\n\t // deferred to ensure that job is run. Also use deferred that\n\t // resolves to outputs from tool.\n\t var run_deferred = $.Deferred(),\n\t ss_deferred = new util.ServerStateDeferred({\n\t ajax_settings: {\n\t url: this.urlRoot,\n\t data: JSON.stringify(payload),\n\t dataType: \"json\",\n\t contentType: 'application/json',\n\t type: \"POST\"\n\t },\n\t interval: 2000,\n\t success_fn: function (response) {\n\t return response !== \"pending\";\n\t }\n\t });\n\t\n\t // Run job and resolve run_deferred to tool outputs.\n\t $.when(ss_deferred.go()).then(function (result) {\n\t run_deferred.resolve(new data.DatasetCollection(result));\n\t });\n\t return run_deferred;\n\t }\n\t });\n\t _.extend(Tool.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool view.\n\t */\n\t var ToolView = Backbone.View.extend({});\n\t\n\t /**\n\t * Wrap collection of tools for fast access/manipulation.\n\t */\n\t var ToolCollection = Backbone.Collection.extend({\n\t model: Tool\n\t });\n\t\n\t /**\n\t * Label or section header in tool panel.\n\t */\n\t var ToolSectionLabel = Backbone.Model.extend(VisibilityMixin);\n\t\n\t /**\n\t * Section of tool panel with elements (labels and tools).\n\t */\n\t var ToolSection = Backbone.Model.extend({\n\t defaults: {\n\t elems: [],\n\t open: false\n\t },\n\t\n\t clear_search_results: function () {\n\t _.each(this.attributes.elems, function (elt) {\n\t elt.show();\n\t });\n\t\n\t this.show();\n\t this.set(\"open\", false);\n\t },\n\t\n\t apply_search_results: function (results) {\n\t var all_hidden = true,\n\t cur_label;\n\t _.each(this.attributes.elems, function (elt) {\n\t if (elt instanceof ToolSectionLabel) {\n\t cur_label = elt;\n\t cur_label.hide();\n\t } else if (elt instanceof Tool) {\n\t if (elt.apply_search_results(results)) {\n\t all_hidden = false;\n\t if (cur_label) {\n\t cur_label.show();\n\t }\n\t }\n\t }\n\t });\n\t\n\t if (all_hidden) {\n\t this.hide();\n\t } else {\n\t this.show();\n\t this.set(\"open\", true);\n\t }\n\t }\n\t });\n\t _.extend(ToolSection.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool search that updates results when query is changed. Result value of null\n\t * indicates that query was not run; if not null, results are from search using\n\t * query.\n\t */\n\t var ToolSearch = Backbone.Model.extend({\n\t defaults: {\n\t search_hint_string: \"search tools\",\n\t min_chars_for_search: 3,\n\t clear_btn_url: \"\",\n\t visible: true,\n\t query: \"\",\n\t results: null,\n\t // ESC (27) will clear the input field and tool search filters\n\t clear_key: 27\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/tools',\n\t\n\t initialize: function () {\n\t this.on(\"change:query\", this.do_search);\n\t },\n\t\n\t /**\n\t * Do the search and update the results.\n\t */\n\t do_search: function () {\n\t var query = this.attributes.query;\n\t\n\t // If query is too short, do not search.\n\t if (query.length < this.attributes.min_chars_for_search) {\n\t this.set(\"results\", null);\n\t return;\n\t }\n\t\n\t // Do search via AJAX.\n\t var q = query;\n\t // Stop previous ajax-request\n\t if (this.timer) {\n\t clearTimeout(this.timer);\n\t }\n\t // Start a new ajax-request in X ms\n\t $(\"#search-clear-btn\").hide();\n\t $(\"#search-spinner\").show();\n\t var self = this;\n\t this.timer = setTimeout(function () {\n\t // log the search to analytics if present\n\t if (typeof ga !== 'undefined') {\n\t ga('send', 'pageview', Galaxy.root + '?q=' + q);\n\t }\n\t $.get(self.urlRoot, { q: q }, function (data) {\n\t self.set(\"results\", data);\n\t $(\"#search-spinner\").hide();\n\t $(\"#search-clear-btn\").show();\n\t }, \"json\");\n\t }, 400);\n\t },\n\t\n\t clear_search: function () {\n\t this.set(\"query\", \"\");\n\t this.set(\"results\", null);\n\t }\n\t\n\t });\n\t _.extend(ToolSearch.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool Panel.\n\t */\n\t var ToolPanel = Backbone.Model.extend({\n\t\n\t initialize: function (options) {\n\t this.attributes.tool_search = options.tool_search;\n\t this.attributes.tool_search.on(\"change:results\", this.apply_search_results, this);\n\t this.attributes.tools = options.tools;\n\t this.attributes.layout = new Backbone.Collection(this.parse(options.layout));\n\t },\n\t\n\t /**\n\t * Parse tool panel dictionary and return collection of tool panel elements.\n\t */\n\t parse: function (response) {\n\t // Recursive function to parse tool panel elements.\n\t var self = this,\n\t\n\t // Helper to recursively parse tool panel.\n\t parse_elt = function (elt_dict) {\n\t var type = elt_dict.model_class;\n\t // There are many types of tools; for now, anything that ends in 'Tool'\n\t // is treated as a generic tool.\n\t if (type.indexOf('Tool') === type.length - 4) {\n\t return self.attributes.tools.get(elt_dict.id);\n\t } else if (type === 'ToolSection') {\n\t // Parse elements.\n\t var elems = _.map(elt_dict.elems, parse_elt);\n\t elt_dict.elems = elems;\n\t return new ToolSection(elt_dict);\n\t } else if (type === 'ToolSectionLabel') {\n\t return new ToolSectionLabel(elt_dict);\n\t }\n\t };\n\t\n\t return _.map(response, parse_elt);\n\t },\n\t\n\t clear_search_results: function () {\n\t this.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSection) {\n\t panel_elt.clear_search_results();\n\t } else {\n\t // Label or tool, so just show.\n\t panel_elt.show();\n\t }\n\t });\n\t },\n\t\n\t apply_search_results: function () {\n\t var results = this.get('tool_search').get('results');\n\t if (results === null) {\n\t this.clear_search_results();\n\t return;\n\t }\n\t\n\t var cur_label = null;\n\t this.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSectionLabel) {\n\t cur_label = panel_elt;\n\t cur_label.hide();\n\t } else if (panel_elt instanceof Tool) {\n\t if (panel_elt.apply_search_results(results)) {\n\t if (cur_label) {\n\t cur_label.show();\n\t }\n\t }\n\t } else {\n\t // Starting new section, so clear current label.\n\t cur_label = null;\n\t panel_elt.apply_search_results(results);\n\t }\n\t });\n\t }\n\t });\n\t\n\t /**\n\t * View classes for Galaxy tools and tool panel.\n\t *\n\t * Views use the templates defined below for rendering. Views update as needed\n\t * based on (a) model/collection events and (b) user interactions; in this sense,\n\t * they are controllers are well and the HTML is the real view in the MVC architecture.\n\t */\n\t\n\t /**\n\t * Base view that handles visibility based on model's hidden attribute.\n\t */\n\t var BaseView = Backbone.View.extend({\n\t initialize: function () {\n\t this.model.on(\"change:hidden\", this.update_visible, this);\n\t this.update_visible();\n\t },\n\t update_visible: function () {\n\t this.model.attributes.hidden ? this.$el.hide() : this.$el.show();\n\t }\n\t });\n\t\n\t /**\n\t * Link to a tool.\n\t */\n\t var ToolLinkView = BaseView.extend({\n\t tagName: 'div',\n\t\n\t render: function () {\n\t // create element\n\t var $link = $('
              ');\n\t $link.append(templates.tool_link(this.model.toJSON()));\n\t\n\t var formStyle = this.model.get('form_style', null);\n\t // open upload dialog for upload tool\n\t if (this.model.id === 'upload1') {\n\t $link.find('a').on('click', function (e) {\n\t e.preventDefault();\n\t Galaxy.upload.show();\n\t });\n\t } else if (formStyle === 'regular') {\n\t // regular tools\n\t var self = this;\n\t $link.find('a').on('click', function (e) {\n\t e.preventDefault();\n\t Galaxy.router.push('/', { tool_id: self.model.id, version: self.model.get('version') });\n\t });\n\t }\n\t\n\t // add element\n\t this.$el.append($link);\n\t return this;\n\t }\n\t });\n\t\n\t /**\n\t * Panel label/section header.\n\t */\n\t var ToolSectionLabelView = BaseView.extend({\n\t tagName: 'div',\n\t className: 'toolPanelLabel',\n\t\n\t render: function () {\n\t this.$el.append($(\"\").text(this.model.attributes.text));\n\t return this;\n\t }\n\t });\n\t\n\t /**\n\t * Panel section.\n\t */\n\t var ToolSectionView = BaseView.extend({\n\t tagName: 'div',\n\t className: 'toolSectionWrapper',\n\t\n\t initialize: function () {\n\t BaseView.prototype.initialize.call(this);\n\t this.model.on(\"change:open\", this.update_open, this);\n\t },\n\t\n\t render: function () {\n\t // Build using template.\n\t this.$el.append(templates.panel_section(this.model.toJSON()));\n\t\n\t // Add tools to section.\n\t var section_body = this.$el.find(\".toolSectionBody\");\n\t _.each(this.model.attributes.elems, function (elt) {\n\t if (elt instanceof Tool) {\n\t var tool_view = new ToolLinkView({ model: elt, className: \"toolTitle\" });\n\t tool_view.render();\n\t section_body.append(tool_view.$el);\n\t } else if (elt instanceof ToolSectionLabel) {\n\t var label_view = new ToolSectionLabelView({ model: elt });\n\t label_view.render();\n\t section_body.append(label_view.$el);\n\t } else {\n\t // TODO: handle nested section bodies?\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t events: {\n\t 'click .toolSectionTitle > a': 'toggle'\n\t },\n\t\n\t /**\n\t * Toggle visibility of tool section.\n\t */\n\t toggle: function () {\n\t this.model.set(\"open\", !this.model.attributes.open);\n\t },\n\t\n\t /**\n\t * Update whether section is open or close.\n\t */\n\t update_open: function () {\n\t this.model.attributes.open ? this.$el.children(\".toolSectionBody\").slideDown(\"fast\") : this.$el.children(\".toolSectionBody\").slideUp(\"fast\");\n\t }\n\t });\n\t\n\t var ToolSearchView = Backbone.View.extend({\n\t tagName: 'div',\n\t id: 'tool-search',\n\t className: 'bar',\n\t\n\t events: {\n\t 'click': 'focus_and_select',\n\t 'keyup :input': 'query_changed',\n\t 'change :input': 'query_changed',\n\t 'click #search-clear-btn': 'clear'\n\t },\n\t\n\t render: function () {\n\t this.$el.append(templates.tool_search(this.model.toJSON()));\n\t if (!this.model.is_visible()) {\n\t this.$el.hide();\n\t }\n\t\n\t // Adjust top for issue 2907 depending on whether the messagebox is visible.\n\t if ($(\"#messagebox\").is(\":visible\")) {\n\t this.$el.css(\"top\", \"95px\");\n\t }\n\t\n\t this.$el.find('[title]').tooltip();\n\t return this;\n\t },\n\t\n\t focus_and_select: function () {\n\t this.$el.find(\":input\").focus().select();\n\t },\n\t\n\t clear: function () {\n\t this.model.clear_search();\n\t this.$el.find(\":input\").val('');\n\t this.focus_and_select();\n\t return false;\n\t },\n\t\n\t query_changed: function (evData) {\n\t // check for the 'clear key' (ESC) first\n\t if (this.model.attributes.clear_key && this.model.attributes.clear_key === evData.which) {\n\t this.clear();\n\t return false;\n\t }\n\t this.model.set(\"query\", this.$el.find(\":input\").val());\n\t }\n\t });\n\t\n\t /**\n\t * Tool panel view. Events triggered include:\n\t * tool_link_click(click event, tool_model)\n\t */\n\t var ToolPanelView = Backbone.View.extend({\n\t tagName: 'div',\n\t className: 'toolMenu',\n\t\n\t /**\n\t * Set up view.\n\t */\n\t initialize: function () {\n\t this.model.get('tool_search').on(\"change:results\", this.handle_search_results, this);\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t\n\t // Render search.\n\t var search_view = new ToolSearchView({ model: this.model.get('tool_search') });\n\t search_view.render();\n\t self.$el.append(search_view.$el);\n\t\n\t // Render panel.\n\t this.model.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSection) {\n\t var section_title_view = new ToolSectionView({ model: panel_elt });\n\t section_title_view.render();\n\t self.$el.append(section_title_view.$el);\n\t } else if (panel_elt instanceof Tool) {\n\t var tool_view = new ToolLinkView({ model: panel_elt, className: \"toolTitleNoSection\" });\n\t tool_view.render();\n\t self.$el.append(tool_view.$el);\n\t } else if (panel_elt instanceof ToolSectionLabel) {\n\t var label_view = new ToolSectionLabelView({ model: panel_elt });\n\t label_view.render();\n\t self.$el.append(label_view.$el);\n\t }\n\t });\n\t\n\t // Setup tool link click eventing.\n\t self.$el.find(\"a.tool-link\").click(function (e) {\n\t // Tool id is always the first class.\n\t var tool_id = $(this).attr('class').split(/\\s+/)[0],\n\t tool = self.model.get('tools').get(tool_id);\n\t\n\t self.trigger(\"tool_link_click\", e, tool);\n\t });\n\t\n\t return this;\n\t },\n\t\n\t handle_search_results: function () {\n\t var results = this.model.get('tool_search').get('results');\n\t if (results && results.length === 0) {\n\t $(\"#search-no-results\").show();\n\t } else {\n\t $(\"#search-no-results\").hide();\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * View for working with a tool: setting parameters and inputs and executing the tool.\n\t */\n\t var ToolFormView = Backbone.View.extend({\n\t className: 'toolForm',\n\t\n\t render: function () {\n\t this.$el.children().remove();\n\t this.$el.append(templates.tool_form(this.model.toJSON()));\n\t }\n\t });\n\t\n\t /**\n\t * Integrated tool menu + tool execution.\n\t */\n\t var IntegratedToolMenuAndView = Backbone.View.extend({\n\t className: 'toolMenuAndView',\n\t\n\t initialize: function () {\n\t this.tool_panel_view = new ToolPanelView({ collection: this.collection });\n\t this.tool_form_view = new ToolFormView();\n\t },\n\t\n\t render: function () {\n\t // Render and append tool panel.\n\t this.tool_panel_view.render();\n\t this.tool_panel_view.$el.css(\"float\", \"left\");\n\t this.$el.append(this.tool_panel_view.$el);\n\t\n\t // Append tool form view.\n\t this.tool_form_view.$el.hide();\n\t this.$el.append(this.tool_form_view.$el);\n\t\n\t // On tool link click, show tool.\n\t var self = this;\n\t this.tool_panel_view.on(\"tool_link_click\", function (e, tool) {\n\t // Prevents click from activating link:\n\t e.preventDefault();\n\t // Show tool that was clicked on:\n\t self.show_tool(tool);\n\t });\n\t },\n\t\n\t /**\n\t * Fetch and display tool.\n\t */\n\t show_tool: function (tool) {\n\t var self = this;\n\t tool.fetch().done(function () {\n\t self.tool_form_view.model = tool;\n\t self.tool_form_view.render();\n\t self.tool_form_view.$el.show();\n\t $('#left').width(\"650px\");\n\t });\n\t }\n\t });\n\t\n\t // TODO: move into relevant views\n\t var templates = {\n\t // the search bar at the top of the tool panel\n\t tool_search: _.template(['\" autocomplete=\"off\" type=\"text\" />', ' ',\n\t //TODO: replace with icon\n\t ''].join('')),\n\t\n\t // the category level container in the tool panel (e.g. 'Get Data', 'Text Manipulation')\n\t panel_section: _.template(['
              \">', '<%- name %>', '
              ', '
              \" class=\"toolSectionBody\" style=\"display: none;\">', '
              ', '
              '].join('')),\n\t\n\t // a single tool's link in the tool panel; will load the tool form in the center panel\n\t tool_link: _.template(['', '<% _.each( labels, function( label ){ %>', '\">', '<%- label %>', '', '<% }); %>', '', ' tool-link\" href=\"<%= link %>\" target=\"<%- target %>\" minsizehint=\"<%- min_width %>\">', '<%- name %>', '', ' <%- description %>'].join('')),\n\t\n\t // the tool form for entering tool parameters, viewing help and executing the tool\n\t // loaded when a tool link is clicked in the tool panel\n\t tool_form: _.template(['
              <%- tool.name %> (version <%- tool.version %>)
              ', '
              ', '<% _.each( tool.inputs, function( input ){ %>', '
              ', '', '
              ', '<%= input.html %>', '
              ', '
              ', '<%- input.help %>', '
              ', '
              ', '
              ', '<% }); %>', '
              ', '
              ', '', '
              ', '
              ', '
              <% tool.help %>
              ', '
              '].join(''), { variable: 'tool' })\n\t };\n\t\n\t // Exports\n\t return {\n\t ToolParameter: ToolParameter,\n\t IntegerToolParameter: IntegerToolParameter,\n\t SelectToolParameter: SelectToolParameter,\n\t Tool: Tool,\n\t ToolCollection: ToolCollection,\n\t ToolSearch: ToolSearch,\n\t ToolPanel: ToolPanel,\n\t ToolPanelView: ToolPanelView,\n\t ToolFormView: ToolFormView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 67 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This renders the content of the ftp popup **/\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils) {\n\t return Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.options = Utils.merge(options, {\n\t class_add: 'upload-icon-button fa fa-square-o',\n\t class_remove: 'upload-icon-button fa fa-check-square-o',\n\t class_partial: 'upload-icon-button fa fa-minus-square-o',\n\t collection: null,\n\t onchange: function () {},\n\t onadd: function () {},\n\t onremove: function () {}\n\t });\n\t this.collection = this.options.collection;\n\t this.setElement(this._template());\n\t this.rows = [];\n\t Utils.get({\n\t url: Galaxy.root + 'api/remote_files',\n\t success: function (ftp_files) {\n\t self._fill(ftp_files);\n\t },\n\t error: function () {\n\t self._fill();\n\t }\n\t });\n\t },\n\t\n\t /** Fill table with ftp entries */\n\t _fill: function (ftp_files) {\n\t if (ftp_files && ftp_files.length > 0) {\n\t this.$('.upload-ftp-content').html($(this._templateTable()));\n\t var size = 0;\n\t for (index in ftp_files) {\n\t this.rows.push(this._add(ftp_files[index]));\n\t size += ftp_files[index].size;\n\t }\n\t this.$('.upload-ftp-number').html(ftp_files.length + ' files');\n\t this.$('.upload-ftp-disk').html(Utils.bytesToString(size, true));\n\t if (this.collection) {\n\t var self = this;\n\t this.$('._has_collection').show();\n\t this.$select_all = this.$('.upload-selectall').addClass(this.options.class_add);\n\t this.$select_all.on('click', function () {\n\t var add = self.$select_all.hasClass(self.options.class_add);\n\t for (index in ftp_files) {\n\t var ftp_file = ftp_files[index];\n\t var model_index = self._find(ftp_file);\n\t if (!model_index && add || model_index && !add) {\n\t self.rows[index].trigger('click');\n\t }\n\t }\n\t });\n\t this._refresh();\n\t }\n\t } else {\n\t this.$('.upload-ftp-content').html($(this._templateInfo()));\n\t }\n\t this.$('.upload-ftp-wait').hide();\n\t },\n\t\n\t /** Add file to table */\n\t _add: function (ftp_file) {\n\t var self = this;\n\t var $it = $(this._templateRow(ftp_file));\n\t var $icon = $it.find('.icon');\n\t this.$('tbody').append($it);\n\t if (this.collection) {\n\t $icon.addClass(this._find(ftp_file) ? this.options.class_remove : this.options.class_add);\n\t $it.on('click', function () {\n\t var model_index = self._find(ftp_file);\n\t $icon.removeClass();\n\t if (!model_index) {\n\t self.options.onadd(ftp_file);\n\t $icon.addClass(self.options.class_remove);\n\t } else {\n\t self.options.onremove(model_index);\n\t $icon.addClass(self.options.class_add);\n\t }\n\t self._refresh();\n\t });\n\t } else {\n\t $it.on('click', function () {\n\t self.options.onchange(ftp_file);\n\t });\n\t }\n\t return $it;\n\t },\n\t\n\t /** Refresh select all button state */\n\t _refresh: function () {\n\t var filtered = this.collection.where({ file_mode: 'ftp', enabled: true });\n\t this.$select_all.removeClass();\n\t if (filtered.length == 0) {\n\t this.$select_all.addClass(this.options.class_add);\n\t } else {\n\t this.$select_all.addClass(filtered.length == this.rows.length ? this.options.class_remove : this.options.class_partial);\n\t }\n\t },\n\t\n\t /** Get model index */\n\t _find: function (ftp_file) {\n\t var item = this.collection.findWhere({\n\t file_path: ftp_file.path,\n\t file_mode: 'ftp',\n\t enabled: true\n\t });\n\t return item && item.get('id');\n\t },\n\t\n\t /** Template of row */\n\t _templateRow: function (options) {\n\t return '
              ' + _.escape(options.path) + '' + Utils.bytesToString(options.size) + '' + options.ctime + '
              ' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
              NameSizeCreated
              ';\n\t },\n\t\n\t /** Template of info message */\n\t _templateInfo: function () {\n\t return '
              ' + 'Your FTP directory does not contain any files.' + '
              ';\n\t },\n\t\n\t /** Template of main view */\n\t _template: function () {\n\t return '
              ' + '
              ' + '
              This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at ' + this.options.ftp_upload_site + ' using your Galaxy credentials (email address and password).
              ' + '
              ' + '
              ';\n\t }\n\t });\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 68 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This renders the content of the settings popup, allowing users to specify flags i.e. for space-to-tab conversion **/\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils) {\n\t return Backbone.View.extend({\n\t options: {\n\t class_check: 'fa-check-square-o',\n\t class_uncheck: 'fa-square-o',\n\t parameters: [{\n\t id: 'space_to_tab',\n\t title: 'Convert spaces to tabs'\n\t }, {\n\t id: 'to_posix_lines',\n\t title: 'Use POSIX standard'\n\t }]\n\t },\n\t\n\t initialize: function (options) {\n\t var self = this;\n\t this.model = options.model;\n\t this.setElement($('
              ').addClass('upload-settings'));\n\t this.$el.append($('
              ').addClass('upload-settings-cover'));\n\t this.$el.append($('').addClass('upload-settings-table ui-table-striped').append(''));\n\t this.$cover = this.$('.upload-settings-cover');\n\t this.$table = this.$('.upload-settings-table > tbody');\n\t this.listenTo(this.model, 'change', this.render, this);\n\t this.model.trigger('change');\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t this.$table.empty();\n\t _.each(this.options.parameters, function (parameter) {\n\t var $checkbox = $('
              ').addClass('upload-' + parameter.id + ' upload-icon-button fa').addClass(self.model.get(parameter.id) && self.options.class_check || self.options.class_uncheck).on('click', function () {\n\t self.model.get('enabled') && self.model.set(parameter.id, !self.model.get(parameter.id));\n\t });\n\t self.$table.append($('
              ').append($('' + '' + '' + '');\n\t });\n\t $tmpl.append($table);\n\t } else {\n\t $tmpl.append('No ' + this.model.get('plural').toLowerCase() + ' have been shared with you.');\n\t }\n\t return $tmpl;\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 125 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(82), __webpack_require__(85), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_LI_EDIT, HDA_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI_EDIT.DatasetListItemEdit;\n\t /** @class Editing view for HistoryDatasetAssociation.\n\t */\n\t var HDAListItemEdit = _super.extend(\n\t /** @lends HDAListItemEdit.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t /** In this override, only get details if in the ready state, get rerunnable if in other states.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t\n\t // special case the need for the rerunnable and creating_job attributes\n\t // needed for rendering re-run button on queued, running datasets\n\t } else if (!view.model.has('rerunnable')) {\n\t return view.model.fetch({ silent: true, data: {\n\t // only fetch rerunnable and creating_job to keep overhead down\n\t keys: ['rerunnable', 'creating_job'].join(',')\n\t } });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .unhide-link': function (ev) {\n\t this.model.unhide();return false;\n\t }\n\t }),\n\t\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t HDAListItemEdit.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate(['<% if( !dataset.visible ){ %>',\n\t // add a link to unhide a dataset\n\t '
              ', _l('This dataset has been hidden'), '
              ', _l('Unhide it'), '', '
              ', '<% } %>'], 'dataset')\n\t });\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t //NOTE: *steal* the HDAListItemView titleBar\n\t titleBar: HDA_LI.HDAListItemView.prototype.templates.titleBar,\n\t warnings: warnings\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDAListItemEdit: HDAListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 126 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(87), __webpack_require__(120), __webpack_require__(25), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HDCA_LI, DC_VIEW_EDIT, faIconButton, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = HDCA_LI.HDCAListItemView;\n\t /** @class Editing view for HistoryDatasetCollectionAssociation.\n\t */\n\t var HDCAListItemEdit = _super.extend(\n\t /** @lends HDCAListItemEdit.prototype */{\n\t\n\t /** logger used to record this.log messages, commonly set to console */\n\t //logger : console,\n\t\n\t /** Override to return editable versions of the collection panels */\n\t _getFoldoutPanelClass: function () {\n\t switch (this.model.get('collection_type')) {\n\t case 'list':\n\t return DC_VIEW_EDIT.ListCollectionViewEdit;\n\t case 'paired':\n\t return DC_VIEW_EDIT.PairCollectionViewEdit;\n\t case 'list:paired':\n\t return DC_VIEW_EDIT.ListOfPairsCollectionViewEdit;\n\t case 'list:list':\n\t return DC_VIEW_EDIT.ListOfListsCollectionViewEdit;\n\t }\n\t throw new TypeError('Uknown collection_type: ' + this.model.get('collection_type'));\n\t },\n\t\n\t // ......................................................................... delete\n\t /** In this override, add the delete button. */\n\t _renderPrimaryActions: function () {\n\t this.log(this + '._renderPrimaryActions');\n\t // render the display, edit attr and delete icon-buttons\n\t return _super.prototype._renderPrimaryActions.call(this).concat([this._renderDeleteButton()]);\n\t },\n\t\n\t /** Render icon-button to delete this collection. */\n\t _renderDeleteButton: function () {\n\t var self = this,\n\t deleted = this.model.get('deleted');\n\t return faIconButton({\n\t title: deleted ? _l('Dataset collection is already deleted') : _l('Delete'),\n\t classes: 'delete-btn',\n\t faIcon: 'fa-times',\n\t disabled: deleted,\n\t onclick: function () {\n\t // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n\t self.$el.find('.icon-btn.delete-btn').trigger('mouseout');\n\t self.model['delete']();\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... misc\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDCAListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HDCAListItemEdit: HDCAListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 127 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This class renders the grid list. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(12), __webpack_require__(62), __webpack_require__(84)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, GridView, HistoryModel, historyCopyDialog) {\n\t\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.setElement($('
              '));\n\t this.model = new Backbone.Model();\n\t Utils.get({\n\t url: Galaxy.root + 'history/' + options.action_id,\n\t success: function (response) {\n\t response['dict_format'] = true;\n\t _.each(response['operations'], function (operation) {\n\t if (operation.label == 'Copy') {\n\t operation.onclick = function (id) {\n\t self._showCopyDialog(id);\n\t };\n\t }\n\t });\n\t self.model.set(response);\n\t self.render();\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var grid = new GridView(this.model.attributes);\n\t this.$el.empty().append(grid.$el);\n\t },\n\t\n\t _showCopyDialog: function (id) {\n\t var history = new HistoryModel.History({ id: id });\n\t history.fetch().fail(function () {\n\t alert('History could not be fetched. Please contact an administrator');\n\t }).done(function () {\n\t historyCopyDialog(history, {}).done(function () {\n\t if (window.parent && window.parent.Galaxy && window.parent.Galaxy.currHistoryPanel) {\n\t window.parent.Galaxy.currHistoryPanel.loadCurrentHistory();\n\t }\n\t window.location.reload(true);\n\t });\n\t });\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 128 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(62), __webpack_require__(129), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_MODEL, HISTORY_VIEW_EDIT, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t // ============================================================================\n\t /** session storage for history panel preferences (and to maintain state)\n\t */\n\t\n\t var HistoryViewPrefs = BASE_MVC.SessionStorageModel.extend(\n\t /** @lends HistoryViewPrefs.prototype */{\n\t defaults: {\n\t /** should the tags editor be shown or hidden initially? */\n\t tagsEditorShown: false,\n\t /** should the annotation editor be shown or hidden initially? */\n\t annotationEditorShown: false,\n\t ///** what is the currently focused content (dataset or collection) in the current history?\n\t // * (the history panel will highlight and scroll to the focused content view)\n\t // */\n\t //focusedContentId : null\n\t /** Current scroll position */\n\t scrollPosition: 0\n\t },\n\t toString: function () {\n\t return 'HistoryViewPrefs(' + JSON.stringify(this.toJSON()) + ')';\n\t }\n\t });\n\t\n\t /** key string to store panel prefs (made accessible on class so you can access sessionStorage directly) */\n\t HistoryViewPrefs.storageKey = function storageKey() {\n\t return 'history-panel';\n\t };\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t var _super = HISTORY_VIEW_EDIT.HistoryViewEdit;\n\t // used in root/index.mako\n\t /** @class View/Controller for the user's current history model as used in the history\n\t * panel (current right hand panel) of the analysis page.\n\t *\n\t * The only history panel that:\n\t * will poll for updates.\n\t * displays datasets in reverse hid order.\n\t */\n\t var CurrentHistoryView = _super.extend( /** @lends CurrentHistoryView.prototype */{\n\t\n\t className: _super.prototype.className + ' current-history-panel',\n\t\n\t /** override to use drilldown (and not foldout) for how collections are displayed */\n\t HDCAViewClass: _super.prototype.HDCAViewClass.extend({\n\t foldoutStyle: 'drilldown'\n\t }),\n\t\n\t emptyMsg: [_l('This history is empty'), '. ', _l('You can '), '', _l('load your own data'), '', _l(' or '), '', _l('get data from an external source'), ''].join(''),\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events */\n\t initialize: function (attributes) {\n\t attributes = attributes || {};\n\t\n\t // ---- persistent preferences\n\t /** maintain state / preferences over page loads */\n\t this.preferences = new HistoryViewPrefs(_.extend({\n\t id: HistoryViewPrefs.storageKey()\n\t }, _.pick(attributes, _.keys(HistoryViewPrefs.prototype.defaults))));\n\t\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t /** sub-views that will overlay this panel (collections) */\n\t this.panelStack = [];\n\t\n\t /** id of currently focused content */\n\t this.currentContentId = attributes.currentContentId || null;\n\t //NOTE: purposely not sent to localstorage since panel recreation roughly lines up with a reset of this value\n\t },\n\t\n\t /** Override to cache the current scroll position with a listener */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t\n\t var panel = this;\n\t // reset scroll position when there's a new history\n\t this.on('new-model', function () {\n\t panel.preferences.set('scrollPosition', 0);\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading history/item models\n\t // TODO: next three more appropriate moved to the app level\n\t /** (re-)loads the user's current history & contents w/ details */\n\t loadCurrentHistory: function () {\n\t return this.loadHistory(null, { url: Galaxy.root + 'history/current_history_json' });\n\t },\n\t\n\t /** loads a history & contents w/ details and makes them the current history */\n\t switchToHistory: function (historyId, attributes) {\n\t if (Galaxy.user.isAnonymous()) {\n\t this.trigger('error', _l('You must be logged in to switch histories'), _l('Anonymous user'));\n\t return $.when();\n\t }\n\t return this.loadHistory(historyId, { url: Galaxy.root + 'history/set_as_current?id=' + historyId });\n\t },\n\t\n\t /** creates a new history on the server and sets it as the user's current history */\n\t createNewHistory: function (attributes) {\n\t if (Galaxy.user.isAnonymous()) {\n\t this.trigger('error', _l('You must be logged in to create histories'), _l('Anonymous user'));\n\t return $.when();\n\t }\n\t return this.loadHistory(null, { url: Galaxy.root + 'history/create_new_current' });\n\t },\n\t\n\t /** release/free/shutdown old models and set up panel for new models */\n\t setModel: function (model, attributes, render) {\n\t _super.prototype.setModel.call(this, model, attributes, render);\n\t if (this.model && this.model.id) {\n\t this.log('checking for updates');\n\t this.model.checkForUpdates();\n\t }\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ history/content event listening\n\t /** listening for history events */\n\t _setUpModelListeners: function () {\n\t _super.prototype._setUpModelListeners.call(this);\n\t // re-broadcast any model change events so that listeners don't have to re-bind to each history\n\t return this.listenTo(this.model, {\n\t 'change:nice_size change:size': function () {\n\t this.trigger('history-size-change', this, this.model, arguments);\n\t },\n\t 'change:id': function () {\n\t this.once('loading-done', function () {\n\t this.model.checkForUpdates();\n\t });\n\t }\n\t });\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t // if a hidden item is created (gen. by a workflow), moves thru the updater to the ready state,\n\t // then: remove it from the collection if the panel is set to NOT show hidden datasets\n\t this.listenTo(this.collection, 'state:ready', function (model, newState, oldState) {\n\t if (!model.get('visible') && !this.collection.storage.includeHidden()) {\n\t this.removeItemView(model);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** override to add a handler to capture the scroll position when the parent scrolls */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t // console.log( '_setUpBehaviors', this.$scrollContainer( $where ).get(0), this.$list( $where ) );\n\t // we need to call this in _setUpBehaviors which is called after render since the $el\n\t // may not be attached to $el.parent and $scrollContainer() may not work\n\t var panel = this;\n\t _super.prototype._setUpBehaviors.call(panel, $where);\n\t\n\t // cache the handler to remove and re-add so we don't pile up the handlers\n\t if (!this._debouncedScrollCaptureHandler) {\n\t this._debouncedScrollCaptureHandler = _.debounce(function scrollCapture() {\n\t // cache the scroll position (only if visible)\n\t if (panel.$el.is(':visible')) {\n\t panel.preferences.set('scrollPosition', $(this).scrollTop());\n\t }\n\t }, 40);\n\t }\n\t\n\t panel.$scrollContainer($where).off('scroll', this._debouncedScrollCaptureHandler).on('scroll', this._debouncedScrollCaptureHandler);\n\t return panel;\n\t },\n\t\n\t /** In this override, handle null models and move the search input to the top */\n\t _buildNewRender: function () {\n\t if (!this.model) {\n\t return $();\n\t }\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t $newRender.find('.search').prependTo($newRender.find('> .controls'));\n\t this._renderQuotaMessage($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** render the message displayed when a user is over quota and can't run jobs */\n\t _renderQuotaMessage: function ($whereTo) {\n\t $whereTo = $whereTo || this.$el;\n\t return $(this.templates.quotaMsg({}, this)).prependTo($whereTo.find('.messages'));\n\t },\n\t\n\t /** In this override, get and set current panel preferences when editor is used */\n\t _renderTags: function ($where) {\n\t var panel = this;\n\t // render tags and show/hide based on preferences\n\t _super.prototype._renderTags.call(panel, $where);\n\t if (panel.preferences.get('tagsEditorShown')) {\n\t panel.tagsEditor.toggle(true);\n\t }\n\t // store preference when shown or hidden\n\t panel.listenTo(panel.tagsEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden', function (tagsEditor) {\n\t panel.preferences.set('tagsEditorShown', tagsEditor.hidden);\n\t });\n\t },\n\t\n\t /** In this override, get and set current panel preferences when editor is used */\n\t _renderAnnotation: function ($where) {\n\t var panel = this;\n\t // render annotation and show/hide based on preferences\n\t _super.prototype._renderAnnotation.call(panel, $where);\n\t if (panel.preferences.get('annotationEditorShown')) {\n\t panel.annotationEditor.toggle(true);\n\t }\n\t // store preference when shown or hidden\n\t panel.listenTo(panel.annotationEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden', function (annotationEditor) {\n\t panel.preferences.set('annotationEditorShown', annotationEditor.hidden);\n\t });\n\t },\n\t\n\t /** Override to scroll to cached position (in prefs) after swapping */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t var panel = this;\n\t _.delay(function () {\n\t var pos = panel.preferences.get('scrollPosition');\n\t if (pos) {\n\t panel.scrollTo(pos, 0);\n\t }\n\t }, 10);\n\t //TODO: is this enough of a delay on larger histories?\n\t\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** Override to add the current-content highlight class to currentContentId's view */\n\t _attachItems: function ($whereTo) {\n\t _super.prototype._attachItems.call(this, $whereTo);\n\t var panel = this;\n\t if (panel.currentContentId) {\n\t panel._setCurrentContentById(panel.currentContentId);\n\t }\n\t return this;\n\t },\n\t\n\t /** Override to remove any drill down panels */\n\t addItemView: function (model, collection, options) {\n\t var view = _super.prototype.addItemView.call(this, model, collection, options);\n\t if (!view) {\n\t return view;\n\t }\n\t if (this.panelStack.length) {\n\t return this._collapseDrilldownPanel();\n\t }\n\t return view;\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection sub-views\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t // use pub-sub to: handle drilldown expansion and collapse\n\t return panel.listenTo(view, {\n\t 'expanded:drilldown': function (v, drilldown) {\n\t this._expandDrilldownPanel(drilldown);\n\t },\n\t 'collapsed:drilldown': function (v, drilldown) {\n\t this._collapseDrilldownPanel(drilldown);\n\t }\n\t });\n\t },\n\t\n\t /** display 'current content': add a visible highlight and store the id of a content item */\n\t setCurrentContent: function (view) {\n\t this.$('.history-content.current-content').removeClass('current-content');\n\t if (view) {\n\t view.$el.addClass('current-content');\n\t this.currentContentId = view.model.id;\n\t } else {\n\t this.currentContentId = null;\n\t }\n\t },\n\t\n\t /** find the view with the id and then call setCurrentContent on it */\n\t _setCurrentContentById: function (id) {\n\t var view = this.viewFromModelId(id) || null;\n\t this.setCurrentContent(view);\n\t },\n\t\n\t /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n\t _expandDrilldownPanel: function (drilldown) {\n\t this.panelStack.push(drilldown);\n\t // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n\t this.$controls().add(this.$list()).hide();\n\t drilldown.parentName = this.model.get('name');\n\t drilldown.delegateEvents().render().$el.appendTo(this.$el);\n\t },\n\t\n\t /** Handle drilldown close by freeing the panel and re-rendering this panel */\n\t _collapseDrilldownPanel: function (drilldown) {\n\t this.panelStack.pop();\n\t //TODO: MEM: free the panel\n\t this.$controls().add(this.$list()).show();\n\t },\n\t\n\t // ........................................................................ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t // the two links in the empty message\n\t 'click .uploader-link': function (ev) {\n\t Galaxy.upload.show(ev);\n\t },\n\t 'click .get-data-link': function (ev) {\n\t var $toolMenu = $('.toolMenuContainer');\n\t $toolMenu.parent().scrollTop(0);\n\t $toolMenu.find('span:contains(\"Get Data\")').click();\n\t }\n\t }),\n\t\n\t // ........................................................................ external objects/MVC\n\t listenToGalaxy: function (galaxy) {\n\t this.listenTo(galaxy, {\n\t // when the galaxy_main iframe is loaded with a new page,\n\t // compare the url to the following list and if there's a match\n\t // pull the id from url and indicate in the history view that\n\t // the dataset with that id is the 'current'ly active dataset\n\t 'center-frame:load': function (data) {\n\t var pathToMatch = data.fullpath;\n\t var hdaId = null;\n\t var useToURLRegexMap = {\n\t 'display': /datasets\\/([a-f0-9]+)\\/display/,\n\t 'edit': /datasets\\/([a-f0-9]+)\\/edit/,\n\t 'report_error': /dataset\\/errors\\?id=([a-f0-9]+)/,\n\t 'rerun': /tool_runner\\/rerun\\?id=([a-f0-9]+)/,\n\t 'show_params': /datasets\\/([a-f0-9]+)\\/show_params/\n\t };\n\t _.find(useToURLRegexMap, function (regex, use) {\n\t // grab the more specific match result (1), save, and use it as the find flag\n\t hdaId = _.result(pathToMatch.match(regex), 1);\n\t return hdaId;\n\t });\n\t // need to type mangle to go from web route to history contents\n\t this._setCurrentContentById(hdaId ? 'dataset-' + hdaId : null);\n\t },\n\t // when the center panel is given a new view, clear the current indicator\n\t 'center-panel:load': function (view) {\n\t this._setCurrentContentById();\n\t }\n\t });\n\t },\n\t\n\t //TODO: remove quota meter from panel and remove this\n\t /** add listeners to an external quota meter (mvc/user/user-quotameter.js) */\n\t connectToQuotaMeter: function (quotaMeter) {\n\t if (!quotaMeter) {\n\t return this;\n\t }\n\t // show/hide the 'over quota message' in the history when the meter tells it to\n\t this.listenTo(quotaMeter, 'quota:over', this.showQuotaMessage);\n\t this.listenTo(quotaMeter, 'quota:under', this.hideQuotaMessage);\n\t\n\t // having to add this to handle re-render of hview while overquota (the above do not fire)\n\t this.on('rendered rendered:initial', function () {\n\t if (quotaMeter && quotaMeter.isOverQuota()) {\n\t this.showQuotaMessage();\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** Override to preserve the quota message */\n\t clearMessages: function (ev) {\n\t var $target = !_.isUndefined(ev) ? $(ev.currentTarget) : this.$messages().children('[class$=\"message\"]');\n\t $target = $target.not('.quota-message');\n\t $target.fadeOut(this.fxSpeed, function () {\n\t $(this).remove();\n\t });\n\t return this;\n\t },\n\t\n\t /** Show the over quota message (which happens to be in the history panel).\n\t */\n\t showQuotaMessage: function () {\n\t var $msg = this.$('.quota-message');\n\t if ($msg.is(':hidden')) {\n\t $msg.slideDown(this.fxSpeed);\n\t }\n\t },\n\t\n\t /** Hide the over quota message (which happens to be in the history panel).\n\t */\n\t hideQuotaMessage: function () {\n\t var $msg = this.$('.quota-message');\n\t if (!$msg.is(':hidden')) {\n\t $msg.slideUp(this.fxSpeed);\n\t }\n\t },\n\t\n\t // ........................................................................ options menu\n\t //TODO: remove to batch\n\t /** unhide any hidden datasets */\n\t unhideHidden: function () {\n\t var self = this;\n\t if (confirm(_l('Really unhide all hidden datasets?'))) {\n\t // get all hidden, regardless of deleted/purged\n\t return self.model.contents._filterAndUpdate({ visible: false, deleted: '', purged: '' }, { visible: true }).done(function () {\n\t // TODO: would be better to render these as they're unhidden instead of all at once\n\t if (!self.model.contents.includeHidden) {\n\t self.renderItems();\n\t }\n\t });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** delete any hidden datasets */\n\t deleteHidden: function () {\n\t var self = this;\n\t if (confirm(_l('Really delete all hidden datasets?'))) {\n\t return self.model.contents._filterAndUpdate(\n\t // get all hidden, regardless of deleted/purged\n\t { visible: false, deleted: '', purged: '' },\n\t // both delete *and* unhide them\n\t { deleted: true, visible: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'CurrentHistoryView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t CurrentHistoryView.prototype.templates = function () {\n\t\n\t var quotaMsgTemplate = BASE_MVC.wrapTemplate(['
              ', _l('You are over your disk quota'), '. ', _l('Tool execution is on hold until your disk usage drops below your allocated quota'), '.', '
              '], 'history');\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t quotaMsg: quotaMsgTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t CurrentHistoryView: CurrentHistoryView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 129 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(130), __webpack_require__(61), __webpack_require__(17), __webpack_require__(86), __webpack_require__(125), __webpack_require__(126), __webpack_require__(65), __webpack_require__(78), __webpack_require__(57), __webpack_require__(122), __webpack_require__(121), __webpack_require__(25), __webpack_require__(18), __webpack_require__(7), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_VIEW, HISTORY_CONTENTS, STATES, HDA_MODEL, HDA_LI_EDIT, HDCA_LI_EDIT, TAGS, ANNOTATIONS, LIST_COLLECTION_CREATOR, PAIR_COLLECTION_CREATOR, LIST_OF_PAIRS_COLLECTION_CREATOR, faIconButton, PopupMenu, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t\n\t var _super = HISTORY_VIEW.HistoryView;\n\t // base class for history-view-edit-current and used as-is in history/view.mako\n\t /** @class Editable View/Controller for the history model.\n\t *\n\t * Allows:\n\t * (everything HistoryView allows)\n\t * changing the name\n\t * displaying and editing tags and annotations\n\t * multi-selection and operations on mulitple content items\n\t */\n\t var HistoryViewEdit = _super.extend(\n\t /** @lends HistoryViewEdit.prototype */{\n\t\n\t /** class to use for constructing the HistoryDatasetAssociation views */\n\t HDAViewClass: HDA_LI_EDIT.HDAListItemEdit,\n\t /** class to use for constructing the HistoryDatasetCollectionAssociation views */\n\t HDCAViewClass: HDCA_LI_EDIT.HDCAListItemEdit,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes\n\t */\n\t initialize: function (attributes) {\n\t attributes = attributes || {};\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t // ---- set up instance vars\n\t /** editor for tags - sub-view */\n\t this.tagsEditor = null;\n\t\n\t /** enable drag and drop - sub-view */\n\t this.dragItems = true;\n\t\n\t /** editor for annotations - sub-view */\n\t this.annotationEditor = null;\n\t\n\t /** allow user purge of dataset files? */\n\t this.purgeAllowed = attributes.purgeAllowed || false;\n\t\n\t // states/modes the panel can be in\n\t /** is the panel currently showing the dataset selection controls? */\n\t this.annotationEditorShown = attributes.annotationEditorShown || false;\n\t this.tagsEditorShown = attributes.tagsEditorShown || false;\n\t },\n\t\n\t /** Override to handle history as drag-drop target */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t return this.on({\n\t 'droptarget:drop': function (ev, data) {\n\t // process whatever was dropped and re-hide the drop target\n\t this.dataDropped(data);\n\t this.dropTargetOff();\n\t },\n\t 'view:attached view:removed': function () {\n\t this._renderCounts();\n\t },\n\t 'search:loading-progress': this._renderSearchProgress,\n\t 'search:searching': this._renderSearchFindings\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ listeners\n\t /** listening for history and HDA events */\n\t _setUpModelListeners: function () {\n\t _super.prototype._setUpModelListeners.call(this);\n\t this.listenTo(this.model, 'change:size', this.updateHistoryDiskSize);\n\t return this;\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t this.listenTo(this.collection, {\n\t 'change:deleted': this._handleItemDeletedChange,\n\t 'change:visible': this._handleItemVisibleChange,\n\t 'change:purged': function (model) {\n\t // hafta get the new nice-size w/o the purged model\n\t this.model.fetch();\n\t },\n\t // loading indicators for deleted/hidden\n\t 'fetching-deleted': function (collection) {\n\t this.$('> .controls .deleted-count').html('' + _l('loading...') + '');\n\t },\n\t 'fetching-hidden': function (collection) {\n\t this.$('> .controls .hidden-count').html('' + _l('loading...') + '');\n\t },\n\t 'fetching-deleted-done fetching-hidden-done': this._renderCounts\n\t });\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** In this override, add tag and annotation editors and a btn to toggle the selectors */\n\t _buildNewRender: function () {\n\t // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t if (!this.model) {\n\t return $newRender;\n\t }\n\t\n\t if (Galaxy && Galaxy.user && Galaxy.user.id && Galaxy.user.id === this.model.get('user_id')) {\n\t this._renderTags($newRender);\n\t this._renderAnnotation($newRender);\n\t }\n\t return $newRender;\n\t },\n\t\n\t /** Update the history size display (curr. upper right of panel). */\n\t updateHistoryDiskSize: function () {\n\t this.$('.history-size').text(this.model.get('nice_size'));\n\t },\n\t\n\t /** override to render counts when the items are rendered */\n\t renderItems: function ($whereTo) {\n\t var views = _super.prototype.renderItems.call(this, $whereTo);\n\t if (!this.searchFor) {\n\t this._renderCounts($whereTo);\n\t }\n\t return views;\n\t },\n\t\n\t /** override to show counts, what's deleted/hidden, and links to toggle those */\n\t _renderCounts: function ($whereTo) {\n\t $whereTo = $whereTo instanceof jQuery ? $whereTo : this.$el;\n\t var html = this.templates.counts(this.model.toJSON(), this);\n\t return $whereTo.find('> .controls .subtitle').html(html);\n\t },\n\t\n\t /** render the tags sub-view controller */\n\t _renderTags: function ($where) {\n\t var panel = this;\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.controls .tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // show hide sub-view tag editors when this is shown/hidden\n\t onshow: function () {\n\t panel.toggleHDATagEditors(true, panel.fxSpeed);\n\t },\n\t onhide: function () {\n\t panel.toggleHDATagEditors(false, panel.fxSpeed);\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit history tags'),\n\t classes: 'history-tag-btn',\n\t faIcon: 'fa-tags'\n\t }).appendTo($where.find('.controls .actions'))\n\t });\n\t },\n\t /** render the annotation sub-view controller */\n\t _renderAnnotation: function ($where) {\n\t var panel = this;\n\t this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n\t model: this.model,\n\t el: $where.find('.controls .annotation-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // show hide sub-view view annotation editors when this is shown/hidden\n\t onshow: function () {\n\t panel.toggleHDAAnnotationEditors(true, panel.fxSpeed);\n\t },\n\t onhide: function () {\n\t panel.toggleHDAAnnotationEditors(false, panel.fxSpeed);\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit history annotation'),\n\t classes: 'history-annotate-btn',\n\t faIcon: 'fa-comment'\n\t }).appendTo($where.find('.controls .actions'))\n\t });\n\t },\n\t\n\t /** Set up HistoryViewEdit js/widget behaviours\n\t * In this override, make the name editable\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t if (!this.model) {\n\t return;\n\t }\n\t\n\t // anon users shouldn't have access to any of the following\n\t if (!Galaxy.user || Galaxy.user.isAnonymous() || Galaxy.user.id !== this.model.get('user_id')) {\n\t return;\n\t }\n\t\n\t var panel = this,\n\t nameSelector = '> .controls .name';\n\t $where.find(nameSelector).attr('title', _l('Click to rename history')).tooltip({ placement: 'bottom' }).make_text_editable({\n\t on_finish: function (newName) {\n\t var previousName = panel.model.get('name');\n\t if (newName && newName !== previousName) {\n\t panel.$el.find(nameSelector).text(newName);\n\t panel.model.save({ name: newName }).fail(function () {\n\t panel.$el.find(nameSelector).text(panel.model.previous('name'));\n\t });\n\t } else {\n\t panel.$el.find(nameSelector).text(previousName);\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** return a new popup menu for choosing a multi selection action\n\t * ajax calls made for multiple datasets are queued\n\t */\n\t multiselectActions: function () {\n\t var panel = this,\n\t actions = [{ html: _l('Hide datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.hide;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Unhide datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.unhide;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Delete datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype['delete'];\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Undelete datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.undelete;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }];\n\t if (panel.purgeAllowed) {\n\t actions.push({\n\t html: _l('Permanently delete datasets'), func: function () {\n\t if (confirm(_l('This will permanently remove the data in your datasets. Are you sure?'))) {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.purge;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }\n\t });\n\t }\n\t actions = actions.concat(panel._collectionActions());\n\t return actions;\n\t },\n\t\n\t /** */\n\t _collectionActions: function () {\n\t var panel = this;\n\t return [{ html: _l('Build Dataset List'), func: function () {\n\t panel.buildCollection(\"list\");\n\t }\n\t },\n\t // TODO: Only show quick pair if two things selected.\n\t { html: _l('Build Dataset Pair'), func: function () {\n\t panel.buildCollection(\"paired\");\n\t }\n\t }, { html: _l('Build List of Dataset Pairs'), func: function () {\n\t panel.buildCollection(\"list:paired\");\n\t }\n\t }];\n\t },\n\t\n\t buildCollection: function (collectionType, selection, hideSourceItems) {\n\t var panel = this;\n\t var selection = selection || panel.getSelectedModels();\n\t var hideSourceItems = hideSourceItems || false;\n\t var createFunc;\n\t if (collectionType == \"list\") {\n\t createFunc = LIST_COLLECTION_CREATOR.createListCollection;\n\t } else if (collectionType == \"paired\") {\n\t createFunc = PAIR_COLLECTION_CREATOR.createPairCollection;\n\t } else if (collectionType == \"list:paired\") {\n\t createFunc = LIST_OF_PAIRS_COLLECTION_CREATOR.createListOfPairsCollection;\n\t } else {\n\t console.warn(\"Unknown collectionType encountered \" + collectionType);\n\t }\n\t createFunc(selection, hideSourceItems).done(function () {\n\t panel.model.refresh();\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** In this override, add purgeAllowed and whether tags/annotation editors should be shown */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t _.extend(options, {\n\t purgeAllowed: this.purgeAllowed,\n\t tagsEditorShown: this.tagsEditor && !this.tagsEditor.hidden,\n\t annotationEditorShown: this.annotationEditor && !this.annotationEditor.hidden\n\t });\n\t return options;\n\t },\n\t\n\t /** If this item is deleted and we're not showing deleted items, remove the view\n\t * @param {Model} the item model to check\n\t */\n\t _handleItemDeletedChange: function (itemModel) {\n\t if (itemModel.get('deleted')) {\n\t this._handleItemDeletion(itemModel);\n\t } else {\n\t this._handleItemUndeletion(itemModel);\n\t }\n\t this._renderCounts();\n\t },\n\t\n\t _handleItemDeletion: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.deleted += 1;\n\t contentsShown.active -= 1;\n\t if (!this.model.contents.includeDeleted) {\n\t this.removeItemView(itemModel);\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t _handleItemUndeletion: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.deleted -= 1;\n\t if (!this.model.contents.includeDeleted) {\n\t contentsShown.active -= 1;\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t /** If this item is hidden and we're not showing hidden items, remove the view\n\t * @param {Model} the item model to check\n\t */\n\t _handleItemVisibleChange: function (itemModel) {\n\t if (itemModel.hidden()) {\n\t this._handleItemHidden(itemModel);\n\t } else {\n\t this._handleItemUnhidden(itemModel);\n\t }\n\t this._renderCounts();\n\t },\n\t\n\t _handleItemHidden: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.hidden += 1;\n\t contentsShown.active -= 1;\n\t if (!this.model.contents.includeHidden) {\n\t this.removeItemView(itemModel);\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t _handleItemUnhidden: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.hidden -= 1;\n\t if (!this.model.contents.includeHidden) {\n\t contentsShown.active -= 1;\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t /** toggle the visibility of each content's tagsEditor applying all the args sent to this function */\n\t toggleHDATagEditors: function (showOrHide, speed) {\n\t _.each(this.views, function (view) {\n\t if (view.tagsEditor) {\n\t view.tagsEditor.toggle(showOrHide, speed);\n\t }\n\t });\n\t },\n\t\n\t /** toggle the visibility of each content's annotationEditor applying all the args sent to this function */\n\t toggleHDAAnnotationEditors: function (showOrHide, speed) {\n\t _.each(this.views, function (view) {\n\t if (view.annotationEditor) {\n\t view.annotationEditor.toggle(showOrHide, speed);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .show-selectors-btn': 'toggleSelectors',\n\t 'click .toggle-deleted-link': function (ev) {\n\t this.toggleShowDeleted();\n\t },\n\t 'click .toggle-hidden-link': function (ev) {\n\t this.toggleShowHidden();\n\t }\n\t }),\n\t\n\t // ------------------------------------------------------------------------ search\n\t _renderSearchProgress: function (limit, offset) {\n\t var stop = limit + offset;\n\t return this.$('> .controls .subtitle').html(['', _l('Searching '), stop, '/', this.model.contentsShown(), ''].join(''));\n\t },\n\t\n\t /** override to display number found in subtitle */\n\t _renderSearchFindings: function () {\n\t this.$('> .controls .subtitle').html([_l('Found'), this.views.length].join(' '));\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ as drop target\n\t /** turn all the drag and drop handlers on and add some help text above the drop area */\n\t dropTargetOn: function () {\n\t if (this.dropTarget) {\n\t return this;\n\t }\n\t this.dropTarget = true;\n\t\n\t //TODO: to init\n\t var dropHandlers = {\n\t 'dragenter': _.bind(this.dragenter, this),\n\t 'dragover': _.bind(this.dragover, this),\n\t 'dragleave': _.bind(this.dragleave, this),\n\t 'drop': _.bind(this.drop, this)\n\t };\n\t\n\t var $dropTarget = this._renderDropTarget();\n\t this.$list().before([this._renderDropTargetHelp(), $dropTarget]);\n\t for (var evName in dropHandlers) {\n\t if (dropHandlers.hasOwnProperty(evName)) {\n\t //console.debug( evName, dropHandlers[ evName ] );\n\t $dropTarget.on(evName, dropHandlers[evName]);\n\t }\n\t }\n\t return this;\n\t },\n\t\n\t /** render a box to serve as a 'drop here' area on the history */\n\t _renderDropTarget: function () {\n\t this.$('.history-drop-target').remove();\n\t return $('
              ').addClass('history-drop-target');\n\t },\n\t\n\t /** tell the user how it works */\n\t _renderDropTargetHelp: function () {\n\t this.$('.history-drop-target-help').remove();\n\t return $('
              ').addClass('history-drop-target-help').text(_l('Drag datasets here to copy them to the current history'));\n\t },\n\t\n\t /** shut down drag and drop event handlers and remove drop target */\n\t dropTargetOff: function () {\n\t if (!this.dropTarget) {\n\t return this;\n\t }\n\t //this.log( 'dropTargetOff' );\n\t this.dropTarget = false;\n\t var dropTarget = this.$('.history-drop-target').get(0);\n\t for (var evName in this._dropHandlers) {\n\t if (this._dropHandlers.hasOwnProperty(evName)) {\n\t dropTarget.off(evName, this._dropHandlers[evName]);\n\t }\n\t }\n\t this.$('.history-drop-target').remove();\n\t this.$('.history-drop-target-help').remove();\n\t return this;\n\t },\n\t /** toggle the target on/off */\n\t dropTargetToggle: function () {\n\t if (this.dropTarget) {\n\t this.dropTargetOff();\n\t } else {\n\t this.dropTargetOn();\n\t }\n\t return this;\n\t },\n\t\n\t dragenter: function (ev) {\n\t //console.debug( 'dragenter:', this, ev );\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t this.$('.history-drop-target').css('border', '2px solid black');\n\t },\n\t dragover: function (ev) {\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t },\n\t dragleave: function (ev) {\n\t //console.debug( 'dragleave:', this, ev );\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t this.$('.history-drop-target').css('border', '1px dashed black');\n\t },\n\t /** when (text) is dropped try to parse as json and trigger an event */\n\t drop: function (ev) {\n\t ev.preventDefault();\n\t //ev.stopPropagation();\n\t\n\t var self = this;\n\t var dataTransfer = ev.originalEvent.dataTransfer;\n\t var data = dataTransfer.getData(\"text\");\n\t\n\t dataTransfer.dropEffect = 'move';\n\t try {\n\t data = JSON.parse(data);\n\t } catch (err) {\n\t self.warn('error parsing JSON from drop:', data);\n\t }\n\t\n\t self.trigger('droptarget:drop', ev, data, self);\n\t return false;\n\t },\n\t\n\t /** handler that copies data into the contents */\n\t dataDropped: function (data) {\n\t var self = this;\n\t // HDA: dropping will copy it to the history\n\t if (_.isObject(data) && data.model_class === 'HistoryDatasetAssociation' && data.id) {\n\t if (self.contents.currentPage !== 0) {\n\t return self.contents.fetchPage(0).then(function () {\n\t return self.model.contents.copy(data.id);\n\t });\n\t }\n\t return self.model.contents.copy(data.id);\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ........................................................................ misc\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'HistoryViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t HistoryViewEdit.prototype.templates = function () {\n\t\n\t var countsTemplate = BASE_MVC.wrapTemplate(['<% var shown = Math.max( view.views.length, history.contents_active.active ) %>', '<% if( shown ){ %>', '', '<%- shown %> ', _l('shown'), '', '<% } %>', '<% if( history.contents_active.deleted ){ %>', '', '<% if( view.model.contents.includeDeleted ){ %>', '', _l('hide deleted'), '', '<% } else { %>', '<%- history.contents_active.deleted %> ', '', _l('deleted'), '', '<% } %>', '', '<% } %>', '<% if( history.contents_active.hidden ){ %>', '', '<% if( view.model.contents.includeHidden ){ %>', '', _l('hide hidden'), '', '<% } else { %>', '<%- history.contents_active.hidden %> ', '', _l('hidden'), '', '<% } %>', '', '<% } %>'], 'history');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t counts: countsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HistoryViewEdit: HistoryViewEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 130 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(89), __webpack_require__(62), __webpack_require__(61), __webpack_require__(63), __webpack_require__(85), __webpack_require__(87), __webpack_require__(93), __webpack_require__(92), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6), __webpack_require__(96)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_VIEW, HISTORY_MODEL, HISTORY_CONTENTS, HISTORY_PREFS, HDA_LI, HDCA_LI, USER, ERROR_MODAL, faIconButton, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class non-editable, read-only View/Controller for a history model.\n\t * Allows:\n\t * changing the loaded history\n\t * displaying data, info, and download\n\t * tracking history attrs: size, tags, annotations, name, etc.\n\t * Does not allow:\n\t * changing the name\n\t */\n\t\n\t var _super = LIST_VIEW.ModelListPanel;\n\t var HistoryView = _super.extend(\n\t /** @lends HistoryView.prototype */{\n\t _logNamespace: 'history',\n\t\n\t /** class to use for constructing the HDA views */\n\t HDAViewClass: HDA_LI.HDAListItemView,\n\t /** class to use for constructing the HDCA views */\n\t HDCAViewClass: HDCA_LI.HDCAListItemView,\n\t /** class to used for constructing collection of sub-view models */\n\t collectionClass: HISTORY_CONTENTS.HistoryContents,\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'contents',\n\t\n\t tagName: 'div',\n\t className: _super.prototype.className + ' history-panel',\n\t\n\t /** string to display when the collection is empty */\n\t emptyMsg: _l('This history is empty'),\n\t /** displayed when no items match the search terms */\n\t noneFoundMsg: _l('No matching datasets found'),\n\t /** string used for search placeholder */\n\t searchPlaceholder: _l('search datasets'),\n\t\n\t /** @type {Number} ms to wait after history load to fetch/decorate hdcas with element_count */\n\t FETCH_COLLECTION_COUNTS_DELAY: 2000,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, bind listeners.\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t // ---- instance vars\n\t // control contents/behavior based on where (and in what context) the panel is being used\n\t /** where should pages from links be displayed? (default to new tab/window) */\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t },\n\t\n\t /** create and return a collection for when none is initially passed */\n\t _createDefaultCollection: function () {\n\t // override\n\t return new this.collectionClass([], { history: this.model });\n\t },\n\t\n\t /** In this override, clear the update timer on the model */\n\t freeModel: function () {\n\t _super.prototype.freeModel.call(this);\n\t if (this.model) {\n\t this.model.clearUpdateTimeout();\n\t }\n\t return this;\n\t },\n\t\n\t /** create any event listeners for the panel\n\t * @fires: rendered:initial on the first render\n\t * @fires: empty-history when switching to a history with no contents or creating a new history\n\t */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t this.on({\n\t error: function (model, xhr, options, msg, details) {\n\t this.errorHandler(model, xhr, options, msg, details);\n\t },\n\t 'loading-done': function () {\n\t var self = this;\n\t // after the initial load, decorate with more time consuming fields (like HDCA element_counts)\n\t _.delay(function () {\n\t self.model.contents.fetchCollectionCounts();\n\t }, self.FETCH_COLLECTION_COUNTS_DELAY);\n\t },\n\t 'views:ready view:attached view:removed': function (view) {\n\t this._renderSelectButton();\n\t },\n\t 'view:attached': function (view) {\n\t this.scrollTo(0);\n\t }\n\t });\n\t // this.on( 'all', function(){ console.debug( arguments ); });\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading history/hda models\n\t /** load the history with the given id then it's contents, sending ajax options to both */\n\t loadHistory: function (historyId, options, contentsOptions) {\n\t contentsOptions = _.extend(contentsOptions || { silent: true });\n\t this.info('loadHistory:', historyId, options, contentsOptions);\n\t var self = this;\n\t self.setModel(new HISTORY_MODEL.History({ id: historyId }));\n\t\n\t contentsOptions.silent = true;\n\t self.trigger('loading');\n\t return self.model.fetchWithContents(options, contentsOptions).always(function () {\n\t self.render();\n\t self.trigger('loading-done');\n\t });\n\t },\n\t\n\t /** convenience alias to the model. Updates the item list only (not the history) */\n\t refreshContents: function (options) {\n\t if (this.model) {\n\t return this.model.refresh(options);\n\t }\n\t // may have callbacks - so return an empty promise\n\t return $.when();\n\t },\n\t\n\t /** Override to reset web storage when the id changes (since it needs the id) */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t return this.listenTo(this.collection, {\n\t // 'all' : function(){ console.log( this.collection + ':', arguments ); },\n\t 'fetching-more': function () {\n\t this._toggleContentsLoadingIndicator(true);\n\t this.$emptyMessage().hide();\n\t },\n\t 'fetching-more-done': function () {\n\t this._toggleContentsLoadingIndicator(false);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n\t _showLoadingIndicator: function (msg, speed, callback) {\n\t var $indicator = $('
              ');\n\t this.$el.html($indicator.text(msg).slideDown(!_.isUndefined(speed) ? speed : this.fxSpeed));\n\t },\n\t\n\t /** hide the loading indicator */\n\t _hideLoadingIndicator: function (speed) {\n\t // make speed a bit slower to compensate for slow rendering of up to 500 contents\n\t this.$('.loading-indicator').slideUp(!_.isUndefined(speed) ? speed : this.fxSpeed + 200, function () {\n\t $(this).remove();\n\t });\n\t },\n\t\n\t /** In this override, add a btn to toggle the selectors */\n\t _buildNewRender: function () {\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t this._renderSelectButton($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** button for starting select mode */\n\t _renderSelectButton: function ($where) {\n\t $where = $where || this.$el;\n\t // do not render selector option if no actions\n\t if (!this.multiselectActions().length) {\n\t return null;\n\t }\n\t // do not render (and remove even) if nothing to select\n\t if (!this.views.length) {\n\t this.hideSelectors();\n\t $where.find('.controls .actions .show-selectors-btn').remove();\n\t return null;\n\t }\n\t // don't bother rendering if there's one already\n\t var $existing = $where.find('.controls .actions .show-selectors-btn');\n\t if ($existing.length) {\n\t return $existing;\n\t }\n\t\n\t return faIconButton({\n\t title: _l('Operations on multiple datasets'),\n\t classes: 'show-selectors-btn',\n\t faIcon: 'fa-check-square-o'\n\t }).prependTo($where.find('.controls .actions'));\n\t },\n\t\n\t /** override to avoid showing intial empty message using contents_active */\n\t _renderEmptyMessage: function ($whereTo) {\n\t var self = this;\n\t var $emptyMsg = self.$emptyMessage($whereTo);\n\t\n\t var empty = self.model.get('contents_active').active <= 0;\n\t if (empty) {\n\t return $emptyMsg.empty().append(self.emptyMsg).show();\n\t } else if (self.searchFor && self.model.contents.haveSearchDetails() && !self.views.length) {\n\t return $emptyMsg.empty().append(self.noneFoundMsg).show();\n\t }\n\t $emptyMsg.hide();\n\t return $();\n\t },\n\t\n\t /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n\t $scrollContainer: function ($where) {\n\t // override or set via attributes.$scrollContainer\n\t return this.$list($where);\n\t },\n\t\n\t // ------------------------------------------------------------------------ subviews\n\t _toggleContentsLoadingIndicator: function (show) {\n\t if (!show) {\n\t this.$list().find('.contents-loading-indicator').remove();\n\t } else {\n\t this.$list().html('
              ' + '
              ');\n\t }\n\t },\n\t\n\t /** override to render pagination also */\n\t renderItems: function ($whereTo) {\n\t // console.log( this + '.renderItems-----------------', new Date() );\n\t $whereTo = $whereTo || this.$el;\n\t var self = this;\n\t var $list = self.$list($whereTo);\n\t\n\t // TODO: bootstrap hack to remove orphaned tooltips\n\t $('.tooltip').remove();\n\t\n\t $list.empty();\n\t self.views = [];\n\t\n\t var models = self._filterCollection();\n\t if (models.length) {\n\t self._renderPagination($whereTo);\n\t self.views = self._renderSomeItems(models, $list);\n\t } else {\n\t // TODO: consolidate with _renderPagination above by (???) passing in models/length?\n\t $whereTo.find('> .controls .list-pagination').empty();\n\t }\n\t self._renderEmptyMessage($whereTo).toggle(!models.length);\n\t\n\t self.trigger('views:ready', self.views);\n\t return self.views;\n\t },\n\t\n\t /** render pagination controls if not searching and contents says we're paginating */\n\t _renderPagination: function ($whereTo) {\n\t var $paginationControls = $whereTo.find('> .controls .list-pagination');\n\t if (this.searchFor || !this.model.contents.shouldPaginate()) return $paginationControls.empty();\n\t\n\t $paginationControls.html(this.templates.pagination({\n\t // pagination is 1-based for the user\n\t current: this.model.contents.currentPage + 1,\n\t last: this.model.contents.getLastPage() + 1\n\t }, this));\n\t $paginationControls.find('select.pages').tooltip();\n\t return $paginationControls;\n\t },\n\t\n\t /** render a subset of the entire collection (client-side pagination) */\n\t _renderSomeItems: function (models, $list) {\n\t var self = this;\n\t var views = [];\n\t $list.append(models.map(function (m) {\n\t var view = self._createItemView(m);\n\t views.push(view);\n\t return self._renderItemView$el(view);\n\t }));\n\t return views;\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** in this override, check if the contents would also display based on includeDeleted/hidden */\n\t _filterItem: function (model) {\n\t var self = this;\n\t var contents = self.model.contents;\n\t return (contents.includeHidden || !model.hidden()) && (contents.includeDeleted || !model.isDeletedOrPurged()) && _super.prototype._filterItem.call(self, model);\n\t },\n\t\n\t /** In this override, since history contents are mixed,\n\t * get the appropo view class based on history_content_type\n\t */\n\t _getItemViewClass: function (model) {\n\t var contentType = model.get(\"history_content_type\");\n\t switch (contentType) {\n\t case 'dataset':\n\t return this.HDAViewClass;\n\t case 'dataset_collection':\n\t return this.HDCAViewClass;\n\t }\n\t throw new TypeError('Unknown history_content_type: ' + contentType);\n\t },\n\t\n\t /** in this override, add a linktarget, and expand if id is in web storage */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t expanded: this.model.contents.storage.isExpanded(model.id),\n\t hasUser: this.model.ownedByCurrUser()\n\t });\n\t },\n\t\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t //TODO: send from content view: this.model.collection.storage.addExpanded\n\t // maintain a list of items whose bodies are expanded\n\t return panel.listenTo(view, {\n\t 'expanded': function (v) {\n\t panel.model.contents.storage.addExpanded(v.model);\n\t },\n\t 'collapsed': function (v) {\n\t panel.model.contents.storage.removeExpanded(v.model);\n\t }\n\t });\n\t },\n\t\n\t /** override to remove expandedIds from webstorage */\n\t collapseAll: function () {\n\t this.model.contents.storage.clearExpanded();\n\t _super.prototype.collapseAll.call(this);\n\t },\n\t\n\t // ------------------------------------------------------------------------ selection\n\t /** Override to correctly set the historyId of the new collection */\n\t getSelectedModels: function () {\n\t var collection = _super.prototype.getSelectedModels.call(this);\n\t collection.historyId = this.collection.historyId;\n\t return collection;\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .show-selectors-btn': 'toggleSelectors',\n\t 'click > .controls .prev': '_clickPrevPage',\n\t 'click > .controls .next': '_clickNextPage',\n\t 'change > .controls .pages': '_changePageSelect',\n\t // allow (error) messages to be clicked away\n\t 'click .messages [class$=message]': 'clearMessages'\n\t }),\n\t\n\t _clickPrevPage: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t this.model.contents.fetchPrevPage();\n\t },\n\t\n\t _clickNextPage: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t this.model.contents.fetchNextPage();\n\t },\n\t\n\t _changePageSelect: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t var page = $(ev.currentTarget).val();\n\t this.model.contents.fetchPage(page);\n\t },\n\t\n\t /** Toggle and store the deleted visibility and re-render items\n\t * @returns {Boolean} new setting\n\t */\n\t toggleShowDeleted: function (show, options) {\n\t show = show !== undefined ? show : !this.model.contents.includeDeleted;\n\t var self = this;\n\t var contents = self.model.contents;\n\t contents.setIncludeDeleted(show, options);\n\t self.trigger('show-deleted', show);\n\t\n\t contents.fetchCurrentPage({ renderAll: true });\n\t return show;\n\t },\n\t\n\t /** Toggle and store whether to render explicity hidden contents\n\t * @returns {Boolean} new setting\n\t */\n\t toggleShowHidden: function (show, store, options) {\n\t // console.log( 'toggleShowHidden', show, store );\n\t show = show !== undefined ? show : !this.model.contents.includeHidden;\n\t var self = this;\n\t var contents = self.model.contents;\n\t contents.setIncludeHidden(show, options);\n\t self.trigger('show-hidden', show);\n\t\n\t contents.fetchCurrentPage({ renderAll: true });\n\t return show;\n\t },\n\t\n\t /** On the first search, if there are no details - load them, then search */\n\t _firstSearch: function (searchFor) {\n\t var self = this;\n\t var inputSelector = '> .controls .search-input';\n\t this.log('onFirstSearch', searchFor);\n\t\n\t // if the contents already have enough details to search, search and return now\n\t if (self.model.contents.haveSearchDetails()) {\n\t self.searchItems(searchFor);\n\t return;\n\t }\n\t\n\t // otherwise, load the details progressively here\n\t self.$(inputSelector).searchInput('toggle-loading');\n\t // set this now so that only results will show during progress\n\t self.searchFor = searchFor;\n\t var xhr = self.model.contents.progressivelyFetchDetails({ silent: true }).progress(function (response, limit, offset) {\n\t self.renderItems();\n\t self.trigger('search:loading-progress', limit, offset);\n\t }).always(function () {\n\t self.$el.find(inputSelector).searchInput('toggle-loading');\n\t }).done(function () {\n\t self.searchItems(searchFor, 'force');\n\t });\n\t },\n\t\n\t /** clear the search filters and show all views that are normally shown */\n\t clearSearch: function (searchFor) {\n\t var self = this;\n\t if (!self.searchFor) return self;\n\t //self.log( 'onSearchClear', self );\n\t self.searchFor = '';\n\t self.trigger('search:clear', self);\n\t self.$('> .controls .search-query').val('');\n\t // NOTE: silent + render prevents collection update event with merge only\n\t // - which causes an empty page due to event handler above\n\t self.model.contents.fetchCurrentPage({ silent: true }).done(function () {\n\t self.renderItems();\n\t });\n\t return self;\n\t },\n\t\n\t // ........................................................................ error handling\n\t /** Event handler for errors (from the panel, the history, or the history's contents)\n\t * Alternately use two strings for model and xhr to use custom message and title (respectively)\n\t * @param {Model or View} model the (Backbone) source of the error\n\t * @param {XMLHTTPRequest} xhr any ajax obj. assoc. with the error\n\t * @param {Object} options the options map commonly used with bbone ajax\n\t */\n\t errorHandler: function (model, xhr, options) {\n\t //TODO: to mixin or base model\n\t // interrupted ajax or no connection\n\t if (xhr && xhr.status === 0 && xhr.readyState === 0) {\n\t // return ERROR_MODAL.offlineErrorModal();\n\t // fail silently\n\t return;\n\t }\n\t // otherwise, leave something to report in the console\n\t this.error(model, xhr, options);\n\t // and feedback to a modal\n\t // if sent two strings (and possibly details as 'options'), use those as message and title\n\t if (_.isString(model) && _.isString(xhr)) {\n\t var message = model;\n\t var title = xhr;\n\t return ERROR_MODAL.errorModal(message, title, options);\n\t }\n\t // bad gateway\n\t // TODO: possibly to global handler\n\t if (xhr && xhr.status === 502) {\n\t return ERROR_MODAL.badGatewayErrorModal();\n\t }\n\t return ERROR_MODAL.ajaxErrorModal(model, xhr, options);\n\t },\n\t\n\t /** Remove all messages from the panel. */\n\t clearMessages: function (ev) {\n\t var $target = !_.isUndefined(ev) ? $(ev.currentTarget) : this.$messages().children('[class$=\"message\"]');\n\t $target.fadeOut(this.fxSpeed, function () {\n\t $(this).remove();\n\t });\n\t return this;\n\t },\n\t\n\t // ........................................................................ scrolling\n\t /** Scrolls the panel to show the content sub-view with the given hid.\n\t * @param {Integer} hid the hid of item to scroll into view\n\t * @returns {HistoryView} the panel\n\t */\n\t scrollToHid: function (hid) {\n\t return this.scrollToItem(_.first(this.viewsWhereModel({ hid: hid })));\n\t },\n\t\n\t // ........................................................................ misc\n\t /** utility for adding -st, -nd, -rd, -th to numbers */\n\t ordinalIndicator: function (number) {\n\t var numStr = number + '';\n\t switch (numStr.charAt(numStr.length - 1)) {\n\t case '1':\n\t return numStr + 'st';\n\t case '2':\n\t return numStr + 'nd';\n\t case '3':\n\t return numStr + 'rd';\n\t default:\n\t return numStr + 'th';\n\t }\n\t },\n\t\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'HistoryView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t HistoryView.prototype.templates = function () {\n\t\n\t var mainTemplate = BASE_MVC.wrapTemplate([\n\t // temp container\n\t '
              ', '
              ', '
                ', '
                ', '
                ']);\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                ', '
                ', '
                <%- history.name %>
                ', '
                ', '
                ', '
                <%- history.nice_size %>
                ', '
                ', '
                ', '<% if( history.deleted && history.purged ){ %>', '
                ', _l('This history has been purged and deleted'), '
                ', '<% } else if( history.deleted ){ %>', '
                ', _l('This history has been deleted'), '
                ', '<% } else if( history.purged ){ %>', '
                ', _l('This history has been purged'), '
                ', '<% } %>', '<% if( history.message ){ %>',\n\t // should already be localized\n\t '
                messagesmall\">', '<%= history.message.text %>', '
                ', '<% } %>', '
                ',\n\t\n\t // add tags and annotations\n\t '
                ', '
                ', '
                ', '
                ', '
                ', '
                ', '
                ', '', '', '
                ', '
                ', '
                ', '
                ', '
                ', '
                '], 'history');\n\t\n\t var paginationTemplate = BASE_MVC.wrapTemplate(['', '', ''], 'pages');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t el: mainTemplate,\n\t controls: controlsTemplate,\n\t pagination: paginationTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HistoryView: HistoryView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 131 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(18), __webpack_require__(84), __webpack_require__(7), __webpack_require__(6), __webpack_require__(42)], __WEBPACK_AMD_DEFINE_RESULT__ = function (PopupMenu, historyCopyDialog, BASE_MVC, _l, Webhooks) {\n\t\n\t 'use strict';\n\t\n\t // ============================================================================\n\t\n\t var menu = [{\n\t html: _l('History Lists'),\n\t header: true\n\t }, {\n\t html: _l('Saved Histories'),\n\t href: 'histories/list',\n\t target: '_top'\n\t\n\t }, {\n\t html: _l('Histories Shared with Me'),\n\t href: 'histories/list_shared',\n\t target: '_top'\n\t }, {\n\t html: _l('Current History'),\n\t header: true,\n\t anon: true\n\t }, {\n\t html: _l('Create New'),\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel) {\n\t Galaxy.currHistoryPanel.createNewHistory();\n\t }\n\t }\n\t }, {\n\t html: _l('Copy History'),\n\t func: function () {\n\t historyCopyDialog(Galaxy.currHistoryPanel.model).done(function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }, {\n\t html: _l('Share or Publish'),\n\t href: 'history/sharing'\n\t }, {\n\t html: _l('Show Structure'),\n\t href: 'history/display_structured',\n\t anon: true\n\t }, {\n\t html: _l('Extract Workflow'),\n\t href: 'workflow/build_from_current_history'\n\t }, {\n\t html: _l('Delete'),\n\t anon: true,\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete the current history?'))) {\n\t galaxy_main.window.location.href = 'history/delete?id=' + Galaxy.currHistoryPanel.model.id;\n\t }\n\t }\n\t }, {\n\t html: _l('Delete Permanently'),\n\t purge: true,\n\t anon: true,\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete the current history permanently? This cannot be undone.'))) {\n\t galaxy_main.window.location.href = 'history/delete?purge=True&id=' + Galaxy.currHistoryPanel.model.id;\n\t }\n\t }\n\t }, {\n\t html: _l('Dataset Actions'),\n\t header: true,\n\t anon: true\n\t }, {\n\t html: _l('Copy Datasets'),\n\t href: 'dataset/copy_datasets'\n\t }, {\n\t html: _l('Dataset Security'),\n\t href: 'root/history_set_default_permissions'\n\t }, {\n\t html: _l('Resume Paused Jobs'),\n\t href: 'history/resume_paused_jobs?current=True',\n\t anon: true\n\t }, {\n\t html: _l('Collapse Expanded Datasets'),\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel) {\n\t Galaxy.currHistoryPanel.collapseAll();\n\t }\n\t }\n\t }, {\n\t html: _l('Unhide Hidden Datasets'),\n\t anon: true,\n\t func: function () {\n\t // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really unhide all hidden datasets?'))) {\n\t $.post(Galaxy.root + \"history/adjust_hidden\", { 'user_action': 'unhide' }, function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }\n\t }, {\n\t html: _l('Delete Hidden Datasets'),\n\t anon: true,\n\t func: function () {\n\t // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete all hidden datasets?'))) {\n\t $.post(Galaxy.root + \"history/adjust_hidden\", { 'user_action': 'delete' }, function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }\n\t }, {\n\t html: _l('Purge Deleted Datasets'),\n\t confirm: _l('Really delete all deleted datasets permanently? This cannot be undone.'),\n\t href: 'history/purge_deleted_datasets',\n\t purge: true,\n\t anon: true\n\t }, {\n\t html: _l('Downloads'),\n\t header: true\n\t }, {\n\t html: _l('Export Tool Citations'),\n\t href: 'history/citations',\n\t anon: true\n\t }, {\n\t html: _l('Export History to File'),\n\t href: 'history/export_archive?preview=True',\n\t anon: true\n\t }, {\n\t html: _l('Other Actions'),\n\t header: true\n\t }, {\n\t html: _l('Import from File'),\n\t href: 'history/import_archive'\n\t }];\n\t\n\t // Webhooks\n\t Webhooks.add({\n\t url: 'api/webhooks/history-menu/all',\n\t async: false, // (hypothetically) slows down the performance\n\t callback: function (webhooks) {\n\t var webhooks_menu = [];\n\t\n\t $.each(webhooks.models, function (index, model) {\n\t var webhook = model.toJSON();\n\t if (webhook.activate) {\n\t webhooks_menu.push({\n\t html: _l(webhook.config.title),\n\t // func: function() {},\n\t anon: true\n\t });\n\t }\n\t });\n\t\n\t if (webhooks_menu.length > 0) {\n\t webhooks_menu.unshift({\n\t html: _l('Webhooks'),\n\t header: true\n\t });\n\t $.merge(menu, webhooks_menu);\n\t }\n\t }\n\t });\n\t\n\t function buildMenu(isAnon, purgeAllowed, urlRoot) {\n\t return _.clone(menu).filter(function (menuOption) {\n\t if (isAnon && !menuOption.anon) {\n\t return false;\n\t }\n\t if (!purgeAllowed && menuOption.purge) {\n\t return false;\n\t }\n\t\n\t //TODO:?? hard-coded galaxy_main\n\t if (menuOption.href) {\n\t menuOption.href = urlRoot + menuOption.href;\n\t menuOption.target = menuOption.target || 'galaxy_main';\n\t }\n\t\n\t if (menuOption.confirm) {\n\t menuOption.func = function () {\n\t if (confirm(menuOption.confirm)) {\n\t galaxy_main.location = menuOption.href;\n\t }\n\t };\n\t }\n\t return true;\n\t });\n\t }\n\t\n\t var create = function ($button, options) {\n\t options = options || {};\n\t var isAnon = options.anonymous === undefined ? true : options.anonymous,\n\t purgeAllowed = options.purgeAllowed || false,\n\t menu = buildMenu(isAnon, purgeAllowed, Galaxy.root);\n\t //console.debug( 'menu:', menu );\n\t return new PopupMenu($button, menu);\n\t };\n\t\n\t // ============================================================================\n\t return create;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 132 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** Renders the collection uploader rows */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(41), __webpack_require__(68), __webpack_require__(21), __webpack_require__(22)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, UploadModel, UploadSettings, Popover, Select) {\n\t return Backbone.View.extend({\n\t /** Dictionary of upload states and associated icons */\n\t status_classes: {\n\t init: 'upload-icon-button fa fa-trash-o',\n\t queued: 'upload-icon fa fa-spinner fa-spin',\n\t running: 'upload-icon fa fa-spinner fa-spin',\n\t success: 'upload-icon-button fa fa-check',\n\t error: 'upload-icon-button fa fa-exclamation-triangle'\n\t },\n\t\n\t initialize: function (app, options) {\n\t var self = this;\n\t this.app = app;\n\t this.model = options.model;\n\t this.setElement(this._template(options.model));\n\t this.$mode = this.$('.upload-mode');\n\t this.$title = this.$('.upload-title-extended');\n\t this.$text = this.$('.upload-text');\n\t this.$size = this.$('.upload-size');\n\t this.$info_text = this.$('.upload-info-text');\n\t this.$info_progress = this.$('.upload-info-progress');\n\t this.$text_content = this.$('.upload-text-content');\n\t this.$symbol = this.$('.upload-symbol');\n\t this.$progress_bar = this.$('.upload-progress-bar');\n\t this.$percentage = this.$('.upload-percentage');\n\t\n\t // append popup to settings icon\n\t this.settings = new Popover.View({\n\t title: 'Upload configuration',\n\t container: this.$('.upload-settings'),\n\t placement: 'bottom'\n\t });\n\t\n\t // identify default genome and extension values\n\t var default_genome = this.app.select_genome.value();\n\t var default_extension = this.app.select_extension.value();\n\t\n\t // handle click event\n\t this.$symbol.on('click', function () {\n\t self._removeRow();\n\t });\n\t\n\t // handle text editing event\n\t this.$text_content.on('change input', function (e) {\n\t self.model.set({ 'url_paste': $(e.target).val(),\n\t 'file_size': $(e.target).val().length });\n\t });\n\t\n\t // model events\n\t this.listenTo(this.model, 'change:percentage', function () {\n\t self._refreshPercentage();\n\t });\n\t this.listenTo(this.model, 'change:status', function () {\n\t self._refreshStatus();\n\t });\n\t this.listenTo(this.model, 'change:info', function () {\n\t self._refreshInfo();\n\t });\n\t this.listenTo(this.model, 'change:file_size', function () {\n\t self._refreshFileSize();\n\t });\n\t this.listenTo(this.model, 'remove', function () {\n\t self.remove();\n\t });\n\t this.app.collection.on('reset', function () {\n\t self.remove();\n\t });\n\t },\n\t\n\t render: function () {\n\t var options = this.model.attributes;\n\t this.$title.html(_.escape(options.file_name));\n\t this.$size.html(Utils.bytesToString(options.file_size));\n\t this.$mode.removeClass().addClass('upload-mode').addClass('text-primary');\n\t if (options.file_mode == 'new') {\n\t this.$text.css({ 'width': this.$el.width() - 16 + 'px', 'top': this.$el.height() - 8 + 'px' }).show();\n\t this.$el.height(this.$el.height() - 8 + this.$text.height() + 16);\n\t this.$mode.addClass('fa fa-edit');\n\t } else if (options.file_mode == 'local') {\n\t this.$mode.addClass('fa fa-laptop');\n\t } else if (options.file_mode == 'ftp') {\n\t this.$mode.addClass('fa fa-folder-open-o');\n\t }\n\t },\n\t\n\t /** Refresh info text */\n\t _refreshInfo: function () {\n\t var info = this.model.get('info');\n\t if (info) {\n\t this.$info_text.html('Failed: ' + info).show();\n\t } else {\n\t this.$info_text.hide();\n\t }\n\t },\n\t\n\t /** Refresh percentage status */\n\t _refreshPercentage: function () {\n\t var percentage = parseInt(this.model.get('percentage'));\n\t this.$progress_bar.css({ width: percentage + '%' });\n\t this.$percentage.html(percentage != 100 ? percentage + '%' : 'Adding to history...');\n\t },\n\t\n\t /** Refresh status */\n\t _refreshStatus: function () {\n\t var status = this.model.get('status');\n\t this.$symbol.removeClass().addClass('upload-symbol').addClass(this.status_classes[status]);\n\t this.model.set('enabled', status == 'init');\n\t var enabled = this.model.get('enabled');\n\t this.$text_content.attr('disabled', !enabled);\n\t if (status == 'success') {\n\t this.$el.addClass('success');\n\t this.$percentage.html('100%');\n\t }\n\t if (status == 'error') {\n\t this.$el.addClass('danger');\n\t this.$info_progress.hide();\n\t }\n\t },\n\t\n\t /** Refresh file size */\n\t _refreshFileSize: function () {\n\t this.$size.html(Utils.bytesToString(this.model.get('file_size')));\n\t },\n\t\n\t /** Remove row */\n\t _removeRow: function () {\n\t if (['init', 'success', 'error'].indexOf(this.model.get('status')) !== -1) {\n\t this.app.collection.remove(this.model);\n\t }\n\t },\n\t\n\t /** Attach file info popup */\n\t _showSettings: function () {\n\t if (!this.settings.visible) {\n\t this.settings.empty();\n\t this.settings.append(new UploadSettings(this).$el);\n\t this.settings.show();\n\t } else {\n\t this.settings.hide();\n\t }\n\t },\n\t\n\t /** View template */\n\t _template: function (options) {\n\t return '
                ' + '' +\n '' +\n '' +\n '' +\n '' +\n '';\n },\n\n /** Template of table */\n _templateTable: function() {\n return 'Available files: ' +\n '' +\n '' +\n '  ' +\n '' +\n '' +\n '' +\n '
                ').append($checkbox)).append($('').append(parameter.title)));\n\t });\n\t this.$cover[this.model.get('enabled') && 'hide' || 'show']();\n\t }\n\t });\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 69 */,\n/* 70 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(jQuery, _) {/*\n\t galaxy upload plugins - requires FormData and XMLHttpRequest\n\t*/\n\t;(function ($) {\n\t // add event properties\n\t jQuery.event.props.push(\"dataTransfer\");\n\t\n\t /**\n\t Posts file data to the API\n\t */\n\t $.uploadpost = function (config) {\n\t // parse options\n\t var cnf = $.extend({}, {\n\t data: {},\n\t success: function () {},\n\t error: function () {},\n\t progress: function () {},\n\t url: null,\n\t maxfilesize: 2048,\n\t error_filesize: 'File exceeds 2GB. Please use a FTP client.',\n\t error_default: 'Please make sure the file is available.',\n\t error_server: 'Upload request failed.',\n\t error_login: 'Uploads require you to log in.'\n\t }, config);\n\t\n\t // link data\n\t var data = cnf.data;\n\t\n\t // check errors\n\t if (data.error_message) {\n\t cnf.error(data.error_message);\n\t return;\n\t }\n\t\n\t // construct form data\n\t var form = new FormData();\n\t for (var key in data.payload) {\n\t form.append(key, data.payload[key]);\n\t }\n\t\n\t // add files to submission\n\t var sizes = 0;\n\t for (var key in data.files) {\n\t var d = data.files[key];\n\t form.append(d.name, d.file, d.file.name);\n\t sizes += d.file.size;\n\t }\n\t\n\t // check file size, unless it's an ftp file\n\t if (sizes > 1048576 * cnf.maxfilesize) {\n\t cnf.error(cnf.error_filesize);\n\t return;\n\t }\n\t\n\t // prepare request\n\t xhr = new XMLHttpRequest();\n\t xhr.open('POST', cnf.url, true);\n\t xhr.setRequestHeader('Accept', 'application/json');\n\t xhr.setRequestHeader('Cache-Control', 'no-cache');\n\t xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n\t\n\t // captures state changes\n\t xhr.onreadystatechange = function () {\n\t // check for request completed, server connection closed\n\t if (xhr.readyState == xhr.DONE) {\n\t // parse response\n\t var response = null;\n\t if (xhr.responseText) {\n\t try {\n\t response = jQuery.parseJSON(xhr.responseText);\n\t } catch (e) {\n\t response = xhr.responseText;\n\t }\n\t }\n\t // pass any error to the error option\n\t if (xhr.status < 200 || xhr.status > 299) {\n\t var text = xhr.statusText;\n\t if (xhr.status == 403) {\n\t text = cnf.error_login;\n\t } else if (xhr.status == 0) {\n\t text = cnf.error_server;\n\t } else if (!text) {\n\t text = cnf.error_default;\n\t }\n\t cnf.error(text + ' (' + xhr.status + ')');\n\t } else {\n\t cnf.success(response);\n\t }\n\t }\n\t };\n\t\n\t // prepare upload progress\n\t xhr.upload.addEventListener('progress', function (e) {\n\t if (e.lengthComputable) {\n\t cnf.progress(Math.round(e.loaded * 100 / e.total));\n\t }\n\t }, false);\n\t\n\t // send request\n\t Galaxy.emit.debug('uploadbox::uploadpost()', 'Posting following data.', cnf);\n\t xhr.send(form);\n\t };\n\t\n\t /**\n\t Handles the upload events drag/drop etc.\n\t */\n\t $.fn.uploadinput = function (options) {\n\t // initialize\n\t var el = this;\n\t var opts = $.extend({}, {\n\t ondragover: function () {},\n\t ondragleave: function () {},\n\t onchange: function () {},\n\t multiple: false\n\t }, options);\n\t\n\t // append hidden upload field\n\t var $input = $('');\n\t el.append($input.change(function (e) {\n\t opts.onchange(e.target.files);\n\t $(this).val('');\n\t }));\n\t\n\t // drag/drop events\n\t el.on('drop', function (e) {\n\t opts.ondragleave(e);\n\t if (e.dataTransfer) {\n\t opts.onchange(e.dataTransfer.files);\n\t e.preventDefault();\n\t }\n\t });\n\t el.on('dragover', function (e) {\n\t e.preventDefault();\n\t opts.ondragover(e);\n\t });\n\t el.on('dragleave', function (e) {\n\t e.stopPropagation();\n\t opts.ondragleave(e);\n\t });\n\t\n\t // exports\n\t return {\n\t dialog: function () {\n\t $input.trigger('click');\n\t }\n\t };\n\t };\n\t\n\t /**\n\t Handles the upload queue and events such as drag/drop etc.\n\t */\n\t $.fn.uploadbox = function (options) {\n\t // parse options\n\t var opts = $.extend({}, {\n\t dragover: function () {},\n\t dragleave: function () {},\n\t announce: function (d) {},\n\t initialize: function (d) {},\n\t progress: function (d, m) {},\n\t success: function (d, m) {},\n\t error: function (d, m) {\n\t alert(m);\n\t },\n\t complete: function () {}\n\t }, options);\n\t\n\t // file queue\n\t var queue = {};\n\t\n\t // queue index/length counter\n\t var queue_index = 0;\n\t var queue_length = 0;\n\t\n\t // indicates if queue is currently running\n\t var queue_running = false;\n\t var queue_stop = false;\n\t\n\t // element\n\t var uploadinput = $(this).uploadinput({\n\t multiple: true,\n\t onchange: function (files) {\n\t add(files);\n\t },\n\t ondragover: options.ondragover,\n\t ondragleave: options.ondragleave\n\t });\n\t\n\t // add new files to upload queue\n\t function add(files) {\n\t if (files && files.length && !queue_running) {\n\t var current_index = queue_index;\n\t _.each(files, function (file, key) {\n\t if (file.mode !== 'new' && _.filter(queue, function (f) {\n\t return f.name === file.name && f.size === file.size;\n\t }).length) {\n\t file.duplicate = true;\n\t }\n\t });\n\t _.each(files, function (file) {\n\t if (!file.duplicate) {\n\t var index = String(queue_index++);\n\t queue[index] = file;\n\t opts.announce(index, queue[index]);\n\t queue_length++;\n\t }\n\t });\n\t return current_index;\n\t }\n\t }\n\t\n\t // remove file from queue\n\t function remove(index) {\n\t if (queue[index]) {\n\t delete queue[index];\n\t queue_length--;\n\t }\n\t }\n\t\n\t // process an upload, recursive\n\t function process() {\n\t // validate\n\t if (queue_length == 0 || queue_stop) {\n\t queue_stop = false;\n\t queue_running = false;\n\t opts.complete();\n\t return;\n\t } else {\n\t queue_running = true;\n\t }\n\t\n\t // get an identifier from the queue\n\t var index = -1;\n\t for (var key in queue) {\n\t index = key;\n\t break;\n\t }\n\t\n\t // get current file from queue\n\t var file = queue[index];\n\t\n\t // remove from queue\n\t remove(index);\n\t\n\t // create and submit data\n\t $.uploadpost({\n\t url: opts.url,\n\t data: opts.initialize(index),\n\t success: function (message) {\n\t opts.success(index, message);process();\n\t },\n\t error: function (message) {\n\t opts.error(index, message);process();\n\t },\n\t progress: function (percentage) {\n\t opts.progress(index, percentage);\n\t }\n\t });\n\t }\n\t\n\t /*\n\t public interface\n\t */\n\t\n\t // open file browser for selection\n\t function select() {\n\t uploadinput.dialog();\n\t }\n\t\n\t // remove all entries from queue\n\t function reset(index) {\n\t for (index in queue) {\n\t remove(index);\n\t }\n\t }\n\t\n\t // initiate upload process\n\t function start() {\n\t if (!queue_running) {\n\t queue_running = true;\n\t process();\n\t }\n\t }\n\t\n\t // stop upload process\n\t function stop() {\n\t queue_stop = true;\n\t }\n\t\n\t // set options\n\t function configure(options) {\n\t opts = $.extend({}, opts, options);\n\t return opts;\n\t }\n\t\n\t // verify browser compatibility\n\t function compatible() {\n\t return window.File && window.FormData && window.XMLHttpRequest && window.FileList;\n\t }\n\t\n\t // export functions\n\t return {\n\t 'select': select,\n\t 'add': add,\n\t 'remove': remove,\n\t 'start': start,\n\t 'stop': stop,\n\t 'reset': reset,\n\t 'configure': configure,\n\t 'compatible': compatible\n\t };\n\t };\n\t})(jQuery);\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (baseMVC, _l) {\n\t // =============================================================================\n\t /** A view on any model that has a 'annotation' attribute\n\t */\n\t var AnnotationEditor = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseMVC.HiddenUntilActivatedViewMixin).extend({\n\t\n\t tagName: 'div',\n\t className: 'annotation-display',\n\t\n\t /** Set up listeners, parse options */\n\t initialize: function (options) {\n\t options = options || {};\n\t this.tooltipConfig = options.tooltipConfig || { placement: 'bottom' };\n\t //console.debug( this, options );\n\t // only listen to the model only for changes to annotations\n\t this.listenTo(this.model, 'change:annotation', function () {\n\t this.render();\n\t });\n\t this.hiddenUntilActivated(options.$activator, options);\n\t },\n\t\n\t /** Build the DOM elements, call select to on the created input, and set up behaviors */\n\t render: function () {\n\t var view = this;\n\t this.$el.html(this._template());\n\t\n\t //TODO: handle empties better\n\t this.$annotation().make_text_editable({\n\t use_textarea: true,\n\t on_finish: function (newAnnotation) {\n\t view.$annotation().text(newAnnotation);\n\t view.model.save({ annotation: newAnnotation }, { silent: true }).fail(function () {\n\t view.$annotation().text(view.model.previous('annotation'));\n\t });\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** @returns {String} the html text used to build the view's DOM */\n\t _template: function () {\n\t var annotation = this.model.get('annotation');\n\t return [\n\t //TODO: make prompt optional\n\t '',\n\t // set up initial tags by adding as CSV to input vals (necc. to init select2)\n\t '
                ', _.escape(annotation), '
                '].join('');\n\t },\n\t\n\t /** @returns {jQuery} the main element for this view */\n\t $annotation: function () {\n\t return this.$el.find('.annotation');\n\t },\n\t\n\t /** shut down event listeners and remove this view's DOM */\n\t remove: function () {\n\t this.$annotation.off();\n\t this.stopListening(this.model);\n\t Backbone.View.prototype.remove.call(this);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return ['AnnotationEditor(', this.model + '', ')'].join('');\n\t }\n\t });\n\t // =============================================================================\n\t return {\n\t AnnotationEditor: AnnotationEditor\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 79 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(2), __webpack_require__(7)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, Backbone, BASE_MVC) {\n\t 'use strict';\n\t\n\t //=============================================================================\n\t /**\n\t * A Collection that can be limited/offset/re-ordered/filtered.\n\t * @type {Backbone.Collection}\n\t */\n\t\n\t var ControlledFetchCollection = Backbone.Collection.extend({\n\t\n\t /** call setOrder on initialization to build the comparator based on options */\n\t initialize: function (models, options) {\n\t Backbone.Collection.prototype.initialize.call(this, models, options);\n\t this.setOrder(options.order || this.order, { silent: true });\n\t },\n\t\n\t /** set up to track order changes and re-sort when changed */\n\t _setUpListeners: function () {\n\t return this.on({\n\t 'changed-order': this.sort\n\t });\n\t },\n\t\n\t /** override to provide order and offsets based on instance vars, set limit if passed,\n\t * and set allFetched/fire 'all-fetched' when xhr returns\n\t */\n\t fetch: function (options) {\n\t options = this._buildFetchOptions(options);\n\t // console.log( 'fetch options:', options );\n\t return Backbone.Collection.prototype.fetch.call(this, options);\n\t },\n\t\n\t /** build ajax data/parameters from options */\n\t _buildFetchOptions: function (options) {\n\t // note: we normally want options passed in to override the defaults built here\n\t // so most of these fns will generate defaults\n\t options = _.clone(options) || {};\n\t var self = this;\n\t\n\t // jquery ajax option; allows multiple q/qv for filters (instead of 'q[]')\n\t options.traditional = true;\n\t\n\t // options.data\n\t // we keep limit, offset, etc. in options *as well as move it into data* because:\n\t // - it makes fetch calling convenient to add it to a single options map (instead of as mult. args)\n\t // - it allows the std. event handlers (for fetch, etc.) to have access\n\t // to the pagination options too\n\t // (i.e. this.on( 'sync', function( options ){ if( options.limit ){ ... } }))\n\t // however, when we send to xhr/jquery we copy them to data also so that they become API query params\n\t options.data = options.data || self._buildFetchData(options);\n\t // console.log( 'data:', options.data );\n\t\n\t // options.data.filters --> options.data.q, options.data.qv\n\t var filters = this._buildFetchFilters(options);\n\t // console.log( 'filters:', filters );\n\t if (!_.isEmpty(filters)) {\n\t _.extend(options.data, this._fetchFiltersToAjaxData(filters));\n\t }\n\t // console.log( 'data:', options.data );\n\t return options;\n\t },\n\t\n\t /** Build the dictionary to send to fetch's XHR as data */\n\t _buildFetchData: function (options) {\n\t var defaults = {};\n\t if (this.order) {\n\t defaults.order = this.order;\n\t }\n\t return _.defaults(_.pick(options, this._fetchParams), defaults);\n\t },\n\t\n\t /** These attribute keys are valid params to fetch/API-index */\n\t _fetchParams: [\n\t /** model dependent string to control the order of models returned */\n\t 'order',\n\t /** limit the number of models returned from a fetch */\n\t 'limit',\n\t /** skip this number of models when fetching */\n\t 'offset',\n\t /** what series of attributes to return (model dependent) */\n\t 'view',\n\t /** individual keys to return for the models (see api/histories.index) */\n\t 'keys'],\n\t\n\t /** add any needed filters here based on collection state */\n\t _buildFetchFilters: function (options) {\n\t // override\n\t return _.clone(options.filters || {});\n\t },\n\t\n\t /** Convert dictionary filters to qqv style arrays */\n\t _fetchFiltersToAjaxData: function (filters) {\n\t // return as a map so ajax.data can extend from it\n\t var filterMap = {\n\t q: [],\n\t qv: []\n\t };\n\t _.each(filters, function (v, k) {\n\t // don't send if filter value is empty\n\t if (v === undefined || v === '') {\n\t return;\n\t }\n\t // json to python\n\t if (v === true) {\n\t v = 'True';\n\t }\n\t if (v === false) {\n\t v = 'False';\n\t }\n\t if (v === null) {\n\t v = 'None';\n\t }\n\t // map to k/v arrays (q/qv)\n\t filterMap.q.push(k);\n\t filterMap.qv.push(v);\n\t });\n\t return filterMap;\n\t },\n\t\n\t /** override to reset allFetched flag to false */\n\t reset: function (models, options) {\n\t this.allFetched = false;\n\t return Backbone.Collection.prototype.reset.call(this, models, options);\n\t },\n\t\n\t // ........................................................................ order\n\t order: null,\n\t\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: {\n\t 'update_time': BASE_MVC.buildComparator('update_time', { ascending: false }),\n\t 'update_time-asc': BASE_MVC.buildComparator('update_time', { ascending: true }),\n\t 'create_time': BASE_MVC.buildComparator('create_time', { ascending: false }),\n\t 'create_time-asc': BASE_MVC.buildComparator('create_time', { ascending: true })\n\t },\n\t\n\t /** set the order and comparator for this collection then sort with the new order\n\t * @event 'changed-order' passed the new order and the collection\n\t */\n\t setOrder: function (order, options) {\n\t options = options || {};\n\t var collection = this;\n\t var comparator = collection.comparators[order];\n\t if (_.isUndefined(comparator)) {\n\t throw new Error('unknown order: ' + order);\n\t }\n\t // if( _.isUndefined( comparator ) ){ return; }\n\t if (comparator === collection.comparator) {\n\t return;\n\t }\n\t\n\t var oldOrder = collection.order;\n\t collection.order = order;\n\t collection.comparator = comparator;\n\t\n\t if (!options.silent) {\n\t collection.trigger('changed-order', options);\n\t }\n\t return collection;\n\t }\n\t\n\t });\n\t\n\t //=============================================================================\n\t /**\n\t *\n\t */\n\t var PaginatedCollection = ControlledFetchCollection.extend({\n\t\n\t /** @type {Number} limit used for each page's fetch */\n\t limitPerPage: 500,\n\t\n\t initialize: function (models, options) {\n\t ControlledFetchCollection.prototype.initialize.call(this, models, options);\n\t this.currentPage = options.currentPage || 0;\n\t },\n\t\n\t getTotalItemCount: function () {\n\t return this.length;\n\t },\n\t\n\t shouldPaginate: function () {\n\t return this.getTotalItemCount() >= this.limitPerPage;\n\t },\n\t\n\t getLastPage: function () {\n\t return Math.floor(this.getTotalItemCount() / this.limitPerPage);\n\t },\n\t\n\t getPageCount: function () {\n\t return this.getLastPage() + 1;\n\t },\n\t\n\t getPageLimitOffset: function (pageNum) {\n\t pageNum = this.constrainPageNum(pageNum);\n\t return {\n\t limit: this.limitPerPage,\n\t offset: pageNum * this.limitPerPage\n\t };\n\t },\n\t\n\t constrainPageNum: function (pageNum) {\n\t return Math.max(0, Math.min(pageNum, this.getLastPage()));\n\t },\n\t\n\t /** fetch the next page of data */\n\t fetchPage: function (pageNum, options) {\n\t var self = this;\n\t pageNum = self.constrainPageNum(pageNum);\n\t self.currentPage = pageNum;\n\t options = _.defaults(options || {}, self.getPageLimitOffset(pageNum));\n\t\n\t self.trigger('fetching-more');\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-more-done');\n\t });\n\t },\n\t\n\t fetchCurrentPage: function (options) {\n\t return this.fetchPage(this.currentPage, options);\n\t },\n\t\n\t fetchPrevPage: function (options) {\n\t return this.fetchPage(this.currentPage - 1, options);\n\t },\n\t\n\t fetchNextPage: function (options) {\n\t return this.fetchPage(this.currentPage + 1, options);\n\t }\n\t });\n\t\n\t //=============================================================================\n\t /**\n\t * A Collection that will load more elements without reseting.\n\t */\n\t var InfinitelyScrollingCollection = ControlledFetchCollection.extend({\n\t\n\t /** @type {Number} limit used for the first fetch (or a reset) */\n\t limitOnFirstFetch: null,\n\t /** @type {Number} limit used for each subsequent fetch */\n\t limitPerFetch: 100,\n\t\n\t initialize: function (models, options) {\n\t ControlledFetchCollection.prototype.initialize.call(this, models, options);\n\t /** @type {Integer} number of contents to return from the first fetch */\n\t this.limitOnFirstFetch = options.limitOnFirstFetch || this.limitOnFirstFetch;\n\t /** @type {Integer} limit for every fetch after the first */\n\t this.limitPerFetch = options.limitPerFetch || this.limitPerFetch;\n\t /** @type {Boolean} are all contents fetched? */\n\t this.allFetched = false;\n\t /** @type {Integer} what was the offset of the last content returned */\n\t this.lastFetched = options.lastFetched || 0;\n\t },\n\t\n\t /** build ajax data/parameters from options */\n\t _buildFetchOptions: function (options) {\n\t // options (options for backbone.fetch and jquery.ajax generally)\n\t // backbone option; false here to make fetching an addititive process\n\t options.remove = options.remove || false;\n\t return ControlledFetchCollection.prototype._buildFetchOptions.call(this, options);\n\t },\n\t\n\t /** fetch the first 'page' of data */\n\t fetchFirst: function (options) {\n\t // console.log( 'ControlledFetchCollection.fetchFirst:', options );\n\t options = options ? _.clone(options) : {};\n\t this.allFetched = false;\n\t this.lastFetched = 0;\n\t return this.fetchMore(_.defaults(options, {\n\t reset: true,\n\t limit: this.limitOnFirstFetch\n\t }));\n\t },\n\t\n\t /** fetch the next page of data */\n\t fetchMore: function (options) {\n\t // console.log( 'ControlledFetchCollection.fetchMore:', options );\n\t options = _.clone(options || {});\n\t var collection = this;\n\t\n\t // console.log( 'fetchMore, options.reset:', options.reset );\n\t if (!options.reset && collection.allFetched) {\n\t return jQuery.when();\n\t }\n\t\n\t // TODO: this fails in the edge case where\n\t // the first fetch offset === limit (limit 4, offset 4, collection.length 4)\n\t options.offset = options.reset ? 0 : options.offset || collection.lastFetched;\n\t var limit = options.limit = options.limit || collection.limitPerFetch || null;\n\t // console.log( 'fetchMore, limit:', limit, 'offset:', options.offset );\n\t\n\t collection.trigger('fetching-more');\n\t return collection.fetch(options).always(function () {\n\t collection.trigger('fetching-more-done');\n\t })\n\t // maintain allFetched flag and trigger if all were fetched this time\n\t .done(function _postFetchMore(fetchedData) {\n\t var numFetched = _.isArray(fetchedData) ? fetchedData.length : 0;\n\t collection.lastFetched += numFetched;\n\t // console.log( 'fetchMore, lastFetched:', collection.lastFetched );\n\t // anything less than a full page means we got all there is to get\n\t if (!limit || numFetched < limit) {\n\t collection.allFetched = true;\n\t collection.trigger('all-fetched', this);\n\t }\n\t });\n\t },\n\t\n\t /** fetch all the collection */\n\t fetchAll: function (options) {\n\t // whitelist options to prevent allowing limit/offset/filters\n\t // (use vanilla fetch instead)\n\t options = options || {};\n\t var self = this;\n\t options = _.pick(options, 'silent');\n\t options.filters = {};\n\t return self.fetch(options).done(function (fetchData) {\n\t self.allFetched = true;\n\t self.trigger('all-fetched', self);\n\t });\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t ControlledFetchCollection: ControlledFetchCollection,\n\t PaginatedCollection: PaginatedCollection,\n\t InfinitelyScrollingCollection: InfinitelyScrollingCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))\n\n/***/ },\n/* 80 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n\t\n\t /* For presentation-related functionality shared across collection creators.\n\t Particularily overlapping functionality related to name processing and help.\n\t */\n\t var CollectionCreatorMixin = {\n\t\n\t /** add (or clear if clear is truthy) a validation warning to the DOM element described in what */\n\t _validationWarning: function (what, clear) {\n\t var VALIDATION_CLASS = 'validation-warning';\n\t if (what === 'name') {\n\t what = this.$('.collection-name').add(this.$('.collection-name-prompt'));\n\t this.$('.collection-name').focus().select();\n\t }\n\t if (clear) {\n\t what = what || this.$('.' + VALIDATION_CLASS);\n\t what.removeClass(VALIDATION_CLASS);\n\t } else {\n\t what.addClass(VALIDATION_CLASS);\n\t }\n\t },\n\t\n\t _changeHideOriginals: function (ev) {\n\t this.hideOriginals = this.$('.hide-originals').prop(\"checked\");\n\t },\n\t\n\t // ........................................................................ footer\n\t /** handle a collection name change */\n\t _changeName: function (ev) {\n\t this._validationWarning('name', !!this._getName());\n\t },\n\t\n\t /** check for enter key press when in the collection name and submit */\n\t _nameCheckForEnter: function (ev) {\n\t if (ev.keyCode === 13 && !this.blocking) {\n\t this._clickCreate();\n\t }\n\t },\n\t\n\t /** get the current collection name */\n\t _getName: function () {\n\t return _.escape(this.$('.collection-name').val());\n\t },\n\t\n\t // ........................................................................ header\n\t /** expand help */\n\t _clickMoreHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').addClass('expanded');\n\t this.$('.more-help').hide();\n\t },\n\t /** collapse help */\n\t _clickLessHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').removeClass('expanded');\n\t this.$('.more-help').show();\n\t },\n\t /** toggle help */\n\t _toggleHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').toggleClass('expanded');\n\t this.$('.more-help').toggle();\n\t },\n\t\n\t /** show an alert on the top of the interface containing message (alertClass is bootstrap's alert-*) */\n\t _showAlert: function (message, alertClass) {\n\t alertClass = alertClass || 'alert-danger';\n\t this.$('.main-help').hide();\n\t this.$('.header .alert').attr('class', 'alert alert-dismissable').addClass(alertClass).show().find('.alert-message').html(message);\n\t },\n\t /** hide the alerts at the top */\n\t _hideAlert: function (message) {\n\t this.$('.main-help').show();\n\t this.$('.header .alert').hide();\n\t },\n\t\n\t _cancelCreate: function (ev) {\n\t if (typeof this.oncancel === 'function') {\n\t this.oncancel.call(this);\n\t }\n\t },\n\t\n\t /** attempt to create the current collection */\n\t _clickCreate: function (ev) {\n\t var name = this._getName();\n\t if (!name) {\n\t this._validationWarning('name');\n\t } else if (!this.blocking) {\n\t this.createList(name);\n\t }\n\t },\n\t\n\t _setUpCommonSettings: function (attributes) {\n\t this.hideOriginals = attributes.defaultHideSourceItems || false;\n\t },\n\t\n\t /** render the footer, completion controls, and cancel controls */\n\t _renderFooter: function (speed, callback) {\n\t var instance = this;\n\t var $footer = this.$('.footer').empty().html(this.templates.footer());\n\t _.each(this.footerSettings, function (property, selector) {\n\t this.$(selector).prop('checked', instance[property]);\n\t });\n\t if (typeof this.oncancel === 'function') {\n\t this.$('.cancel-create.btn').show();\n\t }\n\t return $footer;\n\t },\n\t\n\t _creatorTemplates: {\n\t main: _.template(['
                ', '
                ', '
                '].join(''))\n\t }\n\t\n\t };\n\t\n\t //==============================================================================\n\t return {\n\t CollectionCreatorMixin: CollectionCreatorMixin\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 81 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(89), __webpack_require__(56), __webpack_require__(55), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_VIEW, DC_MODEL, DC_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class non-editable, read-only View/Controller for a dataset collection.\n\t */\n\t var _super = LIST_VIEW.ModelListPanel;\n\t var CollectionView = _super.extend(\n\t /** @lends CollectionView.prototype */{\n\t //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\t _logNamespace: logNamespace,\n\t\n\t className: _super.prototype.className + ' dataset-collection-panel',\n\t\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_LI.DatasetDCEListItemView,\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView,\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'elements',\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t\n\t this.hasUser = attributes.hasUser;\n\t /** A stack of panels that currently cover or hide this panel */\n\t this.panelStack = [];\n\t /** The text of the link to go back to the panel containing this one */\n\t this.parentName = attributes.parentName;\n\t /** foldout or drilldown */\n\t this.foldoutStyle = attributes.foldoutStyle || 'foldout';\n\t this.downloadUrl = this.model.attributes.url + '/download';\n\t },\n\t\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var panel = this;\n\t panel.log('_queueNewRender:', $newRender, speed);\n\t\n\t // TODO: jquery@1.12 doesn't change display when the elem has display: flex\n\t // this causes display: block for those elems after the use of show/hide animations\n\t // animations are removed from this view for now until fixed\n\t panel._swapNewRender($newRender);\n\t panel.trigger('rendered', panel);\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** In this override, use model.getVisibleContents */\n\t _filterCollection: function () {\n\t //TODO: should *not* be model.getVisibleContents - visibility is not model related\n\t return this.model.getVisibleContents();\n\t },\n\t\n\t /** override to return proper view class based on element_type */\n\t _getItemViewClass: function (model) {\n\t //this.debug( this + '._getItemViewClass:', model );\n\t //TODO: subclasses use DCEViewClass - but are currently unused - decide\n\t switch (model.get('element_type')) {\n\t case 'hda':\n\t return this.DatasetDCEViewClass;\n\t case 'dataset_collection':\n\t return this.NestedDCDCEViewClass;\n\t }\n\t throw new TypeError('Unknown element type:', model.get('element_type'));\n\t },\n\t\n\t /** override to add link target and anon */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t hasUser: this.hasUser,\n\t //TODO: could move to only nested: list:paired\n\t foldoutStyle: this.foldoutStyle\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection sub-views\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t\n\t // use pub-sub to: handle drilldown expansion and collapse\n\t panel.listenTo(view, {\n\t 'expanded:drilldown': function (v, drilldown) {\n\t this._expandDrilldownPanel(drilldown);\n\t },\n\t 'collapsed:drilldown': function (v, drilldown) {\n\t this._collapseDrilldownPanel(drilldown);\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n\t _expandDrilldownPanel: function (drilldown) {\n\t this.panelStack.push(drilldown);\n\t // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n\t this.$('> .controls').add(this.$list()).hide();\n\t drilldown.parentName = this.model.get('name');\n\t this.$el.append(drilldown.render().$el);\n\t },\n\t\n\t /** Handle drilldown close by freeing the panel and re-rendering this panel */\n\t _collapseDrilldownPanel: function (drilldown) {\n\t this.panelStack.pop();\n\t this.render();\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: {\n\t 'click .navigation .back': 'close'\n\t },\n\t\n\t /** close/remove this collection panel */\n\t close: function (event) {\n\t this.remove();\n\t this.trigger('close');\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'CollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t CollectionView.prototype.templates = function () {\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                ', '', '
                ', '
                <%- collection.name || collection.element_identifier %>
                ', '
                ', '<% if( collection.collection_type === \"list\" ){ %>', _l('a list of datasets'), '<% } else if( collection.collection_type === \"paired\" ){ %>', _l('a pair of datasets'), '<% } else if( collection.collection_type === \"list:paired\" ){ %>', _l('a list of paired datasets'), '<% } else if( collection.collection_type === \"list:list\" ){ %>', _l('a list of dataset lists'), '<% } %>', '
                ', '
                ', '
                ', '', '
                '], 'collection');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t controls: controlsTemplate\n\t });\n\t }();\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListCollectionView = CollectionView.extend(\n\t /** @lends ListCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_LI.DatasetDCEListItemView,\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var PairCollectionView = ListCollectionView.extend(\n\t /** @lends PairCollectionView.prototype */{\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListOfPairsCollectionView = CollectionView.extend(\n\t /** @lends ListOfPairsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView.extend({\n\t foldoutPanelClass: PairCollectionView\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfPairsCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a list of lists dataset collection. */\n\t var ListOfListsCollectionView = CollectionView.extend({\n\t\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView.extend({\n\t foldoutPanelClass: PairCollectionView\n\t }),\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfListsCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CollectionView: CollectionView,\n\t ListCollectionView: ListCollectionView,\n\t PairCollectionView: PairCollectionView,\n\t ListOfPairsCollectionView: ListOfPairsCollectionView,\n\t ListOfListsCollectionView: ListOfListsCollectionView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 82 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(58), __webpack_require__(65), __webpack_require__(78), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, DATASET_LI, TAGS, ANNOTATIONS, faIconButton, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI.DatasetListItemView;\n\t /** @class Editing view for DatasetAssociation.\n\t */\n\t var DatasetListItemEdit = _super.extend(\n\t /** @lends DatasetListItemEdit.prototype */{\n\t\n\t /** set up: options */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t this.hasUser = attributes.hasUser;\n\t\n\t /** allow user purge of dataset files? */\n\t this.purgeAllowed = attributes.purgeAllowed || false;\n\t\n\t //TODO: move to HiddenUntilActivatedViewMixin\n\t /** should the tags editor be shown or hidden initially? */\n\t this.tagsEditorShown = attributes.tagsEditorShown || false;\n\t /** should the tags editor be shown or hidden initially? */\n\t this.annotationEditorShown = attributes.annotationEditorShown || false;\n\t },\n\t\n\t // ......................................................................... titlebar actions\n\t /** In this override, add the other two primary actions: edit and delete */\n\t _renderPrimaryActions: function () {\n\t var actions = _super.prototype._renderPrimaryActions.call(this);\n\t if (this.model.get('state') === STATES.NOT_VIEWABLE) {\n\t return actions;\n\t }\n\t // render the display, edit attr and delete icon-buttons\n\t return _super.prototype._renderPrimaryActions.call(this).concat([this._renderEditButton(), this._renderDeleteButton()]);\n\t },\n\t\n\t //TODO: move titleButtons into state renderers, remove state checks in the buttons\n\t\n\t /** Render icon-button to edit the attributes (format, permissions, etc.) this dataset. */\n\t _renderEditButton: function () {\n\t // don't show edit while uploading, in-accessible\n\t // DO show if in error (ala previous history panel)\n\t if (this.model.get('state') === STATES.DISCARDED || !this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var purged = this.model.get('purged'),\n\t deleted = this.model.get('deleted'),\n\t editBtnData = {\n\t title: _l('Edit attributes'),\n\t href: Galaxy.root + 'datasets/edit?dataset_id=' + this.model.attributes.id,\n\t faIcon: 'fa-pencil',\n\t classes: 'edit-btn'\n\t };\n\t // disable if purged or deleted and explain why in the tooltip\n\t if (deleted || purged) {\n\t editBtnData.disabled = true;\n\t if (purged) {\n\t editBtnData.title = _l('Cannot edit attributes of datasets removed from disk');\n\t } else if (deleted) {\n\t editBtnData.title = _l('Undelete dataset to edit attributes');\n\t }\n\t\n\t // disable if still uploading or new\n\t } else if (_.contains([STATES.UPLOAD, STATES.NEW], this.model.get('state'))) {\n\t editBtnData.disabled = true;\n\t editBtnData.title = _l('This dataset is not yet editable');\n\t }\n\t return faIconButton(editBtnData);\n\t },\n\t\n\t /** Render icon-button to delete this hda. */\n\t _renderDeleteButton: function () {\n\t // don't show delete if...\n\t if (!this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var self = this,\n\t deletedAlready = this.model.isDeletedOrPurged();\n\t return faIconButton({\n\t title: !deletedAlready ? _l('Delete') : _l('Dataset is already deleted'),\n\t disabled: deletedAlready,\n\t faIcon: 'fa-times',\n\t classes: 'delete-btn',\n\t onclick: function () {\n\t // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n\t self.$el.find('.icon-btn.delete-btn').trigger('mouseout');\n\t self.model['delete']();\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... details\n\t /** In this override, add tags and annotations controls, make the ? dbkey a link to editing page */\n\t _renderDetails: function () {\n\t //TODO: generalize to be allow different details for each state\n\t var $details = _super.prototype._renderDetails.call(this),\n\t state = this.model.get('state');\n\t\n\t if (!this.model.isDeletedOrPurged() && _.contains([STATES.OK, STATES.FAILED_METADATA], state)) {\n\t this._renderTags($details);\n\t this._renderAnnotation($details);\n\t this._makeDbkeyEditLink($details);\n\t }\n\t\n\t this._setUpBehaviors($details);\n\t return $details;\n\t },\n\t\n\t /**************************************************************************\n\t * Render help button to show tool help text without rerunning the tool.\n\t * Issue #2100\n\t */\n\t _renderToolHelpButton: function () {\n\t var datasetID = this.model.attributes.dataset_id;\n\t var jobID = this.model.attributes.creating_job;\n\t var self = this;\n\t\n\t var parseToolBuild = function (data) {\n\t var helpString = '
                ';\n\t if (data.name && data.help) {\n\t helpString += 'Tool help for ' + data.name + '
                ';\n\t helpString += data.help;\n\t } else {\n\t helpString += 'Tool help is unavailable for this dataset.
                ';\n\t }\n\t helpString += '
                ';\n\t self.$el.find('.details').append($.parseHTML(helpString));\n\t };\n\t var parseToolID = function (data) {\n\t $.ajax({\n\t url: Galaxy.root + 'api/tools/' + data.tool_id + '/build'\n\t }).done(function (data) {\n\t parseToolBuild(data);\n\t }).fail(function () {\n\t parseToolBuild({});\n\t });\n\t };\n\t if (Galaxy.user.id === null) {\n\t return null;\n\t }\n\t return faIconButton({\n\t title: _l('Tool Help'),\n\t classes: 'icon-btn',\n\t href: '#',\n\t faIcon: 'fa-question',\n\t onclick: function () {\n\t var divString = 'thdiv-' + datasetID;\n\t if (self.$el.find(\".toolhelp\").length > 0) {\n\t self.$el.find(\".toolhelp\").toggle();\n\t } else {\n\t $.ajax({\n\t url: Galaxy.root + 'api/jobs/' + jobID\n\t }).done(function (data) {\n\t parseToolID(data);\n\t }).fail(function () {\n\t console.log('Failed at recovering job information from the Galaxy API for job id \"' + jobID + '\".');\n\t });\n\t }\n\t }\n\t });\n\t },\n\t //*************************************************************************\n\t\n\t /** Add less commonly used actions in the details section based on state */\n\t _renderSecondaryActions: function () {\n\t var actions = _super.prototype._renderSecondaryActions.call(this);\n\t switch (this.model.get('state')) {\n\t case STATES.UPLOAD:\n\t case STATES.NOT_VIEWABLE:\n\t return actions;\n\t case STATES.ERROR:\n\t // error button comes first\n\t actions.unshift(this._renderErrButton());\n\t return actions.concat([this._renderRerunButton(), this._renderToolHelpButton()]);\n\t case STATES.OK:\n\t case STATES.FAILED_METADATA:\n\t return actions.concat([this._renderRerunButton(), this._renderVisualizationsButton(), this._renderToolHelpButton()]);\n\t }\n\t return actions.concat([this._renderRerunButton(), this._renderToolHelpButton()]);\n\t },\n\t\n\t /** Render icon-button to report an error on this dataset to the galaxy admin. */\n\t _renderErrButton: function () {\n\t return faIconButton({\n\t title: _l('View or report this error'),\n\t href: this.model.urls.report_error,\n\t classes: 'report-error-btn',\n\t target: this.linkTarget,\n\t faIcon: 'fa-bug'\n\t });\n\t },\n\t\n\t /** Render icon-button to re-run the job that created this dataset. */\n\t _renderRerunButton: function () {\n\t var creating_job = this.model.get('creating_job');\n\t if (this.model.get('rerunnable')) {\n\t return faIconButton({\n\t title: _l('Run this job again'),\n\t href: this.model.urls.rerun,\n\t classes: 'rerun-btn',\n\t target: this.linkTarget,\n\t faIcon: 'fa-refresh',\n\t onclick: function (ev) {\n\t ev.preventDefault();\n\t Galaxy.router.push('/', { job_id: creating_job });\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Render an icon-button or popupmenu of links based on the applicable visualizations */\n\t _renderVisualizationsButton: function () {\n\t //TODO: someday - lazyload visualizations\n\t var visualizations = this.model.get('visualizations');\n\t if (this.model.isDeletedOrPurged() || !this.hasUser || !this.model.hasData() || _.isEmpty(visualizations)) {\n\t return null;\n\t }\n\t if (!_.isObject(visualizations[0])) {\n\t this.warn('Visualizations have been switched off');\n\t return null;\n\t }\n\t\n\t var $visualizations = $(this.templates.visualizations(visualizations, this));\n\t //HACK: need to re-write those directed at galaxy_main with linkTarget\n\t $visualizations.find('[target=\"galaxy_main\"]').attr('target', this.linkTarget);\n\t // use addBack here to include the root $visualizations elem (for the case of 1 visualization)\n\t this._addScratchBookFn($visualizations.find('.visualization-link').addBack('.visualization-link'));\n\t return $visualizations;\n\t },\n\t\n\t /** add scratchbook functionality to visualization links */\n\t _addScratchBookFn: function ($links) {\n\t var li = this;\n\t $links.click(function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t Galaxy.frame.add({\n\t title: 'Visualization',\n\t url: $(this).attr('href')\n\t });\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t }\n\t });\n\t },\n\t\n\t //TODO: if possible move these to readonly view - but display the owner's tags/annotation (no edit)\n\t /** Render the tags list/control */\n\t _renderTags: function ($where) {\n\t if (!this.hasUser) {\n\t return;\n\t }\n\t var view = this;\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // persist state on the hda view (and not the editor) since these are currently re-created each time\n\t onshow: function () {\n\t view.tagsEditorShown = true;\n\t },\n\t onhide: function () {\n\t view.tagsEditorShown = false;\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit dataset tags'),\n\t classes: 'tag-btn',\n\t faIcon: 'fa-tags'\n\t }).appendTo($where.find('.actions .right'))\n\t });\n\t if (this.tagsEditorShown) {\n\t this.tagsEditor.toggle(true);\n\t }\n\t },\n\t\n\t /** Render the annotation display/control */\n\t _renderAnnotation: function ($where) {\n\t if (!this.hasUser) {\n\t return;\n\t }\n\t var view = this;\n\t this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n\t model: this.model,\n\t el: $where.find('.annotation-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // persist state on the hda view (and not the editor) since these are currently re-created each time\n\t onshow: function () {\n\t view.annotationEditorShown = true;\n\t },\n\t onhide: function () {\n\t view.annotationEditorShown = false;\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit dataset annotation'),\n\t classes: 'annotate-btn',\n\t faIcon: 'fa-comment'\n\t }).appendTo($where.find('.actions .right'))\n\t });\n\t if (this.annotationEditorShown) {\n\t this.annotationEditor.toggle(true);\n\t }\n\t },\n\t\n\t /** If the format/dbkey/genome_build isn't set, make the display a link to the edit page */\n\t _makeDbkeyEditLink: function ($details) {\n\t // make the dbkey a link to editing\n\t if (this.model.get('metadata_dbkey') === '?' && !this.model.isDeletedOrPurged()) {\n\t var editableDbkey = $('?').attr('href', this.model.urls.edit).attr('target', this.linkTarget);\n\t $details.find('.dbkey .value').replaceWith(editableDbkey);\n\t }\n\t },\n\t\n\t // ......................................................................... events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .undelete-link': '_clickUndeleteLink',\n\t 'click .purge-link': '_clickPurgeLink',\n\t\n\t 'click .edit-btn': function (ev) {\n\t this.trigger('edit', this, ev);\n\t },\n\t 'click .delete-btn': function (ev) {\n\t this.trigger('delete', this, ev);\n\t },\n\t 'click .rerun-btn': function (ev) {\n\t this.trigger('rerun', this, ev);\n\t },\n\t 'click .report-err-btn': function (ev) {\n\t this.trigger('report-err', this, ev);\n\t },\n\t 'click .visualization-btn': function (ev) {\n\t this.trigger('visualize', this, ev);\n\t },\n\t 'click .dbkey a': function (ev) {\n\t this.trigger('edit', this, ev);\n\t }\n\t }),\n\t\n\t /** listener for item undelete (in the messages section) */\n\t _clickUndeleteLink: function (ev) {\n\t this.model.undelete();\n\t return false;\n\t },\n\t\n\t /** listener for item purge (in the messages section) */\n\t _clickPurgeLink: function (ev) {\n\t if (confirm(_l('This will permanently remove the data in your dataset. Are you sure?'))) {\n\t this.model.purge();\n\t }\n\t return false;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAEditView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetListItemEdit.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t failed_metadata: BASE_MVC.wrapTemplate([\n\t // in this override, provide a link to the edit page\n\t '<% if( dataset.state === \"failed_metadata\" ){ %>', '', '<% } %>'], 'dataset'),\n\t\n\t deleted: BASE_MVC.wrapTemplate([\n\t // in this override, provide links to undelete or purge the dataset\n\t '<% if( dataset.deleted && !dataset.purged ){ %>',\n\t // deleted not purged\n\t '
                ', _l('This dataset has been deleted'), '
                ', _l('Undelete it'), '', '<% if( view.purgeAllowed ){ %>', '
                ', _l('Permanently remove it from disk'), '', '<% } %>', '
                ', '<% } %>'], 'dataset')\n\t });\n\t\n\t var visualizationsTemplate = BASE_MVC.wrapTemplate(['<% if( visualizations.length === 1 ){ %>', '\"', ' target=\"<%- visualizations[0].target %>\" title=\"', _l('Visualize in'), ' <%- visualizations[0].html %>\">', '', '', '<% } else { %>', '
                ', '', '', '', '', '
                ', '<% } %>'], 'visualizations');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t visualizations: visualizationsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t DatasetListItemEdit: DatasetListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 83 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t var logNamespace = 'dataset';\n\t //==============================================================================\n\t var searchableMixin = BASE_MVC.SearchableModelMixin;\n\t /** @class base model for any DatasetAssociation (HDAs, LDDAs, DatasetCollectionDAs).\n\t * No knowledge of what type (HDA/LDDA/DCDA) should be needed here.\n\t * The DA's are made searchable (by attribute) by mixing in SearchableModelMixin.\n\t */\n\t var DatasetAssociation = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.mixin(searchableMixin, /** @lends DatasetAssociation.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t state: STATES.NEW,\n\t deleted: false,\n\t purged: false,\n\t name: '(unnamed dataset)',\n\t accessible: true,\n\t // sniffed datatype (sam, tabular, bed, etc.)\n\t data_type: '',\n\t file_ext: '',\n\t file_size: 0,\n\t\n\t // array of associated file types (eg. [ 'bam_index', ... ])\n\t meta_files: [],\n\t\n\t misc_blurb: '',\n\t misc_info: '',\n\t\n\t tags: []\n\t // do NOT default on annotation, as this default is valid and will be passed on 'save'\n\t // which is incorrect behavior when the model is only partially fetched (annos are not passed in summary data)\n\t //annotation : ''\n\t },\n\t\n\t /** instance vars and listeners */\n\t initialize: function (attributes, options) {\n\t this.debug(this + '(Dataset).initialize', attributes, options);\n\t\n\t //!! this state is not in trans.app.model.Dataset.states - set it here -\n\t if (!this.get('accessible')) {\n\t this.set('state', STATES.NOT_VIEWABLE);\n\t }\n\t\n\t /** Datasets rely/use some web controllers - have the model generate those URLs on startup */\n\t this.urls = this._generateUrls();\n\t\n\t this._setUpListeners();\n\t },\n\t\n\t /** returns misc. web urls for rendering things like re-run, display, etc. */\n\t _generateUrls: function () {\n\t var id = this.get('id');\n\t if (!id) {\n\t return {};\n\t }\n\t var urls = {\n\t 'purge': 'datasets/' + id + '/purge_async',\n\t 'display': 'datasets/' + id + '/display/?preview=True',\n\t 'edit': 'datasets/' + id + '/edit',\n\t 'download': 'datasets/' + id + '/display' + this._downloadQueryParameters(),\n\t 'report_error': 'dataset/errors?id=' + id,\n\t 'rerun': 'tool_runner/rerun?id=' + id,\n\t 'show_params': 'datasets/' + id + '/show_params',\n\t 'visualization': 'visualization',\n\t 'meta_download': 'dataset/get_metadata_file?hda_id=' + id + '&metadata_name='\n\t };\n\t _.each(urls, function (value, key) {\n\t urls[key] = Galaxy.root + value;\n\t });\n\t this.urls = urls;\n\t return urls;\n\t },\n\t\n\t _downloadQueryParameters: function () {\n\t return '?to_ext=' + this.get('file_ext');\n\t },\n\t\n\t /** set up any event listeners\n\t * event: state:ready fired when this DA moves into/is already in a ready state\n\t */\n\t _setUpListeners: function () {\n\t // if the state has changed and the new state is a ready state, fire an event\n\t this.on('change:state', function (currModel, newState) {\n\t this.log(this + ' has changed state:', currModel, newState);\n\t if (this.inReadyState()) {\n\t this.trigger('state:ready', currModel, newState, this.previous('state'));\n\t }\n\t });\n\t // the download url (currently) relies on having a correct file extension\n\t this.on('change:id change:file_ext', function (currModel) {\n\t this._generateUrls();\n\t });\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** override to add urls */\n\t toJSON: function () {\n\t var json = Backbone.Model.prototype.toJSON.call(this);\n\t //console.warn( 'returning json?' );\n\t //return json;\n\t return _.extend(json, {\n\t urls: this.urls\n\t });\n\t },\n\t\n\t /** Is this dataset deleted or purged? */\n\t isDeletedOrPurged: function () {\n\t return this.get('deleted') || this.get('purged');\n\t },\n\t\n\t /** Is this dataset in a 'ready' state; where 'Ready' states are states where no\n\t * processing (for the ds) is left to do on the server.\n\t */\n\t inReadyState: function () {\n\t var ready = _.contains(STATES.READY_STATES, this.get('state'));\n\t return this.isDeletedOrPurged() || ready;\n\t },\n\t\n\t /** Does this model already contain detailed data (as opposed to just summary level data)? */\n\t hasDetails: function () {\n\t // if it's inaccessible assume it has everything it needs\n\t if (!this.get('accessible')) {\n\t return true;\n\t }\n\t return this.has('annotation');\n\t },\n\t\n\t /** Convenience function to match dataset.has_data. */\n\t hasData: function () {\n\t return this.get('file_size') > 0;\n\t },\n\t\n\t // ........................................................................ ajax\n\t fetch: function (options) {\n\t var dataset = this;\n\t return Backbone.Model.prototype.fetch.call(this, options).always(function () {\n\t dataset._generateUrls();\n\t });\n\t },\n\t\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** override to wait by default */\n\t save: function (attrs, options) {\n\t options = options || {};\n\t options.wait = _.isUndefined(options.wait) ? true : options.wait;\n\t return Backbone.Model.prototype.save.call(this, attrs, options);\n\t },\n\t\n\t //NOTE: subclasses of DA's will need to implement url and urlRoot in order to have these work properly\n\t /** save this dataset, _Mark_ing it as deleted (just a flag) */\n\t 'delete': function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** save this dataset, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted') || this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** remove the file behind this dataset from the filesystem (if permitted) */\n\t purge: function _purge(options) {\n\t //TODO: use, override model.destroy, HDA.delete({ purge: true })\n\t if (this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t options = options || {};\n\t options.url = this.urls.purge;\n\t\n\t //TODO: ideally this would be a DELETE call to the api\n\t // using purge async for now\n\t var hda = this,\n\t xhr = jQuery.ajax(options);\n\t xhr.done(function (message, status, responseObj) {\n\t hda.set({ deleted: true, purged: true });\n\t });\n\t xhr.fail(function (xhr, status, message) {\n\t // Exception messages are hidden within error page including: '...not allowed in this Galaxy instance.'\n\t // unbury and re-add to xhr\n\t var error = _l(\"Unable to purge dataset\");\n\t var messageBuriedInUnfortunatelyFormattedError = 'Removal of datasets by users ' + 'is not allowed in this Galaxy instance';\n\t if (xhr.responseJSON && xhr.responseJSON.error) {\n\t error = xhr.responseJSON.error;\n\t } else if (xhr.responseText.indexOf(messageBuriedInUnfortunatelyFormattedError) !== -1) {\n\t error = messageBuriedInUnfortunatelyFormattedError;\n\t }\n\t xhr.responseText = error;\n\t hda.trigger('error', hda, xhr, options, _l(error), { error: error });\n\t });\n\t return xhr;\n\t },\n\t\n\t // ........................................................................ searching\n\t /** what attributes of an HDA will be used in a text search */\n\t searchAttributes: ['name', 'file_ext', 'genome_build', 'misc_blurb', 'misc_info', 'annotation', 'tags'],\n\t\n\t /** our attr keys don't often match the labels we display to the user - so, when using\n\t * attribute specifiers ('name=\"bler\"') in a term, allow passing in aliases for the\n\t * following attr keys.\n\t */\n\t searchAliases: {\n\t title: 'name',\n\t format: 'file_ext',\n\t database: 'genome_build',\n\t blurb: 'misc_blurb',\n\t description: 'misc_blurb',\n\t info: 'misc_info',\n\t tag: 'tags'\n\t },\n\t\n\t // ........................................................................ misc\n\t /** String representation */\n\t toString: function () {\n\t var nameAndId = this.get('id') || '';\n\t if (this.get('name')) {\n\t nameAndId = '\"' + this.get('name') + '\",' + nameAndId;\n\t }\n\t return 'Dataset(' + nameAndId + ')';\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection for dataset associations.\n\t */\n\t var DatasetAssociationCollection = Backbone.Collection.extend(BASE_MVC.LoggableMixin).extend(\n\t /** @lends HistoryContents.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t model: DatasetAssociation,\n\t\n\t /** root api url */\n\t urlRoot: Galaxy.root + 'api/datasets',\n\t\n\t /** url fn */\n\t url: function () {\n\t return this.urlRoot;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** Get the ids of every item in this collection\n\t * @returns array of encoded ids\n\t */\n\t ids: function () {\n\t return this.map(function (item) {\n\t return item.get('id');\n\t });\n\t },\n\t\n\t /** Get contents that are not ready\n\t * @returns array of content models\n\t */\n\t notReady: function () {\n\t return this.filter(function (content) {\n\t return !content.inReadyState();\n\t });\n\t },\n\t\n\t /** return true if any datasets don't have details */\n\t haveDetails: function () {\n\t return this.all(function (dataset) {\n\t return dataset.hasDetails();\n\t });\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** using a queue, perform ajaxFn on each of the models in this collection */\n\t ajaxQueue: function (ajaxFn, options) {\n\t var deferred = jQuery.Deferred(),\n\t startingLength = this.length,\n\t responses = [];\n\t\n\t if (!startingLength) {\n\t deferred.resolve([]);\n\t return deferred;\n\t }\n\t\n\t // use reverse order (stylistic choice)\n\t var ajaxFns = this.chain().reverse().map(function (dataset, i) {\n\t return function () {\n\t var xhr = ajaxFn.call(dataset, options);\n\t // if successful, notify using the deferred to allow tracking progress\n\t xhr.done(function (response) {\n\t deferred.notify({ curr: i, total: startingLength, response: response, model: dataset });\n\t });\n\t // (regardless of previous error or success) if not last ajax call, shift and call the next\n\t // if last fn, resolve deferred\n\t xhr.always(function (response) {\n\t responses.push(response);\n\t if (ajaxFns.length) {\n\t ajaxFns.shift()();\n\t } else {\n\t deferred.resolve(responses);\n\t }\n\t });\n\t };\n\t }).value();\n\t // start the queue\n\t ajaxFns.shift()();\n\t\n\t return deferred;\n\t },\n\t\n\t // ........................................................................ sorting/filtering\n\t /** return a new collection of datasets whose attributes contain the substring matchesWhat */\n\t matches: function (matchesWhat) {\n\t return this.filter(function (dataset) {\n\t return dataset.matches(matchesWhat);\n\t });\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetAssociationCollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DatasetAssociation: DatasetAssociation,\n\t DatasetAssociationCollection: DatasetAssociationCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 84 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(8), __webpack_require__(92), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (MODAL, ERROR_MODAL, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /**\n\t * A dialog/modal that allows copying a user history or 'importing' from user\n\t * another. Generally called via historyCopyDialog below.\n\t * @type {Object}\n\t */\n\t\n\t var CopyDialog = {\n\t\n\t // language related strings/fns\n\t defaultName: _.template(\"Copy of '<%- name %>'\"),\n\t title: _.template(_l('Copying history') + ' \"<%- name %>\"'),\n\t submitLabel: _l('Copy'),\n\t errorMessage: _l('History could not be copied.'),\n\t progressive: _l('Copying history'),\n\t activeLabel: _l('Copy only the active, non-deleted datasets'),\n\t allLabel: _l('Copy all datasets including deleted ones'),\n\t anonWarning: _l('As an anonymous user, unless you login or register, you will lose your current history ') + _l('after copying this history. '),\n\t\n\t // template for modal body\n\t _template: _.template([\n\t //TODO: remove inline styles\n\t // show a warning message for losing current to anon users\n\t '<% if( isAnon ){ %>', '
                ', '<%- anonWarning %>', _l('You can'), ' ', _l('login here'), ' ', _l('or'), ' ', ' ', _l('register here'), '.', '
                ', '<% } %>', '
                ', '
                ',\n\t // TODO: could use required here and the form validators\n\t // NOTE: use unescaped here if escaped in the modal function below\n\t '\" />', '

                ', _l('Please enter a valid history title'), '

                ',\n\t // if allowAll, add the option to copy deleted datasets, too\n\t '<% if( allowAll ){ %>', '
                ', '

                ', _l('Choose which datasets from the original history to include:'), '

                ',\n\t // copy non-deleted is the default\n\t '/>', '', '
                ', '/>', '', '<% } %>', '
                '].join('')),\n\t\n\t // empty modal body and let the user know the copy is happening\n\t _showAjaxIndicator: function _showAjaxIndicator() {\n\t var indicator = '

                ' + this.progressive + '...

                ';\n\t this.modal.$('.modal-body').empty().append(indicator).css({ 'margin-top': '8px' });\n\t },\n\t\n\t // (sorta) public interface - display the modal, render the form, and potentially copy the history\n\t // returns a jQuery.Deferred done->history copied, fail->user cancelled\n\t dialog: function _dialog(modal, history, options) {\n\t options = options || {};\n\t\n\t var dialog = this,\n\t deferred = jQuery.Deferred(),\n\t\n\t // TODO: getting a little byzantine here\n\t defaultCopyNameFn = options.nameFn || this.defaultName,\n\t defaultCopyName = defaultCopyNameFn({ name: history.get('name') }),\n\t\n\t // TODO: these two might be simpler as one 3 state option (all,active,no-choice)\n\t defaultCopyWhat = options.allDatasets ? 'copy-all' : 'copy-non-deleted',\n\t allowAll = !_.isUndefined(options.allowAll) ? options.allowAll : true,\n\t autoClose = !_.isUndefined(options.autoClose) ? options.autoClose : true;\n\t\n\t this.modal = modal;\n\t\n\t // validate the name and copy if good\n\t function checkNameAndCopy() {\n\t var name = modal.$('#copy-modal-title').val();\n\t if (!name) {\n\t modal.$('.invalid-title').show();\n\t return;\n\t }\n\t // get further settings, shut down and indicate the ajax call, then hide and resolve/reject\n\t var copyAllDatasets = modal.$('input[name=\"copy-what\"]:checked').val() === 'copy-all';\n\t modal.$('button').prop('disabled', true);\n\t dialog._showAjaxIndicator();\n\t history.copy(true, name, copyAllDatasets).done(function (response) {\n\t deferred.resolve(response);\n\t }).fail(function (xhr, status, message) {\n\t var options = { name: name, copyAllDatasets: copyAllDatasets };\n\t ERROR_MODAL.ajaxErrorModal(history, xhr, options, dialog.errorMessage);\n\t deferred.rejectWith(deferred, arguments);\n\t }).done(function () {\n\t if (autoClose) {\n\t modal.hide();\n\t }\n\t });\n\t }\n\t\n\t var originalClosingCallback = options.closing_callback;\n\t modal.show(_.extend(options, {\n\t title: this.title({ name: history.get('name') }),\n\t body: $(dialog._template({\n\t name: defaultCopyName,\n\t isAnon: Galaxy.user.isAnonymous(),\n\t allowAll: allowAll,\n\t copyWhat: defaultCopyWhat,\n\t activeLabel: this.activeLabel,\n\t allLabel: this.allLabel,\n\t anonWarning: this.anonWarning\n\t })),\n\t buttons: _.object([[_l('Cancel'), function () {\n\t modal.hide();\n\t }], [this.submitLabel, checkNameAndCopy]]),\n\t height: 'auto',\n\t closing_events: true,\n\t closing_callback: function _historyCopyClose(cancelled) {\n\t if (cancelled) {\n\t deferred.reject({ cancelled: true });\n\t }\n\t if (originalClosingCallback) {\n\t originalClosingCallback(cancelled);\n\t }\n\t }\n\t }));\n\t\n\t // set the default dataset copy, autofocus the title, and set up for a simple return\n\t modal.$('#copy-modal-title').focus().select();\n\t modal.$('#copy-modal-title').on('keydown', function (ev) {\n\t if (ev.keyCode === 13) {\n\t ev.preventDefault();\n\t checkNameAndCopy();\n\t }\n\t });\n\t\n\t return deferred;\n\t }\n\t };\n\t\n\t //==============================================================================\n\t // maintain the (slight) distinction between copy and import\n\t /**\n\t * Subclass CopyDialog to use the import language.\n\t */\n\t var ImportDialog = _.extend({}, CopyDialog, {\n\t defaultName: _.template(\"imported: <%- name %>\"),\n\t title: _.template(_l('Importing history') + ' \"<%- name %>\"'),\n\t submitLabel: _l('Import'),\n\t errorMessage: _l('History could not be imported.'),\n\t progressive: _l('Importing history'),\n\t activeLabel: _l('Import only the active, non-deleted datasets'),\n\t allLabel: _l('Import all datasets including deleted ones'),\n\t anonWarning: _l('As an anonymous user, unless you login or register, you will lose your current history ') + _l('after importing this history. ')\n\t\n\t });\n\t\n\t //==============================================================================\n\t /**\n\t * Main interface for both history import and history copy dialogs.\n\t * @param {Backbone.Model} history the history to copy\n\t * @param {Object} options a hash\n\t * @return {jQuery.Deferred} promise that fails on close and succeeds on copy\n\t *\n\t * options:\n\t * (this object is also passed to the modal used to display the dialog and accepts modal options)\n\t * {Function} nameFn if defined, use this to build the default name shown to the user\n\t * (the fn is passed: {name: })\n\t * {bool} useImport if true, use the 'import' language (instead of Copy)\n\t * {bool} allowAll if true, allow the user to choose between copying all datasets and\n\t * only non-deleted datasets\n\t * {String} allDatasets default initial checked radio button: 'copy-all' or 'copy-non-deleted',\n\t */\n\t var historyCopyDialog = function (history, options) {\n\t options = options || {};\n\t // create our own modal if Galaxy doesn't have one (mako tab without use_panels)\n\t var modal = window.parent.Galaxy.modal || new MODAL.View({});\n\t return options.useImport ? ImportDialog.dialog(modal, history, options) : CopyDialog.dialog(modal, history, options);\n\t };\n\t\n\t //==============================================================================\n\t return historyCopyDialog;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 85 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(58), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI.DatasetListItemView;\n\t /** @class Read only view for HistoryDatasetAssociation.\n\t * Since there are no controls on the HDAView to hide the dataset,\n\t * the primary thing this class does (currently) is override templates\n\t * to render the HID.\n\t */\n\t var HDAListItemView = _super.extend(\n\t /** @lends HDAListItemView.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t initialize: function (attributes, options) {\n\t _super.prototype.initialize.call(this, attributes, options);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t HDAListItemView.prototype.templates = function () {\n\t\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding the hid display to the title\n\t '
                ', '', '
                ',\n\t //TODO: remove whitespace and use margin-right\n\t '<%- dataset.hid %> ', '<%- dataset.name %>', '
                ', '
                ', '', '<% _.each(_.sortBy(_.uniq(dataset.tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>', '', '
                '], 'dataset');\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate([\n\t // add a warning when hidden\n\t '<% if( !dataset.visible ){ %>', '
                ', _l('This dataset has been hidden'), '
                ', '<% } %>'], 'dataset')\n\t });\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t titleBar: titleBarTemplate,\n\t warnings: warnings\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDAListItemView: HDAListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 86 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(83), __webpack_require__(88), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET, HISTORY_CONTENT, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET.DatasetAssociation,\n\t hcontentMixin = HISTORY_CONTENT.HistoryContentMixin;\n\t /** @class (HDA) model for a Galaxy dataset contained in and related to a history.\n\t */\n\t var HistoryDatasetAssociation = _super.extend(BASE_MVC.mixin(hcontentMixin,\n\t /** @lends HistoryDatasetAssociation.prototype */{\n\t\n\t /** default attributes for a model */\n\t defaults: _.extend({}, _super.prototype.defaults, hcontentMixin.defaults, {\n\t history_content_type: 'dataset',\n\t model_class: 'HistoryDatasetAssociation'\n\t })\n\t }));\n\t\n\t //==============================================================================\n\t return {\n\t HistoryDatasetAssociation: HistoryDatasetAssociation\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 87 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(55), __webpack_require__(81), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, DC_LI, DC_VIEW, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DC_LI.DCListItemView;\n\t /** @class Read only view for HistoryDatasetCollectionAssociation (a dataset collection inside a history).\n\t */\n\t var HDCAListItemView = _super.extend(\n\t /** @lends HDCAListItemView.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t this.listenTo(this.model, {\n\t 'change:tags change:populated change:visible': function (model, options) {\n\t this.render();\n\t }\n\t });\n\t },\n\t\n\t /** Override to provide the proper collections panels as the foldout */\n\t _getFoldoutPanelClass: function () {\n\t switch (this.model.get('collection_type')) {\n\t case 'list':\n\t return DC_VIEW.ListCollectionView;\n\t case 'paired':\n\t return DC_VIEW.PairCollectionView;\n\t case 'list:paired':\n\t return DC_VIEW.ListOfPairsCollectionView;\n\t case 'list:list':\n\t return DC_VIEW.ListOfListsCollectionView;\n\t }\n\t throw new TypeError('Uknown collection_type: ' + this.model.get('collection_type'));\n\t },\n\t\n\t /** In this override, add the state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t //TODO: model currently has no state\n\t var state = !this.model.get('populated') ? STATES.RUNNING : STATES.OK;\n\t //if( this.model.has( 'state' ) ){\n\t this.$el.addClass('state-' + state);\n\t //}\n\t return this.$el;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDCAListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t /** underscore templates */\n\t HDCAListItemView.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate([\n\t // add a warning when hidden\n\t '<% if( !collection.visible ){ %>', '
                ', _l('This collection has been hidden'), '
                ', '<% } %>'], 'collection')\n\t });\n\t\n\t // could steal this from hda-base (or use mixed content)\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding the hid display to the title\n\t '
                ', '', '
                ',\n\t //TODO: remove whitespace and use margin-right\n\t '<%- collection.hid %> ', '<%- collection.name %>', '
                ', '
                ', '', '<% _.each(_.sortBy(_.uniq(collection.tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>', '', '
                '], 'collection');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDCAListItemView: HDCAListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 88 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /** @class Mixin for HistoryContents content (HDAs, HDCAs).\n\t */\n\t\n\t var HistoryContentMixin = {\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t /** parent (containing) history */\n\t history_id: null,\n\t /** some content_type (HistoryContents can contain mixed model classes) */\n\t history_content_type: null,\n\t /** indicating when/what order the content was generated in the context of the history */\n\t hid: null,\n\t /** whether the user wants the content shown (visible) */\n\t visible: true\n\t },\n\t\n\t // ........................................................................ mixed content element\n\t // In order to be part of a MIXED bbone collection, we can't rely on the id\n\t // (which may collide btwn models of different classes)\n\t // Instead, use type_id which prefixes the history_content_type so the bbone collection can differentiate\n\t idAttribute: 'type_id',\n\t\n\t // ........................................................................ common queries\n\t /** the more common alias of visible */\n\t hidden: function () {\n\t return !this.get('visible');\n\t },\n\t\n\t //TODO: remove\n\t /** based on includeDeleted, includeHidden (gen. from the container control),\n\t * would this ds show in the list of ds's?\n\t * @param {Boolean} includeDeleted are we showing deleted hdas?\n\t * @param {Boolean} includeHidden are we showing hidden hdas?\n\t */\n\t isVisible: function (includeDeleted, includeHidden) {\n\t var isVisible = true;\n\t if (!includeDeleted && (this.get('deleted') || this.get('purged'))) {\n\t isVisible = false;\n\t }\n\t if (!includeHidden && !this.get('visible')) {\n\t isVisible = false;\n\t }\n\t return isVisible;\n\t },\n\t\n\t // ........................................................................ ajax\n\t //TODO?: these are probably better done on the leaf classes\n\t /** history content goes through the 'api/histories' API */\n\t urlRoot: Galaxy.root + 'api/histories/',\n\t\n\t /** full url spec. for this content */\n\t url: function () {\n\t var url = this.urlRoot + this.get('history_id') + '/contents/' + this.get('history_content_type') + 's/' + this.get('id');\n\t return url;\n\t },\n\t\n\t /** save this content as not visible */\n\t hide: function (options) {\n\t if (!this.get('visible')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ visible: false }, options);\n\t },\n\t /** save this content as visible */\n\t unhide: function (options) {\n\t if (this.get('visible')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ visible: true }, options);\n\t },\n\t\n\t // ........................................................................ misc\n\t toString: function () {\n\t return [this.get('type_id'), this.get('hid'), this.get('name')].join(':');\n\t }\n\t };\n\t\n\t //==============================================================================\n\t return {\n\t HistoryContentMixin: HistoryContentMixin\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))\n\n/***/ },\n/* 89 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(147), __webpack_require__(7), __webpack_require__(6), __webpack_require__(96)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, LoadingIndicator, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'list';\n\t /* ============================================================================\n\t TODO:\n\t \n\t ============================================================================ */\n\t /** @class View for a list/collection of models and the sub-views of those models.\n\t * Sub-views must (at least have the interface if not) inherit from ListItemView.\n\t * (For a list panel that also includes some 'container' model (History->HistoryContents)\n\t * use ModelWithListPanel)\n\t *\n\t * Allows for:\n\t * searching collection/sub-views\n\t * selecting/multi-selecting sub-views\n\t *\n\t * Currently used:\n\t * for dataset/dataset-choice\n\t * as superclass of ModelListPanel\n\t */\n\t var ListPanel = Backbone.View.extend(BASE_MVC.LoggableMixin).extend( /** @lends ListPanel.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t /** class to use for constructing the sub-views */\n\t viewClass: LIST_ITEM.ListItemView,\n\t /** class to used for constructing collection of sub-view models */\n\t collectionClass: Backbone.Collection,\n\t\n\t tagName: 'div',\n\t className: 'list-panel',\n\t\n\t /** (in ms) that jquery effects will use */\n\t fxSpeed: 'fast',\n\t\n\t /** string to display when the collection has no contents */\n\t emptyMsg: _l('This list is empty'),\n\t /** displayed when no items match the search terms */\n\t noneFoundMsg: _l('No matching items found'),\n\t /** string used for search placeholder */\n\t searchPlaceholder: _l('search'),\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the list\n\t */\n\t initialize: function (attributes, options) {\n\t attributes = attributes || {};\n\t // set the logger if requested\n\t if (attributes.logger) {\n\t this.logger = attributes.logger;\n\t }\n\t this.log(this + '.initialize:', attributes);\n\t\n\t // ---- instance vars\n\t /** how quickly should jquery fx run? */\n\t this.fxSpeed = _.has(attributes, 'fxSpeed') ? attributes.fxSpeed : this.fxSpeed;\n\t\n\t /** filters for displaying subviews */\n\t this.filters = [];\n\t /** current search terms */\n\t this.searchFor = attributes.searchFor || '';\n\t\n\t /** loading indicator */\n\t // this.indicator = new LoadingIndicator( this.$el );\n\t\n\t /** currently showing selectors on items? */\n\t this.selecting = attributes.selecting !== undefined ? attributes.selecting : true;\n\t //this.selecting = false;\n\t\n\t /** cached selected item.model.ids to persist btwn renders */\n\t this.selected = attributes.selected || [];\n\t /** the last selected item.model.id */\n\t this.lastSelected = null;\n\t\n\t /** are sub-views draggable */\n\t this.dragItems = attributes.dragItems || false;\n\t\n\t /** list item view class (when passed models) */\n\t this.viewClass = attributes.viewClass || this.viewClass;\n\t\n\t /** list item views */\n\t this.views = [];\n\t /** list item models */\n\t this.collection = attributes.collection || this._createDefaultCollection();\n\t\n\t /** filter fns run over collection items to see if they should show in the list */\n\t this.filters = attributes.filters || [];\n\t\n\t /** override $scrollContainer fn via attributes - fn should return jq for elem to call scrollTo on */\n\t this.$scrollContainer = attributes.$scrollContainer || this.$scrollContainer;\n\t\n\t /** @type {String} generic title */\n\t this.title = attributes.title || '';\n\t /** @type {String} generic subtitle */\n\t this.subtitle = attributes.subtitle || '';\n\t\n\t this._setUpListeners();\n\t },\n\t\n\t // ------------------------------------------------------------------------ listeners\n\t /** create any event listeners for the list */\n\t _setUpListeners: function () {\n\t this.off();\n\t\n\t //TODO: move errorHandler down into list-view from history-view or\n\t // pass to global error handler (Galaxy)\n\t this.on({\n\t error: function (model, xhr, options, msg, details) {\n\t //this.errorHandler( model, xhr, options, msg, details );\n\t console.error(model, xhr, options, msg, details);\n\t },\n\t // show hide the loading indicator\n\t loading: function () {\n\t this._showLoadingIndicator('loading...', 40);\n\t },\n\t 'loading-done': function () {\n\t this._hideLoadingIndicator(40);\n\t }\n\t });\n\t\n\t // throw the first render up as a diff namespace using once (for outside consumption)\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this._setUpCollectionListeners();\n\t this._setUpViewListeners();\n\t return this;\n\t },\n\t\n\t /** create and return a collection for when none is initially passed */\n\t _createDefaultCollection: function () {\n\t // override\n\t return new this.collectionClass([]);\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t this.log(this + '._setUpCollectionListeners', this.collection);\n\t this.stopListening(this.collection);\n\t\n\t // bubble up error events\n\t this.listenTo(this.collection, {\n\t error: function (model, xhr, options, msg, details) {\n\t this.trigger('error', model, xhr, options, msg, details);\n\t },\n\t update: function (collection, options) {\n\t var changes = options.changes;\n\t // console.info( collection + ', update:', changes, '\\noptions:', options );\n\t // more than one: render everything\n\t if (options.renderAll || changes.added.length + changes.removed.length > 1) {\n\t return this.renderItems();\n\t }\n\t // otherwise, let the single add/remove handlers do it\n\t if (changes.added.length === 1) {\n\t return this.addItemView(_.first(changes.added), collection, options);\n\t }\n\t if (changes.removed.length === 1) {\n\t return this.removeItemView(_.first(changes.removed), collection, options);\n\t }\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** listening for sub-view events that bubble up with the 'view:' prefix */\n\t _setUpViewListeners: function () {\n\t this.log(this + '._setUpViewListeners');\n\t\n\t // shift to select a range\n\t this.on({\n\t 'view:selected': function (view, ev) {\n\t if (ev && ev.shiftKey && this.lastSelected) {\n\t var lastSelectedView = this.viewFromModelId(this.lastSelected);\n\t if (lastSelectedView) {\n\t this.selectRange(view, lastSelectedView);\n\t }\n\t } else if (ev && ev.altKey && !this.selecting) {\n\t this.showSelectors();\n\t }\n\t this.selected.push(view.model.id);\n\t this.lastSelected = view.model.id;\n\t },\n\t\n\t 'view:de-selected': function (view, ev) {\n\t this.selected = _.without(this.selected, view.model.id);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t /** Render this content, set up ui.\n\t * @param {Number or String} speed the speed of the render\n\t */\n\t render: function (speed) {\n\t this.log(this + '.render', speed);\n\t var $newRender = this._buildNewRender();\n\t this._setUpBehaviors($newRender);\n\t this._queueNewRender($newRender, speed);\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el. */\n\t _buildNewRender: function () {\n\t this.debug(this + '(ListPanel)._buildNewRender');\n\t var $newRender = $(this.templates.el({}, this));\n\t this._renderControls($newRender);\n\t this._renderTitle($newRender);\n\t this._renderSubtitle($newRender);\n\t this._renderSearch($newRender);\n\t this.renderItems($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el. */\n\t _renderControls: function ($newRender) {\n\t this.debug(this + '(ListPanel)._renderControls');\n\t var $controls = $(this.templates.controls({}, this));\n\t $newRender.find('.controls').replaceWith($controls);\n\t return $controls;\n\t },\n\t\n\t /** return a jQuery object containing the title DOM */\n\t _renderTitle: function ($where) {\n\t //$where = $where || this.$el;\n\t //$where.find( '.title' ).replaceWith( ... )\n\t },\n\t\n\t /** return a jQuery object containing the subtitle DOM (if any) */\n\t _renderSubtitle: function ($where) {\n\t //$where = $where || this.$el;\n\t //$where.find( '.title' ).replaceWith( ... )\n\t },\n\t\n\t /** Fade out the old el, swap in the new contents, then fade in.\n\t * @param {Number or String} speed jq speed to use for rendering effects\n\t * @fires rendered when rendered\n\t */\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var panel = this;\n\t panel.log('_queueNewRender:', $newRender, speed);\n\t\n\t $(panel).queue('fx', [function (next) {\n\t panel.$el.fadeOut(speed, next);\n\t }, function (next) {\n\t panel._swapNewRender($newRender);\n\t next();\n\t }, function (next) {\n\t panel.$el.fadeIn(speed, next);\n\t }, function (next) {\n\t panel.trigger('rendered', panel);\n\t next();\n\t }]);\n\t },\n\t\n\t /** empty out the current el, move the $newRender's children in */\n\t _swapNewRender: function ($newRender) {\n\t this.$el.empty().attr('class', this.className).append($newRender.children());\n\t if (this.selecting) {\n\t this.showSelectors(0);\n\t }\n\t return this;\n\t },\n\t\n\t /** Set up any behaviors, handlers (ep. plugins) that need to be called when the entire view has been built but\n\t * not attached to the page yet.\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t this.$controls($where).find('[title]').tooltip();\n\t // set up the pupup for actions available when multi selecting\n\t this._renderMultiselectActionMenu($where);\n\t return this;\n\t },\n\t\n\t /** render a menu containing the actions available to sets of selected items */\n\t _renderMultiselectActionMenu: function ($where) {\n\t $where = $where || this.$el;\n\t var $menu = $where.find('.list-action-menu'),\n\t actions = this.multiselectActions();\n\t if (!actions.length) {\n\t return $menu.empty();\n\t }\n\t\n\t var $newMenu = $(['
                ', '', '
                  ', '
                ', '
                '].join(''));\n\t var $actions = actions.map(function (action) {\n\t var html = ['
              • ', action.html, '
              • '].join('');\n\t return $(html).click(function (ev) {\n\t ev.preventDefault();\n\t return action.func(ev);\n\t });\n\t });\n\t $newMenu.find('ul').append($actions);\n\t $menu.replaceWith($newMenu);\n\t return $newMenu;\n\t },\n\t\n\t /** return a list of plain objects used to render multiselect actions menu. Each object should have:\n\t * html: an html string used as the anchor contents\n\t * func: a function called when the anchor is clicked (passed the click event)\n\t */\n\t multiselectActions: function () {\n\t return [];\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-$element shortcuts\n\t /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n\t $scrollContainer: function ($where) {\n\t // override or set via attributes.$scrollContainer\n\t return ($where || this.$el).parent().parent();\n\t },\n\t /** convenience selector for the section that displays the list controls */\n\t $controls: function ($where) {\n\t return ($where || this.$el).find('> .controls');\n\t },\n\t /** list-items: where the subviews are contained in the view's dom */\n\t $list: function ($where) {\n\t return ($where || this.$el).find('> .list-items');\n\t },\n\t /** container where list messages are attached */\n\t $messages: function ($where) {\n\t //TODO: controls isn't really correct here (only for ModelListPanel)\n\t return ($where || this.$el).find('> .controls .messages');\n\t },\n\t /** the message displayed when no views can be shown (no views, none matching search) */\n\t $emptyMessage: function ($where) {\n\t return ($where || this.$el).find('> .empty-message');\n\t },\n\t\n\t // ------------------------------------------------------------------------ hda sub-views\n\t /** render the subviews for the list's collection */\n\t renderItems: function ($whereTo) {\n\t $whereTo = $whereTo || this.$el;\n\t var panel = this;\n\t panel.log(this + '.renderItems', $whereTo);\n\t\n\t var $list = panel.$list($whereTo);\n\t panel.freeViews();\n\t // console.log( 'views freed' );\n\t //TODO:? cache and re-use views?\n\t var shownModels = panel._filterCollection();\n\t // console.log( 'models filtered:', shownModels );\n\t\n\t panel.views = shownModels.map(function (itemModel) {\n\t var view = panel._createItemView(itemModel);\n\t return view;\n\t });\n\t\n\t $list.empty();\n\t // console.log( 'list emptied' );\n\t if (panel.views.length) {\n\t panel._attachItems($whereTo);\n\t // console.log( 'items attached' );\n\t }\n\t panel._renderEmptyMessage($whereTo).toggle(!panel.views.length);\n\t panel.trigger('views:ready', panel.views);\n\t\n\t // console.log( '------------------------------------------- rendering items' );\n\t return panel.views;\n\t },\n\t\n\t /** Filter the collection to only those models that should be currently viewed */\n\t _filterCollection: function () {\n\t // override this\n\t var panel = this;\n\t return panel.collection.filter(_.bind(panel._filterItem, panel));\n\t },\n\t\n\t /** Should the model be viewable in the current state?\n\t * Checks against this.filters and this.searchFor\n\t */\n\t _filterItem: function (model) {\n\t // override this\n\t var panel = this;\n\t return _.every(panel.filters.map(function (fn) {\n\t return fn.call(model);\n\t })) && (!panel.searchFor || model.matchesAll(panel.searchFor));\n\t },\n\t\n\t /** Create a view for a model and set up it's listeners */\n\t _createItemView: function (model) {\n\t var ViewClass = this._getItemViewClass(model);\n\t var options = _.extend(this._getItemViewOptions(model), {\n\t model: model\n\t });\n\t var view = new ViewClass(options);\n\t this._setUpItemViewListeners(view);\n\t return view;\n\t },\n\t\n\t /** Free a view for a model. Note: does not remove it from the DOM */\n\t _destroyItemView: function (view) {\n\t this.stopListening(view);\n\t this.views = _.without(this.views, view);\n\t },\n\t\n\t _destroyItemViews: function (view) {\n\t var self = this;\n\t self.views.forEach(function (v) {\n\t self.stopListening(v);\n\t });\n\t self.views = [];\n\t return self;\n\t },\n\t\n\t /** free any sub-views the list has */\n\t freeViews: function () {\n\t return this._destroyItemViews();\n\t },\n\t\n\t /** Get the bbone view class based on the model */\n\t _getItemViewClass: function (model) {\n\t // override this\n\t return this.viewClass;\n\t },\n\t\n\t /** Get the options passed to the new view based on the model */\n\t _getItemViewOptions: function (model) {\n\t // override this\n\t return {\n\t //logger : this.logger,\n\t fxSpeed: this.fxSpeed,\n\t expanded: false,\n\t selectable: this.selecting,\n\t selected: _.contains(this.selected, model.id),\n\t draggable: this.dragItems\n\t };\n\t },\n\t\n\t /** Set up listeners for new models */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t // send all events to the panel, re-namspaceing them with the view prefix\n\t this.listenTo(view, 'all', function () {\n\t var args = Array.prototype.slice.call(arguments, 0);\n\t args[0] = 'view:' + args[0];\n\t panel.trigger.apply(panel, args);\n\t });\n\t\n\t // drag multiple - hijack ev.setData to add all selected items\n\t this.listenTo(view, 'draggable:dragstart', function (ev, v) {\n\t //TODO: set multiple drag data here\n\t var json = {},\n\t selected = this.getSelectedModels();\n\t if (selected.length) {\n\t json = selected.toJSON();\n\t } else {\n\t json = [v.model.toJSON()];\n\t }\n\t ev.dataTransfer.setData('text', JSON.stringify(json));\n\t //ev.dataTransfer.setDragImage( v.el, 60, 60 );\n\t }, this);\n\t\n\t return panel;\n\t },\n\t\n\t /** Attach views in this.views to the model based on $whereTo */\n\t _attachItems: function ($whereTo) {\n\t var self = this;\n\t // console.log( '_attachItems:', $whereTo, this.$list( $whereTo ) );\n\t //ASSUMES: $list has been emptied\n\t this.$list($whereTo).append(this.views.map(function (view) {\n\t return self._renderItemView$el(view);\n\t }));\n\t return this;\n\t },\n\t\n\t /** get a given subview's $el (or whatever may wrap it) and return it */\n\t _renderItemView$el: function (view) {\n\t // useful to wrap and override\n\t return view.render(0).$el;\n\t },\n\t\n\t /** render the empty/none-found message */\n\t _renderEmptyMessage: function ($whereTo) {\n\t this.debug('_renderEmptyMessage', $whereTo, this.searchFor);\n\t var text = this.searchFor ? this.noneFoundMsg : this.emptyMsg;\n\t return this.$emptyMessage($whereTo).text(text);\n\t },\n\t\n\t /** expand all item views */\n\t expandAll: function () {\n\t _.each(this.views, function (view) {\n\t view.expand();\n\t });\n\t },\n\t\n\t /** collapse all item views */\n\t collapseAll: function () {\n\t _.each(this.views, function (view) {\n\t view.collapse();\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection/views syncing\n\t /** Add a view (if the model should be viewable) to the panel */\n\t addItemView: function (model, collection, options) {\n\t // console.log( this + '.addItemView:', model );\n\t var panel = this;\n\t // get the index of the model in the list of filtered models shown by this list\n\t // in order to insert the view in the proper place\n\t //TODO:? potentially expensive\n\t var modelIndex = panel._filterCollection().indexOf(model);\n\t if (modelIndex === -1) {\n\t return undefined;\n\t }\n\t var view = panel._createItemView(model);\n\t // console.log( 'adding and rendering:', modelIndex, view.toString() );\n\t\n\t $(view).queue('fx', [function (next) {\n\t // hide the empty message first if only view\n\t if (panel.$emptyMessage().is(':visible')) {\n\t panel.$emptyMessage().fadeOut(panel.fxSpeed, next);\n\t } else {\n\t next();\n\t }\n\t }, function (next) {\n\t panel._attachView(view, modelIndex);\n\t next();\n\t }]);\n\t return view;\n\t },\n\t\n\t /** internal fn to add view (to both panel.views and panel.$list) */\n\t _attachView: function (view, modelIndex, useFx) {\n\t // console.log( this + '._attachView:', view, modelIndex, useFx );\n\t useFx = _.isUndefined(useFx) ? true : useFx;\n\t modelIndex = modelIndex || 0;\n\t var panel = this;\n\t\n\t // use the modelIndex to splice into views and insert at the proper index in the DOM\n\t panel.views.splice(modelIndex, 0, view);\n\t panel._insertIntoListAt(modelIndex, panel._renderItemView$el(view).hide());\n\t\n\t panel.trigger('view:attached', view);\n\t if (useFx) {\n\t view.$el.slideDown(panel.fxSpeed, function () {\n\t panel.trigger('view:attached:rendered');\n\t });\n\t } else {\n\t view.$el.show();\n\t panel.trigger('view:attached:rendered');\n\t }\n\t return view;\n\t },\n\t\n\t /** insert a jq object as a child of list-items at the specified *DOM index* */\n\t _insertIntoListAt: function (index, $what) {\n\t // console.log( this + '._insertIntoListAt:', index, $what );\n\t var $list = this.$list();\n\t if (index === 0) {\n\t $list.prepend($what);\n\t } else {\n\t $list.children().eq(index - 1).after($what);\n\t }\n\t return $what;\n\t },\n\t\n\t /** Remove a view from the panel (if found) */\n\t removeItemView: function (model, collection, options) {\n\t var panel = this;\n\t var view = _.find(panel.views, function (v) {\n\t return v.model === model;\n\t });\n\t if (!view) {\n\t return undefined;\n\t }\n\t panel.views = _.without(panel.views, view);\n\t panel.trigger('view:removed', view);\n\t\n\t // potentially show the empty message if no views left\n\t // use anonymous queue here - since remove can happen multiple times\n\t $({}).queue('fx', [function (next) {\n\t view.$el.fadeOut(panel.fxSpeed, next);\n\t }, function (next) {\n\t view.remove();\n\t panel.trigger('view:removed:rendered');\n\t if (!panel.views.length) {\n\t panel._renderEmptyMessage().fadeIn(panel.fxSpeed, next);\n\t } else {\n\t next();\n\t }\n\t }]);\n\t return view;\n\t },\n\t\n\t /** get views based on model.id */\n\t viewFromModelId: function (id) {\n\t return _.find(this.views, function (v) {\n\t return v.model.id === id;\n\t });\n\t },\n\t\n\t /** get views based on model */\n\t viewFromModel: function (model) {\n\t return model ? this.viewFromModelId(model.id) : undefined;\n\t },\n\t\n\t /** get views based on model properties */\n\t viewsWhereModel: function (properties) {\n\t return this.views.filter(function (view) {\n\t return _.isMatch(view.model.attributes, properties);\n\t });\n\t },\n\t\n\t /** A range of views between (and including) viewA and viewB */\n\t viewRange: function (viewA, viewB) {\n\t if (viewA === viewB) {\n\t return viewA ? [viewA] : [];\n\t }\n\t\n\t var indexA = this.views.indexOf(viewA),\n\t indexB = this.views.indexOf(viewB);\n\t\n\t // handle not found\n\t if (indexA === -1 || indexB === -1) {\n\t if (indexA === indexB) {\n\t return [];\n\t }\n\t return indexA === -1 ? [viewB] : [viewA];\n\t }\n\t // reverse if indeces are\n\t //note: end inclusive\n\t return indexA < indexB ? this.views.slice(indexA, indexB + 1) : this.views.slice(indexB, indexA + 1);\n\t },\n\t\n\t // ------------------------------------------------------------------------ searching\n\t /** render a search input for filtering datasets shown\n\t * (see SearchableMixin in base-mvc for implementation of the actual searching)\n\t * return will start the search\n\t * esc will clear the search\n\t * clicking the clear button will clear the search\n\t * uses searchInput in ui.js\n\t */\n\t _renderSearch: function ($where) {\n\t $where.find('.controls .search-input').searchInput({\n\t placeholder: this.searchPlaceholder,\n\t initialVal: this.searchFor,\n\t onfirstsearch: _.bind(this._firstSearch, this),\n\t onsearch: _.bind(this.searchItems, this),\n\t onclear: _.bind(this.clearSearch, this)\n\t });\n\t return $where;\n\t },\n\t\n\t /** What to do on the first search entered */\n\t _firstSearch: function (searchFor) {\n\t // override to load model details if necc.\n\t this.log('onFirstSearch', searchFor);\n\t return this.searchItems(searchFor);\n\t },\n\t\n\t /** filter view list to those that contain the searchFor terms */\n\t searchItems: function (searchFor, force) {\n\t this.log('searchItems', searchFor, this.searchFor, force);\n\t if (!force && this.searchFor === searchFor) {\n\t return this;\n\t }\n\t this.searchFor = searchFor;\n\t this.renderItems();\n\t this.trigger('search:searching', searchFor, this);\n\t var $search = this.$('> .controls .search-query');\n\t if ($search.val() !== searchFor) {\n\t $search.val(searchFor);\n\t }\n\t return this;\n\t },\n\t\n\t /** clear the search filters and show all views that are normally shown */\n\t clearSearch: function (searchFor) {\n\t //this.log( 'onSearchClear', this );\n\t this.searchFor = '';\n\t this.trigger('search:clear', this);\n\t this.$('> .controls .search-query').val('');\n\t this.renderItems();\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ selection\n\t /** @type Integer when the number of list item views is >= to this, don't animate selectors */\n\t THROTTLE_SELECTOR_FX_AT: 20,\n\t\n\t /** show selectors on all visible itemViews and associated controls */\n\t showSelectors: function (speed) {\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t this.selecting = true;\n\t this.$('.list-actions').slideDown(speed);\n\t speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT ? 0 : speed;\n\t _.each(this.views, function (view) {\n\t view.showSelector(speed);\n\t });\n\t //this.selected = [];\n\t //this.lastSelected = null;\n\t },\n\t\n\t /** hide selectors on all visible itemViews and associated controls */\n\t hideSelectors: function (speed) {\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t this.selecting = false;\n\t this.$('.list-actions').slideUp(speed);\n\t speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT ? 0 : speed;\n\t _.each(this.views, function (view) {\n\t view.hideSelector(speed);\n\t });\n\t this.selected = [];\n\t this.lastSelected = null;\n\t },\n\t\n\t /** show or hide selectors on all visible itemViews and associated controls */\n\t toggleSelectors: function () {\n\t if (!this.selecting) {\n\t this.showSelectors();\n\t } else {\n\t this.hideSelectors();\n\t }\n\t },\n\t\n\t /** select all visible items */\n\t selectAll: function (event) {\n\t _.each(this.views, function (view) {\n\t view.select(event);\n\t });\n\t },\n\t\n\t /** deselect all visible items */\n\t deselectAll: function (event) {\n\t this.lastSelected = null;\n\t _.each(this.views, function (view) {\n\t view.deselect(event);\n\t });\n\t },\n\t\n\t /** select a range of datasets between A and B */\n\t selectRange: function (viewA, viewB) {\n\t var range = this.viewRange(viewA, viewB);\n\t _.each(range, function (view) {\n\t view.select();\n\t });\n\t return range;\n\t },\n\t\n\t /** return an array of all currently selected itemViews */\n\t getSelectedViews: function () {\n\t return _.filter(this.views, function (v) {\n\t return v.selected;\n\t });\n\t },\n\t\n\t /** return a collection of the models of all currenly selected items */\n\t getSelectedModels: function () {\n\t // console.log( '(getSelectedModels)' );\n\t return new this.collection.constructor(_.map(this.getSelectedViews(), function (view) {\n\t return view.model;\n\t }));\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading indicator\n\t /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n\t _showLoadingIndicator: function (msg, speed, callback) {\n\t this.debug('_showLoadingIndicator', this.indicator, msg, speed, callback);\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t if (!this.indicator) {\n\t this.indicator = new LoadingIndicator(this.$el);\n\t this.debug('\\t created', this.indicator);\n\t }\n\t if (!this.$el.is(':visible')) {\n\t this.indicator.show(0, callback);\n\t } else {\n\t this.$el.fadeOut(speed);\n\t this.indicator.show(msg, speed, callback);\n\t }\n\t },\n\t\n\t /** hide the loading indicator */\n\t _hideLoadingIndicator: function (speed, callback) {\n\t this.debug('_hideLoadingIndicator', this.indicator, speed, callback);\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t if (this.indicator) {\n\t this.indicator.hide(speed, callback);\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ scrolling\n\t /** get the current scroll position of the panel in its parent */\n\t scrollPosition: function () {\n\t return this.$scrollContainer().scrollTop();\n\t },\n\t\n\t /** set the current scroll position of the panel in its parent */\n\t scrollTo: function (pos, speed) {\n\t speed = speed || 0;\n\t this.$scrollContainer().animate({ scrollTop: pos }, speed);\n\t return this;\n\t },\n\t\n\t /** Scrolls the panel to the top. */\n\t scrollToTop: function (speed) {\n\t return this.scrollTo(0, speed);\n\t },\n\t\n\t /** scroll to the given view in list-items */\n\t scrollToItem: function (view, speed) {\n\t if (!view) {\n\t return this;\n\t }\n\t return this;\n\t },\n\t\n\t /** Scrolls the panel to show the content with the given id. */\n\t scrollToId: function (id, speed) {\n\t return this.scrollToItem(this.viewFromModelId(id), speed);\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: {\n\t 'click .select-all': 'selectAll',\n\t 'click .deselect-all': 'deselectAll'\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** Return a string rep of the panel */\n\t toString: function () {\n\t return 'ListPanel(' + this.collection + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ListPanel.prototype.templates = function () {\n\t\n\t var elTemplate = BASE_MVC.wrapTemplate([\n\t // temp container\n\t '
                ', '
                ', '
                ', '
                ', '
                ']);\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                ', '
                ', '
                <%- view.title %>
                ', '
                ', '
                <%- view.subtitle %>
                ',\n\t // buttons, controls go here\n\t '
                ',\n\t // deleted msg, etc.\n\t '
                ', '
                ', '
                ', '
                ',\n\t\n\t // show when selectors are shown\n\t '
                ', '
                ', '', '', '
                ', '
                ', '
                ', '
                ', '
                ']);\n\t\n\t return {\n\t el: elTemplate,\n\t controls: controlsTemplate\n\t };\n\t }();\n\t\n\t //=============================================================================\n\t /** View for a model that has a sub-collection (e.g. History, DatasetCollection)\n\t * Allows:\n\t * the model to be reset\n\t * auto assign panel.collection to panel.model[ panel.modelCollectionKey ]\n\t *\n\t */\n\t var ModelListPanel = ListPanel.extend({\n\t\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'contents',\n\t\n\t initialize: function (attributes) {\n\t ListPanel.prototype.initialize.call(this, attributes);\n\t this.selecting = attributes.selecting !== undefined ? attributes.selecting : false;\n\t\n\t this.setModel(this.model, attributes);\n\t },\n\t\n\t /** release/free/shutdown old models and set up panel for new models\n\t * @fires new-model with the panel as parameter\n\t */\n\t setModel: function (model, attributes) {\n\t attributes = attributes || {};\n\t this.debug(this + '.setModel:', model, attributes);\n\t\n\t this.freeModel();\n\t this.freeViews();\n\t\n\t if (model) {\n\t var oldModelId = this.model ? this.model.get('id') : null;\n\t\n\t // set up the new model with user, logger, storage, events\n\t this.model = model;\n\t if (this.logger) {\n\t this.model.logger = this.logger;\n\t }\n\t this._setUpModelListeners();\n\t\n\t //TODO: relation btwn model, collection becoming tangled here\n\t // free the collection, and assign the new collection to either\n\t // the model[ modelCollectionKey ], attributes.collection, or an empty vanilla collection\n\t this.stopListening(this.collection);\n\t this.collection = this.model[this.modelCollectionKey] || attributes.collection || this._createDefaultCollection();\n\t this._setUpCollectionListeners();\n\t\n\t if (oldModelId && model.get('id') !== oldModelId) {\n\t this.trigger('new-model', this);\n\t }\n\t }\n\t return this;\n\t },\n\t\n\t /** free the current model and all listeners for it, free any views for the model */\n\t freeModel: function () {\n\t // stop/release the previous model, and clear cache to sub-views\n\t if (this.model) {\n\t this.stopListening(this.model);\n\t //TODO: see base-mvc\n\t //this.model.free();\n\t //this.model = null;\n\t }\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ listening\n\t /** listening for model events */\n\t _setUpModelListeners: function () {\n\t // override\n\t this.log(this + '._setUpModelListeners', this.model);\n\t // bounce model errors up to the panel\n\t this.listenTo(this.model, 'error', function () {\n\t var args = Array.prototype.slice.call(arguments, 0);\n\t //args.unshift( 'model:error' );\n\t args.unshift('error');\n\t this.trigger.apply(this, args);\n\t }, this);\n\t\n\t // debugging\n\t if (this.logger) {\n\t this.listenTo(this.model, 'all', function (event) {\n\t this.info(this + '(model)', event, arguments);\n\t });\n\t }\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el.\n\t */\n\t _renderControls: function ($newRender) {\n\t this.debug(this + '(ModelListPanel)._renderControls');\n\t var json = this.model ? this.model.toJSON() : {},\n\t $controls = $(this.templates.controls(json, this));\n\t $newRender.find('.controls').replaceWith($controls);\n\t return $controls;\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** Return a string rep of the panel */\n\t toString: function () {\n\t return 'ModelListPanel(' + this.model + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ModelListPanel.prototype.templates = function () {\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                ', '
                ',\n\t //TODO: this is really the only difference - consider factoring titlebar out\n\t '
                <%- model.name %>
                ', '
                ', '
                <%- view.subtitle %>
                ', '
                ', '
                ', '
                ', '
                ', '
                ', '
                ', '
                ', '', '', '
                ', '
                ', '
                ', '
                ', '
                ']);\n\t\n\t return _.extend(_.clone(ListPanel.prototype.templates), {\n\t controls: controlsTemplate\n\t });\n\t }();\n\t\n\t //=============================================================================\n\t return {\n\t ListPanel: ListPanel,\n\t ModelListPanel: ModelListPanel\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 90 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This is the run workflow tool form view. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(47), __webpack_require__(5), __webpack_require__(11), __webpack_require__(19), __webpack_require__(43), __webpack_require__(8), __webpack_require__(42), __webpack_require__(143)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, Deferred, Ui, Form, FormData, ToolFormBase, Modal, Webhooks, WorkflowIcons) {\n\t\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.modal = parent.Galaxy.modal || new Modal.View();\n\t this.model = options && options.model || new Backbone.Model(options);\n\t this.deferred = new Deferred();\n\t this.setElement($('
                ').addClass('ui-form-composite').append(this.$message = $('
                ')).append(this.$header = $('
                ')).append(this.$steps = $('
                ')));\n\t $('body').append(this.$el);\n\t this._configure();\n\t this.render();\n\t $(window).resize(function () {\n\t self._refresh();\n\t });\n\t },\n\t\n\t /** Refresh height of scrollable div below header, handle scrolling by lazy loading steps */\n\t _refresh: function (step_index) {\n\t var margin = _.reduce(this.$el.children(), function (memo, child) {\n\t return memo + $(child).outerHeight();\n\t }, 0) - this.$steps.height() + 90;\n\t this.$steps.css('height', $(window).height() - margin);\n\t },\n\t\n\t /** Configures form/step options for each workflow step */\n\t _configure: function () {\n\t var self = this;\n\t this.forms = [];\n\t this.steps = [];\n\t this.links = [];\n\t this.parms = [];\n\t _.each(this.model.get('steps'), function (step, i) {\n\t Galaxy.emit.debug('tool-form-composite::initialize()', i + ' : Preparing workflow step.');\n\t var icon = WorkflowIcons[step.step_type];\n\t var title = parseInt(i + 1) + ': ' + (step.step_label || step.step_name);\n\t if (step.annotation) {\n\t title += ' - ' + step.annotation;\n\t }\n\t if (step.step_version) {\n\t title += ' (Galaxy Version ' + step.step_version + ')';\n\t }\n\t step = Utils.merge({\n\t index: i,\n\t title: _.escape(title),\n\t icon: icon || '',\n\t help: null,\n\t citations: null,\n\t collapsible: true,\n\t collapsed: i > 0 && !self._isDataStep(step),\n\t sustain_version: true,\n\t sustain_repeats: true,\n\t sustain_conditionals: true,\n\t narrow: true,\n\t text_enable: 'Edit',\n\t text_disable: 'Undo',\n\t cls_enable: 'fa fa-edit',\n\t cls_disable: 'fa fa-undo',\n\t errors: step.messages,\n\t initial_errors: true,\n\t cls: 'ui-portlet-narrow',\n\t hide_operations: true,\n\t needs_refresh: false,\n\t always_refresh: step.step_type != 'tool'\n\t }, step);\n\t self.steps[i] = step;\n\t self.links[i] = [];\n\t self.parms[i] = {};\n\t });\n\t\n\t // build linear index of step input pairs\n\t _.each(this.steps, function (step, i) {\n\t FormData.visitInputs(step.inputs, function (input, name) {\n\t self.parms[i][name] = input;\n\t });\n\t });\n\t\n\t // iterate through data input modules and collect linked sub steps\n\t _.each(this.steps, function (step, i) {\n\t _.each(step.output_connections, function (output_connection) {\n\t _.each(self.steps, function (sub_step, j) {\n\t sub_step.step_index === output_connection.input_step_index && self.links[i].push(sub_step);\n\t });\n\t });\n\t });\n\t\n\t // convert all connected data inputs to hidden fields with proper labels,\n\t // and track the linked source step\n\t _.each(this.steps, function (step, i) {\n\t _.each(self.steps, function (sub_step, j) {\n\t var connections_by_name = {};\n\t _.each(step.output_connections, function (connection) {\n\t sub_step.step_index === connection.input_step_index && (connections_by_name[connection.input_name] = connection);\n\t });\n\t _.each(self.parms[j], function (input, name) {\n\t var connection = connections_by_name[name];\n\t if (connection) {\n\t input.type = 'hidden';\n\t input.help = input.step_linked ? input.help + ', ' : '';\n\t input.help += 'Output dataset \\'' + connection.output_name + '\\' from step ' + (parseInt(i) + 1);\n\t input.step_linked = input.step_linked || [];\n\t input.step_linked.push(step);\n\t }\n\t });\n\t });\n\t });\n\t\n\t // identify and configure workflow parameters\n\t var wp_count = 0;\n\t this.wp_inputs = {};\n\t function _handleWorkflowParameter(value, callback) {\n\t var re = /\\$\\{(.+?)\\}/g;\n\t while (match = re.exec(String(value))) {\n\t var wp_name = match[1];\n\t callback(self.wp_inputs[wp_name] = self.wp_inputs[wp_name] || {\n\t label: wp_name,\n\t name: wp_name,\n\t type: 'text',\n\t color: 'hsl( ' + ++wp_count * 100 + ', 70%, 30% )',\n\t style: 'ui-form-wp-source',\n\t links: []\n\t });\n\t }\n\t }\n\t _.each(this.steps, function (step, i) {\n\t _.each(self.parms[i], function (input, name) {\n\t _handleWorkflowParameter(input.value, function (wp_input) {\n\t wp_input.links.push(step);\n\t input.wp_linked = true;\n\t input.type = 'text';\n\t input.backdrop = true;\n\t input.style = 'ui-form-wp-target';\n\t });\n\t });\n\t _.each(step.post_job_actions, function (pja) {\n\t _.each(pja.action_arguments, function (arg) {\n\t _handleWorkflowParameter(arg, function () {});\n\t });\n\t });\n\t });\n\t\n\t // select fields are shown for dynamic fields if all putative data inputs are available,\n\t // or if an explicit reference is specified as data_ref and available\n\t _.each(this.steps, function (step, i) {\n\t if (step.step_type == 'tool') {\n\t var data_resolved = true;\n\t FormData.visitInputs(step.inputs, function (input, name, context) {\n\t var is_runtime_value = input.value && input.value.__class__ == 'RuntimeValue';\n\t var is_data_input = ['data', 'data_collection'].indexOf(input.type) != -1;\n\t var data_ref = context[input.data_ref];\n\t input.step_linked && !self._isDataStep(input.step_linked) && (data_resolved = false);\n\t input.options && (input.options.length == 0 && !data_resolved || input.wp_linked) && (input.is_workflow = true);\n\t data_ref && (input.is_workflow = data_ref.step_linked && !self._isDataStep(data_ref.step_linked) || input.wp_linked);\n\t (is_data_input || input.value && input.value.__class__ == 'RuntimeValue' && !input.step_linked) && (step.collapsed = false);\n\t is_runtime_value && (input.value = input.default_value);\n\t input.flavor = 'workflow';\n\t if (!is_runtime_value && !is_data_input && input.type !== 'hidden' && !input.wp_linked) {\n\t if (input.optional || !Utils.isEmpty(input.value) && input.value !== '') {\n\t input.collapsible_value = input.value;\n\t input.collapsible_preview = true;\n\t }\n\t }\n\t });\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t this.deferred.reset();\n\t this._renderHeader();\n\t this._renderMessage();\n\t this._renderParameters();\n\t this._renderHistory();\n\t _.each(this.steps, function (step) {\n\t self._renderStep(step);\n\t });\n\t },\n\t\n\t /** Render header */\n\t _renderHeader: function () {\n\t var self = this;\n\t this.execute_btn = new Ui.Button({\n\t icon: 'fa-check',\n\t title: 'Run workflow',\n\t cls: 'btn btn-primary',\n\t onclick: function () {\n\t self._execute();\n\t }\n\t });\n\t this.$header.addClass('ui-form-header').empty().append(new Ui.Label({ title: 'Workflow: ' + this.model.get('name') }).$el).append(this.execute_btn.$el);\n\t },\n\t\n\t /** Render message */\n\t _renderMessage: function () {\n\t this.$message.empty();\n\t if (this.model.get('has_upgrade_messages')) {\n\t this.$message.append(new Ui.Message({\n\t message: 'Some tools in this workflow may have changed since it was last saved or some errors were found. The workflow may still run, but any new options will have default values. Please review the messages below to make a decision about whether the changes will affect your analysis.',\n\t status: 'warning',\n\t persistent: true,\n\t fade: false\n\t }).$el);\n\t }\n\t var step_version_changes = this.model.get('step_version_changes');\n\t if (step_version_changes && step_version_changes.length > 0) {\n\t this.$message.append(new Ui.Message({\n\t message: 'Some tools are being executed with different versions compared to those available when this workflow was last saved because the other versions are not or no longer available on this Galaxy instance. To upgrade your workflow and dismiss this message simply edit the workflow and re-save it.',\n\t status: 'warning',\n\t persistent: true,\n\t fade: false\n\t }).$el);\n\t }\n\t },\n\t\n\t /** Render workflow parameters */\n\t _renderParameters: function () {\n\t var self = this;\n\t this.wp_form = null;\n\t if (!_.isEmpty(this.wp_inputs)) {\n\t this.wp_form = new Form({ title: 'Workflow Parameters', inputs: this.wp_inputs, cls: 'ui-portlet-narrow', onchange: function () {\n\t _.each(self.wp_form.input_list, function (input_def, i) {\n\t _.each(input_def.links, function (step) {\n\t self._refreshStep(step);\n\t });\n\t });\n\t }\n\t });\n\t this._append(this.$steps.empty(), this.wp_form.$el);\n\t }\n\t },\n\t\n\t /** Render workflow parameters */\n\t _renderHistory: function () {\n\t this.history_form = new Form({\n\t cls: 'ui-portlet-narrow',\n\t title: 'History Options',\n\t inputs: [{\n\t type: 'conditional',\n\t name: 'new_history',\n\t test_param: {\n\t name: 'check',\n\t label: 'Send results to a new history',\n\t type: 'boolean',\n\t value: 'false',\n\t help: ''\n\t },\n\t cases: [{\n\t value: 'true',\n\t inputs: [{\n\t name: 'name',\n\t label: 'History name',\n\t type: 'text',\n\t value: this.model.get('name')\n\t }]\n\t }]\n\t }]\n\t });\n\t this._append(this.$steps, this.history_form.$el);\n\t },\n\t\n\t /** Render step */\n\t _renderStep: function (step) {\n\t var self = this;\n\t var form = null;\n\t this.deferred.execute(function (promise) {\n\t self.$steps.addClass('ui-steps');\n\t if (step.step_type == 'tool') {\n\t step.postchange = function (process, form) {\n\t var self = this;\n\t var current_state = {\n\t tool_id: step.id,\n\t tool_version: step.version,\n\t inputs: $.extend(true, {}, form.data.create())\n\t };\n\t form.wait(true);\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Sending current state.', current_state);\n\t Utils.request({\n\t type: 'POST',\n\t url: Galaxy.root + 'api/tools/' + step.id + '/build',\n\t data: current_state,\n\t success: function (data) {\n\t form.update(data);\n\t form.wait(false);\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Received new model.', data);\n\t process.resolve();\n\t },\n\t error: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Refresh request failed.', response);\n\t process.reject();\n\t }\n\t });\n\t };\n\t form = new ToolFormBase(step);\n\t if (step.post_job_actions && step.post_job_actions.length) {\n\t form.portlet.append($('
                ').addClass('ui-form-element-disabled').append($('
                ').addClass('ui-form-title').html('Job Post Actions')).append($('
                ').addClass('ui-form-preview').html(_.reduce(step.post_job_actions, function (memo, value) {\n\t return memo + ' ' + value.short_str;\n\t }, ''))));\n\t }\n\t } else {\n\t var is_simple_input = ['data_input', 'data_collection_input'].indexOf(step.step_type) != -1;\n\t _.each(step.inputs, function (input) {\n\t input.flavor = 'module';input.hide_label = is_simple_input;\n\t });\n\t form = new Form(Utils.merge({\n\t title: step.title,\n\t onchange: function () {\n\t _.each(self.links[step.index], function (link) {\n\t self._refreshStep(link);\n\t });\n\t },\n\t inputs: step.inputs && step.inputs.length > 0 ? step.inputs : [{ type: 'hidden', name: 'No options available.', ignore: null }]\n\t }, step));\n\t }\n\t self.forms[step.index] = form;\n\t self._append(self.$steps, form.$el);\n\t self._refresh();\n\t step.needs_refresh && self._refreshStep(step);\n\t form.portlet[!self.show_progress ? 'enable' : 'disable']();\n\t self.show_progress && self.execute_btn.model.set({ wait: true,\n\t wait_text: 'Preparing...',\n\t percentage: (step.index + 1) * 100.0 / self.steps.length });\n\t Galaxy.emit.debug('tool-form-composite::initialize()', step.index + ' : Workflow step state ready.', step);\n\t setTimeout(function () {\n\t promise.resolve();\n\t }, 0);\n\t });\n\t },\n\t\n\t /** Refreshes step values from source step values */\n\t _refreshStep: function (step) {\n\t var self = this;\n\t var form = this.forms[step.index];\n\t if (form) {\n\t _.each(self.parms[step.index], function (input, name) {\n\t if (input.step_linked || input.wp_linked) {\n\t var field = form.field_list[form.data.match(name)];\n\t if (field) {\n\t var new_value = undefined;\n\t if (input.step_linked) {\n\t new_value = { values: [] };\n\t _.each(input.step_linked, function (source_step) {\n\t if (self._isDataStep(source_step)) {\n\t value = self.forms[source_step.index].data.create().input;\n\t value && _.each(value.values, function (v) {\n\t new_value.values.push(v);\n\t });\n\t }\n\t });\n\t if (!input.multiple && new_value.values.length > 0) {\n\t new_value = { values: [new_value.values[0]] };\n\t }\n\t } else if (input.wp_linked) {\n\t new_value = input.value;\n\t var re = /\\$\\{(.+?)\\}/g;\n\t while (match = re.exec(input.value)) {\n\t var wp_field = self.wp_form.field_list[self.wp_form.data.match(match[1])];\n\t var wp_value = wp_field && wp_field.value();\n\t if (wp_value) {\n\t new_value = new_value.split(match[0]).join(wp_value);\n\t }\n\t }\n\t }\n\t if (new_value !== undefined) {\n\t field.value(new_value);\n\t }\n\t }\n\t }\n\t });\n\t form.trigger('change');\n\t } else {\n\t step.needs_refresh = true;\n\t }\n\t },\n\t\n\t /** Refresh the history after job submission while form is shown */\n\t _refreshHistory: function () {\n\t var self = this;\n\t var history = parent.Galaxy && parent.Galaxy.currHistoryPanel && parent.Galaxy.currHistoryPanel.model;\n\t this._refresh_history && clearTimeout(this._refresh_history);\n\t if (history) {\n\t history.refresh().success(function () {\n\t if (history.numOfUnfinishedShownContents() === 0) {\n\t self._refresh_history = setTimeout(function () {\n\t self._refreshHistory();\n\t }, history.UPDATE_DELAY);\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Build remaining steps */\n\t _execute: function () {\n\t var self = this;\n\t this.show_progress = true;\n\t this._enabled(false);\n\t this.deferred.execute(function (promise) {\n\t setTimeout(function () {\n\t promise.resolve();self._submit();\n\t }, 0);\n\t });\n\t },\n\t\n\t /** Validate and submit workflow */\n\t _submit: function () {\n\t var self = this;\n\t var history_form_data = this.history_form.data.create();\n\t var job_def = {\n\t new_history_name: history_form_data['new_history|name'] ? history_form_data['new_history|name'] : null,\n\t history_id: !history_form_data['new_history|name'] ? this.model.get('history_id') : null,\n\t replacement_params: this.wp_form ? this.wp_form.data.create() : {},\n\t parameters: {},\n\t // Tool form will submit flat maps for each parameter\n\t // (e.g. \"repeat_0|cond|param\": \"foo\" instead of nested\n\t // data structures).\n\t parameters_normalized: true,\n\t // Tool form always wants a list of invocations back\n\t // so that inputs can be batched.\n\t batch: true\n\t };\n\t var validated = true;\n\t for (var i in this.forms) {\n\t var form = this.forms[i];\n\t var job_inputs = form.data.create();\n\t var step = self.steps[i];\n\t var step_index = step.step_index;\n\t form.trigger('reset');\n\t for (var job_input_id in job_inputs) {\n\t var input_value = job_inputs[job_input_id];\n\t var input_id = form.data.match(job_input_id);\n\t var input_field = form.field_list[input_id];\n\t var input_def = form.input_list[input_id];\n\t if (!input_def.step_linked) {\n\t if (this._isDataStep(step)) {\n\t validated = input_value && input_value.values && input_value.values.length > 0;\n\t } else {\n\t validated = input_def.optional || input_def.is_workflow && input_value !== '' || !input_def.is_workflow && input_value !== null;\n\t }\n\t if (!validated) {\n\t form.highlight(input_id);\n\t break;\n\t }\n\t job_def.parameters[step_index] = job_def.parameters[step_index] || {};\n\t job_def.parameters[step_index][job_input_id] = job_inputs[job_input_id];\n\t }\n\t }\n\t if (!validated) {\n\t break;\n\t }\n\t }\n\t if (!validated) {\n\t self._enabled(true);\n\t Galaxy.emit.debug('tool-form-composite::submit()', 'Validation failed.', job_def);\n\t } else {\n\t Galaxy.emit.debug('tool-form-composite::submit()', 'Validation complete.', job_def);\n\t Utils.request({\n\t type: 'POST',\n\t url: Galaxy.root + 'api/workflows/' + this.model.id + '/invocations',\n\t data: job_def,\n\t success: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::submit', 'Submission successful.', response);\n\t self.$el.children().hide();\n\t self.$el.append(self._templateSuccess(response));\n\t\n\t // Show Webhook if job is running\n\t if ($.isArray(response) && response.length > 0) {\n\t self.$el.append($('
                ', { id: 'webhook-view' }));\n\t var WebhookApp = new Webhooks.WebhookView({\n\t urlRoot: Galaxy.root + 'api/webhooks/workflow',\n\t toolId: job_def.tool_id,\n\t toolVersion: job_def.tool_version\n\t });\n\t }\n\t\n\t self._refreshHistory();\n\t },\n\t error: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::submit', 'Submission failed.', response);\n\t var input_found = false;\n\t if (response && response.err_data) {\n\t for (var i in self.forms) {\n\t var form = self.forms[i];\n\t var step_related_errors = response.err_data[form.model.get('step_index')];\n\t if (step_related_errors) {\n\t var error_messages = form.data.matchResponse(step_related_errors);\n\t for (var input_id in error_messages) {\n\t form.highlight(input_id, error_messages[input_id]);\n\t input_found = true;\n\t break;\n\t }\n\t }\n\t }\n\t }\n\t if (!input_found) {\n\t self.modal.show({\n\t title: 'Workflow submission failed',\n\t body: self._templateError(job_def, response && response.err_msg),\n\t buttons: {\n\t 'Close': function () {\n\t self.modal.hide();\n\t }\n\t }\n\t });\n\t }\n\t },\n\t complete: function () {\n\t self._enabled(true);\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Append new dom to body */\n\t _append: function ($container, $el) {\n\t $container.append('

                ').append($el);\n\t },\n\t\n\t /** Set enabled/disabled state */\n\t _enabled: function (enabled) {\n\t this.execute_btn.model.set({ wait: !enabled, wait_text: 'Sending...', percentage: -1 });\n\t this.wp_form && this.wp_form.portlet[enabled ? 'enable' : 'disable']();\n\t this.history_form && this.history_form.portlet[enabled ? 'enable' : 'disable']();\n\t _.each(this.forms, function (form) {\n\t form && form.portlet[enabled ? 'enable' : 'disable']();\n\t });\n\t },\n\t\n\t /** Is data input module/step */\n\t _isDataStep: function (steps) {\n\t lst = $.isArray(steps) ? steps : [steps];\n\t for (var i = 0; i < lst.length; i++) {\n\t var step = lst[i];\n\t if (!step || !step.step_type || !step.step_type.startsWith('data')) {\n\t return false;\n\t }\n\t }\n\t return true;\n\t },\n\t\n\t /** Templates */\n\t _templateSuccess: function (response) {\n\t if ($.isArray(response) && response.length > 0) {\n\t return $('

                ').addClass('donemessagelarge').append($('

                ').html('Successfully invoked workflow ' + Utils.sanitize(this.model.get('name')) + '' + (response.length > 1 ? ' ' + response.length + ' times' : '') + '.')).append($('

                ').append('').text('You can check the status of queued jobs and view the resulting data by refreshing the History pane. When the job has been run the status will change from \\'running\\' to \\'finished\\' if completed successfully or \\'error\\' if problems were encountered.'));\n\t } else {\n\t return this._templateError(response, 'Invalid success response. No invocations found.');\n\t }\n\t },\n\t\n\t _templateError: function (response, err_msg) {\n\t return $('

                ').addClass('errormessagelarge').append($('

                ').text('The server could not complete the request. Please contact the Galaxy Team if this error persists. ' + (JSON.stringify(err_msg) || ''))).append($('

                ').text(JSON.stringify(response, null, 4)));\n\t        }\n\t    });\n\t    return {\n\t        View: View\n\t    };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 91 */,\n/* 92 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_l) {\n\t    'use strict';\n\t\n\t    //TODO: toastr is another possibility - I didn't see where I might add details, tho\n\t\n\t    /* ============================================================================\n\t    Error modals meant to replace the o-so-easy alerts.\n\t    \n\t    These are currently styled as errormessages but use the Galaxy.modal\n\t    infrastructure to be shown/closed. They're capable of showing details in a\n\t    togglable dropdown and the details are formatted in a pre.\n\t    \n\t    Example:\n\t        errorModal( 'Heres a message', 'A Title', { some_details: 'here' });\n\t        errorModal( 'Heres a message' ); // no details, title is 'Error'\n\t    \n\t    There are three specialized forms:\n\t        offlineErrorModal       a canned response for when there's no connection\n\t        badGatewayErrorModal    canned response for when Galaxy is restarting\n\t        ajaxErrorModal          plugable into any Backbone class as an\n\t            error event handler by accepting the error args: model, xhr, options\n\t    \n\t    Examples:\n\t        if( navigator.offLine ){ offlineErrorModal(); }\n\t        if( xhr.status === 502 ){ badGatewayErrorModal(); }\n\t        this.listenTo( this.model, 'error', ajaxErrorModal );\n\t    \n\t    ============================================================================ */\n\t\n\t    var CONTACT_MSG = _l('Please contact a Galaxy administrator if the problem persists.');\n\t    var DEFAULT_AJAX_ERR_MSG = _l('An error occurred while updating information with the server.');\n\t    var DETAILS_MSG = _l('The following information can assist the developers in finding the source of the error:');\n\t\n\t    /** private helper that builds the modal and handles adding details */\n\t    function _errorModal(message, title, details) {\n\t        // create and return the modal, adding details button only if needed\n\t        Galaxy.modal.show({\n\t            title: title,\n\t            body: message,\n\t            closing_events: true,\n\t            buttons: { Ok: function () {\n\t                    Galaxy.modal.hide();\n\t                } }\n\t        });\n\t        Galaxy.modal.$el.addClass('error-modal');\n\t\n\t        if (details) {\n\t            Galaxy.modal.$('.error-details').add(Galaxy.modal.$('button:contains(\"Details\")')).remove();\n\t            $('
                ').addClass('error-details').hide().appendTo(Galaxy.modal.$('.modal-content')).append([$('

                ').text(DETAILS_MSG), $('

                ').text(JSON.stringify(details, null, '  '))]);\n\t\n\t            $('').appendTo(Galaxy.modal.$('.buttons')).click(function () {\n\t                Galaxy.modal.$('.error-details').toggle();\n\t            });\n\t        }\n\t        return Galaxy.modal;\n\t    }\n\t\n\t    /** Display a modal showing an error message but fallback to alert if there's no modal */\n\t    function errorModal(message, title, details) {\n\t        if (!message) {\n\t            return;\n\t        }\n\t\n\t        message = _l(message);\n\t        title = _l(title) || _l('Error:');\n\t        if (window.Galaxy && Galaxy.modal) {\n\t            return _errorModal(message, title, details);\n\t        }\n\t\n\t        alert(title + '\\n\\n' + message);\n\t        console.log('error details:', JSON.stringify(details));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** display a modal when the user may be offline */\n\t    function offlineErrorModal() {\n\t        return errorModal(_l('You appear to be offline. Please check your connection and try again.'), _l('Offline?'));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** 502 messages that should be displayed when galaxy is restarting */\n\t    function badGatewayErrorModal() {\n\t        return errorModal(_l('Galaxy is currently unreachable. Please try again in a few minutes.') + ' ' + CONTACT_MSG, _l('Cannot connect to Galaxy'));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** display a modal (with details) about a failed Backbone ajax operation */\n\t    function ajaxErrorModal(model, xhr, options, message, title) {\n\t        message = message || DEFAULT_AJAX_ERR_MSG;\n\t        message += ' ' + CONTACT_MSG;\n\t        title = title || _l('An error occurred');\n\t        var details = _ajaxDetails(model, xhr, options);\n\t        return errorModal(message, title, details);\n\t    }\n\t\n\t    /** build details which may help debugging the ajax call */\n\t    function _ajaxDetails(model, xhr, options) {\n\t        return {\n\t            //TODO: still can't manage Raven id\n\t            raven: _.result(window.Raven, 'lastEventId'),\n\t            userAgent: navigator.userAgent,\n\t            onLine: navigator.onLine,\n\t            version: _.result(Galaxy.config, 'version_major'),\n\t            xhr: _.omit(xhr, _.functions(xhr)),\n\t            options: _.omit(options, 'xhr'),\n\t            // add ajax data from Galaxy object cache\n\t            url: _.result(Galaxy.lastAjax, 'url'),\n\t            data: _.result(Galaxy.lastAjax, 'data'),\n\t            // backbone stuff (auto-redacting email for user)\n\t            model: _.result(model, 'toJSON', model + ''),\n\t            user: _.omit(_.result(Galaxy.user, 'toJSON'), 'email')\n\t        };\n\t    }\n\t\n\t    //=============================================================================\n\t    return {\n\t        errorModal: errorModal,\n\t        offlineErrorModal: offlineErrorModal,\n\t        badGatewayErrorModal: badGatewayErrorModal,\n\t        ajaxErrorModal: ajaxErrorModal\n\t    };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 93 */,\n/* 94 */,\n/* 95 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, $) {(function (factory) {\n\t    if (true) {\n\t        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t    } else {\n\t        // Browser globals\n\t        factory(jQuery);\n\t    }\n\t})(function () {\n\t    //=============================================================================\n\t\n\t    jQuery.fn.extend({\n\t        hoverhighlight: function $hoverhighlight(scope, color) {\n\t            scope = scope || 'body';\n\t            if (!this.length) {\n\t                return this;\n\t            }\n\t\n\t            $(this).each(function () {\n\t                var $this = $(this),\n\t                    targetSelector = $this.data('target');\n\t\n\t                if (targetSelector) {\n\t                    $this.mouseover(function (ev) {\n\t                        $(targetSelector, scope).css({\n\t                            background: color\n\t                        });\n\t                    }).mouseout(function (ev) {\n\t                        $(targetSelector).css({\n\t                            background: ''\n\t                        });\n\t                    });\n\t                }\n\t            });\n\t            return this;\n\t        }\n\t    });\n\t});\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 96 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, jQuery) {// from: https://raw.githubusercontent.com/umdjs/umd/master/jqueryPlugin.js\n\t// Uses AMD or browser globals to create a jQuery plugin.\n\t(function (factory) {\n\t    if (true) {\n\t        //TODO: So...this turns out to be an all or nothing thing. If I load jQuery in the define below, it will\n\t        //  (of course) wipe the old jquery *and all the plugins loaded into it*. So the define below *is still\n\t        //  relying on jquery being loaded globally* in order to preserve plugins.\n\t        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t    } else {\n\t        // Browser globals\n\t        factory(jQuery);\n\t    }\n\t})(function () {\n\t    var _l = window._l || function (s) {\n\t        return s;\n\t    };\n\t\n\t    //TODO: consolidate with tool menu functionality, use there\n\t\n\t    /** searchInput: (jQuery plugin)\n\t     *      Creates a search input, a clear button, and loading indicator\n\t     *      within the selected node.\n\t     *\n\t     *      When the user either presses return or enters some minimal number\n\t     *      of characters, a callback is called. Pressing ESC when the input\n\t     *      is focused will clear the input and call a separate callback.\n\t     */\n\t    function searchInput(parentNode, options) {\n\t        var KEYCODE_ESC = 27,\n\t            KEYCODE_RETURN = 13,\n\t            $parentNode = $(parentNode),\n\t            firstSearch = true,\n\t            defaults = {\n\t            initialVal: '',\n\t            name: 'search',\n\t            placeholder: 'search',\n\t            classes: '',\n\t            onclear: function () {},\n\t            onfirstsearch: null,\n\t            onsearch: function (inputVal) {},\n\t            minSearchLen: 0,\n\t            escWillClear: true,\n\t            oninit: function () {}\n\t        };\n\t\n\t        // .................................................................... input rendering and events\n\t        // visually clear the search, trigger an event, and call the callback\n\t        function clearSearchInput(event) {\n\t            var $input = $(this).parent().children('input');\n\t            $input.val('').trigger('searchInput.clear').blur();\n\t            options.onclear();\n\t        }\n\t\n\t        // search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)\n\t        function search(event, searchTerms) {\n\t            if (!searchTerms) {\n\t                return clearSearchInput();\n\t            }\n\t            $(this).trigger('search.search', searchTerms);\n\t            if (typeof options.onfirstsearch === 'function' && firstSearch) {\n\t                firstSearch = false;\n\t                options.onfirstsearch(searchTerms);\n\t            } else {\n\t                options.onsearch(searchTerms);\n\t            }\n\t        }\n\t\n\t        // .................................................................... input rendering and events\n\t        function inputTemplate() {\n\t            // class search-query is bootstrap 2.3 style that now lives in base.less\n\t            return [''].join('');\n\t        }\n\t\n\t        // the search input that responds to keyboard events and displays the search value\n\t        function $input() {\n\t            return $(inputTemplate())\n\t            // select all text on a focus\n\t            .focus(function (event) {\n\t                $(this).select();\n\t            })\n\t            // attach behaviors to esc, return if desired, search on some min len string\n\t            .keyup(function (event) {\n\t                event.preventDefault();\n\t                event.stopPropagation();\n\t\n\t                // esc key will clear if desired\n\t                if (event.which === KEYCODE_ESC && options.escWillClear) {\n\t                    clearSearchInput.call(this, event);\n\t                } else {\n\t                    var searchTerms = $(this).val();\n\t                    // return key or the search string len > minSearchLen (if not 0) triggers search\n\t                    if (event.which === KEYCODE_RETURN || options.minSearchLen && searchTerms.length >= options.minSearchLen) {\n\t                        search.call(this, event, searchTerms);\n\t                    }\n\t                }\n\t            }).val(options.initialVal);\n\t        }\n\t\n\t        // .................................................................... clear button rendering and events\n\t        // a button for clearing the search bar, placed on the right hand side\n\t        function $clearBtn() {\n\t            return $([''].join('')).tooltip({ placement: 'bottom' }).click(function (event) {\n\t                clearSearchInput.call(this, event);\n\t            });\n\t        }\n\t\n\t        // .................................................................... loadingIndicator rendering\n\t        // a button for clearing the search bar, placed on the right hand side\n\t        function $loadingIndicator() {\n\t            return $([''].join('')).hide().tooltip({ placement: 'bottom' });\n\t        }\n\t\n\t        // .................................................................... commands\n\t        // visually swap the load, clear buttons\n\t        function toggleLoadingIndicator() {\n\t            $parentNode.find('.search-loading').toggle();\n\t            $parentNode.find('.search-clear').toggle();\n\t        }\n\t\n\t        // .................................................................... init\n\t        // string command (not constructor)\n\t        if (jQuery.type(options) === 'string') {\n\t            if (options === 'toggle-loading') {\n\t                toggleLoadingIndicator();\n\t            }\n\t            return $parentNode;\n\t        }\n\t\n\t        // initial render\n\t        if (jQuery.type(options) === 'object') {\n\t            options = jQuery.extend(true, {}, defaults, options);\n\t        }\n\t        //NOTE: prepended\n\t        return $parentNode.addClass('search-input').prepend([$input(), $clearBtn(), $loadingIndicator()]);\n\t    }\n\t\n\t    // as jq plugin\n\t    jQuery.fn.extend({\n\t        searchInput: function $searchInput(options) {\n\t            return this.each(function () {\n\t                return searchInput(this, options);\n\t            });\n\t        }\n\t    });\n\t});\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 97 */,\n/* 98 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n\t    // Alphanumeric/natural sort fn\n\t    function naturalSort(a, b) {\n\t        // setup temp-scope variables for comparison evauluation\n\t        var re = /(-?[0-9\\.]+)/g,\n\t            x = a.toString().toLowerCase() || '',\n\t            y = b.toString().toLowerCase() || '',\n\t            nC = String.fromCharCode(0),\n\t            xN = x.replace(re, nC + '$1' + nC).split(nC),\n\t            yN = y.replace(re, nC + '$1' + nC).split(nC),\n\t            xD = new Date(x).getTime(),\n\t            yD = xD ? new Date(y).getTime() : null;\n\t        // natural sorting of dates\n\t        if (yD) {\n\t            if (xD < yD) {\n\t                return -1;\n\t            } else if (xD > yD) {\n\t                return 1;\n\t            }\n\t        }\n\t        // natural sorting through split numeric strings and default strings\n\t        var oFxNcL, oFyNcL;\n\t        for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {\n\t            oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];\n\t            oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];\n\t            if (oFxNcL < oFyNcL) {\n\t                return -1;\n\t            } else if (oFxNcL > oFyNcL) {\n\t                return 1;\n\t            }\n\t        }\n\t        return 0;\n\t    }\n\t\n\t    return naturalSort;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 99 */,\n/* 100 */,\n/* 101 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Backbone) {var Ui = __webpack_require__(5),\n\t    historyOptionsMenu = __webpack_require__(131);\n\tCurrentHistoryView = __webpack_require__(128).CurrentHistoryView, _l = __webpack_require__(6);\n\t\n\t/** the right hand panel in the analysis page that shows the current history */\n\tvar HistoryPanel = Backbone.View.extend({\n\t\n\t    initialize: function (page, options) {\n\t        var self = this;\n\t        this.userIsAnonymous = Galaxy.user.isAnonymous();\n\t        this.allow_user_dataset_purge = options.config.allow_user_dataset_purge;\n\t        this.root = options.root;\n\t\n\t        // view of the current history\n\t        this.historyView = new CurrentHistoryView({\n\t            className: CurrentHistoryView.prototype.className + ' middle',\n\t            purgeAllowed: this.allow_user_dataset_purge,\n\t            linkTarget: 'galaxy_main'\n\t        });\n\t\n\t        // add history panel to Galaxy object\n\t        Galaxy.currHistoryPanel = this.historyView;\n\t        Galaxy.currHistoryPanel.listenToGalaxy(Galaxy);\n\t\n\t        // build buttons\n\t        this.buttonRefresh = new Ui.ButtonLink({\n\t            id: 'history-refresh-button',\n\t            title: 'Refresh history',\n\t            cls: 'panel-header-button',\n\t            icon: 'fa fa-refresh',\n\t            onclick: function () {\n\t                self.historyView.loadCurrentHistory();\n\t            }\n\t        });\n\t        this.buttonOptions = new Ui.ButtonLink({\n\t            id: 'history-options-button',\n\t            title: 'History options',\n\t            cls: 'panel-header-button',\n\t            target: 'galaxy_main',\n\t            icon: 'fa fa-cog',\n\t            href: this.root + 'root/history_options'\n\t        });\n\t        this.buttonViewMulti = new Ui.ButtonLink({\n\t            id: 'history-view-multi-button',\n\t            title: 'View all histories',\n\t            cls: 'panel-header-button',\n\t            icon: 'fa fa-columns',\n\t            href: this.root + 'history/view_multiple'\n\t        });\n\t\n\t        // define components\n\t        this.model = new Backbone.Model({\n\t            cls: 'history-right-panel',\n\t            title: _l('History'),\n\t            buttons: [this.buttonRefresh, this.buttonOptions, this.buttonViewMulti]\n\t        });\n\t\n\t        // build body template and connect history view\n\t        this.setElement(this._template());\n\t        this.historyView.setElement(this.$el);\n\t        this.historyView.connectToQuotaMeter(Galaxy.quotaMeter);\n\t        this.historyView.loadCurrentHistory();\n\t\n\t        // fetch to update the quota meter adding 'current' for any anon-user's id\n\t        Galaxy.listenTo(this.historyView, 'history-size-change', function () {\n\t            Galaxy.user.fetch({ url: Galaxy.user.urlRoot() + '/' + (Galaxy.user.id || 'current') });\n\t        });\n\t    },\n\t\n\t    render: function () {\n\t        this.optionsMenu = historyOptionsMenu(this.buttonOptions.$el, {\n\t            anonymous: this.userIsAnonymous,\n\t            purgeAllowed: this.allow_user_dataset_purge,\n\t            root: this.root\n\t        });\n\t        this.buttonViewMulti.$el[!this.userIsAnonymous ? 'show' : 'hide']();\n\t    },\n\t\n\t    /** add history view div */\n\t    _template: function (data) {\n\t        return ['
                '].join('');\n\t },\n\t\n\t toString: function () {\n\t return 'historyPanel';\n\t }\n\t});\n\t\n\tmodule.exports = HistoryPanel;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))\n\n/***/ },\n/* 102 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Backbone, _) {var Tools = __webpack_require__(66),\n\t Upload = __webpack_require__(139),\n\t _l = __webpack_require__(6),\n\t ToolForm = __webpack_require__(90);\n\t\n\tvar ToolPanel = Backbone.View.extend({\n\t initialize: function (page, options) {\n\t // access configuration options\n\t var config = options.config;\n\t this.root = options.root;\n\t\n\t /** @type {Object[]} descriptions of user's workflows to be shown in the tool menu */\n\t this.stored_workflow_menu_entries = config.stored_workflow_menu_entries || [];\n\t\n\t // create tool search, tool panel, and tool panel view.\n\t var tool_search = new Tools.ToolSearch({\n\t hidden: false\n\t });\n\t var tools = new Tools.ToolCollection(config.toolbox);\n\t this.tool_panel = new Tools.ToolPanel({\n\t tool_search: tool_search,\n\t tools: tools,\n\t layout: config.toolbox_in_panel\n\t });\n\t this.tool_panel_view = new Tools.ToolPanelView({ model: this.tool_panel });\n\t\n\t // add upload modal\n\t this.upload_button = new Upload({\n\t nginx_upload_path: config.nginx_upload_path,\n\t ftp_upload_site: config.ftp_upload_site,\n\t default_genome: config.default_genome,\n\t default_extension: config.default_extension\n\t });\n\t\n\t // add uploader button to Galaxy object\n\t Galaxy.upload = this.upload_button;\n\t\n\t // components for panel definition\n\t this.model = new Backbone.Model({\n\t title: _l('Tools'),\n\t buttons: [this.upload_button]\n\t });\n\t\n\t // build body template\n\t this.setElement(this._template());\n\t },\n\t\n\t render: function () {\n\t // if there are tools, render panel and display everything\n\t var self = this;\n\t if (this.tool_panel.get('layout').size() > 0) {\n\t this.$el.prepend(this.tool_panel_view.$el);\n\t this.tool_panel_view.render();\n\t }\n\t // build the dom for the workflow portion of the tool menu\n\t // add internal workflow list\n\t self.$('#internal-workflows').append(self._templateAllWorkflow({\n\t title: _l('All workflows'),\n\t href: 'workflow'\n\t }));\n\t _.each(this.stored_workflow_menu_entries, function (menu_entry) {\n\t self.$('#internal-workflows').append(self._templateWorkflowLink({\n\t title: menu_entry.stored_workflow.name,\n\t href: 'workflow/run?id=' + menu_entry.encoded_stored_workflow_id\n\t }));\n\t });\n\t },\n\t\n\t /** build a link to one tool */\n\t _templateTool: function (tool) {\n\t return [''].join('');\n\t },\n\t\n\t /** build a link to 'All Workflows' */\n\t _templateAllWorkflow: function (tool) {\n\t return ['
                ',\n\t // global\n\t '', tool.title, '', '
                '].join('');\n\t },\n\t\n\t /** build links to workflows in toolpanel */\n\t _templateWorkflowLink: function (wf) {\n\t return [''].join('');\n\t },\n\t\n\t /** override to include inital menu dom and workflow section */\n\t _template: function () {\n\t return ['
                ', '
                ', '
                ', '', _l('Search did not match any tools.'), '', '
                ', '
                ', '
                ', '
                ', '
                ', '', _l('Workflows'), '', '
                ', '
                ', '
                ', '
                ', '
                '].join('');\n\t },\n\t\n\t toString: function () {\n\t return 'toolPanel';\n\t }\n\t});\n\t\n\tmodule.exports = ToolPanel;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 103 */,\n/* 104 */,\n/* 105 */,\n/* 106 */,\n/* 107 */,\n/* 108 */,\n/* 109 */,\n/* 110 */,\n/* 111 */,\n/* 112 */,\n/* 113 */,\n/* 114 */,\n/* 115 */,\n/* 116 */,\n/* 117 */,\n/* 118 */,\n/* 119 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(55), __webpack_require__(82), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_LI, DATASET_LI_EDIT, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var DCListItemView = DC_LI.DCListItemView;\n\t /** @class Edit view for DatasetCollection.\n\t */\n\t var DCListItemEdit = DCListItemView.extend(\n\t /** @lends DCListItemEdit.prototype */{\n\t\n\t /** override to add linkTarget */\n\t initialize: function (attributes) {\n\t DCListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t var DCEListItemView = DC_LI.DCEListItemView;\n\t /** @class Read only view for DatasetCollectionElement.\n\t */\n\t var DCEListItemEdit = DCEListItemView.extend(\n\t /** @lends DCEListItemEdit.prototype */{\n\t //TODO: this might be expendable - compacted with HDAListItemView\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t DCEListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t // NOTE: this does not inherit from DatasetDCEListItemView as you would expect\n\t //TODO: but should - if we can find something simpler than using diamond\n\t /** @class Editable view for a DatasetCollectionElement that is also an DatasetAssociation\n\t * (a dataset contained in a dataset collection).\n\t */\n\t var DatasetDCEListItemEdit = DATASET_LI_EDIT.DatasetListItemEdit.extend(\n\t /** @lends DatasetDCEListItemEdit.prototype */{\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t DATASET_LI_EDIT.DatasetListItemEdit.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // NOTE: this does not inherit from DatasetDCEListItemView - so we duplicate this here\n\t //TODO: fix\n\t /** In this override, only get details if in the ready state.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Override to remove delete button */\n\t _renderDeleteButton: function () {\n\t return null;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetDCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetDCEListItemEdit.prototype.templates = function () {\n\t\n\t return _.extend({}, DATASET_LI_EDIT.DatasetListItemEdit.prototype.templates, {\n\t titleBar: DC_LI.DatasetDCEListItemView.prototype.templates.titleBar\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested DC).\n\t */\n\t var NestedDCDCEListItemEdit = DC_LI.NestedDCDCEListItemView.extend(\n\t /** @lends NestedDCDCEListItemEdit.prototype */{\n\t\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'NestedDCDCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DCListItemEdit: DCListItemEdit,\n\t DCEListItemEdit: DCEListItemEdit,\n\t DatasetDCEListItemEdit: DatasetDCEListItemEdit,\n\t NestedDCDCEListItemEdit: NestedDCDCEListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 120 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(81), __webpack_require__(56), __webpack_require__(119), __webpack_require__(7), __webpack_require__(65), __webpack_require__(25), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_VIEW, DC_MODEL, DC_EDIT, BASE_MVC, TAGS, faIconButton, _l) {\n\t\n\t 'use strict';\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class editable View/Controller for a dataset collection.\n\t */\n\t\n\t var _super = DC_VIEW.CollectionView;\n\t var CollectionViewEdit = _super.extend(\n\t /** @lends CollectionView.prototype */{\n\t //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\t\n\t /** logger used to record this.log messages, commonly set to console */\n\t //logger : console,\n\t\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_EDIT.DatasetDCEListItemEdit,\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** In this override, make the collection name editable\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t if (!this.model) {\n\t return;\n\t }\n\t\n\t // anon users shouldn't have access to any of the following\n\t if (!Galaxy.user || Galaxy.user.isAnonymous()) {\n\t return;\n\t }\n\t\n\t this.tagsEditorShown = true;\n\t\n\t //TODO: extract\n\t var panel = this,\n\t nameSelector = '> .controls .name';\n\t $where.find(nameSelector).attr('title', _l('Click to rename collection')).tooltip({ placement: 'bottom' }).make_text_editable({\n\t on_finish: function (newName) {\n\t var previousName = panel.model.get('name');\n\t if (newName && newName !== previousName) {\n\t panel.$el.find(nameSelector).text(newName);\n\t panel.model.save({ name: newName }).fail(function () {\n\t panel.$el.find(nameSelector).text(panel.model.previous('name'));\n\t });\n\t } else {\n\t panel.$el.find(nameSelector).text(previousName);\n\t }\n\t }\n\t });\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t usePrompt: false\n\t });\n\t this.tagsEditor.toggle(true);\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'CollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_EDIT.DatasetDCEListItemEdit,\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class Editable, read-only View/Controller for a dataset collection. */\n\t var PairCollectionViewEdit = ListCollectionViewEdit.extend(\n\t /** @lends PairCollectionViewEdit.prototype */{\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class Editable (roughly since these collections are immutable),\n\t * View/Controller for a dataset collection.\n\t */\n\t var NestedPairCollectionViewEdit = PairCollectionViewEdit.extend(\n\t /** @lends NestedPairCollectionViewEdit.prototype */{\n\t\n\t /** Override to remove the editable text from the name/identifier - these collections are considered immutable */\n\t _setUpBehaviors: function ($where) {\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'NestedPairCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class editable, View/Controller for a list of pairs dataset collection. */\n\t var ListOfPairsCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListOfPairsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit.extend({\n\t foldoutPanelClass: NestedPairCollectionViewEdit\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfPairsCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class View/Controller for a list of lists dataset collection. */\n\t var ListOfListsCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListOfListsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit.extend({\n\t foldoutPanelClass: NestedPairCollectionViewEdit\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfListsCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CollectionViewEdit: CollectionViewEdit,\n\t ListCollectionViewEdit: ListCollectionViewEdit,\n\t PairCollectionViewEdit: PairCollectionViewEdit,\n\t ListOfPairsCollectionViewEdit: ListOfPairsCollectionViewEdit,\n\t ListOfListsCollectionViewEdit: ListOfListsCollectionViewEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 121 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(151), __webpack_require__(98), __webpack_require__(80), __webpack_require__(7), __webpack_require__(6), __webpack_require__(95)], __WEBPACK_AMD_DEFINE_RESULT__ = function (levenshteinDistance, naturalSort, baseCreator, baseMVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /* ============================================================================\n\t TODO:\n\t \n\t \n\t PROGRAMMATICALLY:\n\t currPanel.once( 'rendered', function(){\n\t currPanel.showSelectors();\n\t currPanel.selectAll();\n\t _.last( currPanel.actionsPopup.options ).func();\n\t });\n\t \n\t ============================================================================ */\n\t /** A view for paired datasets in the collections creator.\n\t */\n\t var PairView = Backbone.View.extend(baseMVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t tagName: 'li',\n\t className: 'dataset paired',\n\t\n\t initialize: function (attributes) {\n\t this.pair = attributes.pair || {};\n\t },\n\t\n\t template: _.template(['<%- pair.forward.name %>', '', '<%- pair.name %>', '', '<%- pair.reverse.name %>'].join('')),\n\t\n\t render: function () {\n\t this.$el.attr('draggable', true).data('pair', this.pair).html(this.template({ pair: this.pair })).addClass('flex-column-container');\n\t return this;\n\t },\n\t\n\t events: {\n\t 'dragstart': '_dragstart',\n\t 'dragend': '_dragend',\n\t 'dragover': '_sendToParent',\n\t 'drop': '_sendToParent'\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragstart: function (ev) {\n\t ev.currentTarget.style.opacity = '0.4';\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t\n\t ev.dataTransfer.effectAllowed = 'move';\n\t ev.dataTransfer.setData('text/plain', JSON.stringify(this.pair));\n\t\n\t this.$el.parent().trigger('pair.dragstart', [this]);\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragend: function (ev) {\n\t ev.currentTarget.style.opacity = '1.0';\n\t this.$el.parent().trigger('pair.dragend', [this]);\n\t },\n\t\n\t /** manually bubble up an event to the parent/container */\n\t _sendToParent: function (ev) {\n\t this.$el.parent().trigger(ev);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'PairView(' + this.pair.name + ')';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t /** returns an autopair function that uses the provided options.match function */\n\t function autoPairFnBuilder(options) {\n\t options = options || {};\n\t options.createPair = options.createPair || function _defaultCreatePair(params) {\n\t params = params || {};\n\t var a = params.listA.splice(params.indexA, 1)[0],\n\t b = params.listB.splice(params.indexB, 1)[0],\n\t aInBIndex = params.listB.indexOf(a),\n\t bInAIndex = params.listA.indexOf(b);\n\t if (aInBIndex !== -1) {\n\t params.listB.splice(aInBIndex, 1);\n\t }\n\t if (bInAIndex !== -1) {\n\t params.listA.splice(bInAIndex, 1);\n\t }\n\t return this._pair(a, b, { silent: true });\n\t };\n\t // compile these here outside of the loop\n\t var _regexps = [];\n\t function getRegExps() {\n\t if (!_regexps.length) {\n\t _regexps = [new RegExp(this.filters[0]), new RegExp(this.filters[1])];\n\t }\n\t return _regexps;\n\t }\n\t // mangle params as needed\n\t options.preprocessMatch = options.preprocessMatch || function _defaultPreprocessMatch(params) {\n\t var regexps = getRegExps.call(this);\n\t return _.extend(params, {\n\t matchTo: params.matchTo.name.replace(regexps[0], ''),\n\t possible: params.possible.name.replace(regexps[1], '')\n\t });\n\t };\n\t\n\t return function _strategy(params) {\n\t this.debug('autopair _strategy ---------------------------');\n\t params = params || {};\n\t var listA = params.listA,\n\t listB = params.listB,\n\t indexA = 0,\n\t indexB,\n\t bestMatch = {\n\t score: 0.0,\n\t index: null\n\t },\n\t paired = [];\n\t //console.debug( 'params:', JSON.stringify( params, null, ' ' ) );\n\t this.debug('starting list lens:', listA.length, listB.length);\n\t this.debug('bestMatch (starting):', JSON.stringify(bestMatch, null, ' '));\n\t\n\t while (indexA < listA.length) {\n\t var matchTo = listA[indexA];\n\t bestMatch.score = 0.0;\n\t\n\t for (indexB = 0; indexB < listB.length; indexB++) {\n\t var possible = listB[indexB];\n\t this.debug(indexA + ':' + matchTo.name);\n\t this.debug(indexB + ':' + possible.name);\n\t\n\t // no matching with self\n\t if (listA[indexA] !== listB[indexB]) {\n\t bestMatch = options.match.call(this, options.preprocessMatch.call(this, {\n\t matchTo: matchTo,\n\t possible: possible,\n\t index: indexB,\n\t bestMatch: bestMatch\n\t }));\n\t this.debug('bestMatch:', JSON.stringify(bestMatch, null, ' '));\n\t if (bestMatch.score === 1.0) {\n\t this.debug('breaking early due to perfect match');\n\t break;\n\t }\n\t }\n\t }\n\t var scoreThreshold = options.scoreThreshold.call(this);\n\t this.debug('scoreThreshold:', scoreThreshold);\n\t this.debug('bestMatch.score:', bestMatch.score);\n\t\n\t if (bestMatch.score >= scoreThreshold) {\n\t //console.debug( 'autoPairFnBuilder.strategy', listA[ indexA ].name, listB[ bestMatch.index ].name );\n\t paired.push(options.createPair.call(this, {\n\t listA: listA,\n\t indexA: indexA,\n\t listB: listB,\n\t indexB: bestMatch.index\n\t }));\n\t //console.debug( 'list lens now:', listA.length, listB.length );\n\t } else {\n\t indexA += 1;\n\t }\n\t if (!listA.length || !listB.length) {\n\t return paired;\n\t }\n\t }\n\t this.debug('paired:', JSON.stringify(paired, null, ' '));\n\t this.debug('autopair _strategy ---------------------------');\n\t return paired;\n\t };\n\t }\n\t\n\t // ============================================================================\n\t /** An interface for building collections of paired datasets.\n\t */\n\t var PairedCollectionCreator = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseCreator.CollectionCreatorMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t className: 'list-of-pairs-collection-creator collection-creator flex-row-container',\n\t\n\t /** set up initial options, instance vars, behaviors, and autopair (if set to do so) */\n\t initialize: function (attributes) {\n\t this.metric('PairedCollectionCreator.initialize', attributes);\n\t //this.debug( '-- PairedCollectionCreator:', attributes );\n\t\n\t attributes = _.defaults(attributes, {\n\t datasets: [],\n\t filters: this.DEFAULT_FILTERS,\n\t automaticallyPair: true,\n\t strategy: 'lcs',\n\t matchPercentage: 0.9,\n\t twoPassAutopairing: true\n\t });\n\t\n\t /** unordered, original list */\n\t this.initialList = attributes.datasets;\n\t\n\t /** is this from a history? if so, what's its id? */\n\t this.historyId = attributes.historyId;\n\t\n\t /** which filters should be used initially? (String[2] or name in commonFilters) */\n\t this.filters = this.commonFilters[attributes.filters] || this.commonFilters[this.DEFAULT_FILTERS];\n\t if (_.isArray(attributes.filters)) {\n\t this.filters = attributes.filters;\n\t }\n\t\n\t /** try to auto pair the unpaired datasets on load? */\n\t this.automaticallyPair = attributes.automaticallyPair;\n\t\n\t /** what method to use for auto pairing (will be passed aggression level) */\n\t this.strategy = this.strategies[attributes.strategy] || this.strategies[this.DEFAULT_STRATEGY];\n\t if (_.isFunction(attributes.strategy)) {\n\t this.strategy = attributes.strategy;\n\t }\n\t\n\t /** distance/mismatch level allowed for autopairing */\n\t this.matchPercentage = attributes.matchPercentage;\n\t\n\t /** try to autopair using simple first, then this.strategy on the remainder */\n\t this.twoPassAutopairing = attributes.twoPassAutopairing;\n\t\n\t /** remove file extensions (\\.*) from created pair names? */\n\t this.removeExtensions = true;\n\t //this.removeExtensions = false;\n\t\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t this.oncancel = attributes.oncancel;\n\t /** fn to call when the collection is created (scoped to this) */\n\t this.oncreate = attributes.oncreate;\n\t\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t this.autoscrollDist = attributes.autoscrollDist || 24;\n\t\n\t /** is the unpaired panel shown? */\n\t this.unpairedPanelHidden = false;\n\t /** is the paired panel shown? */\n\t this.pairedPanelHidden = false;\n\t\n\t /** DOM elements currently being dragged */\n\t this.$dragging = null;\n\t\n\t /** Used for blocking UI events during ajax/operations (don't post twice) */\n\t this.blocking = false;\n\t\n\t this._setUpCommonSettings(attributes);\n\t this._setUpBehaviors();\n\t this._dataSetUp();\n\t },\n\t\n\t /** map of common filter pairs by name */\n\t commonFilters: {\n\t illumina: ['_1', '_2'],\n\t Rs: ['_R1', '_R2']\n\t },\n\t /** which commonFilter to use by default */\n\t DEFAULT_FILTERS: 'illumina',\n\t\n\t /** map of name->fn for autopairing */\n\t strategies: {\n\t 'simple': 'autopairSimple',\n\t 'lcs': 'autopairLCS',\n\t 'levenshtein': 'autopairLevenshtein'\n\t },\n\t /** default autopair strategy name */\n\t DEFAULT_STRATEGY: 'lcs',\n\t\n\t // ------------------------------------------------------------------------ process raw list\n\t /** set up main data: cache initialList, sort, and autopair */\n\t _dataSetUp: function () {\n\t //this.debug( '-- _dataSetUp' );\n\t\n\t this.paired = [];\n\t this.unpaired = [];\n\t\n\t this.selectedIds = [];\n\t\n\t // sort initial list, add ids if needed, and save new working copy to unpaired\n\t this._sortInitialList();\n\t this._ensureIds();\n\t this.unpaired = this.initialList.slice(0);\n\t\n\t if (this.automaticallyPair) {\n\t this.autoPair();\n\t this.once('rendered:initial', function () {\n\t this.trigger('autopair');\n\t });\n\t }\n\t },\n\t\n\t /** sort initial list */\n\t _sortInitialList: function () {\n\t //this.debug( '-- _sortInitialList' );\n\t this._sortDatasetList(this.initialList);\n\t },\n\t\n\t /** sort a list of datasets */\n\t _sortDatasetList: function (list) {\n\t // currently only natural sort by name\n\t list.sort(function (a, b) {\n\t return naturalSort(a.name, b.name);\n\t });\n\t return list;\n\t },\n\t\n\t /** add ids to dataset objs in initial list if none */\n\t _ensureIds: function () {\n\t this.initialList.forEach(function (dataset) {\n\t if (!dataset.hasOwnProperty('id')) {\n\t dataset.id = _.uniqueId();\n\t }\n\t });\n\t return this.initialList;\n\t },\n\t\n\t /** split initial list into two lists, those that pass forward filters & those passing reverse */\n\t _splitByFilters: function () {\n\t var regexFilters = this.filters.map(function (stringFilter) {\n\t return new RegExp(stringFilter);\n\t }),\n\t split = [[], []];\n\t\n\t function _filter(unpaired, filter) {\n\t return filter.test(unpaired.name);\n\t //return dataset.name.indexOf( filter ) >= 0;\n\t }\n\t this.unpaired.forEach(function _filterEach(unpaired) {\n\t // 90% of the time this seems to work, but:\n\t //TODO: this treats *all* strings as regex which may confuse people - possibly check for // surrounding?\n\t // would need explanation in help as well\n\t regexFilters.forEach(function (filter, i) {\n\t if (_filter(unpaired, filter)) {\n\t split[i].push(unpaired);\n\t }\n\t });\n\t });\n\t return split;\n\t },\n\t\n\t /** add a dataset to the unpaired list in it's proper order */\n\t _addToUnpaired: function (dataset) {\n\t // currently, unpaired is natural sorted by name, use binary search to find insertion point\n\t var binSearchSortedIndex = function (low, hi) {\n\t if (low === hi) {\n\t return low;\n\t }\n\t\n\t var mid = Math.floor((hi - low) / 2) + low,\n\t compared = naturalSort(dataset.name, this.unpaired[mid].name);\n\t\n\t if (compared < 0) {\n\t return binSearchSortedIndex(low, mid);\n\t } else if (compared > 0) {\n\t return binSearchSortedIndex(mid + 1, hi);\n\t }\n\t // walk the equal to find the last\n\t while (this.unpaired[mid] && this.unpaired[mid].name === dataset.name) {\n\t mid++;\n\t }\n\t return mid;\n\t }.bind(this);\n\t\n\t this.unpaired.splice(binSearchSortedIndex(0, this.unpaired.length), 0, dataset);\n\t },\n\t\n\t // ------------------------------------------------------------------------ auto pairing\n\t /** two passes to automatically create pairs:\n\t * use both simpleAutoPair, then the fn mentioned in strategy\n\t */\n\t autoPair: function (strategy) {\n\t // split first using exact matching\n\t var split = this._splitByFilters(),\n\t paired = [];\n\t if (this.twoPassAutopairing) {\n\t paired = this.autopairSimple({\n\t listA: split[0],\n\t listB: split[1]\n\t });\n\t split = this._splitByFilters();\n\t }\n\t\n\t // uncomment to see printlns while running tests\n\t //this.debug = function(){ console.log.apply( console, arguments ); };\n\t\n\t // then try the remainder with something less strict\n\t strategy = strategy || this.strategy;\n\t split = this._splitByFilters();\n\t paired = paired.concat(this[strategy].call(this, {\n\t listA: split[0],\n\t listB: split[1]\n\t }));\n\t return paired;\n\t },\n\t\n\t /** autopair by exact match */\n\t autopairSimple: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return 1.0;\n\t },\n\t match: function _match(params) {\n\t params = params || {};\n\t if (params.matchTo === params.possible) {\n\t return {\n\t index: params.index,\n\t score: 1.0\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** autopair by levenshtein edit distance scoring */\n\t autopairLevenshtein: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return this.matchPercentage;\n\t },\n\t match: function _matches(params) {\n\t params = params || {};\n\t var distance = levenshteinDistance(params.matchTo, params.possible),\n\t score = 1.0 - distance / Math.max(params.matchTo.length, params.possible.length);\n\t if (score > params.bestMatch.score) {\n\t return {\n\t index: params.index,\n\t score: score\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** autopair by longest common substrings scoring */\n\t autopairLCS: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return this.matchPercentage;\n\t },\n\t match: function _matches(params) {\n\t params = params || {};\n\t var match = this._naiveStartingAndEndingLCS(params.matchTo, params.possible).length,\n\t score = match / Math.max(params.matchTo.length, params.possible.length);\n\t if (score > params.bestMatch.score) {\n\t return {\n\t index: params.index,\n\t score: score\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** return the concat'd longest common prefix and suffix from two strings */\n\t _naiveStartingAndEndingLCS: function (s1, s2) {\n\t var fwdLCS = '',\n\t revLCS = '',\n\t i = 0,\n\t j = 0;\n\t while (i < s1.length && i < s2.length) {\n\t if (s1[i] !== s2[i]) {\n\t break;\n\t }\n\t fwdLCS += s1[i];\n\t i += 1;\n\t }\n\t if (i === s1.length) {\n\t return s1;\n\t }\n\t if (i === s2.length) {\n\t return s2;\n\t }\n\t\n\t i = s1.length - 1;\n\t j = s2.length - 1;\n\t while (i >= 0 && j >= 0) {\n\t if (s1[i] !== s2[j]) {\n\t break;\n\t }\n\t revLCS = [s1[i], revLCS].join('');\n\t i -= 1;\n\t j -= 1;\n\t }\n\t return fwdLCS + revLCS;\n\t },\n\t\n\t // ------------------------------------------------------------------------ pairing / unpairing\n\t /** create a pair from fwd and rev, removing them from unpaired, and placing the new pair in paired */\n\t _pair: function (fwd, rev, options) {\n\t options = options || {};\n\t this.debug('_pair:', fwd, rev);\n\t var pair = this._createPair(fwd, rev, options.name);\n\t this.paired.push(pair);\n\t this.unpaired = _.without(this.unpaired, fwd, rev);\n\t if (!options.silent) {\n\t this.trigger('pair:new', pair);\n\t }\n\t return pair;\n\t },\n\t\n\t /** create a pair Object from fwd and rev, adding the name attribute (will guess if not given) */\n\t _createPair: function (fwd, rev, name) {\n\t // ensure existance and don't pair something with itself\n\t if (!(fwd && rev) || fwd === rev) {\n\t throw new Error('Bad pairing: ' + [JSON.stringify(fwd), JSON.stringify(rev)]);\n\t }\n\t name = name || this._guessNameForPair(fwd, rev);\n\t return { forward: fwd, name: name, reverse: rev };\n\t },\n\t\n\t /** try to find a good pair name for the given fwd and rev datasets */\n\t _guessNameForPair: function (fwd, rev, removeExtensions) {\n\t removeExtensions = removeExtensions !== undefined ? removeExtensions : this.removeExtensions;\n\t var fwdName = fwd.name,\n\t revName = rev.name,\n\t lcs = this._naiveStartingAndEndingLCS(fwdName.replace(new RegExp(this.filters[0]), ''), revName.replace(new RegExp(this.filters[1]), ''));\n\t if (removeExtensions) {\n\t var lastDotIndex = lcs.lastIndexOf('.');\n\t if (lastDotIndex > 0) {\n\t var extension = lcs.slice(lastDotIndex, lcs.length);\n\t lcs = lcs.replace(extension, '');\n\t fwdName = fwdName.replace(extension, '');\n\t revName = revName.replace(extension, '');\n\t }\n\t }\n\t return lcs || fwdName + ' & ' + revName;\n\t },\n\t\n\t /** unpair a pair, removing it from paired, and adding the fwd,rev datasets back into unpaired */\n\t _unpair: function (pair, options) {\n\t options = options || {};\n\t if (!pair) {\n\t throw new Error('Bad pair: ' + JSON.stringify(pair));\n\t }\n\t this.paired = _.without(this.paired, pair);\n\t this._addToUnpaired(pair.forward);\n\t this._addToUnpaired(pair.reverse);\n\t\n\t if (!options.silent) {\n\t this.trigger('pair:unpair', [pair]);\n\t }\n\t return pair;\n\t },\n\t\n\t /** unpair all paired datasets */\n\t unpairAll: function () {\n\t var pairs = [];\n\t while (this.paired.length) {\n\t pairs.push(this._unpair(this.paired[0], { silent: true }));\n\t }\n\t this.trigger('pair:unpair', pairs);\n\t },\n\t\n\t // ------------------------------------------------------------------------ API\n\t /** convert a pair into JSON compatible with the collections API */\n\t _pairToJSON: function (pair, src) {\n\t src = src || 'hda';\n\t //TODO: consider making this the pair structure when created instead\n\t return {\n\t collection_type: 'paired',\n\t src: 'new_collection',\n\t name: pair.name,\n\t element_identifiers: [{\n\t name: 'forward',\n\t id: pair.forward.id,\n\t src: src\n\t }, {\n\t name: 'reverse',\n\t id: pair.reverse.id,\n\t src: src\n\t }]\n\t };\n\t },\n\t\n\t /** create the collection via the API\n\t * @returns {jQuery.xhr Object} the jquery ajax request\n\t */\n\t createList: function (name) {\n\t var creator = this,\n\t url = Galaxy.root + 'api/histories/' + this.historyId + '/contents/dataset_collections';\n\t\n\t //TODO: use ListPairedCollection.create()\n\t var ajaxData = {\n\t type: 'dataset_collection',\n\t collection_type: 'list:paired',\n\t hide_source_items: creator.hideOriginals || false,\n\t name: _.escape(name || creator.$('.collection-name').val()),\n\t element_identifiers: creator.paired.map(function (pair) {\n\t return creator._pairToJSON(pair);\n\t })\n\t\n\t };\n\t //this.debug( JSON.stringify( ajaxData ) );\n\t creator.blocking = true;\n\t return jQuery.ajax(url, {\n\t type: 'POST',\n\t contentType: 'application/json',\n\t dataType: 'json',\n\t data: JSON.stringify(ajaxData)\n\t }).always(function () {\n\t creator.blocking = false;\n\t }).fail(function (xhr, status, message) {\n\t creator._ajaxErrHandler(xhr, status, message);\n\t }).done(function (response, message, xhr) {\n\t //this.info( 'ok', response, message, xhr );\n\t creator.trigger('collection:created', response, message, xhr);\n\t creator.metric('collection:created', response);\n\t if (typeof creator.oncreate === 'function') {\n\t creator.oncreate.call(this, response, message, xhr);\n\t }\n\t });\n\t },\n\t\n\t /** handle ajax errors with feedback and details to the user (if available) */\n\t _ajaxErrHandler: function (xhr, status, message) {\n\t this.error(xhr, status, message);\n\t var content = _l('An error occurred while creating this collection');\n\t if (xhr) {\n\t if (xhr.readyState === 0 && xhr.status === 0) {\n\t content += ': ' + _l('Galaxy could not be reached and may be updating.') + _l(' Try again in a few minutes.');\n\t } else if (xhr.responseJSON) {\n\t content += '
                ' + JSON.stringify(xhr.responseJSON) + '
                ';\n\t } else {\n\t content += ': ' + message;\n\t }\n\t }\n\t creator._showAlert(content, 'alert-danger');\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t //this.$el.empty().html( this.templates.main() );\n\t this.$el.empty().html(this.templates.main());\n\t this._renderHeader(speed);\n\t this._renderMiddle(speed);\n\t this._renderFooter(speed);\n\t this._addPluginComponents();\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render the header section */\n\t _renderHeader: function (speed, callback) {\n\t //this.debug( '-- _renderHeader' );\n\t var $header = this.$('.header').empty().html(this.templates.header()).find('.help-content').prepend($(this.templates.helpContent()));\n\t\n\t this._renderFilters();\n\t return $header;\n\t },\n\t /** fill the filter inputs with the filter values */\n\t _renderFilters: function () {\n\t return this.$('.forward-column .column-header input').val(this.filters[0]).add(this.$('.reverse-column .column-header input').val(this.filters[1]));\n\t },\n\t\n\t /** render the middle including unpaired and paired sections (which may be hidden) */\n\t _renderMiddle: function (speed, callback) {\n\t var $middle = this.$('.middle').empty().html(this.templates.middle());\n\t\n\t // (re-) hide the un/paired panels based on instance vars\n\t if (this.unpairedPanelHidden) {\n\t this.$('.unpaired-columns').hide();\n\t } else if (this.pairedPanelHidden) {\n\t this.$('.paired-columns').hide();\n\t }\n\t\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t return $middle;\n\t },\n\t /** render the unpaired section, showing datasets accrd. to filters, update the unpaired counts */\n\t _renderUnpaired: function (speed, callback) {\n\t //this.debug( '-- _renderUnpaired' );\n\t var creator = this,\n\t $fwd,\n\t $rev,\n\t $prd = [],\n\t split = this._splitByFilters();\n\t // update unpaired counts\n\t this.$('.forward-column .title').text([split[0].length, _l('unpaired forward')].join(' '));\n\t this.$('.forward-column .unpaired-info').text(this._renderUnpairedDisplayStr(this.unpaired.length - split[0].length));\n\t this.$('.reverse-column .title').text([split[1].length, _l('unpaired reverse')].join(' '));\n\t this.$('.reverse-column .unpaired-info').text(this._renderUnpairedDisplayStr(this.unpaired.length - split[1].length));\n\t\n\t this.$('.unpaired-columns .column-datasets').empty();\n\t\n\t // show/hide the auto pair button if any unpaired are left\n\t this.$('.autopair-link').toggle(this.unpaired.length !== 0);\n\t if (this.unpaired.length === 0) {\n\t this._renderUnpairedEmpty();\n\t return;\n\t }\n\t\n\t // create the dataset dom arrays\n\t $rev = split[1].map(function (dataset, i) {\n\t // if there'll be a fwd dataset across the way, add a button to pair the row\n\t if (split[0][i] !== undefined && split[0][i] !== dataset) {\n\t $prd.push(creator._renderPairButton());\n\t }\n\t return creator._renderUnpairedDataset(dataset);\n\t });\n\t $fwd = split[0].map(function (dataset) {\n\t return creator._renderUnpairedDataset(dataset);\n\t });\n\t\n\t if (!$fwd.length && !$rev.length) {\n\t this._renderUnpairedNotShown();\n\t return;\n\t }\n\t // add to appropo cols\n\t //TODO: not the best way to render - consider rendering the entire unpaired-columns section in a fragment\n\t // and swapping out that\n\t this.$('.unpaired-columns .forward-column .column-datasets').append($fwd).add(this.$('.unpaired-columns .paired-column .column-datasets').append($prd)).add(this.$('.unpaired-columns .reverse-column .column-datasets').append($rev));\n\t this._adjUnpairedOnScrollbar();\n\t },\n\t /** return a string to display the count of filtered out datasets */\n\t _renderUnpairedDisplayStr: function (numFiltered) {\n\t return ['(', numFiltered, ' ', _l('filtered out'), ')'].join('');\n\t },\n\t /** return an unattached jQuery DOM element to represent an unpaired dataset */\n\t _renderUnpairedDataset: function (dataset) {\n\t //TODO: to underscore template\n\t return $('
              • ').attr('id', 'dataset-' + dataset.id).addClass('dataset unpaired').attr('draggable', true).addClass(dataset.selected ? 'selected' : '').append($('').addClass('dataset-name').text(dataset.name))\n\t //??\n\t .data('dataset', dataset);\n\t },\n\t /** render the button that may go between unpaired datasets, allowing the user to pair a row */\n\t _renderPairButton: function () {\n\t //TODO: *not* a dataset - don't pretend like it is\n\t return $('
              • ').addClass('dataset unpaired').append($('').addClass('dataset-name').text(_l('Pair these datasets')));\n\t },\n\t /** a message to display when no unpaired left */\n\t _renderUnpairedEmpty: function () {\n\t //this.debug( '-- renderUnpairedEmpty' );\n\t var $msg = $('
                ').text('(' + _l('no remaining unpaired datasets') + ')');\n\t this.$('.unpaired-columns .paired-column .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t /** a message to display when no unpaired can be shown with the current filters */\n\t _renderUnpairedNotShown: function () {\n\t //this.debug( '-- renderUnpairedEmpty' );\n\t var $msg = $('
                ').text('(' + _l('no datasets were found matching the current filters') + ')');\n\t this.$('.unpaired-columns .paired-column .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t /** try to detect if the unpaired section has a scrollbar and adjust left column for better centering of all */\n\t _adjUnpairedOnScrollbar: function () {\n\t var $unpairedColumns = this.$('.unpaired-columns').last(),\n\t $firstDataset = this.$('.unpaired-columns .reverse-column .dataset').first();\n\t if (!$firstDataset.length) {\n\t return;\n\t }\n\t var ucRight = $unpairedColumns.offset().left + $unpairedColumns.outerWidth(),\n\t dsRight = $firstDataset.offset().left + $firstDataset.outerWidth(),\n\t rightDiff = Math.floor(ucRight) - Math.floor(dsRight);\n\t //this.debug( 'rightDiff:', ucRight, '-', dsRight, '=', rightDiff );\n\t this.$('.unpaired-columns .forward-column').css('margin-left', rightDiff > 0 ? rightDiff : 0);\n\t },\n\t\n\t /** render the paired section and update counts of paired datasets */\n\t _renderPaired: function (speed, callback) {\n\t //this.debug( '-- _renderPaired' );\n\t this.$('.paired-column-title .title').text([this.paired.length, _l('paired')].join(' '));\n\t // show/hide the unpair all link\n\t this.$('.unpair-all-link').toggle(this.paired.length !== 0);\n\t if (this.paired.length === 0) {\n\t this._renderPairedEmpty();\n\t return;\n\t //TODO: would be best to return here (the $columns)\n\t } else {\n\t // show/hide 'remove extensions link' when any paired and they seem to have extensions\n\t this.$('.remove-extensions-link').show();\n\t }\n\t\n\t this.$('.paired-columns .column-datasets').empty();\n\t var creator = this;\n\t this.paired.forEach(function (pair, i) {\n\t //TODO: cache these?\n\t var pairView = new PairView({ pair: pair });\n\t creator.$('.paired-columns .column-datasets').append(pairView.render().$el).append([''].join(''));\n\t });\n\t },\n\t /** a message to display when none paired */\n\t _renderPairedEmpty: function () {\n\t var $msg = $('
                ').text('(' + _l('no paired datasets yet') + ')');\n\t this.$('.paired-columns .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t\n\t footerSettings: {\n\t '.hide-originals': 'hideOriginals',\n\t '.remove-extensions': 'removeExtensions'\n\t },\n\t\n\t /** add any jQuery/bootstrap/custom plugins to elements rendered */\n\t _addPluginComponents: function () {\n\t this._chooseFiltersPopover('.choose-filters-link');\n\t this.$('.help-content i').hoverhighlight('.collection-creator', 'rgba( 64, 255, 255, 1.0 )');\n\t },\n\t\n\t /** build a filter selection popover allowing selection of common filter pairs */\n\t _chooseFiltersPopover: function (selector) {\n\t function filterChoice(val1, val2) {\n\t return [''].join('');\n\t }\n\t var $popoverContent = $(_.template(['
                ', '
                ', _l('Choose from the following filters to change which unpaired reads are shown in the display'), ':
                ', _.values(this.commonFilters).map(function (filterSet) {\n\t return filterChoice(filterSet[0], filterSet[1]);\n\t }).join(''), '
                '].join(''))({}));\n\t\n\t return this.$(selector).popover({\n\t container: '.collection-creator',\n\t placement: 'bottom',\n\t html: true,\n\t //animation : false,\n\t content: $popoverContent\n\t });\n\t },\n\t\n\t /** add (or clear if clear is truthy) a validation warning to what */\n\t _validationWarning: function (what, clear) {\n\t var VALIDATION_CLASS = 'validation-warning';\n\t if (what === 'name') {\n\t what = this.$('.collection-name').add(this.$('.collection-name-prompt'));\n\t this.$('.collection-name').focus().select();\n\t }\n\t if (clear) {\n\t what = what || this.$('.' + VALIDATION_CLASS);\n\t what.removeClass(VALIDATION_CLASS);\n\t } else {\n\t what.addClass(VALIDATION_CLASS);\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ events\n\t /** set up event handlers on self */\n\t _setUpBehaviors: function () {\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this.on('pair:new', function () {\n\t //TODO: ideally only re-render the columns (or even elements) involved\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t\n\t // scroll to bottom where new pairs are added\n\t //TODO: this doesn't seem to work - innerHeight sticks at 133...\n\t // may have to do with improper flex columns\n\t //var $pairedView = this.$( '.paired-columns' );\n\t //$pairedView.scrollTop( $pairedView.innerHeight() );\n\t //this.debug( $pairedView.height() )\n\t this.$('.paired-columns').scrollTop(8000000);\n\t });\n\t this.on('pair:unpair', function (pairs) {\n\t //TODO: ideally only re-render the columns (or even elements) involved\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t this.splitView();\n\t });\n\t\n\t this.on('filter-change', function () {\n\t this.filters = [this.$('.forward-unpaired-filter input').val(), this.$('.reverse-unpaired-filter input').val()];\n\t this.metric('filter-change', this.filters);\n\t this._renderFilters();\n\t this._renderUnpaired();\n\t });\n\t\n\t this.on('autopair', function () {\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t\n\t var message,\n\t msgClass = null;\n\t if (this.paired.length) {\n\t msgClass = 'alert-success';\n\t message = this.paired.length + ' ' + _l('pairs created');\n\t if (!this.unpaired.length) {\n\t message += ': ' + _l('all datasets have been successfully paired');\n\t this.hideUnpaired();\n\t this.$('.collection-name').focus();\n\t }\n\t } else {\n\t message = _l(['Could not automatically create any pairs from the given dataset names.', 'You may want to choose or enter different filters and try auto-pairing again.', 'Close this message using the X on the right to view more help.'].join(' '));\n\t }\n\t this._showAlert(message, msgClass);\n\t });\n\t\n\t //this.on( 'all', function(){\n\t // this.info( arguments );\n\t //});\n\t return this;\n\t },\n\t\n\t events: {\n\t // header\n\t 'click .more-help': '_clickMoreHelp',\n\t 'click .less-help': '_clickLessHelp',\n\t 'click .main-help': '_toggleHelp',\n\t 'click .header .alert button': '_hideAlert',\n\t 'click .forward-column .column-title': '_clickShowOnlyUnpaired',\n\t 'click .reverse-column .column-title': '_clickShowOnlyUnpaired',\n\t 'click .unpair-all-link': '_clickUnpairAll',\n\t //TODO: this seems kinda backasswards - re-sending jq event as a backbone event, can we listen directly?\n\t 'change .forward-unpaired-filter input': function (ev) {\n\t this.trigger('filter-change');\n\t },\n\t 'focus .forward-unpaired-filter input': function (ev) {\n\t $(ev.currentTarget).select();\n\t },\n\t 'click .autopair-link': '_clickAutopair',\n\t 'click .choose-filters .filter-choice': '_clickFilterChoice',\n\t 'click .clear-filters-link': '_clearFilters',\n\t 'change .reverse-unpaired-filter input': function (ev) {\n\t this.trigger('filter-change');\n\t },\n\t 'focus .reverse-unpaired-filter input': function (ev) {\n\t $(ev.currentTarget).select();\n\t },\n\t // unpaired\n\t 'click .forward-column .dataset.unpaired': '_clickUnpairedDataset',\n\t 'click .reverse-column .dataset.unpaired': '_clickUnpairedDataset',\n\t 'click .paired-column .dataset.unpaired': '_clickPairRow',\n\t 'click .unpaired-columns': 'clearSelectedUnpaired',\n\t 'mousedown .unpaired-columns .dataset': '_mousedownUnpaired',\n\t // divider\n\t 'click .paired-column-title': '_clickShowOnlyPaired',\n\t 'mousedown .flexible-partition-drag': '_startPartitionDrag',\n\t // paired\n\t 'click .paired-columns .dataset.paired': 'selectPair',\n\t 'click .paired-columns': 'clearSelectedPaired',\n\t 'click .paired-columns .pair-name': '_clickPairName',\n\t 'click .unpair-btn': '_clickUnpair',\n\t // paired - drop target\n\t //'dragenter .paired-columns' : '_dragenterPairedColumns',\n\t //'dragleave .paired-columns .column-datasets': '_dragleavePairedColumns',\n\t 'dragover .paired-columns .column-datasets': '_dragoverPairedColumns',\n\t 'drop .paired-columns .column-datasets': '_dropPairedColumns',\n\t\n\t 'pair.dragstart .paired-columns .column-datasets': '_pairDragstart',\n\t 'pair.dragend .paired-columns .column-datasets': '_pairDragend',\n\t\n\t // footer\n\t 'change .remove-extensions': function (ev) {\n\t this.toggleExtensions();\n\t },\n\t 'change .collection-name': '_changeName',\n\t 'keydown .collection-name': '_nameCheckForEnter',\n\t 'change .hide-originals': '_changeHideOriginals',\n\t 'click .cancel-create': '_cancelCreate',\n\t 'click .create-collection': '_clickCreate' //,\n\t },\n\t\n\t /** toggle between showing only unpaired and split view */\n\t _clickShowOnlyUnpaired: function (ev) {\n\t //this.debug( 'click unpaired', ev.currentTarget );\n\t if (this.$('.paired-columns').is(':visible')) {\n\t this.hidePaired();\n\t } else {\n\t this.splitView();\n\t }\n\t },\n\t /** toggle between showing only paired and split view */\n\t _clickShowOnlyPaired: function (ev) {\n\t //this.debug( 'click paired' );\n\t if (this.$('.unpaired-columns').is(':visible')) {\n\t this.hideUnpaired();\n\t } else {\n\t this.splitView();\n\t }\n\t },\n\t\n\t /** hide unpaired, show paired */\n\t hideUnpaired: function (speed, callback) {\n\t this.unpairedPanelHidden = true;\n\t this.pairedPanelHidden = false;\n\t this._renderMiddle(speed, callback);\n\t },\n\t /** hide paired, show unpaired */\n\t hidePaired: function (speed, callback) {\n\t this.unpairedPanelHidden = false;\n\t this.pairedPanelHidden = true;\n\t this._renderMiddle(speed, callback);\n\t },\n\t /** show both paired and unpaired (splitting evenly) */\n\t splitView: function (speed, callback) {\n\t this.unpairedPanelHidden = this.pairedPanelHidden = false;\n\t this._renderMiddle(speed, callback);\n\t return this;\n\t },\n\t\n\t /** unpair all paired and do other super neat stuff which I'm not really sure about yet... */\n\t _clickUnpairAll: function (ev) {\n\t this.metric('unpairAll');\n\t this.unpairAll();\n\t },\n\t\n\t /** attempt to autopair */\n\t _clickAutopair: function (ev) {\n\t var paired = this.autoPair();\n\t this.metric('autopair', paired.length, this.unpaired.length);\n\t this.trigger('autopair');\n\t },\n\t\n\t /** set the filters based on the data attributes of the button click target */\n\t _clickFilterChoice: function (ev) {\n\t var $selected = $(ev.currentTarget);\n\t this.$('.forward-unpaired-filter input').val($selected.data('forward'));\n\t this.$('.reverse-unpaired-filter input').val($selected.data('reverse'));\n\t this._hideChooseFilters();\n\t this.trigger('filter-change');\n\t },\n\t\n\t /** hide the choose filters popover */\n\t _hideChooseFilters: function () {\n\t //TODO: update bootstrap and remove the following hack\n\t // see also: https://github.com/twbs/bootstrap/issues/10260\n\t this.$('.choose-filters-link').popover('hide');\n\t this.$('.popover').css('display', 'none');\n\t },\n\t\n\t /** clear both filters */\n\t _clearFilters: function (ev) {\n\t this.$('.forward-unpaired-filter input').val('');\n\t this.$('.reverse-unpaired-filter input').val('');\n\t this.trigger('filter-change');\n\t },\n\t\n\t // ........................................................................ unpaired\n\t /** select an unpaired dataset */\n\t _clickUnpairedDataset: function (ev) {\n\t ev.stopPropagation();\n\t return this.toggleSelectUnpaired($(ev.currentTarget));\n\t },\n\t\n\t /** Toggle the selection of an unpaired dataset representation.\n\t * @param [jQuery] $dataset the unpaired dataset dom rep to select\n\t * @param [Boolean] options.force if defined, force selection based on T/F; otherwise, toggle\n\t */\n\t toggleSelectUnpaired: function ($dataset, options) {\n\t options = options || {};\n\t var dataset = $dataset.data('dataset'),\n\t select = options.force !== undefined ? options.force : !$dataset.hasClass('selected');\n\t //this.debug( id, options.force, $dataset, dataset );\n\t if (!$dataset.length || dataset === undefined) {\n\t return $dataset;\n\t }\n\t\n\t if (select) {\n\t $dataset.addClass('selected');\n\t if (!options.waitToPair) {\n\t this.pairAllSelected();\n\t }\n\t } else {\n\t $dataset.removeClass('selected');\n\t //delete dataset.selected;\n\t }\n\t return $dataset;\n\t },\n\t\n\t /** pair all the currently selected unpaired datasets */\n\t pairAllSelected: function (options) {\n\t options = options || {};\n\t var creator = this,\n\t fwds = [],\n\t revs = [],\n\t pairs = [];\n\t creator.$('.unpaired-columns .forward-column .dataset.selected').each(function () {\n\t fwds.push($(this).data('dataset'));\n\t });\n\t creator.$('.unpaired-columns .reverse-column .dataset.selected').each(function () {\n\t revs.push($(this).data('dataset'));\n\t });\n\t fwds.length = revs.length = Math.min(fwds.length, revs.length);\n\t //this.debug( fwds );\n\t //this.debug( revs );\n\t fwds.forEach(function (fwd, i) {\n\t try {\n\t pairs.push(creator._pair(fwd, revs[i], { silent: true }));\n\t } catch (err) {\n\t //TODO: preserve selected state of those that couldn't be paired\n\t //TODO: warn that some could not be paired\n\t creator.error(err);\n\t }\n\t });\n\t if (pairs.length && !options.silent) {\n\t this.trigger('pair:new', pairs);\n\t }\n\t return pairs;\n\t },\n\t\n\t /** clear the selection on all unpaired datasets */\n\t clearSelectedUnpaired: function () {\n\t this.$('.unpaired-columns .dataset.selected').removeClass('selected');\n\t },\n\t\n\t /** when holding down the shift key on a click, 'paint' the moused over datasets as selected */\n\t _mousedownUnpaired: function (ev) {\n\t if (ev.shiftKey) {\n\t var creator = this,\n\t $startTarget = $(ev.target).addClass('selected'),\n\t moveListener = function (ev) {\n\t creator.$(ev.target).filter('.dataset').addClass('selected');\n\t };\n\t $startTarget.parent().on('mousemove', moveListener);\n\t\n\t // on any mouseup, stop listening to the move and try to pair any selected\n\t $(document).one('mouseup', function (ev) {\n\t $startTarget.parent().off('mousemove', moveListener);\n\t creator.pairAllSelected();\n\t });\n\t }\n\t },\n\t\n\t /** attempt to pair two datasets directly across from one another */\n\t _clickPairRow: function (ev) {\n\t //if( !ev.currentTarget ){ return true; }\n\t var rowIndex = $(ev.currentTarget).index(),\n\t fwd = $('.unpaired-columns .forward-column .dataset').eq(rowIndex).data('dataset'),\n\t rev = $('.unpaired-columns .reverse-column .dataset').eq(rowIndex).data('dataset');\n\t //this.debug( 'row:', rowIndex, fwd, rev );\n\t this._pair(fwd, rev);\n\t },\n\t\n\t // ........................................................................ divider/partition\n\t /** start dragging the visible divider/partition between unpaired and paired panes */\n\t _startPartitionDrag: function (ev) {\n\t var creator = this,\n\t startingY = ev.pageY;\n\t //this.debug( 'partition drag START:', ev );\n\t $('body').css('cursor', 'ns-resize');\n\t creator.$('.flexible-partition-drag').css('color', 'black');\n\t\n\t function endDrag(ev) {\n\t //creator.debug( 'partition drag STOP:', ev );\n\t // doing this by an added class didn't really work well - kept flashing still\n\t creator.$('.flexible-partition-drag').css('color', '');\n\t $('body').css('cursor', '').unbind('mousemove', trackMouse);\n\t }\n\t function trackMouse(ev) {\n\t var offset = ev.pageY - startingY;\n\t //creator.debug( 'partition:', startingY, offset );\n\t if (!creator.adjPartition(offset)) {\n\t //creator.debug( 'mouseup triggered' );\n\t $('body').trigger('mouseup');\n\t }\n\t creator._adjUnpairedOnScrollbar();\n\t startingY += offset;\n\t }\n\t $('body').mousemove(trackMouse);\n\t $('body').one('mouseup', endDrag);\n\t },\n\t\n\t /** adjust the parition up/down +/-adj pixels */\n\t adjPartition: function (adj) {\n\t var $unpaired = this.$('.unpaired-columns'),\n\t $paired = this.$('.paired-columns'),\n\t unpairedHi = parseInt($unpaired.css('height'), 10),\n\t pairedHi = parseInt($paired.css('height'), 10);\n\t //this.debug( adj, 'hi\\'s:', unpairedHi, pairedHi, unpairedHi + adj, pairedHi - adj );\n\t\n\t unpairedHi = Math.max(10, unpairedHi + adj);\n\t pairedHi = pairedHi - adj;\n\t\n\t var movingUpwards = adj < 0;\n\t // when the divider gets close to the top - lock into hiding the unpaired section\n\t if (movingUpwards) {\n\t if (this.unpairedPanelHidden) {\n\t return false;\n\t } else if (unpairedHi <= 10) {\n\t this.hideUnpaired();\n\t return false;\n\t }\n\t } else {\n\t if (this.unpairedPanelHidden) {\n\t $unpaired.show();\n\t this.unpairedPanelHidden = false;\n\t }\n\t }\n\t\n\t // when the divider gets close to the bottom - lock into hiding the paired section\n\t if (!movingUpwards) {\n\t if (this.pairedPanelHidden) {\n\t return false;\n\t } else if (pairedHi <= 15) {\n\t this.hidePaired();\n\t return false;\n\t }\n\t } else {\n\t if (this.pairedPanelHidden) {\n\t $paired.show();\n\t this.pairedPanelHidden = false;\n\t }\n\t }\n\t\n\t $unpaired.css({\n\t height: unpairedHi + 'px',\n\t flex: '0 0 auto'\n\t });\n\t return true;\n\t },\n\t\n\t // ........................................................................ paired\n\t /** select a pair when clicked */\n\t selectPair: function (ev) {\n\t ev.stopPropagation();\n\t $(ev.currentTarget).toggleClass('selected');\n\t },\n\t\n\t /** deselect all pairs */\n\t clearSelectedPaired: function (ev) {\n\t this.$('.paired-columns .dataset.selected').removeClass('selected');\n\t },\n\t\n\t /** rename a pair when the pair name is clicked */\n\t _clickPairName: function (ev) {\n\t ev.stopPropagation();\n\t var $name = $(ev.currentTarget),\n\t $pair = $name.parent().parent(),\n\t index = $pair.index('.dataset.paired'),\n\t pair = this.paired[index],\n\t response = prompt('Enter a new name for the pair:', pair.name);\n\t if (response) {\n\t pair.name = response;\n\t // set a flag (which won't be passed in json creation) for manual naming so we don't overwrite these\n\t // when adding/removing extensions\n\t //hackish\n\t pair.customizedName = true;\n\t $name.text(pair.name);\n\t }\n\t },\n\t\n\t /** unpair this pair */\n\t _clickUnpair: function (ev) {\n\t //if( !ev.currentTarget ){ return true; }\n\t var pairIndex = Math.floor($(ev.currentTarget).index('.unpair-btn'));\n\t //this.debug( 'pair:', pairIndex );\n\t this._unpair(this.paired[pairIndex]);\n\t },\n\t\n\t // ........................................................................ paired - drag and drop re-ordering\n\t //_dragenterPairedColumns : function( ev ){\n\t // this.debug( '_dragenterPairedColumns:', ev );\n\t //},\n\t //_dragleavePairedColumns : function( ev ){\n\t // //this.debug( '_dragleavePairedColumns:', ev );\n\t //},\n\t /** track the mouse drag over the paired list adding a placeholder to show where the drop would occur */\n\t _dragoverPairedColumns: function (ev) {\n\t //this.debug( '_dragoverPairedColumns:', ev );\n\t ev.preventDefault();\n\t\n\t var $list = this.$('.paired-columns .column-datasets');\n\t this._checkForAutoscroll($list, ev.originalEvent.clientY);\n\t //this.debug( ev.originalEvent.clientX, ev.originalEvent.clientY );\n\t var $nearest = this._getNearestPairedDatasetLi(ev.originalEvent.clientY);\n\t\n\t $('.element-drop-placeholder').remove();\n\t var $placeholder = $('
                ');\n\t if (!$nearest.length) {\n\t $list.append($placeholder);\n\t } else {\n\t $nearest.before($placeholder);\n\t }\n\t },\n\t\n\t /** If the mouse is near enough to the list's top or bottom, scroll the list */\n\t _checkForAutoscroll: function ($element, y) {\n\t var AUTOSCROLL_SPEED = 2;\n\t var offset = $element.offset(),\n\t scrollTop = $element.scrollTop(),\n\t upperDist = y - offset.top,\n\t lowerDist = offset.top + $element.outerHeight() - y;\n\t //this.debug( '_checkForAutoscroll:', scrollTop, upperDist, lowerDist );\n\t if (upperDist >= 0 && upperDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop - AUTOSCROLL_SPEED);\n\t } else if (lowerDist >= 0 && lowerDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop + AUTOSCROLL_SPEED);\n\t }\n\t },\n\t\n\t /** get the nearest *previous* paired dataset PairView based on the mouse's Y coordinate.\n\t * If the y is at the end of the list, return an empty jQuery object.\n\t */\n\t _getNearestPairedDatasetLi: function (y) {\n\t var WIGGLE = 4,\n\t lis = this.$('.paired-columns .column-datasets li').toArray();\n\t for (var i = 0; i < lis.length; i++) {\n\t var $li = $(lis[i]),\n\t top = $li.offset().top,\n\t halfHeight = Math.floor($li.outerHeight() / 2) + WIGGLE;\n\t if (top + halfHeight > y && top - halfHeight < y) {\n\t //this.debug( y, top + halfHeight, top - halfHeight )\n\t return $li;\n\t }\n\t }\n\t return $();\n\t },\n\t /** drop (dragged/selected PairViews) onto the list, re-ordering both the DOM and the internal array of pairs */\n\t _dropPairedColumns: function (ev) {\n\t // both required for firefox\n\t ev.preventDefault();\n\t ev.dataTransfer.dropEffect = 'move';\n\t\n\t var $nearest = this._getNearestPairedDatasetLi(ev.originalEvent.clientY);\n\t if ($nearest.length) {\n\t this.$dragging.insertBefore($nearest);\n\t } else {\n\t // no nearest before - insert after last element (unpair button)\n\t this.$dragging.insertAfter(this.$('.paired-columns .unpair-btn').last());\n\t }\n\t // resync the creator's list of paired based on the new DOM order\n\t this._syncPairsToDom();\n\t return false;\n\t },\n\t /** resync the creator's list of paired based on the DOM order of pairs */\n\t _syncPairsToDom: function () {\n\t var newPaired = [];\n\t //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n\t this.$('.paired-columns .dataset.paired').each(function () {\n\t newPaired.push($(this).data('pair'));\n\t });\n\t //this.debug( newPaired );\n\t this.paired = newPaired;\n\t this._renderPaired();\n\t },\n\t /** drag communication with pair sub-views: dragstart */\n\t _pairDragstart: function (ev, pair) {\n\t //this.debug( '_pairDragstart', ev, pair )\n\t // auto select the pair causing the event and move all selected\n\t pair.$el.addClass('selected');\n\t var $selected = this.$('.paired-columns .dataset.selected');\n\t this.$dragging = $selected;\n\t },\n\t /** drag communication with pair sub-views: dragend - remove the placeholder */\n\t _pairDragend: function (ev, pair) {\n\t //this.debug( '_pairDragend', ev, pair )\n\t $('.element-drop-placeholder').remove();\n\t this.$dragging = null;\n\t },\n\t\n\t // ........................................................................ footer\n\t toggleExtensions: function (force) {\n\t var creator = this;\n\t creator.removeExtensions = force !== undefined ? force : !creator.removeExtensions;\n\t\n\t _.each(creator.paired, function (pair) {\n\t // don't overwrite custom names\n\t if (pair.customizedName) {\n\t return;\n\t }\n\t pair.name = creator._guessNameForPair(pair.forward, pair.reverse);\n\t });\n\t\n\t creator._renderPaired();\n\t creator._renderFooter();\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** debug a dataset list */\n\t _printList: function (list) {\n\t var creator = this;\n\t _.each(list, function (e) {\n\t if (list === creator.paired) {\n\t creator._printPair(e);\n\t } else {\n\t //creator.debug( e );\n\t }\n\t });\n\t },\n\t\n\t /** print a pair Object */\n\t _printPair: function (pair) {\n\t this.debug(pair.forward.name, pair.reverse.name, ': ->', pair.name);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'PairedCollectionCreator';\n\t },\n\t\n\t templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\t\n\t /** the header (not including help text) */\n\t header: _.template(['', '
                ', '', '', '
                ', '
                ', '
                ', '
                ', '
                ', '', _l('Unpaired forward'), '', '', '
                ', '
                ', '', '
                ', '
                ', '
                ', '', '
                ', '
                ', '
                ', '', _l('Unpaired reverse'), '', '', '
                ', '
                ', '', '
                ', '
                ', '
                ', '
                '].join('')),\n\t\n\t /** the middle: unpaired, divider, and paired */\n\t middle: _.template([\n\t // contains two flex rows (rows that fill available space) and a divider btwn\n\t '
                ', '
                ', '
                  ', '
                  ', '
                  ', '
                    ', '
                    ', '
                    ', '
                      ', '
                      ', '
                      ', '
                      ', '
                      ', '
                      ', '
                      ', '', '
                      ', '', _l('Unpair all'), '', '
                      ', '
                      ', '
                      ', '
                        ', '
                        '].join('')),\n\t\n\t /** creation and cancel controls */\n\t footer: _.template(['
                        ', '
                        ', '', '', '
                        ', '
                        ', '', '
                        ', _l('Name'), ':
                        ', '
                        ', '
                        ', '
                        ', '
                        ', '', '
                        ', '', '', '
                        ', '
                        ', '
                        ', '', '
                        ', '
                        '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

                        ', _l(['Collections of paired datasets are ordered lists of dataset pairs (often forward and reverse reads). ', 'These collections can be passed to tools and workflows in order to have analyses done on each member of ', 'the entire group. This interface allows you to create a collection, choose which datasets are paired, ', 'and re-order the final collection.'].join('')), '

                        ', '

                        ', _l(['Unpaired datasets are shown in the unpaired section ', '(hover over the underlined words to highlight below). ', 'Paired datasets are shown in the paired section.', '

                          To pair datasets, you can:', '
                        • Click a dataset in the ', 'forward column ', 'to select it then click a dataset in the ', 'reverse column.', '
                        • ', '
                        • Click one of the \"Pair these datasets\" buttons in the ', 'middle column ', 'to pair the datasets in a particular row.', '
                        • ', '
                        • Click \"Auto-pair\" ', 'to have your datasets automatically paired based on name.', '
                        • ', '
                        '].join('')), '

                        ', '

                        ', _l(['

                          You can filter what is shown in the unpaired sections by:', '
                        • Entering partial dataset names in either the ', 'forward filter or ', 'reverse filter.', '
                        • ', '
                        • Choosing from a list of preset filters by clicking the ', '\"Choose filters\" link.', '
                        • ', '
                        • Entering regular expressions to match dataset names. See: ', 'MDN\\'s JavaScript Regular Expression Tutorial. ', 'Note: forward slashes (\\\\) are not needed.', '
                        • ', '
                        • Clearing the filters by clicking the ', '\"Clear filters\" link.', '
                        • ', '
                        '].join('')), '

                        ', '

                        ', _l(['To unpair individual dataset pairs, click the ', 'unpair buttons ( ). ', 'Click the \"Unpair all\" link to unpair all pairs.'].join('')), '

                        ', '

                        ', _l(['You can include or remove the file extensions (e.g. \".fastq\") from your pair names by toggling the ', '\"Remove file extensions from pair names?\" control.'].join('')), '

                        ', '

                        ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\". ', '(Note: you do not have to pair all unpaired datasets to finish.)'].join('')), '

                        '].join(''))\n\t })\n\t });\n\t\n\t //=============================================================================\n\t /** a modal version of the paired collection creator */\n\t var pairedCollectionCreatorModal = function _pairedCollectionCreatorModal(datasets, options) {\n\t\n\t var deferred = jQuery.Deferred(),\n\t creator;\n\t\n\t options = _.defaults(options || {}, {\n\t datasets: datasets,\n\t oncancel: function () {\n\t Galaxy.modal.hide();\n\t deferred.reject('cancelled');\n\t },\n\t oncreate: function (creator, response) {\n\t Galaxy.modal.hide();\n\t deferred.resolve(response);\n\t }\n\t });\n\t\n\t if (!window.Galaxy || !Galaxy.modal) {\n\t throw new Error('Galaxy or Galaxy.modal not found');\n\t }\n\t\n\t creator = new PairedCollectionCreator(options);\n\t Galaxy.modal.show({\n\t title: 'Create a collection of paired datasets',\n\t body: creator.$el,\n\t width: '80%',\n\t height: '800px',\n\t closing_events: true\n\t });\n\t creator.render();\n\t window.creator = creator;\n\t\n\t //TODO: remove modal header\n\t return deferred;\n\t };\n\t\n\t //=============================================================================\n\t function createListOfPairsCollection(collection, defaultHideSourceItems) {\n\t var elements = collection.toJSON();\n\t //TODO: validate elements\n\t return pairedCollectionCreatorModal(elements, {\n\t historyId: collection.historyId,\n\t defaultHideSourceItems: defaultHideSourceItems\n\t });\n\t }\n\t\n\t //=============================================================================\n\t return {\n\t PairedCollectionCreator: PairedCollectionCreator,\n\t pairedCollectionCreatorModal: pairedCollectionCreatorModal,\n\t createListOfPairsCollection: createListOfPairsCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 122 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(57), __webpack_require__(60), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_CREATOR, HDCA, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /*==============================================================================\n\t TODO:\n\t the paired creator doesn't really mesh with the list creator as parent\n\t it may be better to make an abstract super class for both\n\t composites may inherit from this (or vis-versa)\n\t PairedDatasetCollectionElementView doesn't make a lot of sense\n\t \n\t ==============================================================================*/\n\t /** */\n\t var PairedDatasetCollectionElementView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n\t tagName: 'li',\n\t className: 'collection-element',\n\t\n\t initialize: function (attributes) {\n\t this.element = attributes.element || {};\n\t this.identifier = attributes.identifier;\n\t },\n\t\n\t render: function () {\n\t this.$el.attr('data-element-id', this.element.id).html(this.template({ identifier: this.identifier, element: this.element }));\n\t return this;\n\t },\n\t\n\t //TODO: lots of unused space in the element - possibly load details and display them horiz.\n\t template: _.template(['<%- identifier %>', '<%- element.name %>'].join('')),\n\t\n\t /** remove the DOM and any listeners */\n\t destroy: function () {\n\t this.off();\n\t this.$el.remove();\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'DatasetCollectionElementView()';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t var _super = LIST_CREATOR.ListCollectionCreator;\n\t\n\t /** An interface for building collections.\n\t */\n\t var PairCollectionCreator = _super.extend({\n\t\n\t /** the class used to display individual elements */\n\t elementViewClass: PairedDatasetCollectionElementView,\n\t /** the class this creator will create and save */\n\t collectionClass: HDCA.HistoryPairDatasetCollection,\n\t className: 'pair-collection-creator collection-creator flex-row-container',\n\t\n\t /** override to no-op */\n\t _mangleDuplicateNames: function () {},\n\t\n\t // TODO: this whole pattern sucks. There needs to be two classes of problem area:\n\t // bad inital choices and\n\t // when the user has painted his/her self into a corner during creation/use-of-the-creator\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t if (this.workingElements.length === 2) {\n\t return _super.prototype.render.call(this, speed, callback);\n\t }\n\t return this._renderInvalid(speed, callback);\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering elements\n\t /** render forward/reverse */\n\t _renderList: function (speed, callback) {\n\t //this.debug( '-- _renderList' );\n\t //precondition: there are two valid elements in workingElements\n\t var creator = this,\n\t $tmp = jQuery('
                        '),\n\t $list = creator.$list();\n\t\n\t // lose the original views, create the new, append all at once, then call their renders\n\t _.each(this.elementViews, function (view) {\n\t view.destroy();\n\t creator.removeElementView(view);\n\t });\n\t $tmp.append(creator._createForwardElementView().$el);\n\t $tmp.append(creator._createReverseElementView().$el);\n\t $list.empty().append($tmp.children());\n\t _.invoke(creator.elementViews, 'render');\n\t },\n\t\n\t /** create the forward element view */\n\t _createForwardElementView: function () {\n\t return this._createElementView(this.workingElements[0], { identifier: 'forward' });\n\t },\n\t\n\t /** create the forward element view */\n\t _createReverseElementView: function () {\n\t return this._createElementView(this.workingElements[1], { identifier: 'reverse' });\n\t },\n\t\n\t /** create an element view, cache in elementViews, and return */\n\t _createElementView: function (element, options) {\n\t var elementView = new this.elementViewClass(_.extend(options, {\n\t element: element\n\t }));\n\t this.elementViews.push(elementView);\n\t return elementView;\n\t },\n\t\n\t /** swap the forward, reverse elements and re-render */\n\t swap: function () {\n\t this.workingElements = [this.workingElements[1], this.workingElements[0]];\n\t this._renderList();\n\t },\n\t\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .swap': 'swap'\n\t }),\n\t\n\t // ------------------------------------------------------------------------ templates\n\t //TODO: move to require text plugin and load these as text\n\t //TODO: underscore currently unnecc. bc no vars are used\n\t //TODO: better way of localizing text-nodes in long strings\n\t /** underscore template fns attached to class */\n\t templates: _.extend(_.clone(_super.prototype.templates), {\n\t /** the middle: element list */\n\t middle: _.template(['', '
                        ', '
                        '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

                        ', _l(['Pair collections are permanent collections containing two datasets: one forward and one reverse. ', 'Often these are forward and reverse reads. The pair collections can be passed to tools and ', 'workflows in order to have analyses done on both datasets. This interface allows ', 'you to create a pair, name it, and swap which is forward and which reverse.'].join('')), '

                        ', '
                          ', '
                        • ', _l(['Click the \"Swap\" link to make your forward dataset the reverse ', 'and the reverse dataset forward.'].join('')), '
                        • ', '
                        • ', _l(['Click the \"Cancel\" button to exit the interface.'].join('')), '
                        • ', '

                        ', '

                        ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\".'].join('')), '

                        '].join('')),\n\t\n\t /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n\t invalidInitial: _.template(['
                        ', '
                        ', '', '<% if( _.size( problems ) ){ %>', _l('The following selections could not be included due to problems'), '
                          <% _.each( problems, function( problem ){ %>', '
                        • <%- problem.element.name %>: <%- problem.text %>
                        • ', '<% }); %>
                        ', '<% } else if( _.size( elements ) === 0 ){ %>', _l('No datasets were selected'), '.', '<% } else if( _.size( elements ) === 1 ){ %>', _l('Only one dataset was selected'), ': <%- elements[0].name %>', '<% } else if( _.size( elements ) > 2 ){ %>', _l('Too many datasets were selected'), ': <%- _.pluck( elements, \"name\" ).join( \", \") %>', '<% } %>', '
                        ', _l('Two (and only two) elements are needed for the pair'), '. ', _l('You may need to '), '', _l('cancel'), ' ', _l('and reselect new elements'), '.', '
                        ', '
                        ', '
                        ', '
                        ', '
                        ', '
                        ', '',\n\t // _l( 'Create a different kind of collection' ),\n\t '
                        ', '
                        ', '
                        '].join(''))\n\t }),\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionCreator';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** List collection flavor of collectionCreatorModal. */\n\t var pairCollectionCreatorModal = function _pairCollectionCreatorModal(elements, options) {\n\t options = options || {};\n\t options.title = _l('Create a collection from a pair of datasets');\n\t return LIST_CREATOR.collectionCreatorModal(elements, options, PairCollectionCreator);\n\t };\n\t\n\t //==============================================================================\n\t /** Use a modal to create a pair collection, then add it to the given history contents.\n\t * @returns {Deferred} resolved when the collection is added to the history.\n\t */\n\t function createPairCollection(contents, defaultHideSourceItems) {\n\t var elements = contents.toJSON(),\n\t promise = pairCollectionCreatorModal(elements, {\n\t defaultHideSourceItems: defaultHideSourceItems,\n\t creationFn: function (elements, name, hideSourceItems) {\n\t elements = [{ name: \"forward\", src: \"hda\", id: elements[0].id }, { name: \"reverse\", src: \"hda\", id: elements[1].id }];\n\t return contents.createHDCA(elements, 'paired', name, hideSourceItems);\n\t }\n\t });\n\t return promise;\n\t }\n\t\n\t //==============================================================================\n\t return {\n\t PairCollectionCreator: PairCollectionCreator,\n\t pairCollectionCreatorModal: pairCollectionCreatorModal,\n\t createPairCollection: createPairCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 123 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(46), __webpack_require__(5), __webpack_require__(11)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, Tabs, Ui, Form) {\n\t\n\t /** Dataset edit attributes view */\n\t var View = Backbone.View.extend({\n\t initialize: function () {\n\t this.setElement('
                        ');\n\t this.model = new Backbone.Model({ 'dataset_id': Galaxy.params.dataset_id });\n\t this.render();\n\t },\n\t\n\t // Fetch data for the selected dataset and \n\t // build tabs for editing its attributes\n\t render: function () {\n\t var url = Galaxy.root + 'dataset/edit',\n\t self = this;\n\t Utils.get({\n\t url: url,\n\t data: { 'dataset_id': self.model.get('dataset_id') },\n\t success: function (response) {\n\t self.render_attribute_page(self, response);\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while loading the dataset.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t\n\t /** Render all the tabs view */\n\t render_attribute_page: function (self, response) {\n\t var message = {\n\t 'message': response.message,\n\t 'status': response.status,\n\t 'persistent': true,\n\t 'cls': response.status + 'message'\n\t };\n\t self.$el.empty().append(self._templateHeader());\n\t self.display_message(message, self.$('.response-message'));\n\t // Create all tabs\n\t self.create_tabs(response, self.$('.edit-attr'));\n\t },\n\t\n\t /** Perform AJAX post call */\n\t call_ajax: function (self, data, tab_name) {\n\t var post_url = Galaxy.root + 'dataset/edit';\n\t $.ajax({\n\t type: \"PUT\",\n\t url: post_url,\n\t data: data,\n\t success: function (response) {\n\t self.render_attribute_page(self, response);\n\t self.reload_history();\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t\n\t /** Display actions messages */\n\t display_message: function (response, $el) {\n\t $el.empty().html(new Ui.Message(response).$el);\n\t },\n\t\n\t /** Create tabs for different attributes of dataset*/\n\t create_tabs: function (response, $el_edit_attr) {\n\t var self = this;\n\t self.tabs = new Tabs.View();\n\t self.tabs.add({\n\t id: 'attributes',\n\t title: 'Attributes',\n\t icon: 'fa fa-bars',\n\t tooltip: 'Edit dataset attributes',\n\t $el: self._getAttributesFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'convert',\n\t title: 'Convert',\n\t icon: 'fa-gear',\n\t tooltip: 'Convert to new format',\n\t $el: self._getConvertFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'datatype',\n\t title: 'Datatypes',\n\t icon: 'fa-database',\n\t tooltip: 'Change data type',\n\t $el: self._getChangeDataTypeFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'permissions',\n\t title: 'Permissions',\n\t icon: 'fa-user',\n\t tooltip: 'Permissions',\n\t $el: self._getPermissionsFormTemplate(response)\n\t });\n\t $el_edit_attr.append(self.tabs.$el);\n\t self.tabs.showTab('attributes');\n\t },\n\t\n\t /** Main template */\n\t _templateHeader: function () {\n\t return '
                        ' + '
                        ' + '

                        Edit Dataset Attributes

                        ' + '
                        ';\n\t },\n\t\n\t /** Attributes tab template */\n\t _getAttributesFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Edit attributes',\n\t inputs: response.edit_attributes_inputs,\n\t operations: {\n\t 'submit_editattr': new Ui.ButtonIcon({\n\t tooltip: 'Save attributes of the dataset.',\n\t icon: 'fa-floppy-o ',\n\t title: 'Save attributes',\n\t onclick: function () {\n\t self._submit(self, form, response, \"edit_attributes\");\n\t }\n\t }),\n\t 'submit_autocorrect': new Ui.ButtonIcon({\n\t tooltip: 'This will inspect the dataset and attempt to correct the values of fields if they are not accurate.',\n\t icon: 'fa-undo ',\n\t title: 'Auto-detect',\n\t onclick: function () {\n\t self._submit(self, form, response, \"auto-detect\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Convert tab template */\n\t _getConvertFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Convert to new format',\n\t inputs: response.convert_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Convert the datatype to a new format.',\n\t title: 'Convert datatype',\n\t icon: 'fa-exchange ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"convert\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Change datatype template */\n\t _getChangeDataTypeFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Change datatype',\n\t inputs: response.convert_datatype_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Change the datatype to a new type.',\n\t title: 'Change datatype',\n\t icon: 'fa-exchange ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"change\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Permissions template */\n\t _getPermissionsFormTemplate: function (response) {\n\t var template = \"\",\n\t self = this;\n\t if (response.can_manage_dataset) {\n\t var form = new Form({\n\t title: 'Manage dataset permissions on ' + response.display_name,\n\t inputs: response.permission_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Save permissions.',\n\t title: 'Save permissions',\n\t icon: 'fa-floppy-o ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"permissions\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t } else {\n\t var form = new Form({\n\t title: 'View permissions',\n\t inputs: response.permission_inputs\n\t });\n\t return form.$el;\n\t }\n\t },\n\t\n\t /** Submit action */\n\t _submit: function (self, form, response, type) {\n\t var form_data = form.data.create();\n\t form_data.dataset_id = response.dataset_id;\n\t switch (type) {\n\t case \"edit_attributes\":\n\t form_data.save = 'Save';\n\t break;\n\t\n\t case \"auto-detect\":\n\t form_data.detect = 'Auto-detect';\n\t break;\n\t\n\t case \"convert\":\n\t if (form_data.target_type !== null && form_data.target_type) {\n\t form_data.dataset_id = response.dataset_id;\n\t form_data.convert_data = 'Convert';\n\t }\n\t break;\n\t\n\t case \"change\":\n\t form_data.change = 'Save';\n\t break;\n\t\n\t case \"permissions\":\n\t var post_data = {};\n\t post_data.permissions = JSON.stringify(form_data);\n\t post_data.update_roles_button = \"Save\";\n\t post_data.dataset_id = response.dataset_id;\n\t form_data = post_data;\n\t break;\n\t }\n\t self.call_ajax(self, form_data);\n\t },\n\t\n\t /** Reload Galaxy's history after updating dataset's attributes */\n\t reload_history: function () {\n\t if (window.Galaxy) {\n\t window.Galaxy.currHistoryPanel.loadCurrentHistory();\n\t }\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 124 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This class renders the grid list with shared section. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(12)], __WEBPACK_AMD_DEFINE_RESULT__ = function (GridView) {\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.setElement($('
                        '));\n\t this.model = new Backbone.Model(options);\n\t this.item = this.model.get('item');\n\t $.ajax({\n\t url: Galaxy.root + this.item + '/' + this.model.get('action_id'),\n\t success: function (response) {\n\t response['dict_format'] = true;\n\t self.model.set(response);\n\t self.render();\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var grid = new GridView(this.model.attributes);\n\t this.$el.empty().append(grid.$el);\n\t this.$el.append(this._templateShared());\n\t },\n\t\n\t _templateShared: function () {\n\t var self = this;\n\t var $tmpl = $('
                        ' + '

                        ' + this.model.get('plural') + ' shared with you by others

                        ' + '
                        ');\n\t var options = this.model.attributes;\n\t if (options.shared_by_others && options.shared_by_others.length > 0) {\n\t var $table = $('' + '' + '' + '' + '' + '
                        TitleOwner
                        ');\n\t _.each(options.shared_by_others, function (it, index) {\n\t var display_url = Galaxy.root + self.item + '/display_by_username_and_slug?username=' + it.username + '&slug=' + it.slug;\n\t $table.append('
                      1. ' + '' + _.escape(it.title) + '' + '' + _.escape(it.username) + '
                        ' + '
                        ' + '
                        ' + '
                        ' + '
                        ' + '
                        You can tell Galaxy to download data from web by entering URL in this box (one per line). You can also directly paste the contents of a file.
                        ' + '',\n '
                        ',\n '
                        '\n ].join( '' );\n }\n});\n\n//==============================================================================\nreturn {\n CitationView : CitationView,\n CitationListView : CitationListView\n};\n\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/citation/citation-view.js","define([\n \"mvc/list/list-item\",\n \"mvc/dataset/dataset-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_ITEM, DATASET_LI, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar FoldoutListItemView = LIST_ITEM.FoldoutListItemView,\n ListItemView = LIST_ITEM.ListItemView;\n/** @class Read only view for DatasetCollection.\n */\nvar DCListItemView = FoldoutListItemView.extend(\n/** @lends DCListItemView.prototype */{\n\n className : FoldoutListItemView.prototype.className + \" dataset-collection\",\n id : function(){\n return [ 'dataset_collection', this.model.get( 'id' ) ].join( '-' );\n },\n\n /** override to add linkTarget */\n initialize : function( attributes ){\n this.linkTarget = attributes.linkTarget || '_blank';\n this.hasUser = attributes.hasUser;\n FoldoutListItemView.prototype.initialize.call( this, attributes );\n },\n\n /** event listeners */\n _setUpListeners : function(){\n FoldoutListItemView.prototype._setUpListeners.call( this );\n this.listenTo( this.model, 'change', function( model, options ){\n // if the model has changed deletion status render it entirely\n if( _.has( model.changed, 'deleted' ) ){\n this.render();\n\n // if the model has been decorated after the fact with the element count,\n // render the subtitle where the count is displayed\n } else if( _.has( model.changed, 'element_count' ) ){\n this.$( '> .title-bar .subtitle' ).replaceWith( this._renderSubtitle() );\n }\n });\n },\n\n // ......................................................................... rendering\n /** render a subtitle to show the user what sort of collection this is */\n _renderSubtitle : function(){\n return $( this.templates.subtitle( this.model.toJSON(), this ) );\n },\n\n // ......................................................................... foldout\n /** override to add linktarget to sub-panel */\n _getFoldoutPanelOptions : function(){\n var options = FoldoutListItemView.prototype._getFoldoutPanelOptions.call( this );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n hasUser : this.hasUser\n });\n },\n\n /** override to not catch sub-panel selectors */\n $selector : function(){\n return this.$( '> .selector' );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDCListItemView.prototype.templates = (function(){\n\n var warnings = _.extend( {}, FoldoutListItemView.prototype.templates.warnings, {\n error : BASE_MVC.wrapTemplate([\n // error during index fetch - show error on dataset\n '<% if( model.error ){ %>',\n '
                        ',\n _l( 'There was an error getting the data for this collection' ), ': <%- model.error %>',\n '
                        ',\n '<% } %>'\n ]),\n purged : BASE_MVC.wrapTemplate([\n '<% if( model.purged ){ %>',\n '
                        ',\n _l( 'This collection has been deleted and removed from disk' ),\n '
                        ',\n '<% } %>'\n ]),\n deleted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.deleted && !model.purged ){ %>',\n '
                        ',\n _l( 'This collection has been deleted' ),\n '
                        ',\n '<% } %>'\n ])\n });\n\n // use element identifier\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '
                        ',\n '<%- collection.element_identifier || collection.name %>',\n '
                        ',\n '
                        ',\n '
                        '\n ], 'collection' );\n\n // use element identifier\n var subtitleTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '<% var countText = collection.element_count? ( collection.element_count + \" \" ) : \"\"; %>',\n '<% if( collection.collection_type === \"list\" ){ %>',\n _l( 'a list of <%- countText %>datasets' ),\n '<% } else if( collection.collection_type === \"paired\" ){ %>',\n _l( 'a pair of datasets' ),\n '<% } else if( collection.collection_type === \"list:paired\" ){ %>',\n _l( 'a list of <%- countText %>dataset pairs' ),\n '<% } else if( collection.collection_type === \"list:list\" ){ %>',\n _l( 'a list of <%- countText %>dataset lists' ),\n '<% } %>',\n '
                        '\n ], 'collection' );\n\n return _.extend( {}, FoldoutListItemView.prototype.templates, {\n warnings : warnings,\n titleBar : titleBarTemplate,\n subtitle : subtitleTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for DatasetCollectionElement.\n */\nvar DCEListItemView = ListItemView.extend(\n/** @lends DCEListItemView.prototype */{\n\n /** add the DCE class to the list item */\n className : ListItemView.prototype.className + \" dataset-collection-element\",\n\n /** set up */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( 'DCEListItemView.initialize:', attributes );\n ListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCEListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDCEListItemView.prototype.templates = (function(){\n\n // use the element identifier here - since that will persist and the user will need it\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '
                        ',\n '<%- element.element_identifier %>',\n '
                        ',\n '
                        ',\n '
                        '\n ], 'element' );\n\n return _.extend( {}, ListItemView.prototype.templates, {\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also an DatasetAssociation\n * (a dataset contained in a dataset collection).\n */\nvar DatasetDCEListItemView = DATASET_LI.DatasetListItemView.extend(\n/** @lends DatasetDCEListItemView.prototype */{\n\n className : DATASET_LI.DatasetListItemView.prototype.className + \" dataset-collection-element\",\n\n /** set up */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( 'DatasetDCEListItemView.initialize:', attributes );\n DATASET_LI.DatasetListItemView.prototype.initialize.call( this, attributes );\n },\n\n /** In this override, only get details if in the ready state.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetDCEListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetDCEListItemView.prototype.templates = (function(){\n\n // use the element identifier here and not the dataset name\n //TODO:?? can we steal the DCE titlebar?\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '',\n '
                        ',\n '<%- element.element_identifier %>',\n '
                        ',\n '
                        '\n ], 'element' );\n\n return _.extend( {}, DATASET_LI.DatasetListItemView.prototype.templates, {\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n * (a nested DC).\n */\nvar NestedDCDCEListItemView = DCListItemView.extend(\n/** @lends NestedDCDCEListItemView.prototype */{\n\n className : DCListItemView.prototype.className + \" dataset-collection-element\",\n\n /** In this override, add the state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n DCListItemView.prototype._swapNewRender.call( this, $newRender );\n var state = this.model.get( 'state' ) || 'ok';\n this.$el.addClass( 'state-' + state );\n return this.$el;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'NestedDCDCEListItemView(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n return {\n DCListItemView : DCListItemView,\n DCEListItemView : DCEListItemView,\n DatasetDCEListItemView : DatasetDCEListItemView,\n NestedDCDCEListItemView : NestedDCDCEListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-li.js","define([\n \"mvc/dataset/dataset-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_MODEL, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/*\nNotes:\n\nTerminology:\n DatasetCollection/DC : a container of datasets or nested DatasetCollections\n Element/DatasetCollectionElement/DCE : an item contained in a DatasetCollection\n HistoryDatasetCollectionAssociation/HDCA: a DatasetCollection contained in a history\n\n\nThis all seems too complex unfortunately:\n\n- Terminology collision between DatasetCollections (DCs) and Backbone Collections.\n- In the DatasetCollections API JSON, DC Elements use a 'Has A' stucture to *contain*\n either a dataset or a nested DC. This would make the hierarchy much taller. I've\n decided to merge the contained JSON with the DC element json - making the 'has a'\n relation into an 'is a' relation. This seems simpler to me and allowed a lot of\n DRY in both models and views, but may make tracking or tracing within these models\n more difficult (since DatasetCollectionElements are now *also* DatasetAssociations\n or DatasetCollections (nested)). This also violates the rule of thumb about\n favoring aggregation over inheritance.\n- Currently, there are three DatasetCollection subclasses: List, Pair, and ListPaired.\n These each should a) be usable on their own, b) be usable in the context of\n nesting within a collection model (at least in the case of ListPaired), and\n c) be usable within the context of other container models (like History or\n LibraryFolder, etc.). I've tried to separate/extract classes in order to\n handle those three situations, but it's proven difficult to do in a simple,\n readable manner.\n- Ideally, histories and libraries would inherit from the same server models as\n dataset collections do since they are (in essence) dataset collections themselves -\n making the whole nested structure simpler. This would be a large, error-prone\n refactoring and migration.\n\nMany of the classes and heirarchy are meant as extension points so, while the\nrelations and flow may be difficult to understand initially, they'll allow us to\nhandle the growth or flux dataset collection in the future (w/o actually implementing\nany YAGNI).\n\n*/\n//_________________________________________________________________________________________________ ELEMENTS\n/** @class mixin for Dataset collection elements.\n * When collection elements are passed from the API, the underlying element is\n * in a sub-object 'object' (IOW, a DCE representing an HDA will have HDA json in element.object).\n * This mixin uses the constructor and parse methods to merge that JSON with the DCE attribtues\n * effectively changing a DCE from a container to a subclass (has a --> is a).\n */\nvar DatasetCollectionElementMixin = {\n\n /** default attributes used by elements in a dataset collection */\n defaults : {\n model_class : 'DatasetCollectionElement',\n element_identifier : null,\n element_index : null,\n element_type : null\n },\n\n /** merge the attributes of the sub-object 'object' into this model */\n _mergeObject : function( attributes ){\n // if we don't preserve and correct ids here, the element id becomes the object id\n // and collision in backbone's _byId will occur and only\n _.extend( attributes, attributes.object, { element_id: attributes.id });\n delete attributes.object;\n return attributes;\n },\n\n /** override to merge this.object into this */\n constructor : function( attributes, options ){\n // console.debug( '\\t DatasetCollectionElement.constructor:', attributes, options );\n attributes = this._mergeObject( attributes );\n this.idAttribute = 'element_id';\n Backbone.Model.apply( this, arguments );\n },\n\n /** when the model is fetched, merge this.object into this */\n parse : function( response, options ){\n var attributes = response;\n attributes = this._mergeObject( attributes );\n return attributes;\n }\n};\n\n/** @class Concrete class of Generic DatasetCollectionElement */\nvar DatasetCollectionElement = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( DatasetCollectionElementMixin )\n .extend({ _logNamespace : 'collections' });\n\n\n//==============================================================================\n/** @class Base/Abstract Backbone collection for Generic DCEs. */\nvar DCECollection = Backbone.Collection.extend( BASE_MVC.LoggableMixin ).extend(\n/** @lends DCECollection.prototype */{\n _logNamespace : 'collections',\n\n model: DatasetCollectionElement,\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetCollectionElementCollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a dataset collection element that is a dataset (HDA).\n */\nvar DatasetDCE = DATASET_MODEL.DatasetAssociation.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends DatasetDCE.prototype */{\n\n /** url fn */\n url : function(){\n // won't always be an hda\n if( !this.has( 'history_id' ) ){\n console.warn( 'no endpoint for non-hdas within a collection yet' );\n // (a little silly since this api endpoint *also* points at hdas)\n return Galaxy.root + 'api/datasets';\n }\n return Galaxy.root + 'api/histories/' + this.get( 'history_id' ) + '/contents/' + this.get( 'id' );\n },\n\n defaults : _.extend( {},\n DATASET_MODEL.DatasetAssociation.prototype.defaults,\n DatasetCollectionElementMixin.defaults\n ),\n\n _downloadQueryParameters : function() {\n return '?to_ext=' + this.get( 'file_ext' ) + '&hdca_id=' + this.get( 'parent_hdca_id' ) + '&element_identifier=' + this.get( 'element_identifier' );\n },\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually for now\n /** call the mixin constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t DatasetDCE.constructor:', attributes, options );\n //DATASET_MODEL.DatasetAssociation.prototype.constructor.call( this, attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** Does this model already contain detailed data (as opposed to just summary level data)? */\n hasDetails : function(){\n return this.elements && this.elements.length;\n },\n\n /** String representation. */\n toString : function(){\n var objStr = this.get( 'element_identifier' );\n return ([ 'DatasetDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class DCECollection of DatasetDCE's (a list of datasets, a pair of datasets).\n */\nvar DatasetDCECollection = DCECollection.extend(\n/** @lends DatasetDCECollection.prototype */{\n model: DatasetDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//_________________________________________________________________________________________________ COLLECTIONS\n/** @class Backbone model for Dataset Collections.\n * The DC API returns an array of JSON objects under the attribute elements.\n * This model:\n * - removes that array/attribute ('elements') from the model,\n * - creates a bbone collection (of the class defined in the 'collectionClass' attribute),\n * - passes that json onto the bbone collection\n * - caches the bbone collection in this.elements\n */\nvar DatasetCollection = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.SearchableModelMixin )\n .extend(/** @lends DatasetCollection.prototype */{\n _logNamespace : 'collections',\n\n /** default attributes for a model */\n defaults : {\n /* 'list', 'paired', or 'list:paired' */\n collection_type : null,\n //??\n deleted : false\n },\n\n /** Which class to use for elements */\n collectionClass : DCECollection,\n\n /** set up: create elements instance var and (on changes to elements) update them */\n initialize : function( model, options ){\n this.debug( this + '(DatasetCollection).initialize:', model, options, this );\n this.elements = this._createElementsModel();\n this.on( 'change:elements', function(){\n this.log( 'change:elements' );\n //TODO: prob. better to update the collection instead of re-creating it\n this.elements = this._createElementsModel();\n });\n },\n\n /** move elements model attribute to full collection */\n _createElementsModel : function(){\n this.debug( this + '._createElementsModel', this.collectionClass, this.get( 'elements' ), this.elements );\n //TODO: same patterns as DatasetCollectionElement _createObjectModel - refactor to BASE_MVC.hasSubModel?\n var elements = this.get( 'elements' ) || [];\n this.unset( 'elements', { silent: true });\n var self = this;\n _.each(elements, function(element, index) {\n _.extend(element, {\"parent_hdca_id\": self.get(\"id\")});\n });\n this.elements = new this.collectionClass( elements );\n //this.debug( 'collectionClass:', this.collectionClass + '', this.elements );\n return this.elements;\n },\n\n // ........................................................................ common queries\n /** pass the elements back within the model json when this is serialized */\n toJSON : function(){\n var json = Backbone.Model.prototype.toJSON.call( this );\n if( this.elements ){\n json.elements = this.elements.toJSON();\n }\n return json;\n },\n\n /** Is this collection in a 'ready' state no processing (for the collection) is left\n * to do on the server.\n */\n inReadyState : function(){\n var populated = this.get( 'populated' );\n return ( this.isDeletedOrPurged() || populated );\n },\n\n //TODO:?? the following are the same interface as DatasetAssociation - can we combine?\n /** Does the DC contain any elements yet? Is a fetch() required? */\n hasDetails : function(){\n return this.elements.length !== 0;\n },\n\n /** Given the filters, what models in this.elements would be returned? */\n getVisibleContents : function( filters ){\n // filters unused for now\n return this.elements;\n },\n\n // ........................................................................ ajax\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** save this dataset, _Mark_ing it as deleted (just a flag) */\n 'delete' : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** save this dataset, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) || this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** Is this collection deleted or purged? */\n isDeletedOrPurged : function(){\n return ( this.get( 'deleted' ) || this.get( 'purged' ) );\n },\n\n // ........................................................................ searchable\n /** searchable attributes for collections */\n searchAttributes : [\n 'name', 'tags'\n ],\n\n // ........................................................................ misc\n /** String representation */\n toString : function(){\n var idAndName = [ this.get( 'id' ), this.get( 'name' ) || this.get( 'element_identifier' ) ];\n return 'DatasetCollection(' + ( idAndName.join(',') ) + ')';\n }\n});\n\n\n//==============================================================================\n/** Model for a DatasetCollection containing datasets (non-nested).\n */\nvar ListDatasetCollection = DatasetCollection.extend(\n/** @lends ListDatasetCollection.prototype */{\n\n /** override since we know the collection will only contain datasets */\n collectionClass : DatasetDCECollection,\n\n /** String representation. */\n toString : function(){ return 'List' + DatasetCollection.prototype.toString.call( this ); }\n});\n\n\n//==============================================================================\n/** Model for a DatasetCollection containing fwd/rev datasets (a list of 2).\n */\nvar PairDatasetCollection = ListDatasetCollection.extend(\n/** @lends PairDatasetCollection.prototype */{\n\n /** String representation. */\n toString : function(){ return 'Pair' + DatasetCollection.prototype.toString.call( this ); }\n});\n\n\n//_________________________________________________________________________________________________ NESTED COLLECTIONS\n// this is where things get weird, man. Weird.\n//TODO: it might be possible to compact all the following...I think.\n//==============================================================================\n/** @class Backbone model for a Generic DatasetCollectionElement that is also a DatasetCollection\n * (a nested collection). Currently only list:paired.\n */\nvar NestedDCDCE = DatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedDCDCE.prototype */{\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually it now\n /** call the mixin constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedDCDCE.constructor:', attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection containing Generic NestedDCDCE's (nested dataset collections).\n */\nvar NestedDCDCECollection = DCECollection.extend(\n/** @lends NestedDCDCECollection.prototype */{\n\n /** This is a collection of nested collections */\n model: NestedDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a paired dataset collection within a list:paired dataset collection.\n */\nvar NestedPairDCDCE = PairDatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedPairDCDCE.prototype */{\n//TODO:?? possibly rename to NestedDatasetCollection?\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually it now\n /** This is both a collection and a collection element - call the constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedPairDCDCE.constructor:', attributes, options );\n //DatasetCollection.constructor.call( this, attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedPairDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection for a backbone collection containing paired dataset collections.\n */\nvar NestedPairDCDCECollection = NestedDCDCECollection.extend(\n/** @lends PairDCDCECollection.prototype */{\n\n /** We know this collection is composed of only nested pair collections */\n model: NestedPairDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedPairDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone Model for a DatasetCollection (list) that contains DatasetCollections (pairs).\n */\nvar ListPairedDatasetCollection = DatasetCollection.extend(\n/** @lends ListPairedDatasetCollection.prototype */{\n\n /** list:paired is the only collection that itself contains collections */\n collectionClass : NestedPairDCDCECollection,\n\n /** String representation. */\n toString : function(){\n return ([ 'ListPairedDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a list dataset collection within a list:list dataset collection. */\nvar NestedListDCDCE = ListDatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedListDCDCE.prototype */{\n\n /** This is both a collection and a collection element - call the constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedListDCDCE.constructor:', attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedListDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection containing list dataset collections. */\nvar NestedListDCDCECollection = NestedDCDCECollection.extend({\n\n /** We know this collection is composed of only nested pair collections */\n model: NestedListDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedListDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone Model for a DatasetCollection (list) that contains other lists. */\nvar ListOfListsDatasetCollection = DatasetCollection.extend({\n\n /** list:paired is the only collection that itself contains collections */\n collectionClass : NestedListDCDCECollection,\n\n /** String representation. */\n toString : function(){\n return ([ 'ListOfListsDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n ListDatasetCollection : ListDatasetCollection,\n PairDatasetCollection : PairDatasetCollection,\n ListPairedDatasetCollection : ListPairedDatasetCollection,\n ListOfListsDatasetCollection: ListOfListsDatasetCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-model.js","\ndefine([\n \"mvc/history/hdca-model\",\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"mvc/collection/base-creator\",\n \"mvc/ui/ui-modal\",\n \"utils/natural-sort\",\n \"utils/localization\",\n \"ui/hoverhighlight\"\n], function( HDCA, STATES, BASE_MVC, baseCreator, UI_MODAL, naturalSort, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n\n/*==============================================================================\nTODO:\n use proper Element model and not just json\n straighten out createFn, collection.createHDCA\n possibly stop using modals for this\n It would be neat to do a drag and drop\n\n==============================================================================*/\n/** A view for both DatasetDCEs and NestedDCDCEs\n * (things that implement collection-model:DatasetCollectionElementMixin)\n */\nvar DatasetCollectionElementView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n//TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n tagName : 'li',\n className : 'collection-element',\n\n initialize : function( attributes ){\n this.element = attributes.element || {};\n this.selected = attributes.selected || false;\n },\n\n render : function(){\n this.$el\n .attr( 'data-element-id', this.element.id )\n .attr( 'draggable', true )\n .html( this.template({ element: this.element }) );\n if( this.selected ){\n this.$el.addClass( 'selected' );\n }\n return this;\n },\n\n //TODO: lots of unused space in the element - possibly load details and display them horiz.\n template : _.template([\n '',\n '<%- element.name %>',\n '',\n '',\n ].join('')),\n\n /** select this element and pub */\n select : function( toggle ){\n this.$el.toggleClass( 'selected', toggle );\n this.trigger( 'select', {\n source : this,\n selected : this.$el.hasClass( 'selected' )\n });\n },\n\n /** animate the removal of this element and pub */\n discard : function(){\n var view = this,\n parentWidth = this.$el.parent().width();\n this.$el.animate({ 'margin-right' : parentWidth }, 'fast', function(){\n view.trigger( 'discard', {\n source : view\n });\n view.destroy();\n });\n },\n\n /** remove the DOM and any listeners */\n destroy : function(){\n this.off();\n this.$el.remove();\n },\n\n events : {\n 'click' : '_click',\n 'click .name' : '_clickName',\n 'click .discard': '_clickDiscard',\n\n 'dragstart' : '_dragstart',\n 'dragend' : '_dragend',\n 'dragover' : '_sendToParent',\n 'drop' : '_sendToParent'\n },\n\n /** select when the li is clicked */\n _click : function( ev ){\n ev.stopPropagation();\n this.select( ev );\n },\n\n /** rename a pair when the name is clicked */\n _clickName : function( ev ){\n ev.stopPropagation();\n ev.preventDefault();\n var promptString = [ _l( 'Enter a new name for the element' ), ':\\n(',\n _l( 'Note that changing the name here will not rename the dataset' ), ')' ].join( '' ),\n response = prompt( _l( 'Enter a new name for the element' ) + ':', this.element.name );\n if( response ){\n this.element.name = response;\n this.render();\n }\n //TODO: cancelling with ESC leads to closure of the creator...\n },\n\n /** discard when the discard button is clicked */\n _clickDiscard : function( ev ){\n ev.stopPropagation();\n this.discard();\n },\n\n /** dragging pairs for re-ordering */\n _dragstart : function( ev ){\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n ev.dataTransfer.effectAllowed = 'move';\n ev.dataTransfer.setData( 'text/plain', JSON.stringify( this.element ) );\n\n this.$el.addClass( 'dragging' );\n this.$el.parent().trigger( 'collection-element.dragstart', [ this ] );\n },\n\n /** dragging for re-ordering */\n _dragend : function( ev ){\n this.$el.removeClass( 'dragging' );\n this.$el.parent().trigger( 'collection-element.dragend', [ this ] );\n },\n\n /** manually bubble up an event to the parent/container */\n _sendToParent : function( ev ){\n this.$el.parent().trigger( ev );\n },\n\n /** string rep */\n toString : function(){\n return 'DatasetCollectionElementView()';\n }\n});\n\n\n// ============================================================================\n/** An interface for building collections.\n */\nvar ListCollectionCreator = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend( baseCreator.CollectionCreatorMixin ).extend({\n _logNamespace : logNamespace,\n\n /** the class used to display individual elements */\n elementViewClass : DatasetCollectionElementView,\n /** the class this creator will create and save */\n collectionClass : HDCA.HistoryListDatasetCollection,\n className : 'list-collection-creator collection-creator flex-row-container',\n\n /** minimum number of valid elements to start with in order to build a collection of this type */\n minElements : 1,\n\n defaultAttributes : {\n//TODO: remove - use new collectionClass().save()\n /** takes elements and creates the proper collection - returns a promise */\n creationFn : function(){ throw new TypeError( 'no creation fn for creator' ); },\n /** fn to call when the collection is created (scoped to this) */\n oncreate : function(){},\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n oncancel : function(){},\n /** distance from list edge to begin autoscrolling list */\n autoscrollDist : 24,\n /** Color passed to hoverhighlight */\n highlightClr : 'rgba( 64, 255, 255, 1.0 )'\n },\n\n footerSettings : {\n '.hide-originals': 'hideOriginals'\n },\n\n /** set up initial options, instance vars, behaviors */\n initialize : function( attributes ){\n this.metric( 'ListCollectionCreator.initialize', attributes );\n var creator = this;\n _.each( this.defaultAttributes, function( value, key ){\n value = attributes[ key ] || value;\n creator[ key ] = value;\n });\n\n /** unordered, original list - cache to allow reversal */\n creator.initialElements = attributes.elements || [];\n\n this._setUpCommonSettings( attributes );\n this._instanceSetUp();\n this._elementsSetUp();\n this._setUpBehaviors();\n },\n\n /** set up instance vars */\n _instanceSetUp : function(){\n /** Ids of elements that have been selected by the user - to preserve over renders */\n this.selectedIds = {};\n /** DOM elements currently being dragged */\n this.$dragging = null;\n /** Used for blocking UI events during ajax/operations (don't post twice) */\n this.blocking = false;\n },\n\n // ------------------------------------------------------------------------ process raw list\n /** set up main data */\n _elementsSetUp : function(){\n //this.debug( '-- _dataSetUp' );\n /** a list of invalid elements and the reasons they aren't valid */\n this.invalidElements = [];\n//TODO: handle fundamental problem of syncing DOM, views, and list here\n /** data for list in progress */\n this.workingElements = [];\n /** views for workingElements */\n this.elementViews = [];\n\n // copy initial list, sort, add ids if needed\n this.workingElements = this.initialElements.slice( 0 );\n this._ensureElementIds();\n this._validateElements();\n this._mangleDuplicateNames();\n this._sortElements();\n },\n\n /** add ids to dataset objs in initial list if none */\n _ensureElementIds : function(){\n this.workingElements.forEach( function( element ){\n if( !element.hasOwnProperty( 'id' ) ){\n element.id = _.uniqueId();\n }\n });\n return this.workingElements;\n },\n\n /** separate working list into valid and invalid elements for this collection */\n _validateElements : function(){\n var creator = this,\n existingNames = {};\n creator.invalidElements = [];\n\n this.workingElements = this.workingElements.filter( function( element ){\n var problem = creator._isElementInvalid( element );\n if( problem ){\n creator.invalidElements.push({\n element : element,\n text : problem\n });\n }\n return !problem;\n });\n return this.workingElements;\n },\n\n /** describe what is wrong with a particular element if anything */\n _isElementInvalid : function( element ){\n if( element.history_content_type !== 'dataset' ){\n return _l( \"is not a dataset\" );\n }\n var validState = element.state === STATES.OK || _.contains( STATES.NOT_READY_STATES, element.state );\n if( ! validState ){\n return _l( \"has errored, is paused, or is not accessible\" );\n }\n if( element.deleted || element.purged ){\n return _l( \"has been deleted or purged\" );\n }\n return null;\n },\n\n /** mangle duplicate names using a mac-like '(counter)' addition to any duplicates */\n _mangleDuplicateNames : function(){\n var SAFETY = 900,\n counter = 1,\n existingNames = {};\n this.workingElements.forEach( function( element ){\n var currName = element.name;\n while( existingNames.hasOwnProperty( currName ) ){\n currName = element.name + ' (' + counter + ')';\n counter += 1;\n if( counter >= SAFETY ){\n throw new Error( 'Safety hit in while loop - thats impressive' );\n }\n }\n element.name = currName;\n existingNames[ element.name ] = true;\n });\n },\n\n /** sort a list of elements */\n _sortElements : function( list ){\n // // currently only natural sort by name\n // this.workingElements.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n // return this.workingElements;\n },\n\n // ------------------------------------------------------------------------ rendering\n // templates : ListCollectionCreator.templates,\n /** render the entire interface */\n render : function( speed, callback ){\n //this.debug( '-- _render' );\n if( this.workingElements.length < this.minElements ){\n return this._renderInvalid( speed, callback );\n }\n\n this.$el.empty().html( this.templates.main() );\n this._renderHeader( speed );\n this._renderMiddle( speed );\n this._renderFooter( speed );\n this._addPluginComponents();\n this.$( '.collection-name' ).focus();\n this.trigger( 'rendered', this );\n return this;\n },\n\n\n /** render a simplified interface aimed at telling the user why they can't move forward */\n _renderInvalid : function( speed, callback ){\n //this.debug( '-- _render' );\n this.$el.empty().html( this.templates.invalidInitial({\n problems: this.invalidElements,\n elements: this.workingElements,\n }));\n if( typeof this.oncancel === 'function' ){\n this.$( '.cancel-create.btn' ).show();\n }\n this.trigger( 'rendered', this );\n return this;\n },\n\n /** render the header section */\n _renderHeader : function( speed, callback ){\n var $header = this.$( '.header' ).empty().html( this.templates.header() )\n .find( '.help-content' ).prepend( $( this.templates.helpContent() ) );\n //TODO: should only show once despite calling _renderHeader again\n if( this.invalidElements.length ){\n this._invalidElementsAlert();\n }\n return $header;\n },\n\n /** render the middle including the elements */\n _renderMiddle : function( speed, callback ){\n var $middle = this.$( '.middle' ).empty().html( this.templates.middle() );\n this._renderList( speed );\n return $middle;\n },\n\n /** add any jQuery/bootstrap/custom plugins to elements rendered */\n _addPluginComponents : function(){\n this.$( '.help-content i' ).hoverhighlight( '.collection-creator', this.highlightClr );\n },\n\n /** build and show an alert describing any elements that could not be included due to problems */\n _invalidElementsAlert : function(){\n this._showAlert( this.templates.invalidElements({ problems: this.invalidElements }), 'alert-warning' );\n },\n\n _disableNameAndCreate : function( disable ){\n disable = !_.isUndefined( disable )? disable : true;\n if( disable ){\n this.$( '.collection-name' ).prop( 'disabled', true );\n this.$( '.create-collection' ).toggleClass( 'disabled', true );\n // } else {\n // this.$( '.collection-name' ).prop( 'disabled', false );\n // this.$( '.create-collection' ).removeClass( 'disable' );\n }\n },\n\n // ------------------------------------------------------------------------ rendering elements\n /** conv. to the main list display DOM */\n $list : function(){\n return this.$( '.collection-elements' );\n },\n\n /** show or hide the clear selected control based on the num of selected elements */\n _renderClearSelected : function(){\n if( _.size( this.selectedIds ) ){\n this.$( '.collection-elements-controls > .clear-selected' ).show();\n } else {\n this.$( '.collection-elements-controls > .clear-selected' ).hide();\n }\n },\n\n /** render the elements in order (or a warning if no elements found) */\n _renderList : function( speed, callback ){\n //this.debug( '-- _renderList' );\n var creator = this,\n $tmp = jQuery( '
                        ' ),\n $list = creator.$list();\n\n _.each( this.elementViews, function( view ){\n view.destroy();\n creator.removeElementView( view );\n });\n\n // if( !this.workingElements.length ){\n // this._renderNoValidElements();\n // return;\n // }\n\n creator.workingElements.forEach( function( element ){\n var elementView = creator._createElementView( element );\n $tmp.append( elementView.$el );\n });\n\n creator._renderClearSelected();\n $list.empty().append( $tmp.children() );\n _.invoke( creator.elementViews, 'render' );\n\n if( $list.height() > $list.css( 'max-height' ) ){\n $list.css( 'border-width', '1px 0px 1px 0px' );\n } else {\n $list.css( 'border-width', '0px' );\n }\n },\n\n /** create an element view, cache in elementViews, set up listeners, and return */\n _createElementView : function( element ){\n var elementView = new this.elementViewClass({\n//TODO: use non-generic class or not all\n // model : COLLECTION.DatasetDCE( element )\n element : element,\n selected: _.has( this.selectedIds, element.id )\n });\n this.elementViews.push( elementView );\n this._listenToElementView( elementView );\n return elementView;\n },\n\n /** listen to any element events */\n _listenToElementView : function( view ){\n var creator = this;\n creator.listenTo( view, {\n select : function( data ){\n var element = data.source.element;\n if( data.selected ){\n creator.selectedIds[ element.id ] = true;\n } else {\n delete creator.selectedIds[ element.id ];\n }\n creator.trigger( 'elements:select', data );\n },\n discard : function( data ){\n creator.trigger( 'elements:discard', data );\n }\n });\n },\n\n /** add a new element view based on the json in element */\n addElementView : function( element ){\n//TODO: workingElements is sorted, add element in appropo index\n // add element, sort elements, find element index\n // var view = this._createElementView( element );\n // return view;\n },\n\n /** stop listening to view and remove from caches */\n removeElementView : function( view ){\n delete this.selectedIds[ view.element.id ];\n this._renderClearSelected();\n\n this.elementViews = _.without( this.elementViews, view );\n this.stopListening( view );\n },\n\n /** render a message in the list that no elements remain to create a collection */\n _renderNoElementsLeft : function(){\n this._disableNameAndCreate( true );\n this.$( '.collection-elements' ).append( this.templates.noElementsLeft() );\n },\n\n // /** render a message in the list that no valid elements were found to create a collection */\n // _renderNoValidElements : function(){\n // this._disableNameAndCreate( true );\n // this.$( '.collection-elements' ).append( this.templates.noValidElements() );\n // },\n\n // ------------------------------------------------------------------------ API\n /** convert element into JSON compatible with the collections API */\n _elementToJSON : function( element ){\n // return element.toJSON();\n return element;\n },\n\n /** create the collection via the API\n * @returns {jQuery.xhr Object} the jquery ajax request\n */\n createList : function( name ){\n if( !this.workingElements.length ){\n var message = _l( 'No valid elements for final list' ) + '. ';\n message += '' + _l( 'Cancel' ) + ' ';\n message += _l( 'or' );\n message += ' ' + _l( 'start over' ) + '.';\n this._showAlert( message );\n return;\n }\n\n var creator = this,\n elements = this.workingElements.map( function( element ){\n return creator._elementToJSON( element );\n });\n\n creator.blocking = true;\n return creator.creationFn( elements, name, creator.hideOriginals )\n .always( function(){\n creator.blocking = false;\n })\n .fail( function( xhr, status, message ){\n creator.trigger( 'error', {\n xhr : xhr,\n status : status,\n message : _l( 'An error occurred while creating this collection' )\n });\n })\n .done( function( response, message, xhr ){\n creator.trigger( 'collection:created', response, message, xhr );\n creator.metric( 'collection:created', response );\n if( typeof creator.oncreate === 'function' ){\n creator.oncreate.call( this, response, message, xhr );\n }\n });\n },\n\n // ------------------------------------------------------------------------ events\n /** set up event handlers on self */\n _setUpBehaviors : function(){\n this.on( 'error', this._errorHandler );\n\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this.on( 'elements:select', function( data ){\n this._renderClearSelected();\n });\n\n this.on( 'elements:discard', function( data ){\n var element = data.source.element;\n this.removeElementView( data.source );\n\n this.workingElements = _.without( this.workingElements, element );\n if( !this.workingElements.length ){\n this._renderNoElementsLeft();\n }\n });\n\n //this.on( 'all', function(){\n // this.info( arguments );\n //});\n return this;\n },\n\n /** handle errors with feedback and details to the user (if available) */\n _errorHandler : function( data ){\n this.error( data );\n\n var creator = this;\n content = data.message || _l( 'An error occurred' );\n if( data.xhr ){\n var xhr = data.xhr,\n message = data.message;\n if( xhr.readyState === 0 && xhr.status === 0 ){\n content += ': ' + _l( 'Galaxy could not be reached and may be updating.' ) +\n _l( ' Try again in a few minutes.' );\n } else if( xhr.responseJSON ){\n content += ':
                        ' + JSON.stringify( xhr.responseJSON ) + '
                        ';\n } else {\n content += ': ' + message;\n }\n }\n creator._showAlert( content, 'alert-danger' );\n },\n\n events : {\n // header\n 'click .more-help' : '_clickMoreHelp',\n 'click .less-help' : '_clickLessHelp',\n 'click .main-help' : '_toggleHelp',\n 'click .header .alert button' : '_hideAlert',\n\n 'click .reset' : 'reset',\n 'click .clear-selected' : 'clearSelectedElements',\n\n // elements - selection\n 'click .collection-elements' : 'clearSelectedElements',\n\n // elements - drop target\n // 'dragenter .collection-elements': '_dragenterElements',\n // 'dragleave .collection-elements': '_dragleaveElements',\n 'dragover .collection-elements' : '_dragoverElements',\n 'drop .collection-elements' : '_dropElements',\n\n // these bubble up from the elements as custom events\n 'collection-element.dragstart .collection-elements' : '_elementDragstart',\n 'collection-element.dragend .collection-elements' : '_elementDragend',\n\n // footer\n 'change .collection-name' : '_changeName',\n 'keydown .collection-name' : '_nameCheckForEnter',\n 'change .hide-originals' : '_changeHideOriginals',\n 'click .cancel-create' : '_cancelCreate',\n 'click .create-collection' : '_clickCreate'//,\n },\n\n // ........................................................................ elements\n /** reset all data to the initial state */\n reset : function(){\n this._instanceSetUp();\n this._elementsSetUp();\n this.render();\n },\n\n /** deselect all elements */\n clearSelectedElements : function( ev ){\n this.$( '.collection-elements .collection-element' ).removeClass( 'selected' );\n this.$( '.collection-elements-controls > .clear-selected' ).hide();\n },\n\n //_dragenterElements : function( ev ){\n // //this.debug( '_dragenterElements:', ev );\n //},\n//TODO: if selected are dragged out of the list area - remove the placeholder - cuz it won't work anyway\n // _dragleaveElements : function( ev ){\n // //this.debug( '_dragleaveElements:', ev );\n // },\n\n /** track the mouse drag over the list adding a placeholder to show where the drop would occur */\n _dragoverElements : function( ev ){\n //this.debug( '_dragoverElements:', ev );\n ev.preventDefault();\n\n var $list = this.$list();\n this._checkForAutoscroll( $list, ev.originalEvent.clientY );\n var $nearest = this._getNearestElement( ev.originalEvent.clientY );\n\n //TODO: no need to re-create - move instead\n this.$( '.element-drop-placeholder' ).remove();\n var $placeholder = $( '
                        ' );\n if( !$nearest.length ){\n $list.append( $placeholder );\n } else {\n $nearest.before( $placeholder );\n }\n },\n\n /** If the mouse is near enough to the list's top or bottom, scroll the list */\n _checkForAutoscroll : function( $element, y ){\n var AUTOSCROLL_SPEED = 2,\n offset = $element.offset(),\n scrollTop = $element.scrollTop(),\n upperDist = y - offset.top,\n lowerDist = ( offset.top + $element.outerHeight() ) - y;\n if( upperDist >= 0 && upperDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop - AUTOSCROLL_SPEED );\n } else if( lowerDist >= 0 && lowerDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop + AUTOSCROLL_SPEED );\n }\n },\n\n /** get the nearest element based on the mouse's Y coordinate.\n * If the y is at the end of the list, return an empty jQuery object.\n */\n _getNearestElement : function( y ){\n var WIGGLE = 4,\n lis = this.$( '.collection-elements li.collection-element' ).toArray();\n for( var i=0; i y && top - halfHeight < y ){\n return $li;\n }\n }\n return $();\n },\n\n /** drop (dragged/selected elements) onto the list, re-ordering the internal list */\n _dropElements : function( ev ){\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n // both required for firefox\n ev.preventDefault();\n ev.dataTransfer.dropEffect = 'move';\n\n // insert before the nearest element or after the last.\n var $nearest = this._getNearestElement( ev.clientY );\n if( $nearest.length ){\n this.$dragging.insertBefore( $nearest );\n } else {\n // no nearest before - insert after last element\n this.$dragging.insertAfter( this.$( '.collection-elements .collection-element' ).last() );\n }\n // resync the creator's list based on the new DOM order\n this._syncOrderToDom();\n return false;\n },\n\n /** resync the creator's list of elements based on the DOM order */\n _syncOrderToDom : function(){\n var creator = this,\n newElements = [];\n //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n this.$( '.collection-elements .collection-element' ).each( function(){\n var id = $( this ).attr( 'data-element-id' ),\n element = _.findWhere( creator.workingElements, { id: id });\n if( element ){\n newElements.push( element );\n } else {\n console.error( 'missing element: ', id );\n }\n });\n this.workingElements = newElements;\n this._renderList();\n },\n\n /** drag communication with element sub-views: dragstart */\n _elementDragstart : function( ev, element ){\n // auto select the element causing the event and move all selected\n element.select( true );\n this.$dragging = this.$( '.collection-elements .collection-element.selected' );\n },\n\n /** drag communication with element sub-views: dragend - remove the placeholder */\n _elementDragend : function( ev, element ){\n $( '.element-drop-placeholder' ).remove();\n this.$dragging = null;\n },\n\n // ------------------------------------------------------------------------ templates\n //TODO: move to require text plugin and load these as text\n //TODO: underscore currently unnecc. bc no vars are used\n //TODO: better way of localizing text-nodes in long strings\n /** underscore template fns attached to class */\n templates : _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\n /** the header (not including help text) */\n header : _.template([\n '
                        ',\n '', _l( 'More help' ), '',\n '
                        ',\n '', _l( 'Less' ), '',\n '
                        ',\n '
                        ',\n '
                        ',\n '',\n '',\n '
                        ',\n ].join('')),\n\n /** the middle: element list */\n middle : _.template([\n '',\n '
                        ',\n '
                        '\n ].join('')),\n\n /** creation and cancel controls */\n footer : _.template([\n '
                        ',\n '
                        ',\n '',\n '
                        ',\n '
                        ',\n '',\n '
                        ', _l( 'Name' ), ':
                        ',\n '
                        ',\n '
                        ',\n\n '
                        ',\n '
                        ',\n '',\n '
                        ',\n '',\n '',\n '
                        ',\n '
                        ',\n\n '
                        ',\n '',\n '
                        ',\n '
                        '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                        ', _l([\n 'Collections of datasets are permanent, ordered lists of datasets that can be passed to tools and ',\n 'workflows in order to have analyses done on each member of the entire group. This interface allows ',\n 'you to create a collection and re-order the final collection.'\n ].join( '' )), '

                        ',\n '
                          ',\n '
                        • ', _l([\n 'Rename elements in the list by clicking on ',\n 'the existing name.'\n ].join( '' )), '
                        • ',\n '
                        • ', _l([\n 'Discard elements from the final created list by clicking on the ',\n '\"Discard\" button.'\n ].join( '' )), '
                        • ',\n '
                        • ', _l([\n 'Reorder the list by clicking and dragging elements. Select multiple elements by clicking on ',\n 'them and you can then move those selected by dragging the ',\n 'entire group. Deselect them by clicking them again or by clicking the ',\n 'the \"Clear selected\" link.'\n ].join( '' )), '
                        • ',\n '
                        • ', _l([\n 'Click the \"Start over\" link to begin again as if you had just opened ',\n 'the interface.'\n ].join( '' )), '
                        • ',\n '
                        • ', _l([\n 'Click the \"Cancel\" button to exit the interface.'\n ].join( '' )), '
                        • ',\n '

                        ',\n '

                        ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\".'\n ].join( '' )), '

                        '\n ].join('')),\n\n /** shown in list when all elements are discarded */\n invalidElements : _.template([\n _l( 'The following selections could not be included due to problems:' ),\n '
                          <% _.each( problems, function( problem ){ %>',\n '
                        • <%- problem.element.name %>: <%- problem.text %>
                        • ',\n '<% }); %>
                        '\n ].join('')),\n\n /** shown in list when all elements are discarded */\n noElementsLeft : _.template([\n '
                      2. ',\n _l( 'No elements left! ' ),\n _l( 'Would you like to ' ), '', _l( 'start over' ), '?',\n '
                      3. '\n ].join('')),\n\n /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n invalidInitial : _.template([\n '
                        ',\n '
                        ',\n '',\n '<% if( _.size( problems ) ){ %>',\n _l( 'The following selections could not be included due to problems' ), ':',\n '
                          <% _.each( problems, function( problem ){ %>',\n '
                        • <%- problem.element.name %>: <%- problem.text %>
                        • ',\n '<% }); %>
                        ',\n '<% } else if( _.size( elements ) < 1 ){ %>',\n _l( 'No datasets were selected' ), '.',\n '<% } %>',\n '
                        ',\n _l( 'At least one element is needed for the collection' ), '. ',\n _l( 'You may need to ' ),\n '', _l( 'cancel' ), ' ',\n _l( 'and reselect new elements' ), '.',\n '
                        ',\n '
                        ',\n '
                        ',\n '
                        ',\n '
                        ',\n '
                        ',\n '',\n // _l( 'Create a different kind of collection' ),\n '
                        ',\n '
                        ',\n '
                        '\n ].join('')),\n }),\n\n // ------------------------------------------------------------------------ misc\n /** string rep */\n toString : function(){ return 'ListCollectionCreator'; }\n});\n\n\n\n//=============================================================================\n/** Create a modal and load its body with the given CreatorClass creator type\n * @returns {Deferred} resolved when creator has built a collection.\n */\nvar collectionCreatorModal = function _collectionCreatorModal( elements, options, CreatorClass ){\n\n var deferred = jQuery.Deferred(),\n modal = Galaxy.modal || ( new UI_MODAL.View() ),\n creator;\n\n options = _.defaults( options || {}, {\n elements : elements,\n oncancel : function(){\n modal.hide();\n deferred.reject( 'cancelled' );\n },\n oncreate : function( creator, response ){\n modal.hide();\n deferred.resolve( response );\n }\n });\n\n creator = new CreatorClass( options );\n modal.show({\n title : options.title || _l( 'Create a collection' ),\n body : creator.$el,\n width : '80%',\n height : '100%',\n closing_events: true\n });\n creator.render();\n window._collectionCreator = creator;\n\n //TODO: remove modal header\n return deferred;\n};\n\n/** List collection flavor of collectionCreatorModal. */\nvar listCollectionCreatorModal = function _listCollectionCreatorModal( elements, options ){\n options = options || {};\n options.title = _l( 'Create a collection from a list of datasets' );\n return collectionCreatorModal( elements, options, ListCollectionCreator );\n};\n\n\n//==============================================================================\n/** Use a modal to create a list collection, then add it to the given history contents.\n * @returns {Deferred} resolved when the collection is added to the history.\n */\nfunction createListCollection( contents, defaultHideSourceItems ){\n var elements = contents.toJSON(),\n promise = listCollectionCreatorModal( elements, {\n defaultHideSourceItems: defaultHideSourceItems,\n creationFn : function( elements, name, hideSourceItems ){\n elements = elements.map( function( element ){\n return {\n id : element.id,\n name : element.name,\n //TODO: this allows for list:list even if the filter above does not - reconcile\n src : ( element.history_content_type === 'dataset'? 'hda' : 'hdca' )\n };\n });\n return contents.createHDCA( elements, 'list', name, hideSourceItems );\n }\n });\n return promise;\n}\n\n//==============================================================================\n return {\n DatasetCollectionElementView: DatasetCollectionElementView,\n ListCollectionCreator : ListCollectionCreator,\n\n collectionCreatorModal : collectionCreatorModal,\n listCollectionCreatorModal : listCollectionCreatorModal,\n createListCollection : createListCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/list-collection-creator.js","define([\n \"mvc/list/list-item\",\n \"mvc/dataset/states\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_ITEM, STATES, faIconButton, BASE_MVC, _l ){\n'use strict';\n\nvar logNamespace = 'dataset';\n/*==============================================================================\nTODO:\n straighten out state rendering and templates used\n inaccessible/STATES.NOT_VIEWABLE is a special case\n simplify button rendering\n\n==============================================================================*/\nvar _super = LIST_ITEM.ListItemView;\n/** @class Read only list view for either LDDAs, HDAs, or HDADCEs.\n * Roughly, any DatasetInstance (and not a raw Dataset).\n */\nvar DatasetListItemView = _super.extend(\n/** @lends DatasetListItemView.prototype */{\n _logNamespace : logNamespace,\n\n className : _super.prototype.className + \" dataset\",\n //TODO:?? doesn't exactly match an hda's type_id\n id : function(){\n return [ 'dataset', this.model.get( 'id' ) ].join( '-' );\n },\n\n /** Set up: instance vars, options, and event handlers */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( this + '.initialize:', attributes );\n _super.prototype.initialize.call( this, attributes );\n\n /** where should pages from links be displayed? (default to new tab/window) */\n this.linkTarget = attributes.linkTarget || '_blank';\n },\n\n /** event listeners */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n var self = this;\n\n // re-rendering on any model changes\n return self.listenTo( self.model, {\n 'change': function( model ){\n // if the model moved into the ready state and is expanded without details, fetch those details now\n if( self.model.changedAttributes().state &&\n self.model.inReadyState() &&\n self.expanded &&\n !self.model.hasDetails() ){\n // normally, will render automatically (due to fetch -> change),\n // but! setting_metadata sometimes doesn't cause any other changes besides state\n // so, not rendering causes it to seem frozen in setting_metadata state\n self.model.fetch({ silent : true })\n .done( function(){ self.render(); });\n } else {\n if( _.has( model.changed, 'tags' ) && _.keys( model.changed ).length === 1 ){\n // If only the tags have changed, rerender specifically\n // the titlebar region. Otherwise default to the full\n // render.\n self.$( '.nametags' ).html( self._renderNametags() );\n } else {\n self.render();\n }\n }\n }\n });\n },\n\n // ......................................................................... expandable\n /** In this override, only get details if in the ready state, get rerunnable if in other states.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n // ......................................................................... removal\n /** Remove this view's html from the DOM and remove all event listeners.\n * @param {Number or String} speed jq effect speed\n * @param {Function} callback an optional function called when removal is done (scoped to this view)\n */\n remove : function( speed, callback ){\n var view = this;\n speed = speed || this.fxSpeed;\n this.$el.fadeOut( speed, function(){\n Backbone.View.prototype.remove.call( view );\n if( callback ){ callback.call( view ); }\n });\n },\n\n // ......................................................................... rendering\n /* TODO:\n dataset states are the issue primarily making dataset rendering complex\n each state should have it's own way of displaying/set of details\n often with different actions that can be applied\n throw in deleted/purged/visible and things get complicated easily\n I've considered (a couple of times) - creating a view for each state\n - but recreating the view during an update...seems wrong\n */\n /** In this override, add the dataset state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n if( this.model.has( 'state' ) ){\n this.$el.addClass( 'state-' + this.model.get( 'state' ) );\n }\n return this.$el;\n },\n\n // ................................................................................ titlebar\n /** In this override, add the dataset display button. */\n _renderPrimaryActions : function(){\n // render just the display for read-only\n return [ this._renderDisplayButton() ];\n },\n\n /** Render icon-button to display dataset data */\n _renderDisplayButton : function(){\n // don't show display if not viewable or not accessible\n var state = this.model.get( 'state' );\n if( ( state === STATES.NOT_VIEWABLE ) ||\n ( state === STATES.DISCARDED ) ||\n ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var displayBtnData = {\n target : this.linkTarget,\n classes : 'display-btn'\n };\n\n // show a disabled display if the data's been purged\n if( this.model.get( 'purged' ) ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'Cannot display datasets removed from disk' );\n\n // disable if still uploading\n } else if( state === STATES.UPLOAD ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'This dataset must finish uploading before it can be viewed' );\n\n // disable if still new\n } else if( state === STATES.NEW ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'This dataset is not yet viewable' );\n\n } else {\n displayBtnData.title = _l( 'View data' );\n\n // default link for dataset\n displayBtnData.href = this.model.urls.display;\n\n // add frame manager option onclick event\n var self = this;\n displayBtnData.onclick = function( ev ){\n if (Galaxy.frame && Galaxy.frame.active) {\n // Add dataset to frames.\n Galaxy.frame.addDataset(self.model.get('id'));\n ev.preventDefault();\n }\n };\n }\n displayBtnData.faIcon = 'fa-eye';\n return faIconButton( displayBtnData );\n },\n\n // ......................................................................... rendering details\n /** Render the enclosing div of the hda body and, if expanded, the html in the body\n * @returns {jQuery} rendered DOM\n */\n _renderDetails : function(){\n //TODO: generalize to be allow different details for each state\n\n // no access - render nothing but a message\n if( this.model.get( 'state' ) === STATES.NOT_VIEWABLE ){\n return $( this.templates.noAccess( this.model.toJSON(), this ) );\n }\n\n var $details = _super.prototype._renderDetails.call( this );\n $details.find( '.actions .left' ).empty().append( this._renderSecondaryActions() );\n $details.find( '.summary' ).html( this._renderSummary() )\n .prepend( this._renderDetailMessages() );\n $details.find( '.display-applications' ).html( this._renderDisplayApplications() );\n\n this._setUpBehaviors( $details );\n return $details;\n },\n\n /** Defer to the appropo summary rendering fn based on state */\n _renderSummary : function(){\n var json = this.model.toJSON(),\n summaryRenderFn = this.templates.summaries[ json.state ];\n summaryRenderFn = summaryRenderFn || this.templates.summaries.unknown;\n return summaryRenderFn( json, this );\n },\n\n /** Render messages to be displayed only when the details are shown */\n _renderDetailMessages : function(){\n var view = this,\n $warnings = $( '
                        ' ),\n json = view.model.toJSON();\n //TODO:! unordered (map)\n _.each( view.templates.detailMessages, function( templateFn ){\n $warnings.append( $( templateFn( json, view ) ) );\n });\n return $warnings;\n },\n\n /** Render the external display application links */\n _renderDisplayApplications : function(){\n if( this.model.isDeletedOrPurged() ){ return ''; }\n // render both old and new display apps using the same template\n return [\n this.templates.displayApplications( this.model.get( 'display_apps' ), this ),\n this.templates.displayApplications( this.model.get( 'display_types' ), this )\n ].join( '' );\n },\n\n // ......................................................................... secondary/details actions\n /** A series of links/buttons for less commonly used actions: re-run, info, etc. */\n _renderSecondaryActions : function(){\n this.debug( '_renderSecondaryActions' );\n switch( this.model.get( 'state' ) ){\n case STATES.NOT_VIEWABLE:\n return [];\n case STATES.OK:\n case STATES.FAILED_METADATA:\n case STATES.ERROR:\n return [ this._renderDownloadButton(), this._renderShowParamsButton() ];\n }\n return [ this._renderShowParamsButton() ];\n },\n\n /** Render icon-button to show the input and output (stdout/err) for the job that created this.\n * @returns {jQuery} rendered DOM\n */\n _renderShowParamsButton : function(){\n // gen. safe to show in all cases\n return faIconButton({\n title : _l( 'View details' ),\n classes : 'params-btn',\n href : this.model.urls.show_params,\n target : this.linkTarget,\n faIcon : 'fa-info-circle',\n onclick : function( ev ) {\n if ( Galaxy.frame && Galaxy.frame.active ) {\n Galaxy.frame.add( { title: 'Dataset details', url: this.href } );\n ev.preventDefault();\n ev.stopPropagation();\n }\n }\n });\n },\n\n\n /** Render icon-button/popupmenu to download the data (and/or the associated meta files (bai, etc.)) for this.\n * @returns {jQuery} rendered DOM\n */\n _renderDownloadButton : function(){\n // don't show anything if the data's been purged\n if( this.model.get( 'purged' ) || !this.model.hasData() ){ return null; }\n\n // return either: a popupmenu with links to download assoc. meta files (if there are meta files)\n // or a single download icon-button (if there are no meta files)\n if( !_.isEmpty( this.model.get( 'meta_files' ) ) ){\n return this._renderMetaFileDownloadButton();\n }\n\n return $([\n '',\n '',\n ''\n ].join( '' ));\n },\n\n /** Render the download button which opens a dropdown with links to download assoc. meta files (indeces, etc.) */\n _renderMetaFileDownloadButton : function(){\n var urls = this.model.urls;\n return $([\n '
                        ',\n '',\n '',\n '',\n '',\n '
                        '\n ].join( '\\n' ));\n },\n\n _renderNametags : function(){\n var tpl = _.template([\n '<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>'].join(''));\n return tpl({tags: this.model.get('tags')});\n },\n\n // ......................................................................... misc\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .display-btn' : function( ev ){ this.trigger( 'display', this, ev ); },\n 'click .params-btn' : function( ev ){ this.trigger( 'params', this, ev ); },\n 'click .download-btn' : function( ev ){ this.trigger( 'download', this, ev ); }\n }),\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetListItemView.prototype.templates = (function(){\n//TODO: move to require text! plugin\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n failed_metadata : BASE_MVC.wrapTemplate([\n // failed metadata is rendered as a warning on an otherwise ok dataset view\n '<% if( model.state === \"failed_metadata\" ){ %>',\n '
                        ',\n _l( 'An error occurred setting the metadata for this dataset' ),\n '
                        ',\n '<% } %>'\n ]),\n error : BASE_MVC.wrapTemplate([\n // error during index fetch - show error on dataset\n '<% if( model.error ){ %>',\n '
                        ',\n _l( 'There was an error getting the data for this dataset' ), ': <%- model.error %>',\n '
                        ',\n '<% } %>'\n ]),\n purged : BASE_MVC.wrapTemplate([\n '<% if( model.purged ){ %>',\n '
                        ',\n _l( 'This dataset has been deleted and removed from disk' ),\n '
                        ',\n '<% } %>'\n ]),\n deleted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.deleted && !model.purged ){ %>',\n '
                        ',\n _l( 'This dataset has been deleted' ),\n '
                        ',\n '<% } %>'\n ])\n\n //NOTE: hidden warning is only needed for HDAs\n });\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '
                        ',\n\n '
                        ',\n '
                        ',\n '
                        ',\n '
                        ',\n\n // do not display tags, annotation, display apps, or peek when deleted\n '<% if( !dataset.deleted && !dataset.purged ){ %>',\n '
                        ',\n '
                        ',\n\n '
                        ',\n\n '<% if( dataset.peek ){ %>',\n '
                        <%= dataset.peek %>
                        ',\n '<% } %>',\n '<% } %>',\n '
                        '\n ], 'dataset' );\n\n var noAccessTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n '
                        ',\n _l( 'You do not have permission to view this dataset' ),\n '
                        ',\n '
                        '\n ], 'dataset' );\n\n//TODO: still toooooooooooooo complex - rework\n var summaryTemplates = {};\n summaryTemplates[ STATES.OK ] = summaryTemplates[ STATES.FAILED_METADATA ] = BASE_MVC.wrapTemplate([\n '<% if( dataset.misc_blurb ){ %>',\n '
                        ',\n '<%- dataset.misc_blurb %>',\n '
                        ',\n '<% } %>',\n\n '<% if( dataset.file_ext ){ %>',\n '
                        ',\n '',\n '<%- dataset.file_ext %>',\n '
                        ',\n '<% } %>',\n\n '<% if( dataset.metadata_dbkey ){ %>',\n '
                        ',\n '',\n '',\n '<%- dataset.metadata_dbkey %>',\n '',\n '
                        ',\n '<% } %>',\n\n '<% if( dataset.misc_info ){ %>',\n '
                        ',\n '<%- dataset.misc_info %>',\n '
                        ',\n '<% } %>'\n ], 'dataset' );\n summaryTemplates[ STATES.NEW ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'This is a new dataset and not all of its data are available yet' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.NOT_VIEWABLE ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'You do not have permission to view this dataset' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.DISCARDED ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'The job creating this dataset was cancelled before completion' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.QUEUED ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'This job is waiting to run' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.RUNNING ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'This job is currently running' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.UPLOAD ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'This dataset is currently uploading' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.SETTING_METADATA ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'Metadata is being auto-detected' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.PAUSED ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'This job is paused. Use the \"Resume Paused Jobs\" in the history menu to resume' ), '
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.ERROR ] = BASE_MVC.wrapTemplate([\n '<% if( !dataset.purged ){ %>',\n '
                        <%- dataset.misc_blurb %>
                        ',\n '<% } %>',\n '', _l( 'An error occurred with this dataset' ), ':',\n '
                        <%- dataset.misc_info %>
                        '\n ], 'dataset' );\n summaryTemplates[ STATES.EMPTY ] = BASE_MVC.wrapTemplate([\n '
                        ', _l( 'No data' ), ': <%- dataset.misc_blurb %>
                        '\n ], 'dataset' );\n summaryTemplates.unknown = BASE_MVC.wrapTemplate([\n '
                        Error: unknown dataset state: \"<%- dataset.state %>\"
                        '\n ], 'dataset' );\n\n // messages to be displayed only within the details section ('below the fold')\n var detailMessageTemplates = {\n resubmitted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.resubmitted ){ %>',\n '
                        ',\n _l( 'The job creating this dataset has been resubmitted' ),\n '
                        ',\n '<% } %>'\n ])\n };\n\n // this is applied to both old and new style display apps\n var displayApplicationsTemplate = BASE_MVC.wrapTemplate([\n '<% _.each( apps, function( app ){ %>',\n '
                        ',\n '<%- app.label %> ',\n '',\n '<% _.each( app.links, function( link ){ %>',\n '\" href=\"<%- link.href %>\">',\n '<% print( _l( link.text ) ); %>',\n ' ',\n '<% }); %>',\n '',\n '
                        ',\n '<% }); %>'\n ], 'apps' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n details : detailsTemplate,\n noAccess : noAccessTemplate,\n summaries : summaryTemplates,\n detailMessages : detailMessageTemplates,\n displayApplications : displayApplicationsTemplate\n });\n}());\n\n\n// ============================================================================\n return {\n DatasetListItemView : DatasetListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-li.js","/** Generic form view */\ndefine( [ 'mvc/form/form-view', 'mvc/ui/ui-misc' ], function( Form, Ui ) {\n\n var View = Backbone.View.extend({\n\n initialize: function( options ) {\n this.model = new Backbone.Model( options );\n this.url = this.model.get( 'url' );\n this.redirect = this.model.get( 'redirect' );\n this.setElement( '
                        ' );\n this.render();\n },\n\n render: function() {\n var self = this;\n $.ajax({\n url : Galaxy.root + this.url,\n type : 'GET'\n }).done( function( response ) {\n var options = $.extend( {}, self.model.attributes, response );\n var form = new Form({\n title : options.title,\n message: options.message,\n status : options.status || 'warning',\n icon : options.icon,\n inputs : options.inputs,\n buttons: {\n 'submit': new Ui.Button({\n tooltip : options.submit_tooltip,\n title : options.submit_title || 'Save settings',\n icon : options.submit_icon || 'fa-save',\n cls : 'btn btn-primary ui-clear-float',\n onclick : function() { self._submit( form ) }\n })\n }\n });\n self.$el.empty().append( form.$el );\n }).fail( function( response ) {\n self.$el.empty().append( new Ui.Message({\n message : 'Failed to load resource ' + self.url + '.',\n status : 'danger',\n persistent : true\n }).$el );\n });\n },\n\n _submit: function( form ) {\n var self = this;\n $.ajax( {\n url : Galaxy.root + self.url,\n data : JSON.stringify( form.data.create() ),\n type : 'PUT',\n contentType : 'application/json'\n }).done( function( response ) {\n var success_message = { message: response.message, status: 'success', persistent: false };\n if ( self.redirect ) {\n window.location = Galaxy.root + self.redirect + '?' + $.param( success_message );\n } else {\n form.data.matchModel( response, function ( input, input_id ) {\n form.field_list[ input_id ].value( input.value );\n });\n self._showMessage( form, success_message );\n }\n }).fail( function( response ) {\n self._showMessage( form, { message: response.responseJSON.err_msg, status: 'danger', persistent: false } );\n });\n },\n\n _showMessage: function( form, options ) {\n var $panel = form.$el.parents().filter(function() {\n return [ 'auto', 'scroll' ].indexOf( $( this ).css( 'overflow' ) ) != -1;\n }).first();\n $panel.animate( { scrollTop : 0 }, 500 );\n form.message.update( options );\n }\n });\n\n return {\n View : View\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/form/form-wrapper.js","define([\n \"mvc/collection/collection-model\",\n \"mvc/history/history-content-model\",\n \"utils/localization\"\n], function( DC_MODEL, HISTORY_CONTENT, _l ){\n\n'use strict';\n\n/*==============================================================================\n\nModels for DatasetCollections contained within a history.\n\nTODO:\n these might be compactable to one class if some duplication with\n collection-model is used.\n\n==============================================================================*/\nvar hcontentMixin = HISTORY_CONTENT.HistoryContentMixin,\n ListDC = DC_MODEL.ListDatasetCollection,\n PairDC = DC_MODEL.PairDatasetCollection,\n ListPairedDC = DC_MODEL.ListPairedDatasetCollection,\n ListOfListsDC = DC_MODEL.ListOfListsDatasetCollection;\n\n//==============================================================================\n/** Override to post to contents route w/o id. */\nfunction buildHDCASave( _super ){\n return function _save( attributes, options ){\n if( this.isNew() ){\n options = options || {};\n options.url = this.urlRoot + this.get( 'history_id' ) + '/contents';\n attributes = attributes || {};\n attributes.type = 'dataset_collection';\n }\n return _super.call( this, attributes, options );\n };\n}\n\n\n//==============================================================================\n/** @class Backbone model for List Dataset Collection within a History.\n */\nvar HistoryListDatasetCollection = ListDC.extend( hcontentMixin ).extend(\n/** @lends HistoryListDatasetCollection.prototype */{\n\n defaults : _.extend( _.clone( ListDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + ListDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for Pair Dataset Collection within a History.\n * @constructs\n */\nvar HistoryPairDatasetCollection = PairDC.extend( hcontentMixin ).extend(\n/** @lends HistoryPairDatasetCollection.prototype */{\n\n defaults : _.extend( _.clone( PairDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'paired',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( PairDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + PairDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for List of Pairs Dataset Collection within a History. */\nvar HistoryListPairedDatasetCollection = ListPairedDC.extend( hcontentMixin ).extend({\n\n defaults : _.extend( _.clone( ListPairedDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list:paired',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListPairedDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + ListPairedDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for List of Lists Dataset Collection within a History. */\nvar HistoryListOfListsDatasetCollection = ListOfListsDC.extend( hcontentMixin ).extend({\n\n defaults : _.extend( _.clone( ListOfListsDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list:list',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListOfListsDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return ([ 'HistoryListOfListsDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n HistoryListDatasetCollection : HistoryListDatasetCollection,\n HistoryPairDatasetCollection : HistoryPairDatasetCollection,\n HistoryListPairedDatasetCollection : HistoryListPairedDatasetCollection,\n HistoryListOfListsDatasetCollection : HistoryListOfListsDatasetCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-model.js","define([\n \"mvc/base/controlled-fetch-collection\",\n \"mvc/history/hda-model\",\n \"mvc/history/hdca-model\",\n \"mvc/history/history-preferences\",\n \"mvc/base-mvc\",\n \"utils/ajax-queue\"\n], function( CONTROLLED_FETCH_COLLECTION, HDA_MODEL, HDCA_MODEL, HISTORY_PREFS, BASE_MVC, AJAX_QUEUE ){\n'use strict';\n\n//==============================================================================\nvar _super = CONTROLLED_FETCH_COLLECTION.PaginatedCollection;\n/** @class Backbone collection for history content.\n * NOTE: history content seems like a dataset collection, but differs in that it is mixed:\n * each element can be either an HDA (dataset) or a DatasetCollection and co-exist on\n * the same level.\n * Dataset collections on the other hand are not mixed and (so far) can only contain either\n * HDAs or child dataset collections on one level.\n * This is why this does not inherit from any of the DatasetCollections (currently).\n */\nvar HistoryContents = _super.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : 'history',\n\n // ........................................................................ composite collection\n /** since history content is a mix, override model fn into a factory, creating based on history_content_type */\n model : function( attrs, options ) {\n if( attrs.history_content_type === \"dataset\" ) {\n return new HDA_MODEL.HistoryDatasetAssociation( attrs, options );\n\n } else if( attrs.history_content_type === \"dataset_collection\" ) {\n switch( attrs.collection_type ){\n case 'list':\n return new HDCA_MODEL.HistoryListDatasetCollection( attrs, options );\n case 'paired':\n return new HDCA_MODEL.HistoryPairDatasetCollection( attrs, options );\n case 'list:paired':\n return new HDCA_MODEL.HistoryListPairedDatasetCollection( attrs, options );\n case 'list:list':\n return new HDCA_MODEL.HistoryListOfListsDatasetCollection( attrs, options );\n }\n // This is a hack inside a hack:\n // Raise a plain object with validationError to fake a model.validationError\n // (since we don't have a model to use validate with)\n // (the outer hack being the mixed content/model function in this collection)\n var msg = 'Unknown collection_type: ' + attrs.collection_type;\n console.warn( msg, attrs );\n return { validationError : msg };\n }\n return { validationError : 'Unknown history_content_type: ' + attrs.history_content_type };\n },\n\n // ........................................................................ set up\n limitPerPage : 500,\n\n /** @type {Integer} how many contents per call to fetch when using progressivelyFetchDetails */\n limitPerProgressiveFetch : 500,\n\n /** @type {String} order used here and when fetching from server */\n order : 'hid',\n\n /** root api url */\n urlRoot : Galaxy.root + 'api/histories',\n\n /** complete api url */\n url : function(){\n return this.urlRoot + '/' + this.historyId + '/contents';\n },\n\n /** Set up */\n initialize : function( models, options ){\n options = options || {};\n _super.prototype.initialize.call( this, models, options );\n\n this.history = options.history || null;\n this.setHistoryId( options.historyId || null );\n /** @type {Boolean} does this collection contain and fetch deleted elements */\n this.includeDeleted = options.includeDeleted || this.includeDeleted;\n /** @type {Boolean} does this collection contain and fetch non-visible elements */\n this.includeHidden = options.includeHidden || this.includeHidden;\n\n // backbonejs uses collection.model.prototype.idAttribute to determine if a model is *already* in a collection\n // and either merged or replaced. In this case, our 'model' is a function so we need to add idAttribute\n // manually here - if we don't, contents will not merge but be replaced/swapped.\n this.model.prototype.idAttribute = 'type_id';\n },\n\n setHistoryId : function( newId ){\n this.historyId = newId;\n this._setUpWebStorage();\n },\n\n /** Set up client side storage. Currently PersistanStorage keyed under 'history:' */\n _setUpWebStorage : function( initialSettings ){\n // TODO: use initialSettings\n if( !this.historyId ){ return; }\n this.storage = new HISTORY_PREFS.HistoryPrefs({\n id: HISTORY_PREFS.HistoryPrefs.historyStorageKey( this.historyId )\n });\n this.trigger( 'new-storage', this.storage, this );\n\n this.on({\n 'include-deleted' : function( newVal ){\n this.storage.includeDeleted( newVal );\n },\n 'include-hidden' : function( newVal ){\n this.storage.includeHidden( newVal );\n }\n });\n\n this.includeDeleted = this.storage.includeDeleted() || false;\n this.includeHidden = this.storage.includeHidden() || false;\n return this;\n },\n\n // ........................................................................ common queries\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : _.extend( _.clone( _super.prototype.comparators ), {\n 'name' : BASE_MVC.buildComparator( 'name', { ascending: true }),\n 'name-dsc' : BASE_MVC.buildComparator( 'name', { ascending: false }),\n 'hid' : BASE_MVC.buildComparator( 'hid', { ascending: false }),\n 'hid-asc' : BASE_MVC.buildComparator( 'hid', { ascending: true }),\n }),\n\n /** Get every model in this collection not in a 'ready' state (running). */\n running : function(){\n return this.filter( function( c ){ return !c.inReadyState(); });\n },\n\n /** return contents that are not ready and not deleted/hidden */\n runningAndActive : function(){\n return this.filter( function( c ){\n return ( !c.inReadyState() )\n && ( c.get( 'visible' ) )\n // TODO: deletedOrPurged?\n && ( !c.get( 'deleted' ) );\n });\n },\n\n /** Get the model with the given hid\n * @param {Int} hid the hid to search for\n * @returns {HistoryDatasetAssociation} the model with the given hid or undefined if not found\n */\n getByHid : function( hid ){\n // note: there *can* be more than one content with a given hid, this finds the first based on order\n return this.findWhere({ hid: hid });\n },\n\n /** return true if all contents have details */\n haveDetails : function(){\n return this.all( function( c ){ return c.hasDetails(); });\n },\n\n // ........................................................................ hidden / deleted\n /** return a new contents collection of only hidden items */\n hidden : function(){\n return this.filter( function( c ){ return c.hidden(); });\n },\n\n /** return a new contents collection of only hidden items */\n deleted : function(){\n return this.filter( function( c ){ return c.get( 'deleted' ); });\n },\n\n /** return a new contents collection of only hidden items */\n visibleAndUndeleted : function(){\n return this.filter( function( c ){\n return ( c.get( 'visible' ) )\n // TODO: deletedOrPurged?\n && ( !c.get( 'deleted' ) );\n });\n },\n\n /** create a setter in order to publish the change */\n setIncludeDeleted : function( setting, options ){\n if( _.isBoolean( setting ) && setting !== this.includeDeleted ){\n this.includeDeleted = setting;\n if( _.result( options, 'silent' ) ){ return; }\n this.trigger( 'include-deleted', setting, this );\n }\n },\n\n /** create a setter in order to publish the change */\n setIncludeHidden : function( setting, options ){\n if( _.isBoolean( setting ) && setting !== this.includeHidden ){\n this.includeHidden = setting;\n options = options || {};\n if( _.result( options, 'silent' ) ){ return; }\n this.trigger( 'include-hidden', setting, this );\n }\n },\n\n // ........................................................................ ajax\n // ............ controlled fetch collection\n /** override to get expanded ids from sessionStorage and pass to API as details */\n fetch : function( options ){\n options = options || {};\n if( this.historyId && !options.details ){\n var prefs = HISTORY_PREFS.HistoryPrefs.get( this.historyId ).toJSON();\n if( !_.isEmpty( prefs.expandedIds ) ){\n options.details = _.values( prefs.expandedIds ).join( ',' );\n }\n }\n return _super.prototype.fetch.call( this, options );\n },\n\n // ............. ControlledFetch stuff\n /** override to include the API versioning flag */\n _buildFetchData : function( options ){\n return _.extend( _super.prototype._buildFetchData.call( this, options ), {\n v : 'dev'\n });\n },\n\n /** Extend to include details and version */\n _fetchParams : _super.prototype._fetchParams.concat([\n // TODO: remove (the need for) both\n /** version */\n 'v',\n /** dataset ids to get full details of */\n 'details',\n ]),\n\n /** override to add deleted/hidden filters */\n _buildFetchFilters : function( options ){\n var superFilters = _super.prototype._buildFetchFilters.call( this, options ) || {};\n var filters = {};\n if( !this.includeDeleted ){\n filters.deleted = false;\n filters.purged = false;\n }\n if( !this.includeHidden ){\n filters.visible = true;\n }\n return _.defaults( superFilters, filters );\n },\n\n // ............ paginated collection\n getTotalItemCount : function(){\n return this.history.contentsShown();\n },\n\n // ............ history contents specific ajax\n /** override to filter requested contents to those updated after the Date 'since' */\n fetchUpdated : function( since, options ){\n if( since ){\n options = options || { filters: {} };\n options.remove = false;\n options.filters = {\n 'update_time-ge' : since.toISOString(),\n // workflows will produce hidden datasets (non-output datasets) that still\n // need to be updated in the collection or they'll update forever\n // we can remove the default visible filter by using an 'empty' value\n visible : ''\n };\n }\n return this.fetch( options );\n },\n\n /** fetch all the deleted==true contents of this collection */\n fetchDeleted : function( options ){\n options = options || {};\n var self = this;\n options.filters = _.extend( options.filters, {\n // all deleted, purged or not\n deleted : true,\n purged : undefined\n });\n options.remove = false;\n\n self.trigger( 'fetching-deleted', self );\n return self.fetch( options )\n .always( function(){ self.trigger( 'fetching-deleted-done', self ); });\n },\n\n /** fetch all the visible==false contents of this collection */\n fetchHidden : function( options ){\n options = options || {};\n var self = this;\n options.filters = _.extend( options.filters, {\n visible : false\n });\n options.remove = false;\n\n self.trigger( 'fetching-hidden', self );\n return self.fetch( options )\n .always( function(){ self.trigger( 'fetching-hidden-done', self ); });\n },\n\n /** fetch detailed model data for all contents in this collection */\n fetchAllDetails : function( options ){\n options = options || {};\n var detailsFlag = { details: 'all' };\n options.data = _.extend( options.data || {}, detailsFlag );\n return this.fetch( options );\n },\n\n /** specialty fetch method for retrieving the element_counts of all hdcas in the history */\n fetchCollectionCounts : function( options ){\n options = options || {};\n options.keys = [ 'type_id', 'element_count' ].join( ',' );\n options.filters = _.extend( options.filters || {}, {\n history_content_type: 'dataset_collection',\n });\n options.remove = false;\n return this.fetch( options );\n },\n\n // ............. quasi-batch ops\n // TODO: to batch\n /** helper that fetches using filterParams then calls save on each fetched using updateWhat as the save params */\n _filterAndUpdate : function( filterParams, updateWhat ){\n var self = this;\n var idAttribute = self.model.prototype.idAttribute;\n var updateArgs = [ updateWhat ];\n\n return self.fetch({ filters: filterParams, remove: false })\n .then( function( fetched ){\n // convert filtered json array to model array\n fetched = fetched.reduce( function( modelArray, currJson, i ){\n var model = self.get( currJson[ idAttribute ] );\n return model? modelArray.concat( model ) : modelArray;\n }, []);\n return self.ajaxQueue( 'save', updateArgs, fetched );\n });\n },\n\n /** using a queue, perform ajaxFn on each of the models in this collection */\n ajaxQueue : function( ajaxFn, args, collection ){\n collection = collection || this.models;\n return new AJAX_QUEUE.AjaxQueue( collection.slice().reverse().map( function( content, i ){\n var fn = _.isString( ajaxFn )? content[ ajaxFn ] : ajaxFn;\n return function(){ return fn.apply( content, args ); };\n })).deferred;\n },\n\n /** fetch contents' details in batches of limitPerCall - note: only get searchable details here */\n progressivelyFetchDetails : function( options ){\n options = options || {};\n var deferred = jQuery.Deferred();\n var self = this;\n var limit = options.limitPerCall || self.limitPerProgressiveFetch;\n // TODO: only fetch tags and annotations if specifically requested\n var searchAttributes = HDA_MODEL.HistoryDatasetAssociation.prototype.searchAttributes;\n var detailKeys = searchAttributes.join( ',' );\n\n function _recursivelyFetch( offset ){\n offset = offset || 0;\n var _options = _.extend( _.clone( options ), {\n view : 'summary',\n keys : detailKeys,\n limit : limit,\n offset : offset,\n reset : offset === 0,\n remove : false\n });\n\n _.defer( function(){\n self.fetch.call( self, _options )\n .fail( deferred.reject )\n .done( function( response ){\n deferred.notify( response, limit, offset );\n if( response.length !== limit ){\n self.allFetched = true;\n deferred.resolve( response, limit, offset );\n\n } else {\n _recursivelyFetch( offset + limit );\n }\n });\n });\n }\n _recursivelyFetch();\n return deferred;\n },\n\n /** does some bit of JSON represent something that can be copied into this contents collection */\n isCopyable : function( contentsJSON ){\n var copyableModelClasses = [\n 'HistoryDatasetAssociation',\n 'HistoryDatasetCollectionAssociation'\n ];\n return ( ( _.isObject( contentsJSON ) && contentsJSON.id )\n && ( _.contains( copyableModelClasses, contentsJSON.model_class ) ) );\n },\n\n /** copy an existing, accessible hda into this collection */\n copy : function( json ){\n // TODO: somehow showhorn all this into 'save'\n var id, type, contentType;\n if( _.isString( json ) ){\n id = json;\n contentType = 'hda';\n type = 'dataset';\n } else {\n id = json.id;\n contentType = ({\n 'HistoryDatasetAssociation' : 'hda',\n 'LibraryDatasetDatasetAssociation' : 'ldda',\n 'HistoryDatasetCollectionAssociation' : 'hdca'\n })[ json.model_class ] || 'hda';\n type = ( contentType === 'hdca'? 'dataset_collection' : 'dataset' );\n }\n var collection = this,\n xhr = jQuery.ajax( this.url(), {\n method: 'POST',\n contentType: 'application/json',\n data: JSON.stringify({\n content : id,\n source : contentType,\n type : type\n })\n })\n .done( function( response ){\n collection.add([ response ], { parse: true });\n })\n .fail( function( error, status, message ){\n collection.trigger( 'error', collection, xhr, {},\n 'Error copying contents', { type: type, id: id, source: contentType });\n });\n return xhr;\n },\n\n /** create a new HDCA in this collection */\n createHDCA : function( elementIdentifiers, collectionType, name, hideSourceItems, options ){\n // normally collection.create returns the new model, but we need the promise from the ajax, so we fake create\n //precondition: elementIdentifiers is an array of plain js objects\n // in the proper form to create the collectionType\n var hdca = this.model({\n history_content_type: 'dataset_collection',\n collection_type : collectionType,\n history_id : this.historyId,\n name : name,\n hide_source_items : hideSourceItems || false,\n // should probably be able to just send in a bunch of json here and restruct per class\n // note: element_identifiers is now (incorrectly) an attribute\n element_identifiers : elementIdentifiers\n // do not create the model on the client until the ajax returns\n });\n return hdca.save( options );\n },\n\n // ........................................................................ searching\n /** return true if all contents have the searchable attributes */\n haveSearchDetails : function(){\n return this.allFetched && this.all( function( content ){\n // null (which is a valid returned annotation value)\n // will return false when using content.has( 'annotation' )\n //TODO: a bit hacky - formalize\n return _.has( content.attributes, 'annotation' );\n });\n },\n\n /** return a new collection of contents whose attributes contain the substring matchesWhat */\n matches : function( matchesWhat ){\n return this.filter( function( content ){\n return content.matches( matchesWhat );\n });\n },\n\n // ........................................................................ misc\n /** In this override, copy the historyId to the clone */\n clone : function(){\n var clone = Backbone.Collection.prototype.clone.call( this );\n clone.historyId = this.historyId;\n return clone;\n },\n\n /** String representation. */\n toString : function(){\n return ([ 'HistoryContents(', [ this.historyId, this.length ].join(), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n HistoryContents : HistoryContents\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-contents.js","\ndefine([\n \"mvc/history/history-contents\",\n \"mvc/history/history-preferences\",\n \"mvc/base/controlled-fetch-collection\",\n \"utils/utils\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( HISTORY_CONTENTS, HISTORY_PREFS, CONTROLLED_FETCH_COLLECTION, UTILS, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/** @class Model for a Galaxy history resource - both a record of user\n * tool use and a collection of the datasets those tools produced.\n * @name History\n * @augments Backbone.Model\n */\nvar History = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.mixin( BASE_MVC.SearchableModelMixin, /** @lends History.prototype */{\n _logNamespace : 'history',\n\n /** ms between fetches when checking running jobs/datasets for updates */\n UPDATE_DELAY : 4000,\n\n // values from api (may need more)\n defaults : {\n model_class : 'History',\n id : null,\n name : 'Unnamed History',\n state : 'new',\n\n deleted : false,\n contents_active : {},\n contents_states : {},\n },\n\n urlRoot: Galaxy.root + 'api/histories',\n\n contentsClass : HISTORY_CONTENTS.HistoryContents,\n\n /** What model fields to search with */\n searchAttributes : [\n 'name', 'annotation', 'tags'\n ],\n\n /** Adding title and singular tag */\n searchAliases : {\n title : 'name',\n tag : 'tags'\n },\n\n // ........................................................................ set up/tear down\n /** Set up the model\n * @param {Object} historyJSON model data for this History\n * @param {Object} options any extra settings including logger\n */\n initialize : function( historyJSON, options ){\n options = options || {};\n this.logger = options.logger || null;\n this.log( this + \".initialize:\", historyJSON, options );\n\n /** HistoryContents collection of the HDAs contained in this history. */\n this.contents = new this.contentsClass( [], {\n history : this,\n historyId : this.get( 'id' ),\n order : options.order,\n });\n\n this._setUpListeners();\n this._setUpCollectionListeners();\n\n /** cached timeout id for the dataset updater */\n this.updateTimeoutId = null;\n },\n\n /** set up any event listeners for this history including those to the contained HDAs\n * events: error:contents if an error occurred with the contents collection\n */\n _setUpListeners : function(){\n // if the model's id changes ('current' or null -> an actual id), update the contents history_id\n return this.on({\n 'error' : function( model, xhr, options, msg, details ){\n this.clearUpdateTimeout();\n },\n 'change:id' : function( model, newId ){\n if( this.contents ){\n this.contents.historyId = newId;\n }\n },\n });\n },\n\n /** event handlers for the contents submodels */\n _setUpCollectionListeners : function(){\n if( !this.contents ){ return this; }\n // bubble up errors\n return this.listenTo( this.contents, {\n 'error' : function(){\n this.trigger.apply( this, jQuery.makeArray( arguments ) );\n },\n });\n },\n\n // ........................................................................ derived attributes\n /** */\n contentsShown : function(){\n var contentsActive = this.get( 'contents_active' );\n var shown = contentsActive.active || 0;\n shown += this.contents.includeDeleted? contentsActive.deleted : 0;\n shown += this.contents.includeHidden? contentsActive.hidden : 0;\n return shown;\n },\n\n /** convert size in bytes to a more human readable version */\n nice_size : function(){\n var size = this.get( 'size' );\n return size? UTILS.bytesToString( size, true, 2 ) : _l( '(empty)' );\n },\n\n /** override to add nice_size */\n toJSON : function(){\n return _.extend( Backbone.Model.prototype.toJSON.call( this ), {\n nice_size : this.nice_size()\n });\n },\n\n /** override to allow getting nice_size */\n get : function( key ){\n if( key === 'nice_size' ){\n return this.nice_size();\n }\n return Backbone.Model.prototype.get.apply( this, arguments );\n },\n\n // ........................................................................ common queries\n /** T/F is this history owned by the current user (Galaxy.user)\n * Note: that this will return false for an anon user even if the history is theirs.\n */\n ownedByCurrUser : function(){\n // no currUser\n if( !Galaxy || !Galaxy.user ){\n return false;\n }\n // user is anon or history isn't owned\n if( Galaxy.user.isAnonymous() || Galaxy.user.id !== this.get( 'user_id' ) ){\n return false;\n }\n return true;\n },\n\n /** Return the number of running jobs assoc with this history (note: unknown === 0) */\n numOfUnfinishedJobs : function(){\n var unfinishedJobIds = this.get( 'non_ready_jobs' );\n return unfinishedJobIds? unfinishedJobIds.length : 0;\n },\n\n /** Return the number of running hda/hdcas in this history (note: unknown === 0) */\n numOfUnfinishedShownContents : function(){\n return this.contents.runningAndActive().length || 0;\n },\n\n // ........................................................................ updates\n _fetchContentRelatedAttributes : function(){\n var contentRelatedAttrs = [ 'size', 'non_ready_jobs', 'contents_active', 'hid_counter' ];\n return this.fetch({ data : $.param({ keys : contentRelatedAttrs.join( ',' ) }) });\n },\n\n /** check for any changes since the last time we updated (or fetch all if ) */\n refresh : function( options ){\n // console.log( this + '.refresh' );\n options = options || {};\n var self = this;\n\n // note if there was no previous update time, all summary contents will be fetched\n var lastUpdateTime = self.lastUpdateTime;\n // if we don't flip this, then a fully-fetched list will not be re-checked via fetch\n this.contents.allFetched = false;\n var fetchFn = self.contents.currentPage !== 0\n ? function(){ return self.contents.fetchPage( self.contents.currentPage ); }\n : function(){ return self.contents.fetchUpdated( lastUpdateTime ); };\n // note: if there was no previous update time, all summary contents will be fetched\n return fetchFn()\n .done( function( response, status, xhr ){\n var serverResponseDatetime;\n try {\n serverResponseDatetime = new Date( xhr.getResponseHeader( 'Date' ) );\n } catch( err ){}\n self.lastUpdateTime = serverResponseDatetime || new Date();\n self.checkForUpdates( options );\n });\n },\n\n /** continuously fetch updated contents every UPDATE_DELAY ms if this history's datasets or jobs are unfinished */\n checkForUpdates : function( options ){\n // console.log( this + '.checkForUpdates' );\n options = options || {};\n var delay = this.UPDATE_DELAY;\n var self = this;\n if( !self.id ){ return; }\n\n function _delayThenUpdate(){\n // prevent buildup of updater timeouts by clearing previous if any, then set new and cache id\n self.clearUpdateTimeout();\n self.updateTimeoutId = setTimeout( function(){\n self.refresh( options );\n }, delay );\n }\n\n // if there are still datasets in the non-ready state, recurse into this function with the new time\n var nonReadyContentCount = this.numOfUnfinishedShownContents();\n // console.log( 'nonReadyContentCount:', nonReadyContentCount );\n if( nonReadyContentCount > 0 ){\n _delayThenUpdate();\n\n } else {\n // no datasets are running, but currently runnning jobs may still produce new datasets\n // see if the history has any running jobs and continue to update if so\n // (also update the size for the user in either case)\n self._fetchContentRelatedAttributes()\n .done( function( historyData ){\n // console.log( 'non_ready_jobs:', historyData.non_ready_jobs );\n if( self.numOfUnfinishedJobs() > 0 ){\n _delayThenUpdate();\n\n } else {\n // otherwise, let listeners know that all updates have stopped\n self.trigger( 'ready' );\n }\n });\n }\n },\n\n /** clear the timeout and the cached timeout id */\n clearUpdateTimeout : function(){\n if( this.updateTimeoutId ){\n clearTimeout( this.updateTimeoutId );\n this.updateTimeoutId = null;\n }\n },\n\n // ........................................................................ ajax\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** fetch this histories data (using options) then it's contents (using contentsOptions) */\n fetchWithContents : function( options, contentsOptions ){\n options = options || {};\n var self = this;\n\n // console.log( this + '.fetchWithContents' );\n // TODO: push down to a base class\n options.view = 'dev-detailed';\n\n // fetch history then use history data to fetch (paginated) contents\n return this.fetch( options ).then( function getContents( history ){\n self.contents.history = self;\n self.contents.setHistoryId( history.id );\n return self.fetchContents( contentsOptions );\n });\n },\n\n /** fetch this histories contents, adjusting options based on the stored history preferences */\n fetchContents : function( options ){\n options = options || {};\n var self = this;\n\n // we're updating, reset the update time\n self.lastUpdateTime = new Date();\n return self.contents.fetchCurrentPage( options );\n },\n\n /** save this history, _Mark_ing it as deleted (just a flag) */\n _delete : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** purge this history, _Mark_ing it as purged and removing all dataset data from the server */\n purge : function( options ){\n if( this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: true, purged: true }, options );\n },\n /** save this history, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** Make a copy of this history on the server\n * @param {Boolean} current if true, set the copy as the new current history (default: true)\n * @param {String} name name of new history (default: none - server sets to: Copy of )\n * @fires copied passed this history and the response JSON from the copy\n * @returns {xhr}\n */\n copy : function( current, name, allDatasets ){\n current = ( current !== undefined )?( current ):( true );\n if( !this.id ){\n throw new Error( 'You must set the history ID before copying it.' );\n }\n\n var postData = { history_id : this.id };\n if( current ){\n postData.current = true;\n }\n if( name ){\n postData.name = name;\n }\n if( !allDatasets ){\n postData.all_datasets = false;\n }\n postData.view = 'dev-detailed';\n\n var history = this;\n var copy = jQuery.post( this.urlRoot, postData );\n // if current - queue to setAsCurrent before firing 'copied'\n if( current ){\n return copy.then( function( response ){\n var newHistory = new History( response );\n return newHistory.setAsCurrent()\n .done( function(){\n history.trigger( 'copied', history, response );\n });\n });\n }\n return copy.done( function( response ){\n history.trigger( 'copied', history, response );\n });\n },\n\n setAsCurrent : function(){\n var history = this,\n xhr = jQuery.getJSON( Galaxy.root + 'history/set_as_current?id=' + this.id );\n\n xhr.done( function(){\n history.trigger( 'set-as-current', history );\n });\n return xhr;\n },\n\n // ........................................................................ misc\n toString : function(){\n return 'History(' + this.get( 'id' ) + ',' + this.get( 'name' ) + ')';\n }\n}));\n\n\n//==============================================================================\nvar _collectionSuper = CONTROLLED_FETCH_COLLECTION.InfinitelyScrollingCollection;\n/** @class A collection of histories (per user)\n * that maintains the current history as the first in the collection.\n * New or copied histories become the current history.\n */\nvar HistoryCollection = _collectionSuper.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : 'history',\n\n model : History,\n /** @type {String} initial order used by collection */\n order : 'update_time',\n /** @type {Number} limit used for the first fetch (or a reset) */\n limitOnFirstFetch : 10,\n /** @type {Number} limit used for each subsequent fetch */\n limitPerFetch : 10,\n\n initialize : function( models, options ){\n options = options || {};\n this.log( 'HistoryCollection.initialize', models, options );\n _collectionSuper.prototype.initialize.call( this, models, options );\n\n /** @type {boolean} should deleted histories be included */\n this.includeDeleted = options.includeDeleted || false;\n\n /** @type {String} encoded id of the history that's current */\n this.currentHistoryId = options.currentHistoryId;\n\n this.setUpListeners();\n // note: models are sent to reset *after* this fn ends; up to this point\n // the collection *is empty*\n },\n\n urlRoot : Galaxy.root + 'api/histories',\n url : function(){ return this.urlRoot; },\n\n /** set up reflexive event handlers */\n setUpListeners : function setUpListeners(){\n return this.on({\n // when a history is deleted, remove it from the collection (if optionally set to do so)\n 'change:deleted' : function( history ){\n // TODO: this becomes complicated when more filters are used\n this.debug( 'change:deleted', this.includeDeleted, history.get( 'deleted' ) );\n if( !this.includeDeleted && history.get( 'deleted' ) ){\n this.remove( history );\n }\n },\n // listen for a history copy, setting it to current\n 'copied' : function( original, newData ){\n this.setCurrent( new History( newData, [] ) );\n },\n // when a history is made current, track the id in the collection\n 'set-as-current' : function( history ){\n var oldCurrentId = this.currentHistoryId;\n this.trigger( 'no-longer-current', oldCurrentId );\n this.currentHistoryId = history.id;\n }\n });\n },\n\n /** override to change view */\n _buildFetchData : function( options ){\n return _.extend( _collectionSuper.prototype._buildFetchData.call( this, options ), {\n view : 'dev-detailed'\n });\n },\n\n /** override to filter out deleted and purged */\n _buildFetchFilters : function( options ){\n var superFilters = _collectionSuper.prototype._buildFetchFilters.call( this, options ) || {};\n var filters = {};\n if( !this.includeDeleted ){\n filters.deleted = false;\n filters.purged = false;\n } else {\n // force API to return both deleted and non\n //TODO: when the API is updated, remove this\n filters.deleted = null;\n }\n return _.defaults( superFilters, filters );\n },\n\n /** override to fetch current as well (as it may be outside the first 10, etc.) */\n fetchFirst : function( options ){\n var self = this;\n // TODO: batch?\n var xhr = $.when();\n if( this.currentHistoryId ){\n xhr = _collectionSuper.prototype.fetchFirst.call( self, {\n silent: true,\n limit : 1,\n filters: {\n // without these a deleted current history will return [] here and block the other xhr\n 'purged' : '',\n 'deleted' : '',\n 'encoded_id-in' : this.currentHistoryId,\n }\n });\n }\n return xhr.then( function(){\n options = options || {};\n options.offset = 0;\n return self.fetchMore( options );\n });\n },\n\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : _.extend( _.clone( _collectionSuper.prototype.comparators ), {\n 'name' : BASE_MVC.buildComparator( 'name', { ascending: true }),\n 'name-dsc' : BASE_MVC.buildComparator( 'name', { ascending: false }),\n 'size' : BASE_MVC.buildComparator( 'size', { ascending: false }),\n 'size-asc' : BASE_MVC.buildComparator( 'size', { ascending: true }),\n }),\n\n /** override to always have the current history first */\n sort : function( options ){\n options = options || {};\n var silent = options.silent;\n var currentHistory = this.remove( this.get( this.currentHistoryId ) );\n _collectionSuper.prototype.sort.call( this, _.defaults({ silent: true }, options ) );\n this.unshift( currentHistory, { silent: true });\n if( !silent ){\n this.trigger( 'sort', this, options );\n }\n return this;\n },\n\n /** create a new history and by default set it to be the current history */\n create : function create( data, hdas, historyOptions, xhrOptions ){\n //TODO: .create is actually a collection function that's overridden here\n var collection = this,\n xhr = jQuery.getJSON( Galaxy.root + 'history/create_new_current' );\n return xhr.done( function( newData ){\n collection.setCurrent( new History( newData, [], historyOptions || {} ) );\n });\n },\n\n /** set the current history to the given history, placing it first in the collection.\n * Pass standard bbone options for use in unshift.\n * @triggers new-current passed history and this collection\n */\n setCurrent : function( history, options ){\n options = options || {};\n // new histories go in the front\n this.unshift( history, options );\n this.currentHistoryId = history.get( 'id' );\n if( !options.silent ){\n this.trigger( 'new-current', history, this );\n }\n return this;\n },\n\n toString: function toString(){\n return 'HistoryCollection(' + this.length + ',current:' + this.currentHistoryId + ')';\n }\n});\n\n\n//==============================================================================\nreturn {\n History : History,\n HistoryCollection : HistoryCollection\n};});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-model.js","define([\n \"mvc/base-mvc\"\n], function( BASE_MVC ){\n\n'use strict';\n\nvar logNamespace = 'history';\n\n// ============================================================================\n/** session storage for individual history preferences */\nvar HistoryPrefs = BASE_MVC.SessionStorageModel.extend(\n/** @lends HistoryPrefs.prototype */{\n //TODO:?? move to user prefs?\n defaults : {\n //TODO:?? expandedIds to array?\n expandedIds : {},\n show_deleted : false,\n show_hidden : false\n },\n\n /** add an hda id to the hash of expanded hdas */\n addExpanded : function( model ){\n//TODO: use type_id and not model\n var current = this.get( 'expandedIds' );\n current[ model.id ] = model.get( 'id' );\n this.save( 'expandedIds', current );\n },\n\n /** remove an hda id from the hash of expanded hdas */\n removeExpanded : function( model ){\n var current = this.get( 'expandedIds' );\n delete current[ model.id ];\n this.save( 'expandedIds', current );\n },\n\n isExpanded : function( contentId ){\n return _.result( this.get( 'expandedIds' ), contentId, false );\n },\n\n allExpanded : function(){\n return _.values( this.get( 'expandedIds' ) );\n },\n\n clearExpanded : function(){\n this.set( 'expandedIds', {} );\n },\n\n includeDeleted : function( val ){\n // moving the invocation here so other components don't need to know the key\n // TODO: change this key later\n if( !_.isUndefined( val ) ){ this.set( 'show_deleted', val ); }\n return this.get( 'show_deleted' );\n },\n\n includeHidden : function( val ){\n // TODO: change this key later\n if( !_.isUndefined( val ) ){ this.set( 'show_hidden', val ); }\n return this.get( 'show_hidden' );\n },\n\n toString : function(){\n return 'HistoryPrefs(' + this.id + ')';\n }\n\n}, {\n // ........................................................................ class vars\n // class lvl for access w/o instantiation\n storageKeyPrefix : 'history:',\n\n /** key string to store each histories settings under */\n historyStorageKey : function historyStorageKey( historyId ){\n if( !historyId ){\n throw new Error( 'HistoryPrefs.historyStorageKey needs valid id: ' + historyId );\n }\n // single point of change\n return ( HistoryPrefs.storageKeyPrefix + historyId );\n },\n\n /** return the existing storage for the history with the given id (or create one if it doesn't exist) */\n get : function get( historyId ){\n return new HistoryPrefs({ id: HistoryPrefs.historyStorageKey( historyId ) });\n },\n\n /** clear all history related items in sessionStorage */\n clearAll : function clearAll( historyId ){\n for( var key in sessionStorage ){\n if( key.indexOf( HistoryPrefs.storageKeyPrefix ) === 0 ){\n sessionStorage.removeItem( key );\n }\n }\n }\n});\n\n//==============================================================================\n return {\n HistoryPrefs: HistoryPrefs\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-preferences.js","define([\n 'mvc/base-mvc',\n 'utils/localization'\n], function( BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'list';\n//==============================================================================\n/** A view which, when first rendered, shows only summary data/attributes, but\n * can be expanded to show further details (and optionally fetch those\n * details from the server).\n */\nvar ExpandableView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n //TODO: Although the reasoning behind them is different, this shares a lot with HiddenUntilActivated above: combine them\n //PRECONDITION: model must have method hasDetails\n //PRECONDITION: subclasses must have templates.el and templates.details\n\n initialize : function( attributes ){\n /** are the details of this view expanded/shown or not? */\n this.expanded = attributes.expanded || false;\n this.log( '\\t expanded:', this.expanded );\n this.fxSpeed = attributes.fxSpeed !== undefined? attributes.fxSpeed : this.fxSpeed;\n },\n\n // ........................................................................ render main\n /** jq fx speed */\n fxSpeed : 'fast',\n\n /** Render this content, set up ui.\n * @param {Number or String} speed the speed of the render\n */\n render : function( speed ){\n var $newRender = this._buildNewRender();\n this._setUpBehaviors( $newRender );\n this._queueNewRender( $newRender, speed );\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el.\n * If the view is already expanded, build the details as well.\n */\n _buildNewRender : function(){\n // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n var $newRender = $( this.templates.el( this.model.toJSON(), this ) );\n if( this.expanded ){\n this.$details( $newRender ).replaceWith( this._renderDetails().show() );\n }\n return $newRender;\n },\n\n /** Fade out the old el, swap in the new contents, then fade in.\n * @param {Number or String} speed jq speed to use for rendering effects\n * @fires rendered when rendered\n */\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var view = this;\n\n if( speed === 0 ){\n view._swapNewRender( $newRender );\n view.trigger( 'rendered', view );\n\n } else {\n $( view ).queue( 'fx', [\n function( next ){\n view.$el.fadeOut( speed, next );\n },\n function( next ){\n view._swapNewRender( $newRender );\n next();\n },\n function( next ){\n view.$el.fadeIn( speed, next );\n },\n function( next ){\n view.trigger( 'rendered', view );\n next();\n }\n ]);\n }\n },\n\n /** empty out the current el, move the $newRender's children in */\n _swapNewRender : function( $newRender ){\n return this.$el.empty()\n .attr( 'class', _.isFunction( this.className )? this.className(): this.className )\n .append( $newRender.children() );\n },\n\n /** set up js behaviors, event handlers for elements within the given container\n * @param {jQuery} $container jq object that contains the elements to process (defaults to this.$el)\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n // set up canned behavior on children (bootstrap, popupmenus, editable_text, etc.)\n //make_popup_menus( $where );\n $where.find( '[title]' ).tooltip({ placement : 'bottom' });\n },\n\n // ......................................................................... details\n /** shortcut to details DOM (as jQ) */\n $details : function( $where ){\n $where = $where || this.$el;\n return $where.find( '> .details' );\n },\n\n /** build the DOM for the details and set up behaviors on it */\n _renderDetails : function(){\n var $newDetails = $( this.templates.details( this.model.toJSON(), this ) );\n this._setUpBehaviors( $newDetails );\n return $newDetails;\n },\n\n // ......................................................................... expansion/details\n /** Show or hide the details\n * @param {Boolean} expand if true, expand; if false, collapse\n */\n toggleExpanded : function( expand ){\n expand = ( expand === undefined )?( !this.expanded ):( expand );\n if( expand ){\n this.expand();\n } else {\n this.collapse();\n }\n return this;\n },\n\n /** Render and show the full, detailed body of this view including extra data and controls.\n * note: if the model does not have detailed data, fetch that data before showing the body\n * @fires expanded when a body has been expanded\n */\n expand : function(){\n var view = this;\n return view._fetchModelDetails().always( function(){\n view._expand();\n });\n },\n\n /** Check for model details and, if none, fetch them.\n * @returns {jQuery.promise} the model.fetch.xhr if details are being fetched, an empty promise if not\n */\n _fetchModelDetails : function(){\n if( !this.model.hasDetails() ){\n return this.model.fetch();\n }\n return jQuery.when();\n },\n\n /** Inner fn called when expand (public) has fetched the details */\n _expand : function(){\n var view = this,\n $newDetails = view._renderDetails();\n view.$details().replaceWith( $newDetails );\n // needs to be set after the above or the slide will not show\n view.expanded = true;\n view.$details().slideDown( view.fxSpeed, function(){\n view.trigger( 'expanded', view );\n });\n },\n\n /** Hide the body/details of an HDA.\n * @fires collapsed when a body has been collapsed\n */\n collapse : function(){\n this.debug( this + '(ExpandableView).collapse' );\n var view = this;\n view.expanded = false;\n this.$details().slideUp( view.fxSpeed, function(){\n view.trigger( 'collapsed', view );\n });\n }\n\n});\n\n\n//==============================================================================\n/** A view that is displayed in some larger list/grid/collection.\n * Inherits from Expandable, Selectable, Draggable.\n * The DOM contains warnings, a title bar, and a series of primary action controls.\n * Primary actions are meant to be easily accessible item functions (such as delete)\n * that are rendered in the title bar.\n *\n * Details are rendered when the user clicks the title bar or presses enter/space when\n * the title bar is in focus.\n *\n * Designed as a base class for history panel contents - but usable elsewhere (I hope).\n */\nvar ListItemView = ExpandableView.extend(\n BASE_MVC.mixin( BASE_MVC.SelectableViewMixin, BASE_MVC.DraggableViewMixin, {\n\n tagName : 'div',\n className : 'list-item',\n\n /** Set up the base class and all mixins */\n initialize : function( attributes ){\n ExpandableView.prototype.initialize.call( this, attributes );\n BASE_MVC.SelectableViewMixin.initialize.call( this, attributes );\n BASE_MVC.DraggableViewMixin.initialize.call( this, attributes );\n this._setUpListeners();\n },\n\n /** event listeners */\n _setUpListeners : function(){\n // hide the primary actions in the title bar when selectable and narrow\n this.on( 'selectable', function( isSelectable ){\n if( isSelectable ){\n this.$( '.primary-actions' ).hide();\n } else {\n this.$( '.primary-actions' ).show();\n }\n }, this );\n return this;\n },\n\n // ........................................................................ rendering\n /** In this override, call methods to build warnings, titlebar and primary actions */\n _buildNewRender : function(){\n var $newRender = ExpandableView.prototype._buildNewRender.call( this );\n $newRender.children( '.warnings' ).replaceWith( this._renderWarnings() );\n $newRender.children( '.title-bar' ).replaceWith( this._renderTitleBar() );\n $newRender.children( '.primary-actions' ).append( this._renderPrimaryActions() );\n $newRender.find( '> .title-bar .subtitle' ).replaceWith( this._renderSubtitle() );\n return $newRender;\n },\n\n /** In this override, render the selector controls and set up dragging before the swap */\n _swapNewRender : function( $newRender ){\n ExpandableView.prototype._swapNewRender.call( this, $newRender );\n if( this.selectable ){ this.showSelector( 0 ); }\n if( this.draggable ){ this.draggableOn(); }\n return this.$el;\n },\n\n /** Render any warnings the item may need to show (e.g. \"I'm deleted\") */\n _renderWarnings : function(){\n var view = this,\n $warnings = $( '
                        ' ),\n json = view.model.toJSON();\n //TODO:! unordered (map)\n _.each( view.templates.warnings, function( templateFn ){\n $warnings.append( $( templateFn( json, view ) ) );\n });\n return $warnings;\n },\n\n /** Render the title bar (the main/exposed SUMMARY dom element) */\n _renderTitleBar : function(){\n return $( this.templates.titleBar( this.model.toJSON(), this ) );\n },\n\n /** Return an array of jQ objects containing common/easily-accessible item controls */\n _renderPrimaryActions : function(){\n // override this\n return [];\n },\n\n /** Render the title bar (the main/exposed SUMMARY dom element) */\n _renderSubtitle : function(){\n return $( this.templates.subtitle( this.model.toJSON(), this ) );\n },\n\n // ......................................................................... events\n /** event map */\n events : {\n // expand the body when the title is clicked or when in focus and space or enter is pressed\n 'click .title-bar' : '_clickTitleBar',\n 'keydown .title-bar' : '_keyDownTitleBar',\n 'click .selector' : 'toggleSelect'\n },\n\n /** expand when the title bar is clicked */\n _clickTitleBar : function( event ){\n event.stopPropagation();\n if( event.altKey ){\n this.toggleSelect( event );\n if( !this.selectable ){\n this.showSelector();\n }\n } else {\n this.toggleExpanded();\n }\n },\n\n /** expand when the title bar is in focus and enter or space is pressed */\n _keyDownTitleBar : function( event ){\n // bail (with propagation) if keydown and not space or enter\n var KEYCODE_SPACE = 32, KEYCODE_RETURN = 13;\n if( event && ( event.type === 'keydown' )\n &&( event.keyCode === KEYCODE_SPACE || event.keyCode === KEYCODE_RETURN ) ){\n this.toggleExpanded();\n event.stopPropagation();\n return false;\n }\n return true;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'ListItemView(' + modelString + ')';\n }\n}));\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nListItemView.prototype.templates = (function(){\n\n var elTemplato = BASE_MVC.wrapTemplate([\n '
                        ',\n // errors, messages, etc.\n '
                        ',\n\n // multi-select checkbox\n '
                        ',\n '',\n '
                        ',\n // space for title bar buttons - gen. floated to the right\n '
                        ',\n '
                        ',\n\n // expandable area for more details\n '
                        ',\n '
                        '\n ]);\n\n var warnings = {};\n\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding a tabindex here allows focusing the title bar and the use of keydown to expand the dataset display\n '
                        ',\n //TODO: prob. belongs in dataset-list-item\n '',\n '
                        ',\n '<%- element.name %>',\n '
                        ',\n '
                        ',\n '
                        '\n ], 'element' );\n\n var subtitleTemplate = BASE_MVC.wrapTemplate([\n // override this\n '
                        '\n ]);\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n // override this\n '
                        '\n ]);\n\n return {\n el : elTemplato,\n warnings : warnings,\n titleBar : titleBarTemplate,\n subtitle : subtitleTemplate,\n details : detailsTemplate\n };\n}());\n\n\n//==============================================================================\n/** A view that is displayed in some larger list/grid/collection.\n * *AND* can display some sub-list of it's own when expanded (e.g. dataset collections).\n * This list will 'foldout' when the item is expanded depending on this.foldoutStyle:\n * If 'foldout': will expand vertically to show the nested list\n * If 'drilldown': will overlay the parent list\n *\n * Inherits from ListItemView.\n *\n * _renderDetails does the work of creating this.details: a sub-view that shows the nested list\n */\nvar FoldoutListItemView = ListItemView.extend({\n\n /** If 'foldout': show the sub-panel inside the expanded item\n * If 'drilldown': only fire events and handle by pub-sub\n * (allow the panel containing this item to attach it, hide itself, etc.)\n */\n foldoutStyle : 'foldout',\n /** Panel view class to instantiate for the sub-panel */\n foldoutPanelClass : null,\n\n /** override to:\n * add attributes foldoutStyle and foldoutPanelClass for config poly\n * disrespect attributes.expanded if drilldown\n */\n initialize : function( attributes ){\n if( this.foldoutStyle === 'drilldown' ){ this.expanded = false; }\n this.foldoutStyle = attributes.foldoutStyle || this.foldoutStyle;\n this.foldoutPanelClass = attributes.foldoutPanelClass || this.foldoutPanelClass;\n\n ListItemView.prototype.initialize.call( this, attributes );\n this.foldout = this._createFoldoutPanel();\n },\n\n /** in this override, attach the foldout panel when rendering details */\n _renderDetails : function(){\n if( this.foldoutStyle === 'drilldown' ){ return $(); }\n var $newDetails = ListItemView.prototype._renderDetails.call( this );\n return this._attachFoldout( this.foldout, $newDetails );\n },\n\n /** In this override, handle collection expansion. */\n _createFoldoutPanel : function(){\n var model = this.model;\n var FoldoutClass = this._getFoldoutPanelClass( model ),\n options = this._getFoldoutPanelOptions( model ),\n foldout = new FoldoutClass( _.extend( options, {\n model : model\n }));\n return foldout;\n },\n\n /** Stub to return proper foldout panel class */\n _getFoldoutPanelClass : function(){\n // override\n return this.foldoutPanelClass;\n },\n\n /** Stub to return proper foldout panel options */\n _getFoldoutPanelOptions : function(){\n return {\n // propagate foldout style down\n foldoutStyle : this.foldoutStyle,\n fxSpeed : this.fxSpeed\n };\n },\n\n /** Render the foldout panel inside the view, hiding controls */\n _attachFoldout : function( foldout, $whereTo ){\n $whereTo = $whereTo || this.$( '> .details' );\n this.foldout = foldout.render( 0 );\n foldout.$( '> .controls' ).hide();\n return $whereTo.append( foldout.$el );\n },\n\n /** In this override, branch on foldoutStyle to show expanded */\n expand : function(){\n var view = this;\n return view._fetchModelDetails()\n .always(function(){\n if( view.foldoutStyle === 'foldout' ){\n view._expand();\n } else if( view.foldoutStyle === 'drilldown' ){\n view._expandByDrilldown();\n }\n });\n },\n\n /** For drilldown, set up close handler and fire expanded:drilldown\n * containing views can listen to this and handle other things\n * (like hiding themselves) by listening for expanded/collapsed:drilldown\n */\n _expandByDrilldown : function(){\n var view = this;\n // attachment and rendering done by listener\n view.listenTo( view.foldout, 'close', function(){\n view.trigger( 'collapsed:drilldown', view, view.foldout );\n });\n view.trigger( 'expanded:drilldown', view, view.foldout );\n }\n\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nFoldoutListItemView.prototype.templates = (function(){\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n // override with more info (that goes above the panel)\n '
                        '\n ], 'collection' );\n\n return _.extend( {}, ListItemView.prototype.templates, {\n details : detailsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n ExpandableView : ExpandableView,\n ListItemView : ListItemView,\n FoldoutListItemView : FoldoutListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/list/list-item.js","define([\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( baseMVC, _l ){\n// =============================================================================\n/** A view on any model that has a 'tags' attribute (a list of tag strings)\n * Incorporates the select2 jQuery plugin for tags display/editing:\n * http://ivaynberg.github.io/select2/\n */\nvar TagsEditor = Backbone.View\n .extend( baseMVC.LoggableMixin )\n .extend( baseMVC.HiddenUntilActivatedViewMixin ).extend({\n\n tagName : 'div',\n className : 'tags-display',\n\n /** Set up listeners, parse options */\n initialize : function( options ){\n //console.debug( this, options );\n // only listen to the model only for changes to tags - re-render\n if (options.usePrompt === false) {\n this.label = '';\n } else {\n this.label = '';\n }\n this.hiddenUntilActivated( options.$activator, options );\n },\n\n /** Build the DOM elements, call select to on the created input, and set up behaviors */\n render : function(){\n var self = this;\n this.$el.html( this._template() );\n\n this.$input().select2({\n placeholder : 'Add tags',\n width : '100%',\n tags : function(){\n // initialize possible tags in the dropdown based on all the tags the user has used so far\n return self._getTagsUsed();\n }\n });\n\n this._setUpBehaviors();\n return this;\n },\n\n _hashToName: function(tag){\n if (tag.startsWith('#')){\n return 'name:' + tag.slice(1);\n }\n return tag;\n },\n\n _nameToHash: function(tag){\n if (tag.startsWith('name:')){\n tag = '#' + tag.slice(5);\n }\n return tag;\n },\n\n /** @returns {String} the html text used to build the view's DOM */\n _template : function(){\n return [\n this.label,\n // set up initial tags by adding as CSV to input vals (necc. to init select2)\n ''\n ].join( '' );\n },\n\n /** @returns {String} the sorted, comma-separated tags from the model */\n tagsToCSV : function(){\n var self = this;\n var tagsArray = this.model.get( 'tags' );\n if( !_.isArray( tagsArray ) || _.isEmpty( tagsArray ) ){\n return '';\n }\n return tagsArray.map( function( tag ){\n return _.escape( self._nameToHash( tag ) );\n }).sort().join( ',' );\n },\n\n /** @returns {jQuery} the input for this view */\n $input : function(){\n return this.$el.find( 'input.tags-input' );\n },\n\n /** @returns {String[]} all tags used by the current user */\n _getTagsUsed : function(){\n//TODO: global\n var self = this;\n return _.map(Galaxy.user.get( 'tags_used' ), self._nameToHash);\n },\n\n /** set up any event listeners on the view's DOM (mostly handled by select2) */\n _setUpBehaviors : function(){\n var self = this;\n this.$input().on( 'change', function( event ){\n // Modify any 'hashtag' 'nametags'\n event.val = _.map(event.val, self._hashToName);\n // save the model's tags in either remove or added event\n self.model.save({ tags: event.val });\n // if it's new, add the tag to the users tags\n if( event.added ){\n //??: solve weird behavior in FF on test.galaxyproject.org where\n // event.added.text is string object: 'String{ 0=\"o\", 1=\"n\", 2=\"e\" }'\n self._addNewTagToTagsUsed( event.added.text + '' );\n }\n });\n },\n\n /** add a new tag (if not already there) to the list of all tags used by the user\n * @param {String} newTag the tag to add to the list of used\n */\n _addNewTagToTagsUsed : function( newTag ){\n//TODO: global\n var tagsUsed = Galaxy.user.get( 'tags_used' );\n if( !_.contains( tagsUsed, newTag ) ){\n tagsUsed.push( newTag );\n tagsUsed.sort();\n Galaxy.user.set( 'tags_used', tagsUsed );\n }\n },\n\n /** shut down event listeners and remove this view's DOM */\n remove : function(){\n this.$input.off();\n this.stopListening( this.model );\n Backbone.View.prototype.remove.call( this );\n },\n\n /** string rep */\n toString : function(){ return [ 'TagsEditor(', this.model + '', ')' ].join(''); }\n});\n\n// =============================================================================\nreturn {\n TagsEditor : TagsEditor\n};\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tag.js","/**\n * Model, view, and controller objects for Galaxy tools and tool panel.\n */\n\n define([\n \"libs/underscore\",\n \"viz/trackster/util\",\n \"mvc/dataset/data\",\n \"mvc/tool/tool-form\"\n\n], function(_, util, data, ToolForm) {\n 'use strict';\n\n/**\n * Mixin for tracking model visibility.\n */\nvar VisibilityMixin = {\n hidden: false,\n\n show: function() {\n this.set(\"hidden\", false);\n },\n\n hide: function() {\n this.set(\"hidden\", true);\n },\n\n toggle: function() {\n this.set(\"hidden\", !this.get(\"hidden\"));\n },\n\n is_visible: function() {\n return !this.attributes.hidden;\n }\n\n};\n\n/**\n * A tool parameter.\n */\nvar ToolParameter = Backbone.Model.extend({\n defaults: {\n name: null,\n label: null,\n type: null,\n value: null,\n html: null,\n num_samples: 5\n },\n\n initialize: function(options) {\n this.attributes.html = unescape(this.attributes.html);\n },\n\n copy: function() {\n return new ToolParameter(this.toJSON());\n },\n\n set_value: function(value) {\n this.set('value', value || '');\n }\n});\n\nvar ToolParameterCollection = Backbone.Collection.extend({\n model: ToolParameter\n});\n\n/**\n * A data tool parameter.\n */\nvar DataToolParameter = ToolParameter.extend({});\n\n/**\n * An integer tool parameter.\n */\nvar IntegerToolParameter = ToolParameter.extend({\n set_value: function(value) {\n this.set('value', parseInt(value, 10));\n },\n\n /**\n * Returns samples from a tool input.\n */\n get_samples: function() {\n return d3.scale.linear()\n .domain([this.get('min'), this.get('max')])\n .ticks(this.get('num_samples'));\n }\n});\n\nvar FloatToolParameter = IntegerToolParameter.extend({\n set_value: function(value) {\n this.set('value', parseFloat(value));\n }\n});\n\n/**\n * A select tool parameter.\n */\nvar SelectToolParameter = ToolParameter.extend({\n /**\n * Returns tool options.\n */\n get_samples: function() {\n return _.map(this.get('options'), function(option) {\n return option[0];\n });\n }\n});\n\n// Set up dictionary of parameter types.\nToolParameter.subModelTypes = {\n 'integer': IntegerToolParameter,\n 'float': FloatToolParameter,\n 'data': DataToolParameter,\n 'select': SelectToolParameter\n};\n\n/**\n * A Galaxy tool.\n */\nvar Tool = Backbone.Model.extend({\n // Default attributes.\n defaults: {\n id: null,\n name: null,\n description: null,\n target: null,\n inputs: [],\n outputs: []\n },\n\n urlRoot: Galaxy.root + 'api/tools',\n\n initialize: function(options) {\n\n // Set parameters.\n this.set('inputs', new ToolParameterCollection(_.map(options.inputs, function(p) {\n var p_class = ToolParameter.subModelTypes[p.type] || ToolParameter;\n return new p_class(p);\n })));\n },\n\n /**\n *\n */\n toJSON: function() {\n var rval = Backbone.Model.prototype.toJSON.call(this);\n\n // Convert inputs to JSON manually.\n rval.inputs = this.get('inputs').map(function(i) { return i.toJSON(); });\n return rval;\n },\n\n /**\n * Removes inputs of a particular type; this is useful because not all inputs can be handled by\n * client and server yet.\n */\n remove_inputs: function(types) {\n var tool = this,\n incompatible_inputs = tool.get('inputs').filter( function(input) {\n return ( types.indexOf( input.get('type') ) !== -1);\n });\n tool.get('inputs').remove(incompatible_inputs);\n },\n\n /**\n * Returns object copy, optionally including only inputs that can be sampled.\n */\n copy: function(only_samplable_inputs) {\n var copy = new Tool(this.toJSON());\n\n // Return only samplable inputs if flag is set.\n if (only_samplable_inputs) {\n var valid_inputs = new Backbone.Collection();\n copy.get('inputs').each(function(input) {\n if (input.get_samples()) {\n valid_inputs.push(input);\n }\n });\n copy.set('inputs', valid_inputs);\n }\n\n return copy;\n },\n\n apply_search_results: function(results) {\n ( _.indexOf(results, this.attributes.id) !== -1 ? this.show() : this.hide() );\n return this.is_visible();\n },\n\n /**\n * Set a tool input's value.\n */\n set_input_value: function(name, value) {\n this.get('inputs').find(function(input) {\n return input.get('name') === name;\n }).set('value', value);\n },\n\n /**\n * Set many input values at once.\n */\n set_input_values: function(inputs_dict) {\n var self = this;\n _.each(_.keys(inputs_dict), function(input_name) {\n self.set_input_value(input_name, inputs_dict[input_name]);\n });\n },\n\n /**\n * Run tool; returns a Deferred that resolves to the tool's output(s).\n */\n run: function() {\n return this._run();\n },\n\n /**\n * Rerun tool using regions and a target dataset.\n */\n rerun: function(target_dataset, regions) {\n return this._run({\n action: 'rerun',\n target_dataset_id: target_dataset.id,\n regions: regions\n });\n },\n\n /**\n * Returns input dict for tool's inputs.\n */\n get_inputs_dict: function() {\n var input_dict = {};\n this.get('inputs').each(function(input) {\n input_dict[input.get('name')] = input.get('value');\n });\n return input_dict;\n },\n\n /**\n * Run tool; returns a Deferred that resolves to the tool's output(s).\n * NOTE: this method is a helper method and should not be called directly.\n */\n _run: function(additional_params) {\n // Create payload.\n var payload = _.extend({\n tool_id: this.id,\n inputs: this.get_inputs_dict()\n }, additional_params);\n\n // Because job may require indexing datasets, use server-side\n // deferred to ensure that job is run. Also use deferred that\n // resolves to outputs from tool.\n var run_deferred = $.Deferred(),\n ss_deferred = new util.ServerStateDeferred({\n ajax_settings: {\n url: this.urlRoot,\n data: JSON.stringify(payload),\n dataType: \"json\",\n contentType: 'application/json',\n type: \"POST\"\n },\n interval: 2000,\n success_fn: function(response) {\n return response !== \"pending\";\n }\n });\n\n // Run job and resolve run_deferred to tool outputs.\n $.when(ss_deferred.go()).then(function(result) {\n run_deferred.resolve(new data.DatasetCollection(result));\n });\n return run_deferred;\n }\n});\n_.extend(Tool.prototype, VisibilityMixin);\n\n/**\n * Tool view.\n */\nvar ToolView = Backbone.View.extend({\n\n});\n\n/**\n * Wrap collection of tools for fast access/manipulation.\n */\nvar ToolCollection = Backbone.Collection.extend({\n model: Tool\n});\n\n/**\n * Label or section header in tool panel.\n */\nvar ToolSectionLabel = Backbone.Model.extend(VisibilityMixin);\n\n/**\n * Section of tool panel with elements (labels and tools).\n */\nvar ToolSection = Backbone.Model.extend({\n defaults: {\n elems: [],\n open: false\n },\n\n clear_search_results: function() {\n _.each(this.attributes.elems, function(elt) {\n elt.show();\n });\n\n this.show();\n this.set(\"open\", false);\n },\n\n apply_search_results: function(results) {\n var all_hidden = true,\n cur_label;\n _.each(this.attributes.elems, function(elt) {\n if (elt instanceof ToolSectionLabel) {\n cur_label = elt;\n cur_label.hide();\n }\n else if (elt instanceof Tool) {\n if (elt.apply_search_results(results)) {\n all_hidden = false;\n if (cur_label) {\n cur_label.show();\n }\n }\n }\n });\n\n if (all_hidden) {\n this.hide();\n }\n else {\n this.show();\n this.set(\"open\", true);\n }\n }\n});\n_.extend(ToolSection.prototype, VisibilityMixin);\n\n/**\n * Tool search that updates results when query is changed. Result value of null\n * indicates that query was not run; if not null, results are from search using\n * query.\n */\nvar ToolSearch = Backbone.Model.extend({\n defaults: {\n search_hint_string: \"search tools\",\n min_chars_for_search: 3,\n clear_btn_url: \"\",\n visible: true,\n query: \"\",\n results: null,\n // ESC (27) will clear the input field and tool search filters\n clear_key: 27\n },\n\n urlRoot: Galaxy.root + 'api/tools',\n\n initialize: function() {\n this.on(\"change:query\", this.do_search);\n },\n\n /**\n * Do the search and update the results.\n */\n do_search: function() {\n var query = this.attributes.query;\n\n // If query is too short, do not search.\n if (query.length < this.attributes.min_chars_for_search) {\n this.set(\"results\", null);\n return;\n }\n\n // Do search via AJAX.\n var q = query;\n // Stop previous ajax-request\n if (this.timer) {\n clearTimeout(this.timer);\n }\n // Start a new ajax-request in X ms\n $(\"#search-clear-btn\").hide();\n $(\"#search-spinner\").show();\n var self = this;\n this.timer = setTimeout(function () {\n // log the search to analytics if present\n if ( typeof ga !== 'undefined' ) {\n ga( 'send', 'pageview', Galaxy.root + '?q=' + q );\n }\n $.get( self.urlRoot, { q: q }, function (data) {\n self.set(\"results\", data);\n $(\"#search-spinner\").hide();\n $(\"#search-clear-btn\").show();\n }, \"json\" );\n }, 400 );\n },\n\n clear_search: function() {\n this.set(\"query\", \"\");\n this.set(\"results\", null);\n }\n\n});\n_.extend(ToolSearch.prototype, VisibilityMixin);\n\n/**\n * Tool Panel.\n */\nvar ToolPanel = Backbone.Model.extend({\n\n initialize: function(options) {\n this.attributes.tool_search = options.tool_search;\n this.attributes.tool_search.on(\"change:results\", this.apply_search_results, this);\n this.attributes.tools = options.tools;\n this.attributes.layout = new Backbone.Collection( this.parse(options.layout) );\n },\n\n /**\n * Parse tool panel dictionary and return collection of tool panel elements.\n */\n parse: function(response) {\n // Recursive function to parse tool panel elements.\n var self = this,\n // Helper to recursively parse tool panel.\n parse_elt = function(elt_dict) {\n var type = elt_dict.model_class;\n // There are many types of tools; for now, anything that ends in 'Tool'\n // is treated as a generic tool.\n if ( type.indexOf('Tool') === type.length - 4 ) {\n return self.attributes.tools.get(elt_dict.id);\n }\n else if (type === 'ToolSection') {\n // Parse elements.\n var elems = _.map(elt_dict.elems, parse_elt);\n elt_dict.elems = elems;\n return new ToolSection(elt_dict);\n }\n else if (type === 'ToolSectionLabel') {\n return new ToolSectionLabel(elt_dict);\n }\n };\n\n return _.map(response, parse_elt);\n },\n\n clear_search_results: function() {\n this.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSection) {\n panel_elt.clear_search_results();\n }\n else {\n // Label or tool, so just show.\n panel_elt.show();\n }\n });\n },\n\n apply_search_results: function() {\n var results = this.get('tool_search').get('results');\n if (results === null) {\n this.clear_search_results();\n return;\n }\n\n var cur_label = null;\n this.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSectionLabel) {\n cur_label = panel_elt;\n cur_label.hide();\n }\n else if (panel_elt instanceof Tool) {\n if (panel_elt.apply_search_results(results)) {\n if (cur_label) {\n cur_label.show();\n }\n }\n }\n else {\n // Starting new section, so clear current label.\n cur_label = null;\n panel_elt.apply_search_results(results);\n }\n });\n }\n});\n\n/**\n * View classes for Galaxy tools and tool panel.\n *\n * Views use the templates defined below for rendering. Views update as needed\n * based on (a) model/collection events and (b) user interactions; in this sense,\n * they are controllers are well and the HTML is the real view in the MVC architecture.\n */\n\n/**\n * Base view that handles visibility based on model's hidden attribute.\n */\nvar BaseView = Backbone.View.extend({\n initialize: function() {\n this.model.on(\"change:hidden\", this.update_visible, this);\n this.update_visible();\n },\n update_visible: function() {\n ( this.model.attributes.hidden ? this.$el.hide() : this.$el.show() );\n }\n});\n\n/**\n * Link to a tool.\n */\nvar ToolLinkView = BaseView.extend({\n tagName: 'div',\n\n render: function() {\n // create element\n var $link = $('
                        ');\n $link.append(templates.tool_link(this.model.toJSON()));\n\n var formStyle = this.model.get( 'form_style', null );\n // open upload dialog for upload tool\n if (this.model.id === 'upload1') {\n $link.find('a').on('click', function(e) {\n e.preventDefault();\n Galaxy.upload.show();\n });\n }\n else if ( formStyle === 'regular' ) { // regular tools\n var self = this;\n $link.find('a').on('click', function(e) {\n e.preventDefault();\n Galaxy.router.push( '/', { tool_id : self.model.id, version : self.model.get('version') } );\n });\n }\n\n // add element\n this.$el.append($link);\n return this;\n }\n});\n\n/**\n * Panel label/section header.\n */\nvar ToolSectionLabelView = BaseView.extend({\n tagName: 'div',\n className: 'toolPanelLabel',\n\n render: function() {\n this.$el.append( $(\"\").text(this.model.attributes.text) );\n return this;\n }\n});\n\n/**\n * Panel section.\n */\nvar ToolSectionView = BaseView.extend({\n tagName: 'div',\n className: 'toolSectionWrapper',\n\n initialize: function() {\n BaseView.prototype.initialize.call(this);\n this.model.on(\"change:open\", this.update_open, this);\n },\n\n render: function() {\n // Build using template.\n this.$el.append( templates.panel_section(this.model.toJSON()) );\n\n // Add tools to section.\n var section_body = this.$el.find(\".toolSectionBody\");\n _.each(this.model.attributes.elems, function(elt) {\n if (elt instanceof Tool) {\n var tool_view = new ToolLinkView({model: elt, className: \"toolTitle\"});\n tool_view.render();\n section_body.append(tool_view.$el);\n }\n else if (elt instanceof ToolSectionLabel) {\n var label_view = new ToolSectionLabelView({model: elt});\n label_view.render();\n section_body.append(label_view.$el);\n }\n else {\n // TODO: handle nested section bodies?\n }\n });\n return this;\n },\n\n events: {\n 'click .toolSectionTitle > a': 'toggle'\n },\n\n /**\n * Toggle visibility of tool section.\n */\n toggle: function() {\n this.model.set(\"open\", !this.model.attributes.open);\n },\n\n /**\n * Update whether section is open or close.\n */\n update_open: function() {\n (this.model.attributes.open ?\n this.$el.children(\".toolSectionBody\").slideDown(\"fast\") :\n this.$el.children(\".toolSectionBody\").slideUp(\"fast\")\n );\n }\n});\n\nvar ToolSearchView = Backbone.View.extend({\n tagName: 'div',\n id: 'tool-search',\n className: 'bar',\n\n events: {\n 'click': 'focus_and_select',\n 'keyup :input': 'query_changed',\n 'change :input': 'query_changed',\n 'click #search-clear-btn': 'clear'\n },\n\n render: function() {\n this.$el.append( templates.tool_search(this.model.toJSON()) );\n if (!this.model.is_visible()) {\n this.$el.hide();\n }\n\n // Adjust top for issue 2907 depending on whether the messagebox is visible.\n if ($(\"#messagebox\").is(\":visible\")) {\n this.$el.css(\"top\",\"95px\");\n }\n\n this.$el.find('[title]').tooltip();\n return this;\n },\n\n focus_and_select: function() {\n this.$el.find(\":input\").focus().select();\n },\n\n clear: function() {\n this.model.clear_search();\n this.$el.find(\":input\").val('');\n this.focus_and_select();\n return false;\n },\n\n query_changed: function( evData ) {\n // check for the 'clear key' (ESC) first\n if( ( this.model.attributes.clear_key ) &&\n ( this.model.attributes.clear_key === evData.which ) ){\n this.clear();\n return false;\n }\n this.model.set(\"query\", this.$el.find(\":input\").val());\n }\n});\n\n/**\n * Tool panel view. Events triggered include:\n * tool_link_click(click event, tool_model)\n */\nvar ToolPanelView = Backbone.View.extend({\n tagName: 'div',\n className: 'toolMenu',\n\n /**\n * Set up view.\n */\n initialize: function() {\n this.model.get('tool_search').on(\"change:results\", this.handle_search_results, this);\n },\n\n render: function() {\n var self = this;\n\n // Render search.\n var search_view = new ToolSearchView( { model: this.model.get('tool_search') } );\n search_view.render();\n self.$el.append(search_view.$el);\n\n // Render panel.\n this.model.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSection) {\n var section_title_view = new ToolSectionView({model: panel_elt});\n section_title_view.render();\n self.$el.append(section_title_view.$el);\n }\n else if (panel_elt instanceof Tool) {\n var tool_view = new ToolLinkView({model: panel_elt, className: \"toolTitleNoSection\"});\n tool_view.render();\n self.$el.append(tool_view.$el);\n }\n else if (panel_elt instanceof ToolSectionLabel) {\n var label_view = new ToolSectionLabelView({model: panel_elt});\n label_view.render();\n self.$el.append(label_view.$el);\n }\n });\n\n // Setup tool link click eventing.\n self.$el.find(\"a.tool-link\").click(function(e) {\n // Tool id is always the first class.\n var\n tool_id = $(this).attr('class').split(/\\s+/)[0],\n tool = self.model.get('tools').get(tool_id);\n\n self.trigger(\"tool_link_click\", e, tool);\n });\n\n return this;\n },\n\n handle_search_results: function() {\n var results = this.model.get('tool_search').get('results');\n if (results && results.length === 0) {\n $(\"#search-no-results\").show();\n }\n else {\n $(\"#search-no-results\").hide();\n }\n }\n});\n\n/**\n * View for working with a tool: setting parameters and inputs and executing the tool.\n */\nvar ToolFormView = Backbone.View.extend({\n className: 'toolForm',\n\n render: function() {\n this.$el.children().remove();\n this.$el.append( templates.tool_form(this.model.toJSON()) );\n }\n});\n\n/**\n * Integrated tool menu + tool execution.\n */\nvar IntegratedToolMenuAndView = Backbone.View.extend({\n className: 'toolMenuAndView',\n\n initialize: function() {\n this.tool_panel_view = new ToolPanelView({collection: this.collection});\n this.tool_form_view = new ToolFormView();\n },\n\n render: function() {\n // Render and append tool panel.\n this.tool_panel_view.render();\n this.tool_panel_view.$el.css(\"float\", \"left\");\n this.$el.append(this.tool_panel_view.$el);\n\n // Append tool form view.\n this.tool_form_view.$el.hide();\n this.$el.append(this.tool_form_view.$el);\n\n // On tool link click, show tool.\n var self = this;\n this.tool_panel_view.on(\"tool_link_click\", function(e, tool) {\n // Prevents click from activating link:\n e.preventDefault();\n // Show tool that was clicked on:\n self.show_tool(tool);\n });\n },\n\n /**\n * Fetch and display tool.\n */\n show_tool: function(tool) {\n var self = this;\n tool.fetch().done( function() {\n self.tool_form_view.model = tool;\n self.tool_form_view.render();\n self.tool_form_view.$el.show();\n $('#left').width(\"650px\");\n });\n }\n});\n\n// TODO: move into relevant views\nvar templates = {\n // the search bar at the top of the tool panel\n tool_search : _.template([\n '\" autocomplete=\"off\" type=\"text\" />',\n ' ',\n //TODO: replace with icon\n '',\n ].join('')),\n\n // the category level container in the tool panel (e.g. 'Get Data', 'Text Manipulation')\n panel_section : _.template([\n '
                        \">',\n '<%- name %>',\n '
                        ',\n '
                        \" class=\"toolSectionBody\" style=\"display: none;\">',\n '
                        ',\n '
                        '\n ].join('')),\n\n // a single tool's link in the tool panel; will load the tool form in the center panel\n tool_link : _.template([\n '',\n '<% _.each( labels, function( label ){ %>',\n '\">',\n '<%- label %>',\n '',\n '<% }); %>',\n '',\n ' tool-link\" href=\"<%= link %>\" target=\"<%- target %>\" minsizehint=\"<%- min_width %>\">',\n '<%- name %>',\n '',\n ' <%- description %>'\n ].join('')),\n\n // the tool form for entering tool parameters, viewing help and executing the tool\n // loaded when a tool link is clicked in the tool panel\n tool_form : _.template([\n '
                        <%- tool.name %> (version <%- tool.version %>)
                        ',\n '
                        ',\n '<% _.each( tool.inputs, function( input ){ %>',\n '
                        ',\n '',\n '
                        ',\n '<%= input.html %>',\n '
                        ',\n '
                        ',\n '<%- input.help %>',\n '
                        ',\n '
                        ',\n '
                        ',\n '<% }); %>',\n '
                        ',\n '
                        ',\n '',\n '
                        ',\n '
                        ',\n '
                        <% tool.help %>
                        ',\n '
                        ',\n // TODO: we need scoping here because 'help' is the dom for the help menu in the masthead\n // which implies a leaky variable that I can't find\n ].join(''), { variable: 'tool' }),\n};\n\n\n// Exports\nreturn {\n ToolParameter: ToolParameter,\n IntegerToolParameter: IntegerToolParameter,\n SelectToolParameter: SelectToolParameter,\n Tool: Tool,\n ToolCollection: ToolCollection,\n ToolSearch: ToolSearch,\n ToolPanel: ToolPanel,\n ToolPanelView: ToolPanelView,\n ToolFormView: ToolFormView\n};\n\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tool/tools.js","/** This renders the content of the ftp popup **/\ndefine( [ 'utils/utils' ], function( Utils ) {\n return Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.options = Utils.merge( options, {\n class_add : 'upload-icon-button fa fa-square-o',\n class_remove : 'upload-icon-button fa fa-check-square-o',\n class_partial : 'upload-icon-button fa fa-minus-square-o',\n collection : null,\n onchange : function() {},\n onadd : function() {},\n onremove : function() {}\n } );\n this.collection = this.options.collection;\n this.setElement( this._template() );\n this.rows = [];\n Utils.get({\n url : Galaxy.root + 'api/remote_files',\n success : function( ftp_files ) { self._fill( ftp_files ) },\n error : function() { self._fill(); }\n });\n },\n\n /** Fill table with ftp entries */\n _fill: function( ftp_files ) {\n if ( ftp_files && ftp_files.length > 0 ) {\n this.$( '.upload-ftp-content' ).html( $( this._templateTable() ) );\n var size = 0;\n for ( index in ftp_files ) {\n this.rows.push( this._add( ftp_files[ index ] ) );\n size += ftp_files[ index ].size;\n }\n this.$( '.upload-ftp-number' ).html( ftp_files.length + ' files' );\n this.$( '.upload-ftp-disk' ).html( Utils.bytesToString ( size, true ) );\n if ( this.collection ) {\n var self = this;\n this.$( '._has_collection' ).show();\n this.$select_all = this.$( '.upload-selectall' ).addClass( this.options.class_add );\n this.$select_all.on( 'click', function() {\n var add = self.$select_all.hasClass( self.options.class_add );\n for ( index in ftp_files ) {\n var ftp_file = ftp_files[ index ];\n var model_index = self._find( ftp_file );\n if( !model_index && add || model_index && !add ) {\n self.rows[ index ].trigger( 'click' );\n }\n }\n });\n this._refresh();\n }\n } else {\n this.$( '.upload-ftp-content' ).html( $( this._templateInfo() ) );\n }\n this.$( '.upload-ftp-wait' ).hide();\n },\n\n /** Add file to table */\n _add: function( ftp_file ) {\n var self = this;\n var $it = $( this._templateRow( ftp_file ) );\n var $icon = $it.find( '.icon' );\n this.$( 'tbody' ).append( $it );\n if ( this.collection ) {\n $icon.addClass( this._find( ftp_file ) ? this.options.class_remove : this.options.class_add );\n $it.on('click', function() {\n var model_index = self._find( ftp_file );\n $icon.removeClass();\n if ( !model_index ) {\n self.options.onadd( ftp_file );\n $icon.addClass( self.options.class_remove );\n } else {\n self.options.onremove( model_index );\n $icon.addClass( self.options.class_add );\n }\n self._refresh();\n });\n } else {\n $it.on('click', function() { self.options.onchange( ftp_file ) } );\n }\n return $it;\n },\n\n /** Refresh select all button state */\n _refresh: function() {\n var filtered = this.collection.where( { file_mode: 'ftp', enabled: true } );\n this.$select_all.removeClass();\n if ( filtered.length == 0 ) {\n this.$select_all.addClass( this.options.class_add );\n } else {\n this.$select_all.addClass( filtered.length == this.rows.length ? this.options.class_remove : this.options.class_partial );\n }\n },\n\n /** Get model index */\n _find: function( ftp_file ) {\n var item = this.collection.findWhere({\n file_path : ftp_file.path,\n file_mode : 'ftp',\n enabled : true\n });\n return item && item.get('id');\n },\n\n /** Template of row */\n _templateRow: function( options ) {\n return '
                        ' + _.escape(options.path) + '' + Utils.bytesToString( options.size ) + '' + options.ctime + '
                        ' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '
                        NameSizeCreated
                        ';\n },\n\n /** Template of info message */\n _templateInfo: function() {\n return '
                        ' +\n 'Your FTP directory does not contain any files.' +\n '
                        ';\n },\n\n /** Template of main view */\n _template: function() {\n return '
                        ' +\n '
                        ' +\n '
                        This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at ' + this.options.ftp_upload_site + ' using your Galaxy credentials (email address and password).
                        ' +\n '
                        ' +\n '
                        ';\n }\n });\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/upload/upload-ftp.js","/** This renders the content of the settings popup, allowing users to specify flags i.e. for space-to-tab conversion **/\ndefine( [ 'utils/utils' ], function( Utils ) {\n return Backbone.View.extend({\n options: {\n class_check : 'fa-check-square-o',\n class_uncheck : 'fa-square-o',\n parameters : [{\n id : 'space_to_tab',\n title : 'Convert spaces to tabs',\n },{\n id : 'to_posix_lines',\n title : 'Use POSIX standard'\n }]\n },\n\n initialize: function( options ) {\n var self = this;\n this.model = options.model;\n this.setElement( $( '
                        ' ).addClass( 'upload-settings' ) );\n this.$el.append( $( '
                        ' ).addClass( 'upload-settings-cover' ) );\n this.$el.append( $( '' ).addClass( 'upload-settings-table ui-table-striped' ).append( '' ) );\n this.$cover = this.$( '.upload-settings-cover' );\n this.$table = this.$( '.upload-settings-table > tbody' );\n this.listenTo ( this.model, 'change', this.render, this );\n this.model.trigger( 'change' );\n },\n\n render: function() {\n var self = this;\n this.$table.empty();\n _.each( this.options.parameters, function( parameter ) {\n var $checkbox = $( '
                        ' ).addClass( 'upload-' + parameter.id + ' upload-icon-button fa' )\n .addClass( self.model.get( parameter.id ) && self.options.class_check || self.options.class_uncheck )\n .on( 'click', function() {\n self.model.get( 'enabled' ) && self.model.set( parameter.id, !self.model.get( parameter.id ) )\n });\n self.$table.append( $( '
                        ' ).append( $( '' +\n '' +\n '' +\n '' );\n });\n $tmpl.append( $table );\n } else {\n $tmpl.append( 'No ' + this.model.get( 'plural' ).toLowerCase() + ' have been shared with you.' );\n }\n return $tmpl;\n }\n });\n\n return {\n View: View\n }\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/grid/grid-shared.js","define([\n \"mvc/dataset/dataset-li-edit\",\n \"mvc/history/hda-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_LI_EDIT, HDA_LI, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DATASET_LI_EDIT.DatasetListItemEdit;\n/** @class Editing view for HistoryDatasetAssociation.\n */\nvar HDAListItemEdit = _super.extend(\n/** @lends HDAListItemEdit.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n /** In this override, only get details if in the ready state, get rerunnable if in other states.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n\n // special case the need for the rerunnable and creating_job attributes\n // needed for rendering re-run button on queued, running datasets\n } else if( !view.model.has( 'rerunnable' ) ){\n return view.model.fetch({ silent: true, data: {\n // only fetch rerunnable and creating_job to keep overhead down\n keys: [ 'rerunnable', 'creating_job' ].join(',')\n }});\n }\n return jQuery.when();\n },\n\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .unhide-link' : function( ev ){ this.model.unhide(); return false; }\n }),\n\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAListItemEdit(' + modelString + ')';\n }\n});\n\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nHDAListItemEdit.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n '<% if( !dataset.visible ){ %>',\n // add a link to unhide a dataset\n '
                        ',\n _l( 'This dataset has been hidden' ),\n '
                        ', _l( 'Unhide it' ), '',\n '
                        ',\n '<% } %>'\n ], 'dataset' )\n });\n\n return _.extend( {}, _super.prototype.templates, {\n //NOTE: *steal* the HDAListItemView titleBar\n titleBar : HDA_LI.HDAListItemView.prototype.templates.titleBar,\n warnings : warnings\n });\n}());\n\n\n//==============================================================================\n return {\n HDAListItemEdit : HDAListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-li-edit.js","define([\n \"mvc/history/hdca-li\",\n \"mvc/collection/collection-view-edit\",\n \"ui/fa-icon-button\",\n \"utils/localization\"\n], function( HDCA_LI, DC_VIEW_EDIT, faIconButton, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = HDCA_LI.HDCAListItemView;\n/** @class Editing view for HistoryDatasetCollectionAssociation.\n */\nvar HDCAListItemEdit = _super.extend(\n/** @lends HDCAListItemEdit.prototype */{\n\n /** logger used to record this.log messages, commonly set to console */\n //logger : console,\n\n /** Override to return editable versions of the collection panels */\n _getFoldoutPanelClass : function(){\n switch( this.model.get( 'collection_type' ) ){\n case 'list':\n return DC_VIEW_EDIT.ListCollectionViewEdit;\n case 'paired':\n return DC_VIEW_EDIT.PairCollectionViewEdit;\n case 'list:paired':\n return DC_VIEW_EDIT.ListOfPairsCollectionViewEdit;\n case 'list:list':\n return DC_VIEW_EDIT.ListOfListsCollectionViewEdit;\n }\n throw new TypeError( 'Uknown collection_type: ' + this.model.get( 'collection_type' ) );\n },\n\n // ......................................................................... delete\n /** In this override, add the delete button. */\n _renderPrimaryActions : function(){\n this.log( this + '._renderPrimaryActions' );\n // render the display, edit attr and delete icon-buttons\n return _super.prototype._renderPrimaryActions.call( this )\n .concat([\n this._renderDeleteButton()\n ]);\n },\n\n /** Render icon-button to delete this collection. */\n _renderDeleteButton : function(){\n var self = this,\n deleted = this.model.get( 'deleted' );\n return faIconButton({\n title : deleted? _l( 'Dataset collection is already deleted' ): _l( 'Delete' ),\n classes : 'delete-btn',\n faIcon : 'fa-times',\n disabled : deleted,\n onclick : function() {\n // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n self.$el.find( '.icon-btn.delete-btn' ).trigger( 'mouseout' );\n self.model[ 'delete' ]();\n }\n });\n },\n\n // ......................................................................... misc\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDCAListItemEdit(' + modelString + ')';\n }\n});\n\n//==============================================================================\n return {\n HDCAListItemEdit : HDCAListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-li-edit.js","/** This class renders the grid list. */\ndefine( [ 'utils/utils', 'mvc/grid/grid-view', 'mvc/history/history-model', 'mvc/history/copy-dialog' ], function( Utils, GridView, HistoryModel, historyCopyDialog ) {\n\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.setElement( $( '
                        ' ) );\n this.model = new Backbone.Model();\n Utils.get({\n url : Galaxy.root + 'history/' + options.action_id,\n success : function( response ) {\n response[ 'dict_format' ] = true;\n _.each( response[ 'operations' ], function( operation ) {\n if ( operation.label == 'Copy' ) {\n operation.onclick = function( id ) { self._showCopyDialog( id ) };\n }\n });\n self.model.set( response );\n self.render();\n }\n });\n },\n\n render: function() {\n var grid = new GridView( this.model.attributes );\n this.$el.empty().append( grid.$el );\n },\n\n _showCopyDialog: function( id ) {\n var history = new HistoryModel.History( { id : id } );\n history.fetch()\n .fail( function() {\n alert( 'History could not be fetched. Please contact an administrator' );\n })\n .done( function(){\n historyCopyDialog( history, {} ).done( function() {\n if( window.parent && window.parent.Galaxy && window.parent.Galaxy.currHistoryPanel ) {\n window.parent.Galaxy.currHistoryPanel.loadCurrentHistory();\n }\n window.location.reload( true );\n } );\n });\n }\n });\n\n return {\n View: View\n }\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-list.js","define([\n \"mvc/history/history-model\",\n \"mvc/history/history-view-edit\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( HISTORY_MODEL, HISTORY_VIEW_EDIT, BASE_MVC, _l ){\n\n'use strict';\n\n// ============================================================================\n/** session storage for history panel preferences (and to maintain state)\n */\nvar HistoryViewPrefs = BASE_MVC.SessionStorageModel.extend(\n/** @lends HistoryViewPrefs.prototype */{\n defaults : {\n /** should the tags editor be shown or hidden initially? */\n tagsEditorShown : false,\n /** should the annotation editor be shown or hidden initially? */\n annotationEditorShown : false,\n ///** what is the currently focused content (dataset or collection) in the current history?\n // * (the history panel will highlight and scroll to the focused content view)\n // */\n //focusedContentId : null\n /** Current scroll position */\n scrollPosition : 0\n },\n toString : function(){\n return 'HistoryViewPrefs(' + JSON.stringify( this.toJSON() ) + ')';\n }\n});\n\n/** key string to store panel prefs (made accessible on class so you can access sessionStorage directly) */\nHistoryViewPrefs.storageKey = function storageKey(){\n return ( 'history-panel' );\n};\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\nvar _super = HISTORY_VIEW_EDIT.HistoryViewEdit;\n// used in root/index.mako\n/** @class View/Controller for the user's current history model as used in the history\n * panel (current right hand panel) of the analysis page.\n *\n * The only history panel that:\n * will poll for updates.\n * displays datasets in reverse hid order.\n */\nvar CurrentHistoryView = _super.extend(/** @lends CurrentHistoryView.prototype */{\n\n className : _super.prototype.className + ' current-history-panel',\n\n /** override to use drilldown (and not foldout) for how collections are displayed */\n HDCAViewClass : _super.prototype.HDCAViewClass.extend({\n foldoutStyle : 'drilldown'\n }),\n\n emptyMsg : [\n _l( 'This history is empty' ), '. ',\n _l( 'You can ' ),\n '',\n _l( 'load your own data' ),\n '',\n _l( ' or ' ),\n '',\n _l( 'get data from an external source' ),\n ''\n ].join(''),\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events */\n initialize : function( attributes ){\n attributes = attributes || {};\n\n // ---- persistent preferences\n /** maintain state / preferences over page loads */\n this.preferences = new HistoryViewPrefs( _.extend({\n id : HistoryViewPrefs.storageKey()\n }, _.pick( attributes, _.keys( HistoryViewPrefs.prototype.defaults ) )));\n\n _super.prototype.initialize.call( this, attributes );\n\n /** sub-views that will overlay this panel (collections) */\n this.panelStack = [];\n\n /** id of currently focused content */\n this.currentContentId = attributes.currentContentId || null;\n //NOTE: purposely not sent to localstorage since panel recreation roughly lines up with a reset of this value\n },\n\n /** Override to cache the current scroll position with a listener */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n\n var panel = this;\n // reset scroll position when there's a new history\n this.on( 'new-model', function(){\n panel.preferences.set( 'scrollPosition', 0 );\n });\n },\n\n // ------------------------------------------------------------------------ loading history/item models\n // TODO: next three more appropriate moved to the app level\n /** (re-)loads the user's current history & contents w/ details */\n loadCurrentHistory : function(){\n return this.loadHistory( null, { url : Galaxy.root + 'history/current_history_json' });\n },\n\n /** loads a history & contents w/ details and makes them the current history */\n switchToHistory : function( historyId, attributes ){\n if( Galaxy.user.isAnonymous() ){\n this.trigger( 'error', _l( 'You must be logged in to switch histories' ), _l( 'Anonymous user' ) );\n return $.when();\n }\n return this.loadHistory( historyId, { url : Galaxy.root + 'history/set_as_current?id=' + historyId });\n },\n\n /** creates a new history on the server and sets it as the user's current history */\n createNewHistory : function( attributes ){\n if( Galaxy.user.isAnonymous() ){\n this.trigger( 'error', _l( 'You must be logged in to create histories' ), _l( 'Anonymous user' ) );\n return $.when();\n }\n return this.loadHistory( null, { url : Galaxy.root + 'history/create_new_current' });\n },\n\n /** release/free/shutdown old models and set up panel for new models */\n setModel : function( model, attributes, render ){\n _super.prototype.setModel.call( this, model, attributes, render );\n if( this.model && this.model.id ){\n this.log( 'checking for updates' );\n this.model.checkForUpdates();\n }\n return this;\n },\n\n // ------------------------------------------------------------------------ history/content event listening\n /** listening for history events */\n _setUpModelListeners : function(){\n _super.prototype._setUpModelListeners.call( this );\n // re-broadcast any model change events so that listeners don't have to re-bind to each history\n return this.listenTo( this.model, {\n 'change:nice_size change:size' : function(){\n this.trigger( 'history-size-change', this, this.model, arguments );\n },\n 'change:id' : function(){\n this.once( 'loading-done', function(){ this.model.checkForUpdates(); });\n }\n });\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n // if a hidden item is created (gen. by a workflow), moves thru the updater to the ready state,\n // then: remove it from the collection if the panel is set to NOT show hidden datasets\n this.listenTo( this.collection, 'state:ready', function( model, newState, oldState ){\n if( ( !model.get( 'visible' ) )\n && ( !this.collection.storage.includeHidden() ) ){\n this.removeItemView( model );\n }\n });\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** override to add a handler to capture the scroll position when the parent scrolls */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n // console.log( '_setUpBehaviors', this.$scrollContainer( $where ).get(0), this.$list( $where ) );\n // we need to call this in _setUpBehaviors which is called after render since the $el\n // may not be attached to $el.parent and $scrollContainer() may not work\n var panel = this;\n _super.prototype._setUpBehaviors.call( panel, $where );\n\n // cache the handler to remove and re-add so we don't pile up the handlers\n if( !this._debouncedScrollCaptureHandler ){\n this._debouncedScrollCaptureHandler = _.debounce( function scrollCapture(){\n // cache the scroll position (only if visible)\n if( panel.$el.is( ':visible' ) ){\n panel.preferences.set( 'scrollPosition', $( this ).scrollTop() );\n }\n }, 40 );\n }\n\n panel.$scrollContainer( $where )\n .off( 'scroll', this._debouncedScrollCaptureHandler )\n .on( 'scroll', this._debouncedScrollCaptureHandler );\n return panel;\n },\n\n /** In this override, handle null models and move the search input to the top */\n _buildNewRender : function(){\n if( !this.model ){ return $(); }\n var $newRender = _super.prototype._buildNewRender.call( this );\n $newRender.find( '.search' ).prependTo( $newRender.find( '> .controls' ) );\n this._renderQuotaMessage( $newRender );\n return $newRender;\n },\n\n /** render the message displayed when a user is over quota and can't run jobs */\n _renderQuotaMessage : function( $whereTo ){\n $whereTo = $whereTo || this.$el;\n return $( this.templates.quotaMsg( {}, this ) ).prependTo( $whereTo.find( '.messages' ) );\n },\n\n /** In this override, get and set current panel preferences when editor is used */\n _renderTags : function( $where ){\n var panel = this;\n // render tags and show/hide based on preferences\n _super.prototype._renderTags.call( panel, $where );\n if( panel.preferences.get( 'tagsEditorShown' ) ){\n panel.tagsEditor.toggle( true );\n }\n // store preference when shown or hidden\n panel.listenTo( panel.tagsEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden',\n function( tagsEditor ){\n panel.preferences.set( 'tagsEditorShown', tagsEditor.hidden );\n }\n );\n },\n\n /** In this override, get and set current panel preferences when editor is used */\n _renderAnnotation : function( $where ){\n var panel = this;\n // render annotation and show/hide based on preferences\n _super.prototype._renderAnnotation.call( panel, $where );\n if( panel.preferences.get( 'annotationEditorShown' ) ){\n panel.annotationEditor.toggle( true );\n }\n // store preference when shown or hidden\n panel.listenTo( panel.annotationEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden',\n function( annotationEditor ){\n panel.preferences.set( 'annotationEditorShown', annotationEditor.hidden );\n }\n );\n },\n\n /** Override to scroll to cached position (in prefs) after swapping */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n var panel = this;\n _.delay( function(){\n var pos = panel.preferences.get( 'scrollPosition' );\n if( pos ){\n panel.scrollTo( pos, 0 );\n }\n }, 10 );\n //TODO: is this enough of a delay on larger histories?\n\n return this;\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** Override to add the current-content highlight class to currentContentId's view */\n _attachItems : function( $whereTo ){\n _super.prototype._attachItems.call( this, $whereTo );\n var panel = this;\n if( panel.currentContentId ){\n panel._setCurrentContentById( panel.currentContentId );\n }\n return this;\n },\n\n /** Override to remove any drill down panels */\n addItemView : function( model, collection, options ){\n var view = _super.prototype.addItemView.call( this, model, collection, options );\n if( !view ){ return view; }\n if( this.panelStack.length ){ return this._collapseDrilldownPanel(); }\n return view;\n },\n\n // ------------------------------------------------------------------------ collection sub-views\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n // use pub-sub to: handle drilldown expansion and collapse\n return panel.listenTo( view, {\n 'expanded:drilldown' : function( v, drilldown ){\n this._expandDrilldownPanel( drilldown );\n },\n 'collapsed:drilldown' : function( v, drilldown ){\n this._collapseDrilldownPanel( drilldown );\n },\n });\n },\n\n /** display 'current content': add a visible highlight and store the id of a content item */\n setCurrentContent : function( view ){\n this.$( '.history-content.current-content' ).removeClass( 'current-content' );\n if( view ){\n view.$el.addClass( 'current-content' );\n this.currentContentId = view.model.id;\n } else {\n this.currentContentId = null;\n }\n },\n\n /** find the view with the id and then call setCurrentContent on it */\n _setCurrentContentById : function( id ){\n var view = this.viewFromModelId( id ) || null;\n this.setCurrentContent( view );\n },\n\n /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n _expandDrilldownPanel : function( drilldown ){\n this.panelStack.push( drilldown );\n // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n this.$controls().add( this.$list() ).hide();\n drilldown.parentName = this.model.get( 'name' );\n drilldown.delegateEvents().render().$el.appendTo( this.$el );\n },\n\n /** Handle drilldown close by freeing the panel and re-rendering this panel */\n _collapseDrilldownPanel : function( drilldown ){\n this.panelStack.pop();\n //TODO: MEM: free the panel\n this.$controls().add( this.$list() ).show();\n },\n\n // ........................................................................ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n // the two links in the empty message\n 'click .uploader-link' : function( ev ){ Galaxy.upload.show( ev ); },\n 'click .get-data-link' : function( ev ){\n var $toolMenu = $( '.toolMenuContainer' );\n $toolMenu.parent().scrollTop( 0 );\n $toolMenu.find( 'span:contains(\"Get Data\")' ).click();\n }\n }),\n\n // ........................................................................ external objects/MVC\n listenToGalaxy : function( galaxy ){\n this.listenTo( galaxy, {\n // when the galaxy_main iframe is loaded with a new page,\n // compare the url to the following list and if there's a match\n // pull the id from url and indicate in the history view that\n // the dataset with that id is the 'current'ly active dataset\n 'center-frame:load': function( data ){\n var pathToMatch = data.fullpath;\n var hdaId = null;\n var useToURLRegexMap = {\n 'display' : /datasets\\/([a-f0-9]+)\\/display/,\n 'edit' : /datasets\\/([a-f0-9]+)\\/edit/,\n 'report_error' : /dataset\\/errors\\?id=([a-f0-9]+)/,\n 'rerun' : /tool_runner\\/rerun\\?id=([a-f0-9]+)/,\n 'show_params' : /datasets\\/([a-f0-9]+)\\/show_params/,\n // no great way to do this here? (leave it in the dataset event handlers above?)\n // 'visualization' : 'visualization',\n };\n _.find( useToURLRegexMap, function( regex, use ){\n // grab the more specific match result (1), save, and use it as the find flag\n hdaId = _.result( pathToMatch.match( regex ), 1 );\n return hdaId;\n });\n // need to type mangle to go from web route to history contents\n this._setCurrentContentById( hdaId? ( 'dataset-' + hdaId ) : null );\n },\n // when the center panel is given a new view, clear the current indicator\n 'center-panel:load': function( view ){\n this._setCurrentContentById();\n }\n });\n },\n\n //TODO: remove quota meter from panel and remove this\n /** add listeners to an external quota meter (mvc/user/user-quotameter.js) */\n connectToQuotaMeter : function( quotaMeter ){\n if( !quotaMeter ){\n return this;\n }\n // show/hide the 'over quota message' in the history when the meter tells it to\n this.listenTo( quotaMeter, 'quota:over', this.showQuotaMessage );\n this.listenTo( quotaMeter, 'quota:under', this.hideQuotaMessage );\n\n // having to add this to handle re-render of hview while overquota (the above do not fire)\n this.on( 'rendered rendered:initial', function(){\n if( quotaMeter && quotaMeter.isOverQuota() ){\n this.showQuotaMessage();\n }\n });\n return this;\n },\n\n /** Override to preserve the quota message */\n clearMessages : function( ev ){\n var $target = !_.isUndefined( ev )?\n $( ev.currentTarget )\n :this.$messages().children( '[class$=\"message\"]' );\n $target = $target.not( '.quota-message' );\n $target.fadeOut( this.fxSpeed, function(){\n $( this ).remove();\n });\n return this;\n },\n\n /** Show the over quota message (which happens to be in the history panel).\n */\n showQuotaMessage : function(){\n var $msg = this.$( '.quota-message' );\n if( $msg.is( ':hidden' ) ){ $msg.slideDown( this.fxSpeed ); }\n },\n\n /** Hide the over quota message (which happens to be in the history panel).\n */\n hideQuotaMessage : function(){\n var $msg = this.$( '.quota-message' );\n if( !$msg.is( ':hidden' ) ){ $msg.slideUp( this.fxSpeed ); }\n },\n\n // ........................................................................ options menu\n //TODO: remove to batch\n /** unhide any hidden datasets */\n unhideHidden : function() {\n var self = this;\n if( confirm( _l( 'Really unhide all hidden datasets?' ) ) ){\n // get all hidden, regardless of deleted/purged\n return self.model.contents._filterAndUpdate(\n { visible: false, deleted: '', purged: '' },\n { visible : true }\n ).done( function(){\n // TODO: would be better to render these as they're unhidden instead of all at once\n if( !self.model.contents.includeHidden ){\n self.renderItems();\n }\n });\n }\n return jQuery.when();\n },\n\n /** delete any hidden datasets */\n deleteHidden : function() {\n var self = this;\n if( confirm( _l( 'Really delete all hidden datasets?' ) ) ){\n return self.model.contents._filterAndUpdate(\n // get all hidden, regardless of deleted/purged\n { visible: false, deleted: '', purged: '' },\n // both delete *and* unhide them\n { deleted : true, visible: true }\n );\n }\n return jQuery.when();\n },\n\n /** Return a string rep of the history */\n toString : function(){\n return 'CurrentHistoryView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nCurrentHistoryView.prototype.templates = (function(){\n\n var quotaMsgTemplate = BASE_MVC.wrapTemplate([\n '
                        ',\n _l( 'You are over your disk quota' ), '. ',\n _l( 'Tool execution is on hold until your disk usage drops below your allocated quota' ), '.',\n '
                        '\n ], 'history' );\n return _.extend( _.clone( _super.prototype.templates ), {\n quotaMsg : quotaMsgTemplate\n });\n\n}());\n\n\n//==============================================================================\n return {\n CurrentHistoryView : CurrentHistoryView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view-edit-current.js","define([\n \"mvc/history/history-view\",\n \"mvc/history/history-contents\",\n \"mvc/dataset/states\",\n \"mvc/history/hda-model\",\n \"mvc/history/hda-li-edit\",\n \"mvc/history/hdca-li-edit\",\n \"mvc/tag\",\n \"mvc/annotation\",\n \"mvc/collection/list-collection-creator\",\n \"mvc/collection/pair-collection-creator\",\n \"mvc/collection/list-of-pairs-collection-creator\",\n \"ui/fa-icon-button\",\n \"mvc/ui/popup-menu\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function(\n HISTORY_VIEW,\n HISTORY_CONTENTS,\n STATES,\n HDA_MODEL,\n HDA_LI_EDIT,\n HDCA_LI_EDIT,\n TAGS,\n ANNOTATIONS,\n LIST_COLLECTION_CREATOR,\n PAIR_COLLECTION_CREATOR,\n LIST_OF_PAIRS_COLLECTION_CREATOR,\n faIconButton,\n PopupMenu,\n BASE_MVC,\n _l\n){\n\n'use strict';\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\nvar _super = HISTORY_VIEW.HistoryView;\n// base class for history-view-edit-current and used as-is in history/view.mako\n/** @class Editable View/Controller for the history model.\n *\n * Allows:\n * (everything HistoryView allows)\n * changing the name\n * displaying and editing tags and annotations\n * multi-selection and operations on mulitple content items\n */\nvar HistoryViewEdit = _super.extend(\n/** @lends HistoryViewEdit.prototype */{\n\n /** class to use for constructing the HistoryDatasetAssociation views */\n HDAViewClass : HDA_LI_EDIT.HDAListItemEdit,\n /** class to use for constructing the HistoryDatasetCollectionAssociation views */\n HDCAViewClass : HDCA_LI_EDIT.HDCAListItemEdit,\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes\n */\n initialize : function( attributes ){\n attributes = attributes || {};\n _super.prototype.initialize.call( this, attributes );\n\n // ---- set up instance vars\n /** editor for tags - sub-view */\n this.tagsEditor = null;\n\n /** enable drag and drop - sub-view */\n this.dragItems = true;\n\n /** editor for annotations - sub-view */\n this.annotationEditor = null;\n\n /** allow user purge of dataset files? */\n this.purgeAllowed = attributes.purgeAllowed || false;\n\n // states/modes the panel can be in\n /** is the panel currently showing the dataset selection controls? */\n this.annotationEditorShown = attributes.annotationEditorShown || false;\n this.tagsEditorShown = attributes.tagsEditorShown || false;\n },\n\n /** Override to handle history as drag-drop target */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n return this.on({\n 'droptarget:drop': function( ev, data ){\n // process whatever was dropped and re-hide the drop target\n this.dataDropped( data );\n this.dropTargetOff();\n },\n 'view:attached view:removed': function(){\n this._renderCounts();\n },\n 'search:loading-progress': this._renderSearchProgress,\n 'search:searching': this._renderSearchFindings,\n });\n },\n\n // ------------------------------------------------------------------------ listeners\n /** listening for history and HDA events */\n _setUpModelListeners : function(){\n _super.prototype._setUpModelListeners.call( this );\n this.listenTo( this.model, 'change:size', this.updateHistoryDiskSize );\n return this;\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n this.listenTo( this.collection, {\n 'change:deleted': this._handleItemDeletedChange,\n 'change:visible': this._handleItemVisibleChange,\n 'change:purged' : function( model ){\n // hafta get the new nice-size w/o the purged model\n this.model.fetch();\n },\n // loading indicators for deleted/hidden\n 'fetching-deleted' : function( collection ){\n this.$( '> .controls .deleted-count' )\n .html( '' + _l( 'loading...' ) + '' );\n },\n 'fetching-hidden' : function( collection ){\n this.$( '> .controls .hidden-count' )\n .html( '' + _l( 'loading...' ) + '' );\n },\n 'fetching-deleted-done fetching-hidden-done' : this._renderCounts,\n });\n return this;\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** In this override, add tag and annotation editors and a btn to toggle the selectors */\n _buildNewRender : function(){\n // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n var $newRender = _super.prototype._buildNewRender.call( this );\n if( !this.model ){ return $newRender; }\n\n if( Galaxy && Galaxy.user && Galaxy.user.id && Galaxy.user.id === this.model.get( 'user_id' ) ){\n this._renderTags( $newRender );\n this._renderAnnotation( $newRender );\n }\n return $newRender;\n },\n\n /** Update the history size display (curr. upper right of panel). */\n updateHistoryDiskSize : function(){\n this.$( '.history-size' ).text( this.model.get( 'nice_size' ) );\n },\n\n /** override to render counts when the items are rendered */\n renderItems : function( $whereTo ){\n var views = _super.prototype.renderItems.call( this, $whereTo );\n if( !this.searchFor ){ this._renderCounts( $whereTo ); }\n return views;\n },\n\n /** override to show counts, what's deleted/hidden, and links to toggle those */\n _renderCounts : function( $whereTo ){\n $whereTo = $whereTo instanceof jQuery? $whereTo : this.$el;\n var html = this.templates.counts( this.model.toJSON(), this );\n return $whereTo.find( '> .controls .subtitle' ).html( html );\n },\n\n /** render the tags sub-view controller */\n _renderTags : function( $where ){\n var panel = this;\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.controls .tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n // show hide sub-view tag editors when this is shown/hidden\n onshow : function(){\n panel.toggleHDATagEditors( true, panel.fxSpeed );\n },\n onhide : function(){\n panel.toggleHDATagEditors( false, panel.fxSpeed );\n },\n $activator : faIconButton({\n title : _l( 'Edit history tags' ),\n classes : 'history-tag-btn',\n faIcon : 'fa-tags'\n }).appendTo( $where.find( '.controls .actions' ) )\n });\n },\n /** render the annotation sub-view controller */\n _renderAnnotation : function( $where ){\n var panel = this;\n this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n model : this.model,\n el : $where.find( '.controls .annotation-display' ),\n onshowFirstTime : function(){ this.render(); },\n // show hide sub-view view annotation editors when this is shown/hidden\n onshow : function(){\n panel.toggleHDAAnnotationEditors( true, panel.fxSpeed );\n },\n onhide : function(){\n panel.toggleHDAAnnotationEditors( false, panel.fxSpeed );\n },\n $activator : faIconButton({\n title : _l( 'Edit history annotation' ),\n classes : 'history-annotate-btn',\n faIcon : 'fa-comment'\n }).appendTo( $where.find( '.controls .actions' ) )\n });\n },\n\n /** Set up HistoryViewEdit js/widget behaviours\n * In this override, make the name editable\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n _super.prototype._setUpBehaviors.call( this, $where );\n if( !this.model ){ return; }\n\n // anon users shouldn't have access to any of the following\n if( ( !Galaxy.user || Galaxy.user.isAnonymous() )\n || ( Galaxy.user.id !== this.model.get( 'user_id' ) ) ){\n return;\n }\n\n var panel = this,\n nameSelector = '> .controls .name';\n $where.find( nameSelector )\n .attr( 'title', _l( 'Click to rename history' ) )\n .tooltip({ placement: 'bottom' })\n .make_text_editable({\n on_finish: function( newName ){\n var previousName = panel.model.get( 'name' );\n if( newName && newName !== previousName ){\n panel.$el.find( nameSelector ).text( newName );\n panel.model.save({ name: newName })\n .fail( function(){\n panel.$el.find( nameSelector ).text( panel.model.previous( 'name' ) );\n });\n } else {\n panel.$el.find( nameSelector ).text( previousName );\n }\n }\n });\n },\n\n /** return a new popup menu for choosing a multi selection action\n * ajax calls made for multiple datasets are queued\n */\n multiselectActions : function(){\n var panel = this,\n actions = [\n { html: _l( 'Hide datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.hide;\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Unhide datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.unhide;\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Delete datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype['delete'];\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Undelete datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.undelete;\n panel.getSelectedModels().ajaxQueue( action );\n }\n }\n ];\n if( panel.purgeAllowed ){\n actions.push({\n html: _l( 'Permanently delete datasets' ), func: function(){\n if( confirm( _l( 'This will permanently remove the data in your datasets. Are you sure?' ) ) ){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.purge;\n panel.getSelectedModels().ajaxQueue( action );\n }\n }\n });\n }\n actions = actions.concat( panel._collectionActions() );\n return actions;\n },\n\n /** */\n _collectionActions : function(){\n var panel = this;\n return [\n { html: _l( 'Build Dataset List' ), func: function() { panel.buildCollection( \"list\") }\n },\n // TODO: Only show quick pair if two things selected.\n { html: _l( 'Build Dataset Pair' ), func: function() { panel.buildCollection( \"paired\") }\n },\n { html: _l( 'Build List of Dataset Pairs' ), func: function() { panel.buildCollection( \"list:paired\" ) }\n },\n ];\n },\n\n buildCollection : function( collectionType, selection, hideSourceItems ) {\n var panel = this;\n var selection = selection || panel.getSelectedModels();\n var hideSourceItems = hideSourceItems || false;\n var createFunc;\n if( collectionType == \"list\" ) {\n createFunc = LIST_COLLECTION_CREATOR.createListCollection;\n } else if( collectionType == \"paired\" ) {\n createFunc = PAIR_COLLECTION_CREATOR.createPairCollection;\n } else if( collectionType == \"list:paired\" ) {\n createFunc = LIST_OF_PAIRS_COLLECTION_CREATOR.createListOfPairsCollection;\n } else {\n console.warn( \"Unknown collectionType encountered \" + collectionType );\n }\n createFunc( selection, hideSourceItems ).done( function() { panel.model.refresh() } );\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** In this override, add purgeAllowed and whether tags/annotation editors should be shown */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n _.extend( options, {\n purgeAllowed : this.purgeAllowed,\n tagsEditorShown : ( this.tagsEditor && !this.tagsEditor.hidden ),\n annotationEditorShown : ( this.annotationEditor && !this.annotationEditor.hidden )\n });\n return options;\n },\n\n /** If this item is deleted and we're not showing deleted items, remove the view\n * @param {Model} the item model to check\n */\n _handleItemDeletedChange : function( itemModel ){\n if( itemModel.get( 'deleted' ) ){\n this._handleItemDeletion( itemModel );\n } else {\n this._handleItemUndeletion( itemModel );\n }\n this._renderCounts();\n },\n\n _handleItemDeletion : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.deleted += 1;\n contentsShown.active -= 1;\n if( !this.model.contents.includeDeleted ){\n this.removeItemView( itemModel );\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n _handleItemUndeletion : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.deleted -= 1;\n if( !this.model.contents.includeDeleted ){\n contentsShown.active -= 1;\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n /** If this item is hidden and we're not showing hidden items, remove the view\n * @param {Model} the item model to check\n */\n _handleItemVisibleChange : function( itemModel ){\n if( itemModel.hidden() ){\n this._handleItemHidden( itemModel );\n } else {\n this._handleItemUnhidden( itemModel );\n }\n this._renderCounts();\n },\n\n _handleItemHidden : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.hidden += 1;\n contentsShown.active -= 1;\n if( !this.model.contents.includeHidden ){\n this.removeItemView( itemModel );\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n _handleItemUnhidden : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.hidden -= 1;\n if( !this.model.contents.includeHidden ){\n contentsShown.active -= 1;\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n /** toggle the visibility of each content's tagsEditor applying all the args sent to this function */\n toggleHDATagEditors : function( showOrHide, speed ){\n _.each( this.views, function( view ){\n if( view.tagsEditor ){\n view.tagsEditor.toggle( showOrHide, speed );\n }\n });\n },\n\n /** toggle the visibility of each content's annotationEditor applying all the args sent to this function */\n toggleHDAAnnotationEditors : function( showOrHide, speed ){\n _.each( this.views, function( view ){\n if( view.annotationEditor ){\n view.annotationEditor.toggle( showOrHide, speed );\n }\n });\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .show-selectors-btn' : 'toggleSelectors',\n 'click .toggle-deleted-link' : function( ev ){ this.toggleShowDeleted(); },\n 'click .toggle-hidden-link' : function( ev ){ this.toggleShowHidden(); }\n }),\n\n // ------------------------------------------------------------------------ search\n _renderSearchProgress : function( limit, offset ){\n var stop = limit + offset;\n return this.$( '> .controls .subtitle' ).html([\n '',\n _l( 'Searching ' ), stop, '/', this.model.contentsShown(),\n ''\n ].join(''));\n },\n\n /** override to display number found in subtitle */\n _renderSearchFindings : function(){\n this.$( '> .controls .subtitle' ).html([\n _l( 'Found' ), this.views.length\n ].join(' '));\n return this;\n },\n\n // ------------------------------------------------------------------------ as drop target\n /** turn all the drag and drop handlers on and add some help text above the drop area */\n dropTargetOn : function(){\n if( this.dropTarget ){ return this; }\n this.dropTarget = true;\n\n //TODO: to init\n var dropHandlers = {\n 'dragenter' : _.bind( this.dragenter, this ),\n 'dragover' : _.bind( this.dragover, this ),\n 'dragleave' : _.bind( this.dragleave, this ),\n 'drop' : _.bind( this.drop, this )\n };\n\n var $dropTarget = this._renderDropTarget();\n this.$list().before([ this._renderDropTargetHelp(), $dropTarget ]);\n for( var evName in dropHandlers ){\n if( dropHandlers.hasOwnProperty( evName ) ){\n //console.debug( evName, dropHandlers[ evName ] );\n $dropTarget.on( evName, dropHandlers[ evName ] );\n }\n }\n return this;\n },\n\n /** render a box to serve as a 'drop here' area on the history */\n _renderDropTarget : function(){\n this.$( '.history-drop-target' ).remove();\n return $( '
                        ' ).addClass( 'history-drop-target' );\n },\n\n /** tell the user how it works */\n _renderDropTargetHelp : function(){\n this.$( '.history-drop-target-help' ).remove();\n return $( '
                        ' ).addClass( 'history-drop-target-help' )\n .text( _l( 'Drag datasets here to copy them to the current history' ) );\n },\n\n /** shut down drag and drop event handlers and remove drop target */\n dropTargetOff : function(){\n if( !this.dropTarget ){ return this; }\n //this.log( 'dropTargetOff' );\n this.dropTarget = false;\n var dropTarget = this.$( '.history-drop-target' ).get(0);\n for( var evName in this._dropHandlers ){\n if( this._dropHandlers.hasOwnProperty( evName ) ){\n dropTarget.off( evName, this._dropHandlers[ evName ] );\n }\n }\n this.$( '.history-drop-target' ).remove();\n this.$( '.history-drop-target-help' ).remove();\n return this;\n },\n /** toggle the target on/off */\n dropTargetToggle : function(){\n if( this.dropTarget ){\n this.dropTargetOff();\n } else {\n this.dropTargetOn();\n }\n return this;\n },\n\n dragenter : function( ev ){\n //console.debug( 'dragenter:', this, ev );\n ev.preventDefault();\n ev.stopPropagation();\n this.$( '.history-drop-target' ).css( 'border', '2px solid black' );\n },\n dragover : function( ev ){\n ev.preventDefault();\n ev.stopPropagation();\n },\n dragleave : function( ev ){\n //console.debug( 'dragleave:', this, ev );\n ev.preventDefault();\n ev.stopPropagation();\n this.$( '.history-drop-target' ).css( 'border', '1px dashed black' );\n },\n /** when (text) is dropped try to parse as json and trigger an event */\n drop : function( ev ){\n ev.preventDefault();\n //ev.stopPropagation();\n\n var self = this;\n var dataTransfer = ev.originalEvent.dataTransfer;\n var data = dataTransfer.getData( \"text\" );\n\n dataTransfer.dropEffect = 'move';\n try {\n data = JSON.parse( data );\n } catch( err ){\n self.warn( 'error parsing JSON from drop:', data );\n }\n\n self.trigger( 'droptarget:drop', ev, data, self );\n return false;\n },\n\n /** handler that copies data into the contents */\n dataDropped : function( data ){\n var self = this;\n // HDA: dropping will copy it to the history\n if( _.isObject( data ) && data.model_class === 'HistoryDatasetAssociation' && data.id ){\n if( self.contents.currentPage !== 0 ){\n return self.contents.fetchPage( 0 )\n .then( function(){\n return self.model.contents.copy( data.id );\n });\n }\n return self.model.contents.copy( data.id );\n }\n return jQuery.when();\n },\n\n // ........................................................................ misc\n /** Return a string rep of the history */\n toString : function(){\n return 'HistoryViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n//------------------------------------------------------------------------------ TEMPLATES\nHistoryViewEdit.prototype.templates = (function(){\n\n var countsTemplate = BASE_MVC.wrapTemplate([\n '<% var shown = Math.max( view.views.length, history.contents_active.active ) %>',\n '<% if( shown ){ %>',\n '',\n '<%- shown %> ', _l( 'shown' ),\n '',\n '<% } %>',\n\n '<% if( history.contents_active.deleted ){ %>',\n '',\n '<% if( view.model.contents.includeDeleted ){ %>',\n '',\n _l( 'hide deleted' ),\n '',\n '<% } else { %>',\n '<%- history.contents_active.deleted %> ',\n '',\n _l( 'deleted' ),\n '',\n '<% } %>',\n '',\n '<% } %>',\n\n '<% if( history.contents_active.hidden ){ %>',\n '',\n '<% if( view.model.contents.includeHidden ){ %>',\n '',\n _l( 'hide hidden' ),\n '',\n '<% } else { %>',\n '<%- history.contents_active.hidden %> ',\n '',\n _l( 'hidden' ),\n '',\n '<% } %>',\n '',\n '<% } %>',\n ], 'history' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n counts : countsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n HistoryViewEdit : HistoryViewEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view-edit.js","define([\n \"mvc/list/list-view\",\n \"mvc/history/history-model\",\n \"mvc/history/history-contents\",\n \"mvc/history/history-preferences\",\n \"mvc/history/hda-li\",\n \"mvc/history/hdca-li\",\n \"mvc/user/user-model\",\n \"mvc/ui/error-modal\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/search-input\"\n], function(\n LIST_VIEW,\n HISTORY_MODEL,\n HISTORY_CONTENTS,\n HISTORY_PREFS,\n HDA_LI,\n HDCA_LI,\n USER,\n ERROR_MODAL,\n faIconButton,\n BASE_MVC,\n _l\n){\n'use strict';\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class non-editable, read-only View/Controller for a history model.\n * Allows:\n * changing the loaded history\n * displaying data, info, and download\n * tracking history attrs: size, tags, annotations, name, etc.\n * Does not allow:\n * changing the name\n */\nvar _super = LIST_VIEW.ModelListPanel;\nvar HistoryView = _super.extend(\n/** @lends HistoryView.prototype */{\n _logNamespace : 'history',\n\n /** class to use for constructing the HDA views */\n HDAViewClass : HDA_LI.HDAListItemView,\n /** class to use for constructing the HDCA views */\n HDCAViewClass : HDCA_LI.HDCAListItemView,\n /** class to used for constructing collection of sub-view models */\n collectionClass : HISTORY_CONTENTS.HistoryContents,\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'contents',\n\n tagName : 'div',\n className : _super.prototype.className + ' history-panel',\n\n /** string to display when the collection is empty */\n emptyMsg : _l( 'This history is empty' ),\n /** displayed when no items match the search terms */\n noneFoundMsg : _l( 'No matching datasets found' ),\n /** string used for search placeholder */\n searchPlaceholder : _l( 'search datasets' ),\n\n /** @type {Number} ms to wait after history load to fetch/decorate hdcas with element_count */\n FETCH_COLLECTION_COUNTS_DELAY : 2000,\n\n // ......................................................................... SET UP\n /** Set up the view, bind listeners.\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n // ---- instance vars\n // control contents/behavior based on where (and in what context) the panel is being used\n /** where should pages from links be displayed? (default to new tab/window) */\n this.linkTarget = attributes.linkTarget || '_blank';\n },\n\n /** create and return a collection for when none is initially passed */\n _createDefaultCollection : function(){\n // override\n return new this.collectionClass([], { history: this.model });\n },\n\n /** In this override, clear the update timer on the model */\n freeModel : function(){\n _super.prototype.freeModel.call( this );\n if( this.model ){\n this.model.clearUpdateTimeout();\n }\n return this;\n },\n\n /** create any event listeners for the panel\n * @fires: rendered:initial on the first render\n * @fires: empty-history when switching to a history with no contents or creating a new history\n */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n this.on({\n error : function( model, xhr, options, msg, details ){\n this.errorHandler( model, xhr, options, msg, details );\n },\n 'loading-done' : function(){\n var self = this;\n // after the initial load, decorate with more time consuming fields (like HDCA element_counts)\n _.delay( function(){\n self.model.contents.fetchCollectionCounts();\n }, self.FETCH_COLLECTION_COUNTS_DELAY );\n },\n 'views:ready view:attached view:removed' : function( view ){\n this._renderSelectButton();\n },\n 'view:attached' : function( view ){\n this.scrollTo(0);\n },\n });\n // this.on( 'all', function(){ console.debug( arguments ); });\n },\n\n // ------------------------------------------------------------------------ loading history/hda models\n /** load the history with the given id then it's contents, sending ajax options to both */\n loadHistory : function( historyId, options, contentsOptions ){\n contentsOptions = _.extend( contentsOptions || { silent: true });\n this.info( 'loadHistory:', historyId, options, contentsOptions );\n var self = this;\n self.setModel( new HISTORY_MODEL.History({ id : historyId }) );\n\n contentsOptions.silent = true;\n self.trigger( 'loading' );\n return self.model\n .fetchWithContents( options, contentsOptions )\n .always( function(){\n self.render();\n self.trigger( 'loading-done' );\n });\n },\n\n /** convenience alias to the model. Updates the item list only (not the history) */\n refreshContents : function( options ){\n if( this.model ){\n return this.model.refresh( options );\n }\n // may have callbacks - so return an empty promise\n return $.when();\n },\n\n /** Override to reset web storage when the id changes (since it needs the id) */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n return this.listenTo( this.collection, {\n // 'all' : function(){ console.log( this.collection + ':', arguments ); },\n 'fetching-more' : function(){\n this._toggleContentsLoadingIndicator( true );\n this.$emptyMessage().hide();\n },\n 'fetching-more-done': function(){ this._toggleContentsLoadingIndicator( false ); },\n });\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n _showLoadingIndicator : function( msg, speed, callback ){\n var $indicator = $( '
                        ' );\n this.$el.html( $indicator.text( msg ).slideDown( !_.isUndefined( speed )? speed : this.fxSpeed ) );\n },\n\n /** hide the loading indicator */\n _hideLoadingIndicator : function( speed ){\n // make speed a bit slower to compensate for slow rendering of up to 500 contents\n this.$( '.loading-indicator' ).slideUp( !_.isUndefined( speed )? speed : ( this.fxSpeed + 200 ), function(){\n $( this ).remove();\n });\n },\n\n /** In this override, add a btn to toggle the selectors */\n _buildNewRender : function(){\n var $newRender = _super.prototype._buildNewRender.call( this );\n this._renderSelectButton( $newRender );\n return $newRender;\n },\n\n /** button for starting select mode */\n _renderSelectButton : function( $where ){\n $where = $where || this.$el;\n // do not render selector option if no actions\n if( !this.multiselectActions().length ){\n return null;\n }\n // do not render (and remove even) if nothing to select\n if( !this.views.length ){\n this.hideSelectors();\n $where.find( '.controls .actions .show-selectors-btn' ).remove();\n return null;\n }\n // don't bother rendering if there's one already\n var $existing = $where.find( '.controls .actions .show-selectors-btn' );\n if( $existing.length ){\n return $existing;\n }\n\n return faIconButton({\n title : _l( 'Operations on multiple datasets' ),\n classes : 'show-selectors-btn',\n faIcon : 'fa-check-square-o'\n }).prependTo( $where.find( '.controls .actions' ) );\n },\n\n /** override to avoid showing intial empty message using contents_active */\n _renderEmptyMessage : function( $whereTo ){\n var self = this;\n var $emptyMsg = self.$emptyMessage( $whereTo );\n\n var empty = self.model.get( 'contents_active' ).active <= 0;\n if( empty ){\n return $emptyMsg.empty().append( self.emptyMsg ).show();\n\n } else if( self.searchFor && self.model.contents.haveSearchDetails() && !self.views.length ){\n return $emptyMsg.empty().append( self.noneFoundMsg ).show();\n }\n $emptyMsg.hide();\n return $();\n },\n\n /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n $scrollContainer : function( $where ){\n // override or set via attributes.$scrollContainer\n return this.$list( $where );\n },\n\n // ------------------------------------------------------------------------ subviews\n _toggleContentsLoadingIndicator : function( show ){\n if( !show ){\n this.$list().find( '.contents-loading-indicator' ).remove();\n } else {\n this.$list().html( '
                        '\n + '
                        ' );\n }\n },\n\n /** override to render pagination also */\n renderItems: function( $whereTo ){\n // console.log( this + '.renderItems-----------------', new Date() );\n $whereTo = $whereTo || this.$el;\n var self = this;\n var $list = self.$list( $whereTo );\n\n // TODO: bootstrap hack to remove orphaned tooltips\n $( '.tooltip' ).remove();\n\n $list.empty();\n self.views = [];\n\n var models = self._filterCollection();\n if( models.length ){\n self._renderPagination( $whereTo );\n self.views = self._renderSomeItems( models, $list );\n } else {\n // TODO: consolidate with _renderPagination above by (???) passing in models/length?\n $whereTo.find( '> .controls .list-pagination' ).empty();\n }\n self._renderEmptyMessage( $whereTo ).toggle( !models.length );\n\n self.trigger( 'views:ready', self.views );\n return self.views;\n },\n\n /** render pagination controls if not searching and contents says we're paginating */\n _renderPagination: function( $whereTo ){\n var $paginationControls = $whereTo.find( '> .controls .list-pagination' );\n if( this.searchFor || !this.model.contents.shouldPaginate() ) return $paginationControls.empty();\n\n $paginationControls.html( this.templates.pagination({\n // pagination is 1-based for the user\n current : this.model.contents.currentPage + 1,\n last : this.model.contents.getLastPage() + 1,\n }, this ));\n $paginationControls.find( 'select.pages' ).tooltip();\n return $paginationControls;\n },\n\n /** render a subset of the entire collection (client-side pagination) */\n _renderSomeItems: function( models, $list ){\n var self = this;\n var views = [];\n $list.append( models.map( function( m ){\n var view = self._createItemView( m );\n views.push( view );\n return self._renderItemView$el( view );\n }));\n return views;\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** in this override, check if the contents would also display based on includeDeleted/hidden */\n _filterItem : function( model ){\n var self = this;\n var contents = self.model.contents;\n return ( contents.includeHidden || !model.hidden() )\n && ( contents.includeDeleted || !model.isDeletedOrPurged() )\n && ( _super.prototype._filterItem.call( self, model ) );\n },\n\n /** In this override, since history contents are mixed,\n * get the appropo view class based on history_content_type\n */\n _getItemViewClass : function( model ){\n var contentType = model.get( \"history_content_type\" );\n switch( contentType ){\n case 'dataset':\n return this.HDAViewClass;\n case 'dataset_collection':\n return this.HDCAViewClass;\n }\n throw new TypeError( 'Unknown history_content_type: ' + contentType );\n },\n\n /** in this override, add a linktarget, and expand if id is in web storage */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n expanded : this.model.contents.storage.isExpanded( model.id ),\n hasUser : this.model.ownedByCurrUser()\n });\n },\n\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n //TODO: send from content view: this.model.collection.storage.addExpanded\n // maintain a list of items whose bodies are expanded\n return panel.listenTo( view, {\n 'expanded': function( v ){\n panel.model.contents.storage.addExpanded( v.model );\n },\n 'collapsed': function( v ){\n panel.model.contents.storage.removeExpanded( v.model );\n }\n });\n },\n\n /** override to remove expandedIds from webstorage */\n collapseAll : function(){\n this.model.contents.storage.clearExpanded();\n _super.prototype.collapseAll.call( this );\n },\n\n // ------------------------------------------------------------------------ selection\n /** Override to correctly set the historyId of the new collection */\n getSelectedModels : function(){\n var collection = _super.prototype.getSelectedModels.call( this );\n collection.historyId = this.collection.historyId;\n return collection;\n },\n\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .show-selectors-btn' : 'toggleSelectors',\n 'click > .controls .prev' : '_clickPrevPage',\n 'click > .controls .next' : '_clickNextPage',\n 'change > .controls .pages' : '_changePageSelect',\n // allow (error) messages to be clicked away\n 'click .messages [class$=message]' : 'clearMessages',\n }),\n\n _clickPrevPage : function( ev ){\n this.model.clearUpdateTimeout();\n this.model.contents.fetchPrevPage();\n },\n\n _clickNextPage : function( ev ){\n this.model.clearUpdateTimeout();\n this.model.contents.fetchNextPage();\n },\n\n _changePageSelect : function( ev ){\n this.model.clearUpdateTimeout();\n var page = $( ev.currentTarget ).val();\n this.model.contents.fetchPage( page );\n },\n\n /** Toggle and store the deleted visibility and re-render items\n * @returns {Boolean} new setting\n */\n toggleShowDeleted : function( show, options ){\n show = ( show !== undefined )?( show ):( !this.model.contents.includeDeleted );\n var self = this;\n var contents = self.model.contents;\n contents.setIncludeDeleted( show, options );\n self.trigger( 'show-deleted', show );\n\n contents.fetchCurrentPage({ renderAll: true });\n return show;\n },\n\n /** Toggle and store whether to render explicity hidden contents\n * @returns {Boolean} new setting\n */\n toggleShowHidden : function( show, store, options ){\n // console.log( 'toggleShowHidden', show, store );\n show = ( show !== undefined )?( show ):( !this.model.contents.includeHidden );\n var self = this;\n var contents = self.model.contents;\n contents.setIncludeHidden( show, options );\n self.trigger( 'show-hidden', show );\n\n contents.fetchCurrentPage({ renderAll: true });\n return show;\n },\n\n /** On the first search, if there are no details - load them, then search */\n _firstSearch : function( searchFor ){\n var self = this;\n var inputSelector = '> .controls .search-input';\n this.log( 'onFirstSearch', searchFor );\n\n // if the contents already have enough details to search, search and return now\n if( self.model.contents.haveSearchDetails() ){\n self.searchItems( searchFor );\n return;\n }\n\n // otherwise, load the details progressively here\n self.$( inputSelector ).searchInput( 'toggle-loading' );\n // set this now so that only results will show during progress\n self.searchFor = searchFor;\n var xhr = self.model.contents.progressivelyFetchDetails({ silent: true })\n .progress( function( response, limit, offset ){\n self.renderItems();\n self.trigger( 'search:loading-progress', limit, offset );\n })\n .always( function(){\n self.$el.find( inputSelector ).searchInput( 'toggle-loading' );\n })\n .done( function(){\n self.searchItems( searchFor, 'force' );\n });\n },\n\n /** clear the search filters and show all views that are normally shown */\n clearSearch : function( searchFor ){\n var self = this;\n if( !self.searchFor ) return self;\n //self.log( 'onSearchClear', self );\n self.searchFor = '';\n self.trigger( 'search:clear', self );\n self.$( '> .controls .search-query' ).val( '' );\n // NOTE: silent + render prevents collection update event with merge only\n // - which causes an empty page due to event handler above\n self.model.contents.fetchCurrentPage({ silent: true })\n .done( function(){\n self.renderItems();\n });\n return self;\n },\n\n // ........................................................................ error handling\n /** Event handler for errors (from the panel, the history, or the history's contents)\n * Alternately use two strings for model and xhr to use custom message and title (respectively)\n * @param {Model or View} model the (Backbone) source of the error\n * @param {XMLHTTPRequest} xhr any ajax obj. assoc. with the error\n * @param {Object} options the options map commonly used with bbone ajax\n */\n errorHandler : function( model, xhr, options ){\n //TODO: to mixin or base model\n // interrupted ajax or no connection\n if( xhr && xhr.status === 0 && xhr.readyState === 0 ){\n // return ERROR_MODAL.offlineErrorModal();\n // fail silently\n return;\n }\n // otherwise, leave something to report in the console\n this.error( model, xhr, options );\n // and feedback to a modal\n // if sent two strings (and possibly details as 'options'), use those as message and title\n if( _.isString( model ) && _.isString( xhr ) ){\n var message = model;\n var title = xhr;\n return ERROR_MODAL.errorModal( message, title, options );\n }\n // bad gateway\n // TODO: possibly to global handler\n if( xhr && xhr.status === 502 ){\n return ERROR_MODAL.badGatewayErrorModal();\n }\n return ERROR_MODAL.ajaxErrorModal( model, xhr, options );\n },\n\n /** Remove all messages from the panel. */\n clearMessages : function( ev ){\n var $target = !_.isUndefined( ev )?\n $( ev.currentTarget )\n :this.$messages().children( '[class$=\"message\"]' );\n $target.fadeOut( this.fxSpeed, function(){\n $( this ).remove();\n });\n return this;\n },\n\n // ........................................................................ scrolling\n /** Scrolls the panel to show the content sub-view with the given hid.\n * @param {Integer} hid the hid of item to scroll into view\n * @returns {HistoryView} the panel\n */\n scrollToHid : function( hid ){\n return this.scrollToItem( _.first( this.viewsWhereModel({ hid: hid }) ) );\n },\n\n // ........................................................................ misc\n /** utility for adding -st, -nd, -rd, -th to numbers */\n ordinalIndicator : function( number ){\n var numStr = number + '';\n switch( numStr.charAt( numStr.length - 1 )){\n case '1': return numStr + 'st';\n case '2': return numStr + 'nd';\n case '3': return numStr + 'rd';\n default : return numStr + 'th';\n }\n },\n\n /** Return a string rep of the history */\n toString : function(){\n return 'HistoryView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nHistoryView.prototype.templates = (function(){\n\n var mainTemplate = BASE_MVC.wrapTemplate([\n // temp container\n '
                        ',\n '
                        ',\n '
                          ',\n '
                          ',\n '
                          '\n ]);\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                          ',\n '
                          ',\n '
                          <%- history.name %>
                          ',\n '
                          ',\n '
                          ',\n '
                          <%- history.nice_size %>
                          ',\n\n '
                          ',\n\n '
                          ',\n '<% if( history.deleted && history.purged ){ %>',\n '
                          ',\n _l( 'This history has been purged and deleted' ),\n '
                          ',\n '<% } else if( history.deleted ){ %>',\n '
                          ',\n _l( 'This history has been deleted' ),\n '
                          ',\n '<% } else if( history.purged ){ %>',\n '
                          ',\n _l( 'This history has been purged' ),\n '
                          ',\n '<% } %>',\n\n '<% if( history.message ){ %>',\n // should already be localized\n '
                          messagesmall\">',\n '<%= history.message.text %>',\n '
                          ',\n '<% } %>',\n '
                          ',\n\n // add tags and annotations\n '
                          ',\n '
                          ',\n\n '
                          ',\n '
                          ',\n '
                          ',\n\n '
                          ',\n '
                          ',\n '',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ], 'history' );\n\n var paginationTemplate = BASE_MVC.wrapTemplate([\n '',\n '',\n '',\n ], 'pages' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n el : mainTemplate,\n controls : controlsTemplate,\n pagination : paginationTemplate,\n });\n}());\n\n\n//==============================================================================\n return {\n HistoryView: HistoryView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view.js","define([\n \"mvc/ui/popup-menu\",\n \"mvc/history/copy-dialog\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"mvc/webhooks\"\n], function( PopupMenu, historyCopyDialog, BASE_MVC, _l, Webhooks ){\n\n'use strict';\n\n// ============================================================================\nvar menu = [\n {\n html : _l( 'History Lists' ),\n header : true\n },\n {\n html : _l( 'Saved Histories' ),\n href : 'histories/list',\n target : '_top'\n\n },\n {\n html : _l( 'Histories Shared with Me' ),\n href : 'histories/list_shared',\n target : '_top'\n },\n {\n html : _l( 'Current History' ),\n header : true,\n anon : true\n },\n {\n html : _l( 'Create New' ),\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel ){\n Galaxy.currHistoryPanel.createNewHistory();\n }\n },\n },\n {\n html : _l( 'Copy History' ),\n func : function() {\n historyCopyDialog( Galaxy.currHistoryPanel.model )\n .done( function(){\n Galaxy.currHistoryPanel.loadCurrentHistory();\n });\n },\n },\n {\n html : _l( 'Share or Publish' ),\n href : 'history/sharing',\n },\n {\n html : _l( 'Show Structure' ),\n href : 'history/display_structured',\n anon : true,\n },\n {\n html : _l( 'Extract Workflow' ),\n href : 'workflow/build_from_current_history',\n },\n {\n html : _l( 'Delete' ),\n anon : true,\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really delete the current history?' ) ) ){\n galaxy_main.window.location.href = 'history/delete?id=' + Galaxy.currHistoryPanel.model.id;\n }\n },\n },\n {\n html : _l( 'Delete Permanently' ),\n purge : true,\n anon : true,\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel\n && confirm( _l( 'Really delete the current history permanently? This cannot be undone.' ) ) ){\n galaxy_main.window.location.href = 'history/delete?purge=True&id=' + Galaxy.currHistoryPanel.model.id;\n }\n },\n },\n\n\n {\n html : _l( 'Dataset Actions' ),\n header : true,\n anon : true\n },\n {\n html : _l( 'Copy Datasets' ),\n href : 'dataset/copy_datasets',\n },\n {\n html : _l( 'Dataset Security' ),\n href : 'root/history_set_default_permissions',\n },\n {\n html : _l( 'Resume Paused Jobs' ),\n href : 'history/resume_paused_jobs?current=True',\n anon : true,\n },\n {\n html : _l( 'Collapse Expanded Datasets' ),\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel ){\n Galaxy.currHistoryPanel.collapseAll();\n }\n },\n },\n {\n html : _l( 'Unhide Hidden Datasets' ),\n anon : true,\n func : function() {\n // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really unhide all hidden datasets?' ) ) ){\n $.post(Galaxy.root + \"history/adjust_hidden\",\n { 'user_action' : 'unhide' },\n function(){Galaxy.currHistoryPanel.loadCurrentHistory();});\n }\n },\n },\n {\n html : _l( 'Delete Hidden Datasets' ),\n anon : true,\n func : function() {\n // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really delete all hidden datasets?' ) ) ){\n $.post(Galaxy.root + \"history/adjust_hidden\",\n { 'user_action' : 'delete' },\n function(){Galaxy.currHistoryPanel.loadCurrentHistory();});\n }\n },\n },\n {\n html : _l( 'Purge Deleted Datasets' ),\n confirm : _l( 'Really delete all deleted datasets permanently? This cannot be undone.' ),\n href : 'history/purge_deleted_datasets',\n purge : true,\n anon : true,\n },\n\n\n {\n html : _l( 'Downloads' ),\n header : true\n },\n {\n html : _l( 'Export Tool Citations' ),\n href : 'history/citations',\n anon : true,\n },\n {\n html : _l( 'Export History to File' ),\n href : 'history/export_archive?preview=True',\n anon : true,\n },\n\n {\n html : _l( 'Other Actions' ),\n header : true\n },\n {\n html : _l( 'Import from File' ),\n href : 'history/import_archive',\n }\n];\n\n// Webhooks\nWebhooks.add({\n url: 'api/webhooks/history-menu/all',\n async: false, // (hypothetically) slows down the performance\n callback: function(webhooks) {\n var webhooks_menu = [];\n\n $.each(webhooks.models, function(index, model) {\n var webhook = model.toJSON();\n if (webhook.activate) {\n webhooks_menu.push({\n html : _l( webhook.config.title ),\n // func: function() {},\n anon : true\n });\n }\n });\n\n if (webhooks_menu.length > 0) {\n webhooks_menu.unshift({\n html : _l( 'Webhooks' ),\n header : true\n });\n $.merge(menu, webhooks_menu);\n }\n }\n});\n\n\nfunction buildMenu( isAnon, purgeAllowed, urlRoot ){\n return _.clone( menu ).filter( function( menuOption ){\n if( isAnon && !menuOption.anon ){\n return false;\n }\n if( !purgeAllowed && menuOption.purge ){\n return false;\n }\n\n //TODO:?? hard-coded galaxy_main\n if( menuOption.href ){\n menuOption.href = urlRoot + menuOption.href;\n menuOption.target = menuOption.target || 'galaxy_main';\n }\n\n if( menuOption.confirm ){\n menuOption.func = function(){\n if( confirm( menuOption.confirm ) ){\n galaxy_main.location = menuOption.href;\n }\n };\n }\n return true;\n });\n}\n\nvar create = function( $button, options ){\n options = options || {};\n var isAnon = options.anonymous === undefined? true : options.anonymous,\n purgeAllowed = options.purgeAllowed || false,\n menu = buildMenu( isAnon, purgeAllowed, Galaxy.root );\n //console.debug( 'menu:', menu );\n return new PopupMenu( $button, menu );\n};\n\n\n// ============================================================================\n return create;\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/options-menu.js","/** Renders the collection uploader rows */\ndefine( [ 'utils/utils', 'mvc/upload/upload-model', 'mvc/upload/upload-settings', 'mvc/ui/ui-popover', 'mvc/ui/ui-select' ],\nfunction( Utils, UploadModel, UploadSettings, Popover, Select ) {\n return Backbone.View.extend({\n /** Dictionary of upload states and associated icons */\n status_classes : {\n init : 'upload-icon-button fa fa-trash-o',\n queued : 'upload-icon fa fa-spinner fa-spin',\n running : 'upload-icon fa fa-spinner fa-spin',\n success : 'upload-icon-button fa fa-check',\n error : 'upload-icon-button fa fa-exclamation-triangle'\n },\n\n initialize: function( app, options ) {\n var self = this;\n this.app = app;\n this.model = options.model;\n this.setElement( this._template( options.model ) );\n this.$mode = this.$( '.upload-mode' );\n this.$title = this.$( '.upload-title-extended' );\n this.$text = this.$( '.upload-text' );\n this.$size = this.$( '.upload-size' );\n this.$info_text = this.$( '.upload-info-text' );\n this.$info_progress = this.$( '.upload-info-progress' );\n this.$text_content = this.$( '.upload-text-content' );\n this.$symbol = this.$( '.upload-symbol' );\n this.$progress_bar = this.$( '.upload-progress-bar' );\n this.$percentage = this.$( '.upload-percentage' );\n\n // append popup to settings icon\n this.settings = new Popover.View({\n title : 'Upload configuration',\n container : this.$( '.upload-settings' ),\n placement : 'bottom'\n });\n\n // identify default genome and extension values\n var default_genome = this.app.select_genome.value();\n var default_extension = this.app.select_extension.value();\n\n // handle click event\n this.$symbol.on('click', function() { self._removeRow(); });\n\n // handle text editing event\n this.$text_content.on( 'change input', function( e ) {\n self.model.set( { 'url_paste': $( e.target ).val(),\n 'file_size': $( e.target ).val().length } );\n });\n\n // model events\n this.listenTo( this.model, 'change:percentage', function() { self._refreshPercentage() } );\n this.listenTo( this.model, 'change:status', function() { self._refreshStatus() } );\n this.listenTo( this.model, 'change:info', function() { self._refreshInfo() } );\n this.listenTo( this.model, 'change:file_size', function() { self._refreshFileSize() } );\n this.listenTo( this.model, 'remove', function() { self.remove() } );\n this.app.collection.on('reset', function() { self.remove() } );\n },\n\n render: function() {\n var options = this.model.attributes;\n this.$title.html( _.escape( options.file_name ) );\n this.$size.html( Utils.bytesToString ( options.file_size ) );\n this.$mode.removeClass().addClass( 'upload-mode' ).addClass( 'text-primary' );\n if ( options.file_mode == 'new' ) {\n this.$text.css( { 'width' : this.$el.width() - 16 + 'px', 'top' : this.$el.height() - 8 + 'px' } ).show();\n this.$el.height( this.$el.height() - 8 + this.$text.height() + 16 );\n this.$mode.addClass( 'fa fa-edit' );\n } else if ( options.file_mode == 'local' ) {\n this.$mode.addClass( 'fa fa-laptop' );\n } else if ( options.file_mode == 'ftp' ) {\n this.$mode.addClass( 'fa fa-folder-open-o' );\n }\n },\n\n /** Refresh info text */\n _refreshInfo: function() {\n var info = this.model.get( 'info' );\n if ( info ) {\n this.$info_text.html( 'Failed: ' + info ).show();\n } else {\n this.$info_text.hide();\n }\n },\n\n /** Refresh percentage status */\n _refreshPercentage : function() {\n var percentage = parseInt( this.model.get( 'percentage' ) );\n this.$progress_bar.css( { width : percentage + '%' } );\n this.$percentage.html( percentage != 100 ? percentage + '%' : 'Adding to history...' );\n },\n\n /** Refresh status */\n _refreshStatus : function() {\n var status = this.model.get( 'status' );\n this.$symbol.removeClass().addClass( 'upload-symbol' ).addClass( this.status_classes[ status ] );\n this.model.set( 'enabled', status == 'init' );\n var enabled = this.model.get( 'enabled' );\n this.$text_content.attr( 'disabled', !enabled );\n if ( status == 'success' ) {\n this.$el.addClass( 'success' );\n this.$percentage.html( '100%' );\n }\n if ( status == 'error' ) {\n this.$el.addClass( 'danger' );\n this.$info_progress.hide();\n }\n },\n\n /** Refresh file size */\n _refreshFileSize: function() {\n this.$size.html( Utils.bytesToString ( this.model.get( 'file_size' ) ) );\n },\n\n /** Remove row */\n _removeRow: function() {\n if ( [ 'init', 'success', 'error' ].indexOf( this.model.get( 'status' ) ) !== -1 ) {\n this.app.collection.remove( this.model );\n }\n },\n\n /** Attach file info popup */\n _showSettings : function() {\n if ( !this.settings.visible ) {\n this.settings.empty();\n this.settings.append( ( new UploadSettings( this ) ).$el );\n this.settings.show();\n } else {\n this.settings.hide();\n }\n },\n\n /** View template */\n _template: function( options ) {\n return '
                          ' +\n '' + '' + '' + '' + '' + '';\n\t },\n\t\n\t /** Template of table */\n\t _templateTable: function () {\n\t return 'Available files: ' + '' + '' + '  ' + '' + '' + '' + '
                          ' ).append( $checkbox ) )\n .append( $( '' ).append( parameter.title ) ) )\n });\n this.$cover[ this.model.get( 'enabled' ) && 'hide' || 'show' ]();\n }\n });\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/upload/upload-settings.js","/*\n galaxy upload plugins - requires FormData and XMLHttpRequest\n*/\n;(function($){\n // add event properties\n jQuery.event.props.push(\"dataTransfer\");\n\n /**\n Posts file data to the API\n */\n $.uploadpost = function (config) {\n // parse options\n var cnf = $.extend({}, {\n data : {},\n success : function() {},\n error : function() {},\n progress : function() {},\n url : null,\n maxfilesize : 2048,\n error_filesize : 'File exceeds 2GB. Please use a FTP client.',\n error_default : 'Please make sure the file is available.',\n error_server : 'Upload request failed.',\n error_login : 'Uploads require you to log in.'\n }, config);\n\n // link data\n var data = cnf.data;\n\n // check errors\n if (data.error_message) {\n cnf.error(data.error_message);\n return;\n }\n\n // construct form data\n var form = new FormData();\n for (var key in data.payload) {\n form.append(key, data.payload[key]);\n }\n\n // add files to submission\n var sizes = 0;\n for (var key in data.files) {\n var d = data.files[key];\n form.append(d.name, d.file, d.file.name);\n sizes += d.file.size;\n }\n\n // check file size, unless it's an ftp file\n if (sizes > 1048576 * cnf.maxfilesize) {\n cnf.error(cnf.error_filesize);\n return;\n }\n\n // prepare request\n xhr = new XMLHttpRequest();\n xhr.open('POST', cnf.url, true);\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.setRequestHeader('Cache-Control', 'no-cache');\n xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n\n // captures state changes\n xhr.onreadystatechange = function() {\n // check for request completed, server connection closed\n if (xhr.readyState == xhr.DONE) {\n // parse response\n var response = null;\n if (xhr.responseText) {\n try {\n response = jQuery.parseJSON(xhr.responseText);\n } catch (e) {\n response = xhr.responseText;\n }\n }\n // pass any error to the error option\n if (xhr.status < 200 || xhr.status > 299) {\n var text = xhr.statusText;\n if (xhr.status == 403) {\n text = cnf.error_login;\n } else if (xhr.status == 0) {\n text = cnf.error_server;\n } else if (!text) {\n text = cnf.error_default;\n }\n cnf.error(text + ' (' + xhr.status + ')');\n } else {\n cnf.success(response);\n }\n }\n }\n\n // prepare upload progress\n xhr.upload.addEventListener('progress', function(e) {\n if (e.lengthComputable) {\n cnf.progress(Math.round((e.loaded * 100) / e.total));\n }\n }, false);\n\n // send request\n Galaxy.emit.debug('uploadbox::uploadpost()', 'Posting following data.', cnf);\n xhr.send(form);\n }\n\n /**\n Handles the upload events drag/drop etc.\n */\n $.fn.uploadinput = function(options) {\n // initialize\n var el = this;\n var opts = $.extend({}, {\n ondragover : function() {},\n ondragleave : function() {},\n onchange : function() {},\n multiple : false\n }, options);\n\n // append hidden upload field\n var $input = $('');\n el.append($input.change(function (e) {\n opts.onchange(e.target.files);\n $(this).val('');\n }));\n\n // drag/drop events\n el.on('drop', function (e) {\n opts.ondragleave(e);\n if(e.dataTransfer) {\n opts.onchange(e.dataTransfer.files);\n e.preventDefault();\n }\n });\n el.on('dragover', function (e) {\n e.preventDefault();\n opts.ondragover(e);\n });\n el.on('dragleave', function (e) {\n e.stopPropagation();\n opts.ondragleave(e);\n });\n\n // exports\n return {\n dialog: function () {\n $input.trigger('click');\n }\n }\n }\n\n /**\n Handles the upload queue and events such as drag/drop etc.\n */\n $.fn.uploadbox = function(options) {\n // parse options\n var opts = $.extend({}, {\n dragover : function() {},\n dragleave : function() {},\n announce : function(d) {},\n initialize : function(d) {},\n progress : function(d, m) {},\n success : function(d, m) {},\n error : function(d, m) { alert(m); },\n complete : function() {}\n }, options);\n\n // file queue\n var queue = {};\n\n // queue index/length counter\n var queue_index = 0;\n var queue_length = 0;\n\n // indicates if queue is currently running\n var queue_running = false;\n var queue_stop = false;\n\n // element\n var uploadinput = $(this).uploadinput({\n multiple : true,\n onchange : function(files) { add(files); },\n ondragover : options.ondragover,\n ondragleave : options.ondragleave\n });\n\n // add new files to upload queue\n function add(files) {\n if (files && files.length && !queue_running) {\n var current_index = queue_index;\n _.each(files, function(file, key) {\n if (file.mode !== 'new' && _.filter(queue, function(f) {\n return f.name === file.name && f.size === file.size;\n }).length) {\n file.duplicate = true;\n }\n });\n _.each(files, function(file) {\n if (!file.duplicate) {\n var index = String(queue_index++);\n queue[index] = file;\n opts.announce(index, queue[index]);\n queue_length++;\n }\n });\n return current_index;\n }\n }\n\n // remove file from queue\n function remove(index) {\n if (queue[index]) {\n delete queue[index];\n queue_length--;\n }\n }\n\n // process an upload, recursive\n function process() {\n // validate\n if (queue_length == 0 || queue_stop) {\n queue_stop = false;\n queue_running = false;\n opts.complete();\n return;\n } else {\n queue_running = true;\n }\n\n // get an identifier from the queue\n var index = -1;\n for (var key in queue) {\n index = key;\n break;\n }\n\n // get current file from queue\n var file = queue[index];\n\n // remove from queue\n remove(index)\n\n // create and submit data\n $.uploadpost({\n url : opts.url,\n data : opts.initialize(index),\n success : function(message) { opts.success(index, message); process();},\n error : function(message) { opts.error(index, message); process();},\n progress : function(percentage) { opts.progress(index, percentage); }\n });\n }\n\n /*\n public interface\n */\n\n // open file browser for selection\n function select() {\n uploadinput.dialog();\n }\n\n // remove all entries from queue\n function reset(index) {\n for (index in queue) {\n remove(index);\n }\n }\n\n // initiate upload process\n function start() {\n if (!queue_running) {\n queue_running = true;\n process();\n }\n }\n\n // stop upload process\n function stop() {\n queue_stop = true;\n }\n\n // set options\n function configure(options) {\n opts = $.extend({}, opts, options);\n return opts;\n }\n\n // verify browser compatibility\n function compatible() {\n return window.File && window.FormData && window.XMLHttpRequest && window.FileList;\n }\n\n // export functions\n return {\n 'select' : select,\n 'add' : add,\n 'remove' : remove,\n 'start' : start,\n 'stop' : stop,\n 'reset' : reset,\n 'configure' : configure,\n 'compatible' : compatible\n };\n }\n})(jQuery);\n\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/utils/uploadbox.js","define([\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function( baseMVC, _l ){\n// =============================================================================\n/** A view on any model that has a 'annotation' attribute\n */\nvar AnnotationEditor = Backbone.View\n .extend( baseMVC.LoggableMixin )\n .extend( baseMVC.HiddenUntilActivatedViewMixin ).extend({\n\n tagName : 'div',\n className : 'annotation-display',\n\n /** Set up listeners, parse options */\n initialize : function( options ){\n options = options || {};\n this.tooltipConfig = options.tooltipConfig || { placement: 'bottom' };\n //console.debug( this, options );\n // only listen to the model only for changes to annotations\n this.listenTo( this.model, 'change:annotation', function(){\n this.render();\n });\n this.hiddenUntilActivated( options.$activator, options );\n },\n\n /** Build the DOM elements, call select to on the created input, and set up behaviors */\n render : function(){\n var view = this;\n this.$el.html( this._template() );\n\n //TODO: handle empties better\n this.$annotation().make_text_editable({\n use_textarea: true,\n on_finish: function( newAnnotation ){\n view.$annotation().text( newAnnotation );\n view.model.save({ annotation: newAnnotation }, { silent: true })\n .fail( function(){\n view.$annotation().text( view.model.previous( 'annotation' ) );\n });\n }\n });\n return this;\n },\n\n /** @returns {String} the html text used to build the view's DOM */\n _template : function(){\n var annotation = this.model.get( 'annotation' );\n return [\n //TODO: make prompt optional\n '',\n // set up initial tags by adding as CSV to input vals (necc. to init select2)\n '
                          ',\n _.escape( annotation ),\n '
                          '\n ].join( '' );\n },\n\n /** @returns {jQuery} the main element for this view */\n $annotation : function(){\n return this.$el.find( '.annotation' );\n },\n\n /** shut down event listeners and remove this view's DOM */\n remove : function(){\n this.$annotation.off();\n this.stopListening( this.model );\n Backbone.View.prototype.remove.call( this );\n },\n\n /** string rep */\n toString : function(){ return [ 'AnnotationEditor(', this.model + '', ')' ].join(''); }\n});\n// =============================================================================\nreturn {\n AnnotationEditor : AnnotationEditor\n};\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/annotation.js","define([\n 'libs/underscore',\n 'libs/backbone',\n 'mvc/base-mvc',\n], function( _, Backbone, BASE_MVC ){\n'use strict';\n\n//=============================================================================\n/**\n * A Collection that can be limited/offset/re-ordered/filtered.\n * @type {Backbone.Collection}\n */\nvar ControlledFetchCollection = Backbone.Collection.extend({\n\n /** call setOrder on initialization to build the comparator based on options */\n initialize : function( models, options ){\n Backbone.Collection.prototype.initialize.call( this, models, options );\n this.setOrder( options.order || this.order, { silent: true });\n },\n\n /** set up to track order changes and re-sort when changed */\n _setUpListeners : function(){\n return this.on({\n 'changed-order' : this.sort\n });\n },\n\n /** override to provide order and offsets based on instance vars, set limit if passed,\n * and set allFetched/fire 'all-fetched' when xhr returns\n */\n fetch : function( options ){\n options = this._buildFetchOptions( options );\n // console.log( 'fetch options:', options );\n return Backbone.Collection.prototype.fetch.call( this, options );\n },\n\n /** build ajax data/parameters from options */\n _buildFetchOptions : function( options ){\n // note: we normally want options passed in to override the defaults built here\n // so most of these fns will generate defaults\n options = _.clone( options ) || {};\n var self = this;\n\n // jquery ajax option; allows multiple q/qv for filters (instead of 'q[]')\n options.traditional = true;\n\n // options.data\n // we keep limit, offset, etc. in options *as well as move it into data* because:\n // - it makes fetch calling convenient to add it to a single options map (instead of as mult. args)\n // - it allows the std. event handlers (for fetch, etc.) to have access\n // to the pagination options too\n // (i.e. this.on( 'sync', function( options ){ if( options.limit ){ ... } }))\n // however, when we send to xhr/jquery we copy them to data also so that they become API query params\n options.data = options.data || self._buildFetchData( options );\n // console.log( 'data:', options.data );\n\n // options.data.filters --> options.data.q, options.data.qv\n var filters = this._buildFetchFilters( options );\n // console.log( 'filters:', filters );\n if( !_.isEmpty( filters ) ){\n _.extend( options.data, this._fetchFiltersToAjaxData( filters ) );\n }\n // console.log( 'data:', options.data );\n return options;\n },\n\n /** Build the dictionary to send to fetch's XHR as data */\n _buildFetchData : function( options ){\n var defaults = {};\n if( this.order ){ defaults.order = this.order; }\n return _.defaults( _.pick( options, this._fetchParams ), defaults );\n },\n\n /** These attribute keys are valid params to fetch/API-index */\n _fetchParams : [\n /** model dependent string to control the order of models returned */\n 'order',\n /** limit the number of models returned from a fetch */\n 'limit',\n /** skip this number of models when fetching */\n 'offset',\n /** what series of attributes to return (model dependent) */\n 'view',\n /** individual keys to return for the models (see api/histories.index) */\n 'keys'\n ],\n\n /** add any needed filters here based on collection state */\n _buildFetchFilters : function( options ){\n // override\n return _.clone( options.filters || {} );\n },\n\n /** Convert dictionary filters to qqv style arrays */\n _fetchFiltersToAjaxData : function( filters ){\n // return as a map so ajax.data can extend from it\n var filterMap = {\n q : [],\n qv : []\n };\n _.each( filters, function( v, k ){\n // don't send if filter value is empty\n if( v === undefined || v === '' ){ return; }\n // json to python\n if( v === true ){ v = 'True'; }\n if( v === false ){ v = 'False'; }\n if( v === null ){ v = 'None'; }\n // map to k/v arrays (q/qv)\n filterMap.q.push( k );\n filterMap.qv.push( v );\n });\n return filterMap;\n },\n\n /** override to reset allFetched flag to false */\n reset : function( models, options ){\n this.allFetched = false;\n return Backbone.Collection.prototype.reset.call( this, models, options );\n },\n\n // ........................................................................ order\n order : null,\n\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : {\n 'update_time' : BASE_MVC.buildComparator( 'update_time', { ascending: false }),\n 'update_time-asc' : BASE_MVC.buildComparator( 'update_time', { ascending: true }),\n 'create_time' : BASE_MVC.buildComparator( 'create_time', { ascending: false }),\n 'create_time-asc' : BASE_MVC.buildComparator( 'create_time', { ascending: true }),\n },\n\n /** set the order and comparator for this collection then sort with the new order\n * @event 'changed-order' passed the new order and the collection\n */\n setOrder : function( order, options ){\n options = options || {};\n var collection = this;\n var comparator = collection.comparators[ order ];\n if( _.isUndefined( comparator ) ){ throw new Error( 'unknown order: ' + order ); }\n // if( _.isUndefined( comparator ) ){ return; }\n if( comparator === collection.comparator ){ return; }\n\n var oldOrder = collection.order;\n collection.order = order;\n collection.comparator = comparator;\n\n if( !options.silent ){\n collection.trigger( 'changed-order', options );\n }\n return collection;\n },\n\n});\n\n\n//=============================================================================\n/**\n *\n */\nvar PaginatedCollection = ControlledFetchCollection.extend({\n\n /** @type {Number} limit used for each page's fetch */\n limitPerPage : 500,\n\n initialize : function( models, options ){\n ControlledFetchCollection.prototype.initialize.call( this, models, options );\n this.currentPage = options.currentPage || 0;\n },\n\n getTotalItemCount : function(){\n return this.length;\n },\n\n shouldPaginate : function(){\n return this.getTotalItemCount() >= this.limitPerPage;\n },\n\n getLastPage : function(){\n return Math.floor( this.getTotalItemCount() / this.limitPerPage );\n },\n\n getPageCount : function(){\n return this.getLastPage() + 1;\n },\n\n getPageLimitOffset : function( pageNum ){\n pageNum = this.constrainPageNum( pageNum );\n return {\n limit : this.limitPerPage,\n offset: pageNum * this.limitPerPage\n };\n },\n\n constrainPageNum : function( pageNum ){\n return Math.max( 0, Math.min( pageNum, this.getLastPage() ));\n },\n\n /** fetch the next page of data */\n fetchPage : function( pageNum, options ){\n var self = this;\n pageNum = self.constrainPageNum( pageNum );\n self.currentPage = pageNum;\n options = _.defaults( options || {}, self.getPageLimitOffset( pageNum ) );\n\n self.trigger( 'fetching-more' );\n return self.fetch( options )\n .always( function(){\n self.trigger( 'fetching-more-done' );\n });\n },\n\n fetchCurrentPage : function( options ){\n return this.fetchPage( this.currentPage, options );\n },\n\n fetchPrevPage : function( options ){\n return this.fetchPage( this.currentPage - 1, options );\n },\n\n fetchNextPage : function( options ){\n return this.fetchPage( this.currentPage + 1, options );\n },\n});\n\n\n//=============================================================================\n/**\n * A Collection that will load more elements without reseting.\n */\nvar InfinitelyScrollingCollection = ControlledFetchCollection.extend({\n\n /** @type {Number} limit used for the first fetch (or a reset) */\n limitOnFirstFetch : null,\n /** @type {Number} limit used for each subsequent fetch */\n limitPerFetch : 100,\n\n initialize : function( models, options ){\n ControlledFetchCollection.prototype.initialize.call( this, models, options );\n /** @type {Integer} number of contents to return from the first fetch */\n this.limitOnFirstFetch = options.limitOnFirstFetch || this.limitOnFirstFetch;\n /** @type {Integer} limit for every fetch after the first */\n this.limitPerFetch = options.limitPerFetch || this.limitPerFetch;\n /** @type {Boolean} are all contents fetched? */\n this.allFetched = false;\n /** @type {Integer} what was the offset of the last content returned */\n this.lastFetched = options.lastFetched || 0;\n },\n\n /** build ajax data/parameters from options */\n _buildFetchOptions : function( options ){\n // options (options for backbone.fetch and jquery.ajax generally)\n // backbone option; false here to make fetching an addititive process\n options.remove = options.remove || false;\n return ControlledFetchCollection.prototype._buildFetchOptions.call( this, options );\n },\n\n /** fetch the first 'page' of data */\n fetchFirst : function( options ){\n // console.log( 'ControlledFetchCollection.fetchFirst:', options );\n options = options? _.clone( options ) : {};\n this.allFetched = false;\n this.lastFetched = 0;\n return this.fetchMore( _.defaults( options, {\n reset : true,\n limit : this.limitOnFirstFetch,\n }));\n },\n\n /** fetch the next page of data */\n fetchMore : function( options ){\n // console.log( 'ControlledFetchCollection.fetchMore:', options );\n options = _.clone( options || {} );\n var collection = this;\n\n // console.log( 'fetchMore, options.reset:', options.reset );\n if( ( !options.reset && collection.allFetched ) ){\n return jQuery.when();\n }\n\n // TODO: this fails in the edge case where\n // the first fetch offset === limit (limit 4, offset 4, collection.length 4)\n options.offset = options.reset? 0 : ( options.offset || collection.lastFetched );\n var limit = options.limit = options.limit || collection.limitPerFetch || null;\n // console.log( 'fetchMore, limit:', limit, 'offset:', options.offset );\n\n collection.trigger( 'fetching-more' );\n return collection.fetch( options )\n .always( function(){\n collection.trigger( 'fetching-more-done' );\n })\n // maintain allFetched flag and trigger if all were fetched this time\n .done( function _postFetchMore( fetchedData ){\n var numFetched = _.isArray( fetchedData )? fetchedData.length : 0;\n collection.lastFetched += numFetched;\n // console.log( 'fetchMore, lastFetched:', collection.lastFetched );\n // anything less than a full page means we got all there is to get\n if( !limit || numFetched < limit ){\n collection.allFetched = true;\n collection.trigger( 'all-fetched', this );\n }\n }\n );\n },\n\n /** fetch all the collection */\n fetchAll : function( options ){\n // whitelist options to prevent allowing limit/offset/filters\n // (use vanilla fetch instead)\n options = options || {};\n var self = this;\n options = _.pick( options, 'silent' );\n options.filters = {};\n return self.fetch( options ).done( function( fetchData ){\n self.allFetched = true;\n self.trigger( 'all-fetched', self );\n });\n },\n});\n\n\n//==============================================================================\n return {\n ControlledFetchCollection : ControlledFetchCollection,\n PaginatedCollection : PaginatedCollection,\n InfinitelyScrollingCollection : InfinitelyScrollingCollection,\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/base/controlled-fetch-collection.js","define([\n], function( ){\n\n/* For presentation-related functionality shared across collection creators.\n Particularily overlapping functionality related to name processing and help.\n*/\nvar CollectionCreatorMixin = {\n\n /** add (or clear if clear is truthy) a validation warning to the DOM element described in what */\n _validationWarning : function( what, clear ){\n var VALIDATION_CLASS = 'validation-warning';\n if( what === 'name' ){\n what = this.$( '.collection-name' ).add( this.$( '.collection-name-prompt' ) );\n this.$( '.collection-name' ).focus().select();\n }\n if( clear ){\n what = what || this.$( '.' + VALIDATION_CLASS );\n what.removeClass( VALIDATION_CLASS );\n } else {\n what.addClass( VALIDATION_CLASS );\n }\n },\n\n _changeHideOriginals: function( ev ) {\n this.hideOriginals = this.$( '.hide-originals' ).prop(\"checked\");\n },\n\n // ........................................................................ footer\n /** handle a collection name change */\n _changeName : function( ev ){\n this._validationWarning( 'name', !!this._getName() );\n },\n\n /** check for enter key press when in the collection name and submit */\n _nameCheckForEnter : function( ev ){\n if( ev.keyCode === 13 && !this.blocking ){\n this._clickCreate();\n }\n },\n\n /** get the current collection name */\n _getName : function(){\n return _.escape( this.$( '.collection-name' ).val() );\n },\n\n // ........................................................................ header\n /** expand help */\n _clickMoreHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).addClass( 'expanded' );\n this.$( '.more-help' ).hide();\n },\n /** collapse help */\n _clickLessHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).removeClass( 'expanded' );\n this.$( '.more-help' ).show();\n },\n /** toggle help */\n _toggleHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).toggleClass( 'expanded' );\n this.$( '.more-help' ).toggle();\n },\n\n /** show an alert on the top of the interface containing message (alertClass is bootstrap's alert-*) */\n _showAlert : function( message, alertClass ){\n alertClass = alertClass || 'alert-danger';\n this.$( '.main-help' ).hide();\n this.$( '.header .alert' )\n .attr( 'class', 'alert alert-dismissable' ).addClass( alertClass ).show()\n .find( '.alert-message' ).html( message );\n },\n /** hide the alerts at the top */\n _hideAlert : function( message ){\n this.$( '.main-help' ).show();\n this.$( '.header .alert' ).hide();\n },\n\n _cancelCreate: function( ev ){\n if( typeof this.oncancel === 'function' ){\n this.oncancel.call( this );\n }\n },\n\n /** attempt to create the current collection */\n _clickCreate : function( ev ){\n var name = this._getName();\n if( !name ){\n this._validationWarning( 'name' );\n } else if( !this.blocking ){\n this.createList( name );\n }\n },\n\n _setUpCommonSettings : function( attributes ) {\n this.hideOriginals = attributes.defaultHideSourceItems || false;\n },\n\n /** render the footer, completion controls, and cancel controls */\n _renderFooter : function( speed, callback ){\n var instance = this;\n var $footer = this.$( '.footer' ).empty().html( this.templates.footer() );\n _.each( this.footerSettings, function( property, selector ) {\n this.$( selector ).prop( 'checked', instance[ property ] );\n });\n if( typeof this.oncancel === 'function' ){\n this.$( '.cancel-create.btn' ).show();\n }\n return $footer;\n },\n\n _creatorTemplates: {\n main : _.template([\n '
                          ',\n '
                          ',\n '
                          '\n ].join('')),\n }\n\n}\n\n//==============================================================================\n return {\n CollectionCreatorMixin: CollectionCreatorMixin\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/base-creator.js","define([\n \"mvc/list/list-view\",\n \"mvc/collection/collection-model\",\n \"mvc/collection/collection-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_VIEW, DC_MODEL, DC_LI, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class non-editable, read-only View/Controller for a dataset collection.\n */\nvar _super = LIST_VIEW.ModelListPanel;\nvar CollectionView = _super.extend(\n/** @lends CollectionView.prototype */{\n //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n _logNamespace : logNamespace,\n\n className : _super.prototype.className + ' dataset-collection-panel',\n\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_LI.DatasetDCEListItemView,\n /** sub view class used for nested collections */\n NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView,\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'elements',\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n this.linkTarget = attributes.linkTarget || '_blank';\n\n this.hasUser = attributes.hasUser;\n /** A stack of panels that currently cover or hide this panel */\n this.panelStack = [];\n /** The text of the link to go back to the panel containing this one */\n this.parentName = attributes.parentName;\n /** foldout or drilldown */\n this.foldoutStyle = attributes.foldoutStyle || 'foldout';\n this.downloadUrl = this.model.attributes.url + '/download';\n },\n\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var panel = this;\n panel.log( '_queueNewRender:', $newRender, speed );\n\n // TODO: jquery@1.12 doesn't change display when the elem has display: flex\n // this causes display: block for those elems after the use of show/hide animations\n // animations are removed from this view for now until fixed\n panel._swapNewRender( $newRender );\n panel.trigger( 'rendered', panel );\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** In this override, use model.getVisibleContents */\n _filterCollection : function(){\n //TODO: should *not* be model.getVisibleContents - visibility is not model related\n return this.model.getVisibleContents();\n },\n\n /** override to return proper view class based on element_type */\n _getItemViewClass : function( model ){\n //this.debug( this + '._getItemViewClass:', model );\n //TODO: subclasses use DCEViewClass - but are currently unused - decide\n switch( model.get( 'element_type' ) ){\n case 'hda':\n return this.DatasetDCEViewClass;\n case 'dataset_collection':\n return this.NestedDCDCEViewClass;\n }\n throw new TypeError( 'Unknown element type:', model.get( 'element_type' ) );\n },\n\n /** override to add link target and anon */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n hasUser : this.hasUser,\n //TODO: could move to only nested: list:paired\n foldoutStyle : this.foldoutStyle\n });\n },\n\n // ------------------------------------------------------------------------ collection sub-views\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n\n // use pub-sub to: handle drilldown expansion and collapse\n panel.listenTo( view, {\n 'expanded:drilldown': function( v, drilldown ){\n this._expandDrilldownPanel( drilldown );\n },\n 'collapsed:drilldown': function( v, drilldown ){\n this._collapseDrilldownPanel( drilldown );\n }\n });\n return this;\n },\n\n /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n _expandDrilldownPanel : function( drilldown ){\n this.panelStack.push( drilldown );\n // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n this.$( '> .controls' ).add( this.$list() ).hide();\n drilldown.parentName = this.model.get( 'name' );\n this.$el.append( drilldown.render().$el );\n },\n\n /** Handle drilldown close by freeing the panel and re-rendering this panel */\n _collapseDrilldownPanel : function( drilldown ){\n this.panelStack.pop();\n this.render();\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : {\n 'click .navigation .back' : 'close'\n },\n\n /** close/remove this collection panel */\n close : function( event ){\n this.remove();\n this.trigger( 'close' );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'CollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nCollectionView.prototype.templates = (function(){\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                          ',\n '',\n\n '
                          ',\n '
                          <%- collection.name || collection.element_identifier %>
                          ',\n '
                          ',\n '<% if( collection.collection_type === \"list\" ){ %>',\n _l( 'a list of datasets' ),\n '<% } else if( collection.collection_type === \"paired\" ){ %>',\n _l( 'a pair of datasets' ),\n '<% } else if( collection.collection_type === \"list:paired\" ){ %>',\n _l( 'a list of paired datasets' ),\n '<% } else if( collection.collection_type === \"list:list\" ){ %>',\n _l( 'a list of dataset lists' ),\n '<% } %>',\n '
                          ',\n '
                          ',\n\n '
                          ',\n\n '',\n '
                          ',\n ], 'collection' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n controls : controlsTemplate\n });\n}());\n\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListCollectionView = CollectionView.extend(\n/** @lends ListCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_LI.DatasetDCEListItemView,\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar PairCollectionView = ListCollectionView.extend(\n/** @lends PairCollectionView.prototype */{\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'PairCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListOfPairsCollectionView = CollectionView.extend(\n/** @lends ListOfPairsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_LI.NestedDCDCEListItemView.extend({\n foldoutPanelClass : PairCollectionView\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfPairsCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a list of lists dataset collection. */\nvar ListOfListsCollectionView = CollectionView.extend({\n\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_LI.NestedDCDCEListItemView.extend({\n foldoutPanelClass : PairCollectionView\n }),\n\n /** string rep */\n toString : function(){\n return 'ListOfListsCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//==============================================================================\n return {\n CollectionView : CollectionView,\n ListCollectionView : ListCollectionView,\n PairCollectionView : PairCollectionView,\n ListOfPairsCollectionView : ListOfPairsCollectionView,\n ListOfListsCollectionView : ListOfListsCollectionView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-view.js","define([\n \"mvc/dataset/states\",\n \"mvc/dataset/dataset-li\",\n \"mvc/tag\",\n \"mvc/annotation\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, DATASET_LI, TAGS, ANNOTATIONS, faIconButton, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar _super = DATASET_LI.DatasetListItemView;\n/** @class Editing view for DatasetAssociation.\n */\nvar DatasetListItemEdit = _super.extend(\n/** @lends DatasetListItemEdit.prototype */{\n\n /** set up: options */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n this.hasUser = attributes.hasUser;\n\n /** allow user purge of dataset files? */\n this.purgeAllowed = attributes.purgeAllowed || false;\n\n //TODO: move to HiddenUntilActivatedViewMixin\n /** should the tags editor be shown or hidden initially? */\n this.tagsEditorShown = attributes.tagsEditorShown || false;\n /** should the tags editor be shown or hidden initially? */\n this.annotationEditorShown = attributes.annotationEditorShown || false;\n },\n\n // ......................................................................... titlebar actions\n /** In this override, add the other two primary actions: edit and delete */\n _renderPrimaryActions : function(){\n var actions = _super.prototype._renderPrimaryActions.call( this );\n if( this.model.get( 'state' ) === STATES.NOT_VIEWABLE ){\n return actions;\n }\n // render the display, edit attr and delete icon-buttons\n return _super.prototype._renderPrimaryActions.call( this ).concat([\n this._renderEditButton(),\n this._renderDeleteButton()\n ]);\n },\n\n //TODO: move titleButtons into state renderers, remove state checks in the buttons\n\n /** Render icon-button to edit the attributes (format, permissions, etc.) this dataset. */\n _renderEditButton : function(){\n // don't show edit while uploading, in-accessible\n // DO show if in error (ala previous history panel)\n if( ( this.model.get( 'state' ) === STATES.DISCARDED )\n || ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var purged = this.model.get( 'purged' ),\n deleted = this.model.get( 'deleted' ),\n editBtnData = {\n title : _l( 'Edit attributes' ),\n href : Galaxy.root + 'datasets/edit?dataset_id=' + this.model.attributes.id,\n faIcon : 'fa-pencil',\n classes : 'edit-btn'\n };\n // disable if purged or deleted and explain why in the tooltip\n if( deleted || purged ){\n editBtnData.disabled = true;\n if( purged ){\n editBtnData.title = _l( 'Cannot edit attributes of datasets removed from disk' );\n } else if( deleted ){\n editBtnData.title = _l( 'Undelete dataset to edit attributes' );\n }\n\n // disable if still uploading or new\n } else if( _.contains( [ STATES.UPLOAD, STATES.NEW ], this.model.get( 'state' ) ) ){\n editBtnData.disabled = true;\n editBtnData.title = _l( 'This dataset is not yet editable' );\n }\n return faIconButton( editBtnData );\n },\n\n /** Render icon-button to delete this hda. */\n _renderDeleteButton : function(){\n // don't show delete if...\n if( ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var self = this,\n deletedAlready = this.model.isDeletedOrPurged();\n return faIconButton({\n title : !deletedAlready? _l( 'Delete' ) : _l( 'Dataset is already deleted' ),\n disabled : deletedAlready,\n faIcon : 'fa-times',\n classes : 'delete-btn',\n onclick : function() {\n // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n self.$el.find( '.icon-btn.delete-btn' ).trigger( 'mouseout' );\n self.model[ 'delete' ]();\n }\n });\n },\n\n // ......................................................................... details\n /** In this override, add tags and annotations controls, make the ? dbkey a link to editing page */\n _renderDetails : function(){\n //TODO: generalize to be allow different details for each state\n var $details = _super.prototype._renderDetails.call( this ),\n state = this.model.get( 'state' );\n\n if( !this.model.isDeletedOrPurged() && _.contains([ STATES.OK, STATES.FAILED_METADATA ], state ) ){\n this._renderTags( $details );\n this._renderAnnotation( $details );\n this._makeDbkeyEditLink( $details );\n }\n\n this._setUpBehaviors( $details );\n return $details;\n },\n\n /**************************************************************************\n * Render help button to show tool help text without rerunning the tool.\n * Issue #2100\n */\n _renderToolHelpButton : function() {\n var datasetID = this.model.attributes.dataset_id;\n var jobID = this.model.attributes.creating_job;\n var self = this;\n\n var parseToolBuild = function(data) {\n var helpString = '
                          '\n if (data.name && data.help){\n helpString += 'Tool help for ' + data.name + '
                          ';\n helpString += data.help;\n } else {\n helpString += 'Tool help is unavailable for this dataset.
                          ';\n }\n helpString += '
                          ';\n self.$el.find( '.details' ).append($.parseHTML(helpString));\n };\n var parseToolID = function(data) {\n $.ajax({\n url: Galaxy.root + 'api/tools/' + data.tool_id + '/build'\n }).done(function(data){\n parseToolBuild(data);\n }).fail(function(){\n parseToolBuild({})\n });\n };\n if (Galaxy.user.id === null){\n return null\n }\n return faIconButton({\n title: _l('Tool Help'),\n classes: 'icon-btn',\n href: '#',\n faIcon: 'fa-question',\n onclick: function() {\n var divString = 'thdiv-' + datasetID;\n if (self.$el.find(\".toolhelp\").length > 0){\n self.$el.find(\".toolhelp\").toggle();\n } else {\n $.ajax({\n url: Galaxy.root + 'api/jobs/' + jobID\n }).done(function(data){\n parseToolID(data);\n }).fail(function(){\n console.log('Failed at recovering job information from the Galaxy API for job id \"' + jobID + '\".');\n });\n }\n }\n });\n },\n //*************************************************************************\n\n /** Add less commonly used actions in the details section based on state */\n _renderSecondaryActions : function(){\n var actions = _super.prototype._renderSecondaryActions.call( this );\n switch( this.model.get( 'state' ) ){\n case STATES.UPLOAD:\n case STATES.NOT_VIEWABLE:\n return actions;\n case STATES.ERROR:\n // error button comes first\n actions.unshift( this._renderErrButton() );\n return actions.concat([ this._renderRerunButton(), this._renderToolHelpButton() ]);\n case STATES.OK:\n case STATES.FAILED_METADATA:\n return actions.concat([ this._renderRerunButton(), this._renderVisualizationsButton(), this._renderToolHelpButton() ]);\n }\n return actions.concat([ this._renderRerunButton(), this._renderToolHelpButton() ]);\n },\n\n /** Render icon-button to report an error on this dataset to the galaxy admin. */\n _renderErrButton : function(){\n return faIconButton({\n title : _l( 'View or report this error' ),\n href : this.model.urls.report_error,\n classes : 'report-error-btn',\n target : this.linkTarget,\n faIcon : 'fa-bug'\n });\n },\n\n /** Render icon-button to re-run the job that created this dataset. */\n _renderRerunButton : function(){\n var creating_job = this.model.get( 'creating_job' );\n if( this.model.get( 'rerunnable' ) ){\n return faIconButton({\n title : _l( 'Run this job again' ),\n href : this.model.urls.rerun,\n classes : 'rerun-btn',\n target : this.linkTarget,\n faIcon : 'fa-refresh',\n onclick : function( ev ) {\n ev.preventDefault();\n Galaxy.router.push( '/', { job_id : creating_job } );\n }\n });\n }\n },\n\n /** Render an icon-button or popupmenu of links based on the applicable visualizations */\n _renderVisualizationsButton : function(){\n //TODO: someday - lazyload visualizations\n var visualizations = this.model.get( 'visualizations' );\n if( ( this.model.isDeletedOrPurged() )\n || ( !this.hasUser )\n || ( !this.model.hasData() )\n || ( _.isEmpty( visualizations ) ) ){\n return null;\n }\n if( !_.isObject( visualizations[0] ) ){\n this.warn( 'Visualizations have been switched off' );\n return null;\n }\n\n var $visualizations = $( this.templates.visualizations( visualizations, this ) );\n //HACK: need to re-write those directed at galaxy_main with linkTarget\n $visualizations.find( '[target=\"galaxy_main\"]').attr( 'target', this.linkTarget );\n // use addBack here to include the root $visualizations elem (for the case of 1 visualization)\n this._addScratchBookFn( $visualizations.find( '.visualization-link' ).addBack( '.visualization-link' ) );\n return $visualizations;\n },\n\n /** add scratchbook functionality to visualization links */\n _addScratchBookFn : function( $links ){\n var li = this;\n $links.click( function( ev ){\n if( Galaxy.frame && Galaxy.frame.active ){\n Galaxy.frame.add({\n title : 'Visualization',\n url : $( this ).attr( 'href' )\n });\n ev.preventDefault();\n ev.stopPropagation();\n }\n });\n },\n\n //TODO: if possible move these to readonly view - but display the owner's tags/annotation (no edit)\n /** Render the tags list/control */\n _renderTags : function( $where ){\n if( !this.hasUser ){ return; }\n var view = this;\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n // persist state on the hda view (and not the editor) since these are currently re-created each time\n onshow : function(){ view.tagsEditorShown = true; },\n onhide : function(){ view.tagsEditorShown = false; },\n $activator : faIconButton({\n title : _l( 'Edit dataset tags' ),\n classes : 'tag-btn',\n faIcon : 'fa-tags'\n }).appendTo( $where.find( '.actions .right' ) )\n });\n if( this.tagsEditorShown ){ this.tagsEditor.toggle( true ); }\n },\n\n /** Render the annotation display/control */\n _renderAnnotation : function( $where ){\n if( !this.hasUser ){ return; }\n var view = this;\n this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n model : this.model,\n el : $where.find( '.annotation-display' ),\n onshowFirstTime : function(){ this.render(); },\n // persist state on the hda view (and not the editor) since these are currently re-created each time\n onshow : function(){ view.annotationEditorShown = true; },\n onhide : function(){ view.annotationEditorShown = false; },\n $activator : faIconButton({\n title : _l( 'Edit dataset annotation' ),\n classes : 'annotate-btn',\n faIcon : 'fa-comment'\n }).appendTo( $where.find( '.actions .right' ) )\n });\n if( this.annotationEditorShown ){ this.annotationEditor.toggle( true ); }\n },\n\n /** If the format/dbkey/genome_build isn't set, make the display a link to the edit page */\n _makeDbkeyEditLink : function( $details ){\n // make the dbkey a link to editing\n if( this.model.get( 'metadata_dbkey' ) === '?'\n && !this.model.isDeletedOrPurged() ){\n var editableDbkey = $( '?' )\n .attr( 'href', this.model.urls.edit )\n .attr( 'target', this.linkTarget );\n $details.find( '.dbkey .value' ).replaceWith( editableDbkey );\n }\n },\n\n // ......................................................................... events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .undelete-link' : '_clickUndeleteLink',\n 'click .purge-link' : '_clickPurgeLink',\n\n 'click .edit-btn' : function( ev ){ this.trigger( 'edit', this, ev ); },\n 'click .delete-btn' : function( ev ){ this.trigger( 'delete', this, ev ); },\n 'click .rerun-btn' : function( ev ){ this.trigger( 'rerun', this, ev ); },\n 'click .report-err-btn' : function( ev ){ this.trigger( 'report-err', this, ev ); },\n 'click .visualization-btn' : function( ev ){ this.trigger( 'visualize', this, ev ); },\n 'click .dbkey a' : function( ev ){ this.trigger( 'edit', this, ev ); }\n }),\n\n /** listener for item undelete (in the messages section) */\n _clickUndeleteLink : function( ev ){\n this.model.undelete();\n return false;\n },\n\n /** listener for item purge (in the messages section) */\n _clickPurgeLink : function( ev ){\n if( confirm( _l( 'This will permanently remove the data in your dataset. Are you sure?' ) ) ){\n this.model.purge();\n }\n return false;\n },\n\n // ......................................................................... misc\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAEditView(' + modelString + ')';\n }\n});\n\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetListItemEdit.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n failed_metadata : BASE_MVC.wrapTemplate([\n // in this override, provide a link to the edit page\n '<% if( dataset.state === \"failed_metadata\" ){ %>',\n '',\n '<% } %>'\n ], 'dataset' ),\n\n deleted : BASE_MVC.wrapTemplate([\n // in this override, provide links to undelete or purge the dataset\n '<% if( dataset.deleted && !dataset.purged ){ %>',\n // deleted not purged\n '
                          ',\n _l( 'This dataset has been deleted' ),\n '
                          ', _l( 'Undelete it' ), '',\n '<% if( view.purgeAllowed ){ %>',\n '
                          ',\n _l( 'Permanently remove it from disk' ),\n '',\n '<% } %>',\n '
                          ',\n '<% } %>'\n ], 'dataset' )\n });\n\n var visualizationsTemplate = BASE_MVC.wrapTemplate([\n '<% if( visualizations.length === 1 ){ %>',\n '\"',\n ' target=\"<%- visualizations[0].target %>\" title=\"', _l( 'Visualize in' ),\n ' <%- visualizations[0].html %>\">',\n '',\n '',\n\n '<% } else { %>',\n '
                          ',\n '',\n '',\n '',\n '',\n '
                          ',\n '<% } %>'\n ], 'visualizations' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n visualizations : visualizationsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n DatasetListItemEdit : DatasetListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-li-edit.js","define([\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, BASE_MVC, _l ){\n'use strict';\n\nvar logNamespace = 'dataset';\n//==============================================================================\nvar searchableMixin = BASE_MVC.SearchableModelMixin;\n/** @class base model for any DatasetAssociation (HDAs, LDDAs, DatasetCollectionDAs).\n * No knowledge of what type (HDA/LDDA/DCDA) should be needed here.\n * The DA's are made searchable (by attribute) by mixing in SearchableModelMixin.\n */\nvar DatasetAssociation = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.mixin( searchableMixin, /** @lends DatasetAssociation.prototype */{\n _logNamespace : logNamespace,\n\n /** default attributes for a model */\n defaults : {\n state : STATES.NEW,\n deleted : false,\n purged : false,\n name : '(unnamed dataset)',\n accessible : true,\n // sniffed datatype (sam, tabular, bed, etc.)\n data_type : '',\n file_ext : '',\n file_size : 0,\n\n // array of associated file types (eg. [ 'bam_index', ... ])\n meta_files : [],\n\n misc_blurb : '',\n misc_info : '',\n\n tags : []\n // do NOT default on annotation, as this default is valid and will be passed on 'save'\n // which is incorrect behavior when the model is only partially fetched (annos are not passed in summary data)\n //annotation : ''\n },\n\n /** instance vars and listeners */\n initialize : function( attributes, options ){\n this.debug( this + '(Dataset).initialize', attributes, options );\n\n //!! this state is not in trans.app.model.Dataset.states - set it here -\n if( !this.get( 'accessible' ) ){\n this.set( 'state', STATES.NOT_VIEWABLE );\n }\n\n /** Datasets rely/use some web controllers - have the model generate those URLs on startup */\n this.urls = this._generateUrls();\n\n this._setUpListeners();\n },\n\n /** returns misc. web urls for rendering things like re-run, display, etc. */\n _generateUrls : function(){\n var id = this.get( 'id' );\n if( !id ){ return {}; }\n var urls = {\n 'purge' : 'datasets/' + id + '/purge_async',\n 'display' : 'datasets/' + id + '/display/?preview=True',\n 'edit' : 'datasets/' + id + '/edit',\n 'download' : 'datasets/' + id + '/display' + this._downloadQueryParameters(),\n 'report_error' : 'dataset/errors?id=' + id,\n 'rerun' : 'tool_runner/rerun?id=' + id,\n 'show_params' : 'datasets/' + id + '/show_params',\n 'visualization' : 'visualization',\n 'meta_download' : 'dataset/get_metadata_file?hda_id=' + id + '&metadata_name='\n };\n _.each( urls, function( value, key ){\n urls[ key ] = Galaxy.root + value;\n });\n this.urls = urls;\n return urls;\n },\n\n _downloadQueryParameters : function() {\n return '?to_ext=' + this.get( 'file_ext' );\n },\n\n /** set up any event listeners\n * event: state:ready fired when this DA moves into/is already in a ready state\n */\n _setUpListeners : function(){\n // if the state has changed and the new state is a ready state, fire an event\n this.on( 'change:state', function( currModel, newState ){\n this.log( this + ' has changed state:', currModel, newState );\n if( this.inReadyState() ){\n this.trigger( 'state:ready', currModel, newState, this.previous( 'state' ) );\n }\n });\n // the download url (currently) relies on having a correct file extension\n this.on( 'change:id change:file_ext', function( currModel ){\n this._generateUrls();\n });\n },\n\n // ........................................................................ common queries\n /** override to add urls */\n toJSON : function(){\n var json = Backbone.Model.prototype.toJSON.call( this );\n //console.warn( 'returning json?' );\n //return json;\n return _.extend( json, {\n urls : this.urls\n });\n },\n\n /** Is this dataset deleted or purged? */\n isDeletedOrPurged : function(){\n return ( this.get( 'deleted' ) || this.get( 'purged' ) );\n },\n\n /** Is this dataset in a 'ready' state; where 'Ready' states are states where no\n * processing (for the ds) is left to do on the server.\n */\n inReadyState : function(){\n var ready = _.contains( STATES.READY_STATES, this.get( 'state' ) );\n return ( this.isDeletedOrPurged() || ready );\n },\n\n /** Does this model already contain detailed data (as opposed to just summary level data)? */\n hasDetails : function(){\n // if it's inaccessible assume it has everything it needs\n if( !this.get( 'accessible' ) ){ return true; }\n return this.has( 'annotation' );\n },\n\n /** Convenience function to match dataset.has_data. */\n hasData : function(){\n return ( this.get( 'file_size' ) > 0 );\n },\n\n // ........................................................................ ajax\n fetch : function( options ){\n var dataset = this;\n return Backbone.Model.prototype.fetch.call( this, options )\n .always( function(){\n dataset._generateUrls();\n });\n },\n\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** override to wait by default */\n save : function( attrs, options ){\n options = options || {};\n options.wait = _.isUndefined( options.wait ) ? true : options.wait;\n return Backbone.Model.prototype.save.call( this, attrs, options );\n },\n\n //NOTE: subclasses of DA's will need to implement url and urlRoot in order to have these work properly\n /** save this dataset, _Mark_ing it as deleted (just a flag) */\n 'delete' : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** save this dataset, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) || this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** remove the file behind this dataset from the filesystem (if permitted) */\n purge : function _purge( options ){\n //TODO: use, override model.destroy, HDA.delete({ purge: true })\n if( this.get( 'purged' ) ){ return jQuery.when(); }\n options = options || {};\n options.url = this.urls.purge;\n\n //TODO: ideally this would be a DELETE call to the api\n // using purge async for now\n var hda = this,\n xhr = jQuery.ajax( options );\n xhr.done( function( message, status, responseObj ){\n hda.set({ deleted: true, purged: true });\n });\n xhr.fail( function( xhr, status, message ){\n // Exception messages are hidden within error page including: '...not allowed in this Galaxy instance.'\n // unbury and re-add to xhr\n var error = _l( \"Unable to purge dataset\" );\n var messageBuriedInUnfortunatelyFormattedError = ( 'Removal of datasets by users '\n + 'is not allowed in this Galaxy instance' );\n if( xhr.responseJSON && xhr.responseJSON.error ){\n error = xhr.responseJSON.error;\n } else if( xhr.responseText.indexOf( messageBuriedInUnfortunatelyFormattedError ) !== -1 ){\n error = messageBuriedInUnfortunatelyFormattedError;\n }\n xhr.responseText = error;\n hda.trigger( 'error', hda, xhr, options, _l( error ), { error: error } );\n });\n return xhr;\n },\n\n // ........................................................................ searching\n /** what attributes of an HDA will be used in a text search */\n searchAttributes : [\n 'name', 'file_ext', 'genome_build', 'misc_blurb', 'misc_info', 'annotation', 'tags'\n ],\n\n /** our attr keys don't often match the labels we display to the user - so, when using\n * attribute specifiers ('name=\"bler\"') in a term, allow passing in aliases for the\n * following attr keys.\n */\n searchAliases : {\n title : 'name',\n format : 'file_ext',\n database : 'genome_build',\n blurb : 'misc_blurb',\n description : 'misc_blurb',\n info : 'misc_info',\n tag : 'tags'\n },\n\n // ........................................................................ misc\n /** String representation */\n toString : function(){\n var nameAndId = this.get( 'id' ) || '';\n if( this.get( 'name' ) ){\n nameAndId = '\"' + this.get( 'name' ) + '\",' + nameAndId;\n }\n return 'Dataset(' + nameAndId + ')';\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection for dataset associations.\n */\nvar DatasetAssociationCollection = Backbone.Collection.extend( BASE_MVC.LoggableMixin ).extend(\n/** @lends HistoryContents.prototype */{\n _logNamespace : logNamespace,\n\n model : DatasetAssociation,\n\n /** root api url */\n urlRoot : Galaxy.root + 'api/datasets',\n\n /** url fn */\n url : function(){\n return this.urlRoot;\n },\n\n // ........................................................................ common queries\n /** Get the ids of every item in this collection\n * @returns array of encoded ids\n */\n ids : function(){\n return this.map( function( item ){ return item.get('id'); });\n },\n\n /** Get contents that are not ready\n * @returns array of content models\n */\n notReady : function(){\n return this.filter( function( content ){\n return !content.inReadyState();\n });\n },\n\n /** return true if any datasets don't have details */\n haveDetails : function(){\n return this.all( function( dataset ){ return dataset.hasDetails(); });\n },\n\n // ........................................................................ ajax\n /** using a queue, perform ajaxFn on each of the models in this collection */\n ajaxQueue : function( ajaxFn, options ){\n var deferred = jQuery.Deferred(),\n startingLength = this.length,\n responses = [];\n\n if( !startingLength ){\n deferred.resolve([]);\n return deferred;\n }\n\n // use reverse order (stylistic choice)\n var ajaxFns = this.chain().reverse().map( function( dataset, i ){\n return function(){\n var xhr = ajaxFn.call( dataset, options );\n // if successful, notify using the deferred to allow tracking progress\n xhr.done( function( response ){\n deferred.notify({ curr: i, total: startingLength, response: response, model: dataset });\n });\n // (regardless of previous error or success) if not last ajax call, shift and call the next\n // if last fn, resolve deferred\n xhr.always( function( response ){\n responses.push( response );\n if( ajaxFns.length ){\n ajaxFns.shift()();\n } else {\n deferred.resolve( responses );\n }\n });\n };\n }).value();\n // start the queue\n ajaxFns.shift()();\n\n return deferred;\n },\n\n // ........................................................................ sorting/filtering\n /** return a new collection of datasets whose attributes contain the substring matchesWhat */\n matches : function( matchesWhat ){\n return this.filter( function( dataset ){\n return dataset.matches( matchesWhat );\n });\n },\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetAssociationCollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n DatasetAssociation : DatasetAssociation,\n DatasetAssociationCollection : DatasetAssociationCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-model.js","define([\n \"mvc/ui/ui-modal\",\n \"mvc/ui/error-modal\",\n \"utils/localization\"\n], function( MODAL, ERROR_MODAL, _l ){\n\n'use strict';\n\n//==============================================================================\n/**\n * A dialog/modal that allows copying a user history or 'importing' from user\n * another. Generally called via historyCopyDialog below.\n * @type {Object}\n */\nvar CopyDialog = {\n\n // language related strings/fns\n defaultName : _.template( \"Copy of '<%- name %>'\" ),\n title : _.template( _l( 'Copying history' ) + ' \"<%- name %>\"' ),\n submitLabel : _l( 'Copy' ),\n errorMessage : _l( 'History could not be copied.' ),\n progressive : _l( 'Copying history' ),\n activeLabel : _l( 'Copy only the active, non-deleted datasets' ),\n allLabel : _l( 'Copy all datasets including deleted ones' ),\n anonWarning : _l( 'As an anonymous user, unless you login or register, you will lose your current history ' ) +\n _l( 'after copying this history. ' ),\n\n // template for modal body\n _template : _.template([\n //TODO: remove inline styles\n // show a warning message for losing current to anon users\n '<% if( isAnon ){ %>',\n '
                          ',\n '<%- anonWarning %>',\n _l( 'You can' ),\n ' ', _l( 'login here' ), ' ', _l( 'or' ), ' ',\n ' ', _l( 'register here' ), '.',\n '
                          ',\n '<% } %>',\n '
                          ',\n '
                          ',\n // TODO: could use required here and the form validators\n // NOTE: use unescaped here if escaped in the modal function below\n '\" />',\n '

                          ',\n _l( 'Please enter a valid history title' ),\n '

                          ',\n // if allowAll, add the option to copy deleted datasets, too\n '<% if( allowAll ){ %>',\n '
                          ',\n '

                          ', _l( 'Choose which datasets from the original history to include:' ), '

                          ',\n // copy non-deleted is the default\n '/>',\n '',\n '
                          ',\n '/>',\n '',\n '<% } %>',\n '
                          '\n ].join( '' )),\n\n // empty modal body and let the user know the copy is happening\n _showAjaxIndicator : function _showAjaxIndicator(){\n var indicator = '

                          ' + this.progressive + '...

                          ';\n this.modal.$( '.modal-body' ).empty().append( indicator ).css({ 'margin-top': '8px' });\n },\n\n // (sorta) public interface - display the modal, render the form, and potentially copy the history\n // returns a jQuery.Deferred done->history copied, fail->user cancelled\n dialog : function _dialog( modal, history, options ){\n options = options || {};\n\n var dialog = this,\n deferred = jQuery.Deferred(),\n // TODO: getting a little byzantine here\n defaultCopyNameFn = options.nameFn || this.defaultName,\n defaultCopyName = defaultCopyNameFn({ name: history.get( 'name' ) }),\n // TODO: these two might be simpler as one 3 state option (all,active,no-choice)\n defaultCopyWhat = options.allDatasets? 'copy-all' : 'copy-non-deleted',\n allowAll = !_.isUndefined( options.allowAll )? options.allowAll : true,\n autoClose = !_.isUndefined( options.autoClose )? options.autoClose : true;\n\n this.modal = modal;\n\n\n // validate the name and copy if good\n function checkNameAndCopy(){\n var name = modal.$( '#copy-modal-title' ).val();\n if( !name ){\n modal.$( '.invalid-title' ).show();\n return;\n }\n // get further settings, shut down and indicate the ajax call, then hide and resolve/reject\n var copyAllDatasets = modal.$( 'input[name=\"copy-what\"]:checked' ).val() === 'copy-all';\n modal.$( 'button' ).prop( 'disabled', true );\n dialog._showAjaxIndicator();\n history.copy( true, name, copyAllDatasets )\n .done( function( response ){\n deferred.resolve( response );\n })\n .fail( function( xhr, status, message ){\n var options = { name: name, copyAllDatasets: copyAllDatasets };\n ERROR_MODAL.ajaxErrorModal( history, xhr, options, dialog.errorMessage );\n deferred.rejectWith( deferred, arguments );\n })\n .done( function(){\n if( autoClose ){ modal.hide(); }\n });\n }\n\n var originalClosingCallback = options.closing_callback;\n modal.show( _.extend( options, {\n title : this.title({ name: history.get( 'name' ) }),\n body : $( dialog._template({\n name : defaultCopyName,\n isAnon : Galaxy.user.isAnonymous(),\n allowAll : allowAll,\n copyWhat : defaultCopyWhat,\n activeLabel : this.activeLabel,\n allLabel : this.allLabel,\n anonWarning : this.anonWarning,\n })),\n buttons : _.object([\n [ _l( 'Cancel' ), function(){ modal.hide(); } ],\n [ this.submitLabel, checkNameAndCopy ]\n ]),\n height : 'auto',\n closing_events : true,\n closing_callback: function _historyCopyClose( cancelled ){\n if( cancelled ){\n deferred.reject({ cancelled : true });\n }\n if( originalClosingCallback ){\n originalClosingCallback( cancelled );\n }\n }\n }));\n\n // set the default dataset copy, autofocus the title, and set up for a simple return\n modal.$( '#copy-modal-title' ).focus().select();\n modal.$( '#copy-modal-title' ).on( 'keydown', function( ev ){\n if( ev.keyCode === 13 ){\n ev.preventDefault();\n checkNameAndCopy();\n }\n });\n\n return deferred;\n },\n};\n\n//==============================================================================\n// maintain the (slight) distinction between copy and import\n/**\n * Subclass CopyDialog to use the import language.\n */\nvar ImportDialog = _.extend( {}, CopyDialog, {\n defaultName : _.template( \"imported: <%- name %>\" ),\n title : _.template( _l( 'Importing history' ) + ' \"<%- name %>\"' ),\n submitLabel : _l( 'Import' ),\n errorMessage : _l( 'History could not be imported.' ),\n progressive : _l( 'Importing history' ),\n activeLabel : _l( 'Import only the active, non-deleted datasets' ),\n allLabel : _l( 'Import all datasets including deleted ones' ),\n anonWarning : _l( 'As an anonymous user, unless you login or register, you will lose your current history ' ) +\n _l( 'after importing this history. ' ),\n\n});\n\n//==============================================================================\n/**\n * Main interface for both history import and history copy dialogs.\n * @param {Backbone.Model} history the history to copy\n * @param {Object} options a hash\n * @return {jQuery.Deferred} promise that fails on close and succeeds on copy\n *\n * options:\n * (this object is also passed to the modal used to display the dialog and accepts modal options)\n * {Function} nameFn if defined, use this to build the default name shown to the user\n * (the fn is passed: {name: })\n * {bool} useImport if true, use the 'import' language (instead of Copy)\n * {bool} allowAll if true, allow the user to choose between copying all datasets and\n * only non-deleted datasets\n * {String} allDatasets default initial checked radio button: 'copy-all' or 'copy-non-deleted',\n */\nvar historyCopyDialog = function( history, options ){\n options = options || {};\n // create our own modal if Galaxy doesn't have one (mako tab without use_panels)\n var modal = window.parent.Galaxy.modal || new MODAL.View({});\n return options.useImport?\n ImportDialog.dialog( modal, history, options ):\n CopyDialog.dialog( modal, history, options );\n};\n\n\n//==============================================================================\n return historyCopyDialog;\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/copy-dialog.js","define([\n \"mvc/dataset/dataset-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_LI, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DATASET_LI.DatasetListItemView;\n/** @class Read only view for HistoryDatasetAssociation.\n * Since there are no controls on the HDAView to hide the dataset,\n * the primary thing this class does (currently) is override templates\n * to render the HID.\n */\nvar HDAListItemView = _super.extend(\n/** @lends HDAListItemView.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n initialize : function( attributes, options ){\n _super.prototype.initialize.call( this, attributes, options );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nHDAListItemView.prototype.templates = (function(){\n\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding the hid display to the title\n '
                          ',\n '',\n '
                          ',\n //TODO: remove whitespace and use margin-right\n '<%- dataset.hid %> ',\n '<%- dataset.name %>',\n '
                          ',\n '
                          ',\n '',\n '<% _.each(_.sortBy(_.uniq(dataset.tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>',\n '',\n '
                          '\n ], 'dataset' );\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n // add a warning when hidden\n '<% if( !dataset.visible ){ %>',\n '
                          ',\n _l( 'This dataset has been hidden' ),\n '
                          ',\n '<% } %>'\n ], 'dataset' )\n });\n\n return _.extend( {}, _super.prototype.templates, {\n titleBar : titleBarTemplate,\n warnings : warnings\n });\n}());\n\n\n\n//==============================================================================\n return {\n HDAListItemView : HDAListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-li.js","define([\n \"mvc/dataset/dataset-model\",\n \"mvc/history/history-content-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET, HISTORY_CONTENT, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\nvar _super = DATASET.DatasetAssociation,\n hcontentMixin = HISTORY_CONTENT.HistoryContentMixin;\n/** @class (HDA) model for a Galaxy dataset contained in and related to a history.\n */\nvar HistoryDatasetAssociation = _super.extend( BASE_MVC.mixin( hcontentMixin,\n/** @lends HistoryDatasetAssociation.prototype */{\n\n /** default attributes for a model */\n defaults : _.extend( {}, _super.prototype.defaults, hcontentMixin.defaults, {\n history_content_type: 'dataset',\n model_class : 'HistoryDatasetAssociation'\n }),\n}));\n\n//==============================================================================\n return {\n HistoryDatasetAssociation : HistoryDatasetAssociation\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-model.js","define([\n \"mvc/dataset/states\",\n \"mvc/collection/collection-li\",\n \"mvc/collection/collection-view\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, DC_LI, DC_VIEW, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DC_LI.DCListItemView;\n/** @class Read only view for HistoryDatasetCollectionAssociation (a dataset collection inside a history).\n */\nvar HDCAListItemView = _super.extend(\n/** @lends HDCAListItemView.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n /** event listeners */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n this.listenTo( this.model, {\n 'change:tags change:populated change:visible' : function( model, options ){ this.render(); },\n });\n },\n\n /** Override to provide the proper collections panels as the foldout */\n _getFoldoutPanelClass : function(){\n switch( this.model.get( 'collection_type' ) ){\n case 'list':\n return DC_VIEW.ListCollectionView;\n case 'paired':\n return DC_VIEW.PairCollectionView;\n case 'list:paired':\n return DC_VIEW.ListOfPairsCollectionView;\n case 'list:list':\n return DC_VIEW.ListOfListsCollectionView;\n }\n throw new TypeError( 'Uknown collection_type: ' + this.model.get( 'collection_type' ) );\n },\n\n /** In this override, add the state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n //TODO: model currently has no state\n var state = !this.model.get( 'populated' ) ? STATES.RUNNING : STATES.OK;\n //if( this.model.has( 'state' ) ){\n this.$el.addClass( 'state-' + state );\n //}\n return this.$el;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDCAListItemView(' + modelString + ')';\n }\n});\n\n/** underscore templates */\nHDCAListItemView.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n // add a warning when hidden\n '<% if( !collection.visible ){ %>',\n '
                          ',\n _l( 'This collection has been hidden' ),\n '
                          ',\n '<% } %>'\n ], 'collection' )\n });\n\n// could steal this from hda-base (or use mixed content)\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding the hid display to the title\n '
                          ',\n '',\n '
                          ',\n //TODO: remove whitespace and use margin-right\n '<%- collection.hid %> ',\n '<%- collection.name %>',\n '
                          ',\n '
                          ',\n '',\n '<% _.each(_.sortBy(_.uniq(collection.tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>',\n '',\n '
                          '\n ], 'collection' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n HDCAListItemView : HDCAListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-li.js","define([\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/** @class Mixin for HistoryContents content (HDAs, HDCAs).\n */\nvar HistoryContentMixin = {\n\n /** default attributes for a model */\n defaults : {\n /** parent (containing) history */\n history_id : null,\n /** some content_type (HistoryContents can contain mixed model classes) */\n history_content_type: null,\n /** indicating when/what order the content was generated in the context of the history */\n hid : null,\n /** whether the user wants the content shown (visible) */\n visible : true\n },\n\n // ........................................................................ mixed content element\n // In order to be part of a MIXED bbone collection, we can't rely on the id\n // (which may collide btwn models of different classes)\n // Instead, use type_id which prefixes the history_content_type so the bbone collection can differentiate\n idAttribute : 'type_id',\n\n // ........................................................................ common queries\n /** the more common alias of visible */\n hidden : function(){\n return !this.get( 'visible' );\n },\n\n//TODO: remove\n /** based on includeDeleted, includeHidden (gen. from the container control),\n * would this ds show in the list of ds's?\n * @param {Boolean} includeDeleted are we showing deleted hdas?\n * @param {Boolean} includeHidden are we showing hidden hdas?\n */\n isVisible : function( includeDeleted, includeHidden ){\n var isVisible = true;\n if( ( !includeDeleted )\n && ( this.get( 'deleted' ) || this.get( 'purged' ) ) ){\n isVisible = false;\n }\n if( ( !includeHidden )\n && ( !this.get( 'visible' ) ) ){\n isVisible = false;\n }\n return isVisible;\n },\n\n // ........................................................................ ajax\n //TODO?: these are probably better done on the leaf classes\n /** history content goes through the 'api/histories' API */\n urlRoot: Galaxy.root + 'api/histories/',\n\n /** full url spec. for this content */\n url : function(){\n var url = this.urlRoot + this.get( 'history_id' ) + '/contents/'\n + this.get('history_content_type') + 's/' + this.get( 'id' );\n return url;\n },\n\n /** save this content as not visible */\n hide : function( options ){\n if( !this.get( 'visible' ) ){ return jQuery.when(); }\n return this.save( { visible: false }, options );\n },\n /** save this content as visible */\n unhide : function( options ){\n if( this.get( 'visible' ) ){ return jQuery.when(); }\n return this.save( { visible: true }, options );\n },\n\n // ........................................................................ misc\n toString : function(){\n return ([ this.get( 'type_id' ), this.get( 'hid' ), this.get( 'name' ) ].join(':'));\n }\n};\n\n\n//==============================================================================\n return {\n HistoryContentMixin : HistoryContentMixin\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-content-model.js","define([\n \"mvc/list/list-item\",\n \"ui/loading-indicator\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/search-input\"\n], function( LIST_ITEM, LoadingIndicator, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'list';\n/* ============================================================================\nTODO:\n\n============================================================================ */\n/** @class View for a list/collection of models and the sub-views of those models.\n * Sub-views must (at least have the interface if not) inherit from ListItemView.\n * (For a list panel that also includes some 'container' model (History->HistoryContents)\n * use ModelWithListPanel)\n *\n * Allows for:\n * searching collection/sub-views\n * selecting/multi-selecting sub-views\n *\n * Currently used:\n * for dataset/dataset-choice\n * as superclass of ModelListPanel\n */\nvar ListPanel = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend(/** @lends ListPanel.prototype */{\n _logNamespace : logNamespace,\n\n /** class to use for constructing the sub-views */\n viewClass : LIST_ITEM.ListItemView,\n /** class to used for constructing collection of sub-view models */\n collectionClass : Backbone.Collection,\n\n tagName : 'div',\n className : 'list-panel',\n\n /** (in ms) that jquery effects will use */\n fxSpeed : 'fast',\n\n /** string to display when the collection has no contents */\n emptyMsg : _l( 'This list is empty' ),\n /** displayed when no items match the search terms */\n noneFoundMsg : _l( 'No matching items found' ),\n /** string used for search placeholder */\n searchPlaceholder : _l( 'search' ),\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the list\n */\n initialize : function( attributes, options ){\n attributes = attributes || {};\n // set the logger if requested\n if( attributes.logger ){\n this.logger = attributes.logger;\n }\n this.log( this + '.initialize:', attributes );\n\n // ---- instance vars\n /** how quickly should jquery fx run? */\n this.fxSpeed = _.has( attributes, 'fxSpeed' )?( attributes.fxSpeed ):( this.fxSpeed );\n\n /** filters for displaying subviews */\n this.filters = [];\n /** current search terms */\n this.searchFor = attributes.searchFor || '';\n\n /** loading indicator */\n // this.indicator = new LoadingIndicator( this.$el );\n\n /** currently showing selectors on items? */\n this.selecting = ( attributes.selecting !== undefined )? attributes.selecting : true;\n //this.selecting = false;\n\n /** cached selected item.model.ids to persist btwn renders */\n this.selected = attributes.selected || [];\n /** the last selected item.model.id */\n this.lastSelected = null;\n\n /** are sub-views draggable */\n this.dragItems = attributes.dragItems || false;\n\n /** list item view class (when passed models) */\n this.viewClass = attributes.viewClass || this.viewClass;\n\n /** list item views */\n this.views = [];\n /** list item models */\n this.collection = attributes.collection || this._createDefaultCollection();\n\n /** filter fns run over collection items to see if they should show in the list */\n this.filters = attributes.filters || [];\n\n /** override $scrollContainer fn via attributes - fn should return jq for elem to call scrollTo on */\n this.$scrollContainer = attributes.$scrollContainer || this.$scrollContainer;\n\n /** @type {String} generic title */\n this.title = attributes.title || '';\n /** @type {String} generic subtitle */\n this.subtitle = attributes.subtitle || '';\n\n this._setUpListeners();\n },\n\n // ------------------------------------------------------------------------ listeners\n /** create any event listeners for the list */\n _setUpListeners : function(){\n this.off();\n\n //TODO: move errorHandler down into list-view from history-view or\n // pass to global error handler (Galaxy)\n this.on({\n error: function( model, xhr, options, msg, details ){\n //this.errorHandler( model, xhr, options, msg, details );\n console.error( model, xhr, options, msg, details );\n },\n // show hide the loading indicator\n loading: function(){\n this._showLoadingIndicator( 'loading...', 40 );\n },\n 'loading-done': function(){\n this._hideLoadingIndicator( 40 );\n },\n });\n\n // throw the first render up as a diff namespace using once (for outside consumption)\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this._setUpCollectionListeners();\n this._setUpViewListeners();\n return this;\n },\n\n /** create and return a collection for when none is initially passed */\n _createDefaultCollection : function(){\n // override\n return new this.collectionClass([]);\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n this.log( this + '._setUpCollectionListeners', this.collection );\n this.stopListening( this.collection );\n\n // bubble up error events\n this.listenTo( this.collection, {\n error : function( model, xhr, options, msg, details ){\n this.trigger( 'error', model, xhr, options, msg, details );\n },\n update : function( collection, options ){\n var changes = options.changes;\n // console.info( collection + ', update:', changes, '\\noptions:', options );\n // more than one: render everything\n if( options.renderAll || ( changes.added.length + changes.removed.length > 1 ) ){\n return this.renderItems();\n }\n // otherwise, let the single add/remove handlers do it\n if( changes.added.length === 1 ){\n return this.addItemView( _.first( changes.added ), collection, options );\n }\n if( changes.removed.length === 1 ){\n return this.removeItemView( _.first( changes.removed ), collection, options );\n }\n }\n });\n return this;\n },\n\n /** listening for sub-view events that bubble up with the 'view:' prefix */\n _setUpViewListeners : function(){\n this.log( this + '._setUpViewListeners' );\n\n // shift to select a range\n this.on({\n 'view:selected': function( view, ev ){\n if( ev && ev.shiftKey && this.lastSelected ){\n var lastSelectedView = this.viewFromModelId( this.lastSelected );\n if( lastSelectedView ){\n this.selectRange( view, lastSelectedView );\n }\n } else if( ev && ev.altKey && !this.selecting ){\n this.showSelectors();\n }\n this.selected.push( view.model.id );\n this.lastSelected = view.model.id;\n },\n\n 'view:de-selected': function( view, ev ){\n this.selected = _.without( this.selected, view.model.id );\n }\n });\n },\n\n // ------------------------------------------------------------------------ rendering\n /** Render this content, set up ui.\n * @param {Number or String} speed the speed of the render\n */\n render : function( speed ){\n this.log( this + '.render', speed );\n var $newRender = this._buildNewRender();\n this._setUpBehaviors( $newRender );\n this._queueNewRender( $newRender, speed );\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el. */\n _buildNewRender : function(){\n this.debug( this + '(ListPanel)._buildNewRender' );\n var $newRender = $( this.templates.el( {}, this ) );\n this._renderControls( $newRender );\n this._renderTitle( $newRender );\n this._renderSubtitle( $newRender );\n this._renderSearch( $newRender );\n this.renderItems( $newRender );\n return $newRender;\n },\n\n /** Build a temp div containing the new children for the view's $el. */\n _renderControls : function( $newRender ){\n this.debug( this + '(ListPanel)._renderControls' );\n var $controls = $( this.templates.controls( {}, this ) );\n $newRender.find( '.controls' ).replaceWith( $controls );\n return $controls;\n },\n\n /** return a jQuery object containing the title DOM */\n _renderTitle : function( $where ){\n //$where = $where || this.$el;\n //$where.find( '.title' ).replaceWith( ... )\n },\n\n /** return a jQuery object containing the subtitle DOM (if any) */\n _renderSubtitle : function( $where ){\n //$where = $where || this.$el;\n //$where.find( '.title' ).replaceWith( ... )\n },\n\n /** Fade out the old el, swap in the new contents, then fade in.\n * @param {Number or String} speed jq speed to use for rendering effects\n * @fires rendered when rendered\n */\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var panel = this;\n panel.log( '_queueNewRender:', $newRender, speed );\n\n $( panel ).queue( 'fx', [\n function( next ){\n panel.$el.fadeOut( speed, next );\n },\n function( next ){\n panel._swapNewRender( $newRender );\n next();\n },\n function( next ){\n panel.$el.fadeIn( speed, next );\n },\n function( next ){\n panel.trigger( 'rendered', panel );\n next();\n }\n ]);\n },\n\n /** empty out the current el, move the $newRender's children in */\n _swapNewRender : function( $newRender ){\n this.$el.empty().attr( 'class', this.className ).append( $newRender.children() );\n if( this.selecting ){ this.showSelectors( 0 ); }\n return this;\n },\n\n /** Set up any behaviors, handlers (ep. plugins) that need to be called when the entire view has been built but\n * not attached to the page yet.\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n this.$controls( $where ).find('[title]').tooltip();\n // set up the pupup for actions available when multi selecting\n this._renderMultiselectActionMenu( $where );\n return this;\n },\n\n /** render a menu containing the actions available to sets of selected items */\n _renderMultiselectActionMenu : function( $where ){\n $where = $where || this.$el;\n var $menu = $where.find( '.list-action-menu' ),\n actions = this.multiselectActions();\n if( !actions.length ){\n return $menu.empty();\n }\n\n var $newMenu = $([\n '
                          ',\n '',\n '
                            ', '
                          ',\n '
                          '\n ].join(''));\n var $actions = actions.map( function( action ){\n var html = [ '
                        • ', action.html, '
                        • ' ].join( '' );\n return $( html ).click( function( ev ){\n ev.preventDefault();\n return action.func( ev );\n });\n });\n $newMenu.find( 'ul' ).append( $actions );\n $menu.replaceWith( $newMenu );\n return $newMenu;\n },\n\n /** return a list of plain objects used to render multiselect actions menu. Each object should have:\n * html: an html string used as the anchor contents\n * func: a function called when the anchor is clicked (passed the click event)\n */\n multiselectActions : function(){\n return [];\n },\n\n // ------------------------------------------------------------------------ sub-$element shortcuts\n /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n $scrollContainer : function( $where ){\n // override or set via attributes.$scrollContainer\n return ( $where || this.$el ).parent().parent();\n },\n /** convenience selector for the section that displays the list controls */\n $controls : function( $where ){\n return ( $where || this.$el ).find( '> .controls' );\n },\n /** list-items: where the subviews are contained in the view's dom */\n $list : function( $where ){\n return ( $where || this.$el ).find( '> .list-items' );\n },\n /** container where list messages are attached */\n $messages : function( $where ){\n //TODO: controls isn't really correct here (only for ModelListPanel)\n return ( $where || this.$el ).find( '> .controls .messages' );\n },\n /** the message displayed when no views can be shown (no views, none matching search) */\n $emptyMessage : function( $where ){\n return ( $where || this.$el ).find( '> .empty-message' );\n },\n\n // ------------------------------------------------------------------------ hda sub-views\n /** render the subviews for the list's collection */\n renderItems : function( $whereTo ){\n $whereTo = $whereTo || this.$el;\n var panel = this;\n panel.log( this + '.renderItems', $whereTo );\n\n var $list = panel.$list( $whereTo );\n panel.freeViews();\n // console.log( 'views freed' );\n //TODO:? cache and re-use views?\n var shownModels = panel._filterCollection();\n // console.log( 'models filtered:', shownModels );\n\n panel.views = shownModels.map( function( itemModel ){\n var view = panel._createItemView( itemModel );\n return view;\n });\n\n $list.empty();\n // console.log( 'list emptied' );\n if( panel.views.length ){\n panel._attachItems( $whereTo );\n // console.log( 'items attached' );\n }\n panel._renderEmptyMessage( $whereTo ).toggle( !panel.views.length );\n panel.trigger( 'views:ready', panel.views );\n\n // console.log( '------------------------------------------- rendering items' );\n return panel.views;\n },\n\n /** Filter the collection to only those models that should be currently viewed */\n _filterCollection : function(){\n // override this\n var panel = this;\n return panel.collection.filter( _.bind( panel._filterItem, panel ) );\n },\n\n /** Should the model be viewable in the current state?\n * Checks against this.filters and this.searchFor\n */\n _filterItem : function( model ){\n // override this\n var panel = this;\n return ( _.every( panel.filters.map( function( fn ){ return fn.call( model ); }) ) )\n && ( !panel.searchFor || model.matchesAll( panel.searchFor ) );\n },\n\n /** Create a view for a model and set up it's listeners */\n _createItemView : function( model ){\n var ViewClass = this._getItemViewClass( model );\n var options = _.extend( this._getItemViewOptions( model ), {\n model : model\n });\n var view = new ViewClass( options );\n this._setUpItemViewListeners( view );\n return view;\n },\n\n /** Free a view for a model. Note: does not remove it from the DOM */\n _destroyItemView : function( view ){\n this.stopListening( view );\n this.views = _.without( this.views, view );\n },\n\n _destroyItemViews : function( view ){\n var self = this;\n self.views.forEach( function( v ){\n self.stopListening( v );\n });\n self.views = [];\n return self;\n },\n\n /** free any sub-views the list has */\n freeViews : function(){\n return this._destroyItemViews();\n },\n\n /** Get the bbone view class based on the model */\n _getItemViewClass : function( model ){\n // override this\n return this.viewClass;\n },\n\n /** Get the options passed to the new view based on the model */\n _getItemViewOptions : function( model ){\n // override this\n return {\n //logger : this.logger,\n fxSpeed : this.fxSpeed,\n expanded : false,\n selectable : this.selecting,\n selected : _.contains( this.selected, model.id ),\n draggable : this.dragItems\n };\n },\n\n /** Set up listeners for new models */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n // send all events to the panel, re-namspaceing them with the view prefix\n this.listenTo( view, 'all', function(){\n var args = Array.prototype.slice.call( arguments, 0 );\n args[0] = 'view:' + args[0];\n panel.trigger.apply( panel, args );\n });\n\n // drag multiple - hijack ev.setData to add all selected items\n this.listenTo( view, 'draggable:dragstart', function( ev, v ){\n //TODO: set multiple drag data here\n var json = {},\n selected = this.getSelectedModels();\n if( selected.length ){\n json = selected.toJSON();\n } else {\n json = [ v.model.toJSON() ];\n }\n ev.dataTransfer.setData( 'text', JSON.stringify( json ) );\n //ev.dataTransfer.setDragImage( v.el, 60, 60 );\n }, this );\n\n return panel;\n },\n\n /** Attach views in this.views to the model based on $whereTo */\n _attachItems : function( $whereTo ){\n var self = this;\n // console.log( '_attachItems:', $whereTo, this.$list( $whereTo ) );\n //ASSUMES: $list has been emptied\n this.$list( $whereTo ).append( this.views.map( function( view ){\n return self._renderItemView$el( view );\n }));\n return this;\n },\n\n /** get a given subview's $el (or whatever may wrap it) and return it */\n _renderItemView$el : function( view ){\n // useful to wrap and override\n return view.render(0).$el;\n },\n\n /** render the empty/none-found message */\n _renderEmptyMessage : function( $whereTo ){\n this.debug( '_renderEmptyMessage', $whereTo, this.searchFor );\n var text = this.searchFor? this.noneFoundMsg : this.emptyMsg;\n return this.$emptyMessage( $whereTo ).text( text );\n },\n\n /** expand all item views */\n expandAll : function(){\n _.each( this.views, function( view ){\n view.expand();\n });\n },\n\n /** collapse all item views */\n collapseAll : function(){\n _.each( this.views, function( view ){\n view.collapse();\n });\n },\n\n // ------------------------------------------------------------------------ collection/views syncing\n /** Add a view (if the model should be viewable) to the panel */\n addItemView : function( model, collection, options ){\n // console.log( this + '.addItemView:', model );\n var panel = this;\n // get the index of the model in the list of filtered models shown by this list\n // in order to insert the view in the proper place\n //TODO:? potentially expensive\n var modelIndex = panel._filterCollection().indexOf( model );\n if( modelIndex === -1 ){ return undefined; }\n var view = panel._createItemView( model );\n // console.log( 'adding and rendering:', modelIndex, view.toString() );\n\n $( view ).queue( 'fx', [\n function( next ){\n // hide the empty message first if only view\n if( panel.$emptyMessage().is( ':visible' ) ){\n panel.$emptyMessage().fadeOut( panel.fxSpeed, next );\n } else {\n next();\n }\n },\n function( next ){\n panel._attachView( view, modelIndex );\n next();\n }\n ]);\n return view;\n },\n\n /** internal fn to add view (to both panel.views and panel.$list) */\n _attachView : function( view, modelIndex, useFx ){\n // console.log( this + '._attachView:', view, modelIndex, useFx );\n useFx = _.isUndefined( useFx )? true : useFx;\n modelIndex = modelIndex || 0;\n var panel = this;\n\n // use the modelIndex to splice into views and insert at the proper index in the DOM\n panel.views.splice( modelIndex, 0, view );\n panel._insertIntoListAt( modelIndex, panel._renderItemView$el( view ).hide() );\n\n panel.trigger( 'view:attached', view );\n if( useFx ){\n view.$el.slideDown( panel.fxSpeed, function(){\n panel.trigger( 'view:attached:rendered' );\n });\n } else {\n view.$el.show();\n panel.trigger( 'view:attached:rendered' );\n }\n return view;\n },\n\n /** insert a jq object as a child of list-items at the specified *DOM index* */\n _insertIntoListAt : function( index, $what ){\n // console.log( this + '._insertIntoListAt:', index, $what );\n var $list = this.$list();\n if( index === 0 ){\n $list.prepend( $what );\n } else {\n $list.children().eq( index - 1 ).after( $what );\n }\n return $what;\n },\n\n /** Remove a view from the panel (if found) */\n removeItemView : function( model, collection, options ){\n var panel = this;\n var view = _.find( panel.views, function( v ){ return v.model === model; });\n if( !view ){ return undefined; }\n panel.views = _.without( panel.views, view );\n panel.trigger( 'view:removed', view );\n\n // potentially show the empty message if no views left\n // use anonymous queue here - since remove can happen multiple times\n $({}).queue( 'fx', [\n function( next ){\n view.$el.fadeOut( panel.fxSpeed, next );\n },\n function( next ){\n view.remove();\n panel.trigger( 'view:removed:rendered' );\n if( !panel.views.length ){\n panel._renderEmptyMessage().fadeIn( panel.fxSpeed, next );\n } else {\n next();\n }\n }\n ]);\n return view;\n },\n\n /** get views based on model.id */\n viewFromModelId : function( id ){\n return _.find( this.views, function( v ){ return v.model.id === id; });\n },\n\n /** get views based on model */\n viewFromModel : function( model ){\n return model ? this.viewFromModelId( model.id ) : undefined;\n },\n\n /** get views based on model properties */\n viewsWhereModel : function( properties ){\n return this.views.filter( function( view ){\n return _.isMatch( view.model.attributes, properties );\n });\n },\n\n /** A range of views between (and including) viewA and viewB */\n viewRange : function( viewA, viewB ){\n if( viewA === viewB ){ return ( viewA )?( [ viewA ] ):( [] ); }\n\n var indexA = this.views.indexOf( viewA ),\n indexB = this.views.indexOf( viewB );\n\n // handle not found\n if( indexA === -1 || indexB === -1 ){\n if( indexA === indexB ){ return []; }\n return ( indexA === -1 )?( [ viewB ] ):( [ viewA ] );\n }\n // reverse if indeces are\n //note: end inclusive\n return ( indexA < indexB )?\n this.views.slice( indexA, indexB + 1 ) :\n this.views.slice( indexB, indexA + 1 );\n },\n\n // ------------------------------------------------------------------------ searching\n /** render a search input for filtering datasets shown\n * (see SearchableMixin in base-mvc for implementation of the actual searching)\n * return will start the search\n * esc will clear the search\n * clicking the clear button will clear the search\n * uses searchInput in ui.js\n */\n _renderSearch : function( $where ){\n $where.find( '.controls .search-input' ).searchInput({\n placeholder : this.searchPlaceholder,\n initialVal : this.searchFor,\n onfirstsearch : _.bind( this._firstSearch, this ),\n onsearch : _.bind( this.searchItems, this ),\n onclear : _.bind( this.clearSearch, this )\n });\n return $where;\n },\n\n /** What to do on the first search entered */\n _firstSearch : function( searchFor ){\n // override to load model details if necc.\n this.log( 'onFirstSearch', searchFor );\n return this.searchItems( searchFor );\n },\n\n /** filter view list to those that contain the searchFor terms */\n searchItems : function( searchFor, force ){\n this.log( 'searchItems', searchFor, this.searchFor, force );\n if( !force && this.searchFor === searchFor ){ return this; }\n this.searchFor = searchFor;\n this.renderItems();\n this.trigger( 'search:searching', searchFor, this );\n var $search = this.$( '> .controls .search-query' );\n if( $search.val() !== searchFor ){\n $search.val( searchFor );\n }\n return this;\n },\n\n /** clear the search filters and show all views that are normally shown */\n clearSearch : function( searchFor ){\n //this.log( 'onSearchClear', this );\n this.searchFor = '';\n this.trigger( 'search:clear', this );\n this.$( '> .controls .search-query' ).val( '' );\n this.renderItems();\n return this;\n },\n\n // ------------------------------------------------------------------------ selection\n /** @type Integer when the number of list item views is >= to this, don't animate selectors */\n THROTTLE_SELECTOR_FX_AT : 20,\n\n /** show selectors on all visible itemViews and associated controls */\n showSelectors : function( speed ){\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n this.selecting = true;\n this.$( '.list-actions' ).slideDown( speed );\n speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT? 0 : speed;\n _.each( this.views, function( view ){\n view.showSelector( speed );\n });\n //this.selected = [];\n //this.lastSelected = null;\n },\n\n /** hide selectors on all visible itemViews and associated controls */\n hideSelectors : function( speed ){\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n this.selecting = false;\n this.$( '.list-actions' ).slideUp( speed );\n speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT? 0 : speed;\n _.each( this.views, function( view ){\n view.hideSelector( speed );\n });\n this.selected = [];\n this.lastSelected = null;\n },\n\n /** show or hide selectors on all visible itemViews and associated controls */\n toggleSelectors : function(){\n if( !this.selecting ){\n this.showSelectors();\n } else {\n this.hideSelectors();\n }\n },\n\n /** select all visible items */\n selectAll : function( event ){\n _.each( this.views, function( view ){\n view.select( event );\n });\n },\n\n /** deselect all visible items */\n deselectAll : function( event ){\n this.lastSelected = null;\n _.each( this.views, function( view ){\n view.deselect( event );\n });\n },\n\n /** select a range of datasets between A and B */\n selectRange : function( viewA, viewB ){\n var range = this.viewRange( viewA, viewB );\n _.each( range, function( view ){\n view.select();\n });\n return range;\n },\n\n /** return an array of all currently selected itemViews */\n getSelectedViews : function(){\n return _.filter( this.views, function( v ){\n return v.selected;\n });\n },\n\n /** return a collection of the models of all currenly selected items */\n getSelectedModels : function(){\n // console.log( '(getSelectedModels)' );\n return new this.collection.constructor( _.map( this.getSelectedViews(), function( view ){\n return view.model;\n }));\n },\n\n // ------------------------------------------------------------------------ loading indicator\n /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n _showLoadingIndicator : function( msg, speed, callback ){\n this.debug( '_showLoadingIndicator', this.indicator, msg, speed, callback );\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n if( !this.indicator ){\n this.indicator = new LoadingIndicator( this.$el );\n this.debug( '\\t created', this.indicator );\n }\n if( !this.$el.is( ':visible' ) ){\n this.indicator.show( 0, callback );\n } else {\n this.$el.fadeOut( speed );\n this.indicator.show( msg, speed, callback );\n }\n },\n\n /** hide the loading indicator */\n _hideLoadingIndicator : function( speed, callback ){\n this.debug( '_hideLoadingIndicator', this.indicator, speed, callback );\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n if( this.indicator ){\n this.indicator.hide( speed, callback );\n }\n },\n\n // ------------------------------------------------------------------------ scrolling\n /** get the current scroll position of the panel in its parent */\n scrollPosition : function(){\n return this.$scrollContainer().scrollTop();\n },\n\n /** set the current scroll position of the panel in its parent */\n scrollTo : function( pos, speed ){\n speed = speed || 0;\n this.$scrollContainer().animate({ scrollTop: pos }, speed );\n return this;\n },\n\n /** Scrolls the panel to the top. */\n scrollToTop : function( speed ){\n return this.scrollTo( 0, speed );\n },\n\n /** scroll to the given view in list-items */\n scrollToItem : function( view, speed ){\n if( !view ){ return this; }\n return this;\n },\n\n /** Scrolls the panel to show the content with the given id. */\n scrollToId : function( id, speed ){\n return this.scrollToItem( this.viewFromModelId( id ), speed );\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : {\n 'click .select-all' : 'selectAll',\n 'click .deselect-all' : 'deselectAll'\n },\n\n // ------------------------------------------------------------------------ misc\n /** Return a string rep of the panel */\n toString : function(){\n return 'ListPanel(' + this.collection + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nListPanel.prototype.templates = (function(){\n\n var elTemplate = BASE_MVC.wrapTemplate([\n // temp container\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ]);\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                          ',\n '
                          ',\n '
                          <%- view.title %>
                          ',\n '
                          ',\n '
                          <%- view.subtitle %>
                          ',\n // buttons, controls go here\n '
                          ',\n // deleted msg, etc.\n '
                          ',\n\n '
                          ',\n '
                          ',\n '
                          ',\n\n // show when selectors are shown\n '
                          ',\n '
                          ',\n '',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ]);\n\n return {\n el : elTemplate,\n controls : controlsTemplate\n };\n}());\n\n\n//=============================================================================\n/** View for a model that has a sub-collection (e.g. History, DatasetCollection)\n * Allows:\n * the model to be reset\n * auto assign panel.collection to panel.model[ panel.modelCollectionKey ]\n *\n */\nvar ModelListPanel = ListPanel.extend({\n\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'contents',\n\n initialize : function( attributes ){\n ListPanel.prototype.initialize.call( this, attributes );\n this.selecting = ( attributes.selecting !== undefined )? attributes.selecting : false;\n\n this.setModel( this.model, attributes );\n },\n\n /** release/free/shutdown old models and set up panel for new models\n * @fires new-model with the panel as parameter\n */\n setModel : function( model, attributes ){\n attributes = attributes || {};\n this.debug( this + '.setModel:', model, attributes );\n\n this.freeModel();\n this.freeViews();\n\n if( model ){\n var oldModelId = this.model? this.model.get( 'id' ): null;\n\n // set up the new model with user, logger, storage, events\n this.model = model;\n if( this.logger ){\n this.model.logger = this.logger;\n }\n this._setUpModelListeners();\n\n //TODO: relation btwn model, collection becoming tangled here\n // free the collection, and assign the new collection to either\n // the model[ modelCollectionKey ], attributes.collection, or an empty vanilla collection\n this.stopListening( this.collection );\n this.collection = this.model[ this.modelCollectionKey ]\n || attributes.collection\n || this._createDefaultCollection();\n this._setUpCollectionListeners();\n\n if( oldModelId && model.get( 'id' ) !== oldModelId ){\n this.trigger( 'new-model', this );\n }\n }\n return this;\n },\n\n /** free the current model and all listeners for it, free any views for the model */\n freeModel : function(){\n // stop/release the previous model, and clear cache to sub-views\n if( this.model ){\n this.stopListening( this.model );\n //TODO: see base-mvc\n //this.model.free();\n //this.model = null;\n }\n return this;\n },\n\n // ------------------------------------------------------------------------ listening\n /** listening for model events */\n _setUpModelListeners : function(){\n // override\n this.log( this + '._setUpModelListeners', this.model );\n // bounce model errors up to the panel\n this.listenTo( this.model, 'error', function(){\n var args = Array.prototype.slice.call( arguments, 0 );\n //args.unshift( 'model:error' );\n args.unshift( 'error' );\n this.trigger.apply( this, args );\n }, this );\n\n // debugging\n if( this.logger ){\n this.listenTo( this.model, 'all', function( event ){\n this.info( this + '(model)', event, arguments );\n });\n }\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el.\n */\n _renderControls : function( $newRender ){\n this.debug( this + '(ModelListPanel)._renderControls' );\n var json = this.model? this.model.toJSON() : {},\n $controls = $( this.templates.controls( json, this ) );\n $newRender.find( '.controls' ).replaceWith( $controls );\n return $controls;\n },\n\n // ------------------------------------------------------------------------ misc\n /** Return a string rep of the panel */\n toString : function(){\n return 'ModelListPanel(' + this.model + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nModelListPanel.prototype.templates = (function(){\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                          ',\n '
                          ',\n //TODO: this is really the only difference - consider factoring titlebar out\n '
                          <%- model.name %>
                          ',\n '
                          ',\n '
                          <%- view.subtitle %>
                          ',\n '
                          ',\n '
                          ',\n\n '
                          ',\n '
                          ',\n '
                          ',\n\n '
                          ',\n '
                          ',\n '',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ]);\n\n return _.extend( _.clone( ListPanel.prototype.templates ), {\n controls : controlsTemplate\n });\n}());\n\n\n//=============================================================================\n return {\n ListPanel : ListPanel,\n ModelListPanel : ModelListPanel\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/list/list-view.js","/** This is the run workflow tool form view. */\ndefine([ 'utils/utils', 'utils/deferred', 'mvc/ui/ui-misc', 'mvc/form/form-view', 'mvc/form/form-data', 'mvc/tool/tool-form-base', 'mvc/ui/ui-modal', 'mvc/webhooks', 'mvc/workflow/workflow-icons' ],\n function( Utils, Deferred, Ui, Form, FormData, ToolFormBase, Modal, Webhooks, WorkflowIcons ) {\n\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.modal = parent.Galaxy.modal || new Modal.View();\n this.model = options && options.model || new Backbone.Model( options );\n this.deferred = new Deferred();\n this.setElement( $( '
                          ' ).addClass( 'ui-form-composite' )\n .append( this.$message = $( '
                          ' ) )\n .append( this.$header = $( '
                          ' ) )\n .append( this.$steps = $( '
                          ' ) ) );\n $( 'body' ).append( this.$el );\n this._configure();\n this.render();\n $( window ).resize( function() { self._refresh() } );\n },\n\n /** Refresh height of scrollable div below header, handle scrolling by lazy loading steps */\n _refresh: function( step_index ) {\n var margin = _.reduce( this.$el.children(), function( memo, child ) {\n return memo + $( child ).outerHeight();\n }, 0 ) - this.$steps.height() + 90;\n this.$steps.css( 'height', $( window ).height() - margin );\n },\n\n /** Configures form/step options for each workflow step */\n _configure: function() {\n var self = this;\n this.forms = [];\n this.steps = [];\n this.links = [];\n this.parms = [];\n _.each( this.model.get( 'steps' ), function( step, i ) {\n Galaxy.emit.debug( 'tool-form-composite::initialize()', i + ' : Preparing workflow step.' );\n var icon = WorkflowIcons[ step.step_type ];\n var title = parseInt( i + 1 ) + ': ' + ( step.step_label || step.step_name );\n if ( step.annotation ) {\n title += ' - ' + step.annotation;\n }\n if ( step.step_version ) {\n title += ' (Galaxy Version ' + step.step_version + ')';\n }\n step = Utils.merge( {\n index : i,\n title : _.escape( title ),\n icon : icon || '',\n help : null,\n citations : null,\n collapsible : true,\n collapsed : i > 0 && !self._isDataStep( step ),\n sustain_version : true,\n sustain_repeats : true,\n sustain_conditionals : true,\n narrow : true,\n text_enable : 'Edit',\n text_disable : 'Undo',\n cls_enable : 'fa fa-edit',\n cls_disable : 'fa fa-undo',\n errors : step.messages,\n initial_errors : true,\n cls : 'ui-portlet-narrow',\n hide_operations : true,\n needs_refresh : false,\n always_refresh : step.step_type != 'tool'\n }, step );\n self.steps[ i ] = step;\n self.links[ i ] = [];\n self.parms[ i ] = {};\n });\n\n // build linear index of step input pairs\n _.each( this.steps, function( step, i ) {\n FormData.visitInputs( step.inputs, function( input, name ) {\n self.parms[ i ][ name ] = input;\n });\n });\n\n // iterate through data input modules and collect linked sub steps\n _.each( this.steps, function( step, i ) {\n _.each( step.output_connections, function( output_connection ) {\n _.each( self.steps, function( sub_step, j ) {\n sub_step.step_index === output_connection.input_step_index && self.links[ i ].push( sub_step );\n });\n });\n });\n\n // convert all connected data inputs to hidden fields with proper labels,\n // and track the linked source step\n _.each( this.steps, function( step, i ) {\n _.each( self.steps, function( sub_step, j ) {\n var connections_by_name = {};\n _.each( step.output_connections, function( connection ) {\n sub_step.step_index === connection.input_step_index && ( connections_by_name[ connection.input_name ] = connection );\n });\n _.each( self.parms[ j ], function( input, name ) {\n var connection = connections_by_name[ name ];\n if ( connection ) {\n input.type = 'hidden';\n input.help = input.step_linked ? input.help + ', ' : '';\n input.help += 'Output dataset \\'' + connection.output_name + '\\' from step ' + ( parseInt( i ) + 1 );\n input.step_linked = input.step_linked || [];\n input.step_linked.push( step );\n }\n });\n });\n });\n\n // identify and configure workflow parameters\n var wp_count = 0;\n this.wp_inputs = {};\n function _handleWorkflowParameter( value, callback ) {\n var re = /\\$\\{(.+?)\\}/g;\n while ( match = re.exec( String( value ) ) ) {\n var wp_name = match[ 1 ];\n callback( self.wp_inputs[ wp_name ] = self.wp_inputs[ wp_name ] || {\n label : wp_name,\n name : wp_name,\n type : 'text',\n color : 'hsl( ' + ( ++wp_count * 100 ) + ', 70%, 30% )',\n style : 'ui-form-wp-source',\n links : []\n });\n }\n }\n _.each( this.steps, function( step, i ) {\n _.each( self.parms[ i ], function( input, name ) {\n _handleWorkflowParameter( input.value, function( wp_input ) {\n wp_input.links.push( step );\n input.wp_linked = true;\n input.type = 'text';\n input.backdrop = true;\n input.style = 'ui-form-wp-target';\n });\n });\n _.each( step.post_job_actions, function( pja ) {\n _.each( pja.action_arguments, function( arg ) {\n _handleWorkflowParameter( arg, function() {} );\n });\n });\n });\n\n // select fields are shown for dynamic fields if all putative data inputs are available,\n // or if an explicit reference is specified as data_ref and available\n _.each( this.steps, function( step, i ) {\n if ( step.step_type == 'tool' ) {\n var data_resolved = true;\n FormData.visitInputs( step.inputs, function ( input, name, context ) {\n var is_runtime_value = input.value && input.value.__class__ == 'RuntimeValue';\n var is_data_input = ([ 'data', 'data_collection' ]).indexOf( input.type ) != -1;\n var data_ref = context[ input.data_ref ];\n input.step_linked && !self._isDataStep( input.step_linked ) && ( data_resolved = false );\n input.options && ( ( input.options.length == 0 && !data_resolved ) || input.wp_linked ) && ( input.is_workflow = true );\n data_ref && ( input.is_workflow = ( data_ref.step_linked && !self._isDataStep( data_ref.step_linked ) ) || input.wp_linked );\n ( is_data_input || ( input.value && input.value.__class__ == 'RuntimeValue' && !input.step_linked ) ) && ( step.collapsed = false );\n is_runtime_value && ( input.value = input.default_value );\n input.flavor = 'workflow';\n if ( !is_runtime_value && !is_data_input && input.type !== 'hidden' && !input.wp_linked ) {\n if ( input.optional || ( !Utils.isEmpty( input.value ) && input.value !== '' ) ) {\n input.collapsible_value = input.value;\n input.collapsible_preview = true;\n }\n }\n });\n }\n });\n },\n\n render: function() {\n var self = this;\n this.deferred.reset();\n this._renderHeader();\n this._renderMessage();\n this._renderParameters();\n this._renderHistory();\n _.each ( this.steps, function( step ) { self._renderStep( step ) } );\n },\n\n /** Render header */\n _renderHeader: function() {\n var self = this;\n this.execute_btn = new Ui.Button({\n icon : 'fa-check',\n title : 'Run workflow',\n cls : 'btn btn-primary',\n onclick : function() { self._execute() }\n });\n this.$header.addClass( 'ui-form-header' ).empty()\n .append( new Ui.Label( { title: 'Workflow: ' + this.model.get( 'name' ) } ).$el )\n .append( this.execute_btn.$el );\n },\n\n /** Render message */\n _renderMessage: function() {\n this.$message.empty();\n if ( this.model.get( 'has_upgrade_messages' ) ) {\n this.$message.append( new Ui.Message( {\n message : 'Some tools in this workflow may have changed since it was last saved or some errors were found. The workflow may still run, but any new options will have default values. Please review the messages below to make a decision about whether the changes will affect your analysis.',\n status : 'warning',\n persistent : true,\n fade : false\n } ).$el );\n }\n var step_version_changes = this.model.get( 'step_version_changes' );\n if ( step_version_changes && step_version_changes.length > 0 ) {\n this.$message.append( new Ui.Message( {\n message : 'Some tools are being executed with different versions compared to those available when this workflow was last saved because the other versions are not or no longer available on this Galaxy instance. To upgrade your workflow and dismiss this message simply edit the workflow and re-save it.',\n status : 'warning',\n persistent : true,\n fade : false\n } ).$el );\n }\n },\n\n /** Render workflow parameters */\n _renderParameters: function() {\n var self = this;\n this.wp_form = null;\n if ( !_.isEmpty( this.wp_inputs ) ) {\n this.wp_form = new Form({ title: 'Workflow Parameters', inputs: this.wp_inputs, cls: 'ui-portlet-narrow', onchange: function() {\n _.each( self.wp_form.input_list, function( input_def, i ) {\n _.each( input_def.links, function( step ) { self._refreshStep( step ) } );\n });\n }\n });\n this._append( this.$steps.empty(), this.wp_form.$el );\n }\n },\n\n /** Render workflow parameters */\n _renderHistory: function() {\n this.history_form = new Form({\n cls : 'ui-portlet-narrow',\n title : 'History Options',\n inputs : [{\n type : 'conditional',\n name : 'new_history',\n test_param : {\n name : 'check',\n label : 'Send results to a new history',\n type : 'boolean',\n value : 'false',\n help : ''\n },\n cases : [{\n value : 'true',\n inputs : [{\n name : 'name',\n label : 'History name',\n type : 'text',\n value : this.model.get( 'name' )\n }]\n }]\n }]\n });\n this._append( this.$steps, this.history_form.$el );\n },\n\n /** Render step */\n _renderStep: function( step ) {\n var self = this;\n var form = null;\n this.deferred.execute( function( promise ) {\n self.$steps.addClass( 'ui-steps' );\n if ( step.step_type == 'tool' ) {\n step.postchange = function( process, form ) {\n var self = this;\n var current_state = {\n tool_id : step.id,\n tool_version : step.version,\n inputs : $.extend( true, {}, form.data.create() )\n }\n form.wait( true );\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Sending current state.', current_state );\n Utils.request({\n type : 'POST',\n url : Galaxy.root + 'api/tools/' + step.id + '/build',\n data : current_state,\n success : function( data ) {\n form.update( data );\n form.wait( false );\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Received new model.', data );\n process.resolve();\n },\n error : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Refresh request failed.', response );\n process.reject();\n }\n });\n };\n form = new ToolFormBase( step );\n if ( step.post_job_actions && step.post_job_actions.length ) {\n form.portlet.append( $( '
                          ' ).addClass( 'ui-form-element-disabled' )\n .append( $( '
                          ' ).addClass( 'ui-form-title' ).html( 'Job Post Actions' ) )\n .append( $( '
                          ' ).addClass( 'ui-form-preview' ).html(\n _.reduce( step.post_job_actions, function( memo, value ) {\n return memo + ' ' + value.short_str;\n }, '' ) ) )\n );\n }\n } else {\n var is_simple_input = ([ 'data_input', 'data_collection_input' ]).indexOf( step.step_type ) != -1;\n _.each( step.inputs, function( input ) { input.flavor = 'module'; input.hide_label = is_simple_input; } );\n form = new Form( Utils.merge({\n title : step.title,\n onchange : function() { _.each( self.links[ step.index ], function( link ) { self._refreshStep( link ) } ) },\n inputs : step.inputs && step.inputs.length > 0 ? step.inputs : [ { type: 'hidden', name: 'No options available.', ignore: null } ]\n }, step ) );\n }\n self.forms[ step.index ] = form;\n self._append( self.$steps, form.$el );\n self._refresh();\n step.needs_refresh && self._refreshStep( step );\n form.portlet[ !self.show_progress ? 'enable' : 'disable' ]();\n self.show_progress && self.execute_btn.model.set( { wait : true,\n wait_text : 'Preparing...',\n percentage : ( step.index + 1 ) * 100.0 / self.steps.length } );\n Galaxy.emit.debug( 'tool-form-composite::initialize()', step.index + ' : Workflow step state ready.', step );\n setTimeout( function() { promise.resolve() }, 0 );\n });\n },\n\n /** Refreshes step values from source step values */\n _refreshStep: function( step ) {\n var self = this;\n var form = this.forms[ step.index ];\n if ( form ) {\n _.each( self.parms[ step.index ], function( input, name ) {\n if ( input.step_linked || input.wp_linked ) {\n var field = form.field_list[ form.data.match( name ) ];\n if ( field ) {\n var new_value = undefined;\n if ( input.step_linked ) {\n new_value = { values: [] };\n _.each( input.step_linked, function( source_step ) {\n if ( self._isDataStep( source_step ) ) {\n value = self.forms[ source_step.index ].data.create().input;\n value && _.each( value.values, function( v ) { new_value.values.push( v ) } );\n }\n });\n if ( !input.multiple && new_value.values.length > 0 ) {\n new_value = { values: [ new_value.values[ 0 ] ] };\n }\n } else if ( input.wp_linked ) {\n new_value = input.value;\n var re = /\\$\\{(.+?)\\}/g;\n while ( match = re.exec( input.value ) ) {\n var wp_field = self.wp_form.field_list[ self.wp_form.data.match( match[ 1 ] ) ];\n var wp_value = wp_field && wp_field.value();\n if ( wp_value ) {\n new_value = new_value.split( match[ 0 ] ).join( wp_value );\n }\n }\n }\n if ( new_value !== undefined ) {\n field.value( new_value );\n }\n }\n }\n });\n form.trigger( 'change' );\n } else {\n step.needs_refresh = true;\n }\n },\n\n /** Refresh the history after job submission while form is shown */\n _refreshHistory: function() {\n var self = this;\n var history = parent.Galaxy && parent.Galaxy.currHistoryPanel && parent.Galaxy.currHistoryPanel.model;\n this._refresh_history && clearTimeout( this._refresh_history );\n if ( history ) {\n history.refresh().success( function() {\n if ( history.numOfUnfinishedShownContents() === 0 ) {\n self._refresh_history = setTimeout( function() { self._refreshHistory() }, history.UPDATE_DELAY );\n }\n });\n }\n },\n\n /** Build remaining steps */\n _execute: function() {\n var self = this;\n this.show_progress = true;\n this._enabled( false );\n this.deferred.execute( function( promise ) {\n setTimeout( function() { promise.resolve(); self._submit(); }, 0 );\n });\n },\n\n /** Validate and submit workflow */\n _submit: function() {\n var self = this;\n var history_form_data = this.history_form.data.create();\n var job_def = {\n new_history_name : history_form_data[ 'new_history|name' ] ? history_form_data[ 'new_history|name' ] : null,\n history_id : !history_form_data[ 'new_history|name' ] ? this.model.get( 'history_id' ) : null,\n replacement_params : this.wp_form ? this.wp_form.data.create() : {},\n parameters : {},\n // Tool form will submit flat maps for each parameter\n // (e.g. \"repeat_0|cond|param\": \"foo\" instead of nested\n // data structures).\n parameters_normalized : true,\n // Tool form always wants a list of invocations back\n // so that inputs can be batched.\n batch : true\n };\n var validated = true;\n for ( var i in this.forms ) {\n var form = this.forms[ i ];\n var job_inputs = form.data.create();\n var step = self.steps[ i ];\n var step_index = step.step_index;\n form.trigger( 'reset' );\n for ( var job_input_id in job_inputs ) {\n var input_value = job_inputs[ job_input_id ];\n var input_id = form.data.match( job_input_id );\n var input_field = form.field_list[ input_id ];\n var input_def = form.input_list[ input_id ];\n if ( !input_def.step_linked ) {\n if ( this._isDataStep( step ) ) {\n validated = input_value && input_value.values && input_value.values.length > 0;\n } else {\n validated = input_def.optional || ( input_def.is_workflow && input_value !== '' ) || ( !input_def.is_workflow && input_value !== null );\n }\n if ( !validated ) {\n form.highlight( input_id );\n break;\n }\n job_def.parameters[ step_index ] = job_def.parameters[ step_index ] || {};\n job_def.parameters[ step_index ][ job_input_id ] = job_inputs[ job_input_id ];\n }\n }\n if ( !validated ) {\n break;\n }\n }\n if ( !validated ) {\n self._enabled( true );\n Galaxy.emit.debug( 'tool-form-composite::submit()', 'Validation failed.', job_def );\n } else {\n Galaxy.emit.debug( 'tool-form-composite::submit()', 'Validation complete.', job_def );\n Utils.request({\n type : 'POST',\n url : Galaxy.root + 'api/workflows/' + this.model.id + '/invocations',\n data : job_def,\n success : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::submit', 'Submission successful.', response );\n self.$el.children().hide();\n self.$el.append( self._templateSuccess( response ) );\n\n // Show Webhook if job is running\n if ($.isArray( response ) && response.length > 0) {\n self.$el.append( $( '
                          ', { id: 'webhook-view' } ) );\n var WebhookApp = new Webhooks.WebhookView({\n urlRoot: Galaxy.root + 'api/webhooks/workflow',\n toolId: job_def.tool_id,\n toolVersion: job_def.tool_version,\n });\n }\n\n self._refreshHistory();\n },\n error : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::submit', 'Submission failed.', response );\n var input_found = false;\n if ( response && response.err_data ) {\n for ( var i in self.forms ) {\n var form = self.forms[ i ];\n var step_related_errors = response.err_data[ form.model.get( 'step_index' ) ];\n if ( step_related_errors ) {\n var error_messages = form.data.matchResponse( step_related_errors );\n for ( var input_id in error_messages ) {\n form.highlight( input_id, error_messages[ input_id ] );\n input_found = true;\n break;\n }\n }\n }\n }\n if ( !input_found ) {\n self.modal.show({\n title : 'Workflow submission failed',\n body : self._templateError( job_def, response && response.err_msg ),\n buttons : {\n 'Close' : function() {\n self.modal.hide();\n }\n }\n });\n }\n },\n complete: function() {\n self._enabled( true );\n }\n });\n }\n },\n\n /** Append new dom to body */\n _append: function( $container, $el ) {\n $container.append( '

                          ' ).append( $el );\n },\n\n /** Set enabled/disabled state */\n _enabled: function( enabled ) {\n this.execute_btn.model.set( { wait: !enabled, wait_text: 'Sending...', percentage: -1 } );\n this.wp_form && this.wp_form.portlet[ enabled ? 'enable' : 'disable' ]();\n this.history_form && this.history_form.portlet[ enabled ? 'enable' : 'disable' ]();\n _.each( this.forms, function( form ) { form && form.portlet[ enabled ? 'enable' : 'disable' ]() } );\n },\n\n /** Is data input module/step */\n _isDataStep: function( steps ) {\n lst = $.isArray( steps ) ? steps : [ steps ] ;\n for ( var i = 0; i < lst.length; i++ ) {\n var step = lst[ i ];\n if ( !step || !step.step_type || !step.step_type.startsWith( 'data' ) ) {\n return false;\n }\n }\n return true;\n },\n\n /** Templates */\n _templateSuccess: function( response ) {\n if ( $.isArray( response ) && response.length > 0 ) {\n return $( '

                          ' ).addClass( 'donemessagelarge' )\n .append( $( '

                          ' ).html( 'Successfully invoked workflow ' + Utils.sanitize( this.model.get( 'name' ) ) + '' + ( response.length > 1 ? ' ' + response.length + ' times' : '' ) + '.' ) )\n .append( $( '

                          ' ).append( '' ).text( 'You can check the status of queued jobs and view the resulting data by refreshing the History pane. When the job has been run the status will change from \\'running\\' to \\'finished\\' if completed successfully or \\'error\\' if problems were encountered.' ) );\n } else {\n return this._templateError( response, 'Invalid success response. No invocations found.' );\n }\n },\n\n _templateError: function( response, err_msg ) {\n return $( '

                          ' ).addClass( 'errormessagelarge' )\n .append( $( '

                          ' ).text( 'The server could not complete the request. Please contact the Galaxy Team if this error persists. ' + ( JSON.stringify( err_msg ) || '' ) ) )\n .append( $( '

                          ' ).text( JSON.stringify( response, null, 4 ) ) );\n        }\n    });\n    return {\n        View: View\n    };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tool/tool-form-composite.js","define([\n    \"utils/localization\"\n], function( _l ){\n'use strict';\n\n//TODO: toastr is another possibility - I didn't see where I might add details, tho\n\n/* ============================================================================\nError modals meant to replace the o-so-easy alerts.\n\nThese are currently styled as errormessages but use the Galaxy.modal\ninfrastructure to be shown/closed. They're capable of showing details in a\ntogglable dropdown and the details are formatted in a pre.\n\nExample:\n    errorModal( 'Heres a message', 'A Title', { some_details: 'here' });\n    errorModal( 'Heres a message' ); // no details, title is 'Error'\n\nThere are three specialized forms:\n    offlineErrorModal       a canned response for when there's no connection\n    badGatewayErrorModal    canned response for when Galaxy is restarting\n    ajaxErrorModal          plugable into any Backbone class as an\n        error event handler by accepting the error args: model, xhr, options\n\nExamples:\n    if( navigator.offLine ){ offlineErrorModal(); }\n    if( xhr.status === 502 ){ badGatewayErrorModal(); }\n    this.listenTo( this.model, 'error', ajaxErrorModal );\n\n============================================================================ */\n\nvar CONTACT_MSG = _l( 'Please contact a Galaxy administrator if the problem persists.' );\nvar DEFAULT_AJAX_ERR_MSG = _l( 'An error occurred while updating information with the server.' );\nvar DETAILS_MSG = _l( 'The following information can assist the developers in finding the source of the error:' );\n\n/** private helper that builds the modal and handles adding details */\nfunction _errorModal( message, title, details ){\n    // create and return the modal, adding details button only if needed\n    Galaxy.modal.show({\n        title           : title,\n        body            : message,\n        closing_events  : true,\n        buttons         : { Ok: function(){ Galaxy.modal.hide(); } },\n    });\n    Galaxy.modal.$el.addClass( 'error-modal' );\n\n    if( details ){\n        Galaxy.modal.$( '.error-details' ).add( Galaxy.modal.$( 'button:contains(\"Details\")' ) ).remove();\n        $( '
                          ' ).addClass( 'error-details' )\n .hide().appendTo( Galaxy.modal.$( '.modal-content' ) )\n .append([\n $( '

                          ' ).text( DETAILS_MSG ),\n $( '

                          ' ).text( JSON.stringify( details, null, '  ' ) )\n            ]);\n\n        $( '' )\n            .appendTo( Galaxy.modal.$( '.buttons' ) )\n            .click( function(){ Galaxy.modal.$( '.error-details' ).toggle(); });\n    }\n    return Galaxy.modal;\n}\n\n/** Display a modal showing an error message but fallback to alert if there's no modal */\nfunction errorModal( message, title, details ){\n    if( !message ){ return; }\n\n    message = _l( message );\n    title = _l( title ) || _l( 'Error:' );\n    if( window.Galaxy && Galaxy.modal ){\n        return _errorModal( message, title, details );\n    }\n\n    alert( title + '\\n\\n' + message );\n    console.log( 'error details:', JSON.stringify( details ) );\n}\n\n\n// ----------------------------------------------------------------------------\n/** display a modal when the user may be offline */\nfunction offlineErrorModal(){\n    return errorModal(\n        _l( 'You appear to be offline. Please check your connection and try again.' ),\n        _l( 'Offline?' )\n    );\n}\n\n\n// ----------------------------------------------------------------------------\n/** 502 messages that should be displayed when galaxy is restarting */\nfunction badGatewayErrorModal(){\n    return errorModal(\n        _l( 'Galaxy is currently unreachable. Please try again in a few minutes.' ) + ' ' + CONTACT_MSG,\n        _l( 'Cannot connect to Galaxy' )\n    );\n}\n\n\n// ----------------------------------------------------------------------------\n/** display a modal (with details) about a failed Backbone ajax operation */\nfunction ajaxErrorModal( model, xhr, options, message, title ){\n    message = message || DEFAULT_AJAX_ERR_MSG;\n    message += ' ' + CONTACT_MSG;\n    title = title || _l( 'An error occurred' );\n    var details = _ajaxDetails( model, xhr, options );\n    return errorModal( message, title, details );\n}\n\n/** build details which may help debugging the ajax call */\nfunction _ajaxDetails( model, xhr, options ){\n    return {\n//TODO: still can't manage Raven id\n        raven       : _.result( window.Raven, 'lastEventId' ),\n        userAgent   : navigator.userAgent,\n        onLine      : navigator.onLine,\n        version     : _.result( Galaxy.config, 'version_major' ),\n        xhr         : _.omit( xhr, _.functions( xhr ) ),\n        options     : _.omit( options, 'xhr' ),\n        // add ajax data from Galaxy object cache\n        url         : _.result( Galaxy.lastAjax, 'url' ),\n        data        : _.result( Galaxy.lastAjax, 'data' ),\n        // backbone stuff (auto-redacting email for user)\n        model       : _.result( model, 'toJSON' , model + '' ),\n        user        : _.omit( _.result( Galaxy.user, 'toJSON' ), 'email' ),\n    };\n}\n\n\n//=============================================================================\n    return {\n        errorModal          : errorModal,\n        offlineErrorModal   : offlineErrorModal,\n        badGatewayErrorModal: badGatewayErrorModal,\n        ajaxErrorModal      : ajaxErrorModal\n    };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/ui/error-modal.js","(function (factory) {\n    if (typeof define === 'function' && define.amd) {\n        define([], factory);\n    } else {\n        // Browser globals\n        factory(jQuery);\n    }\n\n}(function () {\n//=============================================================================\n\n    jQuery.fn.extend({\n        hoverhighlight : function $hoverhighlight( scope, color ){\n            scope = scope || 'body';\n            if( !this.length ){ return this; }\n\n            $( this ).each( function(){\n                var $this = $( this ),\n                    targetSelector = $this.data( 'target' );\n\n                if( targetSelector ){\n                    $this.mouseover( function( ev ){\n                        $( targetSelector, scope ).css({\n                            background: color\n                        });\n                    })\n                    .mouseout( function( ev ){\n                        $( targetSelector ).css({\n                            background: ''\n                        });\n                    });\n                }\n            });\n            return this;\n        }\n    });\n}));\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/ui/hoverhighlight.js","// from: https://raw.githubusercontent.com/umdjs/umd/master/jqueryPlugin.js\n// Uses AMD or browser globals to create a jQuery plugin.\n(function (factory) {\n    if (typeof define === 'function' && define.amd) {\n        //TODO: So...this turns out to be an all or nothing thing. If I load jQuery in the define below, it will\n        //  (of course) wipe the old jquery *and all the plugins loaded into it*. So the define below *is still\n        //  relying on jquery being loaded globally* in order to preserve plugins.\n        define([], factory);\n    } else {\n        // Browser globals\n        factory(jQuery);\n    }\n\n}(function () {\n    var _l = window._l || function( s ){ return s; };\n\n    //TODO: consolidate with tool menu functionality, use there\n\n    /** searchInput: (jQuery plugin)\n     *      Creates a search input, a clear button, and loading indicator\n     *      within the selected node.\n     *\n     *      When the user either presses return or enters some minimal number\n     *      of characters, a callback is called. Pressing ESC when the input\n     *      is focused will clear the input and call a separate callback.\n     */\n    function searchInput( parentNode, options ){\n        var KEYCODE_ESC     = 27,\n            KEYCODE_RETURN  = 13,\n            $parentNode     = $( parentNode ),\n            firstSearch     = true,\n            defaults = {\n                initialVal      : '',\n                name            : 'search',\n                placeholder     : 'search',\n                classes         : '',\n                onclear         : function(){},\n                onfirstsearch   : null,\n                onsearch        : function( inputVal ){},\n                minSearchLen    : 0,\n                escWillClear    : true,\n                oninit          : function(){}\n            };\n\n        // .................................................................... input rendering and events\n        // visually clear the search, trigger an event, and call the callback\n        function clearSearchInput( event ){\n            var $input = $( this ).parent().children( 'input' );\n            $input.val( '' ).trigger( 'searchInput.clear' ).blur();\n            options.onclear();\n        }\n\n        // search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)\n        function search( event, searchTerms ){\n            if( !searchTerms ){\n                return clearSearchInput();\n            }\n            $( this ).trigger( 'search.search', searchTerms );\n            if( typeof options.onfirstsearch === 'function' && firstSearch ){\n                firstSearch = false;\n                options.onfirstsearch( searchTerms );\n            } else {\n                options.onsearch( searchTerms );\n            }\n        }\n\n        // .................................................................... input rendering and events\n        function inputTemplate(){\n            // class search-query is bootstrap 2.3 style that now lives in base.less\n            return [ '' ].join( '' );\n        }\n\n        // the search input that responds to keyboard events and displays the search value\n        function $input(){\n            return $( inputTemplate() )\n                // select all text on a focus\n                .focus( function( event ){\n                    $( this ).select();\n                })\n                // attach behaviors to esc, return if desired, search on some min len string\n                .keyup( function( event ){\n                    event.preventDefault();\n                    event.stopPropagation();\n\n                    // esc key will clear if desired\n                    if( event.which === KEYCODE_ESC && options.escWillClear ){\n                        clearSearchInput.call( this, event );\n\n                    } else {\n                        var searchTerms = $( this ).val();\n                        // return key or the search string len > minSearchLen (if not 0) triggers search\n                        if( ( event.which === KEYCODE_RETURN )\n                        ||  ( options.minSearchLen && searchTerms.length >= options.minSearchLen ) ){\n                            search.call( this, event, searchTerms );\n                        }\n                    }\n                })\n                .val( options.initialVal );\n        }\n\n        // .................................................................... clear button rendering and events\n        // a button for clearing the search bar, placed on the right hand side\n        function $clearBtn(){\n            return $([ '' ].join('') )\n            .tooltip({ placement: 'bottom' })\n            .click( function( event ){\n                clearSearchInput.call( this, event );\n            });\n        }\n\n        // .................................................................... loadingIndicator rendering\n        // a button for clearing the search bar, placed on the right hand side\n        function $loadingIndicator(){\n            return $([ '' ].join('') )\n                .hide().tooltip({ placement: 'bottom' });\n        }\n\n        // .................................................................... commands\n        // visually swap the load, clear buttons\n        function toggleLoadingIndicator(){\n            $parentNode.find( '.search-loading' ).toggle();\n            $parentNode.find( '.search-clear' ).toggle();\n        }\n\n        // .................................................................... init\n        // string command (not constructor)\n        if( jQuery.type( options ) === 'string' ){\n            if( options === 'toggle-loading' ){\n                toggleLoadingIndicator();\n            }\n            return $parentNode;\n        }\n\n        // initial render\n        if( jQuery.type( options ) === 'object' ){\n            options = jQuery.extend( true, {}, defaults, options );\n        }\n        //NOTE: prepended\n        return $parentNode.addClass( 'search-input' ).prepend([ $input(), $clearBtn(), $loadingIndicator() ]);\n    }\n\n    // as jq plugin\n    jQuery.fn.extend({\n        searchInput : function $searchInput( options ){\n            return this.each( function(){\n                return searchInput( this, options );\n            });\n        }\n    });\n}));\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/ui/search-input.js","define([], function(){\n// Alphanumeric/natural sort fn\nfunction naturalSort(a, b) {\n    // setup temp-scope variables for comparison evauluation\n    var re = /(-?[0-9\\.]+)/g,\n        x = a.toString().toLowerCase() || '',\n        y = b.toString().toLowerCase() || '',\n        nC = String.fromCharCode(0),\n        xN = x.replace( re, nC + '$1' + nC ).split(nC),\n        yN = y.replace( re, nC + '$1' + nC ).split(nC),\n        xD = (new Date(x)).getTime(),\n        yD = xD ? (new Date(y)).getTime() : null;\n    // natural sorting of dates\n    if ( yD ) {\n        if ( xD < yD ) { return -1; }\n        else if ( xD > yD ) { return 1; }\n    }\n    // natural sorting through split numeric strings and default strings\n    var oFxNcL, oFyNcL;\n    for ( var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++ ) {\n        oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];\n        oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];\n        if (oFxNcL < oFyNcL) { return -1; }\n        else if (oFxNcL > oFyNcL) { return 1; }\n    }\n    return 0;\n}\n\nreturn naturalSort;\n})\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/utils/natural-sort.js","var Ui = require( 'mvc/ui/ui-misc' ),\n    historyOptionsMenu = require( 'mvc/history/options-menu' );\n    CurrentHistoryView = require( 'mvc/history/history-view-edit-current' ).CurrentHistoryView,\n    _l = require( 'utils/localization' );\n\n/** the right hand panel in the analysis page that shows the current history */\nvar HistoryPanel = Backbone.View.extend({\n\n    initialize : function( page, options ) {\n        var self = this;\n        this.userIsAnonymous            = Galaxy.user.isAnonymous();\n        this.allow_user_dataset_purge   = options.config.allow_user_dataset_purge;\n        this.root                       = options.root;\n\n        // view of the current history\n        this.historyView = new CurrentHistoryView({\n            className       : CurrentHistoryView.prototype.className + ' middle',\n            purgeAllowed    : this.allow_user_dataset_purge,\n            linkTarget      : 'galaxy_main'\n        });\n\n        // add history panel to Galaxy object\n        Galaxy.currHistoryPanel = this.historyView;\n        Galaxy.currHistoryPanel.listenToGalaxy( Galaxy );\n\n        // build buttons\n        this.buttonRefresh = new Ui.ButtonLink({\n            id      : 'history-refresh-button',\n            title   : 'Refresh history',\n            cls     : 'panel-header-button',\n            icon    : 'fa fa-refresh',\n            onclick : function() {\n                self.historyView.loadCurrentHistory();\n            }\n        });\n        this.buttonOptions = new Ui.ButtonLink({\n            id      : 'history-options-button',\n            title   : 'History options',\n            cls     : 'panel-header-button',\n            target  : 'galaxy_main',\n            icon    : 'fa fa-cog',\n            href    : this.root + 'root/history_options'\n        });\n        this.buttonViewMulti = new Ui.ButtonLink({\n            id      : 'history-view-multi-button',\n            title   : 'View all histories',\n            cls     : 'panel-header-button',\n            icon    : 'fa fa-columns',\n            href    : this.root + 'history/view_multiple'\n        });\n\n        // define components\n        this.model = new Backbone.Model({\n            cls     : 'history-right-panel',\n            title   : _l( 'History' ),\n            buttons : [ this.buttonRefresh, this.buttonOptions, this.buttonViewMulti ]\n        });\n\n        // build body template and connect history view\n        this.setElement( this._template() );\n        this.historyView.setElement( this.$el );\n        this.historyView.connectToQuotaMeter( Galaxy.quotaMeter );\n        this.historyView.loadCurrentHistory();\n\n        // fetch to update the quota meter adding 'current' for any anon-user's id\n        Galaxy.listenTo( this.historyView, 'history-size-change', function(){\n            Galaxy.user.fetch({ url: Galaxy.user.urlRoot() + '/' + ( Galaxy.user.id || 'current' ) });\n        });\n    },\n\n    render : function() {\n        this.optionsMenu = historyOptionsMenu( this.buttonOptions.$el, {\n            anonymous    : this.userIsAnonymous,\n            purgeAllowed : this.allow_user_dataset_purge,\n            root         : this.root\n        });\n        this.buttonViewMulti.$el[ !this.userIsAnonymous ? 'show' : 'hide' ]();\n    },\n\n    /** add history view div */\n    _template : function( data ){\n        return [\n            '
                          ',\n ].join('');\n },\n\n toString : function() { return 'historyPanel' }\n});\n\nmodule.exports = HistoryPanel;\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/apps/panels/history-panel.js","var Tools = require( 'mvc/tool/tools' ),\n Upload = require( 'mvc/upload/upload-view' ),\n _l = require( 'utils/localization' ),\n ToolForm = require( 'mvc/tool/tool-form-composite' );\n\nvar ToolPanel = Backbone.View.extend({\n initialize: function( page, options ) {\n // access configuration options\n var config = options.config;\n this.root = options.root;\n\n /** @type {Object[]} descriptions of user's workflows to be shown in the tool menu */\n this.stored_workflow_menu_entries = config.stored_workflow_menu_entries || [];\n\n // create tool search, tool panel, and tool panel view.\n var tool_search = new Tools.ToolSearch({\n hidden : false\n });\n var tools = new Tools.ToolCollection( config.toolbox );\n this.tool_panel = new Tools.ToolPanel({\n tool_search : tool_search,\n tools : tools,\n layout : config.toolbox_in_panel\n });\n this.tool_panel_view = new Tools.ToolPanelView({ model: this.tool_panel });\n\n // add upload modal\n this.upload_button = new Upload({\n nginx_upload_path : config.nginx_upload_path,\n ftp_upload_site : config.ftp_upload_site,\n default_genome : config.default_genome,\n default_extension : config.default_extension,\n });\n\n // add uploader button to Galaxy object\n Galaxy.upload = this.upload_button;\n\n // components for panel definition\n this.model = new Backbone.Model({\n title : _l( 'Tools' ),\n buttons : [ this.upload_button ]\n });\n\n // build body template\n this.setElement( this._template() );\n },\n\n render : function(){\n // if there are tools, render panel and display everything\n var self = this;\n if ( this.tool_panel.get( 'layout' ).size() > 0 ) {\n this.$el.prepend( this.tool_panel_view.$el );\n this.tool_panel_view.render();\n }\n // build the dom for the workflow portion of the tool menu\n // add internal workflow list\n self.$( '#internal-workflows' ).append( self._templateAllWorkflow({\n title : _l( 'All workflows' ),\n href : 'workflow'\n }));\n _.each( this.stored_workflow_menu_entries, function( menu_entry ){\n self.$( '#internal-workflows' ).append( self._templateWorkflowLink({\n title : menu_entry.stored_workflow.name,\n href : 'workflow/run?id=' + menu_entry.encoded_stored_workflow_id\n }));\n });\n },\n\n /** build a link to one tool */\n _templateTool: function( tool ) {\n return [\n '
                          ',\n '', tool.title, '',\n '
                          '\n ].join('');\n },\n\n /** build a link to 'All Workflows' */\n _templateAllWorkflow: function( tool ) {\n return [\n '
                          ',\n // global\n '', tool.title, '',\n '
                          '\n ].join('');\n },\n\n /** build links to workflows in toolpanel */\n _templateWorkflowLink: function( wf ) {\n return [\n '
                          ',\n '', wf.title, '',\n '
                          '\n ].join('');\n },\n\n /** override to include inital menu dom and workflow section */\n _template : function() {\n return [\n '
                          ',\n '
                          ',\n '
                          ',\n '', _l( 'Search did not match any tools.' ), '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '', _l( 'Workflows' ), '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ].join('');\n },\n\n toString : function() { return 'toolPanel' }\n});\n\nmodule.exports = ToolPanel;\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/apps/panels/tool-panel.js","define([\n \"mvc/collection/collection-li\",\n \"mvc/dataset/dataset-li-edit\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DC_LI, DATASET_LI_EDIT, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar DCListItemView = DC_LI.DCListItemView;\n/** @class Edit view for DatasetCollection.\n */\nvar DCListItemEdit = DCListItemView.extend(\n/** @lends DCListItemEdit.prototype */{\n\n /** override to add linkTarget */\n initialize : function( attributes ){\n DCListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\nvar DCEListItemView = DC_LI.DCEListItemView;\n/** @class Read only view for DatasetCollectionElement.\n */\nvar DCEListItemEdit = DCEListItemView.extend(\n/** @lends DCEListItemEdit.prototype */{\n//TODO: this might be expendable - compacted with HDAListItemView\n\n /** set up */\n initialize : function( attributes ){\n DCEListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCEListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n// NOTE: this does not inherit from DatasetDCEListItemView as you would expect\n//TODO: but should - if we can find something simpler than using diamond\n/** @class Editable view for a DatasetCollectionElement that is also an DatasetAssociation\n * (a dataset contained in a dataset collection).\n */\nvar DatasetDCEListItemEdit = DATASET_LI_EDIT.DatasetListItemEdit.extend(\n/** @lends DatasetDCEListItemEdit.prototype */{\n\n /** set up */\n initialize : function( attributes ){\n DATASET_LI_EDIT.DatasetListItemEdit.prototype.initialize.call( this, attributes );\n },\n\n // NOTE: this does not inherit from DatasetDCEListItemView - so we duplicate this here\n //TODO: fix\n /** In this override, only get details if in the ready state.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n /** Override to remove delete button */\n _renderDeleteButton : function(){\n return null;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetDCEListItemEdit(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetDCEListItemEdit.prototype.templates = (function(){\n\n return _.extend( {}, DATASET_LI_EDIT.DatasetListItemEdit.prototype.templates, {\n titleBar : DC_LI.DatasetDCEListItemView.prototype.templates.titleBar\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n * (a nested DC).\n */\nvar NestedDCDCEListItemEdit = DC_LI.NestedDCDCEListItemView.extend(\n/** @lends NestedDCDCEListItemEdit.prototype */{\n\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'NestedDCDCEListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n return {\n DCListItemEdit : DCListItemEdit,\n DCEListItemEdit : DCEListItemEdit,\n DatasetDCEListItemEdit : DatasetDCEListItemEdit,\n NestedDCDCEListItemEdit : NestedDCDCEListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-li-edit.js","define([\n \"mvc/collection/collection-view\",\n \"mvc/collection/collection-model\",\n \"mvc/collection/collection-li-edit\",\n \"mvc/base-mvc\",\n \"mvc/tag\",\n \"ui/fa-icon-button\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function( DC_VIEW, DC_MODEL, DC_EDIT, BASE_MVC, TAGS, faIconButton, _l ){\n\n'use strict';\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class editable View/Controller for a dataset collection.\n */\nvar _super = DC_VIEW.CollectionView;\nvar CollectionViewEdit = _super.extend(\n/** @lends CollectionView.prototype */{\n //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\n /** logger used to record this.log messages, commonly set to console */\n //logger : console,\n\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_EDIT.DatasetDCEListItemEdit,\n /** sub view class used for nested collections */\n NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit,\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n },\n\n /** In this override, make the collection name editable\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n _super.prototype._setUpBehaviors.call( this, $where );\n if( !this.model ){ return; }\n\n // anon users shouldn't have access to any of the following\n if( !Galaxy.user || Galaxy.user.isAnonymous() ){\n return;\n }\n\n this.tagsEditorShown = true;\n\n //TODO: extract\n var panel = this,\n nameSelector = '> .controls .name';\n $where.find( nameSelector )\n .attr( 'title', _l( 'Click to rename collection' ) )\n .tooltip({ placement: 'bottom' })\n .make_text_editable({\n on_finish: function( newName ){\n var previousName = panel.model.get( 'name' );\n if( newName && newName !== previousName ){\n panel.$el.find( nameSelector ).text( newName );\n panel.model.save({ name: newName })\n .fail( function(){\n panel.$el.find( nameSelector ).text( panel.model.previous( 'name' ) );\n });\n } else {\n panel.$el.find( nameSelector ).text( previousName );\n }\n }\n });\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n usePrompt : false\n });\n this.tagsEditor.toggle( true );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'CollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_EDIT.DatasetDCEListItemEdit,\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class Editable, read-only View/Controller for a dataset collection. */\nvar PairCollectionViewEdit = ListCollectionViewEdit.extend(\n/** @lends PairCollectionViewEdit.prototype */{\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'PairCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class Editable (roughly since these collections are immutable),\n * View/Controller for a dataset collection.\n */\nvar NestedPairCollectionViewEdit = PairCollectionViewEdit.extend(\n/** @lends NestedPairCollectionViewEdit.prototype */{\n\n /** Override to remove the editable text from the name/identifier - these collections are considered immutable */\n _setUpBehaviors : function( $where ){\n _super.prototype._setUpBehaviors.call( this, $where );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'NestedPairCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class editable, View/Controller for a list of pairs dataset collection. */\nvar ListOfPairsCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListOfPairsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_EDIT.NestedDCDCEListItemEdit.extend({\n foldoutPanelClass : NestedPairCollectionViewEdit\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfPairsCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class View/Controller for a list of lists dataset collection. */\nvar ListOfListsCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListOfListsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_EDIT.NestedDCDCEListItemEdit.extend({\n foldoutPanelClass : NestedPairCollectionViewEdit\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfListsCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//==============================================================================\n return {\n CollectionViewEdit : CollectionViewEdit,\n ListCollectionViewEdit : ListCollectionViewEdit,\n PairCollectionViewEdit : PairCollectionViewEdit,\n ListOfPairsCollectionViewEdit : ListOfPairsCollectionViewEdit,\n ListOfListsCollectionViewEdit : ListOfListsCollectionViewEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-view-edit.js","define([\n \"utils/levenshtein\",\n \"utils/natural-sort\",\n \"mvc/collection/base-creator\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/hoverhighlight\"\n], function( levenshteinDistance, naturalSort, baseCreator, baseMVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/* ============================================================================\nTODO:\n\n\nPROGRAMMATICALLY:\ncurrPanel.once( 'rendered', function(){\n currPanel.showSelectors();\n currPanel.selectAll();\n _.last( currPanel.actionsPopup.options ).func();\n});\n\n============================================================================ */\n/** A view for paired datasets in the collections creator.\n */\nvar PairView = Backbone.View.extend( baseMVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n tagName : 'li',\n className : 'dataset paired',\n\n initialize : function( attributes ){\n this.pair = attributes.pair || {};\n },\n\n template : _.template([\n '<%- pair.forward.name %>',\n '',\n '<%- pair.name %>',\n '',\n '<%- pair.reverse.name %>'\n ].join('')),\n\n render : function(){\n this.$el\n .attr( 'draggable', true )\n .data( 'pair', this.pair )\n .html( this.template({ pair: this.pair }) )\n .addClass( 'flex-column-container' );\n return this;\n },\n\n events : {\n 'dragstart' : '_dragstart',\n 'dragend' : '_dragend',\n 'dragover' : '_sendToParent',\n 'drop' : '_sendToParent'\n },\n\n /** dragging pairs for re-ordering */\n _dragstart : function( ev ){\n ev.currentTarget.style.opacity = '0.4';\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n\n ev.dataTransfer.effectAllowed = 'move';\n ev.dataTransfer.setData( 'text/plain', JSON.stringify( this.pair ) );\n\n this.$el.parent().trigger( 'pair.dragstart', [ this ] );\n },\n\n /** dragging pairs for re-ordering */\n _dragend : function( ev ){\n ev.currentTarget.style.opacity = '1.0';\n this.$el.parent().trigger( 'pair.dragend', [ this ] );\n },\n\n /** manually bubble up an event to the parent/container */\n _sendToParent : function( ev ){\n this.$el.parent().trigger( ev );\n },\n\n /** string rep */\n toString : function(){\n return 'PairView(' + this.pair.name + ')';\n }\n});\n\n\n// ============================================================================\n/** returns an autopair function that uses the provided options.match function */\nfunction autoPairFnBuilder( options ){\n options = options || {};\n options.createPair = options.createPair || function _defaultCreatePair( params ){\n params = params || {};\n var a = params.listA.splice( params.indexA, 1 )[0],\n b = params.listB.splice( params.indexB, 1 )[0],\n aInBIndex = params.listB.indexOf( a ),\n bInAIndex = params.listA.indexOf( b );\n if( aInBIndex !== -1 ){ params.listB.splice( aInBIndex, 1 ); }\n if( bInAIndex !== -1 ){ params.listA.splice( bInAIndex, 1 ); }\n return this._pair( a, b, { silent: true });\n };\n // compile these here outside of the loop\n var _regexps = [];\n function getRegExps(){\n if( !_regexps.length ){\n _regexps = [\n new RegExp( this.filters[0] ),\n new RegExp( this.filters[1] )\n ];\n }\n return _regexps;\n }\n // mangle params as needed\n options.preprocessMatch = options.preprocessMatch || function _defaultPreprocessMatch( params ){\n var regexps = getRegExps.call( this );\n return _.extend( params, {\n matchTo : params.matchTo.name.replace( regexps[0], '' ),\n possible : params.possible.name.replace( regexps[1], '' )\n });\n };\n\n return function _strategy( params ){\n this.debug( 'autopair _strategy ---------------------------' );\n params = params || {};\n var listA = params.listA,\n listB = params.listB,\n indexA = 0, indexB,\n bestMatch = {\n score : 0.0,\n index : null\n },\n paired = [];\n //console.debug( 'params:', JSON.stringify( params, null, ' ' ) );\n this.debug( 'starting list lens:', listA.length, listB.length );\n this.debug( 'bestMatch (starting):', JSON.stringify( bestMatch, null, ' ' ) );\n\n while( indexA < listA.length ){\n var matchTo = listA[ indexA ];\n bestMatch.score = 0.0;\n\n for( indexB=0; indexB= scoreThreshold ){\n //console.debug( 'autoPairFnBuilder.strategy', listA[ indexA ].name, listB[ bestMatch.index ].name );\n paired.push( options.createPair.call( this, {\n listA : listA,\n indexA : indexA,\n listB : listB,\n indexB : bestMatch.index\n }));\n //console.debug( 'list lens now:', listA.length, listB.length );\n } else {\n indexA += 1;\n }\n if( !listA.length || !listB.length ){\n return paired;\n }\n }\n this.debug( 'paired:', JSON.stringify( paired, null, ' ' ) );\n this.debug( 'autopair _strategy ---------------------------' );\n return paired;\n };\n}\n\n\n// ============================================================================\n/** An interface for building collections of paired datasets.\n */\nvar PairedCollectionCreator = Backbone.View.extend( baseMVC.LoggableMixin ).extend( baseCreator.CollectionCreatorMixin ).extend({\n _logNamespace : logNamespace,\n\n className: 'list-of-pairs-collection-creator collection-creator flex-row-container',\n\n /** set up initial options, instance vars, behaviors, and autopair (if set to do so) */\n initialize : function( attributes ){\n this.metric( 'PairedCollectionCreator.initialize', attributes );\n //this.debug( '-- PairedCollectionCreator:', attributes );\n\n attributes = _.defaults( attributes, {\n datasets : [],\n filters : this.DEFAULT_FILTERS,\n automaticallyPair : true,\n strategy : 'lcs',\n matchPercentage : 0.9,\n twoPassAutopairing : true\n });\n\n /** unordered, original list */\n this.initialList = attributes.datasets;\n\n /** is this from a history? if so, what's its id? */\n this.historyId = attributes.historyId;\n\n /** which filters should be used initially? (String[2] or name in commonFilters) */\n this.filters = this.commonFilters[ attributes.filters ] || this.commonFilters[ this.DEFAULT_FILTERS ];\n if( _.isArray( attributes.filters ) ){\n this.filters = attributes.filters;\n }\n\n /** try to auto pair the unpaired datasets on load? */\n this.automaticallyPair = attributes.automaticallyPair;\n\n /** what method to use for auto pairing (will be passed aggression level) */\n this.strategy = this.strategies[ attributes.strategy ] || this.strategies[ this.DEFAULT_STRATEGY ];\n if( _.isFunction( attributes.strategy ) ){\n this.strategy = attributes.strategy;\n }\n\n /** distance/mismatch level allowed for autopairing */\n this.matchPercentage = attributes.matchPercentage;\n\n /** try to autopair using simple first, then this.strategy on the remainder */\n this.twoPassAutopairing = attributes.twoPassAutopairing;\n\n /** remove file extensions (\\.*) from created pair names? */\n this.removeExtensions = true;\n //this.removeExtensions = false;\n\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n this.oncancel = attributes.oncancel;\n /** fn to call when the collection is created (scoped to this) */\n this.oncreate = attributes.oncreate;\n\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n this.autoscrollDist = attributes.autoscrollDist || 24;\n\n /** is the unpaired panel shown? */\n this.unpairedPanelHidden = false;\n /** is the paired panel shown? */\n this.pairedPanelHidden = false;\n\n /** DOM elements currently being dragged */\n this.$dragging = null;\n\n /** Used for blocking UI events during ajax/operations (don't post twice) */\n this.blocking = false;\n\n this._setUpCommonSettings( attributes );\n this._setUpBehaviors();\n this._dataSetUp();\n },\n\n /** map of common filter pairs by name */\n commonFilters : {\n illumina : [ '_1', '_2' ],\n Rs : [ '_R1', '_R2' ]\n },\n /** which commonFilter to use by default */\n DEFAULT_FILTERS : 'illumina',\n\n /** map of name->fn for autopairing */\n strategies : {\n 'simple' : 'autopairSimple',\n 'lcs' : 'autopairLCS',\n 'levenshtein' : 'autopairLevenshtein'\n },\n /** default autopair strategy name */\n DEFAULT_STRATEGY : 'lcs',\n\n // ------------------------------------------------------------------------ process raw list\n /** set up main data: cache initialList, sort, and autopair */\n _dataSetUp : function(){\n //this.debug( '-- _dataSetUp' );\n\n this.paired = [];\n this.unpaired = [];\n\n this.selectedIds = [];\n\n // sort initial list, add ids if needed, and save new working copy to unpaired\n this._sortInitialList();\n this._ensureIds();\n this.unpaired = this.initialList.slice( 0 );\n\n if( this.automaticallyPair ){\n this.autoPair();\n this.once( 'rendered:initial', function(){\n this.trigger( 'autopair' );\n });\n }\n },\n\n /** sort initial list */\n _sortInitialList : function(){\n //this.debug( '-- _sortInitialList' );\n this._sortDatasetList( this.initialList );\n },\n\n /** sort a list of datasets */\n _sortDatasetList : function( list ){\n // currently only natural sort by name\n list.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n return list;\n },\n\n /** add ids to dataset objs in initial list if none */\n _ensureIds : function(){\n this.initialList.forEach( function( dataset ){\n if( !dataset.hasOwnProperty( 'id' ) ){\n dataset.id = _.uniqueId();\n }\n });\n return this.initialList;\n },\n\n /** split initial list into two lists, those that pass forward filters & those passing reverse */\n _splitByFilters : function(){\n var regexFilters = this.filters.map( function( stringFilter ){\n return new RegExp( stringFilter );\n }),\n split = [ [], [] ];\n\n function _filter( unpaired, filter ){\n return filter.test( unpaired.name );\n //return dataset.name.indexOf( filter ) >= 0;\n }\n this.unpaired.forEach( function _filterEach( unpaired ){\n // 90% of the time this seems to work, but:\n //TODO: this treats *all* strings as regex which may confuse people - possibly check for // surrounding?\n // would need explanation in help as well\n regexFilters.forEach( function( filter, i ){\n if( _filter( unpaired, filter ) ){\n split[i].push( unpaired );\n }\n });\n });\n return split;\n },\n\n /** add a dataset to the unpaired list in it's proper order */\n _addToUnpaired : function( dataset ){\n // currently, unpaired is natural sorted by name, use binary search to find insertion point\n var binSearchSortedIndex = function( low, hi ){\n if( low === hi ){ return low; }\n\n var mid = Math.floor( ( hi - low ) / 2 ) + low,\n compared = naturalSort( dataset.name, this.unpaired[ mid ].name );\n\n if( compared < 0 ){\n return binSearchSortedIndex( low, mid );\n } else if( compared > 0 ){\n return binSearchSortedIndex( mid + 1, hi );\n }\n // walk the equal to find the last\n while( this.unpaired[ mid ] && this.unpaired[ mid ].name === dataset.name ){ mid++; }\n return mid;\n\n }.bind( this );\n\n this.unpaired.splice( binSearchSortedIndex( 0, this.unpaired.length ), 0, dataset );\n },\n\n // ------------------------------------------------------------------------ auto pairing\n /** two passes to automatically create pairs:\n * use both simpleAutoPair, then the fn mentioned in strategy\n */\n autoPair : function( strategy ){\n // split first using exact matching\n var split = this._splitByFilters(),\n paired = [];\n if( this.twoPassAutopairing ){\n paired = this.autopairSimple({\n listA : split[0],\n listB : split[1]\n });\n split = this._splitByFilters();\n }\n\n // uncomment to see printlns while running tests\n //this.debug = function(){ console.log.apply( console, arguments ); };\n\n // then try the remainder with something less strict\n strategy = strategy || this.strategy;\n split = this._splitByFilters();\n paired = paired.concat( this[ strategy ].call( this, {\n listA : split[0],\n listB : split[1]\n }));\n return paired;\n },\n\n /** autopair by exact match */\n autopairSimple : autoPairFnBuilder({\n scoreThreshold: function(){ return 1.0; },\n match : function _match( params ){\n params = params || {};\n if( params.matchTo === params.possible ){\n return {\n index: params.index,\n score: 1.0\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** autopair by levenshtein edit distance scoring */\n autopairLevenshtein : autoPairFnBuilder({\n scoreThreshold: function(){ return this.matchPercentage; },\n match : function _matches( params ){\n params = params || {};\n var distance = levenshteinDistance( params.matchTo, params.possible ),\n score = 1.0 - ( distance / ( Math.max( params.matchTo.length, params.possible.length ) ) );\n if( score > params.bestMatch.score ){\n return {\n index: params.index,\n score: score\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** autopair by longest common substrings scoring */\n autopairLCS : autoPairFnBuilder({\n scoreThreshold: function(){ return this.matchPercentage; },\n match : function _matches( params ){\n params = params || {};\n var match = this._naiveStartingAndEndingLCS( params.matchTo, params.possible ).length,\n score = match / ( Math.max( params.matchTo.length, params.possible.length ) );\n if( score > params.bestMatch.score ){\n return {\n index: params.index,\n score: score\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** return the concat'd longest common prefix and suffix from two strings */\n _naiveStartingAndEndingLCS : function( s1, s2 ){\n var fwdLCS = '',\n revLCS = '',\n i = 0, j = 0;\n while( i < s1.length && i < s2.length ){\n if( s1[ i ] !== s2[ i ] ){\n break;\n }\n fwdLCS += s1[ i ];\n i += 1;\n }\n if( i === s1.length ){ return s1; }\n if( i === s2.length ){ return s2; }\n\n i = ( s1.length - 1 );\n j = ( s2.length - 1 );\n while( i >= 0 && j >= 0 ){\n if( s1[ i ] !== s2[ j ] ){\n break;\n }\n revLCS = [ s1[ i ], revLCS ].join( '' );\n i -= 1;\n j -= 1;\n }\n return fwdLCS + revLCS;\n },\n\n // ------------------------------------------------------------------------ pairing / unpairing\n /** create a pair from fwd and rev, removing them from unpaired, and placing the new pair in paired */\n _pair : function( fwd, rev, options ){\n options = options || {};\n this.debug( '_pair:', fwd, rev );\n var pair = this._createPair( fwd, rev, options.name );\n this.paired.push( pair );\n this.unpaired = _.without( this.unpaired, fwd, rev );\n if( !options.silent ){\n this.trigger( 'pair:new', pair );\n }\n return pair;\n },\n\n /** create a pair Object from fwd and rev, adding the name attribute (will guess if not given) */\n _createPair : function( fwd, rev, name ){\n // ensure existance and don't pair something with itself\n if( !( fwd && rev ) || ( fwd === rev ) ){\n throw new Error( 'Bad pairing: ' + [ JSON.stringify( fwd ), JSON.stringify( rev ) ] );\n }\n name = name || this._guessNameForPair( fwd, rev );\n return { forward : fwd, name : name, reverse : rev };\n },\n\n /** try to find a good pair name for the given fwd and rev datasets */\n _guessNameForPair : function( fwd, rev, removeExtensions ){\n removeExtensions = ( removeExtensions !== undefined )?( removeExtensions ):( this.removeExtensions );\n var fwdName = fwd.name,\n revName = rev.name,\n lcs = this._naiveStartingAndEndingLCS(\n fwdName.replace( new RegExp( this.filters[0] ), '' ),\n revName.replace( new RegExp( this.filters[1] ), '' )\n );\n if( removeExtensions ){\n var lastDotIndex = lcs.lastIndexOf( '.' );\n if( lastDotIndex > 0 ){\n var extension = lcs.slice( lastDotIndex, lcs.length );\n lcs = lcs.replace( extension, '' );\n fwdName = fwdName.replace( extension, '' );\n revName = revName.replace( extension, '' );\n }\n }\n return lcs || ( fwdName + ' & ' + revName );\n },\n\n /** unpair a pair, removing it from paired, and adding the fwd,rev datasets back into unpaired */\n _unpair : function( pair, options ){\n options = options || {};\n if( !pair ){\n throw new Error( 'Bad pair: ' + JSON.stringify( pair ) );\n }\n this.paired = _.without( this.paired, pair );\n this._addToUnpaired( pair.forward );\n this._addToUnpaired( pair.reverse );\n\n if( !options.silent ){\n this.trigger( 'pair:unpair', [ pair ] );\n }\n return pair;\n },\n\n /** unpair all paired datasets */\n unpairAll : function(){\n var pairs = [];\n while( this.paired.length ){\n pairs.push( this._unpair( this.paired[ 0 ], { silent: true }) );\n }\n this.trigger( 'pair:unpair', pairs );\n },\n\n // ------------------------------------------------------------------------ API\n /** convert a pair into JSON compatible with the collections API */\n _pairToJSON : function( pair, src ){\n src = src || 'hda';\n //TODO: consider making this the pair structure when created instead\n return {\n collection_type : 'paired',\n src : 'new_collection',\n name : pair.name,\n element_identifiers : [{\n name : 'forward',\n id : pair.forward.id,\n src : src\n }, {\n name : 'reverse',\n id : pair.reverse.id,\n src : src\n }]\n };\n },\n\n /** create the collection via the API\n * @returns {jQuery.xhr Object} the jquery ajax request\n */\n createList : function( name ){\n var creator = this,\n url = Galaxy.root + 'api/histories/' + this.historyId + '/contents/dataset_collections';\n\n //TODO: use ListPairedCollection.create()\n var ajaxData = {\n type : 'dataset_collection',\n collection_type : 'list:paired',\n hide_source_items : creator.hideOriginals || false,\n name : _.escape( name || creator.$( '.collection-name' ).val() ),\n element_identifiers : creator.paired.map( function( pair ){\n return creator._pairToJSON( pair );\n })\n\n };\n //this.debug( JSON.stringify( ajaxData ) );\n creator.blocking = true;\n return jQuery.ajax( url, {\n type : 'POST',\n contentType : 'application/json',\n dataType : 'json',\n data : JSON.stringify( ajaxData )\n })\n .always( function(){\n creator.blocking = false;\n })\n .fail( function( xhr, status, message ){\n creator._ajaxErrHandler( xhr, status, message );\n })\n .done( function( response, message, xhr ){\n //this.info( 'ok', response, message, xhr );\n creator.trigger( 'collection:created', response, message, xhr );\n creator.metric( 'collection:created', response );\n if( typeof creator.oncreate === 'function' ){\n creator.oncreate.call( this, response, message, xhr );\n }\n });\n },\n\n /** handle ajax errors with feedback and details to the user (if available) */\n _ajaxErrHandler : function( xhr, status, message ){\n this.error( xhr, status, message );\n var content = _l( 'An error occurred while creating this collection' );\n if( xhr ){\n if( xhr.readyState === 0 && xhr.status === 0 ){\n content += ': ' + _l( 'Galaxy could not be reached and may be updating.' )\n + _l( ' Try again in a few minutes.' );\n } else if( xhr.responseJSON ){\n content += '
                          ' + JSON.stringify( xhr.responseJSON ) + '
                          ';\n } else {\n content += ': ' + message;\n }\n }\n creator._showAlert( content, 'alert-danger' );\n },\n\n // ------------------------------------------------------------------------ rendering\n /** render the entire interface */\n render : function( speed, callback ){\n //this.debug( '-- _render' );\n //this.$el.empty().html( this.templates.main() );\n this.$el.empty().html( this.templates.main() );\n this._renderHeader( speed );\n this._renderMiddle( speed );\n this._renderFooter( speed );\n this._addPluginComponents();\n this.trigger( 'rendered', this );\n return this;\n },\n\n /** render the header section */\n _renderHeader : function( speed, callback ){\n //this.debug( '-- _renderHeader' );\n var $header = this.$( '.header' ).empty().html( this.templates.header() )\n .find( '.help-content' ).prepend( $( this.templates.helpContent() ) );\n\n this._renderFilters();\n return $header;\n },\n /** fill the filter inputs with the filter values */\n _renderFilters : function(){\n return this.$( '.forward-column .column-header input' ).val( this.filters[0] )\n .add( this.$( '.reverse-column .column-header input' ).val( this.filters[1] ) );\n },\n\n /** render the middle including unpaired and paired sections (which may be hidden) */\n _renderMiddle : function( speed, callback ){\n var $middle = this.$( '.middle' ).empty().html( this.templates.middle() );\n\n // (re-) hide the un/paired panels based on instance vars\n if( this.unpairedPanelHidden ){\n this.$( '.unpaired-columns' ).hide();\n } else if( this.pairedPanelHidden ){\n this.$( '.paired-columns' ).hide();\n }\n\n this._renderUnpaired();\n this._renderPaired();\n return $middle;\n },\n /** render the unpaired section, showing datasets accrd. to filters, update the unpaired counts */\n _renderUnpaired : function( speed, callback ){\n //this.debug( '-- _renderUnpaired' );\n var creator = this,\n $fwd, $rev, $prd = [],\n split = this._splitByFilters();\n // update unpaired counts\n this.$( '.forward-column .title' )\n .text([ split[0].length, _l( 'unpaired forward' ) ].join( ' ' ));\n this.$( '.forward-column .unpaired-info' )\n .text( this._renderUnpairedDisplayStr( this.unpaired.length - split[0].length ) );\n this.$( '.reverse-column .title' )\n .text([ split[1].length, _l( 'unpaired reverse' ) ].join( ' ' ));\n this.$( '.reverse-column .unpaired-info' )\n .text( this._renderUnpairedDisplayStr( this.unpaired.length - split[1].length ) );\n\n this.$( '.unpaired-columns .column-datasets' ).empty();\n\n // show/hide the auto pair button if any unpaired are left\n this.$( '.autopair-link' ).toggle( this.unpaired.length !== 0 );\n if( this.unpaired.length === 0 ){\n this._renderUnpairedEmpty();\n return;\n }\n\n // create the dataset dom arrays\n $rev = split[1].map( function( dataset, i ){\n // if there'll be a fwd dataset across the way, add a button to pair the row\n if( ( split[0][ i ] !== undefined )\n && ( split[0][ i ] !== dataset ) ){\n $prd.push( creator._renderPairButton() );\n }\n return creator._renderUnpairedDataset( dataset );\n });\n $fwd = split[0].map( function( dataset ){\n return creator._renderUnpairedDataset( dataset );\n });\n\n if( !$fwd.length && !$rev.length ){\n this._renderUnpairedNotShown();\n return;\n }\n // add to appropo cols\n //TODO: not the best way to render - consider rendering the entire unpaired-columns section in a fragment\n // and swapping out that\n this.$( '.unpaired-columns .forward-column .column-datasets' ).append( $fwd )\n .add( this.$( '.unpaired-columns .paired-column .column-datasets' ).append( $prd ) )\n .add( this.$( '.unpaired-columns .reverse-column .column-datasets' ).append( $rev ) );\n this._adjUnpairedOnScrollbar();\n },\n /** return a string to display the count of filtered out datasets */\n _renderUnpairedDisplayStr : function( numFiltered ){\n return [ '(', numFiltered, ' ', _l( 'filtered out' ), ')' ].join('');\n },\n /** return an unattached jQuery DOM element to represent an unpaired dataset */\n _renderUnpairedDataset : function( dataset ){\n //TODO: to underscore template\n return $( '
                        • ')\n .attr( 'id', 'dataset-' + dataset.id )\n .addClass( 'dataset unpaired' )\n .attr( 'draggable', true )\n .addClass( dataset.selected? 'selected': '' )\n .append( $( '' ).addClass( 'dataset-name' ).text( dataset.name ) )\n //??\n .data( 'dataset', dataset );\n },\n /** render the button that may go between unpaired datasets, allowing the user to pair a row */\n _renderPairButton : function(){\n //TODO: *not* a dataset - don't pretend like it is\n return $( '
                        • ').addClass( 'dataset unpaired' )\n .append( $( '' ).addClass( 'dataset-name' ).text( _l( 'Pair these datasets' ) ) );\n },\n /** a message to display when no unpaired left */\n _renderUnpairedEmpty : function(){\n //this.debug( '-- renderUnpairedEmpty' );\n var $msg = $( '
                          ' )\n .text( '(' + _l( 'no remaining unpaired datasets' ) + ')' );\n this.$( '.unpaired-columns .paired-column .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n /** a message to display when no unpaired can be shown with the current filters */\n _renderUnpairedNotShown : function(){\n //this.debug( '-- renderUnpairedEmpty' );\n var $msg = $( '
                          ' )\n .text( '(' + _l( 'no datasets were found matching the current filters' ) + ')' );\n this.$( '.unpaired-columns .paired-column .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n /** try to detect if the unpaired section has a scrollbar and adjust left column for better centering of all */\n _adjUnpairedOnScrollbar : function(){\n var $unpairedColumns = this.$( '.unpaired-columns' ).last(),\n $firstDataset = this.$( '.unpaired-columns .reverse-column .dataset' ).first();\n if( !$firstDataset.length ){ return; }\n var ucRight = $unpairedColumns.offset().left + $unpairedColumns.outerWidth(),\n dsRight = $firstDataset.offset().left + $firstDataset.outerWidth(),\n rightDiff = Math.floor( ucRight ) - Math.floor( dsRight );\n //this.debug( 'rightDiff:', ucRight, '-', dsRight, '=', rightDiff );\n this.$( '.unpaired-columns .forward-column' )\n .css( 'margin-left', ( rightDiff > 0 )? rightDiff: 0 );\n },\n\n /** render the paired section and update counts of paired datasets */\n _renderPaired : function( speed, callback ){\n //this.debug( '-- _renderPaired' );\n this.$( '.paired-column-title .title' ).text([ this.paired.length, _l( 'paired' ) ].join( ' ' ) );\n // show/hide the unpair all link\n this.$( '.unpair-all-link' ).toggle( this.paired.length !== 0 );\n if( this.paired.length === 0 ){\n this._renderPairedEmpty();\n return;\n //TODO: would be best to return here (the $columns)\n } else {\n // show/hide 'remove extensions link' when any paired and they seem to have extensions\n this.$( '.remove-extensions-link' ).show();\n }\n\n this.$( '.paired-columns .column-datasets' ).empty();\n var creator = this;\n this.paired.forEach( function( pair, i ){\n //TODO: cache these?\n var pairView = new PairView({ pair: pair });\n creator.$( '.paired-columns .column-datasets' )\n .append( pairView.render().$el )\n .append([\n ''\n ].join( '' ));\n });\n },\n /** a message to display when none paired */\n _renderPairedEmpty : function(){\n var $msg = $( '
                          ' )\n .text( '(' + _l( 'no paired datasets yet' ) + ')' );\n this.$( '.paired-columns .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n\n footerSettings : {\n '.hide-originals': 'hideOriginals',\n '.remove-extensions': 'removeExtensions'\n },\n\n /** add any jQuery/bootstrap/custom plugins to elements rendered */\n _addPluginComponents : function(){\n this._chooseFiltersPopover( '.choose-filters-link' );\n this.$( '.help-content i' ).hoverhighlight( '.collection-creator', 'rgba( 64, 255, 255, 1.0 )' );\n },\n\n /** build a filter selection popover allowing selection of common filter pairs */\n _chooseFiltersPopover : function( selector ){\n function filterChoice( val1, val2 ){\n return [\n ''\n ].join('');\n }\n var $popoverContent = $( _.template([\n '
                          ',\n '
                          ',\n _l( 'Choose from the following filters to change which unpaired reads are shown in the display' ),\n ':
                          ',\n _.values( this.commonFilters ).map( function( filterSet ){\n return filterChoice( filterSet[0], filterSet[1] );\n }).join( '' ),\n '
                          '\n ].join(''))({}));\n\n return this.$( selector ).popover({\n container : '.collection-creator',\n placement : 'bottom',\n html : true,\n //animation : false,\n content : $popoverContent\n });\n },\n\n /** add (or clear if clear is truthy) a validation warning to what */\n _validationWarning : function( what, clear ){\n var VALIDATION_CLASS = 'validation-warning';\n if( what === 'name' ){\n what = this.$( '.collection-name' ).add( this.$( '.collection-name-prompt' ) );\n this.$( '.collection-name' ).focus().select();\n }\n if( clear ){\n what = what || this.$( '.' + VALIDATION_CLASS );\n what.removeClass( VALIDATION_CLASS );\n } else {\n what.addClass( VALIDATION_CLASS );\n }\n },\n\n // ------------------------------------------------------------------------ events\n /** set up event handlers on self */\n _setUpBehaviors : function(){\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this.on( 'pair:new', function(){\n //TODO: ideally only re-render the columns (or even elements) involved\n this._renderUnpaired();\n this._renderPaired();\n\n // scroll to bottom where new pairs are added\n //TODO: this doesn't seem to work - innerHeight sticks at 133...\n // may have to do with improper flex columns\n //var $pairedView = this.$( '.paired-columns' );\n //$pairedView.scrollTop( $pairedView.innerHeight() );\n //this.debug( $pairedView.height() )\n this.$( '.paired-columns' ).scrollTop( 8000000 );\n });\n this.on( 'pair:unpair', function( pairs ){\n //TODO: ideally only re-render the columns (or even elements) involved\n this._renderUnpaired();\n this._renderPaired();\n this.splitView();\n });\n\n this.on( 'filter-change', function(){\n this.filters = [\n this.$( '.forward-unpaired-filter input' ).val(),\n this.$( '.reverse-unpaired-filter input' ).val()\n ];\n this.metric( 'filter-change', this.filters );\n this._renderFilters();\n this._renderUnpaired();\n });\n\n this.on( 'autopair', function(){\n this._renderUnpaired();\n this._renderPaired();\n\n var message, msgClass = null;\n if( this.paired.length ){\n msgClass = 'alert-success';\n message = this.paired.length + ' ' + _l( 'pairs created' );\n if( !this.unpaired.length ){\n message += ': ' + _l( 'all datasets have been successfully paired' );\n this.hideUnpaired();\n this.$( '.collection-name' ).focus();\n }\n } else {\n message = _l([\n 'Could not automatically create any pairs from the given dataset names.',\n 'You may want to choose or enter different filters and try auto-pairing again.',\n 'Close this message using the X on the right to view more help.'\n ].join( ' ' ));\n }\n this._showAlert( message, msgClass );\n });\n\n //this.on( 'all', function(){\n // this.info( arguments );\n //});\n return this;\n },\n\n events : {\n // header\n 'click .more-help' : '_clickMoreHelp',\n 'click .less-help' : '_clickLessHelp',\n 'click .main-help' : '_toggleHelp',\n 'click .header .alert button' : '_hideAlert',\n 'click .forward-column .column-title' : '_clickShowOnlyUnpaired',\n 'click .reverse-column .column-title' : '_clickShowOnlyUnpaired',\n 'click .unpair-all-link' : '_clickUnpairAll',\n //TODO: this seems kinda backasswards - re-sending jq event as a backbone event, can we listen directly?\n 'change .forward-unpaired-filter input' : function( ev ){ this.trigger( 'filter-change' ); },\n 'focus .forward-unpaired-filter input' : function( ev ){ $( ev.currentTarget ).select(); },\n 'click .autopair-link' : '_clickAutopair',\n 'click .choose-filters .filter-choice' : '_clickFilterChoice',\n 'click .clear-filters-link' : '_clearFilters',\n 'change .reverse-unpaired-filter input' : function( ev ){ this.trigger( 'filter-change' ); },\n 'focus .reverse-unpaired-filter input' : function( ev ){ $( ev.currentTarget ).select(); },\n // unpaired\n 'click .forward-column .dataset.unpaired' : '_clickUnpairedDataset',\n 'click .reverse-column .dataset.unpaired' : '_clickUnpairedDataset',\n 'click .paired-column .dataset.unpaired' : '_clickPairRow',\n 'click .unpaired-columns' : 'clearSelectedUnpaired',\n 'mousedown .unpaired-columns .dataset' : '_mousedownUnpaired',\n // divider\n 'click .paired-column-title' : '_clickShowOnlyPaired',\n 'mousedown .flexible-partition-drag' : '_startPartitionDrag',\n // paired\n 'click .paired-columns .dataset.paired' : 'selectPair',\n 'click .paired-columns' : 'clearSelectedPaired',\n 'click .paired-columns .pair-name' : '_clickPairName',\n 'click .unpair-btn' : '_clickUnpair',\n // paired - drop target\n //'dragenter .paired-columns' : '_dragenterPairedColumns',\n //'dragleave .paired-columns .column-datasets': '_dragleavePairedColumns',\n 'dragover .paired-columns .column-datasets' : '_dragoverPairedColumns',\n 'drop .paired-columns .column-datasets' : '_dropPairedColumns',\n\n 'pair.dragstart .paired-columns .column-datasets' : '_pairDragstart',\n 'pair.dragend .paired-columns .column-datasets' : '_pairDragend',\n\n // footer\n 'change .remove-extensions' : function( ev ){ this.toggleExtensions(); },\n 'change .collection-name' : '_changeName',\n 'keydown .collection-name' : '_nameCheckForEnter',\n 'change .hide-originals' : '_changeHideOriginals',\n 'click .cancel-create' : '_cancelCreate',\n 'click .create-collection' : '_clickCreate'//,\n },\n\n /** toggle between showing only unpaired and split view */\n _clickShowOnlyUnpaired : function( ev ){\n //this.debug( 'click unpaired', ev.currentTarget );\n if( this.$( '.paired-columns' ).is( ':visible' ) ){\n this.hidePaired();\n } else {\n this.splitView();\n }\n },\n /** toggle between showing only paired and split view */\n _clickShowOnlyPaired : function( ev ){\n //this.debug( 'click paired' );\n if( this.$( '.unpaired-columns' ).is( ':visible' ) ){\n this.hideUnpaired();\n } else {\n this.splitView();\n }\n },\n\n /** hide unpaired, show paired */\n hideUnpaired : function( speed, callback ){\n this.unpairedPanelHidden = true;\n this.pairedPanelHidden = false;\n this._renderMiddle( speed, callback );\n },\n /** hide paired, show unpaired */\n hidePaired : function( speed, callback ){\n this.unpairedPanelHidden = false;\n this.pairedPanelHidden = true;\n this._renderMiddle( speed, callback );\n },\n /** show both paired and unpaired (splitting evenly) */\n splitView : function( speed, callback ){\n this.unpairedPanelHidden = this.pairedPanelHidden = false;\n this._renderMiddle( speed, callback );\n return this;\n },\n\n /** unpair all paired and do other super neat stuff which I'm not really sure about yet... */\n _clickUnpairAll : function( ev ){\n this.metric( 'unpairAll' );\n this.unpairAll();\n },\n\n /** attempt to autopair */\n _clickAutopair : function( ev ){\n var paired = this.autoPair();\n this.metric( 'autopair', paired.length, this.unpaired.length );\n this.trigger( 'autopair' );\n },\n\n /** set the filters based on the data attributes of the button click target */\n _clickFilterChoice : function( ev ){\n var $selected = $( ev.currentTarget );\n this.$( '.forward-unpaired-filter input' ).val( $selected.data( 'forward' ) );\n this.$( '.reverse-unpaired-filter input' ).val( $selected.data( 'reverse' ) );\n this._hideChooseFilters();\n this.trigger( 'filter-change' );\n },\n\n /** hide the choose filters popover */\n _hideChooseFilters : function(){\n //TODO: update bootstrap and remove the following hack\n // see also: https://github.com/twbs/bootstrap/issues/10260\n this.$( '.choose-filters-link' ).popover( 'hide' );\n this.$( '.popover' ).css( 'display', 'none' );\n },\n\n /** clear both filters */\n _clearFilters : function( ev ){\n this.$( '.forward-unpaired-filter input' ).val( '' );\n this.$( '.reverse-unpaired-filter input' ).val( '' );\n this.trigger( 'filter-change' );\n },\n\n // ........................................................................ unpaired\n /** select an unpaired dataset */\n _clickUnpairedDataset : function( ev ){\n ev.stopPropagation();\n return this.toggleSelectUnpaired( $( ev.currentTarget ) );\n },\n\n /** Toggle the selection of an unpaired dataset representation.\n * @param [jQuery] $dataset the unpaired dataset dom rep to select\n * @param [Boolean] options.force if defined, force selection based on T/F; otherwise, toggle\n */\n toggleSelectUnpaired : function( $dataset, options ){\n options = options || {};\n var dataset = $dataset.data( 'dataset' ),\n select = options.force !== undefined? options.force: !$dataset.hasClass( 'selected' );\n //this.debug( id, options.force, $dataset, dataset );\n if( !$dataset.length || dataset === undefined ){ return $dataset; }\n\n if( select ){\n $dataset.addClass( 'selected' );\n if( !options.waitToPair ){\n this.pairAllSelected();\n }\n\n } else {\n $dataset.removeClass( 'selected' );\n //delete dataset.selected;\n }\n return $dataset;\n },\n\n /** pair all the currently selected unpaired datasets */\n pairAllSelected : function( options ){\n options = options || {};\n var creator = this,\n fwds = [],\n revs = [],\n pairs = [];\n creator.$( '.unpaired-columns .forward-column .dataset.selected' ).each( function(){\n fwds.push( $( this ).data( 'dataset' ) );\n });\n creator.$( '.unpaired-columns .reverse-column .dataset.selected' ).each( function(){\n revs.push( $( this ).data( 'dataset' ) );\n });\n fwds.length = revs.length = Math.min( fwds.length, revs.length );\n //this.debug( fwds );\n //this.debug( revs );\n fwds.forEach( function( fwd, i ){\n try {\n pairs.push( creator._pair( fwd, revs[i], { silent: true }) );\n\n } catch( err ){\n //TODO: preserve selected state of those that couldn't be paired\n //TODO: warn that some could not be paired\n creator.error( err );\n }\n });\n if( pairs.length && !options.silent ){\n this.trigger( 'pair:new', pairs );\n }\n return pairs;\n },\n\n /** clear the selection on all unpaired datasets */\n clearSelectedUnpaired : function(){\n this.$( '.unpaired-columns .dataset.selected' ).removeClass( 'selected' );\n },\n\n /** when holding down the shift key on a click, 'paint' the moused over datasets as selected */\n _mousedownUnpaired : function( ev ){\n if( ev.shiftKey ){\n var creator = this,\n $startTarget = $( ev.target ).addClass( 'selected' ),\n moveListener = function( ev ){\n creator.$( ev.target ).filter( '.dataset' ).addClass( 'selected' );\n };\n $startTarget.parent().on( 'mousemove', moveListener );\n\n // on any mouseup, stop listening to the move and try to pair any selected\n $( document ).one( 'mouseup', function( ev ){\n $startTarget.parent().off( 'mousemove', moveListener );\n creator.pairAllSelected();\n });\n }\n },\n\n /** attempt to pair two datasets directly across from one another */\n _clickPairRow : function( ev ){\n //if( !ev.currentTarget ){ return true; }\n var rowIndex = $( ev.currentTarget ).index(),\n fwd = $( '.unpaired-columns .forward-column .dataset' ).eq( rowIndex ).data( 'dataset' ),\n rev = $( '.unpaired-columns .reverse-column .dataset' ).eq( rowIndex ).data( 'dataset' );\n //this.debug( 'row:', rowIndex, fwd, rev );\n this._pair( fwd, rev );\n },\n\n // ........................................................................ divider/partition\n /** start dragging the visible divider/partition between unpaired and paired panes */\n _startPartitionDrag : function( ev ){\n var creator = this,\n startingY = ev.pageY;\n //this.debug( 'partition drag START:', ev );\n $( 'body' ).css( 'cursor', 'ns-resize' );\n creator.$( '.flexible-partition-drag' ).css( 'color', 'black' );\n\n function endDrag( ev ){\n //creator.debug( 'partition drag STOP:', ev );\n // doing this by an added class didn't really work well - kept flashing still\n creator.$( '.flexible-partition-drag' ).css( 'color', '' );\n $( 'body' ).css( 'cursor', '' ).unbind( 'mousemove', trackMouse );\n }\n function trackMouse( ev ){\n var offset = ev.pageY - startingY;\n //creator.debug( 'partition:', startingY, offset );\n if( !creator.adjPartition( offset ) ){\n //creator.debug( 'mouseup triggered' );\n $( 'body' ).trigger( 'mouseup' );\n }\n creator._adjUnpairedOnScrollbar();\n startingY += offset;\n }\n $( 'body' ).mousemove( trackMouse );\n $( 'body' ).one( 'mouseup', endDrag );\n },\n\n /** adjust the parition up/down +/-adj pixels */\n adjPartition : function( adj ){\n var $unpaired = this.$( '.unpaired-columns' ),\n $paired = this.$( '.paired-columns' ),\n unpairedHi = parseInt( $unpaired.css( 'height' ), 10 ),\n pairedHi = parseInt( $paired.css( 'height' ), 10 );\n //this.debug( adj, 'hi\\'s:', unpairedHi, pairedHi, unpairedHi + adj, pairedHi - adj );\n\n unpairedHi = Math.max( 10, unpairedHi + adj );\n pairedHi = pairedHi - adj;\n\n var movingUpwards = adj < 0;\n // when the divider gets close to the top - lock into hiding the unpaired section\n if( movingUpwards ){\n if( this.unpairedPanelHidden ){\n return false;\n } else if( unpairedHi <= 10 ){\n this.hideUnpaired();\n return false;\n }\n } else {\n if( this.unpairedPanelHidden ){\n $unpaired.show();\n this.unpairedPanelHidden = false;\n }\n }\n\n // when the divider gets close to the bottom - lock into hiding the paired section\n if( !movingUpwards ){\n if( this.pairedPanelHidden ){\n return false;\n } else if( pairedHi <= 15 ){\n this.hidePaired();\n return false;\n }\n\n } else {\n if( this.pairedPanelHidden ){\n $paired.show();\n this.pairedPanelHidden = false;\n }\n }\n\n $unpaired.css({\n height : unpairedHi + 'px',\n flex : '0 0 auto'\n });\n return true;\n },\n\n // ........................................................................ paired\n /** select a pair when clicked */\n selectPair : function( ev ){\n ev.stopPropagation();\n $( ev.currentTarget ).toggleClass( 'selected' );\n },\n\n /** deselect all pairs */\n clearSelectedPaired : function( ev ){\n this.$( '.paired-columns .dataset.selected' ).removeClass( 'selected' );\n },\n\n /** rename a pair when the pair name is clicked */\n _clickPairName : function( ev ){\n ev.stopPropagation();\n var $name = $( ev.currentTarget ),\n $pair = $name.parent().parent(),\n index = $pair.index( '.dataset.paired' ),\n pair = this.paired[ index ],\n response = prompt( 'Enter a new name for the pair:', pair.name );\n if( response ){\n pair.name = response;\n // set a flag (which won't be passed in json creation) for manual naming so we don't overwrite these\n // when adding/removing extensions\n //hackish\n pair.customizedName = true;\n $name.text( pair.name );\n }\n },\n\n /** unpair this pair */\n _clickUnpair : function( ev ){\n //if( !ev.currentTarget ){ return true; }\n var pairIndex = Math.floor( $( ev.currentTarget ).index( '.unpair-btn' ) );\n //this.debug( 'pair:', pairIndex );\n this._unpair( this.paired[ pairIndex ] );\n },\n\n // ........................................................................ paired - drag and drop re-ordering\n //_dragenterPairedColumns : function( ev ){\n // this.debug( '_dragenterPairedColumns:', ev );\n //},\n //_dragleavePairedColumns : function( ev ){\n // //this.debug( '_dragleavePairedColumns:', ev );\n //},\n /** track the mouse drag over the paired list adding a placeholder to show where the drop would occur */\n _dragoverPairedColumns : function( ev ){\n //this.debug( '_dragoverPairedColumns:', ev );\n ev.preventDefault();\n\n var $list = this.$( '.paired-columns .column-datasets' );\n this._checkForAutoscroll( $list, ev.originalEvent.clientY );\n //this.debug( ev.originalEvent.clientX, ev.originalEvent.clientY );\n var $nearest = this._getNearestPairedDatasetLi( ev.originalEvent.clientY );\n\n $( '.element-drop-placeholder' ).remove();\n var $placeholder = $( '
                          ' );\n if( !$nearest.length ){\n $list.append( $placeholder );\n } else {\n $nearest.before( $placeholder );\n }\n },\n\n /** If the mouse is near enough to the list's top or bottom, scroll the list */\n _checkForAutoscroll : function( $element, y ){\n var AUTOSCROLL_SPEED = 2;\n var offset = $element.offset(),\n scrollTop = $element.scrollTop(),\n upperDist = y - offset.top,\n lowerDist = ( offset.top + $element.outerHeight() ) - y;\n //this.debug( '_checkForAutoscroll:', scrollTop, upperDist, lowerDist );\n if( upperDist >= 0 && upperDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop - AUTOSCROLL_SPEED );\n } else if( lowerDist >= 0 && lowerDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop + AUTOSCROLL_SPEED );\n }\n },\n\n /** get the nearest *previous* paired dataset PairView based on the mouse's Y coordinate.\n * If the y is at the end of the list, return an empty jQuery object.\n */\n _getNearestPairedDatasetLi : function( y ){\n var WIGGLE = 4,\n lis = this.$( '.paired-columns .column-datasets li' ).toArray();\n for( var i=0; i y && top - halfHeight < y ){\n //this.debug( y, top + halfHeight, top - halfHeight )\n return $li;\n }\n }\n return $();\n },\n /** drop (dragged/selected PairViews) onto the list, re-ordering both the DOM and the internal array of pairs */\n _dropPairedColumns : function( ev ){\n // both required for firefox\n ev.preventDefault();\n ev.dataTransfer.dropEffect = 'move';\n\n var $nearest = this._getNearestPairedDatasetLi( ev.originalEvent.clientY );\n if( $nearest.length ){\n this.$dragging.insertBefore( $nearest );\n\n } else {\n // no nearest before - insert after last element (unpair button)\n this.$dragging.insertAfter( this.$( '.paired-columns .unpair-btn' ).last() );\n }\n // resync the creator's list of paired based on the new DOM order\n this._syncPairsToDom();\n return false;\n },\n /** resync the creator's list of paired based on the DOM order of pairs */\n _syncPairsToDom : function(){\n var newPaired = [];\n //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n this.$( '.paired-columns .dataset.paired' ).each( function(){\n newPaired.push( $( this ).data( 'pair' ) );\n });\n //this.debug( newPaired );\n this.paired = newPaired;\n this._renderPaired();\n },\n /** drag communication with pair sub-views: dragstart */\n _pairDragstart : function( ev, pair ){\n //this.debug( '_pairDragstart', ev, pair )\n // auto select the pair causing the event and move all selected\n pair.$el.addClass( 'selected' );\n var $selected = this.$( '.paired-columns .dataset.selected' );\n this.$dragging = $selected;\n },\n /** drag communication with pair sub-views: dragend - remove the placeholder */\n _pairDragend : function( ev, pair ){\n //this.debug( '_pairDragend', ev, pair )\n $( '.element-drop-placeholder' ).remove();\n this.$dragging = null;\n },\n\n // ........................................................................ footer\n toggleExtensions : function( force ){\n var creator = this;\n creator.removeExtensions = ( force !== undefined )?( force ):( !creator.removeExtensions );\n\n _.each( creator.paired, function( pair ){\n // don't overwrite custom names\n if( pair.customizedName ){ return; }\n pair.name = creator._guessNameForPair( pair.forward, pair.reverse );\n });\n\n creator._renderPaired();\n creator._renderFooter();\n },\n\n // ------------------------------------------------------------------------ misc\n /** debug a dataset list */\n _printList : function( list ){\n var creator = this;\n _.each( list, function( e ){\n if( list === creator.paired ){\n creator._printPair( e );\n } else {\n //creator.debug( e );\n }\n });\n },\n\n /** print a pair Object */\n _printPair : function( pair ){\n this.debug( pair.forward.name, pair.reverse.name, ': ->', pair.name );\n },\n\n /** string rep */\n toString : function(){ return 'PairedCollectionCreator'; },\n\n templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\n /** the header (not including help text) */\n header : _.template([\n '
                          ',\n '', _l( 'More help' ), '',\n '
                          ',\n '', _l( 'Less' ), '',\n '
                          ',\n '
                          ',\n '
                          ',\n '',\n '',\n '
                          ',\n\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          ',\n '', _l( 'Unpaired forward' ), '',\n '',\n '
                          ',\n '
                          ',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '', _l( 'Unpaired reverse' ), '',\n '',\n '
                          ',\n '
                          ',\n '',\n '
                          ',\n '
                          ',\n '
                          ',\n '
                          '\n ].join('')),\n\n /** the middle: unpaired, divider, and paired */\n middle : _.template([\n // contains two flex rows (rows that fill available space) and a divider btwn\n '
                          ',\n '
                          ',\n '
                            ',\n '
                            ',\n '
                            ',\n '
                              ',\n '
                              ',\n '
                              ',\n '
                                ',\n '
                                ',\n '
                                ',\n '
                                ',\n '
                                ',\n '
                                ',\n '
                                ',\n '',\n '
                                ',\n '',\n _l( 'Unpair all' ),\n '',\n '
                                ',\n '
                                ',\n '
                                ',\n '
                                  ',\n '
                                  '\n ].join('')),\n\n /** creation and cancel controls */\n footer : _.template([\n '
                                  ',\n '
                                  ',\n '',\n '',\n '
                                  ',\n '
                                  ',\n '',\n '
                                  ', _l( 'Name' ), ':
                                  ',\n '
                                  ',\n '
                                  ',\n\n '
                                  ',\n '
                                  ',\n '',\n '
                                  ',\n '',\n '',\n '
                                  ',\n '
                                  ',\n\n '
                                  ',\n '',\n '
                                  ',\n '
                                  '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                                  ', _l([\n 'Collections of paired datasets are ordered lists of dataset pairs (often forward and reverse reads). ',\n 'These collections can be passed to tools and workflows in order to have analyses done on each member of ',\n 'the entire group. This interface allows you to create a collection, choose which datasets are paired, ',\n 'and re-order the final collection.'\n ].join( '' )), '

                                  ',\n '

                                  ', _l([\n 'Unpaired datasets are shown in the unpaired section ',\n '(hover over the underlined words to highlight below). ',\n 'Paired datasets are shown in the paired section.',\n '

                                    To pair datasets, you can:',\n '
                                  • Click a dataset in the ',\n 'forward column ',\n 'to select it then click a dataset in the ',\n 'reverse column.',\n '
                                  • ',\n '
                                  • Click one of the \"Pair these datasets\" buttons in the ',\n 'middle column ',\n 'to pair the datasets in a particular row.',\n '
                                  • ',\n '
                                  • Click \"Auto-pair\" ',\n 'to have your datasets automatically paired based on name.',\n '
                                  • ',\n '
                                  '\n ].join( '' )), '

                                  ',\n '

                                  ', _l([\n '

                                    You can filter what is shown in the unpaired sections by:',\n '
                                  • Entering partial dataset names in either the ',\n 'forward filter or ',\n 'reverse filter.',\n '
                                  • ',\n '
                                  • Choosing from a list of preset filters by clicking the ',\n '\"Choose filters\" link.',\n '
                                  • ',\n '
                                  • Entering regular expressions to match dataset names. See: ',\n 'MDN\\'s JavaScript Regular Expression Tutorial. ',\n 'Note: forward slashes (\\\\) are not needed.',\n '
                                  • ',\n '
                                  • Clearing the filters by clicking the ',\n '\"Clear filters\" link.',\n '
                                  • ',\n '
                                  '\n ].join( '' )), '

                                  ',\n '

                                  ', _l([\n 'To unpair individual dataset pairs, click the ',\n 'unpair buttons ( ). ',\n 'Click the \"Unpair all\" link to unpair all pairs.'\n ].join( '' )), '

                                  ',\n '

                                  ', _l([\n 'You can include or remove the file extensions (e.g. \".fastq\") from your pair names by toggling the ',\n '\"Remove file extensions from pair names?\" control.'\n ].join( '' )), '

                                  ',\n '

                                  ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\". ',\n '(Note: you do not have to pair all unpaired datasets to finish.)'\n ].join( '' )), '

                                  '\n ].join(''))\n })\n});\n\n//=============================================================================\n/** a modal version of the paired collection creator */\nvar pairedCollectionCreatorModal = function _pairedCollectionCreatorModal( datasets, options ){\n\n var deferred = jQuery.Deferred(),\n creator;\n\n options = _.defaults( options || {}, {\n datasets : datasets,\n oncancel : function(){\n Galaxy.modal.hide();\n deferred.reject( 'cancelled' );\n },\n oncreate : function( creator, response ){\n Galaxy.modal.hide();\n deferred.resolve( response );\n }\n });\n\n if( !window.Galaxy || !Galaxy.modal ){\n throw new Error( 'Galaxy or Galaxy.modal not found' );\n }\n\n creator = new PairedCollectionCreator( options );\n Galaxy.modal.show({\n title : 'Create a collection of paired datasets',\n body : creator.$el,\n width : '80%',\n height : '800px',\n closing_events: true\n });\n creator.render();\n window.creator = creator;\n\n //TODO: remove modal header\n return deferred;\n};\n\n\n//=============================================================================\nfunction createListOfPairsCollection( collection, defaultHideSourceItems ){\n var elements = collection.toJSON();\n//TODO: validate elements\n return pairedCollectionCreatorModal( elements, {\n historyId : collection.historyId,\n defaultHideSourceItems: defaultHideSourceItems\n });\n}\n\n\n//=============================================================================\n return {\n PairedCollectionCreator : PairedCollectionCreator,\n pairedCollectionCreatorModal : pairedCollectionCreatorModal,\n createListOfPairsCollection : createListOfPairsCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/list-of-pairs-collection-creator.js","define([\n \"mvc/collection/list-collection-creator\",\n \"mvc/history/hdca-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_CREATOR, HDCA, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/*==============================================================================\nTODO:\n the paired creator doesn't really mesh with the list creator as parent\n it may be better to make an abstract super class for both\n composites may inherit from this (or vis-versa)\n PairedDatasetCollectionElementView doesn't make a lot of sense\n\n==============================================================================*/\n/** */\nvar PairedDatasetCollectionElementView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n//TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n tagName : 'li',\n className : 'collection-element',\n\n initialize : function( attributes ){\n this.element = attributes.element || {};\n this.identifier = attributes.identifier;\n },\n\n render : function(){\n this.$el\n .attr( 'data-element-id', this.element.id )\n .html( this.template({ identifier: this.identifier, element: this.element }) );\n return this;\n },\n\n //TODO: lots of unused space in the element - possibly load details and display them horiz.\n template : _.template([\n '<%- identifier %>',\n '<%- element.name %>',\n ].join('')),\n\n /** remove the DOM and any listeners */\n destroy : function(){\n this.off();\n this.$el.remove();\n },\n\n /** string rep */\n toString : function(){\n return 'DatasetCollectionElementView()';\n }\n});\n\n\n// ============================================================================\nvar _super = LIST_CREATOR.ListCollectionCreator;\n\n/** An interface for building collections.\n */\nvar PairCollectionCreator = _super.extend({\n\n /** the class used to display individual elements */\n elementViewClass : PairedDatasetCollectionElementView,\n /** the class this creator will create and save */\n collectionClass : HDCA.HistoryPairDatasetCollection,\n className : 'pair-collection-creator collection-creator flex-row-container',\n\n /** override to no-op */\n _mangleDuplicateNames : function(){},\n\n // TODO: this whole pattern sucks. There needs to be two classes of problem area:\n // bad inital choices and\n // when the user has painted his/her self into a corner during creation/use-of-the-creator\n /** render the entire interface */\n render : function( speed, callback ){\n if( this.workingElements.length === 2 ){\n return _super.prototype.render.call( this, speed, callback );\n }\n return this._renderInvalid( speed, callback );\n },\n\n // ------------------------------------------------------------------------ rendering elements\n /** render forward/reverse */\n _renderList : function( speed, callback ){\n //this.debug( '-- _renderList' );\n //precondition: there are two valid elements in workingElements\n var creator = this,\n $tmp = jQuery( '
                                  ' ),\n $list = creator.$list();\n\n // lose the original views, create the new, append all at once, then call their renders\n _.each( this.elementViews, function( view ){\n view.destroy();\n creator.removeElementView( view );\n });\n $tmp.append( creator._createForwardElementView().$el );\n $tmp.append( creator._createReverseElementView().$el );\n $list.empty().append( $tmp.children() );\n _.invoke( creator.elementViews, 'render' );\n },\n\n /** create the forward element view */\n _createForwardElementView : function(){\n return this._createElementView( this.workingElements[0], { identifier: 'forward' } );\n },\n\n /** create the forward element view */\n _createReverseElementView : function(){\n return this._createElementView( this.workingElements[1], { identifier: 'reverse' } );\n },\n\n /** create an element view, cache in elementViews, and return */\n _createElementView : function( element, options ){\n var elementView = new this.elementViewClass( _.extend( options, {\n element : element,\n }));\n this.elementViews.push( elementView );\n return elementView;\n },\n\n /** swap the forward, reverse elements and re-render */\n swap : function(){\n this.workingElements = [\n this.workingElements[1],\n this.workingElements[0],\n ];\n this._renderList();\n },\n\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .swap' : 'swap',\n }),\n\n // ------------------------------------------------------------------------ templates\n //TODO: move to require text plugin and load these as text\n //TODO: underscore currently unnecc. bc no vars are used\n //TODO: better way of localizing text-nodes in long strings\n /** underscore template fns attached to class */\n templates : _.extend( _.clone( _super.prototype.templates ), {\n /** the middle: element list */\n middle : _.template([\n '',\n '
                                  ',\n '
                                  '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                                  ', _l([\n 'Pair collections are permanent collections containing two datasets: one forward and one reverse. ',\n 'Often these are forward and reverse reads. The pair collections can be passed to tools and ',\n 'workflows in order to have analyses done on both datasets. This interface allows ',\n 'you to create a pair, name it, and swap which is forward and which reverse.'\n ].join( '' )), '

                                  ',\n '
                                    ',\n '
                                  • ', _l([\n 'Click the \"Swap\" link to make your forward dataset the reverse ',\n 'and the reverse dataset forward.'\n ].join( '' )), '
                                  • ',\n '
                                  • ', _l([\n 'Click the \"Cancel\" button to exit the interface.'\n ].join( '' )), '
                                  • ',\n '

                                  ',\n '

                                  ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\".'\n ].join( '' )), '

                                  '\n ].join('')),\n\n /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n invalidInitial : _.template([\n '
                                  ',\n '
                                  ',\n '',\n '<% if( _.size( problems ) ){ %>',\n _l( 'The following selections could not be included due to problems' ),\n '
                                    <% _.each( problems, function( problem ){ %>',\n '
                                  • <%- problem.element.name %>: <%- problem.text %>
                                  • ',\n '<% }); %>
                                  ',\n '<% } else if( _.size( elements ) === 0 ){ %>',\n _l( 'No datasets were selected' ), '.',\n '<% } else if( _.size( elements ) === 1 ){ %>',\n _l( 'Only one dataset was selected' ), ': <%- elements[0].name %>',\n '<% } else if( _.size( elements ) > 2 ){ %>',\n _l( 'Too many datasets were selected' ),\n ': <%- _.pluck( elements, \"name\" ).join( \", \") %>',\n '<% } %>',\n '
                                  ',\n _l( 'Two (and only two) elements are needed for the pair' ), '. ',\n _l( 'You may need to ' ),\n '', _l( 'cancel' ), ' ',\n _l( 'and reselect new elements' ), '.',\n '
                                  ',\n '
                                  ',\n '
                                  ',\n '
                                  ',\n '
                                  ',\n '
                                  ',\n '',\n // _l( 'Create a different kind of collection' ),\n '
                                  ',\n '
                                  ',\n '
                                  '\n ].join('')),\n }),\n\n // ------------------------------------------------------------------------ misc\n /** string rep */\n toString : function(){ return 'PairCollectionCreator'; }\n});\n\n\n//==============================================================================\n/** List collection flavor of collectionCreatorModal. */\nvar pairCollectionCreatorModal = function _pairCollectionCreatorModal( elements, options ){\n options = options || {};\n options.title = _l( 'Create a collection from a pair of datasets' );\n return LIST_CREATOR.collectionCreatorModal( elements, options, PairCollectionCreator );\n};\n\n\n//==============================================================================\n/** Use a modal to create a pair collection, then add it to the given history contents.\n * @returns {Deferred} resolved when the collection is added to the history.\n */\nfunction createPairCollection( contents, defaultHideSourceItems ){\n var elements = contents.toJSON(),\n promise = pairCollectionCreatorModal( elements, {\n defaultHideSourceItems: defaultHideSourceItems,\n creationFn : function( elements, name, hideSourceItems ){\n elements = [\n { name: \"forward\", src: \"hda\", id: elements[0].id },\n { name: \"reverse\", src: \"hda\", id: elements[1].id }\n ];\n return contents.createHDCA( elements, 'paired', name, hideSourceItems );\n }\n });\n return promise;\n}\n\n//==============================================================================\n return {\n PairCollectionCreator : PairCollectionCreator,\n pairCollectionCreatorModal : pairCollectionCreatorModal,\n createPairCollection : createPairCollection,\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/pair-collection-creator.js","\ndefine( [ 'utils/utils', 'mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/form/form-view' ], function( Utils, Tabs, Ui, Form ) {\n\n /** Dataset edit attributes view */\n var View = Backbone.View.extend({\n initialize: function() {\n this.setElement( '
                                  ' );\n this.model = new Backbone.Model( { 'dataset_id': Galaxy.params.dataset_id } );\n this.render();\n },\n\n // Fetch data for the selected dataset and \n // build tabs for editing its attributes\n render: function() {\n var url = Galaxy.root + 'dataset/edit',\n self = this;\n Utils.get({\n url : url,\n data : { 'dataset_id' : self.model.get( 'dataset_id' ) },\n success : function( response ) {\n self.render_attribute_page( self, response );\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while loading the dataset.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n\n /** Render all the tabs view */\n render_attribute_page: function( self, response ) {\n var message = {\n 'message' : response.message,\n 'status' : response.status,\n 'persistent' : true,\n 'cls' : response.status + 'message'\n };\n self.$el.empty().append( self._templateHeader() );\n self.display_message( message, self.$( '.response-message' ) );\n // Create all tabs\n self.create_tabs( response, self.$( '.edit-attr' ) );\n },\n\n /** Perform AJAX post call */\n call_ajax: function( self, data, tab_name ) {\n var post_url = Galaxy.root + 'dataset/edit';\n $.ajax({\n type: \"PUT\",\n url: post_url,\n data: data,\n success: function( response ) {\n self.render_attribute_page( self, response );\n self.reload_history();\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n\n /** Display actions messages */\n display_message: function( response, $el ) {\n $el.empty().html( new Ui.Message( response ).$el );\n },\n\n /** Create tabs for different attributes of dataset*/\n create_tabs: function( response, $el_edit_attr ) {\n var self = this;\n self.tabs = new Tabs.View();\n self.tabs.add({\n id : 'attributes',\n title : 'Attributes',\n icon : 'fa fa-bars',\n tooltip : 'Edit dataset attributes',\n $el : self._getAttributesFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'convert',\n title : 'Convert',\n icon : 'fa-gear',\n tooltip : 'Convert to new format',\n $el : self._getConvertFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'datatype',\n title : 'Datatypes',\n icon : 'fa-database',\n tooltip : 'Change data type',\n $el : self._getChangeDataTypeFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'permissions',\n title : 'Permissions',\n icon : 'fa-user',\n tooltip : 'Permissions',\n $el : self._getPermissionsFormTemplate( response )\n });\n $el_edit_attr.append( self.tabs.$el );\n self.tabs.showTab( 'attributes' );\n },\n\n /** Main template */\n _templateHeader: function() {\n return '
                                  ' +\n '
                                  ' +\n '

                                  Edit Dataset Attributes

                                  ' +\n '
                                  ';\n },\n\n /** Attributes tab template */\n _getAttributesFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Edit attributes',\n inputs : response.edit_attributes_inputs,\n operations: {\n 'submit_editattr' : new Ui.ButtonIcon({\n tooltip : 'Save attributes of the dataset.',\n icon : 'fa-floppy-o ',\n title : 'Save attributes',\n onclick : function() { self._submit( self, form, response, \"edit_attributes\" ) }\n }),\n 'submit_autocorrect' : new Ui.ButtonIcon({\n tooltip : 'This will inspect the dataset and attempt to correct the values of fields if they are not accurate.',\n icon : 'fa-undo ',\n title : 'Auto-detect',\n onclick : function() { self._submit( self, form, response, \"auto-detect\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Convert tab template */\n _getConvertFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Convert to new format',\n inputs : response.convert_inputs,\n operations: {\n 'submit' : new Ui.ButtonIcon({\n tooltip : 'Convert the datatype to a new format.',\n title : 'Convert datatype',\n icon : 'fa-exchange ',\n onclick : function() { self._submit( self, form, response, \"convert\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Change datatype template */\n _getChangeDataTypeFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Change datatype',\n inputs : response.convert_datatype_inputs,\n operations: {\n 'submit' : new Ui.ButtonIcon({\n tooltip : 'Change the datatype to a new type.',\n title : 'Change datatype',\n icon : 'fa-exchange ',\n onclick : function() { self._submit( self, form, response, \"change\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Permissions template */\n _getPermissionsFormTemplate: function( response ) {\n var template = \"\",\n self = this;\n if( response.can_manage_dataset ) {\n var form = new Form({\n title : 'Manage dataset permissions on ' + response.display_name,\n inputs : response.permission_inputs,\n operations: {\n 'submit': new Ui.ButtonIcon({\n tooltip : 'Save permissions.',\n title : 'Save permissions',\n icon : 'fa-floppy-o ',\n onclick : function() { self._submit( self, form, response, \"permissions\" ) }\n })\n }\n });\n return form.$el;\n }\n else {\n var form = new Form({\n title : 'View permissions',\n inputs : response.permission_inputs\n });\n return form.$el;\n }\n },\n\n /** Submit action */\n _submit: function( self, form, response, type ) {\n var form_data = form.data.create();\n form_data.dataset_id = response.dataset_id;\n switch( type ) {\n case \"edit_attributes\":\n form_data.save = 'Save';\n break;\n\n case \"auto-detect\":\n form_data.detect = 'Auto-detect';\n break;\n \n case \"convert\":\n if ( form_data.target_type !== null && form_data.target_type ) {\n form_data.dataset_id = response.dataset_id;\n form_data.convert_data = 'Convert';\n }\n break;\n\n case \"change\":\n form_data.change = 'Save';\n break;\n\n case \"permissions\":\n var post_data = {};\n post_data.permissions = JSON.stringify( form_data );\n post_data.update_roles_button = \"Save\";\n post_data.dataset_id = response.dataset_id;\n form_data = post_data;\n break; \n }\n self.call_ajax( self, form_data );\n },\n\n /** Reload Galaxy's history after updating dataset's attributes */\n reload_history: function() {\n if ( window.Galaxy ) {\n window.Galaxy.currHistoryPanel.loadCurrentHistory();\n }\n }\n });\n\n return {\n View : View\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-edit-attributes.js","/** This class renders the grid list with shared section. */\ndefine( [ 'mvc/grid/grid-view' ], function( GridView ) {\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.setElement( $( '
                                  ' ) );\n this.model = new Backbone.Model( options );\n this.item = this.model.get( 'item' );\n $.ajax({\n url : Galaxy.root + this.item + '/' + this.model.get( 'action_id' ),\n success : function( response ) {\n response[ 'dict_format' ] = true;\n self.model.set( response );\n self.render();\n }\n });\n },\n\n render: function() {\n var grid = new GridView( this.model.attributes );\n this.$el.empty().append( grid.$el );\n this.$el.append( this._templateShared() );\n },\n\n _templateShared: function() {\n var self = this;\n var $tmpl = $( '
                                  ' +\n '

                                  ' + this.model.get( 'plural' ) + ' shared with you by others

                                  ' +\n '
                                  ' );\n var options = this.model.attributes;\n if ( options.shared_by_others && options.shared_by_others.length > 0 ) {\n var $table = $( '' +\n '' +\n '' +\n '' +\n '' +\n '
                                  TitleOwner
                                  ' );\n _.each( options.shared_by_others, function( it, index ) {\n var display_url = Galaxy.root + self.item + '/display_by_username_and_slug?username=' + it.username + '&slug=' + it.slug;\n $table.append( '
                                1. ' +\n '' + _.escape( it.title ) + '' +\n '' + _.escape( it.username ) + '
                                  ' +\n '
                                  ' +\n '
                                  ' +\n '
                                  ' +\n '
                                  ' +\n '
                                  You can tell Galaxy to download data from web by entering URL in this box (one per line). You can also directly paste the contents of a file.
                                  ' +\n '', '
                                  ', '
                                  '].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CitationView: CitationView,\n\t CitationListView: CitationListView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))\n\n/***/ },\n/* 55 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(58), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, DATASET_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var FoldoutListItemView = LIST_ITEM.FoldoutListItemView,\n\t ListItemView = LIST_ITEM.ListItemView;\n\t /** @class Read only view for DatasetCollection.\n\t */\n\t var DCListItemView = FoldoutListItemView.extend(\n\t /** @lends DCListItemView.prototype */{\n\t\n\t className: FoldoutListItemView.prototype.className + \" dataset-collection\",\n\t id: function () {\n\t return ['dataset_collection', this.model.get('id')].join('-');\n\t },\n\t\n\t /** override to add linkTarget */\n\t initialize: function (attributes) {\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t this.hasUser = attributes.hasUser;\n\t FoldoutListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t FoldoutListItemView.prototype._setUpListeners.call(this);\n\t this.listenTo(this.model, 'change', function (model, options) {\n\t // if the model has changed deletion status render it entirely\n\t if (_.has(model.changed, 'deleted')) {\n\t this.render();\n\t\n\t // if the model has been decorated after the fact with the element count,\n\t // render the subtitle where the count is displayed\n\t } else if (_.has(model.changed, 'element_count')) {\n\t this.$('> .title-bar .subtitle').replaceWith(this._renderSubtitle());\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... rendering\n\t /** render a subtitle to show the user what sort of collection this is */\n\t _renderSubtitle: function () {\n\t return $(this.templates.subtitle(this.model.toJSON(), this));\n\t },\n\t\n\t // ......................................................................... foldout\n\t /** override to add linktarget to sub-panel */\n\t _getFoldoutPanelOptions: function () {\n\t var options = FoldoutListItemView.prototype._getFoldoutPanelOptions.call(this);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t hasUser: this.hasUser\n\t });\n\t },\n\t\n\t /** override to not catch sub-panel selectors */\n\t $selector: function () {\n\t return this.$('> .selector');\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DCListItemView.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, FoldoutListItemView.prototype.templates.warnings, {\n\t error: BASE_MVC.wrapTemplate([\n\t // error during index fetch - show error on dataset\n\t '<% if( model.error ){ %>', '
                                  ', _l('There was an error getting the data for this collection'), ': <%- model.error %>', '
                                  ', '<% } %>']),\n\t purged: BASE_MVC.wrapTemplate(['<% if( model.purged ){ %>', '
                                  ', _l('This collection has been deleted and removed from disk'), '
                                  ', '<% } %>']),\n\t deleted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.deleted && !model.purged ){ %>', '
                                  ', _l('This collection has been deleted'), '
                                  ', '<% } %>'])\n\t });\n\t\n\t // use element identifier\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
                                  ', '
                                  ', '<%- collection.element_identifier || collection.name %>', '
                                  ', '
                                  ', '
                                  '], 'collection');\n\t\n\t // use element identifier\n\t var subtitleTemplate = BASE_MVC.wrapTemplate(['
                                  ', '<% var countText = collection.element_count? ( collection.element_count + \" \" ) : \"\"; %>', '<% if( collection.collection_type === \"list\" ){ %>', _l('a list of <%- countText %>datasets'), '<% } else if( collection.collection_type === \"paired\" ){ %>', _l('a pair of datasets'), '<% } else if( collection.collection_type === \"list:paired\" ){ %>', _l('a list of <%- countText %>dataset pairs'), '<% } else if( collection.collection_type === \"list:list\" ){ %>', _l('a list of <%- countText %>dataset lists'), '<% } %>', '
                                  '], 'collection');\n\t\n\t return _.extend({}, FoldoutListItemView.prototype.templates, {\n\t warnings: warnings,\n\t titleBar: titleBarTemplate,\n\t subtitle: subtitleTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for DatasetCollectionElement.\n\t */\n\t var DCEListItemView = ListItemView.extend(\n\t /** @lends DCEListItemView.prototype */{\n\t\n\t /** add the DCE class to the list item */\n\t className: ListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log('DCEListItemView.initialize:', attributes);\n\t ListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DCEListItemView.prototype.templates = function () {\n\t\n\t // use the element identifier here - since that will persist and the user will need it\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
                                  ', '
                                  ', '<%- element.element_identifier %>', '
                                  ', '
                                  ', '
                                  '], 'element');\n\t\n\t return _.extend({}, ListItemView.prototype.templates, {\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also an DatasetAssociation\n\t * (a dataset contained in a dataset collection).\n\t */\n\t var DatasetDCEListItemView = DATASET_LI.DatasetListItemView.extend(\n\t /** @lends DatasetDCEListItemView.prototype */{\n\t\n\t className: DATASET_LI.DatasetListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log('DatasetDCEListItemView.initialize:', attributes);\n\t DATASET_LI.DatasetListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** In this override, only get details if in the ready state.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetDCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetDCEListItemView.prototype.templates = function () {\n\t\n\t // use the element identifier here and not the dataset name\n\t //TODO:?? can we steal the DCE titlebar?\n\t var titleBarTemplate = BASE_MVC.wrapTemplate(['
                                  ', '', '
                                  ', '<%- element.element_identifier %>', '
                                  ', '
                                  '], 'element');\n\t\n\t return _.extend({}, DATASET_LI.DatasetListItemView.prototype.templates, {\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested DC).\n\t */\n\t var NestedDCDCEListItemView = DCListItemView.extend(\n\t /** @lends NestedDCDCEListItemView.prototype */{\n\t\n\t className: DCListItemView.prototype.className + \" dataset-collection-element\",\n\t\n\t /** In this override, add the state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t DCListItemView.prototype._swapNewRender.call(this, $newRender);\n\t var state = this.model.get('state') || 'ok';\n\t this.$el.addClass('state-' + state);\n\t return this.$el;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'NestedDCDCEListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DCListItemView: DCListItemView,\n\t DCEListItemView: DCEListItemView,\n\t DatasetDCEListItemView: DatasetDCEListItemView,\n\t NestedDCDCEListItemView: NestedDCDCEListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 56 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, Backbone, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(83), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_MODEL, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /*\n\t Notes:\n\t \n\t Terminology:\n\t DatasetCollection/DC : a container of datasets or nested DatasetCollections\n\t Element/DatasetCollectionElement/DCE : an item contained in a DatasetCollection\n\t HistoryDatasetCollectionAssociation/HDCA: a DatasetCollection contained in a history\n\t \n\t \n\t This all seems too complex unfortunately:\n\t \n\t - Terminology collision between DatasetCollections (DCs) and Backbone Collections.\n\t - In the DatasetCollections API JSON, DC Elements use a 'Has A' stucture to *contain*\n\t either a dataset or a nested DC. This would make the hierarchy much taller. I've\n\t decided to merge the contained JSON with the DC element json - making the 'has a'\n\t relation into an 'is a' relation. This seems simpler to me and allowed a lot of\n\t DRY in both models and views, but may make tracking or tracing within these models\n\t more difficult (since DatasetCollectionElements are now *also* DatasetAssociations\n\t or DatasetCollections (nested)). This also violates the rule of thumb about\n\t favoring aggregation over inheritance.\n\t - Currently, there are three DatasetCollection subclasses: List, Pair, and ListPaired.\n\t These each should a) be usable on their own, b) be usable in the context of\n\t nesting within a collection model (at least in the case of ListPaired), and\n\t c) be usable within the context of other container models (like History or\n\t LibraryFolder, etc.). I've tried to separate/extract classes in order to\n\t handle those three situations, but it's proven difficult to do in a simple,\n\t readable manner.\n\t - Ideally, histories and libraries would inherit from the same server models as\n\t dataset collections do since they are (in essence) dataset collections themselves -\n\t making the whole nested structure simpler. This would be a large, error-prone\n\t refactoring and migration.\n\t \n\t Many of the classes and heirarchy are meant as extension points so, while the\n\t relations and flow may be difficult to understand initially, they'll allow us to\n\t handle the growth or flux dataset collection in the future (w/o actually implementing\n\t any YAGNI).\n\t \n\t */\n\t //_________________________________________________________________________________________________ ELEMENTS\n\t /** @class mixin for Dataset collection elements.\n\t * When collection elements are passed from the API, the underlying element is\n\t * in a sub-object 'object' (IOW, a DCE representing an HDA will have HDA json in element.object).\n\t * This mixin uses the constructor and parse methods to merge that JSON with the DCE attribtues\n\t * effectively changing a DCE from a container to a subclass (has a --> is a).\n\t */\n\t\n\t var DatasetCollectionElementMixin = {\n\t\n\t /** default attributes used by elements in a dataset collection */\n\t defaults: {\n\t model_class: 'DatasetCollectionElement',\n\t element_identifier: null,\n\t element_index: null,\n\t element_type: null\n\t },\n\t\n\t /** merge the attributes of the sub-object 'object' into this model */\n\t _mergeObject: function (attributes) {\n\t // if we don't preserve and correct ids here, the element id becomes the object id\n\t // and collision in backbone's _byId will occur and only\n\t _.extend(attributes, attributes.object, { element_id: attributes.id });\n\t delete attributes.object;\n\t return attributes;\n\t },\n\t\n\t /** override to merge this.object into this */\n\t constructor: function (attributes, options) {\n\t // console.debug( '\\t DatasetCollectionElement.constructor:', attributes, options );\n\t attributes = this._mergeObject(attributes);\n\t this.idAttribute = 'element_id';\n\t Backbone.Model.apply(this, arguments);\n\t },\n\t\n\t /** when the model is fetched, merge this.object into this */\n\t parse: function (response, options) {\n\t var attributes = response;\n\t attributes = this._mergeObject(attributes);\n\t return attributes;\n\t }\n\t };\n\t\n\t /** @class Concrete class of Generic DatasetCollectionElement */\n\t var DatasetCollectionElement = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(DatasetCollectionElementMixin).extend({ _logNamespace: 'collections' });\n\t\n\t //==============================================================================\n\t /** @class Base/Abstract Backbone collection for Generic DCEs. */\n\t var DCECollection = Backbone.Collection.extend(BASE_MVC.LoggableMixin).extend(\n\t /** @lends DCECollection.prototype */{\n\t _logNamespace: 'collections',\n\t\n\t model: DatasetCollectionElement,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetCollectionElementCollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a dataset collection element that is a dataset (HDA).\n\t */\n\t var DatasetDCE = DATASET_MODEL.DatasetAssociation.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends DatasetDCE.prototype */{\n\t\n\t /** url fn */\n\t url: function () {\n\t // won't always be an hda\n\t if (!this.has('history_id')) {\n\t console.warn('no endpoint for non-hdas within a collection yet');\n\t // (a little silly since this api endpoint *also* points at hdas)\n\t return Galaxy.root + 'api/datasets';\n\t }\n\t return Galaxy.root + 'api/histories/' + this.get('history_id') + '/contents/' + this.get('id');\n\t },\n\t\n\t defaults: _.extend({}, DATASET_MODEL.DatasetAssociation.prototype.defaults, DatasetCollectionElementMixin.defaults),\n\t\n\t _downloadQueryParameters: function () {\n\t return '?to_ext=' + this.get('file_ext') + '&hdca_id=' + this.get('parent_hdca_id') + '&element_identifier=' + this.get('element_identifier');\n\t },\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually for now\n\t /** call the mixin constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t DatasetDCE.constructor:', attributes, options);\n\t //DATASET_MODEL.DatasetAssociation.prototype.constructor.call( this, attributes, options );\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** Does this model already contain detailed data (as opposed to just summary level data)? */\n\t hasDetails: function () {\n\t return this.elements && this.elements.length;\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.get('element_identifier');\n\t return ['DatasetDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class DCECollection of DatasetDCE's (a list of datasets, a pair of datasets).\n\t */\n\t var DatasetDCECollection = DCECollection.extend(\n\t /** @lends DatasetDCECollection.prototype */{\n\t model: DatasetDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //_________________________________________________________________________________________________ COLLECTIONS\n\t /** @class Backbone model for Dataset Collections.\n\t * The DC API returns an array of JSON objects under the attribute elements.\n\t * This model:\n\t * - removes that array/attribute ('elements') from the model,\n\t * - creates a bbone collection (of the class defined in the 'collectionClass' attribute),\n\t * - passes that json onto the bbone collection\n\t * - caches the bbone collection in this.elements\n\t */\n\t var DatasetCollection = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.SearchableModelMixin).extend( /** @lends DatasetCollection.prototype */{\n\t _logNamespace: 'collections',\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t /* 'list', 'paired', or 'list:paired' */\n\t collection_type: null,\n\t //??\n\t deleted: false\n\t },\n\t\n\t /** Which class to use for elements */\n\t collectionClass: DCECollection,\n\t\n\t /** set up: create elements instance var and (on changes to elements) update them */\n\t initialize: function (model, options) {\n\t this.debug(this + '(DatasetCollection).initialize:', model, options, this);\n\t this.elements = this._createElementsModel();\n\t this.on('change:elements', function () {\n\t this.log('change:elements');\n\t //TODO: prob. better to update the collection instead of re-creating it\n\t this.elements = this._createElementsModel();\n\t });\n\t },\n\t\n\t /** move elements model attribute to full collection */\n\t _createElementsModel: function () {\n\t this.debug(this + '._createElementsModel', this.collectionClass, this.get('elements'), this.elements);\n\t //TODO: same patterns as DatasetCollectionElement _createObjectModel - refactor to BASE_MVC.hasSubModel?\n\t var elements = this.get('elements') || [];\n\t this.unset('elements', { silent: true });\n\t var self = this;\n\t _.each(elements, function (element, index) {\n\t _.extend(element, { \"parent_hdca_id\": self.get(\"id\") });\n\t });\n\t this.elements = new this.collectionClass(elements);\n\t //this.debug( 'collectionClass:', this.collectionClass + '', this.elements );\n\t return this.elements;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** pass the elements back within the model json when this is serialized */\n\t toJSON: function () {\n\t var json = Backbone.Model.prototype.toJSON.call(this);\n\t if (this.elements) {\n\t json.elements = this.elements.toJSON();\n\t }\n\t return json;\n\t },\n\t\n\t /** Is this collection in a 'ready' state no processing (for the collection) is left\n\t * to do on the server.\n\t */\n\t inReadyState: function () {\n\t var populated = this.get('populated');\n\t return this.isDeletedOrPurged() || populated;\n\t },\n\t\n\t //TODO:?? the following are the same interface as DatasetAssociation - can we combine?\n\t /** Does the DC contain any elements yet? Is a fetch() required? */\n\t hasDetails: function () {\n\t return this.elements.length !== 0;\n\t },\n\t\n\t /** Given the filters, what models in this.elements would be returned? */\n\t getVisibleContents: function (filters) {\n\t // filters unused for now\n\t return this.elements;\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** save this dataset, _Mark_ing it as deleted (just a flag) */\n\t 'delete': function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** save this dataset, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted') || this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** Is this collection deleted or purged? */\n\t isDeletedOrPurged: function () {\n\t return this.get('deleted') || this.get('purged');\n\t },\n\t\n\t // ........................................................................ searchable\n\t /** searchable attributes for collections */\n\t searchAttributes: ['name', 'tags'],\n\t\n\t // ........................................................................ misc\n\t /** String representation */\n\t toString: function () {\n\t var idAndName = [this.get('id'), this.get('name') || this.get('element_identifier')];\n\t return 'DatasetCollection(' + idAndName.join(',') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** Model for a DatasetCollection containing datasets (non-nested).\n\t */\n\t var ListDatasetCollection = DatasetCollection.extend(\n\t /** @lends ListDatasetCollection.prototype */{\n\t\n\t /** override since we know the collection will only contain datasets */\n\t collectionClass: DatasetDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'List' + DatasetCollection.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** Model for a DatasetCollection containing fwd/rev datasets (a list of 2).\n\t */\n\t var PairDatasetCollection = ListDatasetCollection.extend(\n\t /** @lends PairDatasetCollection.prototype */{\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'Pair' + DatasetCollection.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //_________________________________________________________________________________________________ NESTED COLLECTIONS\n\t // this is where things get weird, man. Weird.\n\t //TODO: it might be possible to compact all the following...I think.\n\t //==============================================================================\n\t /** @class Backbone model for a Generic DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested collection). Currently only list:paired.\n\t */\n\t var NestedDCDCE = DatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedDCDCE.prototype */{\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually it now\n\t /** call the mixin constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedDCDCE.constructor:', attributes, options);\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection containing Generic NestedDCDCE's (nested dataset collections).\n\t */\n\t var NestedDCDCECollection = DCECollection.extend(\n\t /** @lends NestedDCDCECollection.prototype */{\n\t\n\t /** This is a collection of nested collections */\n\t model: NestedDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a paired dataset collection within a list:paired dataset collection.\n\t */\n\t var NestedPairDCDCE = PairDatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedPairDCDCE.prototype */{\n\t //TODO:?? possibly rename to NestedDatasetCollection?\n\t\n\t // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n\t // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n\t // - re-apply manually it now\n\t /** This is both a collection and a collection element - call the constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedPairDCDCE.constructor:', attributes, options);\n\t //DatasetCollection.constructor.call( this, attributes, options );\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedPairDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection for a backbone collection containing paired dataset collections.\n\t */\n\t var NestedPairDCDCECollection = NestedDCDCECollection.extend(\n\t /** @lends PairDCDCECollection.prototype */{\n\t\n\t /** We know this collection is composed of only nested pair collections */\n\t model: NestedPairDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedPairDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone Model for a DatasetCollection (list) that contains DatasetCollections (pairs).\n\t */\n\t var ListPairedDatasetCollection = DatasetCollection.extend(\n\t /** @lends ListPairedDatasetCollection.prototype */{\n\t\n\t /** list:paired is the only collection that itself contains collections */\n\t collectionClass: NestedPairDCDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['ListPairedDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for a list dataset collection within a list:list dataset collection. */\n\t var NestedListDCDCE = ListDatasetCollection.extend(BASE_MVC.mixin(DatasetCollectionElementMixin,\n\t /** @lends NestedListDCDCE.prototype */{\n\t\n\t /** This is both a collection and a collection element - call the constructor */\n\t constructor: function (attributes, options) {\n\t this.debug('\\t NestedListDCDCE.constructor:', attributes, options);\n\t DatasetCollectionElementMixin.constructor.call(this, attributes, options);\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t var objStr = this.object ? '' + this.object : this.get('element_identifier');\n\t return ['NestedListDCDCE(', objStr, ')'].join('');\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection containing list dataset collections. */\n\t var NestedListDCDCECollection = NestedDCDCECollection.extend({\n\t\n\t /** We know this collection is composed of only nested pair collections */\n\t model: NestedListDCDCE,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['NestedListDCDCECollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone Model for a DatasetCollection (list) that contains other lists. */\n\t var ListOfListsDatasetCollection = DatasetCollection.extend({\n\t\n\t /** list:paired is the only collection that itself contains collections */\n\t collectionClass: NestedListDCDCECollection,\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['ListOfListsDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t ListDatasetCollection: ListDatasetCollection,\n\t PairDatasetCollection: PairDatasetCollection,\n\t ListPairedDatasetCollection: ListPairedDatasetCollection,\n\t ListOfListsDatasetCollection: ListOfListsDatasetCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 57 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, $, jQuery) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(60), __webpack_require__(17), __webpack_require__(7), __webpack_require__(80), __webpack_require__(8), __webpack_require__(98), __webpack_require__(6), __webpack_require__(95)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HDCA, STATES, BASE_MVC, baseCreator, UI_MODAL, naturalSort, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t\n\t /*==============================================================================\n\t TODO:\n\t use proper Element model and not just json\n\t straighten out createFn, collection.createHDCA\n\t possibly stop using modals for this\n\t It would be neat to do a drag and drop\n\t \n\t ==============================================================================*/\n\t /** A view for both DatasetDCEs and NestedDCDCEs\n\t * (things that implement collection-model:DatasetCollectionElementMixin)\n\t */\n\t var DatasetCollectionElementView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n\t tagName: 'li',\n\t className: 'collection-element',\n\t\n\t initialize: function (attributes) {\n\t this.element = attributes.element || {};\n\t this.selected = attributes.selected || false;\n\t },\n\t\n\t render: function () {\n\t this.$el.attr('data-element-id', this.element.id).attr('draggable', true).html(this.template({ element: this.element }));\n\t if (this.selected) {\n\t this.$el.addClass('selected');\n\t }\n\t return this;\n\t },\n\t\n\t //TODO: lots of unused space in the element - possibly load details and display them horiz.\n\t template: _.template(['', '<%- element.name %>', '', ''].join('')),\n\t\n\t /** select this element and pub */\n\t select: function (toggle) {\n\t this.$el.toggleClass('selected', toggle);\n\t this.trigger('select', {\n\t source: this,\n\t selected: this.$el.hasClass('selected')\n\t });\n\t },\n\t\n\t /** animate the removal of this element and pub */\n\t discard: function () {\n\t var view = this,\n\t parentWidth = this.$el.parent().width();\n\t this.$el.animate({ 'margin-right': parentWidth }, 'fast', function () {\n\t view.trigger('discard', {\n\t source: view\n\t });\n\t view.destroy();\n\t });\n\t },\n\t\n\t /** remove the DOM and any listeners */\n\t destroy: function () {\n\t this.off();\n\t this.$el.remove();\n\t },\n\t\n\t events: {\n\t 'click': '_click',\n\t 'click .name': '_clickName',\n\t 'click .discard': '_clickDiscard',\n\t\n\t 'dragstart': '_dragstart',\n\t 'dragend': '_dragend',\n\t 'dragover': '_sendToParent',\n\t 'drop': '_sendToParent'\n\t },\n\t\n\t /** select when the li is clicked */\n\t _click: function (ev) {\n\t ev.stopPropagation();\n\t this.select(ev);\n\t },\n\t\n\t /** rename a pair when the name is clicked */\n\t _clickName: function (ev) {\n\t ev.stopPropagation();\n\t ev.preventDefault();\n\t var promptString = [_l('Enter a new name for the element'), ':\\n(', _l('Note that changing the name here will not rename the dataset'), ')'].join(''),\n\t response = prompt(_l('Enter a new name for the element') + ':', this.element.name);\n\t if (response) {\n\t this.element.name = response;\n\t this.render();\n\t }\n\t //TODO: cancelling with ESC leads to closure of the creator...\n\t },\n\t\n\t /** discard when the discard button is clicked */\n\t _clickDiscard: function (ev) {\n\t ev.stopPropagation();\n\t this.discard();\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragstart: function (ev) {\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t ev.dataTransfer.effectAllowed = 'move';\n\t ev.dataTransfer.setData('text/plain', JSON.stringify(this.element));\n\t\n\t this.$el.addClass('dragging');\n\t this.$el.parent().trigger('collection-element.dragstart', [this]);\n\t },\n\t\n\t /** dragging for re-ordering */\n\t _dragend: function (ev) {\n\t this.$el.removeClass('dragging');\n\t this.$el.parent().trigger('collection-element.dragend', [this]);\n\t },\n\t\n\t /** manually bubble up an event to the parent/container */\n\t _sendToParent: function (ev) {\n\t this.$el.parent().trigger(ev);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'DatasetCollectionElementView()';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t /** An interface for building collections.\n\t */\n\t var ListCollectionCreator = Backbone.View.extend(BASE_MVC.LoggableMixin).extend(baseCreator.CollectionCreatorMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t /** the class used to display individual elements */\n\t elementViewClass: DatasetCollectionElementView,\n\t /** the class this creator will create and save */\n\t collectionClass: HDCA.HistoryListDatasetCollection,\n\t className: 'list-collection-creator collection-creator flex-row-container',\n\t\n\t /** minimum number of valid elements to start with in order to build a collection of this type */\n\t minElements: 1,\n\t\n\t defaultAttributes: {\n\t //TODO: remove - use new collectionClass().save()\n\t /** takes elements and creates the proper collection - returns a promise */\n\t creationFn: function () {\n\t throw new TypeError('no creation fn for creator');\n\t },\n\t /** fn to call when the collection is created (scoped to this) */\n\t oncreate: function () {},\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t oncancel: function () {},\n\t /** distance from list edge to begin autoscrolling list */\n\t autoscrollDist: 24,\n\t /** Color passed to hoverhighlight */\n\t highlightClr: 'rgba( 64, 255, 255, 1.0 )'\n\t },\n\t\n\t footerSettings: {\n\t '.hide-originals': 'hideOriginals'\n\t },\n\t\n\t /** set up initial options, instance vars, behaviors */\n\t initialize: function (attributes) {\n\t this.metric('ListCollectionCreator.initialize', attributes);\n\t var creator = this;\n\t _.each(this.defaultAttributes, function (value, key) {\n\t value = attributes[key] || value;\n\t creator[key] = value;\n\t });\n\t\n\t /** unordered, original list - cache to allow reversal */\n\t creator.initialElements = attributes.elements || [];\n\t\n\t this._setUpCommonSettings(attributes);\n\t this._instanceSetUp();\n\t this._elementsSetUp();\n\t this._setUpBehaviors();\n\t },\n\t\n\t /** set up instance vars */\n\t _instanceSetUp: function () {\n\t /** Ids of elements that have been selected by the user - to preserve over renders */\n\t this.selectedIds = {};\n\t /** DOM elements currently being dragged */\n\t this.$dragging = null;\n\t /** Used for blocking UI events during ajax/operations (don't post twice) */\n\t this.blocking = false;\n\t },\n\t\n\t // ------------------------------------------------------------------------ process raw list\n\t /** set up main data */\n\t _elementsSetUp: function () {\n\t //this.debug( '-- _dataSetUp' );\n\t /** a list of invalid elements and the reasons they aren't valid */\n\t this.invalidElements = [];\n\t //TODO: handle fundamental problem of syncing DOM, views, and list here\n\t /** data for list in progress */\n\t this.workingElements = [];\n\t /** views for workingElements */\n\t this.elementViews = [];\n\t\n\t // copy initial list, sort, add ids if needed\n\t this.workingElements = this.initialElements.slice(0);\n\t this._ensureElementIds();\n\t this._validateElements();\n\t this._mangleDuplicateNames();\n\t this._sortElements();\n\t },\n\t\n\t /** add ids to dataset objs in initial list if none */\n\t _ensureElementIds: function () {\n\t this.workingElements.forEach(function (element) {\n\t if (!element.hasOwnProperty('id')) {\n\t element.id = _.uniqueId();\n\t }\n\t });\n\t return this.workingElements;\n\t },\n\t\n\t /** separate working list into valid and invalid elements for this collection */\n\t _validateElements: function () {\n\t var creator = this,\n\t existingNames = {};\n\t creator.invalidElements = [];\n\t\n\t this.workingElements = this.workingElements.filter(function (element) {\n\t var problem = creator._isElementInvalid(element);\n\t if (problem) {\n\t creator.invalidElements.push({\n\t element: element,\n\t text: problem\n\t });\n\t }\n\t return !problem;\n\t });\n\t return this.workingElements;\n\t },\n\t\n\t /** describe what is wrong with a particular element if anything */\n\t _isElementInvalid: function (element) {\n\t if (element.history_content_type !== 'dataset') {\n\t return _l(\"is not a dataset\");\n\t }\n\t var validState = element.state === STATES.OK || _.contains(STATES.NOT_READY_STATES, element.state);\n\t if (!validState) {\n\t return _l(\"has errored, is paused, or is not accessible\");\n\t }\n\t if (element.deleted || element.purged) {\n\t return _l(\"has been deleted or purged\");\n\t }\n\t return null;\n\t },\n\t\n\t /** mangle duplicate names using a mac-like '(counter)' addition to any duplicates */\n\t _mangleDuplicateNames: function () {\n\t var SAFETY = 900,\n\t counter = 1,\n\t existingNames = {};\n\t this.workingElements.forEach(function (element) {\n\t var currName = element.name;\n\t while (existingNames.hasOwnProperty(currName)) {\n\t currName = element.name + ' (' + counter + ')';\n\t counter += 1;\n\t if (counter >= SAFETY) {\n\t throw new Error('Safety hit in while loop - thats impressive');\n\t }\n\t }\n\t element.name = currName;\n\t existingNames[element.name] = true;\n\t });\n\t },\n\t\n\t /** sort a list of elements */\n\t _sortElements: function (list) {\n\t // // currently only natural sort by name\n\t // this.workingElements.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n\t // return this.workingElements;\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t // templates : ListCollectionCreator.templates,\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t if (this.workingElements.length < this.minElements) {\n\t return this._renderInvalid(speed, callback);\n\t }\n\t\n\t this.$el.empty().html(this.templates.main());\n\t this._renderHeader(speed);\n\t this._renderMiddle(speed);\n\t this._renderFooter(speed);\n\t this._addPluginComponents();\n\t this.$('.collection-name').focus();\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render a simplified interface aimed at telling the user why they can't move forward */\n\t _renderInvalid: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t this.$el.empty().html(this.templates.invalidInitial({\n\t problems: this.invalidElements,\n\t elements: this.workingElements\n\t }));\n\t if (typeof this.oncancel === 'function') {\n\t this.$('.cancel-create.btn').show();\n\t }\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render the header section */\n\t _renderHeader: function (speed, callback) {\n\t var $header = this.$('.header').empty().html(this.templates.header()).find('.help-content').prepend($(this.templates.helpContent()));\n\t //TODO: should only show once despite calling _renderHeader again\n\t if (this.invalidElements.length) {\n\t this._invalidElementsAlert();\n\t }\n\t return $header;\n\t },\n\t\n\t /** render the middle including the elements */\n\t _renderMiddle: function (speed, callback) {\n\t var $middle = this.$('.middle').empty().html(this.templates.middle());\n\t this._renderList(speed);\n\t return $middle;\n\t },\n\t\n\t /** add any jQuery/bootstrap/custom plugins to elements rendered */\n\t _addPluginComponents: function () {\n\t this.$('.help-content i').hoverhighlight('.collection-creator', this.highlightClr);\n\t },\n\t\n\t /** build and show an alert describing any elements that could not be included due to problems */\n\t _invalidElementsAlert: function () {\n\t this._showAlert(this.templates.invalidElements({ problems: this.invalidElements }), 'alert-warning');\n\t },\n\t\n\t _disableNameAndCreate: function (disable) {\n\t disable = !_.isUndefined(disable) ? disable : true;\n\t if (disable) {\n\t this.$('.collection-name').prop('disabled', true);\n\t this.$('.create-collection').toggleClass('disabled', true);\n\t // } else {\n\t // this.$( '.collection-name' ).prop( 'disabled', false );\n\t // this.$( '.create-collection' ).removeClass( 'disable' );\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering elements\n\t /** conv. to the main list display DOM */\n\t $list: function () {\n\t return this.$('.collection-elements');\n\t },\n\t\n\t /** show or hide the clear selected control based on the num of selected elements */\n\t _renderClearSelected: function () {\n\t if (_.size(this.selectedIds)) {\n\t this.$('.collection-elements-controls > .clear-selected').show();\n\t } else {\n\t this.$('.collection-elements-controls > .clear-selected').hide();\n\t }\n\t },\n\t\n\t /** render the elements in order (or a warning if no elements found) */\n\t _renderList: function (speed, callback) {\n\t //this.debug( '-- _renderList' );\n\t var creator = this,\n\t $tmp = jQuery('
                                  '),\n\t $list = creator.$list();\n\t\n\t _.each(this.elementViews, function (view) {\n\t view.destroy();\n\t creator.removeElementView(view);\n\t });\n\t\n\t // if( !this.workingElements.length ){\n\t // this._renderNoValidElements();\n\t // return;\n\t // }\n\t\n\t creator.workingElements.forEach(function (element) {\n\t var elementView = creator._createElementView(element);\n\t $tmp.append(elementView.$el);\n\t });\n\t\n\t creator._renderClearSelected();\n\t $list.empty().append($tmp.children());\n\t _.invoke(creator.elementViews, 'render');\n\t\n\t if ($list.height() > $list.css('max-height')) {\n\t $list.css('border-width', '1px 0px 1px 0px');\n\t } else {\n\t $list.css('border-width', '0px');\n\t }\n\t },\n\t\n\t /** create an element view, cache in elementViews, set up listeners, and return */\n\t _createElementView: function (element) {\n\t var elementView = new this.elementViewClass({\n\t //TODO: use non-generic class or not all\n\t // model : COLLECTION.DatasetDCE( element )\n\t element: element,\n\t selected: _.has(this.selectedIds, element.id)\n\t });\n\t this.elementViews.push(elementView);\n\t this._listenToElementView(elementView);\n\t return elementView;\n\t },\n\t\n\t /** listen to any element events */\n\t _listenToElementView: function (view) {\n\t var creator = this;\n\t creator.listenTo(view, {\n\t select: function (data) {\n\t var element = data.source.element;\n\t if (data.selected) {\n\t creator.selectedIds[element.id] = true;\n\t } else {\n\t delete creator.selectedIds[element.id];\n\t }\n\t creator.trigger('elements:select', data);\n\t },\n\t discard: function (data) {\n\t creator.trigger('elements:discard', data);\n\t }\n\t });\n\t },\n\t\n\t /** add a new element view based on the json in element */\n\t addElementView: function (element) {\n\t //TODO: workingElements is sorted, add element in appropo index\n\t // add element, sort elements, find element index\n\t // var view = this._createElementView( element );\n\t // return view;\n\t },\n\t\n\t /** stop listening to view and remove from caches */\n\t removeElementView: function (view) {\n\t delete this.selectedIds[view.element.id];\n\t this._renderClearSelected();\n\t\n\t this.elementViews = _.without(this.elementViews, view);\n\t this.stopListening(view);\n\t },\n\t\n\t /** render a message in the list that no elements remain to create a collection */\n\t _renderNoElementsLeft: function () {\n\t this._disableNameAndCreate(true);\n\t this.$('.collection-elements').append(this.templates.noElementsLeft());\n\t },\n\t\n\t // /** render a message in the list that no valid elements were found to create a collection */\n\t // _renderNoValidElements : function(){\n\t // this._disableNameAndCreate( true );\n\t // this.$( '.collection-elements' ).append( this.templates.noValidElements() );\n\t // },\n\t\n\t // ------------------------------------------------------------------------ API\n\t /** convert element into JSON compatible with the collections API */\n\t _elementToJSON: function (element) {\n\t // return element.toJSON();\n\t return element;\n\t },\n\t\n\t /** create the collection via the API\n\t * @returns {jQuery.xhr Object} the jquery ajax request\n\t */\n\t createList: function (name) {\n\t if (!this.workingElements.length) {\n\t var message = _l('No valid elements for final list') + '. ';\n\t message += '' + _l('Cancel') + ' ';\n\t message += _l('or');\n\t message += ' ' + _l('start over') + '.';\n\t this._showAlert(message);\n\t return;\n\t }\n\t\n\t var creator = this,\n\t elements = this.workingElements.map(function (element) {\n\t return creator._elementToJSON(element);\n\t });\n\t\n\t creator.blocking = true;\n\t return creator.creationFn(elements, name, creator.hideOriginals).always(function () {\n\t creator.blocking = false;\n\t }).fail(function (xhr, status, message) {\n\t creator.trigger('error', {\n\t xhr: xhr,\n\t status: status,\n\t message: _l('An error occurred while creating this collection')\n\t });\n\t }).done(function (response, message, xhr) {\n\t creator.trigger('collection:created', response, message, xhr);\n\t creator.metric('collection:created', response);\n\t if (typeof creator.oncreate === 'function') {\n\t creator.oncreate.call(this, response, message, xhr);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ events\n\t /** set up event handlers on self */\n\t _setUpBehaviors: function () {\n\t this.on('error', this._errorHandler);\n\t\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this.on('elements:select', function (data) {\n\t this._renderClearSelected();\n\t });\n\t\n\t this.on('elements:discard', function (data) {\n\t var element = data.source.element;\n\t this.removeElementView(data.source);\n\t\n\t this.workingElements = _.without(this.workingElements, element);\n\t if (!this.workingElements.length) {\n\t this._renderNoElementsLeft();\n\t }\n\t });\n\t\n\t //this.on( 'all', function(){\n\t // this.info( arguments );\n\t //});\n\t return this;\n\t },\n\t\n\t /** handle errors with feedback and details to the user (if available) */\n\t _errorHandler: function (data) {\n\t this.error(data);\n\t\n\t var creator = this;\n\t content = data.message || _l('An error occurred');\n\t if (data.xhr) {\n\t var xhr = data.xhr,\n\t message = data.message;\n\t if (xhr.readyState === 0 && xhr.status === 0) {\n\t content += ': ' + _l('Galaxy could not be reached and may be updating.') + _l(' Try again in a few minutes.');\n\t } else if (xhr.responseJSON) {\n\t content += ':
                                  ' + JSON.stringify(xhr.responseJSON) + '
                                  ';\n\t } else {\n\t content += ': ' + message;\n\t }\n\t }\n\t creator._showAlert(content, 'alert-danger');\n\t },\n\t\n\t events: {\n\t // header\n\t 'click .more-help': '_clickMoreHelp',\n\t 'click .less-help': '_clickLessHelp',\n\t 'click .main-help': '_toggleHelp',\n\t 'click .header .alert button': '_hideAlert',\n\t\n\t 'click .reset': 'reset',\n\t 'click .clear-selected': 'clearSelectedElements',\n\t\n\t // elements - selection\n\t 'click .collection-elements': 'clearSelectedElements',\n\t\n\t // elements - drop target\n\t // 'dragenter .collection-elements': '_dragenterElements',\n\t // 'dragleave .collection-elements': '_dragleaveElements',\n\t 'dragover .collection-elements': '_dragoverElements',\n\t 'drop .collection-elements': '_dropElements',\n\t\n\t // these bubble up from the elements as custom events\n\t 'collection-element.dragstart .collection-elements': '_elementDragstart',\n\t 'collection-element.dragend .collection-elements': '_elementDragend',\n\t\n\t // footer\n\t 'change .collection-name': '_changeName',\n\t 'keydown .collection-name': '_nameCheckForEnter',\n\t 'change .hide-originals': '_changeHideOriginals',\n\t 'click .cancel-create': '_cancelCreate',\n\t 'click .create-collection': '_clickCreate' //,\n\t },\n\t\n\t // ........................................................................ elements\n\t /** reset all data to the initial state */\n\t reset: function () {\n\t this._instanceSetUp();\n\t this._elementsSetUp();\n\t this.render();\n\t },\n\t\n\t /** deselect all elements */\n\t clearSelectedElements: function (ev) {\n\t this.$('.collection-elements .collection-element').removeClass('selected');\n\t this.$('.collection-elements-controls > .clear-selected').hide();\n\t },\n\t\n\t //_dragenterElements : function( ev ){\n\t // //this.debug( '_dragenterElements:', ev );\n\t //},\n\t //TODO: if selected are dragged out of the list area - remove the placeholder - cuz it won't work anyway\n\t // _dragleaveElements : function( ev ){\n\t // //this.debug( '_dragleaveElements:', ev );\n\t // },\n\t\n\t /** track the mouse drag over the list adding a placeholder to show where the drop would occur */\n\t _dragoverElements: function (ev) {\n\t //this.debug( '_dragoverElements:', ev );\n\t ev.preventDefault();\n\t\n\t var $list = this.$list();\n\t this._checkForAutoscroll($list, ev.originalEvent.clientY);\n\t var $nearest = this._getNearestElement(ev.originalEvent.clientY);\n\t\n\t //TODO: no need to re-create - move instead\n\t this.$('.element-drop-placeholder').remove();\n\t var $placeholder = $('
                                  ');\n\t if (!$nearest.length) {\n\t $list.append($placeholder);\n\t } else {\n\t $nearest.before($placeholder);\n\t }\n\t },\n\t\n\t /** If the mouse is near enough to the list's top or bottom, scroll the list */\n\t _checkForAutoscroll: function ($element, y) {\n\t var AUTOSCROLL_SPEED = 2,\n\t offset = $element.offset(),\n\t scrollTop = $element.scrollTop(),\n\t upperDist = y - offset.top,\n\t lowerDist = offset.top + $element.outerHeight() - y;\n\t if (upperDist >= 0 && upperDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop - AUTOSCROLL_SPEED);\n\t } else if (lowerDist >= 0 && lowerDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop + AUTOSCROLL_SPEED);\n\t }\n\t },\n\t\n\t /** get the nearest element based on the mouse's Y coordinate.\n\t * If the y is at the end of the list, return an empty jQuery object.\n\t */\n\t _getNearestElement: function (y) {\n\t var WIGGLE = 4,\n\t lis = this.$('.collection-elements li.collection-element').toArray();\n\t for (var i = 0; i < lis.length; i++) {\n\t var $li = $(lis[i]),\n\t top = $li.offset().top,\n\t halfHeight = Math.floor($li.outerHeight() / 2) + WIGGLE;\n\t if (top + halfHeight > y && top - halfHeight < y) {\n\t return $li;\n\t }\n\t }\n\t return $();\n\t },\n\t\n\t /** drop (dragged/selected elements) onto the list, re-ordering the internal list */\n\t _dropElements: function (ev) {\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t // both required for firefox\n\t ev.preventDefault();\n\t ev.dataTransfer.dropEffect = 'move';\n\t\n\t // insert before the nearest element or after the last.\n\t var $nearest = this._getNearestElement(ev.clientY);\n\t if ($nearest.length) {\n\t this.$dragging.insertBefore($nearest);\n\t } else {\n\t // no nearest before - insert after last element\n\t this.$dragging.insertAfter(this.$('.collection-elements .collection-element').last());\n\t }\n\t // resync the creator's list based on the new DOM order\n\t this._syncOrderToDom();\n\t return false;\n\t },\n\t\n\t /** resync the creator's list of elements based on the DOM order */\n\t _syncOrderToDom: function () {\n\t var creator = this,\n\t newElements = [];\n\t //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n\t this.$('.collection-elements .collection-element').each(function () {\n\t var id = $(this).attr('data-element-id'),\n\t element = _.findWhere(creator.workingElements, { id: id });\n\t if (element) {\n\t newElements.push(element);\n\t } else {\n\t console.error('missing element: ', id);\n\t }\n\t });\n\t this.workingElements = newElements;\n\t this._renderList();\n\t },\n\t\n\t /** drag communication with element sub-views: dragstart */\n\t _elementDragstart: function (ev, element) {\n\t // auto select the element causing the event and move all selected\n\t element.select(true);\n\t this.$dragging = this.$('.collection-elements .collection-element.selected');\n\t },\n\t\n\t /** drag communication with element sub-views: dragend - remove the placeholder */\n\t _elementDragend: function (ev, element) {\n\t $('.element-drop-placeholder').remove();\n\t this.$dragging = null;\n\t },\n\t\n\t // ------------------------------------------------------------------------ templates\n\t //TODO: move to require text plugin and load these as text\n\t //TODO: underscore currently unnecc. bc no vars are used\n\t //TODO: better way of localizing text-nodes in long strings\n\t /** underscore template fns attached to class */\n\t templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\t\n\t /** the header (not including help text) */\n\t header: _.template(['', '
                                  ', '', '', '
                                  '].join('')),\n\t\n\t /** the middle: element list */\n\t middle: _.template(['', '
                                  ', '
                                  '].join('')),\n\t\n\t /** creation and cancel controls */\n\t footer: _.template(['
                                  ', '
                                  ', '', '
                                  ', '
                                  ', '', '
                                  ', _l('Name'), ':
                                  ', '
                                  ', '
                                  ', '
                                  ', '
                                  ', '', '
                                  ', '', '', '
                                  ', '
                                  ', '
                                  ', '', '
                                  ', '
                                  '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

                                  ', _l(['Collections of datasets are permanent, ordered lists of datasets that can be passed to tools and ', 'workflows in order to have analyses done on each member of the entire group. This interface allows ', 'you to create a collection and re-order the final collection.'].join('')), '

                                  ', '
                                    ', '
                                  • ', _l(['Rename elements in the list by clicking on ', 'the existing name.'].join('')), '
                                  • ', '
                                  • ', _l(['Discard elements from the final created list by clicking on the ', '\"Discard\" button.'].join('')), '
                                  • ', '
                                  • ', _l(['Reorder the list by clicking and dragging elements. Select multiple elements by clicking on ', 'them and you can then move those selected by dragging the ', 'entire group. Deselect them by clicking them again or by clicking the ', 'the \"Clear selected\" link.'].join('')), '
                                  • ', '
                                  • ', _l(['Click the \"Start over\" link to begin again as if you had just opened ', 'the interface.'].join('')), '
                                  • ', '
                                  • ', _l(['Click the \"Cancel\" button to exit the interface.'].join('')), '
                                  • ', '

                                  ', '

                                  ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\".'].join('')), '

                                  '].join('')),\n\t\n\t /** shown in list when all elements are discarded */\n\t invalidElements: _.template([_l('The following selections could not be included due to problems:'), '
                                    <% _.each( problems, function( problem ){ %>', '
                                  • <%- problem.element.name %>: <%- problem.text %>
                                  • ', '<% }); %>
                                  '].join('')),\n\t\n\t /** shown in list when all elements are discarded */\n\t noElementsLeft: _.template(['
                                2. ', _l('No elements left! '), _l('Would you like to '), '', _l('start over'), '?', '
                                3. '].join('')),\n\t\n\t /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n\t invalidInitial: _.template(['
                                  ', '
                                  ', '', '<% if( _.size( problems ) ){ %>', _l('The following selections could not be included due to problems'), ':', '
                                    <% _.each( problems, function( problem ){ %>', '
                                  • <%- problem.element.name %>: <%- problem.text %>
                                  • ', '<% }); %>
                                  ', '<% } else if( _.size( elements ) < 1 ){ %>', _l('No datasets were selected'), '.', '<% } %>', '
                                  ', _l('At least one element is needed for the collection'), '. ', _l('You may need to '), '', _l('cancel'), ' ', _l('and reselect new elements'), '.', '
                                  ', '
                                  ', '
                                  ', '
                                  ', '
                                  ', '
                                  ', '',\n\t // _l( 'Create a different kind of collection' ),\n\t '
                                  ', '
                                  ', '
                                  '].join(''))\n\t }),\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionCreator';\n\t }\n\t });\n\t\n\t //=============================================================================\n\t /** Create a modal and load its body with the given CreatorClass creator type\n\t * @returns {Deferred} resolved when creator has built a collection.\n\t */\n\t var collectionCreatorModal = function _collectionCreatorModal(elements, options, CreatorClass) {\n\t\n\t var deferred = jQuery.Deferred(),\n\t modal = Galaxy.modal || new UI_MODAL.View(),\n\t creator;\n\t\n\t options = _.defaults(options || {}, {\n\t elements: elements,\n\t oncancel: function () {\n\t modal.hide();\n\t deferred.reject('cancelled');\n\t },\n\t oncreate: function (creator, response) {\n\t modal.hide();\n\t deferred.resolve(response);\n\t }\n\t });\n\t\n\t creator = new CreatorClass(options);\n\t modal.show({\n\t title: options.title || _l('Create a collection'),\n\t body: creator.$el,\n\t width: '80%',\n\t height: '100%',\n\t closing_events: true\n\t });\n\t creator.render();\n\t window._collectionCreator = creator;\n\t\n\t //TODO: remove modal header\n\t return deferred;\n\t };\n\t\n\t /** List collection flavor of collectionCreatorModal. */\n\t var listCollectionCreatorModal = function _listCollectionCreatorModal(elements, options) {\n\t options = options || {};\n\t options.title = _l('Create a collection from a list of datasets');\n\t return collectionCreatorModal(elements, options, ListCollectionCreator);\n\t };\n\t\n\t //==============================================================================\n\t /** Use a modal to create a list collection, then add it to the given history contents.\n\t * @returns {Deferred} resolved when the collection is added to the history.\n\t */\n\t function createListCollection(contents, defaultHideSourceItems) {\n\t var elements = contents.toJSON(),\n\t promise = listCollectionCreatorModal(elements, {\n\t defaultHideSourceItems: defaultHideSourceItems,\n\t creationFn: function (elements, name, hideSourceItems) {\n\t elements = elements.map(function (element) {\n\t return {\n\t id: element.id,\n\t name: element.name,\n\t //TODO: this allows for list:list even if the filter above does not - reconcile\n\t src: element.history_content_type === 'dataset' ? 'hda' : 'hdca'\n\t };\n\t });\n\t return contents.createHDCA(elements, 'list', name, hideSourceItems);\n\t }\n\t });\n\t return promise;\n\t }\n\t\n\t //==============================================================================\n\t return {\n\t DatasetCollectionElementView: DatasetCollectionElementView,\n\t ListCollectionCreator: ListCollectionCreator,\n\t\n\t collectionCreatorModal: collectionCreatorModal,\n\t listCollectionCreatorModal: listCollectionCreatorModal,\n\t createListCollection: createListCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 58 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, Backbone, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(17), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, STATES, faIconButton, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t var logNamespace = 'dataset';\n\t /*==============================================================================\n\t TODO:\n\t straighten out state rendering and templates used\n\t inaccessible/STATES.NOT_VIEWABLE is a special case\n\t simplify button rendering\n\t \n\t ==============================================================================*/\n\t var _super = LIST_ITEM.ListItemView;\n\t /** @class Read only list view for either LDDAs, HDAs, or HDADCEs.\n\t * Roughly, any DatasetInstance (and not a raw Dataset).\n\t */\n\t var DatasetListItemView = _super.extend(\n\t /** @lends DatasetListItemView.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t className: _super.prototype.className + \" dataset\",\n\t //TODO:?? doesn't exactly match an hda's type_id\n\t id: function () {\n\t return ['dataset', this.model.get('id')].join('-');\n\t },\n\t\n\t /** Set up: instance vars, options, and event handlers */\n\t initialize: function (attributes) {\n\t if (attributes.logger) {\n\t this.logger = this.model.logger = attributes.logger;\n\t }\n\t this.log(this + '.initialize:', attributes);\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t /** where should pages from links be displayed? (default to new tab/window) */\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t var self = this;\n\t\n\t // re-rendering on any model changes\n\t return self.listenTo(self.model, {\n\t 'change': function (model) {\n\t // if the model moved into the ready state and is expanded without details, fetch those details now\n\t if (self.model.changedAttributes().state && self.model.inReadyState() && self.expanded && !self.model.hasDetails()) {\n\t // normally, will render automatically (due to fetch -> change),\n\t // but! setting_metadata sometimes doesn't cause any other changes besides state\n\t // so, not rendering causes it to seem frozen in setting_metadata state\n\t self.model.fetch({ silent: true }).done(function () {\n\t self.render();\n\t });\n\t } else {\n\t if (_.has(model.changed, 'tags') && _.keys(model.changed).length === 1) {\n\t // If only the tags have changed, rerender specifically\n\t // the titlebar region. Otherwise default to the full\n\t // render.\n\t self.$('.nametags').html(self._renderNametags());\n\t } else {\n\t self.render();\n\t }\n\t }\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... expandable\n\t /** In this override, only get details if in the ready state, get rerunnable if in other states.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ......................................................................... removal\n\t /** Remove this view's html from the DOM and remove all event listeners.\n\t * @param {Number or String} speed jq effect speed\n\t * @param {Function} callback an optional function called when removal is done (scoped to this view)\n\t */\n\t remove: function (speed, callback) {\n\t var view = this;\n\t speed = speed || this.fxSpeed;\n\t this.$el.fadeOut(speed, function () {\n\t Backbone.View.prototype.remove.call(view);\n\t if (callback) {\n\t callback.call(view);\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... rendering\n\t /* TODO:\n\t dataset states are the issue primarily making dataset rendering complex\n\t each state should have it's own way of displaying/set of details\n\t often with different actions that can be applied\n\t throw in deleted/purged/visible and things get complicated easily\n\t I've considered (a couple of times) - creating a view for each state\n\t - but recreating the view during an update...seems wrong\n\t */\n\t /** In this override, add the dataset state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t if (this.model.has('state')) {\n\t this.$el.addClass('state-' + this.model.get('state'));\n\t }\n\t return this.$el;\n\t },\n\t\n\t // ................................................................................ titlebar\n\t /** In this override, add the dataset display button. */\n\t _renderPrimaryActions: function () {\n\t // render just the display for read-only\n\t return [this._renderDisplayButton()];\n\t },\n\t\n\t /** Render icon-button to display dataset data */\n\t _renderDisplayButton: function () {\n\t // don't show display if not viewable or not accessible\n\t var state = this.model.get('state');\n\t if (state === STATES.NOT_VIEWABLE || state === STATES.DISCARDED || !this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var displayBtnData = {\n\t target: this.linkTarget,\n\t classes: 'display-btn'\n\t };\n\t\n\t // show a disabled display if the data's been purged\n\t if (this.model.get('purged')) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('Cannot display datasets removed from disk');\n\t\n\t // disable if still uploading\n\t } else if (state === STATES.UPLOAD) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('This dataset must finish uploading before it can be viewed');\n\t\n\t // disable if still new\n\t } else if (state === STATES.NEW) {\n\t displayBtnData.disabled = true;\n\t displayBtnData.title = _l('This dataset is not yet viewable');\n\t } else {\n\t displayBtnData.title = _l('View data');\n\t\n\t // default link for dataset\n\t displayBtnData.href = this.model.urls.display;\n\t\n\t // add frame manager option onclick event\n\t var self = this;\n\t displayBtnData.onclick = function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t // Add dataset to frames.\n\t Galaxy.frame.addDataset(self.model.get('id'));\n\t ev.preventDefault();\n\t }\n\t };\n\t }\n\t displayBtnData.faIcon = 'fa-eye';\n\t return faIconButton(displayBtnData);\n\t },\n\t\n\t // ......................................................................... rendering details\n\t /** Render the enclosing div of the hda body and, if expanded, the html in the body\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderDetails: function () {\n\t //TODO: generalize to be allow different details for each state\n\t\n\t // no access - render nothing but a message\n\t if (this.model.get('state') === STATES.NOT_VIEWABLE) {\n\t return $(this.templates.noAccess(this.model.toJSON(), this));\n\t }\n\t\n\t var $details = _super.prototype._renderDetails.call(this);\n\t $details.find('.actions .left').empty().append(this._renderSecondaryActions());\n\t $details.find('.summary').html(this._renderSummary()).prepend(this._renderDetailMessages());\n\t $details.find('.display-applications').html(this._renderDisplayApplications());\n\t\n\t this._setUpBehaviors($details);\n\t return $details;\n\t },\n\t\n\t /** Defer to the appropo summary rendering fn based on state */\n\t _renderSummary: function () {\n\t var json = this.model.toJSON(),\n\t summaryRenderFn = this.templates.summaries[json.state];\n\t summaryRenderFn = summaryRenderFn || this.templates.summaries.unknown;\n\t return summaryRenderFn(json, this);\n\t },\n\t\n\t /** Render messages to be displayed only when the details are shown */\n\t _renderDetailMessages: function () {\n\t var view = this,\n\t $warnings = $('
                                  '),\n\t json = view.model.toJSON();\n\t //TODO:! unordered (map)\n\t _.each(view.templates.detailMessages, function (templateFn) {\n\t $warnings.append($(templateFn(json, view)));\n\t });\n\t return $warnings;\n\t },\n\t\n\t /** Render the external display application links */\n\t _renderDisplayApplications: function () {\n\t if (this.model.isDeletedOrPurged()) {\n\t return '';\n\t }\n\t // render both old and new display apps using the same template\n\t return [this.templates.displayApplications(this.model.get('display_apps'), this), this.templates.displayApplications(this.model.get('display_types'), this)].join('');\n\t },\n\t\n\t // ......................................................................... secondary/details actions\n\t /** A series of links/buttons for less commonly used actions: re-run, info, etc. */\n\t _renderSecondaryActions: function () {\n\t this.debug('_renderSecondaryActions');\n\t switch (this.model.get('state')) {\n\t case STATES.NOT_VIEWABLE:\n\t return [];\n\t case STATES.OK:\n\t case STATES.FAILED_METADATA:\n\t case STATES.ERROR:\n\t return [this._renderDownloadButton(), this._renderShowParamsButton()];\n\t }\n\t return [this._renderShowParamsButton()];\n\t },\n\t\n\t /** Render icon-button to show the input and output (stdout/err) for the job that created this.\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderShowParamsButton: function () {\n\t // gen. safe to show in all cases\n\t return faIconButton({\n\t title: _l('View details'),\n\t classes: 'params-btn',\n\t href: this.model.urls.show_params,\n\t target: this.linkTarget,\n\t faIcon: 'fa-info-circle',\n\t onclick: function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t Galaxy.frame.add({ title: 'Dataset details', url: this.href });\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** Render icon-button/popupmenu to download the data (and/or the associated meta files (bai, etc.)) for this.\n\t * @returns {jQuery} rendered DOM\n\t */\n\t _renderDownloadButton: function () {\n\t // don't show anything if the data's been purged\n\t if (this.model.get('purged') || !this.model.hasData()) {\n\t return null;\n\t }\n\t\n\t // return either: a popupmenu with links to download assoc. meta files (if there are meta files)\n\t // or a single download icon-button (if there are no meta files)\n\t if (!_.isEmpty(this.model.get('meta_files'))) {\n\t return this._renderMetaFileDownloadButton();\n\t }\n\t\n\t return $(['', '', ''].join(''));\n\t },\n\t\n\t /** Render the download button which opens a dropdown with links to download assoc. meta files (indeces, etc.) */\n\t _renderMetaFileDownloadButton: function () {\n\t var urls = this.model.urls;\n\t return $(['
                                  ', '', '', '', '', '
                                  '].join('\\n'));\n\t },\n\t\n\t _renderNametags: function () {\n\t var tpl = _.template(['<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>'].join(''));\n\t return tpl({ tags: this.model.get('tags') });\n\t },\n\t\n\t // ......................................................................... misc\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .display-btn': function (ev) {\n\t this.trigger('display', this, ev);\n\t },\n\t 'click .params-btn': function (ev) {\n\t this.trigger('params', this, ev);\n\t },\n\t 'click .download-btn': function (ev) {\n\t this.trigger('download', this, ev);\n\t }\n\t }),\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetListItemView.prototype.templates = function () {\n\t //TODO: move to require text! plugin\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t failed_metadata: BASE_MVC.wrapTemplate([\n\t // failed metadata is rendered as a warning on an otherwise ok dataset view\n\t '<% if( model.state === \"failed_metadata\" ){ %>', '
                                  ', _l('An error occurred setting the metadata for this dataset'), '
                                  ', '<% } %>']),\n\t error: BASE_MVC.wrapTemplate([\n\t // error during index fetch - show error on dataset\n\t '<% if( model.error ){ %>', '
                                  ', _l('There was an error getting the data for this dataset'), ': <%- model.error %>', '
                                  ', '<% } %>']),\n\t purged: BASE_MVC.wrapTemplate(['<% if( model.purged ){ %>', '
                                  ', _l('This dataset has been deleted and removed from disk'), '
                                  ', '<% } %>']),\n\t deleted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.deleted && !model.purged ){ %>', '
                                  ', _l('This dataset has been deleted'), '
                                  ', '<% } %>'])\n\t\n\t //NOTE: hidden warning is only needed for HDAs\n\t });\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate(['
                                  ', '
                                  ', '
                                  ', '
                                  ', '
                                  ', '
                                  ',\n\t\n\t // do not display tags, annotation, display apps, or peek when deleted\n\t '<% if( !dataset.deleted && !dataset.purged ){ %>', '
                                  ', '
                                  ', '
                                  ', '<% if( dataset.peek ){ %>', '
                                  <%= dataset.peek %>
                                  ', '<% } %>', '<% } %>', '
                                  '], 'dataset');\n\t\n\t var noAccessTemplate = BASE_MVC.wrapTemplate(['
                                  ', '
                                  ', _l('You do not have permission to view this dataset'), '
                                  ', '
                                  '], 'dataset');\n\t\n\t //TODO: still toooooooooooooo complex - rework\n\t var summaryTemplates = {};\n\t summaryTemplates[STATES.OK] = summaryTemplates[STATES.FAILED_METADATA] = BASE_MVC.wrapTemplate(['<% if( dataset.misc_blurb ){ %>', '
                                  ', '<%- dataset.misc_blurb %>', '
                                  ', '<% } %>', '<% if( dataset.file_ext ){ %>', '
                                  ', '', '<%- dataset.file_ext %>', '
                                  ', '<% } %>', '<% if( dataset.metadata_dbkey ){ %>', '
                                  ', '', '', '<%- dataset.metadata_dbkey %>', '', '
                                  ', '<% } %>', '<% if( dataset.misc_info ){ %>', '
                                  ', '<%- dataset.misc_info %>', '
                                  ', '<% } %>'], 'dataset');\n\t summaryTemplates[STATES.NEW] = BASE_MVC.wrapTemplate(['
                                  ', _l('This is a new dataset and not all of its data are available yet'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.NOT_VIEWABLE] = BASE_MVC.wrapTemplate(['
                                  ', _l('You do not have permission to view this dataset'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.DISCARDED] = BASE_MVC.wrapTemplate(['
                                  ', _l('The job creating this dataset was cancelled before completion'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.QUEUED] = BASE_MVC.wrapTemplate(['
                                  ', _l('This job is waiting to run'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.RUNNING] = BASE_MVC.wrapTemplate(['
                                  ', _l('This job is currently running'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.UPLOAD] = BASE_MVC.wrapTemplate(['
                                  ', _l('This dataset is currently uploading'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.SETTING_METADATA] = BASE_MVC.wrapTemplate(['
                                  ', _l('Metadata is being auto-detected'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.PAUSED] = BASE_MVC.wrapTemplate(['
                                  ', _l('This job is paused. Use the \"Resume Paused Jobs\" in the history menu to resume'), '
                                  '], 'dataset');\n\t summaryTemplates[STATES.ERROR] = BASE_MVC.wrapTemplate(['<% if( !dataset.purged ){ %>', '
                                  <%- dataset.misc_blurb %>
                                  ', '<% } %>', '', _l('An error occurred with this dataset'), ':', '
                                  <%- dataset.misc_info %>
                                  '], 'dataset');\n\t summaryTemplates[STATES.EMPTY] = BASE_MVC.wrapTemplate(['
                                  ', _l('No data'), ': <%- dataset.misc_blurb %>
                                  '], 'dataset');\n\t summaryTemplates.unknown = BASE_MVC.wrapTemplate(['
                                  Error: unknown dataset state: \"<%- dataset.state %>\"
                                  '], 'dataset');\n\t\n\t // messages to be displayed only within the details section ('below the fold')\n\t var detailMessageTemplates = {\n\t resubmitted: BASE_MVC.wrapTemplate([\n\t // deleted not purged\n\t '<% if( model.resubmitted ){ %>', '
                                  ', _l('The job creating this dataset has been resubmitted'), '
                                  ', '<% } %>'])\n\t };\n\t\n\t // this is applied to both old and new style display apps\n\t var displayApplicationsTemplate = BASE_MVC.wrapTemplate(['<% _.each( apps, function( app ){ %>', '
                                  ', '<%- app.label %> ', '', '<% _.each( app.links, function( link ){ %>', '\" href=\"<%- link.href %>\">', '<% print( _l( link.text ) ); %>', ' ', '<% }); %>', '', '
                                  ', '<% }); %>'], 'apps');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t details: detailsTemplate,\n\t noAccess: noAccessTemplate,\n\t summaries: summaryTemplates,\n\t detailMessages: detailMessageTemplates,\n\t displayApplications: displayApplicationsTemplate\n\t });\n\t }();\n\t\n\t // ============================================================================\n\t return {\n\t DatasetListItemView: DatasetListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 59 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {/** Generic form view */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(10), __webpack_require__(5)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Form, Ui) {\n\t\n\t var View = Backbone.View.extend({\n\t\n\t initialize: function (options) {\n\t this.model = new Backbone.Model(options);\n\t this.url = this.model.get('url');\n\t this.redirect = this.model.get('redirect');\n\t this.setElement('
                                  ');\n\t this.render();\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t $.ajax({\n\t url: Galaxy.root + this.url,\n\t type: 'GET'\n\t }).done(function (response) {\n\t var options = $.extend({}, self.model.attributes, response);\n\t var form = new Form({\n\t title: options.title,\n\t message: options.message,\n\t status: options.status || 'warning',\n\t icon: options.icon,\n\t inputs: options.inputs,\n\t buttons: {\n\t 'submit': new Ui.Button({\n\t tooltip: options.submit_tooltip,\n\t title: options.submit_title || 'Save settings',\n\t icon: options.submit_icon || 'fa-save',\n\t cls: 'btn btn-primary ui-clear-float',\n\t onclick: function () {\n\t self._submit(form);\n\t }\n\t })\n\t }\n\t });\n\t self.$el.empty().append(form.$el);\n\t }).fail(function (response) {\n\t self.$el.empty().append(new Ui.Message({\n\t message: 'Failed to load resource ' + self.url + '.',\n\t status: 'danger',\n\t persistent: true\n\t }).$el);\n\t });\n\t },\n\t\n\t _submit: function (form) {\n\t var self = this;\n\t $.ajax({\n\t url: Galaxy.root + self.url,\n\t data: JSON.stringify(form.data.create()),\n\t type: 'PUT',\n\t contentType: 'application/json'\n\t }).done(function (response) {\n\t var success_message = { message: response.message, status: 'success', persistent: false };\n\t if (self.redirect) {\n\t window.location = Galaxy.root + self.redirect + '?' + $.param(success_message);\n\t } else {\n\t form.data.matchModel(response, function (input, input_id) {\n\t form.field_list[input_id].value(input.value);\n\t });\n\t self._showMessage(form, success_message);\n\t }\n\t }).fail(function (response) {\n\t self._showMessage(form, { message: response.responseJSON.err_msg, status: 'danger', persistent: false });\n\t });\n\t },\n\t\n\t _showMessage: function (form, options) {\n\t var $panel = form.$el.parents().filter(function () {\n\t return ['auto', 'scroll'].indexOf($(this).css('overflow')) != -1;\n\t }).first();\n\t $panel.animate({ scrollTop: 0 }, 500);\n\t form.message.update(options);\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 60 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(56), __webpack_require__(88), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_MODEL, HISTORY_CONTENT, _l) {\n\t\n\t 'use strict';\n\t\n\t /*==============================================================================\n\t \n\t Models for DatasetCollections contained within a history.\n\t \n\t TODO:\n\t these might be compactable to one class if some duplication with\n\t collection-model is used.\n\t \n\t ==============================================================================*/\n\t\n\t var hcontentMixin = HISTORY_CONTENT.HistoryContentMixin,\n\t ListDC = DC_MODEL.ListDatasetCollection,\n\t PairDC = DC_MODEL.PairDatasetCollection,\n\t ListPairedDC = DC_MODEL.ListPairedDatasetCollection,\n\t ListOfListsDC = DC_MODEL.ListOfListsDatasetCollection;\n\t\n\t //==============================================================================\n\t /** Override to post to contents route w/o id. */\n\t function buildHDCASave(_super) {\n\t return function _save(attributes, options) {\n\t if (this.isNew()) {\n\t options = options || {};\n\t options.url = this.urlRoot + this.get('history_id') + '/contents';\n\t attributes = attributes || {};\n\t attributes.type = 'dataset_collection';\n\t }\n\t return _super.call(this, attributes, options);\n\t };\n\t }\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List Dataset Collection within a History.\n\t */\n\t var HistoryListDatasetCollection = ListDC.extend(hcontentMixin).extend(\n\t /** @lends HistoryListDatasetCollection.prototype */{\n\t\n\t defaults: _.extend(_.clone(ListDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + ListDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for Pair Dataset Collection within a History.\n\t * @constructs\n\t */\n\t var HistoryPairDatasetCollection = PairDC.extend(hcontentMixin).extend(\n\t /** @lends HistoryPairDatasetCollection.prototype */{\n\t\n\t defaults: _.extend(_.clone(PairDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'paired',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(PairDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + PairDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List of Pairs Dataset Collection within a History. */\n\t var HistoryListPairedDatasetCollection = ListPairedDC.extend(hcontentMixin).extend({\n\t\n\t defaults: _.extend(_.clone(ListPairedDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list:paired',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListPairedDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return 'History' + ListPairedDC.prototype.toString.call(this);\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** @class Backbone model for List of Lists Dataset Collection within a History. */\n\t var HistoryListOfListsDatasetCollection = ListOfListsDC.extend(hcontentMixin).extend({\n\t\n\t defaults: _.extend(_.clone(ListOfListsDC.prototype.defaults), {\n\t history_content_type: 'dataset_collection',\n\t collection_type: 'list:list',\n\t model_class: 'HistoryDatasetCollectionAssociation'\n\t }),\n\t\n\t /** Override to post to contents route w/o id. */\n\t save: buildHDCASave(ListOfListsDC.prototype.save),\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['HistoryListOfListsDatasetCollection(', this.get('name'), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryListDatasetCollection: HistoryListDatasetCollection,\n\t HistoryPairDatasetCollection: HistoryPairDatasetCollection,\n\t HistoryListPairedDatasetCollection: HistoryListPairedDatasetCollection,\n\t HistoryListOfListsDatasetCollection: HistoryListOfListsDatasetCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 61 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, Backbone) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(79), __webpack_require__(86), __webpack_require__(60), __webpack_require__(63), __webpack_require__(7), __webpack_require__(150)], __WEBPACK_AMD_DEFINE_RESULT__ = function (CONTROLLED_FETCH_COLLECTION, HDA_MODEL, HDCA_MODEL, HISTORY_PREFS, BASE_MVC, AJAX_QUEUE) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = CONTROLLED_FETCH_COLLECTION.PaginatedCollection;\n\t /** @class Backbone collection for history content.\n\t * NOTE: history content seems like a dataset collection, but differs in that it is mixed:\n\t * each element can be either an HDA (dataset) or a DatasetCollection and co-exist on\n\t * the same level.\n\t * Dataset collections on the other hand are not mixed and (so far) can only contain either\n\t * HDAs or child dataset collections on one level.\n\t * This is why this does not inherit from any of the DatasetCollections (currently).\n\t */\n\t var HistoryContents = _super.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: 'history',\n\t\n\t // ........................................................................ composite collection\n\t /** since history content is a mix, override model fn into a factory, creating based on history_content_type */\n\t model: function (attrs, options) {\n\t if (attrs.history_content_type === \"dataset\") {\n\t return new HDA_MODEL.HistoryDatasetAssociation(attrs, options);\n\t } else if (attrs.history_content_type === \"dataset_collection\") {\n\t switch (attrs.collection_type) {\n\t case 'list':\n\t return new HDCA_MODEL.HistoryListDatasetCollection(attrs, options);\n\t case 'paired':\n\t return new HDCA_MODEL.HistoryPairDatasetCollection(attrs, options);\n\t case 'list:paired':\n\t return new HDCA_MODEL.HistoryListPairedDatasetCollection(attrs, options);\n\t case 'list:list':\n\t return new HDCA_MODEL.HistoryListOfListsDatasetCollection(attrs, options);\n\t }\n\t // This is a hack inside a hack:\n\t // Raise a plain object with validationError to fake a model.validationError\n\t // (since we don't have a model to use validate with)\n\t // (the outer hack being the mixed content/model function in this collection)\n\t var msg = 'Unknown collection_type: ' + attrs.collection_type;\n\t console.warn(msg, attrs);\n\t return { validationError: msg };\n\t }\n\t return { validationError: 'Unknown history_content_type: ' + attrs.history_content_type };\n\t },\n\t\n\t // ........................................................................ set up\n\t limitPerPage: 500,\n\t\n\t /** @type {Integer} how many contents per call to fetch when using progressivelyFetchDetails */\n\t limitPerProgressiveFetch: 500,\n\t\n\t /** @type {String} order used here and when fetching from server */\n\t order: 'hid',\n\t\n\t /** root api url */\n\t urlRoot: Galaxy.root + 'api/histories',\n\t\n\t /** complete api url */\n\t url: function () {\n\t return this.urlRoot + '/' + this.historyId + '/contents';\n\t },\n\t\n\t /** Set up */\n\t initialize: function (models, options) {\n\t options = options || {};\n\t _super.prototype.initialize.call(this, models, options);\n\t\n\t this.history = options.history || null;\n\t this.setHistoryId(options.historyId || null);\n\t /** @type {Boolean} does this collection contain and fetch deleted elements */\n\t this.includeDeleted = options.includeDeleted || this.includeDeleted;\n\t /** @type {Boolean} does this collection contain and fetch non-visible elements */\n\t this.includeHidden = options.includeHidden || this.includeHidden;\n\t\n\t // backbonejs uses collection.model.prototype.idAttribute to determine if a model is *already* in a collection\n\t // and either merged or replaced. In this case, our 'model' is a function so we need to add idAttribute\n\t // manually here - if we don't, contents will not merge but be replaced/swapped.\n\t this.model.prototype.idAttribute = 'type_id';\n\t },\n\t\n\t setHistoryId: function (newId) {\n\t this.historyId = newId;\n\t this._setUpWebStorage();\n\t },\n\t\n\t /** Set up client side storage. Currently PersistanStorage keyed under 'history:' */\n\t _setUpWebStorage: function (initialSettings) {\n\t // TODO: use initialSettings\n\t if (!this.historyId) {\n\t return;\n\t }\n\t this.storage = new HISTORY_PREFS.HistoryPrefs({\n\t id: HISTORY_PREFS.HistoryPrefs.historyStorageKey(this.historyId)\n\t });\n\t this.trigger('new-storage', this.storage, this);\n\t\n\t this.on({\n\t 'include-deleted': function (newVal) {\n\t this.storage.includeDeleted(newVal);\n\t },\n\t 'include-hidden': function (newVal) {\n\t this.storage.includeHidden(newVal);\n\t }\n\t });\n\t\n\t this.includeDeleted = this.storage.includeDeleted() || false;\n\t this.includeHidden = this.storage.includeHidden() || false;\n\t return this;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: _.extend(_.clone(_super.prototype.comparators), {\n\t 'name': BASE_MVC.buildComparator('name', { ascending: true }),\n\t 'name-dsc': BASE_MVC.buildComparator('name', { ascending: false }),\n\t 'hid': BASE_MVC.buildComparator('hid', { ascending: false }),\n\t 'hid-asc': BASE_MVC.buildComparator('hid', { ascending: true })\n\t }),\n\t\n\t /** Get every model in this collection not in a 'ready' state (running). */\n\t running: function () {\n\t return this.filter(function (c) {\n\t return !c.inReadyState();\n\t });\n\t },\n\t\n\t /** return contents that are not ready and not deleted/hidden */\n\t runningAndActive: function () {\n\t return this.filter(function (c) {\n\t return !c.inReadyState() && c.get('visible')\n\t // TODO: deletedOrPurged?\n\t && !c.get('deleted');\n\t });\n\t },\n\t\n\t /** Get the model with the given hid\n\t * @param {Int} hid the hid to search for\n\t * @returns {HistoryDatasetAssociation} the model with the given hid or undefined if not found\n\t */\n\t getByHid: function (hid) {\n\t // note: there *can* be more than one content with a given hid, this finds the first based on order\n\t return this.findWhere({ hid: hid });\n\t },\n\t\n\t /** return true if all contents have details */\n\t haveDetails: function () {\n\t return this.all(function (c) {\n\t return c.hasDetails();\n\t });\n\t },\n\t\n\t // ........................................................................ hidden / deleted\n\t /** return a new contents collection of only hidden items */\n\t hidden: function () {\n\t return this.filter(function (c) {\n\t return c.hidden();\n\t });\n\t },\n\t\n\t /** return a new contents collection of only hidden items */\n\t deleted: function () {\n\t return this.filter(function (c) {\n\t return c.get('deleted');\n\t });\n\t },\n\t\n\t /** return a new contents collection of only hidden items */\n\t visibleAndUndeleted: function () {\n\t return this.filter(function (c) {\n\t return c.get('visible') &&\n\t // TODO: deletedOrPurged?\n\t !c.get('deleted');\n\t });\n\t },\n\t\n\t /** create a setter in order to publish the change */\n\t setIncludeDeleted: function (setting, options) {\n\t if (_.isBoolean(setting) && setting !== this.includeDeleted) {\n\t this.includeDeleted = setting;\n\t if (_.result(options, 'silent')) {\n\t return;\n\t }\n\t this.trigger('include-deleted', setting, this);\n\t }\n\t },\n\t\n\t /** create a setter in order to publish the change */\n\t setIncludeHidden: function (setting, options) {\n\t if (_.isBoolean(setting) && setting !== this.includeHidden) {\n\t this.includeHidden = setting;\n\t options = options || {};\n\t if (_.result(options, 'silent')) {\n\t return;\n\t }\n\t this.trigger('include-hidden', setting, this);\n\t }\n\t },\n\t\n\t // ........................................................................ ajax\n\t // ............ controlled fetch collection\n\t /** override to get expanded ids from sessionStorage and pass to API as details */\n\t fetch: function (options) {\n\t options = options || {};\n\t if (this.historyId && !options.details) {\n\t var prefs = HISTORY_PREFS.HistoryPrefs.get(this.historyId).toJSON();\n\t if (!_.isEmpty(prefs.expandedIds)) {\n\t options.details = _.values(prefs.expandedIds).join(',');\n\t }\n\t }\n\t return _super.prototype.fetch.call(this, options);\n\t },\n\t\n\t // ............. ControlledFetch stuff\n\t /** override to include the API versioning flag */\n\t _buildFetchData: function (options) {\n\t return _.extend(_super.prototype._buildFetchData.call(this, options), {\n\t v: 'dev'\n\t });\n\t },\n\t\n\t /** Extend to include details and version */\n\t _fetchParams: _super.prototype._fetchParams.concat([\n\t // TODO: remove (the need for) both\n\t /** version */\n\t 'v',\n\t /** dataset ids to get full details of */\n\t 'details']),\n\t\n\t /** override to add deleted/hidden filters */\n\t _buildFetchFilters: function (options) {\n\t var superFilters = _super.prototype._buildFetchFilters.call(this, options) || {};\n\t var filters = {};\n\t if (!this.includeDeleted) {\n\t filters.deleted = false;\n\t filters.purged = false;\n\t }\n\t if (!this.includeHidden) {\n\t filters.visible = true;\n\t }\n\t return _.defaults(superFilters, filters);\n\t },\n\t\n\t // ............ paginated collection\n\t getTotalItemCount: function () {\n\t return this.history.contentsShown();\n\t },\n\t\n\t // ............ history contents specific ajax\n\t /** override to filter requested contents to those updated after the Date 'since' */\n\t fetchUpdated: function (since, options) {\n\t if (since) {\n\t options = options || { filters: {} };\n\t options.remove = false;\n\t options.filters = {\n\t 'update_time-ge': since.toISOString(),\n\t // workflows will produce hidden datasets (non-output datasets) that still\n\t // need to be updated in the collection or they'll update forever\n\t // we can remove the default visible filter by using an 'empty' value\n\t visible: ''\n\t };\n\t }\n\t return this.fetch(options);\n\t },\n\t\n\t /** fetch all the deleted==true contents of this collection */\n\t fetchDeleted: function (options) {\n\t options = options || {};\n\t var self = this;\n\t options.filters = _.extend(options.filters, {\n\t // all deleted, purged or not\n\t deleted: true,\n\t purged: undefined\n\t });\n\t options.remove = false;\n\t\n\t self.trigger('fetching-deleted', self);\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-deleted-done', self);\n\t });\n\t },\n\t\n\t /** fetch all the visible==false contents of this collection */\n\t fetchHidden: function (options) {\n\t options = options || {};\n\t var self = this;\n\t options.filters = _.extend(options.filters, {\n\t visible: false\n\t });\n\t options.remove = false;\n\t\n\t self.trigger('fetching-hidden', self);\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-hidden-done', self);\n\t });\n\t },\n\t\n\t /** fetch detailed model data for all contents in this collection */\n\t fetchAllDetails: function (options) {\n\t options = options || {};\n\t var detailsFlag = { details: 'all' };\n\t options.data = _.extend(options.data || {}, detailsFlag);\n\t return this.fetch(options);\n\t },\n\t\n\t /** specialty fetch method for retrieving the element_counts of all hdcas in the history */\n\t fetchCollectionCounts: function (options) {\n\t options = options || {};\n\t options.keys = ['type_id', 'element_count'].join(',');\n\t options.filters = _.extend(options.filters || {}, {\n\t history_content_type: 'dataset_collection'\n\t });\n\t options.remove = false;\n\t return this.fetch(options);\n\t },\n\t\n\t // ............. quasi-batch ops\n\t // TODO: to batch\n\t /** helper that fetches using filterParams then calls save on each fetched using updateWhat as the save params */\n\t _filterAndUpdate: function (filterParams, updateWhat) {\n\t var self = this;\n\t var idAttribute = self.model.prototype.idAttribute;\n\t var updateArgs = [updateWhat];\n\t\n\t return self.fetch({ filters: filterParams, remove: false }).then(function (fetched) {\n\t // convert filtered json array to model array\n\t fetched = fetched.reduce(function (modelArray, currJson, i) {\n\t var model = self.get(currJson[idAttribute]);\n\t return model ? modelArray.concat(model) : modelArray;\n\t }, []);\n\t return self.ajaxQueue('save', updateArgs, fetched);\n\t });\n\t },\n\t\n\t /** using a queue, perform ajaxFn on each of the models in this collection */\n\t ajaxQueue: function (ajaxFn, args, collection) {\n\t collection = collection || this.models;\n\t return new AJAX_QUEUE.AjaxQueue(collection.slice().reverse().map(function (content, i) {\n\t var fn = _.isString(ajaxFn) ? content[ajaxFn] : ajaxFn;\n\t return function () {\n\t return fn.apply(content, args);\n\t };\n\t })).deferred;\n\t },\n\t\n\t /** fetch contents' details in batches of limitPerCall - note: only get searchable details here */\n\t progressivelyFetchDetails: function (options) {\n\t options = options || {};\n\t var deferred = jQuery.Deferred();\n\t var self = this;\n\t var limit = options.limitPerCall || self.limitPerProgressiveFetch;\n\t // TODO: only fetch tags and annotations if specifically requested\n\t var searchAttributes = HDA_MODEL.HistoryDatasetAssociation.prototype.searchAttributes;\n\t var detailKeys = searchAttributes.join(',');\n\t\n\t function _recursivelyFetch(offset) {\n\t offset = offset || 0;\n\t var _options = _.extend(_.clone(options), {\n\t view: 'summary',\n\t keys: detailKeys,\n\t limit: limit,\n\t offset: offset,\n\t reset: offset === 0,\n\t remove: false\n\t });\n\t\n\t _.defer(function () {\n\t self.fetch.call(self, _options).fail(deferred.reject).done(function (response) {\n\t deferred.notify(response, limit, offset);\n\t if (response.length !== limit) {\n\t self.allFetched = true;\n\t deferred.resolve(response, limit, offset);\n\t } else {\n\t _recursivelyFetch(offset + limit);\n\t }\n\t });\n\t });\n\t }\n\t _recursivelyFetch();\n\t return deferred;\n\t },\n\t\n\t /** does some bit of JSON represent something that can be copied into this contents collection */\n\t isCopyable: function (contentsJSON) {\n\t var copyableModelClasses = ['HistoryDatasetAssociation', 'HistoryDatasetCollectionAssociation'];\n\t return _.isObject(contentsJSON) && contentsJSON.id && _.contains(copyableModelClasses, contentsJSON.model_class);\n\t },\n\t\n\t /** copy an existing, accessible hda into this collection */\n\t copy: function (json) {\n\t // TODO: somehow showhorn all this into 'save'\n\t var id, type, contentType;\n\t if (_.isString(json)) {\n\t id = json;\n\t contentType = 'hda';\n\t type = 'dataset';\n\t } else {\n\t id = json.id;\n\t contentType = {\n\t 'HistoryDatasetAssociation': 'hda',\n\t 'LibraryDatasetDatasetAssociation': 'ldda',\n\t 'HistoryDatasetCollectionAssociation': 'hdca'\n\t }[json.model_class] || 'hda';\n\t type = contentType === 'hdca' ? 'dataset_collection' : 'dataset';\n\t }\n\t var collection = this,\n\t xhr = jQuery.ajax(this.url(), {\n\t method: 'POST',\n\t contentType: 'application/json',\n\t data: JSON.stringify({\n\t content: id,\n\t source: contentType,\n\t type: type\n\t })\n\t }).done(function (response) {\n\t collection.add([response], { parse: true });\n\t }).fail(function (error, status, message) {\n\t collection.trigger('error', collection, xhr, {}, 'Error copying contents', { type: type, id: id, source: contentType });\n\t });\n\t return xhr;\n\t },\n\t\n\t /** create a new HDCA in this collection */\n\t createHDCA: function (elementIdentifiers, collectionType, name, hideSourceItems, options) {\n\t // normally collection.create returns the new model, but we need the promise from the ajax, so we fake create\n\t //precondition: elementIdentifiers is an array of plain js objects\n\t // in the proper form to create the collectionType\n\t var hdca = this.model({\n\t history_content_type: 'dataset_collection',\n\t collection_type: collectionType,\n\t history_id: this.historyId,\n\t name: name,\n\t hide_source_items: hideSourceItems || false,\n\t // should probably be able to just send in a bunch of json here and restruct per class\n\t // note: element_identifiers is now (incorrectly) an attribute\n\t element_identifiers: elementIdentifiers\n\t // do not create the model on the client until the ajax returns\n\t });\n\t return hdca.save(options);\n\t },\n\t\n\t // ........................................................................ searching\n\t /** return true if all contents have the searchable attributes */\n\t haveSearchDetails: function () {\n\t return this.allFetched && this.all(function (content) {\n\t // null (which is a valid returned annotation value)\n\t // will return false when using content.has( 'annotation' )\n\t //TODO: a bit hacky - formalize\n\t return _.has(content.attributes, 'annotation');\n\t });\n\t },\n\t\n\t /** return a new collection of contents whose attributes contain the substring matchesWhat */\n\t matches: function (matchesWhat) {\n\t return this.filter(function (content) {\n\t return content.matches(matchesWhat);\n\t });\n\t },\n\t\n\t // ........................................................................ misc\n\t /** In this override, copy the historyId to the clone */\n\t clone: function () {\n\t var clone = Backbone.Collection.prototype.clone.call(this);\n\t clone.historyId = this.historyId;\n\t return clone;\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['HistoryContents(', [this.historyId, this.length].join(), ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryContents: HistoryContents\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(2)))\n\n/***/ },\n/* 62 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, jQuery, _, $) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(61), __webpack_require__(63), __webpack_require__(79), __webpack_require__(4), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_CONTENTS, HISTORY_PREFS, CONTROLLED_FETCH_COLLECTION, UTILS, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /** @class Model for a Galaxy history resource - both a record of user\n\t * tool use and a collection of the datasets those tools produced.\n\t * @name History\n\t * @augments Backbone.Model\n\t */\n\t\n\t var History = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.mixin(BASE_MVC.SearchableModelMixin, /** @lends History.prototype */{\n\t _logNamespace: 'history',\n\t\n\t /** ms between fetches when checking running jobs/datasets for updates */\n\t UPDATE_DELAY: 4000,\n\t\n\t // values from api (may need more)\n\t defaults: {\n\t model_class: 'History',\n\t id: null,\n\t name: 'Unnamed History',\n\t state: 'new',\n\t\n\t deleted: false,\n\t contents_active: {},\n\t contents_states: {}\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/histories',\n\t\n\t contentsClass: HISTORY_CONTENTS.HistoryContents,\n\t\n\t /** What model fields to search with */\n\t searchAttributes: ['name', 'annotation', 'tags'],\n\t\n\t /** Adding title and singular tag */\n\t searchAliases: {\n\t title: 'name',\n\t tag: 'tags'\n\t },\n\t\n\t // ........................................................................ set up/tear down\n\t /** Set up the model\n\t * @param {Object} historyJSON model data for this History\n\t * @param {Object} options any extra settings including logger\n\t */\n\t initialize: function (historyJSON, options) {\n\t options = options || {};\n\t this.logger = options.logger || null;\n\t this.log(this + \".initialize:\", historyJSON, options);\n\t\n\t /** HistoryContents collection of the HDAs contained in this history. */\n\t this.contents = new this.contentsClass([], {\n\t history: this,\n\t historyId: this.get('id'),\n\t order: options.order\n\t });\n\t\n\t this._setUpListeners();\n\t this._setUpCollectionListeners();\n\t\n\t /** cached timeout id for the dataset updater */\n\t this.updateTimeoutId = null;\n\t },\n\t\n\t /** set up any event listeners for this history including those to the contained HDAs\n\t * events: error:contents if an error occurred with the contents collection\n\t */\n\t _setUpListeners: function () {\n\t // if the model's id changes ('current' or null -> an actual id), update the contents history_id\n\t return this.on({\n\t 'error': function (model, xhr, options, msg, details) {\n\t this.clearUpdateTimeout();\n\t },\n\t 'change:id': function (model, newId) {\n\t if (this.contents) {\n\t this.contents.historyId = newId;\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** event handlers for the contents submodels */\n\t _setUpCollectionListeners: function () {\n\t if (!this.contents) {\n\t return this;\n\t }\n\t // bubble up errors\n\t return this.listenTo(this.contents, {\n\t 'error': function () {\n\t this.trigger.apply(this, jQuery.makeArray(arguments));\n\t }\n\t });\n\t },\n\t\n\t // ........................................................................ derived attributes\n\t /** */\n\t contentsShown: function () {\n\t var contentsActive = this.get('contents_active');\n\t var shown = contentsActive.active || 0;\n\t shown += this.contents.includeDeleted ? contentsActive.deleted : 0;\n\t shown += this.contents.includeHidden ? contentsActive.hidden : 0;\n\t return shown;\n\t },\n\t\n\t /** convert size in bytes to a more human readable version */\n\t nice_size: function () {\n\t var size = this.get('size');\n\t return size ? UTILS.bytesToString(size, true, 2) : _l('(empty)');\n\t },\n\t\n\t /** override to add nice_size */\n\t toJSON: function () {\n\t return _.extend(Backbone.Model.prototype.toJSON.call(this), {\n\t nice_size: this.nice_size()\n\t });\n\t },\n\t\n\t /** override to allow getting nice_size */\n\t get: function (key) {\n\t if (key === 'nice_size') {\n\t return this.nice_size();\n\t }\n\t return Backbone.Model.prototype.get.apply(this, arguments);\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** T/F is this history owned by the current user (Galaxy.user)\n\t * Note: that this will return false for an anon user even if the history is theirs.\n\t */\n\t ownedByCurrUser: function () {\n\t // no currUser\n\t if (!Galaxy || !Galaxy.user) {\n\t return false;\n\t }\n\t // user is anon or history isn't owned\n\t if (Galaxy.user.isAnonymous() || Galaxy.user.id !== this.get('user_id')) {\n\t return false;\n\t }\n\t return true;\n\t },\n\t\n\t /** Return the number of running jobs assoc with this history (note: unknown === 0) */\n\t numOfUnfinishedJobs: function () {\n\t var unfinishedJobIds = this.get('non_ready_jobs');\n\t return unfinishedJobIds ? unfinishedJobIds.length : 0;\n\t },\n\t\n\t /** Return the number of running hda/hdcas in this history (note: unknown === 0) */\n\t numOfUnfinishedShownContents: function () {\n\t return this.contents.runningAndActive().length || 0;\n\t },\n\t\n\t // ........................................................................ updates\n\t _fetchContentRelatedAttributes: function () {\n\t var contentRelatedAttrs = ['size', 'non_ready_jobs', 'contents_active', 'hid_counter'];\n\t return this.fetch({ data: $.param({ keys: contentRelatedAttrs.join(',') }) });\n\t },\n\t\n\t /** check for any changes since the last time we updated (or fetch all if ) */\n\t refresh: function (options) {\n\t // console.log( this + '.refresh' );\n\t options = options || {};\n\t var self = this;\n\t\n\t // note if there was no previous update time, all summary contents will be fetched\n\t var lastUpdateTime = self.lastUpdateTime;\n\t // if we don't flip this, then a fully-fetched list will not be re-checked via fetch\n\t this.contents.allFetched = false;\n\t var fetchFn = self.contents.currentPage !== 0 ? function () {\n\t return self.contents.fetchPage(self.contents.currentPage);\n\t } : function () {\n\t return self.contents.fetchUpdated(lastUpdateTime);\n\t };\n\t // note: if there was no previous update time, all summary contents will be fetched\n\t return fetchFn().done(function (response, status, xhr) {\n\t var serverResponseDatetime;\n\t try {\n\t serverResponseDatetime = new Date(xhr.getResponseHeader('Date'));\n\t } catch (err) {}\n\t self.lastUpdateTime = serverResponseDatetime || new Date();\n\t self.checkForUpdates(options);\n\t });\n\t },\n\t\n\t /** continuously fetch updated contents every UPDATE_DELAY ms if this history's datasets or jobs are unfinished */\n\t checkForUpdates: function (options) {\n\t // console.log( this + '.checkForUpdates' );\n\t options = options || {};\n\t var delay = this.UPDATE_DELAY;\n\t var self = this;\n\t if (!self.id) {\n\t return;\n\t }\n\t\n\t function _delayThenUpdate() {\n\t // prevent buildup of updater timeouts by clearing previous if any, then set new and cache id\n\t self.clearUpdateTimeout();\n\t self.updateTimeoutId = setTimeout(function () {\n\t self.refresh(options);\n\t }, delay);\n\t }\n\t\n\t // if there are still datasets in the non-ready state, recurse into this function with the new time\n\t var nonReadyContentCount = this.numOfUnfinishedShownContents();\n\t // console.log( 'nonReadyContentCount:', nonReadyContentCount );\n\t if (nonReadyContentCount > 0) {\n\t _delayThenUpdate();\n\t } else {\n\t // no datasets are running, but currently runnning jobs may still produce new datasets\n\t // see if the history has any running jobs and continue to update if so\n\t // (also update the size for the user in either case)\n\t self._fetchContentRelatedAttributes().done(function (historyData) {\n\t // console.log( 'non_ready_jobs:', historyData.non_ready_jobs );\n\t if (self.numOfUnfinishedJobs() > 0) {\n\t _delayThenUpdate();\n\t } else {\n\t // otherwise, let listeners know that all updates have stopped\n\t self.trigger('ready');\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** clear the timeout and the cached timeout id */\n\t clearUpdateTimeout: function () {\n\t if (this.updateTimeoutId) {\n\t clearTimeout(this.updateTimeoutId);\n\t this.updateTimeoutId = null;\n\t }\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** fetch this histories data (using options) then it's contents (using contentsOptions) */\n\t fetchWithContents: function (options, contentsOptions) {\n\t options = options || {};\n\t var self = this;\n\t\n\t // console.log( this + '.fetchWithContents' );\n\t // TODO: push down to a base class\n\t options.view = 'dev-detailed';\n\t\n\t // fetch history then use history data to fetch (paginated) contents\n\t return this.fetch(options).then(function getContents(history) {\n\t self.contents.history = self;\n\t self.contents.setHistoryId(history.id);\n\t return self.fetchContents(contentsOptions);\n\t });\n\t },\n\t\n\t /** fetch this histories contents, adjusting options based on the stored history preferences */\n\t fetchContents: function (options) {\n\t options = options || {};\n\t var self = this;\n\t\n\t // we're updating, reset the update time\n\t self.lastUpdateTime = new Date();\n\t return self.contents.fetchCurrentPage(options);\n\t },\n\t\n\t /** save this history, _Mark_ing it as deleted (just a flag) */\n\t _delete: function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** purge this history, _Mark_ing it as purged and removing all dataset data from the server */\n\t purge: function (options) {\n\t if (this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true, purged: true }, options);\n\t },\n\t /** save this history, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** Make a copy of this history on the server\n\t * @param {Boolean} current if true, set the copy as the new current history (default: true)\n\t * @param {String} name name of new history (default: none - server sets to: Copy of )\n\t * @fires copied passed this history and the response JSON from the copy\n\t * @returns {xhr}\n\t */\n\t copy: function (current, name, allDatasets) {\n\t current = current !== undefined ? current : true;\n\t if (!this.id) {\n\t throw new Error('You must set the history ID before copying it.');\n\t }\n\t\n\t var postData = { history_id: this.id };\n\t if (current) {\n\t postData.current = true;\n\t }\n\t if (name) {\n\t postData.name = name;\n\t }\n\t if (!allDatasets) {\n\t postData.all_datasets = false;\n\t }\n\t postData.view = 'dev-detailed';\n\t\n\t var history = this;\n\t var copy = jQuery.post(this.urlRoot, postData);\n\t // if current - queue to setAsCurrent before firing 'copied'\n\t if (current) {\n\t return copy.then(function (response) {\n\t var newHistory = new History(response);\n\t return newHistory.setAsCurrent().done(function () {\n\t history.trigger('copied', history, response);\n\t });\n\t });\n\t }\n\t return copy.done(function (response) {\n\t history.trigger('copied', history, response);\n\t });\n\t },\n\t\n\t setAsCurrent: function () {\n\t var history = this,\n\t xhr = jQuery.getJSON(Galaxy.root + 'history/set_as_current?id=' + this.id);\n\t\n\t xhr.done(function () {\n\t history.trigger('set-as-current', history);\n\t });\n\t return xhr;\n\t },\n\t\n\t // ........................................................................ misc\n\t toString: function () {\n\t return 'History(' + this.get('id') + ',' + this.get('name') + ')';\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t var _collectionSuper = CONTROLLED_FETCH_COLLECTION.InfinitelyScrollingCollection;\n\t /** @class A collection of histories (per user)\n\t * that maintains the current history as the first in the collection.\n\t * New or copied histories become the current history.\n\t */\n\t var HistoryCollection = _collectionSuper.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: 'history',\n\t\n\t model: History,\n\t /** @type {String} initial order used by collection */\n\t order: 'update_time',\n\t /** @type {Number} limit used for the first fetch (or a reset) */\n\t limitOnFirstFetch: 10,\n\t /** @type {Number} limit used for each subsequent fetch */\n\t limitPerFetch: 10,\n\t\n\t initialize: function (models, options) {\n\t options = options || {};\n\t this.log('HistoryCollection.initialize', models, options);\n\t _collectionSuper.prototype.initialize.call(this, models, options);\n\t\n\t /** @type {boolean} should deleted histories be included */\n\t this.includeDeleted = options.includeDeleted || false;\n\t\n\t /** @type {String} encoded id of the history that's current */\n\t this.currentHistoryId = options.currentHistoryId;\n\t\n\t this.setUpListeners();\n\t // note: models are sent to reset *after* this fn ends; up to this point\n\t // the collection *is empty*\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/histories',\n\t url: function () {\n\t return this.urlRoot;\n\t },\n\t\n\t /** set up reflexive event handlers */\n\t setUpListeners: function setUpListeners() {\n\t return this.on({\n\t // when a history is deleted, remove it from the collection (if optionally set to do so)\n\t 'change:deleted': function (history) {\n\t // TODO: this becomes complicated when more filters are used\n\t this.debug('change:deleted', this.includeDeleted, history.get('deleted'));\n\t if (!this.includeDeleted && history.get('deleted')) {\n\t this.remove(history);\n\t }\n\t },\n\t // listen for a history copy, setting it to current\n\t 'copied': function (original, newData) {\n\t this.setCurrent(new History(newData, []));\n\t },\n\t // when a history is made current, track the id in the collection\n\t 'set-as-current': function (history) {\n\t var oldCurrentId = this.currentHistoryId;\n\t this.trigger('no-longer-current', oldCurrentId);\n\t this.currentHistoryId = history.id;\n\t }\n\t });\n\t },\n\t\n\t /** override to change view */\n\t _buildFetchData: function (options) {\n\t return _.extend(_collectionSuper.prototype._buildFetchData.call(this, options), {\n\t view: 'dev-detailed'\n\t });\n\t },\n\t\n\t /** override to filter out deleted and purged */\n\t _buildFetchFilters: function (options) {\n\t var superFilters = _collectionSuper.prototype._buildFetchFilters.call(this, options) || {};\n\t var filters = {};\n\t if (!this.includeDeleted) {\n\t filters.deleted = false;\n\t filters.purged = false;\n\t } else {\n\t // force API to return both deleted and non\n\t //TODO: when the API is updated, remove this\n\t filters.deleted = null;\n\t }\n\t return _.defaults(superFilters, filters);\n\t },\n\t\n\t /** override to fetch current as well (as it may be outside the first 10, etc.) */\n\t fetchFirst: function (options) {\n\t var self = this;\n\t // TODO: batch?\n\t var xhr = $.when();\n\t if (this.currentHistoryId) {\n\t xhr = _collectionSuper.prototype.fetchFirst.call(self, {\n\t silent: true,\n\t limit: 1,\n\t filters: {\n\t // without these a deleted current history will return [] here and block the other xhr\n\t 'purged': '',\n\t 'deleted': '',\n\t 'encoded_id-in': this.currentHistoryId\n\t }\n\t });\n\t }\n\t return xhr.then(function () {\n\t options = options || {};\n\t options.offset = 0;\n\t return self.fetchMore(options);\n\t });\n\t },\n\t\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: _.extend(_.clone(_collectionSuper.prototype.comparators), {\n\t 'name': BASE_MVC.buildComparator('name', { ascending: true }),\n\t 'name-dsc': BASE_MVC.buildComparator('name', { ascending: false }),\n\t 'size': BASE_MVC.buildComparator('size', { ascending: false }),\n\t 'size-asc': BASE_MVC.buildComparator('size', { ascending: true })\n\t }),\n\t\n\t /** override to always have the current history first */\n\t sort: function (options) {\n\t options = options || {};\n\t var silent = options.silent;\n\t var currentHistory = this.remove(this.get(this.currentHistoryId));\n\t _collectionSuper.prototype.sort.call(this, _.defaults({ silent: true }, options));\n\t this.unshift(currentHistory, { silent: true });\n\t if (!silent) {\n\t this.trigger('sort', this, options);\n\t }\n\t return this;\n\t },\n\t\n\t /** create a new history and by default set it to be the current history */\n\t create: function create(data, hdas, historyOptions, xhrOptions) {\n\t //TODO: .create is actually a collection function that's overridden here\n\t var collection = this,\n\t xhr = jQuery.getJSON(Galaxy.root + 'history/create_new_current');\n\t return xhr.done(function (newData) {\n\t collection.setCurrent(new History(newData, [], historyOptions || {}));\n\t });\n\t },\n\t\n\t /** set the current history to the given history, placing it first in the collection.\n\t * Pass standard bbone options for use in unshift.\n\t * @triggers new-current passed history and this collection\n\t */\n\t setCurrent: function (history, options) {\n\t options = options || {};\n\t // new histories go in the front\n\t this.unshift(history, options);\n\t this.currentHistoryId = history.get('id');\n\t if (!options.silent) {\n\t this.trigger('new-current', history, this);\n\t }\n\t return this;\n\t },\n\t\n\t toString: function toString() {\n\t return 'HistoryCollection(' + this.length + ',current:' + this.currentHistoryId + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t History: History,\n\t HistoryCollection: HistoryCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 63 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7)], __WEBPACK_AMD_DEFINE_RESULT__ = function (BASE_MVC) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'history';\n\t\n\t // ============================================================================\n\t /** session storage for individual history preferences */\n\t var HistoryPrefs = BASE_MVC.SessionStorageModel.extend(\n\t /** @lends HistoryPrefs.prototype */{\n\t //TODO:?? move to user prefs?\n\t defaults: {\n\t //TODO:?? expandedIds to array?\n\t expandedIds: {},\n\t show_deleted: false,\n\t show_hidden: false\n\t },\n\t\n\t /** add an hda id to the hash of expanded hdas */\n\t addExpanded: function (model) {\n\t //TODO: use type_id and not model\n\t var current = this.get('expandedIds');\n\t current[model.id] = model.get('id');\n\t this.save('expandedIds', current);\n\t },\n\t\n\t /** remove an hda id from the hash of expanded hdas */\n\t removeExpanded: function (model) {\n\t var current = this.get('expandedIds');\n\t delete current[model.id];\n\t this.save('expandedIds', current);\n\t },\n\t\n\t isExpanded: function (contentId) {\n\t return _.result(this.get('expandedIds'), contentId, false);\n\t },\n\t\n\t allExpanded: function () {\n\t return _.values(this.get('expandedIds'));\n\t },\n\t\n\t clearExpanded: function () {\n\t this.set('expandedIds', {});\n\t },\n\t\n\t includeDeleted: function (val) {\n\t // moving the invocation here so other components don't need to know the key\n\t // TODO: change this key later\n\t if (!_.isUndefined(val)) {\n\t this.set('show_deleted', val);\n\t }\n\t return this.get('show_deleted');\n\t },\n\t\n\t includeHidden: function (val) {\n\t // TODO: change this key later\n\t if (!_.isUndefined(val)) {\n\t this.set('show_hidden', val);\n\t }\n\t return this.get('show_hidden');\n\t },\n\t\n\t toString: function () {\n\t return 'HistoryPrefs(' + this.id + ')';\n\t }\n\t\n\t }, {\n\t // ........................................................................ class vars\n\t // class lvl for access w/o instantiation\n\t storageKeyPrefix: 'history:',\n\t\n\t /** key string to store each histories settings under */\n\t historyStorageKey: function historyStorageKey(historyId) {\n\t if (!historyId) {\n\t throw new Error('HistoryPrefs.historyStorageKey needs valid id: ' + historyId);\n\t }\n\t // single point of change\n\t return HistoryPrefs.storageKeyPrefix + historyId;\n\t },\n\t\n\t /** return the existing storage for the history with the given id (or create one if it doesn't exist) */\n\t get: function get(historyId) {\n\t return new HistoryPrefs({ id: HistoryPrefs.historyStorageKey(historyId) });\n\t },\n\t\n\t /** clear all history related items in sessionStorage */\n\t clearAll: function clearAll(historyId) {\n\t for (var key in sessionStorage) {\n\t if (key.indexOf(HistoryPrefs.storageKeyPrefix) === 0) {\n\t sessionStorage.removeItem(key);\n\t }\n\t }\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HistoryPrefs: HistoryPrefs\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 64 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'list';\n\t //==============================================================================\n\t /** A view which, when first rendered, shows only summary data/attributes, but\n\t * can be expanded to show further details (and optionally fetch those\n\t * details from the server).\n\t */\n\t var ExpandableView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: Although the reasoning behind them is different, this shares a lot with HiddenUntilActivated above: combine them\n\t //PRECONDITION: model must have method hasDetails\n\t //PRECONDITION: subclasses must have templates.el and templates.details\n\t\n\t initialize: function (attributes) {\n\t /** are the details of this view expanded/shown or not? */\n\t this.expanded = attributes.expanded || false;\n\t this.log('\\t expanded:', this.expanded);\n\t this.fxSpeed = attributes.fxSpeed !== undefined ? attributes.fxSpeed : this.fxSpeed;\n\t },\n\t\n\t // ........................................................................ render main\n\t /** jq fx speed */\n\t fxSpeed: 'fast',\n\t\n\t /** Render this content, set up ui.\n\t * @param {Number or String} speed the speed of the render\n\t */\n\t render: function (speed) {\n\t var $newRender = this._buildNewRender();\n\t this._setUpBehaviors($newRender);\n\t this._queueNewRender($newRender, speed);\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el.\n\t * If the view is already expanded, build the details as well.\n\t */\n\t _buildNewRender: function () {\n\t // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n\t var $newRender = $(this.templates.el(this.model.toJSON(), this));\n\t if (this.expanded) {\n\t this.$details($newRender).replaceWith(this._renderDetails().show());\n\t }\n\t return $newRender;\n\t },\n\t\n\t /** Fade out the old el, swap in the new contents, then fade in.\n\t * @param {Number or String} speed jq speed to use for rendering effects\n\t * @fires rendered when rendered\n\t */\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var view = this;\n\t\n\t if (speed === 0) {\n\t view._swapNewRender($newRender);\n\t view.trigger('rendered', view);\n\t } else {\n\t $(view).queue('fx', [function (next) {\n\t view.$el.fadeOut(speed, next);\n\t }, function (next) {\n\t view._swapNewRender($newRender);\n\t next();\n\t }, function (next) {\n\t view.$el.fadeIn(speed, next);\n\t }, function (next) {\n\t view.trigger('rendered', view);\n\t next();\n\t }]);\n\t }\n\t },\n\t\n\t /** empty out the current el, move the $newRender's children in */\n\t _swapNewRender: function ($newRender) {\n\t return this.$el.empty().attr('class', _.isFunction(this.className) ? this.className() : this.className).append($newRender.children());\n\t },\n\t\n\t /** set up js behaviors, event handlers for elements within the given container\n\t * @param {jQuery} $container jq object that contains the elements to process (defaults to this.$el)\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t // set up canned behavior on children (bootstrap, popupmenus, editable_text, etc.)\n\t //make_popup_menus( $where );\n\t $where.find('[title]').tooltip({ placement: 'bottom' });\n\t },\n\t\n\t // ......................................................................... details\n\t /** shortcut to details DOM (as jQ) */\n\t $details: function ($where) {\n\t $where = $where || this.$el;\n\t return $where.find('> .details');\n\t },\n\t\n\t /** build the DOM for the details and set up behaviors on it */\n\t _renderDetails: function () {\n\t var $newDetails = $(this.templates.details(this.model.toJSON(), this));\n\t this._setUpBehaviors($newDetails);\n\t return $newDetails;\n\t },\n\t\n\t // ......................................................................... expansion/details\n\t /** Show or hide the details\n\t * @param {Boolean} expand if true, expand; if false, collapse\n\t */\n\t toggleExpanded: function (expand) {\n\t expand = expand === undefined ? !this.expanded : expand;\n\t if (expand) {\n\t this.expand();\n\t } else {\n\t this.collapse();\n\t }\n\t return this;\n\t },\n\t\n\t /** Render and show the full, detailed body of this view including extra data and controls.\n\t * note: if the model does not have detailed data, fetch that data before showing the body\n\t * @fires expanded when a body has been expanded\n\t */\n\t expand: function () {\n\t var view = this;\n\t return view._fetchModelDetails().always(function () {\n\t view._expand();\n\t });\n\t },\n\t\n\t /** Check for model details and, if none, fetch them.\n\t * @returns {jQuery.promise} the model.fetch.xhr if details are being fetched, an empty promise if not\n\t */\n\t _fetchModelDetails: function () {\n\t if (!this.model.hasDetails()) {\n\t return this.model.fetch();\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Inner fn called when expand (public) has fetched the details */\n\t _expand: function () {\n\t var view = this,\n\t $newDetails = view._renderDetails();\n\t view.$details().replaceWith($newDetails);\n\t // needs to be set after the above or the slide will not show\n\t view.expanded = true;\n\t view.$details().slideDown(view.fxSpeed, function () {\n\t view.trigger('expanded', view);\n\t });\n\t },\n\t\n\t /** Hide the body/details of an HDA.\n\t * @fires collapsed when a body has been collapsed\n\t */\n\t collapse: function () {\n\t this.debug(this + '(ExpandableView).collapse');\n\t var view = this;\n\t view.expanded = false;\n\t this.$details().slideUp(view.fxSpeed, function () {\n\t view.trigger('collapsed', view);\n\t });\n\t }\n\t\n\t });\n\t\n\t //==============================================================================\n\t /** A view that is displayed in some larger list/grid/collection.\n\t * Inherits from Expandable, Selectable, Draggable.\n\t * The DOM contains warnings, a title bar, and a series of primary action controls.\n\t * Primary actions are meant to be easily accessible item functions (such as delete)\n\t * that are rendered in the title bar.\n\t *\n\t * Details are rendered when the user clicks the title bar or presses enter/space when\n\t * the title bar is in focus.\n\t *\n\t * Designed as a base class for history panel contents - but usable elsewhere (I hope).\n\t */\n\t var ListItemView = ExpandableView.extend(BASE_MVC.mixin(BASE_MVC.SelectableViewMixin, BASE_MVC.DraggableViewMixin, {\n\t\n\t tagName: 'div',\n\t className: 'list-item',\n\t\n\t /** Set up the base class and all mixins */\n\t initialize: function (attributes) {\n\t ExpandableView.prototype.initialize.call(this, attributes);\n\t BASE_MVC.SelectableViewMixin.initialize.call(this, attributes);\n\t BASE_MVC.DraggableViewMixin.initialize.call(this, attributes);\n\t this._setUpListeners();\n\t },\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t // hide the primary actions in the title bar when selectable and narrow\n\t this.on('selectable', function (isSelectable) {\n\t if (isSelectable) {\n\t this.$('.primary-actions').hide();\n\t } else {\n\t this.$('.primary-actions').show();\n\t }\n\t }, this);\n\t return this;\n\t },\n\t\n\t // ........................................................................ rendering\n\t /** In this override, call methods to build warnings, titlebar and primary actions */\n\t _buildNewRender: function () {\n\t var $newRender = ExpandableView.prototype._buildNewRender.call(this);\n\t $newRender.children('.warnings').replaceWith(this._renderWarnings());\n\t $newRender.children('.title-bar').replaceWith(this._renderTitleBar());\n\t $newRender.children('.primary-actions').append(this._renderPrimaryActions());\n\t $newRender.find('> .title-bar .subtitle').replaceWith(this._renderSubtitle());\n\t return $newRender;\n\t },\n\t\n\t /** In this override, render the selector controls and set up dragging before the swap */\n\t _swapNewRender: function ($newRender) {\n\t ExpandableView.prototype._swapNewRender.call(this, $newRender);\n\t if (this.selectable) {\n\t this.showSelector(0);\n\t }\n\t if (this.draggable) {\n\t this.draggableOn();\n\t }\n\t return this.$el;\n\t },\n\t\n\t /** Render any warnings the item may need to show (e.g. \"I'm deleted\") */\n\t _renderWarnings: function () {\n\t var view = this,\n\t $warnings = $('
                                  '),\n\t json = view.model.toJSON();\n\t //TODO:! unordered (map)\n\t _.each(view.templates.warnings, function (templateFn) {\n\t $warnings.append($(templateFn(json, view)));\n\t });\n\t return $warnings;\n\t },\n\t\n\t /** Render the title bar (the main/exposed SUMMARY dom element) */\n\t _renderTitleBar: function () {\n\t return $(this.templates.titleBar(this.model.toJSON(), this));\n\t },\n\t\n\t /** Return an array of jQ objects containing common/easily-accessible item controls */\n\t _renderPrimaryActions: function () {\n\t // override this\n\t return [];\n\t },\n\t\n\t /** Render the title bar (the main/exposed SUMMARY dom element) */\n\t _renderSubtitle: function () {\n\t return $(this.templates.subtitle(this.model.toJSON(), this));\n\t },\n\t\n\t // ......................................................................... events\n\t /** event map */\n\t events: {\n\t // expand the body when the title is clicked or when in focus and space or enter is pressed\n\t 'click .title-bar': '_clickTitleBar',\n\t 'keydown .title-bar': '_keyDownTitleBar',\n\t 'click .selector': 'toggleSelect'\n\t },\n\t\n\t /** expand when the title bar is clicked */\n\t _clickTitleBar: function (event) {\n\t event.stopPropagation();\n\t if (event.altKey) {\n\t this.toggleSelect(event);\n\t if (!this.selectable) {\n\t this.showSelector();\n\t }\n\t } else {\n\t this.toggleExpanded();\n\t }\n\t },\n\t\n\t /** expand when the title bar is in focus and enter or space is pressed */\n\t _keyDownTitleBar: function (event) {\n\t // bail (with propagation) if keydown and not space or enter\n\t var KEYCODE_SPACE = 32,\n\t KEYCODE_RETURN = 13;\n\t if (event && event.type === 'keydown' && (event.keyCode === KEYCODE_SPACE || event.keyCode === KEYCODE_RETURN)) {\n\t this.toggleExpanded();\n\t event.stopPropagation();\n\t return false;\n\t }\n\t return true;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'ListItemView(' + modelString + ')';\n\t }\n\t }));\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ListItemView.prototype.templates = function () {\n\t\n\t var elTemplato = BASE_MVC.wrapTemplate(['
                                  ',\n\t // errors, messages, etc.\n\t '
                                  ',\n\t\n\t // multi-select checkbox\n\t '
                                  ', '', '
                                  ',\n\t // space for title bar buttons - gen. floated to the right\n\t '
                                  ', '
                                  ',\n\t\n\t // expandable area for more details\n\t '
                                  ', '
                                  ']);\n\t\n\t var warnings = {};\n\t\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding a tabindex here allows focusing the title bar and the use of keydown to expand the dataset display\n\t '
                                  ',\n\t //TODO: prob. belongs in dataset-list-item\n\t '', '
                                  ', '<%- element.name %>', '
                                  ', '
                                  ', '
                                  '], 'element');\n\t\n\t var subtitleTemplate = BASE_MVC.wrapTemplate([\n\t // override this\n\t '
                                  ']);\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate([\n\t // override this\n\t '
                                  ']);\n\t\n\t return {\n\t el: elTemplato,\n\t warnings: warnings,\n\t titleBar: titleBarTemplate,\n\t subtitle: subtitleTemplate,\n\t details: detailsTemplate\n\t };\n\t }();\n\t\n\t //==============================================================================\n\t /** A view that is displayed in some larger list/grid/collection.\n\t * *AND* can display some sub-list of it's own when expanded (e.g. dataset collections).\n\t * This list will 'foldout' when the item is expanded depending on this.foldoutStyle:\n\t * If 'foldout': will expand vertically to show the nested list\n\t * If 'drilldown': will overlay the parent list\n\t *\n\t * Inherits from ListItemView.\n\t *\n\t * _renderDetails does the work of creating this.details: a sub-view that shows the nested list\n\t */\n\t var FoldoutListItemView = ListItemView.extend({\n\t\n\t /** If 'foldout': show the sub-panel inside the expanded item\n\t * If 'drilldown': only fire events and handle by pub-sub\n\t * (allow the panel containing this item to attach it, hide itself, etc.)\n\t */\n\t foldoutStyle: 'foldout',\n\t /** Panel view class to instantiate for the sub-panel */\n\t foldoutPanelClass: null,\n\t\n\t /** override to:\n\t * add attributes foldoutStyle and foldoutPanelClass for config poly\n\t * disrespect attributes.expanded if drilldown\n\t */\n\t initialize: function (attributes) {\n\t if (this.foldoutStyle === 'drilldown') {\n\t this.expanded = false;\n\t }\n\t this.foldoutStyle = attributes.foldoutStyle || this.foldoutStyle;\n\t this.foldoutPanelClass = attributes.foldoutPanelClass || this.foldoutPanelClass;\n\t\n\t ListItemView.prototype.initialize.call(this, attributes);\n\t this.foldout = this._createFoldoutPanel();\n\t },\n\t\n\t /** in this override, attach the foldout panel when rendering details */\n\t _renderDetails: function () {\n\t if (this.foldoutStyle === 'drilldown') {\n\t return $();\n\t }\n\t var $newDetails = ListItemView.prototype._renderDetails.call(this);\n\t return this._attachFoldout(this.foldout, $newDetails);\n\t },\n\t\n\t /** In this override, handle collection expansion. */\n\t _createFoldoutPanel: function () {\n\t var model = this.model;\n\t var FoldoutClass = this._getFoldoutPanelClass(model),\n\t options = this._getFoldoutPanelOptions(model),\n\t foldout = new FoldoutClass(_.extend(options, {\n\t model: model\n\t }));\n\t return foldout;\n\t },\n\t\n\t /** Stub to return proper foldout panel class */\n\t _getFoldoutPanelClass: function () {\n\t // override\n\t return this.foldoutPanelClass;\n\t },\n\t\n\t /** Stub to return proper foldout panel options */\n\t _getFoldoutPanelOptions: function () {\n\t return {\n\t // propagate foldout style down\n\t foldoutStyle: this.foldoutStyle,\n\t fxSpeed: this.fxSpeed\n\t };\n\t },\n\t\n\t /** Render the foldout panel inside the view, hiding controls */\n\t _attachFoldout: function (foldout, $whereTo) {\n\t $whereTo = $whereTo || this.$('> .details');\n\t this.foldout = foldout.render(0);\n\t foldout.$('> .controls').hide();\n\t return $whereTo.append(foldout.$el);\n\t },\n\t\n\t /** In this override, branch on foldoutStyle to show expanded */\n\t expand: function () {\n\t var view = this;\n\t return view._fetchModelDetails().always(function () {\n\t if (view.foldoutStyle === 'foldout') {\n\t view._expand();\n\t } else if (view.foldoutStyle === 'drilldown') {\n\t view._expandByDrilldown();\n\t }\n\t });\n\t },\n\t\n\t /** For drilldown, set up close handler and fire expanded:drilldown\n\t * containing views can listen to this and handle other things\n\t * (like hiding themselves) by listening for expanded/collapsed:drilldown\n\t */\n\t _expandByDrilldown: function () {\n\t var view = this;\n\t // attachment and rendering done by listener\n\t view.listenTo(view.foldout, 'close', function () {\n\t view.trigger('collapsed:drilldown', view, view.foldout);\n\t });\n\t view.trigger('expanded:drilldown', view, view.foldout);\n\t }\n\t\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t FoldoutListItemView.prototype.templates = function () {\n\t\n\t var detailsTemplate = BASE_MVC.wrapTemplate(['
                                  ',\n\t // override with more info (that goes above the panel)\n\t '
                                  '], 'collection');\n\t\n\t return _.extend({}, ListItemView.prototype.templates, {\n\t details: detailsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t ExpandableView: ExpandableView,\n\t ListItemView: ListItemView,\n\t FoldoutListItemView: FoldoutListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 65 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (baseMVC, _l) {\n\t // =============================================================================\n\t /** A view on any model that has a 'tags' attribute (a list of tag strings)\n\t * Incorporates the select2 jQuery plugin for tags display/editing:\n\t * http://ivaynberg.github.io/select2/\n\t */\n\t var TagsEditor = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseMVC.HiddenUntilActivatedViewMixin).extend({\n\t\n\t tagName: 'div',\n\t className: 'tags-display',\n\t\n\t /** Set up listeners, parse options */\n\t initialize: function (options) {\n\t //console.debug( this, options );\n\t // only listen to the model only for changes to tags - re-render\n\t if (options.usePrompt === false) {\n\t this.label = '';\n\t } else {\n\t this.label = '';\n\t }\n\t this.hiddenUntilActivated(options.$activator, options);\n\t },\n\t\n\t /** Build the DOM elements, call select to on the created input, and set up behaviors */\n\t render: function () {\n\t var self = this;\n\t this.$el.html(this._template());\n\t\n\t this.$input().select2({\n\t placeholder: 'Add tags',\n\t width: '100%',\n\t tags: function () {\n\t // initialize possible tags in the dropdown based on all the tags the user has used so far\n\t return self._getTagsUsed();\n\t }\n\t });\n\t\n\t this._setUpBehaviors();\n\t return this;\n\t },\n\t\n\t _hashToName: function (tag) {\n\t if (tag.startsWith('#')) {\n\t return 'name:' + tag.slice(1);\n\t }\n\t return tag;\n\t },\n\t\n\t _nameToHash: function (tag) {\n\t if (tag.startsWith('name:')) {\n\t tag = '#' + tag.slice(5);\n\t }\n\t return tag;\n\t },\n\t\n\t /** @returns {String} the html text used to build the view's DOM */\n\t _template: function () {\n\t return [this.label,\n\t // set up initial tags by adding as CSV to input vals (necc. to init select2)\n\t ''].join('');\n\t },\n\t\n\t /** @returns {String} the sorted, comma-separated tags from the model */\n\t tagsToCSV: function () {\n\t var self = this;\n\t var tagsArray = this.model.get('tags');\n\t if (!_.isArray(tagsArray) || _.isEmpty(tagsArray)) {\n\t return '';\n\t }\n\t return tagsArray.map(function (tag) {\n\t return _.escape(self._nameToHash(tag));\n\t }).sort().join(',');\n\t },\n\t\n\t /** @returns {jQuery} the input for this view */\n\t $input: function () {\n\t return this.$el.find('input.tags-input');\n\t },\n\t\n\t /** @returns {String[]} all tags used by the current user */\n\t _getTagsUsed: function () {\n\t //TODO: global\n\t var self = this;\n\t return _.map(Galaxy.user.get('tags_used'), self._nameToHash);\n\t },\n\t\n\t /** set up any event listeners on the view's DOM (mostly handled by select2) */\n\t _setUpBehaviors: function () {\n\t var self = this;\n\t this.$input().on('change', function (event) {\n\t // Modify any 'hashtag' 'nametags'\n\t event.val = _.map(event.val, self._hashToName);\n\t // save the model's tags in either remove or added event\n\t self.model.save({ tags: event.val });\n\t // if it's new, add the tag to the users tags\n\t if (event.added) {\n\t //??: solve weird behavior in FF on test.galaxyproject.org where\n\t // event.added.text is string object: 'String{ 0=\"o\", 1=\"n\", 2=\"e\" }'\n\t self._addNewTagToTagsUsed(event.added.text + '');\n\t }\n\t });\n\t },\n\t\n\t /** add a new tag (if not already there) to the list of all tags used by the user\n\t * @param {String} newTag the tag to add to the list of used\n\t */\n\t _addNewTagToTagsUsed: function (newTag) {\n\t //TODO: global\n\t var tagsUsed = Galaxy.user.get('tags_used');\n\t if (!_.contains(tagsUsed, newTag)) {\n\t tagsUsed.push(newTag);\n\t tagsUsed.sort();\n\t Galaxy.user.set('tags_used', tagsUsed);\n\t }\n\t },\n\t\n\t /** shut down event listeners and remove this view's DOM */\n\t remove: function () {\n\t this.$input.off();\n\t this.stopListening(this.model);\n\t Backbone.View.prototype.remove.call(this);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return ['TagsEditor(', this.model + '', ')'].join('');\n\t }\n\t });\n\t\n\t // =============================================================================\n\t return {\n\t TagsEditor: TagsEditor\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 66 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {/**\n\t * Model, view, and controller objects for Galaxy tools and tool panel.\n\t */\n\t\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(27), __webpack_require__(16), __webpack_require__(44)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, util, data, ToolForm) {\n\t 'use strict';\n\t\n\t /**\n\t * Mixin for tracking model visibility.\n\t */\n\t\n\t var VisibilityMixin = {\n\t hidden: false,\n\t\n\t show: function () {\n\t this.set(\"hidden\", false);\n\t },\n\t\n\t hide: function () {\n\t this.set(\"hidden\", true);\n\t },\n\t\n\t toggle: function () {\n\t this.set(\"hidden\", !this.get(\"hidden\"));\n\t },\n\t\n\t is_visible: function () {\n\t return !this.attributes.hidden;\n\t }\n\t\n\t };\n\t\n\t /**\n\t * A tool parameter.\n\t */\n\t var ToolParameter = Backbone.Model.extend({\n\t defaults: {\n\t name: null,\n\t label: null,\n\t type: null,\n\t value: null,\n\t html: null,\n\t num_samples: 5\n\t },\n\t\n\t initialize: function (options) {\n\t this.attributes.html = unescape(this.attributes.html);\n\t },\n\t\n\t copy: function () {\n\t return new ToolParameter(this.toJSON());\n\t },\n\t\n\t set_value: function (value) {\n\t this.set('value', value || '');\n\t }\n\t });\n\t\n\t var ToolParameterCollection = Backbone.Collection.extend({\n\t model: ToolParameter\n\t });\n\t\n\t /**\n\t * A data tool parameter.\n\t */\n\t var DataToolParameter = ToolParameter.extend({});\n\t\n\t /**\n\t * An integer tool parameter.\n\t */\n\t var IntegerToolParameter = ToolParameter.extend({\n\t set_value: function (value) {\n\t this.set('value', parseInt(value, 10));\n\t },\n\t\n\t /**\n\t * Returns samples from a tool input.\n\t */\n\t get_samples: function () {\n\t return d3.scale.linear().domain([this.get('min'), this.get('max')]).ticks(this.get('num_samples'));\n\t }\n\t });\n\t\n\t var FloatToolParameter = IntegerToolParameter.extend({\n\t set_value: function (value) {\n\t this.set('value', parseFloat(value));\n\t }\n\t });\n\t\n\t /**\n\t * A select tool parameter.\n\t */\n\t var SelectToolParameter = ToolParameter.extend({\n\t /**\n\t * Returns tool options.\n\t */\n\t get_samples: function () {\n\t return _.map(this.get('options'), function (option) {\n\t return option[0];\n\t });\n\t }\n\t });\n\t\n\t // Set up dictionary of parameter types.\n\t ToolParameter.subModelTypes = {\n\t 'integer': IntegerToolParameter,\n\t 'float': FloatToolParameter,\n\t 'data': DataToolParameter,\n\t 'select': SelectToolParameter\n\t };\n\t\n\t /**\n\t * A Galaxy tool.\n\t */\n\t var Tool = Backbone.Model.extend({\n\t // Default attributes.\n\t defaults: {\n\t id: null,\n\t name: null,\n\t description: null,\n\t target: null,\n\t inputs: [],\n\t outputs: []\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/tools',\n\t\n\t initialize: function (options) {\n\t\n\t // Set parameters.\n\t this.set('inputs', new ToolParameterCollection(_.map(options.inputs, function (p) {\n\t var p_class = ToolParameter.subModelTypes[p.type] || ToolParameter;\n\t return new p_class(p);\n\t })));\n\t },\n\t\n\t /**\n\t *\n\t */\n\t toJSON: function () {\n\t var rval = Backbone.Model.prototype.toJSON.call(this);\n\t\n\t // Convert inputs to JSON manually.\n\t rval.inputs = this.get('inputs').map(function (i) {\n\t return i.toJSON();\n\t });\n\t return rval;\n\t },\n\t\n\t /**\n\t * Removes inputs of a particular type; this is useful because not all inputs can be handled by\n\t * client and server yet.\n\t */\n\t remove_inputs: function (types) {\n\t var tool = this,\n\t incompatible_inputs = tool.get('inputs').filter(function (input) {\n\t return types.indexOf(input.get('type')) !== -1;\n\t });\n\t tool.get('inputs').remove(incompatible_inputs);\n\t },\n\t\n\t /**\n\t * Returns object copy, optionally including only inputs that can be sampled.\n\t */\n\t copy: function (only_samplable_inputs) {\n\t var copy = new Tool(this.toJSON());\n\t\n\t // Return only samplable inputs if flag is set.\n\t if (only_samplable_inputs) {\n\t var valid_inputs = new Backbone.Collection();\n\t copy.get('inputs').each(function (input) {\n\t if (input.get_samples()) {\n\t valid_inputs.push(input);\n\t }\n\t });\n\t copy.set('inputs', valid_inputs);\n\t }\n\t\n\t return copy;\n\t },\n\t\n\t apply_search_results: function (results) {\n\t _.indexOf(results, this.attributes.id) !== -1 ? this.show() : this.hide();\n\t return this.is_visible();\n\t },\n\t\n\t /**\n\t * Set a tool input's value.\n\t */\n\t set_input_value: function (name, value) {\n\t this.get('inputs').find(function (input) {\n\t return input.get('name') === name;\n\t }).set('value', value);\n\t },\n\t\n\t /**\n\t * Set many input values at once.\n\t */\n\t set_input_values: function (inputs_dict) {\n\t var self = this;\n\t _.each(_.keys(inputs_dict), function (input_name) {\n\t self.set_input_value(input_name, inputs_dict[input_name]);\n\t });\n\t },\n\t\n\t /**\n\t * Run tool; returns a Deferred that resolves to the tool's output(s).\n\t */\n\t run: function () {\n\t return this._run();\n\t },\n\t\n\t /**\n\t * Rerun tool using regions and a target dataset.\n\t */\n\t rerun: function (target_dataset, regions) {\n\t return this._run({\n\t action: 'rerun',\n\t target_dataset_id: target_dataset.id,\n\t regions: regions\n\t });\n\t },\n\t\n\t /**\n\t * Returns input dict for tool's inputs.\n\t */\n\t get_inputs_dict: function () {\n\t var input_dict = {};\n\t this.get('inputs').each(function (input) {\n\t input_dict[input.get('name')] = input.get('value');\n\t });\n\t return input_dict;\n\t },\n\t\n\t /**\n\t * Run tool; returns a Deferred that resolves to the tool's output(s).\n\t * NOTE: this method is a helper method and should not be called directly.\n\t */\n\t _run: function (additional_params) {\n\t // Create payload.\n\t var payload = _.extend({\n\t tool_id: this.id,\n\t inputs: this.get_inputs_dict()\n\t }, additional_params);\n\t\n\t // Because job may require indexing datasets, use server-side\n\t // deferred to ensure that job is run. Also use deferred that\n\t // resolves to outputs from tool.\n\t var run_deferred = $.Deferred(),\n\t ss_deferred = new util.ServerStateDeferred({\n\t ajax_settings: {\n\t url: this.urlRoot,\n\t data: JSON.stringify(payload),\n\t dataType: \"json\",\n\t contentType: 'application/json',\n\t type: \"POST\"\n\t },\n\t interval: 2000,\n\t success_fn: function (response) {\n\t return response !== \"pending\";\n\t }\n\t });\n\t\n\t // Run job and resolve run_deferred to tool outputs.\n\t $.when(ss_deferred.go()).then(function (result) {\n\t run_deferred.resolve(new data.DatasetCollection(result));\n\t });\n\t return run_deferred;\n\t }\n\t });\n\t _.extend(Tool.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool view.\n\t */\n\t var ToolView = Backbone.View.extend({});\n\t\n\t /**\n\t * Wrap collection of tools for fast access/manipulation.\n\t */\n\t var ToolCollection = Backbone.Collection.extend({\n\t model: Tool\n\t });\n\t\n\t /**\n\t * Label or section header in tool panel.\n\t */\n\t var ToolSectionLabel = Backbone.Model.extend(VisibilityMixin);\n\t\n\t /**\n\t * Section of tool panel with elements (labels and tools).\n\t */\n\t var ToolSection = Backbone.Model.extend({\n\t defaults: {\n\t elems: [],\n\t open: false\n\t },\n\t\n\t clear_search_results: function () {\n\t _.each(this.attributes.elems, function (elt) {\n\t elt.show();\n\t });\n\t\n\t this.show();\n\t this.set(\"open\", false);\n\t },\n\t\n\t apply_search_results: function (results) {\n\t var all_hidden = true,\n\t cur_label;\n\t _.each(this.attributes.elems, function (elt) {\n\t if (elt instanceof ToolSectionLabel) {\n\t cur_label = elt;\n\t cur_label.hide();\n\t } else if (elt instanceof Tool) {\n\t if (elt.apply_search_results(results)) {\n\t all_hidden = false;\n\t if (cur_label) {\n\t cur_label.show();\n\t }\n\t }\n\t }\n\t });\n\t\n\t if (all_hidden) {\n\t this.hide();\n\t } else {\n\t this.show();\n\t this.set(\"open\", true);\n\t }\n\t }\n\t });\n\t _.extend(ToolSection.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool search that updates results when query is changed. Result value of null\n\t * indicates that query was not run; if not null, results are from search using\n\t * query.\n\t */\n\t var ToolSearch = Backbone.Model.extend({\n\t defaults: {\n\t search_hint_string: \"search tools\",\n\t min_chars_for_search: 3,\n\t clear_btn_url: \"\",\n\t visible: true,\n\t query: \"\",\n\t results: null,\n\t // ESC (27) will clear the input field and tool search filters\n\t clear_key: 27\n\t },\n\t\n\t urlRoot: Galaxy.root + 'api/tools',\n\t\n\t initialize: function () {\n\t this.on(\"change:query\", this.do_search);\n\t },\n\t\n\t /**\n\t * Do the search and update the results.\n\t */\n\t do_search: function () {\n\t var query = this.attributes.query;\n\t\n\t // If query is too short, do not search.\n\t if (query.length < this.attributes.min_chars_for_search) {\n\t this.set(\"results\", null);\n\t return;\n\t }\n\t\n\t // Do search via AJAX.\n\t var q = query;\n\t // Stop previous ajax-request\n\t if (this.timer) {\n\t clearTimeout(this.timer);\n\t }\n\t // Start a new ajax-request in X ms\n\t $(\"#search-clear-btn\").hide();\n\t $(\"#search-spinner\").show();\n\t var self = this;\n\t this.timer = setTimeout(function () {\n\t // log the search to analytics if present\n\t if (typeof ga !== 'undefined') {\n\t ga('send', 'pageview', Galaxy.root + '?q=' + q);\n\t }\n\t $.get(self.urlRoot, { q: q }, function (data) {\n\t self.set(\"results\", data);\n\t $(\"#search-spinner\").hide();\n\t $(\"#search-clear-btn\").show();\n\t }, \"json\");\n\t }, 400);\n\t },\n\t\n\t clear_search: function () {\n\t this.set(\"query\", \"\");\n\t this.set(\"results\", null);\n\t }\n\t\n\t });\n\t _.extend(ToolSearch.prototype, VisibilityMixin);\n\t\n\t /**\n\t * Tool Panel.\n\t */\n\t var ToolPanel = Backbone.Model.extend({\n\t\n\t initialize: function (options) {\n\t this.attributes.tool_search = options.tool_search;\n\t this.attributes.tool_search.on(\"change:results\", this.apply_search_results, this);\n\t this.attributes.tools = options.tools;\n\t this.attributes.layout = new Backbone.Collection(this.parse(options.layout));\n\t },\n\t\n\t /**\n\t * Parse tool panel dictionary and return collection of tool panel elements.\n\t */\n\t parse: function (response) {\n\t // Recursive function to parse tool panel elements.\n\t var self = this,\n\t\n\t // Helper to recursively parse tool panel.\n\t parse_elt = function (elt_dict) {\n\t var type = elt_dict.model_class;\n\t // There are many types of tools; for now, anything that ends in 'Tool'\n\t // is treated as a generic tool.\n\t if (type.indexOf('Tool') === type.length - 4) {\n\t return self.attributes.tools.get(elt_dict.id);\n\t } else if (type === 'ToolSection') {\n\t // Parse elements.\n\t var elems = _.map(elt_dict.elems, parse_elt);\n\t elt_dict.elems = elems;\n\t return new ToolSection(elt_dict);\n\t } else if (type === 'ToolSectionLabel') {\n\t return new ToolSectionLabel(elt_dict);\n\t }\n\t };\n\t\n\t return _.map(response, parse_elt);\n\t },\n\t\n\t clear_search_results: function () {\n\t this.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSection) {\n\t panel_elt.clear_search_results();\n\t } else {\n\t // Label or tool, so just show.\n\t panel_elt.show();\n\t }\n\t });\n\t },\n\t\n\t apply_search_results: function () {\n\t var results = this.get('tool_search').get('results');\n\t if (results === null) {\n\t this.clear_search_results();\n\t return;\n\t }\n\t\n\t var cur_label = null;\n\t this.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSectionLabel) {\n\t cur_label = panel_elt;\n\t cur_label.hide();\n\t } else if (panel_elt instanceof Tool) {\n\t if (panel_elt.apply_search_results(results)) {\n\t if (cur_label) {\n\t cur_label.show();\n\t }\n\t }\n\t } else {\n\t // Starting new section, so clear current label.\n\t cur_label = null;\n\t panel_elt.apply_search_results(results);\n\t }\n\t });\n\t }\n\t });\n\t\n\t /**\n\t * View classes for Galaxy tools and tool panel.\n\t *\n\t * Views use the templates defined below for rendering. Views update as needed\n\t * based on (a) model/collection events and (b) user interactions; in this sense,\n\t * they are controllers are well and the HTML is the real view in the MVC architecture.\n\t */\n\t\n\t /**\n\t * Base view that handles visibility based on model's hidden attribute.\n\t */\n\t var BaseView = Backbone.View.extend({\n\t initialize: function () {\n\t this.model.on(\"change:hidden\", this.update_visible, this);\n\t this.update_visible();\n\t },\n\t update_visible: function () {\n\t this.model.attributes.hidden ? this.$el.hide() : this.$el.show();\n\t }\n\t });\n\t\n\t /**\n\t * Link to a tool.\n\t */\n\t var ToolLinkView = BaseView.extend({\n\t tagName: 'div',\n\t\n\t render: function () {\n\t // create element\n\t var $link = $('
                                  ');\n\t $link.append(templates.tool_link(this.model.toJSON()));\n\t\n\t var formStyle = this.model.get('form_style', null);\n\t // open upload dialog for upload tool\n\t if (this.model.id === 'upload1') {\n\t $link.find('a').on('click', function (e) {\n\t e.preventDefault();\n\t Galaxy.upload.show();\n\t });\n\t } else if (formStyle === 'regular') {\n\t // regular tools\n\t var self = this;\n\t $link.find('a').on('click', function (e) {\n\t e.preventDefault();\n\t Galaxy.router.push('/', { tool_id: self.model.id, version: self.model.get('version') });\n\t });\n\t }\n\t\n\t // add element\n\t this.$el.append($link);\n\t return this;\n\t }\n\t });\n\t\n\t /**\n\t * Panel label/section header.\n\t */\n\t var ToolSectionLabelView = BaseView.extend({\n\t tagName: 'div',\n\t className: 'toolPanelLabel',\n\t\n\t render: function () {\n\t this.$el.append($(\"\").text(this.model.attributes.text));\n\t return this;\n\t }\n\t });\n\t\n\t /**\n\t * Panel section.\n\t */\n\t var ToolSectionView = BaseView.extend({\n\t tagName: 'div',\n\t className: 'toolSectionWrapper',\n\t\n\t initialize: function () {\n\t BaseView.prototype.initialize.call(this);\n\t this.model.on(\"change:open\", this.update_open, this);\n\t },\n\t\n\t render: function () {\n\t // Build using template.\n\t this.$el.append(templates.panel_section(this.model.toJSON()));\n\t\n\t // Add tools to section.\n\t var section_body = this.$el.find(\".toolSectionBody\");\n\t _.each(this.model.attributes.elems, function (elt) {\n\t if (elt instanceof Tool) {\n\t var tool_view = new ToolLinkView({ model: elt, className: \"toolTitle\" });\n\t tool_view.render();\n\t section_body.append(tool_view.$el);\n\t } else if (elt instanceof ToolSectionLabel) {\n\t var label_view = new ToolSectionLabelView({ model: elt });\n\t label_view.render();\n\t section_body.append(label_view.$el);\n\t } else {\n\t // TODO: handle nested section bodies?\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t events: {\n\t 'click .toolSectionTitle > a': 'toggle'\n\t },\n\t\n\t /**\n\t * Toggle visibility of tool section.\n\t */\n\t toggle: function () {\n\t this.model.set(\"open\", !this.model.attributes.open);\n\t },\n\t\n\t /**\n\t * Update whether section is open or close.\n\t */\n\t update_open: function () {\n\t this.model.attributes.open ? this.$el.children(\".toolSectionBody\").slideDown(\"fast\") : this.$el.children(\".toolSectionBody\").slideUp(\"fast\");\n\t }\n\t });\n\t\n\t var ToolSearchView = Backbone.View.extend({\n\t tagName: 'div',\n\t id: 'tool-search',\n\t className: 'bar',\n\t\n\t events: {\n\t 'click': 'focus_and_select',\n\t 'keyup :input': 'query_changed',\n\t 'change :input': 'query_changed',\n\t 'click #search-clear-btn': 'clear'\n\t },\n\t\n\t render: function () {\n\t this.$el.append(templates.tool_search(this.model.toJSON()));\n\t if (!this.model.is_visible()) {\n\t this.$el.hide();\n\t }\n\t\n\t // Adjust top for issue 2907 depending on whether the messagebox is visible.\n\t if ($(\"#messagebox\").is(\":visible\")) {\n\t this.$el.css(\"top\", \"95px\");\n\t }\n\t\n\t this.$el.find('[title]').tooltip();\n\t return this;\n\t },\n\t\n\t focus_and_select: function () {\n\t this.$el.find(\":input\").focus().select();\n\t },\n\t\n\t clear: function () {\n\t this.model.clear_search();\n\t this.$el.find(\":input\").val('');\n\t this.focus_and_select();\n\t return false;\n\t },\n\t\n\t query_changed: function (evData) {\n\t // check for the 'clear key' (ESC) first\n\t if (this.model.attributes.clear_key && this.model.attributes.clear_key === evData.which) {\n\t this.clear();\n\t return false;\n\t }\n\t this.model.set(\"query\", this.$el.find(\":input\").val());\n\t }\n\t });\n\t\n\t /**\n\t * Tool panel view. Events triggered include:\n\t * tool_link_click(click event, tool_model)\n\t */\n\t var ToolPanelView = Backbone.View.extend({\n\t tagName: 'div',\n\t className: 'toolMenu',\n\t\n\t /**\n\t * Set up view.\n\t */\n\t initialize: function () {\n\t this.model.get('tool_search').on(\"change:results\", this.handle_search_results, this);\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t\n\t // Render search.\n\t var search_view = new ToolSearchView({ model: this.model.get('tool_search') });\n\t search_view.render();\n\t self.$el.append(search_view.$el);\n\t\n\t // Render panel.\n\t this.model.get('layout').each(function (panel_elt) {\n\t if (panel_elt instanceof ToolSection) {\n\t var section_title_view = new ToolSectionView({ model: panel_elt });\n\t section_title_view.render();\n\t self.$el.append(section_title_view.$el);\n\t } else if (panel_elt instanceof Tool) {\n\t var tool_view = new ToolLinkView({ model: panel_elt, className: \"toolTitleNoSection\" });\n\t tool_view.render();\n\t self.$el.append(tool_view.$el);\n\t } else if (panel_elt instanceof ToolSectionLabel) {\n\t var label_view = new ToolSectionLabelView({ model: panel_elt });\n\t label_view.render();\n\t self.$el.append(label_view.$el);\n\t }\n\t });\n\t\n\t // Setup tool link click eventing.\n\t self.$el.find(\"a.tool-link\").click(function (e) {\n\t // Tool id is always the first class.\n\t var tool_id = $(this).attr('class').split(/\\s+/)[0],\n\t tool = self.model.get('tools').get(tool_id);\n\t\n\t self.trigger(\"tool_link_click\", e, tool);\n\t });\n\t\n\t return this;\n\t },\n\t\n\t handle_search_results: function () {\n\t var results = this.model.get('tool_search').get('results');\n\t if (results && results.length === 0) {\n\t $(\"#search-no-results\").show();\n\t } else {\n\t $(\"#search-no-results\").hide();\n\t }\n\t }\n\t });\n\t\n\t /**\n\t * View for working with a tool: setting parameters and inputs and executing the tool.\n\t */\n\t var ToolFormView = Backbone.View.extend({\n\t className: 'toolForm',\n\t\n\t render: function () {\n\t this.$el.children().remove();\n\t this.$el.append(templates.tool_form(this.model.toJSON()));\n\t }\n\t });\n\t\n\t /**\n\t * Integrated tool menu + tool execution.\n\t */\n\t var IntegratedToolMenuAndView = Backbone.View.extend({\n\t className: 'toolMenuAndView',\n\t\n\t initialize: function () {\n\t this.tool_panel_view = new ToolPanelView({ collection: this.collection });\n\t this.tool_form_view = new ToolFormView();\n\t },\n\t\n\t render: function () {\n\t // Render and append tool panel.\n\t this.tool_panel_view.render();\n\t this.tool_panel_view.$el.css(\"float\", \"left\");\n\t this.$el.append(this.tool_panel_view.$el);\n\t\n\t // Append tool form view.\n\t this.tool_form_view.$el.hide();\n\t this.$el.append(this.tool_form_view.$el);\n\t\n\t // On tool link click, show tool.\n\t var self = this;\n\t this.tool_panel_view.on(\"tool_link_click\", function (e, tool) {\n\t // Prevents click from activating link:\n\t e.preventDefault();\n\t // Show tool that was clicked on:\n\t self.show_tool(tool);\n\t });\n\t },\n\t\n\t /**\n\t * Fetch and display tool.\n\t */\n\t show_tool: function (tool) {\n\t var self = this;\n\t tool.fetch().done(function () {\n\t self.tool_form_view.model = tool;\n\t self.tool_form_view.render();\n\t self.tool_form_view.$el.show();\n\t $('#left').width(\"650px\");\n\t });\n\t }\n\t });\n\t\n\t // TODO: move into relevant views\n\t var templates = {\n\t // the search bar at the top of the tool panel\n\t tool_search: _.template(['\" autocomplete=\"off\" type=\"text\" />', ' ',\n\t //TODO: replace with icon\n\t ''].join('')),\n\t\n\t // the category level container in the tool panel (e.g. 'Get Data', 'Text Manipulation')\n\t panel_section: _.template(['
                                  \">', '<%- name %>', '
                                  ', '
                                  \" class=\"toolSectionBody\" style=\"display: none;\">', '
                                  ', '
                                  '].join('')),\n\t\n\t // a single tool's link in the tool panel; will load the tool form in the center panel\n\t tool_link: _.template(['', '<% _.each( labels, function( label ){ %>', '\">', '<%- label %>', '', '<% }); %>', '', ' tool-link\" href=\"<%= link %>\" target=\"<%- target %>\" minsizehint=\"<%- min_width %>\">', '<%- name %>', '', ' <%- description %>'].join('')),\n\t\n\t // the tool form for entering tool parameters, viewing help and executing the tool\n\t // loaded when a tool link is clicked in the tool panel\n\t tool_form: _.template(['
                                  <%- tool.name %> (version <%- tool.version %>)
                                  ', '
                                  ', '<% _.each( tool.inputs, function( input ){ %>', '
                                  ', '', '
                                  ', '<%= input.html %>', '
                                  ', '
                                  ', '<%- input.help %>', '
                                  ', '
                                  ', '
                                  ', '<% }); %>', '
                                  ', '
                                  ', '', '
                                  ', '
                                  ', '
                                  <% tool.help %>
                                  ', '
                                  '].join(''), { variable: 'tool' })\n\t };\n\t\n\t // Exports\n\t return {\n\t ToolParameter: ToolParameter,\n\t IntegerToolParameter: IntegerToolParameter,\n\t SelectToolParameter: SelectToolParameter,\n\t Tool: Tool,\n\t ToolCollection: ToolCollection,\n\t ToolSearch: ToolSearch,\n\t ToolPanel: ToolPanel,\n\t ToolPanelView: ToolPanelView,\n\t ToolFormView: ToolFormView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 67 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This renders the content of the ftp popup **/\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils) {\n\t return Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.options = Utils.merge(options, {\n\t class_add: 'upload-icon-button fa fa-square-o',\n\t class_remove: 'upload-icon-button fa fa-check-square-o',\n\t class_partial: 'upload-icon-button fa fa-minus-square-o',\n\t collection: null,\n\t onchange: function () {},\n\t onadd: function () {},\n\t onremove: function () {}\n\t });\n\t this.collection = this.options.collection;\n\t this.setElement(this._template());\n\t this.rows = [];\n\t Utils.get({\n\t url: Galaxy.root + 'api/remote_files',\n\t success: function (ftp_files) {\n\t self._fill(ftp_files);\n\t },\n\t error: function () {\n\t self._fill();\n\t }\n\t });\n\t },\n\t\n\t /** Fill table with ftp entries */\n\t _fill: function (ftp_files) {\n\t if (ftp_files && ftp_files.length > 0) {\n\t this.$('.upload-ftp-content').html($(this._templateTable()));\n\t var size = 0;\n\t for (index in ftp_files) {\n\t this.rows.push(this._add(ftp_files[index]));\n\t size += ftp_files[index].size;\n\t }\n\t this.$('.upload-ftp-number').html(ftp_files.length + ' files');\n\t this.$('.upload-ftp-disk').html(Utils.bytesToString(size, true));\n\t if (this.collection) {\n\t var self = this;\n\t this.$('._has_collection').show();\n\t this.$select_all = this.$('.upload-selectall').addClass(this.options.class_add);\n\t this.$select_all.on('click', function () {\n\t var add = self.$select_all.hasClass(self.options.class_add);\n\t for (index in ftp_files) {\n\t var ftp_file = ftp_files[index];\n\t var model_index = self._find(ftp_file);\n\t if (!model_index && add || model_index && !add) {\n\t self.rows[index].trigger('click');\n\t }\n\t }\n\t });\n\t this._refresh();\n\t }\n\t } else {\n\t this.$('.upload-ftp-content').html($(this._templateInfo()));\n\t }\n\t this.$('.upload-ftp-wait').hide();\n\t },\n\t\n\t /** Add file to table */\n\t _add: function (ftp_file) {\n\t var self = this;\n\t var $it = $(this._templateRow(ftp_file));\n\t var $icon = $it.find('.icon');\n\t this.$('tbody').append($it);\n\t if (this.collection) {\n\t $icon.addClass(this._find(ftp_file) ? this.options.class_remove : this.options.class_add);\n\t $it.on('click', function () {\n\t var model_index = self._find(ftp_file);\n\t $icon.removeClass();\n\t if (!model_index) {\n\t self.options.onadd(ftp_file);\n\t $icon.addClass(self.options.class_remove);\n\t } else {\n\t self.options.onremove(model_index);\n\t $icon.addClass(self.options.class_add);\n\t }\n\t self._refresh();\n\t });\n\t } else {\n\t $it.on('click', function () {\n\t self.options.onchange(ftp_file);\n\t });\n\t }\n\t return $it;\n\t },\n\t\n\t /** Refresh select all button state */\n\t _refresh: function () {\n\t var filtered = this.collection.where({ file_mode: 'ftp', enabled: true });\n\t this.$select_all.removeClass();\n\t if (filtered.length == 0) {\n\t this.$select_all.addClass(this.options.class_add);\n\t } else {\n\t this.$select_all.addClass(filtered.length == this.rows.length ? this.options.class_remove : this.options.class_partial);\n\t }\n\t },\n\t\n\t /** Get model index */\n\t _find: function (ftp_file) {\n\t var item = this.collection.findWhere({\n\t file_path: ftp_file.path,\n\t file_mode: 'ftp',\n\t enabled: true\n\t });\n\t return item && item.get('id');\n\t },\n\t\n\t /** Template of row */\n\t _templateRow: function (options) {\n\t return '
                                  ' + _.escape(options.path) + '' + Utils.bytesToString(options.size) + '' + options.ctime + '
                                  ' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
                                  NameSizeCreated
                                  ';\n\t },\n\t\n\t /** Template of info message */\n\t _templateInfo: function () {\n\t return '
                                  ' + 'Your FTP directory does not contain any files.' + '
                                  ';\n\t },\n\t\n\t /** Template of main view */\n\t _template: function () {\n\t return '
                                  ' + '
                                  ' + '
                                  This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at ' + this.options.ftp_upload_site + ' using your Galaxy credentials (email address and password).
                                  ' + '
                                  ' + '
                                  ';\n\t }\n\t });\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 68 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This renders the content of the settings popup, allowing users to specify flags i.e. for space-to-tab conversion **/\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils) {\n\t return Backbone.View.extend({\n\t options: {\n\t class_check: 'fa-check-square-o',\n\t class_uncheck: 'fa-square-o',\n\t parameters: [{\n\t id: 'space_to_tab',\n\t title: 'Convert spaces to tabs'\n\t }, {\n\t id: 'to_posix_lines',\n\t title: 'Use POSIX standard'\n\t }]\n\t },\n\t\n\t initialize: function (options) {\n\t var self = this;\n\t this.model = options.model;\n\t this.setElement($('
                                  ').addClass('upload-settings'));\n\t this.$el.append($('
                                  ').addClass('upload-settings-cover'));\n\t this.$el.append($('').addClass('upload-settings-table ui-table-striped').append(''));\n\t this.$cover = this.$('.upload-settings-cover');\n\t this.$table = this.$('.upload-settings-table > tbody');\n\t this.listenTo(this.model, 'change', this.render, this);\n\t this.model.trigger('change');\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t this.$table.empty();\n\t _.each(this.options.parameters, function (parameter) {\n\t var $checkbox = $('
                                  ').addClass('upload-' + parameter.id + ' upload-icon-button fa').addClass(self.model.get(parameter.id) && self.options.class_check || self.options.class_uncheck).on('click', function () {\n\t self.model.get('enabled') && self.model.set(parameter.id, !self.model.get(parameter.id));\n\t });\n\t self.$table.append($('
                                  ').append($('' + '' + '' + '');\n\t });\n\t $tmpl.append($table);\n\t } else {\n\t $tmpl.append('No ' + this.model.get('plural').toLowerCase() + ' have been shared with you.');\n\t }\n\t return $tmpl;\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 126 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(82), __webpack_require__(85), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_LI_EDIT, HDA_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI_EDIT.DatasetListItemEdit;\n\t /** @class Editing view for HistoryDatasetAssociation.\n\t */\n\t var HDAListItemEdit = _super.extend(\n\t /** @lends HDAListItemEdit.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t /** In this override, only get details if in the ready state, get rerunnable if in other states.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t\n\t // special case the need for the rerunnable and creating_job attributes\n\t // needed for rendering re-run button on queued, running datasets\n\t } else if (!view.model.has('rerunnable')) {\n\t return view.model.fetch({ silent: true, data: {\n\t // only fetch rerunnable and creating_job to keep overhead down\n\t keys: ['rerunnable', 'creating_job'].join(',')\n\t } });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .unhide-link': function (ev) {\n\t this.model.unhide();return false;\n\t }\n\t }),\n\t\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t HDAListItemEdit.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate(['<% if( !dataset.visible ){ %>',\n\t // add a link to unhide a dataset\n\t '
                                  ', _l('This dataset has been hidden'), '
                                  ', _l('Unhide it'), '', '
                                  ', '<% } %>'], 'dataset')\n\t });\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t //NOTE: *steal* the HDAListItemView titleBar\n\t titleBar: HDA_LI.HDAListItemView.prototype.templates.titleBar,\n\t warnings: warnings\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDAListItemEdit: HDAListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 127 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(87), __webpack_require__(120), __webpack_require__(25), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HDCA_LI, DC_VIEW_EDIT, faIconButton, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = HDCA_LI.HDCAListItemView;\n\t /** @class Editing view for HistoryDatasetCollectionAssociation.\n\t */\n\t var HDCAListItemEdit = _super.extend(\n\t /** @lends HDCAListItemEdit.prototype */{\n\t\n\t /** logger used to record this.log messages, commonly set to console */\n\t //logger : console,\n\t\n\t /** Override to return editable versions of the collection panels */\n\t _getFoldoutPanelClass: function () {\n\t switch (this.model.get('collection_type')) {\n\t case 'list':\n\t return DC_VIEW_EDIT.ListCollectionViewEdit;\n\t case 'paired':\n\t return DC_VIEW_EDIT.PairCollectionViewEdit;\n\t case 'list:paired':\n\t return DC_VIEW_EDIT.ListOfPairsCollectionViewEdit;\n\t case 'list:list':\n\t return DC_VIEW_EDIT.ListOfListsCollectionViewEdit;\n\t }\n\t throw new TypeError('Uknown collection_type: ' + this.model.get('collection_type'));\n\t },\n\t\n\t // ......................................................................... delete\n\t /** In this override, add the delete button. */\n\t _renderPrimaryActions: function () {\n\t this.log(this + '._renderPrimaryActions');\n\t // render the display, edit attr and delete icon-buttons\n\t return _super.prototype._renderPrimaryActions.call(this).concat([this._renderDeleteButton()]);\n\t },\n\t\n\t /** Render icon-button to delete this collection. */\n\t _renderDeleteButton: function () {\n\t var self = this,\n\t deleted = this.model.get('deleted');\n\t return faIconButton({\n\t title: deleted ? _l('Dataset collection is already deleted') : _l('Delete'),\n\t classes: 'delete-btn',\n\t faIcon: 'fa-times',\n\t disabled: deleted,\n\t onclick: function () {\n\t // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n\t self.$el.find('.icon-btn.delete-btn').trigger('mouseout');\n\t self.model['delete']();\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... misc\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDCAListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t HDCAListItemEdit: HDCAListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 128 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This class renders the grid list. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(12), __webpack_require__(62), __webpack_require__(84)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, GridView, HistoryModel, historyCopyDialog) {\n\t\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.setElement($('
                                  '));\n\t this.model = new Backbone.Model();\n\t Utils.get({\n\t url: Galaxy.root + 'history/' + options.action_id,\n\t success: function (response) {\n\t response['dict_format'] = true;\n\t _.each(response['operations'], function (operation) {\n\t if (operation.label == 'Copy') {\n\t operation.onclick = function (id) {\n\t self._showCopyDialog(id);\n\t };\n\t }\n\t });\n\t self.model.set(response);\n\t self.render();\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var grid = new GridView(this.model.attributes);\n\t this.$el.empty().append(grid.$el);\n\t },\n\t\n\t _showCopyDialog: function (id) {\n\t var history = new HistoryModel.History({ id: id });\n\t history.fetch().fail(function () {\n\t alert('History could not be fetched. Please contact an administrator');\n\t }).done(function () {\n\t historyCopyDialog(history, {}).done(function () {\n\t if (window.parent && window.parent.Galaxy && window.parent.Galaxy.currHistoryPanel) {\n\t window.parent.Galaxy.currHistoryPanel.loadCurrentHistory();\n\t }\n\t window.location.reload(true);\n\t });\n\t });\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 129 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(62), __webpack_require__(130), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_MODEL, HISTORY_VIEW_EDIT, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t // ============================================================================\n\t /** session storage for history panel preferences (and to maintain state)\n\t */\n\t\n\t var HistoryViewPrefs = BASE_MVC.SessionStorageModel.extend(\n\t /** @lends HistoryViewPrefs.prototype */{\n\t defaults: {\n\t /** should the tags editor be shown or hidden initially? */\n\t tagsEditorShown: false,\n\t /** should the annotation editor be shown or hidden initially? */\n\t annotationEditorShown: false,\n\t ///** what is the currently focused content (dataset or collection) in the current history?\n\t // * (the history panel will highlight and scroll to the focused content view)\n\t // */\n\t //focusedContentId : null\n\t /** Current scroll position */\n\t scrollPosition: 0\n\t },\n\t toString: function () {\n\t return 'HistoryViewPrefs(' + JSON.stringify(this.toJSON()) + ')';\n\t }\n\t });\n\t\n\t /** key string to store panel prefs (made accessible on class so you can access sessionStorage directly) */\n\t HistoryViewPrefs.storageKey = function storageKey() {\n\t return 'history-panel';\n\t };\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t var _super = HISTORY_VIEW_EDIT.HistoryViewEdit;\n\t // used in root/index.mako\n\t /** @class View/Controller for the user's current history model as used in the history\n\t * panel (current right hand panel) of the analysis page.\n\t *\n\t * The only history panel that:\n\t * will poll for updates.\n\t * displays datasets in reverse hid order.\n\t */\n\t var CurrentHistoryView = _super.extend( /** @lends CurrentHistoryView.prototype */{\n\t\n\t className: _super.prototype.className + ' current-history-panel',\n\t\n\t /** override to use drilldown (and not foldout) for how collections are displayed */\n\t HDCAViewClass: _super.prototype.HDCAViewClass.extend({\n\t foldoutStyle: 'drilldown'\n\t }),\n\t\n\t emptyMsg: [_l('This history is empty'), '. ', _l('You can '), '', _l('load your own data'), '', _l(' or '), '', _l('get data from an external source'), ''].join(''),\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events */\n\t initialize: function (attributes) {\n\t attributes = attributes || {};\n\t\n\t // ---- persistent preferences\n\t /** maintain state / preferences over page loads */\n\t this.preferences = new HistoryViewPrefs(_.extend({\n\t id: HistoryViewPrefs.storageKey()\n\t }, _.pick(attributes, _.keys(HistoryViewPrefs.prototype.defaults))));\n\t\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t /** sub-views that will overlay this panel (collections) */\n\t this.panelStack = [];\n\t\n\t /** id of currently focused content */\n\t this.currentContentId = attributes.currentContentId || null;\n\t //NOTE: purposely not sent to localstorage since panel recreation roughly lines up with a reset of this value\n\t },\n\t\n\t /** Override to cache the current scroll position with a listener */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t\n\t var panel = this;\n\t // reset scroll position when there's a new history\n\t this.on('new-model', function () {\n\t panel.preferences.set('scrollPosition', 0);\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading history/item models\n\t // TODO: next three more appropriate moved to the app level\n\t /** (re-)loads the user's current history & contents w/ details */\n\t loadCurrentHistory: function () {\n\t return this.loadHistory(null, { url: Galaxy.root + 'history/current_history_json' });\n\t },\n\t\n\t /** loads a history & contents w/ details and makes them the current history */\n\t switchToHistory: function (historyId, attributes) {\n\t if (Galaxy.user.isAnonymous()) {\n\t this.trigger('error', _l('You must be logged in to switch histories'), _l('Anonymous user'));\n\t return $.when();\n\t }\n\t return this.loadHistory(historyId, { url: Galaxy.root + 'history/set_as_current?id=' + historyId });\n\t },\n\t\n\t /** creates a new history on the server and sets it as the user's current history */\n\t createNewHistory: function (attributes) {\n\t if (Galaxy.user.isAnonymous()) {\n\t this.trigger('error', _l('You must be logged in to create histories'), _l('Anonymous user'));\n\t return $.when();\n\t }\n\t return this.loadHistory(null, { url: Galaxy.root + 'history/create_new_current' });\n\t },\n\t\n\t /** release/free/shutdown old models and set up panel for new models */\n\t setModel: function (model, attributes, render) {\n\t _super.prototype.setModel.call(this, model, attributes, render);\n\t if (this.model && this.model.id) {\n\t this.log('checking for updates');\n\t this.model.checkForUpdates();\n\t }\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ history/content event listening\n\t /** listening for history events */\n\t _setUpModelListeners: function () {\n\t _super.prototype._setUpModelListeners.call(this);\n\t // re-broadcast any model change events so that listeners don't have to re-bind to each history\n\t return this.listenTo(this.model, {\n\t 'change:nice_size change:size': function () {\n\t this.trigger('history-size-change', this, this.model, arguments);\n\t },\n\t 'change:id': function () {\n\t this.once('loading-done', function () {\n\t this.model.checkForUpdates();\n\t });\n\t }\n\t });\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t // if a hidden item is created (gen. by a workflow), moves thru the updater to the ready state,\n\t // then: remove it from the collection if the panel is set to NOT show hidden datasets\n\t this.listenTo(this.collection, 'state:ready', function (model, newState, oldState) {\n\t if (!model.get('visible') && !this.collection.storage.includeHidden()) {\n\t this.removeItemView(model);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** override to add a handler to capture the scroll position when the parent scrolls */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t // console.log( '_setUpBehaviors', this.$scrollContainer( $where ).get(0), this.$list( $where ) );\n\t // we need to call this in _setUpBehaviors which is called after render since the $el\n\t // may not be attached to $el.parent and $scrollContainer() may not work\n\t var panel = this;\n\t _super.prototype._setUpBehaviors.call(panel, $where);\n\t\n\t // cache the handler to remove and re-add so we don't pile up the handlers\n\t if (!this._debouncedScrollCaptureHandler) {\n\t this._debouncedScrollCaptureHandler = _.debounce(function scrollCapture() {\n\t // cache the scroll position (only if visible)\n\t if (panel.$el.is(':visible')) {\n\t panel.preferences.set('scrollPosition', $(this).scrollTop());\n\t }\n\t }, 40);\n\t }\n\t\n\t panel.$scrollContainer($where).off('scroll', this._debouncedScrollCaptureHandler).on('scroll', this._debouncedScrollCaptureHandler);\n\t return panel;\n\t },\n\t\n\t /** In this override, handle null models and move the search input to the top */\n\t _buildNewRender: function () {\n\t if (!this.model) {\n\t return $();\n\t }\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t $newRender.find('.search').prependTo($newRender.find('> .controls'));\n\t this._renderQuotaMessage($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** render the message displayed when a user is over quota and can't run jobs */\n\t _renderQuotaMessage: function ($whereTo) {\n\t $whereTo = $whereTo || this.$el;\n\t return $(this.templates.quotaMsg({}, this)).prependTo($whereTo.find('.messages'));\n\t },\n\t\n\t /** In this override, get and set current panel preferences when editor is used */\n\t _renderTags: function ($where) {\n\t var panel = this;\n\t // render tags and show/hide based on preferences\n\t _super.prototype._renderTags.call(panel, $where);\n\t if (panel.preferences.get('tagsEditorShown')) {\n\t panel.tagsEditor.toggle(true);\n\t }\n\t // store preference when shown or hidden\n\t panel.listenTo(panel.tagsEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden', function (tagsEditor) {\n\t panel.preferences.set('tagsEditorShown', tagsEditor.hidden);\n\t });\n\t },\n\t\n\t /** In this override, get and set current panel preferences when editor is used */\n\t _renderAnnotation: function ($where) {\n\t var panel = this;\n\t // render annotation and show/hide based on preferences\n\t _super.prototype._renderAnnotation.call(panel, $where);\n\t if (panel.preferences.get('annotationEditorShown')) {\n\t panel.annotationEditor.toggle(true);\n\t }\n\t // store preference when shown or hidden\n\t panel.listenTo(panel.annotationEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden', function (annotationEditor) {\n\t panel.preferences.set('annotationEditorShown', annotationEditor.hidden);\n\t });\n\t },\n\t\n\t /** Override to scroll to cached position (in prefs) after swapping */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t var panel = this;\n\t _.delay(function () {\n\t var pos = panel.preferences.get('scrollPosition');\n\t if (pos) {\n\t panel.scrollTo(pos, 0);\n\t }\n\t }, 10);\n\t //TODO: is this enough of a delay on larger histories?\n\t\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** Override to add the current-content highlight class to currentContentId's view */\n\t _attachItems: function ($whereTo) {\n\t _super.prototype._attachItems.call(this, $whereTo);\n\t var panel = this;\n\t if (panel.currentContentId) {\n\t panel._setCurrentContentById(panel.currentContentId);\n\t }\n\t return this;\n\t },\n\t\n\t /** Override to remove any drill down panels */\n\t addItemView: function (model, collection, options) {\n\t var view = _super.prototype.addItemView.call(this, model, collection, options);\n\t if (!view) {\n\t return view;\n\t }\n\t if (this.panelStack.length) {\n\t return this._collapseDrilldownPanel();\n\t }\n\t return view;\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection sub-views\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t // use pub-sub to: handle drilldown expansion and collapse\n\t return panel.listenTo(view, {\n\t 'expanded:drilldown': function (v, drilldown) {\n\t this._expandDrilldownPanel(drilldown);\n\t },\n\t 'collapsed:drilldown': function (v, drilldown) {\n\t this._collapseDrilldownPanel(drilldown);\n\t }\n\t });\n\t },\n\t\n\t /** display 'current content': add a visible highlight and store the id of a content item */\n\t setCurrentContent: function (view) {\n\t this.$('.history-content.current-content').removeClass('current-content');\n\t if (view) {\n\t view.$el.addClass('current-content');\n\t this.currentContentId = view.model.id;\n\t } else {\n\t this.currentContentId = null;\n\t }\n\t },\n\t\n\t /** find the view with the id and then call setCurrentContent on it */\n\t _setCurrentContentById: function (id) {\n\t var view = this.viewFromModelId(id) || null;\n\t this.setCurrentContent(view);\n\t },\n\t\n\t /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n\t _expandDrilldownPanel: function (drilldown) {\n\t this.panelStack.push(drilldown);\n\t // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n\t this.$controls().add(this.$list()).hide();\n\t drilldown.parentName = this.model.get('name');\n\t drilldown.delegateEvents().render().$el.appendTo(this.$el);\n\t },\n\t\n\t /** Handle drilldown close by freeing the panel and re-rendering this panel */\n\t _collapseDrilldownPanel: function (drilldown) {\n\t this.panelStack.pop();\n\t //TODO: MEM: free the panel\n\t this.$controls().add(this.$list()).show();\n\t },\n\t\n\t // ........................................................................ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t // the two links in the empty message\n\t 'click .uploader-link': function (ev) {\n\t Galaxy.upload.show(ev);\n\t },\n\t 'click .get-data-link': function (ev) {\n\t var $toolMenu = $('.toolMenuContainer');\n\t $toolMenu.parent().scrollTop(0);\n\t $toolMenu.find('span:contains(\"Get Data\")').click();\n\t }\n\t }),\n\t\n\t // ........................................................................ external objects/MVC\n\t listenToGalaxy: function (galaxy) {\n\t this.listenTo(galaxy, {\n\t // when the galaxy_main iframe is loaded with a new page,\n\t // compare the url to the following list and if there's a match\n\t // pull the id from url and indicate in the history view that\n\t // the dataset with that id is the 'current'ly active dataset\n\t 'center-frame:load': function (data) {\n\t var pathToMatch = data.fullpath;\n\t var hdaId = null;\n\t var useToURLRegexMap = {\n\t 'display': /datasets\\/([a-f0-9]+)\\/display/,\n\t 'edit': /datasets\\/([a-f0-9]+)\\/edit/,\n\t 'report_error': /dataset\\/errors\\?id=([a-f0-9]+)/,\n\t 'rerun': /tool_runner\\/rerun\\?id=([a-f0-9]+)/,\n\t 'show_params': /datasets\\/([a-f0-9]+)\\/show_params/\n\t };\n\t _.find(useToURLRegexMap, function (regex, use) {\n\t // grab the more specific match result (1), save, and use it as the find flag\n\t hdaId = _.result(pathToMatch.match(regex), 1);\n\t return hdaId;\n\t });\n\t // need to type mangle to go from web route to history contents\n\t this._setCurrentContentById(hdaId ? 'dataset-' + hdaId : null);\n\t },\n\t // when the center panel is given a new view, clear the current indicator\n\t 'center-panel:load': function (view) {\n\t this._setCurrentContentById();\n\t }\n\t });\n\t },\n\t\n\t //TODO: remove quota meter from panel and remove this\n\t /** add listeners to an external quota meter (mvc/user/user-quotameter.js) */\n\t connectToQuotaMeter: function (quotaMeter) {\n\t if (!quotaMeter) {\n\t return this;\n\t }\n\t // show/hide the 'over quota message' in the history when the meter tells it to\n\t this.listenTo(quotaMeter, 'quota:over', this.showQuotaMessage);\n\t this.listenTo(quotaMeter, 'quota:under', this.hideQuotaMessage);\n\t\n\t // having to add this to handle re-render of hview while overquota (the above do not fire)\n\t this.on('rendered rendered:initial', function () {\n\t if (quotaMeter && quotaMeter.isOverQuota()) {\n\t this.showQuotaMessage();\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** Override to preserve the quota message */\n\t clearMessages: function (ev) {\n\t var $target = !_.isUndefined(ev) ? $(ev.currentTarget) : this.$messages().children('[class$=\"message\"]');\n\t $target = $target.not('.quota-message');\n\t $target.fadeOut(this.fxSpeed, function () {\n\t $(this).remove();\n\t });\n\t return this;\n\t },\n\t\n\t /** Show the over quota message (which happens to be in the history panel).\n\t */\n\t showQuotaMessage: function () {\n\t var $msg = this.$('.quota-message');\n\t if ($msg.is(':hidden')) {\n\t $msg.slideDown(this.fxSpeed);\n\t }\n\t },\n\t\n\t /** Hide the over quota message (which happens to be in the history panel).\n\t */\n\t hideQuotaMessage: function () {\n\t var $msg = this.$('.quota-message');\n\t if (!$msg.is(':hidden')) {\n\t $msg.slideUp(this.fxSpeed);\n\t }\n\t },\n\t\n\t // ........................................................................ options menu\n\t //TODO: remove to batch\n\t /** unhide any hidden datasets */\n\t unhideHidden: function () {\n\t var self = this;\n\t if (confirm(_l('Really unhide all hidden datasets?'))) {\n\t // get all hidden, regardless of deleted/purged\n\t return self.model.contents._filterAndUpdate({ visible: false, deleted: '', purged: '' }, { visible: true }).done(function () {\n\t // TODO: would be better to render these as they're unhidden instead of all at once\n\t if (!self.model.contents.includeHidden) {\n\t self.renderItems();\n\t }\n\t });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** delete any hidden datasets */\n\t deleteHidden: function () {\n\t var self = this;\n\t if (confirm(_l('Really delete all hidden datasets?'))) {\n\t return self.model.contents._filterAndUpdate(\n\t // get all hidden, regardless of deleted/purged\n\t { visible: false, deleted: '', purged: '' },\n\t // both delete *and* unhide them\n\t { deleted: true, visible: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'CurrentHistoryView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t CurrentHistoryView.prototype.templates = function () {\n\t\n\t var quotaMsgTemplate = BASE_MVC.wrapTemplate(['
                                  ', _l('You are over your disk quota'), '. ', _l('Tool execution is on hold until your disk usage drops below your allocated quota'), '.', '
                                  '], 'history');\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t quotaMsg: quotaMsgTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t CurrentHistoryView: CurrentHistoryView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 130 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(131), __webpack_require__(61), __webpack_require__(17), __webpack_require__(86), __webpack_require__(126), __webpack_require__(127), __webpack_require__(65), __webpack_require__(78), __webpack_require__(57), __webpack_require__(122), __webpack_require__(121), __webpack_require__(25), __webpack_require__(18), __webpack_require__(7), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (HISTORY_VIEW, HISTORY_CONTENTS, STATES, HDA_MODEL, HDA_LI_EDIT, HDCA_LI_EDIT, TAGS, ANNOTATIONS, LIST_COLLECTION_CREATOR, PAIR_COLLECTION_CREATOR, LIST_OF_PAIRS_COLLECTION_CREATOR, faIconButton, PopupMenu, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t\n\t var _super = HISTORY_VIEW.HistoryView;\n\t // base class for history-view-edit-current and used as-is in history/view.mako\n\t /** @class Editable View/Controller for the history model.\n\t *\n\t * Allows:\n\t * (everything HistoryView allows)\n\t * changing the name\n\t * displaying and editing tags and annotations\n\t * multi-selection and operations on mulitple content items\n\t */\n\t var HistoryViewEdit = _super.extend(\n\t /** @lends HistoryViewEdit.prototype */{\n\t\n\t /** class to use for constructing the HistoryDatasetAssociation views */\n\t HDAViewClass: HDA_LI_EDIT.HDAListItemEdit,\n\t /** class to use for constructing the HistoryDatasetCollectionAssociation views */\n\t HDCAViewClass: HDCA_LI_EDIT.HDCAListItemEdit,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes\n\t */\n\t initialize: function (attributes) {\n\t attributes = attributes || {};\n\t _super.prototype.initialize.call(this, attributes);\n\t\n\t // ---- set up instance vars\n\t /** editor for tags - sub-view */\n\t this.tagsEditor = null;\n\t\n\t /** enable drag and drop - sub-view */\n\t this.dragItems = true;\n\t\n\t /** editor for annotations - sub-view */\n\t this.annotationEditor = null;\n\t\n\t /** allow user purge of dataset files? */\n\t this.purgeAllowed = attributes.purgeAllowed || false;\n\t\n\t // states/modes the panel can be in\n\t /** is the panel currently showing the dataset selection controls? */\n\t this.annotationEditorShown = attributes.annotationEditorShown || false;\n\t this.tagsEditorShown = attributes.tagsEditorShown || false;\n\t },\n\t\n\t /** Override to handle history as drag-drop target */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t return this.on({\n\t 'droptarget:drop': function (ev, data) {\n\t // process whatever was dropped and re-hide the drop target\n\t this.dataDropped(data);\n\t this.dropTargetOff();\n\t },\n\t 'view:attached view:removed': function () {\n\t this._renderCounts();\n\t },\n\t 'search:loading-progress': this._renderSearchProgress,\n\t 'search:searching': this._renderSearchFindings\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ listeners\n\t /** listening for history and HDA events */\n\t _setUpModelListeners: function () {\n\t _super.prototype._setUpModelListeners.call(this);\n\t this.listenTo(this.model, 'change:size', this.updateHistoryDiskSize);\n\t return this;\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t this.listenTo(this.collection, {\n\t 'change:deleted': this._handleItemDeletedChange,\n\t 'change:visible': this._handleItemVisibleChange,\n\t 'change:purged': function (model) {\n\t // hafta get the new nice-size w/o the purged model\n\t this.model.fetch();\n\t },\n\t // loading indicators for deleted/hidden\n\t 'fetching-deleted': function (collection) {\n\t this.$('> .controls .deleted-count').html('' + _l('loading...') + '');\n\t },\n\t 'fetching-hidden': function (collection) {\n\t this.$('> .controls .hidden-count').html('' + _l('loading...') + '');\n\t },\n\t 'fetching-deleted-done fetching-hidden-done': this._renderCounts\n\t });\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** In this override, add tag and annotation editors and a btn to toggle the selectors */\n\t _buildNewRender: function () {\n\t // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t if (!this.model) {\n\t return $newRender;\n\t }\n\t\n\t if (Galaxy && Galaxy.user && Galaxy.user.id && Galaxy.user.id === this.model.get('user_id')) {\n\t this._renderTags($newRender);\n\t this._renderAnnotation($newRender);\n\t }\n\t return $newRender;\n\t },\n\t\n\t /** Update the history size display (curr. upper right of panel). */\n\t updateHistoryDiskSize: function () {\n\t this.$('.history-size').text(this.model.get('nice_size'));\n\t },\n\t\n\t /** override to render counts when the items are rendered */\n\t renderItems: function ($whereTo) {\n\t var views = _super.prototype.renderItems.call(this, $whereTo);\n\t if (!this.searchFor) {\n\t this._renderCounts($whereTo);\n\t }\n\t return views;\n\t },\n\t\n\t /** override to show counts, what's deleted/hidden, and links to toggle those */\n\t _renderCounts: function ($whereTo) {\n\t $whereTo = $whereTo instanceof jQuery ? $whereTo : this.$el;\n\t var html = this.templates.counts(this.model.toJSON(), this);\n\t return $whereTo.find('> .controls .subtitle').html(html);\n\t },\n\t\n\t /** render the tags sub-view controller */\n\t _renderTags: function ($where) {\n\t var panel = this;\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.controls .tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // show hide sub-view tag editors when this is shown/hidden\n\t onshow: function () {\n\t panel.toggleHDATagEditors(true, panel.fxSpeed);\n\t },\n\t onhide: function () {\n\t panel.toggleHDATagEditors(false, panel.fxSpeed);\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit history tags'),\n\t classes: 'history-tag-btn',\n\t faIcon: 'fa-tags'\n\t }).appendTo($where.find('.controls .actions'))\n\t });\n\t },\n\t /** render the annotation sub-view controller */\n\t _renderAnnotation: function ($where) {\n\t var panel = this;\n\t this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n\t model: this.model,\n\t el: $where.find('.controls .annotation-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // show hide sub-view view annotation editors when this is shown/hidden\n\t onshow: function () {\n\t panel.toggleHDAAnnotationEditors(true, panel.fxSpeed);\n\t },\n\t onhide: function () {\n\t panel.toggleHDAAnnotationEditors(false, panel.fxSpeed);\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit history annotation'),\n\t classes: 'history-annotate-btn',\n\t faIcon: 'fa-comment'\n\t }).appendTo($where.find('.controls .actions'))\n\t });\n\t },\n\t\n\t /** Set up HistoryViewEdit js/widget behaviours\n\t * In this override, make the name editable\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t if (!this.model) {\n\t return;\n\t }\n\t\n\t // anon users shouldn't have access to any of the following\n\t if (!Galaxy.user || Galaxy.user.isAnonymous() || Galaxy.user.id !== this.model.get('user_id')) {\n\t return;\n\t }\n\t\n\t var panel = this,\n\t nameSelector = '> .controls .name';\n\t $where.find(nameSelector).attr('title', _l('Click to rename history')).tooltip({ placement: 'bottom' }).make_text_editable({\n\t on_finish: function (newName) {\n\t var previousName = panel.model.get('name');\n\t if (newName && newName !== previousName) {\n\t panel.$el.find(nameSelector).text(newName);\n\t panel.model.save({ name: newName }).fail(function () {\n\t panel.$el.find(nameSelector).text(panel.model.previous('name'));\n\t });\n\t } else {\n\t panel.$el.find(nameSelector).text(previousName);\n\t }\n\t }\n\t });\n\t },\n\t\n\t /** return a new popup menu for choosing a multi selection action\n\t * ajax calls made for multiple datasets are queued\n\t */\n\t multiselectActions: function () {\n\t var panel = this,\n\t actions = [{ html: _l('Hide datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.hide;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Unhide datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.unhide;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Delete datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype['delete'];\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }, { html: _l('Undelete datasets'), func: function () {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.undelete;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }];\n\t if (panel.purgeAllowed) {\n\t actions.push({\n\t html: _l('Permanently delete datasets'), func: function () {\n\t if (confirm(_l('This will permanently remove the data in your datasets. Are you sure?'))) {\n\t var action = HDA_MODEL.HistoryDatasetAssociation.prototype.purge;\n\t panel.getSelectedModels().ajaxQueue(action);\n\t }\n\t }\n\t });\n\t }\n\t actions = actions.concat(panel._collectionActions());\n\t return actions;\n\t },\n\t\n\t /** */\n\t _collectionActions: function () {\n\t var panel = this;\n\t return [{ html: _l('Build Dataset List'), func: function () {\n\t panel.buildCollection(\"list\");\n\t }\n\t },\n\t // TODO: Only show quick pair if two things selected.\n\t { html: _l('Build Dataset Pair'), func: function () {\n\t panel.buildCollection(\"paired\");\n\t }\n\t }, { html: _l('Build List of Dataset Pairs'), func: function () {\n\t panel.buildCollection(\"list:paired\");\n\t }\n\t }];\n\t },\n\t\n\t buildCollection: function (collectionType, selection, hideSourceItems) {\n\t var panel = this;\n\t var selection = selection || panel.getSelectedModels();\n\t var hideSourceItems = hideSourceItems || false;\n\t var createFunc;\n\t if (collectionType == \"list\") {\n\t createFunc = LIST_COLLECTION_CREATOR.createListCollection;\n\t } else if (collectionType == \"paired\") {\n\t createFunc = PAIR_COLLECTION_CREATOR.createPairCollection;\n\t } else if (collectionType == \"list:paired\") {\n\t createFunc = LIST_OF_PAIRS_COLLECTION_CREATOR.createListOfPairsCollection;\n\t } else {\n\t console.warn(\"Unknown collectionType encountered \" + collectionType);\n\t }\n\t createFunc(selection, hideSourceItems).done(function () {\n\t panel.model.refresh();\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** In this override, add purgeAllowed and whether tags/annotation editors should be shown */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t _.extend(options, {\n\t purgeAllowed: this.purgeAllowed,\n\t tagsEditorShown: this.tagsEditor && !this.tagsEditor.hidden,\n\t annotationEditorShown: this.annotationEditor && !this.annotationEditor.hidden\n\t });\n\t return options;\n\t },\n\t\n\t /** If this item is deleted and we're not showing deleted items, remove the view\n\t * @param {Model} the item model to check\n\t */\n\t _handleItemDeletedChange: function (itemModel) {\n\t if (itemModel.get('deleted')) {\n\t this._handleItemDeletion(itemModel);\n\t } else {\n\t this._handleItemUndeletion(itemModel);\n\t }\n\t this._renderCounts();\n\t },\n\t\n\t _handleItemDeletion: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.deleted += 1;\n\t contentsShown.active -= 1;\n\t if (!this.model.contents.includeDeleted) {\n\t this.removeItemView(itemModel);\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t _handleItemUndeletion: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.deleted -= 1;\n\t if (!this.model.contents.includeDeleted) {\n\t contentsShown.active -= 1;\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t /** If this item is hidden and we're not showing hidden items, remove the view\n\t * @param {Model} the item model to check\n\t */\n\t _handleItemVisibleChange: function (itemModel) {\n\t if (itemModel.hidden()) {\n\t this._handleItemHidden(itemModel);\n\t } else {\n\t this._handleItemUnhidden(itemModel);\n\t }\n\t this._renderCounts();\n\t },\n\t\n\t _handleItemHidden: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.hidden += 1;\n\t contentsShown.active -= 1;\n\t if (!this.model.contents.includeHidden) {\n\t this.removeItemView(itemModel);\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t _handleItemUnhidden: function (itemModel) {\n\t var contentsShown = this.model.get('contents_active');\n\t contentsShown.hidden -= 1;\n\t if (!this.model.contents.includeHidden) {\n\t contentsShown.active -= 1;\n\t }\n\t this.model.set('contents_active', contentsShown);\n\t },\n\t\n\t /** toggle the visibility of each content's tagsEditor applying all the args sent to this function */\n\t toggleHDATagEditors: function (showOrHide, speed) {\n\t _.each(this.views, function (view) {\n\t if (view.tagsEditor) {\n\t view.tagsEditor.toggle(showOrHide, speed);\n\t }\n\t });\n\t },\n\t\n\t /** toggle the visibility of each content's annotationEditor applying all the args sent to this function */\n\t toggleHDAAnnotationEditors: function (showOrHide, speed) {\n\t _.each(this.views, function (view) {\n\t if (view.annotationEditor) {\n\t view.annotationEditor.toggle(showOrHide, speed);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .show-selectors-btn': 'toggleSelectors',\n\t 'click .toggle-deleted-link': function (ev) {\n\t this.toggleShowDeleted();\n\t },\n\t 'click .toggle-hidden-link': function (ev) {\n\t this.toggleShowHidden();\n\t }\n\t }),\n\t\n\t // ------------------------------------------------------------------------ search\n\t _renderSearchProgress: function (limit, offset) {\n\t var stop = limit + offset;\n\t return this.$('> .controls .subtitle').html(['', _l('Searching '), stop, '/', this.model.contentsShown(), ''].join(''));\n\t },\n\t\n\t /** override to display number found in subtitle */\n\t _renderSearchFindings: function () {\n\t this.$('> .controls .subtitle').html([_l('Found'), this.views.length].join(' '));\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ as drop target\n\t /** turn all the drag and drop handlers on and add some help text above the drop area */\n\t dropTargetOn: function () {\n\t if (this.dropTarget) {\n\t return this;\n\t }\n\t this.dropTarget = true;\n\t\n\t //TODO: to init\n\t var dropHandlers = {\n\t 'dragenter': _.bind(this.dragenter, this),\n\t 'dragover': _.bind(this.dragover, this),\n\t 'dragleave': _.bind(this.dragleave, this),\n\t 'drop': _.bind(this.drop, this)\n\t };\n\t\n\t var $dropTarget = this._renderDropTarget();\n\t this.$list().before([this._renderDropTargetHelp(), $dropTarget]);\n\t for (var evName in dropHandlers) {\n\t if (dropHandlers.hasOwnProperty(evName)) {\n\t //console.debug( evName, dropHandlers[ evName ] );\n\t $dropTarget.on(evName, dropHandlers[evName]);\n\t }\n\t }\n\t return this;\n\t },\n\t\n\t /** render a box to serve as a 'drop here' area on the history */\n\t _renderDropTarget: function () {\n\t this.$('.history-drop-target').remove();\n\t return $('
                                  ').addClass('history-drop-target');\n\t },\n\t\n\t /** tell the user how it works */\n\t _renderDropTargetHelp: function () {\n\t this.$('.history-drop-target-help').remove();\n\t return $('
                                  ').addClass('history-drop-target-help').text(_l('Drag datasets here to copy them to the current history'));\n\t },\n\t\n\t /** shut down drag and drop event handlers and remove drop target */\n\t dropTargetOff: function () {\n\t if (!this.dropTarget) {\n\t return this;\n\t }\n\t //this.log( 'dropTargetOff' );\n\t this.dropTarget = false;\n\t var dropTarget = this.$('.history-drop-target').get(0);\n\t for (var evName in this._dropHandlers) {\n\t if (this._dropHandlers.hasOwnProperty(evName)) {\n\t dropTarget.off(evName, this._dropHandlers[evName]);\n\t }\n\t }\n\t this.$('.history-drop-target').remove();\n\t this.$('.history-drop-target-help').remove();\n\t return this;\n\t },\n\t /** toggle the target on/off */\n\t dropTargetToggle: function () {\n\t if (this.dropTarget) {\n\t this.dropTargetOff();\n\t } else {\n\t this.dropTargetOn();\n\t }\n\t return this;\n\t },\n\t\n\t dragenter: function (ev) {\n\t //console.debug( 'dragenter:', this, ev );\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t this.$('.history-drop-target').css('border', '2px solid black');\n\t },\n\t dragover: function (ev) {\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t },\n\t dragleave: function (ev) {\n\t //console.debug( 'dragleave:', this, ev );\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t this.$('.history-drop-target').css('border', '1px dashed black');\n\t },\n\t /** when (text) is dropped try to parse as json and trigger an event */\n\t drop: function (ev) {\n\t ev.preventDefault();\n\t //ev.stopPropagation();\n\t\n\t var self = this;\n\t var dataTransfer = ev.originalEvent.dataTransfer;\n\t var data = dataTransfer.getData(\"text\");\n\t\n\t dataTransfer.dropEffect = 'move';\n\t try {\n\t data = JSON.parse(data);\n\t } catch (err) {\n\t self.warn('error parsing JSON from drop:', data);\n\t }\n\t\n\t self.trigger('droptarget:drop', ev, data, self);\n\t return false;\n\t },\n\t\n\t /** handler that copies data into the contents */\n\t dataDropped: function (data) {\n\t var self = this;\n\t // HDA: dropping will copy it to the history\n\t if (_.isObject(data) && data.model_class === 'HistoryDatasetAssociation' && data.id) {\n\t if (self.contents.currentPage !== 0) {\n\t return self.contents.fetchPage(0).then(function () {\n\t return self.model.contents.copy(data.id);\n\t });\n\t }\n\t return self.model.contents.copy(data.id);\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t // ........................................................................ misc\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'HistoryViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t HistoryViewEdit.prototype.templates = function () {\n\t\n\t var countsTemplate = BASE_MVC.wrapTemplate(['<% var shown = Math.max( view.views.length, history.contents_active.active ) %>', '<% if( shown ){ %>', '', '<%- shown %> ', _l('shown'), '', '<% } %>', '<% if( history.contents_active.deleted ){ %>', '', '<% if( view.model.contents.includeDeleted ){ %>', '', _l('hide deleted'), '', '<% } else { %>', '<%- history.contents_active.deleted %> ', '', _l('deleted'), '', '<% } %>', '', '<% } %>', '<% if( history.contents_active.hidden ){ %>', '', '<% if( view.model.contents.includeHidden ){ %>', '', _l('hide hidden'), '', '<% } else { %>', '<%- history.contents_active.hidden %> ', '', _l('hidden'), '', '<% } %>', '', '<% } %>'], 'history');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t counts: countsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HistoryViewEdit: HistoryViewEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 131 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(89), __webpack_require__(62), __webpack_require__(61), __webpack_require__(63), __webpack_require__(85), __webpack_require__(87), __webpack_require__(93), __webpack_require__(92), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6), __webpack_require__(96)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_VIEW, HISTORY_MODEL, HISTORY_CONTENTS, HISTORY_PREFS, HDA_LI, HDCA_LI, USER, ERROR_MODAL, faIconButton, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class non-editable, read-only View/Controller for a history model.\n\t * Allows:\n\t * changing the loaded history\n\t * displaying data, info, and download\n\t * tracking history attrs: size, tags, annotations, name, etc.\n\t * Does not allow:\n\t * changing the name\n\t */\n\t\n\t var _super = LIST_VIEW.ModelListPanel;\n\t var HistoryView = _super.extend(\n\t /** @lends HistoryView.prototype */{\n\t _logNamespace: 'history',\n\t\n\t /** class to use for constructing the HDA views */\n\t HDAViewClass: HDA_LI.HDAListItemView,\n\t /** class to use for constructing the HDCA views */\n\t HDCAViewClass: HDCA_LI.HDCAListItemView,\n\t /** class to used for constructing collection of sub-view models */\n\t collectionClass: HISTORY_CONTENTS.HistoryContents,\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'contents',\n\t\n\t tagName: 'div',\n\t className: _super.prototype.className + ' history-panel',\n\t\n\t /** string to display when the collection is empty */\n\t emptyMsg: _l('This history is empty'),\n\t /** displayed when no items match the search terms */\n\t noneFoundMsg: _l('No matching datasets found'),\n\t /** string used for search placeholder */\n\t searchPlaceholder: _l('search datasets'),\n\t\n\t /** @type {Number} ms to wait after history load to fetch/decorate hdcas with element_count */\n\t FETCH_COLLECTION_COUNTS_DELAY: 2000,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, bind listeners.\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t // ---- instance vars\n\t // control contents/behavior based on where (and in what context) the panel is being used\n\t /** where should pages from links be displayed? (default to new tab/window) */\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t },\n\t\n\t /** create and return a collection for when none is initially passed */\n\t _createDefaultCollection: function () {\n\t // override\n\t return new this.collectionClass([], { history: this.model });\n\t },\n\t\n\t /** In this override, clear the update timer on the model */\n\t freeModel: function () {\n\t _super.prototype.freeModel.call(this);\n\t if (this.model) {\n\t this.model.clearUpdateTimeout();\n\t }\n\t return this;\n\t },\n\t\n\t /** create any event listeners for the panel\n\t * @fires: rendered:initial on the first render\n\t * @fires: empty-history when switching to a history with no contents or creating a new history\n\t */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t this.on({\n\t error: function (model, xhr, options, msg, details) {\n\t this.errorHandler(model, xhr, options, msg, details);\n\t },\n\t 'loading-done': function () {\n\t var self = this;\n\t // after the initial load, decorate with more time consuming fields (like HDCA element_counts)\n\t _.delay(function () {\n\t self.model.contents.fetchCollectionCounts();\n\t }, self.FETCH_COLLECTION_COUNTS_DELAY);\n\t },\n\t 'views:ready view:attached view:removed': function (view) {\n\t this._renderSelectButton();\n\t },\n\t 'view:attached': function (view) {\n\t this.scrollTo(0);\n\t }\n\t });\n\t // this.on( 'all', function(){ console.debug( arguments ); });\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading history/hda models\n\t /** load the history with the given id then it's contents, sending ajax options to both */\n\t loadHistory: function (historyId, options, contentsOptions) {\n\t contentsOptions = _.extend(contentsOptions || { silent: true });\n\t this.info('loadHistory:', historyId, options, contentsOptions);\n\t var self = this;\n\t self.setModel(new HISTORY_MODEL.History({ id: historyId }));\n\t\n\t contentsOptions.silent = true;\n\t self.trigger('loading');\n\t return self.model.fetchWithContents(options, contentsOptions).always(function () {\n\t self.render();\n\t self.trigger('loading-done');\n\t });\n\t },\n\t\n\t /** convenience alias to the model. Updates the item list only (not the history) */\n\t refreshContents: function (options) {\n\t if (this.model) {\n\t return this.model.refresh(options);\n\t }\n\t // may have callbacks - so return an empty promise\n\t return $.when();\n\t },\n\t\n\t /** Override to reset web storage when the id changes (since it needs the id) */\n\t _setUpCollectionListeners: function () {\n\t _super.prototype._setUpCollectionListeners.call(this);\n\t return this.listenTo(this.collection, {\n\t // 'all' : function(){ console.log( this.collection + ':', arguments ); },\n\t 'fetching-more': function () {\n\t this._toggleContentsLoadingIndicator(true);\n\t this.$emptyMessage().hide();\n\t },\n\t 'fetching-more-done': function () {\n\t this._toggleContentsLoadingIndicator(false);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel rendering\n\t /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n\t _showLoadingIndicator: function (msg, speed, callback) {\n\t var $indicator = $('
                                  ');\n\t this.$el.html($indicator.text(msg).slideDown(!_.isUndefined(speed) ? speed : this.fxSpeed));\n\t },\n\t\n\t /** hide the loading indicator */\n\t _hideLoadingIndicator: function (speed) {\n\t // make speed a bit slower to compensate for slow rendering of up to 500 contents\n\t this.$('.loading-indicator').slideUp(!_.isUndefined(speed) ? speed : this.fxSpeed + 200, function () {\n\t $(this).remove();\n\t });\n\t },\n\t\n\t /** In this override, add a btn to toggle the selectors */\n\t _buildNewRender: function () {\n\t var $newRender = _super.prototype._buildNewRender.call(this);\n\t this._renderSelectButton($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** button for starting select mode */\n\t _renderSelectButton: function ($where) {\n\t $where = $where || this.$el;\n\t // do not render selector option if no actions\n\t if (!this.multiselectActions().length) {\n\t return null;\n\t }\n\t // do not render (and remove even) if nothing to select\n\t if (!this.views.length) {\n\t this.hideSelectors();\n\t $where.find('.controls .actions .show-selectors-btn').remove();\n\t return null;\n\t }\n\t // don't bother rendering if there's one already\n\t var $existing = $where.find('.controls .actions .show-selectors-btn');\n\t if ($existing.length) {\n\t return $existing;\n\t }\n\t\n\t return faIconButton({\n\t title: _l('Operations on multiple datasets'),\n\t classes: 'show-selectors-btn',\n\t faIcon: 'fa-check-square-o'\n\t }).prependTo($where.find('.controls .actions'));\n\t },\n\t\n\t /** override to avoid showing intial empty message using contents_active */\n\t _renderEmptyMessage: function ($whereTo) {\n\t var self = this;\n\t var $emptyMsg = self.$emptyMessage($whereTo);\n\t\n\t var empty = self.model.get('contents_active').active <= 0;\n\t if (empty) {\n\t return $emptyMsg.empty().append(self.emptyMsg).show();\n\t } else if (self.searchFor && self.model.contents.haveSearchDetails() && !self.views.length) {\n\t return $emptyMsg.empty().append(self.noneFoundMsg).show();\n\t }\n\t $emptyMsg.hide();\n\t return $();\n\t },\n\t\n\t /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n\t $scrollContainer: function ($where) {\n\t // override or set via attributes.$scrollContainer\n\t return this.$list($where);\n\t },\n\t\n\t // ------------------------------------------------------------------------ subviews\n\t _toggleContentsLoadingIndicator: function (show) {\n\t if (!show) {\n\t this.$list().find('.contents-loading-indicator').remove();\n\t } else {\n\t this.$list().html('
                                  ' + '
                                  ');\n\t }\n\t },\n\t\n\t /** override to render pagination also */\n\t renderItems: function ($whereTo) {\n\t // console.log( this + '.renderItems-----------------', new Date() );\n\t $whereTo = $whereTo || this.$el;\n\t var self = this;\n\t var $list = self.$list($whereTo);\n\t\n\t // TODO: bootstrap hack to remove orphaned tooltips\n\t $('.tooltip').remove();\n\t\n\t $list.empty();\n\t self.views = [];\n\t\n\t var models = self._filterCollection();\n\t if (models.length) {\n\t self._renderPagination($whereTo);\n\t self.views = self._renderSomeItems(models, $list);\n\t } else {\n\t // TODO: consolidate with _renderPagination above by (???) passing in models/length?\n\t $whereTo.find('> .controls .list-pagination').empty();\n\t }\n\t self._renderEmptyMessage($whereTo).toggle(!models.length);\n\t\n\t self.trigger('views:ready', self.views);\n\t return self.views;\n\t },\n\t\n\t /** render pagination controls if not searching and contents says we're paginating */\n\t _renderPagination: function ($whereTo) {\n\t var $paginationControls = $whereTo.find('> .controls .list-pagination');\n\t if (this.searchFor || !this.model.contents.shouldPaginate()) return $paginationControls.empty();\n\t\n\t $paginationControls.html(this.templates.pagination({\n\t // pagination is 1-based for the user\n\t current: this.model.contents.currentPage + 1,\n\t last: this.model.contents.getLastPage() + 1\n\t }, this));\n\t $paginationControls.find('select.pages').tooltip();\n\t return $paginationControls;\n\t },\n\t\n\t /** render a subset of the entire collection (client-side pagination) */\n\t _renderSomeItems: function (models, $list) {\n\t var self = this;\n\t var views = [];\n\t $list.append(models.map(function (m) {\n\t var view = self._createItemView(m);\n\t views.push(view);\n\t return self._renderItemView$el(view);\n\t }));\n\t return views;\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** in this override, check if the contents would also display based on includeDeleted/hidden */\n\t _filterItem: function (model) {\n\t var self = this;\n\t var contents = self.model.contents;\n\t return (contents.includeHidden || !model.hidden()) && (contents.includeDeleted || !model.isDeletedOrPurged()) && _super.prototype._filterItem.call(self, model);\n\t },\n\t\n\t /** In this override, since history contents are mixed,\n\t * get the appropo view class based on history_content_type\n\t */\n\t _getItemViewClass: function (model) {\n\t var contentType = model.get(\"history_content_type\");\n\t switch (contentType) {\n\t case 'dataset':\n\t return this.HDAViewClass;\n\t case 'dataset_collection':\n\t return this.HDCAViewClass;\n\t }\n\t throw new TypeError('Unknown history_content_type: ' + contentType);\n\t },\n\t\n\t /** in this override, add a linktarget, and expand if id is in web storage */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t expanded: this.model.contents.storage.isExpanded(model.id),\n\t hasUser: this.model.ownedByCurrUser()\n\t });\n\t },\n\t\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t //TODO: send from content view: this.model.collection.storage.addExpanded\n\t // maintain a list of items whose bodies are expanded\n\t return panel.listenTo(view, {\n\t 'expanded': function (v) {\n\t panel.model.contents.storage.addExpanded(v.model);\n\t },\n\t 'collapsed': function (v) {\n\t panel.model.contents.storage.removeExpanded(v.model);\n\t }\n\t });\n\t },\n\t\n\t /** override to remove expandedIds from webstorage */\n\t collapseAll: function () {\n\t this.model.contents.storage.clearExpanded();\n\t _super.prototype.collapseAll.call(this);\n\t },\n\t\n\t // ------------------------------------------------------------------------ selection\n\t /** Override to correctly set the historyId of the new collection */\n\t getSelectedModels: function () {\n\t var collection = _super.prototype.getSelectedModels.call(this);\n\t collection.historyId = this.collection.historyId;\n\t return collection;\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .show-selectors-btn': 'toggleSelectors',\n\t 'click > .controls .prev': '_clickPrevPage',\n\t 'click > .controls .next': '_clickNextPage',\n\t 'change > .controls .pages': '_changePageSelect',\n\t // allow (error) messages to be clicked away\n\t 'click .messages [class$=message]': 'clearMessages'\n\t }),\n\t\n\t _clickPrevPage: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t this.model.contents.fetchPrevPage();\n\t },\n\t\n\t _clickNextPage: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t this.model.contents.fetchNextPage();\n\t },\n\t\n\t _changePageSelect: function (ev) {\n\t this.model.clearUpdateTimeout();\n\t var page = $(ev.currentTarget).val();\n\t this.model.contents.fetchPage(page);\n\t },\n\t\n\t /** Toggle and store the deleted visibility and re-render items\n\t * @returns {Boolean} new setting\n\t */\n\t toggleShowDeleted: function (show, options) {\n\t show = show !== undefined ? show : !this.model.contents.includeDeleted;\n\t var self = this;\n\t var contents = self.model.contents;\n\t contents.setIncludeDeleted(show, options);\n\t self.trigger('show-deleted', show);\n\t\n\t contents.fetchCurrentPage({ renderAll: true });\n\t return show;\n\t },\n\t\n\t /** Toggle and store whether to render explicity hidden contents\n\t * @returns {Boolean} new setting\n\t */\n\t toggleShowHidden: function (show, store, options) {\n\t // console.log( 'toggleShowHidden', show, store );\n\t show = show !== undefined ? show : !this.model.contents.includeHidden;\n\t var self = this;\n\t var contents = self.model.contents;\n\t contents.setIncludeHidden(show, options);\n\t self.trigger('show-hidden', show);\n\t\n\t contents.fetchCurrentPage({ renderAll: true });\n\t return show;\n\t },\n\t\n\t /** On the first search, if there are no details - load them, then search */\n\t _firstSearch: function (searchFor) {\n\t var self = this;\n\t var inputSelector = '> .controls .search-input';\n\t this.log('onFirstSearch', searchFor);\n\t\n\t // if the contents already have enough details to search, search and return now\n\t if (self.model.contents.haveSearchDetails()) {\n\t self.searchItems(searchFor);\n\t return;\n\t }\n\t\n\t // otherwise, load the details progressively here\n\t self.$(inputSelector).searchInput('toggle-loading');\n\t // set this now so that only results will show during progress\n\t self.searchFor = searchFor;\n\t var xhr = self.model.contents.progressivelyFetchDetails({ silent: true }).progress(function (response, limit, offset) {\n\t self.renderItems();\n\t self.trigger('search:loading-progress', limit, offset);\n\t }).always(function () {\n\t self.$el.find(inputSelector).searchInput('toggle-loading');\n\t }).done(function () {\n\t self.searchItems(searchFor, 'force');\n\t });\n\t },\n\t\n\t /** clear the search filters and show all views that are normally shown */\n\t clearSearch: function (searchFor) {\n\t var self = this;\n\t if (!self.searchFor) return self;\n\t //self.log( 'onSearchClear', self );\n\t self.searchFor = '';\n\t self.trigger('search:clear', self);\n\t self.$('> .controls .search-query').val('');\n\t // NOTE: silent + render prevents collection update event with merge only\n\t // - which causes an empty page due to event handler above\n\t self.model.contents.fetchCurrentPage({ silent: true }).done(function () {\n\t self.renderItems();\n\t });\n\t return self;\n\t },\n\t\n\t // ........................................................................ error handling\n\t /** Event handler for errors (from the panel, the history, or the history's contents)\n\t * Alternately use two strings for model and xhr to use custom message and title (respectively)\n\t * @param {Model or View} model the (Backbone) source of the error\n\t * @param {XMLHTTPRequest} xhr any ajax obj. assoc. with the error\n\t * @param {Object} options the options map commonly used with bbone ajax\n\t */\n\t errorHandler: function (model, xhr, options) {\n\t //TODO: to mixin or base model\n\t // interrupted ajax or no connection\n\t if (xhr && xhr.status === 0 && xhr.readyState === 0) {\n\t // return ERROR_MODAL.offlineErrorModal();\n\t // fail silently\n\t return;\n\t }\n\t // otherwise, leave something to report in the console\n\t this.error(model, xhr, options);\n\t // and feedback to a modal\n\t // if sent two strings (and possibly details as 'options'), use those as message and title\n\t if (_.isString(model) && _.isString(xhr)) {\n\t var message = model;\n\t var title = xhr;\n\t return ERROR_MODAL.errorModal(message, title, options);\n\t }\n\t // bad gateway\n\t // TODO: possibly to global handler\n\t if (xhr && xhr.status === 502) {\n\t return ERROR_MODAL.badGatewayErrorModal();\n\t }\n\t return ERROR_MODAL.ajaxErrorModal(model, xhr, options);\n\t },\n\t\n\t /** Remove all messages from the panel. */\n\t clearMessages: function (ev) {\n\t var $target = !_.isUndefined(ev) ? $(ev.currentTarget) : this.$messages().children('[class$=\"message\"]');\n\t $target.fadeOut(this.fxSpeed, function () {\n\t $(this).remove();\n\t });\n\t return this;\n\t },\n\t\n\t // ........................................................................ scrolling\n\t /** Scrolls the panel to show the content sub-view with the given hid.\n\t * @param {Integer} hid the hid of item to scroll into view\n\t * @returns {HistoryView} the panel\n\t */\n\t scrollToHid: function (hid) {\n\t return this.scrollToItem(_.first(this.viewsWhereModel({ hid: hid })));\n\t },\n\t\n\t // ........................................................................ misc\n\t /** utility for adding -st, -nd, -rd, -th to numbers */\n\t ordinalIndicator: function (number) {\n\t var numStr = number + '';\n\t switch (numStr.charAt(numStr.length - 1)) {\n\t case '1':\n\t return numStr + 'st';\n\t case '2':\n\t return numStr + 'nd';\n\t case '3':\n\t return numStr + 'rd';\n\t default:\n\t return numStr + 'th';\n\t }\n\t },\n\t\n\t /** Return a string rep of the history */\n\t toString: function () {\n\t return 'HistoryView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t HistoryView.prototype.templates = function () {\n\t\n\t var mainTemplate = BASE_MVC.wrapTemplate([\n\t // temp container\n\t '
                                  ', '
                                  ', '
                                    ', '
                                    ', '
                                    ']);\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                                    ', '
                                    ', '
                                    <%- history.name %>
                                    ', '
                                    ', '
                                    ', '
                                    <%- history.nice_size %>
                                    ', '
                                    ', '
                                    ', '<% if( history.deleted && history.purged ){ %>', '
                                    ', _l('This history has been purged and deleted'), '
                                    ', '<% } else if( history.deleted ){ %>', '
                                    ', _l('This history has been deleted'), '
                                    ', '<% } else if( history.purged ){ %>', '
                                    ', _l('This history has been purged'), '
                                    ', '<% } %>', '<% if( history.message ){ %>',\n\t // should already be localized\n\t '
                                    messagesmall\">', '<%= history.message.text %>', '
                                    ', '<% } %>', '
                                    ',\n\t\n\t // add tags and annotations\n\t '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '', '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    '], 'history');\n\t\n\t var paginationTemplate = BASE_MVC.wrapTemplate(['', '', ''], 'pages');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t el: mainTemplate,\n\t controls: controlsTemplate,\n\t pagination: paginationTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HistoryView: HistoryView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 132 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(18), __webpack_require__(84), __webpack_require__(7), __webpack_require__(6), __webpack_require__(42)], __WEBPACK_AMD_DEFINE_RESULT__ = function (PopupMenu, historyCopyDialog, BASE_MVC, _l, Webhooks) {\n\t\n\t 'use strict';\n\t\n\t // ============================================================================\n\t\n\t var menu = [{\n\t html: _l('History Lists'),\n\t header: true\n\t }, {\n\t html: _l('Saved Histories'),\n\t href: 'histories/list',\n\t target: '_top'\n\t\n\t }, {\n\t html: _l('Histories Shared with Me'),\n\t href: 'histories/list_shared',\n\t target: '_top'\n\t }, {\n\t html: _l('Current History'),\n\t header: true,\n\t anon: true\n\t }, {\n\t html: _l('Create New'),\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel) {\n\t Galaxy.currHistoryPanel.createNewHistory();\n\t }\n\t }\n\t }, {\n\t html: _l('Copy History'),\n\t func: function () {\n\t historyCopyDialog(Galaxy.currHistoryPanel.model).done(function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }, {\n\t html: _l('Share or Publish'),\n\t href: 'history/sharing'\n\t }, {\n\t html: _l('Show Structure'),\n\t href: 'history/display_structured',\n\t anon: true\n\t }, {\n\t html: _l('Extract Workflow'),\n\t href: 'workflow/build_from_current_history'\n\t }, {\n\t html: _l('Delete'),\n\t anon: true,\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete the current history?'))) {\n\t galaxy_main.window.location.href = 'history/delete?id=' + Galaxy.currHistoryPanel.model.id;\n\t }\n\t }\n\t }, {\n\t html: _l('Delete Permanently'),\n\t purge: true,\n\t anon: true,\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete the current history permanently? This cannot be undone.'))) {\n\t galaxy_main.window.location.href = 'history/delete?purge=True&id=' + Galaxy.currHistoryPanel.model.id;\n\t }\n\t }\n\t }, {\n\t html: _l('Dataset Actions'),\n\t header: true,\n\t anon: true\n\t }, {\n\t html: _l('Copy Datasets'),\n\t href: 'dataset/copy_datasets'\n\t }, {\n\t html: _l('Dataset Security'),\n\t href: 'root/history_set_default_permissions'\n\t }, {\n\t html: _l('Resume Paused Jobs'),\n\t href: 'history/resume_paused_jobs?current=True',\n\t anon: true\n\t }, {\n\t html: _l('Collapse Expanded Datasets'),\n\t func: function () {\n\t if (Galaxy && Galaxy.currHistoryPanel) {\n\t Galaxy.currHistoryPanel.collapseAll();\n\t }\n\t }\n\t }, {\n\t html: _l('Unhide Hidden Datasets'),\n\t anon: true,\n\t func: function () {\n\t // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really unhide all hidden datasets?'))) {\n\t $.post(Galaxy.root + \"history/adjust_hidden\", { 'user_action': 'unhide' }, function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }\n\t }, {\n\t html: _l('Delete Hidden Datasets'),\n\t anon: true,\n\t func: function () {\n\t // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n\t if (Galaxy && Galaxy.currHistoryPanel && confirm(_l('Really delete all hidden datasets?'))) {\n\t $.post(Galaxy.root + \"history/adjust_hidden\", { 'user_action': 'delete' }, function () {\n\t Galaxy.currHistoryPanel.loadCurrentHistory();\n\t });\n\t }\n\t }\n\t }, {\n\t html: _l('Purge Deleted Datasets'),\n\t confirm: _l('Really delete all deleted datasets permanently? This cannot be undone.'),\n\t href: 'history/purge_deleted_datasets',\n\t purge: true,\n\t anon: true\n\t }, {\n\t html: _l('Downloads'),\n\t header: true\n\t }, {\n\t html: _l('Export Tool Citations'),\n\t href: 'history/citations',\n\t anon: true\n\t }, {\n\t html: _l('Export History to File'),\n\t href: 'history/export_archive?preview=True',\n\t anon: true\n\t }, {\n\t html: _l('Other Actions'),\n\t header: true\n\t }, {\n\t html: _l('Import from File'),\n\t href: 'history/import_archive'\n\t }];\n\t\n\t // Webhooks\n\t Webhooks.add({\n\t url: 'api/webhooks/history-menu/all',\n\t async: false, // (hypothetically) slows down the performance\n\t callback: function (webhooks) {\n\t var webhooks_menu = [];\n\t\n\t $.each(webhooks.models, function (index, model) {\n\t var webhook = model.toJSON();\n\t if (webhook.activate) {\n\t webhooks_menu.push({\n\t html: _l(webhook.config.title),\n\t // func: function() {},\n\t anon: true\n\t });\n\t }\n\t });\n\t\n\t if (webhooks_menu.length > 0) {\n\t webhooks_menu.unshift({\n\t html: _l('Webhooks'),\n\t header: true\n\t });\n\t $.merge(menu, webhooks_menu);\n\t }\n\t }\n\t });\n\t\n\t function buildMenu(isAnon, purgeAllowed, urlRoot) {\n\t return _.clone(menu).filter(function (menuOption) {\n\t if (isAnon && !menuOption.anon) {\n\t return false;\n\t }\n\t if (!purgeAllowed && menuOption.purge) {\n\t return false;\n\t }\n\t\n\t //TODO:?? hard-coded galaxy_main\n\t if (menuOption.href) {\n\t menuOption.href = urlRoot + menuOption.href;\n\t menuOption.target = menuOption.target || 'galaxy_main';\n\t }\n\t\n\t if (menuOption.confirm) {\n\t menuOption.func = function () {\n\t if (confirm(menuOption.confirm)) {\n\t galaxy_main.location = menuOption.href;\n\t }\n\t };\n\t }\n\t return true;\n\t });\n\t }\n\t\n\t var create = function ($button, options) {\n\t options = options || {};\n\t var isAnon = options.anonymous === undefined ? true : options.anonymous,\n\t purgeAllowed = options.purgeAllowed || false,\n\t menu = buildMenu(isAnon, purgeAllowed, Galaxy.root);\n\t //console.debug( 'menu:', menu );\n\t return new PopupMenu($button, menu);\n\t };\n\t\n\t // ============================================================================\n\t return create;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 133 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** Renders the collection uploader rows */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(41), __webpack_require__(68), __webpack_require__(21), __webpack_require__(22)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, UploadModel, UploadSettings, Popover, Select) {\n\t return Backbone.View.extend({\n\t /** Dictionary of upload states and associated icons */\n\t status_classes: {\n\t init: 'upload-icon-button fa fa-trash-o',\n\t queued: 'upload-icon fa fa-spinner fa-spin',\n\t running: 'upload-icon fa fa-spinner fa-spin',\n\t success: 'upload-icon-button fa fa-check',\n\t error: 'upload-icon-button fa fa-exclamation-triangle'\n\t },\n\t\n\t initialize: function (app, options) {\n\t var self = this;\n\t this.app = app;\n\t this.model = options.model;\n\t this.setElement(this._template(options.model));\n\t this.$mode = this.$('.upload-mode');\n\t this.$title = this.$('.upload-title-extended');\n\t this.$text = this.$('.upload-text');\n\t this.$size = this.$('.upload-size');\n\t this.$info_text = this.$('.upload-info-text');\n\t this.$info_progress = this.$('.upload-info-progress');\n\t this.$text_content = this.$('.upload-text-content');\n\t this.$symbol = this.$('.upload-symbol');\n\t this.$progress_bar = this.$('.upload-progress-bar');\n\t this.$percentage = this.$('.upload-percentage');\n\t\n\t // append popup to settings icon\n\t this.settings = new Popover.View({\n\t title: 'Upload configuration',\n\t container: this.$('.upload-settings'),\n\t placement: 'bottom'\n\t });\n\t\n\t // identify default genome and extension values\n\t var default_genome = this.app.select_genome.value();\n\t var default_extension = this.app.select_extension.value();\n\t\n\t // handle click event\n\t this.$symbol.on('click', function () {\n\t self._removeRow();\n\t });\n\t\n\t // handle text editing event\n\t this.$text_content.on('change input', function (e) {\n\t self.model.set({ 'url_paste': $(e.target).val(),\n\t 'file_size': $(e.target).val().length });\n\t });\n\t\n\t // model events\n\t this.listenTo(this.model, 'change:percentage', function () {\n\t self._refreshPercentage();\n\t });\n\t this.listenTo(this.model, 'change:status', function () {\n\t self._refreshStatus();\n\t });\n\t this.listenTo(this.model, 'change:info', function () {\n\t self._refreshInfo();\n\t });\n\t this.listenTo(this.model, 'change:file_size', function () {\n\t self._refreshFileSize();\n\t });\n\t this.listenTo(this.model, 'remove', function () {\n\t self.remove();\n\t });\n\t this.app.collection.on('reset', function () {\n\t self.remove();\n\t });\n\t },\n\t\n\t render: function () {\n\t var options = this.model.attributes;\n\t this.$title.html(_.escape(options.file_name));\n\t this.$size.html(Utils.bytesToString(options.file_size));\n\t this.$mode.removeClass().addClass('upload-mode').addClass('text-primary');\n\t if (options.file_mode == 'new') {\n\t this.$text.css({ 'width': this.$el.width() - 16 + 'px', 'top': this.$el.height() - 8 + 'px' }).show();\n\t this.$el.height(this.$el.height() - 8 + this.$text.height() + 16);\n\t this.$mode.addClass('fa fa-edit');\n\t } else if (options.file_mode == 'local') {\n\t this.$mode.addClass('fa fa-laptop');\n\t } else if (options.file_mode == 'ftp') {\n\t this.$mode.addClass('fa fa-folder-open-o');\n\t }\n\t },\n\t\n\t /** Refresh info text */\n\t _refreshInfo: function () {\n\t var info = this.model.get('info');\n\t if (info) {\n\t this.$info_text.html('Failed: ' + info).show();\n\t } else {\n\t this.$info_text.hide();\n\t }\n\t },\n\t\n\t /** Refresh percentage status */\n\t _refreshPercentage: function () {\n\t var percentage = parseInt(this.model.get('percentage'));\n\t this.$progress_bar.css({ width: percentage + '%' });\n\t this.$percentage.html(percentage != 100 ? percentage + '%' : 'Adding to history...');\n\t },\n\t\n\t /** Refresh status */\n\t _refreshStatus: function () {\n\t var status = this.model.get('status');\n\t this.$symbol.removeClass().addClass('upload-symbol').addClass(this.status_classes[status]);\n\t this.model.set('enabled', status == 'init');\n\t var enabled = this.model.get('enabled');\n\t this.$text_content.attr('disabled', !enabled);\n\t if (status == 'success') {\n\t this.$el.addClass('success');\n\t this.$percentage.html('100%');\n\t }\n\t if (status == 'error') {\n\t this.$el.addClass('danger');\n\t this.$info_progress.hide();\n\t }\n\t },\n\t\n\t /** Refresh file size */\n\t _refreshFileSize: function () {\n\t this.$size.html(Utils.bytesToString(this.model.get('file_size')));\n\t },\n\t\n\t /** Remove row */\n\t _removeRow: function () {\n\t if (['init', 'success', 'error'].indexOf(this.model.get('status')) !== -1) {\n\t this.app.collection.remove(this.model);\n\t }\n\t },\n\t\n\t /** Attach file info popup */\n\t _showSettings: function () {\n\t if (!this.settings.visible) {\n\t this.settings.empty();\n\t this.settings.append(new UploadSettings(this).$el);\n\t this.settings.show();\n\t } else {\n\t this.settings.hide();\n\t }\n\t },\n\t\n\t /** View template */\n\t _template: function (options) {\n\t return '
                                    ' + '' +\n '' +\n '' +\n '' +\n '' +\n '';\n },\n\n /** Template of table */\n _templateTable: function() {\n return 'Available files: ' +\n '' +\n '' +\n '  ' +\n '' +\n '' +\n '' +\n '
                                    ').append($checkbox)).append($('').append(parameter.title)));\n\t });\n\t this.$cover[this.model.get('enabled') && 'hide' || 'show']();\n\t }\n\t });\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 69 */,\n/* 70 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(jQuery, _) {/*\n\t galaxy upload plugins - requires FormData and XMLHttpRequest\n\t*/\n\t;(function ($) {\n\t // add event properties\n\t jQuery.event.props.push(\"dataTransfer\");\n\t\n\t /**\n\t Posts file data to the API\n\t */\n\t $.uploadpost = function (config) {\n\t // parse options\n\t var cnf = $.extend({}, {\n\t data: {},\n\t success: function () {},\n\t error: function () {},\n\t progress: function () {},\n\t url: null,\n\t maxfilesize: 2048,\n\t error_filesize: 'File exceeds 2GB. Please use a FTP client.',\n\t error_default: 'Please make sure the file is available.',\n\t error_server: 'Upload request failed.',\n\t error_login: 'Uploads require you to log in.'\n\t }, config);\n\t\n\t // link data\n\t var data = cnf.data;\n\t\n\t // check errors\n\t if (data.error_message) {\n\t cnf.error(data.error_message);\n\t return;\n\t }\n\t\n\t // construct form data\n\t var form = new FormData();\n\t for (var key in data.payload) {\n\t form.append(key, data.payload[key]);\n\t }\n\t\n\t // add files to submission\n\t var sizes = 0;\n\t for (var key in data.files) {\n\t var d = data.files[key];\n\t form.append(d.name, d.file, d.file.name);\n\t sizes += d.file.size;\n\t }\n\t\n\t // check file size, unless it's an ftp file\n\t if (sizes > 1048576 * cnf.maxfilesize) {\n\t cnf.error(cnf.error_filesize);\n\t return;\n\t }\n\t\n\t // prepare request\n\t xhr = new XMLHttpRequest();\n\t xhr.open('POST', cnf.url, true);\n\t xhr.setRequestHeader('Accept', 'application/json');\n\t xhr.setRequestHeader('Cache-Control', 'no-cache');\n\t xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n\t\n\t // captures state changes\n\t xhr.onreadystatechange = function () {\n\t // check for request completed, server connection closed\n\t if (xhr.readyState == xhr.DONE) {\n\t // parse response\n\t var response = null;\n\t if (xhr.responseText) {\n\t try {\n\t response = jQuery.parseJSON(xhr.responseText);\n\t } catch (e) {\n\t response = xhr.responseText;\n\t }\n\t }\n\t // pass any error to the error option\n\t if (xhr.status < 200 || xhr.status > 299) {\n\t var text = xhr.statusText;\n\t if (xhr.status == 403) {\n\t text = cnf.error_login;\n\t } else if (xhr.status == 0) {\n\t text = cnf.error_server;\n\t } else if (!text) {\n\t text = cnf.error_default;\n\t }\n\t cnf.error(text + ' (' + xhr.status + ')');\n\t } else {\n\t cnf.success(response);\n\t }\n\t }\n\t };\n\t\n\t // prepare upload progress\n\t xhr.upload.addEventListener('progress', function (e) {\n\t if (e.lengthComputable) {\n\t cnf.progress(Math.round(e.loaded * 100 / e.total));\n\t }\n\t }, false);\n\t\n\t // send request\n\t Galaxy.emit.debug('uploadbox::uploadpost()', 'Posting following data.', cnf);\n\t xhr.send(form);\n\t };\n\t\n\t /**\n\t Handles the upload events drag/drop etc.\n\t */\n\t $.fn.uploadinput = function (options) {\n\t // initialize\n\t var el = this;\n\t var opts = $.extend({}, {\n\t ondragover: function () {},\n\t ondragleave: function () {},\n\t onchange: function () {},\n\t multiple: false\n\t }, options);\n\t\n\t // append hidden upload field\n\t var $input = $('');\n\t el.append($input.change(function (e) {\n\t opts.onchange(e.target.files);\n\t $(this).val('');\n\t }));\n\t\n\t // drag/drop events\n\t el.on('drop', function (e) {\n\t opts.ondragleave(e);\n\t if (e.dataTransfer) {\n\t opts.onchange(e.dataTransfer.files);\n\t e.preventDefault();\n\t }\n\t });\n\t el.on('dragover', function (e) {\n\t e.preventDefault();\n\t opts.ondragover(e);\n\t });\n\t el.on('dragleave', function (e) {\n\t e.stopPropagation();\n\t opts.ondragleave(e);\n\t });\n\t\n\t // exports\n\t return {\n\t dialog: function () {\n\t $input.trigger('click');\n\t }\n\t };\n\t };\n\t\n\t /**\n\t Handles the upload queue and events such as drag/drop etc.\n\t */\n\t $.fn.uploadbox = function (options) {\n\t // parse options\n\t var opts = $.extend({}, {\n\t dragover: function () {},\n\t dragleave: function () {},\n\t announce: function (d) {},\n\t initialize: function (d) {},\n\t progress: function (d, m) {},\n\t success: function (d, m) {},\n\t error: function (d, m) {\n\t alert(m);\n\t },\n\t complete: function () {}\n\t }, options);\n\t\n\t // file queue\n\t var queue = {};\n\t\n\t // queue index/length counter\n\t var queue_index = 0;\n\t var queue_length = 0;\n\t\n\t // indicates if queue is currently running\n\t var queue_running = false;\n\t var queue_stop = false;\n\t\n\t // element\n\t var uploadinput = $(this).uploadinput({\n\t multiple: true,\n\t onchange: function (files) {\n\t add(files);\n\t },\n\t ondragover: options.ondragover,\n\t ondragleave: options.ondragleave\n\t });\n\t\n\t // add new files to upload queue\n\t function add(files) {\n\t if (files && files.length && !queue_running) {\n\t var current_index = queue_index;\n\t _.each(files, function (file, key) {\n\t if (file.mode !== 'new' && _.filter(queue, function (f) {\n\t return f.name === file.name && f.size === file.size;\n\t }).length) {\n\t file.duplicate = true;\n\t }\n\t });\n\t _.each(files, function (file) {\n\t if (!file.duplicate) {\n\t var index = String(queue_index++);\n\t queue[index] = file;\n\t opts.announce(index, queue[index]);\n\t queue_length++;\n\t }\n\t });\n\t return current_index;\n\t }\n\t }\n\t\n\t // remove file from queue\n\t function remove(index) {\n\t if (queue[index]) {\n\t delete queue[index];\n\t queue_length--;\n\t }\n\t }\n\t\n\t // process an upload, recursive\n\t function process() {\n\t // validate\n\t if (queue_length == 0 || queue_stop) {\n\t queue_stop = false;\n\t queue_running = false;\n\t opts.complete();\n\t return;\n\t } else {\n\t queue_running = true;\n\t }\n\t\n\t // get an identifier from the queue\n\t var index = -1;\n\t for (var key in queue) {\n\t index = key;\n\t break;\n\t }\n\t\n\t // get current file from queue\n\t var file = queue[index];\n\t\n\t // remove from queue\n\t remove(index);\n\t\n\t // create and submit data\n\t $.uploadpost({\n\t url: opts.url,\n\t data: opts.initialize(index),\n\t success: function (message) {\n\t opts.success(index, message);process();\n\t },\n\t error: function (message) {\n\t opts.error(index, message);process();\n\t },\n\t progress: function (percentage) {\n\t opts.progress(index, percentage);\n\t }\n\t });\n\t }\n\t\n\t /*\n\t public interface\n\t */\n\t\n\t // open file browser for selection\n\t function select() {\n\t uploadinput.dialog();\n\t }\n\t\n\t // remove all entries from queue\n\t function reset(index) {\n\t for (index in queue) {\n\t remove(index);\n\t }\n\t }\n\t\n\t // initiate upload process\n\t function start() {\n\t if (!queue_running) {\n\t queue_running = true;\n\t process();\n\t }\n\t }\n\t\n\t // stop upload process\n\t function stop() {\n\t queue_stop = true;\n\t }\n\t\n\t // set options\n\t function configure(options) {\n\t opts = $.extend({}, opts, options);\n\t return opts;\n\t }\n\t\n\t // verify browser compatibility\n\t function compatible() {\n\t return window.File && window.FormData && window.XMLHttpRequest && window.FileList;\n\t }\n\t\n\t // export functions\n\t return {\n\t 'select': select,\n\t 'add': add,\n\t 'remove': remove,\n\t 'start': start,\n\t 'stop': stop,\n\t 'reset': reset,\n\t 'configure': configure,\n\t 'compatible': compatible\n\t };\n\t };\n\t})(jQuery);\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(7), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (baseMVC, _l) {\n\t // =============================================================================\n\t /** A view on any model that has a 'annotation' attribute\n\t */\n\t var AnnotationEditor = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseMVC.HiddenUntilActivatedViewMixin).extend({\n\t\n\t tagName: 'div',\n\t className: 'annotation-display',\n\t\n\t /** Set up listeners, parse options */\n\t initialize: function (options) {\n\t options = options || {};\n\t this.tooltipConfig = options.tooltipConfig || { placement: 'bottom' };\n\t //console.debug( this, options );\n\t // only listen to the model only for changes to annotations\n\t this.listenTo(this.model, 'change:annotation', function () {\n\t this.render();\n\t });\n\t this.hiddenUntilActivated(options.$activator, options);\n\t },\n\t\n\t /** Build the DOM elements, call select to on the created input, and set up behaviors */\n\t render: function () {\n\t var view = this;\n\t this.$el.html(this._template());\n\t\n\t //TODO: handle empties better\n\t this.$annotation().make_text_editable({\n\t use_textarea: true,\n\t on_finish: function (newAnnotation) {\n\t view.$annotation().text(newAnnotation);\n\t view.model.save({ annotation: newAnnotation }, { silent: true }).fail(function () {\n\t view.$annotation().text(view.model.previous('annotation'));\n\t });\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** @returns {String} the html text used to build the view's DOM */\n\t _template: function () {\n\t var annotation = this.model.get('annotation');\n\t return [\n\t //TODO: make prompt optional\n\t '',\n\t // set up initial tags by adding as CSV to input vals (necc. to init select2)\n\t '
                                    ', _.escape(annotation), '
                                    '].join('');\n\t },\n\t\n\t /** @returns {jQuery} the main element for this view */\n\t $annotation: function () {\n\t return this.$el.find('.annotation');\n\t },\n\t\n\t /** shut down event listeners and remove this view's DOM */\n\t remove: function () {\n\t this.$annotation.off();\n\t this.stopListening(this.model);\n\t Backbone.View.prototype.remove.call(this);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return ['AnnotationEditor(', this.model + '', ')'].join('');\n\t }\n\t });\n\t // =============================================================================\n\t return {\n\t AnnotationEditor: AnnotationEditor\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 79 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(3), __webpack_require__(2), __webpack_require__(7)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, Backbone, BASE_MVC) {\n\t 'use strict';\n\t\n\t //=============================================================================\n\t /**\n\t * A Collection that can be limited/offset/re-ordered/filtered.\n\t * @type {Backbone.Collection}\n\t */\n\t\n\t var ControlledFetchCollection = Backbone.Collection.extend({\n\t\n\t /** call setOrder on initialization to build the comparator based on options */\n\t initialize: function (models, options) {\n\t Backbone.Collection.prototype.initialize.call(this, models, options);\n\t this.setOrder(options.order || this.order, { silent: true });\n\t },\n\t\n\t /** set up to track order changes and re-sort when changed */\n\t _setUpListeners: function () {\n\t return this.on({\n\t 'changed-order': this.sort\n\t });\n\t },\n\t\n\t /** override to provide order and offsets based on instance vars, set limit if passed,\n\t * and set allFetched/fire 'all-fetched' when xhr returns\n\t */\n\t fetch: function (options) {\n\t options = this._buildFetchOptions(options);\n\t // console.log( 'fetch options:', options );\n\t return Backbone.Collection.prototype.fetch.call(this, options);\n\t },\n\t\n\t /** build ajax data/parameters from options */\n\t _buildFetchOptions: function (options) {\n\t // note: we normally want options passed in to override the defaults built here\n\t // so most of these fns will generate defaults\n\t options = _.clone(options) || {};\n\t var self = this;\n\t\n\t // jquery ajax option; allows multiple q/qv for filters (instead of 'q[]')\n\t options.traditional = true;\n\t\n\t // options.data\n\t // we keep limit, offset, etc. in options *as well as move it into data* because:\n\t // - it makes fetch calling convenient to add it to a single options map (instead of as mult. args)\n\t // - it allows the std. event handlers (for fetch, etc.) to have access\n\t // to the pagination options too\n\t // (i.e. this.on( 'sync', function( options ){ if( options.limit ){ ... } }))\n\t // however, when we send to xhr/jquery we copy them to data also so that they become API query params\n\t options.data = options.data || self._buildFetchData(options);\n\t // console.log( 'data:', options.data );\n\t\n\t // options.data.filters --> options.data.q, options.data.qv\n\t var filters = this._buildFetchFilters(options);\n\t // console.log( 'filters:', filters );\n\t if (!_.isEmpty(filters)) {\n\t _.extend(options.data, this._fetchFiltersToAjaxData(filters));\n\t }\n\t // console.log( 'data:', options.data );\n\t return options;\n\t },\n\t\n\t /** Build the dictionary to send to fetch's XHR as data */\n\t _buildFetchData: function (options) {\n\t var defaults = {};\n\t if (this.order) {\n\t defaults.order = this.order;\n\t }\n\t return _.defaults(_.pick(options, this._fetchParams), defaults);\n\t },\n\t\n\t /** These attribute keys are valid params to fetch/API-index */\n\t _fetchParams: [\n\t /** model dependent string to control the order of models returned */\n\t 'order',\n\t /** limit the number of models returned from a fetch */\n\t 'limit',\n\t /** skip this number of models when fetching */\n\t 'offset',\n\t /** what series of attributes to return (model dependent) */\n\t 'view',\n\t /** individual keys to return for the models (see api/histories.index) */\n\t 'keys'],\n\t\n\t /** add any needed filters here based on collection state */\n\t _buildFetchFilters: function (options) {\n\t // override\n\t return _.clone(options.filters || {});\n\t },\n\t\n\t /** Convert dictionary filters to qqv style arrays */\n\t _fetchFiltersToAjaxData: function (filters) {\n\t // return as a map so ajax.data can extend from it\n\t var filterMap = {\n\t q: [],\n\t qv: []\n\t };\n\t _.each(filters, function (v, k) {\n\t // don't send if filter value is empty\n\t if (v === undefined || v === '') {\n\t return;\n\t }\n\t // json to python\n\t if (v === true) {\n\t v = 'True';\n\t }\n\t if (v === false) {\n\t v = 'False';\n\t }\n\t if (v === null) {\n\t v = 'None';\n\t }\n\t // map to k/v arrays (q/qv)\n\t filterMap.q.push(k);\n\t filterMap.qv.push(v);\n\t });\n\t return filterMap;\n\t },\n\t\n\t /** override to reset allFetched flag to false */\n\t reset: function (models, options) {\n\t this.allFetched = false;\n\t return Backbone.Collection.prototype.reset.call(this, models, options);\n\t },\n\t\n\t // ........................................................................ order\n\t order: null,\n\t\n\t /** @type {Object} map of collection available sorting orders containing comparator fns */\n\t comparators: {\n\t 'update_time': BASE_MVC.buildComparator('update_time', { ascending: false }),\n\t 'update_time-asc': BASE_MVC.buildComparator('update_time', { ascending: true }),\n\t 'create_time': BASE_MVC.buildComparator('create_time', { ascending: false }),\n\t 'create_time-asc': BASE_MVC.buildComparator('create_time', { ascending: true })\n\t },\n\t\n\t /** set the order and comparator for this collection then sort with the new order\n\t * @event 'changed-order' passed the new order and the collection\n\t */\n\t setOrder: function (order, options) {\n\t options = options || {};\n\t var collection = this;\n\t var comparator = collection.comparators[order];\n\t if (_.isUndefined(comparator)) {\n\t throw new Error('unknown order: ' + order);\n\t }\n\t // if( _.isUndefined( comparator ) ){ return; }\n\t if (comparator === collection.comparator) {\n\t return;\n\t }\n\t\n\t var oldOrder = collection.order;\n\t collection.order = order;\n\t collection.comparator = comparator;\n\t\n\t if (!options.silent) {\n\t collection.trigger('changed-order', options);\n\t }\n\t return collection;\n\t }\n\t\n\t });\n\t\n\t //=============================================================================\n\t /**\n\t *\n\t */\n\t var PaginatedCollection = ControlledFetchCollection.extend({\n\t\n\t /** @type {Number} limit used for each page's fetch */\n\t limitPerPage: 500,\n\t\n\t initialize: function (models, options) {\n\t ControlledFetchCollection.prototype.initialize.call(this, models, options);\n\t this.currentPage = options.currentPage || 0;\n\t },\n\t\n\t getTotalItemCount: function () {\n\t return this.length;\n\t },\n\t\n\t shouldPaginate: function () {\n\t return this.getTotalItemCount() >= this.limitPerPage;\n\t },\n\t\n\t getLastPage: function () {\n\t return Math.floor(this.getTotalItemCount() / this.limitPerPage);\n\t },\n\t\n\t getPageCount: function () {\n\t return this.getLastPage() + 1;\n\t },\n\t\n\t getPageLimitOffset: function (pageNum) {\n\t pageNum = this.constrainPageNum(pageNum);\n\t return {\n\t limit: this.limitPerPage,\n\t offset: pageNum * this.limitPerPage\n\t };\n\t },\n\t\n\t constrainPageNum: function (pageNum) {\n\t return Math.max(0, Math.min(pageNum, this.getLastPage()));\n\t },\n\t\n\t /** fetch the next page of data */\n\t fetchPage: function (pageNum, options) {\n\t var self = this;\n\t pageNum = self.constrainPageNum(pageNum);\n\t self.currentPage = pageNum;\n\t options = _.defaults(options || {}, self.getPageLimitOffset(pageNum));\n\t\n\t self.trigger('fetching-more');\n\t return self.fetch(options).always(function () {\n\t self.trigger('fetching-more-done');\n\t });\n\t },\n\t\n\t fetchCurrentPage: function (options) {\n\t return this.fetchPage(this.currentPage, options);\n\t },\n\t\n\t fetchPrevPage: function (options) {\n\t return this.fetchPage(this.currentPage - 1, options);\n\t },\n\t\n\t fetchNextPage: function (options) {\n\t return this.fetchPage(this.currentPage + 1, options);\n\t }\n\t });\n\t\n\t //=============================================================================\n\t /**\n\t * A Collection that will load more elements without reseting.\n\t */\n\t var InfinitelyScrollingCollection = ControlledFetchCollection.extend({\n\t\n\t /** @type {Number} limit used for the first fetch (or a reset) */\n\t limitOnFirstFetch: null,\n\t /** @type {Number} limit used for each subsequent fetch */\n\t limitPerFetch: 100,\n\t\n\t initialize: function (models, options) {\n\t ControlledFetchCollection.prototype.initialize.call(this, models, options);\n\t /** @type {Integer} number of contents to return from the first fetch */\n\t this.limitOnFirstFetch = options.limitOnFirstFetch || this.limitOnFirstFetch;\n\t /** @type {Integer} limit for every fetch after the first */\n\t this.limitPerFetch = options.limitPerFetch || this.limitPerFetch;\n\t /** @type {Boolean} are all contents fetched? */\n\t this.allFetched = false;\n\t /** @type {Integer} what was the offset of the last content returned */\n\t this.lastFetched = options.lastFetched || 0;\n\t },\n\t\n\t /** build ajax data/parameters from options */\n\t _buildFetchOptions: function (options) {\n\t // options (options for backbone.fetch and jquery.ajax generally)\n\t // backbone option; false here to make fetching an addititive process\n\t options.remove = options.remove || false;\n\t return ControlledFetchCollection.prototype._buildFetchOptions.call(this, options);\n\t },\n\t\n\t /** fetch the first 'page' of data */\n\t fetchFirst: function (options) {\n\t // console.log( 'ControlledFetchCollection.fetchFirst:', options );\n\t options = options ? _.clone(options) : {};\n\t this.allFetched = false;\n\t this.lastFetched = 0;\n\t return this.fetchMore(_.defaults(options, {\n\t reset: true,\n\t limit: this.limitOnFirstFetch\n\t }));\n\t },\n\t\n\t /** fetch the next page of data */\n\t fetchMore: function (options) {\n\t // console.log( 'ControlledFetchCollection.fetchMore:', options );\n\t options = _.clone(options || {});\n\t var collection = this;\n\t\n\t // console.log( 'fetchMore, options.reset:', options.reset );\n\t if (!options.reset && collection.allFetched) {\n\t return jQuery.when();\n\t }\n\t\n\t // TODO: this fails in the edge case where\n\t // the first fetch offset === limit (limit 4, offset 4, collection.length 4)\n\t options.offset = options.reset ? 0 : options.offset || collection.lastFetched;\n\t var limit = options.limit = options.limit || collection.limitPerFetch || null;\n\t // console.log( 'fetchMore, limit:', limit, 'offset:', options.offset );\n\t\n\t collection.trigger('fetching-more');\n\t return collection.fetch(options).always(function () {\n\t collection.trigger('fetching-more-done');\n\t })\n\t // maintain allFetched flag and trigger if all were fetched this time\n\t .done(function _postFetchMore(fetchedData) {\n\t var numFetched = _.isArray(fetchedData) ? fetchedData.length : 0;\n\t collection.lastFetched += numFetched;\n\t // console.log( 'fetchMore, lastFetched:', collection.lastFetched );\n\t // anything less than a full page means we got all there is to get\n\t if (!limit || numFetched < limit) {\n\t collection.allFetched = true;\n\t collection.trigger('all-fetched', this);\n\t }\n\t });\n\t },\n\t\n\t /** fetch all the collection */\n\t fetchAll: function (options) {\n\t // whitelist options to prevent allowing limit/offset/filters\n\t // (use vanilla fetch instead)\n\t options = options || {};\n\t var self = this;\n\t options = _.pick(options, 'silent');\n\t options.filters = {};\n\t return self.fetch(options).done(function (fetchData) {\n\t self.allFetched = true;\n\t self.trigger('all-fetched', self);\n\t });\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t ControlledFetchCollection: ControlledFetchCollection,\n\t PaginatedCollection: PaginatedCollection,\n\t InfinitelyScrollingCollection: InfinitelyScrollingCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))\n\n/***/ },\n/* 80 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n\t\n\t /* For presentation-related functionality shared across collection creators.\n\t Particularily overlapping functionality related to name processing and help.\n\t */\n\t var CollectionCreatorMixin = {\n\t\n\t /** add (or clear if clear is truthy) a validation warning to the DOM element described in what */\n\t _validationWarning: function (what, clear) {\n\t var VALIDATION_CLASS = 'validation-warning';\n\t if (what === 'name') {\n\t what = this.$('.collection-name').add(this.$('.collection-name-prompt'));\n\t this.$('.collection-name').focus().select();\n\t }\n\t if (clear) {\n\t what = what || this.$('.' + VALIDATION_CLASS);\n\t what.removeClass(VALIDATION_CLASS);\n\t } else {\n\t what.addClass(VALIDATION_CLASS);\n\t }\n\t },\n\t\n\t _changeHideOriginals: function (ev) {\n\t this.hideOriginals = this.$('.hide-originals').prop(\"checked\");\n\t },\n\t\n\t // ........................................................................ footer\n\t /** handle a collection name change */\n\t _changeName: function (ev) {\n\t this._validationWarning('name', !!this._getName());\n\t },\n\t\n\t /** check for enter key press when in the collection name and submit */\n\t _nameCheckForEnter: function (ev) {\n\t if (ev.keyCode === 13 && !this.blocking) {\n\t this._clickCreate();\n\t }\n\t },\n\t\n\t /** get the current collection name */\n\t _getName: function () {\n\t return _.escape(this.$('.collection-name').val());\n\t },\n\t\n\t // ........................................................................ header\n\t /** expand help */\n\t _clickMoreHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').addClass('expanded');\n\t this.$('.more-help').hide();\n\t },\n\t /** collapse help */\n\t _clickLessHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').removeClass('expanded');\n\t this.$('.more-help').show();\n\t },\n\t /** toggle help */\n\t _toggleHelp: function (ev) {\n\t ev.stopPropagation();\n\t this.$('.main-help').toggleClass('expanded');\n\t this.$('.more-help').toggle();\n\t },\n\t\n\t /** show an alert on the top of the interface containing message (alertClass is bootstrap's alert-*) */\n\t _showAlert: function (message, alertClass) {\n\t alertClass = alertClass || 'alert-danger';\n\t this.$('.main-help').hide();\n\t this.$('.header .alert').attr('class', 'alert alert-dismissable').addClass(alertClass).show().find('.alert-message').html(message);\n\t },\n\t /** hide the alerts at the top */\n\t _hideAlert: function (message) {\n\t this.$('.main-help').show();\n\t this.$('.header .alert').hide();\n\t },\n\t\n\t _cancelCreate: function (ev) {\n\t if (typeof this.oncancel === 'function') {\n\t this.oncancel.call(this);\n\t }\n\t },\n\t\n\t /** attempt to create the current collection */\n\t _clickCreate: function (ev) {\n\t var name = this._getName();\n\t if (!name) {\n\t this._validationWarning('name');\n\t } else if (!this.blocking) {\n\t this.createList(name);\n\t }\n\t },\n\t\n\t _setUpCommonSettings: function (attributes) {\n\t this.hideOriginals = attributes.defaultHideSourceItems || false;\n\t },\n\t\n\t /** render the footer, completion controls, and cancel controls */\n\t _renderFooter: function (speed, callback) {\n\t var instance = this;\n\t var $footer = this.$('.footer').empty().html(this.templates.footer());\n\t _.each(this.footerSettings, function (property, selector) {\n\t this.$(selector).prop('checked', instance[property]);\n\t });\n\t if (typeof this.oncancel === 'function') {\n\t this.$('.cancel-create.btn').show();\n\t }\n\t return $footer;\n\t },\n\t\n\t _creatorTemplates: {\n\t main: _.template(['
                                    ', '
                                    ', '
                                    '].join(''))\n\t }\n\t\n\t };\n\t\n\t //==============================================================================\n\t return {\n\t CollectionCreatorMixin: CollectionCreatorMixin\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 81 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(89), __webpack_require__(56), __webpack_require__(55), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_VIEW, DC_MODEL, DC_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class non-editable, read-only View/Controller for a dataset collection.\n\t */\n\t var _super = LIST_VIEW.ModelListPanel;\n\t var CollectionView = _super.extend(\n\t /** @lends CollectionView.prototype */{\n\t //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\t _logNamespace: logNamespace,\n\t\n\t className: _super.prototype.className + ' dataset-collection-panel',\n\t\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_LI.DatasetDCEListItemView,\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView,\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'elements',\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t this.linkTarget = attributes.linkTarget || '_blank';\n\t\n\t this.hasUser = attributes.hasUser;\n\t /** A stack of panels that currently cover or hide this panel */\n\t this.panelStack = [];\n\t /** The text of the link to go back to the panel containing this one */\n\t this.parentName = attributes.parentName;\n\t /** foldout or drilldown */\n\t this.foldoutStyle = attributes.foldoutStyle || 'foldout';\n\t this.downloadUrl = this.model.attributes.url + '/download';\n\t },\n\t\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var panel = this;\n\t panel.log('_queueNewRender:', $newRender, speed);\n\t\n\t // TODO: jquery@1.12 doesn't change display when the elem has display: flex\n\t // this causes display: block for those elems after the use of show/hide animations\n\t // animations are removed from this view for now until fixed\n\t panel._swapNewRender($newRender);\n\t panel.trigger('rendered', panel);\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-views\n\t /** In this override, use model.getVisibleContents */\n\t _filterCollection: function () {\n\t //TODO: should *not* be model.getVisibleContents - visibility is not model related\n\t return this.model.getVisibleContents();\n\t },\n\t\n\t /** override to return proper view class based on element_type */\n\t _getItemViewClass: function (model) {\n\t //this.debug( this + '._getItemViewClass:', model );\n\t //TODO: subclasses use DCEViewClass - but are currently unused - decide\n\t switch (model.get('element_type')) {\n\t case 'hda':\n\t return this.DatasetDCEViewClass;\n\t case 'dataset_collection':\n\t return this.NestedDCDCEViewClass;\n\t }\n\t throw new TypeError('Unknown element type:', model.get('element_type'));\n\t },\n\t\n\t /** override to add link target and anon */\n\t _getItemViewOptions: function (model) {\n\t var options = _super.prototype._getItemViewOptions.call(this, model);\n\t return _.extend(options, {\n\t linkTarget: this.linkTarget,\n\t hasUser: this.hasUser,\n\t //TODO: could move to only nested: list:paired\n\t foldoutStyle: this.foldoutStyle\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection sub-views\n\t /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t _super.prototype._setUpItemViewListeners.call(panel, view);\n\t\n\t // use pub-sub to: handle drilldown expansion and collapse\n\t panel.listenTo(view, {\n\t 'expanded:drilldown': function (v, drilldown) {\n\t this._expandDrilldownPanel(drilldown);\n\t },\n\t 'collapsed:drilldown': function (v, drilldown) {\n\t this._collapseDrilldownPanel(drilldown);\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n\t _expandDrilldownPanel: function (drilldown) {\n\t this.panelStack.push(drilldown);\n\t // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n\t this.$('> .controls').add(this.$list()).hide();\n\t drilldown.parentName = this.model.get('name');\n\t this.$el.append(drilldown.render().$el);\n\t },\n\t\n\t /** Handle drilldown close by freeing the panel and re-rendering this panel */\n\t _collapseDrilldownPanel: function (drilldown) {\n\t this.panelStack.pop();\n\t this.render();\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: {\n\t 'click .navigation .back': 'close'\n\t },\n\t\n\t /** close/remove this collection panel */\n\t close: function (event) {\n\t this.remove();\n\t this.trigger('close');\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'CollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //------------------------------------------------------------------------------ TEMPLATES\n\t CollectionView.prototype.templates = function () {\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                                    ', '', '
                                    ', '
                                    <%- collection.name || collection.element_identifier %>
                                    ', '
                                    ', '<% if( collection.collection_type === \"list\" ){ %>', _l('a list of datasets'), '<% } else if( collection.collection_type === \"paired\" ){ %>', _l('a pair of datasets'), '<% } else if( collection.collection_type === \"list:paired\" ){ %>', _l('a list of paired datasets'), '<% } else if( collection.collection_type === \"list:list\" ){ %>', _l('a list of dataset lists'), '<% } %>', '
                                    ', '
                                    ', '
                                    ', '', '
                                    '], 'collection');\n\t\n\t return _.extend(_.clone(_super.prototype.templates), {\n\t controls: controlsTemplate\n\t });\n\t }();\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListCollectionView = CollectionView.extend(\n\t /** @lends ListCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_LI.DatasetDCEListItemView,\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var PairCollectionView = ListCollectionView.extend(\n\t /** @lends PairCollectionView.prototype */{\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListOfPairsCollectionView = CollectionView.extend(\n\t /** @lends ListOfPairsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView.extend({\n\t foldoutPanelClass: PairCollectionView\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfPairsCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a list of lists dataset collection. */\n\t var ListOfListsCollectionView = CollectionView.extend({\n\t\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView.extend({\n\t foldoutPanelClass: PairCollectionView\n\t }),\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfListsCollectionView(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CollectionView: CollectionView,\n\t ListCollectionView: ListCollectionView,\n\t PairCollectionView: PairCollectionView,\n\t ListOfPairsCollectionView: ListOfPairsCollectionView,\n\t ListOfListsCollectionView: ListOfListsCollectionView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 82 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(58), __webpack_require__(65), __webpack_require__(78), __webpack_require__(25), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, DATASET_LI, TAGS, ANNOTATIONS, faIconButton, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI.DatasetListItemView;\n\t /** @class Editing view for DatasetAssociation.\n\t */\n\t var DatasetListItemEdit = _super.extend(\n\t /** @lends DatasetListItemEdit.prototype */{\n\t\n\t /** set up: options */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t this.hasUser = attributes.hasUser;\n\t\n\t /** allow user purge of dataset files? */\n\t this.purgeAllowed = attributes.purgeAllowed || false;\n\t\n\t //TODO: move to HiddenUntilActivatedViewMixin\n\t /** should the tags editor be shown or hidden initially? */\n\t this.tagsEditorShown = attributes.tagsEditorShown || false;\n\t /** should the tags editor be shown or hidden initially? */\n\t this.annotationEditorShown = attributes.annotationEditorShown || false;\n\t },\n\t\n\t // ......................................................................... titlebar actions\n\t /** In this override, add the other two primary actions: edit and delete */\n\t _renderPrimaryActions: function () {\n\t var actions = _super.prototype._renderPrimaryActions.call(this);\n\t if (this.model.get('state') === STATES.NOT_VIEWABLE) {\n\t return actions;\n\t }\n\t // render the display, edit attr and delete icon-buttons\n\t return _super.prototype._renderPrimaryActions.call(this).concat([this._renderEditButton(), this._renderDeleteButton()]);\n\t },\n\t\n\t //TODO: move titleButtons into state renderers, remove state checks in the buttons\n\t\n\t /** Render icon-button to edit the attributes (format, permissions, etc.) this dataset. */\n\t _renderEditButton: function () {\n\t // don't show edit while uploading, in-accessible\n\t // DO show if in error (ala previous history panel)\n\t if (this.model.get('state') === STATES.DISCARDED || !this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var purged = this.model.get('purged'),\n\t deleted = this.model.get('deleted'),\n\t editBtnData = {\n\t title: _l('Edit attributes'),\n\t href: Galaxy.root + 'datasets/edit?dataset_id=' + this.model.attributes.id,\n\t faIcon: 'fa-pencil',\n\t classes: 'edit-btn'\n\t };\n\t // disable if purged or deleted and explain why in the tooltip\n\t if (deleted || purged) {\n\t editBtnData.disabled = true;\n\t if (purged) {\n\t editBtnData.title = _l('Cannot edit attributes of datasets removed from disk');\n\t } else if (deleted) {\n\t editBtnData.title = _l('Undelete dataset to edit attributes');\n\t }\n\t\n\t // disable if still uploading or new\n\t } else if (_.contains([STATES.UPLOAD, STATES.NEW], this.model.get('state'))) {\n\t editBtnData.disabled = true;\n\t editBtnData.title = _l('This dataset is not yet editable');\n\t }\n\t return faIconButton(editBtnData);\n\t },\n\t\n\t /** Render icon-button to delete this hda. */\n\t _renderDeleteButton: function () {\n\t // don't show delete if...\n\t if (!this.model.get('accessible')) {\n\t return null;\n\t }\n\t\n\t var self = this,\n\t deletedAlready = this.model.isDeletedOrPurged();\n\t return faIconButton({\n\t title: !deletedAlready ? _l('Delete') : _l('Dataset is already deleted'),\n\t disabled: deletedAlready,\n\t faIcon: 'fa-times',\n\t classes: 'delete-btn',\n\t onclick: function () {\n\t // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n\t self.$el.find('.icon-btn.delete-btn').trigger('mouseout');\n\t self.model['delete']();\n\t }\n\t });\n\t },\n\t\n\t // ......................................................................... details\n\t /** In this override, add tags and annotations controls, make the ? dbkey a link to editing page */\n\t _renderDetails: function () {\n\t //TODO: generalize to be allow different details for each state\n\t var $details = _super.prototype._renderDetails.call(this),\n\t state = this.model.get('state');\n\t\n\t if (!this.model.isDeletedOrPurged() && _.contains([STATES.OK, STATES.FAILED_METADATA], state)) {\n\t this._renderTags($details);\n\t this._renderAnnotation($details);\n\t this._makeDbkeyEditLink($details);\n\t }\n\t\n\t this._setUpBehaviors($details);\n\t return $details;\n\t },\n\t\n\t /**************************************************************************\n\t * Render help button to show tool help text without rerunning the tool.\n\t * Issue #2100\n\t */\n\t _renderToolHelpButton: function () {\n\t var datasetID = this.model.attributes.dataset_id;\n\t var jobID = this.model.attributes.creating_job;\n\t var self = this;\n\t\n\t var parseToolBuild = function (data) {\n\t var helpString = '
                                    ';\n\t if (data.name && data.help) {\n\t helpString += 'Tool help for ' + data.name + '
                                    ';\n\t helpString += data.help;\n\t } else {\n\t helpString += 'Tool help is unavailable for this dataset.
                                    ';\n\t }\n\t helpString += '
                                    ';\n\t self.$el.find('.details').append($.parseHTML(helpString));\n\t };\n\t var parseToolID = function (data) {\n\t $.ajax({\n\t url: Galaxy.root + 'api/tools/' + data.tool_id + '/build'\n\t }).done(function (data) {\n\t parseToolBuild(data);\n\t }).fail(function () {\n\t parseToolBuild({});\n\t });\n\t };\n\t if (Galaxy.user.id === null) {\n\t return null;\n\t }\n\t return faIconButton({\n\t title: _l('Tool Help'),\n\t classes: 'icon-btn',\n\t href: '#',\n\t faIcon: 'fa-question',\n\t onclick: function () {\n\t var divString = 'thdiv-' + datasetID;\n\t if (self.$el.find(\".toolhelp\").length > 0) {\n\t self.$el.find(\".toolhelp\").toggle();\n\t } else {\n\t $.ajax({\n\t url: Galaxy.root + 'api/jobs/' + jobID\n\t }).done(function (data) {\n\t parseToolID(data);\n\t }).fail(function () {\n\t console.log('Failed at recovering job information from the Galaxy API for job id \"' + jobID + '\".');\n\t });\n\t }\n\t }\n\t });\n\t },\n\t //*************************************************************************\n\t\n\t /** Add less commonly used actions in the details section based on state */\n\t _renderSecondaryActions: function () {\n\t var actions = _super.prototype._renderSecondaryActions.call(this);\n\t switch (this.model.get('state')) {\n\t case STATES.UPLOAD:\n\t case STATES.NOT_VIEWABLE:\n\t return actions;\n\t case STATES.ERROR:\n\t // error button comes first\n\t actions.unshift(this._renderErrButton());\n\t return actions.concat([this._renderRerunButton(), this._renderToolHelpButton()]);\n\t case STATES.OK:\n\t case STATES.FAILED_METADATA:\n\t return actions.concat([this._renderRerunButton(), this._renderVisualizationsButton(), this._renderToolHelpButton()]);\n\t }\n\t return actions.concat([this._renderRerunButton(), this._renderToolHelpButton()]);\n\t },\n\t\n\t /** Render icon-button to report an error on this dataset to the galaxy admin. */\n\t _renderErrButton: function () {\n\t return faIconButton({\n\t title: _l('View or report this error'),\n\t href: Galaxy.root + 'datasets/error?dataset_id=' + this.model.attributes.id,\n\t classes: 'report-error-btn',\n\t faIcon: 'fa-bug'\n\t });\n\t },\n\t\n\t /** Render icon-button to re-run the job that created this dataset. */\n\t _renderRerunButton: function () {\n\t var creating_job = this.model.get('creating_job');\n\t if (this.model.get('rerunnable')) {\n\t return faIconButton({\n\t title: _l('Run this job again'),\n\t href: this.model.urls.rerun,\n\t classes: 'rerun-btn',\n\t target: this.linkTarget,\n\t faIcon: 'fa-refresh',\n\t onclick: function (ev) {\n\t ev.preventDefault();\n\t Galaxy.router.push('/', { job_id: creating_job });\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Render an icon-button or popupmenu of links based on the applicable visualizations */\n\t _renderVisualizationsButton: function () {\n\t //TODO: someday - lazyload visualizations\n\t var visualizations = this.model.get('visualizations');\n\t if (this.model.isDeletedOrPurged() || !this.hasUser || !this.model.hasData() || _.isEmpty(visualizations)) {\n\t return null;\n\t }\n\t if (!_.isObject(visualizations[0])) {\n\t this.warn('Visualizations have been switched off');\n\t return null;\n\t }\n\t\n\t var $visualizations = $(this.templates.visualizations(visualizations, this));\n\t //HACK: need to re-write those directed at galaxy_main with linkTarget\n\t $visualizations.find('[target=\"galaxy_main\"]').attr('target', this.linkTarget);\n\t // use addBack here to include the root $visualizations elem (for the case of 1 visualization)\n\t this._addScratchBookFn($visualizations.find('.visualization-link').addBack('.visualization-link'));\n\t return $visualizations;\n\t },\n\t\n\t /** add scratchbook functionality to visualization links */\n\t _addScratchBookFn: function ($links) {\n\t var li = this;\n\t $links.click(function (ev) {\n\t if (Galaxy.frame && Galaxy.frame.active) {\n\t Galaxy.frame.add({\n\t title: 'Visualization',\n\t url: $(this).attr('href')\n\t });\n\t ev.preventDefault();\n\t ev.stopPropagation();\n\t }\n\t });\n\t },\n\t\n\t //TODO: if possible move these to readonly view - but display the owner's tags/annotation (no edit)\n\t /** Render the tags list/control */\n\t _renderTags: function ($where) {\n\t if (!this.hasUser) {\n\t return;\n\t }\n\t var view = this;\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // persist state on the hda view (and not the editor) since these are currently re-created each time\n\t onshow: function () {\n\t view.tagsEditorShown = true;\n\t },\n\t onhide: function () {\n\t view.tagsEditorShown = false;\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit dataset tags'),\n\t classes: 'tag-btn',\n\t faIcon: 'fa-tags'\n\t }).appendTo($where.find('.actions .right'))\n\t });\n\t if (this.tagsEditorShown) {\n\t this.tagsEditor.toggle(true);\n\t }\n\t },\n\t\n\t /** Render the annotation display/control */\n\t _renderAnnotation: function ($where) {\n\t if (!this.hasUser) {\n\t return;\n\t }\n\t var view = this;\n\t this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n\t model: this.model,\n\t el: $where.find('.annotation-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t // persist state on the hda view (and not the editor) since these are currently re-created each time\n\t onshow: function () {\n\t view.annotationEditorShown = true;\n\t },\n\t onhide: function () {\n\t view.annotationEditorShown = false;\n\t },\n\t $activator: faIconButton({\n\t title: _l('Edit dataset annotation'),\n\t classes: 'annotate-btn',\n\t faIcon: 'fa-comment'\n\t }).appendTo($where.find('.actions .right'))\n\t });\n\t if (this.annotationEditorShown) {\n\t this.annotationEditor.toggle(true);\n\t }\n\t },\n\t\n\t /** If the format/dbkey/genome_build isn't set, make the display a link to the edit page */\n\t _makeDbkeyEditLink: function ($details) {\n\t // make the dbkey a link to editing\n\t if (this.model.get('metadata_dbkey') === '?' && !this.model.isDeletedOrPurged()) {\n\t var editableDbkey = $('?').attr('href', this.model.urls.edit).attr('target', this.linkTarget);\n\t $details.find('.dbkey .value').replaceWith(editableDbkey);\n\t }\n\t },\n\t\n\t // ......................................................................... events\n\t /** event map */\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .undelete-link': '_clickUndeleteLink',\n\t 'click .purge-link': '_clickPurgeLink',\n\t\n\t 'click .edit-btn': function (ev) {\n\t this.trigger('edit', this, ev);\n\t },\n\t 'click .delete-btn': function (ev) {\n\t this.trigger('delete', this, ev);\n\t },\n\t 'click .rerun-btn': function (ev) {\n\t this.trigger('rerun', this, ev);\n\t },\n\t 'click .report-err-btn': function (ev) {\n\t this.trigger('report-err', this, ev);\n\t },\n\t 'click .visualization-btn': function (ev) {\n\t this.trigger('visualize', this, ev);\n\t },\n\t 'click .dbkey a': function (ev) {\n\t this.trigger('edit', this, ev);\n\t }\n\t }),\n\t\n\t /** listener for item undelete (in the messages section) */\n\t _clickUndeleteLink: function (ev) {\n\t this.model.undelete();\n\t return false;\n\t },\n\t\n\t /** listener for item purge (in the messages section) */\n\t _clickPurgeLink: function (ev) {\n\t if (confirm(_l('This will permanently remove the data in your dataset. Are you sure?'))) {\n\t this.model.purge();\n\t }\n\t return false;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** string rep */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAEditView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetListItemEdit.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t failed_metadata: BASE_MVC.wrapTemplate([\n\t // in this override, provide a link to the edit page\n\t '<% if( dataset.state === \"failed_metadata\" ){ %>', '', '<% } %>'], 'dataset'),\n\t\n\t deleted: BASE_MVC.wrapTemplate([\n\t // in this override, provide links to undelete or purge the dataset\n\t '<% if( dataset.deleted && !dataset.purged ){ %>',\n\t // deleted not purged\n\t '
                                    ', _l('This dataset has been deleted'), '
                                    ', _l('Undelete it'), '', '<% if( view.purgeAllowed ){ %>', '
                                    ', _l('Permanently remove it from disk'), '', '<% } %>', '
                                    ', '<% } %>'], 'dataset')\n\t });\n\t\n\t var visualizationsTemplate = BASE_MVC.wrapTemplate(['<% if( visualizations.length === 1 ){ %>', '\"', ' target=\"<%- visualizations[0].target %>\" title=\"', _l('Visualize in'), ' <%- visualizations[0].html %>\">', '', '', '<% } else { %>', '
                                    ', '', '', '', '', '
                                    ', '<% } %>'], 'visualizations');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t visualizations: visualizationsTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t DatasetListItemEdit: DatasetListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 83 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t var logNamespace = 'dataset';\n\t //==============================================================================\n\t var searchableMixin = BASE_MVC.SearchableModelMixin;\n\t /** @class base model for any DatasetAssociation (HDAs, LDDAs, DatasetCollectionDAs).\n\t * No knowledge of what type (HDA/LDDA/DCDA) should be needed here.\n\t * The DA's are made searchable (by attribute) by mixing in SearchableModelMixin.\n\t */\n\t var DatasetAssociation = Backbone.Model.extend(BASE_MVC.LoggableMixin).extend(BASE_MVC.mixin(searchableMixin, /** @lends DatasetAssociation.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t state: STATES.NEW,\n\t deleted: false,\n\t purged: false,\n\t name: '(unnamed dataset)',\n\t accessible: true,\n\t // sniffed datatype (sam, tabular, bed, etc.)\n\t data_type: '',\n\t file_ext: '',\n\t file_size: 0,\n\t\n\t // array of associated file types (eg. [ 'bam_index', ... ])\n\t meta_files: [],\n\t\n\t misc_blurb: '',\n\t misc_info: '',\n\t\n\t tags: []\n\t // do NOT default on annotation, as this default is valid and will be passed on 'save'\n\t // which is incorrect behavior when the model is only partially fetched (annos are not passed in summary data)\n\t //annotation : ''\n\t },\n\t\n\t /** instance vars and listeners */\n\t initialize: function (attributes, options) {\n\t this.debug(this + '(Dataset).initialize', attributes, options);\n\t\n\t //!! this state is not in trans.app.model.Dataset.states - set it here -\n\t if (!this.get('accessible')) {\n\t this.set('state', STATES.NOT_VIEWABLE);\n\t }\n\t\n\t /** Datasets rely/use some web controllers - have the model generate those URLs on startup */\n\t this.urls = this._generateUrls();\n\t\n\t this._setUpListeners();\n\t },\n\t\n\t /** returns misc. web urls for rendering things like re-run, display, etc. */\n\t _generateUrls: function () {\n\t var id = this.get('id');\n\t if (!id) {\n\t return {};\n\t }\n\t var urls = {\n\t 'purge': 'datasets/' + id + '/purge_async',\n\t 'display': 'datasets/' + id + '/display/?preview=True',\n\t 'edit': 'datasets/' + id + '/edit',\n\t 'download': 'datasets/' + id + '/display' + this._downloadQueryParameters(),\n\t 'report_error': 'dataset/errors?id=' + id,\n\t 'rerun': 'tool_runner/rerun?id=' + id,\n\t 'show_params': 'datasets/' + id + '/show_params',\n\t 'visualization': 'visualization',\n\t 'meta_download': 'dataset/get_metadata_file?hda_id=' + id + '&metadata_name='\n\t };\n\t _.each(urls, function (value, key) {\n\t urls[key] = Galaxy.root + value;\n\t });\n\t this.urls = urls;\n\t return urls;\n\t },\n\t\n\t _downloadQueryParameters: function () {\n\t return '?to_ext=' + this.get('file_ext');\n\t },\n\t\n\t /** set up any event listeners\n\t * event: state:ready fired when this DA moves into/is already in a ready state\n\t */\n\t _setUpListeners: function () {\n\t // if the state has changed and the new state is a ready state, fire an event\n\t this.on('change:state', function (currModel, newState) {\n\t this.log(this + ' has changed state:', currModel, newState);\n\t if (this.inReadyState()) {\n\t this.trigger('state:ready', currModel, newState, this.previous('state'));\n\t }\n\t });\n\t // the download url (currently) relies on having a correct file extension\n\t this.on('change:id change:file_ext', function (currModel) {\n\t this._generateUrls();\n\t });\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** override to add urls */\n\t toJSON: function () {\n\t var json = Backbone.Model.prototype.toJSON.call(this);\n\t //console.warn( 'returning json?' );\n\t //return json;\n\t return _.extend(json, {\n\t urls: this.urls\n\t });\n\t },\n\t\n\t /** Is this dataset deleted or purged? */\n\t isDeletedOrPurged: function () {\n\t return this.get('deleted') || this.get('purged');\n\t },\n\t\n\t /** Is this dataset in a 'ready' state; where 'Ready' states are states where no\n\t * processing (for the ds) is left to do on the server.\n\t */\n\t inReadyState: function () {\n\t var ready = _.contains(STATES.READY_STATES, this.get('state'));\n\t return this.isDeletedOrPurged() || ready;\n\t },\n\t\n\t /** Does this model already contain detailed data (as opposed to just summary level data)? */\n\t hasDetails: function () {\n\t // if it's inaccessible assume it has everything it needs\n\t if (!this.get('accessible')) {\n\t return true;\n\t }\n\t return this.has('annotation');\n\t },\n\t\n\t /** Convenience function to match dataset.has_data. */\n\t hasData: function () {\n\t return this.get('file_size') > 0;\n\t },\n\t\n\t // ........................................................................ ajax\n\t fetch: function (options) {\n\t var dataset = this;\n\t return Backbone.Model.prototype.fetch.call(this, options).always(function () {\n\t dataset._generateUrls();\n\t });\n\t },\n\t\n\t /** override to use actual Dates objects for create/update times */\n\t parse: function (response, options) {\n\t var parsed = Backbone.Model.prototype.parse.call(this, response, options);\n\t if (parsed.create_time) {\n\t parsed.create_time = new Date(parsed.create_time);\n\t }\n\t if (parsed.update_time) {\n\t parsed.update_time = new Date(parsed.update_time);\n\t }\n\t return parsed;\n\t },\n\t\n\t /** override to wait by default */\n\t save: function (attrs, options) {\n\t options = options || {};\n\t options.wait = _.isUndefined(options.wait) ? true : options.wait;\n\t return Backbone.Model.prototype.save.call(this, attrs, options);\n\t },\n\t\n\t //NOTE: subclasses of DA's will need to implement url and urlRoot in order to have these work properly\n\t /** save this dataset, _Mark_ing it as deleted (just a flag) */\n\t 'delete': function (options) {\n\t if (this.get('deleted')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: true }, options);\n\t },\n\t /** save this dataset, _Mark_ing it as undeleted */\n\t undelete: function (options) {\n\t if (!this.get('deleted') || this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ deleted: false }, options);\n\t },\n\t\n\t /** remove the file behind this dataset from the filesystem (if permitted) */\n\t purge: function _purge(options) {\n\t //TODO: use, override model.destroy, HDA.delete({ purge: true })\n\t if (this.get('purged')) {\n\t return jQuery.when();\n\t }\n\t options = options || {};\n\t options.url = this.urls.purge;\n\t\n\t //TODO: ideally this would be a DELETE call to the api\n\t // using purge async for now\n\t var hda = this,\n\t xhr = jQuery.ajax(options);\n\t xhr.done(function (message, status, responseObj) {\n\t hda.set({ deleted: true, purged: true });\n\t });\n\t xhr.fail(function (xhr, status, message) {\n\t // Exception messages are hidden within error page including: '...not allowed in this Galaxy instance.'\n\t // unbury and re-add to xhr\n\t var error = _l(\"Unable to purge dataset\");\n\t var messageBuriedInUnfortunatelyFormattedError = 'Removal of datasets by users ' + 'is not allowed in this Galaxy instance';\n\t if (xhr.responseJSON && xhr.responseJSON.error) {\n\t error = xhr.responseJSON.error;\n\t } else if (xhr.responseText.indexOf(messageBuriedInUnfortunatelyFormattedError) !== -1) {\n\t error = messageBuriedInUnfortunatelyFormattedError;\n\t }\n\t xhr.responseText = error;\n\t hda.trigger('error', hda, xhr, options, _l(error), { error: error });\n\t });\n\t return xhr;\n\t },\n\t\n\t // ........................................................................ searching\n\t /** what attributes of an HDA will be used in a text search */\n\t searchAttributes: ['name', 'file_ext', 'genome_build', 'misc_blurb', 'misc_info', 'annotation', 'tags'],\n\t\n\t /** our attr keys don't often match the labels we display to the user - so, when using\n\t * attribute specifiers ('name=\"bler\"') in a term, allow passing in aliases for the\n\t * following attr keys.\n\t */\n\t searchAliases: {\n\t title: 'name',\n\t format: 'file_ext',\n\t database: 'genome_build',\n\t blurb: 'misc_blurb',\n\t description: 'misc_blurb',\n\t info: 'misc_info',\n\t tag: 'tags'\n\t },\n\t\n\t // ........................................................................ misc\n\t /** String representation */\n\t toString: function () {\n\t var nameAndId = this.get('id') || '';\n\t if (this.get('name')) {\n\t nameAndId = '\"' + this.get('name') + '\",' + nameAndId;\n\t }\n\t return 'Dataset(' + nameAndId + ')';\n\t }\n\t }));\n\t\n\t //==============================================================================\n\t /** @class Backbone collection for dataset associations.\n\t */\n\t var DatasetAssociationCollection = Backbone.Collection.extend(BASE_MVC.LoggableMixin).extend(\n\t /** @lends HistoryContents.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t model: DatasetAssociation,\n\t\n\t /** root api url */\n\t urlRoot: Galaxy.root + 'api/datasets',\n\t\n\t /** url fn */\n\t url: function () {\n\t return this.urlRoot;\n\t },\n\t\n\t // ........................................................................ common queries\n\t /** Get the ids of every item in this collection\n\t * @returns array of encoded ids\n\t */\n\t ids: function () {\n\t return this.map(function (item) {\n\t return item.get('id');\n\t });\n\t },\n\t\n\t /** Get contents that are not ready\n\t * @returns array of content models\n\t */\n\t notReady: function () {\n\t return this.filter(function (content) {\n\t return !content.inReadyState();\n\t });\n\t },\n\t\n\t /** return true if any datasets don't have details */\n\t haveDetails: function () {\n\t return this.all(function (dataset) {\n\t return dataset.hasDetails();\n\t });\n\t },\n\t\n\t // ........................................................................ ajax\n\t /** using a queue, perform ajaxFn on each of the models in this collection */\n\t ajaxQueue: function (ajaxFn, options) {\n\t var deferred = jQuery.Deferred(),\n\t startingLength = this.length,\n\t responses = [];\n\t\n\t if (!startingLength) {\n\t deferred.resolve([]);\n\t return deferred;\n\t }\n\t\n\t // use reverse order (stylistic choice)\n\t var ajaxFns = this.chain().reverse().map(function (dataset, i) {\n\t return function () {\n\t var xhr = ajaxFn.call(dataset, options);\n\t // if successful, notify using the deferred to allow tracking progress\n\t xhr.done(function (response) {\n\t deferred.notify({ curr: i, total: startingLength, response: response, model: dataset });\n\t });\n\t // (regardless of previous error or success) if not last ajax call, shift and call the next\n\t // if last fn, resolve deferred\n\t xhr.always(function (response) {\n\t responses.push(response);\n\t if (ajaxFns.length) {\n\t ajaxFns.shift()();\n\t } else {\n\t deferred.resolve(responses);\n\t }\n\t });\n\t };\n\t }).value();\n\t // start the queue\n\t ajaxFns.shift()();\n\t\n\t return deferred;\n\t },\n\t\n\t // ........................................................................ sorting/filtering\n\t /** return a new collection of datasets whose attributes contain the substring matchesWhat */\n\t matches: function (matchesWhat) {\n\t return this.filter(function (dataset) {\n\t return dataset.matches(matchesWhat);\n\t });\n\t },\n\t\n\t /** String representation. */\n\t toString: function () {\n\t return ['DatasetAssociationCollection(', this.length, ')'].join('');\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DatasetAssociation: DatasetAssociation,\n\t DatasetAssociationCollection: DatasetAssociationCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 84 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_, jQuery, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(8), __webpack_require__(92), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (MODAL, ERROR_MODAL, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /**\n\t * A dialog/modal that allows copying a user history or 'importing' from user\n\t * another. Generally called via historyCopyDialog below.\n\t * @type {Object}\n\t */\n\t\n\t var CopyDialog = {\n\t\n\t // language related strings/fns\n\t defaultName: _.template(\"Copy of '<%- name %>'\"),\n\t title: _.template(_l('Copying history') + ' \"<%- name %>\"'),\n\t submitLabel: _l('Copy'),\n\t errorMessage: _l('History could not be copied.'),\n\t progressive: _l('Copying history'),\n\t activeLabel: _l('Copy only the active, non-deleted datasets'),\n\t allLabel: _l('Copy all datasets including deleted ones'),\n\t anonWarning: _l('As an anonymous user, unless you login or register, you will lose your current history ') + _l('after copying this history. '),\n\t\n\t // template for modal body\n\t _template: _.template([\n\t //TODO: remove inline styles\n\t // show a warning message for losing current to anon users\n\t '<% if( isAnon ){ %>', '
                                    ', '<%- anonWarning %>', _l('You can'), ' ', _l('login here'), ' ', _l('or'), ' ', ' ', _l('register here'), '.', '
                                    ', '<% } %>', '
                                    ', '
                                    ',\n\t // TODO: could use required here and the form validators\n\t // NOTE: use unescaped here if escaped in the modal function below\n\t '\" />', '

                                    ', _l('Please enter a valid history title'), '

                                    ',\n\t // if allowAll, add the option to copy deleted datasets, too\n\t '<% if( allowAll ){ %>', '
                                    ', '

                                    ', _l('Choose which datasets from the original history to include:'), '

                                    ',\n\t // copy non-deleted is the default\n\t '/>', '', '
                                    ', '/>', '', '<% } %>', '
                                    '].join('')),\n\t\n\t // empty modal body and let the user know the copy is happening\n\t _showAjaxIndicator: function _showAjaxIndicator() {\n\t var indicator = '

                                    ' + this.progressive + '...

                                    ';\n\t this.modal.$('.modal-body').empty().append(indicator).css({ 'margin-top': '8px' });\n\t },\n\t\n\t // (sorta) public interface - display the modal, render the form, and potentially copy the history\n\t // returns a jQuery.Deferred done->history copied, fail->user cancelled\n\t dialog: function _dialog(modal, history, options) {\n\t options = options || {};\n\t\n\t var dialog = this,\n\t deferred = jQuery.Deferred(),\n\t\n\t // TODO: getting a little byzantine here\n\t defaultCopyNameFn = options.nameFn || this.defaultName,\n\t defaultCopyName = defaultCopyNameFn({ name: history.get('name') }),\n\t\n\t // TODO: these two might be simpler as one 3 state option (all,active,no-choice)\n\t defaultCopyWhat = options.allDatasets ? 'copy-all' : 'copy-non-deleted',\n\t allowAll = !_.isUndefined(options.allowAll) ? options.allowAll : true,\n\t autoClose = !_.isUndefined(options.autoClose) ? options.autoClose : true;\n\t\n\t this.modal = modal;\n\t\n\t // validate the name and copy if good\n\t function checkNameAndCopy() {\n\t var name = modal.$('#copy-modal-title').val();\n\t if (!name) {\n\t modal.$('.invalid-title').show();\n\t return;\n\t }\n\t // get further settings, shut down and indicate the ajax call, then hide and resolve/reject\n\t var copyAllDatasets = modal.$('input[name=\"copy-what\"]:checked').val() === 'copy-all';\n\t modal.$('button').prop('disabled', true);\n\t dialog._showAjaxIndicator();\n\t history.copy(true, name, copyAllDatasets).done(function (response) {\n\t deferred.resolve(response);\n\t }).fail(function (xhr, status, message) {\n\t var options = { name: name, copyAllDatasets: copyAllDatasets };\n\t ERROR_MODAL.ajaxErrorModal(history, xhr, options, dialog.errorMessage);\n\t deferred.rejectWith(deferred, arguments);\n\t }).done(function () {\n\t if (autoClose) {\n\t modal.hide();\n\t }\n\t });\n\t }\n\t\n\t var originalClosingCallback = options.closing_callback;\n\t modal.show(_.extend(options, {\n\t title: this.title({ name: history.get('name') }),\n\t body: $(dialog._template({\n\t name: defaultCopyName,\n\t isAnon: Galaxy.user.isAnonymous(),\n\t allowAll: allowAll,\n\t copyWhat: defaultCopyWhat,\n\t activeLabel: this.activeLabel,\n\t allLabel: this.allLabel,\n\t anonWarning: this.anonWarning\n\t })),\n\t buttons: _.object([[_l('Cancel'), function () {\n\t modal.hide();\n\t }], [this.submitLabel, checkNameAndCopy]]),\n\t height: 'auto',\n\t closing_events: true,\n\t closing_callback: function _historyCopyClose(cancelled) {\n\t if (cancelled) {\n\t deferred.reject({ cancelled: true });\n\t }\n\t if (originalClosingCallback) {\n\t originalClosingCallback(cancelled);\n\t }\n\t }\n\t }));\n\t\n\t // set the default dataset copy, autofocus the title, and set up for a simple return\n\t modal.$('#copy-modal-title').focus().select();\n\t modal.$('#copy-modal-title').on('keydown', function (ev) {\n\t if (ev.keyCode === 13) {\n\t ev.preventDefault();\n\t checkNameAndCopy();\n\t }\n\t });\n\t\n\t return deferred;\n\t }\n\t };\n\t\n\t //==============================================================================\n\t // maintain the (slight) distinction between copy and import\n\t /**\n\t * Subclass CopyDialog to use the import language.\n\t */\n\t var ImportDialog = _.extend({}, CopyDialog, {\n\t defaultName: _.template(\"imported: <%- name %>\"),\n\t title: _.template(_l('Importing history') + ' \"<%- name %>\"'),\n\t submitLabel: _l('Import'),\n\t errorMessage: _l('History could not be imported.'),\n\t progressive: _l('Importing history'),\n\t activeLabel: _l('Import only the active, non-deleted datasets'),\n\t allLabel: _l('Import all datasets including deleted ones'),\n\t anonWarning: _l('As an anonymous user, unless you login or register, you will lose your current history ') + _l('after importing this history. ')\n\t\n\t });\n\t\n\t //==============================================================================\n\t /**\n\t * Main interface for both history import and history copy dialogs.\n\t * @param {Backbone.Model} history the history to copy\n\t * @param {Object} options a hash\n\t * @return {jQuery.Deferred} promise that fails on close and succeeds on copy\n\t *\n\t * options:\n\t * (this object is also passed to the modal used to display the dialog and accepts modal options)\n\t * {Function} nameFn if defined, use this to build the default name shown to the user\n\t * (the fn is passed: {name: })\n\t * {bool} useImport if true, use the 'import' language (instead of Copy)\n\t * {bool} allowAll if true, allow the user to choose between copying all datasets and\n\t * only non-deleted datasets\n\t * {String} allDatasets default initial checked radio button: 'copy-all' or 'copy-non-deleted',\n\t */\n\t var historyCopyDialog = function (history, options) {\n\t options = options || {};\n\t // create our own modal if Galaxy doesn't have one (mako tab without use_panels)\n\t var modal = window.parent.Galaxy.modal || new MODAL.View({});\n\t return options.useImport ? ImportDialog.dialog(modal, history, options) : CopyDialog.dialog(modal, history, options);\n\t };\n\t\n\t //==============================================================================\n\t return historyCopyDialog;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 85 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(58), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET_LI, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET_LI.DatasetListItemView;\n\t /** @class Read only view for HistoryDatasetAssociation.\n\t * Since there are no controls on the HDAView to hide the dataset,\n\t * the primary thing this class does (currently) is override templates\n\t * to render the HID.\n\t */\n\t var HDAListItemView = _super.extend(\n\t /** @lends HDAListItemView.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t initialize: function (attributes, options) {\n\t _super.prototype.initialize.call(this, attributes, options);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDAListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t HDAListItemView.prototype.templates = function () {\n\t\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding the hid display to the title\n\t '
                                    ', '', '
                                    ',\n\t //TODO: remove whitespace and use margin-right\n\t '<%- dataset.hid %> ', '<%- dataset.name %>', '
                                    ', '
                                    ', '', '<% _.each(_.sortBy(_.uniq(dataset.tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>', '', '
                                    '], 'dataset');\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate([\n\t // add a warning when hidden\n\t '<% if( !dataset.visible ){ %>', '
                                    ', _l('This dataset has been hidden'), '
                                    ', '<% } %>'], 'dataset')\n\t });\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t titleBar: titleBarTemplate,\n\t warnings: warnings\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDAListItemView: HDAListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 86 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(83), __webpack_require__(88), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DATASET, HISTORY_CONTENT, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DATASET.DatasetAssociation,\n\t hcontentMixin = HISTORY_CONTENT.HistoryContentMixin;\n\t /** @class (HDA) model for a Galaxy dataset contained in and related to a history.\n\t */\n\t var HistoryDatasetAssociation = _super.extend(BASE_MVC.mixin(hcontentMixin,\n\t /** @lends HistoryDatasetAssociation.prototype */{\n\t\n\t /** default attributes for a model */\n\t defaults: _.extend({}, _super.prototype.defaults, hcontentMixin.defaults, {\n\t history_content_type: 'dataset',\n\t model_class: 'HistoryDatasetAssociation'\n\t })\n\t }));\n\t\n\t //==============================================================================\n\t return {\n\t HistoryDatasetAssociation: HistoryDatasetAssociation\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 87 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(_) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(55), __webpack_require__(81), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, DC_LI, DC_VIEW, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t //==============================================================================\n\t\n\t var _super = DC_LI.DCListItemView;\n\t /** @class Read only view for HistoryDatasetCollectionAssociation (a dataset collection inside a history).\n\t */\n\t var HDCAListItemView = _super.extend(\n\t /** @lends HDCAListItemView.prototype */{\n\t\n\t className: _super.prototype.className + \" history-content\",\n\t\n\t /** event listeners */\n\t _setUpListeners: function () {\n\t _super.prototype._setUpListeners.call(this);\n\t this.listenTo(this.model, {\n\t 'change:tags change:populated change:visible': function (model, options) {\n\t this.render();\n\t }\n\t });\n\t },\n\t\n\t /** Override to provide the proper collections panels as the foldout */\n\t _getFoldoutPanelClass: function () {\n\t switch (this.model.get('collection_type')) {\n\t case 'list':\n\t return DC_VIEW.ListCollectionView;\n\t case 'paired':\n\t return DC_VIEW.PairCollectionView;\n\t case 'list:paired':\n\t return DC_VIEW.ListOfPairsCollectionView;\n\t case 'list:list':\n\t return DC_VIEW.ListOfListsCollectionView;\n\t }\n\t throw new TypeError('Uknown collection_type: ' + this.model.get('collection_type'));\n\t },\n\t\n\t /** In this override, add the state as a class for use with state-based CSS */\n\t _swapNewRender: function ($newRender) {\n\t _super.prototype._swapNewRender.call(this, $newRender);\n\t //TODO: model currently has no state\n\t var state = !this.model.get('populated') ? STATES.RUNNING : STATES.OK;\n\t //if( this.model.has( 'state' ) ){\n\t this.$el.addClass('state-' + state);\n\t //}\n\t return this.$el;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'HDCAListItemView(' + modelString + ')';\n\t }\n\t });\n\t\n\t /** underscore templates */\n\t HDCAListItemView.prototype.templates = function () {\n\t\n\t var warnings = _.extend({}, _super.prototype.templates.warnings, {\n\t hidden: BASE_MVC.wrapTemplate([\n\t // add a warning when hidden\n\t '<% if( !collection.visible ){ %>', '
                                    ', _l('This collection has been hidden'), '
                                    ', '<% } %>'], 'collection')\n\t });\n\t\n\t // could steal this from hda-base (or use mixed content)\n\t var titleBarTemplate = BASE_MVC.wrapTemplate([\n\t // adding the hid display to the title\n\t '
                                    ', '', '
                                    ',\n\t //TODO: remove whitespace and use margin-right\n\t '<%- collection.hid %> ', '<%- collection.name %>', '
                                    ', '
                                    ', '', '<% _.each(_.sortBy(_.uniq(collection.tags), function(x) { return x }), function(tag){ %>', '<% if (tag.indexOf(\"name:\") == 0){ %>', '<%- tag.slice(5) %>', '<% } %>', '<% }); %>', '', '
                                    '], 'collection');\n\t\n\t return _.extend({}, _super.prototype.templates, {\n\t warnings: warnings,\n\t titleBar: titleBarTemplate\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t return {\n\t HDCAListItemView: HDCAListItemView\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))\n\n/***/ },\n/* 88 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(17), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (STATES, BASE_MVC, _l) {\n\t 'use strict';\n\t\n\t //==============================================================================\n\t /** @class Mixin for HistoryContents content (HDAs, HDCAs).\n\t */\n\t\n\t var HistoryContentMixin = {\n\t\n\t /** default attributes for a model */\n\t defaults: {\n\t /** parent (containing) history */\n\t history_id: null,\n\t /** some content_type (HistoryContents can contain mixed model classes) */\n\t history_content_type: null,\n\t /** indicating when/what order the content was generated in the context of the history */\n\t hid: null,\n\t /** whether the user wants the content shown (visible) */\n\t visible: true\n\t },\n\t\n\t // ........................................................................ mixed content element\n\t // In order to be part of a MIXED bbone collection, we can't rely on the id\n\t // (which may collide btwn models of different classes)\n\t // Instead, use type_id which prefixes the history_content_type so the bbone collection can differentiate\n\t idAttribute: 'type_id',\n\t\n\t // ........................................................................ common queries\n\t /** the more common alias of visible */\n\t hidden: function () {\n\t return !this.get('visible');\n\t },\n\t\n\t //TODO: remove\n\t /** based on includeDeleted, includeHidden (gen. from the container control),\n\t * would this ds show in the list of ds's?\n\t * @param {Boolean} includeDeleted are we showing deleted hdas?\n\t * @param {Boolean} includeHidden are we showing hidden hdas?\n\t */\n\t isVisible: function (includeDeleted, includeHidden) {\n\t var isVisible = true;\n\t if (!includeDeleted && (this.get('deleted') || this.get('purged'))) {\n\t isVisible = false;\n\t }\n\t if (!includeHidden && !this.get('visible')) {\n\t isVisible = false;\n\t }\n\t return isVisible;\n\t },\n\t\n\t // ........................................................................ ajax\n\t //TODO?: these are probably better done on the leaf classes\n\t /** history content goes through the 'api/histories' API */\n\t urlRoot: Galaxy.root + 'api/histories/',\n\t\n\t /** full url spec. for this content */\n\t url: function () {\n\t var url = this.urlRoot + this.get('history_id') + '/contents/' + this.get('history_content_type') + 's/' + this.get('id');\n\t return url;\n\t },\n\t\n\t /** save this content as not visible */\n\t hide: function (options) {\n\t if (!this.get('visible')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ visible: false }, options);\n\t },\n\t /** save this content as visible */\n\t unhide: function (options) {\n\t if (this.get('visible')) {\n\t return jQuery.when();\n\t }\n\t return this.save({ visible: true }, options);\n\t },\n\t\n\t // ........................................................................ misc\n\t toString: function () {\n\t return [this.get('type_id'), this.get('hid'), this.get('name')].join(':');\n\t }\n\t };\n\t\n\t //==============================================================================\n\t return {\n\t HistoryContentMixin: HistoryContentMixin\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))\n\n/***/ },\n/* 89 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(64), __webpack_require__(148), __webpack_require__(7), __webpack_require__(6), __webpack_require__(96)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_ITEM, LoadingIndicator, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'list';\n\t /* ============================================================================\n\t TODO:\n\t \n\t ============================================================================ */\n\t /** @class View for a list/collection of models and the sub-views of those models.\n\t * Sub-views must (at least have the interface if not) inherit from ListItemView.\n\t * (For a list panel that also includes some 'container' model (History->HistoryContents)\n\t * use ModelWithListPanel)\n\t *\n\t * Allows for:\n\t * searching collection/sub-views\n\t * selecting/multi-selecting sub-views\n\t *\n\t * Currently used:\n\t * for dataset/dataset-choice\n\t * as superclass of ModelListPanel\n\t */\n\t var ListPanel = Backbone.View.extend(BASE_MVC.LoggableMixin).extend( /** @lends ListPanel.prototype */{\n\t _logNamespace: logNamespace,\n\t\n\t /** class to use for constructing the sub-views */\n\t viewClass: LIST_ITEM.ListItemView,\n\t /** class to used for constructing collection of sub-view models */\n\t collectionClass: Backbone.Collection,\n\t\n\t tagName: 'div',\n\t className: 'list-panel',\n\t\n\t /** (in ms) that jquery effects will use */\n\t fxSpeed: 'fast',\n\t\n\t /** string to display when the collection has no contents */\n\t emptyMsg: _l('This list is empty'),\n\t /** displayed when no items match the search terms */\n\t noneFoundMsg: _l('No matching items found'),\n\t /** string used for search placeholder */\n\t searchPlaceholder: _l('search'),\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the list\n\t */\n\t initialize: function (attributes, options) {\n\t attributes = attributes || {};\n\t // set the logger if requested\n\t if (attributes.logger) {\n\t this.logger = attributes.logger;\n\t }\n\t this.log(this + '.initialize:', attributes);\n\t\n\t // ---- instance vars\n\t /** how quickly should jquery fx run? */\n\t this.fxSpeed = _.has(attributes, 'fxSpeed') ? attributes.fxSpeed : this.fxSpeed;\n\t\n\t /** filters for displaying subviews */\n\t this.filters = [];\n\t /** current search terms */\n\t this.searchFor = attributes.searchFor || '';\n\t\n\t /** loading indicator */\n\t // this.indicator = new LoadingIndicator( this.$el );\n\t\n\t /** currently showing selectors on items? */\n\t this.selecting = attributes.selecting !== undefined ? attributes.selecting : true;\n\t //this.selecting = false;\n\t\n\t /** cached selected item.model.ids to persist btwn renders */\n\t this.selected = attributes.selected || [];\n\t /** the last selected item.model.id */\n\t this.lastSelected = null;\n\t\n\t /** are sub-views draggable */\n\t this.dragItems = attributes.dragItems || false;\n\t\n\t /** list item view class (when passed models) */\n\t this.viewClass = attributes.viewClass || this.viewClass;\n\t\n\t /** list item views */\n\t this.views = [];\n\t /** list item models */\n\t this.collection = attributes.collection || this._createDefaultCollection();\n\t\n\t /** filter fns run over collection items to see if they should show in the list */\n\t this.filters = attributes.filters || [];\n\t\n\t /** override $scrollContainer fn via attributes - fn should return jq for elem to call scrollTo on */\n\t this.$scrollContainer = attributes.$scrollContainer || this.$scrollContainer;\n\t\n\t /** @type {String} generic title */\n\t this.title = attributes.title || '';\n\t /** @type {String} generic subtitle */\n\t this.subtitle = attributes.subtitle || '';\n\t\n\t this._setUpListeners();\n\t },\n\t\n\t // ------------------------------------------------------------------------ listeners\n\t /** create any event listeners for the list */\n\t _setUpListeners: function () {\n\t this.off();\n\t\n\t //TODO: move errorHandler down into list-view from history-view or\n\t // pass to global error handler (Galaxy)\n\t this.on({\n\t error: function (model, xhr, options, msg, details) {\n\t //this.errorHandler( model, xhr, options, msg, details );\n\t console.error(model, xhr, options, msg, details);\n\t },\n\t // show hide the loading indicator\n\t loading: function () {\n\t this._showLoadingIndicator('loading...', 40);\n\t },\n\t 'loading-done': function () {\n\t this._hideLoadingIndicator(40);\n\t }\n\t });\n\t\n\t // throw the first render up as a diff namespace using once (for outside consumption)\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this._setUpCollectionListeners();\n\t this._setUpViewListeners();\n\t return this;\n\t },\n\t\n\t /** create and return a collection for when none is initially passed */\n\t _createDefaultCollection: function () {\n\t // override\n\t return new this.collectionClass([]);\n\t },\n\t\n\t /** listening for collection events */\n\t _setUpCollectionListeners: function () {\n\t this.log(this + '._setUpCollectionListeners', this.collection);\n\t this.stopListening(this.collection);\n\t\n\t // bubble up error events\n\t this.listenTo(this.collection, {\n\t error: function (model, xhr, options, msg, details) {\n\t this.trigger('error', model, xhr, options, msg, details);\n\t },\n\t update: function (collection, options) {\n\t var changes = options.changes;\n\t // console.info( collection + ', update:', changes, '\\noptions:', options );\n\t // more than one: render everything\n\t if (options.renderAll || changes.added.length + changes.removed.length > 1) {\n\t return this.renderItems();\n\t }\n\t // otherwise, let the single add/remove handlers do it\n\t if (changes.added.length === 1) {\n\t return this.addItemView(_.first(changes.added), collection, options);\n\t }\n\t if (changes.removed.length === 1) {\n\t return this.removeItemView(_.first(changes.removed), collection, options);\n\t }\n\t }\n\t });\n\t return this;\n\t },\n\t\n\t /** listening for sub-view events that bubble up with the 'view:' prefix */\n\t _setUpViewListeners: function () {\n\t this.log(this + '._setUpViewListeners');\n\t\n\t // shift to select a range\n\t this.on({\n\t 'view:selected': function (view, ev) {\n\t if (ev && ev.shiftKey && this.lastSelected) {\n\t var lastSelectedView = this.viewFromModelId(this.lastSelected);\n\t if (lastSelectedView) {\n\t this.selectRange(view, lastSelectedView);\n\t }\n\t } else if (ev && ev.altKey && !this.selecting) {\n\t this.showSelectors();\n\t }\n\t this.selected.push(view.model.id);\n\t this.lastSelected = view.model.id;\n\t },\n\t\n\t 'view:de-selected': function (view, ev) {\n\t this.selected = _.without(this.selected, view.model.id);\n\t }\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t /** Render this content, set up ui.\n\t * @param {Number or String} speed the speed of the render\n\t */\n\t render: function (speed) {\n\t this.log(this + '.render', speed);\n\t var $newRender = this._buildNewRender();\n\t this._setUpBehaviors($newRender);\n\t this._queueNewRender($newRender, speed);\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el. */\n\t _buildNewRender: function () {\n\t this.debug(this + '(ListPanel)._buildNewRender');\n\t var $newRender = $(this.templates.el({}, this));\n\t this._renderControls($newRender);\n\t this._renderTitle($newRender);\n\t this._renderSubtitle($newRender);\n\t this._renderSearch($newRender);\n\t this.renderItems($newRender);\n\t return $newRender;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el. */\n\t _renderControls: function ($newRender) {\n\t this.debug(this + '(ListPanel)._renderControls');\n\t var $controls = $(this.templates.controls({}, this));\n\t $newRender.find('.controls').replaceWith($controls);\n\t return $controls;\n\t },\n\t\n\t /** return a jQuery object containing the title DOM */\n\t _renderTitle: function ($where) {\n\t //$where = $where || this.$el;\n\t //$where.find( '.title' ).replaceWith( ... )\n\t },\n\t\n\t /** return a jQuery object containing the subtitle DOM (if any) */\n\t _renderSubtitle: function ($where) {\n\t //$where = $where || this.$el;\n\t //$where.find( '.title' ).replaceWith( ... )\n\t },\n\t\n\t /** Fade out the old el, swap in the new contents, then fade in.\n\t * @param {Number or String} speed jq speed to use for rendering effects\n\t * @fires rendered when rendered\n\t */\n\t _queueNewRender: function ($newRender, speed) {\n\t speed = speed === undefined ? this.fxSpeed : speed;\n\t var panel = this;\n\t panel.log('_queueNewRender:', $newRender, speed);\n\t\n\t $(panel).queue('fx', [function (next) {\n\t panel.$el.fadeOut(speed, next);\n\t }, function (next) {\n\t panel._swapNewRender($newRender);\n\t next();\n\t }, function (next) {\n\t panel.$el.fadeIn(speed, next);\n\t }, function (next) {\n\t panel.trigger('rendered', panel);\n\t next();\n\t }]);\n\t },\n\t\n\t /** empty out the current el, move the $newRender's children in */\n\t _swapNewRender: function ($newRender) {\n\t this.$el.empty().attr('class', this.className).append($newRender.children());\n\t if (this.selecting) {\n\t this.showSelectors(0);\n\t }\n\t return this;\n\t },\n\t\n\t /** Set up any behaviors, handlers (ep. plugins) that need to be called when the entire view has been built but\n\t * not attached to the page yet.\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t this.$controls($where).find('[title]').tooltip();\n\t // set up the pupup for actions available when multi selecting\n\t this._renderMultiselectActionMenu($where);\n\t return this;\n\t },\n\t\n\t /** render a menu containing the actions available to sets of selected items */\n\t _renderMultiselectActionMenu: function ($where) {\n\t $where = $where || this.$el;\n\t var $menu = $where.find('.list-action-menu'),\n\t actions = this.multiselectActions();\n\t if (!actions.length) {\n\t return $menu.empty();\n\t }\n\t\n\t var $newMenu = $(['
                                    ', '', '
                                      ', '
                                    ', '
                                    '].join(''));\n\t var $actions = actions.map(function (action) {\n\t var html = ['
                                  • ', action.html, '
                                  • '].join('');\n\t return $(html).click(function (ev) {\n\t ev.preventDefault();\n\t return action.func(ev);\n\t });\n\t });\n\t $newMenu.find('ul').append($actions);\n\t $menu.replaceWith($newMenu);\n\t return $newMenu;\n\t },\n\t\n\t /** return a list of plain objects used to render multiselect actions menu. Each object should have:\n\t * html: an html string used as the anchor contents\n\t * func: a function called when the anchor is clicked (passed the click event)\n\t */\n\t multiselectActions: function () {\n\t return [];\n\t },\n\t\n\t // ------------------------------------------------------------------------ sub-$element shortcuts\n\t /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n\t $scrollContainer: function ($where) {\n\t // override or set via attributes.$scrollContainer\n\t return ($where || this.$el).parent().parent();\n\t },\n\t /** convenience selector for the section that displays the list controls */\n\t $controls: function ($where) {\n\t return ($where || this.$el).find('> .controls');\n\t },\n\t /** list-items: where the subviews are contained in the view's dom */\n\t $list: function ($where) {\n\t return ($where || this.$el).find('> .list-items');\n\t },\n\t /** container where list messages are attached */\n\t $messages: function ($where) {\n\t //TODO: controls isn't really correct here (only for ModelListPanel)\n\t return ($where || this.$el).find('> .controls .messages');\n\t },\n\t /** the message displayed when no views can be shown (no views, none matching search) */\n\t $emptyMessage: function ($where) {\n\t return ($where || this.$el).find('> .empty-message');\n\t },\n\t\n\t // ------------------------------------------------------------------------ hda sub-views\n\t /** render the subviews for the list's collection */\n\t renderItems: function ($whereTo) {\n\t $whereTo = $whereTo || this.$el;\n\t var panel = this;\n\t panel.log(this + '.renderItems', $whereTo);\n\t\n\t var $list = panel.$list($whereTo);\n\t panel.freeViews();\n\t // console.log( 'views freed' );\n\t //TODO:? cache and re-use views?\n\t var shownModels = panel._filterCollection();\n\t // console.log( 'models filtered:', shownModels );\n\t\n\t panel.views = shownModels.map(function (itemModel) {\n\t var view = panel._createItemView(itemModel);\n\t return view;\n\t });\n\t\n\t $list.empty();\n\t // console.log( 'list emptied' );\n\t if (panel.views.length) {\n\t panel._attachItems($whereTo);\n\t // console.log( 'items attached' );\n\t }\n\t panel._renderEmptyMessage($whereTo).toggle(!panel.views.length);\n\t panel.trigger('views:ready', panel.views);\n\t\n\t // console.log( '------------------------------------------- rendering items' );\n\t return panel.views;\n\t },\n\t\n\t /** Filter the collection to only those models that should be currently viewed */\n\t _filterCollection: function () {\n\t // override this\n\t var panel = this;\n\t return panel.collection.filter(_.bind(panel._filterItem, panel));\n\t },\n\t\n\t /** Should the model be viewable in the current state?\n\t * Checks against this.filters and this.searchFor\n\t */\n\t _filterItem: function (model) {\n\t // override this\n\t var panel = this;\n\t return _.every(panel.filters.map(function (fn) {\n\t return fn.call(model);\n\t })) && (!panel.searchFor || model.matchesAll(panel.searchFor));\n\t },\n\t\n\t /** Create a view for a model and set up it's listeners */\n\t _createItemView: function (model) {\n\t var ViewClass = this._getItemViewClass(model);\n\t var options = _.extend(this._getItemViewOptions(model), {\n\t model: model\n\t });\n\t var view = new ViewClass(options);\n\t this._setUpItemViewListeners(view);\n\t return view;\n\t },\n\t\n\t /** Free a view for a model. Note: does not remove it from the DOM */\n\t _destroyItemView: function (view) {\n\t this.stopListening(view);\n\t this.views = _.without(this.views, view);\n\t },\n\t\n\t _destroyItemViews: function (view) {\n\t var self = this;\n\t self.views.forEach(function (v) {\n\t self.stopListening(v);\n\t });\n\t self.views = [];\n\t return self;\n\t },\n\t\n\t /** free any sub-views the list has */\n\t freeViews: function () {\n\t return this._destroyItemViews();\n\t },\n\t\n\t /** Get the bbone view class based on the model */\n\t _getItemViewClass: function (model) {\n\t // override this\n\t return this.viewClass;\n\t },\n\t\n\t /** Get the options passed to the new view based on the model */\n\t _getItemViewOptions: function (model) {\n\t // override this\n\t return {\n\t //logger : this.logger,\n\t fxSpeed: this.fxSpeed,\n\t expanded: false,\n\t selectable: this.selecting,\n\t selected: _.contains(this.selected, model.id),\n\t draggable: this.dragItems\n\t };\n\t },\n\t\n\t /** Set up listeners for new models */\n\t _setUpItemViewListeners: function (view) {\n\t var panel = this;\n\t // send all events to the panel, re-namspaceing them with the view prefix\n\t this.listenTo(view, 'all', function () {\n\t var args = Array.prototype.slice.call(arguments, 0);\n\t args[0] = 'view:' + args[0];\n\t panel.trigger.apply(panel, args);\n\t });\n\t\n\t // drag multiple - hijack ev.setData to add all selected items\n\t this.listenTo(view, 'draggable:dragstart', function (ev, v) {\n\t //TODO: set multiple drag data here\n\t var json = {},\n\t selected = this.getSelectedModels();\n\t if (selected.length) {\n\t json = selected.toJSON();\n\t } else {\n\t json = [v.model.toJSON()];\n\t }\n\t ev.dataTransfer.setData('text', JSON.stringify(json));\n\t //ev.dataTransfer.setDragImage( v.el, 60, 60 );\n\t }, this);\n\t\n\t return panel;\n\t },\n\t\n\t /** Attach views in this.views to the model based on $whereTo */\n\t _attachItems: function ($whereTo) {\n\t var self = this;\n\t // console.log( '_attachItems:', $whereTo, this.$list( $whereTo ) );\n\t //ASSUMES: $list has been emptied\n\t this.$list($whereTo).append(this.views.map(function (view) {\n\t return self._renderItemView$el(view);\n\t }));\n\t return this;\n\t },\n\t\n\t /** get a given subview's $el (or whatever may wrap it) and return it */\n\t _renderItemView$el: function (view) {\n\t // useful to wrap and override\n\t return view.render(0).$el;\n\t },\n\t\n\t /** render the empty/none-found message */\n\t _renderEmptyMessage: function ($whereTo) {\n\t this.debug('_renderEmptyMessage', $whereTo, this.searchFor);\n\t var text = this.searchFor ? this.noneFoundMsg : this.emptyMsg;\n\t return this.$emptyMessage($whereTo).text(text);\n\t },\n\t\n\t /** expand all item views */\n\t expandAll: function () {\n\t _.each(this.views, function (view) {\n\t view.expand();\n\t });\n\t },\n\t\n\t /** collapse all item views */\n\t collapseAll: function () {\n\t _.each(this.views, function (view) {\n\t view.collapse();\n\t });\n\t },\n\t\n\t // ------------------------------------------------------------------------ collection/views syncing\n\t /** Add a view (if the model should be viewable) to the panel */\n\t addItemView: function (model, collection, options) {\n\t // console.log( this + '.addItemView:', model );\n\t var panel = this;\n\t // get the index of the model in the list of filtered models shown by this list\n\t // in order to insert the view in the proper place\n\t //TODO:? potentially expensive\n\t var modelIndex = panel._filterCollection().indexOf(model);\n\t if (modelIndex === -1) {\n\t return undefined;\n\t }\n\t var view = panel._createItemView(model);\n\t // console.log( 'adding and rendering:', modelIndex, view.toString() );\n\t\n\t $(view).queue('fx', [function (next) {\n\t // hide the empty message first if only view\n\t if (panel.$emptyMessage().is(':visible')) {\n\t panel.$emptyMessage().fadeOut(panel.fxSpeed, next);\n\t } else {\n\t next();\n\t }\n\t }, function (next) {\n\t panel._attachView(view, modelIndex);\n\t next();\n\t }]);\n\t return view;\n\t },\n\t\n\t /** internal fn to add view (to both panel.views and panel.$list) */\n\t _attachView: function (view, modelIndex, useFx) {\n\t // console.log( this + '._attachView:', view, modelIndex, useFx );\n\t useFx = _.isUndefined(useFx) ? true : useFx;\n\t modelIndex = modelIndex || 0;\n\t var panel = this;\n\t\n\t // use the modelIndex to splice into views and insert at the proper index in the DOM\n\t panel.views.splice(modelIndex, 0, view);\n\t panel._insertIntoListAt(modelIndex, panel._renderItemView$el(view).hide());\n\t\n\t panel.trigger('view:attached', view);\n\t if (useFx) {\n\t view.$el.slideDown(panel.fxSpeed, function () {\n\t panel.trigger('view:attached:rendered');\n\t });\n\t } else {\n\t view.$el.show();\n\t panel.trigger('view:attached:rendered');\n\t }\n\t return view;\n\t },\n\t\n\t /** insert a jq object as a child of list-items at the specified *DOM index* */\n\t _insertIntoListAt: function (index, $what) {\n\t // console.log( this + '._insertIntoListAt:', index, $what );\n\t var $list = this.$list();\n\t if (index === 0) {\n\t $list.prepend($what);\n\t } else {\n\t $list.children().eq(index - 1).after($what);\n\t }\n\t return $what;\n\t },\n\t\n\t /** Remove a view from the panel (if found) */\n\t removeItemView: function (model, collection, options) {\n\t var panel = this;\n\t var view = _.find(panel.views, function (v) {\n\t return v.model === model;\n\t });\n\t if (!view) {\n\t return undefined;\n\t }\n\t panel.views = _.without(panel.views, view);\n\t panel.trigger('view:removed', view);\n\t\n\t // potentially show the empty message if no views left\n\t // use anonymous queue here - since remove can happen multiple times\n\t $({}).queue('fx', [function (next) {\n\t view.$el.fadeOut(panel.fxSpeed, next);\n\t }, function (next) {\n\t view.remove();\n\t panel.trigger('view:removed:rendered');\n\t if (!panel.views.length) {\n\t panel._renderEmptyMessage().fadeIn(panel.fxSpeed, next);\n\t } else {\n\t next();\n\t }\n\t }]);\n\t return view;\n\t },\n\t\n\t /** get views based on model.id */\n\t viewFromModelId: function (id) {\n\t return _.find(this.views, function (v) {\n\t return v.model.id === id;\n\t });\n\t },\n\t\n\t /** get views based on model */\n\t viewFromModel: function (model) {\n\t return model ? this.viewFromModelId(model.id) : undefined;\n\t },\n\t\n\t /** get views based on model properties */\n\t viewsWhereModel: function (properties) {\n\t return this.views.filter(function (view) {\n\t return _.isMatch(view.model.attributes, properties);\n\t });\n\t },\n\t\n\t /** A range of views between (and including) viewA and viewB */\n\t viewRange: function (viewA, viewB) {\n\t if (viewA === viewB) {\n\t return viewA ? [viewA] : [];\n\t }\n\t\n\t var indexA = this.views.indexOf(viewA),\n\t indexB = this.views.indexOf(viewB);\n\t\n\t // handle not found\n\t if (indexA === -1 || indexB === -1) {\n\t if (indexA === indexB) {\n\t return [];\n\t }\n\t return indexA === -1 ? [viewB] : [viewA];\n\t }\n\t // reverse if indeces are\n\t //note: end inclusive\n\t return indexA < indexB ? this.views.slice(indexA, indexB + 1) : this.views.slice(indexB, indexA + 1);\n\t },\n\t\n\t // ------------------------------------------------------------------------ searching\n\t /** render a search input for filtering datasets shown\n\t * (see SearchableMixin in base-mvc for implementation of the actual searching)\n\t * return will start the search\n\t * esc will clear the search\n\t * clicking the clear button will clear the search\n\t * uses searchInput in ui.js\n\t */\n\t _renderSearch: function ($where) {\n\t $where.find('.controls .search-input').searchInput({\n\t placeholder: this.searchPlaceholder,\n\t initialVal: this.searchFor,\n\t onfirstsearch: _.bind(this._firstSearch, this),\n\t onsearch: _.bind(this.searchItems, this),\n\t onclear: _.bind(this.clearSearch, this)\n\t });\n\t return $where;\n\t },\n\t\n\t /** What to do on the first search entered */\n\t _firstSearch: function (searchFor) {\n\t // override to load model details if necc.\n\t this.log('onFirstSearch', searchFor);\n\t return this.searchItems(searchFor);\n\t },\n\t\n\t /** filter view list to those that contain the searchFor terms */\n\t searchItems: function (searchFor, force) {\n\t this.log('searchItems', searchFor, this.searchFor, force);\n\t if (!force && this.searchFor === searchFor) {\n\t return this;\n\t }\n\t this.searchFor = searchFor;\n\t this.renderItems();\n\t this.trigger('search:searching', searchFor, this);\n\t var $search = this.$('> .controls .search-query');\n\t if ($search.val() !== searchFor) {\n\t $search.val(searchFor);\n\t }\n\t return this;\n\t },\n\t\n\t /** clear the search filters and show all views that are normally shown */\n\t clearSearch: function (searchFor) {\n\t //this.log( 'onSearchClear', this );\n\t this.searchFor = '';\n\t this.trigger('search:clear', this);\n\t this.$('> .controls .search-query').val('');\n\t this.renderItems();\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ selection\n\t /** @type Integer when the number of list item views is >= to this, don't animate selectors */\n\t THROTTLE_SELECTOR_FX_AT: 20,\n\t\n\t /** show selectors on all visible itemViews and associated controls */\n\t showSelectors: function (speed) {\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t this.selecting = true;\n\t this.$('.list-actions').slideDown(speed);\n\t speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT ? 0 : speed;\n\t _.each(this.views, function (view) {\n\t view.showSelector(speed);\n\t });\n\t //this.selected = [];\n\t //this.lastSelected = null;\n\t },\n\t\n\t /** hide selectors on all visible itemViews and associated controls */\n\t hideSelectors: function (speed) {\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t this.selecting = false;\n\t this.$('.list-actions').slideUp(speed);\n\t speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT ? 0 : speed;\n\t _.each(this.views, function (view) {\n\t view.hideSelector(speed);\n\t });\n\t this.selected = [];\n\t this.lastSelected = null;\n\t },\n\t\n\t /** show or hide selectors on all visible itemViews and associated controls */\n\t toggleSelectors: function () {\n\t if (!this.selecting) {\n\t this.showSelectors();\n\t } else {\n\t this.hideSelectors();\n\t }\n\t },\n\t\n\t /** select all visible items */\n\t selectAll: function (event) {\n\t _.each(this.views, function (view) {\n\t view.select(event);\n\t });\n\t },\n\t\n\t /** deselect all visible items */\n\t deselectAll: function (event) {\n\t this.lastSelected = null;\n\t _.each(this.views, function (view) {\n\t view.deselect(event);\n\t });\n\t },\n\t\n\t /** select a range of datasets between A and B */\n\t selectRange: function (viewA, viewB) {\n\t var range = this.viewRange(viewA, viewB);\n\t _.each(range, function (view) {\n\t view.select();\n\t });\n\t return range;\n\t },\n\t\n\t /** return an array of all currently selected itemViews */\n\t getSelectedViews: function () {\n\t return _.filter(this.views, function (v) {\n\t return v.selected;\n\t });\n\t },\n\t\n\t /** return a collection of the models of all currenly selected items */\n\t getSelectedModels: function () {\n\t // console.log( '(getSelectedModels)' );\n\t return new this.collection.constructor(_.map(this.getSelectedViews(), function (view) {\n\t return view.model;\n\t }));\n\t },\n\t\n\t // ------------------------------------------------------------------------ loading indicator\n\t /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n\t _showLoadingIndicator: function (msg, speed, callback) {\n\t this.debug('_showLoadingIndicator', this.indicator, msg, speed, callback);\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t if (!this.indicator) {\n\t this.indicator = new LoadingIndicator(this.$el);\n\t this.debug('\\t created', this.indicator);\n\t }\n\t if (!this.$el.is(':visible')) {\n\t this.indicator.show(0, callback);\n\t } else {\n\t this.$el.fadeOut(speed);\n\t this.indicator.show(msg, speed, callback);\n\t }\n\t },\n\t\n\t /** hide the loading indicator */\n\t _hideLoadingIndicator: function (speed, callback) {\n\t this.debug('_hideLoadingIndicator', this.indicator, speed, callback);\n\t speed = speed !== undefined ? speed : this.fxSpeed;\n\t if (this.indicator) {\n\t this.indicator.hide(speed, callback);\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ scrolling\n\t /** get the current scroll position of the panel in its parent */\n\t scrollPosition: function () {\n\t return this.$scrollContainer().scrollTop();\n\t },\n\t\n\t /** set the current scroll position of the panel in its parent */\n\t scrollTo: function (pos, speed) {\n\t speed = speed || 0;\n\t this.$scrollContainer().animate({ scrollTop: pos }, speed);\n\t return this;\n\t },\n\t\n\t /** Scrolls the panel to the top. */\n\t scrollToTop: function (speed) {\n\t return this.scrollTo(0, speed);\n\t },\n\t\n\t /** scroll to the given view in list-items */\n\t scrollToItem: function (view, speed) {\n\t if (!view) {\n\t return this;\n\t }\n\t return this;\n\t },\n\t\n\t /** Scrolls the panel to show the content with the given id. */\n\t scrollToId: function (id, speed) {\n\t return this.scrollToItem(this.viewFromModelId(id), speed);\n\t },\n\t\n\t // ------------------------------------------------------------------------ panel events\n\t /** event map */\n\t events: {\n\t 'click .select-all': 'selectAll',\n\t 'click .deselect-all': 'deselectAll'\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** Return a string rep of the panel */\n\t toString: function () {\n\t return 'ListPanel(' + this.collection + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ListPanel.prototype.templates = function () {\n\t\n\t var elTemplate = BASE_MVC.wrapTemplate([\n\t // temp container\n\t '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ']);\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                                    ', '
                                    ', '
                                    <%- view.title %>
                                    ', '
                                    ', '
                                    <%- view.subtitle %>
                                    ',\n\t // buttons, controls go here\n\t '
                                    ',\n\t // deleted msg, etc.\n\t '
                                    ', '
                                    ', '
                                    ', '
                                    ',\n\t\n\t // show when selectors are shown\n\t '
                                    ', '
                                    ', '', '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ']);\n\t\n\t return {\n\t el: elTemplate,\n\t controls: controlsTemplate\n\t };\n\t }();\n\t\n\t //=============================================================================\n\t /** View for a model that has a sub-collection (e.g. History, DatasetCollection)\n\t * Allows:\n\t * the model to be reset\n\t * auto assign panel.collection to panel.model[ panel.modelCollectionKey ]\n\t *\n\t */\n\t var ModelListPanel = ListPanel.extend({\n\t\n\t /** key of attribute in model to assign to this.collection */\n\t modelCollectionKey: 'contents',\n\t\n\t initialize: function (attributes) {\n\t ListPanel.prototype.initialize.call(this, attributes);\n\t this.selecting = attributes.selecting !== undefined ? attributes.selecting : false;\n\t\n\t this.setModel(this.model, attributes);\n\t },\n\t\n\t /** release/free/shutdown old models and set up panel for new models\n\t * @fires new-model with the panel as parameter\n\t */\n\t setModel: function (model, attributes) {\n\t attributes = attributes || {};\n\t this.debug(this + '.setModel:', model, attributes);\n\t\n\t this.freeModel();\n\t this.freeViews();\n\t\n\t if (model) {\n\t var oldModelId = this.model ? this.model.get('id') : null;\n\t\n\t // set up the new model with user, logger, storage, events\n\t this.model = model;\n\t if (this.logger) {\n\t this.model.logger = this.logger;\n\t }\n\t this._setUpModelListeners();\n\t\n\t //TODO: relation btwn model, collection becoming tangled here\n\t // free the collection, and assign the new collection to either\n\t // the model[ modelCollectionKey ], attributes.collection, or an empty vanilla collection\n\t this.stopListening(this.collection);\n\t this.collection = this.model[this.modelCollectionKey] || attributes.collection || this._createDefaultCollection();\n\t this._setUpCollectionListeners();\n\t\n\t if (oldModelId && model.get('id') !== oldModelId) {\n\t this.trigger('new-model', this);\n\t }\n\t }\n\t return this;\n\t },\n\t\n\t /** free the current model and all listeners for it, free any views for the model */\n\t freeModel: function () {\n\t // stop/release the previous model, and clear cache to sub-views\n\t if (this.model) {\n\t this.stopListening(this.model);\n\t //TODO: see base-mvc\n\t //this.model.free();\n\t //this.model = null;\n\t }\n\t return this;\n\t },\n\t\n\t // ------------------------------------------------------------------------ listening\n\t /** listening for model events */\n\t _setUpModelListeners: function () {\n\t // override\n\t this.log(this + '._setUpModelListeners', this.model);\n\t // bounce model errors up to the panel\n\t this.listenTo(this.model, 'error', function () {\n\t var args = Array.prototype.slice.call(arguments, 0);\n\t //args.unshift( 'model:error' );\n\t args.unshift('error');\n\t this.trigger.apply(this, args);\n\t }, this);\n\t\n\t // debugging\n\t if (this.logger) {\n\t this.listenTo(this.model, 'all', function (event) {\n\t this.info(this + '(model)', event, arguments);\n\t });\n\t }\n\t return this;\n\t },\n\t\n\t /** Build a temp div containing the new children for the view's $el.\n\t */\n\t _renderControls: function ($newRender) {\n\t this.debug(this + '(ModelListPanel)._renderControls');\n\t var json = this.model ? this.model.toJSON() : {},\n\t $controls = $(this.templates.controls(json, this));\n\t $newRender.find('.controls').replaceWith($controls);\n\t return $controls;\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** Return a string rep of the panel */\n\t toString: function () {\n\t return 'ModelListPanel(' + this.model + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t ModelListPanel.prototype.templates = function () {\n\t\n\t var controlsTemplate = BASE_MVC.wrapTemplate(['
                                    ', '
                                    ',\n\t //TODO: this is really the only difference - consider factoring titlebar out\n\t '
                                    <%- model.name %>
                                    ', '
                                    ', '
                                    <%- view.subtitle %>
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '', '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ']);\n\t\n\t return _.extend(_.clone(ListPanel.prototype.templates), {\n\t controls: controlsTemplate\n\t });\n\t }();\n\t\n\t //=============================================================================\n\t return {\n\t ListPanel: ListPanel,\n\t ModelListPanel: ModelListPanel\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 90 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This is the run workflow tool form view. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(47), __webpack_require__(5), __webpack_require__(10), __webpack_require__(19), __webpack_require__(43), __webpack_require__(8), __webpack_require__(42), __webpack_require__(144)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, Deferred, Ui, Form, FormData, ToolFormBase, Modal, Webhooks, WorkflowIcons) {\n\t\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.modal = parent.Galaxy.modal || new Modal.View();\n\t this.model = options && options.model || new Backbone.Model(options);\n\t this.deferred = new Deferred();\n\t this.setElement($('
                                    ').addClass('ui-form-composite').append(this.$message = $('
                                    ')).append(this.$header = $('
                                    ')).append(this.$steps = $('
                                    ')));\n\t $('body').append(this.$el);\n\t this._configure();\n\t this.render();\n\t $(window).resize(function () {\n\t self._refresh();\n\t });\n\t },\n\t\n\t /** Refresh height of scrollable div below header, handle scrolling by lazy loading steps */\n\t _refresh: function (step_index) {\n\t var margin = _.reduce(this.$el.children(), function (memo, child) {\n\t return memo + $(child).outerHeight();\n\t }, 0) - this.$steps.height() + 90;\n\t this.$steps.css('height', $(window).height() - margin);\n\t },\n\t\n\t /** Configures form/step options for each workflow step */\n\t _configure: function () {\n\t var self = this;\n\t this.forms = [];\n\t this.steps = [];\n\t this.links = [];\n\t this.parms = [];\n\t _.each(this.model.get('steps'), function (step, i) {\n\t Galaxy.emit.debug('tool-form-composite::initialize()', i + ' : Preparing workflow step.');\n\t var icon = WorkflowIcons[step.step_type];\n\t var title = parseInt(i + 1) + ': ' + (step.step_label || step.step_name);\n\t if (step.annotation) {\n\t title += ' - ' + step.annotation;\n\t }\n\t if (step.step_version) {\n\t title += ' (Galaxy Version ' + step.step_version + ')';\n\t }\n\t step = Utils.merge({\n\t index: i,\n\t title: _.escape(title),\n\t icon: icon || '',\n\t help: null,\n\t citations: null,\n\t collapsible: true,\n\t collapsed: i > 0 && !self._isDataStep(step),\n\t sustain_version: true,\n\t sustain_repeats: true,\n\t sustain_conditionals: true,\n\t narrow: true,\n\t text_enable: 'Edit',\n\t text_disable: 'Undo',\n\t cls_enable: 'fa fa-edit',\n\t cls_disable: 'fa fa-undo',\n\t errors: step.messages,\n\t initial_errors: true,\n\t cls: 'ui-portlet-narrow',\n\t hide_operations: true,\n\t needs_refresh: false,\n\t always_refresh: step.step_type != 'tool'\n\t }, step);\n\t self.steps[i] = step;\n\t self.links[i] = [];\n\t self.parms[i] = {};\n\t });\n\t\n\t // build linear index of step input pairs\n\t _.each(this.steps, function (step, i) {\n\t FormData.visitInputs(step.inputs, function (input, name) {\n\t self.parms[i][name] = input;\n\t });\n\t });\n\t\n\t // iterate through data input modules and collect linked sub steps\n\t _.each(this.steps, function (step, i) {\n\t _.each(step.output_connections, function (output_connection) {\n\t _.each(self.steps, function (sub_step, j) {\n\t sub_step.step_index === output_connection.input_step_index && self.links[i].push(sub_step);\n\t });\n\t });\n\t });\n\t\n\t // convert all connected data inputs to hidden fields with proper labels,\n\t // and track the linked source step\n\t _.each(this.steps, function (step, i) {\n\t _.each(self.steps, function (sub_step, j) {\n\t var connections_by_name = {};\n\t _.each(step.output_connections, function (connection) {\n\t sub_step.step_index === connection.input_step_index && (connections_by_name[connection.input_name] = connection);\n\t });\n\t _.each(self.parms[j], function (input, name) {\n\t var connection = connections_by_name[name];\n\t if (connection) {\n\t input.type = 'hidden';\n\t input.help = input.step_linked ? input.help + ', ' : '';\n\t input.help += 'Output dataset \\'' + connection.output_name + '\\' from step ' + (parseInt(i) + 1);\n\t input.step_linked = input.step_linked || [];\n\t input.step_linked.push(step);\n\t }\n\t });\n\t });\n\t });\n\t\n\t // identify and configure workflow parameters\n\t var wp_count = 0;\n\t this.wp_inputs = {};\n\t function _handleWorkflowParameter(value, callback) {\n\t var re = /\\$\\{(.+?)\\}/g;\n\t while (match = re.exec(String(value))) {\n\t var wp_name = match[1];\n\t callback(self.wp_inputs[wp_name] = self.wp_inputs[wp_name] || {\n\t label: wp_name,\n\t name: wp_name,\n\t type: 'text',\n\t color: 'hsl( ' + ++wp_count * 100 + ', 70%, 30% )',\n\t style: 'ui-form-wp-source',\n\t links: []\n\t });\n\t }\n\t }\n\t _.each(this.steps, function (step, i) {\n\t _.each(self.parms[i], function (input, name) {\n\t _handleWorkflowParameter(input.value, function (wp_input) {\n\t wp_input.links.push(step);\n\t input.wp_linked = true;\n\t input.type = 'text';\n\t input.backdrop = true;\n\t input.style = 'ui-form-wp-target';\n\t });\n\t });\n\t _.each(step.post_job_actions, function (pja) {\n\t _.each(pja.action_arguments, function (arg) {\n\t _handleWorkflowParameter(arg, function () {});\n\t });\n\t });\n\t });\n\t\n\t // select fields are shown for dynamic fields if all putative data inputs are available,\n\t // or if an explicit reference is specified as data_ref and available\n\t _.each(this.steps, function (step, i) {\n\t if (step.step_type == 'tool') {\n\t var data_resolved = true;\n\t FormData.visitInputs(step.inputs, function (input, name, context) {\n\t var is_runtime_value = input.value && input.value.__class__ == 'RuntimeValue';\n\t var is_data_input = ['data', 'data_collection'].indexOf(input.type) != -1;\n\t var data_ref = context[input.data_ref];\n\t input.step_linked && !self._isDataStep(input.step_linked) && (data_resolved = false);\n\t input.options && (input.options.length == 0 && !data_resolved || input.wp_linked) && (input.is_workflow = true);\n\t data_ref && (input.is_workflow = data_ref.step_linked && !self._isDataStep(data_ref.step_linked) || input.wp_linked);\n\t (is_data_input || input.value && input.value.__class__ == 'RuntimeValue' && !input.step_linked) && (step.collapsed = false);\n\t is_runtime_value && (input.value = input.default_value);\n\t input.flavor = 'workflow';\n\t if (!is_runtime_value && !is_data_input && input.type !== 'hidden' && !input.wp_linked) {\n\t if (input.optional || !Utils.isEmpty(input.value) && input.value !== '') {\n\t input.collapsible_value = input.value;\n\t input.collapsible_preview = true;\n\t }\n\t }\n\t });\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var self = this;\n\t this.deferred.reset();\n\t this._renderHeader();\n\t this._renderMessage();\n\t this._renderParameters();\n\t this._renderHistory();\n\t _.each(this.steps, function (step) {\n\t self._renderStep(step);\n\t });\n\t },\n\t\n\t /** Render header */\n\t _renderHeader: function () {\n\t var self = this;\n\t this.execute_btn = new Ui.Button({\n\t icon: 'fa-check',\n\t title: 'Run workflow',\n\t cls: 'btn btn-primary',\n\t onclick: function () {\n\t self._execute();\n\t }\n\t });\n\t this.$header.addClass('ui-form-header').empty().append(new Ui.Label({ title: 'Workflow: ' + this.model.get('name') }).$el).append(this.execute_btn.$el);\n\t },\n\t\n\t /** Render message */\n\t _renderMessage: function () {\n\t this.$message.empty();\n\t if (this.model.get('has_upgrade_messages')) {\n\t this.$message.append(new Ui.Message({\n\t message: 'Some tools in this workflow may have changed since it was last saved or some errors were found. The workflow may still run, but any new options will have default values. Please review the messages below to make a decision about whether the changes will affect your analysis.',\n\t status: 'warning',\n\t persistent: true,\n\t fade: false\n\t }).$el);\n\t }\n\t var step_version_changes = this.model.get('step_version_changes');\n\t if (step_version_changes && step_version_changes.length > 0) {\n\t this.$message.append(new Ui.Message({\n\t message: 'Some tools are being executed with different versions compared to those available when this workflow was last saved because the other versions are not or no longer available on this Galaxy instance. To upgrade your workflow and dismiss this message simply edit the workflow and re-save it.',\n\t status: 'warning',\n\t persistent: true,\n\t fade: false\n\t }).$el);\n\t }\n\t },\n\t\n\t /** Render workflow parameters */\n\t _renderParameters: function () {\n\t var self = this;\n\t this.wp_form = null;\n\t if (!_.isEmpty(this.wp_inputs)) {\n\t this.wp_form = new Form({ title: 'Workflow Parameters', inputs: this.wp_inputs, cls: 'ui-portlet-narrow', onchange: function () {\n\t _.each(self.wp_form.input_list, function (input_def, i) {\n\t _.each(input_def.links, function (step) {\n\t self._refreshStep(step);\n\t });\n\t });\n\t }\n\t });\n\t this._append(this.$steps.empty(), this.wp_form.$el);\n\t }\n\t },\n\t\n\t /** Render workflow parameters */\n\t _renderHistory: function () {\n\t this.history_form = new Form({\n\t cls: 'ui-portlet-narrow',\n\t title: 'History Options',\n\t inputs: [{\n\t type: 'conditional',\n\t name: 'new_history',\n\t test_param: {\n\t name: 'check',\n\t label: 'Send results to a new history',\n\t type: 'boolean',\n\t value: 'false',\n\t help: ''\n\t },\n\t cases: [{\n\t value: 'true',\n\t inputs: [{\n\t name: 'name',\n\t label: 'History name',\n\t type: 'text',\n\t value: this.model.get('name')\n\t }]\n\t }]\n\t }]\n\t });\n\t this._append(this.$steps, this.history_form.$el);\n\t },\n\t\n\t /** Render step */\n\t _renderStep: function (step) {\n\t var self = this;\n\t var form = null;\n\t this.deferred.execute(function (promise) {\n\t self.$steps.addClass('ui-steps');\n\t if (step.step_type == 'tool') {\n\t step.postchange = function (process, form) {\n\t var self = this;\n\t var current_state = {\n\t tool_id: step.id,\n\t tool_version: step.version,\n\t inputs: $.extend(true, {}, form.data.create())\n\t };\n\t form.wait(true);\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Sending current state.', current_state);\n\t Utils.request({\n\t type: 'POST',\n\t url: Galaxy.root + 'api/tools/' + step.id + '/build',\n\t data: current_state,\n\t success: function (data) {\n\t form.update(data);\n\t form.wait(false);\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Received new model.', data);\n\t process.resolve();\n\t },\n\t error: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::postchange()', 'Refresh request failed.', response);\n\t process.reject();\n\t }\n\t });\n\t };\n\t form = new ToolFormBase(step);\n\t if (step.post_job_actions && step.post_job_actions.length) {\n\t form.portlet.append($('
                                    ').addClass('ui-form-element-disabled').append($('
                                    ').addClass('ui-form-title').html('Job Post Actions')).append($('
                                    ').addClass('ui-form-preview').html(_.reduce(step.post_job_actions, function (memo, value) {\n\t return memo + ' ' + value.short_str;\n\t }, ''))));\n\t }\n\t } else {\n\t var is_simple_input = ['data_input', 'data_collection_input'].indexOf(step.step_type) != -1;\n\t _.each(step.inputs, function (input) {\n\t input.flavor = 'module';input.hide_label = is_simple_input;\n\t });\n\t form = new Form(Utils.merge({\n\t title: step.title,\n\t onchange: function () {\n\t _.each(self.links[step.index], function (link) {\n\t self._refreshStep(link);\n\t });\n\t },\n\t inputs: step.inputs && step.inputs.length > 0 ? step.inputs : [{ type: 'hidden', name: 'No options available.', ignore: null }]\n\t }, step));\n\t }\n\t self.forms[step.index] = form;\n\t self._append(self.$steps, form.$el);\n\t self._refresh();\n\t step.needs_refresh && self._refreshStep(step);\n\t form.portlet[!self.show_progress ? 'enable' : 'disable']();\n\t self.show_progress && self.execute_btn.model.set({ wait: true,\n\t wait_text: 'Preparing...',\n\t percentage: (step.index + 1) * 100.0 / self.steps.length });\n\t Galaxy.emit.debug('tool-form-composite::initialize()', step.index + ' : Workflow step state ready.', step);\n\t setTimeout(function () {\n\t promise.resolve();\n\t }, 0);\n\t });\n\t },\n\t\n\t /** Refreshes step values from source step values */\n\t _refreshStep: function (step) {\n\t var self = this;\n\t var form = this.forms[step.index];\n\t if (form) {\n\t _.each(self.parms[step.index], function (input, name) {\n\t if (input.step_linked || input.wp_linked) {\n\t var field = form.field_list[form.data.match(name)];\n\t if (field) {\n\t var new_value = undefined;\n\t if (input.step_linked) {\n\t new_value = { values: [] };\n\t _.each(input.step_linked, function (source_step) {\n\t if (self._isDataStep(source_step)) {\n\t value = self.forms[source_step.index].data.create().input;\n\t value && _.each(value.values, function (v) {\n\t new_value.values.push(v);\n\t });\n\t }\n\t });\n\t if (!input.multiple && new_value.values.length > 0) {\n\t new_value = { values: [new_value.values[0]] };\n\t }\n\t } else if (input.wp_linked) {\n\t new_value = input.value;\n\t var re = /\\$\\{(.+?)\\}/g;\n\t while (match = re.exec(input.value)) {\n\t var wp_field = self.wp_form.field_list[self.wp_form.data.match(match[1])];\n\t var wp_value = wp_field && wp_field.value();\n\t if (wp_value) {\n\t new_value = new_value.split(match[0]).join(wp_value);\n\t }\n\t }\n\t }\n\t if (new_value !== undefined) {\n\t field.value(new_value);\n\t }\n\t }\n\t }\n\t });\n\t form.trigger('change');\n\t } else {\n\t step.needs_refresh = true;\n\t }\n\t },\n\t\n\t /** Refresh the history after job submission while form is shown */\n\t _refreshHistory: function () {\n\t var self = this;\n\t var history = parent.Galaxy && parent.Galaxy.currHistoryPanel && parent.Galaxy.currHistoryPanel.model;\n\t this._refresh_history && clearTimeout(this._refresh_history);\n\t if (history) {\n\t history.refresh().success(function () {\n\t if (history.numOfUnfinishedShownContents() === 0) {\n\t self._refresh_history = setTimeout(function () {\n\t self._refreshHistory();\n\t }, history.UPDATE_DELAY);\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Build remaining steps */\n\t _execute: function () {\n\t var self = this;\n\t this.show_progress = true;\n\t this._enabled(false);\n\t this.deferred.execute(function (promise) {\n\t setTimeout(function () {\n\t promise.resolve();self._submit();\n\t }, 0);\n\t });\n\t },\n\t\n\t /** Validate and submit workflow */\n\t _submit: function () {\n\t var self = this;\n\t var history_form_data = this.history_form.data.create();\n\t var job_def = {\n\t new_history_name: history_form_data['new_history|name'] ? history_form_data['new_history|name'] : null,\n\t history_id: !history_form_data['new_history|name'] ? this.model.get('history_id') : null,\n\t replacement_params: this.wp_form ? this.wp_form.data.create() : {},\n\t parameters: {},\n\t // Tool form will submit flat maps for each parameter\n\t // (e.g. \"repeat_0|cond|param\": \"foo\" instead of nested\n\t // data structures).\n\t parameters_normalized: true,\n\t // Tool form always wants a list of invocations back\n\t // so that inputs can be batched.\n\t batch: true\n\t };\n\t var validated = true;\n\t for (var i in this.forms) {\n\t var form = this.forms[i];\n\t var job_inputs = form.data.create();\n\t var step = self.steps[i];\n\t var step_index = step.step_index;\n\t form.trigger('reset');\n\t for (var job_input_id in job_inputs) {\n\t var input_value = job_inputs[job_input_id];\n\t var input_id = form.data.match(job_input_id);\n\t var input_field = form.field_list[input_id];\n\t var input_def = form.input_list[input_id];\n\t if (!input_def.step_linked) {\n\t if (this._isDataStep(step)) {\n\t validated = input_value && input_value.values && input_value.values.length > 0;\n\t } else {\n\t validated = input_def.optional || input_def.is_workflow && input_value !== '' || !input_def.is_workflow && input_value !== null;\n\t }\n\t if (!validated) {\n\t form.highlight(input_id);\n\t break;\n\t }\n\t job_def.parameters[step_index] = job_def.parameters[step_index] || {};\n\t job_def.parameters[step_index][job_input_id] = job_inputs[job_input_id];\n\t }\n\t }\n\t if (!validated) {\n\t break;\n\t }\n\t }\n\t if (!validated) {\n\t self._enabled(true);\n\t Galaxy.emit.debug('tool-form-composite::submit()', 'Validation failed.', job_def);\n\t } else {\n\t Galaxy.emit.debug('tool-form-composite::submit()', 'Validation complete.', job_def);\n\t Utils.request({\n\t type: 'POST',\n\t url: Galaxy.root + 'api/workflows/' + this.model.id + '/invocations',\n\t data: job_def,\n\t success: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::submit', 'Submission successful.', response);\n\t self.$el.children().hide();\n\t self.$el.append(self._templateSuccess(response));\n\t\n\t // Show Webhook if job is running\n\t if ($.isArray(response) && response.length > 0) {\n\t self.$el.append($('
                                    ', { id: 'webhook-view' }));\n\t var WebhookApp = new Webhooks.WebhookView({\n\t urlRoot: Galaxy.root + 'api/webhooks/workflow',\n\t toolId: job_def.tool_id,\n\t toolVersion: job_def.tool_version\n\t });\n\t }\n\t\n\t self._refreshHistory();\n\t },\n\t error: function (response) {\n\t Galaxy.emit.debug('tool-form-composite::submit', 'Submission failed.', response);\n\t var input_found = false;\n\t if (response && response.err_data) {\n\t for (var i in self.forms) {\n\t var form = self.forms[i];\n\t var step_related_errors = response.err_data[form.model.get('step_index')];\n\t if (step_related_errors) {\n\t var error_messages = form.data.matchResponse(step_related_errors);\n\t for (var input_id in error_messages) {\n\t form.highlight(input_id, error_messages[input_id]);\n\t input_found = true;\n\t break;\n\t }\n\t }\n\t }\n\t }\n\t if (!input_found) {\n\t self.modal.show({\n\t title: 'Workflow submission failed',\n\t body: self._templateError(job_def, response && response.err_msg),\n\t buttons: {\n\t 'Close': function () {\n\t self.modal.hide();\n\t }\n\t }\n\t });\n\t }\n\t },\n\t complete: function () {\n\t self._enabled(true);\n\t }\n\t });\n\t }\n\t },\n\t\n\t /** Append new dom to body */\n\t _append: function ($container, $el) {\n\t $container.append('

                                    ').append($el);\n\t },\n\t\n\t /** Set enabled/disabled state */\n\t _enabled: function (enabled) {\n\t this.execute_btn.model.set({ wait: !enabled, wait_text: 'Sending...', percentage: -1 });\n\t this.wp_form && this.wp_form.portlet[enabled ? 'enable' : 'disable']();\n\t this.history_form && this.history_form.portlet[enabled ? 'enable' : 'disable']();\n\t _.each(this.forms, function (form) {\n\t form && form.portlet[enabled ? 'enable' : 'disable']();\n\t });\n\t },\n\t\n\t /** Is data input module/step */\n\t _isDataStep: function (steps) {\n\t lst = $.isArray(steps) ? steps : [steps];\n\t for (var i = 0; i < lst.length; i++) {\n\t var step = lst[i];\n\t if (!step || !step.step_type || !step.step_type.startsWith('data')) {\n\t return false;\n\t }\n\t }\n\t return true;\n\t },\n\t\n\t /** Templates */\n\t _templateSuccess: function (response) {\n\t if ($.isArray(response) && response.length > 0) {\n\t return $('

                                    ').addClass('donemessagelarge').append($('

                                    ').html('Successfully invoked workflow ' + Utils.sanitize(this.model.get('name')) + '' + (response.length > 1 ? ' ' + response.length + ' times' : '') + '.')).append($('

                                    ').append('').text('You can check the status of queued jobs and view the resulting data by refreshing the History pane. When the job has been run the status will change from \\'running\\' to \\'finished\\' if completed successfully or \\'error\\' if problems were encountered.'));\n\t } else {\n\t return this._templateError(response, 'Invalid success response. No invocations found.');\n\t }\n\t },\n\t\n\t _templateError: function (response, err_msg) {\n\t return $('

                                    ').addClass('errormessagelarge').append($('

                                    ').text('The server could not complete the request. Please contact the Galaxy Team if this error persists. ' + (JSON.stringify(err_msg) || ''))).append($('

                                    ').text(JSON.stringify(response, null, 4)));\n\t        }\n\t    });\n\t    return {\n\t        View: View\n\t    };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 91 */,\n/* 92 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_l) {\n\t    'use strict';\n\t\n\t    //TODO: toastr is another possibility - I didn't see where I might add details, tho\n\t\n\t    /* ============================================================================\n\t    Error modals meant to replace the o-so-easy alerts.\n\t    \n\t    These are currently styled as errormessages but use the Galaxy.modal\n\t    infrastructure to be shown/closed. They're capable of showing details in a\n\t    togglable dropdown and the details are formatted in a pre.\n\t    \n\t    Example:\n\t        errorModal( 'Heres a message', 'A Title', { some_details: 'here' });\n\t        errorModal( 'Heres a message' ); // no details, title is 'Error'\n\t    \n\t    There are three specialized forms:\n\t        offlineErrorModal       a canned response for when there's no connection\n\t        badGatewayErrorModal    canned response for when Galaxy is restarting\n\t        ajaxErrorModal          plugable into any Backbone class as an\n\t            error event handler by accepting the error args: model, xhr, options\n\t    \n\t    Examples:\n\t        if( navigator.offLine ){ offlineErrorModal(); }\n\t        if( xhr.status === 502 ){ badGatewayErrorModal(); }\n\t        this.listenTo( this.model, 'error', ajaxErrorModal );\n\t    \n\t    ============================================================================ */\n\t\n\t    var CONTACT_MSG = _l('Please contact a Galaxy administrator if the problem persists.');\n\t    var DEFAULT_AJAX_ERR_MSG = _l('An error occurred while updating information with the server.');\n\t    var DETAILS_MSG = _l('The following information can assist the developers in finding the source of the error:');\n\t\n\t    /** private helper that builds the modal and handles adding details */\n\t    function _errorModal(message, title, details) {\n\t        // create and return the modal, adding details button only if needed\n\t        Galaxy.modal.show({\n\t            title: title,\n\t            body: message,\n\t            closing_events: true,\n\t            buttons: { Ok: function () {\n\t                    Galaxy.modal.hide();\n\t                } }\n\t        });\n\t        Galaxy.modal.$el.addClass('error-modal');\n\t\n\t        if (details) {\n\t            Galaxy.modal.$('.error-details').add(Galaxy.modal.$('button:contains(\"Details\")')).remove();\n\t            $('
                                    ').addClass('error-details').hide().appendTo(Galaxy.modal.$('.modal-content')).append([$('

                                    ').text(DETAILS_MSG), $('

                                    ').text(JSON.stringify(details, null, '  '))]);\n\t\n\t            $('').appendTo(Galaxy.modal.$('.buttons')).click(function () {\n\t                Galaxy.modal.$('.error-details').toggle();\n\t            });\n\t        }\n\t        return Galaxy.modal;\n\t    }\n\t\n\t    /** Display a modal showing an error message but fallback to alert if there's no modal */\n\t    function errorModal(message, title, details) {\n\t        if (!message) {\n\t            return;\n\t        }\n\t\n\t        message = _l(message);\n\t        title = _l(title) || _l('Error:');\n\t        if (window.Galaxy && Galaxy.modal) {\n\t            return _errorModal(message, title, details);\n\t        }\n\t\n\t        alert(title + '\\n\\n' + message);\n\t        console.log('error details:', JSON.stringify(details));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** display a modal when the user may be offline */\n\t    function offlineErrorModal() {\n\t        return errorModal(_l('You appear to be offline. Please check your connection and try again.'), _l('Offline?'));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** 502 messages that should be displayed when galaxy is restarting */\n\t    function badGatewayErrorModal() {\n\t        return errorModal(_l('Galaxy is currently unreachable. Please try again in a few minutes.') + ' ' + CONTACT_MSG, _l('Cannot connect to Galaxy'));\n\t    }\n\t\n\t    // ----------------------------------------------------------------------------\n\t    /** display a modal (with details) about a failed Backbone ajax operation */\n\t    function ajaxErrorModal(model, xhr, options, message, title) {\n\t        message = message || DEFAULT_AJAX_ERR_MSG;\n\t        message += ' ' + CONTACT_MSG;\n\t        title = title || _l('An error occurred');\n\t        var details = _ajaxDetails(model, xhr, options);\n\t        return errorModal(message, title, details);\n\t    }\n\t\n\t    /** build details which may help debugging the ajax call */\n\t    function _ajaxDetails(model, xhr, options) {\n\t        return {\n\t            //TODO: still can't manage Raven id\n\t            raven: _.result(window.Raven, 'lastEventId'),\n\t            userAgent: navigator.userAgent,\n\t            onLine: navigator.onLine,\n\t            version: _.result(Galaxy.config, 'version_major'),\n\t            xhr: _.omit(xhr, _.functions(xhr)),\n\t            options: _.omit(options, 'xhr'),\n\t            // add ajax data from Galaxy object cache\n\t            url: _.result(Galaxy.lastAjax, 'url'),\n\t            data: _.result(Galaxy.lastAjax, 'data'),\n\t            // backbone stuff (auto-redacting email for user)\n\t            model: _.result(model, 'toJSON', model + ''),\n\t            user: _.omit(_.result(Galaxy.user, 'toJSON'), 'email')\n\t        };\n\t    }\n\t\n\t    //=============================================================================\n\t    return {\n\t        errorModal: errorModal,\n\t        offlineErrorModal: offlineErrorModal,\n\t        badGatewayErrorModal: badGatewayErrorModal,\n\t        ajaxErrorModal: ajaxErrorModal\n\t    };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 93 */,\n/* 94 */,\n/* 95 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, $) {(function (factory) {\n\t    if (true) {\n\t        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t    } else {\n\t        // Browser globals\n\t        factory(jQuery);\n\t    }\n\t})(function () {\n\t    //=============================================================================\n\t\n\t    jQuery.fn.extend({\n\t        hoverhighlight: function $hoverhighlight(scope, color) {\n\t            scope = scope || 'body';\n\t            if (!this.length) {\n\t                return this;\n\t            }\n\t\n\t            $(this).each(function () {\n\t                var $this = $(this),\n\t                    targetSelector = $this.data('target');\n\t\n\t                if (targetSelector) {\n\t                    $this.mouseover(function (ev) {\n\t                        $(targetSelector, scope).css({\n\t                            background: color\n\t                        });\n\t                    }).mouseout(function (ev) {\n\t                        $(targetSelector).css({\n\t                            background: ''\n\t                        });\n\t                    });\n\t                }\n\t            });\n\t            return this;\n\t        }\n\t    });\n\t});\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 96 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function($, jQuery) {// from: https://raw.githubusercontent.com/umdjs/umd/master/jqueryPlugin.js\n\t// Uses AMD or browser globals to create a jQuery plugin.\n\t(function (factory) {\n\t    if (true) {\n\t        //TODO: So...this turns out to be an all or nothing thing. If I load jQuery in the define below, it will\n\t        //  (of course) wipe the old jquery *and all the plugins loaded into it*. So the define below *is still\n\t        //  relying on jquery being loaded globally* in order to preserve plugins.\n\t        !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t    } else {\n\t        // Browser globals\n\t        factory(jQuery);\n\t    }\n\t})(function () {\n\t    var _l = window._l || function (s) {\n\t        return s;\n\t    };\n\t\n\t    //TODO: consolidate with tool menu functionality, use there\n\t\n\t    /** searchInput: (jQuery plugin)\n\t     *      Creates a search input, a clear button, and loading indicator\n\t     *      within the selected node.\n\t     *\n\t     *      When the user either presses return or enters some minimal number\n\t     *      of characters, a callback is called. Pressing ESC when the input\n\t     *      is focused will clear the input and call a separate callback.\n\t     */\n\t    function searchInput(parentNode, options) {\n\t        var KEYCODE_ESC = 27,\n\t            KEYCODE_RETURN = 13,\n\t            $parentNode = $(parentNode),\n\t            firstSearch = true,\n\t            defaults = {\n\t            initialVal: '',\n\t            name: 'search',\n\t            placeholder: 'search',\n\t            classes: '',\n\t            onclear: function () {},\n\t            onfirstsearch: null,\n\t            onsearch: function (inputVal) {},\n\t            minSearchLen: 0,\n\t            escWillClear: true,\n\t            oninit: function () {}\n\t        };\n\t\n\t        // .................................................................... input rendering and events\n\t        // visually clear the search, trigger an event, and call the callback\n\t        function clearSearchInput(event) {\n\t            var $input = $(this).parent().children('input');\n\t            $input.val('').trigger('searchInput.clear').blur();\n\t            options.onclear();\n\t        }\n\t\n\t        // search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)\n\t        function search(event, searchTerms) {\n\t            if (!searchTerms) {\n\t                return clearSearchInput();\n\t            }\n\t            $(this).trigger('search.search', searchTerms);\n\t            if (typeof options.onfirstsearch === 'function' && firstSearch) {\n\t                firstSearch = false;\n\t                options.onfirstsearch(searchTerms);\n\t            } else {\n\t                options.onsearch(searchTerms);\n\t            }\n\t        }\n\t\n\t        // .................................................................... input rendering and events\n\t        function inputTemplate() {\n\t            // class search-query is bootstrap 2.3 style that now lives in base.less\n\t            return [''].join('');\n\t        }\n\t\n\t        // the search input that responds to keyboard events and displays the search value\n\t        function $input() {\n\t            return $(inputTemplate())\n\t            // select all text on a focus\n\t            .focus(function (event) {\n\t                $(this).select();\n\t            })\n\t            // attach behaviors to esc, return if desired, search on some min len string\n\t            .keyup(function (event) {\n\t                event.preventDefault();\n\t                event.stopPropagation();\n\t\n\t                // esc key will clear if desired\n\t                if (event.which === KEYCODE_ESC && options.escWillClear) {\n\t                    clearSearchInput.call(this, event);\n\t                } else {\n\t                    var searchTerms = $(this).val();\n\t                    // return key or the search string len > minSearchLen (if not 0) triggers search\n\t                    if (event.which === KEYCODE_RETURN || options.minSearchLen && searchTerms.length >= options.minSearchLen) {\n\t                        search.call(this, event, searchTerms);\n\t                    }\n\t                }\n\t            }).val(options.initialVal);\n\t        }\n\t\n\t        // .................................................................... clear button rendering and events\n\t        // a button for clearing the search bar, placed on the right hand side\n\t        function $clearBtn() {\n\t            return $([''].join('')).tooltip({ placement: 'bottom' }).click(function (event) {\n\t                clearSearchInput.call(this, event);\n\t            });\n\t        }\n\t\n\t        // .................................................................... loadingIndicator rendering\n\t        // a button for clearing the search bar, placed on the right hand side\n\t        function $loadingIndicator() {\n\t            return $([''].join('')).hide().tooltip({ placement: 'bottom' });\n\t        }\n\t\n\t        // .................................................................... commands\n\t        // visually swap the load, clear buttons\n\t        function toggleLoadingIndicator() {\n\t            $parentNode.find('.search-loading').toggle();\n\t            $parentNode.find('.search-clear').toggle();\n\t        }\n\t\n\t        // .................................................................... init\n\t        // string command (not constructor)\n\t        if (jQuery.type(options) === 'string') {\n\t            if (options === 'toggle-loading') {\n\t                toggleLoadingIndicator();\n\t            }\n\t            return $parentNode;\n\t        }\n\t\n\t        // initial render\n\t        if (jQuery.type(options) === 'object') {\n\t            options = jQuery.extend(true, {}, defaults, options);\n\t        }\n\t        //NOTE: prepended\n\t        return $parentNode.addClass('search-input').prepend([$input(), $clearBtn(), $loadingIndicator()]);\n\t    }\n\t\n\t    // as jq plugin\n\t    jQuery.fn.extend({\n\t        searchInput: function $searchInput(options) {\n\t            return this.each(function () {\n\t                return searchInput(this, options);\n\t            });\n\t        }\n\t    });\n\t});\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 97 */,\n/* 98 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {\n\t    // Alphanumeric/natural sort fn\n\t    function naturalSort(a, b) {\n\t        // setup temp-scope variables for comparison evauluation\n\t        var re = /(-?[0-9\\.]+)/g,\n\t            x = a.toString().toLowerCase() || '',\n\t            y = b.toString().toLowerCase() || '',\n\t            nC = String.fromCharCode(0),\n\t            xN = x.replace(re, nC + '$1' + nC).split(nC),\n\t            yN = y.replace(re, nC + '$1' + nC).split(nC),\n\t            xD = new Date(x).getTime(),\n\t            yD = xD ? new Date(y).getTime() : null;\n\t        // natural sorting of dates\n\t        if (yD) {\n\t            if (xD < yD) {\n\t                return -1;\n\t            } else if (xD > yD) {\n\t                return 1;\n\t            }\n\t        }\n\t        // natural sorting through split numeric strings and default strings\n\t        var oFxNcL, oFyNcL;\n\t        for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {\n\t            oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];\n\t            oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];\n\t            if (oFxNcL < oFyNcL) {\n\t                return -1;\n\t            } else if (oFxNcL > oFyNcL) {\n\t                return 1;\n\t            }\n\t        }\n\t        return 0;\n\t    }\n\t\n\t    return naturalSort;\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 99 */,\n/* 100 */,\n/* 101 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Backbone) {var Ui = __webpack_require__(5),\n\t    historyOptionsMenu = __webpack_require__(132);\n\tCurrentHistoryView = __webpack_require__(129).CurrentHistoryView, _l = __webpack_require__(6);\n\t\n\t/** the right hand panel in the analysis page that shows the current history */\n\tvar HistoryPanel = Backbone.View.extend({\n\t\n\t    initialize: function (page, options) {\n\t        var self = this;\n\t        this.userIsAnonymous = Galaxy.user.isAnonymous();\n\t        this.allow_user_dataset_purge = options.config.allow_user_dataset_purge;\n\t        this.root = options.root;\n\t\n\t        // view of the current history\n\t        this.historyView = new CurrentHistoryView({\n\t            className: CurrentHistoryView.prototype.className + ' middle',\n\t            purgeAllowed: this.allow_user_dataset_purge,\n\t            linkTarget: 'galaxy_main'\n\t        });\n\t\n\t        // add history panel to Galaxy object\n\t        Galaxy.currHistoryPanel = this.historyView;\n\t        Galaxy.currHistoryPanel.listenToGalaxy(Galaxy);\n\t\n\t        // build buttons\n\t        this.buttonRefresh = new Ui.ButtonLink({\n\t            id: 'history-refresh-button',\n\t            title: 'Refresh history',\n\t            cls: 'panel-header-button',\n\t            icon: 'fa fa-refresh',\n\t            onclick: function () {\n\t                self.historyView.loadCurrentHistory();\n\t            }\n\t        });\n\t        this.buttonOptions = new Ui.ButtonLink({\n\t            id: 'history-options-button',\n\t            title: 'History options',\n\t            cls: 'panel-header-button',\n\t            target: 'galaxy_main',\n\t            icon: 'fa fa-cog',\n\t            href: this.root + 'root/history_options'\n\t        });\n\t        this.buttonViewMulti = new Ui.ButtonLink({\n\t            id: 'history-view-multi-button',\n\t            title: 'View all histories',\n\t            cls: 'panel-header-button',\n\t            icon: 'fa fa-columns',\n\t            href: this.root + 'history/view_multiple'\n\t        });\n\t\n\t        // define components\n\t        this.model = new Backbone.Model({\n\t            cls: 'history-right-panel',\n\t            title: _l('History'),\n\t            buttons: [this.buttonRefresh, this.buttonOptions, this.buttonViewMulti]\n\t        });\n\t\n\t        // build body template and connect history view\n\t        this.setElement(this._template());\n\t        this.historyView.setElement(this.$el);\n\t        this.historyView.connectToQuotaMeter(Galaxy.quotaMeter);\n\t        this.historyView.loadCurrentHistory();\n\t\n\t        // fetch to update the quota meter adding 'current' for any anon-user's id\n\t        Galaxy.listenTo(this.historyView, 'history-size-change', function () {\n\t            Galaxy.user.fetch({ url: Galaxy.user.urlRoot() + '/' + (Galaxy.user.id || 'current') });\n\t        });\n\t    },\n\t\n\t    render: function () {\n\t        this.optionsMenu = historyOptionsMenu(this.buttonOptions.$el, {\n\t            anonymous: this.userIsAnonymous,\n\t            purgeAllowed: this.allow_user_dataset_purge,\n\t            root: this.root\n\t        });\n\t        this.buttonViewMulti.$el[!this.userIsAnonymous ? 'show' : 'hide']();\n\t    },\n\t\n\t    /** add history view div */\n\t    _template: function (data) {\n\t        return ['
                                    '].join('');\n\t },\n\t\n\t toString: function () {\n\t return 'historyPanel';\n\t }\n\t});\n\t\n\tmodule.exports = HistoryPanel;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))\n\n/***/ },\n/* 102 */\n/***/ function(module, exports, __webpack_require__) {\n\n\t/* WEBPACK VAR INJECTION */(function(Backbone, _) {var Tools = __webpack_require__(66),\n\t Upload = __webpack_require__(140),\n\t _l = __webpack_require__(6),\n\t ToolForm = __webpack_require__(90);\n\t\n\tvar ToolPanel = Backbone.View.extend({\n\t initialize: function (page, options) {\n\t // access configuration options\n\t var config = options.config;\n\t this.root = options.root;\n\t\n\t /** @type {Object[]} descriptions of user's workflows to be shown in the tool menu */\n\t this.stored_workflow_menu_entries = config.stored_workflow_menu_entries || [];\n\t\n\t // create tool search, tool panel, and tool panel view.\n\t var tool_search = new Tools.ToolSearch({\n\t hidden: false\n\t });\n\t var tools = new Tools.ToolCollection(config.toolbox);\n\t this.tool_panel = new Tools.ToolPanel({\n\t tool_search: tool_search,\n\t tools: tools,\n\t layout: config.toolbox_in_panel\n\t });\n\t this.tool_panel_view = new Tools.ToolPanelView({ model: this.tool_panel });\n\t\n\t // add upload modal\n\t this.upload_button = new Upload({\n\t nginx_upload_path: config.nginx_upload_path,\n\t ftp_upload_site: config.ftp_upload_site,\n\t default_genome: config.default_genome,\n\t default_extension: config.default_extension\n\t });\n\t\n\t // add uploader button to Galaxy object\n\t Galaxy.upload = this.upload_button;\n\t\n\t // components for panel definition\n\t this.model = new Backbone.Model({\n\t title: _l('Tools'),\n\t buttons: [this.upload_button]\n\t });\n\t\n\t // build body template\n\t this.setElement(this._template());\n\t },\n\t\n\t render: function () {\n\t // if there are tools, render panel and display everything\n\t var self = this;\n\t if (this.tool_panel.get('layout').size() > 0) {\n\t this.$el.prepend(this.tool_panel_view.$el);\n\t this.tool_panel_view.render();\n\t }\n\t // build the dom for the workflow portion of the tool menu\n\t // add internal workflow list\n\t self.$('#internal-workflows').append(self._templateAllWorkflow({\n\t title: _l('All workflows'),\n\t href: 'workflow'\n\t }));\n\t _.each(this.stored_workflow_menu_entries, function (menu_entry) {\n\t self.$('#internal-workflows').append(self._templateWorkflowLink({\n\t title: menu_entry.stored_workflow.name,\n\t href: 'workflow/run?id=' + menu_entry.encoded_stored_workflow_id\n\t }));\n\t });\n\t },\n\t\n\t /** build a link to one tool */\n\t _templateTool: function (tool) {\n\t return [''].join('');\n\t },\n\t\n\t /** build a link to 'All Workflows' */\n\t _templateAllWorkflow: function (tool) {\n\t return ['
                                    ',\n\t // global\n\t '', tool.title, '', '
                                    '].join('');\n\t },\n\t\n\t /** build links to workflows in toolpanel */\n\t _templateWorkflowLink: function (wf) {\n\t return [''].join('');\n\t },\n\t\n\t /** override to include inital menu dom and workflow section */\n\t _template: function () {\n\t return ['
                                    ', '
                                    ', '
                                    ', '', _l('Search did not match any tools.'), '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '', _l('Workflows'), '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    '].join('');\n\t },\n\t\n\t toString: function () {\n\t return 'toolPanel';\n\t }\n\t});\n\t\n\tmodule.exports = ToolPanel;\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3)))\n\n/***/ },\n/* 103 */,\n/* 104 */,\n/* 105 */,\n/* 106 */,\n/* 107 */,\n/* 108 */,\n/* 109 */,\n/* 110 */,\n/* 111 */,\n/* 112 */,\n/* 113 */,\n/* 114 */,\n/* 115 */,\n/* 116 */,\n/* 117 */,\n/* 118 */,\n/* 119 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(jQuery, _) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(55), __webpack_require__(82), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_LI, DATASET_LI_EDIT, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t //==============================================================================\n\t\n\t var DCListItemView = DC_LI.DCListItemView;\n\t /** @class Edit view for DatasetCollection.\n\t */\n\t var DCListItemEdit = DCListItemView.extend(\n\t /** @lends DCListItemEdit.prototype */{\n\t\n\t /** override to add linkTarget */\n\t initialize: function (attributes) {\n\t DCListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t var DCEListItemView = DC_LI.DCEListItemView;\n\t /** @class Read only view for DatasetCollectionElement.\n\t */\n\t var DCEListItemEdit = DCEListItemView.extend(\n\t /** @lends DCEListItemEdit.prototype */{\n\t //TODO: this might be expendable - compacted with HDAListItemView\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t DCEListItemView.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t // NOTE: this does not inherit from DatasetDCEListItemView as you would expect\n\t //TODO: but should - if we can find something simpler than using diamond\n\t /** @class Editable view for a DatasetCollectionElement that is also an DatasetAssociation\n\t * (a dataset contained in a dataset collection).\n\t */\n\t var DatasetDCEListItemEdit = DATASET_LI_EDIT.DatasetListItemEdit.extend(\n\t /** @lends DatasetDCEListItemEdit.prototype */{\n\t\n\t /** set up */\n\t initialize: function (attributes) {\n\t DATASET_LI_EDIT.DatasetListItemEdit.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t // NOTE: this does not inherit from DatasetDCEListItemView - so we duplicate this here\n\t //TODO: fix\n\t /** In this override, only get details if in the ready state.\n\t * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n\t */\n\t _fetchModelDetails: function () {\n\t var view = this;\n\t if (view.model.inReadyState() && !view.model.hasDetails()) {\n\t return view.model.fetch({ silent: true });\n\t }\n\t return jQuery.when();\n\t },\n\t\n\t /** Override to remove delete button */\n\t _renderDeleteButton: function () {\n\t return null;\n\t },\n\t\n\t // ......................................................................... misc\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'DatasetDCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t // ............................................................................ TEMPLATES\n\t /** underscore templates */\n\t DatasetDCEListItemEdit.prototype.templates = function () {\n\t\n\t return _.extend({}, DATASET_LI_EDIT.DatasetListItemEdit.prototype.templates, {\n\t titleBar: DC_LI.DatasetDCEListItemView.prototype.templates.titleBar\n\t });\n\t }();\n\t\n\t //==============================================================================\n\t /** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n\t * (a nested DC).\n\t */\n\t var NestedDCDCEListItemEdit = DC_LI.NestedDCDCEListItemView.extend(\n\t /** @lends NestedDCDCEListItemEdit.prototype */{\n\t\n\t /** String representation */\n\t toString: function () {\n\t var modelString = this.model ? this.model + '' : '(no model)';\n\t return 'NestedDCDCEListItemEdit(' + modelString + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t DCListItemEdit: DCListItemEdit,\n\t DCEListItemEdit: DCEListItemEdit,\n\t DatasetDCEListItemEdit: DatasetDCEListItemEdit,\n\t NestedDCDCEListItemEdit: NestedDCDCEListItemEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1), __webpack_require__(3)))\n\n/***/ },\n/* 120 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(81), __webpack_require__(56), __webpack_require__(119), __webpack_require__(7), __webpack_require__(65), __webpack_require__(25), __webpack_require__(6), __webpack_require__(24)], __WEBPACK_AMD_DEFINE_RESULT__ = function (DC_VIEW, DC_MODEL, DC_EDIT, BASE_MVC, TAGS, faIconButton, _l) {\n\t\n\t 'use strict';\n\t /* =============================================================================\n\t TODO:\n\t \n\t ============================================================================= */\n\t /** @class editable View/Controller for a dataset collection.\n\t */\n\t\n\t var _super = DC_VIEW.CollectionView;\n\t var CollectionViewEdit = _super.extend(\n\t /** @lends CollectionView.prototype */{\n\t //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\t\n\t /** logger used to record this.log messages, commonly set to console */\n\t //logger : console,\n\t\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_EDIT.DatasetDCEListItemEdit,\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit,\n\t\n\t // ......................................................................... SET UP\n\t /** Set up the view, set up storage, bind listeners to HistoryContents events\n\t * @param {Object} attributes optional settings for the panel\n\t */\n\t initialize: function (attributes) {\n\t _super.prototype.initialize.call(this, attributes);\n\t },\n\t\n\t /** In this override, make the collection name editable\n\t */\n\t _setUpBehaviors: function ($where) {\n\t $where = $where || this.$el;\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t if (!this.model) {\n\t return;\n\t }\n\t\n\t // anon users shouldn't have access to any of the following\n\t if (!Galaxy.user || Galaxy.user.isAnonymous()) {\n\t return;\n\t }\n\t\n\t this.tagsEditorShown = true;\n\t\n\t //TODO: extract\n\t var panel = this,\n\t nameSelector = '> .controls .name';\n\t $where.find(nameSelector).attr('title', _l('Click to rename collection')).tooltip({ placement: 'bottom' }).make_text_editable({\n\t on_finish: function (newName) {\n\t var previousName = panel.model.get('name');\n\t if (newName && newName !== previousName) {\n\t panel.$el.find(nameSelector).text(newName);\n\t panel.model.save({ name: newName }).fail(function () {\n\t panel.$el.find(nameSelector).text(panel.model.previous('name'));\n\t });\n\t } else {\n\t panel.$el.find(nameSelector).text(previousName);\n\t }\n\t }\n\t });\n\t this.tagsEditor = new TAGS.TagsEditor({\n\t model: this.model,\n\t el: $where.find('.tags-display'),\n\t onshowFirstTime: function () {\n\t this.render();\n\t },\n\t usePrompt: false\n\t });\n\t this.tagsEditor.toggle(true);\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'CollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class non-editable, read-only View/Controller for a dataset collection. */\n\t var ListCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for datasets */\n\t DatasetDCEViewClass: DC_EDIT.DatasetDCEListItemEdit,\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class Editable, read-only View/Controller for a dataset collection. */\n\t var PairCollectionViewEdit = ListCollectionViewEdit.extend(\n\t /** @lends PairCollectionViewEdit.prototype */{\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class Editable (roughly since these collections are immutable),\n\t * View/Controller for a dataset collection.\n\t */\n\t var NestedPairCollectionViewEdit = PairCollectionViewEdit.extend(\n\t /** @lends NestedPairCollectionViewEdit.prototype */{\n\t\n\t /** Override to remove the editable text from the name/identifier - these collections are considered immutable */\n\t _setUpBehaviors: function ($where) {\n\t _super.prototype._setUpBehaviors.call(this, $where);\n\t },\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'NestedPairCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class editable, View/Controller for a list of pairs dataset collection. */\n\t var ListOfPairsCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListOfPairsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit.extend({\n\t foldoutPanelClass: NestedPairCollectionViewEdit\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfPairsCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t // =============================================================================\n\t /** @class View/Controller for a list of lists dataset collection. */\n\t var ListOfListsCollectionViewEdit = CollectionViewEdit.extend(\n\t /** @lends ListOfListsCollectionView.prototype */{\n\t\n\t //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n\t /** sub view class used for nested collections */\n\t NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit.extend({\n\t foldoutPanelClass: NestedPairCollectionViewEdit\n\t }),\n\t\n\t // ........................................................................ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'ListOfListsCollectionViewEdit(' + (this.model ? this.model.get('name') : '') + ')';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t return {\n\t CollectionViewEdit: CollectionViewEdit,\n\t ListCollectionViewEdit: ListCollectionViewEdit,\n\t PairCollectionViewEdit: PairCollectionViewEdit,\n\t ListOfPairsCollectionViewEdit: ListOfPairsCollectionViewEdit,\n\t ListOfListsCollectionViewEdit: ListOfListsCollectionViewEdit\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\n/***/ },\n/* 121 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(152), __webpack_require__(98), __webpack_require__(80), __webpack_require__(7), __webpack_require__(6), __webpack_require__(95)], __WEBPACK_AMD_DEFINE_RESULT__ = function (levenshteinDistance, naturalSort, baseCreator, baseMVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /* ============================================================================\n\t TODO:\n\t \n\t \n\t PROGRAMMATICALLY:\n\t currPanel.once( 'rendered', function(){\n\t currPanel.showSelectors();\n\t currPanel.selectAll();\n\t _.last( currPanel.actionsPopup.options ).func();\n\t });\n\t \n\t ============================================================================ */\n\t /** A view for paired datasets in the collections creator.\n\t */\n\t var PairView = Backbone.View.extend(baseMVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t tagName: 'li',\n\t className: 'dataset paired',\n\t\n\t initialize: function (attributes) {\n\t this.pair = attributes.pair || {};\n\t },\n\t\n\t template: _.template(['<%- pair.forward.name %>', '', '<%- pair.name %>', '', '<%- pair.reverse.name %>'].join('')),\n\t\n\t render: function () {\n\t this.$el.attr('draggable', true).data('pair', this.pair).html(this.template({ pair: this.pair })).addClass('flex-column-container');\n\t return this;\n\t },\n\t\n\t events: {\n\t 'dragstart': '_dragstart',\n\t 'dragend': '_dragend',\n\t 'dragover': '_sendToParent',\n\t 'drop': '_sendToParent'\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragstart: function (ev) {\n\t ev.currentTarget.style.opacity = '0.4';\n\t if (ev.originalEvent) {\n\t ev = ev.originalEvent;\n\t }\n\t\n\t ev.dataTransfer.effectAllowed = 'move';\n\t ev.dataTransfer.setData('text/plain', JSON.stringify(this.pair));\n\t\n\t this.$el.parent().trigger('pair.dragstart', [this]);\n\t },\n\t\n\t /** dragging pairs for re-ordering */\n\t _dragend: function (ev) {\n\t ev.currentTarget.style.opacity = '1.0';\n\t this.$el.parent().trigger('pair.dragend', [this]);\n\t },\n\t\n\t /** manually bubble up an event to the parent/container */\n\t _sendToParent: function (ev) {\n\t this.$el.parent().trigger(ev);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'PairView(' + this.pair.name + ')';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t /** returns an autopair function that uses the provided options.match function */\n\t function autoPairFnBuilder(options) {\n\t options = options || {};\n\t options.createPair = options.createPair || function _defaultCreatePair(params) {\n\t params = params || {};\n\t var a = params.listA.splice(params.indexA, 1)[0],\n\t b = params.listB.splice(params.indexB, 1)[0],\n\t aInBIndex = params.listB.indexOf(a),\n\t bInAIndex = params.listA.indexOf(b);\n\t if (aInBIndex !== -1) {\n\t params.listB.splice(aInBIndex, 1);\n\t }\n\t if (bInAIndex !== -1) {\n\t params.listA.splice(bInAIndex, 1);\n\t }\n\t return this._pair(a, b, { silent: true });\n\t };\n\t // compile these here outside of the loop\n\t var _regexps = [];\n\t function getRegExps() {\n\t if (!_regexps.length) {\n\t _regexps = [new RegExp(this.filters[0]), new RegExp(this.filters[1])];\n\t }\n\t return _regexps;\n\t }\n\t // mangle params as needed\n\t options.preprocessMatch = options.preprocessMatch || function _defaultPreprocessMatch(params) {\n\t var regexps = getRegExps.call(this);\n\t return _.extend(params, {\n\t matchTo: params.matchTo.name.replace(regexps[0], ''),\n\t possible: params.possible.name.replace(regexps[1], '')\n\t });\n\t };\n\t\n\t return function _strategy(params) {\n\t this.debug('autopair _strategy ---------------------------');\n\t params = params || {};\n\t var listA = params.listA,\n\t listB = params.listB,\n\t indexA = 0,\n\t indexB,\n\t bestMatch = {\n\t score: 0.0,\n\t index: null\n\t },\n\t paired = [];\n\t //console.debug( 'params:', JSON.stringify( params, null, ' ' ) );\n\t this.debug('starting list lens:', listA.length, listB.length);\n\t this.debug('bestMatch (starting):', JSON.stringify(bestMatch, null, ' '));\n\t\n\t while (indexA < listA.length) {\n\t var matchTo = listA[indexA];\n\t bestMatch.score = 0.0;\n\t\n\t for (indexB = 0; indexB < listB.length; indexB++) {\n\t var possible = listB[indexB];\n\t this.debug(indexA + ':' + matchTo.name);\n\t this.debug(indexB + ':' + possible.name);\n\t\n\t // no matching with self\n\t if (listA[indexA] !== listB[indexB]) {\n\t bestMatch = options.match.call(this, options.preprocessMatch.call(this, {\n\t matchTo: matchTo,\n\t possible: possible,\n\t index: indexB,\n\t bestMatch: bestMatch\n\t }));\n\t this.debug('bestMatch:', JSON.stringify(bestMatch, null, ' '));\n\t if (bestMatch.score === 1.0) {\n\t this.debug('breaking early due to perfect match');\n\t break;\n\t }\n\t }\n\t }\n\t var scoreThreshold = options.scoreThreshold.call(this);\n\t this.debug('scoreThreshold:', scoreThreshold);\n\t this.debug('bestMatch.score:', bestMatch.score);\n\t\n\t if (bestMatch.score >= scoreThreshold) {\n\t //console.debug( 'autoPairFnBuilder.strategy', listA[ indexA ].name, listB[ bestMatch.index ].name );\n\t paired.push(options.createPair.call(this, {\n\t listA: listA,\n\t indexA: indexA,\n\t listB: listB,\n\t indexB: bestMatch.index\n\t }));\n\t //console.debug( 'list lens now:', listA.length, listB.length );\n\t } else {\n\t indexA += 1;\n\t }\n\t if (!listA.length || !listB.length) {\n\t return paired;\n\t }\n\t }\n\t this.debug('paired:', JSON.stringify(paired, null, ' '));\n\t this.debug('autopair _strategy ---------------------------');\n\t return paired;\n\t };\n\t }\n\t\n\t // ============================================================================\n\t /** An interface for building collections of paired datasets.\n\t */\n\t var PairedCollectionCreator = Backbone.View.extend(baseMVC.LoggableMixin).extend(baseCreator.CollectionCreatorMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t className: 'list-of-pairs-collection-creator collection-creator flex-row-container',\n\t\n\t /** set up initial options, instance vars, behaviors, and autopair (if set to do so) */\n\t initialize: function (attributes) {\n\t this.metric('PairedCollectionCreator.initialize', attributes);\n\t //this.debug( '-- PairedCollectionCreator:', attributes );\n\t\n\t attributes = _.defaults(attributes, {\n\t datasets: [],\n\t filters: this.DEFAULT_FILTERS,\n\t automaticallyPair: true,\n\t strategy: 'lcs',\n\t matchPercentage: 0.9,\n\t twoPassAutopairing: true\n\t });\n\t\n\t /** unordered, original list */\n\t this.initialList = attributes.datasets;\n\t\n\t /** is this from a history? if so, what's its id? */\n\t this.historyId = attributes.historyId;\n\t\n\t /** which filters should be used initially? (String[2] or name in commonFilters) */\n\t this.filters = this.commonFilters[attributes.filters] || this.commonFilters[this.DEFAULT_FILTERS];\n\t if (_.isArray(attributes.filters)) {\n\t this.filters = attributes.filters;\n\t }\n\t\n\t /** try to auto pair the unpaired datasets on load? */\n\t this.automaticallyPair = attributes.automaticallyPair;\n\t\n\t /** what method to use for auto pairing (will be passed aggression level) */\n\t this.strategy = this.strategies[attributes.strategy] || this.strategies[this.DEFAULT_STRATEGY];\n\t if (_.isFunction(attributes.strategy)) {\n\t this.strategy = attributes.strategy;\n\t }\n\t\n\t /** distance/mismatch level allowed for autopairing */\n\t this.matchPercentage = attributes.matchPercentage;\n\t\n\t /** try to autopair using simple first, then this.strategy on the remainder */\n\t this.twoPassAutopairing = attributes.twoPassAutopairing;\n\t\n\t /** remove file extensions (\\.*) from created pair names? */\n\t this.removeExtensions = true;\n\t //this.removeExtensions = false;\n\t\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t this.oncancel = attributes.oncancel;\n\t /** fn to call when the collection is created (scoped to this) */\n\t this.oncreate = attributes.oncreate;\n\t\n\t /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n\t this.autoscrollDist = attributes.autoscrollDist || 24;\n\t\n\t /** is the unpaired panel shown? */\n\t this.unpairedPanelHidden = false;\n\t /** is the paired panel shown? */\n\t this.pairedPanelHidden = false;\n\t\n\t /** DOM elements currently being dragged */\n\t this.$dragging = null;\n\t\n\t /** Used for blocking UI events during ajax/operations (don't post twice) */\n\t this.blocking = false;\n\t\n\t this._setUpCommonSettings(attributes);\n\t this._setUpBehaviors();\n\t this._dataSetUp();\n\t },\n\t\n\t /** map of common filter pairs by name */\n\t commonFilters: {\n\t illumina: ['_1', '_2'],\n\t Rs: ['_R1', '_R2']\n\t },\n\t /** which commonFilter to use by default */\n\t DEFAULT_FILTERS: 'illumina',\n\t\n\t /** map of name->fn for autopairing */\n\t strategies: {\n\t 'simple': 'autopairSimple',\n\t 'lcs': 'autopairLCS',\n\t 'levenshtein': 'autopairLevenshtein'\n\t },\n\t /** default autopair strategy name */\n\t DEFAULT_STRATEGY: 'lcs',\n\t\n\t // ------------------------------------------------------------------------ process raw list\n\t /** set up main data: cache initialList, sort, and autopair */\n\t _dataSetUp: function () {\n\t //this.debug( '-- _dataSetUp' );\n\t\n\t this.paired = [];\n\t this.unpaired = [];\n\t\n\t this.selectedIds = [];\n\t\n\t // sort initial list, add ids if needed, and save new working copy to unpaired\n\t this._sortInitialList();\n\t this._ensureIds();\n\t this.unpaired = this.initialList.slice(0);\n\t\n\t if (this.automaticallyPair) {\n\t this.autoPair();\n\t this.once('rendered:initial', function () {\n\t this.trigger('autopair');\n\t });\n\t }\n\t },\n\t\n\t /** sort initial list */\n\t _sortInitialList: function () {\n\t //this.debug( '-- _sortInitialList' );\n\t this._sortDatasetList(this.initialList);\n\t },\n\t\n\t /** sort a list of datasets */\n\t _sortDatasetList: function (list) {\n\t // currently only natural sort by name\n\t list.sort(function (a, b) {\n\t return naturalSort(a.name, b.name);\n\t });\n\t return list;\n\t },\n\t\n\t /** add ids to dataset objs in initial list if none */\n\t _ensureIds: function () {\n\t this.initialList.forEach(function (dataset) {\n\t if (!dataset.hasOwnProperty('id')) {\n\t dataset.id = _.uniqueId();\n\t }\n\t });\n\t return this.initialList;\n\t },\n\t\n\t /** split initial list into two lists, those that pass forward filters & those passing reverse */\n\t _splitByFilters: function () {\n\t var regexFilters = this.filters.map(function (stringFilter) {\n\t return new RegExp(stringFilter);\n\t }),\n\t split = [[], []];\n\t\n\t function _filter(unpaired, filter) {\n\t return filter.test(unpaired.name);\n\t //return dataset.name.indexOf( filter ) >= 0;\n\t }\n\t this.unpaired.forEach(function _filterEach(unpaired) {\n\t // 90% of the time this seems to work, but:\n\t //TODO: this treats *all* strings as regex which may confuse people - possibly check for // surrounding?\n\t // would need explanation in help as well\n\t regexFilters.forEach(function (filter, i) {\n\t if (_filter(unpaired, filter)) {\n\t split[i].push(unpaired);\n\t }\n\t });\n\t });\n\t return split;\n\t },\n\t\n\t /** add a dataset to the unpaired list in it's proper order */\n\t _addToUnpaired: function (dataset) {\n\t // currently, unpaired is natural sorted by name, use binary search to find insertion point\n\t var binSearchSortedIndex = function (low, hi) {\n\t if (low === hi) {\n\t return low;\n\t }\n\t\n\t var mid = Math.floor((hi - low) / 2) + low,\n\t compared = naturalSort(dataset.name, this.unpaired[mid].name);\n\t\n\t if (compared < 0) {\n\t return binSearchSortedIndex(low, mid);\n\t } else if (compared > 0) {\n\t return binSearchSortedIndex(mid + 1, hi);\n\t }\n\t // walk the equal to find the last\n\t while (this.unpaired[mid] && this.unpaired[mid].name === dataset.name) {\n\t mid++;\n\t }\n\t return mid;\n\t }.bind(this);\n\t\n\t this.unpaired.splice(binSearchSortedIndex(0, this.unpaired.length), 0, dataset);\n\t },\n\t\n\t // ------------------------------------------------------------------------ auto pairing\n\t /** two passes to automatically create pairs:\n\t * use both simpleAutoPair, then the fn mentioned in strategy\n\t */\n\t autoPair: function (strategy) {\n\t // split first using exact matching\n\t var split = this._splitByFilters(),\n\t paired = [];\n\t if (this.twoPassAutopairing) {\n\t paired = this.autopairSimple({\n\t listA: split[0],\n\t listB: split[1]\n\t });\n\t split = this._splitByFilters();\n\t }\n\t\n\t // uncomment to see printlns while running tests\n\t //this.debug = function(){ console.log.apply( console, arguments ); };\n\t\n\t // then try the remainder with something less strict\n\t strategy = strategy || this.strategy;\n\t split = this._splitByFilters();\n\t paired = paired.concat(this[strategy].call(this, {\n\t listA: split[0],\n\t listB: split[1]\n\t }));\n\t return paired;\n\t },\n\t\n\t /** autopair by exact match */\n\t autopairSimple: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return 1.0;\n\t },\n\t match: function _match(params) {\n\t params = params || {};\n\t if (params.matchTo === params.possible) {\n\t return {\n\t index: params.index,\n\t score: 1.0\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** autopair by levenshtein edit distance scoring */\n\t autopairLevenshtein: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return this.matchPercentage;\n\t },\n\t match: function _matches(params) {\n\t params = params || {};\n\t var distance = levenshteinDistance(params.matchTo, params.possible),\n\t score = 1.0 - distance / Math.max(params.matchTo.length, params.possible.length);\n\t if (score > params.bestMatch.score) {\n\t return {\n\t index: params.index,\n\t score: score\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** autopair by longest common substrings scoring */\n\t autopairLCS: autoPairFnBuilder({\n\t scoreThreshold: function () {\n\t return this.matchPercentage;\n\t },\n\t match: function _matches(params) {\n\t params = params || {};\n\t var match = this._naiveStartingAndEndingLCS(params.matchTo, params.possible).length,\n\t score = match / Math.max(params.matchTo.length, params.possible.length);\n\t if (score > params.bestMatch.score) {\n\t return {\n\t index: params.index,\n\t score: score\n\t };\n\t }\n\t return params.bestMatch;\n\t }\n\t }),\n\t\n\t /** return the concat'd longest common prefix and suffix from two strings */\n\t _naiveStartingAndEndingLCS: function (s1, s2) {\n\t var fwdLCS = '',\n\t revLCS = '',\n\t i = 0,\n\t j = 0;\n\t while (i < s1.length && i < s2.length) {\n\t if (s1[i] !== s2[i]) {\n\t break;\n\t }\n\t fwdLCS += s1[i];\n\t i += 1;\n\t }\n\t if (i === s1.length) {\n\t return s1;\n\t }\n\t if (i === s2.length) {\n\t return s2;\n\t }\n\t\n\t i = s1.length - 1;\n\t j = s2.length - 1;\n\t while (i >= 0 && j >= 0) {\n\t if (s1[i] !== s2[j]) {\n\t break;\n\t }\n\t revLCS = [s1[i], revLCS].join('');\n\t i -= 1;\n\t j -= 1;\n\t }\n\t return fwdLCS + revLCS;\n\t },\n\t\n\t // ------------------------------------------------------------------------ pairing / unpairing\n\t /** create a pair from fwd and rev, removing them from unpaired, and placing the new pair in paired */\n\t _pair: function (fwd, rev, options) {\n\t options = options || {};\n\t this.debug('_pair:', fwd, rev);\n\t var pair = this._createPair(fwd, rev, options.name);\n\t this.paired.push(pair);\n\t this.unpaired = _.without(this.unpaired, fwd, rev);\n\t if (!options.silent) {\n\t this.trigger('pair:new', pair);\n\t }\n\t return pair;\n\t },\n\t\n\t /** create a pair Object from fwd and rev, adding the name attribute (will guess if not given) */\n\t _createPair: function (fwd, rev, name) {\n\t // ensure existance and don't pair something with itself\n\t if (!(fwd && rev) || fwd === rev) {\n\t throw new Error('Bad pairing: ' + [JSON.stringify(fwd), JSON.stringify(rev)]);\n\t }\n\t name = name || this._guessNameForPair(fwd, rev);\n\t return { forward: fwd, name: name, reverse: rev };\n\t },\n\t\n\t /** try to find a good pair name for the given fwd and rev datasets */\n\t _guessNameForPair: function (fwd, rev, removeExtensions) {\n\t removeExtensions = removeExtensions !== undefined ? removeExtensions : this.removeExtensions;\n\t var fwdName = fwd.name,\n\t revName = rev.name,\n\t lcs = this._naiveStartingAndEndingLCS(fwdName.replace(new RegExp(this.filters[0]), ''), revName.replace(new RegExp(this.filters[1]), ''));\n\t if (removeExtensions) {\n\t var lastDotIndex = lcs.lastIndexOf('.');\n\t if (lastDotIndex > 0) {\n\t var extension = lcs.slice(lastDotIndex, lcs.length);\n\t lcs = lcs.replace(extension, '');\n\t fwdName = fwdName.replace(extension, '');\n\t revName = revName.replace(extension, '');\n\t }\n\t }\n\t return lcs || fwdName + ' & ' + revName;\n\t },\n\t\n\t /** unpair a pair, removing it from paired, and adding the fwd,rev datasets back into unpaired */\n\t _unpair: function (pair, options) {\n\t options = options || {};\n\t if (!pair) {\n\t throw new Error('Bad pair: ' + JSON.stringify(pair));\n\t }\n\t this.paired = _.without(this.paired, pair);\n\t this._addToUnpaired(pair.forward);\n\t this._addToUnpaired(pair.reverse);\n\t\n\t if (!options.silent) {\n\t this.trigger('pair:unpair', [pair]);\n\t }\n\t return pair;\n\t },\n\t\n\t /** unpair all paired datasets */\n\t unpairAll: function () {\n\t var pairs = [];\n\t while (this.paired.length) {\n\t pairs.push(this._unpair(this.paired[0], { silent: true }));\n\t }\n\t this.trigger('pair:unpair', pairs);\n\t },\n\t\n\t // ------------------------------------------------------------------------ API\n\t /** convert a pair into JSON compatible with the collections API */\n\t _pairToJSON: function (pair, src) {\n\t src = src || 'hda';\n\t //TODO: consider making this the pair structure when created instead\n\t return {\n\t collection_type: 'paired',\n\t src: 'new_collection',\n\t name: pair.name,\n\t element_identifiers: [{\n\t name: 'forward',\n\t id: pair.forward.id,\n\t src: src\n\t }, {\n\t name: 'reverse',\n\t id: pair.reverse.id,\n\t src: src\n\t }]\n\t };\n\t },\n\t\n\t /** create the collection via the API\n\t * @returns {jQuery.xhr Object} the jquery ajax request\n\t */\n\t createList: function (name) {\n\t var creator = this,\n\t url = Galaxy.root + 'api/histories/' + this.historyId + '/contents/dataset_collections';\n\t\n\t //TODO: use ListPairedCollection.create()\n\t var ajaxData = {\n\t type: 'dataset_collection',\n\t collection_type: 'list:paired',\n\t hide_source_items: creator.hideOriginals || false,\n\t name: _.escape(name || creator.$('.collection-name').val()),\n\t element_identifiers: creator.paired.map(function (pair) {\n\t return creator._pairToJSON(pair);\n\t })\n\t\n\t };\n\t //this.debug( JSON.stringify( ajaxData ) );\n\t creator.blocking = true;\n\t return jQuery.ajax(url, {\n\t type: 'POST',\n\t contentType: 'application/json',\n\t dataType: 'json',\n\t data: JSON.stringify(ajaxData)\n\t }).always(function () {\n\t creator.blocking = false;\n\t }).fail(function (xhr, status, message) {\n\t creator._ajaxErrHandler(xhr, status, message);\n\t }).done(function (response, message, xhr) {\n\t //this.info( 'ok', response, message, xhr );\n\t creator.trigger('collection:created', response, message, xhr);\n\t creator.metric('collection:created', response);\n\t if (typeof creator.oncreate === 'function') {\n\t creator.oncreate.call(this, response, message, xhr);\n\t }\n\t });\n\t },\n\t\n\t /** handle ajax errors with feedback and details to the user (if available) */\n\t _ajaxErrHandler: function (xhr, status, message) {\n\t this.error(xhr, status, message);\n\t var content = _l('An error occurred while creating this collection');\n\t if (xhr) {\n\t if (xhr.readyState === 0 && xhr.status === 0) {\n\t content += ': ' + _l('Galaxy could not be reached and may be updating.') + _l(' Try again in a few minutes.');\n\t } else if (xhr.responseJSON) {\n\t content += '
                                    ' + JSON.stringify(xhr.responseJSON) + '
                                    ';\n\t } else {\n\t content += ': ' + message;\n\t }\n\t }\n\t creator._showAlert(content, 'alert-danger');\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t //this.debug( '-- _render' );\n\t //this.$el.empty().html( this.templates.main() );\n\t this.$el.empty().html(this.templates.main());\n\t this._renderHeader(speed);\n\t this._renderMiddle(speed);\n\t this._renderFooter(speed);\n\t this._addPluginComponents();\n\t this.trigger('rendered', this);\n\t return this;\n\t },\n\t\n\t /** render the header section */\n\t _renderHeader: function (speed, callback) {\n\t //this.debug( '-- _renderHeader' );\n\t var $header = this.$('.header').empty().html(this.templates.header()).find('.help-content').prepend($(this.templates.helpContent()));\n\t\n\t this._renderFilters();\n\t return $header;\n\t },\n\t /** fill the filter inputs with the filter values */\n\t _renderFilters: function () {\n\t return this.$('.forward-column .column-header input').val(this.filters[0]).add(this.$('.reverse-column .column-header input').val(this.filters[1]));\n\t },\n\t\n\t /** render the middle including unpaired and paired sections (which may be hidden) */\n\t _renderMiddle: function (speed, callback) {\n\t var $middle = this.$('.middle').empty().html(this.templates.middle());\n\t\n\t // (re-) hide the un/paired panels based on instance vars\n\t if (this.unpairedPanelHidden) {\n\t this.$('.unpaired-columns').hide();\n\t } else if (this.pairedPanelHidden) {\n\t this.$('.paired-columns').hide();\n\t }\n\t\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t return $middle;\n\t },\n\t /** render the unpaired section, showing datasets accrd. to filters, update the unpaired counts */\n\t _renderUnpaired: function (speed, callback) {\n\t //this.debug( '-- _renderUnpaired' );\n\t var creator = this,\n\t $fwd,\n\t $rev,\n\t $prd = [],\n\t split = this._splitByFilters();\n\t // update unpaired counts\n\t this.$('.forward-column .title').text([split[0].length, _l('unpaired forward')].join(' '));\n\t this.$('.forward-column .unpaired-info').text(this._renderUnpairedDisplayStr(this.unpaired.length - split[0].length));\n\t this.$('.reverse-column .title').text([split[1].length, _l('unpaired reverse')].join(' '));\n\t this.$('.reverse-column .unpaired-info').text(this._renderUnpairedDisplayStr(this.unpaired.length - split[1].length));\n\t\n\t this.$('.unpaired-columns .column-datasets').empty();\n\t\n\t // show/hide the auto pair button if any unpaired are left\n\t this.$('.autopair-link').toggle(this.unpaired.length !== 0);\n\t if (this.unpaired.length === 0) {\n\t this._renderUnpairedEmpty();\n\t return;\n\t }\n\t\n\t // create the dataset dom arrays\n\t $rev = split[1].map(function (dataset, i) {\n\t // if there'll be a fwd dataset across the way, add a button to pair the row\n\t if (split[0][i] !== undefined && split[0][i] !== dataset) {\n\t $prd.push(creator._renderPairButton());\n\t }\n\t return creator._renderUnpairedDataset(dataset);\n\t });\n\t $fwd = split[0].map(function (dataset) {\n\t return creator._renderUnpairedDataset(dataset);\n\t });\n\t\n\t if (!$fwd.length && !$rev.length) {\n\t this._renderUnpairedNotShown();\n\t return;\n\t }\n\t // add to appropo cols\n\t //TODO: not the best way to render - consider rendering the entire unpaired-columns section in a fragment\n\t // and swapping out that\n\t this.$('.unpaired-columns .forward-column .column-datasets').append($fwd).add(this.$('.unpaired-columns .paired-column .column-datasets').append($prd)).add(this.$('.unpaired-columns .reverse-column .column-datasets').append($rev));\n\t this._adjUnpairedOnScrollbar();\n\t },\n\t /** return a string to display the count of filtered out datasets */\n\t _renderUnpairedDisplayStr: function (numFiltered) {\n\t return ['(', numFiltered, ' ', _l('filtered out'), ')'].join('');\n\t },\n\t /** return an unattached jQuery DOM element to represent an unpaired dataset */\n\t _renderUnpairedDataset: function (dataset) {\n\t //TODO: to underscore template\n\t return $('
                                  • ').attr('id', 'dataset-' + dataset.id).addClass('dataset unpaired').attr('draggable', true).addClass(dataset.selected ? 'selected' : '').append($('').addClass('dataset-name').text(dataset.name))\n\t //??\n\t .data('dataset', dataset);\n\t },\n\t /** render the button that may go between unpaired datasets, allowing the user to pair a row */\n\t _renderPairButton: function () {\n\t //TODO: *not* a dataset - don't pretend like it is\n\t return $('
                                  • ').addClass('dataset unpaired').append($('').addClass('dataset-name').text(_l('Pair these datasets')));\n\t },\n\t /** a message to display when no unpaired left */\n\t _renderUnpairedEmpty: function () {\n\t //this.debug( '-- renderUnpairedEmpty' );\n\t var $msg = $('
                                    ').text('(' + _l('no remaining unpaired datasets') + ')');\n\t this.$('.unpaired-columns .paired-column .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t /** a message to display when no unpaired can be shown with the current filters */\n\t _renderUnpairedNotShown: function () {\n\t //this.debug( '-- renderUnpairedEmpty' );\n\t var $msg = $('
                                    ').text('(' + _l('no datasets were found matching the current filters') + ')');\n\t this.$('.unpaired-columns .paired-column .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t /** try to detect if the unpaired section has a scrollbar and adjust left column for better centering of all */\n\t _adjUnpairedOnScrollbar: function () {\n\t var $unpairedColumns = this.$('.unpaired-columns').last(),\n\t $firstDataset = this.$('.unpaired-columns .reverse-column .dataset').first();\n\t if (!$firstDataset.length) {\n\t return;\n\t }\n\t var ucRight = $unpairedColumns.offset().left + $unpairedColumns.outerWidth(),\n\t dsRight = $firstDataset.offset().left + $firstDataset.outerWidth(),\n\t rightDiff = Math.floor(ucRight) - Math.floor(dsRight);\n\t //this.debug( 'rightDiff:', ucRight, '-', dsRight, '=', rightDiff );\n\t this.$('.unpaired-columns .forward-column').css('margin-left', rightDiff > 0 ? rightDiff : 0);\n\t },\n\t\n\t /** render the paired section and update counts of paired datasets */\n\t _renderPaired: function (speed, callback) {\n\t //this.debug( '-- _renderPaired' );\n\t this.$('.paired-column-title .title').text([this.paired.length, _l('paired')].join(' '));\n\t // show/hide the unpair all link\n\t this.$('.unpair-all-link').toggle(this.paired.length !== 0);\n\t if (this.paired.length === 0) {\n\t this._renderPairedEmpty();\n\t return;\n\t //TODO: would be best to return here (the $columns)\n\t } else {\n\t // show/hide 'remove extensions link' when any paired and they seem to have extensions\n\t this.$('.remove-extensions-link').show();\n\t }\n\t\n\t this.$('.paired-columns .column-datasets').empty();\n\t var creator = this;\n\t this.paired.forEach(function (pair, i) {\n\t //TODO: cache these?\n\t var pairView = new PairView({ pair: pair });\n\t creator.$('.paired-columns .column-datasets').append(pairView.render().$el).append([''].join(''));\n\t });\n\t },\n\t /** a message to display when none paired */\n\t _renderPairedEmpty: function () {\n\t var $msg = $('
                                    ').text('(' + _l('no paired datasets yet') + ')');\n\t this.$('.paired-columns .column-datasets').empty().prepend($msg);\n\t return $msg;\n\t },\n\t\n\t footerSettings: {\n\t '.hide-originals': 'hideOriginals',\n\t '.remove-extensions': 'removeExtensions'\n\t },\n\t\n\t /** add any jQuery/bootstrap/custom plugins to elements rendered */\n\t _addPluginComponents: function () {\n\t this._chooseFiltersPopover('.choose-filters-link');\n\t this.$('.help-content i').hoverhighlight('.collection-creator', 'rgba( 64, 255, 255, 1.0 )');\n\t },\n\t\n\t /** build a filter selection popover allowing selection of common filter pairs */\n\t _chooseFiltersPopover: function (selector) {\n\t function filterChoice(val1, val2) {\n\t return [''].join('');\n\t }\n\t var $popoverContent = $(_.template(['
                                    ', '
                                    ', _l('Choose from the following filters to change which unpaired reads are shown in the display'), ':
                                    ', _.values(this.commonFilters).map(function (filterSet) {\n\t return filterChoice(filterSet[0], filterSet[1]);\n\t }).join(''), '
                                    '].join(''))({}));\n\t\n\t return this.$(selector).popover({\n\t container: '.collection-creator',\n\t placement: 'bottom',\n\t html: true,\n\t //animation : false,\n\t content: $popoverContent\n\t });\n\t },\n\t\n\t /** add (or clear if clear is truthy) a validation warning to what */\n\t _validationWarning: function (what, clear) {\n\t var VALIDATION_CLASS = 'validation-warning';\n\t if (what === 'name') {\n\t what = this.$('.collection-name').add(this.$('.collection-name-prompt'));\n\t this.$('.collection-name').focus().select();\n\t }\n\t if (clear) {\n\t what = what || this.$('.' + VALIDATION_CLASS);\n\t what.removeClass(VALIDATION_CLASS);\n\t } else {\n\t what.addClass(VALIDATION_CLASS);\n\t }\n\t },\n\t\n\t // ------------------------------------------------------------------------ events\n\t /** set up event handlers on self */\n\t _setUpBehaviors: function () {\n\t this.once('rendered', function () {\n\t this.trigger('rendered:initial', this);\n\t });\n\t\n\t this.on('pair:new', function () {\n\t //TODO: ideally only re-render the columns (or even elements) involved\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t\n\t // scroll to bottom where new pairs are added\n\t //TODO: this doesn't seem to work - innerHeight sticks at 133...\n\t // may have to do with improper flex columns\n\t //var $pairedView = this.$( '.paired-columns' );\n\t //$pairedView.scrollTop( $pairedView.innerHeight() );\n\t //this.debug( $pairedView.height() )\n\t this.$('.paired-columns').scrollTop(8000000);\n\t });\n\t this.on('pair:unpair', function (pairs) {\n\t //TODO: ideally only re-render the columns (or even elements) involved\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t this.splitView();\n\t });\n\t\n\t this.on('filter-change', function () {\n\t this.filters = [this.$('.forward-unpaired-filter input').val(), this.$('.reverse-unpaired-filter input').val()];\n\t this.metric('filter-change', this.filters);\n\t this._renderFilters();\n\t this._renderUnpaired();\n\t });\n\t\n\t this.on('autopair', function () {\n\t this._renderUnpaired();\n\t this._renderPaired();\n\t\n\t var message,\n\t msgClass = null;\n\t if (this.paired.length) {\n\t msgClass = 'alert-success';\n\t message = this.paired.length + ' ' + _l('pairs created');\n\t if (!this.unpaired.length) {\n\t message += ': ' + _l('all datasets have been successfully paired');\n\t this.hideUnpaired();\n\t this.$('.collection-name').focus();\n\t }\n\t } else {\n\t message = _l(['Could not automatically create any pairs from the given dataset names.', 'You may want to choose or enter different filters and try auto-pairing again.', 'Close this message using the X on the right to view more help.'].join(' '));\n\t }\n\t this._showAlert(message, msgClass);\n\t });\n\t\n\t //this.on( 'all', function(){\n\t // this.info( arguments );\n\t //});\n\t return this;\n\t },\n\t\n\t events: {\n\t // header\n\t 'click .more-help': '_clickMoreHelp',\n\t 'click .less-help': '_clickLessHelp',\n\t 'click .main-help': '_toggleHelp',\n\t 'click .header .alert button': '_hideAlert',\n\t 'click .forward-column .column-title': '_clickShowOnlyUnpaired',\n\t 'click .reverse-column .column-title': '_clickShowOnlyUnpaired',\n\t 'click .unpair-all-link': '_clickUnpairAll',\n\t //TODO: this seems kinda backasswards - re-sending jq event as a backbone event, can we listen directly?\n\t 'change .forward-unpaired-filter input': function (ev) {\n\t this.trigger('filter-change');\n\t },\n\t 'focus .forward-unpaired-filter input': function (ev) {\n\t $(ev.currentTarget).select();\n\t },\n\t 'click .autopair-link': '_clickAutopair',\n\t 'click .choose-filters .filter-choice': '_clickFilterChoice',\n\t 'click .clear-filters-link': '_clearFilters',\n\t 'change .reverse-unpaired-filter input': function (ev) {\n\t this.trigger('filter-change');\n\t },\n\t 'focus .reverse-unpaired-filter input': function (ev) {\n\t $(ev.currentTarget).select();\n\t },\n\t // unpaired\n\t 'click .forward-column .dataset.unpaired': '_clickUnpairedDataset',\n\t 'click .reverse-column .dataset.unpaired': '_clickUnpairedDataset',\n\t 'click .paired-column .dataset.unpaired': '_clickPairRow',\n\t 'click .unpaired-columns': 'clearSelectedUnpaired',\n\t 'mousedown .unpaired-columns .dataset': '_mousedownUnpaired',\n\t // divider\n\t 'click .paired-column-title': '_clickShowOnlyPaired',\n\t 'mousedown .flexible-partition-drag': '_startPartitionDrag',\n\t // paired\n\t 'click .paired-columns .dataset.paired': 'selectPair',\n\t 'click .paired-columns': 'clearSelectedPaired',\n\t 'click .paired-columns .pair-name': '_clickPairName',\n\t 'click .unpair-btn': '_clickUnpair',\n\t // paired - drop target\n\t //'dragenter .paired-columns' : '_dragenterPairedColumns',\n\t //'dragleave .paired-columns .column-datasets': '_dragleavePairedColumns',\n\t 'dragover .paired-columns .column-datasets': '_dragoverPairedColumns',\n\t 'drop .paired-columns .column-datasets': '_dropPairedColumns',\n\t\n\t 'pair.dragstart .paired-columns .column-datasets': '_pairDragstart',\n\t 'pair.dragend .paired-columns .column-datasets': '_pairDragend',\n\t\n\t // footer\n\t 'change .remove-extensions': function (ev) {\n\t this.toggleExtensions();\n\t },\n\t 'change .collection-name': '_changeName',\n\t 'keydown .collection-name': '_nameCheckForEnter',\n\t 'change .hide-originals': '_changeHideOriginals',\n\t 'click .cancel-create': '_cancelCreate',\n\t 'click .create-collection': '_clickCreate' //,\n\t },\n\t\n\t /** toggle between showing only unpaired and split view */\n\t _clickShowOnlyUnpaired: function (ev) {\n\t //this.debug( 'click unpaired', ev.currentTarget );\n\t if (this.$('.paired-columns').is(':visible')) {\n\t this.hidePaired();\n\t } else {\n\t this.splitView();\n\t }\n\t },\n\t /** toggle between showing only paired and split view */\n\t _clickShowOnlyPaired: function (ev) {\n\t //this.debug( 'click paired' );\n\t if (this.$('.unpaired-columns').is(':visible')) {\n\t this.hideUnpaired();\n\t } else {\n\t this.splitView();\n\t }\n\t },\n\t\n\t /** hide unpaired, show paired */\n\t hideUnpaired: function (speed, callback) {\n\t this.unpairedPanelHidden = true;\n\t this.pairedPanelHidden = false;\n\t this._renderMiddle(speed, callback);\n\t },\n\t /** hide paired, show unpaired */\n\t hidePaired: function (speed, callback) {\n\t this.unpairedPanelHidden = false;\n\t this.pairedPanelHidden = true;\n\t this._renderMiddle(speed, callback);\n\t },\n\t /** show both paired and unpaired (splitting evenly) */\n\t splitView: function (speed, callback) {\n\t this.unpairedPanelHidden = this.pairedPanelHidden = false;\n\t this._renderMiddle(speed, callback);\n\t return this;\n\t },\n\t\n\t /** unpair all paired and do other super neat stuff which I'm not really sure about yet... */\n\t _clickUnpairAll: function (ev) {\n\t this.metric('unpairAll');\n\t this.unpairAll();\n\t },\n\t\n\t /** attempt to autopair */\n\t _clickAutopair: function (ev) {\n\t var paired = this.autoPair();\n\t this.metric('autopair', paired.length, this.unpaired.length);\n\t this.trigger('autopair');\n\t },\n\t\n\t /** set the filters based on the data attributes of the button click target */\n\t _clickFilterChoice: function (ev) {\n\t var $selected = $(ev.currentTarget);\n\t this.$('.forward-unpaired-filter input').val($selected.data('forward'));\n\t this.$('.reverse-unpaired-filter input').val($selected.data('reverse'));\n\t this._hideChooseFilters();\n\t this.trigger('filter-change');\n\t },\n\t\n\t /** hide the choose filters popover */\n\t _hideChooseFilters: function () {\n\t //TODO: update bootstrap and remove the following hack\n\t // see also: https://github.com/twbs/bootstrap/issues/10260\n\t this.$('.choose-filters-link').popover('hide');\n\t this.$('.popover').css('display', 'none');\n\t },\n\t\n\t /** clear both filters */\n\t _clearFilters: function (ev) {\n\t this.$('.forward-unpaired-filter input').val('');\n\t this.$('.reverse-unpaired-filter input').val('');\n\t this.trigger('filter-change');\n\t },\n\t\n\t // ........................................................................ unpaired\n\t /** select an unpaired dataset */\n\t _clickUnpairedDataset: function (ev) {\n\t ev.stopPropagation();\n\t return this.toggleSelectUnpaired($(ev.currentTarget));\n\t },\n\t\n\t /** Toggle the selection of an unpaired dataset representation.\n\t * @param [jQuery] $dataset the unpaired dataset dom rep to select\n\t * @param [Boolean] options.force if defined, force selection based on T/F; otherwise, toggle\n\t */\n\t toggleSelectUnpaired: function ($dataset, options) {\n\t options = options || {};\n\t var dataset = $dataset.data('dataset'),\n\t select = options.force !== undefined ? options.force : !$dataset.hasClass('selected');\n\t //this.debug( id, options.force, $dataset, dataset );\n\t if (!$dataset.length || dataset === undefined) {\n\t return $dataset;\n\t }\n\t\n\t if (select) {\n\t $dataset.addClass('selected');\n\t if (!options.waitToPair) {\n\t this.pairAllSelected();\n\t }\n\t } else {\n\t $dataset.removeClass('selected');\n\t //delete dataset.selected;\n\t }\n\t return $dataset;\n\t },\n\t\n\t /** pair all the currently selected unpaired datasets */\n\t pairAllSelected: function (options) {\n\t options = options || {};\n\t var creator = this,\n\t fwds = [],\n\t revs = [],\n\t pairs = [];\n\t creator.$('.unpaired-columns .forward-column .dataset.selected').each(function () {\n\t fwds.push($(this).data('dataset'));\n\t });\n\t creator.$('.unpaired-columns .reverse-column .dataset.selected').each(function () {\n\t revs.push($(this).data('dataset'));\n\t });\n\t fwds.length = revs.length = Math.min(fwds.length, revs.length);\n\t //this.debug( fwds );\n\t //this.debug( revs );\n\t fwds.forEach(function (fwd, i) {\n\t try {\n\t pairs.push(creator._pair(fwd, revs[i], { silent: true }));\n\t } catch (err) {\n\t //TODO: preserve selected state of those that couldn't be paired\n\t //TODO: warn that some could not be paired\n\t creator.error(err);\n\t }\n\t });\n\t if (pairs.length && !options.silent) {\n\t this.trigger('pair:new', pairs);\n\t }\n\t return pairs;\n\t },\n\t\n\t /** clear the selection on all unpaired datasets */\n\t clearSelectedUnpaired: function () {\n\t this.$('.unpaired-columns .dataset.selected').removeClass('selected');\n\t },\n\t\n\t /** when holding down the shift key on a click, 'paint' the moused over datasets as selected */\n\t _mousedownUnpaired: function (ev) {\n\t if (ev.shiftKey) {\n\t var creator = this,\n\t $startTarget = $(ev.target).addClass('selected'),\n\t moveListener = function (ev) {\n\t creator.$(ev.target).filter('.dataset').addClass('selected');\n\t };\n\t $startTarget.parent().on('mousemove', moveListener);\n\t\n\t // on any mouseup, stop listening to the move and try to pair any selected\n\t $(document).one('mouseup', function (ev) {\n\t $startTarget.parent().off('mousemove', moveListener);\n\t creator.pairAllSelected();\n\t });\n\t }\n\t },\n\t\n\t /** attempt to pair two datasets directly across from one another */\n\t _clickPairRow: function (ev) {\n\t //if( !ev.currentTarget ){ return true; }\n\t var rowIndex = $(ev.currentTarget).index(),\n\t fwd = $('.unpaired-columns .forward-column .dataset').eq(rowIndex).data('dataset'),\n\t rev = $('.unpaired-columns .reverse-column .dataset').eq(rowIndex).data('dataset');\n\t //this.debug( 'row:', rowIndex, fwd, rev );\n\t this._pair(fwd, rev);\n\t },\n\t\n\t // ........................................................................ divider/partition\n\t /** start dragging the visible divider/partition between unpaired and paired panes */\n\t _startPartitionDrag: function (ev) {\n\t var creator = this,\n\t startingY = ev.pageY;\n\t //this.debug( 'partition drag START:', ev );\n\t $('body').css('cursor', 'ns-resize');\n\t creator.$('.flexible-partition-drag').css('color', 'black');\n\t\n\t function endDrag(ev) {\n\t //creator.debug( 'partition drag STOP:', ev );\n\t // doing this by an added class didn't really work well - kept flashing still\n\t creator.$('.flexible-partition-drag').css('color', '');\n\t $('body').css('cursor', '').unbind('mousemove', trackMouse);\n\t }\n\t function trackMouse(ev) {\n\t var offset = ev.pageY - startingY;\n\t //creator.debug( 'partition:', startingY, offset );\n\t if (!creator.adjPartition(offset)) {\n\t //creator.debug( 'mouseup triggered' );\n\t $('body').trigger('mouseup');\n\t }\n\t creator._adjUnpairedOnScrollbar();\n\t startingY += offset;\n\t }\n\t $('body').mousemove(trackMouse);\n\t $('body').one('mouseup', endDrag);\n\t },\n\t\n\t /** adjust the parition up/down +/-adj pixels */\n\t adjPartition: function (adj) {\n\t var $unpaired = this.$('.unpaired-columns'),\n\t $paired = this.$('.paired-columns'),\n\t unpairedHi = parseInt($unpaired.css('height'), 10),\n\t pairedHi = parseInt($paired.css('height'), 10);\n\t //this.debug( adj, 'hi\\'s:', unpairedHi, pairedHi, unpairedHi + adj, pairedHi - adj );\n\t\n\t unpairedHi = Math.max(10, unpairedHi + adj);\n\t pairedHi = pairedHi - adj;\n\t\n\t var movingUpwards = adj < 0;\n\t // when the divider gets close to the top - lock into hiding the unpaired section\n\t if (movingUpwards) {\n\t if (this.unpairedPanelHidden) {\n\t return false;\n\t } else if (unpairedHi <= 10) {\n\t this.hideUnpaired();\n\t return false;\n\t }\n\t } else {\n\t if (this.unpairedPanelHidden) {\n\t $unpaired.show();\n\t this.unpairedPanelHidden = false;\n\t }\n\t }\n\t\n\t // when the divider gets close to the bottom - lock into hiding the paired section\n\t if (!movingUpwards) {\n\t if (this.pairedPanelHidden) {\n\t return false;\n\t } else if (pairedHi <= 15) {\n\t this.hidePaired();\n\t return false;\n\t }\n\t } else {\n\t if (this.pairedPanelHidden) {\n\t $paired.show();\n\t this.pairedPanelHidden = false;\n\t }\n\t }\n\t\n\t $unpaired.css({\n\t height: unpairedHi + 'px',\n\t flex: '0 0 auto'\n\t });\n\t return true;\n\t },\n\t\n\t // ........................................................................ paired\n\t /** select a pair when clicked */\n\t selectPair: function (ev) {\n\t ev.stopPropagation();\n\t $(ev.currentTarget).toggleClass('selected');\n\t },\n\t\n\t /** deselect all pairs */\n\t clearSelectedPaired: function (ev) {\n\t this.$('.paired-columns .dataset.selected').removeClass('selected');\n\t },\n\t\n\t /** rename a pair when the pair name is clicked */\n\t _clickPairName: function (ev) {\n\t ev.stopPropagation();\n\t var $name = $(ev.currentTarget),\n\t $pair = $name.parent().parent(),\n\t index = $pair.index('.dataset.paired'),\n\t pair = this.paired[index],\n\t response = prompt('Enter a new name for the pair:', pair.name);\n\t if (response) {\n\t pair.name = response;\n\t // set a flag (which won't be passed in json creation) for manual naming so we don't overwrite these\n\t // when adding/removing extensions\n\t //hackish\n\t pair.customizedName = true;\n\t $name.text(pair.name);\n\t }\n\t },\n\t\n\t /** unpair this pair */\n\t _clickUnpair: function (ev) {\n\t //if( !ev.currentTarget ){ return true; }\n\t var pairIndex = Math.floor($(ev.currentTarget).index('.unpair-btn'));\n\t //this.debug( 'pair:', pairIndex );\n\t this._unpair(this.paired[pairIndex]);\n\t },\n\t\n\t // ........................................................................ paired - drag and drop re-ordering\n\t //_dragenterPairedColumns : function( ev ){\n\t // this.debug( '_dragenterPairedColumns:', ev );\n\t //},\n\t //_dragleavePairedColumns : function( ev ){\n\t // //this.debug( '_dragleavePairedColumns:', ev );\n\t //},\n\t /** track the mouse drag over the paired list adding a placeholder to show where the drop would occur */\n\t _dragoverPairedColumns: function (ev) {\n\t //this.debug( '_dragoverPairedColumns:', ev );\n\t ev.preventDefault();\n\t\n\t var $list = this.$('.paired-columns .column-datasets');\n\t this._checkForAutoscroll($list, ev.originalEvent.clientY);\n\t //this.debug( ev.originalEvent.clientX, ev.originalEvent.clientY );\n\t var $nearest = this._getNearestPairedDatasetLi(ev.originalEvent.clientY);\n\t\n\t $('.element-drop-placeholder').remove();\n\t var $placeholder = $('
                                    ');\n\t if (!$nearest.length) {\n\t $list.append($placeholder);\n\t } else {\n\t $nearest.before($placeholder);\n\t }\n\t },\n\t\n\t /** If the mouse is near enough to the list's top or bottom, scroll the list */\n\t _checkForAutoscroll: function ($element, y) {\n\t var AUTOSCROLL_SPEED = 2;\n\t var offset = $element.offset(),\n\t scrollTop = $element.scrollTop(),\n\t upperDist = y - offset.top,\n\t lowerDist = offset.top + $element.outerHeight() - y;\n\t //this.debug( '_checkForAutoscroll:', scrollTop, upperDist, lowerDist );\n\t if (upperDist >= 0 && upperDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop - AUTOSCROLL_SPEED);\n\t } else if (lowerDist >= 0 && lowerDist < this.autoscrollDist) {\n\t $element.scrollTop(scrollTop + AUTOSCROLL_SPEED);\n\t }\n\t },\n\t\n\t /** get the nearest *previous* paired dataset PairView based on the mouse's Y coordinate.\n\t * If the y is at the end of the list, return an empty jQuery object.\n\t */\n\t _getNearestPairedDatasetLi: function (y) {\n\t var WIGGLE = 4,\n\t lis = this.$('.paired-columns .column-datasets li').toArray();\n\t for (var i = 0; i < lis.length; i++) {\n\t var $li = $(lis[i]),\n\t top = $li.offset().top,\n\t halfHeight = Math.floor($li.outerHeight() / 2) + WIGGLE;\n\t if (top + halfHeight > y && top - halfHeight < y) {\n\t //this.debug( y, top + halfHeight, top - halfHeight )\n\t return $li;\n\t }\n\t }\n\t return $();\n\t },\n\t /** drop (dragged/selected PairViews) onto the list, re-ordering both the DOM and the internal array of pairs */\n\t _dropPairedColumns: function (ev) {\n\t // both required for firefox\n\t ev.preventDefault();\n\t ev.dataTransfer.dropEffect = 'move';\n\t\n\t var $nearest = this._getNearestPairedDatasetLi(ev.originalEvent.clientY);\n\t if ($nearest.length) {\n\t this.$dragging.insertBefore($nearest);\n\t } else {\n\t // no nearest before - insert after last element (unpair button)\n\t this.$dragging.insertAfter(this.$('.paired-columns .unpair-btn').last());\n\t }\n\t // resync the creator's list of paired based on the new DOM order\n\t this._syncPairsToDom();\n\t return false;\n\t },\n\t /** resync the creator's list of paired based on the DOM order of pairs */\n\t _syncPairsToDom: function () {\n\t var newPaired = [];\n\t //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n\t this.$('.paired-columns .dataset.paired').each(function () {\n\t newPaired.push($(this).data('pair'));\n\t });\n\t //this.debug( newPaired );\n\t this.paired = newPaired;\n\t this._renderPaired();\n\t },\n\t /** drag communication with pair sub-views: dragstart */\n\t _pairDragstart: function (ev, pair) {\n\t //this.debug( '_pairDragstart', ev, pair )\n\t // auto select the pair causing the event and move all selected\n\t pair.$el.addClass('selected');\n\t var $selected = this.$('.paired-columns .dataset.selected');\n\t this.$dragging = $selected;\n\t },\n\t /** drag communication with pair sub-views: dragend - remove the placeholder */\n\t _pairDragend: function (ev, pair) {\n\t //this.debug( '_pairDragend', ev, pair )\n\t $('.element-drop-placeholder').remove();\n\t this.$dragging = null;\n\t },\n\t\n\t // ........................................................................ footer\n\t toggleExtensions: function (force) {\n\t var creator = this;\n\t creator.removeExtensions = force !== undefined ? force : !creator.removeExtensions;\n\t\n\t _.each(creator.paired, function (pair) {\n\t // don't overwrite custom names\n\t if (pair.customizedName) {\n\t return;\n\t }\n\t pair.name = creator._guessNameForPair(pair.forward, pair.reverse);\n\t });\n\t\n\t creator._renderPaired();\n\t creator._renderFooter();\n\t },\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** debug a dataset list */\n\t _printList: function (list) {\n\t var creator = this;\n\t _.each(list, function (e) {\n\t if (list === creator.paired) {\n\t creator._printPair(e);\n\t } else {\n\t //creator.debug( e );\n\t }\n\t });\n\t },\n\t\n\t /** print a pair Object */\n\t _printPair: function (pair) {\n\t this.debug(pair.forward.name, pair.reverse.name, ': ->', pair.name);\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'PairedCollectionCreator';\n\t },\n\t\n\t templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\t\n\t /** the header (not including help text) */\n\t header: _.template(['', '
                                    ', '', '', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '
                                    ', '', _l('Unpaired forward'), '', '', '
                                    ', '
                                    ', '', '
                                    ', '
                                    ', '
                                    ', '', '
                                    ', '
                                    ', '
                                    ', '', _l('Unpaired reverse'), '', '', '
                                    ', '
                                    ', '', '
                                    ', '
                                    ', '
                                    ', '
                                    '].join('')),\n\t\n\t /** the middle: unpaired, divider, and paired */\n\t middle: _.template([\n\t // contains two flex rows (rows that fill available space) and a divider btwn\n\t '
                                    ', '
                                    ', '
                                      ', '
                                      ', '
                                      ', '
                                        ', '
                                        ', '
                                        ', '
                                          ', '
                                          ', '
                                          ', '
                                          ', '
                                          ', '
                                          ', '
                                          ', '', '
                                          ', '', _l('Unpair all'), '', '
                                          ', '
                                          ', '
                                          ', '
                                            ', '
                                            '].join('')),\n\t\n\t /** creation and cancel controls */\n\t footer: _.template(['
                                            ', '
                                            ', '', '', '
                                            ', '
                                            ', '', '
                                            ', _l('Name'), ':
                                            ', '
                                            ', '
                                            ', '
                                            ', '
                                            ', '', '
                                            ', '', '', '
                                            ', '
                                            ', '
                                            ', '', '
                                            ', '
                                            '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

                                            ', _l(['Collections of paired datasets are ordered lists of dataset pairs (often forward and reverse reads). ', 'These collections can be passed to tools and workflows in order to have analyses done on each member of ', 'the entire group. This interface allows you to create a collection, choose which datasets are paired, ', 'and re-order the final collection.'].join('')), '

                                            ', '

                                            ', _l(['Unpaired datasets are shown in the unpaired section ', '(hover over the underlined words to highlight below). ', 'Paired datasets are shown in the paired section.', '

                                              To pair datasets, you can:', '
                                            • Click a dataset in the ', 'forward column ', 'to select it then click a dataset in the ', 'reverse column.', '
                                            • ', '
                                            • Click one of the \"Pair these datasets\" buttons in the ', 'middle column ', 'to pair the datasets in a particular row.', '
                                            • ', '
                                            • Click \"Auto-pair\" ', 'to have your datasets automatically paired based on name.', '
                                            • ', '
                                            '].join('')), '

                                            ', '

                                            ', _l(['

                                              You can filter what is shown in the unpaired sections by:', '
                                            • Entering partial dataset names in either the ', 'forward filter or ', 'reverse filter.', '
                                            • ', '
                                            • Choosing from a list of preset filters by clicking the ', '\"Choose filters\" link.', '
                                            • ', '
                                            • Entering regular expressions to match dataset names. See: ', 'MDN\\'s JavaScript Regular Expression Tutorial. ', 'Note: forward slashes (\\\\) are not needed.', '
                                            • ', '
                                            • Clearing the filters by clicking the ', '\"Clear filters\" link.', '
                                            • ', '
                                            '].join('')), '

                                            ', '

                                            ', _l(['To unpair individual dataset pairs, click the ', 'unpair buttons ( ). ', 'Click the \"Unpair all\" link to unpair all pairs.'].join('')), '

                                            ', '

                                            ', _l(['You can include or remove the file extensions (e.g. \".fastq\") from your pair names by toggling the ', '\"Remove file extensions from pair names?\" control.'].join('')), '

                                            ', '

                                            ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\". ', '(Note: you do not have to pair all unpaired datasets to finish.)'].join('')), '

                                            '].join(''))\n\t })\n\t });\n\t\n\t //=============================================================================\n\t /** a modal version of the paired collection creator */\n\t var pairedCollectionCreatorModal = function _pairedCollectionCreatorModal(datasets, options) {\n\t\n\t var deferred = jQuery.Deferred(),\n\t creator;\n\t\n\t options = _.defaults(options || {}, {\n\t datasets: datasets,\n\t oncancel: function () {\n\t Galaxy.modal.hide();\n\t deferred.reject('cancelled');\n\t },\n\t oncreate: function (creator, response) {\n\t Galaxy.modal.hide();\n\t deferred.resolve(response);\n\t }\n\t });\n\t\n\t if (!window.Galaxy || !Galaxy.modal) {\n\t throw new Error('Galaxy or Galaxy.modal not found');\n\t }\n\t\n\t creator = new PairedCollectionCreator(options);\n\t Galaxy.modal.show({\n\t title: 'Create a collection of paired datasets',\n\t body: creator.$el,\n\t width: '80%',\n\t height: '800px',\n\t closing_events: true\n\t });\n\t creator.render();\n\t window.creator = creator;\n\t\n\t //TODO: remove modal header\n\t return deferred;\n\t };\n\t\n\t //=============================================================================\n\t function createListOfPairsCollection(collection, defaultHideSourceItems) {\n\t var elements = collection.toJSON();\n\t //TODO: validate elements\n\t return pairedCollectionCreatorModal(elements, {\n\t historyId: collection.historyId,\n\t defaultHideSourceItems: defaultHideSourceItems\n\t });\n\t }\n\t\n\t //=============================================================================\n\t return {\n\t PairedCollectionCreator: PairedCollectionCreator,\n\t pairedCollectionCreatorModal: pairedCollectionCreatorModal,\n\t createListOfPairsCollection: createListOfPairsCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1), __webpack_require__(1)))\n\n/***/ },\n/* 122 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, _, jQuery) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(57), __webpack_require__(60), __webpack_require__(7), __webpack_require__(6)], __WEBPACK_AMD_DEFINE_RESULT__ = function (LIST_CREATOR, HDCA, BASE_MVC, _l) {\n\t\n\t 'use strict';\n\t\n\t var logNamespace = 'collections';\n\t /*==============================================================================\n\t TODO:\n\t the paired creator doesn't really mesh with the list creator as parent\n\t it may be better to make an abstract super class for both\n\t composites may inherit from this (or vis-versa)\n\t PairedDatasetCollectionElementView doesn't make a lot of sense\n\t \n\t ==============================================================================*/\n\t /** */\n\t var PairedDatasetCollectionElementView = Backbone.View.extend(BASE_MVC.LoggableMixin).extend({\n\t _logNamespace: logNamespace,\n\t\n\t //TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n\t tagName: 'li',\n\t className: 'collection-element',\n\t\n\t initialize: function (attributes) {\n\t this.element = attributes.element || {};\n\t this.identifier = attributes.identifier;\n\t },\n\t\n\t render: function () {\n\t this.$el.attr('data-element-id', this.element.id).html(this.template({ identifier: this.identifier, element: this.element }));\n\t return this;\n\t },\n\t\n\t //TODO: lots of unused space in the element - possibly load details and display them horiz.\n\t template: _.template(['<%- identifier %>', '<%- element.name %>'].join('')),\n\t\n\t /** remove the DOM and any listeners */\n\t destroy: function () {\n\t this.off();\n\t this.$el.remove();\n\t },\n\t\n\t /** string rep */\n\t toString: function () {\n\t return 'DatasetCollectionElementView()';\n\t }\n\t });\n\t\n\t // ============================================================================\n\t var _super = LIST_CREATOR.ListCollectionCreator;\n\t\n\t /** An interface for building collections.\n\t */\n\t var PairCollectionCreator = _super.extend({\n\t\n\t /** the class used to display individual elements */\n\t elementViewClass: PairedDatasetCollectionElementView,\n\t /** the class this creator will create and save */\n\t collectionClass: HDCA.HistoryPairDatasetCollection,\n\t className: 'pair-collection-creator collection-creator flex-row-container',\n\t\n\t /** override to no-op */\n\t _mangleDuplicateNames: function () {},\n\t\n\t // TODO: this whole pattern sucks. There needs to be two classes of problem area:\n\t // bad inital choices and\n\t // when the user has painted his/her self into a corner during creation/use-of-the-creator\n\t /** render the entire interface */\n\t render: function (speed, callback) {\n\t if (this.workingElements.length === 2) {\n\t return _super.prototype.render.call(this, speed, callback);\n\t }\n\t return this._renderInvalid(speed, callback);\n\t },\n\t\n\t // ------------------------------------------------------------------------ rendering elements\n\t /** render forward/reverse */\n\t _renderList: function (speed, callback) {\n\t //this.debug( '-- _renderList' );\n\t //precondition: there are two valid elements in workingElements\n\t var creator = this,\n\t $tmp = jQuery('
                                            '),\n\t $list = creator.$list();\n\t\n\t // lose the original views, create the new, append all at once, then call their renders\n\t _.each(this.elementViews, function (view) {\n\t view.destroy();\n\t creator.removeElementView(view);\n\t });\n\t $tmp.append(creator._createForwardElementView().$el);\n\t $tmp.append(creator._createReverseElementView().$el);\n\t $list.empty().append($tmp.children());\n\t _.invoke(creator.elementViews, 'render');\n\t },\n\t\n\t /** create the forward element view */\n\t _createForwardElementView: function () {\n\t return this._createElementView(this.workingElements[0], { identifier: 'forward' });\n\t },\n\t\n\t /** create the forward element view */\n\t _createReverseElementView: function () {\n\t return this._createElementView(this.workingElements[1], { identifier: 'reverse' });\n\t },\n\t\n\t /** create an element view, cache in elementViews, and return */\n\t _createElementView: function (element, options) {\n\t var elementView = new this.elementViewClass(_.extend(options, {\n\t element: element\n\t }));\n\t this.elementViews.push(elementView);\n\t return elementView;\n\t },\n\t\n\t /** swap the forward, reverse elements and re-render */\n\t swap: function () {\n\t this.workingElements = [this.workingElements[1], this.workingElements[0]];\n\t this._renderList();\n\t },\n\t\n\t events: _.extend(_.clone(_super.prototype.events), {\n\t 'click .swap': 'swap'\n\t }),\n\t\n\t // ------------------------------------------------------------------------ templates\n\t //TODO: move to require text plugin and load these as text\n\t //TODO: underscore currently unnecc. bc no vars are used\n\t //TODO: better way of localizing text-nodes in long strings\n\t /** underscore template fns attached to class */\n\t templates: _.extend(_.clone(_super.prototype.templates), {\n\t /** the middle: element list */\n\t middle: _.template(['', '
                                            ', '
                                            '].join('')),\n\t\n\t /** help content */\n\t helpContent: _.template(['

                                            ', _l(['Pair collections are permanent collections containing two datasets: one forward and one reverse. ', 'Often these are forward and reverse reads. The pair collections can be passed to tools and ', 'workflows in order to have analyses done on both datasets. This interface allows ', 'you to create a pair, name it, and swap which is forward and which reverse.'].join('')), '

                                            ', '
                                              ', '
                                            • ', _l(['Click the \"Swap\" link to make your forward dataset the reverse ', 'and the reverse dataset forward.'].join('')), '
                                            • ', '
                                            • ', _l(['Click the \"Cancel\" button to exit the interface.'].join('')), '
                                            • ', '

                                            ', '

                                            ', _l(['Once your collection is complete, enter a name and ', 'click \"Create list\".'].join('')), '

                                            '].join('')),\n\t\n\t /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n\t invalidInitial: _.template(['
                                            ', '
                                            ', '', '<% if( _.size( problems ) ){ %>', _l('The following selections could not be included due to problems'), '
                                              <% _.each( problems, function( problem ){ %>', '
                                            • <%- problem.element.name %>: <%- problem.text %>
                                            • ', '<% }); %>
                                            ', '<% } else if( _.size( elements ) === 0 ){ %>', _l('No datasets were selected'), '.', '<% } else if( _.size( elements ) === 1 ){ %>', _l('Only one dataset was selected'), ': <%- elements[0].name %>', '<% } else if( _.size( elements ) > 2 ){ %>', _l('Too many datasets were selected'), ': <%- _.pluck( elements, \"name\" ).join( \", \") %>', '<% } %>', '
                                            ', _l('Two (and only two) elements are needed for the pair'), '. ', _l('You may need to '), '', _l('cancel'), ' ', _l('and reselect new elements'), '.', '
                                            ', '
                                            ', '
                                            ', '
                                            ', '
                                            ', '
                                            ', '',\n\t // _l( 'Create a different kind of collection' ),\n\t '
                                            ', '
                                            ', '
                                            '].join(''))\n\t }),\n\t\n\t // ------------------------------------------------------------------------ misc\n\t /** string rep */\n\t toString: function () {\n\t return 'PairCollectionCreator';\n\t }\n\t });\n\t\n\t //==============================================================================\n\t /** List collection flavor of collectionCreatorModal. */\n\t var pairCollectionCreatorModal = function _pairCollectionCreatorModal(elements, options) {\n\t options = options || {};\n\t options.title = _l('Create a collection from a pair of datasets');\n\t return LIST_CREATOR.collectionCreatorModal(elements, options, PairCollectionCreator);\n\t };\n\t\n\t //==============================================================================\n\t /** Use a modal to create a pair collection, then add it to the given history contents.\n\t * @returns {Deferred} resolved when the collection is added to the history.\n\t */\n\t function createPairCollection(contents, defaultHideSourceItems) {\n\t var elements = contents.toJSON(),\n\t promise = pairCollectionCreatorModal(elements, {\n\t defaultHideSourceItems: defaultHideSourceItems,\n\t creationFn: function (elements, name, hideSourceItems) {\n\t elements = [{ name: \"forward\", src: \"hda\", id: elements[0].id }, { name: \"reverse\", src: \"hda\", id: elements[1].id }];\n\t return contents.createHDCA(elements, 'paired', name, hideSourceItems);\n\t }\n\t });\n\t return promise;\n\t }\n\t\n\t //==============================================================================\n\t return {\n\t PairCollectionCreator: PairCollectionCreator,\n\t pairCollectionCreatorModal: pairCollectionCreatorModal,\n\t createPairCollection: createPairCollection\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(3), __webpack_require__(1)))\n\n/***/ },\n/* 123 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(46), __webpack_require__(5), __webpack_require__(10)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, Tabs, Ui, Form) {\n\t\n\t /** Dataset edit attributes view */\n\t var View = Backbone.View.extend({\n\t initialize: function () {\n\t this.setElement('
                                            ');\n\t this.model = new Backbone.Model({ 'dataset_id': Galaxy.params.dataset_id });\n\t this.render();\n\t },\n\t\n\t // Fetch data for the selected dataset and \n\t // build tabs for editing its attributes\n\t render: function () {\n\t var url = Galaxy.root + 'dataset/edit',\n\t self = this;\n\t Utils.get({\n\t url: url,\n\t data: { 'dataset_id': self.model.get('dataset_id') },\n\t success: function (response) {\n\t self.render_attribute_page(self, response);\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while loading the dataset.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t\n\t /** Render all the tabs view */\n\t render_attribute_page: function (self, response) {\n\t var message = {\n\t 'message': response.message,\n\t 'status': response.status,\n\t 'persistent': true,\n\t 'cls': response.status + 'message'\n\t };\n\t self.$el.empty().append(self._templateHeader());\n\t self.display_message(message, self.$('.response-message'));\n\t // Create all tabs\n\t self.create_tabs(response, self.$('.edit-attr'));\n\t },\n\t\n\t /** Perform AJAX post call */\n\t call_ajax: function (self, data, tab_name) {\n\t var post_url = Galaxy.root + 'dataset/edit';\n\t $.ajax({\n\t type: \"PUT\",\n\t url: post_url,\n\t data: data,\n\t success: function (response) {\n\t self.render_attribute_page(self, response);\n\t self.reload_history();\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t\n\t /** Display actions messages */\n\t display_message: function (response, $el) {\n\t $el.empty().html(new Ui.Message(response).$el);\n\t },\n\t\n\t /** Create tabs for different attributes of dataset*/\n\t create_tabs: function (response, $el_edit_attr) {\n\t var self = this;\n\t self.tabs = new Tabs.View();\n\t self.tabs.add({\n\t id: 'attributes',\n\t title: 'Attributes',\n\t icon: 'fa fa-bars',\n\t tooltip: 'Edit dataset attributes',\n\t $el: self._getAttributesFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'convert',\n\t title: 'Convert',\n\t icon: 'fa-gear',\n\t tooltip: 'Convert to new format',\n\t $el: self._getConvertFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'datatype',\n\t title: 'Datatypes',\n\t icon: 'fa-database',\n\t tooltip: 'Change data type',\n\t $el: self._getChangeDataTypeFormTemplate(response)\n\t });\n\t\n\t self.tabs.add({\n\t id: 'permissions',\n\t title: 'Permissions',\n\t icon: 'fa-user',\n\t tooltip: 'Permissions',\n\t $el: self._getPermissionsFormTemplate(response)\n\t });\n\t $el_edit_attr.append(self.tabs.$el);\n\t self.tabs.showTab('attributes');\n\t },\n\t\n\t /** Main template */\n\t _templateHeader: function () {\n\t return '
                                            ' + '
                                            ' + '

                                            Edit Dataset Attributes

                                            ' + '
                                            ';\n\t },\n\t\n\t /** Attributes tab template */\n\t _getAttributesFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Edit attributes',\n\t inputs: response.edit_attributes_inputs,\n\t operations: {\n\t 'submit_editattr': new Ui.ButtonIcon({\n\t tooltip: 'Save attributes of the dataset.',\n\t icon: 'fa-floppy-o ',\n\t title: 'Save attributes',\n\t onclick: function () {\n\t self._submit(self, form, response, \"edit_attributes\");\n\t }\n\t }),\n\t 'submit_autocorrect': new Ui.ButtonIcon({\n\t tooltip: 'This will inspect the dataset and attempt to correct the values of fields if they are not accurate.',\n\t icon: 'fa-undo ',\n\t title: 'Auto-detect',\n\t onclick: function () {\n\t self._submit(self, form, response, \"auto-detect\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Convert tab template */\n\t _getConvertFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Convert to new format',\n\t inputs: response.convert_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Convert the datatype to a new format.',\n\t title: 'Convert datatype',\n\t icon: 'fa-exchange ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"convert\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Change datatype template */\n\t _getChangeDataTypeFormTemplate: function (response) {\n\t var self = this;\n\t var form = new Form({\n\t title: 'Change datatype',\n\t inputs: response.convert_datatype_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Change the datatype to a new type.',\n\t title: 'Change datatype',\n\t icon: 'fa-exchange ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"change\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Permissions template */\n\t _getPermissionsFormTemplate: function (response) {\n\t var template = \"\",\n\t self = this;\n\t if (response.can_manage_dataset) {\n\t var form = new Form({\n\t title: 'Manage dataset permissions on ' + response.display_name,\n\t inputs: response.permission_inputs,\n\t operations: {\n\t 'submit': new Ui.ButtonIcon({\n\t tooltip: 'Save permissions.',\n\t title: 'Save permissions',\n\t icon: 'fa-floppy-o ',\n\t onclick: function () {\n\t self._submit(self, form, response, \"permissions\");\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t } else {\n\t var form = new Form({\n\t title: 'View permissions',\n\t inputs: response.permission_inputs\n\t });\n\t return form.$el;\n\t }\n\t },\n\t\n\t /** Submit action */\n\t _submit: function (self, form, response, type) {\n\t var form_data = form.data.create();\n\t form_data.dataset_id = response.dataset_id;\n\t switch (type) {\n\t case \"edit_attributes\":\n\t form_data.save = 'Save';\n\t break;\n\t\n\t case \"auto-detect\":\n\t form_data.detect = 'Auto-detect';\n\t break;\n\t\n\t case \"convert\":\n\t if (form_data.target_type !== null && form_data.target_type) {\n\t form_data.dataset_id = response.dataset_id;\n\t form_data.convert_data = 'Convert';\n\t }\n\t break;\n\t\n\t case \"change\":\n\t form_data.change = 'Save';\n\t break;\n\t\n\t case \"permissions\":\n\t var post_data = {};\n\t post_data.permissions = JSON.stringify(form_data);\n\t post_data.update_roles_button = \"Save\";\n\t post_data.dataset_id = response.dataset_id;\n\t form_data = post_data;\n\t break;\n\t }\n\t self.call_ajax(self, form_data);\n\t },\n\t\n\t /** Reload Galaxy's history after updating dataset's attributes */\n\t reload_history: function () {\n\t if (window.Galaxy) {\n\t window.Galaxy.currHistoryPanel.loadCurrentHistory();\n\t }\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 124 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $) {!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(4), __webpack_require__(5), __webpack_require__(10)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Utils, Ui, Form) {\n\t\n\t /** Dataset edit attributes view */\n\t var View = Backbone.View.extend({\n\t initialize: function () {\n\t this.setElement('
                                            ');\n\t this.model = new Backbone.Model({ 'dataset_id': Galaxy.params.dataset_id });\n\t this.render();\n\t },\n\t\n\t // Fetch data for the selected dataset and\n\t render: function () {\n\t var data_url = Galaxy.root + 'api/datasets/' + this.model.get('dataset_id'),\n\t self = this;\n\t\n\t Utils.get({\n\t url: data_url,\n\t success: function (dataset) {\n\t var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True';\n\t Utils.get({\n\t url: job_url,\n\t success: function (job) {\n\t var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True';\n\t self.render_error_page(self, dataset, job);\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while loading the job.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while loading the dataset.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t },\n\t\n\t /** Render the view */\n\t render_error_page: function (self, dataset, job) {\n\t self.$el.empty().append(self._templateHeader());\n\t self.$el.append('

                                            Dataset Error

                                            ');\n\t self.$el.append('

                                            An error occured while running the tool ' + job.tool_id + '.

                                            ');\n\t self.$el.append('

                                            Tool execution generated the following messages:

                                            ');\n\t self.$el.append('
                                            ' + job.stderr + '
                                            ');\n\t self.$el.append('

                                            Report This Error

                                          1. ');\n\t self.$el.append('

                                            Usually the local Galaxy administrators regularly review errors that occur on the server. However, if you would like to provide additional information (such as what you were trying to do when the error occurred) and a contact e-mail address, we will be better able to investigate your problem and get back to you.

                                            ');\n\t self.$el.append(self._getBugFormTemplate(dataset, job));\n\t },\n\t\n\t /** Display actions messages */\n\t display_message: function (response, $el, doNotClear, safe) {\n\t if (!safe) {\n\t if (doNotClear) {\n\t $el.append(new Ui.Message(response).$el);\n\t } else {\n\t $el.empty().html(new Ui.Message(response).$el);\n\t }\n\t } else {\n\t if (doNotClear) {\n\t $el.append(new Ui.UnescapedMessage(response).$el);\n\t } else {\n\t $el.empty().html(new Ui.UnescapedMessage(response).$el);\n\t }\n\t }\n\t },\n\t\n\t /** Main template */\n\t _templateHeader: function () {\n\t return '
                                            ' + '
                                            ' + '
                                            ';\n\t },\n\t\n\t /** Convert tab template */\n\t _getBugFormTemplate: function (dataset, job) {\n\t var self = this;\n\t var inputs = [{\n\t \"help\": \"Your email address\",\n\t \"options\": [],\n\t \"type\": \"text\",\n\t \"name\": \"email\",\n\t \"label\": \"Your email\",\n\t \"value\": Galaxy.user.get('email')\n\t }, {\n\t \"help\": \"Any additional comments you can provide regarding what you were doing at the time of the bug.\",\n\t \"options\": [],\n\t \"type\": \"text\",\n\t \"area\": true,\n\t \"name\": \"message\",\n\t \"label\": \"Message\"\n\t }];\n\t\n\t // TODO\n\t if (false) {\n\t inputs.push({\n\t \"name\": \"public_consent\",\n\t \"label\": \"Public Disclosure Consent\",\n\t \"help\": \"This Galaxy is configured to report to one or more error reporting backends that public to the world. By selecting 'yes', you acknowledge that this bug report will be made public.\",\n\t \"value\": String(Boolean(false)),\n\t \"options\": [],\n\t \"type\": \"boolean\"\n\t });\n\t }\n\t\n\t var form = new Form({\n\t title: 'Error Report',\n\t inputs: inputs,\n\t buttons: {\n\t save: new Ui.Button({\n\t icon: 'fa-bug',\n\t title: 'Report',\n\t cls: 'ui-button btn btn-primary',\n\t floating: 'clear',\n\t onclick: function () {\n\t var form_data = form.data.create();\n\t var url = Galaxy.root + 'api/jobs/' + job.id + '/error';\n\t form_data.dataset_id = dataset.id;\n\t self.submit(form_data, url);\n\t }\n\t })\n\t }\n\t });\n\t return form.$el;\n\t },\n\t\n\t /** Make ajax request */\n\t submit: function (form_data, url) {\n\t var self = this;\n\t // Some required metadata\n\t $.ajax({\n\t type: \"POST\",\n\t url: url,\n\t data: form_data,\n\t success: function (response) {\n\t // Clear out the div\n\t self.$el.empty().append(self._templateHeader());\n\t // And display the messages.\n\t response.messages.forEach(function (message) {\n\t self.display_message({\n\t 'status': message[1],\n\t 'message': message[0],\n\t 'persistent': true\n\t }, self.$('.response-message'), true, true);\n\t });\n\t },\n\t error: function (response) {\n\t var error_response = {\n\t 'status': 'error',\n\t 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n\t 'persistent': true,\n\t 'cls': 'errormessage'\n\t };\n\t self.display_message(error_response, self.$('.response-message'));\n\t }\n\t });\n\t }\n\t });\n\t\n\t return {\n\t View: View\n\t };\n\t}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n\t/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(1)))\n\n/***/ },\n/* 125 */\n/***/ function(module, exports, __webpack_require__) {\n\n\tvar __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(Backbone, $, _) {/** This class renders the grid list with shared section. */\n\t!(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(12)], __WEBPACK_AMD_DEFINE_RESULT__ = function (GridView) {\n\t var View = Backbone.View.extend({\n\t initialize: function (options) {\n\t var self = this;\n\t this.setElement($('
                                            '));\n\t this.model = new Backbone.Model(options);\n\t this.item = this.model.get('item');\n\t $.ajax({\n\t url: Galaxy.root + this.item + '/' + this.model.get('action_id'),\n\t success: function (response) {\n\t response['dict_format'] = true;\n\t self.model.set(response);\n\t self.render();\n\t }\n\t });\n\t },\n\t\n\t render: function () {\n\t var grid = new GridView(this.model.attributes);\n\t this.$el.empty().append(grid.$el);\n\t this.$el.append(this._templateShared());\n\t },\n\t\n\t _templateShared: function () {\n\t var self = this;\n\t var $tmpl = $('
                                            ' + '

                                            ' + this.model.get('plural') + ' shared with you by others

                                            ' + '
                                            ');\n\t var options = this.model.attributes;\n\t if (options.shared_by_others && options.shared_by_others.length > 0) {\n\t var $table = $('' + '' + '' + '' + '' + '
                                            TitleOwner
                                            ');\n\t _.each(options.shared_by_others, function (it, index) {\n\t var display_url = Galaxy.root + self.item + '/display_by_username_and_slug?username=' + it.username + '&slug=' + it.slug;\n\t $table.append('
                                            ' + '' + _.escape(it.title) + '' + '' + _.escape(it.username) + '
                                            ' + '
                                            ' + '
                                            ' + '
                                            ' + '
                                            ' + '
                                            You can tell Galaxy to download data from web by entering URL in this box (one per line). You can also directly paste the contents of a file.
                                            ' + '',\n '
                                            ',\n '
                                            '\n ].join( '' );\n }\n});\n\n//==============================================================================\nreturn {\n CitationView : CitationView,\n CitationListView : CitationListView\n};\n\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/citation/citation-view.js","define([\n \"mvc/list/list-item\",\n \"mvc/dataset/dataset-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_ITEM, DATASET_LI, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar FoldoutListItemView = LIST_ITEM.FoldoutListItemView,\n ListItemView = LIST_ITEM.ListItemView;\n/** @class Read only view for DatasetCollection.\n */\nvar DCListItemView = FoldoutListItemView.extend(\n/** @lends DCListItemView.prototype */{\n\n className : FoldoutListItemView.prototype.className + \" dataset-collection\",\n id : function(){\n return [ 'dataset_collection', this.model.get( 'id' ) ].join( '-' );\n },\n\n /** override to add linkTarget */\n initialize : function( attributes ){\n this.linkTarget = attributes.linkTarget || '_blank';\n this.hasUser = attributes.hasUser;\n FoldoutListItemView.prototype.initialize.call( this, attributes );\n },\n\n /** event listeners */\n _setUpListeners : function(){\n FoldoutListItemView.prototype._setUpListeners.call( this );\n this.listenTo( this.model, 'change', function( model, options ){\n // if the model has changed deletion status render it entirely\n if( _.has( model.changed, 'deleted' ) ){\n this.render();\n\n // if the model has been decorated after the fact with the element count,\n // render the subtitle where the count is displayed\n } else if( _.has( model.changed, 'element_count' ) ){\n this.$( '> .title-bar .subtitle' ).replaceWith( this._renderSubtitle() );\n }\n });\n },\n\n // ......................................................................... rendering\n /** render a subtitle to show the user what sort of collection this is */\n _renderSubtitle : function(){\n return $( this.templates.subtitle( this.model.toJSON(), this ) );\n },\n\n // ......................................................................... foldout\n /** override to add linktarget to sub-panel */\n _getFoldoutPanelOptions : function(){\n var options = FoldoutListItemView.prototype._getFoldoutPanelOptions.call( this );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n hasUser : this.hasUser\n });\n },\n\n /** override to not catch sub-panel selectors */\n $selector : function(){\n return this.$( '> .selector' );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDCListItemView.prototype.templates = (function(){\n\n var warnings = _.extend( {}, FoldoutListItemView.prototype.templates.warnings, {\n error : BASE_MVC.wrapTemplate([\n // error during index fetch - show error on dataset\n '<% if( model.error ){ %>',\n '
                                            ',\n _l( 'There was an error getting the data for this collection' ), ': <%- model.error %>',\n '
                                            ',\n '<% } %>'\n ]),\n purged : BASE_MVC.wrapTemplate([\n '<% if( model.purged ){ %>',\n '
                                            ',\n _l( 'This collection has been deleted and removed from disk' ),\n '
                                            ',\n '<% } %>'\n ]),\n deleted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.deleted && !model.purged ){ %>',\n '
                                            ',\n _l( 'This collection has been deleted' ),\n '
                                            ',\n '<% } %>'\n ])\n });\n\n // use element identifier\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '
                                            ',\n '<%- collection.element_identifier || collection.name %>',\n '
                                            ',\n '
                                            ',\n '
                                            '\n ], 'collection' );\n\n // use element identifier\n var subtitleTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '<% var countText = collection.element_count? ( collection.element_count + \" \" ) : \"\"; %>',\n '<% if( collection.collection_type === \"list\" ){ %>',\n _l( 'a list of <%- countText %>datasets' ),\n '<% } else if( collection.collection_type === \"paired\" ){ %>',\n _l( 'a pair of datasets' ),\n '<% } else if( collection.collection_type === \"list:paired\" ){ %>',\n _l( 'a list of <%- countText %>dataset pairs' ),\n '<% } else if( collection.collection_type === \"list:list\" ){ %>',\n _l( 'a list of <%- countText %>dataset lists' ),\n '<% } %>',\n '
                                            '\n ], 'collection' );\n\n return _.extend( {}, FoldoutListItemView.prototype.templates, {\n warnings : warnings,\n titleBar : titleBarTemplate,\n subtitle : subtitleTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for DatasetCollectionElement.\n */\nvar DCEListItemView = ListItemView.extend(\n/** @lends DCEListItemView.prototype */{\n\n /** add the DCE class to the list item */\n className : ListItemView.prototype.className + \" dataset-collection-element\",\n\n /** set up */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( 'DCEListItemView.initialize:', attributes );\n ListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCEListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDCEListItemView.prototype.templates = (function(){\n\n // use the element identifier here - since that will persist and the user will need it\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '
                                            ',\n '<%- element.element_identifier %>',\n '
                                            ',\n '
                                            ',\n '
                                            '\n ], 'element' );\n\n return _.extend( {}, ListItemView.prototype.templates, {\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also an DatasetAssociation\n * (a dataset contained in a dataset collection).\n */\nvar DatasetDCEListItemView = DATASET_LI.DatasetListItemView.extend(\n/** @lends DatasetDCEListItemView.prototype */{\n\n className : DATASET_LI.DatasetListItemView.prototype.className + \" dataset-collection-element\",\n\n /** set up */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( 'DatasetDCEListItemView.initialize:', attributes );\n DATASET_LI.DatasetListItemView.prototype.initialize.call( this, attributes );\n },\n\n /** In this override, only get details if in the ready state.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetDCEListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetDCEListItemView.prototype.templates = (function(){\n\n // use the element identifier here and not the dataset name\n //TODO:?? can we steal the DCE titlebar?\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '',\n '
                                            ',\n '<%- element.element_identifier %>',\n '
                                            ',\n '
                                            '\n ], 'element' );\n\n return _.extend( {}, DATASET_LI.DatasetListItemView.prototype.templates, {\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n * (a nested DC).\n */\nvar NestedDCDCEListItemView = DCListItemView.extend(\n/** @lends NestedDCDCEListItemView.prototype */{\n\n className : DCListItemView.prototype.className + \" dataset-collection-element\",\n\n /** In this override, add the state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n DCListItemView.prototype._swapNewRender.call( this, $newRender );\n var state = this.model.get( 'state' ) || 'ok';\n this.$el.addClass( 'state-' + state );\n return this.$el;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'NestedDCDCEListItemView(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n return {\n DCListItemView : DCListItemView,\n DCEListItemView : DCEListItemView,\n DatasetDCEListItemView : DatasetDCEListItemView,\n NestedDCDCEListItemView : NestedDCDCEListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-li.js","define([\n \"mvc/dataset/dataset-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_MODEL, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/*\nNotes:\n\nTerminology:\n DatasetCollection/DC : a container of datasets or nested DatasetCollections\n Element/DatasetCollectionElement/DCE : an item contained in a DatasetCollection\n HistoryDatasetCollectionAssociation/HDCA: a DatasetCollection contained in a history\n\n\nThis all seems too complex unfortunately:\n\n- Terminology collision between DatasetCollections (DCs) and Backbone Collections.\n- In the DatasetCollections API JSON, DC Elements use a 'Has A' stucture to *contain*\n either a dataset or a nested DC. This would make the hierarchy much taller. I've\n decided to merge the contained JSON with the DC element json - making the 'has a'\n relation into an 'is a' relation. This seems simpler to me and allowed a lot of\n DRY in both models and views, but may make tracking or tracing within these models\n more difficult (since DatasetCollectionElements are now *also* DatasetAssociations\n or DatasetCollections (nested)). This also violates the rule of thumb about\n favoring aggregation over inheritance.\n- Currently, there are three DatasetCollection subclasses: List, Pair, and ListPaired.\n These each should a) be usable on their own, b) be usable in the context of\n nesting within a collection model (at least in the case of ListPaired), and\n c) be usable within the context of other container models (like History or\n LibraryFolder, etc.). I've tried to separate/extract classes in order to\n handle those three situations, but it's proven difficult to do in a simple,\n readable manner.\n- Ideally, histories and libraries would inherit from the same server models as\n dataset collections do since they are (in essence) dataset collections themselves -\n making the whole nested structure simpler. This would be a large, error-prone\n refactoring and migration.\n\nMany of the classes and heirarchy are meant as extension points so, while the\nrelations and flow may be difficult to understand initially, they'll allow us to\nhandle the growth or flux dataset collection in the future (w/o actually implementing\nany YAGNI).\n\n*/\n//_________________________________________________________________________________________________ ELEMENTS\n/** @class mixin for Dataset collection elements.\n * When collection elements are passed from the API, the underlying element is\n * in a sub-object 'object' (IOW, a DCE representing an HDA will have HDA json in element.object).\n * This mixin uses the constructor and parse methods to merge that JSON with the DCE attribtues\n * effectively changing a DCE from a container to a subclass (has a --> is a).\n */\nvar DatasetCollectionElementMixin = {\n\n /** default attributes used by elements in a dataset collection */\n defaults : {\n model_class : 'DatasetCollectionElement',\n element_identifier : null,\n element_index : null,\n element_type : null\n },\n\n /** merge the attributes of the sub-object 'object' into this model */\n _mergeObject : function( attributes ){\n // if we don't preserve and correct ids here, the element id becomes the object id\n // and collision in backbone's _byId will occur and only\n _.extend( attributes, attributes.object, { element_id: attributes.id });\n delete attributes.object;\n return attributes;\n },\n\n /** override to merge this.object into this */\n constructor : function( attributes, options ){\n // console.debug( '\\t DatasetCollectionElement.constructor:', attributes, options );\n attributes = this._mergeObject( attributes );\n this.idAttribute = 'element_id';\n Backbone.Model.apply( this, arguments );\n },\n\n /** when the model is fetched, merge this.object into this */\n parse : function( response, options ){\n var attributes = response;\n attributes = this._mergeObject( attributes );\n return attributes;\n }\n};\n\n/** @class Concrete class of Generic DatasetCollectionElement */\nvar DatasetCollectionElement = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( DatasetCollectionElementMixin )\n .extend({ _logNamespace : 'collections' });\n\n\n//==============================================================================\n/** @class Base/Abstract Backbone collection for Generic DCEs. */\nvar DCECollection = Backbone.Collection.extend( BASE_MVC.LoggableMixin ).extend(\n/** @lends DCECollection.prototype */{\n _logNamespace : 'collections',\n\n model: DatasetCollectionElement,\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetCollectionElementCollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a dataset collection element that is a dataset (HDA).\n */\nvar DatasetDCE = DATASET_MODEL.DatasetAssociation.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends DatasetDCE.prototype */{\n\n /** url fn */\n url : function(){\n // won't always be an hda\n if( !this.has( 'history_id' ) ){\n console.warn( 'no endpoint for non-hdas within a collection yet' );\n // (a little silly since this api endpoint *also* points at hdas)\n return Galaxy.root + 'api/datasets';\n }\n return Galaxy.root + 'api/histories/' + this.get( 'history_id' ) + '/contents/' + this.get( 'id' );\n },\n\n defaults : _.extend( {},\n DATASET_MODEL.DatasetAssociation.prototype.defaults,\n DatasetCollectionElementMixin.defaults\n ),\n\n _downloadQueryParameters : function() {\n return '?to_ext=' + this.get( 'file_ext' ) + '&hdca_id=' + this.get( 'parent_hdca_id' ) + '&element_identifier=' + this.get( 'element_identifier' );\n },\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually for now\n /** call the mixin constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t DatasetDCE.constructor:', attributes, options );\n //DATASET_MODEL.DatasetAssociation.prototype.constructor.call( this, attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** Does this model already contain detailed data (as opposed to just summary level data)? */\n hasDetails : function(){\n return this.elements && this.elements.length;\n },\n\n /** String representation. */\n toString : function(){\n var objStr = this.get( 'element_identifier' );\n return ([ 'DatasetDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class DCECollection of DatasetDCE's (a list of datasets, a pair of datasets).\n */\nvar DatasetDCECollection = DCECollection.extend(\n/** @lends DatasetDCECollection.prototype */{\n model: DatasetDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//_________________________________________________________________________________________________ COLLECTIONS\n/** @class Backbone model for Dataset Collections.\n * The DC API returns an array of JSON objects under the attribute elements.\n * This model:\n * - removes that array/attribute ('elements') from the model,\n * - creates a bbone collection (of the class defined in the 'collectionClass' attribute),\n * - passes that json onto the bbone collection\n * - caches the bbone collection in this.elements\n */\nvar DatasetCollection = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.SearchableModelMixin )\n .extend(/** @lends DatasetCollection.prototype */{\n _logNamespace : 'collections',\n\n /** default attributes for a model */\n defaults : {\n /* 'list', 'paired', or 'list:paired' */\n collection_type : null,\n //??\n deleted : false\n },\n\n /** Which class to use for elements */\n collectionClass : DCECollection,\n\n /** set up: create elements instance var and (on changes to elements) update them */\n initialize : function( model, options ){\n this.debug( this + '(DatasetCollection).initialize:', model, options, this );\n this.elements = this._createElementsModel();\n this.on( 'change:elements', function(){\n this.log( 'change:elements' );\n //TODO: prob. better to update the collection instead of re-creating it\n this.elements = this._createElementsModel();\n });\n },\n\n /** move elements model attribute to full collection */\n _createElementsModel : function(){\n this.debug( this + '._createElementsModel', this.collectionClass, this.get( 'elements' ), this.elements );\n //TODO: same patterns as DatasetCollectionElement _createObjectModel - refactor to BASE_MVC.hasSubModel?\n var elements = this.get( 'elements' ) || [];\n this.unset( 'elements', { silent: true });\n var self = this;\n _.each(elements, function(element, index) {\n _.extend(element, {\"parent_hdca_id\": self.get(\"id\")});\n });\n this.elements = new this.collectionClass( elements );\n //this.debug( 'collectionClass:', this.collectionClass + '', this.elements );\n return this.elements;\n },\n\n // ........................................................................ common queries\n /** pass the elements back within the model json when this is serialized */\n toJSON : function(){\n var json = Backbone.Model.prototype.toJSON.call( this );\n if( this.elements ){\n json.elements = this.elements.toJSON();\n }\n return json;\n },\n\n /** Is this collection in a 'ready' state no processing (for the collection) is left\n * to do on the server.\n */\n inReadyState : function(){\n var populated = this.get( 'populated' );\n return ( this.isDeletedOrPurged() || populated );\n },\n\n //TODO:?? the following are the same interface as DatasetAssociation - can we combine?\n /** Does the DC contain any elements yet? Is a fetch() required? */\n hasDetails : function(){\n return this.elements.length !== 0;\n },\n\n /** Given the filters, what models in this.elements would be returned? */\n getVisibleContents : function( filters ){\n // filters unused for now\n return this.elements;\n },\n\n // ........................................................................ ajax\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** save this dataset, _Mark_ing it as deleted (just a flag) */\n 'delete' : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** save this dataset, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) || this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** Is this collection deleted or purged? */\n isDeletedOrPurged : function(){\n return ( this.get( 'deleted' ) || this.get( 'purged' ) );\n },\n\n // ........................................................................ searchable\n /** searchable attributes for collections */\n searchAttributes : [\n 'name', 'tags'\n ],\n\n // ........................................................................ misc\n /** String representation */\n toString : function(){\n var idAndName = [ this.get( 'id' ), this.get( 'name' ) || this.get( 'element_identifier' ) ];\n return 'DatasetCollection(' + ( idAndName.join(',') ) + ')';\n }\n});\n\n\n//==============================================================================\n/** Model for a DatasetCollection containing datasets (non-nested).\n */\nvar ListDatasetCollection = DatasetCollection.extend(\n/** @lends ListDatasetCollection.prototype */{\n\n /** override since we know the collection will only contain datasets */\n collectionClass : DatasetDCECollection,\n\n /** String representation. */\n toString : function(){ return 'List' + DatasetCollection.prototype.toString.call( this ); }\n});\n\n\n//==============================================================================\n/** Model for a DatasetCollection containing fwd/rev datasets (a list of 2).\n */\nvar PairDatasetCollection = ListDatasetCollection.extend(\n/** @lends PairDatasetCollection.prototype */{\n\n /** String representation. */\n toString : function(){ return 'Pair' + DatasetCollection.prototype.toString.call( this ); }\n});\n\n\n//_________________________________________________________________________________________________ NESTED COLLECTIONS\n// this is where things get weird, man. Weird.\n//TODO: it might be possible to compact all the following...I think.\n//==============================================================================\n/** @class Backbone model for a Generic DatasetCollectionElement that is also a DatasetCollection\n * (a nested collection). Currently only list:paired.\n */\nvar NestedDCDCE = DatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedDCDCE.prototype */{\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually it now\n /** call the mixin constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedDCDCE.constructor:', attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection containing Generic NestedDCDCE's (nested dataset collections).\n */\nvar NestedDCDCECollection = DCECollection.extend(\n/** @lends NestedDCDCECollection.prototype */{\n\n /** This is a collection of nested collections */\n model: NestedDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a paired dataset collection within a list:paired dataset collection.\n */\nvar NestedPairDCDCE = PairDatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedPairDCDCE.prototype */{\n//TODO:?? possibly rename to NestedDatasetCollection?\n\n // because all objects have constructors (as this hashmap would even if this next line wasn't present)\n // the constructor in hcontentMixin won't be attached by BASE_MVC.mixin to this model\n // - re-apply manually it now\n /** This is both a collection and a collection element - call the constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedPairDCDCE.constructor:', attributes, options );\n //DatasetCollection.constructor.call( this, attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedPairDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection for a backbone collection containing paired dataset collections.\n */\nvar NestedPairDCDCECollection = NestedDCDCECollection.extend(\n/** @lends PairDCDCECollection.prototype */{\n\n /** We know this collection is composed of only nested pair collections */\n model: NestedPairDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedPairDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone Model for a DatasetCollection (list) that contains DatasetCollections (pairs).\n */\nvar ListPairedDatasetCollection = DatasetCollection.extend(\n/** @lends ListPairedDatasetCollection.prototype */{\n\n /** list:paired is the only collection that itself contains collections */\n collectionClass : NestedPairDCDCECollection,\n\n /** String representation. */\n toString : function(){\n return ([ 'ListPairedDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for a list dataset collection within a list:list dataset collection. */\nvar NestedListDCDCE = ListDatasetCollection.extend( BASE_MVC.mixin( DatasetCollectionElementMixin,\n/** @lends NestedListDCDCE.prototype */{\n\n /** This is both a collection and a collection element - call the constructor */\n constructor : function( attributes, options ){\n this.debug( '\\t NestedListDCDCE.constructor:', attributes, options );\n DatasetCollectionElementMixin.constructor.call( this, attributes, options );\n },\n\n /** String representation. */\n toString : function(){\n var objStr = ( this.object )?( '' + this.object ):( this.get( 'element_identifier' ) );\n return ([ 'NestedListDCDCE(', objStr, ')' ].join( '' ));\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection containing list dataset collections. */\nvar NestedListDCDCECollection = NestedDCDCECollection.extend({\n\n /** We know this collection is composed of only nested pair collections */\n model: NestedListDCDCE,\n\n /** String representation. */\n toString : function(){\n return ([ 'NestedListDCDCECollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n/** @class Backbone Model for a DatasetCollection (list) that contains other lists. */\nvar ListOfListsDatasetCollection = DatasetCollection.extend({\n\n /** list:paired is the only collection that itself contains collections */\n collectionClass : NestedListDCDCECollection,\n\n /** String representation. */\n toString : function(){\n return ([ 'ListOfListsDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n ListDatasetCollection : ListDatasetCollection,\n PairDatasetCollection : PairDatasetCollection,\n ListPairedDatasetCollection : ListPairedDatasetCollection,\n ListOfListsDatasetCollection: ListOfListsDatasetCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-model.js","\ndefine([\n \"mvc/history/hdca-model\",\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"mvc/collection/base-creator\",\n \"mvc/ui/ui-modal\",\n \"utils/natural-sort\",\n \"utils/localization\",\n \"ui/hoverhighlight\"\n], function( HDCA, STATES, BASE_MVC, baseCreator, UI_MODAL, naturalSort, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n\n/*==============================================================================\nTODO:\n use proper Element model and not just json\n straighten out createFn, collection.createHDCA\n possibly stop using modals for this\n It would be neat to do a drag and drop\n\n==============================================================================*/\n/** A view for both DatasetDCEs and NestedDCDCEs\n * (things that implement collection-model:DatasetCollectionElementMixin)\n */\nvar DatasetCollectionElementView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n//TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n tagName : 'li',\n className : 'collection-element',\n\n initialize : function( attributes ){\n this.element = attributes.element || {};\n this.selected = attributes.selected || false;\n },\n\n render : function(){\n this.$el\n .attr( 'data-element-id', this.element.id )\n .attr( 'draggable', true )\n .html( this.template({ element: this.element }) );\n if( this.selected ){\n this.$el.addClass( 'selected' );\n }\n return this;\n },\n\n //TODO: lots of unused space in the element - possibly load details and display them horiz.\n template : _.template([\n '',\n '<%- element.name %>',\n '',\n '',\n ].join('')),\n\n /** select this element and pub */\n select : function( toggle ){\n this.$el.toggleClass( 'selected', toggle );\n this.trigger( 'select', {\n source : this,\n selected : this.$el.hasClass( 'selected' )\n });\n },\n\n /** animate the removal of this element and pub */\n discard : function(){\n var view = this,\n parentWidth = this.$el.parent().width();\n this.$el.animate({ 'margin-right' : parentWidth }, 'fast', function(){\n view.trigger( 'discard', {\n source : view\n });\n view.destroy();\n });\n },\n\n /** remove the DOM and any listeners */\n destroy : function(){\n this.off();\n this.$el.remove();\n },\n\n events : {\n 'click' : '_click',\n 'click .name' : '_clickName',\n 'click .discard': '_clickDiscard',\n\n 'dragstart' : '_dragstart',\n 'dragend' : '_dragend',\n 'dragover' : '_sendToParent',\n 'drop' : '_sendToParent'\n },\n\n /** select when the li is clicked */\n _click : function( ev ){\n ev.stopPropagation();\n this.select( ev );\n },\n\n /** rename a pair when the name is clicked */\n _clickName : function( ev ){\n ev.stopPropagation();\n ev.preventDefault();\n var promptString = [ _l( 'Enter a new name for the element' ), ':\\n(',\n _l( 'Note that changing the name here will not rename the dataset' ), ')' ].join( '' ),\n response = prompt( _l( 'Enter a new name for the element' ) + ':', this.element.name );\n if( response ){\n this.element.name = response;\n this.render();\n }\n //TODO: cancelling with ESC leads to closure of the creator...\n },\n\n /** discard when the discard button is clicked */\n _clickDiscard : function( ev ){\n ev.stopPropagation();\n this.discard();\n },\n\n /** dragging pairs for re-ordering */\n _dragstart : function( ev ){\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n ev.dataTransfer.effectAllowed = 'move';\n ev.dataTransfer.setData( 'text/plain', JSON.stringify( this.element ) );\n\n this.$el.addClass( 'dragging' );\n this.$el.parent().trigger( 'collection-element.dragstart', [ this ] );\n },\n\n /** dragging for re-ordering */\n _dragend : function( ev ){\n this.$el.removeClass( 'dragging' );\n this.$el.parent().trigger( 'collection-element.dragend', [ this ] );\n },\n\n /** manually bubble up an event to the parent/container */\n _sendToParent : function( ev ){\n this.$el.parent().trigger( ev );\n },\n\n /** string rep */\n toString : function(){\n return 'DatasetCollectionElementView()';\n }\n});\n\n\n// ============================================================================\n/** An interface for building collections.\n */\nvar ListCollectionCreator = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend( baseCreator.CollectionCreatorMixin ).extend({\n _logNamespace : logNamespace,\n\n /** the class used to display individual elements */\n elementViewClass : DatasetCollectionElementView,\n /** the class this creator will create and save */\n collectionClass : HDCA.HistoryListDatasetCollection,\n className : 'list-collection-creator collection-creator flex-row-container',\n\n /** minimum number of valid elements to start with in order to build a collection of this type */\n minElements : 1,\n\n defaultAttributes : {\n//TODO: remove - use new collectionClass().save()\n /** takes elements and creates the proper collection - returns a promise */\n creationFn : function(){ throw new TypeError( 'no creation fn for creator' ); },\n /** fn to call when the collection is created (scoped to this) */\n oncreate : function(){},\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n oncancel : function(){},\n /** distance from list edge to begin autoscrolling list */\n autoscrollDist : 24,\n /** Color passed to hoverhighlight */\n highlightClr : 'rgba( 64, 255, 255, 1.0 )'\n },\n\n footerSettings : {\n '.hide-originals': 'hideOriginals'\n },\n\n /** set up initial options, instance vars, behaviors */\n initialize : function( attributes ){\n this.metric( 'ListCollectionCreator.initialize', attributes );\n var creator = this;\n _.each( this.defaultAttributes, function( value, key ){\n value = attributes[ key ] || value;\n creator[ key ] = value;\n });\n\n /** unordered, original list - cache to allow reversal */\n creator.initialElements = attributes.elements || [];\n\n this._setUpCommonSettings( attributes );\n this._instanceSetUp();\n this._elementsSetUp();\n this._setUpBehaviors();\n },\n\n /** set up instance vars */\n _instanceSetUp : function(){\n /** Ids of elements that have been selected by the user - to preserve over renders */\n this.selectedIds = {};\n /** DOM elements currently being dragged */\n this.$dragging = null;\n /** Used for blocking UI events during ajax/operations (don't post twice) */\n this.blocking = false;\n },\n\n // ------------------------------------------------------------------------ process raw list\n /** set up main data */\n _elementsSetUp : function(){\n //this.debug( '-- _dataSetUp' );\n /** a list of invalid elements and the reasons they aren't valid */\n this.invalidElements = [];\n//TODO: handle fundamental problem of syncing DOM, views, and list here\n /** data for list in progress */\n this.workingElements = [];\n /** views for workingElements */\n this.elementViews = [];\n\n // copy initial list, sort, add ids if needed\n this.workingElements = this.initialElements.slice( 0 );\n this._ensureElementIds();\n this._validateElements();\n this._mangleDuplicateNames();\n this._sortElements();\n },\n\n /** add ids to dataset objs in initial list if none */\n _ensureElementIds : function(){\n this.workingElements.forEach( function( element ){\n if( !element.hasOwnProperty( 'id' ) ){\n element.id = _.uniqueId();\n }\n });\n return this.workingElements;\n },\n\n /** separate working list into valid and invalid elements for this collection */\n _validateElements : function(){\n var creator = this,\n existingNames = {};\n creator.invalidElements = [];\n\n this.workingElements = this.workingElements.filter( function( element ){\n var problem = creator._isElementInvalid( element );\n if( problem ){\n creator.invalidElements.push({\n element : element,\n text : problem\n });\n }\n return !problem;\n });\n return this.workingElements;\n },\n\n /** describe what is wrong with a particular element if anything */\n _isElementInvalid : function( element ){\n if( element.history_content_type !== 'dataset' ){\n return _l( \"is not a dataset\" );\n }\n var validState = element.state === STATES.OK || _.contains( STATES.NOT_READY_STATES, element.state );\n if( ! validState ){\n return _l( \"has errored, is paused, or is not accessible\" );\n }\n if( element.deleted || element.purged ){\n return _l( \"has been deleted or purged\" );\n }\n return null;\n },\n\n /** mangle duplicate names using a mac-like '(counter)' addition to any duplicates */\n _mangleDuplicateNames : function(){\n var SAFETY = 900,\n counter = 1,\n existingNames = {};\n this.workingElements.forEach( function( element ){\n var currName = element.name;\n while( existingNames.hasOwnProperty( currName ) ){\n currName = element.name + ' (' + counter + ')';\n counter += 1;\n if( counter >= SAFETY ){\n throw new Error( 'Safety hit in while loop - thats impressive' );\n }\n }\n element.name = currName;\n existingNames[ element.name ] = true;\n });\n },\n\n /** sort a list of elements */\n _sortElements : function( list ){\n // // currently only natural sort by name\n // this.workingElements.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n // return this.workingElements;\n },\n\n // ------------------------------------------------------------------------ rendering\n // templates : ListCollectionCreator.templates,\n /** render the entire interface */\n render : function( speed, callback ){\n //this.debug( '-- _render' );\n if( this.workingElements.length < this.minElements ){\n return this._renderInvalid( speed, callback );\n }\n\n this.$el.empty().html( this.templates.main() );\n this._renderHeader( speed );\n this._renderMiddle( speed );\n this._renderFooter( speed );\n this._addPluginComponents();\n this.$( '.collection-name' ).focus();\n this.trigger( 'rendered', this );\n return this;\n },\n\n\n /** render a simplified interface aimed at telling the user why they can't move forward */\n _renderInvalid : function( speed, callback ){\n //this.debug( '-- _render' );\n this.$el.empty().html( this.templates.invalidInitial({\n problems: this.invalidElements,\n elements: this.workingElements,\n }));\n if( typeof this.oncancel === 'function' ){\n this.$( '.cancel-create.btn' ).show();\n }\n this.trigger( 'rendered', this );\n return this;\n },\n\n /** render the header section */\n _renderHeader : function( speed, callback ){\n var $header = this.$( '.header' ).empty().html( this.templates.header() )\n .find( '.help-content' ).prepend( $( this.templates.helpContent() ) );\n //TODO: should only show once despite calling _renderHeader again\n if( this.invalidElements.length ){\n this._invalidElementsAlert();\n }\n return $header;\n },\n\n /** render the middle including the elements */\n _renderMiddle : function( speed, callback ){\n var $middle = this.$( '.middle' ).empty().html( this.templates.middle() );\n this._renderList( speed );\n return $middle;\n },\n\n /** add any jQuery/bootstrap/custom plugins to elements rendered */\n _addPluginComponents : function(){\n this.$( '.help-content i' ).hoverhighlight( '.collection-creator', this.highlightClr );\n },\n\n /** build and show an alert describing any elements that could not be included due to problems */\n _invalidElementsAlert : function(){\n this._showAlert( this.templates.invalidElements({ problems: this.invalidElements }), 'alert-warning' );\n },\n\n _disableNameAndCreate : function( disable ){\n disable = !_.isUndefined( disable )? disable : true;\n if( disable ){\n this.$( '.collection-name' ).prop( 'disabled', true );\n this.$( '.create-collection' ).toggleClass( 'disabled', true );\n // } else {\n // this.$( '.collection-name' ).prop( 'disabled', false );\n // this.$( '.create-collection' ).removeClass( 'disable' );\n }\n },\n\n // ------------------------------------------------------------------------ rendering elements\n /** conv. to the main list display DOM */\n $list : function(){\n return this.$( '.collection-elements' );\n },\n\n /** show or hide the clear selected control based on the num of selected elements */\n _renderClearSelected : function(){\n if( _.size( this.selectedIds ) ){\n this.$( '.collection-elements-controls > .clear-selected' ).show();\n } else {\n this.$( '.collection-elements-controls > .clear-selected' ).hide();\n }\n },\n\n /** render the elements in order (or a warning if no elements found) */\n _renderList : function( speed, callback ){\n //this.debug( '-- _renderList' );\n var creator = this,\n $tmp = jQuery( '
                                            ' ),\n $list = creator.$list();\n\n _.each( this.elementViews, function( view ){\n view.destroy();\n creator.removeElementView( view );\n });\n\n // if( !this.workingElements.length ){\n // this._renderNoValidElements();\n // return;\n // }\n\n creator.workingElements.forEach( function( element ){\n var elementView = creator._createElementView( element );\n $tmp.append( elementView.$el );\n });\n\n creator._renderClearSelected();\n $list.empty().append( $tmp.children() );\n _.invoke( creator.elementViews, 'render' );\n\n if( $list.height() > $list.css( 'max-height' ) ){\n $list.css( 'border-width', '1px 0px 1px 0px' );\n } else {\n $list.css( 'border-width', '0px' );\n }\n },\n\n /** create an element view, cache in elementViews, set up listeners, and return */\n _createElementView : function( element ){\n var elementView = new this.elementViewClass({\n//TODO: use non-generic class or not all\n // model : COLLECTION.DatasetDCE( element )\n element : element,\n selected: _.has( this.selectedIds, element.id )\n });\n this.elementViews.push( elementView );\n this._listenToElementView( elementView );\n return elementView;\n },\n\n /** listen to any element events */\n _listenToElementView : function( view ){\n var creator = this;\n creator.listenTo( view, {\n select : function( data ){\n var element = data.source.element;\n if( data.selected ){\n creator.selectedIds[ element.id ] = true;\n } else {\n delete creator.selectedIds[ element.id ];\n }\n creator.trigger( 'elements:select', data );\n },\n discard : function( data ){\n creator.trigger( 'elements:discard', data );\n }\n });\n },\n\n /** add a new element view based on the json in element */\n addElementView : function( element ){\n//TODO: workingElements is sorted, add element in appropo index\n // add element, sort elements, find element index\n // var view = this._createElementView( element );\n // return view;\n },\n\n /** stop listening to view and remove from caches */\n removeElementView : function( view ){\n delete this.selectedIds[ view.element.id ];\n this._renderClearSelected();\n\n this.elementViews = _.without( this.elementViews, view );\n this.stopListening( view );\n },\n\n /** render a message in the list that no elements remain to create a collection */\n _renderNoElementsLeft : function(){\n this._disableNameAndCreate( true );\n this.$( '.collection-elements' ).append( this.templates.noElementsLeft() );\n },\n\n // /** render a message in the list that no valid elements were found to create a collection */\n // _renderNoValidElements : function(){\n // this._disableNameAndCreate( true );\n // this.$( '.collection-elements' ).append( this.templates.noValidElements() );\n // },\n\n // ------------------------------------------------------------------------ API\n /** convert element into JSON compatible with the collections API */\n _elementToJSON : function( element ){\n // return element.toJSON();\n return element;\n },\n\n /** create the collection via the API\n * @returns {jQuery.xhr Object} the jquery ajax request\n */\n createList : function( name ){\n if( !this.workingElements.length ){\n var message = _l( 'No valid elements for final list' ) + '. ';\n message += '' + _l( 'Cancel' ) + ' ';\n message += _l( 'or' );\n message += ' ' + _l( 'start over' ) + '.';\n this._showAlert( message );\n return;\n }\n\n var creator = this,\n elements = this.workingElements.map( function( element ){\n return creator._elementToJSON( element );\n });\n\n creator.blocking = true;\n return creator.creationFn( elements, name, creator.hideOriginals )\n .always( function(){\n creator.blocking = false;\n })\n .fail( function( xhr, status, message ){\n creator.trigger( 'error', {\n xhr : xhr,\n status : status,\n message : _l( 'An error occurred while creating this collection' )\n });\n })\n .done( function( response, message, xhr ){\n creator.trigger( 'collection:created', response, message, xhr );\n creator.metric( 'collection:created', response );\n if( typeof creator.oncreate === 'function' ){\n creator.oncreate.call( this, response, message, xhr );\n }\n });\n },\n\n // ------------------------------------------------------------------------ events\n /** set up event handlers on self */\n _setUpBehaviors : function(){\n this.on( 'error', this._errorHandler );\n\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this.on( 'elements:select', function( data ){\n this._renderClearSelected();\n });\n\n this.on( 'elements:discard', function( data ){\n var element = data.source.element;\n this.removeElementView( data.source );\n\n this.workingElements = _.without( this.workingElements, element );\n if( !this.workingElements.length ){\n this._renderNoElementsLeft();\n }\n });\n\n //this.on( 'all', function(){\n // this.info( arguments );\n //});\n return this;\n },\n\n /** handle errors with feedback and details to the user (if available) */\n _errorHandler : function( data ){\n this.error( data );\n\n var creator = this;\n content = data.message || _l( 'An error occurred' );\n if( data.xhr ){\n var xhr = data.xhr,\n message = data.message;\n if( xhr.readyState === 0 && xhr.status === 0 ){\n content += ': ' + _l( 'Galaxy could not be reached and may be updating.' ) +\n _l( ' Try again in a few minutes.' );\n } else if( xhr.responseJSON ){\n content += ':
                                            ' + JSON.stringify( xhr.responseJSON ) + '
                                            ';\n } else {\n content += ': ' + message;\n }\n }\n creator._showAlert( content, 'alert-danger' );\n },\n\n events : {\n // header\n 'click .more-help' : '_clickMoreHelp',\n 'click .less-help' : '_clickLessHelp',\n 'click .main-help' : '_toggleHelp',\n 'click .header .alert button' : '_hideAlert',\n\n 'click .reset' : 'reset',\n 'click .clear-selected' : 'clearSelectedElements',\n\n // elements - selection\n 'click .collection-elements' : 'clearSelectedElements',\n\n // elements - drop target\n // 'dragenter .collection-elements': '_dragenterElements',\n // 'dragleave .collection-elements': '_dragleaveElements',\n 'dragover .collection-elements' : '_dragoverElements',\n 'drop .collection-elements' : '_dropElements',\n\n // these bubble up from the elements as custom events\n 'collection-element.dragstart .collection-elements' : '_elementDragstart',\n 'collection-element.dragend .collection-elements' : '_elementDragend',\n\n // footer\n 'change .collection-name' : '_changeName',\n 'keydown .collection-name' : '_nameCheckForEnter',\n 'change .hide-originals' : '_changeHideOriginals',\n 'click .cancel-create' : '_cancelCreate',\n 'click .create-collection' : '_clickCreate'//,\n },\n\n // ........................................................................ elements\n /** reset all data to the initial state */\n reset : function(){\n this._instanceSetUp();\n this._elementsSetUp();\n this.render();\n },\n\n /** deselect all elements */\n clearSelectedElements : function( ev ){\n this.$( '.collection-elements .collection-element' ).removeClass( 'selected' );\n this.$( '.collection-elements-controls > .clear-selected' ).hide();\n },\n\n //_dragenterElements : function( ev ){\n // //this.debug( '_dragenterElements:', ev );\n //},\n//TODO: if selected are dragged out of the list area - remove the placeholder - cuz it won't work anyway\n // _dragleaveElements : function( ev ){\n // //this.debug( '_dragleaveElements:', ev );\n // },\n\n /** track the mouse drag over the list adding a placeholder to show where the drop would occur */\n _dragoverElements : function( ev ){\n //this.debug( '_dragoverElements:', ev );\n ev.preventDefault();\n\n var $list = this.$list();\n this._checkForAutoscroll( $list, ev.originalEvent.clientY );\n var $nearest = this._getNearestElement( ev.originalEvent.clientY );\n\n //TODO: no need to re-create - move instead\n this.$( '.element-drop-placeholder' ).remove();\n var $placeholder = $( '
                                            ' );\n if( !$nearest.length ){\n $list.append( $placeholder );\n } else {\n $nearest.before( $placeholder );\n }\n },\n\n /** If the mouse is near enough to the list's top or bottom, scroll the list */\n _checkForAutoscroll : function( $element, y ){\n var AUTOSCROLL_SPEED = 2,\n offset = $element.offset(),\n scrollTop = $element.scrollTop(),\n upperDist = y - offset.top,\n lowerDist = ( offset.top + $element.outerHeight() ) - y;\n if( upperDist >= 0 && upperDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop - AUTOSCROLL_SPEED );\n } else if( lowerDist >= 0 && lowerDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop + AUTOSCROLL_SPEED );\n }\n },\n\n /** get the nearest element based on the mouse's Y coordinate.\n * If the y is at the end of the list, return an empty jQuery object.\n */\n _getNearestElement : function( y ){\n var WIGGLE = 4,\n lis = this.$( '.collection-elements li.collection-element' ).toArray();\n for( var i=0; i y && top - halfHeight < y ){\n return $li;\n }\n }\n return $();\n },\n\n /** drop (dragged/selected elements) onto the list, re-ordering the internal list */\n _dropElements : function( ev ){\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n // both required for firefox\n ev.preventDefault();\n ev.dataTransfer.dropEffect = 'move';\n\n // insert before the nearest element or after the last.\n var $nearest = this._getNearestElement( ev.clientY );\n if( $nearest.length ){\n this.$dragging.insertBefore( $nearest );\n } else {\n // no nearest before - insert after last element\n this.$dragging.insertAfter( this.$( '.collection-elements .collection-element' ).last() );\n }\n // resync the creator's list based on the new DOM order\n this._syncOrderToDom();\n return false;\n },\n\n /** resync the creator's list of elements based on the DOM order */\n _syncOrderToDom : function(){\n var creator = this,\n newElements = [];\n //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n this.$( '.collection-elements .collection-element' ).each( function(){\n var id = $( this ).attr( 'data-element-id' ),\n element = _.findWhere( creator.workingElements, { id: id });\n if( element ){\n newElements.push( element );\n } else {\n console.error( 'missing element: ', id );\n }\n });\n this.workingElements = newElements;\n this._renderList();\n },\n\n /** drag communication with element sub-views: dragstart */\n _elementDragstart : function( ev, element ){\n // auto select the element causing the event and move all selected\n element.select( true );\n this.$dragging = this.$( '.collection-elements .collection-element.selected' );\n },\n\n /** drag communication with element sub-views: dragend - remove the placeholder */\n _elementDragend : function( ev, element ){\n $( '.element-drop-placeholder' ).remove();\n this.$dragging = null;\n },\n\n // ------------------------------------------------------------------------ templates\n //TODO: move to require text plugin and load these as text\n //TODO: underscore currently unnecc. bc no vars are used\n //TODO: better way of localizing text-nodes in long strings\n /** underscore template fns attached to class */\n templates : _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\n /** the header (not including help text) */\n header : _.template([\n '
                                            ',\n '', _l( 'More help' ), '',\n '
                                            ',\n '', _l( 'Less' ), '',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '',\n '',\n '
                                            ',\n ].join('')),\n\n /** the middle: element list */\n middle : _.template([\n '',\n '
                                            ',\n '
                                            '\n ].join('')),\n\n /** creation and cancel controls */\n footer : _.template([\n '
                                            ',\n '
                                            ',\n '',\n '
                                            ',\n '
                                            ',\n '',\n '
                                            ', _l( 'Name' ), ':
                                            ',\n '
                                            ',\n '
                                            ',\n\n '
                                            ',\n '
                                            ',\n '',\n '
                                            ',\n '',\n '',\n '
                                            ',\n '
                                            ',\n\n '
                                            ',\n '',\n '
                                            ',\n '
                                            '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                                            ', _l([\n 'Collections of datasets are permanent, ordered lists of datasets that can be passed to tools and ',\n 'workflows in order to have analyses done on each member of the entire group. This interface allows ',\n 'you to create a collection and re-order the final collection.'\n ].join( '' )), '

                                            ',\n '
                                              ',\n '
                                            • ', _l([\n 'Rename elements in the list by clicking on ',\n 'the existing name.'\n ].join( '' )), '
                                            • ',\n '
                                            • ', _l([\n 'Discard elements from the final created list by clicking on the ',\n '\"Discard\" button.'\n ].join( '' )), '
                                            • ',\n '
                                            • ', _l([\n 'Reorder the list by clicking and dragging elements. Select multiple elements by clicking on ',\n 'them and you can then move those selected by dragging the ',\n 'entire group. Deselect them by clicking them again or by clicking the ',\n 'the \"Clear selected\" link.'\n ].join( '' )), '
                                            • ',\n '
                                            • ', _l([\n 'Click the \"Start over\" link to begin again as if you had just opened ',\n 'the interface.'\n ].join( '' )), '
                                            • ',\n '
                                            • ', _l([\n 'Click the \"Cancel\" button to exit the interface.'\n ].join( '' )), '
                                            • ',\n '

                                            ',\n '

                                            ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\".'\n ].join( '' )), '

                                            '\n ].join('')),\n\n /** shown in list when all elements are discarded */\n invalidElements : _.template([\n _l( 'The following selections could not be included due to problems:' ),\n '
                                              <% _.each( problems, function( problem ){ %>',\n '
                                            • <%- problem.element.name %>: <%- problem.text %>
                                            • ',\n '<% }); %>
                                            '\n ].join('')),\n\n /** shown in list when all elements are discarded */\n noElementsLeft : _.template([\n '
                                          2. ',\n _l( 'No elements left! ' ),\n _l( 'Would you like to ' ), '', _l( 'start over' ), '?',\n '
                                          3. '\n ].join('')),\n\n /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n invalidInitial : _.template([\n '
                                            ',\n '
                                            ',\n '',\n '<% if( _.size( problems ) ){ %>',\n _l( 'The following selections could not be included due to problems' ), ':',\n '
                                              <% _.each( problems, function( problem ){ %>',\n '
                                            • <%- problem.element.name %>: <%- problem.text %>
                                            • ',\n '<% }); %>
                                            ',\n '<% } else if( _.size( elements ) < 1 ){ %>',\n _l( 'No datasets were selected' ), '.',\n '<% } %>',\n '
                                            ',\n _l( 'At least one element is needed for the collection' ), '. ',\n _l( 'You may need to ' ),\n '', _l( 'cancel' ), ' ',\n _l( 'and reselect new elements' ), '.',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '',\n // _l( 'Create a different kind of collection' ),\n '
                                            ',\n '
                                            ',\n '
                                            '\n ].join('')),\n }),\n\n // ------------------------------------------------------------------------ misc\n /** string rep */\n toString : function(){ return 'ListCollectionCreator'; }\n});\n\n\n\n//=============================================================================\n/** Create a modal and load its body with the given CreatorClass creator type\n * @returns {Deferred} resolved when creator has built a collection.\n */\nvar collectionCreatorModal = function _collectionCreatorModal( elements, options, CreatorClass ){\n\n var deferred = jQuery.Deferred(),\n modal = Galaxy.modal || ( new UI_MODAL.View() ),\n creator;\n\n options = _.defaults( options || {}, {\n elements : elements,\n oncancel : function(){\n modal.hide();\n deferred.reject( 'cancelled' );\n },\n oncreate : function( creator, response ){\n modal.hide();\n deferred.resolve( response );\n }\n });\n\n creator = new CreatorClass( options );\n modal.show({\n title : options.title || _l( 'Create a collection' ),\n body : creator.$el,\n width : '80%',\n height : '100%',\n closing_events: true\n });\n creator.render();\n window._collectionCreator = creator;\n\n //TODO: remove modal header\n return deferred;\n};\n\n/** List collection flavor of collectionCreatorModal. */\nvar listCollectionCreatorModal = function _listCollectionCreatorModal( elements, options ){\n options = options || {};\n options.title = _l( 'Create a collection from a list of datasets' );\n return collectionCreatorModal( elements, options, ListCollectionCreator );\n};\n\n\n//==============================================================================\n/** Use a modal to create a list collection, then add it to the given history contents.\n * @returns {Deferred} resolved when the collection is added to the history.\n */\nfunction createListCollection( contents, defaultHideSourceItems ){\n var elements = contents.toJSON(),\n promise = listCollectionCreatorModal( elements, {\n defaultHideSourceItems: defaultHideSourceItems,\n creationFn : function( elements, name, hideSourceItems ){\n elements = elements.map( function( element ){\n return {\n id : element.id,\n name : element.name,\n //TODO: this allows for list:list even if the filter above does not - reconcile\n src : ( element.history_content_type === 'dataset'? 'hda' : 'hdca' )\n };\n });\n return contents.createHDCA( elements, 'list', name, hideSourceItems );\n }\n });\n return promise;\n}\n\n//==============================================================================\n return {\n DatasetCollectionElementView: DatasetCollectionElementView,\n ListCollectionCreator : ListCollectionCreator,\n\n collectionCreatorModal : collectionCreatorModal,\n listCollectionCreatorModal : listCollectionCreatorModal,\n createListCollection : createListCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/list-collection-creator.js","define([\n \"mvc/list/list-item\",\n \"mvc/dataset/states\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_ITEM, STATES, faIconButton, BASE_MVC, _l ){\n'use strict';\n\nvar logNamespace = 'dataset';\n/*==============================================================================\nTODO:\n straighten out state rendering and templates used\n inaccessible/STATES.NOT_VIEWABLE is a special case\n simplify button rendering\n\n==============================================================================*/\nvar _super = LIST_ITEM.ListItemView;\n/** @class Read only list view for either LDDAs, HDAs, or HDADCEs.\n * Roughly, any DatasetInstance (and not a raw Dataset).\n */\nvar DatasetListItemView = _super.extend(\n/** @lends DatasetListItemView.prototype */{\n _logNamespace : logNamespace,\n\n className : _super.prototype.className + \" dataset\",\n //TODO:?? doesn't exactly match an hda's type_id\n id : function(){\n return [ 'dataset', this.model.get( 'id' ) ].join( '-' );\n },\n\n /** Set up: instance vars, options, and event handlers */\n initialize : function( attributes ){\n if( attributes.logger ){ this.logger = this.model.logger = attributes.logger; }\n this.log( this + '.initialize:', attributes );\n _super.prototype.initialize.call( this, attributes );\n\n /** where should pages from links be displayed? (default to new tab/window) */\n this.linkTarget = attributes.linkTarget || '_blank';\n },\n\n /** event listeners */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n var self = this;\n\n // re-rendering on any model changes\n return self.listenTo( self.model, {\n 'change': function( model ){\n // if the model moved into the ready state and is expanded without details, fetch those details now\n if( self.model.changedAttributes().state &&\n self.model.inReadyState() &&\n self.expanded &&\n !self.model.hasDetails() ){\n // normally, will render automatically (due to fetch -> change),\n // but! setting_metadata sometimes doesn't cause any other changes besides state\n // so, not rendering causes it to seem frozen in setting_metadata state\n self.model.fetch({ silent : true })\n .done( function(){ self.render(); });\n } else {\n if( _.has( model.changed, 'tags' ) && _.keys( model.changed ).length === 1 ){\n // If only the tags have changed, rerender specifically\n // the titlebar region. Otherwise default to the full\n // render.\n self.$( '.nametags' ).html( self._renderNametags() );\n } else {\n self.render();\n }\n }\n }\n });\n },\n\n // ......................................................................... expandable\n /** In this override, only get details if in the ready state, get rerunnable if in other states.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n // ......................................................................... removal\n /** Remove this view's html from the DOM and remove all event listeners.\n * @param {Number or String} speed jq effect speed\n * @param {Function} callback an optional function called when removal is done (scoped to this view)\n */\n remove : function( speed, callback ){\n var view = this;\n speed = speed || this.fxSpeed;\n this.$el.fadeOut( speed, function(){\n Backbone.View.prototype.remove.call( view );\n if( callback ){ callback.call( view ); }\n });\n },\n\n // ......................................................................... rendering\n /* TODO:\n dataset states are the issue primarily making dataset rendering complex\n each state should have it's own way of displaying/set of details\n often with different actions that can be applied\n throw in deleted/purged/visible and things get complicated easily\n I've considered (a couple of times) - creating a view for each state\n - but recreating the view during an update...seems wrong\n */\n /** In this override, add the dataset state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n if( this.model.has( 'state' ) ){\n this.$el.addClass( 'state-' + this.model.get( 'state' ) );\n }\n return this.$el;\n },\n\n // ................................................................................ titlebar\n /** In this override, add the dataset display button. */\n _renderPrimaryActions : function(){\n // render just the display for read-only\n return [ this._renderDisplayButton() ];\n },\n\n /** Render icon-button to display dataset data */\n _renderDisplayButton : function(){\n // don't show display if not viewable or not accessible\n var state = this.model.get( 'state' );\n if( ( state === STATES.NOT_VIEWABLE ) ||\n ( state === STATES.DISCARDED ) ||\n ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var displayBtnData = {\n target : this.linkTarget,\n classes : 'display-btn'\n };\n\n // show a disabled display if the data's been purged\n if( this.model.get( 'purged' ) ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'Cannot display datasets removed from disk' );\n\n // disable if still uploading\n } else if( state === STATES.UPLOAD ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'This dataset must finish uploading before it can be viewed' );\n\n // disable if still new\n } else if( state === STATES.NEW ){\n displayBtnData.disabled = true;\n displayBtnData.title = _l( 'This dataset is not yet viewable' );\n\n } else {\n displayBtnData.title = _l( 'View data' );\n\n // default link for dataset\n displayBtnData.href = this.model.urls.display;\n\n // add frame manager option onclick event\n var self = this;\n displayBtnData.onclick = function( ev ){\n if (Galaxy.frame && Galaxy.frame.active) {\n // Add dataset to frames.\n Galaxy.frame.addDataset(self.model.get('id'));\n ev.preventDefault();\n }\n };\n }\n displayBtnData.faIcon = 'fa-eye';\n return faIconButton( displayBtnData );\n },\n\n // ......................................................................... rendering details\n /** Render the enclosing div of the hda body and, if expanded, the html in the body\n * @returns {jQuery} rendered DOM\n */\n _renderDetails : function(){\n //TODO: generalize to be allow different details for each state\n\n // no access - render nothing but a message\n if( this.model.get( 'state' ) === STATES.NOT_VIEWABLE ){\n return $( this.templates.noAccess( this.model.toJSON(), this ) );\n }\n\n var $details = _super.prototype._renderDetails.call( this );\n $details.find( '.actions .left' ).empty().append( this._renderSecondaryActions() );\n $details.find( '.summary' ).html( this._renderSummary() )\n .prepend( this._renderDetailMessages() );\n $details.find( '.display-applications' ).html( this._renderDisplayApplications() );\n\n this._setUpBehaviors( $details );\n return $details;\n },\n\n /** Defer to the appropo summary rendering fn based on state */\n _renderSummary : function(){\n var json = this.model.toJSON(),\n summaryRenderFn = this.templates.summaries[ json.state ];\n summaryRenderFn = summaryRenderFn || this.templates.summaries.unknown;\n return summaryRenderFn( json, this );\n },\n\n /** Render messages to be displayed only when the details are shown */\n _renderDetailMessages : function(){\n var view = this,\n $warnings = $( '
                                            ' ),\n json = view.model.toJSON();\n //TODO:! unordered (map)\n _.each( view.templates.detailMessages, function( templateFn ){\n $warnings.append( $( templateFn( json, view ) ) );\n });\n return $warnings;\n },\n\n /** Render the external display application links */\n _renderDisplayApplications : function(){\n if( this.model.isDeletedOrPurged() ){ return ''; }\n // render both old and new display apps using the same template\n return [\n this.templates.displayApplications( this.model.get( 'display_apps' ), this ),\n this.templates.displayApplications( this.model.get( 'display_types' ), this )\n ].join( '' );\n },\n\n // ......................................................................... secondary/details actions\n /** A series of links/buttons for less commonly used actions: re-run, info, etc. */\n _renderSecondaryActions : function(){\n this.debug( '_renderSecondaryActions' );\n switch( this.model.get( 'state' ) ){\n case STATES.NOT_VIEWABLE:\n return [];\n case STATES.OK:\n case STATES.FAILED_METADATA:\n case STATES.ERROR:\n return [ this._renderDownloadButton(), this._renderShowParamsButton() ];\n }\n return [ this._renderShowParamsButton() ];\n },\n\n /** Render icon-button to show the input and output (stdout/err) for the job that created this.\n * @returns {jQuery} rendered DOM\n */\n _renderShowParamsButton : function(){\n // gen. safe to show in all cases\n return faIconButton({\n title : _l( 'View details' ),\n classes : 'params-btn',\n href : this.model.urls.show_params,\n target : this.linkTarget,\n faIcon : 'fa-info-circle',\n onclick : function( ev ) {\n if ( Galaxy.frame && Galaxy.frame.active ) {\n Galaxy.frame.add( { title: 'Dataset details', url: this.href } );\n ev.preventDefault();\n ev.stopPropagation();\n }\n }\n });\n },\n\n\n /** Render icon-button/popupmenu to download the data (and/or the associated meta files (bai, etc.)) for this.\n * @returns {jQuery} rendered DOM\n */\n _renderDownloadButton : function(){\n // don't show anything if the data's been purged\n if( this.model.get( 'purged' ) || !this.model.hasData() ){ return null; }\n\n // return either: a popupmenu with links to download assoc. meta files (if there are meta files)\n // or a single download icon-button (if there are no meta files)\n if( !_.isEmpty( this.model.get( 'meta_files' ) ) ){\n return this._renderMetaFileDownloadButton();\n }\n\n return $([\n '',\n '',\n ''\n ].join( '' ));\n },\n\n /** Render the download button which opens a dropdown with links to download assoc. meta files (indeces, etc.) */\n _renderMetaFileDownloadButton : function(){\n var urls = this.model.urls;\n return $([\n '
                                            ',\n '',\n '',\n '',\n '',\n '
                                            '\n ].join( '\\n' ));\n },\n\n _renderNametags : function(){\n var tpl = _.template([\n '<% _.each(_.sortBy(_.uniq(tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>'].join(''));\n return tpl({tags: this.model.get('tags')});\n },\n\n // ......................................................................... misc\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .display-btn' : function( ev ){ this.trigger( 'display', this, ev ); },\n 'click .params-btn' : function( ev ){ this.trigger( 'params', this, ev ); },\n 'click .download-btn' : function( ev ){ this.trigger( 'download', this, ev ); }\n }),\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetListItemView.prototype.templates = (function(){\n//TODO: move to require text! plugin\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n failed_metadata : BASE_MVC.wrapTemplate([\n // failed metadata is rendered as a warning on an otherwise ok dataset view\n '<% if( model.state === \"failed_metadata\" ){ %>',\n '
                                            ',\n _l( 'An error occurred setting the metadata for this dataset' ),\n '
                                            ',\n '<% } %>'\n ]),\n error : BASE_MVC.wrapTemplate([\n // error during index fetch - show error on dataset\n '<% if( model.error ){ %>',\n '
                                            ',\n _l( 'There was an error getting the data for this dataset' ), ': <%- model.error %>',\n '
                                            ',\n '<% } %>'\n ]),\n purged : BASE_MVC.wrapTemplate([\n '<% if( model.purged ){ %>',\n '
                                            ',\n _l( 'This dataset has been deleted and removed from disk' ),\n '
                                            ',\n '<% } %>'\n ]),\n deleted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.deleted && !model.purged ){ %>',\n '
                                            ',\n _l( 'This dataset has been deleted' ),\n '
                                            ',\n '<% } %>'\n ])\n\n //NOTE: hidden warning is only needed for HDAs\n });\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '
                                            ',\n\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n\n // do not display tags, annotation, display apps, or peek when deleted\n '<% if( !dataset.deleted && !dataset.purged ){ %>',\n '
                                            ',\n '
                                            ',\n\n '
                                            ',\n\n '<% if( dataset.peek ){ %>',\n '
                                            <%= dataset.peek %>
                                            ',\n '<% } %>',\n '<% } %>',\n '
                                            '\n ], 'dataset' );\n\n var noAccessTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n '
                                            ',\n _l( 'You do not have permission to view this dataset' ),\n '
                                            ',\n '
                                            '\n ], 'dataset' );\n\n//TODO: still toooooooooooooo complex - rework\n var summaryTemplates = {};\n summaryTemplates[ STATES.OK ] = summaryTemplates[ STATES.FAILED_METADATA ] = BASE_MVC.wrapTemplate([\n '<% if( dataset.misc_blurb ){ %>',\n '
                                            ',\n '<%- dataset.misc_blurb %>',\n '
                                            ',\n '<% } %>',\n\n '<% if( dataset.file_ext ){ %>',\n '
                                            ',\n '',\n '<%- dataset.file_ext %>',\n '
                                            ',\n '<% } %>',\n\n '<% if( dataset.metadata_dbkey ){ %>',\n '
                                            ',\n '',\n '',\n '<%- dataset.metadata_dbkey %>',\n '',\n '
                                            ',\n '<% } %>',\n\n '<% if( dataset.misc_info ){ %>',\n '
                                            ',\n '<%- dataset.misc_info %>',\n '
                                            ',\n '<% } %>'\n ], 'dataset' );\n summaryTemplates[ STATES.NEW ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'This is a new dataset and not all of its data are available yet' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.NOT_VIEWABLE ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'You do not have permission to view this dataset' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.DISCARDED ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'The job creating this dataset was cancelled before completion' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.QUEUED ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'This job is waiting to run' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.RUNNING ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'This job is currently running' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.UPLOAD ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'This dataset is currently uploading' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.SETTING_METADATA ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'Metadata is being auto-detected' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.PAUSED ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'This job is paused. Use the \"Resume Paused Jobs\" in the history menu to resume' ), '
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.ERROR ] = BASE_MVC.wrapTemplate([\n '<% if( !dataset.purged ){ %>',\n '
                                            <%- dataset.misc_blurb %>
                                            ',\n '<% } %>',\n '', _l( 'An error occurred with this dataset' ), ':',\n '
                                            <%- dataset.misc_info %>
                                            '\n ], 'dataset' );\n summaryTemplates[ STATES.EMPTY ] = BASE_MVC.wrapTemplate([\n '
                                            ', _l( 'No data' ), ': <%- dataset.misc_blurb %>
                                            '\n ], 'dataset' );\n summaryTemplates.unknown = BASE_MVC.wrapTemplate([\n '
                                            Error: unknown dataset state: \"<%- dataset.state %>\"
                                            '\n ], 'dataset' );\n\n // messages to be displayed only within the details section ('below the fold')\n var detailMessageTemplates = {\n resubmitted : BASE_MVC.wrapTemplate([\n // deleted not purged\n '<% if( model.resubmitted ){ %>',\n '
                                            ',\n _l( 'The job creating this dataset has been resubmitted' ),\n '
                                            ',\n '<% } %>'\n ])\n };\n\n // this is applied to both old and new style display apps\n var displayApplicationsTemplate = BASE_MVC.wrapTemplate([\n '<% _.each( apps, function( app ){ %>',\n '
                                            ',\n '<%- app.label %> ',\n '',\n '<% _.each( app.links, function( link ){ %>',\n '\" href=\"<%- link.href %>\">',\n '<% print( _l( link.text ) ); %>',\n ' ',\n '<% }); %>',\n '',\n '
                                            ',\n '<% }); %>'\n ], 'apps' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n details : detailsTemplate,\n noAccess : noAccessTemplate,\n summaries : summaryTemplates,\n detailMessages : detailMessageTemplates,\n displayApplications : displayApplicationsTemplate\n });\n}());\n\n\n// ============================================================================\n return {\n DatasetListItemView : DatasetListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-li.js","/** Generic form view */\ndefine( [ 'mvc/form/form-view', 'mvc/ui/ui-misc' ], function( Form, Ui ) {\n\n var View = Backbone.View.extend({\n\n initialize: function( options ) {\n this.model = new Backbone.Model( options );\n this.url = this.model.get( 'url' );\n this.redirect = this.model.get( 'redirect' );\n this.setElement( '
                                            ' );\n this.render();\n },\n\n render: function() {\n var self = this;\n $.ajax({\n url : Galaxy.root + this.url,\n type : 'GET'\n }).done( function( response ) {\n var options = $.extend( {}, self.model.attributes, response );\n var form = new Form({\n title : options.title,\n message: options.message,\n status : options.status || 'warning',\n icon : options.icon,\n inputs : options.inputs,\n buttons: {\n 'submit': new Ui.Button({\n tooltip : options.submit_tooltip,\n title : options.submit_title || 'Save settings',\n icon : options.submit_icon || 'fa-save',\n cls : 'btn btn-primary ui-clear-float',\n onclick : function() { self._submit( form ) }\n })\n }\n });\n self.$el.empty().append( form.$el );\n }).fail( function( response ) {\n self.$el.empty().append( new Ui.Message({\n message : 'Failed to load resource ' + self.url + '.',\n status : 'danger',\n persistent : true\n }).$el );\n });\n },\n\n _submit: function( form ) {\n var self = this;\n $.ajax( {\n url : Galaxy.root + self.url,\n data : JSON.stringify( form.data.create() ),\n type : 'PUT',\n contentType : 'application/json'\n }).done( function( response ) {\n var success_message = { message: response.message, status: 'success', persistent: false };\n if ( self.redirect ) {\n window.location = Galaxy.root + self.redirect + '?' + $.param( success_message );\n } else {\n form.data.matchModel( response, function ( input, input_id ) {\n form.field_list[ input_id ].value( input.value );\n });\n self._showMessage( form, success_message );\n }\n }).fail( function( response ) {\n self._showMessage( form, { message: response.responseJSON.err_msg, status: 'danger', persistent: false } );\n });\n },\n\n _showMessage: function( form, options ) {\n var $panel = form.$el.parents().filter(function() {\n return [ 'auto', 'scroll' ].indexOf( $( this ).css( 'overflow' ) ) != -1;\n }).first();\n $panel.animate( { scrollTop : 0 }, 500 );\n form.message.update( options );\n }\n });\n\n return {\n View : View\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/form/form-wrapper.js","define([\n \"mvc/collection/collection-model\",\n \"mvc/history/history-content-model\",\n \"utils/localization\"\n], function( DC_MODEL, HISTORY_CONTENT, _l ){\n\n'use strict';\n\n/*==============================================================================\n\nModels for DatasetCollections contained within a history.\n\nTODO:\n these might be compactable to one class if some duplication with\n collection-model is used.\n\n==============================================================================*/\nvar hcontentMixin = HISTORY_CONTENT.HistoryContentMixin,\n ListDC = DC_MODEL.ListDatasetCollection,\n PairDC = DC_MODEL.PairDatasetCollection,\n ListPairedDC = DC_MODEL.ListPairedDatasetCollection,\n ListOfListsDC = DC_MODEL.ListOfListsDatasetCollection;\n\n//==============================================================================\n/** Override to post to contents route w/o id. */\nfunction buildHDCASave( _super ){\n return function _save( attributes, options ){\n if( this.isNew() ){\n options = options || {};\n options.url = this.urlRoot + this.get( 'history_id' ) + '/contents';\n attributes = attributes || {};\n attributes.type = 'dataset_collection';\n }\n return _super.call( this, attributes, options );\n };\n}\n\n\n//==============================================================================\n/** @class Backbone model for List Dataset Collection within a History.\n */\nvar HistoryListDatasetCollection = ListDC.extend( hcontentMixin ).extend(\n/** @lends HistoryListDatasetCollection.prototype */{\n\n defaults : _.extend( _.clone( ListDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + ListDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for Pair Dataset Collection within a History.\n * @constructs\n */\nvar HistoryPairDatasetCollection = PairDC.extend( hcontentMixin ).extend(\n/** @lends HistoryPairDatasetCollection.prototype */{\n\n defaults : _.extend( _.clone( PairDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'paired',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( PairDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + PairDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for List of Pairs Dataset Collection within a History. */\nvar HistoryListPairedDatasetCollection = ListPairedDC.extend( hcontentMixin ).extend({\n\n defaults : _.extend( _.clone( ListPairedDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list:paired',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListPairedDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return 'History' + ListPairedDC.prototype.toString.call( this );\n }\n});\n\n\n//==============================================================================\n/** @class Backbone model for List of Lists Dataset Collection within a History. */\nvar HistoryListOfListsDatasetCollection = ListOfListsDC.extend( hcontentMixin ).extend({\n\n defaults : _.extend( _.clone( ListOfListsDC.prototype.defaults ), {\n history_content_type: 'dataset_collection',\n collection_type : 'list:list',\n model_class : 'HistoryDatasetCollectionAssociation'\n }),\n\n /** Override to post to contents route w/o id. */\n save : buildHDCASave( ListOfListsDC.prototype.save ),\n\n /** String representation. */\n toString : function(){\n return ([ 'HistoryListOfListsDatasetCollection(', this.get( 'name' ), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n HistoryListDatasetCollection : HistoryListDatasetCollection,\n HistoryPairDatasetCollection : HistoryPairDatasetCollection,\n HistoryListPairedDatasetCollection : HistoryListPairedDatasetCollection,\n HistoryListOfListsDatasetCollection : HistoryListOfListsDatasetCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-model.js","define([\n \"mvc/base/controlled-fetch-collection\",\n \"mvc/history/hda-model\",\n \"mvc/history/hdca-model\",\n \"mvc/history/history-preferences\",\n \"mvc/base-mvc\",\n \"utils/ajax-queue\"\n], function( CONTROLLED_FETCH_COLLECTION, HDA_MODEL, HDCA_MODEL, HISTORY_PREFS, BASE_MVC, AJAX_QUEUE ){\n'use strict';\n\n//==============================================================================\nvar _super = CONTROLLED_FETCH_COLLECTION.PaginatedCollection;\n/** @class Backbone collection for history content.\n * NOTE: history content seems like a dataset collection, but differs in that it is mixed:\n * each element can be either an HDA (dataset) or a DatasetCollection and co-exist on\n * the same level.\n * Dataset collections on the other hand are not mixed and (so far) can only contain either\n * HDAs or child dataset collections on one level.\n * This is why this does not inherit from any of the DatasetCollections (currently).\n */\nvar HistoryContents = _super.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : 'history',\n\n // ........................................................................ composite collection\n /** since history content is a mix, override model fn into a factory, creating based on history_content_type */\n model : function( attrs, options ) {\n if( attrs.history_content_type === \"dataset\" ) {\n return new HDA_MODEL.HistoryDatasetAssociation( attrs, options );\n\n } else if( attrs.history_content_type === \"dataset_collection\" ) {\n switch( attrs.collection_type ){\n case 'list':\n return new HDCA_MODEL.HistoryListDatasetCollection( attrs, options );\n case 'paired':\n return new HDCA_MODEL.HistoryPairDatasetCollection( attrs, options );\n case 'list:paired':\n return new HDCA_MODEL.HistoryListPairedDatasetCollection( attrs, options );\n case 'list:list':\n return new HDCA_MODEL.HistoryListOfListsDatasetCollection( attrs, options );\n }\n // This is a hack inside a hack:\n // Raise a plain object with validationError to fake a model.validationError\n // (since we don't have a model to use validate with)\n // (the outer hack being the mixed content/model function in this collection)\n var msg = 'Unknown collection_type: ' + attrs.collection_type;\n console.warn( msg, attrs );\n return { validationError : msg };\n }\n return { validationError : 'Unknown history_content_type: ' + attrs.history_content_type };\n },\n\n // ........................................................................ set up\n limitPerPage : 500,\n\n /** @type {Integer} how many contents per call to fetch when using progressivelyFetchDetails */\n limitPerProgressiveFetch : 500,\n\n /** @type {String} order used here and when fetching from server */\n order : 'hid',\n\n /** root api url */\n urlRoot : Galaxy.root + 'api/histories',\n\n /** complete api url */\n url : function(){\n return this.urlRoot + '/' + this.historyId + '/contents';\n },\n\n /** Set up */\n initialize : function( models, options ){\n options = options || {};\n _super.prototype.initialize.call( this, models, options );\n\n this.history = options.history || null;\n this.setHistoryId( options.historyId || null );\n /** @type {Boolean} does this collection contain and fetch deleted elements */\n this.includeDeleted = options.includeDeleted || this.includeDeleted;\n /** @type {Boolean} does this collection contain and fetch non-visible elements */\n this.includeHidden = options.includeHidden || this.includeHidden;\n\n // backbonejs uses collection.model.prototype.idAttribute to determine if a model is *already* in a collection\n // and either merged or replaced. In this case, our 'model' is a function so we need to add idAttribute\n // manually here - if we don't, contents will not merge but be replaced/swapped.\n this.model.prototype.idAttribute = 'type_id';\n },\n\n setHistoryId : function( newId ){\n this.historyId = newId;\n this._setUpWebStorage();\n },\n\n /** Set up client side storage. Currently PersistanStorage keyed under 'history:' */\n _setUpWebStorage : function( initialSettings ){\n // TODO: use initialSettings\n if( !this.historyId ){ return; }\n this.storage = new HISTORY_PREFS.HistoryPrefs({\n id: HISTORY_PREFS.HistoryPrefs.historyStorageKey( this.historyId )\n });\n this.trigger( 'new-storage', this.storage, this );\n\n this.on({\n 'include-deleted' : function( newVal ){\n this.storage.includeDeleted( newVal );\n },\n 'include-hidden' : function( newVal ){\n this.storage.includeHidden( newVal );\n }\n });\n\n this.includeDeleted = this.storage.includeDeleted() || false;\n this.includeHidden = this.storage.includeHidden() || false;\n return this;\n },\n\n // ........................................................................ common queries\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : _.extend( _.clone( _super.prototype.comparators ), {\n 'name' : BASE_MVC.buildComparator( 'name', { ascending: true }),\n 'name-dsc' : BASE_MVC.buildComparator( 'name', { ascending: false }),\n 'hid' : BASE_MVC.buildComparator( 'hid', { ascending: false }),\n 'hid-asc' : BASE_MVC.buildComparator( 'hid', { ascending: true }),\n }),\n\n /** Get every model in this collection not in a 'ready' state (running). */\n running : function(){\n return this.filter( function( c ){ return !c.inReadyState(); });\n },\n\n /** return contents that are not ready and not deleted/hidden */\n runningAndActive : function(){\n return this.filter( function( c ){\n return ( !c.inReadyState() )\n && ( c.get( 'visible' ) )\n // TODO: deletedOrPurged?\n && ( !c.get( 'deleted' ) );\n });\n },\n\n /** Get the model with the given hid\n * @param {Int} hid the hid to search for\n * @returns {HistoryDatasetAssociation} the model with the given hid or undefined if not found\n */\n getByHid : function( hid ){\n // note: there *can* be more than one content with a given hid, this finds the first based on order\n return this.findWhere({ hid: hid });\n },\n\n /** return true if all contents have details */\n haveDetails : function(){\n return this.all( function( c ){ return c.hasDetails(); });\n },\n\n // ........................................................................ hidden / deleted\n /** return a new contents collection of only hidden items */\n hidden : function(){\n return this.filter( function( c ){ return c.hidden(); });\n },\n\n /** return a new contents collection of only hidden items */\n deleted : function(){\n return this.filter( function( c ){ return c.get( 'deleted' ); });\n },\n\n /** return a new contents collection of only hidden items */\n visibleAndUndeleted : function(){\n return this.filter( function( c ){\n return ( c.get( 'visible' ) )\n // TODO: deletedOrPurged?\n && ( !c.get( 'deleted' ) );\n });\n },\n\n /** create a setter in order to publish the change */\n setIncludeDeleted : function( setting, options ){\n if( _.isBoolean( setting ) && setting !== this.includeDeleted ){\n this.includeDeleted = setting;\n if( _.result( options, 'silent' ) ){ return; }\n this.trigger( 'include-deleted', setting, this );\n }\n },\n\n /** create a setter in order to publish the change */\n setIncludeHidden : function( setting, options ){\n if( _.isBoolean( setting ) && setting !== this.includeHidden ){\n this.includeHidden = setting;\n options = options || {};\n if( _.result( options, 'silent' ) ){ return; }\n this.trigger( 'include-hidden', setting, this );\n }\n },\n\n // ........................................................................ ajax\n // ............ controlled fetch collection\n /** override to get expanded ids from sessionStorage and pass to API as details */\n fetch : function( options ){\n options = options || {};\n if( this.historyId && !options.details ){\n var prefs = HISTORY_PREFS.HistoryPrefs.get( this.historyId ).toJSON();\n if( !_.isEmpty( prefs.expandedIds ) ){\n options.details = _.values( prefs.expandedIds ).join( ',' );\n }\n }\n return _super.prototype.fetch.call( this, options );\n },\n\n // ............. ControlledFetch stuff\n /** override to include the API versioning flag */\n _buildFetchData : function( options ){\n return _.extend( _super.prototype._buildFetchData.call( this, options ), {\n v : 'dev'\n });\n },\n\n /** Extend to include details and version */\n _fetchParams : _super.prototype._fetchParams.concat([\n // TODO: remove (the need for) both\n /** version */\n 'v',\n /** dataset ids to get full details of */\n 'details',\n ]),\n\n /** override to add deleted/hidden filters */\n _buildFetchFilters : function( options ){\n var superFilters = _super.prototype._buildFetchFilters.call( this, options ) || {};\n var filters = {};\n if( !this.includeDeleted ){\n filters.deleted = false;\n filters.purged = false;\n }\n if( !this.includeHidden ){\n filters.visible = true;\n }\n return _.defaults( superFilters, filters );\n },\n\n // ............ paginated collection\n getTotalItemCount : function(){\n return this.history.contentsShown();\n },\n\n // ............ history contents specific ajax\n /** override to filter requested contents to those updated after the Date 'since' */\n fetchUpdated : function( since, options ){\n if( since ){\n options = options || { filters: {} };\n options.remove = false;\n options.filters = {\n 'update_time-ge' : since.toISOString(),\n // workflows will produce hidden datasets (non-output datasets) that still\n // need to be updated in the collection or they'll update forever\n // we can remove the default visible filter by using an 'empty' value\n visible : ''\n };\n }\n return this.fetch( options );\n },\n\n /** fetch all the deleted==true contents of this collection */\n fetchDeleted : function( options ){\n options = options || {};\n var self = this;\n options.filters = _.extend( options.filters, {\n // all deleted, purged or not\n deleted : true,\n purged : undefined\n });\n options.remove = false;\n\n self.trigger( 'fetching-deleted', self );\n return self.fetch( options )\n .always( function(){ self.trigger( 'fetching-deleted-done', self ); });\n },\n\n /** fetch all the visible==false contents of this collection */\n fetchHidden : function( options ){\n options = options || {};\n var self = this;\n options.filters = _.extend( options.filters, {\n visible : false\n });\n options.remove = false;\n\n self.trigger( 'fetching-hidden', self );\n return self.fetch( options )\n .always( function(){ self.trigger( 'fetching-hidden-done', self ); });\n },\n\n /** fetch detailed model data for all contents in this collection */\n fetchAllDetails : function( options ){\n options = options || {};\n var detailsFlag = { details: 'all' };\n options.data = _.extend( options.data || {}, detailsFlag );\n return this.fetch( options );\n },\n\n /** specialty fetch method for retrieving the element_counts of all hdcas in the history */\n fetchCollectionCounts : function( options ){\n options = options || {};\n options.keys = [ 'type_id', 'element_count' ].join( ',' );\n options.filters = _.extend( options.filters || {}, {\n history_content_type: 'dataset_collection',\n });\n options.remove = false;\n return this.fetch( options );\n },\n\n // ............. quasi-batch ops\n // TODO: to batch\n /** helper that fetches using filterParams then calls save on each fetched using updateWhat as the save params */\n _filterAndUpdate : function( filterParams, updateWhat ){\n var self = this;\n var idAttribute = self.model.prototype.idAttribute;\n var updateArgs = [ updateWhat ];\n\n return self.fetch({ filters: filterParams, remove: false })\n .then( function( fetched ){\n // convert filtered json array to model array\n fetched = fetched.reduce( function( modelArray, currJson, i ){\n var model = self.get( currJson[ idAttribute ] );\n return model? modelArray.concat( model ) : modelArray;\n }, []);\n return self.ajaxQueue( 'save', updateArgs, fetched );\n });\n },\n\n /** using a queue, perform ajaxFn on each of the models in this collection */\n ajaxQueue : function( ajaxFn, args, collection ){\n collection = collection || this.models;\n return new AJAX_QUEUE.AjaxQueue( collection.slice().reverse().map( function( content, i ){\n var fn = _.isString( ajaxFn )? content[ ajaxFn ] : ajaxFn;\n return function(){ return fn.apply( content, args ); };\n })).deferred;\n },\n\n /** fetch contents' details in batches of limitPerCall - note: only get searchable details here */\n progressivelyFetchDetails : function( options ){\n options = options || {};\n var deferred = jQuery.Deferred();\n var self = this;\n var limit = options.limitPerCall || self.limitPerProgressiveFetch;\n // TODO: only fetch tags and annotations if specifically requested\n var searchAttributes = HDA_MODEL.HistoryDatasetAssociation.prototype.searchAttributes;\n var detailKeys = searchAttributes.join( ',' );\n\n function _recursivelyFetch( offset ){\n offset = offset || 0;\n var _options = _.extend( _.clone( options ), {\n view : 'summary',\n keys : detailKeys,\n limit : limit,\n offset : offset,\n reset : offset === 0,\n remove : false\n });\n\n _.defer( function(){\n self.fetch.call( self, _options )\n .fail( deferred.reject )\n .done( function( response ){\n deferred.notify( response, limit, offset );\n if( response.length !== limit ){\n self.allFetched = true;\n deferred.resolve( response, limit, offset );\n\n } else {\n _recursivelyFetch( offset + limit );\n }\n });\n });\n }\n _recursivelyFetch();\n return deferred;\n },\n\n /** does some bit of JSON represent something that can be copied into this contents collection */\n isCopyable : function( contentsJSON ){\n var copyableModelClasses = [\n 'HistoryDatasetAssociation',\n 'HistoryDatasetCollectionAssociation'\n ];\n return ( ( _.isObject( contentsJSON ) && contentsJSON.id )\n && ( _.contains( copyableModelClasses, contentsJSON.model_class ) ) );\n },\n\n /** copy an existing, accessible hda into this collection */\n copy : function( json ){\n // TODO: somehow showhorn all this into 'save'\n var id, type, contentType;\n if( _.isString( json ) ){\n id = json;\n contentType = 'hda';\n type = 'dataset';\n } else {\n id = json.id;\n contentType = ({\n 'HistoryDatasetAssociation' : 'hda',\n 'LibraryDatasetDatasetAssociation' : 'ldda',\n 'HistoryDatasetCollectionAssociation' : 'hdca'\n })[ json.model_class ] || 'hda';\n type = ( contentType === 'hdca'? 'dataset_collection' : 'dataset' );\n }\n var collection = this,\n xhr = jQuery.ajax( this.url(), {\n method: 'POST',\n contentType: 'application/json',\n data: JSON.stringify({\n content : id,\n source : contentType,\n type : type\n })\n })\n .done( function( response ){\n collection.add([ response ], { parse: true });\n })\n .fail( function( error, status, message ){\n collection.trigger( 'error', collection, xhr, {},\n 'Error copying contents', { type: type, id: id, source: contentType });\n });\n return xhr;\n },\n\n /** create a new HDCA in this collection */\n createHDCA : function( elementIdentifiers, collectionType, name, hideSourceItems, options ){\n // normally collection.create returns the new model, but we need the promise from the ajax, so we fake create\n //precondition: elementIdentifiers is an array of plain js objects\n // in the proper form to create the collectionType\n var hdca = this.model({\n history_content_type: 'dataset_collection',\n collection_type : collectionType,\n history_id : this.historyId,\n name : name,\n hide_source_items : hideSourceItems || false,\n // should probably be able to just send in a bunch of json here and restruct per class\n // note: element_identifiers is now (incorrectly) an attribute\n element_identifiers : elementIdentifiers\n // do not create the model on the client until the ajax returns\n });\n return hdca.save( options );\n },\n\n // ........................................................................ searching\n /** return true if all contents have the searchable attributes */\n haveSearchDetails : function(){\n return this.allFetched && this.all( function( content ){\n // null (which is a valid returned annotation value)\n // will return false when using content.has( 'annotation' )\n //TODO: a bit hacky - formalize\n return _.has( content.attributes, 'annotation' );\n });\n },\n\n /** return a new collection of contents whose attributes contain the substring matchesWhat */\n matches : function( matchesWhat ){\n return this.filter( function( content ){\n return content.matches( matchesWhat );\n });\n },\n\n // ........................................................................ misc\n /** In this override, copy the historyId to the clone */\n clone : function(){\n var clone = Backbone.Collection.prototype.clone.call( this );\n clone.historyId = this.historyId;\n return clone;\n },\n\n /** String representation. */\n toString : function(){\n return ([ 'HistoryContents(', [ this.historyId, this.length ].join(), ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n HistoryContents : HistoryContents\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-contents.js","\ndefine([\n \"mvc/history/history-contents\",\n \"mvc/history/history-preferences\",\n \"mvc/base/controlled-fetch-collection\",\n \"utils/utils\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( HISTORY_CONTENTS, HISTORY_PREFS, CONTROLLED_FETCH_COLLECTION, UTILS, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/** @class Model for a Galaxy history resource - both a record of user\n * tool use and a collection of the datasets those tools produced.\n * @name History\n * @augments Backbone.Model\n */\nvar History = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.mixin( BASE_MVC.SearchableModelMixin, /** @lends History.prototype */{\n _logNamespace : 'history',\n\n /** ms between fetches when checking running jobs/datasets for updates */\n UPDATE_DELAY : 4000,\n\n // values from api (may need more)\n defaults : {\n model_class : 'History',\n id : null,\n name : 'Unnamed History',\n state : 'new',\n\n deleted : false,\n contents_active : {},\n contents_states : {},\n },\n\n urlRoot: Galaxy.root + 'api/histories',\n\n contentsClass : HISTORY_CONTENTS.HistoryContents,\n\n /** What model fields to search with */\n searchAttributes : [\n 'name', 'annotation', 'tags'\n ],\n\n /** Adding title and singular tag */\n searchAliases : {\n title : 'name',\n tag : 'tags'\n },\n\n // ........................................................................ set up/tear down\n /** Set up the model\n * @param {Object} historyJSON model data for this History\n * @param {Object} options any extra settings including logger\n */\n initialize : function( historyJSON, options ){\n options = options || {};\n this.logger = options.logger || null;\n this.log( this + \".initialize:\", historyJSON, options );\n\n /** HistoryContents collection of the HDAs contained in this history. */\n this.contents = new this.contentsClass( [], {\n history : this,\n historyId : this.get( 'id' ),\n order : options.order,\n });\n\n this._setUpListeners();\n this._setUpCollectionListeners();\n\n /** cached timeout id for the dataset updater */\n this.updateTimeoutId = null;\n },\n\n /** set up any event listeners for this history including those to the contained HDAs\n * events: error:contents if an error occurred with the contents collection\n */\n _setUpListeners : function(){\n // if the model's id changes ('current' or null -> an actual id), update the contents history_id\n return this.on({\n 'error' : function( model, xhr, options, msg, details ){\n this.clearUpdateTimeout();\n },\n 'change:id' : function( model, newId ){\n if( this.contents ){\n this.contents.historyId = newId;\n }\n },\n });\n },\n\n /** event handlers for the contents submodels */\n _setUpCollectionListeners : function(){\n if( !this.contents ){ return this; }\n // bubble up errors\n return this.listenTo( this.contents, {\n 'error' : function(){\n this.trigger.apply( this, jQuery.makeArray( arguments ) );\n },\n });\n },\n\n // ........................................................................ derived attributes\n /** */\n contentsShown : function(){\n var contentsActive = this.get( 'contents_active' );\n var shown = contentsActive.active || 0;\n shown += this.contents.includeDeleted? contentsActive.deleted : 0;\n shown += this.contents.includeHidden? contentsActive.hidden : 0;\n return shown;\n },\n\n /** convert size in bytes to a more human readable version */\n nice_size : function(){\n var size = this.get( 'size' );\n return size? UTILS.bytesToString( size, true, 2 ) : _l( '(empty)' );\n },\n\n /** override to add nice_size */\n toJSON : function(){\n return _.extend( Backbone.Model.prototype.toJSON.call( this ), {\n nice_size : this.nice_size()\n });\n },\n\n /** override to allow getting nice_size */\n get : function( key ){\n if( key === 'nice_size' ){\n return this.nice_size();\n }\n return Backbone.Model.prototype.get.apply( this, arguments );\n },\n\n // ........................................................................ common queries\n /** T/F is this history owned by the current user (Galaxy.user)\n * Note: that this will return false for an anon user even if the history is theirs.\n */\n ownedByCurrUser : function(){\n // no currUser\n if( !Galaxy || !Galaxy.user ){\n return false;\n }\n // user is anon or history isn't owned\n if( Galaxy.user.isAnonymous() || Galaxy.user.id !== this.get( 'user_id' ) ){\n return false;\n }\n return true;\n },\n\n /** Return the number of running jobs assoc with this history (note: unknown === 0) */\n numOfUnfinishedJobs : function(){\n var unfinishedJobIds = this.get( 'non_ready_jobs' );\n return unfinishedJobIds? unfinishedJobIds.length : 0;\n },\n\n /** Return the number of running hda/hdcas in this history (note: unknown === 0) */\n numOfUnfinishedShownContents : function(){\n return this.contents.runningAndActive().length || 0;\n },\n\n // ........................................................................ updates\n _fetchContentRelatedAttributes : function(){\n var contentRelatedAttrs = [ 'size', 'non_ready_jobs', 'contents_active', 'hid_counter' ];\n return this.fetch({ data : $.param({ keys : contentRelatedAttrs.join( ',' ) }) });\n },\n\n /** check for any changes since the last time we updated (or fetch all if ) */\n refresh : function( options ){\n // console.log( this + '.refresh' );\n options = options || {};\n var self = this;\n\n // note if there was no previous update time, all summary contents will be fetched\n var lastUpdateTime = self.lastUpdateTime;\n // if we don't flip this, then a fully-fetched list will not be re-checked via fetch\n this.contents.allFetched = false;\n var fetchFn = self.contents.currentPage !== 0\n ? function(){ return self.contents.fetchPage( self.contents.currentPage ); }\n : function(){ return self.contents.fetchUpdated( lastUpdateTime ); };\n // note: if there was no previous update time, all summary contents will be fetched\n return fetchFn()\n .done( function( response, status, xhr ){\n var serverResponseDatetime;\n try {\n serverResponseDatetime = new Date( xhr.getResponseHeader( 'Date' ) );\n } catch( err ){}\n self.lastUpdateTime = serverResponseDatetime || new Date();\n self.checkForUpdates( options );\n });\n },\n\n /** continuously fetch updated contents every UPDATE_DELAY ms if this history's datasets or jobs are unfinished */\n checkForUpdates : function( options ){\n // console.log( this + '.checkForUpdates' );\n options = options || {};\n var delay = this.UPDATE_DELAY;\n var self = this;\n if( !self.id ){ return; }\n\n function _delayThenUpdate(){\n // prevent buildup of updater timeouts by clearing previous if any, then set new and cache id\n self.clearUpdateTimeout();\n self.updateTimeoutId = setTimeout( function(){\n self.refresh( options );\n }, delay );\n }\n\n // if there are still datasets in the non-ready state, recurse into this function with the new time\n var nonReadyContentCount = this.numOfUnfinishedShownContents();\n // console.log( 'nonReadyContentCount:', nonReadyContentCount );\n if( nonReadyContentCount > 0 ){\n _delayThenUpdate();\n\n } else {\n // no datasets are running, but currently runnning jobs may still produce new datasets\n // see if the history has any running jobs and continue to update if so\n // (also update the size for the user in either case)\n self._fetchContentRelatedAttributes()\n .done( function( historyData ){\n // console.log( 'non_ready_jobs:', historyData.non_ready_jobs );\n if( self.numOfUnfinishedJobs() > 0 ){\n _delayThenUpdate();\n\n } else {\n // otherwise, let listeners know that all updates have stopped\n self.trigger( 'ready' );\n }\n });\n }\n },\n\n /** clear the timeout and the cached timeout id */\n clearUpdateTimeout : function(){\n if( this.updateTimeoutId ){\n clearTimeout( this.updateTimeoutId );\n this.updateTimeoutId = null;\n }\n },\n\n // ........................................................................ ajax\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** fetch this histories data (using options) then it's contents (using contentsOptions) */\n fetchWithContents : function( options, contentsOptions ){\n options = options || {};\n var self = this;\n\n // console.log( this + '.fetchWithContents' );\n // TODO: push down to a base class\n options.view = 'dev-detailed';\n\n // fetch history then use history data to fetch (paginated) contents\n return this.fetch( options ).then( function getContents( history ){\n self.contents.history = self;\n self.contents.setHistoryId( history.id );\n return self.fetchContents( contentsOptions );\n });\n },\n\n /** fetch this histories contents, adjusting options based on the stored history preferences */\n fetchContents : function( options ){\n options = options || {};\n var self = this;\n\n // we're updating, reset the update time\n self.lastUpdateTime = new Date();\n return self.contents.fetchCurrentPage( options );\n },\n\n /** save this history, _Mark_ing it as deleted (just a flag) */\n _delete : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** purge this history, _Mark_ing it as purged and removing all dataset data from the server */\n purge : function( options ){\n if( this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: true, purged: true }, options );\n },\n /** save this history, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** Make a copy of this history on the server\n * @param {Boolean} current if true, set the copy as the new current history (default: true)\n * @param {String} name name of new history (default: none - server sets to: Copy of )\n * @fires copied passed this history and the response JSON from the copy\n * @returns {xhr}\n */\n copy : function( current, name, allDatasets ){\n current = ( current !== undefined )?( current ):( true );\n if( !this.id ){\n throw new Error( 'You must set the history ID before copying it.' );\n }\n\n var postData = { history_id : this.id };\n if( current ){\n postData.current = true;\n }\n if( name ){\n postData.name = name;\n }\n if( !allDatasets ){\n postData.all_datasets = false;\n }\n postData.view = 'dev-detailed';\n\n var history = this;\n var copy = jQuery.post( this.urlRoot, postData );\n // if current - queue to setAsCurrent before firing 'copied'\n if( current ){\n return copy.then( function( response ){\n var newHistory = new History( response );\n return newHistory.setAsCurrent()\n .done( function(){\n history.trigger( 'copied', history, response );\n });\n });\n }\n return copy.done( function( response ){\n history.trigger( 'copied', history, response );\n });\n },\n\n setAsCurrent : function(){\n var history = this,\n xhr = jQuery.getJSON( Galaxy.root + 'history/set_as_current?id=' + this.id );\n\n xhr.done( function(){\n history.trigger( 'set-as-current', history );\n });\n return xhr;\n },\n\n // ........................................................................ misc\n toString : function(){\n return 'History(' + this.get( 'id' ) + ',' + this.get( 'name' ) + ')';\n }\n}));\n\n\n//==============================================================================\nvar _collectionSuper = CONTROLLED_FETCH_COLLECTION.InfinitelyScrollingCollection;\n/** @class A collection of histories (per user)\n * that maintains the current history as the first in the collection.\n * New or copied histories become the current history.\n */\nvar HistoryCollection = _collectionSuper.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : 'history',\n\n model : History,\n /** @type {String} initial order used by collection */\n order : 'update_time',\n /** @type {Number} limit used for the first fetch (or a reset) */\n limitOnFirstFetch : 10,\n /** @type {Number} limit used for each subsequent fetch */\n limitPerFetch : 10,\n\n initialize : function( models, options ){\n options = options || {};\n this.log( 'HistoryCollection.initialize', models, options );\n _collectionSuper.prototype.initialize.call( this, models, options );\n\n /** @type {boolean} should deleted histories be included */\n this.includeDeleted = options.includeDeleted || false;\n\n /** @type {String} encoded id of the history that's current */\n this.currentHistoryId = options.currentHistoryId;\n\n this.setUpListeners();\n // note: models are sent to reset *after* this fn ends; up to this point\n // the collection *is empty*\n },\n\n urlRoot : Galaxy.root + 'api/histories',\n url : function(){ return this.urlRoot; },\n\n /** set up reflexive event handlers */\n setUpListeners : function setUpListeners(){\n return this.on({\n // when a history is deleted, remove it from the collection (if optionally set to do so)\n 'change:deleted' : function( history ){\n // TODO: this becomes complicated when more filters are used\n this.debug( 'change:deleted', this.includeDeleted, history.get( 'deleted' ) );\n if( !this.includeDeleted && history.get( 'deleted' ) ){\n this.remove( history );\n }\n },\n // listen for a history copy, setting it to current\n 'copied' : function( original, newData ){\n this.setCurrent( new History( newData, [] ) );\n },\n // when a history is made current, track the id in the collection\n 'set-as-current' : function( history ){\n var oldCurrentId = this.currentHistoryId;\n this.trigger( 'no-longer-current', oldCurrentId );\n this.currentHistoryId = history.id;\n }\n });\n },\n\n /** override to change view */\n _buildFetchData : function( options ){\n return _.extend( _collectionSuper.prototype._buildFetchData.call( this, options ), {\n view : 'dev-detailed'\n });\n },\n\n /** override to filter out deleted and purged */\n _buildFetchFilters : function( options ){\n var superFilters = _collectionSuper.prototype._buildFetchFilters.call( this, options ) || {};\n var filters = {};\n if( !this.includeDeleted ){\n filters.deleted = false;\n filters.purged = false;\n } else {\n // force API to return both deleted and non\n //TODO: when the API is updated, remove this\n filters.deleted = null;\n }\n return _.defaults( superFilters, filters );\n },\n\n /** override to fetch current as well (as it may be outside the first 10, etc.) */\n fetchFirst : function( options ){\n var self = this;\n // TODO: batch?\n var xhr = $.when();\n if( this.currentHistoryId ){\n xhr = _collectionSuper.prototype.fetchFirst.call( self, {\n silent: true,\n limit : 1,\n filters: {\n // without these a deleted current history will return [] here and block the other xhr\n 'purged' : '',\n 'deleted' : '',\n 'encoded_id-in' : this.currentHistoryId,\n }\n });\n }\n return xhr.then( function(){\n options = options || {};\n options.offset = 0;\n return self.fetchMore( options );\n });\n },\n\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : _.extend( _.clone( _collectionSuper.prototype.comparators ), {\n 'name' : BASE_MVC.buildComparator( 'name', { ascending: true }),\n 'name-dsc' : BASE_MVC.buildComparator( 'name', { ascending: false }),\n 'size' : BASE_MVC.buildComparator( 'size', { ascending: false }),\n 'size-asc' : BASE_MVC.buildComparator( 'size', { ascending: true }),\n }),\n\n /** override to always have the current history first */\n sort : function( options ){\n options = options || {};\n var silent = options.silent;\n var currentHistory = this.remove( this.get( this.currentHistoryId ) );\n _collectionSuper.prototype.sort.call( this, _.defaults({ silent: true }, options ) );\n this.unshift( currentHistory, { silent: true });\n if( !silent ){\n this.trigger( 'sort', this, options );\n }\n return this;\n },\n\n /** create a new history and by default set it to be the current history */\n create : function create( data, hdas, historyOptions, xhrOptions ){\n //TODO: .create is actually a collection function that's overridden here\n var collection = this,\n xhr = jQuery.getJSON( Galaxy.root + 'history/create_new_current' );\n return xhr.done( function( newData ){\n collection.setCurrent( new History( newData, [], historyOptions || {} ) );\n });\n },\n\n /** set the current history to the given history, placing it first in the collection.\n * Pass standard bbone options for use in unshift.\n * @triggers new-current passed history and this collection\n */\n setCurrent : function( history, options ){\n options = options || {};\n // new histories go in the front\n this.unshift( history, options );\n this.currentHistoryId = history.get( 'id' );\n if( !options.silent ){\n this.trigger( 'new-current', history, this );\n }\n return this;\n },\n\n toString: function toString(){\n return 'HistoryCollection(' + this.length + ',current:' + this.currentHistoryId + ')';\n }\n});\n\n\n//==============================================================================\nreturn {\n History : History,\n HistoryCollection : HistoryCollection\n};});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-model.js","define([\n \"mvc/base-mvc\"\n], function( BASE_MVC ){\n\n'use strict';\n\nvar logNamespace = 'history';\n\n// ============================================================================\n/** session storage for individual history preferences */\nvar HistoryPrefs = BASE_MVC.SessionStorageModel.extend(\n/** @lends HistoryPrefs.prototype */{\n //TODO:?? move to user prefs?\n defaults : {\n //TODO:?? expandedIds to array?\n expandedIds : {},\n show_deleted : false,\n show_hidden : false\n },\n\n /** add an hda id to the hash of expanded hdas */\n addExpanded : function( model ){\n//TODO: use type_id and not model\n var current = this.get( 'expandedIds' );\n current[ model.id ] = model.get( 'id' );\n this.save( 'expandedIds', current );\n },\n\n /** remove an hda id from the hash of expanded hdas */\n removeExpanded : function( model ){\n var current = this.get( 'expandedIds' );\n delete current[ model.id ];\n this.save( 'expandedIds', current );\n },\n\n isExpanded : function( contentId ){\n return _.result( this.get( 'expandedIds' ), contentId, false );\n },\n\n allExpanded : function(){\n return _.values( this.get( 'expandedIds' ) );\n },\n\n clearExpanded : function(){\n this.set( 'expandedIds', {} );\n },\n\n includeDeleted : function( val ){\n // moving the invocation here so other components don't need to know the key\n // TODO: change this key later\n if( !_.isUndefined( val ) ){ this.set( 'show_deleted', val ); }\n return this.get( 'show_deleted' );\n },\n\n includeHidden : function( val ){\n // TODO: change this key later\n if( !_.isUndefined( val ) ){ this.set( 'show_hidden', val ); }\n return this.get( 'show_hidden' );\n },\n\n toString : function(){\n return 'HistoryPrefs(' + this.id + ')';\n }\n\n}, {\n // ........................................................................ class vars\n // class lvl for access w/o instantiation\n storageKeyPrefix : 'history:',\n\n /** key string to store each histories settings under */\n historyStorageKey : function historyStorageKey( historyId ){\n if( !historyId ){\n throw new Error( 'HistoryPrefs.historyStorageKey needs valid id: ' + historyId );\n }\n // single point of change\n return ( HistoryPrefs.storageKeyPrefix + historyId );\n },\n\n /** return the existing storage for the history with the given id (or create one if it doesn't exist) */\n get : function get( historyId ){\n return new HistoryPrefs({ id: HistoryPrefs.historyStorageKey( historyId ) });\n },\n\n /** clear all history related items in sessionStorage */\n clearAll : function clearAll( historyId ){\n for( var key in sessionStorage ){\n if( key.indexOf( HistoryPrefs.storageKeyPrefix ) === 0 ){\n sessionStorage.removeItem( key );\n }\n }\n }\n});\n\n//==============================================================================\n return {\n HistoryPrefs: HistoryPrefs\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-preferences.js","define([\n 'mvc/base-mvc',\n 'utils/localization'\n], function( BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'list';\n//==============================================================================\n/** A view which, when first rendered, shows only summary data/attributes, but\n * can be expanded to show further details (and optionally fetch those\n * details from the server).\n */\nvar ExpandableView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n //TODO: Although the reasoning behind them is different, this shares a lot with HiddenUntilActivated above: combine them\n //PRECONDITION: model must have method hasDetails\n //PRECONDITION: subclasses must have templates.el and templates.details\n\n initialize : function( attributes ){\n /** are the details of this view expanded/shown or not? */\n this.expanded = attributes.expanded || false;\n this.log( '\\t expanded:', this.expanded );\n this.fxSpeed = attributes.fxSpeed !== undefined? attributes.fxSpeed : this.fxSpeed;\n },\n\n // ........................................................................ render main\n /** jq fx speed */\n fxSpeed : 'fast',\n\n /** Render this content, set up ui.\n * @param {Number or String} speed the speed of the render\n */\n render : function( speed ){\n var $newRender = this._buildNewRender();\n this._setUpBehaviors( $newRender );\n this._queueNewRender( $newRender, speed );\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el.\n * If the view is already expanded, build the details as well.\n */\n _buildNewRender : function(){\n // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n var $newRender = $( this.templates.el( this.model.toJSON(), this ) );\n if( this.expanded ){\n this.$details( $newRender ).replaceWith( this._renderDetails().show() );\n }\n return $newRender;\n },\n\n /** Fade out the old el, swap in the new contents, then fade in.\n * @param {Number or String} speed jq speed to use for rendering effects\n * @fires rendered when rendered\n */\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var view = this;\n\n if( speed === 0 ){\n view._swapNewRender( $newRender );\n view.trigger( 'rendered', view );\n\n } else {\n $( view ).queue( 'fx', [\n function( next ){\n view.$el.fadeOut( speed, next );\n },\n function( next ){\n view._swapNewRender( $newRender );\n next();\n },\n function( next ){\n view.$el.fadeIn( speed, next );\n },\n function( next ){\n view.trigger( 'rendered', view );\n next();\n }\n ]);\n }\n },\n\n /** empty out the current el, move the $newRender's children in */\n _swapNewRender : function( $newRender ){\n return this.$el.empty()\n .attr( 'class', _.isFunction( this.className )? this.className(): this.className )\n .append( $newRender.children() );\n },\n\n /** set up js behaviors, event handlers for elements within the given container\n * @param {jQuery} $container jq object that contains the elements to process (defaults to this.$el)\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n // set up canned behavior on children (bootstrap, popupmenus, editable_text, etc.)\n //make_popup_menus( $where );\n $where.find( '[title]' ).tooltip({ placement : 'bottom' });\n },\n\n // ......................................................................... details\n /** shortcut to details DOM (as jQ) */\n $details : function( $where ){\n $where = $where || this.$el;\n return $where.find( '> .details' );\n },\n\n /** build the DOM for the details and set up behaviors on it */\n _renderDetails : function(){\n var $newDetails = $( this.templates.details( this.model.toJSON(), this ) );\n this._setUpBehaviors( $newDetails );\n return $newDetails;\n },\n\n // ......................................................................... expansion/details\n /** Show or hide the details\n * @param {Boolean} expand if true, expand; if false, collapse\n */\n toggleExpanded : function( expand ){\n expand = ( expand === undefined )?( !this.expanded ):( expand );\n if( expand ){\n this.expand();\n } else {\n this.collapse();\n }\n return this;\n },\n\n /** Render and show the full, detailed body of this view including extra data and controls.\n * note: if the model does not have detailed data, fetch that data before showing the body\n * @fires expanded when a body has been expanded\n */\n expand : function(){\n var view = this;\n return view._fetchModelDetails().always( function(){\n view._expand();\n });\n },\n\n /** Check for model details and, if none, fetch them.\n * @returns {jQuery.promise} the model.fetch.xhr if details are being fetched, an empty promise if not\n */\n _fetchModelDetails : function(){\n if( !this.model.hasDetails() ){\n return this.model.fetch();\n }\n return jQuery.when();\n },\n\n /** Inner fn called when expand (public) has fetched the details */\n _expand : function(){\n var view = this,\n $newDetails = view._renderDetails();\n view.$details().replaceWith( $newDetails );\n // needs to be set after the above or the slide will not show\n view.expanded = true;\n view.$details().slideDown( view.fxSpeed, function(){\n view.trigger( 'expanded', view );\n });\n },\n\n /** Hide the body/details of an HDA.\n * @fires collapsed when a body has been collapsed\n */\n collapse : function(){\n this.debug( this + '(ExpandableView).collapse' );\n var view = this;\n view.expanded = false;\n this.$details().slideUp( view.fxSpeed, function(){\n view.trigger( 'collapsed', view );\n });\n }\n\n});\n\n\n//==============================================================================\n/** A view that is displayed in some larger list/grid/collection.\n * Inherits from Expandable, Selectable, Draggable.\n * The DOM contains warnings, a title bar, and a series of primary action controls.\n * Primary actions are meant to be easily accessible item functions (such as delete)\n * that are rendered in the title bar.\n *\n * Details are rendered when the user clicks the title bar or presses enter/space when\n * the title bar is in focus.\n *\n * Designed as a base class for history panel contents - but usable elsewhere (I hope).\n */\nvar ListItemView = ExpandableView.extend(\n BASE_MVC.mixin( BASE_MVC.SelectableViewMixin, BASE_MVC.DraggableViewMixin, {\n\n tagName : 'div',\n className : 'list-item',\n\n /** Set up the base class and all mixins */\n initialize : function( attributes ){\n ExpandableView.prototype.initialize.call( this, attributes );\n BASE_MVC.SelectableViewMixin.initialize.call( this, attributes );\n BASE_MVC.DraggableViewMixin.initialize.call( this, attributes );\n this._setUpListeners();\n },\n\n /** event listeners */\n _setUpListeners : function(){\n // hide the primary actions in the title bar when selectable and narrow\n this.on( 'selectable', function( isSelectable ){\n if( isSelectable ){\n this.$( '.primary-actions' ).hide();\n } else {\n this.$( '.primary-actions' ).show();\n }\n }, this );\n return this;\n },\n\n // ........................................................................ rendering\n /** In this override, call methods to build warnings, titlebar and primary actions */\n _buildNewRender : function(){\n var $newRender = ExpandableView.prototype._buildNewRender.call( this );\n $newRender.children( '.warnings' ).replaceWith( this._renderWarnings() );\n $newRender.children( '.title-bar' ).replaceWith( this._renderTitleBar() );\n $newRender.children( '.primary-actions' ).append( this._renderPrimaryActions() );\n $newRender.find( '> .title-bar .subtitle' ).replaceWith( this._renderSubtitle() );\n return $newRender;\n },\n\n /** In this override, render the selector controls and set up dragging before the swap */\n _swapNewRender : function( $newRender ){\n ExpandableView.prototype._swapNewRender.call( this, $newRender );\n if( this.selectable ){ this.showSelector( 0 ); }\n if( this.draggable ){ this.draggableOn(); }\n return this.$el;\n },\n\n /** Render any warnings the item may need to show (e.g. \"I'm deleted\") */\n _renderWarnings : function(){\n var view = this,\n $warnings = $( '
                                            ' ),\n json = view.model.toJSON();\n //TODO:! unordered (map)\n _.each( view.templates.warnings, function( templateFn ){\n $warnings.append( $( templateFn( json, view ) ) );\n });\n return $warnings;\n },\n\n /** Render the title bar (the main/exposed SUMMARY dom element) */\n _renderTitleBar : function(){\n return $( this.templates.titleBar( this.model.toJSON(), this ) );\n },\n\n /** Return an array of jQ objects containing common/easily-accessible item controls */\n _renderPrimaryActions : function(){\n // override this\n return [];\n },\n\n /** Render the title bar (the main/exposed SUMMARY dom element) */\n _renderSubtitle : function(){\n return $( this.templates.subtitle( this.model.toJSON(), this ) );\n },\n\n // ......................................................................... events\n /** event map */\n events : {\n // expand the body when the title is clicked or when in focus and space or enter is pressed\n 'click .title-bar' : '_clickTitleBar',\n 'keydown .title-bar' : '_keyDownTitleBar',\n 'click .selector' : 'toggleSelect'\n },\n\n /** expand when the title bar is clicked */\n _clickTitleBar : function( event ){\n event.stopPropagation();\n if( event.altKey ){\n this.toggleSelect( event );\n if( !this.selectable ){\n this.showSelector();\n }\n } else {\n this.toggleExpanded();\n }\n },\n\n /** expand when the title bar is in focus and enter or space is pressed */\n _keyDownTitleBar : function( event ){\n // bail (with propagation) if keydown and not space or enter\n var KEYCODE_SPACE = 32, KEYCODE_RETURN = 13;\n if( event && ( event.type === 'keydown' )\n &&( event.keyCode === KEYCODE_SPACE || event.keyCode === KEYCODE_RETURN ) ){\n this.toggleExpanded();\n event.stopPropagation();\n return false;\n }\n return true;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'ListItemView(' + modelString + ')';\n }\n}));\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nListItemView.prototype.templates = (function(){\n\n var elTemplato = BASE_MVC.wrapTemplate([\n '
                                            ',\n // errors, messages, etc.\n '
                                            ',\n\n // multi-select checkbox\n '
                                            ',\n '',\n '
                                            ',\n // space for title bar buttons - gen. floated to the right\n '
                                            ',\n '
                                            ',\n\n // expandable area for more details\n '
                                            ',\n '
                                            '\n ]);\n\n var warnings = {};\n\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding a tabindex here allows focusing the title bar and the use of keydown to expand the dataset display\n '
                                            ',\n //TODO: prob. belongs in dataset-list-item\n '',\n '
                                            ',\n '<%- element.name %>',\n '
                                            ',\n '
                                            ',\n '
                                            '\n ], 'element' );\n\n var subtitleTemplate = BASE_MVC.wrapTemplate([\n // override this\n '
                                            '\n ]);\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n // override this\n '
                                            '\n ]);\n\n return {\n el : elTemplato,\n warnings : warnings,\n titleBar : titleBarTemplate,\n subtitle : subtitleTemplate,\n details : detailsTemplate\n };\n}());\n\n\n//==============================================================================\n/** A view that is displayed in some larger list/grid/collection.\n * *AND* can display some sub-list of it's own when expanded (e.g. dataset collections).\n * This list will 'foldout' when the item is expanded depending on this.foldoutStyle:\n * If 'foldout': will expand vertically to show the nested list\n * If 'drilldown': will overlay the parent list\n *\n * Inherits from ListItemView.\n *\n * _renderDetails does the work of creating this.details: a sub-view that shows the nested list\n */\nvar FoldoutListItemView = ListItemView.extend({\n\n /** If 'foldout': show the sub-panel inside the expanded item\n * If 'drilldown': only fire events and handle by pub-sub\n * (allow the panel containing this item to attach it, hide itself, etc.)\n */\n foldoutStyle : 'foldout',\n /** Panel view class to instantiate for the sub-panel */\n foldoutPanelClass : null,\n\n /** override to:\n * add attributes foldoutStyle and foldoutPanelClass for config poly\n * disrespect attributes.expanded if drilldown\n */\n initialize : function( attributes ){\n if( this.foldoutStyle === 'drilldown' ){ this.expanded = false; }\n this.foldoutStyle = attributes.foldoutStyle || this.foldoutStyle;\n this.foldoutPanelClass = attributes.foldoutPanelClass || this.foldoutPanelClass;\n\n ListItemView.prototype.initialize.call( this, attributes );\n this.foldout = this._createFoldoutPanel();\n },\n\n /** in this override, attach the foldout panel when rendering details */\n _renderDetails : function(){\n if( this.foldoutStyle === 'drilldown' ){ return $(); }\n var $newDetails = ListItemView.prototype._renderDetails.call( this );\n return this._attachFoldout( this.foldout, $newDetails );\n },\n\n /** In this override, handle collection expansion. */\n _createFoldoutPanel : function(){\n var model = this.model;\n var FoldoutClass = this._getFoldoutPanelClass( model ),\n options = this._getFoldoutPanelOptions( model ),\n foldout = new FoldoutClass( _.extend( options, {\n model : model\n }));\n return foldout;\n },\n\n /** Stub to return proper foldout panel class */\n _getFoldoutPanelClass : function(){\n // override\n return this.foldoutPanelClass;\n },\n\n /** Stub to return proper foldout panel options */\n _getFoldoutPanelOptions : function(){\n return {\n // propagate foldout style down\n foldoutStyle : this.foldoutStyle,\n fxSpeed : this.fxSpeed\n };\n },\n\n /** Render the foldout panel inside the view, hiding controls */\n _attachFoldout : function( foldout, $whereTo ){\n $whereTo = $whereTo || this.$( '> .details' );\n this.foldout = foldout.render( 0 );\n foldout.$( '> .controls' ).hide();\n return $whereTo.append( foldout.$el );\n },\n\n /** In this override, branch on foldoutStyle to show expanded */\n expand : function(){\n var view = this;\n return view._fetchModelDetails()\n .always(function(){\n if( view.foldoutStyle === 'foldout' ){\n view._expand();\n } else if( view.foldoutStyle === 'drilldown' ){\n view._expandByDrilldown();\n }\n });\n },\n\n /** For drilldown, set up close handler and fire expanded:drilldown\n * containing views can listen to this and handle other things\n * (like hiding themselves) by listening for expanded/collapsed:drilldown\n */\n _expandByDrilldown : function(){\n var view = this;\n // attachment and rendering done by listener\n view.listenTo( view.foldout, 'close', function(){\n view.trigger( 'collapsed:drilldown', view, view.foldout );\n });\n view.trigger( 'expanded:drilldown', view, view.foldout );\n }\n\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nFoldoutListItemView.prototype.templates = (function(){\n\n var detailsTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n // override with more info (that goes above the panel)\n '
                                            '\n ], 'collection' );\n\n return _.extend( {}, ListItemView.prototype.templates, {\n details : detailsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n ExpandableView : ExpandableView,\n ListItemView : ListItemView,\n FoldoutListItemView : FoldoutListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/list/list-item.js","define([\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( baseMVC, _l ){\n// =============================================================================\n/** A view on any model that has a 'tags' attribute (a list of tag strings)\n * Incorporates the select2 jQuery plugin for tags display/editing:\n * http://ivaynberg.github.io/select2/\n */\nvar TagsEditor = Backbone.View\n .extend( baseMVC.LoggableMixin )\n .extend( baseMVC.HiddenUntilActivatedViewMixin ).extend({\n\n tagName : 'div',\n className : 'tags-display',\n\n /** Set up listeners, parse options */\n initialize : function( options ){\n //console.debug( this, options );\n // only listen to the model only for changes to tags - re-render\n if (options.usePrompt === false) {\n this.label = '';\n } else {\n this.label = '';\n }\n this.hiddenUntilActivated( options.$activator, options );\n },\n\n /** Build the DOM elements, call select to on the created input, and set up behaviors */\n render : function(){\n var self = this;\n this.$el.html( this._template() );\n\n this.$input().select2({\n placeholder : 'Add tags',\n width : '100%',\n tags : function(){\n // initialize possible tags in the dropdown based on all the tags the user has used so far\n return self._getTagsUsed();\n }\n });\n\n this._setUpBehaviors();\n return this;\n },\n\n _hashToName: function(tag){\n if (tag.startsWith('#')){\n return 'name:' + tag.slice(1);\n }\n return tag;\n },\n\n _nameToHash: function(tag){\n if (tag.startsWith('name:')){\n tag = '#' + tag.slice(5);\n }\n return tag;\n },\n\n /** @returns {String} the html text used to build the view's DOM */\n _template : function(){\n return [\n this.label,\n // set up initial tags by adding as CSV to input vals (necc. to init select2)\n ''\n ].join( '' );\n },\n\n /** @returns {String} the sorted, comma-separated tags from the model */\n tagsToCSV : function(){\n var self = this;\n var tagsArray = this.model.get( 'tags' );\n if( !_.isArray( tagsArray ) || _.isEmpty( tagsArray ) ){\n return '';\n }\n return tagsArray.map( function( tag ){\n return _.escape( self._nameToHash( tag ) );\n }).sort().join( ',' );\n },\n\n /** @returns {jQuery} the input for this view */\n $input : function(){\n return this.$el.find( 'input.tags-input' );\n },\n\n /** @returns {String[]} all tags used by the current user */\n _getTagsUsed : function(){\n//TODO: global\n var self = this;\n return _.map(Galaxy.user.get( 'tags_used' ), self._nameToHash);\n },\n\n /** set up any event listeners on the view's DOM (mostly handled by select2) */\n _setUpBehaviors : function(){\n var self = this;\n this.$input().on( 'change', function( event ){\n // Modify any 'hashtag' 'nametags'\n event.val = _.map(event.val, self._hashToName);\n // save the model's tags in either remove or added event\n self.model.save({ tags: event.val });\n // if it's new, add the tag to the users tags\n if( event.added ){\n //??: solve weird behavior in FF on test.galaxyproject.org where\n // event.added.text is string object: 'String{ 0=\"o\", 1=\"n\", 2=\"e\" }'\n self._addNewTagToTagsUsed( event.added.text + '' );\n }\n });\n },\n\n /** add a new tag (if not already there) to the list of all tags used by the user\n * @param {String} newTag the tag to add to the list of used\n */\n _addNewTagToTagsUsed : function( newTag ){\n//TODO: global\n var tagsUsed = Galaxy.user.get( 'tags_used' );\n if( !_.contains( tagsUsed, newTag ) ){\n tagsUsed.push( newTag );\n tagsUsed.sort();\n Galaxy.user.set( 'tags_used', tagsUsed );\n }\n },\n\n /** shut down event listeners and remove this view's DOM */\n remove : function(){\n this.$input.off();\n this.stopListening( this.model );\n Backbone.View.prototype.remove.call( this );\n },\n\n /** string rep */\n toString : function(){ return [ 'TagsEditor(', this.model + '', ')' ].join(''); }\n});\n\n// =============================================================================\nreturn {\n TagsEditor : TagsEditor\n};\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tag.js","/**\n * Model, view, and controller objects for Galaxy tools and tool panel.\n */\n\n define([\n \"libs/underscore\",\n \"viz/trackster/util\",\n \"mvc/dataset/data\",\n \"mvc/tool/tool-form\"\n\n], function(_, util, data, ToolForm) {\n 'use strict';\n\n/**\n * Mixin for tracking model visibility.\n */\nvar VisibilityMixin = {\n hidden: false,\n\n show: function() {\n this.set(\"hidden\", false);\n },\n\n hide: function() {\n this.set(\"hidden\", true);\n },\n\n toggle: function() {\n this.set(\"hidden\", !this.get(\"hidden\"));\n },\n\n is_visible: function() {\n return !this.attributes.hidden;\n }\n\n};\n\n/**\n * A tool parameter.\n */\nvar ToolParameter = Backbone.Model.extend({\n defaults: {\n name: null,\n label: null,\n type: null,\n value: null,\n html: null,\n num_samples: 5\n },\n\n initialize: function(options) {\n this.attributes.html = unescape(this.attributes.html);\n },\n\n copy: function() {\n return new ToolParameter(this.toJSON());\n },\n\n set_value: function(value) {\n this.set('value', value || '');\n }\n});\n\nvar ToolParameterCollection = Backbone.Collection.extend({\n model: ToolParameter\n});\n\n/**\n * A data tool parameter.\n */\nvar DataToolParameter = ToolParameter.extend({});\n\n/**\n * An integer tool parameter.\n */\nvar IntegerToolParameter = ToolParameter.extend({\n set_value: function(value) {\n this.set('value', parseInt(value, 10));\n },\n\n /**\n * Returns samples from a tool input.\n */\n get_samples: function() {\n return d3.scale.linear()\n .domain([this.get('min'), this.get('max')])\n .ticks(this.get('num_samples'));\n }\n});\n\nvar FloatToolParameter = IntegerToolParameter.extend({\n set_value: function(value) {\n this.set('value', parseFloat(value));\n }\n});\n\n/**\n * A select tool parameter.\n */\nvar SelectToolParameter = ToolParameter.extend({\n /**\n * Returns tool options.\n */\n get_samples: function() {\n return _.map(this.get('options'), function(option) {\n return option[0];\n });\n }\n});\n\n// Set up dictionary of parameter types.\nToolParameter.subModelTypes = {\n 'integer': IntegerToolParameter,\n 'float': FloatToolParameter,\n 'data': DataToolParameter,\n 'select': SelectToolParameter\n};\n\n/**\n * A Galaxy tool.\n */\nvar Tool = Backbone.Model.extend({\n // Default attributes.\n defaults: {\n id: null,\n name: null,\n description: null,\n target: null,\n inputs: [],\n outputs: []\n },\n\n urlRoot: Galaxy.root + 'api/tools',\n\n initialize: function(options) {\n\n // Set parameters.\n this.set('inputs', new ToolParameterCollection(_.map(options.inputs, function(p) {\n var p_class = ToolParameter.subModelTypes[p.type] || ToolParameter;\n return new p_class(p);\n })));\n },\n\n /**\n *\n */\n toJSON: function() {\n var rval = Backbone.Model.prototype.toJSON.call(this);\n\n // Convert inputs to JSON manually.\n rval.inputs = this.get('inputs').map(function(i) { return i.toJSON(); });\n return rval;\n },\n\n /**\n * Removes inputs of a particular type; this is useful because not all inputs can be handled by\n * client and server yet.\n */\n remove_inputs: function(types) {\n var tool = this,\n incompatible_inputs = tool.get('inputs').filter( function(input) {\n return ( types.indexOf( input.get('type') ) !== -1);\n });\n tool.get('inputs').remove(incompatible_inputs);\n },\n\n /**\n * Returns object copy, optionally including only inputs that can be sampled.\n */\n copy: function(only_samplable_inputs) {\n var copy = new Tool(this.toJSON());\n\n // Return only samplable inputs if flag is set.\n if (only_samplable_inputs) {\n var valid_inputs = new Backbone.Collection();\n copy.get('inputs').each(function(input) {\n if (input.get_samples()) {\n valid_inputs.push(input);\n }\n });\n copy.set('inputs', valid_inputs);\n }\n\n return copy;\n },\n\n apply_search_results: function(results) {\n ( _.indexOf(results, this.attributes.id) !== -1 ? this.show() : this.hide() );\n return this.is_visible();\n },\n\n /**\n * Set a tool input's value.\n */\n set_input_value: function(name, value) {\n this.get('inputs').find(function(input) {\n return input.get('name') === name;\n }).set('value', value);\n },\n\n /**\n * Set many input values at once.\n */\n set_input_values: function(inputs_dict) {\n var self = this;\n _.each(_.keys(inputs_dict), function(input_name) {\n self.set_input_value(input_name, inputs_dict[input_name]);\n });\n },\n\n /**\n * Run tool; returns a Deferred that resolves to the tool's output(s).\n */\n run: function() {\n return this._run();\n },\n\n /**\n * Rerun tool using regions and a target dataset.\n */\n rerun: function(target_dataset, regions) {\n return this._run({\n action: 'rerun',\n target_dataset_id: target_dataset.id,\n regions: regions\n });\n },\n\n /**\n * Returns input dict for tool's inputs.\n */\n get_inputs_dict: function() {\n var input_dict = {};\n this.get('inputs').each(function(input) {\n input_dict[input.get('name')] = input.get('value');\n });\n return input_dict;\n },\n\n /**\n * Run tool; returns a Deferred that resolves to the tool's output(s).\n * NOTE: this method is a helper method and should not be called directly.\n */\n _run: function(additional_params) {\n // Create payload.\n var payload = _.extend({\n tool_id: this.id,\n inputs: this.get_inputs_dict()\n }, additional_params);\n\n // Because job may require indexing datasets, use server-side\n // deferred to ensure that job is run. Also use deferred that\n // resolves to outputs from tool.\n var run_deferred = $.Deferred(),\n ss_deferred = new util.ServerStateDeferred({\n ajax_settings: {\n url: this.urlRoot,\n data: JSON.stringify(payload),\n dataType: \"json\",\n contentType: 'application/json',\n type: \"POST\"\n },\n interval: 2000,\n success_fn: function(response) {\n return response !== \"pending\";\n }\n });\n\n // Run job and resolve run_deferred to tool outputs.\n $.when(ss_deferred.go()).then(function(result) {\n run_deferred.resolve(new data.DatasetCollection(result));\n });\n return run_deferred;\n }\n});\n_.extend(Tool.prototype, VisibilityMixin);\n\n/**\n * Tool view.\n */\nvar ToolView = Backbone.View.extend({\n\n});\n\n/**\n * Wrap collection of tools for fast access/manipulation.\n */\nvar ToolCollection = Backbone.Collection.extend({\n model: Tool\n});\n\n/**\n * Label or section header in tool panel.\n */\nvar ToolSectionLabel = Backbone.Model.extend(VisibilityMixin);\n\n/**\n * Section of tool panel with elements (labels and tools).\n */\nvar ToolSection = Backbone.Model.extend({\n defaults: {\n elems: [],\n open: false\n },\n\n clear_search_results: function() {\n _.each(this.attributes.elems, function(elt) {\n elt.show();\n });\n\n this.show();\n this.set(\"open\", false);\n },\n\n apply_search_results: function(results) {\n var all_hidden = true,\n cur_label;\n _.each(this.attributes.elems, function(elt) {\n if (elt instanceof ToolSectionLabel) {\n cur_label = elt;\n cur_label.hide();\n }\n else if (elt instanceof Tool) {\n if (elt.apply_search_results(results)) {\n all_hidden = false;\n if (cur_label) {\n cur_label.show();\n }\n }\n }\n });\n\n if (all_hidden) {\n this.hide();\n }\n else {\n this.show();\n this.set(\"open\", true);\n }\n }\n});\n_.extend(ToolSection.prototype, VisibilityMixin);\n\n/**\n * Tool search that updates results when query is changed. Result value of null\n * indicates that query was not run; if not null, results are from search using\n * query.\n */\nvar ToolSearch = Backbone.Model.extend({\n defaults: {\n search_hint_string: \"search tools\",\n min_chars_for_search: 3,\n clear_btn_url: \"\",\n visible: true,\n query: \"\",\n results: null,\n // ESC (27) will clear the input field and tool search filters\n clear_key: 27\n },\n\n urlRoot: Galaxy.root + 'api/tools',\n\n initialize: function() {\n this.on(\"change:query\", this.do_search);\n },\n\n /**\n * Do the search and update the results.\n */\n do_search: function() {\n var query = this.attributes.query;\n\n // If query is too short, do not search.\n if (query.length < this.attributes.min_chars_for_search) {\n this.set(\"results\", null);\n return;\n }\n\n // Do search via AJAX.\n var q = query;\n // Stop previous ajax-request\n if (this.timer) {\n clearTimeout(this.timer);\n }\n // Start a new ajax-request in X ms\n $(\"#search-clear-btn\").hide();\n $(\"#search-spinner\").show();\n var self = this;\n this.timer = setTimeout(function () {\n // log the search to analytics if present\n if ( typeof ga !== 'undefined' ) {\n ga( 'send', 'pageview', Galaxy.root + '?q=' + q );\n }\n $.get( self.urlRoot, { q: q }, function (data) {\n self.set(\"results\", data);\n $(\"#search-spinner\").hide();\n $(\"#search-clear-btn\").show();\n }, \"json\" );\n }, 400 );\n },\n\n clear_search: function() {\n this.set(\"query\", \"\");\n this.set(\"results\", null);\n }\n\n});\n_.extend(ToolSearch.prototype, VisibilityMixin);\n\n/**\n * Tool Panel.\n */\nvar ToolPanel = Backbone.Model.extend({\n\n initialize: function(options) {\n this.attributes.tool_search = options.tool_search;\n this.attributes.tool_search.on(\"change:results\", this.apply_search_results, this);\n this.attributes.tools = options.tools;\n this.attributes.layout = new Backbone.Collection( this.parse(options.layout) );\n },\n\n /**\n * Parse tool panel dictionary and return collection of tool panel elements.\n */\n parse: function(response) {\n // Recursive function to parse tool panel elements.\n var self = this,\n // Helper to recursively parse tool panel.\n parse_elt = function(elt_dict) {\n var type = elt_dict.model_class;\n // There are many types of tools; for now, anything that ends in 'Tool'\n // is treated as a generic tool.\n if ( type.indexOf('Tool') === type.length - 4 ) {\n return self.attributes.tools.get(elt_dict.id);\n }\n else if (type === 'ToolSection') {\n // Parse elements.\n var elems = _.map(elt_dict.elems, parse_elt);\n elt_dict.elems = elems;\n return new ToolSection(elt_dict);\n }\n else if (type === 'ToolSectionLabel') {\n return new ToolSectionLabel(elt_dict);\n }\n };\n\n return _.map(response, parse_elt);\n },\n\n clear_search_results: function() {\n this.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSection) {\n panel_elt.clear_search_results();\n }\n else {\n // Label or tool, so just show.\n panel_elt.show();\n }\n });\n },\n\n apply_search_results: function() {\n var results = this.get('tool_search').get('results');\n if (results === null) {\n this.clear_search_results();\n return;\n }\n\n var cur_label = null;\n this.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSectionLabel) {\n cur_label = panel_elt;\n cur_label.hide();\n }\n else if (panel_elt instanceof Tool) {\n if (panel_elt.apply_search_results(results)) {\n if (cur_label) {\n cur_label.show();\n }\n }\n }\n else {\n // Starting new section, so clear current label.\n cur_label = null;\n panel_elt.apply_search_results(results);\n }\n });\n }\n});\n\n/**\n * View classes for Galaxy tools and tool panel.\n *\n * Views use the templates defined below for rendering. Views update as needed\n * based on (a) model/collection events and (b) user interactions; in this sense,\n * they are controllers are well and the HTML is the real view in the MVC architecture.\n */\n\n/**\n * Base view that handles visibility based on model's hidden attribute.\n */\nvar BaseView = Backbone.View.extend({\n initialize: function() {\n this.model.on(\"change:hidden\", this.update_visible, this);\n this.update_visible();\n },\n update_visible: function() {\n ( this.model.attributes.hidden ? this.$el.hide() : this.$el.show() );\n }\n});\n\n/**\n * Link to a tool.\n */\nvar ToolLinkView = BaseView.extend({\n tagName: 'div',\n\n render: function() {\n // create element\n var $link = $('
                                            ');\n $link.append(templates.tool_link(this.model.toJSON()));\n\n var formStyle = this.model.get( 'form_style', null );\n // open upload dialog for upload tool\n if (this.model.id === 'upload1') {\n $link.find('a').on('click', function(e) {\n e.preventDefault();\n Galaxy.upload.show();\n });\n }\n else if ( formStyle === 'regular' ) { // regular tools\n var self = this;\n $link.find('a').on('click', function(e) {\n e.preventDefault();\n Galaxy.router.push( '/', { tool_id : self.model.id, version : self.model.get('version') } );\n });\n }\n\n // add element\n this.$el.append($link);\n return this;\n }\n});\n\n/**\n * Panel label/section header.\n */\nvar ToolSectionLabelView = BaseView.extend({\n tagName: 'div',\n className: 'toolPanelLabel',\n\n render: function() {\n this.$el.append( $(\"\").text(this.model.attributes.text) );\n return this;\n }\n});\n\n/**\n * Panel section.\n */\nvar ToolSectionView = BaseView.extend({\n tagName: 'div',\n className: 'toolSectionWrapper',\n\n initialize: function() {\n BaseView.prototype.initialize.call(this);\n this.model.on(\"change:open\", this.update_open, this);\n },\n\n render: function() {\n // Build using template.\n this.$el.append( templates.panel_section(this.model.toJSON()) );\n\n // Add tools to section.\n var section_body = this.$el.find(\".toolSectionBody\");\n _.each(this.model.attributes.elems, function(elt) {\n if (elt instanceof Tool) {\n var tool_view = new ToolLinkView({model: elt, className: \"toolTitle\"});\n tool_view.render();\n section_body.append(tool_view.$el);\n }\n else if (elt instanceof ToolSectionLabel) {\n var label_view = new ToolSectionLabelView({model: elt});\n label_view.render();\n section_body.append(label_view.$el);\n }\n else {\n // TODO: handle nested section bodies?\n }\n });\n return this;\n },\n\n events: {\n 'click .toolSectionTitle > a': 'toggle'\n },\n\n /**\n * Toggle visibility of tool section.\n */\n toggle: function() {\n this.model.set(\"open\", !this.model.attributes.open);\n },\n\n /**\n * Update whether section is open or close.\n */\n update_open: function() {\n (this.model.attributes.open ?\n this.$el.children(\".toolSectionBody\").slideDown(\"fast\") :\n this.$el.children(\".toolSectionBody\").slideUp(\"fast\")\n );\n }\n});\n\nvar ToolSearchView = Backbone.View.extend({\n tagName: 'div',\n id: 'tool-search',\n className: 'bar',\n\n events: {\n 'click': 'focus_and_select',\n 'keyup :input': 'query_changed',\n 'change :input': 'query_changed',\n 'click #search-clear-btn': 'clear'\n },\n\n render: function() {\n this.$el.append( templates.tool_search(this.model.toJSON()) );\n if (!this.model.is_visible()) {\n this.$el.hide();\n }\n\n // Adjust top for issue 2907 depending on whether the messagebox is visible.\n if ($(\"#messagebox\").is(\":visible\")) {\n this.$el.css(\"top\",\"95px\");\n }\n\n this.$el.find('[title]').tooltip();\n return this;\n },\n\n focus_and_select: function() {\n this.$el.find(\":input\").focus().select();\n },\n\n clear: function() {\n this.model.clear_search();\n this.$el.find(\":input\").val('');\n this.focus_and_select();\n return false;\n },\n\n query_changed: function( evData ) {\n // check for the 'clear key' (ESC) first\n if( ( this.model.attributes.clear_key ) &&\n ( this.model.attributes.clear_key === evData.which ) ){\n this.clear();\n return false;\n }\n this.model.set(\"query\", this.$el.find(\":input\").val());\n }\n});\n\n/**\n * Tool panel view. Events triggered include:\n * tool_link_click(click event, tool_model)\n */\nvar ToolPanelView = Backbone.View.extend({\n tagName: 'div',\n className: 'toolMenu',\n\n /**\n * Set up view.\n */\n initialize: function() {\n this.model.get('tool_search').on(\"change:results\", this.handle_search_results, this);\n },\n\n render: function() {\n var self = this;\n\n // Render search.\n var search_view = new ToolSearchView( { model: this.model.get('tool_search') } );\n search_view.render();\n self.$el.append(search_view.$el);\n\n // Render panel.\n this.model.get('layout').each(function(panel_elt) {\n if (panel_elt instanceof ToolSection) {\n var section_title_view = new ToolSectionView({model: panel_elt});\n section_title_view.render();\n self.$el.append(section_title_view.$el);\n }\n else if (panel_elt instanceof Tool) {\n var tool_view = new ToolLinkView({model: panel_elt, className: \"toolTitleNoSection\"});\n tool_view.render();\n self.$el.append(tool_view.$el);\n }\n else if (panel_elt instanceof ToolSectionLabel) {\n var label_view = new ToolSectionLabelView({model: panel_elt});\n label_view.render();\n self.$el.append(label_view.$el);\n }\n });\n\n // Setup tool link click eventing.\n self.$el.find(\"a.tool-link\").click(function(e) {\n // Tool id is always the first class.\n var\n tool_id = $(this).attr('class').split(/\\s+/)[0],\n tool = self.model.get('tools').get(tool_id);\n\n self.trigger(\"tool_link_click\", e, tool);\n });\n\n return this;\n },\n\n handle_search_results: function() {\n var results = this.model.get('tool_search').get('results');\n if (results && results.length === 0) {\n $(\"#search-no-results\").show();\n }\n else {\n $(\"#search-no-results\").hide();\n }\n }\n});\n\n/**\n * View for working with a tool: setting parameters and inputs and executing the tool.\n */\nvar ToolFormView = Backbone.View.extend({\n className: 'toolForm',\n\n render: function() {\n this.$el.children().remove();\n this.$el.append( templates.tool_form(this.model.toJSON()) );\n }\n});\n\n/**\n * Integrated tool menu + tool execution.\n */\nvar IntegratedToolMenuAndView = Backbone.View.extend({\n className: 'toolMenuAndView',\n\n initialize: function() {\n this.tool_panel_view = new ToolPanelView({collection: this.collection});\n this.tool_form_view = new ToolFormView();\n },\n\n render: function() {\n // Render and append tool panel.\n this.tool_panel_view.render();\n this.tool_panel_view.$el.css(\"float\", \"left\");\n this.$el.append(this.tool_panel_view.$el);\n\n // Append tool form view.\n this.tool_form_view.$el.hide();\n this.$el.append(this.tool_form_view.$el);\n\n // On tool link click, show tool.\n var self = this;\n this.tool_panel_view.on(\"tool_link_click\", function(e, tool) {\n // Prevents click from activating link:\n e.preventDefault();\n // Show tool that was clicked on:\n self.show_tool(tool);\n });\n },\n\n /**\n * Fetch and display tool.\n */\n show_tool: function(tool) {\n var self = this;\n tool.fetch().done( function() {\n self.tool_form_view.model = tool;\n self.tool_form_view.render();\n self.tool_form_view.$el.show();\n $('#left').width(\"650px\");\n });\n }\n});\n\n// TODO: move into relevant views\nvar templates = {\n // the search bar at the top of the tool panel\n tool_search : _.template([\n '\" autocomplete=\"off\" type=\"text\" />',\n ' ',\n //TODO: replace with icon\n '',\n ].join('')),\n\n // the category level container in the tool panel (e.g. 'Get Data', 'Text Manipulation')\n panel_section : _.template([\n '
                                            \">',\n '<%- name %>',\n '
                                            ',\n '
                                            \" class=\"toolSectionBody\" style=\"display: none;\">',\n '
                                            ',\n '
                                            '\n ].join('')),\n\n // a single tool's link in the tool panel; will load the tool form in the center panel\n tool_link : _.template([\n '',\n '<% _.each( labels, function( label ){ %>',\n '\">',\n '<%- label %>',\n '',\n '<% }); %>',\n '',\n ' tool-link\" href=\"<%= link %>\" target=\"<%- target %>\" minsizehint=\"<%- min_width %>\">',\n '<%- name %>',\n '',\n ' <%- description %>'\n ].join('')),\n\n // the tool form for entering tool parameters, viewing help and executing the tool\n // loaded when a tool link is clicked in the tool panel\n tool_form : _.template([\n '
                                            <%- tool.name %> (version <%- tool.version %>)
                                            ',\n '
                                            ',\n '<% _.each( tool.inputs, function( input ){ %>',\n '
                                            ',\n '',\n '
                                            ',\n '<%= input.html %>',\n '
                                            ',\n '
                                            ',\n '<%- input.help %>',\n '
                                            ',\n '
                                            ',\n '
                                            ',\n '<% }); %>',\n '
                                            ',\n '
                                            ',\n '',\n '
                                            ',\n '
                                            ',\n '
                                            <% tool.help %>
                                            ',\n '
                                            ',\n // TODO: we need scoping here because 'help' is the dom for the help menu in the masthead\n // which implies a leaky variable that I can't find\n ].join(''), { variable: 'tool' }),\n};\n\n\n// Exports\nreturn {\n ToolParameter: ToolParameter,\n IntegerToolParameter: IntegerToolParameter,\n SelectToolParameter: SelectToolParameter,\n Tool: Tool,\n ToolCollection: ToolCollection,\n ToolSearch: ToolSearch,\n ToolPanel: ToolPanel,\n ToolPanelView: ToolPanelView,\n ToolFormView: ToolFormView\n};\n\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tool/tools.js","/** This renders the content of the ftp popup **/\ndefine( [ 'utils/utils' ], function( Utils ) {\n return Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.options = Utils.merge( options, {\n class_add : 'upload-icon-button fa fa-square-o',\n class_remove : 'upload-icon-button fa fa-check-square-o',\n class_partial : 'upload-icon-button fa fa-minus-square-o',\n collection : null,\n onchange : function() {},\n onadd : function() {},\n onremove : function() {}\n } );\n this.collection = this.options.collection;\n this.setElement( this._template() );\n this.rows = [];\n Utils.get({\n url : Galaxy.root + 'api/remote_files',\n success : function( ftp_files ) { self._fill( ftp_files ) },\n error : function() { self._fill(); }\n });\n },\n\n /** Fill table with ftp entries */\n _fill: function( ftp_files ) {\n if ( ftp_files && ftp_files.length > 0 ) {\n this.$( '.upload-ftp-content' ).html( $( this._templateTable() ) );\n var size = 0;\n for ( index in ftp_files ) {\n this.rows.push( this._add( ftp_files[ index ] ) );\n size += ftp_files[ index ].size;\n }\n this.$( '.upload-ftp-number' ).html( ftp_files.length + ' files' );\n this.$( '.upload-ftp-disk' ).html( Utils.bytesToString ( size, true ) );\n if ( this.collection ) {\n var self = this;\n this.$( '._has_collection' ).show();\n this.$select_all = this.$( '.upload-selectall' ).addClass( this.options.class_add );\n this.$select_all.on( 'click', function() {\n var add = self.$select_all.hasClass( self.options.class_add );\n for ( index in ftp_files ) {\n var ftp_file = ftp_files[ index ];\n var model_index = self._find( ftp_file );\n if( !model_index && add || model_index && !add ) {\n self.rows[ index ].trigger( 'click' );\n }\n }\n });\n this._refresh();\n }\n } else {\n this.$( '.upload-ftp-content' ).html( $( this._templateInfo() ) );\n }\n this.$( '.upload-ftp-wait' ).hide();\n },\n\n /** Add file to table */\n _add: function( ftp_file ) {\n var self = this;\n var $it = $( this._templateRow( ftp_file ) );\n var $icon = $it.find( '.icon' );\n this.$( 'tbody' ).append( $it );\n if ( this.collection ) {\n $icon.addClass( this._find( ftp_file ) ? this.options.class_remove : this.options.class_add );\n $it.on('click', function() {\n var model_index = self._find( ftp_file );\n $icon.removeClass();\n if ( !model_index ) {\n self.options.onadd( ftp_file );\n $icon.addClass( self.options.class_remove );\n } else {\n self.options.onremove( model_index );\n $icon.addClass( self.options.class_add );\n }\n self._refresh();\n });\n } else {\n $it.on('click', function() { self.options.onchange( ftp_file ) } );\n }\n return $it;\n },\n\n /** Refresh select all button state */\n _refresh: function() {\n var filtered = this.collection.where( { file_mode: 'ftp', enabled: true } );\n this.$select_all.removeClass();\n if ( filtered.length == 0 ) {\n this.$select_all.addClass( this.options.class_add );\n } else {\n this.$select_all.addClass( filtered.length == this.rows.length ? this.options.class_remove : this.options.class_partial );\n }\n },\n\n /** Get model index */\n _find: function( ftp_file ) {\n var item = this.collection.findWhere({\n file_path : ftp_file.path,\n file_mode : 'ftp',\n enabled : true\n });\n return item && item.get('id');\n },\n\n /** Template of row */\n _templateRow: function( options ) {\n return '
                                            ' + _.escape(options.path) + '' + Utils.bytesToString( options.size ) + '' + options.ctime + '
                                            ' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '' +\n '
                                            NameSizeCreated
                                            ';\n },\n\n /** Template of info message */\n _templateInfo: function() {\n return '
                                            ' +\n 'Your FTP directory does not contain any files.' +\n '
                                            ';\n },\n\n /** Template of main view */\n _template: function() {\n return '
                                            ' +\n '
                                            ' +\n '
                                            This Galaxy server allows you to upload files via FTP. To upload some files, log in to the FTP server at ' + this.options.ftp_upload_site + ' using your Galaxy credentials (email address and password).
                                            ' +\n '
                                            ' +\n '
                                            ';\n }\n });\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/upload/upload-ftp.js","/** This renders the content of the settings popup, allowing users to specify flags i.e. for space-to-tab conversion **/\ndefine( [ 'utils/utils' ], function( Utils ) {\n return Backbone.View.extend({\n options: {\n class_check : 'fa-check-square-o',\n class_uncheck : 'fa-square-o',\n parameters : [{\n id : 'space_to_tab',\n title : 'Convert spaces to tabs',\n },{\n id : 'to_posix_lines',\n title : 'Use POSIX standard'\n }]\n },\n\n initialize: function( options ) {\n var self = this;\n this.model = options.model;\n this.setElement( $( '
                                            ' ).addClass( 'upload-settings' ) );\n this.$el.append( $( '
                                            ' ).addClass( 'upload-settings-cover' ) );\n this.$el.append( $( '' ).addClass( 'upload-settings-table ui-table-striped' ).append( '' ) );\n this.$cover = this.$( '.upload-settings-cover' );\n this.$table = this.$( '.upload-settings-table > tbody' );\n this.listenTo ( this.model, 'change', this.render, this );\n this.model.trigger( 'change' );\n },\n\n render: function() {\n var self = this;\n this.$table.empty();\n _.each( this.options.parameters, function( parameter ) {\n var $checkbox = $( '
                                            ' ).addClass( 'upload-' + parameter.id + ' upload-icon-button fa' )\n .addClass( self.model.get( parameter.id ) && self.options.class_check || self.options.class_uncheck )\n .on( 'click', function() {\n self.model.get( 'enabled' ) && self.model.set( parameter.id, !self.model.get( parameter.id ) )\n });\n self.$table.append( $( '
                                            ' ).append( $( '' +\n '' +\n '' +\n '' );\n });\n $tmpl.append( $table );\n } else {\n $tmpl.append( 'No ' + this.model.get( 'plural' ).toLowerCase() + ' have been shared with you.' );\n }\n return $tmpl;\n }\n });\n\n return {\n View: View\n }\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/grid/grid-shared.js","define([\n \"mvc/dataset/dataset-li-edit\",\n \"mvc/history/hda-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_LI_EDIT, HDA_LI, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DATASET_LI_EDIT.DatasetListItemEdit;\n/** @class Editing view for HistoryDatasetAssociation.\n */\nvar HDAListItemEdit = _super.extend(\n/** @lends HDAListItemEdit.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n /** In this override, only get details if in the ready state, get rerunnable if in other states.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n\n // special case the need for the rerunnable and creating_job attributes\n // needed for rendering re-run button on queued, running datasets\n } else if( !view.model.has( 'rerunnable' ) ){\n return view.model.fetch({ silent: true, data: {\n // only fetch rerunnable and creating_job to keep overhead down\n keys: [ 'rerunnable', 'creating_job' ].join(',')\n }});\n }\n return jQuery.when();\n },\n\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .unhide-link' : function( ev ){ this.model.unhide(); return false; }\n }),\n\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAListItemEdit(' + modelString + ')';\n }\n});\n\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nHDAListItemEdit.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n '<% if( !dataset.visible ){ %>',\n // add a link to unhide a dataset\n '
                                            ',\n _l( 'This dataset has been hidden' ),\n '
                                            ', _l( 'Unhide it' ), '',\n '
                                            ',\n '<% } %>'\n ], 'dataset' )\n });\n\n return _.extend( {}, _super.prototype.templates, {\n //NOTE: *steal* the HDAListItemView titleBar\n titleBar : HDA_LI.HDAListItemView.prototype.templates.titleBar,\n warnings : warnings\n });\n}());\n\n\n//==============================================================================\n return {\n HDAListItemEdit : HDAListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-li-edit.js","define([\n \"mvc/history/hdca-li\",\n \"mvc/collection/collection-view-edit\",\n \"ui/fa-icon-button\",\n \"utils/localization\"\n], function( HDCA_LI, DC_VIEW_EDIT, faIconButton, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = HDCA_LI.HDCAListItemView;\n/** @class Editing view for HistoryDatasetCollectionAssociation.\n */\nvar HDCAListItemEdit = _super.extend(\n/** @lends HDCAListItemEdit.prototype */{\n\n /** logger used to record this.log messages, commonly set to console */\n //logger : console,\n\n /** Override to return editable versions of the collection panels */\n _getFoldoutPanelClass : function(){\n switch( this.model.get( 'collection_type' ) ){\n case 'list':\n return DC_VIEW_EDIT.ListCollectionViewEdit;\n case 'paired':\n return DC_VIEW_EDIT.PairCollectionViewEdit;\n case 'list:paired':\n return DC_VIEW_EDIT.ListOfPairsCollectionViewEdit;\n case 'list:list':\n return DC_VIEW_EDIT.ListOfListsCollectionViewEdit;\n }\n throw new TypeError( 'Uknown collection_type: ' + this.model.get( 'collection_type' ) );\n },\n\n // ......................................................................... delete\n /** In this override, add the delete button. */\n _renderPrimaryActions : function(){\n this.log( this + '._renderPrimaryActions' );\n // render the display, edit attr and delete icon-buttons\n return _super.prototype._renderPrimaryActions.call( this )\n .concat([\n this._renderDeleteButton()\n ]);\n },\n\n /** Render icon-button to delete this collection. */\n _renderDeleteButton : function(){\n var self = this,\n deleted = this.model.get( 'deleted' );\n return faIconButton({\n title : deleted? _l( 'Dataset collection is already deleted' ): _l( 'Delete' ),\n classes : 'delete-btn',\n faIcon : 'fa-times',\n disabled : deleted,\n onclick : function() {\n // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n self.$el.find( '.icon-btn.delete-btn' ).trigger( 'mouseout' );\n self.model[ 'delete' ]();\n }\n });\n },\n\n // ......................................................................... misc\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDCAListItemEdit(' + modelString + ')';\n }\n});\n\n//==============================================================================\n return {\n HDCAListItemEdit : HDCAListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-li-edit.js","/** This class renders the grid list. */\ndefine( [ 'utils/utils', 'mvc/grid/grid-view', 'mvc/history/history-model', 'mvc/history/copy-dialog' ], function( Utils, GridView, HistoryModel, historyCopyDialog ) {\n\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.setElement( $( '
                                            ' ) );\n this.model = new Backbone.Model();\n Utils.get({\n url : Galaxy.root + 'history/' + options.action_id,\n success : function( response ) {\n response[ 'dict_format' ] = true;\n _.each( response[ 'operations' ], function( operation ) {\n if ( operation.label == 'Copy' ) {\n operation.onclick = function( id ) { self._showCopyDialog( id ) };\n }\n });\n self.model.set( response );\n self.render();\n }\n });\n },\n\n render: function() {\n var grid = new GridView( this.model.attributes );\n this.$el.empty().append( grid.$el );\n },\n\n _showCopyDialog: function( id ) {\n var history = new HistoryModel.History( { id : id } );\n history.fetch()\n .fail( function() {\n alert( 'History could not be fetched. Please contact an administrator' );\n })\n .done( function(){\n historyCopyDialog( history, {} ).done( function() {\n if( window.parent && window.parent.Galaxy && window.parent.Galaxy.currHistoryPanel ) {\n window.parent.Galaxy.currHistoryPanel.loadCurrentHistory();\n }\n window.location.reload( true );\n } );\n });\n }\n });\n\n return {\n View: View\n }\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-list.js","define([\n \"mvc/history/history-model\",\n \"mvc/history/history-view-edit\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( HISTORY_MODEL, HISTORY_VIEW_EDIT, BASE_MVC, _l ){\n\n'use strict';\n\n// ============================================================================\n/** session storage for history panel preferences (and to maintain state)\n */\nvar HistoryViewPrefs = BASE_MVC.SessionStorageModel.extend(\n/** @lends HistoryViewPrefs.prototype */{\n defaults : {\n /** should the tags editor be shown or hidden initially? */\n tagsEditorShown : false,\n /** should the annotation editor be shown or hidden initially? */\n annotationEditorShown : false,\n ///** what is the currently focused content (dataset or collection) in the current history?\n // * (the history panel will highlight and scroll to the focused content view)\n // */\n //focusedContentId : null\n /** Current scroll position */\n scrollPosition : 0\n },\n toString : function(){\n return 'HistoryViewPrefs(' + JSON.stringify( this.toJSON() ) + ')';\n }\n});\n\n/** key string to store panel prefs (made accessible on class so you can access sessionStorage directly) */\nHistoryViewPrefs.storageKey = function storageKey(){\n return ( 'history-panel' );\n};\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\nvar _super = HISTORY_VIEW_EDIT.HistoryViewEdit;\n// used in root/index.mako\n/** @class View/Controller for the user's current history model as used in the history\n * panel (current right hand panel) of the analysis page.\n *\n * The only history panel that:\n * will poll for updates.\n * displays datasets in reverse hid order.\n */\nvar CurrentHistoryView = _super.extend(/** @lends CurrentHistoryView.prototype */{\n\n className : _super.prototype.className + ' current-history-panel',\n\n /** override to use drilldown (and not foldout) for how collections are displayed */\n HDCAViewClass : _super.prototype.HDCAViewClass.extend({\n foldoutStyle : 'drilldown'\n }),\n\n emptyMsg : [\n _l( 'This history is empty' ), '. ',\n _l( 'You can ' ),\n '',\n _l( 'load your own data' ),\n '',\n _l( ' or ' ),\n '',\n _l( 'get data from an external source' ),\n ''\n ].join(''),\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events */\n initialize : function( attributes ){\n attributes = attributes || {};\n\n // ---- persistent preferences\n /** maintain state / preferences over page loads */\n this.preferences = new HistoryViewPrefs( _.extend({\n id : HistoryViewPrefs.storageKey()\n }, _.pick( attributes, _.keys( HistoryViewPrefs.prototype.defaults ) )));\n\n _super.prototype.initialize.call( this, attributes );\n\n /** sub-views that will overlay this panel (collections) */\n this.panelStack = [];\n\n /** id of currently focused content */\n this.currentContentId = attributes.currentContentId || null;\n //NOTE: purposely not sent to localstorage since panel recreation roughly lines up with a reset of this value\n },\n\n /** Override to cache the current scroll position with a listener */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n\n var panel = this;\n // reset scroll position when there's a new history\n this.on( 'new-model', function(){\n panel.preferences.set( 'scrollPosition', 0 );\n });\n },\n\n // ------------------------------------------------------------------------ loading history/item models\n // TODO: next three more appropriate moved to the app level\n /** (re-)loads the user's current history & contents w/ details */\n loadCurrentHistory : function(){\n return this.loadHistory( null, { url : Galaxy.root + 'history/current_history_json' });\n },\n\n /** loads a history & contents w/ details and makes them the current history */\n switchToHistory : function( historyId, attributes ){\n if( Galaxy.user.isAnonymous() ){\n this.trigger( 'error', _l( 'You must be logged in to switch histories' ), _l( 'Anonymous user' ) );\n return $.when();\n }\n return this.loadHistory( historyId, { url : Galaxy.root + 'history/set_as_current?id=' + historyId });\n },\n\n /** creates a new history on the server and sets it as the user's current history */\n createNewHistory : function( attributes ){\n if( Galaxy.user.isAnonymous() ){\n this.trigger( 'error', _l( 'You must be logged in to create histories' ), _l( 'Anonymous user' ) );\n return $.when();\n }\n return this.loadHistory( null, { url : Galaxy.root + 'history/create_new_current' });\n },\n\n /** release/free/shutdown old models and set up panel for new models */\n setModel : function( model, attributes, render ){\n _super.prototype.setModel.call( this, model, attributes, render );\n if( this.model && this.model.id ){\n this.log( 'checking for updates' );\n this.model.checkForUpdates();\n }\n return this;\n },\n\n // ------------------------------------------------------------------------ history/content event listening\n /** listening for history events */\n _setUpModelListeners : function(){\n _super.prototype._setUpModelListeners.call( this );\n // re-broadcast any model change events so that listeners don't have to re-bind to each history\n return this.listenTo( this.model, {\n 'change:nice_size change:size' : function(){\n this.trigger( 'history-size-change', this, this.model, arguments );\n },\n 'change:id' : function(){\n this.once( 'loading-done', function(){ this.model.checkForUpdates(); });\n }\n });\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n // if a hidden item is created (gen. by a workflow), moves thru the updater to the ready state,\n // then: remove it from the collection if the panel is set to NOT show hidden datasets\n this.listenTo( this.collection, 'state:ready', function( model, newState, oldState ){\n if( ( !model.get( 'visible' ) )\n && ( !this.collection.storage.includeHidden() ) ){\n this.removeItemView( model );\n }\n });\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** override to add a handler to capture the scroll position when the parent scrolls */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n // console.log( '_setUpBehaviors', this.$scrollContainer( $where ).get(0), this.$list( $where ) );\n // we need to call this in _setUpBehaviors which is called after render since the $el\n // may not be attached to $el.parent and $scrollContainer() may not work\n var panel = this;\n _super.prototype._setUpBehaviors.call( panel, $where );\n\n // cache the handler to remove and re-add so we don't pile up the handlers\n if( !this._debouncedScrollCaptureHandler ){\n this._debouncedScrollCaptureHandler = _.debounce( function scrollCapture(){\n // cache the scroll position (only if visible)\n if( panel.$el.is( ':visible' ) ){\n panel.preferences.set( 'scrollPosition', $( this ).scrollTop() );\n }\n }, 40 );\n }\n\n panel.$scrollContainer( $where )\n .off( 'scroll', this._debouncedScrollCaptureHandler )\n .on( 'scroll', this._debouncedScrollCaptureHandler );\n return panel;\n },\n\n /** In this override, handle null models and move the search input to the top */\n _buildNewRender : function(){\n if( !this.model ){ return $(); }\n var $newRender = _super.prototype._buildNewRender.call( this );\n $newRender.find( '.search' ).prependTo( $newRender.find( '> .controls' ) );\n this._renderQuotaMessage( $newRender );\n return $newRender;\n },\n\n /** render the message displayed when a user is over quota and can't run jobs */\n _renderQuotaMessage : function( $whereTo ){\n $whereTo = $whereTo || this.$el;\n return $( this.templates.quotaMsg( {}, this ) ).prependTo( $whereTo.find( '.messages' ) );\n },\n\n /** In this override, get and set current panel preferences when editor is used */\n _renderTags : function( $where ){\n var panel = this;\n // render tags and show/hide based on preferences\n _super.prototype._renderTags.call( panel, $where );\n if( panel.preferences.get( 'tagsEditorShown' ) ){\n panel.tagsEditor.toggle( true );\n }\n // store preference when shown or hidden\n panel.listenTo( panel.tagsEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden',\n function( tagsEditor ){\n panel.preferences.set( 'tagsEditorShown', tagsEditor.hidden );\n }\n );\n },\n\n /** In this override, get and set current panel preferences when editor is used */\n _renderAnnotation : function( $where ){\n var panel = this;\n // render annotation and show/hide based on preferences\n _super.prototype._renderAnnotation.call( panel, $where );\n if( panel.preferences.get( 'annotationEditorShown' ) ){\n panel.annotationEditor.toggle( true );\n }\n // store preference when shown or hidden\n panel.listenTo( panel.annotationEditor, 'hiddenUntilActivated:shown hiddenUntilActivated:hidden',\n function( annotationEditor ){\n panel.preferences.set( 'annotationEditorShown', annotationEditor.hidden );\n }\n );\n },\n\n /** Override to scroll to cached position (in prefs) after swapping */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n var panel = this;\n _.delay( function(){\n var pos = panel.preferences.get( 'scrollPosition' );\n if( pos ){\n panel.scrollTo( pos, 0 );\n }\n }, 10 );\n //TODO: is this enough of a delay on larger histories?\n\n return this;\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** Override to add the current-content highlight class to currentContentId's view */\n _attachItems : function( $whereTo ){\n _super.prototype._attachItems.call( this, $whereTo );\n var panel = this;\n if( panel.currentContentId ){\n panel._setCurrentContentById( panel.currentContentId );\n }\n return this;\n },\n\n /** Override to remove any drill down panels */\n addItemView : function( model, collection, options ){\n var view = _super.prototype.addItemView.call( this, model, collection, options );\n if( !view ){ return view; }\n if( this.panelStack.length ){ return this._collapseDrilldownPanel(); }\n return view;\n },\n\n // ------------------------------------------------------------------------ collection sub-views\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n // use pub-sub to: handle drilldown expansion and collapse\n return panel.listenTo( view, {\n 'expanded:drilldown' : function( v, drilldown ){\n this._expandDrilldownPanel( drilldown );\n },\n 'collapsed:drilldown' : function( v, drilldown ){\n this._collapseDrilldownPanel( drilldown );\n },\n });\n },\n\n /** display 'current content': add a visible highlight and store the id of a content item */\n setCurrentContent : function( view ){\n this.$( '.history-content.current-content' ).removeClass( 'current-content' );\n if( view ){\n view.$el.addClass( 'current-content' );\n this.currentContentId = view.model.id;\n } else {\n this.currentContentId = null;\n }\n },\n\n /** find the view with the id and then call setCurrentContent on it */\n _setCurrentContentById : function( id ){\n var view = this.viewFromModelId( id ) || null;\n this.setCurrentContent( view );\n },\n\n /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n _expandDrilldownPanel : function( drilldown ){\n this.panelStack.push( drilldown );\n // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n this.$controls().add( this.$list() ).hide();\n drilldown.parentName = this.model.get( 'name' );\n drilldown.delegateEvents().render().$el.appendTo( this.$el );\n },\n\n /** Handle drilldown close by freeing the panel and re-rendering this panel */\n _collapseDrilldownPanel : function( drilldown ){\n this.panelStack.pop();\n //TODO: MEM: free the panel\n this.$controls().add( this.$list() ).show();\n },\n\n // ........................................................................ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n // the two links in the empty message\n 'click .uploader-link' : function( ev ){ Galaxy.upload.show( ev ); },\n 'click .get-data-link' : function( ev ){\n var $toolMenu = $( '.toolMenuContainer' );\n $toolMenu.parent().scrollTop( 0 );\n $toolMenu.find( 'span:contains(\"Get Data\")' ).click();\n }\n }),\n\n // ........................................................................ external objects/MVC\n listenToGalaxy : function( galaxy ){\n this.listenTo( galaxy, {\n // when the galaxy_main iframe is loaded with a new page,\n // compare the url to the following list and if there's a match\n // pull the id from url and indicate in the history view that\n // the dataset with that id is the 'current'ly active dataset\n 'center-frame:load': function( data ){\n var pathToMatch = data.fullpath;\n var hdaId = null;\n var useToURLRegexMap = {\n 'display' : /datasets\\/([a-f0-9]+)\\/display/,\n 'edit' : /datasets\\/([a-f0-9]+)\\/edit/,\n 'report_error' : /dataset\\/errors\\?id=([a-f0-9]+)/,\n 'rerun' : /tool_runner\\/rerun\\?id=([a-f0-9]+)/,\n 'show_params' : /datasets\\/([a-f0-9]+)\\/show_params/,\n // no great way to do this here? (leave it in the dataset event handlers above?)\n // 'visualization' : 'visualization',\n };\n _.find( useToURLRegexMap, function( regex, use ){\n // grab the more specific match result (1), save, and use it as the find flag\n hdaId = _.result( pathToMatch.match( regex ), 1 );\n return hdaId;\n });\n // need to type mangle to go from web route to history contents\n this._setCurrentContentById( hdaId? ( 'dataset-' + hdaId ) : null );\n },\n // when the center panel is given a new view, clear the current indicator\n 'center-panel:load': function( view ){\n this._setCurrentContentById();\n }\n });\n },\n\n //TODO: remove quota meter from panel and remove this\n /** add listeners to an external quota meter (mvc/user/user-quotameter.js) */\n connectToQuotaMeter : function( quotaMeter ){\n if( !quotaMeter ){\n return this;\n }\n // show/hide the 'over quota message' in the history when the meter tells it to\n this.listenTo( quotaMeter, 'quota:over', this.showQuotaMessage );\n this.listenTo( quotaMeter, 'quota:under', this.hideQuotaMessage );\n\n // having to add this to handle re-render of hview while overquota (the above do not fire)\n this.on( 'rendered rendered:initial', function(){\n if( quotaMeter && quotaMeter.isOverQuota() ){\n this.showQuotaMessage();\n }\n });\n return this;\n },\n\n /** Override to preserve the quota message */\n clearMessages : function( ev ){\n var $target = !_.isUndefined( ev )?\n $( ev.currentTarget )\n :this.$messages().children( '[class$=\"message\"]' );\n $target = $target.not( '.quota-message' );\n $target.fadeOut( this.fxSpeed, function(){\n $( this ).remove();\n });\n return this;\n },\n\n /** Show the over quota message (which happens to be in the history panel).\n */\n showQuotaMessage : function(){\n var $msg = this.$( '.quota-message' );\n if( $msg.is( ':hidden' ) ){ $msg.slideDown( this.fxSpeed ); }\n },\n\n /** Hide the over quota message (which happens to be in the history panel).\n */\n hideQuotaMessage : function(){\n var $msg = this.$( '.quota-message' );\n if( !$msg.is( ':hidden' ) ){ $msg.slideUp( this.fxSpeed ); }\n },\n\n // ........................................................................ options menu\n //TODO: remove to batch\n /** unhide any hidden datasets */\n unhideHidden : function() {\n var self = this;\n if( confirm( _l( 'Really unhide all hidden datasets?' ) ) ){\n // get all hidden, regardless of deleted/purged\n return self.model.contents._filterAndUpdate(\n { visible: false, deleted: '', purged: '' },\n { visible : true }\n ).done( function(){\n // TODO: would be better to render these as they're unhidden instead of all at once\n if( !self.model.contents.includeHidden ){\n self.renderItems();\n }\n });\n }\n return jQuery.when();\n },\n\n /** delete any hidden datasets */\n deleteHidden : function() {\n var self = this;\n if( confirm( _l( 'Really delete all hidden datasets?' ) ) ){\n return self.model.contents._filterAndUpdate(\n // get all hidden, regardless of deleted/purged\n { visible: false, deleted: '', purged: '' },\n // both delete *and* unhide them\n { deleted : true, visible: true }\n );\n }\n return jQuery.when();\n },\n\n /** Return a string rep of the history */\n toString : function(){\n return 'CurrentHistoryView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nCurrentHistoryView.prototype.templates = (function(){\n\n var quotaMsgTemplate = BASE_MVC.wrapTemplate([\n '
                                            ',\n _l( 'You are over your disk quota' ), '. ',\n _l( 'Tool execution is on hold until your disk usage drops below your allocated quota' ), '.',\n '
                                            '\n ], 'history' );\n return _.extend( _.clone( _super.prototype.templates ), {\n quotaMsg : quotaMsgTemplate\n });\n\n}());\n\n\n//==============================================================================\n return {\n CurrentHistoryView : CurrentHistoryView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view-edit-current.js","define([\n \"mvc/history/history-view\",\n \"mvc/history/history-contents\",\n \"mvc/dataset/states\",\n \"mvc/history/hda-model\",\n \"mvc/history/hda-li-edit\",\n \"mvc/history/hdca-li-edit\",\n \"mvc/tag\",\n \"mvc/annotation\",\n \"mvc/collection/list-collection-creator\",\n \"mvc/collection/pair-collection-creator\",\n \"mvc/collection/list-of-pairs-collection-creator\",\n \"ui/fa-icon-button\",\n \"mvc/ui/popup-menu\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function(\n HISTORY_VIEW,\n HISTORY_CONTENTS,\n STATES,\n HDA_MODEL,\n HDA_LI_EDIT,\n HDCA_LI_EDIT,\n TAGS,\n ANNOTATIONS,\n LIST_COLLECTION_CREATOR,\n PAIR_COLLECTION_CREATOR,\n LIST_OF_PAIRS_COLLECTION_CREATOR,\n faIconButton,\n PopupMenu,\n BASE_MVC,\n _l\n){\n\n'use strict';\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\nvar _super = HISTORY_VIEW.HistoryView;\n// base class for history-view-edit-current and used as-is in history/view.mako\n/** @class Editable View/Controller for the history model.\n *\n * Allows:\n * (everything HistoryView allows)\n * changing the name\n * displaying and editing tags and annotations\n * multi-selection and operations on mulitple content items\n */\nvar HistoryViewEdit = _super.extend(\n/** @lends HistoryViewEdit.prototype */{\n\n /** class to use for constructing the HistoryDatasetAssociation views */\n HDAViewClass : HDA_LI_EDIT.HDAListItemEdit,\n /** class to use for constructing the HistoryDatasetCollectionAssociation views */\n HDCAViewClass : HDCA_LI_EDIT.HDCAListItemEdit,\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes\n */\n initialize : function( attributes ){\n attributes = attributes || {};\n _super.prototype.initialize.call( this, attributes );\n\n // ---- set up instance vars\n /** editor for tags - sub-view */\n this.tagsEditor = null;\n\n /** enable drag and drop - sub-view */\n this.dragItems = true;\n\n /** editor for annotations - sub-view */\n this.annotationEditor = null;\n\n /** allow user purge of dataset files? */\n this.purgeAllowed = attributes.purgeAllowed || false;\n\n // states/modes the panel can be in\n /** is the panel currently showing the dataset selection controls? */\n this.annotationEditorShown = attributes.annotationEditorShown || false;\n this.tagsEditorShown = attributes.tagsEditorShown || false;\n },\n\n /** Override to handle history as drag-drop target */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n return this.on({\n 'droptarget:drop': function( ev, data ){\n // process whatever was dropped and re-hide the drop target\n this.dataDropped( data );\n this.dropTargetOff();\n },\n 'view:attached view:removed': function(){\n this._renderCounts();\n },\n 'search:loading-progress': this._renderSearchProgress,\n 'search:searching': this._renderSearchFindings,\n });\n },\n\n // ------------------------------------------------------------------------ listeners\n /** listening for history and HDA events */\n _setUpModelListeners : function(){\n _super.prototype._setUpModelListeners.call( this );\n this.listenTo( this.model, 'change:size', this.updateHistoryDiskSize );\n return this;\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n this.listenTo( this.collection, {\n 'change:deleted': this._handleItemDeletedChange,\n 'change:visible': this._handleItemVisibleChange,\n 'change:purged' : function( model ){\n // hafta get the new nice-size w/o the purged model\n this.model.fetch();\n },\n // loading indicators for deleted/hidden\n 'fetching-deleted' : function( collection ){\n this.$( '> .controls .deleted-count' )\n .html( '' + _l( 'loading...' ) + '' );\n },\n 'fetching-hidden' : function( collection ){\n this.$( '> .controls .hidden-count' )\n .html( '' + _l( 'loading...' ) + '' );\n },\n 'fetching-deleted-done fetching-hidden-done' : this._renderCounts,\n });\n return this;\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** In this override, add tag and annotation editors and a btn to toggle the selectors */\n _buildNewRender : function(){\n // create a new render using a skeleton template, render title buttons, render body, and set up events, etc.\n var $newRender = _super.prototype._buildNewRender.call( this );\n if( !this.model ){ return $newRender; }\n\n if( Galaxy && Galaxy.user && Galaxy.user.id && Galaxy.user.id === this.model.get( 'user_id' ) ){\n this._renderTags( $newRender );\n this._renderAnnotation( $newRender );\n }\n return $newRender;\n },\n\n /** Update the history size display (curr. upper right of panel). */\n updateHistoryDiskSize : function(){\n this.$( '.history-size' ).text( this.model.get( 'nice_size' ) );\n },\n\n /** override to render counts when the items are rendered */\n renderItems : function( $whereTo ){\n var views = _super.prototype.renderItems.call( this, $whereTo );\n if( !this.searchFor ){ this._renderCounts( $whereTo ); }\n return views;\n },\n\n /** override to show counts, what's deleted/hidden, and links to toggle those */\n _renderCounts : function( $whereTo ){\n $whereTo = $whereTo instanceof jQuery? $whereTo : this.$el;\n var html = this.templates.counts( this.model.toJSON(), this );\n return $whereTo.find( '> .controls .subtitle' ).html( html );\n },\n\n /** render the tags sub-view controller */\n _renderTags : function( $where ){\n var panel = this;\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.controls .tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n // show hide sub-view tag editors when this is shown/hidden\n onshow : function(){\n panel.toggleHDATagEditors( true, panel.fxSpeed );\n },\n onhide : function(){\n panel.toggleHDATagEditors( false, panel.fxSpeed );\n },\n $activator : faIconButton({\n title : _l( 'Edit history tags' ),\n classes : 'history-tag-btn',\n faIcon : 'fa-tags'\n }).appendTo( $where.find( '.controls .actions' ) )\n });\n },\n /** render the annotation sub-view controller */\n _renderAnnotation : function( $where ){\n var panel = this;\n this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n model : this.model,\n el : $where.find( '.controls .annotation-display' ),\n onshowFirstTime : function(){ this.render(); },\n // show hide sub-view view annotation editors when this is shown/hidden\n onshow : function(){\n panel.toggleHDAAnnotationEditors( true, panel.fxSpeed );\n },\n onhide : function(){\n panel.toggleHDAAnnotationEditors( false, panel.fxSpeed );\n },\n $activator : faIconButton({\n title : _l( 'Edit history annotation' ),\n classes : 'history-annotate-btn',\n faIcon : 'fa-comment'\n }).appendTo( $where.find( '.controls .actions' ) )\n });\n },\n\n /** Set up HistoryViewEdit js/widget behaviours\n * In this override, make the name editable\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n _super.prototype._setUpBehaviors.call( this, $where );\n if( !this.model ){ return; }\n\n // anon users shouldn't have access to any of the following\n if( ( !Galaxy.user || Galaxy.user.isAnonymous() )\n || ( Galaxy.user.id !== this.model.get( 'user_id' ) ) ){\n return;\n }\n\n var panel = this,\n nameSelector = '> .controls .name';\n $where.find( nameSelector )\n .attr( 'title', _l( 'Click to rename history' ) )\n .tooltip({ placement: 'bottom' })\n .make_text_editable({\n on_finish: function( newName ){\n var previousName = panel.model.get( 'name' );\n if( newName && newName !== previousName ){\n panel.$el.find( nameSelector ).text( newName );\n panel.model.save({ name: newName })\n .fail( function(){\n panel.$el.find( nameSelector ).text( panel.model.previous( 'name' ) );\n });\n } else {\n panel.$el.find( nameSelector ).text( previousName );\n }\n }\n });\n },\n\n /** return a new popup menu for choosing a multi selection action\n * ajax calls made for multiple datasets are queued\n */\n multiselectActions : function(){\n var panel = this,\n actions = [\n { html: _l( 'Hide datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.hide;\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Unhide datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.unhide;\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Delete datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype['delete'];\n panel.getSelectedModels().ajaxQueue( action );\n }\n },\n { html: _l( 'Undelete datasets' ), func: function(){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.undelete;\n panel.getSelectedModels().ajaxQueue( action );\n }\n }\n ];\n if( panel.purgeAllowed ){\n actions.push({\n html: _l( 'Permanently delete datasets' ), func: function(){\n if( confirm( _l( 'This will permanently remove the data in your datasets. Are you sure?' ) ) ){\n var action = HDA_MODEL.HistoryDatasetAssociation.prototype.purge;\n panel.getSelectedModels().ajaxQueue( action );\n }\n }\n });\n }\n actions = actions.concat( panel._collectionActions() );\n return actions;\n },\n\n /** */\n _collectionActions : function(){\n var panel = this;\n return [\n { html: _l( 'Build Dataset List' ), func: function() { panel.buildCollection( \"list\") }\n },\n // TODO: Only show quick pair if two things selected.\n { html: _l( 'Build Dataset Pair' ), func: function() { panel.buildCollection( \"paired\") }\n },\n { html: _l( 'Build List of Dataset Pairs' ), func: function() { panel.buildCollection( \"list:paired\" ) }\n },\n ];\n },\n\n buildCollection : function( collectionType, selection, hideSourceItems ) {\n var panel = this;\n var selection = selection || panel.getSelectedModels();\n var hideSourceItems = hideSourceItems || false;\n var createFunc;\n if( collectionType == \"list\" ) {\n createFunc = LIST_COLLECTION_CREATOR.createListCollection;\n } else if( collectionType == \"paired\" ) {\n createFunc = PAIR_COLLECTION_CREATOR.createPairCollection;\n } else if( collectionType == \"list:paired\" ) {\n createFunc = LIST_OF_PAIRS_COLLECTION_CREATOR.createListOfPairsCollection;\n } else {\n console.warn( \"Unknown collectionType encountered \" + collectionType );\n }\n createFunc( selection, hideSourceItems ).done( function() { panel.model.refresh() } );\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** In this override, add purgeAllowed and whether tags/annotation editors should be shown */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n _.extend( options, {\n purgeAllowed : this.purgeAllowed,\n tagsEditorShown : ( this.tagsEditor && !this.tagsEditor.hidden ),\n annotationEditorShown : ( this.annotationEditor && !this.annotationEditor.hidden )\n });\n return options;\n },\n\n /** If this item is deleted and we're not showing deleted items, remove the view\n * @param {Model} the item model to check\n */\n _handleItemDeletedChange : function( itemModel ){\n if( itemModel.get( 'deleted' ) ){\n this._handleItemDeletion( itemModel );\n } else {\n this._handleItemUndeletion( itemModel );\n }\n this._renderCounts();\n },\n\n _handleItemDeletion : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.deleted += 1;\n contentsShown.active -= 1;\n if( !this.model.contents.includeDeleted ){\n this.removeItemView( itemModel );\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n _handleItemUndeletion : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.deleted -= 1;\n if( !this.model.contents.includeDeleted ){\n contentsShown.active -= 1;\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n /** If this item is hidden and we're not showing hidden items, remove the view\n * @param {Model} the item model to check\n */\n _handleItemVisibleChange : function( itemModel ){\n if( itemModel.hidden() ){\n this._handleItemHidden( itemModel );\n } else {\n this._handleItemUnhidden( itemModel );\n }\n this._renderCounts();\n },\n\n _handleItemHidden : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.hidden += 1;\n contentsShown.active -= 1;\n if( !this.model.contents.includeHidden ){\n this.removeItemView( itemModel );\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n _handleItemUnhidden : function( itemModel ){\n var contentsShown = this.model.get( 'contents_active' );\n contentsShown.hidden -= 1;\n if( !this.model.contents.includeHidden ){\n contentsShown.active -= 1;\n }\n this.model.set( 'contents_active', contentsShown );\n },\n\n /** toggle the visibility of each content's tagsEditor applying all the args sent to this function */\n toggleHDATagEditors : function( showOrHide, speed ){\n _.each( this.views, function( view ){\n if( view.tagsEditor ){\n view.tagsEditor.toggle( showOrHide, speed );\n }\n });\n },\n\n /** toggle the visibility of each content's annotationEditor applying all the args sent to this function */\n toggleHDAAnnotationEditors : function( showOrHide, speed ){\n _.each( this.views, function( view ){\n if( view.annotationEditor ){\n view.annotationEditor.toggle( showOrHide, speed );\n }\n });\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .show-selectors-btn' : 'toggleSelectors',\n 'click .toggle-deleted-link' : function( ev ){ this.toggleShowDeleted(); },\n 'click .toggle-hidden-link' : function( ev ){ this.toggleShowHidden(); }\n }),\n\n // ------------------------------------------------------------------------ search\n _renderSearchProgress : function( limit, offset ){\n var stop = limit + offset;\n return this.$( '> .controls .subtitle' ).html([\n '',\n _l( 'Searching ' ), stop, '/', this.model.contentsShown(),\n ''\n ].join(''));\n },\n\n /** override to display number found in subtitle */\n _renderSearchFindings : function(){\n this.$( '> .controls .subtitle' ).html([\n _l( 'Found' ), this.views.length\n ].join(' '));\n return this;\n },\n\n // ------------------------------------------------------------------------ as drop target\n /** turn all the drag and drop handlers on and add some help text above the drop area */\n dropTargetOn : function(){\n if( this.dropTarget ){ return this; }\n this.dropTarget = true;\n\n //TODO: to init\n var dropHandlers = {\n 'dragenter' : _.bind( this.dragenter, this ),\n 'dragover' : _.bind( this.dragover, this ),\n 'dragleave' : _.bind( this.dragleave, this ),\n 'drop' : _.bind( this.drop, this )\n };\n\n var $dropTarget = this._renderDropTarget();\n this.$list().before([ this._renderDropTargetHelp(), $dropTarget ]);\n for( var evName in dropHandlers ){\n if( dropHandlers.hasOwnProperty( evName ) ){\n //console.debug( evName, dropHandlers[ evName ] );\n $dropTarget.on( evName, dropHandlers[ evName ] );\n }\n }\n return this;\n },\n\n /** render a box to serve as a 'drop here' area on the history */\n _renderDropTarget : function(){\n this.$( '.history-drop-target' ).remove();\n return $( '
                                            ' ).addClass( 'history-drop-target' );\n },\n\n /** tell the user how it works */\n _renderDropTargetHelp : function(){\n this.$( '.history-drop-target-help' ).remove();\n return $( '
                                            ' ).addClass( 'history-drop-target-help' )\n .text( _l( 'Drag datasets here to copy them to the current history' ) );\n },\n\n /** shut down drag and drop event handlers and remove drop target */\n dropTargetOff : function(){\n if( !this.dropTarget ){ return this; }\n //this.log( 'dropTargetOff' );\n this.dropTarget = false;\n var dropTarget = this.$( '.history-drop-target' ).get(0);\n for( var evName in this._dropHandlers ){\n if( this._dropHandlers.hasOwnProperty( evName ) ){\n dropTarget.off( evName, this._dropHandlers[ evName ] );\n }\n }\n this.$( '.history-drop-target' ).remove();\n this.$( '.history-drop-target-help' ).remove();\n return this;\n },\n /** toggle the target on/off */\n dropTargetToggle : function(){\n if( this.dropTarget ){\n this.dropTargetOff();\n } else {\n this.dropTargetOn();\n }\n return this;\n },\n\n dragenter : function( ev ){\n //console.debug( 'dragenter:', this, ev );\n ev.preventDefault();\n ev.stopPropagation();\n this.$( '.history-drop-target' ).css( 'border', '2px solid black' );\n },\n dragover : function( ev ){\n ev.preventDefault();\n ev.stopPropagation();\n },\n dragleave : function( ev ){\n //console.debug( 'dragleave:', this, ev );\n ev.preventDefault();\n ev.stopPropagation();\n this.$( '.history-drop-target' ).css( 'border', '1px dashed black' );\n },\n /** when (text) is dropped try to parse as json and trigger an event */\n drop : function( ev ){\n ev.preventDefault();\n //ev.stopPropagation();\n\n var self = this;\n var dataTransfer = ev.originalEvent.dataTransfer;\n var data = dataTransfer.getData( \"text\" );\n\n dataTransfer.dropEffect = 'move';\n try {\n data = JSON.parse( data );\n } catch( err ){\n self.warn( 'error parsing JSON from drop:', data );\n }\n\n self.trigger( 'droptarget:drop', ev, data, self );\n return false;\n },\n\n /** handler that copies data into the contents */\n dataDropped : function( data ){\n var self = this;\n // HDA: dropping will copy it to the history\n if( _.isObject( data ) && data.model_class === 'HistoryDatasetAssociation' && data.id ){\n if( self.contents.currentPage !== 0 ){\n return self.contents.fetchPage( 0 )\n .then( function(){\n return self.model.contents.copy( data.id );\n });\n }\n return self.model.contents.copy( data.id );\n }\n return jQuery.when();\n },\n\n // ........................................................................ misc\n /** Return a string rep of the history */\n toString : function(){\n return 'HistoryViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n//------------------------------------------------------------------------------ TEMPLATES\nHistoryViewEdit.prototype.templates = (function(){\n\n var countsTemplate = BASE_MVC.wrapTemplate([\n '<% var shown = Math.max( view.views.length, history.contents_active.active ) %>',\n '<% if( shown ){ %>',\n '',\n '<%- shown %> ', _l( 'shown' ),\n '',\n '<% } %>',\n\n '<% if( history.contents_active.deleted ){ %>',\n '',\n '<% if( view.model.contents.includeDeleted ){ %>',\n '',\n _l( 'hide deleted' ),\n '',\n '<% } else { %>',\n '<%- history.contents_active.deleted %> ',\n '',\n _l( 'deleted' ),\n '',\n '<% } %>',\n '',\n '<% } %>',\n\n '<% if( history.contents_active.hidden ){ %>',\n '',\n '<% if( view.model.contents.includeHidden ){ %>',\n '',\n _l( 'hide hidden' ),\n '',\n '<% } else { %>',\n '<%- history.contents_active.hidden %> ',\n '',\n _l( 'hidden' ),\n '',\n '<% } %>',\n '',\n '<% } %>',\n ], 'history' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n counts : countsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n HistoryViewEdit : HistoryViewEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view-edit.js","define([\n \"mvc/list/list-view\",\n \"mvc/history/history-model\",\n \"mvc/history/history-contents\",\n \"mvc/history/history-preferences\",\n \"mvc/history/hda-li\",\n \"mvc/history/hdca-li\",\n \"mvc/user/user-model\",\n \"mvc/ui/error-modal\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/search-input\"\n], function(\n LIST_VIEW,\n HISTORY_MODEL,\n HISTORY_CONTENTS,\n HISTORY_PREFS,\n HDA_LI,\n HDCA_LI,\n USER,\n ERROR_MODAL,\n faIconButton,\n BASE_MVC,\n _l\n){\n'use strict';\n\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class non-editable, read-only View/Controller for a history model.\n * Allows:\n * changing the loaded history\n * displaying data, info, and download\n * tracking history attrs: size, tags, annotations, name, etc.\n * Does not allow:\n * changing the name\n */\nvar _super = LIST_VIEW.ModelListPanel;\nvar HistoryView = _super.extend(\n/** @lends HistoryView.prototype */{\n _logNamespace : 'history',\n\n /** class to use for constructing the HDA views */\n HDAViewClass : HDA_LI.HDAListItemView,\n /** class to use for constructing the HDCA views */\n HDCAViewClass : HDCA_LI.HDCAListItemView,\n /** class to used for constructing collection of sub-view models */\n collectionClass : HISTORY_CONTENTS.HistoryContents,\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'contents',\n\n tagName : 'div',\n className : _super.prototype.className + ' history-panel',\n\n /** string to display when the collection is empty */\n emptyMsg : _l( 'This history is empty' ),\n /** displayed when no items match the search terms */\n noneFoundMsg : _l( 'No matching datasets found' ),\n /** string used for search placeholder */\n searchPlaceholder : _l( 'search datasets' ),\n\n /** @type {Number} ms to wait after history load to fetch/decorate hdcas with element_count */\n FETCH_COLLECTION_COUNTS_DELAY : 2000,\n\n // ......................................................................... SET UP\n /** Set up the view, bind listeners.\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n // ---- instance vars\n // control contents/behavior based on where (and in what context) the panel is being used\n /** where should pages from links be displayed? (default to new tab/window) */\n this.linkTarget = attributes.linkTarget || '_blank';\n },\n\n /** create and return a collection for when none is initially passed */\n _createDefaultCollection : function(){\n // override\n return new this.collectionClass([], { history: this.model });\n },\n\n /** In this override, clear the update timer on the model */\n freeModel : function(){\n _super.prototype.freeModel.call( this );\n if( this.model ){\n this.model.clearUpdateTimeout();\n }\n return this;\n },\n\n /** create any event listeners for the panel\n * @fires: rendered:initial on the first render\n * @fires: empty-history when switching to a history with no contents or creating a new history\n */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n this.on({\n error : function( model, xhr, options, msg, details ){\n this.errorHandler( model, xhr, options, msg, details );\n },\n 'loading-done' : function(){\n var self = this;\n // after the initial load, decorate with more time consuming fields (like HDCA element_counts)\n _.delay( function(){\n self.model.contents.fetchCollectionCounts();\n }, self.FETCH_COLLECTION_COUNTS_DELAY );\n },\n 'views:ready view:attached view:removed' : function( view ){\n this._renderSelectButton();\n },\n 'view:attached' : function( view ){\n this.scrollTo(0);\n },\n });\n // this.on( 'all', function(){ console.debug( arguments ); });\n },\n\n // ------------------------------------------------------------------------ loading history/hda models\n /** load the history with the given id then it's contents, sending ajax options to both */\n loadHistory : function( historyId, options, contentsOptions ){\n contentsOptions = _.extend( contentsOptions || { silent: true });\n this.info( 'loadHistory:', historyId, options, contentsOptions );\n var self = this;\n self.setModel( new HISTORY_MODEL.History({ id : historyId }) );\n\n contentsOptions.silent = true;\n self.trigger( 'loading' );\n return self.model\n .fetchWithContents( options, contentsOptions )\n .always( function(){\n self.render();\n self.trigger( 'loading-done' );\n });\n },\n\n /** convenience alias to the model. Updates the item list only (not the history) */\n refreshContents : function( options ){\n if( this.model ){\n return this.model.refresh( options );\n }\n // may have callbacks - so return an empty promise\n return $.when();\n },\n\n /** Override to reset web storage when the id changes (since it needs the id) */\n _setUpCollectionListeners : function(){\n _super.prototype._setUpCollectionListeners.call( this );\n return this.listenTo( this.collection, {\n // 'all' : function(){ console.log( this.collection + ':', arguments ); },\n 'fetching-more' : function(){\n this._toggleContentsLoadingIndicator( true );\n this.$emptyMessage().hide();\n },\n 'fetching-more-done': function(){ this._toggleContentsLoadingIndicator( false ); },\n });\n },\n\n // ------------------------------------------------------------------------ panel rendering\n /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n _showLoadingIndicator : function( msg, speed, callback ){\n var $indicator = $( '
                                            ' );\n this.$el.html( $indicator.text( msg ).slideDown( !_.isUndefined( speed )? speed : this.fxSpeed ) );\n },\n\n /** hide the loading indicator */\n _hideLoadingIndicator : function( speed ){\n // make speed a bit slower to compensate for slow rendering of up to 500 contents\n this.$( '.loading-indicator' ).slideUp( !_.isUndefined( speed )? speed : ( this.fxSpeed + 200 ), function(){\n $( this ).remove();\n });\n },\n\n /** In this override, add a btn to toggle the selectors */\n _buildNewRender : function(){\n var $newRender = _super.prototype._buildNewRender.call( this );\n this._renderSelectButton( $newRender );\n return $newRender;\n },\n\n /** button for starting select mode */\n _renderSelectButton : function( $where ){\n $where = $where || this.$el;\n // do not render selector option if no actions\n if( !this.multiselectActions().length ){\n return null;\n }\n // do not render (and remove even) if nothing to select\n if( !this.views.length ){\n this.hideSelectors();\n $where.find( '.controls .actions .show-selectors-btn' ).remove();\n return null;\n }\n // don't bother rendering if there's one already\n var $existing = $where.find( '.controls .actions .show-selectors-btn' );\n if( $existing.length ){\n return $existing;\n }\n\n return faIconButton({\n title : _l( 'Operations on multiple datasets' ),\n classes : 'show-selectors-btn',\n faIcon : 'fa-check-square-o'\n }).prependTo( $where.find( '.controls .actions' ) );\n },\n\n /** override to avoid showing intial empty message using contents_active */\n _renderEmptyMessage : function( $whereTo ){\n var self = this;\n var $emptyMsg = self.$emptyMessage( $whereTo );\n\n var empty = self.model.get( 'contents_active' ).active <= 0;\n if( empty ){\n return $emptyMsg.empty().append( self.emptyMsg ).show();\n\n } else if( self.searchFor && self.model.contents.haveSearchDetails() && !self.views.length ){\n return $emptyMsg.empty().append( self.noneFoundMsg ).show();\n }\n $emptyMsg.hide();\n return $();\n },\n\n /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n $scrollContainer : function( $where ){\n // override or set via attributes.$scrollContainer\n return this.$list( $where );\n },\n\n // ------------------------------------------------------------------------ subviews\n _toggleContentsLoadingIndicator : function( show ){\n if( !show ){\n this.$list().find( '.contents-loading-indicator' ).remove();\n } else {\n this.$list().html( '
                                            '\n + '
                                            ' );\n }\n },\n\n /** override to render pagination also */\n renderItems: function( $whereTo ){\n // console.log( this + '.renderItems-----------------', new Date() );\n $whereTo = $whereTo || this.$el;\n var self = this;\n var $list = self.$list( $whereTo );\n\n // TODO: bootstrap hack to remove orphaned tooltips\n $( '.tooltip' ).remove();\n\n $list.empty();\n self.views = [];\n\n var models = self._filterCollection();\n if( models.length ){\n self._renderPagination( $whereTo );\n self.views = self._renderSomeItems( models, $list );\n } else {\n // TODO: consolidate with _renderPagination above by (???) passing in models/length?\n $whereTo.find( '> .controls .list-pagination' ).empty();\n }\n self._renderEmptyMessage( $whereTo ).toggle( !models.length );\n\n self.trigger( 'views:ready', self.views );\n return self.views;\n },\n\n /** render pagination controls if not searching and contents says we're paginating */\n _renderPagination: function( $whereTo ){\n var $paginationControls = $whereTo.find( '> .controls .list-pagination' );\n if( this.searchFor || !this.model.contents.shouldPaginate() ) return $paginationControls.empty();\n\n $paginationControls.html( this.templates.pagination({\n // pagination is 1-based for the user\n current : this.model.contents.currentPage + 1,\n last : this.model.contents.getLastPage() + 1,\n }, this ));\n $paginationControls.find( 'select.pages' ).tooltip();\n return $paginationControls;\n },\n\n /** render a subset of the entire collection (client-side pagination) */\n _renderSomeItems: function( models, $list ){\n var self = this;\n var views = [];\n $list.append( models.map( function( m ){\n var view = self._createItemView( m );\n views.push( view );\n return self._renderItemView$el( view );\n }));\n return views;\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** in this override, check if the contents would also display based on includeDeleted/hidden */\n _filterItem : function( model ){\n var self = this;\n var contents = self.model.contents;\n return ( contents.includeHidden || !model.hidden() )\n && ( contents.includeDeleted || !model.isDeletedOrPurged() )\n && ( _super.prototype._filterItem.call( self, model ) );\n },\n\n /** In this override, since history contents are mixed,\n * get the appropo view class based on history_content_type\n */\n _getItemViewClass : function( model ){\n var contentType = model.get( \"history_content_type\" );\n switch( contentType ){\n case 'dataset':\n return this.HDAViewClass;\n case 'dataset_collection':\n return this.HDCAViewClass;\n }\n throw new TypeError( 'Unknown history_content_type: ' + contentType );\n },\n\n /** in this override, add a linktarget, and expand if id is in web storage */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n expanded : this.model.contents.storage.isExpanded( model.id ),\n hasUser : this.model.ownedByCurrUser()\n });\n },\n\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n //TODO: send from content view: this.model.collection.storage.addExpanded\n // maintain a list of items whose bodies are expanded\n return panel.listenTo( view, {\n 'expanded': function( v ){\n panel.model.contents.storage.addExpanded( v.model );\n },\n 'collapsed': function( v ){\n panel.model.contents.storage.removeExpanded( v.model );\n }\n });\n },\n\n /** override to remove expandedIds from webstorage */\n collapseAll : function(){\n this.model.contents.storage.clearExpanded();\n _super.prototype.collapseAll.call( this );\n },\n\n // ------------------------------------------------------------------------ selection\n /** Override to correctly set the historyId of the new collection */\n getSelectedModels : function(){\n var collection = _super.prototype.getSelectedModels.call( this );\n collection.historyId = this.collection.historyId;\n return collection;\n },\n\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .show-selectors-btn' : 'toggleSelectors',\n 'click > .controls .prev' : '_clickPrevPage',\n 'click > .controls .next' : '_clickNextPage',\n 'change > .controls .pages' : '_changePageSelect',\n // allow (error) messages to be clicked away\n 'click .messages [class$=message]' : 'clearMessages',\n }),\n\n _clickPrevPage : function( ev ){\n this.model.clearUpdateTimeout();\n this.model.contents.fetchPrevPage();\n },\n\n _clickNextPage : function( ev ){\n this.model.clearUpdateTimeout();\n this.model.contents.fetchNextPage();\n },\n\n _changePageSelect : function( ev ){\n this.model.clearUpdateTimeout();\n var page = $( ev.currentTarget ).val();\n this.model.contents.fetchPage( page );\n },\n\n /** Toggle and store the deleted visibility and re-render items\n * @returns {Boolean} new setting\n */\n toggleShowDeleted : function( show, options ){\n show = ( show !== undefined )?( show ):( !this.model.contents.includeDeleted );\n var self = this;\n var contents = self.model.contents;\n contents.setIncludeDeleted( show, options );\n self.trigger( 'show-deleted', show );\n\n contents.fetchCurrentPage({ renderAll: true });\n return show;\n },\n\n /** Toggle and store whether to render explicity hidden contents\n * @returns {Boolean} new setting\n */\n toggleShowHidden : function( show, store, options ){\n // console.log( 'toggleShowHidden', show, store );\n show = ( show !== undefined )?( show ):( !this.model.contents.includeHidden );\n var self = this;\n var contents = self.model.contents;\n contents.setIncludeHidden( show, options );\n self.trigger( 'show-hidden', show );\n\n contents.fetchCurrentPage({ renderAll: true });\n return show;\n },\n\n /** On the first search, if there are no details - load them, then search */\n _firstSearch : function( searchFor ){\n var self = this;\n var inputSelector = '> .controls .search-input';\n this.log( 'onFirstSearch', searchFor );\n\n // if the contents already have enough details to search, search and return now\n if( self.model.contents.haveSearchDetails() ){\n self.searchItems( searchFor );\n return;\n }\n\n // otherwise, load the details progressively here\n self.$( inputSelector ).searchInput( 'toggle-loading' );\n // set this now so that only results will show during progress\n self.searchFor = searchFor;\n var xhr = self.model.contents.progressivelyFetchDetails({ silent: true })\n .progress( function( response, limit, offset ){\n self.renderItems();\n self.trigger( 'search:loading-progress', limit, offset );\n })\n .always( function(){\n self.$el.find( inputSelector ).searchInput( 'toggle-loading' );\n })\n .done( function(){\n self.searchItems( searchFor, 'force' );\n });\n },\n\n /** clear the search filters and show all views that are normally shown */\n clearSearch : function( searchFor ){\n var self = this;\n if( !self.searchFor ) return self;\n //self.log( 'onSearchClear', self );\n self.searchFor = '';\n self.trigger( 'search:clear', self );\n self.$( '> .controls .search-query' ).val( '' );\n // NOTE: silent + render prevents collection update event with merge only\n // - which causes an empty page due to event handler above\n self.model.contents.fetchCurrentPage({ silent: true })\n .done( function(){\n self.renderItems();\n });\n return self;\n },\n\n // ........................................................................ error handling\n /** Event handler for errors (from the panel, the history, or the history's contents)\n * Alternately use two strings for model and xhr to use custom message and title (respectively)\n * @param {Model or View} model the (Backbone) source of the error\n * @param {XMLHTTPRequest} xhr any ajax obj. assoc. with the error\n * @param {Object} options the options map commonly used with bbone ajax\n */\n errorHandler : function( model, xhr, options ){\n //TODO: to mixin or base model\n // interrupted ajax or no connection\n if( xhr && xhr.status === 0 && xhr.readyState === 0 ){\n // return ERROR_MODAL.offlineErrorModal();\n // fail silently\n return;\n }\n // otherwise, leave something to report in the console\n this.error( model, xhr, options );\n // and feedback to a modal\n // if sent two strings (and possibly details as 'options'), use those as message and title\n if( _.isString( model ) && _.isString( xhr ) ){\n var message = model;\n var title = xhr;\n return ERROR_MODAL.errorModal( message, title, options );\n }\n // bad gateway\n // TODO: possibly to global handler\n if( xhr && xhr.status === 502 ){\n return ERROR_MODAL.badGatewayErrorModal();\n }\n return ERROR_MODAL.ajaxErrorModal( model, xhr, options );\n },\n\n /** Remove all messages from the panel. */\n clearMessages : function( ev ){\n var $target = !_.isUndefined( ev )?\n $( ev.currentTarget )\n :this.$messages().children( '[class$=\"message\"]' );\n $target.fadeOut( this.fxSpeed, function(){\n $( this ).remove();\n });\n return this;\n },\n\n // ........................................................................ scrolling\n /** Scrolls the panel to show the content sub-view with the given hid.\n * @param {Integer} hid the hid of item to scroll into view\n * @returns {HistoryView} the panel\n */\n scrollToHid : function( hid ){\n return this.scrollToItem( _.first( this.viewsWhereModel({ hid: hid }) ) );\n },\n\n // ........................................................................ misc\n /** utility for adding -st, -nd, -rd, -th to numbers */\n ordinalIndicator : function( number ){\n var numStr = number + '';\n switch( numStr.charAt( numStr.length - 1 )){\n case '1': return numStr + 'st';\n case '2': return numStr + 'nd';\n case '3': return numStr + 'rd';\n default : return numStr + 'th';\n }\n },\n\n /** Return a string rep of the history */\n toString : function(){\n return 'HistoryView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nHistoryView.prototype.templates = (function(){\n\n var mainTemplate = BASE_MVC.wrapTemplate([\n // temp container\n '
                                            ',\n '
                                            ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ]);\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                                              ',\n '
                                              ',\n '
                                              <%- history.name %>
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              <%- history.nice_size %>
                                              ',\n\n '
                                              ',\n\n '
                                              ',\n '<% if( history.deleted && history.purged ){ %>',\n '
                                              ',\n _l( 'This history has been purged and deleted' ),\n '
                                              ',\n '<% } else if( history.deleted ){ %>',\n '
                                              ',\n _l( 'This history has been deleted' ),\n '
                                              ',\n '<% } else if( history.purged ){ %>',\n '
                                              ',\n _l( 'This history has been purged' ),\n '
                                              ',\n '<% } %>',\n\n '<% if( history.message ){ %>',\n // should already be localized\n '
                                              messagesmall\">',\n '<%= history.message.text %>',\n '
                                              ',\n '<% } %>',\n '
                                              ',\n\n // add tags and annotations\n '
                                              ',\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ], 'history' );\n\n var paginationTemplate = BASE_MVC.wrapTemplate([\n '',\n '',\n '',\n ], 'pages' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n el : mainTemplate,\n controls : controlsTemplate,\n pagination : paginationTemplate,\n });\n}());\n\n\n//==============================================================================\n return {\n HistoryView: HistoryView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-view.js","define([\n \"mvc/ui/popup-menu\",\n \"mvc/history/copy-dialog\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"mvc/webhooks\"\n], function( PopupMenu, historyCopyDialog, BASE_MVC, _l, Webhooks ){\n\n'use strict';\n\n// ============================================================================\nvar menu = [\n {\n html : _l( 'History Lists' ),\n header : true\n },\n {\n html : _l( 'Saved Histories' ),\n href : 'histories/list',\n target : '_top'\n\n },\n {\n html : _l( 'Histories Shared with Me' ),\n href : 'histories/list_shared',\n target : '_top'\n },\n {\n html : _l( 'Current History' ),\n header : true,\n anon : true\n },\n {\n html : _l( 'Create New' ),\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel ){\n Galaxy.currHistoryPanel.createNewHistory();\n }\n },\n },\n {\n html : _l( 'Copy History' ),\n func : function() {\n historyCopyDialog( Galaxy.currHistoryPanel.model )\n .done( function(){\n Galaxy.currHistoryPanel.loadCurrentHistory();\n });\n },\n },\n {\n html : _l( 'Share or Publish' ),\n href : 'history/sharing',\n },\n {\n html : _l( 'Show Structure' ),\n href : 'history/display_structured',\n anon : true,\n },\n {\n html : _l( 'Extract Workflow' ),\n href : 'workflow/build_from_current_history',\n },\n {\n html : _l( 'Delete' ),\n anon : true,\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really delete the current history?' ) ) ){\n galaxy_main.window.location.href = 'history/delete?id=' + Galaxy.currHistoryPanel.model.id;\n }\n },\n },\n {\n html : _l( 'Delete Permanently' ),\n purge : true,\n anon : true,\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel\n && confirm( _l( 'Really delete the current history permanently? This cannot be undone.' ) ) ){\n galaxy_main.window.location.href = 'history/delete?purge=True&id=' + Galaxy.currHistoryPanel.model.id;\n }\n },\n },\n\n\n {\n html : _l( 'Dataset Actions' ),\n header : true,\n anon : true\n },\n {\n html : _l( 'Copy Datasets' ),\n href : 'dataset/copy_datasets',\n },\n {\n html : _l( 'Dataset Security' ),\n href : 'root/history_set_default_permissions',\n },\n {\n html : _l( 'Resume Paused Jobs' ),\n href : 'history/resume_paused_jobs?current=True',\n anon : true,\n },\n {\n html : _l( 'Collapse Expanded Datasets' ),\n func : function() {\n if( Galaxy && Galaxy.currHistoryPanel ){\n Galaxy.currHistoryPanel.collapseAll();\n }\n },\n },\n {\n html : _l( 'Unhide Hidden Datasets' ),\n anon : true,\n func : function() {\n // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really unhide all hidden datasets?' ) ) ){\n $.post(Galaxy.root + \"history/adjust_hidden\",\n { 'user_action' : 'unhide' },\n function(){Galaxy.currHistoryPanel.loadCurrentHistory();});\n }\n },\n },\n {\n html : _l( 'Delete Hidden Datasets' ),\n anon : true,\n func : function() {\n // TODO: Deprecate this functionality and replace with group dataset selector and action combination\n if( Galaxy && Galaxy.currHistoryPanel && confirm( _l( 'Really delete all hidden datasets?' ) ) ){\n $.post(Galaxy.root + \"history/adjust_hidden\",\n { 'user_action' : 'delete' },\n function(){Galaxy.currHistoryPanel.loadCurrentHistory();});\n }\n },\n },\n {\n html : _l( 'Purge Deleted Datasets' ),\n confirm : _l( 'Really delete all deleted datasets permanently? This cannot be undone.' ),\n href : 'history/purge_deleted_datasets',\n purge : true,\n anon : true,\n },\n\n\n {\n html : _l( 'Downloads' ),\n header : true\n },\n {\n html : _l( 'Export Tool Citations' ),\n href : 'history/citations',\n anon : true,\n },\n {\n html : _l( 'Export History to File' ),\n href : 'history/export_archive?preview=True',\n anon : true,\n },\n\n {\n html : _l( 'Other Actions' ),\n header : true\n },\n {\n html : _l( 'Import from File' ),\n href : 'history/import_archive',\n }\n];\n\n// Webhooks\nWebhooks.add({\n url: 'api/webhooks/history-menu/all',\n async: false, // (hypothetically) slows down the performance\n callback: function(webhooks) {\n var webhooks_menu = [];\n\n $.each(webhooks.models, function(index, model) {\n var webhook = model.toJSON();\n if (webhook.activate) {\n webhooks_menu.push({\n html : _l( webhook.config.title ),\n // func: function() {},\n anon : true\n });\n }\n });\n\n if (webhooks_menu.length > 0) {\n webhooks_menu.unshift({\n html : _l( 'Webhooks' ),\n header : true\n });\n $.merge(menu, webhooks_menu);\n }\n }\n});\n\n\nfunction buildMenu( isAnon, purgeAllowed, urlRoot ){\n return _.clone( menu ).filter( function( menuOption ){\n if( isAnon && !menuOption.anon ){\n return false;\n }\n if( !purgeAllowed && menuOption.purge ){\n return false;\n }\n\n //TODO:?? hard-coded galaxy_main\n if( menuOption.href ){\n menuOption.href = urlRoot + menuOption.href;\n menuOption.target = menuOption.target || 'galaxy_main';\n }\n\n if( menuOption.confirm ){\n menuOption.func = function(){\n if( confirm( menuOption.confirm ) ){\n galaxy_main.location = menuOption.href;\n }\n };\n }\n return true;\n });\n}\n\nvar create = function( $button, options ){\n options = options || {};\n var isAnon = options.anonymous === undefined? true : options.anonymous,\n purgeAllowed = options.purgeAllowed || false,\n menu = buildMenu( isAnon, purgeAllowed, Galaxy.root );\n //console.debug( 'menu:', menu );\n return new PopupMenu( $button, menu );\n};\n\n\n// ============================================================================\n return create;\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/options-menu.js","/** Renders the collection uploader rows */\ndefine( [ 'utils/utils', 'mvc/upload/upload-model', 'mvc/upload/upload-settings', 'mvc/ui/ui-popover', 'mvc/ui/ui-select' ],\nfunction( Utils, UploadModel, UploadSettings, Popover, Select ) {\n return Backbone.View.extend({\n /** Dictionary of upload states and associated icons */\n status_classes : {\n init : 'upload-icon-button fa fa-trash-o',\n queued : 'upload-icon fa fa-spinner fa-spin',\n running : 'upload-icon fa fa-spinner fa-spin',\n success : 'upload-icon-button fa fa-check',\n error : 'upload-icon-button fa fa-exclamation-triangle'\n },\n\n initialize: function( app, options ) {\n var self = this;\n this.app = app;\n this.model = options.model;\n this.setElement( this._template( options.model ) );\n this.$mode = this.$( '.upload-mode' );\n this.$title = this.$( '.upload-title-extended' );\n this.$text = this.$( '.upload-text' );\n this.$size = this.$( '.upload-size' );\n this.$info_text = this.$( '.upload-info-text' );\n this.$info_progress = this.$( '.upload-info-progress' );\n this.$text_content = this.$( '.upload-text-content' );\n this.$symbol = this.$( '.upload-symbol' );\n this.$progress_bar = this.$( '.upload-progress-bar' );\n this.$percentage = this.$( '.upload-percentage' );\n\n // append popup to settings icon\n this.settings = new Popover.View({\n title : 'Upload configuration',\n container : this.$( '.upload-settings' ),\n placement : 'bottom'\n });\n\n // identify default genome and extension values\n var default_genome = this.app.select_genome.value();\n var default_extension = this.app.select_extension.value();\n\n // handle click event\n this.$symbol.on('click', function() { self._removeRow(); });\n\n // handle text editing event\n this.$text_content.on( 'change input', function( e ) {\n self.model.set( { 'url_paste': $( e.target ).val(),\n 'file_size': $( e.target ).val().length } );\n });\n\n // model events\n this.listenTo( this.model, 'change:percentage', function() { self._refreshPercentage() } );\n this.listenTo( this.model, 'change:status', function() { self._refreshStatus() } );\n this.listenTo( this.model, 'change:info', function() { self._refreshInfo() } );\n this.listenTo( this.model, 'change:file_size', function() { self._refreshFileSize() } );\n this.listenTo( this.model, 'remove', function() { self.remove() } );\n this.app.collection.on('reset', function() { self.remove() } );\n },\n\n render: function() {\n var options = this.model.attributes;\n this.$title.html( _.escape( options.file_name ) );\n this.$size.html( Utils.bytesToString ( options.file_size ) );\n this.$mode.removeClass().addClass( 'upload-mode' ).addClass( 'text-primary' );\n if ( options.file_mode == 'new' ) {\n this.$text.css( { 'width' : this.$el.width() - 16 + 'px', 'top' : this.$el.height() - 8 + 'px' } ).show();\n this.$el.height( this.$el.height() - 8 + this.$text.height() + 16 );\n this.$mode.addClass( 'fa fa-edit' );\n } else if ( options.file_mode == 'local' ) {\n this.$mode.addClass( 'fa fa-laptop' );\n } else if ( options.file_mode == 'ftp' ) {\n this.$mode.addClass( 'fa fa-folder-open-o' );\n }\n },\n\n /** Refresh info text */\n _refreshInfo: function() {\n var info = this.model.get( 'info' );\n if ( info ) {\n this.$info_text.html( 'Failed: ' + info ).show();\n } else {\n this.$info_text.hide();\n }\n },\n\n /** Refresh percentage status */\n _refreshPercentage : function() {\n var percentage = parseInt( this.model.get( 'percentage' ) );\n this.$progress_bar.css( { width : percentage + '%' } );\n this.$percentage.html( percentage != 100 ? percentage + '%' : 'Adding to history...' );\n },\n\n /** Refresh status */\n _refreshStatus : function() {\n var status = this.model.get( 'status' );\n this.$symbol.removeClass().addClass( 'upload-symbol' ).addClass( this.status_classes[ status ] );\n this.model.set( 'enabled', status == 'init' );\n var enabled = this.model.get( 'enabled' );\n this.$text_content.attr( 'disabled', !enabled );\n if ( status == 'success' ) {\n this.$el.addClass( 'success' );\n this.$percentage.html( '100%' );\n }\n if ( status == 'error' ) {\n this.$el.addClass( 'danger' );\n this.$info_progress.hide();\n }\n },\n\n /** Refresh file size */\n _refreshFileSize: function() {\n this.$size.html( Utils.bytesToString ( this.model.get( 'file_size' ) ) );\n },\n\n /** Remove row */\n _removeRow: function() {\n if ( [ 'init', 'success', 'error' ].indexOf( this.model.get( 'status' ) ) !== -1 ) {\n this.app.collection.remove( this.model );\n }\n },\n\n /** Attach file info popup */\n _showSettings : function() {\n if ( !this.settings.visible ) {\n this.settings.empty();\n this.settings.append( ( new UploadSettings( this ) ).$el );\n this.settings.show();\n } else {\n this.settings.hide();\n }\n },\n\n /** View template */\n _template: function( options ) {\n return '
                                              ' +\n ' <% diff --git a/test-data/test.vcf.gz b/test-data/test.vcf.gz new file mode 100644 index 00000000000..1b5b3146fd8 Binary files /dev/null and b/test-data/test.vcf.gz differ diff --git a/test/functional/tools/sample_datatypes_conf.xml b/test/functional/tools/sample_datatypes_conf.xml index 51a95e33078..0431842db02 100644 --- a/test/functional/tools/sample_datatypes_conf.xml +++ b/test/functional/tools/sample_datatypes_conf.xml @@ -21,5 +21,8 @@ + + + diff --git a/test/functional/tools/samples_tool_conf.xml b/test/functional/tools/samples_tool_conf.xml index c4285378ca5..916ce3f5f17 100644 --- a/test/functional/tools/samples_tool_conf.xml +++ b/test/functional/tools/samples_tool_conf.xml @@ -25,6 +25,7 @@ + @@ -149,6 +150,7 @@ + diff --git a/test/functional/tools/vcf_bgzip.xml b/test/functional/tools/vcf_bgzip.xml new file mode 100644 index 00000000000..070be227ee0 --- /dev/null +++ b/test/functional/tools/vcf_bgzip.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + diff --git a/test/unit/tools/test_parsing.py b/test/unit/tools/test_parsing.py index 048a81c1c2e..2fa8c70374e 100644 --- a/test/unit/tools/test_parsing.py +++ b/test/unit/tools/test_parsing.py @@ -124,6 +124,10 @@ class XmlLoaderTestCase(BaseLoaderTestCase): source_file_name = "bwa.xml" source_contents = TOOL_XML_1 + def test_tool_source_to_string(self): + # Previously this threw an Exception - test for regression. + str(self._tool_source) + def test_version(self): assert self._tool_source.parse_version() == "1.0.1"
                                              ' ).append( $checkbox ) )\n .append( $( '' ).append( parameter.title ) ) )\n });\n this.$cover[ this.model.get( 'enabled' ) && 'hide' || 'show' ]();\n }\n });\n});\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/upload/upload-settings.js","/*\n galaxy upload plugins - requires FormData and XMLHttpRequest\n*/\n;(function($){\n // add event properties\n jQuery.event.props.push(\"dataTransfer\");\n\n /**\n Posts file data to the API\n */\n $.uploadpost = function (config) {\n // parse options\n var cnf = $.extend({}, {\n data : {},\n success : function() {},\n error : function() {},\n progress : function() {},\n url : null,\n maxfilesize : 2048,\n error_filesize : 'File exceeds 2GB. Please use a FTP client.',\n error_default : 'Please make sure the file is available.',\n error_server : 'Upload request failed.',\n error_login : 'Uploads require you to log in.'\n }, config);\n\n // link data\n var data = cnf.data;\n\n // check errors\n if (data.error_message) {\n cnf.error(data.error_message);\n return;\n }\n\n // construct form data\n var form = new FormData();\n for (var key in data.payload) {\n form.append(key, data.payload[key]);\n }\n\n // add files to submission\n var sizes = 0;\n for (var key in data.files) {\n var d = data.files[key];\n form.append(d.name, d.file, d.file.name);\n sizes += d.file.size;\n }\n\n // check file size, unless it's an ftp file\n if (sizes > 1048576 * cnf.maxfilesize) {\n cnf.error(cnf.error_filesize);\n return;\n }\n\n // prepare request\n xhr = new XMLHttpRequest();\n xhr.open('POST', cnf.url, true);\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.setRequestHeader('Cache-Control', 'no-cache');\n xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n\n // captures state changes\n xhr.onreadystatechange = function() {\n // check for request completed, server connection closed\n if (xhr.readyState == xhr.DONE) {\n // parse response\n var response = null;\n if (xhr.responseText) {\n try {\n response = jQuery.parseJSON(xhr.responseText);\n } catch (e) {\n response = xhr.responseText;\n }\n }\n // pass any error to the error option\n if (xhr.status < 200 || xhr.status > 299) {\n var text = xhr.statusText;\n if (xhr.status == 403) {\n text = cnf.error_login;\n } else if (xhr.status == 0) {\n text = cnf.error_server;\n } else if (!text) {\n text = cnf.error_default;\n }\n cnf.error(text + ' (' + xhr.status + ')');\n } else {\n cnf.success(response);\n }\n }\n }\n\n // prepare upload progress\n xhr.upload.addEventListener('progress', function(e) {\n if (e.lengthComputable) {\n cnf.progress(Math.round((e.loaded * 100) / e.total));\n }\n }, false);\n\n // send request\n Galaxy.emit.debug('uploadbox::uploadpost()', 'Posting following data.', cnf);\n xhr.send(form);\n }\n\n /**\n Handles the upload events drag/drop etc.\n */\n $.fn.uploadinput = function(options) {\n // initialize\n var el = this;\n var opts = $.extend({}, {\n ondragover : function() {},\n ondragleave : function() {},\n onchange : function() {},\n multiple : false\n }, options);\n\n // append hidden upload field\n var $input = $('');\n el.append($input.change(function (e) {\n opts.onchange(e.target.files);\n $(this).val('');\n }));\n\n // drag/drop events\n el.on('drop', function (e) {\n opts.ondragleave(e);\n if(e.dataTransfer) {\n opts.onchange(e.dataTransfer.files);\n e.preventDefault();\n }\n });\n el.on('dragover', function (e) {\n e.preventDefault();\n opts.ondragover(e);\n });\n el.on('dragleave', function (e) {\n e.stopPropagation();\n opts.ondragleave(e);\n });\n\n // exports\n return {\n dialog: function () {\n $input.trigger('click');\n }\n }\n }\n\n /**\n Handles the upload queue and events such as drag/drop etc.\n */\n $.fn.uploadbox = function(options) {\n // parse options\n var opts = $.extend({}, {\n dragover : function() {},\n dragleave : function() {},\n announce : function(d) {},\n initialize : function(d) {},\n progress : function(d, m) {},\n success : function(d, m) {},\n error : function(d, m) { alert(m); },\n complete : function() {}\n }, options);\n\n // file queue\n var queue = {};\n\n // queue index/length counter\n var queue_index = 0;\n var queue_length = 0;\n\n // indicates if queue is currently running\n var queue_running = false;\n var queue_stop = false;\n\n // element\n var uploadinput = $(this).uploadinput({\n multiple : true,\n onchange : function(files) { add(files); },\n ondragover : options.ondragover,\n ondragleave : options.ondragleave\n });\n\n // add new files to upload queue\n function add(files) {\n if (files && files.length && !queue_running) {\n var current_index = queue_index;\n _.each(files, function(file, key) {\n if (file.mode !== 'new' && _.filter(queue, function(f) {\n return f.name === file.name && f.size === file.size;\n }).length) {\n file.duplicate = true;\n }\n });\n _.each(files, function(file) {\n if (!file.duplicate) {\n var index = String(queue_index++);\n queue[index] = file;\n opts.announce(index, queue[index]);\n queue_length++;\n }\n });\n return current_index;\n }\n }\n\n // remove file from queue\n function remove(index) {\n if (queue[index]) {\n delete queue[index];\n queue_length--;\n }\n }\n\n // process an upload, recursive\n function process() {\n // validate\n if (queue_length == 0 || queue_stop) {\n queue_stop = false;\n queue_running = false;\n opts.complete();\n return;\n } else {\n queue_running = true;\n }\n\n // get an identifier from the queue\n var index = -1;\n for (var key in queue) {\n index = key;\n break;\n }\n\n // get current file from queue\n var file = queue[index];\n\n // remove from queue\n remove(index)\n\n // create and submit data\n $.uploadpost({\n url : opts.url,\n data : opts.initialize(index),\n success : function(message) { opts.success(index, message); process();},\n error : function(message) { opts.error(index, message); process();},\n progress : function(percentage) { opts.progress(index, percentage); }\n });\n }\n\n /*\n public interface\n */\n\n // open file browser for selection\n function select() {\n uploadinput.dialog();\n }\n\n // remove all entries from queue\n function reset(index) {\n for (index in queue) {\n remove(index);\n }\n }\n\n // initiate upload process\n function start() {\n if (!queue_running) {\n queue_running = true;\n process();\n }\n }\n\n // stop upload process\n function stop() {\n queue_stop = true;\n }\n\n // set options\n function configure(options) {\n opts = $.extend({}, opts, options);\n return opts;\n }\n\n // verify browser compatibility\n function compatible() {\n return window.File && window.FormData && window.XMLHttpRequest && window.FileList;\n }\n\n // export functions\n return {\n 'select' : select,\n 'add' : add,\n 'remove' : remove,\n 'start' : start,\n 'stop' : stop,\n 'reset' : reset,\n 'configure' : configure,\n 'compatible' : compatible\n };\n }\n})(jQuery);\n\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/utils/uploadbox.js","define([\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function( baseMVC, _l ){\n// =============================================================================\n/** A view on any model that has a 'annotation' attribute\n */\nvar AnnotationEditor = Backbone.View\n .extend( baseMVC.LoggableMixin )\n .extend( baseMVC.HiddenUntilActivatedViewMixin ).extend({\n\n tagName : 'div',\n className : 'annotation-display',\n\n /** Set up listeners, parse options */\n initialize : function( options ){\n options = options || {};\n this.tooltipConfig = options.tooltipConfig || { placement: 'bottom' };\n //console.debug( this, options );\n // only listen to the model only for changes to annotations\n this.listenTo( this.model, 'change:annotation', function(){\n this.render();\n });\n this.hiddenUntilActivated( options.$activator, options );\n },\n\n /** Build the DOM elements, call select to on the created input, and set up behaviors */\n render : function(){\n var view = this;\n this.$el.html( this._template() );\n\n //TODO: handle empties better\n this.$annotation().make_text_editable({\n use_textarea: true,\n on_finish: function( newAnnotation ){\n view.$annotation().text( newAnnotation );\n view.model.save({ annotation: newAnnotation }, { silent: true })\n .fail( function(){\n view.$annotation().text( view.model.previous( 'annotation' ) );\n });\n }\n });\n return this;\n },\n\n /** @returns {String} the html text used to build the view's DOM */\n _template : function(){\n var annotation = this.model.get( 'annotation' );\n return [\n //TODO: make prompt optional\n '',\n // set up initial tags by adding as CSV to input vals (necc. to init select2)\n '
                                              ',\n _.escape( annotation ),\n '
                                              '\n ].join( '' );\n },\n\n /** @returns {jQuery} the main element for this view */\n $annotation : function(){\n return this.$el.find( '.annotation' );\n },\n\n /** shut down event listeners and remove this view's DOM */\n remove : function(){\n this.$annotation.off();\n this.stopListening( this.model );\n Backbone.View.prototype.remove.call( this );\n },\n\n /** string rep */\n toString : function(){ return [ 'AnnotationEditor(', this.model + '', ')' ].join(''); }\n});\n// =============================================================================\nreturn {\n AnnotationEditor : AnnotationEditor\n};\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/annotation.js","define([\n 'libs/underscore',\n 'libs/backbone',\n 'mvc/base-mvc',\n], function( _, Backbone, BASE_MVC ){\n'use strict';\n\n//=============================================================================\n/**\n * A Collection that can be limited/offset/re-ordered/filtered.\n * @type {Backbone.Collection}\n */\nvar ControlledFetchCollection = Backbone.Collection.extend({\n\n /** call setOrder on initialization to build the comparator based on options */\n initialize : function( models, options ){\n Backbone.Collection.prototype.initialize.call( this, models, options );\n this.setOrder( options.order || this.order, { silent: true });\n },\n\n /** set up to track order changes and re-sort when changed */\n _setUpListeners : function(){\n return this.on({\n 'changed-order' : this.sort\n });\n },\n\n /** override to provide order and offsets based on instance vars, set limit if passed,\n * and set allFetched/fire 'all-fetched' when xhr returns\n */\n fetch : function( options ){\n options = this._buildFetchOptions( options );\n // console.log( 'fetch options:', options );\n return Backbone.Collection.prototype.fetch.call( this, options );\n },\n\n /** build ajax data/parameters from options */\n _buildFetchOptions : function( options ){\n // note: we normally want options passed in to override the defaults built here\n // so most of these fns will generate defaults\n options = _.clone( options ) || {};\n var self = this;\n\n // jquery ajax option; allows multiple q/qv for filters (instead of 'q[]')\n options.traditional = true;\n\n // options.data\n // we keep limit, offset, etc. in options *as well as move it into data* because:\n // - it makes fetch calling convenient to add it to a single options map (instead of as mult. args)\n // - it allows the std. event handlers (for fetch, etc.) to have access\n // to the pagination options too\n // (i.e. this.on( 'sync', function( options ){ if( options.limit ){ ... } }))\n // however, when we send to xhr/jquery we copy them to data also so that they become API query params\n options.data = options.data || self._buildFetchData( options );\n // console.log( 'data:', options.data );\n\n // options.data.filters --> options.data.q, options.data.qv\n var filters = this._buildFetchFilters( options );\n // console.log( 'filters:', filters );\n if( !_.isEmpty( filters ) ){\n _.extend( options.data, this._fetchFiltersToAjaxData( filters ) );\n }\n // console.log( 'data:', options.data );\n return options;\n },\n\n /** Build the dictionary to send to fetch's XHR as data */\n _buildFetchData : function( options ){\n var defaults = {};\n if( this.order ){ defaults.order = this.order; }\n return _.defaults( _.pick( options, this._fetchParams ), defaults );\n },\n\n /** These attribute keys are valid params to fetch/API-index */\n _fetchParams : [\n /** model dependent string to control the order of models returned */\n 'order',\n /** limit the number of models returned from a fetch */\n 'limit',\n /** skip this number of models when fetching */\n 'offset',\n /** what series of attributes to return (model dependent) */\n 'view',\n /** individual keys to return for the models (see api/histories.index) */\n 'keys'\n ],\n\n /** add any needed filters here based on collection state */\n _buildFetchFilters : function( options ){\n // override\n return _.clone( options.filters || {} );\n },\n\n /** Convert dictionary filters to qqv style arrays */\n _fetchFiltersToAjaxData : function( filters ){\n // return as a map so ajax.data can extend from it\n var filterMap = {\n q : [],\n qv : []\n };\n _.each( filters, function( v, k ){\n // don't send if filter value is empty\n if( v === undefined || v === '' ){ return; }\n // json to python\n if( v === true ){ v = 'True'; }\n if( v === false ){ v = 'False'; }\n if( v === null ){ v = 'None'; }\n // map to k/v arrays (q/qv)\n filterMap.q.push( k );\n filterMap.qv.push( v );\n });\n return filterMap;\n },\n\n /** override to reset allFetched flag to false */\n reset : function( models, options ){\n this.allFetched = false;\n return Backbone.Collection.prototype.reset.call( this, models, options );\n },\n\n // ........................................................................ order\n order : null,\n\n /** @type {Object} map of collection available sorting orders containing comparator fns */\n comparators : {\n 'update_time' : BASE_MVC.buildComparator( 'update_time', { ascending: false }),\n 'update_time-asc' : BASE_MVC.buildComparator( 'update_time', { ascending: true }),\n 'create_time' : BASE_MVC.buildComparator( 'create_time', { ascending: false }),\n 'create_time-asc' : BASE_MVC.buildComparator( 'create_time', { ascending: true }),\n },\n\n /** set the order and comparator for this collection then sort with the new order\n * @event 'changed-order' passed the new order and the collection\n */\n setOrder : function( order, options ){\n options = options || {};\n var collection = this;\n var comparator = collection.comparators[ order ];\n if( _.isUndefined( comparator ) ){ throw new Error( 'unknown order: ' + order ); }\n // if( _.isUndefined( comparator ) ){ return; }\n if( comparator === collection.comparator ){ return; }\n\n var oldOrder = collection.order;\n collection.order = order;\n collection.comparator = comparator;\n\n if( !options.silent ){\n collection.trigger( 'changed-order', options );\n }\n return collection;\n },\n\n});\n\n\n//=============================================================================\n/**\n *\n */\nvar PaginatedCollection = ControlledFetchCollection.extend({\n\n /** @type {Number} limit used for each page's fetch */\n limitPerPage : 500,\n\n initialize : function( models, options ){\n ControlledFetchCollection.prototype.initialize.call( this, models, options );\n this.currentPage = options.currentPage || 0;\n },\n\n getTotalItemCount : function(){\n return this.length;\n },\n\n shouldPaginate : function(){\n return this.getTotalItemCount() >= this.limitPerPage;\n },\n\n getLastPage : function(){\n return Math.floor( this.getTotalItemCount() / this.limitPerPage );\n },\n\n getPageCount : function(){\n return this.getLastPage() + 1;\n },\n\n getPageLimitOffset : function( pageNum ){\n pageNum = this.constrainPageNum( pageNum );\n return {\n limit : this.limitPerPage,\n offset: pageNum * this.limitPerPage\n };\n },\n\n constrainPageNum : function( pageNum ){\n return Math.max( 0, Math.min( pageNum, this.getLastPage() ));\n },\n\n /** fetch the next page of data */\n fetchPage : function( pageNum, options ){\n var self = this;\n pageNum = self.constrainPageNum( pageNum );\n self.currentPage = pageNum;\n options = _.defaults( options || {}, self.getPageLimitOffset( pageNum ) );\n\n self.trigger( 'fetching-more' );\n return self.fetch( options )\n .always( function(){\n self.trigger( 'fetching-more-done' );\n });\n },\n\n fetchCurrentPage : function( options ){\n return this.fetchPage( this.currentPage, options );\n },\n\n fetchPrevPage : function( options ){\n return this.fetchPage( this.currentPage - 1, options );\n },\n\n fetchNextPage : function( options ){\n return this.fetchPage( this.currentPage + 1, options );\n },\n});\n\n\n//=============================================================================\n/**\n * A Collection that will load more elements without reseting.\n */\nvar InfinitelyScrollingCollection = ControlledFetchCollection.extend({\n\n /** @type {Number} limit used for the first fetch (or a reset) */\n limitOnFirstFetch : null,\n /** @type {Number} limit used for each subsequent fetch */\n limitPerFetch : 100,\n\n initialize : function( models, options ){\n ControlledFetchCollection.prototype.initialize.call( this, models, options );\n /** @type {Integer} number of contents to return from the first fetch */\n this.limitOnFirstFetch = options.limitOnFirstFetch || this.limitOnFirstFetch;\n /** @type {Integer} limit for every fetch after the first */\n this.limitPerFetch = options.limitPerFetch || this.limitPerFetch;\n /** @type {Boolean} are all contents fetched? */\n this.allFetched = false;\n /** @type {Integer} what was the offset of the last content returned */\n this.lastFetched = options.lastFetched || 0;\n },\n\n /** build ajax data/parameters from options */\n _buildFetchOptions : function( options ){\n // options (options for backbone.fetch and jquery.ajax generally)\n // backbone option; false here to make fetching an addititive process\n options.remove = options.remove || false;\n return ControlledFetchCollection.prototype._buildFetchOptions.call( this, options );\n },\n\n /** fetch the first 'page' of data */\n fetchFirst : function( options ){\n // console.log( 'ControlledFetchCollection.fetchFirst:', options );\n options = options? _.clone( options ) : {};\n this.allFetched = false;\n this.lastFetched = 0;\n return this.fetchMore( _.defaults( options, {\n reset : true,\n limit : this.limitOnFirstFetch,\n }));\n },\n\n /** fetch the next page of data */\n fetchMore : function( options ){\n // console.log( 'ControlledFetchCollection.fetchMore:', options );\n options = _.clone( options || {} );\n var collection = this;\n\n // console.log( 'fetchMore, options.reset:', options.reset );\n if( ( !options.reset && collection.allFetched ) ){\n return jQuery.when();\n }\n\n // TODO: this fails in the edge case where\n // the first fetch offset === limit (limit 4, offset 4, collection.length 4)\n options.offset = options.reset? 0 : ( options.offset || collection.lastFetched );\n var limit = options.limit = options.limit || collection.limitPerFetch || null;\n // console.log( 'fetchMore, limit:', limit, 'offset:', options.offset );\n\n collection.trigger( 'fetching-more' );\n return collection.fetch( options )\n .always( function(){\n collection.trigger( 'fetching-more-done' );\n })\n // maintain allFetched flag and trigger if all were fetched this time\n .done( function _postFetchMore( fetchedData ){\n var numFetched = _.isArray( fetchedData )? fetchedData.length : 0;\n collection.lastFetched += numFetched;\n // console.log( 'fetchMore, lastFetched:', collection.lastFetched );\n // anything less than a full page means we got all there is to get\n if( !limit || numFetched < limit ){\n collection.allFetched = true;\n collection.trigger( 'all-fetched', this );\n }\n }\n );\n },\n\n /** fetch all the collection */\n fetchAll : function( options ){\n // whitelist options to prevent allowing limit/offset/filters\n // (use vanilla fetch instead)\n options = options || {};\n var self = this;\n options = _.pick( options, 'silent' );\n options.filters = {};\n return self.fetch( options ).done( function( fetchData ){\n self.allFetched = true;\n self.trigger( 'all-fetched', self );\n });\n },\n});\n\n\n//==============================================================================\n return {\n ControlledFetchCollection : ControlledFetchCollection,\n PaginatedCollection : PaginatedCollection,\n InfinitelyScrollingCollection : InfinitelyScrollingCollection,\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/base/controlled-fetch-collection.js","define([\n], function( ){\n\n/* For presentation-related functionality shared across collection creators.\n Particularily overlapping functionality related to name processing and help.\n*/\nvar CollectionCreatorMixin = {\n\n /** add (or clear if clear is truthy) a validation warning to the DOM element described in what */\n _validationWarning : function( what, clear ){\n var VALIDATION_CLASS = 'validation-warning';\n if( what === 'name' ){\n what = this.$( '.collection-name' ).add( this.$( '.collection-name-prompt' ) );\n this.$( '.collection-name' ).focus().select();\n }\n if( clear ){\n what = what || this.$( '.' + VALIDATION_CLASS );\n what.removeClass( VALIDATION_CLASS );\n } else {\n what.addClass( VALIDATION_CLASS );\n }\n },\n\n _changeHideOriginals: function( ev ) {\n this.hideOriginals = this.$( '.hide-originals' ).prop(\"checked\");\n },\n\n // ........................................................................ footer\n /** handle a collection name change */\n _changeName : function( ev ){\n this._validationWarning( 'name', !!this._getName() );\n },\n\n /** check for enter key press when in the collection name and submit */\n _nameCheckForEnter : function( ev ){\n if( ev.keyCode === 13 && !this.blocking ){\n this._clickCreate();\n }\n },\n\n /** get the current collection name */\n _getName : function(){\n return _.escape( this.$( '.collection-name' ).val() );\n },\n\n // ........................................................................ header\n /** expand help */\n _clickMoreHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).addClass( 'expanded' );\n this.$( '.more-help' ).hide();\n },\n /** collapse help */\n _clickLessHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).removeClass( 'expanded' );\n this.$( '.more-help' ).show();\n },\n /** toggle help */\n _toggleHelp : function( ev ){\n ev.stopPropagation();\n this.$( '.main-help' ).toggleClass( 'expanded' );\n this.$( '.more-help' ).toggle();\n },\n\n /** show an alert on the top of the interface containing message (alertClass is bootstrap's alert-*) */\n _showAlert : function( message, alertClass ){\n alertClass = alertClass || 'alert-danger';\n this.$( '.main-help' ).hide();\n this.$( '.header .alert' )\n .attr( 'class', 'alert alert-dismissable' ).addClass( alertClass ).show()\n .find( '.alert-message' ).html( message );\n },\n /** hide the alerts at the top */\n _hideAlert : function( message ){\n this.$( '.main-help' ).show();\n this.$( '.header .alert' ).hide();\n },\n\n _cancelCreate: function( ev ){\n if( typeof this.oncancel === 'function' ){\n this.oncancel.call( this );\n }\n },\n\n /** attempt to create the current collection */\n _clickCreate : function( ev ){\n var name = this._getName();\n if( !name ){\n this._validationWarning( 'name' );\n } else if( !this.blocking ){\n this.createList( name );\n }\n },\n\n _setUpCommonSettings : function( attributes ) {\n this.hideOriginals = attributes.defaultHideSourceItems || false;\n },\n\n /** render the footer, completion controls, and cancel controls */\n _renderFooter : function( speed, callback ){\n var instance = this;\n var $footer = this.$( '.footer' ).empty().html( this.templates.footer() );\n _.each( this.footerSettings, function( property, selector ) {\n this.$( selector ).prop( 'checked', instance[ property ] );\n });\n if( typeof this.oncancel === 'function' ){\n this.$( '.cancel-create.btn' ).show();\n }\n return $footer;\n },\n\n _creatorTemplates: {\n main : _.template([\n '
                                              ',\n '
                                              ',\n '
                                              '\n ].join('')),\n }\n\n}\n\n//==============================================================================\n return {\n CollectionCreatorMixin: CollectionCreatorMixin\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/base-creator.js","define([\n \"mvc/list/list-view\",\n \"mvc/collection/collection-model\",\n \"mvc/collection/collection-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_VIEW, DC_MODEL, DC_LI, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class non-editable, read-only View/Controller for a dataset collection.\n */\nvar _super = LIST_VIEW.ModelListPanel;\nvar CollectionView = _super.extend(\n/** @lends CollectionView.prototype */{\n //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n _logNamespace : logNamespace,\n\n className : _super.prototype.className + ' dataset-collection-panel',\n\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_LI.DatasetDCEListItemView,\n /** sub view class used for nested collections */\n NestedDCDCEViewClass: DC_LI.NestedDCDCEListItemView,\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'elements',\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n this.linkTarget = attributes.linkTarget || '_blank';\n\n this.hasUser = attributes.hasUser;\n /** A stack of panels that currently cover or hide this panel */\n this.panelStack = [];\n /** The text of the link to go back to the panel containing this one */\n this.parentName = attributes.parentName;\n /** foldout or drilldown */\n this.foldoutStyle = attributes.foldoutStyle || 'foldout';\n this.downloadUrl = this.model.attributes.url + '/download';\n },\n\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var panel = this;\n panel.log( '_queueNewRender:', $newRender, speed );\n\n // TODO: jquery@1.12 doesn't change display when the elem has display: flex\n // this causes display: block for those elems after the use of show/hide animations\n // animations are removed from this view for now until fixed\n panel._swapNewRender( $newRender );\n panel.trigger( 'rendered', panel );\n },\n\n // ------------------------------------------------------------------------ sub-views\n /** In this override, use model.getVisibleContents */\n _filterCollection : function(){\n //TODO: should *not* be model.getVisibleContents - visibility is not model related\n return this.model.getVisibleContents();\n },\n\n /** override to return proper view class based on element_type */\n _getItemViewClass : function( model ){\n //this.debug( this + '._getItemViewClass:', model );\n //TODO: subclasses use DCEViewClass - but are currently unused - decide\n switch( model.get( 'element_type' ) ){\n case 'hda':\n return this.DatasetDCEViewClass;\n case 'dataset_collection':\n return this.NestedDCDCEViewClass;\n }\n throw new TypeError( 'Unknown element type:', model.get( 'element_type' ) );\n },\n\n /** override to add link target and anon */\n _getItemViewOptions : function( model ){\n var options = _super.prototype._getItemViewOptions.call( this, model );\n return _.extend( options, {\n linkTarget : this.linkTarget,\n hasUser : this.hasUser,\n //TODO: could move to only nested: list:paired\n foldoutStyle : this.foldoutStyle\n });\n },\n\n // ------------------------------------------------------------------------ collection sub-views\n /** In this override, add/remove expanded/collapsed model ids to/from web storage */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n _super.prototype._setUpItemViewListeners.call( panel, view );\n\n // use pub-sub to: handle drilldown expansion and collapse\n panel.listenTo( view, {\n 'expanded:drilldown': function( v, drilldown ){\n this._expandDrilldownPanel( drilldown );\n },\n 'collapsed:drilldown': function( v, drilldown ){\n this._collapseDrilldownPanel( drilldown );\n }\n });\n return this;\n },\n\n /** Handle drill down by hiding this panels list and controls and showing the sub-panel */\n _expandDrilldownPanel : function( drilldown ){\n this.panelStack.push( drilldown );\n // hide this panel's controls and list, set the name for back navigation, and attach to the $el\n this.$( '> .controls' ).add( this.$list() ).hide();\n drilldown.parentName = this.model.get( 'name' );\n this.$el.append( drilldown.render().$el );\n },\n\n /** Handle drilldown close by freeing the panel and re-rendering this panel */\n _collapseDrilldownPanel : function( drilldown ){\n this.panelStack.pop();\n this.render();\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : {\n 'click .navigation .back' : 'close'\n },\n\n /** close/remove this collection panel */\n close : function( event ){\n this.remove();\n this.trigger( 'close' );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'CollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//------------------------------------------------------------------------------ TEMPLATES\nCollectionView.prototype.templates = (function(){\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                                              ',\n '',\n\n '
                                              ',\n '
                                              <%- collection.name || collection.element_identifier %>
                                              ',\n '
                                              ',\n '<% if( collection.collection_type === \"list\" ){ %>',\n _l( 'a list of datasets' ),\n '<% } else if( collection.collection_type === \"paired\" ){ %>',\n _l( 'a pair of datasets' ),\n '<% } else if( collection.collection_type === \"list:paired\" ){ %>',\n _l( 'a list of paired datasets' ),\n '<% } else if( collection.collection_type === \"list:list\" ){ %>',\n _l( 'a list of dataset lists' ),\n '<% } %>',\n '
                                              ',\n '
                                              ',\n\n '
                                              ',\n\n '',\n '
                                              ',\n ], 'collection' );\n\n return _.extend( _.clone( _super.prototype.templates ), {\n controls : controlsTemplate\n });\n}());\n\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListCollectionView = CollectionView.extend(\n/** @lends ListCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_LI.DatasetDCEListItemView,\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar PairCollectionView = ListCollectionView.extend(\n/** @lends PairCollectionView.prototype */{\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'PairCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListOfPairsCollectionView = CollectionView.extend(\n/** @lends ListOfPairsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_LI.NestedDCDCEListItemView.extend({\n foldoutPanelClass : PairCollectionView\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfPairsCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a list of lists dataset collection. */\nvar ListOfListsCollectionView = CollectionView.extend({\n\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_LI.NestedDCDCEListItemView.extend({\n foldoutPanelClass : PairCollectionView\n }),\n\n /** string rep */\n toString : function(){\n return 'ListOfListsCollectionView(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//==============================================================================\n return {\n CollectionView : CollectionView,\n ListCollectionView : ListCollectionView,\n PairCollectionView : PairCollectionView,\n ListOfPairsCollectionView : ListOfPairsCollectionView,\n ListOfListsCollectionView : ListOfListsCollectionView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-view.js","define([\n \"mvc/dataset/states\",\n \"mvc/dataset/dataset-li\",\n \"mvc/tag\",\n \"mvc/annotation\",\n \"ui/fa-icon-button\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, DATASET_LI, TAGS, ANNOTATIONS, faIconButton, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar _super = DATASET_LI.DatasetListItemView;\n/** @class Editing view for DatasetAssociation.\n */\nvar DatasetListItemEdit = _super.extend(\n/** @lends DatasetListItemEdit.prototype */{\n\n /** set up: options */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n this.hasUser = attributes.hasUser;\n\n /** allow user purge of dataset files? */\n this.purgeAllowed = attributes.purgeAllowed || false;\n\n //TODO: move to HiddenUntilActivatedViewMixin\n /** should the tags editor be shown or hidden initially? */\n this.tagsEditorShown = attributes.tagsEditorShown || false;\n /** should the tags editor be shown or hidden initially? */\n this.annotationEditorShown = attributes.annotationEditorShown || false;\n },\n\n // ......................................................................... titlebar actions\n /** In this override, add the other two primary actions: edit and delete */\n _renderPrimaryActions : function(){\n var actions = _super.prototype._renderPrimaryActions.call( this );\n if( this.model.get( 'state' ) === STATES.NOT_VIEWABLE ){\n return actions;\n }\n // render the display, edit attr and delete icon-buttons\n return _super.prototype._renderPrimaryActions.call( this ).concat([\n this._renderEditButton(),\n this._renderDeleteButton()\n ]);\n },\n\n //TODO: move titleButtons into state renderers, remove state checks in the buttons\n\n /** Render icon-button to edit the attributes (format, permissions, etc.) this dataset. */\n _renderEditButton : function(){\n // don't show edit while uploading, in-accessible\n // DO show if in error (ala previous history panel)\n if( ( this.model.get( 'state' ) === STATES.DISCARDED )\n || ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var purged = this.model.get( 'purged' ),\n deleted = this.model.get( 'deleted' ),\n editBtnData = {\n title : _l( 'Edit attributes' ),\n href : Galaxy.root + 'datasets/edit?dataset_id=' + this.model.attributes.id,\n faIcon : 'fa-pencil',\n classes : 'edit-btn'\n };\n // disable if purged or deleted and explain why in the tooltip\n if( deleted || purged ){\n editBtnData.disabled = true;\n if( purged ){\n editBtnData.title = _l( 'Cannot edit attributes of datasets removed from disk' );\n } else if( deleted ){\n editBtnData.title = _l( 'Undelete dataset to edit attributes' );\n }\n\n // disable if still uploading or new\n } else if( _.contains( [ STATES.UPLOAD, STATES.NEW ], this.model.get( 'state' ) ) ){\n editBtnData.disabled = true;\n editBtnData.title = _l( 'This dataset is not yet editable' );\n }\n return faIconButton( editBtnData );\n },\n\n /** Render icon-button to delete this hda. */\n _renderDeleteButton : function(){\n // don't show delete if...\n if( ( !this.model.get( 'accessible' ) ) ){\n return null;\n }\n\n var self = this,\n deletedAlready = this.model.isDeletedOrPurged();\n return faIconButton({\n title : !deletedAlready? _l( 'Delete' ) : _l( 'Dataset is already deleted' ),\n disabled : deletedAlready,\n faIcon : 'fa-times',\n classes : 'delete-btn',\n onclick : function() {\n // ...bler... tooltips being left behind in DOM (hover out never called on deletion)\n self.$el.find( '.icon-btn.delete-btn' ).trigger( 'mouseout' );\n self.model[ 'delete' ]();\n }\n });\n },\n\n // ......................................................................... details\n /** In this override, add tags and annotations controls, make the ? dbkey a link to editing page */\n _renderDetails : function(){\n //TODO: generalize to be allow different details for each state\n var $details = _super.prototype._renderDetails.call( this ),\n state = this.model.get( 'state' );\n\n if( !this.model.isDeletedOrPurged() && _.contains([ STATES.OK, STATES.FAILED_METADATA ], state ) ){\n this._renderTags( $details );\n this._renderAnnotation( $details );\n this._makeDbkeyEditLink( $details );\n }\n\n this._setUpBehaviors( $details );\n return $details;\n },\n\n /**************************************************************************\n * Render help button to show tool help text without rerunning the tool.\n * Issue #2100\n */\n _renderToolHelpButton : function() {\n var datasetID = this.model.attributes.dataset_id;\n var jobID = this.model.attributes.creating_job;\n var self = this;\n\n var parseToolBuild = function(data) {\n var helpString = '
                                              '\n if (data.name && data.help){\n helpString += 'Tool help for ' + data.name + '
                                              ';\n helpString += data.help;\n } else {\n helpString += 'Tool help is unavailable for this dataset.
                                              ';\n }\n helpString += '
                                              ';\n self.$el.find( '.details' ).append($.parseHTML(helpString));\n };\n var parseToolID = function(data) {\n $.ajax({\n url: Galaxy.root + 'api/tools/' + data.tool_id + '/build'\n }).done(function(data){\n parseToolBuild(data);\n }).fail(function(){\n parseToolBuild({})\n });\n };\n if (Galaxy.user.id === null){\n return null\n }\n return faIconButton({\n title: _l('Tool Help'),\n classes: 'icon-btn',\n href: '#',\n faIcon: 'fa-question',\n onclick: function() {\n var divString = 'thdiv-' + datasetID;\n if (self.$el.find(\".toolhelp\").length > 0){\n self.$el.find(\".toolhelp\").toggle();\n } else {\n $.ajax({\n url: Galaxy.root + 'api/jobs/' + jobID\n }).done(function(data){\n parseToolID(data);\n }).fail(function(){\n console.log('Failed at recovering job information from the Galaxy API for job id \"' + jobID + '\".');\n });\n }\n }\n });\n },\n //*************************************************************************\n\n /** Add less commonly used actions in the details section based on state */\n _renderSecondaryActions : function(){\n var actions = _super.prototype._renderSecondaryActions.call( this );\n switch( this.model.get( 'state' ) ){\n case STATES.UPLOAD:\n case STATES.NOT_VIEWABLE:\n return actions;\n case STATES.ERROR:\n // error button comes first\n actions.unshift( this._renderErrButton() );\n return actions.concat([ this._renderRerunButton(), this._renderToolHelpButton() ]);\n case STATES.OK:\n case STATES.FAILED_METADATA:\n return actions.concat([ this._renderRerunButton(), this._renderVisualizationsButton(), this._renderToolHelpButton() ]);\n }\n return actions.concat([ this._renderRerunButton(), this._renderToolHelpButton() ]);\n },\n\n /** Render icon-button to report an error on this dataset to the galaxy admin. */\n _renderErrButton : function(){\n return faIconButton({\n title : _l( 'View or report this error' ),\n href : Galaxy.root + 'datasets/error?dataset_id=' + this.model.attributes.id,\n classes : 'report-error-btn',\n faIcon : 'fa-bug'\n });\n },\n\n /** Render icon-button to re-run the job that created this dataset. */\n _renderRerunButton : function(){\n var creating_job = this.model.get( 'creating_job' );\n if( this.model.get( 'rerunnable' ) ){\n return faIconButton({\n title : _l( 'Run this job again' ),\n href : this.model.urls.rerun,\n classes : 'rerun-btn',\n target : this.linkTarget,\n faIcon : 'fa-refresh',\n onclick : function( ev ) {\n ev.preventDefault();\n Galaxy.router.push( '/', { job_id : creating_job } );\n }\n });\n }\n },\n\n /** Render an icon-button or popupmenu of links based on the applicable visualizations */\n _renderVisualizationsButton : function(){\n //TODO: someday - lazyload visualizations\n var visualizations = this.model.get( 'visualizations' );\n if( ( this.model.isDeletedOrPurged() )\n || ( !this.hasUser )\n || ( !this.model.hasData() )\n || ( _.isEmpty( visualizations ) ) ){\n return null;\n }\n if( !_.isObject( visualizations[0] ) ){\n this.warn( 'Visualizations have been switched off' );\n return null;\n }\n\n var $visualizations = $( this.templates.visualizations( visualizations, this ) );\n //HACK: need to re-write those directed at galaxy_main with linkTarget\n $visualizations.find( '[target=\"galaxy_main\"]').attr( 'target', this.linkTarget );\n // use addBack here to include the root $visualizations elem (for the case of 1 visualization)\n this._addScratchBookFn( $visualizations.find( '.visualization-link' ).addBack( '.visualization-link' ) );\n return $visualizations;\n },\n\n /** add scratchbook functionality to visualization links */\n _addScratchBookFn : function( $links ){\n var li = this;\n $links.click( function( ev ){\n if( Galaxy.frame && Galaxy.frame.active ){\n Galaxy.frame.add({\n title : 'Visualization',\n url : $( this ).attr( 'href' )\n });\n ev.preventDefault();\n ev.stopPropagation();\n }\n });\n },\n\n //TODO: if possible move these to readonly view - but display the owner's tags/annotation (no edit)\n /** Render the tags list/control */\n _renderTags : function( $where ){\n if( !this.hasUser ){ return; }\n var view = this;\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n // persist state on the hda view (and not the editor) since these are currently re-created each time\n onshow : function(){ view.tagsEditorShown = true; },\n onhide : function(){ view.tagsEditorShown = false; },\n $activator : faIconButton({\n title : _l( 'Edit dataset tags' ),\n classes : 'tag-btn',\n faIcon : 'fa-tags'\n }).appendTo( $where.find( '.actions .right' ) )\n });\n if( this.tagsEditorShown ){ this.tagsEditor.toggle( true ); }\n },\n\n /** Render the annotation display/control */\n _renderAnnotation : function( $where ){\n if( !this.hasUser ){ return; }\n var view = this;\n this.annotationEditor = new ANNOTATIONS.AnnotationEditor({\n model : this.model,\n el : $where.find( '.annotation-display' ),\n onshowFirstTime : function(){ this.render(); },\n // persist state on the hda view (and not the editor) since these are currently re-created each time\n onshow : function(){ view.annotationEditorShown = true; },\n onhide : function(){ view.annotationEditorShown = false; },\n $activator : faIconButton({\n title : _l( 'Edit dataset annotation' ),\n classes : 'annotate-btn',\n faIcon : 'fa-comment'\n }).appendTo( $where.find( '.actions .right' ) )\n });\n if( this.annotationEditorShown ){ this.annotationEditor.toggle( true ); }\n },\n\n /** If the format/dbkey/genome_build isn't set, make the display a link to the edit page */\n _makeDbkeyEditLink : function( $details ){\n // make the dbkey a link to editing\n if( this.model.get( 'metadata_dbkey' ) === '?'\n && !this.model.isDeletedOrPurged() ){\n var editableDbkey = $( '?' )\n .attr( 'href', this.model.urls.edit )\n .attr( 'target', this.linkTarget );\n $details.find( '.dbkey .value' ).replaceWith( editableDbkey );\n }\n },\n\n // ......................................................................... events\n /** event map */\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .undelete-link' : '_clickUndeleteLink',\n 'click .purge-link' : '_clickPurgeLink',\n\n 'click .edit-btn' : function( ev ){ this.trigger( 'edit', this, ev ); },\n 'click .delete-btn' : function( ev ){ this.trigger( 'delete', this, ev ); },\n 'click .rerun-btn' : function( ev ){ this.trigger( 'rerun', this, ev ); },\n 'click .report-err-btn' : function( ev ){ this.trigger( 'report-err', this, ev ); },\n 'click .visualization-btn' : function( ev ){ this.trigger( 'visualize', this, ev ); },\n 'click .dbkey a' : function( ev ){ this.trigger( 'edit', this, ev ); }\n }),\n\n /** listener for item undelete (in the messages section) */\n _clickUndeleteLink : function( ev ){\n this.model.undelete();\n return false;\n },\n\n /** listener for item purge (in the messages section) */\n _clickPurgeLink : function( ev ){\n if( confirm( _l( 'This will permanently remove the data in your dataset. Are you sure?' ) ) ){\n this.model.purge();\n }\n return false;\n },\n\n // ......................................................................... misc\n /** string rep */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAEditView(' + modelString + ')';\n }\n});\n\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetListItemEdit.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n failed_metadata : BASE_MVC.wrapTemplate([\n // in this override, provide a link to the edit page\n '<% if( dataset.state === \"failed_metadata\" ){ %>',\n '',\n '<% } %>'\n ], 'dataset' ),\n\n deleted : BASE_MVC.wrapTemplate([\n // in this override, provide links to undelete or purge the dataset\n '<% if( dataset.deleted && !dataset.purged ){ %>',\n // deleted not purged\n '
                                              ',\n _l( 'This dataset has been deleted' ),\n '
                                              ', _l( 'Undelete it' ), '',\n '<% if( view.purgeAllowed ){ %>',\n '
                                              ',\n _l( 'Permanently remove it from disk' ),\n '',\n '<% } %>',\n '
                                              ',\n '<% } %>'\n ], 'dataset' )\n });\n\n var visualizationsTemplate = BASE_MVC.wrapTemplate([\n '<% if( visualizations.length === 1 ){ %>',\n '\"',\n ' target=\"<%- visualizations[0].target %>\" title=\"', _l( 'Visualize in' ),\n ' <%- visualizations[0].html %>\">',\n '',\n '',\n\n '<% } else { %>',\n '
                                              ',\n '',\n '',\n '',\n '',\n '
                                              ',\n '<% } %>'\n ], 'visualizations' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n visualizations : visualizationsTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n DatasetListItemEdit : DatasetListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-li-edit.js","define([\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, BASE_MVC, _l ){\n'use strict';\n\nvar logNamespace = 'dataset';\n//==============================================================================\nvar searchableMixin = BASE_MVC.SearchableModelMixin;\n/** @class base model for any DatasetAssociation (HDAs, LDDAs, DatasetCollectionDAs).\n * No knowledge of what type (HDA/LDDA/DCDA) should be needed here.\n * The DA's are made searchable (by attribute) by mixing in SearchableModelMixin.\n */\nvar DatasetAssociation = Backbone.Model\n .extend( BASE_MVC.LoggableMixin )\n .extend( BASE_MVC.mixin( searchableMixin, /** @lends DatasetAssociation.prototype */{\n _logNamespace : logNamespace,\n\n /** default attributes for a model */\n defaults : {\n state : STATES.NEW,\n deleted : false,\n purged : false,\n name : '(unnamed dataset)',\n accessible : true,\n // sniffed datatype (sam, tabular, bed, etc.)\n data_type : '',\n file_ext : '',\n file_size : 0,\n\n // array of associated file types (eg. [ 'bam_index', ... ])\n meta_files : [],\n\n misc_blurb : '',\n misc_info : '',\n\n tags : []\n // do NOT default on annotation, as this default is valid and will be passed on 'save'\n // which is incorrect behavior when the model is only partially fetched (annos are not passed in summary data)\n //annotation : ''\n },\n\n /** instance vars and listeners */\n initialize : function( attributes, options ){\n this.debug( this + '(Dataset).initialize', attributes, options );\n\n //!! this state is not in trans.app.model.Dataset.states - set it here -\n if( !this.get( 'accessible' ) ){\n this.set( 'state', STATES.NOT_VIEWABLE );\n }\n\n /** Datasets rely/use some web controllers - have the model generate those URLs on startup */\n this.urls = this._generateUrls();\n\n this._setUpListeners();\n },\n\n /** returns misc. web urls for rendering things like re-run, display, etc. */\n _generateUrls : function(){\n var id = this.get( 'id' );\n if( !id ){ return {}; }\n var urls = {\n 'purge' : 'datasets/' + id + '/purge_async',\n 'display' : 'datasets/' + id + '/display/?preview=True',\n 'edit' : 'datasets/' + id + '/edit',\n 'download' : 'datasets/' + id + '/display' + this._downloadQueryParameters(),\n 'report_error' : 'dataset/errors?id=' + id,\n 'rerun' : 'tool_runner/rerun?id=' + id,\n 'show_params' : 'datasets/' + id + '/show_params',\n 'visualization' : 'visualization',\n 'meta_download' : 'dataset/get_metadata_file?hda_id=' + id + '&metadata_name='\n };\n _.each( urls, function( value, key ){\n urls[ key ] = Galaxy.root + value;\n });\n this.urls = urls;\n return urls;\n },\n\n _downloadQueryParameters : function() {\n return '?to_ext=' + this.get( 'file_ext' );\n },\n\n /** set up any event listeners\n * event: state:ready fired when this DA moves into/is already in a ready state\n */\n _setUpListeners : function(){\n // if the state has changed and the new state is a ready state, fire an event\n this.on( 'change:state', function( currModel, newState ){\n this.log( this + ' has changed state:', currModel, newState );\n if( this.inReadyState() ){\n this.trigger( 'state:ready', currModel, newState, this.previous( 'state' ) );\n }\n });\n // the download url (currently) relies on having a correct file extension\n this.on( 'change:id change:file_ext', function( currModel ){\n this._generateUrls();\n });\n },\n\n // ........................................................................ common queries\n /** override to add urls */\n toJSON : function(){\n var json = Backbone.Model.prototype.toJSON.call( this );\n //console.warn( 'returning json?' );\n //return json;\n return _.extend( json, {\n urls : this.urls\n });\n },\n\n /** Is this dataset deleted or purged? */\n isDeletedOrPurged : function(){\n return ( this.get( 'deleted' ) || this.get( 'purged' ) );\n },\n\n /** Is this dataset in a 'ready' state; where 'Ready' states are states where no\n * processing (for the ds) is left to do on the server.\n */\n inReadyState : function(){\n var ready = _.contains( STATES.READY_STATES, this.get( 'state' ) );\n return ( this.isDeletedOrPurged() || ready );\n },\n\n /** Does this model already contain detailed data (as opposed to just summary level data)? */\n hasDetails : function(){\n // if it's inaccessible assume it has everything it needs\n if( !this.get( 'accessible' ) ){ return true; }\n return this.has( 'annotation' );\n },\n\n /** Convenience function to match dataset.has_data. */\n hasData : function(){\n return ( this.get( 'file_size' ) > 0 );\n },\n\n // ........................................................................ ajax\n fetch : function( options ){\n var dataset = this;\n return Backbone.Model.prototype.fetch.call( this, options )\n .always( function(){\n dataset._generateUrls();\n });\n },\n\n /** override to use actual Dates objects for create/update times */\n parse : function( response, options ){\n var parsed = Backbone.Model.prototype.parse.call( this, response, options );\n if( parsed.create_time ){\n parsed.create_time = new Date( parsed.create_time );\n }\n if( parsed.update_time ){\n parsed.update_time = new Date( parsed.update_time );\n }\n return parsed;\n },\n\n /** override to wait by default */\n save : function( attrs, options ){\n options = options || {};\n options.wait = _.isUndefined( options.wait ) ? true : options.wait;\n return Backbone.Model.prototype.save.call( this, attrs, options );\n },\n\n //NOTE: subclasses of DA's will need to implement url and urlRoot in order to have these work properly\n /** save this dataset, _Mark_ing it as deleted (just a flag) */\n 'delete' : function( options ){\n if( this.get( 'deleted' ) ){ return jQuery.when(); }\n return this.save( { deleted: true }, options );\n },\n /** save this dataset, _Mark_ing it as undeleted */\n undelete : function( options ){\n if( !this.get( 'deleted' ) || this.get( 'purged' ) ){ return jQuery.when(); }\n return this.save( { deleted: false }, options );\n },\n\n /** remove the file behind this dataset from the filesystem (if permitted) */\n purge : function _purge( options ){\n //TODO: use, override model.destroy, HDA.delete({ purge: true })\n if( this.get( 'purged' ) ){ return jQuery.when(); }\n options = options || {};\n options.url = this.urls.purge;\n\n //TODO: ideally this would be a DELETE call to the api\n // using purge async for now\n var hda = this,\n xhr = jQuery.ajax( options );\n xhr.done( function( message, status, responseObj ){\n hda.set({ deleted: true, purged: true });\n });\n xhr.fail( function( xhr, status, message ){\n // Exception messages are hidden within error page including: '...not allowed in this Galaxy instance.'\n // unbury and re-add to xhr\n var error = _l( \"Unable to purge dataset\" );\n var messageBuriedInUnfortunatelyFormattedError = ( 'Removal of datasets by users '\n + 'is not allowed in this Galaxy instance' );\n if( xhr.responseJSON && xhr.responseJSON.error ){\n error = xhr.responseJSON.error;\n } else if( xhr.responseText.indexOf( messageBuriedInUnfortunatelyFormattedError ) !== -1 ){\n error = messageBuriedInUnfortunatelyFormattedError;\n }\n xhr.responseText = error;\n hda.trigger( 'error', hda, xhr, options, _l( error ), { error: error } );\n });\n return xhr;\n },\n\n // ........................................................................ searching\n /** what attributes of an HDA will be used in a text search */\n searchAttributes : [\n 'name', 'file_ext', 'genome_build', 'misc_blurb', 'misc_info', 'annotation', 'tags'\n ],\n\n /** our attr keys don't often match the labels we display to the user - so, when using\n * attribute specifiers ('name=\"bler\"') in a term, allow passing in aliases for the\n * following attr keys.\n */\n searchAliases : {\n title : 'name',\n format : 'file_ext',\n database : 'genome_build',\n blurb : 'misc_blurb',\n description : 'misc_blurb',\n info : 'misc_info',\n tag : 'tags'\n },\n\n // ........................................................................ misc\n /** String representation */\n toString : function(){\n var nameAndId = this.get( 'id' ) || '';\n if( this.get( 'name' ) ){\n nameAndId = '\"' + this.get( 'name' ) + '\",' + nameAndId;\n }\n return 'Dataset(' + nameAndId + ')';\n }\n}));\n\n\n//==============================================================================\n/** @class Backbone collection for dataset associations.\n */\nvar DatasetAssociationCollection = Backbone.Collection.extend( BASE_MVC.LoggableMixin ).extend(\n/** @lends HistoryContents.prototype */{\n _logNamespace : logNamespace,\n\n model : DatasetAssociation,\n\n /** root api url */\n urlRoot : Galaxy.root + 'api/datasets',\n\n /** url fn */\n url : function(){\n return this.urlRoot;\n },\n\n // ........................................................................ common queries\n /** Get the ids of every item in this collection\n * @returns array of encoded ids\n */\n ids : function(){\n return this.map( function( item ){ return item.get('id'); });\n },\n\n /** Get contents that are not ready\n * @returns array of content models\n */\n notReady : function(){\n return this.filter( function( content ){\n return !content.inReadyState();\n });\n },\n\n /** return true if any datasets don't have details */\n haveDetails : function(){\n return this.all( function( dataset ){ return dataset.hasDetails(); });\n },\n\n // ........................................................................ ajax\n /** using a queue, perform ajaxFn on each of the models in this collection */\n ajaxQueue : function( ajaxFn, options ){\n var deferred = jQuery.Deferred(),\n startingLength = this.length,\n responses = [];\n\n if( !startingLength ){\n deferred.resolve([]);\n return deferred;\n }\n\n // use reverse order (stylistic choice)\n var ajaxFns = this.chain().reverse().map( function( dataset, i ){\n return function(){\n var xhr = ajaxFn.call( dataset, options );\n // if successful, notify using the deferred to allow tracking progress\n xhr.done( function( response ){\n deferred.notify({ curr: i, total: startingLength, response: response, model: dataset });\n });\n // (regardless of previous error or success) if not last ajax call, shift and call the next\n // if last fn, resolve deferred\n xhr.always( function( response ){\n responses.push( response );\n if( ajaxFns.length ){\n ajaxFns.shift()();\n } else {\n deferred.resolve( responses );\n }\n });\n };\n }).value();\n // start the queue\n ajaxFns.shift()();\n\n return deferred;\n },\n\n // ........................................................................ sorting/filtering\n /** return a new collection of datasets whose attributes contain the substring matchesWhat */\n matches : function( matchesWhat ){\n return this.filter( function( dataset ){\n return dataset.matches( matchesWhat );\n });\n },\n\n /** String representation. */\n toString : function(){\n return ([ 'DatasetAssociationCollection(', this.length, ')' ].join( '' ));\n }\n});\n\n\n//==============================================================================\n return {\n DatasetAssociation : DatasetAssociation,\n DatasetAssociationCollection : DatasetAssociationCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-model.js","define([\n \"mvc/ui/ui-modal\",\n \"mvc/ui/error-modal\",\n \"utils/localization\"\n], function( MODAL, ERROR_MODAL, _l ){\n\n'use strict';\n\n//==============================================================================\n/**\n * A dialog/modal that allows copying a user history or 'importing' from user\n * another. Generally called via historyCopyDialog below.\n * @type {Object}\n */\nvar CopyDialog = {\n\n // language related strings/fns\n defaultName : _.template( \"Copy of '<%- name %>'\" ),\n title : _.template( _l( 'Copying history' ) + ' \"<%- name %>\"' ),\n submitLabel : _l( 'Copy' ),\n errorMessage : _l( 'History could not be copied.' ),\n progressive : _l( 'Copying history' ),\n activeLabel : _l( 'Copy only the active, non-deleted datasets' ),\n allLabel : _l( 'Copy all datasets including deleted ones' ),\n anonWarning : _l( 'As an anonymous user, unless you login or register, you will lose your current history ' ) +\n _l( 'after copying this history. ' ),\n\n // template for modal body\n _template : _.template([\n //TODO: remove inline styles\n // show a warning message for losing current to anon users\n '<% if( isAnon ){ %>',\n '
                                              ',\n '<%- anonWarning %>',\n _l( 'You can' ),\n ' ', _l( 'login here' ), ' ', _l( 'or' ), ' ',\n ' ', _l( 'register here' ), '.',\n '
                                              ',\n '<% } %>',\n '
                                              ',\n '
                                              ',\n // TODO: could use required here and the form validators\n // NOTE: use unescaped here if escaped in the modal function below\n '\" />',\n '

                                              ',\n _l( 'Please enter a valid history title' ),\n '

                                              ',\n // if allowAll, add the option to copy deleted datasets, too\n '<% if( allowAll ){ %>',\n '
                                              ',\n '

                                              ', _l( 'Choose which datasets from the original history to include:' ), '

                                              ',\n // copy non-deleted is the default\n '/>',\n '',\n '
                                              ',\n '/>',\n '',\n '<% } %>',\n '
                                              '\n ].join( '' )),\n\n // empty modal body and let the user know the copy is happening\n _showAjaxIndicator : function _showAjaxIndicator(){\n var indicator = '

                                              ' + this.progressive + '...

                                              ';\n this.modal.$( '.modal-body' ).empty().append( indicator ).css({ 'margin-top': '8px' });\n },\n\n // (sorta) public interface - display the modal, render the form, and potentially copy the history\n // returns a jQuery.Deferred done->history copied, fail->user cancelled\n dialog : function _dialog( modal, history, options ){\n options = options || {};\n\n var dialog = this,\n deferred = jQuery.Deferred(),\n // TODO: getting a little byzantine here\n defaultCopyNameFn = options.nameFn || this.defaultName,\n defaultCopyName = defaultCopyNameFn({ name: history.get( 'name' ) }),\n // TODO: these two might be simpler as one 3 state option (all,active,no-choice)\n defaultCopyWhat = options.allDatasets? 'copy-all' : 'copy-non-deleted',\n allowAll = !_.isUndefined( options.allowAll )? options.allowAll : true,\n autoClose = !_.isUndefined( options.autoClose )? options.autoClose : true;\n\n this.modal = modal;\n\n\n // validate the name and copy if good\n function checkNameAndCopy(){\n var name = modal.$( '#copy-modal-title' ).val();\n if( !name ){\n modal.$( '.invalid-title' ).show();\n return;\n }\n // get further settings, shut down and indicate the ajax call, then hide and resolve/reject\n var copyAllDatasets = modal.$( 'input[name=\"copy-what\"]:checked' ).val() === 'copy-all';\n modal.$( 'button' ).prop( 'disabled', true );\n dialog._showAjaxIndicator();\n history.copy( true, name, copyAllDatasets )\n .done( function( response ){\n deferred.resolve( response );\n })\n .fail( function( xhr, status, message ){\n var options = { name: name, copyAllDatasets: copyAllDatasets };\n ERROR_MODAL.ajaxErrorModal( history, xhr, options, dialog.errorMessage );\n deferred.rejectWith( deferred, arguments );\n })\n .done( function(){\n if( autoClose ){ modal.hide(); }\n });\n }\n\n var originalClosingCallback = options.closing_callback;\n modal.show( _.extend( options, {\n title : this.title({ name: history.get( 'name' ) }),\n body : $( dialog._template({\n name : defaultCopyName,\n isAnon : Galaxy.user.isAnonymous(),\n allowAll : allowAll,\n copyWhat : defaultCopyWhat,\n activeLabel : this.activeLabel,\n allLabel : this.allLabel,\n anonWarning : this.anonWarning,\n })),\n buttons : _.object([\n [ _l( 'Cancel' ), function(){ modal.hide(); } ],\n [ this.submitLabel, checkNameAndCopy ]\n ]),\n height : 'auto',\n closing_events : true,\n closing_callback: function _historyCopyClose( cancelled ){\n if( cancelled ){\n deferred.reject({ cancelled : true });\n }\n if( originalClosingCallback ){\n originalClosingCallback( cancelled );\n }\n }\n }));\n\n // set the default dataset copy, autofocus the title, and set up for a simple return\n modal.$( '#copy-modal-title' ).focus().select();\n modal.$( '#copy-modal-title' ).on( 'keydown', function( ev ){\n if( ev.keyCode === 13 ){\n ev.preventDefault();\n checkNameAndCopy();\n }\n });\n\n return deferred;\n },\n};\n\n//==============================================================================\n// maintain the (slight) distinction between copy and import\n/**\n * Subclass CopyDialog to use the import language.\n */\nvar ImportDialog = _.extend( {}, CopyDialog, {\n defaultName : _.template( \"imported: <%- name %>\" ),\n title : _.template( _l( 'Importing history' ) + ' \"<%- name %>\"' ),\n submitLabel : _l( 'Import' ),\n errorMessage : _l( 'History could not be imported.' ),\n progressive : _l( 'Importing history' ),\n activeLabel : _l( 'Import only the active, non-deleted datasets' ),\n allLabel : _l( 'Import all datasets including deleted ones' ),\n anonWarning : _l( 'As an anonymous user, unless you login or register, you will lose your current history ' ) +\n _l( 'after importing this history. ' ),\n\n});\n\n//==============================================================================\n/**\n * Main interface for both history import and history copy dialogs.\n * @param {Backbone.Model} history the history to copy\n * @param {Object} options a hash\n * @return {jQuery.Deferred} promise that fails on close and succeeds on copy\n *\n * options:\n * (this object is also passed to the modal used to display the dialog and accepts modal options)\n * {Function} nameFn if defined, use this to build the default name shown to the user\n * (the fn is passed: {name: })\n * {bool} useImport if true, use the 'import' language (instead of Copy)\n * {bool} allowAll if true, allow the user to choose between copying all datasets and\n * only non-deleted datasets\n * {String} allDatasets default initial checked radio button: 'copy-all' or 'copy-non-deleted',\n */\nvar historyCopyDialog = function( history, options ){\n options = options || {};\n // create our own modal if Galaxy doesn't have one (mako tab without use_panels)\n var modal = window.parent.Galaxy.modal || new MODAL.View({});\n return options.useImport?\n ImportDialog.dialog( modal, history, options ):\n CopyDialog.dialog( modal, history, options );\n};\n\n\n//==============================================================================\n return historyCopyDialog;\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/copy-dialog.js","define([\n \"mvc/dataset/dataset-li\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET_LI, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DATASET_LI.DatasetListItemView;\n/** @class Read only view for HistoryDatasetAssociation.\n * Since there are no controls on the HDAView to hide the dataset,\n * the primary thing this class does (currently) is override templates\n * to render the HID.\n */\nvar HDAListItemView = _super.extend(\n/** @lends HDAListItemView.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n initialize : function( attributes, options ){\n _super.prototype.initialize.call( this, attributes, options );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDAListItemView(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nHDAListItemView.prototype.templates = (function(){\n\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding the hid display to the title\n '
                                              ',\n '',\n '
                                              ',\n //TODO: remove whitespace and use margin-right\n '<%- dataset.hid %> ',\n '<%- dataset.name %>',\n '
                                              ',\n '
                                              ',\n '',\n '<% _.each(_.sortBy(_.uniq(dataset.tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>',\n '',\n '
                                              '\n ], 'dataset' );\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n // add a warning when hidden\n '<% if( !dataset.visible ){ %>',\n '
                                              ',\n _l( 'This dataset has been hidden' ),\n '
                                              ',\n '<% } %>'\n ], 'dataset' )\n });\n\n return _.extend( {}, _super.prototype.templates, {\n titleBar : titleBarTemplate,\n warnings : warnings\n });\n}());\n\n\n\n//==============================================================================\n return {\n HDAListItemView : HDAListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-li.js","define([\n \"mvc/dataset/dataset-model\",\n \"mvc/history/history-content-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DATASET, HISTORY_CONTENT, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\nvar _super = DATASET.DatasetAssociation,\n hcontentMixin = HISTORY_CONTENT.HistoryContentMixin;\n/** @class (HDA) model for a Galaxy dataset contained in and related to a history.\n */\nvar HistoryDatasetAssociation = _super.extend( BASE_MVC.mixin( hcontentMixin,\n/** @lends HistoryDatasetAssociation.prototype */{\n\n /** default attributes for a model */\n defaults : _.extend( {}, _super.prototype.defaults, hcontentMixin.defaults, {\n history_content_type: 'dataset',\n model_class : 'HistoryDatasetAssociation'\n }),\n}));\n\n//==============================================================================\n return {\n HistoryDatasetAssociation : HistoryDatasetAssociation\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hda-model.js","define([\n \"mvc/dataset/states\",\n \"mvc/collection/collection-li\",\n \"mvc/collection/collection-view\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, DC_LI, DC_VIEW, BASE_MVC, _l ){\n\n'use strict';\n\n//==============================================================================\nvar _super = DC_LI.DCListItemView;\n/** @class Read only view for HistoryDatasetCollectionAssociation (a dataset collection inside a history).\n */\nvar HDCAListItemView = _super.extend(\n/** @lends HDCAListItemView.prototype */{\n\n className : _super.prototype.className + \" history-content\",\n\n /** event listeners */\n _setUpListeners : function(){\n _super.prototype._setUpListeners.call( this );\n this.listenTo( this.model, {\n 'change:tags change:populated change:visible' : function( model, options ){ this.render(); },\n });\n },\n\n /** Override to provide the proper collections panels as the foldout */\n _getFoldoutPanelClass : function(){\n switch( this.model.get( 'collection_type' ) ){\n case 'list':\n return DC_VIEW.ListCollectionView;\n case 'paired':\n return DC_VIEW.PairCollectionView;\n case 'list:paired':\n return DC_VIEW.ListOfPairsCollectionView;\n case 'list:list':\n return DC_VIEW.ListOfListsCollectionView;\n }\n throw new TypeError( 'Uknown collection_type: ' + this.model.get( 'collection_type' ) );\n },\n\n /** In this override, add the state as a class for use with state-based CSS */\n _swapNewRender : function( $newRender ){\n _super.prototype._swapNewRender.call( this, $newRender );\n //TODO: model currently has no state\n var state = !this.model.get( 'populated' ) ? STATES.RUNNING : STATES.OK;\n //if( this.model.has( 'state' ) ){\n this.$el.addClass( 'state-' + state );\n //}\n return this.$el;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'HDCAListItemView(' + modelString + ')';\n }\n});\n\n/** underscore templates */\nHDCAListItemView.prototype.templates = (function(){\n\n var warnings = _.extend( {}, _super.prototype.templates.warnings, {\n hidden : BASE_MVC.wrapTemplate([\n // add a warning when hidden\n '<% if( !collection.visible ){ %>',\n '
                                              ',\n _l( 'This collection has been hidden' ),\n '
                                              ',\n '<% } %>'\n ], 'collection' )\n });\n\n// could steal this from hda-base (or use mixed content)\n var titleBarTemplate = BASE_MVC.wrapTemplate([\n // adding the hid display to the title\n '
                                              ',\n '',\n '
                                              ',\n //TODO: remove whitespace and use margin-right\n '<%- collection.hid %> ',\n '<%- collection.name %>',\n '
                                              ',\n '
                                              ',\n '',\n '<% _.each(_.sortBy(_.uniq(collection.tags), function(x) { return x }), function(tag){ %>',\n '<% if (tag.indexOf(\"name:\") == 0){ %>',\n '<%- tag.slice(5) %>',\n '<% } %>',\n '<% }); %>',\n '',\n '
                                              '\n ], 'collection' );\n\n return _.extend( {}, _super.prototype.templates, {\n warnings : warnings,\n titleBar : titleBarTemplate\n });\n}());\n\n\n//==============================================================================\n return {\n HDCAListItemView : HDCAListItemView\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/hdca-li.js","define([\n \"mvc/dataset/states\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( STATES, BASE_MVC, _l ){\n'use strict';\n\n//==============================================================================\n/** @class Mixin for HistoryContents content (HDAs, HDCAs).\n */\nvar HistoryContentMixin = {\n\n /** default attributes for a model */\n defaults : {\n /** parent (containing) history */\n history_id : null,\n /** some content_type (HistoryContents can contain mixed model classes) */\n history_content_type: null,\n /** indicating when/what order the content was generated in the context of the history */\n hid : null,\n /** whether the user wants the content shown (visible) */\n visible : true\n },\n\n // ........................................................................ mixed content element\n // In order to be part of a MIXED bbone collection, we can't rely on the id\n // (which may collide btwn models of different classes)\n // Instead, use type_id which prefixes the history_content_type so the bbone collection can differentiate\n idAttribute : 'type_id',\n\n // ........................................................................ common queries\n /** the more common alias of visible */\n hidden : function(){\n return !this.get( 'visible' );\n },\n\n//TODO: remove\n /** based on includeDeleted, includeHidden (gen. from the container control),\n * would this ds show in the list of ds's?\n * @param {Boolean} includeDeleted are we showing deleted hdas?\n * @param {Boolean} includeHidden are we showing hidden hdas?\n */\n isVisible : function( includeDeleted, includeHidden ){\n var isVisible = true;\n if( ( !includeDeleted )\n && ( this.get( 'deleted' ) || this.get( 'purged' ) ) ){\n isVisible = false;\n }\n if( ( !includeHidden )\n && ( !this.get( 'visible' ) ) ){\n isVisible = false;\n }\n return isVisible;\n },\n\n // ........................................................................ ajax\n //TODO?: these are probably better done on the leaf classes\n /** history content goes through the 'api/histories' API */\n urlRoot: Galaxy.root + 'api/histories/',\n\n /** full url spec. for this content */\n url : function(){\n var url = this.urlRoot + this.get( 'history_id' ) + '/contents/'\n + this.get('history_content_type') + 's/' + this.get( 'id' );\n return url;\n },\n\n /** save this content as not visible */\n hide : function( options ){\n if( !this.get( 'visible' ) ){ return jQuery.when(); }\n return this.save( { visible: false }, options );\n },\n /** save this content as visible */\n unhide : function( options ){\n if( this.get( 'visible' ) ){ return jQuery.when(); }\n return this.save( { visible: true }, options );\n },\n\n // ........................................................................ misc\n toString : function(){\n return ([ this.get( 'type_id' ), this.get( 'hid' ), this.get( 'name' ) ].join(':'));\n }\n};\n\n\n//==============================================================================\n return {\n HistoryContentMixin : HistoryContentMixin\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/history/history-content-model.js","define([\n \"mvc/list/list-item\",\n \"ui/loading-indicator\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/search-input\"\n], function( LIST_ITEM, LoadingIndicator, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'list';\n/* ============================================================================\nTODO:\n\n============================================================================ */\n/** @class View for a list/collection of models and the sub-views of those models.\n * Sub-views must (at least have the interface if not) inherit from ListItemView.\n * (For a list panel that also includes some 'container' model (History->HistoryContents)\n * use ModelWithListPanel)\n *\n * Allows for:\n * searching collection/sub-views\n * selecting/multi-selecting sub-views\n *\n * Currently used:\n * for dataset/dataset-choice\n * as superclass of ModelListPanel\n */\nvar ListPanel = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend(/** @lends ListPanel.prototype */{\n _logNamespace : logNamespace,\n\n /** class to use for constructing the sub-views */\n viewClass : LIST_ITEM.ListItemView,\n /** class to used for constructing collection of sub-view models */\n collectionClass : Backbone.Collection,\n\n tagName : 'div',\n className : 'list-panel',\n\n /** (in ms) that jquery effects will use */\n fxSpeed : 'fast',\n\n /** string to display when the collection has no contents */\n emptyMsg : _l( 'This list is empty' ),\n /** displayed when no items match the search terms */\n noneFoundMsg : _l( 'No matching items found' ),\n /** string used for search placeholder */\n searchPlaceholder : _l( 'search' ),\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the list\n */\n initialize : function( attributes, options ){\n attributes = attributes || {};\n // set the logger if requested\n if( attributes.logger ){\n this.logger = attributes.logger;\n }\n this.log( this + '.initialize:', attributes );\n\n // ---- instance vars\n /** how quickly should jquery fx run? */\n this.fxSpeed = _.has( attributes, 'fxSpeed' )?( attributes.fxSpeed ):( this.fxSpeed );\n\n /** filters for displaying subviews */\n this.filters = [];\n /** current search terms */\n this.searchFor = attributes.searchFor || '';\n\n /** loading indicator */\n // this.indicator = new LoadingIndicator( this.$el );\n\n /** currently showing selectors on items? */\n this.selecting = ( attributes.selecting !== undefined )? attributes.selecting : true;\n //this.selecting = false;\n\n /** cached selected item.model.ids to persist btwn renders */\n this.selected = attributes.selected || [];\n /** the last selected item.model.id */\n this.lastSelected = null;\n\n /** are sub-views draggable */\n this.dragItems = attributes.dragItems || false;\n\n /** list item view class (when passed models) */\n this.viewClass = attributes.viewClass || this.viewClass;\n\n /** list item views */\n this.views = [];\n /** list item models */\n this.collection = attributes.collection || this._createDefaultCollection();\n\n /** filter fns run over collection items to see if they should show in the list */\n this.filters = attributes.filters || [];\n\n /** override $scrollContainer fn via attributes - fn should return jq for elem to call scrollTo on */\n this.$scrollContainer = attributes.$scrollContainer || this.$scrollContainer;\n\n /** @type {String} generic title */\n this.title = attributes.title || '';\n /** @type {String} generic subtitle */\n this.subtitle = attributes.subtitle || '';\n\n this._setUpListeners();\n },\n\n // ------------------------------------------------------------------------ listeners\n /** create any event listeners for the list */\n _setUpListeners : function(){\n this.off();\n\n //TODO: move errorHandler down into list-view from history-view or\n // pass to global error handler (Galaxy)\n this.on({\n error: function( model, xhr, options, msg, details ){\n //this.errorHandler( model, xhr, options, msg, details );\n console.error( model, xhr, options, msg, details );\n },\n // show hide the loading indicator\n loading: function(){\n this._showLoadingIndicator( 'loading...', 40 );\n },\n 'loading-done': function(){\n this._hideLoadingIndicator( 40 );\n },\n });\n\n // throw the first render up as a diff namespace using once (for outside consumption)\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this._setUpCollectionListeners();\n this._setUpViewListeners();\n return this;\n },\n\n /** create and return a collection for when none is initially passed */\n _createDefaultCollection : function(){\n // override\n return new this.collectionClass([]);\n },\n\n /** listening for collection events */\n _setUpCollectionListeners : function(){\n this.log( this + '._setUpCollectionListeners', this.collection );\n this.stopListening( this.collection );\n\n // bubble up error events\n this.listenTo( this.collection, {\n error : function( model, xhr, options, msg, details ){\n this.trigger( 'error', model, xhr, options, msg, details );\n },\n update : function( collection, options ){\n var changes = options.changes;\n // console.info( collection + ', update:', changes, '\\noptions:', options );\n // more than one: render everything\n if( options.renderAll || ( changes.added.length + changes.removed.length > 1 ) ){\n return this.renderItems();\n }\n // otherwise, let the single add/remove handlers do it\n if( changes.added.length === 1 ){\n return this.addItemView( _.first( changes.added ), collection, options );\n }\n if( changes.removed.length === 1 ){\n return this.removeItemView( _.first( changes.removed ), collection, options );\n }\n }\n });\n return this;\n },\n\n /** listening for sub-view events that bubble up with the 'view:' prefix */\n _setUpViewListeners : function(){\n this.log( this + '._setUpViewListeners' );\n\n // shift to select a range\n this.on({\n 'view:selected': function( view, ev ){\n if( ev && ev.shiftKey && this.lastSelected ){\n var lastSelectedView = this.viewFromModelId( this.lastSelected );\n if( lastSelectedView ){\n this.selectRange( view, lastSelectedView );\n }\n } else if( ev && ev.altKey && !this.selecting ){\n this.showSelectors();\n }\n this.selected.push( view.model.id );\n this.lastSelected = view.model.id;\n },\n\n 'view:de-selected': function( view, ev ){\n this.selected = _.without( this.selected, view.model.id );\n }\n });\n },\n\n // ------------------------------------------------------------------------ rendering\n /** Render this content, set up ui.\n * @param {Number or String} speed the speed of the render\n */\n render : function( speed ){\n this.log( this + '.render', speed );\n var $newRender = this._buildNewRender();\n this._setUpBehaviors( $newRender );\n this._queueNewRender( $newRender, speed );\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el. */\n _buildNewRender : function(){\n this.debug( this + '(ListPanel)._buildNewRender' );\n var $newRender = $( this.templates.el( {}, this ) );\n this._renderControls( $newRender );\n this._renderTitle( $newRender );\n this._renderSubtitle( $newRender );\n this._renderSearch( $newRender );\n this.renderItems( $newRender );\n return $newRender;\n },\n\n /** Build a temp div containing the new children for the view's $el. */\n _renderControls : function( $newRender ){\n this.debug( this + '(ListPanel)._renderControls' );\n var $controls = $( this.templates.controls( {}, this ) );\n $newRender.find( '.controls' ).replaceWith( $controls );\n return $controls;\n },\n\n /** return a jQuery object containing the title DOM */\n _renderTitle : function( $where ){\n //$where = $where || this.$el;\n //$where.find( '.title' ).replaceWith( ... )\n },\n\n /** return a jQuery object containing the subtitle DOM (if any) */\n _renderSubtitle : function( $where ){\n //$where = $where || this.$el;\n //$where.find( '.title' ).replaceWith( ... )\n },\n\n /** Fade out the old el, swap in the new contents, then fade in.\n * @param {Number or String} speed jq speed to use for rendering effects\n * @fires rendered when rendered\n */\n _queueNewRender : function( $newRender, speed ) {\n speed = ( speed === undefined )?( this.fxSpeed ):( speed );\n var panel = this;\n panel.log( '_queueNewRender:', $newRender, speed );\n\n $( panel ).queue( 'fx', [\n function( next ){\n panel.$el.fadeOut( speed, next );\n },\n function( next ){\n panel._swapNewRender( $newRender );\n next();\n },\n function( next ){\n panel.$el.fadeIn( speed, next );\n },\n function( next ){\n panel.trigger( 'rendered', panel );\n next();\n }\n ]);\n },\n\n /** empty out the current el, move the $newRender's children in */\n _swapNewRender : function( $newRender ){\n this.$el.empty().attr( 'class', this.className ).append( $newRender.children() );\n if( this.selecting ){ this.showSelectors( 0 ); }\n return this;\n },\n\n /** Set up any behaviors, handlers (ep. plugins) that need to be called when the entire view has been built but\n * not attached to the page yet.\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n this.$controls( $where ).find('[title]').tooltip();\n // set up the pupup for actions available when multi selecting\n this._renderMultiselectActionMenu( $where );\n return this;\n },\n\n /** render a menu containing the actions available to sets of selected items */\n _renderMultiselectActionMenu : function( $where ){\n $where = $where || this.$el;\n var $menu = $where.find( '.list-action-menu' ),\n actions = this.multiselectActions();\n if( !actions.length ){\n return $menu.empty();\n }\n\n var $newMenu = $([\n '
                                              ',\n '',\n '
                                                ', '
                                              ',\n '
                                              '\n ].join(''));\n var $actions = actions.map( function( action ){\n var html = [ '
                                            • ', action.html, '
                                            • ' ].join( '' );\n return $( html ).click( function( ev ){\n ev.preventDefault();\n return action.func( ev );\n });\n });\n $newMenu.find( 'ul' ).append( $actions );\n $menu.replaceWith( $newMenu );\n return $newMenu;\n },\n\n /** return a list of plain objects used to render multiselect actions menu. Each object should have:\n * html: an html string used as the anchor contents\n * func: a function called when the anchor is clicked (passed the click event)\n */\n multiselectActions : function(){\n return [];\n },\n\n // ------------------------------------------------------------------------ sub-$element shortcuts\n /** the scroll container for this panel - can be $el, $el.parent(), or grandparent depending on context */\n $scrollContainer : function( $where ){\n // override or set via attributes.$scrollContainer\n return ( $where || this.$el ).parent().parent();\n },\n /** convenience selector for the section that displays the list controls */\n $controls : function( $where ){\n return ( $where || this.$el ).find( '> .controls' );\n },\n /** list-items: where the subviews are contained in the view's dom */\n $list : function( $where ){\n return ( $where || this.$el ).find( '> .list-items' );\n },\n /** container where list messages are attached */\n $messages : function( $where ){\n //TODO: controls isn't really correct here (only for ModelListPanel)\n return ( $where || this.$el ).find( '> .controls .messages' );\n },\n /** the message displayed when no views can be shown (no views, none matching search) */\n $emptyMessage : function( $where ){\n return ( $where || this.$el ).find( '> .empty-message' );\n },\n\n // ------------------------------------------------------------------------ hda sub-views\n /** render the subviews for the list's collection */\n renderItems : function( $whereTo ){\n $whereTo = $whereTo || this.$el;\n var panel = this;\n panel.log( this + '.renderItems', $whereTo );\n\n var $list = panel.$list( $whereTo );\n panel.freeViews();\n // console.log( 'views freed' );\n //TODO:? cache and re-use views?\n var shownModels = panel._filterCollection();\n // console.log( 'models filtered:', shownModels );\n\n panel.views = shownModels.map( function( itemModel ){\n var view = panel._createItemView( itemModel );\n return view;\n });\n\n $list.empty();\n // console.log( 'list emptied' );\n if( panel.views.length ){\n panel._attachItems( $whereTo );\n // console.log( 'items attached' );\n }\n panel._renderEmptyMessage( $whereTo ).toggle( !panel.views.length );\n panel.trigger( 'views:ready', panel.views );\n\n // console.log( '------------------------------------------- rendering items' );\n return panel.views;\n },\n\n /** Filter the collection to only those models that should be currently viewed */\n _filterCollection : function(){\n // override this\n var panel = this;\n return panel.collection.filter( _.bind( panel._filterItem, panel ) );\n },\n\n /** Should the model be viewable in the current state?\n * Checks against this.filters and this.searchFor\n */\n _filterItem : function( model ){\n // override this\n var panel = this;\n return ( _.every( panel.filters.map( function( fn ){ return fn.call( model ); }) ) )\n && ( !panel.searchFor || model.matchesAll( panel.searchFor ) );\n },\n\n /** Create a view for a model and set up it's listeners */\n _createItemView : function( model ){\n var ViewClass = this._getItemViewClass( model );\n var options = _.extend( this._getItemViewOptions( model ), {\n model : model\n });\n var view = new ViewClass( options );\n this._setUpItemViewListeners( view );\n return view;\n },\n\n /** Free a view for a model. Note: does not remove it from the DOM */\n _destroyItemView : function( view ){\n this.stopListening( view );\n this.views = _.without( this.views, view );\n },\n\n _destroyItemViews : function( view ){\n var self = this;\n self.views.forEach( function( v ){\n self.stopListening( v );\n });\n self.views = [];\n return self;\n },\n\n /** free any sub-views the list has */\n freeViews : function(){\n return this._destroyItemViews();\n },\n\n /** Get the bbone view class based on the model */\n _getItemViewClass : function( model ){\n // override this\n return this.viewClass;\n },\n\n /** Get the options passed to the new view based on the model */\n _getItemViewOptions : function( model ){\n // override this\n return {\n //logger : this.logger,\n fxSpeed : this.fxSpeed,\n expanded : false,\n selectable : this.selecting,\n selected : _.contains( this.selected, model.id ),\n draggable : this.dragItems\n };\n },\n\n /** Set up listeners for new models */\n _setUpItemViewListeners : function( view ){\n var panel = this;\n // send all events to the panel, re-namspaceing them with the view prefix\n this.listenTo( view, 'all', function(){\n var args = Array.prototype.slice.call( arguments, 0 );\n args[0] = 'view:' + args[0];\n panel.trigger.apply( panel, args );\n });\n\n // drag multiple - hijack ev.setData to add all selected items\n this.listenTo( view, 'draggable:dragstart', function( ev, v ){\n //TODO: set multiple drag data here\n var json = {},\n selected = this.getSelectedModels();\n if( selected.length ){\n json = selected.toJSON();\n } else {\n json = [ v.model.toJSON() ];\n }\n ev.dataTransfer.setData( 'text', JSON.stringify( json ) );\n //ev.dataTransfer.setDragImage( v.el, 60, 60 );\n }, this );\n\n return panel;\n },\n\n /** Attach views in this.views to the model based on $whereTo */\n _attachItems : function( $whereTo ){\n var self = this;\n // console.log( '_attachItems:', $whereTo, this.$list( $whereTo ) );\n //ASSUMES: $list has been emptied\n this.$list( $whereTo ).append( this.views.map( function( view ){\n return self._renderItemView$el( view );\n }));\n return this;\n },\n\n /** get a given subview's $el (or whatever may wrap it) and return it */\n _renderItemView$el : function( view ){\n // useful to wrap and override\n return view.render(0).$el;\n },\n\n /** render the empty/none-found message */\n _renderEmptyMessage : function( $whereTo ){\n this.debug( '_renderEmptyMessage', $whereTo, this.searchFor );\n var text = this.searchFor? this.noneFoundMsg : this.emptyMsg;\n return this.$emptyMessage( $whereTo ).text( text );\n },\n\n /** expand all item views */\n expandAll : function(){\n _.each( this.views, function( view ){\n view.expand();\n });\n },\n\n /** collapse all item views */\n collapseAll : function(){\n _.each( this.views, function( view ){\n view.collapse();\n });\n },\n\n // ------------------------------------------------------------------------ collection/views syncing\n /** Add a view (if the model should be viewable) to the panel */\n addItemView : function( model, collection, options ){\n // console.log( this + '.addItemView:', model );\n var panel = this;\n // get the index of the model in the list of filtered models shown by this list\n // in order to insert the view in the proper place\n //TODO:? potentially expensive\n var modelIndex = panel._filterCollection().indexOf( model );\n if( modelIndex === -1 ){ return undefined; }\n var view = panel._createItemView( model );\n // console.log( 'adding and rendering:', modelIndex, view.toString() );\n\n $( view ).queue( 'fx', [\n function( next ){\n // hide the empty message first if only view\n if( panel.$emptyMessage().is( ':visible' ) ){\n panel.$emptyMessage().fadeOut( panel.fxSpeed, next );\n } else {\n next();\n }\n },\n function( next ){\n panel._attachView( view, modelIndex );\n next();\n }\n ]);\n return view;\n },\n\n /** internal fn to add view (to both panel.views and panel.$list) */\n _attachView : function( view, modelIndex, useFx ){\n // console.log( this + '._attachView:', view, modelIndex, useFx );\n useFx = _.isUndefined( useFx )? true : useFx;\n modelIndex = modelIndex || 0;\n var panel = this;\n\n // use the modelIndex to splice into views and insert at the proper index in the DOM\n panel.views.splice( modelIndex, 0, view );\n panel._insertIntoListAt( modelIndex, panel._renderItemView$el( view ).hide() );\n\n panel.trigger( 'view:attached', view );\n if( useFx ){\n view.$el.slideDown( panel.fxSpeed, function(){\n panel.trigger( 'view:attached:rendered' );\n });\n } else {\n view.$el.show();\n panel.trigger( 'view:attached:rendered' );\n }\n return view;\n },\n\n /** insert a jq object as a child of list-items at the specified *DOM index* */\n _insertIntoListAt : function( index, $what ){\n // console.log( this + '._insertIntoListAt:', index, $what );\n var $list = this.$list();\n if( index === 0 ){\n $list.prepend( $what );\n } else {\n $list.children().eq( index - 1 ).after( $what );\n }\n return $what;\n },\n\n /** Remove a view from the panel (if found) */\n removeItemView : function( model, collection, options ){\n var panel = this;\n var view = _.find( panel.views, function( v ){ return v.model === model; });\n if( !view ){ return undefined; }\n panel.views = _.without( panel.views, view );\n panel.trigger( 'view:removed', view );\n\n // potentially show the empty message if no views left\n // use anonymous queue here - since remove can happen multiple times\n $({}).queue( 'fx', [\n function( next ){\n view.$el.fadeOut( panel.fxSpeed, next );\n },\n function( next ){\n view.remove();\n panel.trigger( 'view:removed:rendered' );\n if( !panel.views.length ){\n panel._renderEmptyMessage().fadeIn( panel.fxSpeed, next );\n } else {\n next();\n }\n }\n ]);\n return view;\n },\n\n /** get views based on model.id */\n viewFromModelId : function( id ){\n return _.find( this.views, function( v ){ return v.model.id === id; });\n },\n\n /** get views based on model */\n viewFromModel : function( model ){\n return model ? this.viewFromModelId( model.id ) : undefined;\n },\n\n /** get views based on model properties */\n viewsWhereModel : function( properties ){\n return this.views.filter( function( view ){\n return _.isMatch( view.model.attributes, properties );\n });\n },\n\n /** A range of views between (and including) viewA and viewB */\n viewRange : function( viewA, viewB ){\n if( viewA === viewB ){ return ( viewA )?( [ viewA ] ):( [] ); }\n\n var indexA = this.views.indexOf( viewA ),\n indexB = this.views.indexOf( viewB );\n\n // handle not found\n if( indexA === -1 || indexB === -1 ){\n if( indexA === indexB ){ return []; }\n return ( indexA === -1 )?( [ viewB ] ):( [ viewA ] );\n }\n // reverse if indeces are\n //note: end inclusive\n return ( indexA < indexB )?\n this.views.slice( indexA, indexB + 1 ) :\n this.views.slice( indexB, indexA + 1 );\n },\n\n // ------------------------------------------------------------------------ searching\n /** render a search input for filtering datasets shown\n * (see SearchableMixin in base-mvc for implementation of the actual searching)\n * return will start the search\n * esc will clear the search\n * clicking the clear button will clear the search\n * uses searchInput in ui.js\n */\n _renderSearch : function( $where ){\n $where.find( '.controls .search-input' ).searchInput({\n placeholder : this.searchPlaceholder,\n initialVal : this.searchFor,\n onfirstsearch : _.bind( this._firstSearch, this ),\n onsearch : _.bind( this.searchItems, this ),\n onclear : _.bind( this.clearSearch, this )\n });\n return $where;\n },\n\n /** What to do on the first search entered */\n _firstSearch : function( searchFor ){\n // override to load model details if necc.\n this.log( 'onFirstSearch', searchFor );\n return this.searchItems( searchFor );\n },\n\n /** filter view list to those that contain the searchFor terms */\n searchItems : function( searchFor, force ){\n this.log( 'searchItems', searchFor, this.searchFor, force );\n if( !force && this.searchFor === searchFor ){ return this; }\n this.searchFor = searchFor;\n this.renderItems();\n this.trigger( 'search:searching', searchFor, this );\n var $search = this.$( '> .controls .search-query' );\n if( $search.val() !== searchFor ){\n $search.val( searchFor );\n }\n return this;\n },\n\n /** clear the search filters and show all views that are normally shown */\n clearSearch : function( searchFor ){\n //this.log( 'onSearchClear', this );\n this.searchFor = '';\n this.trigger( 'search:clear', this );\n this.$( '> .controls .search-query' ).val( '' );\n this.renderItems();\n return this;\n },\n\n // ------------------------------------------------------------------------ selection\n /** @type Integer when the number of list item views is >= to this, don't animate selectors */\n THROTTLE_SELECTOR_FX_AT : 20,\n\n /** show selectors on all visible itemViews and associated controls */\n showSelectors : function( speed ){\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n this.selecting = true;\n this.$( '.list-actions' ).slideDown( speed );\n speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT? 0 : speed;\n _.each( this.views, function( view ){\n view.showSelector( speed );\n });\n //this.selected = [];\n //this.lastSelected = null;\n },\n\n /** hide selectors on all visible itemViews and associated controls */\n hideSelectors : function( speed ){\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n this.selecting = false;\n this.$( '.list-actions' ).slideUp( speed );\n speed = this.views.length >= this.THROTTLE_SELECTOR_FX_AT? 0 : speed;\n _.each( this.views, function( view ){\n view.hideSelector( speed );\n });\n this.selected = [];\n this.lastSelected = null;\n },\n\n /** show or hide selectors on all visible itemViews and associated controls */\n toggleSelectors : function(){\n if( !this.selecting ){\n this.showSelectors();\n } else {\n this.hideSelectors();\n }\n },\n\n /** select all visible items */\n selectAll : function( event ){\n _.each( this.views, function( view ){\n view.select( event );\n });\n },\n\n /** deselect all visible items */\n deselectAll : function( event ){\n this.lastSelected = null;\n _.each( this.views, function( view ){\n view.deselect( event );\n });\n },\n\n /** select a range of datasets between A and B */\n selectRange : function( viewA, viewB ){\n var range = this.viewRange( viewA, viewB );\n _.each( range, function( view ){\n view.select();\n });\n return range;\n },\n\n /** return an array of all currently selected itemViews */\n getSelectedViews : function(){\n return _.filter( this.views, function( v ){\n return v.selected;\n });\n },\n\n /** return a collection of the models of all currenly selected items */\n getSelectedModels : function(){\n // console.log( '(getSelectedModels)' );\n return new this.collection.constructor( _.map( this.getSelectedViews(), function( view ){\n return view.model;\n }));\n },\n\n // ------------------------------------------------------------------------ loading indicator\n /** hide the $el and display a loading indicator (in the $el's parent) when loading new data */\n _showLoadingIndicator : function( msg, speed, callback ){\n this.debug( '_showLoadingIndicator', this.indicator, msg, speed, callback );\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n if( !this.indicator ){\n this.indicator = new LoadingIndicator( this.$el );\n this.debug( '\\t created', this.indicator );\n }\n if( !this.$el.is( ':visible' ) ){\n this.indicator.show( 0, callback );\n } else {\n this.$el.fadeOut( speed );\n this.indicator.show( msg, speed, callback );\n }\n },\n\n /** hide the loading indicator */\n _hideLoadingIndicator : function( speed, callback ){\n this.debug( '_hideLoadingIndicator', this.indicator, speed, callback );\n speed = ( speed !== undefined )?( speed ):( this.fxSpeed );\n if( this.indicator ){\n this.indicator.hide( speed, callback );\n }\n },\n\n // ------------------------------------------------------------------------ scrolling\n /** get the current scroll position of the panel in its parent */\n scrollPosition : function(){\n return this.$scrollContainer().scrollTop();\n },\n\n /** set the current scroll position of the panel in its parent */\n scrollTo : function( pos, speed ){\n speed = speed || 0;\n this.$scrollContainer().animate({ scrollTop: pos }, speed );\n return this;\n },\n\n /** Scrolls the panel to the top. */\n scrollToTop : function( speed ){\n return this.scrollTo( 0, speed );\n },\n\n /** scroll to the given view in list-items */\n scrollToItem : function( view, speed ){\n if( !view ){ return this; }\n return this;\n },\n\n /** Scrolls the panel to show the content with the given id. */\n scrollToId : function( id, speed ){\n return this.scrollToItem( this.viewFromModelId( id ), speed );\n },\n\n // ------------------------------------------------------------------------ panel events\n /** event map */\n events : {\n 'click .select-all' : 'selectAll',\n 'click .deselect-all' : 'deselectAll'\n },\n\n // ------------------------------------------------------------------------ misc\n /** Return a string rep of the panel */\n toString : function(){\n return 'ListPanel(' + this.collection + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nListPanel.prototype.templates = (function(){\n\n var elTemplate = BASE_MVC.wrapTemplate([\n // temp container\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ]);\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                                              ',\n '
                                              ',\n '
                                              <%- view.title %>
                                              ',\n '
                                              ',\n '
                                              <%- view.subtitle %>
                                              ',\n // buttons, controls go here\n '
                                              ',\n // deleted msg, etc.\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '
                                              ',\n\n // show when selectors are shown\n '
                                              ',\n '
                                              ',\n '',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ]);\n\n return {\n el : elTemplate,\n controls : controlsTemplate\n };\n}());\n\n\n//=============================================================================\n/** View for a model that has a sub-collection (e.g. History, DatasetCollection)\n * Allows:\n * the model to be reset\n * auto assign panel.collection to panel.model[ panel.modelCollectionKey ]\n *\n */\nvar ModelListPanel = ListPanel.extend({\n\n /** key of attribute in model to assign to this.collection */\n modelCollectionKey : 'contents',\n\n initialize : function( attributes ){\n ListPanel.prototype.initialize.call( this, attributes );\n this.selecting = ( attributes.selecting !== undefined )? attributes.selecting : false;\n\n this.setModel( this.model, attributes );\n },\n\n /** release/free/shutdown old models and set up panel for new models\n * @fires new-model with the panel as parameter\n */\n setModel : function( model, attributes ){\n attributes = attributes || {};\n this.debug( this + '.setModel:', model, attributes );\n\n this.freeModel();\n this.freeViews();\n\n if( model ){\n var oldModelId = this.model? this.model.get( 'id' ): null;\n\n // set up the new model with user, logger, storage, events\n this.model = model;\n if( this.logger ){\n this.model.logger = this.logger;\n }\n this._setUpModelListeners();\n\n //TODO: relation btwn model, collection becoming tangled here\n // free the collection, and assign the new collection to either\n // the model[ modelCollectionKey ], attributes.collection, or an empty vanilla collection\n this.stopListening( this.collection );\n this.collection = this.model[ this.modelCollectionKey ]\n || attributes.collection\n || this._createDefaultCollection();\n this._setUpCollectionListeners();\n\n if( oldModelId && model.get( 'id' ) !== oldModelId ){\n this.trigger( 'new-model', this );\n }\n }\n return this;\n },\n\n /** free the current model and all listeners for it, free any views for the model */\n freeModel : function(){\n // stop/release the previous model, and clear cache to sub-views\n if( this.model ){\n this.stopListening( this.model );\n //TODO: see base-mvc\n //this.model.free();\n //this.model = null;\n }\n return this;\n },\n\n // ------------------------------------------------------------------------ listening\n /** listening for model events */\n _setUpModelListeners : function(){\n // override\n this.log( this + '._setUpModelListeners', this.model );\n // bounce model errors up to the panel\n this.listenTo( this.model, 'error', function(){\n var args = Array.prototype.slice.call( arguments, 0 );\n //args.unshift( 'model:error' );\n args.unshift( 'error' );\n this.trigger.apply( this, args );\n }, this );\n\n // debugging\n if( this.logger ){\n this.listenTo( this.model, 'all', function( event ){\n this.info( this + '(model)', event, arguments );\n });\n }\n return this;\n },\n\n /** Build a temp div containing the new children for the view's $el.\n */\n _renderControls : function( $newRender ){\n this.debug( this + '(ModelListPanel)._renderControls' );\n var json = this.model? this.model.toJSON() : {},\n $controls = $( this.templates.controls( json, this ) );\n $newRender.find( '.controls' ).replaceWith( $controls );\n return $controls;\n },\n\n // ------------------------------------------------------------------------ misc\n /** Return a string rep of the panel */\n toString : function(){\n return 'ModelListPanel(' + this.model + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nModelListPanel.prototype.templates = (function(){\n\n var controlsTemplate = BASE_MVC.wrapTemplate([\n '
                                              ',\n '
                                              ',\n //TODO: this is really the only difference - consider factoring titlebar out\n '
                                              <%- model.name %>
                                              ',\n '
                                              ',\n '
                                              <%- view.subtitle %>
                                              ',\n '
                                              ',\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ]);\n\n return _.extend( _.clone( ListPanel.prototype.templates ), {\n controls : controlsTemplate\n });\n}());\n\n\n//=============================================================================\n return {\n ListPanel : ListPanel,\n ModelListPanel : ModelListPanel\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/list/list-view.js","/** This is the run workflow tool form view. */\ndefine([ 'utils/utils', 'utils/deferred', 'mvc/ui/ui-misc', 'mvc/form/form-view', 'mvc/form/form-data', 'mvc/tool/tool-form-base', 'mvc/ui/ui-modal', 'mvc/webhooks', 'mvc/workflow/workflow-icons' ],\n function( Utils, Deferred, Ui, Form, FormData, ToolFormBase, Modal, Webhooks, WorkflowIcons ) {\n\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.modal = parent.Galaxy.modal || new Modal.View();\n this.model = options && options.model || new Backbone.Model( options );\n this.deferred = new Deferred();\n this.setElement( $( '
                                              ' ).addClass( 'ui-form-composite' )\n .append( this.$message = $( '
                                              ' ) )\n .append( this.$header = $( '
                                              ' ) )\n .append( this.$steps = $( '
                                              ' ) ) );\n $( 'body' ).append( this.$el );\n this._configure();\n this.render();\n $( window ).resize( function() { self._refresh() } );\n },\n\n /** Refresh height of scrollable div below header, handle scrolling by lazy loading steps */\n _refresh: function( step_index ) {\n var margin = _.reduce( this.$el.children(), function( memo, child ) {\n return memo + $( child ).outerHeight();\n }, 0 ) - this.$steps.height() + 90;\n this.$steps.css( 'height', $( window ).height() - margin );\n },\n\n /** Configures form/step options for each workflow step */\n _configure: function() {\n var self = this;\n this.forms = [];\n this.steps = [];\n this.links = [];\n this.parms = [];\n _.each( this.model.get( 'steps' ), function( step, i ) {\n Galaxy.emit.debug( 'tool-form-composite::initialize()', i + ' : Preparing workflow step.' );\n var icon = WorkflowIcons[ step.step_type ];\n var title = parseInt( i + 1 ) + ': ' + ( step.step_label || step.step_name );\n if ( step.annotation ) {\n title += ' - ' + step.annotation;\n }\n if ( step.step_version ) {\n title += ' (Galaxy Version ' + step.step_version + ')';\n }\n step = Utils.merge( {\n index : i,\n title : _.escape( title ),\n icon : icon || '',\n help : null,\n citations : null,\n collapsible : true,\n collapsed : i > 0 && !self._isDataStep( step ),\n sustain_version : true,\n sustain_repeats : true,\n sustain_conditionals : true,\n narrow : true,\n text_enable : 'Edit',\n text_disable : 'Undo',\n cls_enable : 'fa fa-edit',\n cls_disable : 'fa fa-undo',\n errors : step.messages,\n initial_errors : true,\n cls : 'ui-portlet-narrow',\n hide_operations : true,\n needs_refresh : false,\n always_refresh : step.step_type != 'tool'\n }, step );\n self.steps[ i ] = step;\n self.links[ i ] = [];\n self.parms[ i ] = {};\n });\n\n // build linear index of step input pairs\n _.each( this.steps, function( step, i ) {\n FormData.visitInputs( step.inputs, function( input, name ) {\n self.parms[ i ][ name ] = input;\n });\n });\n\n // iterate through data input modules and collect linked sub steps\n _.each( this.steps, function( step, i ) {\n _.each( step.output_connections, function( output_connection ) {\n _.each( self.steps, function( sub_step, j ) {\n sub_step.step_index === output_connection.input_step_index && self.links[ i ].push( sub_step );\n });\n });\n });\n\n // convert all connected data inputs to hidden fields with proper labels,\n // and track the linked source step\n _.each( this.steps, function( step, i ) {\n _.each( self.steps, function( sub_step, j ) {\n var connections_by_name = {};\n _.each( step.output_connections, function( connection ) {\n sub_step.step_index === connection.input_step_index && ( connections_by_name[ connection.input_name ] = connection );\n });\n _.each( self.parms[ j ], function( input, name ) {\n var connection = connections_by_name[ name ];\n if ( connection ) {\n input.type = 'hidden';\n input.help = input.step_linked ? input.help + ', ' : '';\n input.help += 'Output dataset \\'' + connection.output_name + '\\' from step ' + ( parseInt( i ) + 1 );\n input.step_linked = input.step_linked || [];\n input.step_linked.push( step );\n }\n });\n });\n });\n\n // identify and configure workflow parameters\n var wp_count = 0;\n this.wp_inputs = {};\n function _handleWorkflowParameter( value, callback ) {\n var re = /\\$\\{(.+?)\\}/g;\n while ( match = re.exec( String( value ) ) ) {\n var wp_name = match[ 1 ];\n callback( self.wp_inputs[ wp_name ] = self.wp_inputs[ wp_name ] || {\n label : wp_name,\n name : wp_name,\n type : 'text',\n color : 'hsl( ' + ( ++wp_count * 100 ) + ', 70%, 30% )',\n style : 'ui-form-wp-source',\n links : []\n });\n }\n }\n _.each( this.steps, function( step, i ) {\n _.each( self.parms[ i ], function( input, name ) {\n _handleWorkflowParameter( input.value, function( wp_input ) {\n wp_input.links.push( step );\n input.wp_linked = true;\n input.type = 'text';\n input.backdrop = true;\n input.style = 'ui-form-wp-target';\n });\n });\n _.each( step.post_job_actions, function( pja ) {\n _.each( pja.action_arguments, function( arg ) {\n _handleWorkflowParameter( arg, function() {} );\n });\n });\n });\n\n // select fields are shown for dynamic fields if all putative data inputs are available,\n // or if an explicit reference is specified as data_ref and available\n _.each( this.steps, function( step, i ) {\n if ( step.step_type == 'tool' ) {\n var data_resolved = true;\n FormData.visitInputs( step.inputs, function ( input, name, context ) {\n var is_runtime_value = input.value && input.value.__class__ == 'RuntimeValue';\n var is_data_input = ([ 'data', 'data_collection' ]).indexOf( input.type ) != -1;\n var data_ref = context[ input.data_ref ];\n input.step_linked && !self._isDataStep( input.step_linked ) && ( data_resolved = false );\n input.options && ( ( input.options.length == 0 && !data_resolved ) || input.wp_linked ) && ( input.is_workflow = true );\n data_ref && ( input.is_workflow = ( data_ref.step_linked && !self._isDataStep( data_ref.step_linked ) ) || input.wp_linked );\n ( is_data_input || ( input.value && input.value.__class__ == 'RuntimeValue' && !input.step_linked ) ) && ( step.collapsed = false );\n is_runtime_value && ( input.value = input.default_value );\n input.flavor = 'workflow';\n if ( !is_runtime_value && !is_data_input && input.type !== 'hidden' && !input.wp_linked ) {\n if ( input.optional || ( !Utils.isEmpty( input.value ) && input.value !== '' ) ) {\n input.collapsible_value = input.value;\n input.collapsible_preview = true;\n }\n }\n });\n }\n });\n },\n\n render: function() {\n var self = this;\n this.deferred.reset();\n this._renderHeader();\n this._renderMessage();\n this._renderParameters();\n this._renderHistory();\n _.each ( this.steps, function( step ) { self._renderStep( step ) } );\n },\n\n /** Render header */\n _renderHeader: function() {\n var self = this;\n this.execute_btn = new Ui.Button({\n icon : 'fa-check',\n title : 'Run workflow',\n cls : 'btn btn-primary',\n onclick : function() { self._execute() }\n });\n this.$header.addClass( 'ui-form-header' ).empty()\n .append( new Ui.Label( { title: 'Workflow: ' + this.model.get( 'name' ) } ).$el )\n .append( this.execute_btn.$el );\n },\n\n /** Render message */\n _renderMessage: function() {\n this.$message.empty();\n if ( this.model.get( 'has_upgrade_messages' ) ) {\n this.$message.append( new Ui.Message( {\n message : 'Some tools in this workflow may have changed since it was last saved or some errors were found. The workflow may still run, but any new options will have default values. Please review the messages below to make a decision about whether the changes will affect your analysis.',\n status : 'warning',\n persistent : true,\n fade : false\n } ).$el );\n }\n var step_version_changes = this.model.get( 'step_version_changes' );\n if ( step_version_changes && step_version_changes.length > 0 ) {\n this.$message.append( new Ui.Message( {\n message : 'Some tools are being executed with different versions compared to those available when this workflow was last saved because the other versions are not or no longer available on this Galaxy instance. To upgrade your workflow and dismiss this message simply edit the workflow and re-save it.',\n status : 'warning',\n persistent : true,\n fade : false\n } ).$el );\n }\n },\n\n /** Render workflow parameters */\n _renderParameters: function() {\n var self = this;\n this.wp_form = null;\n if ( !_.isEmpty( this.wp_inputs ) ) {\n this.wp_form = new Form({ title: 'Workflow Parameters', inputs: this.wp_inputs, cls: 'ui-portlet-narrow', onchange: function() {\n _.each( self.wp_form.input_list, function( input_def, i ) {\n _.each( input_def.links, function( step ) { self._refreshStep( step ) } );\n });\n }\n });\n this._append( this.$steps.empty(), this.wp_form.$el );\n }\n },\n\n /** Render workflow parameters */\n _renderHistory: function() {\n this.history_form = new Form({\n cls : 'ui-portlet-narrow',\n title : 'History Options',\n inputs : [{\n type : 'conditional',\n name : 'new_history',\n test_param : {\n name : 'check',\n label : 'Send results to a new history',\n type : 'boolean',\n value : 'false',\n help : ''\n },\n cases : [{\n value : 'true',\n inputs : [{\n name : 'name',\n label : 'History name',\n type : 'text',\n value : this.model.get( 'name' )\n }]\n }]\n }]\n });\n this._append( this.$steps, this.history_form.$el );\n },\n\n /** Render step */\n _renderStep: function( step ) {\n var self = this;\n var form = null;\n this.deferred.execute( function( promise ) {\n self.$steps.addClass( 'ui-steps' );\n if ( step.step_type == 'tool' ) {\n step.postchange = function( process, form ) {\n var self = this;\n var current_state = {\n tool_id : step.id,\n tool_version : step.version,\n inputs : $.extend( true, {}, form.data.create() )\n }\n form.wait( true );\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Sending current state.', current_state );\n Utils.request({\n type : 'POST',\n url : Galaxy.root + 'api/tools/' + step.id + '/build',\n data : current_state,\n success : function( data ) {\n form.update( data );\n form.wait( false );\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Received new model.', data );\n process.resolve();\n },\n error : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::postchange()', 'Refresh request failed.', response );\n process.reject();\n }\n });\n };\n form = new ToolFormBase( step );\n if ( step.post_job_actions && step.post_job_actions.length ) {\n form.portlet.append( $( '
                                              ' ).addClass( 'ui-form-element-disabled' )\n .append( $( '
                                              ' ).addClass( 'ui-form-title' ).html( 'Job Post Actions' ) )\n .append( $( '
                                              ' ).addClass( 'ui-form-preview' ).html(\n _.reduce( step.post_job_actions, function( memo, value ) {\n return memo + ' ' + value.short_str;\n }, '' ) ) )\n );\n }\n } else {\n var is_simple_input = ([ 'data_input', 'data_collection_input' ]).indexOf( step.step_type ) != -1;\n _.each( step.inputs, function( input ) { input.flavor = 'module'; input.hide_label = is_simple_input; } );\n form = new Form( Utils.merge({\n title : step.title,\n onchange : function() { _.each( self.links[ step.index ], function( link ) { self._refreshStep( link ) } ) },\n inputs : step.inputs && step.inputs.length > 0 ? step.inputs : [ { type: 'hidden', name: 'No options available.', ignore: null } ]\n }, step ) );\n }\n self.forms[ step.index ] = form;\n self._append( self.$steps, form.$el );\n self._refresh();\n step.needs_refresh && self._refreshStep( step );\n form.portlet[ !self.show_progress ? 'enable' : 'disable' ]();\n self.show_progress && self.execute_btn.model.set( { wait : true,\n wait_text : 'Preparing...',\n percentage : ( step.index + 1 ) * 100.0 / self.steps.length } );\n Galaxy.emit.debug( 'tool-form-composite::initialize()', step.index + ' : Workflow step state ready.', step );\n setTimeout( function() { promise.resolve() }, 0 );\n });\n },\n\n /** Refreshes step values from source step values */\n _refreshStep: function( step ) {\n var self = this;\n var form = this.forms[ step.index ];\n if ( form ) {\n _.each( self.parms[ step.index ], function( input, name ) {\n if ( input.step_linked || input.wp_linked ) {\n var field = form.field_list[ form.data.match( name ) ];\n if ( field ) {\n var new_value = undefined;\n if ( input.step_linked ) {\n new_value = { values: [] };\n _.each( input.step_linked, function( source_step ) {\n if ( self._isDataStep( source_step ) ) {\n value = self.forms[ source_step.index ].data.create().input;\n value && _.each( value.values, function( v ) { new_value.values.push( v ) } );\n }\n });\n if ( !input.multiple && new_value.values.length > 0 ) {\n new_value = { values: [ new_value.values[ 0 ] ] };\n }\n } else if ( input.wp_linked ) {\n new_value = input.value;\n var re = /\\$\\{(.+?)\\}/g;\n while ( match = re.exec( input.value ) ) {\n var wp_field = self.wp_form.field_list[ self.wp_form.data.match( match[ 1 ] ) ];\n var wp_value = wp_field && wp_field.value();\n if ( wp_value ) {\n new_value = new_value.split( match[ 0 ] ).join( wp_value );\n }\n }\n }\n if ( new_value !== undefined ) {\n field.value( new_value );\n }\n }\n }\n });\n form.trigger( 'change' );\n } else {\n step.needs_refresh = true;\n }\n },\n\n /** Refresh the history after job submission while form is shown */\n _refreshHistory: function() {\n var self = this;\n var history = parent.Galaxy && parent.Galaxy.currHistoryPanel && parent.Galaxy.currHistoryPanel.model;\n this._refresh_history && clearTimeout( this._refresh_history );\n if ( history ) {\n history.refresh().success( function() {\n if ( history.numOfUnfinishedShownContents() === 0 ) {\n self._refresh_history = setTimeout( function() { self._refreshHistory() }, history.UPDATE_DELAY );\n }\n });\n }\n },\n\n /** Build remaining steps */\n _execute: function() {\n var self = this;\n this.show_progress = true;\n this._enabled( false );\n this.deferred.execute( function( promise ) {\n setTimeout( function() { promise.resolve(); self._submit(); }, 0 );\n });\n },\n\n /** Validate and submit workflow */\n _submit: function() {\n var self = this;\n var history_form_data = this.history_form.data.create();\n var job_def = {\n new_history_name : history_form_data[ 'new_history|name' ] ? history_form_data[ 'new_history|name' ] : null,\n history_id : !history_form_data[ 'new_history|name' ] ? this.model.get( 'history_id' ) : null,\n replacement_params : this.wp_form ? this.wp_form.data.create() : {},\n parameters : {},\n // Tool form will submit flat maps for each parameter\n // (e.g. \"repeat_0|cond|param\": \"foo\" instead of nested\n // data structures).\n parameters_normalized : true,\n // Tool form always wants a list of invocations back\n // so that inputs can be batched.\n batch : true\n };\n var validated = true;\n for ( var i in this.forms ) {\n var form = this.forms[ i ];\n var job_inputs = form.data.create();\n var step = self.steps[ i ];\n var step_index = step.step_index;\n form.trigger( 'reset' );\n for ( var job_input_id in job_inputs ) {\n var input_value = job_inputs[ job_input_id ];\n var input_id = form.data.match( job_input_id );\n var input_field = form.field_list[ input_id ];\n var input_def = form.input_list[ input_id ];\n if ( !input_def.step_linked ) {\n if ( this._isDataStep( step ) ) {\n validated = input_value && input_value.values && input_value.values.length > 0;\n } else {\n validated = input_def.optional || ( input_def.is_workflow && input_value !== '' ) || ( !input_def.is_workflow && input_value !== null );\n }\n if ( !validated ) {\n form.highlight( input_id );\n break;\n }\n job_def.parameters[ step_index ] = job_def.parameters[ step_index ] || {};\n job_def.parameters[ step_index ][ job_input_id ] = job_inputs[ job_input_id ];\n }\n }\n if ( !validated ) {\n break;\n }\n }\n if ( !validated ) {\n self._enabled( true );\n Galaxy.emit.debug( 'tool-form-composite::submit()', 'Validation failed.', job_def );\n } else {\n Galaxy.emit.debug( 'tool-form-composite::submit()', 'Validation complete.', job_def );\n Utils.request({\n type : 'POST',\n url : Galaxy.root + 'api/workflows/' + this.model.id + '/invocations',\n data : job_def,\n success : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::submit', 'Submission successful.', response );\n self.$el.children().hide();\n self.$el.append( self._templateSuccess( response ) );\n\n // Show Webhook if job is running\n if ($.isArray( response ) && response.length > 0) {\n self.$el.append( $( '
                                              ', { id: 'webhook-view' } ) );\n var WebhookApp = new Webhooks.WebhookView({\n urlRoot: Galaxy.root + 'api/webhooks/workflow',\n toolId: job_def.tool_id,\n toolVersion: job_def.tool_version,\n });\n }\n\n self._refreshHistory();\n },\n error : function( response ) {\n Galaxy.emit.debug( 'tool-form-composite::submit', 'Submission failed.', response );\n var input_found = false;\n if ( response && response.err_data ) {\n for ( var i in self.forms ) {\n var form = self.forms[ i ];\n var step_related_errors = response.err_data[ form.model.get( 'step_index' ) ];\n if ( step_related_errors ) {\n var error_messages = form.data.matchResponse( step_related_errors );\n for ( var input_id in error_messages ) {\n form.highlight( input_id, error_messages[ input_id ] );\n input_found = true;\n break;\n }\n }\n }\n }\n if ( !input_found ) {\n self.modal.show({\n title : 'Workflow submission failed',\n body : self._templateError( job_def, response && response.err_msg ),\n buttons : {\n 'Close' : function() {\n self.modal.hide();\n }\n }\n });\n }\n },\n complete: function() {\n self._enabled( true );\n }\n });\n }\n },\n\n /** Append new dom to body */\n _append: function( $container, $el ) {\n $container.append( '

                                              ' ).append( $el );\n },\n\n /** Set enabled/disabled state */\n _enabled: function( enabled ) {\n this.execute_btn.model.set( { wait: !enabled, wait_text: 'Sending...', percentage: -1 } );\n this.wp_form && this.wp_form.portlet[ enabled ? 'enable' : 'disable' ]();\n this.history_form && this.history_form.portlet[ enabled ? 'enable' : 'disable' ]();\n _.each( this.forms, function( form ) { form && form.portlet[ enabled ? 'enable' : 'disable' ]() } );\n },\n\n /** Is data input module/step */\n _isDataStep: function( steps ) {\n lst = $.isArray( steps ) ? steps : [ steps ] ;\n for ( var i = 0; i < lst.length; i++ ) {\n var step = lst[ i ];\n if ( !step || !step.step_type || !step.step_type.startsWith( 'data' ) ) {\n return false;\n }\n }\n return true;\n },\n\n /** Templates */\n _templateSuccess: function( response ) {\n if ( $.isArray( response ) && response.length > 0 ) {\n return $( '

                                              ' ).addClass( 'donemessagelarge' )\n .append( $( '

                                              ' ).html( 'Successfully invoked workflow ' + Utils.sanitize( this.model.get( 'name' ) ) + '' + ( response.length > 1 ? ' ' + response.length + ' times' : '' ) + '.' ) )\n .append( $( '

                                              ' ).append( '' ).text( 'You can check the status of queued jobs and view the resulting data by refreshing the History pane. When the job has been run the status will change from \\'running\\' to \\'finished\\' if completed successfully or \\'error\\' if problems were encountered.' ) );\n } else {\n return this._templateError( response, 'Invalid success response. No invocations found.' );\n }\n },\n\n _templateError: function( response, err_msg ) {\n return $( '

                                              ' ).addClass( 'errormessagelarge' )\n .append( $( '

                                              ' ).text( 'The server could not complete the request. Please contact the Galaxy Team if this error persists. ' + ( JSON.stringify( err_msg ) || '' ) ) )\n .append( $( '

                                              ' ).text( JSON.stringify( response, null, 4 ) ) );\n        }\n    });\n    return {\n        View: View\n    };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/tool/tool-form-composite.js","define([\n    \"utils/localization\"\n], function( _l ){\n'use strict';\n\n//TODO: toastr is another possibility - I didn't see where I might add details, tho\n\n/* ============================================================================\nError modals meant to replace the o-so-easy alerts.\n\nThese are currently styled as errormessages but use the Galaxy.modal\ninfrastructure to be shown/closed. They're capable of showing details in a\ntogglable dropdown and the details are formatted in a pre.\n\nExample:\n    errorModal( 'Heres a message', 'A Title', { some_details: 'here' });\n    errorModal( 'Heres a message' ); // no details, title is 'Error'\n\nThere are three specialized forms:\n    offlineErrorModal       a canned response for when there's no connection\n    badGatewayErrorModal    canned response for when Galaxy is restarting\n    ajaxErrorModal          plugable into any Backbone class as an\n        error event handler by accepting the error args: model, xhr, options\n\nExamples:\n    if( navigator.offLine ){ offlineErrorModal(); }\n    if( xhr.status === 502 ){ badGatewayErrorModal(); }\n    this.listenTo( this.model, 'error', ajaxErrorModal );\n\n============================================================================ */\n\nvar CONTACT_MSG = _l( 'Please contact a Galaxy administrator if the problem persists.' );\nvar DEFAULT_AJAX_ERR_MSG = _l( 'An error occurred while updating information with the server.' );\nvar DETAILS_MSG = _l( 'The following information can assist the developers in finding the source of the error:' );\n\n/** private helper that builds the modal and handles adding details */\nfunction _errorModal( message, title, details ){\n    // create and return the modal, adding details button only if needed\n    Galaxy.modal.show({\n        title           : title,\n        body            : message,\n        closing_events  : true,\n        buttons         : { Ok: function(){ Galaxy.modal.hide(); } },\n    });\n    Galaxy.modal.$el.addClass( 'error-modal' );\n\n    if( details ){\n        Galaxy.modal.$( '.error-details' ).add( Galaxy.modal.$( 'button:contains(\"Details\")' ) ).remove();\n        $( '
                                              ' ).addClass( 'error-details' )\n .hide().appendTo( Galaxy.modal.$( '.modal-content' ) )\n .append([\n $( '

                                              ' ).text( DETAILS_MSG ),\n $( '

                                              ' ).text( JSON.stringify( details, null, '  ' ) )\n            ]);\n\n        $( '' )\n            .appendTo( Galaxy.modal.$( '.buttons' ) )\n            .click( function(){ Galaxy.modal.$( '.error-details' ).toggle(); });\n    }\n    return Galaxy.modal;\n}\n\n/** Display a modal showing an error message but fallback to alert if there's no modal */\nfunction errorModal( message, title, details ){\n    if( !message ){ return; }\n\n    message = _l( message );\n    title = _l( title ) || _l( 'Error:' );\n    if( window.Galaxy && Galaxy.modal ){\n        return _errorModal( message, title, details );\n    }\n\n    alert( title + '\\n\\n' + message );\n    console.log( 'error details:', JSON.stringify( details ) );\n}\n\n\n// ----------------------------------------------------------------------------\n/** display a modal when the user may be offline */\nfunction offlineErrorModal(){\n    return errorModal(\n        _l( 'You appear to be offline. Please check your connection and try again.' ),\n        _l( 'Offline?' )\n    );\n}\n\n\n// ----------------------------------------------------------------------------\n/** 502 messages that should be displayed when galaxy is restarting */\nfunction badGatewayErrorModal(){\n    return errorModal(\n        _l( 'Galaxy is currently unreachable. Please try again in a few minutes.' ) + ' ' + CONTACT_MSG,\n        _l( 'Cannot connect to Galaxy' )\n    );\n}\n\n\n// ----------------------------------------------------------------------------\n/** display a modal (with details) about a failed Backbone ajax operation */\nfunction ajaxErrorModal( model, xhr, options, message, title ){\n    message = message || DEFAULT_AJAX_ERR_MSG;\n    message += ' ' + CONTACT_MSG;\n    title = title || _l( 'An error occurred' );\n    var details = _ajaxDetails( model, xhr, options );\n    return errorModal( message, title, details );\n}\n\n/** build details which may help debugging the ajax call */\nfunction _ajaxDetails( model, xhr, options ){\n    return {\n//TODO: still can't manage Raven id\n        raven       : _.result( window.Raven, 'lastEventId' ),\n        userAgent   : navigator.userAgent,\n        onLine      : navigator.onLine,\n        version     : _.result( Galaxy.config, 'version_major' ),\n        xhr         : _.omit( xhr, _.functions( xhr ) ),\n        options     : _.omit( options, 'xhr' ),\n        // add ajax data from Galaxy object cache\n        url         : _.result( Galaxy.lastAjax, 'url' ),\n        data        : _.result( Galaxy.lastAjax, 'data' ),\n        // backbone stuff (auto-redacting email for user)\n        model       : _.result( model, 'toJSON' , model + '' ),\n        user        : _.omit( _.result( Galaxy.user, 'toJSON' ), 'email' ),\n    };\n}\n\n\n//=============================================================================\n    return {\n        errorModal          : errorModal,\n        offlineErrorModal   : offlineErrorModal,\n        badGatewayErrorModal: badGatewayErrorModal,\n        ajaxErrorModal      : ajaxErrorModal\n    };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/ui/error-modal.js","(function (factory) {\n    if (typeof define === 'function' && define.amd) {\n        define([], factory);\n    } else {\n        // Browser globals\n        factory(jQuery);\n    }\n\n}(function () {\n//=============================================================================\n\n    jQuery.fn.extend({\n        hoverhighlight : function $hoverhighlight( scope, color ){\n            scope = scope || 'body';\n            if( !this.length ){ return this; }\n\n            $( this ).each( function(){\n                var $this = $( this ),\n                    targetSelector = $this.data( 'target' );\n\n                if( targetSelector ){\n                    $this.mouseover( function( ev ){\n                        $( targetSelector, scope ).css({\n                            background: color\n                        });\n                    })\n                    .mouseout( function( ev ){\n                        $( targetSelector ).css({\n                            background: ''\n                        });\n                    });\n                }\n            });\n            return this;\n        }\n    });\n}));\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/ui/hoverhighlight.js","// from: https://raw.githubusercontent.com/umdjs/umd/master/jqueryPlugin.js\n// Uses AMD or browser globals to create a jQuery plugin.\n(function (factory) {\n    if (typeof define === 'function' && define.amd) {\n        //TODO: So...this turns out to be an all or nothing thing. If I load jQuery in the define below, it will\n        //  (of course) wipe the old jquery *and all the plugins loaded into it*. So the define below *is still\n        //  relying on jquery being loaded globally* in order to preserve plugins.\n        define([], factory);\n    } else {\n        // Browser globals\n        factory(jQuery);\n    }\n\n}(function () {\n    var _l = window._l || function( s ){ return s; };\n\n    //TODO: consolidate with tool menu functionality, use there\n\n    /** searchInput: (jQuery plugin)\n     *      Creates a search input, a clear button, and loading indicator\n     *      within the selected node.\n     *\n     *      When the user either presses return or enters some minimal number\n     *      of characters, a callback is called. Pressing ESC when the input\n     *      is focused will clear the input and call a separate callback.\n     */\n    function searchInput( parentNode, options ){\n        var KEYCODE_ESC     = 27,\n            KEYCODE_RETURN  = 13,\n            $parentNode     = $( parentNode ),\n            firstSearch     = true,\n            defaults = {\n                initialVal      : '',\n                name            : 'search',\n                placeholder     : 'search',\n                classes         : '',\n                onclear         : function(){},\n                onfirstsearch   : null,\n                onsearch        : function( inputVal ){},\n                minSearchLen    : 0,\n                escWillClear    : true,\n                oninit          : function(){}\n            };\n\n        // .................................................................... input rendering and events\n        // visually clear the search, trigger an event, and call the callback\n        function clearSearchInput( event ){\n            var $input = $( this ).parent().children( 'input' );\n            $input.val( '' ).trigger( 'searchInput.clear' ).blur();\n            options.onclear();\n        }\n\n        // search for searchTerms, trigger an event, call the appropo callback (based on whether this is the first)\n        function search( event, searchTerms ){\n            if( !searchTerms ){\n                return clearSearchInput();\n            }\n            $( this ).trigger( 'search.search', searchTerms );\n            if( typeof options.onfirstsearch === 'function' && firstSearch ){\n                firstSearch = false;\n                options.onfirstsearch( searchTerms );\n            } else {\n                options.onsearch( searchTerms );\n            }\n        }\n\n        // .................................................................... input rendering and events\n        function inputTemplate(){\n            // class search-query is bootstrap 2.3 style that now lives in base.less\n            return [ '' ].join( '' );\n        }\n\n        // the search input that responds to keyboard events and displays the search value\n        function $input(){\n            return $( inputTemplate() )\n                // select all text on a focus\n                .focus( function( event ){\n                    $( this ).select();\n                })\n                // attach behaviors to esc, return if desired, search on some min len string\n                .keyup( function( event ){\n                    event.preventDefault();\n                    event.stopPropagation();\n\n                    // esc key will clear if desired\n                    if( event.which === KEYCODE_ESC && options.escWillClear ){\n                        clearSearchInput.call( this, event );\n\n                    } else {\n                        var searchTerms = $( this ).val();\n                        // return key or the search string len > minSearchLen (if not 0) triggers search\n                        if( ( event.which === KEYCODE_RETURN )\n                        ||  ( options.minSearchLen && searchTerms.length >= options.minSearchLen ) ){\n                            search.call( this, event, searchTerms );\n                        }\n                    }\n                })\n                .val( options.initialVal );\n        }\n\n        // .................................................................... clear button rendering and events\n        // a button for clearing the search bar, placed on the right hand side\n        function $clearBtn(){\n            return $([ '' ].join('') )\n            .tooltip({ placement: 'bottom' })\n            .click( function( event ){\n                clearSearchInput.call( this, event );\n            });\n        }\n\n        // .................................................................... loadingIndicator rendering\n        // a button for clearing the search bar, placed on the right hand side\n        function $loadingIndicator(){\n            return $([ '' ].join('') )\n                .hide().tooltip({ placement: 'bottom' });\n        }\n\n        // .................................................................... commands\n        // visually swap the load, clear buttons\n        function toggleLoadingIndicator(){\n            $parentNode.find( '.search-loading' ).toggle();\n            $parentNode.find( '.search-clear' ).toggle();\n        }\n\n        // .................................................................... init\n        // string command (not constructor)\n        if( jQuery.type( options ) === 'string' ){\n            if( options === 'toggle-loading' ){\n                toggleLoadingIndicator();\n            }\n            return $parentNode;\n        }\n\n        // initial render\n        if( jQuery.type( options ) === 'object' ){\n            options = jQuery.extend( true, {}, defaults, options );\n        }\n        //NOTE: prepended\n        return $parentNode.addClass( 'search-input' ).prepend([ $input(), $clearBtn(), $loadingIndicator() ]);\n    }\n\n    // as jq plugin\n    jQuery.fn.extend({\n        searchInput : function $searchInput( options ){\n            return this.each( function(){\n                return searchInput( this, options );\n            });\n        }\n    });\n}));\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/ui/search-input.js","define([], function(){\n// Alphanumeric/natural sort fn\nfunction naturalSort(a, b) {\n    // setup temp-scope variables for comparison evauluation\n    var re = /(-?[0-9\\.]+)/g,\n        x = a.toString().toLowerCase() || '',\n        y = b.toString().toLowerCase() || '',\n        nC = String.fromCharCode(0),\n        xN = x.replace( re, nC + '$1' + nC ).split(nC),\n        yN = y.replace( re, nC + '$1' + nC ).split(nC),\n        xD = (new Date(x)).getTime(),\n        yD = xD ? (new Date(y)).getTime() : null;\n    // natural sorting of dates\n    if ( yD ) {\n        if ( xD < yD ) { return -1; }\n        else if ( xD > yD ) { return 1; }\n    }\n    // natural sorting through split numeric strings and default strings\n    var oFxNcL, oFyNcL;\n    for ( var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++ ) {\n        oFxNcL = parseFloat(xN[cLoc]) || xN[cLoc];\n        oFyNcL = parseFloat(yN[cLoc]) || yN[cLoc];\n        if (oFxNcL < oFyNcL) { return -1; }\n        else if (oFxNcL > oFyNcL) { return 1; }\n    }\n    return 0;\n}\n\nreturn naturalSort;\n})\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/utils/natural-sort.js","var Ui = require( 'mvc/ui/ui-misc' ),\n    historyOptionsMenu = require( 'mvc/history/options-menu' );\n    CurrentHistoryView = require( 'mvc/history/history-view-edit-current' ).CurrentHistoryView,\n    _l = require( 'utils/localization' );\n\n/** the right hand panel in the analysis page that shows the current history */\nvar HistoryPanel = Backbone.View.extend({\n\n    initialize : function( page, options ) {\n        var self = this;\n        this.userIsAnonymous            = Galaxy.user.isAnonymous();\n        this.allow_user_dataset_purge   = options.config.allow_user_dataset_purge;\n        this.root                       = options.root;\n\n        // view of the current history\n        this.historyView = new CurrentHistoryView({\n            className       : CurrentHistoryView.prototype.className + ' middle',\n            purgeAllowed    : this.allow_user_dataset_purge,\n            linkTarget      : 'galaxy_main'\n        });\n\n        // add history panel to Galaxy object\n        Galaxy.currHistoryPanel = this.historyView;\n        Galaxy.currHistoryPanel.listenToGalaxy( Galaxy );\n\n        // build buttons\n        this.buttonRefresh = new Ui.ButtonLink({\n            id      : 'history-refresh-button',\n            title   : 'Refresh history',\n            cls     : 'panel-header-button',\n            icon    : 'fa fa-refresh',\n            onclick : function() {\n                self.historyView.loadCurrentHistory();\n            }\n        });\n        this.buttonOptions = new Ui.ButtonLink({\n            id      : 'history-options-button',\n            title   : 'History options',\n            cls     : 'panel-header-button',\n            target  : 'galaxy_main',\n            icon    : 'fa fa-cog',\n            href    : this.root + 'root/history_options'\n        });\n        this.buttonViewMulti = new Ui.ButtonLink({\n            id      : 'history-view-multi-button',\n            title   : 'View all histories',\n            cls     : 'panel-header-button',\n            icon    : 'fa fa-columns',\n            href    : this.root + 'history/view_multiple'\n        });\n\n        // define components\n        this.model = new Backbone.Model({\n            cls     : 'history-right-panel',\n            title   : _l( 'History' ),\n            buttons : [ this.buttonRefresh, this.buttonOptions, this.buttonViewMulti ]\n        });\n\n        // build body template and connect history view\n        this.setElement( this._template() );\n        this.historyView.setElement( this.$el );\n        this.historyView.connectToQuotaMeter( Galaxy.quotaMeter );\n        this.historyView.loadCurrentHistory();\n\n        // fetch to update the quota meter adding 'current' for any anon-user's id\n        Galaxy.listenTo( this.historyView, 'history-size-change', function(){\n            Galaxy.user.fetch({ url: Galaxy.user.urlRoot() + '/' + ( Galaxy.user.id || 'current' ) });\n        });\n    },\n\n    render : function() {\n        this.optionsMenu = historyOptionsMenu( this.buttonOptions.$el, {\n            anonymous    : this.userIsAnonymous,\n            purgeAllowed : this.allow_user_dataset_purge,\n            root         : this.root\n        });\n        this.buttonViewMulti.$el[ !this.userIsAnonymous ? 'show' : 'hide' ]();\n    },\n\n    /** add history view div */\n    _template : function( data ){\n        return [\n            '
                                              ',\n ].join('');\n },\n\n toString : function() { return 'historyPanel' }\n});\n\nmodule.exports = HistoryPanel;\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/apps/panels/history-panel.js","var Tools = require( 'mvc/tool/tools' ),\n Upload = require( 'mvc/upload/upload-view' ),\n _l = require( 'utils/localization' ),\n ToolForm = require( 'mvc/tool/tool-form-composite' );\n\nvar ToolPanel = Backbone.View.extend({\n initialize: function( page, options ) {\n // access configuration options\n var config = options.config;\n this.root = options.root;\n\n /** @type {Object[]} descriptions of user's workflows to be shown in the tool menu */\n this.stored_workflow_menu_entries = config.stored_workflow_menu_entries || [];\n\n // create tool search, tool panel, and tool panel view.\n var tool_search = new Tools.ToolSearch({\n hidden : false\n });\n var tools = new Tools.ToolCollection( config.toolbox );\n this.tool_panel = new Tools.ToolPanel({\n tool_search : tool_search,\n tools : tools,\n layout : config.toolbox_in_panel\n });\n this.tool_panel_view = new Tools.ToolPanelView({ model: this.tool_panel });\n\n // add upload modal\n this.upload_button = new Upload({\n nginx_upload_path : config.nginx_upload_path,\n ftp_upload_site : config.ftp_upload_site,\n default_genome : config.default_genome,\n default_extension : config.default_extension,\n });\n\n // add uploader button to Galaxy object\n Galaxy.upload = this.upload_button;\n\n // components for panel definition\n this.model = new Backbone.Model({\n title : _l( 'Tools' ),\n buttons : [ this.upload_button ]\n });\n\n // build body template\n this.setElement( this._template() );\n },\n\n render : function(){\n // if there are tools, render panel and display everything\n var self = this;\n if ( this.tool_panel.get( 'layout' ).size() > 0 ) {\n this.$el.prepend( this.tool_panel_view.$el );\n this.tool_panel_view.render();\n }\n // build the dom for the workflow portion of the tool menu\n // add internal workflow list\n self.$( '#internal-workflows' ).append( self._templateAllWorkflow({\n title : _l( 'All workflows' ),\n href : 'workflow'\n }));\n _.each( this.stored_workflow_menu_entries, function( menu_entry ){\n self.$( '#internal-workflows' ).append( self._templateWorkflowLink({\n title : menu_entry.stored_workflow.name,\n href : 'workflow/run?id=' + menu_entry.encoded_stored_workflow_id\n }));\n });\n },\n\n /** build a link to one tool */\n _templateTool: function( tool ) {\n return [\n '
                                              ',\n '', tool.title, '',\n '
                                              '\n ].join('');\n },\n\n /** build a link to 'All Workflows' */\n _templateAllWorkflow: function( tool ) {\n return [\n '
                                              ',\n // global\n '', tool.title, '',\n '
                                              '\n ].join('');\n },\n\n /** build links to workflows in toolpanel */\n _templateWorkflowLink: function( wf ) {\n return [\n '
                                              ',\n '', wf.title, '',\n '
                                              '\n ].join('');\n },\n\n /** override to include inital menu dom and workflow section */\n _template : function() {\n return [\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '', _l( 'Search did not match any tools.' ), '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '', _l( 'Workflows' ), '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ].join('');\n },\n\n toString : function() { return 'toolPanel' }\n});\n\nmodule.exports = ToolPanel;\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/apps/panels/tool-panel.js","define([\n \"mvc/collection/collection-li\",\n \"mvc/dataset/dataset-li-edit\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( DC_LI, DATASET_LI_EDIT, BASE_MVC, _l ){\n\n'use strict';\n//==============================================================================\nvar DCListItemView = DC_LI.DCListItemView;\n/** @class Edit view for DatasetCollection.\n */\nvar DCListItemEdit = DCListItemView.extend(\n/** @lends DCListItemEdit.prototype */{\n\n /** override to add linkTarget */\n initialize : function( attributes ){\n DCListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\nvar DCEListItemView = DC_LI.DCEListItemView;\n/** @class Read only view for DatasetCollectionElement.\n */\nvar DCEListItemEdit = DCEListItemView.extend(\n/** @lends DCEListItemEdit.prototype */{\n//TODO: this might be expendable - compacted with HDAListItemView\n\n /** set up */\n initialize : function( attributes ){\n DCEListItemView.prototype.initialize.call( this, attributes );\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DCEListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n// NOTE: this does not inherit from DatasetDCEListItemView as you would expect\n//TODO: but should - if we can find something simpler than using diamond\n/** @class Editable view for a DatasetCollectionElement that is also an DatasetAssociation\n * (a dataset contained in a dataset collection).\n */\nvar DatasetDCEListItemEdit = DATASET_LI_EDIT.DatasetListItemEdit.extend(\n/** @lends DatasetDCEListItemEdit.prototype */{\n\n /** set up */\n initialize : function( attributes ){\n DATASET_LI_EDIT.DatasetListItemEdit.prototype.initialize.call( this, attributes );\n },\n\n // NOTE: this does not inherit from DatasetDCEListItemView - so we duplicate this here\n //TODO: fix\n /** In this override, only get details if in the ready state.\n * Note: fetch with no 'change' event triggering to prevent automatic rendering.\n */\n _fetchModelDetails : function(){\n var view = this;\n if( view.model.inReadyState() && !view.model.hasDetails() ){\n return view.model.fetch({ silent: true });\n }\n return jQuery.when();\n },\n\n /** Override to remove delete button */\n _renderDeleteButton : function(){\n return null;\n },\n\n // ......................................................................... misc\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'DatasetDCEListItemEdit(' + modelString + ')';\n }\n});\n\n// ............................................................................ TEMPLATES\n/** underscore templates */\nDatasetDCEListItemEdit.prototype.templates = (function(){\n\n return _.extend( {}, DATASET_LI_EDIT.DatasetListItemEdit.prototype.templates, {\n titleBar : DC_LI.DatasetDCEListItemView.prototype.templates.titleBar\n });\n}());\n\n\n//==============================================================================\n/** @class Read only view for a DatasetCollectionElement that is also a DatasetCollection\n * (a nested DC).\n */\nvar NestedDCDCEListItemEdit = DC_LI.NestedDCDCEListItemView.extend(\n/** @lends NestedDCDCEListItemEdit.prototype */{\n\n /** String representation */\n toString : function(){\n var modelString = ( this.model )?( this.model + '' ):( '(no model)' );\n return 'NestedDCDCEListItemEdit(' + modelString + ')';\n }\n});\n\n\n//==============================================================================\n return {\n DCListItemEdit : DCListItemEdit,\n DCEListItemEdit : DCEListItemEdit,\n DatasetDCEListItemEdit : DatasetDCEListItemEdit,\n NestedDCDCEListItemEdit : NestedDCDCEListItemEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-li-edit.js","define([\n \"mvc/collection/collection-view\",\n \"mvc/collection/collection-model\",\n \"mvc/collection/collection-li-edit\",\n \"mvc/base-mvc\",\n \"mvc/tag\",\n \"ui/fa-icon-button\",\n \"utils/localization\",\n \"ui/editable-text\",\n], function( DC_VIEW, DC_MODEL, DC_EDIT, BASE_MVC, TAGS, faIconButton, _l ){\n\n'use strict';\n/* =============================================================================\nTODO:\n\n============================================================================= */\n/** @class editable View/Controller for a dataset collection.\n */\nvar _super = DC_VIEW.CollectionView;\nvar CollectionViewEdit = _super.extend(\n/** @lends CollectionView.prototype */{\n //MODEL is either a DatasetCollection (or subclass) or a DatasetCollectionElement (list of pairs)\n\n /** logger used to record this.log messages, commonly set to console */\n //logger : console,\n\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_EDIT.DatasetDCEListItemEdit,\n /** sub view class used for nested collections */\n NestedDCDCEViewClass: DC_EDIT.NestedDCDCEListItemEdit,\n\n // ......................................................................... SET UP\n /** Set up the view, set up storage, bind listeners to HistoryContents events\n * @param {Object} attributes optional settings for the panel\n */\n initialize : function( attributes ){\n _super.prototype.initialize.call( this, attributes );\n },\n\n /** In this override, make the collection name editable\n */\n _setUpBehaviors : function( $where ){\n $where = $where || this.$el;\n _super.prototype._setUpBehaviors.call( this, $where );\n if( !this.model ){ return; }\n\n // anon users shouldn't have access to any of the following\n if( !Galaxy.user || Galaxy.user.isAnonymous() ){\n return;\n }\n\n this.tagsEditorShown = true;\n\n //TODO: extract\n var panel = this,\n nameSelector = '> .controls .name';\n $where.find( nameSelector )\n .attr( 'title', _l( 'Click to rename collection' ) )\n .tooltip({ placement: 'bottom' })\n .make_text_editable({\n on_finish: function( newName ){\n var previousName = panel.model.get( 'name' );\n if( newName && newName !== previousName ){\n panel.$el.find( nameSelector ).text( newName );\n panel.model.save({ name: newName })\n .fail( function(){\n panel.$el.find( nameSelector ).text( panel.model.previous( 'name' ) );\n });\n } else {\n panel.$el.find( nameSelector ).text( previousName );\n }\n }\n });\n this.tagsEditor = new TAGS.TagsEditor({\n model : this.model,\n el : $where.find( '.tags-display' ),\n onshowFirstTime : function(){ this.render(); },\n usePrompt : false\n });\n this.tagsEditor.toggle( true );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'CollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class non-editable, read-only View/Controller for a dataset collection. */\nvar ListCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for datasets */\n DatasetDCEViewClass : DC_EDIT.DatasetDCEListItemEdit,\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class Editable, read-only View/Controller for a dataset collection. */\nvar PairCollectionViewEdit = ListCollectionViewEdit.extend(\n/** @lends PairCollectionViewEdit.prototype */{\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'PairCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class Editable (roughly since these collections are immutable),\n * View/Controller for a dataset collection.\n */\nvar NestedPairCollectionViewEdit = PairCollectionViewEdit.extend(\n/** @lends NestedPairCollectionViewEdit.prototype */{\n\n /** Override to remove the editable text from the name/identifier - these collections are considered immutable */\n _setUpBehaviors : function( $where ){\n _super.prototype._setUpBehaviors.call( this, $where );\n },\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'NestedPairCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class editable, View/Controller for a list of pairs dataset collection. */\nvar ListOfPairsCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListOfPairsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_EDIT.NestedDCDCEListItemEdit.extend({\n foldoutPanelClass : NestedPairCollectionViewEdit\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfPairsCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n// =============================================================================\n/** @class View/Controller for a list of lists dataset collection. */\nvar ListOfListsCollectionViewEdit = CollectionViewEdit.extend(\n/** @lends ListOfListsCollectionView.prototype */{\n\n //TODO: not strictly needed - due to switch in CollectionView._getContentClass\n /** sub view class used for nested collections */\n NestedDCDCEViewClass : DC_EDIT.NestedDCDCEListItemEdit.extend({\n foldoutPanelClass : NestedPairCollectionViewEdit\n }),\n\n // ........................................................................ misc\n /** string rep */\n toString : function(){\n return 'ListOfListsCollectionViewEdit(' + (( this.model )?( this.model.get( 'name' )):( '' )) + ')';\n }\n});\n\n\n//==============================================================================\n return {\n CollectionViewEdit : CollectionViewEdit,\n ListCollectionViewEdit : ListCollectionViewEdit,\n PairCollectionViewEdit : PairCollectionViewEdit,\n ListOfPairsCollectionViewEdit : ListOfPairsCollectionViewEdit,\n ListOfListsCollectionViewEdit : ListOfListsCollectionViewEdit\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/collection-view-edit.js","define([\n \"utils/levenshtein\",\n \"utils/natural-sort\",\n \"mvc/collection/base-creator\",\n \"mvc/base-mvc\",\n \"utils/localization\",\n \"ui/hoverhighlight\"\n], function( levenshteinDistance, naturalSort, baseCreator, baseMVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/* ============================================================================\nTODO:\n\n\nPROGRAMMATICALLY:\ncurrPanel.once( 'rendered', function(){\n currPanel.showSelectors();\n currPanel.selectAll();\n _.last( currPanel.actionsPopup.options ).func();\n});\n\n============================================================================ */\n/** A view for paired datasets in the collections creator.\n */\nvar PairView = Backbone.View.extend( baseMVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n tagName : 'li',\n className : 'dataset paired',\n\n initialize : function( attributes ){\n this.pair = attributes.pair || {};\n },\n\n template : _.template([\n '<%- pair.forward.name %>',\n '',\n '<%- pair.name %>',\n '',\n '<%- pair.reverse.name %>'\n ].join('')),\n\n render : function(){\n this.$el\n .attr( 'draggable', true )\n .data( 'pair', this.pair )\n .html( this.template({ pair: this.pair }) )\n .addClass( 'flex-column-container' );\n return this;\n },\n\n events : {\n 'dragstart' : '_dragstart',\n 'dragend' : '_dragend',\n 'dragover' : '_sendToParent',\n 'drop' : '_sendToParent'\n },\n\n /** dragging pairs for re-ordering */\n _dragstart : function( ev ){\n ev.currentTarget.style.opacity = '0.4';\n if( ev.originalEvent ){ ev = ev.originalEvent; }\n\n ev.dataTransfer.effectAllowed = 'move';\n ev.dataTransfer.setData( 'text/plain', JSON.stringify( this.pair ) );\n\n this.$el.parent().trigger( 'pair.dragstart', [ this ] );\n },\n\n /** dragging pairs for re-ordering */\n _dragend : function( ev ){\n ev.currentTarget.style.opacity = '1.0';\n this.$el.parent().trigger( 'pair.dragend', [ this ] );\n },\n\n /** manually bubble up an event to the parent/container */\n _sendToParent : function( ev ){\n this.$el.parent().trigger( ev );\n },\n\n /** string rep */\n toString : function(){\n return 'PairView(' + this.pair.name + ')';\n }\n});\n\n\n// ============================================================================\n/** returns an autopair function that uses the provided options.match function */\nfunction autoPairFnBuilder( options ){\n options = options || {};\n options.createPair = options.createPair || function _defaultCreatePair( params ){\n params = params || {};\n var a = params.listA.splice( params.indexA, 1 )[0],\n b = params.listB.splice( params.indexB, 1 )[0],\n aInBIndex = params.listB.indexOf( a ),\n bInAIndex = params.listA.indexOf( b );\n if( aInBIndex !== -1 ){ params.listB.splice( aInBIndex, 1 ); }\n if( bInAIndex !== -1 ){ params.listA.splice( bInAIndex, 1 ); }\n return this._pair( a, b, { silent: true });\n };\n // compile these here outside of the loop\n var _regexps = [];\n function getRegExps(){\n if( !_regexps.length ){\n _regexps = [\n new RegExp( this.filters[0] ),\n new RegExp( this.filters[1] )\n ];\n }\n return _regexps;\n }\n // mangle params as needed\n options.preprocessMatch = options.preprocessMatch || function _defaultPreprocessMatch( params ){\n var regexps = getRegExps.call( this );\n return _.extend( params, {\n matchTo : params.matchTo.name.replace( regexps[0], '' ),\n possible : params.possible.name.replace( regexps[1], '' )\n });\n };\n\n return function _strategy( params ){\n this.debug( 'autopair _strategy ---------------------------' );\n params = params || {};\n var listA = params.listA,\n listB = params.listB,\n indexA = 0, indexB,\n bestMatch = {\n score : 0.0,\n index : null\n },\n paired = [];\n //console.debug( 'params:', JSON.stringify( params, null, ' ' ) );\n this.debug( 'starting list lens:', listA.length, listB.length );\n this.debug( 'bestMatch (starting):', JSON.stringify( bestMatch, null, ' ' ) );\n\n while( indexA < listA.length ){\n var matchTo = listA[ indexA ];\n bestMatch.score = 0.0;\n\n for( indexB=0; indexB= scoreThreshold ){\n //console.debug( 'autoPairFnBuilder.strategy', listA[ indexA ].name, listB[ bestMatch.index ].name );\n paired.push( options.createPair.call( this, {\n listA : listA,\n indexA : indexA,\n listB : listB,\n indexB : bestMatch.index\n }));\n //console.debug( 'list lens now:', listA.length, listB.length );\n } else {\n indexA += 1;\n }\n if( !listA.length || !listB.length ){\n return paired;\n }\n }\n this.debug( 'paired:', JSON.stringify( paired, null, ' ' ) );\n this.debug( 'autopair _strategy ---------------------------' );\n return paired;\n };\n}\n\n\n// ============================================================================\n/** An interface for building collections of paired datasets.\n */\nvar PairedCollectionCreator = Backbone.View.extend( baseMVC.LoggableMixin ).extend( baseCreator.CollectionCreatorMixin ).extend({\n _logNamespace : logNamespace,\n\n className: 'list-of-pairs-collection-creator collection-creator flex-row-container',\n\n /** set up initial options, instance vars, behaviors, and autopair (if set to do so) */\n initialize : function( attributes ){\n this.metric( 'PairedCollectionCreator.initialize', attributes );\n //this.debug( '-- PairedCollectionCreator:', attributes );\n\n attributes = _.defaults( attributes, {\n datasets : [],\n filters : this.DEFAULT_FILTERS,\n automaticallyPair : true,\n strategy : 'lcs',\n matchPercentage : 0.9,\n twoPassAutopairing : true\n });\n\n /** unordered, original list */\n this.initialList = attributes.datasets;\n\n /** is this from a history? if so, what's its id? */\n this.historyId = attributes.historyId;\n\n /** which filters should be used initially? (String[2] or name in commonFilters) */\n this.filters = this.commonFilters[ attributes.filters ] || this.commonFilters[ this.DEFAULT_FILTERS ];\n if( _.isArray( attributes.filters ) ){\n this.filters = attributes.filters;\n }\n\n /** try to auto pair the unpaired datasets on load? */\n this.automaticallyPair = attributes.automaticallyPair;\n\n /** what method to use for auto pairing (will be passed aggression level) */\n this.strategy = this.strategies[ attributes.strategy ] || this.strategies[ this.DEFAULT_STRATEGY ];\n if( _.isFunction( attributes.strategy ) ){\n this.strategy = attributes.strategy;\n }\n\n /** distance/mismatch level allowed for autopairing */\n this.matchPercentage = attributes.matchPercentage;\n\n /** try to autopair using simple first, then this.strategy on the remainder */\n this.twoPassAutopairing = attributes.twoPassAutopairing;\n\n /** remove file extensions (\\.*) from created pair names? */\n this.removeExtensions = true;\n //this.removeExtensions = false;\n\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n this.oncancel = attributes.oncancel;\n /** fn to call when the collection is created (scoped to this) */\n this.oncreate = attributes.oncreate;\n\n /** fn to call when the cancel button is clicked (scoped to this) - if falsy, no btn is displayed */\n this.autoscrollDist = attributes.autoscrollDist || 24;\n\n /** is the unpaired panel shown? */\n this.unpairedPanelHidden = false;\n /** is the paired panel shown? */\n this.pairedPanelHidden = false;\n\n /** DOM elements currently being dragged */\n this.$dragging = null;\n\n /** Used for blocking UI events during ajax/operations (don't post twice) */\n this.blocking = false;\n\n this._setUpCommonSettings( attributes );\n this._setUpBehaviors();\n this._dataSetUp();\n },\n\n /** map of common filter pairs by name */\n commonFilters : {\n illumina : [ '_1', '_2' ],\n Rs : [ '_R1', '_R2' ]\n },\n /** which commonFilter to use by default */\n DEFAULT_FILTERS : 'illumina',\n\n /** map of name->fn for autopairing */\n strategies : {\n 'simple' : 'autopairSimple',\n 'lcs' : 'autopairLCS',\n 'levenshtein' : 'autopairLevenshtein'\n },\n /** default autopair strategy name */\n DEFAULT_STRATEGY : 'lcs',\n\n // ------------------------------------------------------------------------ process raw list\n /** set up main data: cache initialList, sort, and autopair */\n _dataSetUp : function(){\n //this.debug( '-- _dataSetUp' );\n\n this.paired = [];\n this.unpaired = [];\n\n this.selectedIds = [];\n\n // sort initial list, add ids if needed, and save new working copy to unpaired\n this._sortInitialList();\n this._ensureIds();\n this.unpaired = this.initialList.slice( 0 );\n\n if( this.automaticallyPair ){\n this.autoPair();\n this.once( 'rendered:initial', function(){\n this.trigger( 'autopair' );\n });\n }\n },\n\n /** sort initial list */\n _sortInitialList : function(){\n //this.debug( '-- _sortInitialList' );\n this._sortDatasetList( this.initialList );\n },\n\n /** sort a list of datasets */\n _sortDatasetList : function( list ){\n // currently only natural sort by name\n list.sort( function( a, b ){ return naturalSort( a.name, b.name ); });\n return list;\n },\n\n /** add ids to dataset objs in initial list if none */\n _ensureIds : function(){\n this.initialList.forEach( function( dataset ){\n if( !dataset.hasOwnProperty( 'id' ) ){\n dataset.id = _.uniqueId();\n }\n });\n return this.initialList;\n },\n\n /** split initial list into two lists, those that pass forward filters & those passing reverse */\n _splitByFilters : function(){\n var regexFilters = this.filters.map( function( stringFilter ){\n return new RegExp( stringFilter );\n }),\n split = [ [], [] ];\n\n function _filter( unpaired, filter ){\n return filter.test( unpaired.name );\n //return dataset.name.indexOf( filter ) >= 0;\n }\n this.unpaired.forEach( function _filterEach( unpaired ){\n // 90% of the time this seems to work, but:\n //TODO: this treats *all* strings as regex which may confuse people - possibly check for // surrounding?\n // would need explanation in help as well\n regexFilters.forEach( function( filter, i ){\n if( _filter( unpaired, filter ) ){\n split[i].push( unpaired );\n }\n });\n });\n return split;\n },\n\n /** add a dataset to the unpaired list in it's proper order */\n _addToUnpaired : function( dataset ){\n // currently, unpaired is natural sorted by name, use binary search to find insertion point\n var binSearchSortedIndex = function( low, hi ){\n if( low === hi ){ return low; }\n\n var mid = Math.floor( ( hi - low ) / 2 ) + low,\n compared = naturalSort( dataset.name, this.unpaired[ mid ].name );\n\n if( compared < 0 ){\n return binSearchSortedIndex( low, mid );\n } else if( compared > 0 ){\n return binSearchSortedIndex( mid + 1, hi );\n }\n // walk the equal to find the last\n while( this.unpaired[ mid ] && this.unpaired[ mid ].name === dataset.name ){ mid++; }\n return mid;\n\n }.bind( this );\n\n this.unpaired.splice( binSearchSortedIndex( 0, this.unpaired.length ), 0, dataset );\n },\n\n // ------------------------------------------------------------------------ auto pairing\n /** two passes to automatically create pairs:\n * use both simpleAutoPair, then the fn mentioned in strategy\n */\n autoPair : function( strategy ){\n // split first using exact matching\n var split = this._splitByFilters(),\n paired = [];\n if( this.twoPassAutopairing ){\n paired = this.autopairSimple({\n listA : split[0],\n listB : split[1]\n });\n split = this._splitByFilters();\n }\n\n // uncomment to see printlns while running tests\n //this.debug = function(){ console.log.apply( console, arguments ); };\n\n // then try the remainder with something less strict\n strategy = strategy || this.strategy;\n split = this._splitByFilters();\n paired = paired.concat( this[ strategy ].call( this, {\n listA : split[0],\n listB : split[1]\n }));\n return paired;\n },\n\n /** autopair by exact match */\n autopairSimple : autoPairFnBuilder({\n scoreThreshold: function(){ return 1.0; },\n match : function _match( params ){\n params = params || {};\n if( params.matchTo === params.possible ){\n return {\n index: params.index,\n score: 1.0\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** autopair by levenshtein edit distance scoring */\n autopairLevenshtein : autoPairFnBuilder({\n scoreThreshold: function(){ return this.matchPercentage; },\n match : function _matches( params ){\n params = params || {};\n var distance = levenshteinDistance( params.matchTo, params.possible ),\n score = 1.0 - ( distance / ( Math.max( params.matchTo.length, params.possible.length ) ) );\n if( score > params.bestMatch.score ){\n return {\n index: params.index,\n score: score\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** autopair by longest common substrings scoring */\n autopairLCS : autoPairFnBuilder({\n scoreThreshold: function(){ return this.matchPercentage; },\n match : function _matches( params ){\n params = params || {};\n var match = this._naiveStartingAndEndingLCS( params.matchTo, params.possible ).length,\n score = match / ( Math.max( params.matchTo.length, params.possible.length ) );\n if( score > params.bestMatch.score ){\n return {\n index: params.index,\n score: score\n };\n }\n return params.bestMatch;\n }\n }),\n\n /** return the concat'd longest common prefix and suffix from two strings */\n _naiveStartingAndEndingLCS : function( s1, s2 ){\n var fwdLCS = '',\n revLCS = '',\n i = 0, j = 0;\n while( i < s1.length && i < s2.length ){\n if( s1[ i ] !== s2[ i ] ){\n break;\n }\n fwdLCS += s1[ i ];\n i += 1;\n }\n if( i === s1.length ){ return s1; }\n if( i === s2.length ){ return s2; }\n\n i = ( s1.length - 1 );\n j = ( s2.length - 1 );\n while( i >= 0 && j >= 0 ){\n if( s1[ i ] !== s2[ j ] ){\n break;\n }\n revLCS = [ s1[ i ], revLCS ].join( '' );\n i -= 1;\n j -= 1;\n }\n return fwdLCS + revLCS;\n },\n\n // ------------------------------------------------------------------------ pairing / unpairing\n /** create a pair from fwd and rev, removing them from unpaired, and placing the new pair in paired */\n _pair : function( fwd, rev, options ){\n options = options || {};\n this.debug( '_pair:', fwd, rev );\n var pair = this._createPair( fwd, rev, options.name );\n this.paired.push( pair );\n this.unpaired = _.without( this.unpaired, fwd, rev );\n if( !options.silent ){\n this.trigger( 'pair:new', pair );\n }\n return pair;\n },\n\n /** create a pair Object from fwd and rev, adding the name attribute (will guess if not given) */\n _createPair : function( fwd, rev, name ){\n // ensure existance and don't pair something with itself\n if( !( fwd && rev ) || ( fwd === rev ) ){\n throw new Error( 'Bad pairing: ' + [ JSON.stringify( fwd ), JSON.stringify( rev ) ] );\n }\n name = name || this._guessNameForPair( fwd, rev );\n return { forward : fwd, name : name, reverse : rev };\n },\n\n /** try to find a good pair name for the given fwd and rev datasets */\n _guessNameForPair : function( fwd, rev, removeExtensions ){\n removeExtensions = ( removeExtensions !== undefined )?( removeExtensions ):( this.removeExtensions );\n var fwdName = fwd.name,\n revName = rev.name,\n lcs = this._naiveStartingAndEndingLCS(\n fwdName.replace( new RegExp( this.filters[0] ), '' ),\n revName.replace( new RegExp( this.filters[1] ), '' )\n );\n if( removeExtensions ){\n var lastDotIndex = lcs.lastIndexOf( '.' );\n if( lastDotIndex > 0 ){\n var extension = lcs.slice( lastDotIndex, lcs.length );\n lcs = lcs.replace( extension, '' );\n fwdName = fwdName.replace( extension, '' );\n revName = revName.replace( extension, '' );\n }\n }\n return lcs || ( fwdName + ' & ' + revName );\n },\n\n /** unpair a pair, removing it from paired, and adding the fwd,rev datasets back into unpaired */\n _unpair : function( pair, options ){\n options = options || {};\n if( !pair ){\n throw new Error( 'Bad pair: ' + JSON.stringify( pair ) );\n }\n this.paired = _.without( this.paired, pair );\n this._addToUnpaired( pair.forward );\n this._addToUnpaired( pair.reverse );\n\n if( !options.silent ){\n this.trigger( 'pair:unpair', [ pair ] );\n }\n return pair;\n },\n\n /** unpair all paired datasets */\n unpairAll : function(){\n var pairs = [];\n while( this.paired.length ){\n pairs.push( this._unpair( this.paired[ 0 ], { silent: true }) );\n }\n this.trigger( 'pair:unpair', pairs );\n },\n\n // ------------------------------------------------------------------------ API\n /** convert a pair into JSON compatible with the collections API */\n _pairToJSON : function( pair, src ){\n src = src || 'hda';\n //TODO: consider making this the pair structure when created instead\n return {\n collection_type : 'paired',\n src : 'new_collection',\n name : pair.name,\n element_identifiers : [{\n name : 'forward',\n id : pair.forward.id,\n src : src\n }, {\n name : 'reverse',\n id : pair.reverse.id,\n src : src\n }]\n };\n },\n\n /** create the collection via the API\n * @returns {jQuery.xhr Object} the jquery ajax request\n */\n createList : function( name ){\n var creator = this,\n url = Galaxy.root + 'api/histories/' + this.historyId + '/contents/dataset_collections';\n\n //TODO: use ListPairedCollection.create()\n var ajaxData = {\n type : 'dataset_collection',\n collection_type : 'list:paired',\n hide_source_items : creator.hideOriginals || false,\n name : _.escape( name || creator.$( '.collection-name' ).val() ),\n element_identifiers : creator.paired.map( function( pair ){\n return creator._pairToJSON( pair );\n })\n\n };\n //this.debug( JSON.stringify( ajaxData ) );\n creator.blocking = true;\n return jQuery.ajax( url, {\n type : 'POST',\n contentType : 'application/json',\n dataType : 'json',\n data : JSON.stringify( ajaxData )\n })\n .always( function(){\n creator.blocking = false;\n })\n .fail( function( xhr, status, message ){\n creator._ajaxErrHandler( xhr, status, message );\n })\n .done( function( response, message, xhr ){\n //this.info( 'ok', response, message, xhr );\n creator.trigger( 'collection:created', response, message, xhr );\n creator.metric( 'collection:created', response );\n if( typeof creator.oncreate === 'function' ){\n creator.oncreate.call( this, response, message, xhr );\n }\n });\n },\n\n /** handle ajax errors with feedback and details to the user (if available) */\n _ajaxErrHandler : function( xhr, status, message ){\n this.error( xhr, status, message );\n var content = _l( 'An error occurred while creating this collection' );\n if( xhr ){\n if( xhr.readyState === 0 && xhr.status === 0 ){\n content += ': ' + _l( 'Galaxy could not be reached and may be updating.' )\n + _l( ' Try again in a few minutes.' );\n } else if( xhr.responseJSON ){\n content += '
                                              ' + JSON.stringify( xhr.responseJSON ) + '
                                              ';\n } else {\n content += ': ' + message;\n }\n }\n creator._showAlert( content, 'alert-danger' );\n },\n\n // ------------------------------------------------------------------------ rendering\n /** render the entire interface */\n render : function( speed, callback ){\n //this.debug( '-- _render' );\n //this.$el.empty().html( this.templates.main() );\n this.$el.empty().html( this.templates.main() );\n this._renderHeader( speed );\n this._renderMiddle( speed );\n this._renderFooter( speed );\n this._addPluginComponents();\n this.trigger( 'rendered', this );\n return this;\n },\n\n /** render the header section */\n _renderHeader : function( speed, callback ){\n //this.debug( '-- _renderHeader' );\n var $header = this.$( '.header' ).empty().html( this.templates.header() )\n .find( '.help-content' ).prepend( $( this.templates.helpContent() ) );\n\n this._renderFilters();\n return $header;\n },\n /** fill the filter inputs with the filter values */\n _renderFilters : function(){\n return this.$( '.forward-column .column-header input' ).val( this.filters[0] )\n .add( this.$( '.reverse-column .column-header input' ).val( this.filters[1] ) );\n },\n\n /** render the middle including unpaired and paired sections (which may be hidden) */\n _renderMiddle : function( speed, callback ){\n var $middle = this.$( '.middle' ).empty().html( this.templates.middle() );\n\n // (re-) hide the un/paired panels based on instance vars\n if( this.unpairedPanelHidden ){\n this.$( '.unpaired-columns' ).hide();\n } else if( this.pairedPanelHidden ){\n this.$( '.paired-columns' ).hide();\n }\n\n this._renderUnpaired();\n this._renderPaired();\n return $middle;\n },\n /** render the unpaired section, showing datasets accrd. to filters, update the unpaired counts */\n _renderUnpaired : function( speed, callback ){\n //this.debug( '-- _renderUnpaired' );\n var creator = this,\n $fwd, $rev, $prd = [],\n split = this._splitByFilters();\n // update unpaired counts\n this.$( '.forward-column .title' )\n .text([ split[0].length, _l( 'unpaired forward' ) ].join( ' ' ));\n this.$( '.forward-column .unpaired-info' )\n .text( this._renderUnpairedDisplayStr( this.unpaired.length - split[0].length ) );\n this.$( '.reverse-column .title' )\n .text([ split[1].length, _l( 'unpaired reverse' ) ].join( ' ' ));\n this.$( '.reverse-column .unpaired-info' )\n .text( this._renderUnpairedDisplayStr( this.unpaired.length - split[1].length ) );\n\n this.$( '.unpaired-columns .column-datasets' ).empty();\n\n // show/hide the auto pair button if any unpaired are left\n this.$( '.autopair-link' ).toggle( this.unpaired.length !== 0 );\n if( this.unpaired.length === 0 ){\n this._renderUnpairedEmpty();\n return;\n }\n\n // create the dataset dom arrays\n $rev = split[1].map( function( dataset, i ){\n // if there'll be a fwd dataset across the way, add a button to pair the row\n if( ( split[0][ i ] !== undefined )\n && ( split[0][ i ] !== dataset ) ){\n $prd.push( creator._renderPairButton() );\n }\n return creator._renderUnpairedDataset( dataset );\n });\n $fwd = split[0].map( function( dataset ){\n return creator._renderUnpairedDataset( dataset );\n });\n\n if( !$fwd.length && !$rev.length ){\n this._renderUnpairedNotShown();\n return;\n }\n // add to appropo cols\n //TODO: not the best way to render - consider rendering the entire unpaired-columns section in a fragment\n // and swapping out that\n this.$( '.unpaired-columns .forward-column .column-datasets' ).append( $fwd )\n .add( this.$( '.unpaired-columns .paired-column .column-datasets' ).append( $prd ) )\n .add( this.$( '.unpaired-columns .reverse-column .column-datasets' ).append( $rev ) );\n this._adjUnpairedOnScrollbar();\n },\n /** return a string to display the count of filtered out datasets */\n _renderUnpairedDisplayStr : function( numFiltered ){\n return [ '(', numFiltered, ' ', _l( 'filtered out' ), ')' ].join('');\n },\n /** return an unattached jQuery DOM element to represent an unpaired dataset */\n _renderUnpairedDataset : function( dataset ){\n //TODO: to underscore template\n return $( '
                                            • ')\n .attr( 'id', 'dataset-' + dataset.id )\n .addClass( 'dataset unpaired' )\n .attr( 'draggable', true )\n .addClass( dataset.selected? 'selected': '' )\n .append( $( '' ).addClass( 'dataset-name' ).text( dataset.name ) )\n //??\n .data( 'dataset', dataset );\n },\n /** render the button that may go between unpaired datasets, allowing the user to pair a row */\n _renderPairButton : function(){\n //TODO: *not* a dataset - don't pretend like it is\n return $( '
                                            • ').addClass( 'dataset unpaired' )\n .append( $( '' ).addClass( 'dataset-name' ).text( _l( 'Pair these datasets' ) ) );\n },\n /** a message to display when no unpaired left */\n _renderUnpairedEmpty : function(){\n //this.debug( '-- renderUnpairedEmpty' );\n var $msg = $( '
                                              ' )\n .text( '(' + _l( 'no remaining unpaired datasets' ) + ')' );\n this.$( '.unpaired-columns .paired-column .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n /** a message to display when no unpaired can be shown with the current filters */\n _renderUnpairedNotShown : function(){\n //this.debug( '-- renderUnpairedEmpty' );\n var $msg = $( '
                                              ' )\n .text( '(' + _l( 'no datasets were found matching the current filters' ) + ')' );\n this.$( '.unpaired-columns .paired-column .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n /** try to detect if the unpaired section has a scrollbar and adjust left column for better centering of all */\n _adjUnpairedOnScrollbar : function(){\n var $unpairedColumns = this.$( '.unpaired-columns' ).last(),\n $firstDataset = this.$( '.unpaired-columns .reverse-column .dataset' ).first();\n if( !$firstDataset.length ){ return; }\n var ucRight = $unpairedColumns.offset().left + $unpairedColumns.outerWidth(),\n dsRight = $firstDataset.offset().left + $firstDataset.outerWidth(),\n rightDiff = Math.floor( ucRight ) - Math.floor( dsRight );\n //this.debug( 'rightDiff:', ucRight, '-', dsRight, '=', rightDiff );\n this.$( '.unpaired-columns .forward-column' )\n .css( 'margin-left', ( rightDiff > 0 )? rightDiff: 0 );\n },\n\n /** render the paired section and update counts of paired datasets */\n _renderPaired : function( speed, callback ){\n //this.debug( '-- _renderPaired' );\n this.$( '.paired-column-title .title' ).text([ this.paired.length, _l( 'paired' ) ].join( ' ' ) );\n // show/hide the unpair all link\n this.$( '.unpair-all-link' ).toggle( this.paired.length !== 0 );\n if( this.paired.length === 0 ){\n this._renderPairedEmpty();\n return;\n //TODO: would be best to return here (the $columns)\n } else {\n // show/hide 'remove extensions link' when any paired and they seem to have extensions\n this.$( '.remove-extensions-link' ).show();\n }\n\n this.$( '.paired-columns .column-datasets' ).empty();\n var creator = this;\n this.paired.forEach( function( pair, i ){\n //TODO: cache these?\n var pairView = new PairView({ pair: pair });\n creator.$( '.paired-columns .column-datasets' )\n .append( pairView.render().$el )\n .append([\n ''\n ].join( '' ));\n });\n },\n /** a message to display when none paired */\n _renderPairedEmpty : function(){\n var $msg = $( '
                                              ' )\n .text( '(' + _l( 'no paired datasets yet' ) + ')' );\n this.$( '.paired-columns .column-datasets' ).empty().prepend( $msg );\n return $msg;\n },\n\n footerSettings : {\n '.hide-originals': 'hideOriginals',\n '.remove-extensions': 'removeExtensions'\n },\n\n /** add any jQuery/bootstrap/custom plugins to elements rendered */\n _addPluginComponents : function(){\n this._chooseFiltersPopover( '.choose-filters-link' );\n this.$( '.help-content i' ).hoverhighlight( '.collection-creator', 'rgba( 64, 255, 255, 1.0 )' );\n },\n\n /** build a filter selection popover allowing selection of common filter pairs */\n _chooseFiltersPopover : function( selector ){\n function filterChoice( val1, val2 ){\n return [\n ''\n ].join('');\n }\n var $popoverContent = $( _.template([\n '
                                              ',\n '
                                              ',\n _l( 'Choose from the following filters to change which unpaired reads are shown in the display' ),\n ':
                                              ',\n _.values( this.commonFilters ).map( function( filterSet ){\n return filterChoice( filterSet[0], filterSet[1] );\n }).join( '' ),\n '
                                              '\n ].join(''))({}));\n\n return this.$( selector ).popover({\n container : '.collection-creator',\n placement : 'bottom',\n html : true,\n //animation : false,\n content : $popoverContent\n });\n },\n\n /** add (or clear if clear is truthy) a validation warning to what */\n _validationWarning : function( what, clear ){\n var VALIDATION_CLASS = 'validation-warning';\n if( what === 'name' ){\n what = this.$( '.collection-name' ).add( this.$( '.collection-name-prompt' ) );\n this.$( '.collection-name' ).focus().select();\n }\n if( clear ){\n what = what || this.$( '.' + VALIDATION_CLASS );\n what.removeClass( VALIDATION_CLASS );\n } else {\n what.addClass( VALIDATION_CLASS );\n }\n },\n\n // ------------------------------------------------------------------------ events\n /** set up event handlers on self */\n _setUpBehaviors : function(){\n this.once( 'rendered', function(){\n this.trigger( 'rendered:initial', this );\n });\n\n this.on( 'pair:new', function(){\n //TODO: ideally only re-render the columns (or even elements) involved\n this._renderUnpaired();\n this._renderPaired();\n\n // scroll to bottom where new pairs are added\n //TODO: this doesn't seem to work - innerHeight sticks at 133...\n // may have to do with improper flex columns\n //var $pairedView = this.$( '.paired-columns' );\n //$pairedView.scrollTop( $pairedView.innerHeight() );\n //this.debug( $pairedView.height() )\n this.$( '.paired-columns' ).scrollTop( 8000000 );\n });\n this.on( 'pair:unpair', function( pairs ){\n //TODO: ideally only re-render the columns (or even elements) involved\n this._renderUnpaired();\n this._renderPaired();\n this.splitView();\n });\n\n this.on( 'filter-change', function(){\n this.filters = [\n this.$( '.forward-unpaired-filter input' ).val(),\n this.$( '.reverse-unpaired-filter input' ).val()\n ];\n this.metric( 'filter-change', this.filters );\n this._renderFilters();\n this._renderUnpaired();\n });\n\n this.on( 'autopair', function(){\n this._renderUnpaired();\n this._renderPaired();\n\n var message, msgClass = null;\n if( this.paired.length ){\n msgClass = 'alert-success';\n message = this.paired.length + ' ' + _l( 'pairs created' );\n if( !this.unpaired.length ){\n message += ': ' + _l( 'all datasets have been successfully paired' );\n this.hideUnpaired();\n this.$( '.collection-name' ).focus();\n }\n } else {\n message = _l([\n 'Could not automatically create any pairs from the given dataset names.',\n 'You may want to choose or enter different filters and try auto-pairing again.',\n 'Close this message using the X on the right to view more help.'\n ].join( ' ' ));\n }\n this._showAlert( message, msgClass );\n });\n\n //this.on( 'all', function(){\n // this.info( arguments );\n //});\n return this;\n },\n\n events : {\n // header\n 'click .more-help' : '_clickMoreHelp',\n 'click .less-help' : '_clickLessHelp',\n 'click .main-help' : '_toggleHelp',\n 'click .header .alert button' : '_hideAlert',\n 'click .forward-column .column-title' : '_clickShowOnlyUnpaired',\n 'click .reverse-column .column-title' : '_clickShowOnlyUnpaired',\n 'click .unpair-all-link' : '_clickUnpairAll',\n //TODO: this seems kinda backasswards - re-sending jq event as a backbone event, can we listen directly?\n 'change .forward-unpaired-filter input' : function( ev ){ this.trigger( 'filter-change' ); },\n 'focus .forward-unpaired-filter input' : function( ev ){ $( ev.currentTarget ).select(); },\n 'click .autopair-link' : '_clickAutopair',\n 'click .choose-filters .filter-choice' : '_clickFilterChoice',\n 'click .clear-filters-link' : '_clearFilters',\n 'change .reverse-unpaired-filter input' : function( ev ){ this.trigger( 'filter-change' ); },\n 'focus .reverse-unpaired-filter input' : function( ev ){ $( ev.currentTarget ).select(); },\n // unpaired\n 'click .forward-column .dataset.unpaired' : '_clickUnpairedDataset',\n 'click .reverse-column .dataset.unpaired' : '_clickUnpairedDataset',\n 'click .paired-column .dataset.unpaired' : '_clickPairRow',\n 'click .unpaired-columns' : 'clearSelectedUnpaired',\n 'mousedown .unpaired-columns .dataset' : '_mousedownUnpaired',\n // divider\n 'click .paired-column-title' : '_clickShowOnlyPaired',\n 'mousedown .flexible-partition-drag' : '_startPartitionDrag',\n // paired\n 'click .paired-columns .dataset.paired' : 'selectPair',\n 'click .paired-columns' : 'clearSelectedPaired',\n 'click .paired-columns .pair-name' : '_clickPairName',\n 'click .unpair-btn' : '_clickUnpair',\n // paired - drop target\n //'dragenter .paired-columns' : '_dragenterPairedColumns',\n //'dragleave .paired-columns .column-datasets': '_dragleavePairedColumns',\n 'dragover .paired-columns .column-datasets' : '_dragoverPairedColumns',\n 'drop .paired-columns .column-datasets' : '_dropPairedColumns',\n\n 'pair.dragstart .paired-columns .column-datasets' : '_pairDragstart',\n 'pair.dragend .paired-columns .column-datasets' : '_pairDragend',\n\n // footer\n 'change .remove-extensions' : function( ev ){ this.toggleExtensions(); },\n 'change .collection-name' : '_changeName',\n 'keydown .collection-name' : '_nameCheckForEnter',\n 'change .hide-originals' : '_changeHideOriginals',\n 'click .cancel-create' : '_cancelCreate',\n 'click .create-collection' : '_clickCreate'//,\n },\n\n /** toggle between showing only unpaired and split view */\n _clickShowOnlyUnpaired : function( ev ){\n //this.debug( 'click unpaired', ev.currentTarget );\n if( this.$( '.paired-columns' ).is( ':visible' ) ){\n this.hidePaired();\n } else {\n this.splitView();\n }\n },\n /** toggle between showing only paired and split view */\n _clickShowOnlyPaired : function( ev ){\n //this.debug( 'click paired' );\n if( this.$( '.unpaired-columns' ).is( ':visible' ) ){\n this.hideUnpaired();\n } else {\n this.splitView();\n }\n },\n\n /** hide unpaired, show paired */\n hideUnpaired : function( speed, callback ){\n this.unpairedPanelHidden = true;\n this.pairedPanelHidden = false;\n this._renderMiddle( speed, callback );\n },\n /** hide paired, show unpaired */\n hidePaired : function( speed, callback ){\n this.unpairedPanelHidden = false;\n this.pairedPanelHidden = true;\n this._renderMiddle( speed, callback );\n },\n /** show both paired and unpaired (splitting evenly) */\n splitView : function( speed, callback ){\n this.unpairedPanelHidden = this.pairedPanelHidden = false;\n this._renderMiddle( speed, callback );\n return this;\n },\n\n /** unpair all paired and do other super neat stuff which I'm not really sure about yet... */\n _clickUnpairAll : function( ev ){\n this.metric( 'unpairAll' );\n this.unpairAll();\n },\n\n /** attempt to autopair */\n _clickAutopair : function( ev ){\n var paired = this.autoPair();\n this.metric( 'autopair', paired.length, this.unpaired.length );\n this.trigger( 'autopair' );\n },\n\n /** set the filters based on the data attributes of the button click target */\n _clickFilterChoice : function( ev ){\n var $selected = $( ev.currentTarget );\n this.$( '.forward-unpaired-filter input' ).val( $selected.data( 'forward' ) );\n this.$( '.reverse-unpaired-filter input' ).val( $selected.data( 'reverse' ) );\n this._hideChooseFilters();\n this.trigger( 'filter-change' );\n },\n\n /** hide the choose filters popover */\n _hideChooseFilters : function(){\n //TODO: update bootstrap and remove the following hack\n // see also: https://github.com/twbs/bootstrap/issues/10260\n this.$( '.choose-filters-link' ).popover( 'hide' );\n this.$( '.popover' ).css( 'display', 'none' );\n },\n\n /** clear both filters */\n _clearFilters : function( ev ){\n this.$( '.forward-unpaired-filter input' ).val( '' );\n this.$( '.reverse-unpaired-filter input' ).val( '' );\n this.trigger( 'filter-change' );\n },\n\n // ........................................................................ unpaired\n /** select an unpaired dataset */\n _clickUnpairedDataset : function( ev ){\n ev.stopPropagation();\n return this.toggleSelectUnpaired( $( ev.currentTarget ) );\n },\n\n /** Toggle the selection of an unpaired dataset representation.\n * @param [jQuery] $dataset the unpaired dataset dom rep to select\n * @param [Boolean] options.force if defined, force selection based on T/F; otherwise, toggle\n */\n toggleSelectUnpaired : function( $dataset, options ){\n options = options || {};\n var dataset = $dataset.data( 'dataset' ),\n select = options.force !== undefined? options.force: !$dataset.hasClass( 'selected' );\n //this.debug( id, options.force, $dataset, dataset );\n if( !$dataset.length || dataset === undefined ){ return $dataset; }\n\n if( select ){\n $dataset.addClass( 'selected' );\n if( !options.waitToPair ){\n this.pairAllSelected();\n }\n\n } else {\n $dataset.removeClass( 'selected' );\n //delete dataset.selected;\n }\n return $dataset;\n },\n\n /** pair all the currently selected unpaired datasets */\n pairAllSelected : function( options ){\n options = options || {};\n var creator = this,\n fwds = [],\n revs = [],\n pairs = [];\n creator.$( '.unpaired-columns .forward-column .dataset.selected' ).each( function(){\n fwds.push( $( this ).data( 'dataset' ) );\n });\n creator.$( '.unpaired-columns .reverse-column .dataset.selected' ).each( function(){\n revs.push( $( this ).data( 'dataset' ) );\n });\n fwds.length = revs.length = Math.min( fwds.length, revs.length );\n //this.debug( fwds );\n //this.debug( revs );\n fwds.forEach( function( fwd, i ){\n try {\n pairs.push( creator._pair( fwd, revs[i], { silent: true }) );\n\n } catch( err ){\n //TODO: preserve selected state of those that couldn't be paired\n //TODO: warn that some could not be paired\n creator.error( err );\n }\n });\n if( pairs.length && !options.silent ){\n this.trigger( 'pair:new', pairs );\n }\n return pairs;\n },\n\n /** clear the selection on all unpaired datasets */\n clearSelectedUnpaired : function(){\n this.$( '.unpaired-columns .dataset.selected' ).removeClass( 'selected' );\n },\n\n /** when holding down the shift key on a click, 'paint' the moused over datasets as selected */\n _mousedownUnpaired : function( ev ){\n if( ev.shiftKey ){\n var creator = this,\n $startTarget = $( ev.target ).addClass( 'selected' ),\n moveListener = function( ev ){\n creator.$( ev.target ).filter( '.dataset' ).addClass( 'selected' );\n };\n $startTarget.parent().on( 'mousemove', moveListener );\n\n // on any mouseup, stop listening to the move and try to pair any selected\n $( document ).one( 'mouseup', function( ev ){\n $startTarget.parent().off( 'mousemove', moveListener );\n creator.pairAllSelected();\n });\n }\n },\n\n /** attempt to pair two datasets directly across from one another */\n _clickPairRow : function( ev ){\n //if( !ev.currentTarget ){ return true; }\n var rowIndex = $( ev.currentTarget ).index(),\n fwd = $( '.unpaired-columns .forward-column .dataset' ).eq( rowIndex ).data( 'dataset' ),\n rev = $( '.unpaired-columns .reverse-column .dataset' ).eq( rowIndex ).data( 'dataset' );\n //this.debug( 'row:', rowIndex, fwd, rev );\n this._pair( fwd, rev );\n },\n\n // ........................................................................ divider/partition\n /** start dragging the visible divider/partition between unpaired and paired panes */\n _startPartitionDrag : function( ev ){\n var creator = this,\n startingY = ev.pageY;\n //this.debug( 'partition drag START:', ev );\n $( 'body' ).css( 'cursor', 'ns-resize' );\n creator.$( '.flexible-partition-drag' ).css( 'color', 'black' );\n\n function endDrag( ev ){\n //creator.debug( 'partition drag STOP:', ev );\n // doing this by an added class didn't really work well - kept flashing still\n creator.$( '.flexible-partition-drag' ).css( 'color', '' );\n $( 'body' ).css( 'cursor', '' ).unbind( 'mousemove', trackMouse );\n }\n function trackMouse( ev ){\n var offset = ev.pageY - startingY;\n //creator.debug( 'partition:', startingY, offset );\n if( !creator.adjPartition( offset ) ){\n //creator.debug( 'mouseup triggered' );\n $( 'body' ).trigger( 'mouseup' );\n }\n creator._adjUnpairedOnScrollbar();\n startingY += offset;\n }\n $( 'body' ).mousemove( trackMouse );\n $( 'body' ).one( 'mouseup', endDrag );\n },\n\n /** adjust the parition up/down +/-adj pixels */\n adjPartition : function( adj ){\n var $unpaired = this.$( '.unpaired-columns' ),\n $paired = this.$( '.paired-columns' ),\n unpairedHi = parseInt( $unpaired.css( 'height' ), 10 ),\n pairedHi = parseInt( $paired.css( 'height' ), 10 );\n //this.debug( adj, 'hi\\'s:', unpairedHi, pairedHi, unpairedHi + adj, pairedHi - adj );\n\n unpairedHi = Math.max( 10, unpairedHi + adj );\n pairedHi = pairedHi - adj;\n\n var movingUpwards = adj < 0;\n // when the divider gets close to the top - lock into hiding the unpaired section\n if( movingUpwards ){\n if( this.unpairedPanelHidden ){\n return false;\n } else if( unpairedHi <= 10 ){\n this.hideUnpaired();\n return false;\n }\n } else {\n if( this.unpairedPanelHidden ){\n $unpaired.show();\n this.unpairedPanelHidden = false;\n }\n }\n\n // when the divider gets close to the bottom - lock into hiding the paired section\n if( !movingUpwards ){\n if( this.pairedPanelHidden ){\n return false;\n } else if( pairedHi <= 15 ){\n this.hidePaired();\n return false;\n }\n\n } else {\n if( this.pairedPanelHidden ){\n $paired.show();\n this.pairedPanelHidden = false;\n }\n }\n\n $unpaired.css({\n height : unpairedHi + 'px',\n flex : '0 0 auto'\n });\n return true;\n },\n\n // ........................................................................ paired\n /** select a pair when clicked */\n selectPair : function( ev ){\n ev.stopPropagation();\n $( ev.currentTarget ).toggleClass( 'selected' );\n },\n\n /** deselect all pairs */\n clearSelectedPaired : function( ev ){\n this.$( '.paired-columns .dataset.selected' ).removeClass( 'selected' );\n },\n\n /** rename a pair when the pair name is clicked */\n _clickPairName : function( ev ){\n ev.stopPropagation();\n var $name = $( ev.currentTarget ),\n $pair = $name.parent().parent(),\n index = $pair.index( '.dataset.paired' ),\n pair = this.paired[ index ],\n response = prompt( 'Enter a new name for the pair:', pair.name );\n if( response ){\n pair.name = response;\n // set a flag (which won't be passed in json creation) for manual naming so we don't overwrite these\n // when adding/removing extensions\n //hackish\n pair.customizedName = true;\n $name.text( pair.name );\n }\n },\n\n /** unpair this pair */\n _clickUnpair : function( ev ){\n //if( !ev.currentTarget ){ return true; }\n var pairIndex = Math.floor( $( ev.currentTarget ).index( '.unpair-btn' ) );\n //this.debug( 'pair:', pairIndex );\n this._unpair( this.paired[ pairIndex ] );\n },\n\n // ........................................................................ paired - drag and drop re-ordering\n //_dragenterPairedColumns : function( ev ){\n // this.debug( '_dragenterPairedColumns:', ev );\n //},\n //_dragleavePairedColumns : function( ev ){\n // //this.debug( '_dragleavePairedColumns:', ev );\n //},\n /** track the mouse drag over the paired list adding a placeholder to show where the drop would occur */\n _dragoverPairedColumns : function( ev ){\n //this.debug( '_dragoverPairedColumns:', ev );\n ev.preventDefault();\n\n var $list = this.$( '.paired-columns .column-datasets' );\n this._checkForAutoscroll( $list, ev.originalEvent.clientY );\n //this.debug( ev.originalEvent.clientX, ev.originalEvent.clientY );\n var $nearest = this._getNearestPairedDatasetLi( ev.originalEvent.clientY );\n\n $( '.element-drop-placeholder' ).remove();\n var $placeholder = $( '
                                              ' );\n if( !$nearest.length ){\n $list.append( $placeholder );\n } else {\n $nearest.before( $placeholder );\n }\n },\n\n /** If the mouse is near enough to the list's top or bottom, scroll the list */\n _checkForAutoscroll : function( $element, y ){\n var AUTOSCROLL_SPEED = 2;\n var offset = $element.offset(),\n scrollTop = $element.scrollTop(),\n upperDist = y - offset.top,\n lowerDist = ( offset.top + $element.outerHeight() ) - y;\n //this.debug( '_checkForAutoscroll:', scrollTop, upperDist, lowerDist );\n if( upperDist >= 0 && upperDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop - AUTOSCROLL_SPEED );\n } else if( lowerDist >= 0 && lowerDist < this.autoscrollDist ){\n $element.scrollTop( scrollTop + AUTOSCROLL_SPEED );\n }\n },\n\n /** get the nearest *previous* paired dataset PairView based on the mouse's Y coordinate.\n * If the y is at the end of the list, return an empty jQuery object.\n */\n _getNearestPairedDatasetLi : function( y ){\n var WIGGLE = 4,\n lis = this.$( '.paired-columns .column-datasets li' ).toArray();\n for( var i=0; i y && top - halfHeight < y ){\n //this.debug( y, top + halfHeight, top - halfHeight )\n return $li;\n }\n }\n return $();\n },\n /** drop (dragged/selected PairViews) onto the list, re-ordering both the DOM and the internal array of pairs */\n _dropPairedColumns : function( ev ){\n // both required for firefox\n ev.preventDefault();\n ev.dataTransfer.dropEffect = 'move';\n\n var $nearest = this._getNearestPairedDatasetLi( ev.originalEvent.clientY );\n if( $nearest.length ){\n this.$dragging.insertBefore( $nearest );\n\n } else {\n // no nearest before - insert after last element (unpair button)\n this.$dragging.insertAfter( this.$( '.paired-columns .unpair-btn' ).last() );\n }\n // resync the creator's list of paired based on the new DOM order\n this._syncPairsToDom();\n return false;\n },\n /** resync the creator's list of paired based on the DOM order of pairs */\n _syncPairsToDom : function(){\n var newPaired = [];\n //TODO: doesn't seem wise to use the dom to store these - can't we sync another way?\n this.$( '.paired-columns .dataset.paired' ).each( function(){\n newPaired.push( $( this ).data( 'pair' ) );\n });\n //this.debug( newPaired );\n this.paired = newPaired;\n this._renderPaired();\n },\n /** drag communication with pair sub-views: dragstart */\n _pairDragstart : function( ev, pair ){\n //this.debug( '_pairDragstart', ev, pair )\n // auto select the pair causing the event and move all selected\n pair.$el.addClass( 'selected' );\n var $selected = this.$( '.paired-columns .dataset.selected' );\n this.$dragging = $selected;\n },\n /** drag communication with pair sub-views: dragend - remove the placeholder */\n _pairDragend : function( ev, pair ){\n //this.debug( '_pairDragend', ev, pair )\n $( '.element-drop-placeholder' ).remove();\n this.$dragging = null;\n },\n\n // ........................................................................ footer\n toggleExtensions : function( force ){\n var creator = this;\n creator.removeExtensions = ( force !== undefined )?( force ):( !creator.removeExtensions );\n\n _.each( creator.paired, function( pair ){\n // don't overwrite custom names\n if( pair.customizedName ){ return; }\n pair.name = creator._guessNameForPair( pair.forward, pair.reverse );\n });\n\n creator._renderPaired();\n creator._renderFooter();\n },\n\n // ------------------------------------------------------------------------ misc\n /** debug a dataset list */\n _printList : function( list ){\n var creator = this;\n _.each( list, function( e ){\n if( list === creator.paired ){\n creator._printPair( e );\n } else {\n //creator.debug( e );\n }\n });\n },\n\n /** print a pair Object */\n _printPair : function( pair ){\n this.debug( pair.forward.name, pair.reverse.name, ': ->', pair.name );\n },\n\n /** string rep */\n toString : function(){ return 'PairedCollectionCreator'; },\n\n templates: _.extend({}, baseCreator.CollectionCreatorMixin._creatorTemplates, {\n\n /** the header (not including help text) */\n header : _.template([\n '
                                              ',\n '', _l( 'More help' ), '',\n '
                                              ',\n '', _l( 'Less' ), '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '',\n '',\n '
                                              ',\n\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '', _l( 'Unpaired forward' ), '',\n '',\n '
                                              ',\n '
                                              ',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '', _l( 'Unpaired reverse' ), '',\n '',\n '
                                              ',\n '
                                              ',\n '',\n '
                                              ',\n '
                                              ',\n '
                                              ',\n '
                                              '\n ].join('')),\n\n /** the middle: unpaired, divider, and paired */\n middle : _.template([\n // contains two flex rows (rows that fill available space) and a divider btwn\n '
                                              ',\n '
                                              ',\n '
                                                ',\n '
                                                ',\n '
                                                ',\n '
                                                  ',\n '
                                                  ',\n '
                                                  ',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '',\n '
                                                    ',\n '',\n _l( 'Unpair all' ),\n '',\n '
                                                    ',\n '
                                                    ',\n '
                                                    ',\n '
                                                      ',\n '
                                                      '\n ].join('')),\n\n /** creation and cancel controls */\n footer : _.template([\n '
                                                      ',\n '
                                                      ',\n '',\n '',\n '
                                                      ',\n '
                                                      ',\n '',\n '
                                                      ', _l( 'Name' ), ':
                                                      ',\n '
                                                      ',\n '
                                                      ',\n\n '
                                                      ',\n '
                                                      ',\n '',\n '
                                                      ',\n '',\n '',\n '
                                                      ',\n '
                                                      ',\n\n '
                                                      ',\n '',\n '
                                                      ',\n '
                                                      '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                                                      ', _l([\n 'Collections of paired datasets are ordered lists of dataset pairs (often forward and reverse reads). ',\n 'These collections can be passed to tools and workflows in order to have analyses done on each member of ',\n 'the entire group. This interface allows you to create a collection, choose which datasets are paired, ',\n 'and re-order the final collection.'\n ].join( '' )), '

                                                      ',\n '

                                                      ', _l([\n 'Unpaired datasets are shown in the unpaired section ',\n '(hover over the underlined words to highlight below). ',\n 'Paired datasets are shown in the paired section.',\n '

                                                        To pair datasets, you can:',\n '
                                                      • Click a dataset in the ',\n 'forward column ',\n 'to select it then click a dataset in the ',\n 'reverse column.',\n '
                                                      • ',\n '
                                                      • Click one of the \"Pair these datasets\" buttons in the ',\n 'middle column ',\n 'to pair the datasets in a particular row.',\n '
                                                      • ',\n '
                                                      • Click \"Auto-pair\" ',\n 'to have your datasets automatically paired based on name.',\n '
                                                      • ',\n '
                                                      '\n ].join( '' )), '

                                                      ',\n '

                                                      ', _l([\n '

                                                        You can filter what is shown in the unpaired sections by:',\n '
                                                      • Entering partial dataset names in either the ',\n 'forward filter or ',\n 'reverse filter.',\n '
                                                      • ',\n '
                                                      • Choosing from a list of preset filters by clicking the ',\n '\"Choose filters\" link.',\n '
                                                      • ',\n '
                                                      • Entering regular expressions to match dataset names. See: ',\n 'MDN\\'s JavaScript Regular Expression Tutorial. ',\n 'Note: forward slashes (\\\\) are not needed.',\n '
                                                      • ',\n '
                                                      • Clearing the filters by clicking the ',\n '\"Clear filters\" link.',\n '
                                                      • ',\n '
                                                      '\n ].join( '' )), '

                                                      ',\n '

                                                      ', _l([\n 'To unpair individual dataset pairs, click the ',\n 'unpair buttons ( ). ',\n 'Click the \"Unpair all\" link to unpair all pairs.'\n ].join( '' )), '

                                                      ',\n '

                                                      ', _l([\n 'You can include or remove the file extensions (e.g. \".fastq\") from your pair names by toggling the ',\n '\"Remove file extensions from pair names?\" control.'\n ].join( '' )), '

                                                      ',\n '

                                                      ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\". ',\n '(Note: you do not have to pair all unpaired datasets to finish.)'\n ].join( '' )), '

                                                      '\n ].join(''))\n })\n});\n\n//=============================================================================\n/** a modal version of the paired collection creator */\nvar pairedCollectionCreatorModal = function _pairedCollectionCreatorModal( datasets, options ){\n\n var deferred = jQuery.Deferred(),\n creator;\n\n options = _.defaults( options || {}, {\n datasets : datasets,\n oncancel : function(){\n Galaxy.modal.hide();\n deferred.reject( 'cancelled' );\n },\n oncreate : function( creator, response ){\n Galaxy.modal.hide();\n deferred.resolve( response );\n }\n });\n\n if( !window.Galaxy || !Galaxy.modal ){\n throw new Error( 'Galaxy or Galaxy.modal not found' );\n }\n\n creator = new PairedCollectionCreator( options );\n Galaxy.modal.show({\n title : 'Create a collection of paired datasets',\n body : creator.$el,\n width : '80%',\n height : '800px',\n closing_events: true\n });\n creator.render();\n window.creator = creator;\n\n //TODO: remove modal header\n return deferred;\n};\n\n\n//=============================================================================\nfunction createListOfPairsCollection( collection, defaultHideSourceItems ){\n var elements = collection.toJSON();\n//TODO: validate elements\n return pairedCollectionCreatorModal( elements, {\n historyId : collection.historyId,\n defaultHideSourceItems: defaultHideSourceItems\n });\n}\n\n\n//=============================================================================\n return {\n PairedCollectionCreator : PairedCollectionCreator,\n pairedCollectionCreatorModal : pairedCollectionCreatorModal,\n createListOfPairsCollection : createListOfPairsCollection\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/list-of-pairs-collection-creator.js","define([\n \"mvc/collection/list-collection-creator\",\n \"mvc/history/hdca-model\",\n \"mvc/base-mvc\",\n \"utils/localization\"\n], function( LIST_CREATOR, HDCA, BASE_MVC, _l ){\n\n'use strict';\n\nvar logNamespace = 'collections';\n/*==============================================================================\nTODO:\n the paired creator doesn't really mesh with the list creator as parent\n it may be better to make an abstract super class for both\n composites may inherit from this (or vis-versa)\n PairedDatasetCollectionElementView doesn't make a lot of sense\n\n==============================================================================*/\n/** */\nvar PairedDatasetCollectionElementView = Backbone.View.extend( BASE_MVC.LoggableMixin ).extend({\n _logNamespace : logNamespace,\n\n//TODO: use proper class (DatasetDCE or NestedDCDCE (or the union of both))\n tagName : 'li',\n className : 'collection-element',\n\n initialize : function( attributes ){\n this.element = attributes.element || {};\n this.identifier = attributes.identifier;\n },\n\n render : function(){\n this.$el\n .attr( 'data-element-id', this.element.id )\n .html( this.template({ identifier: this.identifier, element: this.element }) );\n return this;\n },\n\n //TODO: lots of unused space in the element - possibly load details and display them horiz.\n template : _.template([\n '<%- identifier %>',\n '<%- element.name %>',\n ].join('')),\n\n /** remove the DOM and any listeners */\n destroy : function(){\n this.off();\n this.$el.remove();\n },\n\n /** string rep */\n toString : function(){\n return 'DatasetCollectionElementView()';\n }\n});\n\n\n// ============================================================================\nvar _super = LIST_CREATOR.ListCollectionCreator;\n\n/** An interface for building collections.\n */\nvar PairCollectionCreator = _super.extend({\n\n /** the class used to display individual elements */\n elementViewClass : PairedDatasetCollectionElementView,\n /** the class this creator will create and save */\n collectionClass : HDCA.HistoryPairDatasetCollection,\n className : 'pair-collection-creator collection-creator flex-row-container',\n\n /** override to no-op */\n _mangleDuplicateNames : function(){},\n\n // TODO: this whole pattern sucks. There needs to be two classes of problem area:\n // bad inital choices and\n // when the user has painted his/her self into a corner during creation/use-of-the-creator\n /** render the entire interface */\n render : function( speed, callback ){\n if( this.workingElements.length === 2 ){\n return _super.prototype.render.call( this, speed, callback );\n }\n return this._renderInvalid( speed, callback );\n },\n\n // ------------------------------------------------------------------------ rendering elements\n /** render forward/reverse */\n _renderList : function( speed, callback ){\n //this.debug( '-- _renderList' );\n //precondition: there are two valid elements in workingElements\n var creator = this,\n $tmp = jQuery( '
                                                      ' ),\n $list = creator.$list();\n\n // lose the original views, create the new, append all at once, then call their renders\n _.each( this.elementViews, function( view ){\n view.destroy();\n creator.removeElementView( view );\n });\n $tmp.append( creator._createForwardElementView().$el );\n $tmp.append( creator._createReverseElementView().$el );\n $list.empty().append( $tmp.children() );\n _.invoke( creator.elementViews, 'render' );\n },\n\n /** create the forward element view */\n _createForwardElementView : function(){\n return this._createElementView( this.workingElements[0], { identifier: 'forward' } );\n },\n\n /** create the forward element view */\n _createReverseElementView : function(){\n return this._createElementView( this.workingElements[1], { identifier: 'reverse' } );\n },\n\n /** create an element view, cache in elementViews, and return */\n _createElementView : function( element, options ){\n var elementView = new this.elementViewClass( _.extend( options, {\n element : element,\n }));\n this.elementViews.push( elementView );\n return elementView;\n },\n\n /** swap the forward, reverse elements and re-render */\n swap : function(){\n this.workingElements = [\n this.workingElements[1],\n this.workingElements[0],\n ];\n this._renderList();\n },\n\n events : _.extend( _.clone( _super.prototype.events ), {\n 'click .swap' : 'swap',\n }),\n\n // ------------------------------------------------------------------------ templates\n //TODO: move to require text plugin and load these as text\n //TODO: underscore currently unnecc. bc no vars are used\n //TODO: better way of localizing text-nodes in long strings\n /** underscore template fns attached to class */\n templates : _.extend( _.clone( _super.prototype.templates ), {\n /** the middle: element list */\n middle : _.template([\n '',\n '
                                                      ',\n '
                                                      '\n ].join('')),\n\n /** help content */\n helpContent : _.template([\n '

                                                      ', _l([\n 'Pair collections are permanent collections containing two datasets: one forward and one reverse. ',\n 'Often these are forward and reverse reads. The pair collections can be passed to tools and ',\n 'workflows in order to have analyses done on both datasets. This interface allows ',\n 'you to create a pair, name it, and swap which is forward and which reverse.'\n ].join( '' )), '

                                                      ',\n '
                                                        ',\n '
                                                      • ', _l([\n 'Click the \"Swap\" link to make your forward dataset the reverse ',\n 'and the reverse dataset forward.'\n ].join( '' )), '
                                                      • ',\n '
                                                      • ', _l([\n 'Click the \"Cancel\" button to exit the interface.'\n ].join( '' )), '
                                                      • ',\n '

                                                      ',\n '

                                                      ', _l([\n 'Once your collection is complete, enter a name and ',\n 'click \"Create list\".'\n ].join( '' )), '

                                                      '\n ].join('')),\n\n /** a simplified page communicating what went wrong and why the user needs to reselect something else */\n invalidInitial : _.template([\n '
                                                      ',\n '
                                                      ',\n '',\n '<% if( _.size( problems ) ){ %>',\n _l( 'The following selections could not be included due to problems' ),\n '
                                                        <% _.each( problems, function( problem ){ %>',\n '
                                                      • <%- problem.element.name %>: <%- problem.text %>
                                                      • ',\n '<% }); %>
                                                      ',\n '<% } else if( _.size( elements ) === 0 ){ %>',\n _l( 'No datasets were selected' ), '.',\n '<% } else if( _.size( elements ) === 1 ){ %>',\n _l( 'Only one dataset was selected' ), ': <%- elements[0].name %>',\n '<% } else if( _.size( elements ) > 2 ){ %>',\n _l( 'Too many datasets were selected' ),\n ': <%- _.pluck( elements, \"name\" ).join( \", \") %>',\n '<% } %>',\n '
                                                      ',\n _l( 'Two (and only two) elements are needed for the pair' ), '. ',\n _l( 'You may need to ' ),\n '', _l( 'cancel' ), ' ',\n _l( 'and reselect new elements' ), '.',\n '
                                                      ',\n '
                                                      ',\n '
                                                      ',\n '
                                                      ',\n '
                                                      ',\n '
                                                      ',\n '',\n // _l( 'Create a different kind of collection' ),\n '
                                                      ',\n '
                                                      ',\n '
                                                      '\n ].join('')),\n }),\n\n // ------------------------------------------------------------------------ misc\n /** string rep */\n toString : function(){ return 'PairCollectionCreator'; }\n});\n\n\n//==============================================================================\n/** List collection flavor of collectionCreatorModal. */\nvar pairCollectionCreatorModal = function _pairCollectionCreatorModal( elements, options ){\n options = options || {};\n options.title = _l( 'Create a collection from a pair of datasets' );\n return LIST_CREATOR.collectionCreatorModal( elements, options, PairCollectionCreator );\n};\n\n\n//==============================================================================\n/** Use a modal to create a pair collection, then add it to the given history contents.\n * @returns {Deferred} resolved when the collection is added to the history.\n */\nfunction createPairCollection( contents, defaultHideSourceItems ){\n var elements = contents.toJSON(),\n promise = pairCollectionCreatorModal( elements, {\n defaultHideSourceItems: defaultHideSourceItems,\n creationFn : function( elements, name, hideSourceItems ){\n elements = [\n { name: \"forward\", src: \"hda\", id: elements[0].id },\n { name: \"reverse\", src: \"hda\", id: elements[1].id }\n ];\n return contents.createHDCA( elements, 'paired', name, hideSourceItems );\n }\n });\n return promise;\n}\n\n//==============================================================================\n return {\n PairCollectionCreator : PairCollectionCreator,\n pairCollectionCreatorModal : pairCollectionCreatorModal,\n createPairCollection : createPairCollection,\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/collection/pair-collection-creator.js","\ndefine( [ 'utils/utils', 'mvc/ui/ui-tabs', 'mvc/ui/ui-misc', 'mvc/form/form-view' ], function( Utils, Tabs, Ui, Form ) {\n\n /** Dataset edit attributes view */\n var View = Backbone.View.extend({\n initialize: function() {\n this.setElement( '
                                                      ' );\n this.model = new Backbone.Model( { 'dataset_id': Galaxy.params.dataset_id } );\n this.render();\n },\n\n // Fetch data for the selected dataset and \n // build tabs for editing its attributes\n render: function() {\n var url = Galaxy.root + 'dataset/edit',\n self = this;\n Utils.get({\n url : url,\n data : { 'dataset_id' : self.model.get( 'dataset_id' ) },\n success : function( response ) {\n self.render_attribute_page( self, response );\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while loading the dataset.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n\n /** Render all the tabs view */\n render_attribute_page: function( self, response ) {\n var message = {\n 'message' : response.message,\n 'status' : response.status,\n 'persistent' : true,\n 'cls' : response.status + 'message'\n };\n self.$el.empty().append( self._templateHeader() );\n self.display_message( message, self.$( '.response-message' ) );\n // Create all tabs\n self.create_tabs( response, self.$( '.edit-attr' ) );\n },\n\n /** Perform AJAX post call */\n call_ajax: function( self, data, tab_name ) {\n var post_url = Galaxy.root + 'dataset/edit';\n $.ajax({\n type: \"PUT\",\n url: post_url,\n data: data,\n success: function( response ) {\n self.render_attribute_page( self, response );\n self.reload_history();\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n\n /** Display actions messages */\n display_message: function( response, $el ) {\n $el.empty().html( new Ui.Message( response ).$el );\n },\n\n /** Create tabs for different attributes of dataset*/\n create_tabs: function( response, $el_edit_attr ) {\n var self = this;\n self.tabs = new Tabs.View();\n self.tabs.add({\n id : 'attributes',\n title : 'Attributes',\n icon : 'fa fa-bars',\n tooltip : 'Edit dataset attributes',\n $el : self._getAttributesFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'convert',\n title : 'Convert',\n icon : 'fa-gear',\n tooltip : 'Convert to new format',\n $el : self._getConvertFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'datatype',\n title : 'Datatypes',\n icon : 'fa-database',\n tooltip : 'Change data type',\n $el : self._getChangeDataTypeFormTemplate( response )\n });\n\n self.tabs.add({\n id : 'permissions',\n title : 'Permissions',\n icon : 'fa-user',\n tooltip : 'Permissions',\n $el : self._getPermissionsFormTemplate( response )\n });\n $el_edit_attr.append( self.tabs.$el );\n self.tabs.showTab( 'attributes' );\n },\n\n /** Main template */\n _templateHeader: function() {\n return '
                                                      ' +\n '
                                                      ' +\n '

                                                      Edit Dataset Attributes

                                                      ' +\n '
                                                      ';\n },\n\n /** Attributes tab template */\n _getAttributesFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Edit attributes',\n inputs : response.edit_attributes_inputs,\n operations: {\n 'submit_editattr' : new Ui.ButtonIcon({\n tooltip : 'Save attributes of the dataset.',\n icon : 'fa-floppy-o ',\n title : 'Save attributes',\n onclick : function() { self._submit( self, form, response, \"edit_attributes\" ) }\n }),\n 'submit_autocorrect' : new Ui.ButtonIcon({\n tooltip : 'This will inspect the dataset and attempt to correct the values of fields if they are not accurate.',\n icon : 'fa-undo ',\n title : 'Auto-detect',\n onclick : function() { self._submit( self, form, response, \"auto-detect\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Convert tab template */\n _getConvertFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Convert to new format',\n inputs : response.convert_inputs,\n operations: {\n 'submit' : new Ui.ButtonIcon({\n tooltip : 'Convert the datatype to a new format.',\n title : 'Convert datatype',\n icon : 'fa-exchange ',\n onclick : function() { self._submit( self, form, response, \"convert\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Change datatype template */\n _getChangeDataTypeFormTemplate: function( response ) {\n var self = this;\n var form = new Form({\n title : 'Change datatype',\n inputs : response.convert_datatype_inputs,\n operations: {\n 'submit' : new Ui.ButtonIcon({\n tooltip : 'Change the datatype to a new type.',\n title : 'Change datatype',\n icon : 'fa-exchange ',\n onclick : function() { self._submit( self, form, response, \"change\" ) }\n })\n }\n });\n return form.$el;\n },\n\n /** Permissions template */\n _getPermissionsFormTemplate: function( response ) {\n var template = \"\",\n self = this;\n if( response.can_manage_dataset ) {\n var form = new Form({\n title : 'Manage dataset permissions on ' + response.display_name,\n inputs : response.permission_inputs,\n operations: {\n 'submit': new Ui.ButtonIcon({\n tooltip : 'Save permissions.',\n title : 'Save permissions',\n icon : 'fa-floppy-o ',\n onclick : function() { self._submit( self, form, response, \"permissions\" ) }\n })\n }\n });\n return form.$el;\n }\n else {\n var form = new Form({\n title : 'View permissions',\n inputs : response.permission_inputs\n });\n return form.$el;\n }\n },\n\n /** Submit action */\n _submit: function( self, form, response, type ) {\n var form_data = form.data.create();\n form_data.dataset_id = response.dataset_id;\n switch( type ) {\n case \"edit_attributes\":\n form_data.save = 'Save';\n break;\n\n case \"auto-detect\":\n form_data.detect = 'Auto-detect';\n break;\n \n case \"convert\":\n if ( form_data.target_type !== null && form_data.target_type ) {\n form_data.dataset_id = response.dataset_id;\n form_data.convert_data = 'Convert';\n }\n break;\n\n case \"change\":\n form_data.change = 'Save';\n break;\n\n case \"permissions\":\n var post_data = {};\n post_data.permissions = JSON.stringify( form_data );\n post_data.update_roles_button = \"Save\";\n post_data.dataset_id = response.dataset_id;\n form_data = post_data;\n break; \n }\n self.call_ajax( self, form_data );\n },\n\n /** Reload Galaxy's history after updating dataset's attributes */\n reload_history: function() {\n if ( window.Galaxy ) {\n window.Galaxy.currHistoryPanel.loadCurrentHistory();\n }\n }\n });\n\n return {\n View : View\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-edit-attributes.js","define( [ 'utils/utils', 'mvc/ui/ui-misc', 'mvc/form/form-view' ], function( Utils, Ui, Form ) {\n\n /** Dataset edit attributes view */\n var View = Backbone.View.extend({\n initialize: function() {\n this.setElement( '
                                                      ' );\n this.model = new Backbone.Model( { 'dataset_id': Galaxy.params.dataset_id } );\n this.render();\n },\n\n // Fetch data for the selected dataset and\n render: function() {\n var data_url = Galaxy.root + 'api/datasets/' + this.model.get( 'dataset_id' ),\n self = this;\n\n Utils.get({\n url : data_url,\n success : function( dataset ) {\n var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True';\n Utils.get({\n url : job_url,\n success : function( job ) {\n var job_url = Galaxy.root + 'api/jobs/' + dataset.creating_job + '?full=True';\n self.render_error_page( self, dataset, job );\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while loading the job.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while loading the dataset.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n },\n\n /** Render the view */\n render_error_page: function( self, dataset, job ) {\n self.$el.empty().append( self._templateHeader() );\n self.$el.append('

                                                      Dataset Error

                                                      ');\n self.$el.append('

                                                      An error occured while running the tool ' + job.tool_id + '.

                                                      ');\n self.$el.append('

                                                      Tool execution generated the following messages:

                                                      ');\n self.$el.append('
                                                      ' + job.stderr + '
                                                      ');\n self.$el.append('

                                                      Report This Error

                                                    1. ');\n self.$el.append('

                                                      Usually the local Galaxy administrators regularly review errors that occur on the server. However, if you would like to provide additional information (such as what you were trying to do when the error occurred) and a contact e-mail address, we will be better able to investigate your problem and get back to you.

                                                      ');\n self.$el.append(self._getBugFormTemplate(dataset, job));\n },\n\n /** Display actions messages */\n display_message: function( response, $el, doNotClear, safe ) {\n if(!safe){\n if(doNotClear) {\n $el.append( new Ui.Message( response ).$el );\n } else {\n $el.empty().html( new Ui.Message( response ).$el );\n }\n } else {\n if(doNotClear) {\n $el.append( new Ui.UnescapedMessage( response ).$el );\n } else {\n $el.empty().html( new Ui.UnescapedMessage( response ).$el );\n }\n }\n },\n\n /** Main template */\n _templateHeader: function() {\n return '
                                                      ' +\n '
                                                      ' +\n '
                                                      ';\n },\n\n /** Convert tab template */\n _getBugFormTemplate: function(dataset, job) {\n var self = this;\n var inputs = [\n {\n \"help\": \"Your email address\",\n \"options\": [],\n \"type\": \"text\",\n \"name\": \"email\",\n \"label\": \"Your email\",\n \"value\": Galaxy.user.get('email')\n },\n {\n \"help\": \"Any additional comments you can provide regarding what you were doing at the time of the bug.\",\n \"options\": [],\n \"type\": \"text\",\n \"area\": true,\n \"name\": \"message\",\n \"label\": \"Message\"\n }\n ];\n\n // TODO\n if(false && response.any_public){\n inputs.push({\n \"name\": \"public_consent\",\n \"label\": \"Public Disclosure Consent\",\n \"help\": \"This Galaxy is configured to report to one or more error reporting backends that public to the world. By selecting 'yes', you acknowledge that this bug report will be made public.\",\n \"value\": String( Boolean( false ) ),\n \"options\": [],\n \"type\": \"boolean\",\n })\n }\n\n var form = new Form({\n title : 'Error Report',\n inputs : inputs,\n buttons : {\n save : new Ui.Button({\n icon : 'fa-bug',\n title : 'Report',\n cls : 'ui-button btn btn-primary',\n floating : 'clear',\n onclick : function() {\n var form_data = form.data.create();\n var url = Galaxy.root + 'api/jobs/' + job.id + '/error'\n form_data.dataset_id = dataset.id;\n self.submit(form_data, url)\n }\n })\n },\n });\n return form.$el;\n },\n\n /** Make ajax request */\n submit : function(form_data, url){\n var self = this;\n // Some required metadata\n $.ajax({\n type: \"POST\",\n url: url,\n data: form_data,\n success: function( response ) {\n // Clear out the div\n self.$el.empty().append( self._templateHeader() );\n // And display the messages.\n response.messages.forEach(function(message){\n self.display_message( {\n 'status': message[1],\n 'message': message[0],\n 'persistent': true,\n }, self.$( '.response-message' ), true, true );\n });\n },\n error : function( response ) {\n var error_response = {\n 'status': 'error',\n 'message': 'Error occured while saving. Please fill all the required fields and try again.',\n 'persistent': true,\n 'cls': 'errormessage'\n };\n self.display_message( error_response, self.$( '.response-message' ) );\n }\n });\n }\n });\n\n return {\n View : View\n };\n});\n\n\n\n// WEBPACK FOOTER //\n// ./galaxy/scripts/mvc/dataset/dataset-error.js","/** This class renders the grid list with shared section. */\ndefine( [ 'mvc/grid/grid-view' ], function( GridView ) {\n var View = Backbone.View.extend({\n initialize: function( options ) {\n var self = this;\n this.setElement( $( '
                                                      ' ) );\n this.model = new Backbone.Model( options );\n this.item = this.model.get( 'item' );\n $.ajax({\n url : Galaxy.root + this.item + '/' + this.model.get( 'action_id' ),\n success : function( response ) {\n response[ 'dict_format' ] = true;\n self.model.set( response );\n self.render();\n }\n });\n },\n\n render: function() {\n var grid = new GridView( this.model.attributes );\n this.$el.empty().append( grid.$el );\n this.$el.append( this._templateShared() );\n },\n\n _templateShared: function() {\n var self = this;\n var $tmpl = $( '
                                                      ' +\n '

                                                      ' + this.model.get( 'plural' ) + ' shared with you by others

                                                      ' +\n '
                                                      ' );\n var options = this.model.attributes;\n if ( options.shared_by_others && options.shared_by_others.length > 0 ) {\n var $table = $( '' +\n '' +\n '' +\n '' +\n '' +\n '
                                                      TitleOwner
                                                      ' );\n _.each( options.shared_by_others, function( it, index ) {\n var display_url = Galaxy.root + self.item + '/display_by_username_and_slug?username=' + it.username + '&slug=' + it.slug;\n $table.append( '
                                                      ' +\n '' + _.escape( it.title ) + '' +\n '' + _.escape( it.username ) + '
                                                      ' +\n '
                                                      ' +\n '
                                                      ' +\n '
                                                      ' +\n '
                                                      ' +\n '
                                                      You can tell Galaxy to download data from web by entering URL in this box (one per line). You can also directly paste the contents of a file.
                                                      ' +\n '").attr({rows:a,cols:o}).text(i.trim(h)):i("").attr({value:i.trim(h),size:o}),t.attr("id","renaming-active"),t.blur(function(){i(this).remove(),c.show(),u&&u(t)}),t.keyup(function(o){if(27===o.keyCode)i(this).trigger("blur");else if(13===o.keyCode){var r={};r[s]=i(this).val(),i(this).trigger("blur"),i.ajax({url:n,data:r,error:function(){alert("Text editing for elt "+e+" failed")},success:function(e){""!==e?c.text(e):c.html("None"),u&&u(t)}})}}),l&&l(t),c.hide(),t.insertAfter(c),t.focus(),t.select()}})}var i=t;return e}.apply(e,n),!(void 0!==s&&(t.exports=s))},,function(t,e,i){var n,s;(function(i){n=[],s=function(){function t(t){t=t||{};var e=this;return e.userId=window.bootstrapped&&window.bootstrapped.user?window.bootstrapped.user.id:null,e.userId=e.userId||t.userId||null,e.consoleLogger=t.consoleLogger||null,e._init(t),e}function e(t){var e=this;return e._init(t||{})}return t.ALL=0,t.LOG=0,t.DEBUG=10,t.INFO=20,t.WARN=30,t.ERROR=40,t.METRIC=50,t.NONE=100,t.defaultOptions={logLevel:t.NONE,consoleLevel:t.NONE,defaultNamespace:"Galaxy",consoleNamespaceWhitelist:null,clientPrefix:"client.",maxCacheSize:3e3,postSize:1e3,addTime:!0,cacheKeyPrefix:"logs-",postUrl:"/api/metrics",delayPostInMs:6e5,getPingData:void 0,onServerResponse:void 0},t.prototype._init=function(e){var i=this;i.options={};for(var n in t.defaultOptions)t.defaultOptions.hasOwnProperty(n)&&(i.options[n]=e.hasOwnProperty(n)?e[n]:t.defaultOptions[n]);return i.options.logLevel=i._parseLevel(i.options.logLevel),i.options.consoleLevel=i._parseLevel(i.options.consoleLevel),i._sending=!1,i._waiting=null,i._postSize=i.options.postSize,i._initCache(),i},t.prototype._initCache=function(){try{this.cache=new e({maxSize:this.options.maxCacheSize,key:this.options.cacheKeyPrefix+this.userId})}catch(e){this._emitToConsole("warn","MetricsLogger",["Could not intitialize logging cache:",e]),this.options.logLevel=t.NONE}},t.prototype._parseLevel=function(e){var i=typeof e;if("number"===i)return e;if("string"===i){var n=e.toUpperCase();if(t.hasOwnProperty(n))return t[n]}throw new Error("Unknown log level: "+e)},t.prototype.emit=function(t,e,i){var n=this;return e=e||n.options.defaultNamespace,t&&i?(t=n._parseLevel(t),t>=n.options.logLevel&&n._addToCache(t,e,i),n.consoleLogger&&t>=n.options.consoleLevel&&n._emitToConsole(t,e,i),n):n},t.prototype._addToCache=function(t,e,i){this._emitToConsole("debug","MetricsLogger",["_addToCache:",arguments,this.options.addTime,this.cache.length()]);var n=this;try{var s=n.cache.add(n._buildEntry(t,e,i));s>=n._postSize&&n._postCache()}catch(t){n._emitToConsole("warn","MetricsLogger",["Metrics logger could not stringify logArguments:",e,i]),n._emitToConsole("error","MetricsLogger",[t])}return n},t.prototype._buildEntry=function(t,e,i){this._emitToConsole("debug","MetricsLogger",["_buildEntry:",arguments]);var n={level:t,namespace:this.options.clientPrefix+e,args:i};return this.options.addTime&&(n.time=(new Date).toISOString()),n},t.prototype._postCache=function(t){if(t=t||{},this._emitToConsole("info","MetricsLogger",["_postCache",t,this._postSize]),!this.options.postUrl||this._sending)return i.when({});var e=this,n=t.count||e._postSize,s=e.cache.get(n),o=s.length,r="function"==typeof e.options.getPingData?e.options.getPingData():{};return r.metrics=JSON.stringify(s),e._sending=!0,i.post(e.options.postUrl,r).always(function(){e._sending=!1}).fail(function(t,i,n){e._postSize=e.options.maxCacheSize,e.emit("error","MetricsLogger",["_postCache error:",t.readyState,t.status,t.responseJSON||t.responseText])}).done(function(t){"function"==typeof e.options.onServerResponse&&e.options.onServerResponse(t),e.cache.remove(o),e._postSize=e.options.postSize})},t.prototype._delayPost=function(){var t=this;t._waiting=setTimeout(function(){t._waiting=null},t.options.delayPostInMs)},t.prototype._emitToConsole=function(e,i,n){var s=this,o=s.options.consoleNamespaceWhitelist;if(!s.consoleLogger)return s;if(o&&o.indexOf(i)===-1)return s;var r=Array.prototype.slice.call(n,0);return r.unshift(i),e>=t.METRIC&&"function"==typeof s.consoleLogger.info?s.consoleLogger.info.apply(s.consoleLogger,r):e>=t.ERROR&&"function"==typeof s.consoleLogger.error?s.consoleLogger.error.apply(s.consoleLogger,r):(e>=t.WARN&&"function"==typeof s.consoleLogger.warn?s.consoleLogger.warn.apply(s.consoleLogger,r):e>=t.INFO&&"function"==typeof s.consoleLogger.info?s.consoleLogger.info.apply(s.consoleLogger,r):e>=t.DEBUG&&"function"==typeof s.consoleLogger.debug?s.consoleLogger.debug.apply(s.consoleLogger,r):"function"==typeof s.consoleLogger.log&&s.consoleLogger.log.apply(s.consoleLogger,r),s)},t.prototype.log=function(){this.emit(1,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},t.prototype.debug=function(){this.emit(t.DEBUG,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},t.prototype.info=function(){this.emit(t.INFO,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},t.prototype.warn=function(){this.emit(t.WARN,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},t.prototype.error=function(){this.emit(t.ERROR,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},t.prototype.metric=function(){this.emit(t.METRIC,this.options.defaultNamespace,Array.prototype.slice.call(arguments,0))},e.defaultOptions={maxSize:5e3},e.prototype._init=function(t){if(!this._hasStorage())throw new Error("LoggingCache needs localStorage");if(!t.key)throw new Error("LoggingCache needs key for localStorage");return this.key=t.key,this._initStorage(),this.maxSize=t.maxSize||e.defaultOptions.maxSize,this},e.prototype._hasStorage=function(){var t="test";try{return localStorage.setItem(t,t),localStorage.removeItem(t),!0}catch(t){return!1}},e.prototype._initStorage=function(){return null===localStorage.getItem(this.key)?this.empty():this},e.prototype.add=function(t){var e=this,i=e._fetchAndParse(),n=i.length+1-e.maxSize;return n>0&&i.splice(0,n),i.push(t),e._unparseAndStore(i),i.length},e.prototype._fetchAndParse=function(){var t=this;return JSON.parse(localStorage.getItem(t.key))},e.prototype._unparseAndStore=function(t){var e=this;return localStorage.setItem(e.key,JSON.stringify(t))},e.prototype.length=function(){return this._fetchAndParse().length},e.prototype.get=function(t){return this._fetchAndParse().slice(0,t)},e.prototype.remove=function(t){var e=this._fetchAndParse(),i=e.splice(0,t);return this._unparseAndStore(e),i},e.prototype.empty=function(){return localStorage.setItem(this.key,"[]"),this},e.prototype.stringify=function(t){return JSON.stringify(this.get(t))},e.prototype.print=function(){console.log(JSON.stringify(this._fetchAndParse(),null," "))},{MetricsLogger:t,LoggingCache:e}}.apply(e,n),!(void 0!==s&&(t.exports=s))}).call(e,i(1))}]); +!function(t,e,i){function n(i){var n=e.console;o[i]||(o[i]=!0,t.migrateWarnings.push(i),n&&n.warn&&!t.migrateMute&&(n.warn("JQMIGRATE: "+i),t.migrateTrace&&n.trace&&n.trace()))}function s(e,i,s,o){if(Object.defineProperty)try{return void Object.defineProperty(e,i,{configurable:!0,enumerable:!0,get:function(){return n(o),s},set:function(t){n(o),s=t}})}catch(t){}t._definePropertyBroken=!0,e[i]=s}t.migrateVersion="1.4.0";var o={};t.migrateWarnings=[],e.console&&e.console.log&&e.console.log("JQMIGRATE: Migrate is installed"+(t.migrateMute?"":" with logging active")+", version "+t.migrateVersion),t.migrateTrace===i&&(t.migrateTrace=!0),t.migrateReset=function(){o={},t.migrateWarnings.length=0},"BackCompat"===document.compatMode&&n("jQuery is not compatible with Quirks Mode");var r=t("",{size:1}).attr("size")&&t.attrFn,a=t.attr,l=t.attrHooks.value&&t.attrHooks.value.get||function(){return null},u=t.attrHooks.value&&t.attrHooks.value.set||function(){return i},c=/^(?:input|button)$/i,h=/^[238]$/,d=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,p=/^(?:checked|selected)$/i;s(t,"attrFn",r||{},"jQuery.attrFn is deprecated"),t.attr=function(e,s,o,l){var u=s.toLowerCase(),f=e&&e.nodeType;return l&&(a.length<4&&n("jQuery.fn.attr( props, pass ) is deprecated"),e&&!h.test(f)&&(r?s in r:t.isFunction(t.fn[s])))?t(e)[s](o):("type"===s&&o!==i&&c.test(e.nodeName)&&e.parentNode&&n("Can't change the 'type' of an input or button in IE 6/7/8"),!t.attrHooks[u]&&d.test(u)&&(t.attrHooks[u]={get:function(e,n){var s,o=t.prop(e,n);return o===!0||"boolean"!=typeof o&&(s=e.getAttributeNode(n))&&s.nodeValue!==!1?n.toLowerCase():i},set:function(e,i,n){var s;return i===!1?t.removeAttr(e,n):(s=t.propFix[n]||n,s in e&&(e[s]=!0),e.setAttribute(n,n.toLowerCase())),n}},p.test(u)&&n("jQuery.fn.attr('"+u+"') might use property instead of attribute")),a.call(t,e,s,o))},t.attrHooks.value={get:function(t,e){var i=(t.nodeName||"").toLowerCase();return"button"===i?l.apply(this,arguments):("input"!==i&&"option"!==i&&n("jQuery.fn.attr('value') no longer gets properties"),e in t?t.value:null)},set:function(t,e){var i=(t.nodeName||"").toLowerCase();return"button"===i?u.apply(this,arguments):("input"!==i&&"option"!==i&&n("jQuery.fn.attr('value', val) no longer sets properties"),void(t.value=e))}};var f,g,m=t.fn.init,v=t.parseJSON,y=/^\s*)([^>]*)$/;t.fn.init=function(e,s,o){var r,a;return e&&"string"==typeof e&&!t.isPlainObject(s)&&(r=w.exec(t.trim(e)))&&r[0]&&(y.test(e)||n("$(html) HTML strings must start with '<' character"),r[3]&&n("$(html) HTML text after last tag is ignored"),"#"===r[0].charAt(0)&&(n("HTML string cannot start with a '#' character"),t.error("JQMIGRATE: Invalid selector string (XSS)")),s&&s.context&&(s=s.context),t.parseHTML)?m.call(this,t.parseHTML(r[2],s&&s.ownerDocument||s||document,!0),s,o):("#"===e?(n("jQuery( '#' ) is not a valid selector"),e=[]):b.test(e)&&n("Attribute selectors with '#' must be quoted: '"+e+"'"),a=m.apply(this,arguments),e&&e.selector!==i?(a.selector=e.selector,a.context=e.context):(a.selector="string"==typeof e?e:"",e&&(a.context=e.nodeType?e:s||document)),a)},t.fn.init.prototype=t.fn,t.parseJSON=function(t){return t?v.apply(this,arguments):(n("jQuery.parseJSON requires a valid JSON string"),null)},t.uaMatch=function(t){t=t.toLowerCase();var e=/(chrome)[ \/]([\w.]+)/.exec(t)||/(webkit)[ \/]([\w.]+)/.exec(t)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(t)||/(msie) ([\w.]+)/.exec(t)||t.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(t)||[];return{browser:e[1]||"",version:e[2]||"0"}},t.browser||(f=t.uaMatch(navigator.userAgent),g={},f.browser&&(g[f.browser]=!0,g.version=f.version),g.chrome?g.webkit=!0:g.webkit&&(g.safari=!0),t.browser=g),s(t,"browser",t.browser,"jQuery.browser is deprecated"),t.boxModel=t.support.boxModel="CSS1Compat"===document.compatMode,s(t,"boxModel",t.boxModel,"jQuery.boxModel is deprecated"),s(t.support,"boxModel",t.support.boxModel,"jQuery.support.boxModel is deprecated"),t.sub=function(){function e(t,i){return new e.fn.init(t,i)}t.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(n,s){var o=t.fn.init.call(this,n,s,i);return o instanceof e?o:e(o)},e.fn.init.prototype=e.fn;var i=e(document);return n("jQuery.sub() is deprecated"),e},t.fn.size=function(){return n("jQuery.fn.size() is deprecated; use the .length property"),this.length};var _=!1;t.swap&&t.each(["height","width","reliableMarginRight"],function(e,i){var n=t.cssHooks[i]&&t.cssHooks[i].get;n&&(t.cssHooks[i].get=function(){var t;return _=!0,t=n.apply(this,arguments),_=!1,t})}),t.swap=function(t,e,i,s){var o,r,a={};_||n("jQuery.swap() is undocumented and deprecated");for(r in e)a[r]=t.style[r],t.style[r]=e[r];o=i.apply(t,s||[]);for(r in e)t.style[r]=a[r];return o},t.ajaxSetup({converters:{"text json":t.parseJSON}});var x=t.fn.data;t.fn.data=function(e){var s,o,r=this[0];return!r||"events"!==e||1!==arguments.length||(s=t.data(r,e),o=t._data(r,e),s!==i&&s!==o||o===i)?x.apply(this,arguments):(n("Use of jQuery.fn.data('events') is deprecated"),o)};var C=/\/(java|ecma)script/i;t.clean||(t.clean=function(e,i,s,o){i=i||document,i=!i.nodeType&&i[0]||i,i=i.ownerDocument||i,n("jQuery.clean() is deprecated");var r,a,l,u,c=[];if(t.merge(c,t.buildFragment(e,i).childNodes),s)for(l=function(t){if(!t.type||C.test(t.type))return o?o.push(t.parentNode?t.parentNode.removeChild(t):t):s.appendChild(t)},r=0;null!=(a=c[r]);r++)t.nodeName(a,"script")&&l(a)||(s.appendChild(a),"undefined"!=typeof a.getElementsByTagName&&(u=t.grep(t.merge([],a.getElementsByTagName("script")),l),c.splice.apply(c,[r+1,0].concat(u)),r+=u.length));return c});var S=t.event.add,k=t.event.remove,T=t.event.trigger,E=t.fn.toggle,A=t.fn.live,D=t.fn.die,N=t.fn.load,O="ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess",P=new RegExp("\\b(?:"+O+")\\b"),R=/(?:^|\s)hover(\.\S+|)\b/,M=function(e){return"string"!=typeof e||t.event.special.hover?e:(R.test(e)&&n("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"),e&&e.replace(R,"mouseenter$1 mouseleave$1"))};t.event.props&&"attrChange"!==t.event.props[0]&&t.event.props.unshift("attrChange","attrName","relatedNode","srcElement"),t.event.dispatch&&s(t.event,"handle",t.event.dispatch,"jQuery.event.handle is undocumented and deprecated"),t.event.add=function(t,e,i,s,o){t!==document&&P.test(e)&&n("AJAX events should be attached to document: "+e),S.call(this,t,M(e||""),i,s,o)},t.event.remove=function(t,e,i,n,s){k.call(this,t,M(e)||"",i,n,s)},t.each(["load","unload","error"],function(e,i){t.fn[i]=function(){var t=Array.prototype.slice.call(arguments,0);return"load"===i&&"string"==typeof t[0]?N.apply(this,t):(n("jQuery.fn."+i+"() is deprecated"),t.splice(0,0,i),arguments.length?this.bind.apply(this,t):(this.triggerHandler.apply(this,t),this))}}),t.fn.toggle=function(e,i){if(!t.isFunction(e)||!t.isFunction(i))return E.apply(this,arguments);n("jQuery.fn.toggle(handler, handler...) is deprecated");var s=arguments,o=e.guid||t.guid++,r=0,a=function(i){var n=(t._data(this,"lastToggle"+e.guid)||0)%r;return t._data(this,"lastToggle"+e.guid,n+1),i.preventDefault(),s[n].apply(this,arguments)||!1};for(a.guid=o;r=this.options.errorAtPercent},_render_quota:function(){var t=this.model.toJSON(),e=t.quota_percent,i=a(this._templateQuotaMeter(t)),n=i.find(".progress-bar");return this.isOverQuota()?(n.attr("class","progress-bar progress-bar-danger"),i.find(".quota-meter-text").css("color","white"),this.trigger("quota:over",t)):e>=this.options.warnAtPercent?(n.attr("class","progress-bar progress-bar-warning"),this.trigger("quota:under quota:under:approaching",t)):(n.attr("class","progress-bar progress-bar-success"),this.trigger("quota:under quota:under:ok",t)),i},_render_usage:function(){var t=a(this._templateUsage(this.model.toJSON()));return this.log(this+".rendering usage:",t),t},render:function(){var t=null;return this.log(this+".model.quota_percent:",this.model.get("quota_percent")),t=null===this.model.get("quota_percent")||void 0===this.model.get("quota_percent")?this._render_usage():this._render_quota(),this.$el.html(t),this.$el.find(".quota-meter-text").tooltip(),this},_templateQuotaMeter:function(t){return['
                                                      ','
                                                      ','
                                                      ':">",e("Using")," ",t.quota_percent,"%","
                                                      ","
                                                      "].join("")},_templateUsage:function(t){return['
                                                      ','
                                                      ',t.nice_total_disk_usage?e("Using ")+t.nice_total_disk_usage:"","
                                                      ","
                                                      "].join("")},toString:function(){return"UserQuotaMeter("+this.model+")"}});return{UserQuotaMeter:n}}.apply(e,n),!(void 0!==s&&(t.exports=s))}).call(e,i(2),i(3),i(1))},,,function(t,e,i){(function(t,e,n,s){function o(e,i,n){function o(t){var e=s(t),i={placeholder:"Click to select",closeOnSelect:!e.is("[MULTIPLE]"),dropdownAutoWidth:!0,containerCssClass:"select2-minwidth"};return t.select2(i)}t.fn.select2&&(void 0===e&&(e=20),void 0===i&&(i=3e3),n=n||s("select"),n.each(function(){var t=s(this).not("[multiple]"),n=t.find("option").length;ni||t.hasClass("no-autocomplete")||o(t)}))}function r(){s("select[refresh_on_change='true']").off("change").change(function(){var t=s(this),e=t.val(),i=t.attr("refresh_on_change_values");if(i){i=i.split(",");var n=t.attr("last_selected_value");if(s.inArray(e,i)===-1&&s.inArray(n,i)===-1)return}s(window).trigger("refresh_on_change"),s(document).trigger("convert_to_values"),t.get(0).form.submit()}),s(":checkbox[refresh_on_change='true']").off("click").click(function(){var t=s(this),e=t.val(),i=t.attr("refresh_on_change_values");if(i){i=i.split(",");var n=t.attr("last_selected_value");if(s.inArray(e,i)===-1&&s.inArray(n,i)===-1)return}s(window).trigger("refresh_on_change"),t.get(0).form.submit()}),s("a[confirm]").off("click").click(function(){return confirm(s(this).attr("confirm"))})}window.jQuery=t,window.$=t,window._=e,window.Backbone=n,window.panels=i(51),e.extend(window,i(71)),window.async_save_text=i(151);var a=i(149);window.make_popupmenu=a.make_popupmenu,window.make_popup_menus=a.make_popup_menus,window.init_tag_click_function=i(94);var l=i(91);i(26);window.init_refresh_on_change=r,s(document).ready(function(){r(),s.fn.tooltip&&(s(".unified-panel-header [title]").tooltip({placement:"bottom"}),s("[title]").tooltip()),make_popup_menus(),o(20,1500),s("a").click(function(){var t=s(this),e=parent.frames&&parent.frames.galaxy_main;if("galaxy_main"==t.attr("target")&&!e){var i=t.attr("href");i+=i.indexOf("?")==-1?"?":"&",i+="use_panels=True",t.attr("href",i),t.attr("target","_self")}return t});var t=JSON.parse(sessionStorage.getItem("activeGalaxyTour"));if(t&&(t=l.hooked_tour_from_data(t),t&&t.steps&&window&&window.self===window.top)){var i=new Tour(e.extend({steps:t.steps},l.tour_opts));i.init(),i.restart()}s.getJSON("/api/webhooks/onload/all",function(t){e.each(t,function(t){t.activate&&t.script&&(s(" - - - -

                                                      Dataset generation errors

                                                      -

                                                      Dataset ${hda.hid}: ${hda.display_name() | h}

                                                      - <% job = hda.creating_job %> - %if job: - - %if job.traceback: - The Galaxy framework encountered the following error while attempting to run the tool: -
                                                      ${ util.unicodify( job.traceback ) | h}
                                                      - %endif - %if job.stderr or job.info: - Tool execution generated the following error message: - %if job.stderr: -
                                                      ${ util.unicodify( job.stderr ) | h}
                                                      - %elif job.info: -
                                                      ${ util.unicodify( job.info ) | h}
                                                      - %endif - %else: - Tool execution did not generate any error messages. - %endif - %if job.stdout: - The tool produced the following additional output: -
                                                      ${ util.unicodify( job.stdout ) | h}
                                                      - %endif - %else: - The tool did not create any additional job / error info. - %endif - <% - if trans.user: - user_email = trans.user.email - else: - user_email = '' - %> -

                                                      Report this error to the local Galaxy administrators

                                                      -

                                                      - Usually the local Galaxy administrators regularly review errors that occur on the server. - However, if you would like to provide additional information (such as - what you were trying to do when the error occurred) and a contact e-mail - address, we will be better able to investigate your problem and get back - to you. -

                                                      -
                                                      -
                                                      Error Report
                                                      -
                                                      -
                                                      - -
                                                      - - -
                                                      -
                                                      - - -
                                                      -
                                                      - - %if trans.app.config.biostar_url and trans.app.config.biostar_enable_bug_reports: - - %endif -
                                                      -
                                                      -
                                                      -
                                                      - - diff --git a/templates/webapps/tool_shed/repository/common.mako b/templates/webapps/tool_shed/repository/common.mako index ad45e2bc965..65fc9f93fb8 100644 --- a/templates/webapps/tool_shed/repository/common.mako +++ b/templates/webapps/tool_shed/repository/common.mako @@ -280,7 +280,7 @@ elif folder.label == 'Invalid tool dependencies': folder_label = "%s - click the tool dependency to see why it is invalid" % folder_label elif folder.label == 'Valid tools': - col_span_str = 'colspan="3"' + col_span_str = 'colspan="4"' if folder.description: folder_label = "%s - %s" % ( folder_label, folder.description ) else: @@ -870,6 +870,7 @@ %endif <${cell_type}>${tool.description | h} <${cell_type}>${tool.version | h} + <${cell_type}>${tool.profile | h} ##<${cell_type}>${tool.requirements | h}