Commits

jeremy goecks  committed 040555f

Add requireJS support for data, visualization, tools and update dependencies.

  • Participants
  • Parent commits d824b23

Comments (0)

Files changed (11)

File static/scripts/mvc/data.js

+define(["libs/backbone/backbone-relational"], function() {
 /**
  * A dataset. In Galaxy, datasets are associated with a history, so
  * this object is also known as a HistoryDatasetAssociation.
     model: Dataset
 });
 
+return {
+	Dataset: Dataset,
+	DatasetCollection: DatasetCollection
+};
+
+});

File static/scripts/mvc/tools.js

  * and models can be used without views.
  */
 
-// FIXME: copied from visualization module; remove once a module has been created from tools.
-var ServerStateDeferred = Backbone.Model.extend({
-    defaults: {
-        ajax_settings: {},
-        interval: 1000,
-        success_fn: function(result) { return true; }
-    },
-    
-    /**
-     * Returns a deferred that resolves when success function returns true.
-     */
-    go: function() {
-        var deferred = $.Deferred(),
-            self = this,
-            ajax_settings = self.get('ajax_settings'),
-            success_fn = self.get('success_fn'),
-            interval = self.get('interval'),
-             _go = function() {
-                 $.ajax(ajax_settings).success(function(result) {
-                     if (success_fn(result)) {
-                         // Result is good, so resolve.
-                         deferred.resolve(result);
-                     }
-                     else {
-                         // Result not good, try again.
-                         setTimeout(_go, interval);
-                     }
-                 });
-             };
-         _go();
-         return deferred;
-    }
-});
+ define( ["libs/underscore", "viz/trackster/util", "mvc/data", "libs/backbone/backbone-relational" ], 
+         function(_, util, data) {
  
 /**
  * Simple base model for any visible element. Includes useful attributes and ability 
 });
 
 /**
+ * A tool input.
+ */
+var ToolInput = Backbone.RelationalModel.extend({
+    defaults: {
+        name: null,
+        label: null,
+        type: null,
+        value: null,
+        num_samples: 5
+    },
+    
+    initialize: function() {
+        this.attributes.html = unescape(this.attributes.html);
+    },
+
+    copy: function() {
+        return new ToolInput(this.toJSON());
+    },
+    
+    /**
+     * Returns samples from a tool input.
+     */
+    get_samples: function() {
+        var type = this.get('type'),
+            samples = null;
+        if (type === 'number') {
+            samples = d3.scale.linear()
+                        .domain([this.get('min'), this.get('max')])
+                        .ticks(this.get('num_samples'));
+        }
+        else if (type === 'select') {
+            samples = _.map(this.get('options'), function(option) {
+                return option[0];
+            });
+        }
+        
+        return samples;
+    }   
+});
+
+/**
  * A Galaxy tool.
  */
 var Tool = BaseModel.extend({
         {
             type: Backbone.HasMany,
             key: 'inputs',
-            relatedModel: 'ToolInput',
+            relatedModel: ToolInput,
             reverseRelation: {
                 key: 'tool',
                 includeInJSON: false
         // deferred to ensure that job is run. Also use deferred that
         // resolves to outputs from tool.
         var run_deferred = $.Deferred(),
-            ss_deferred = new ServerStateDeferred({
+            ss_deferred = new util.ServerStateDeferred({
             ajax_settings: {
                 url: this.urlRoot,
                 data: JSON.stringify(payload),
         
         // Run job and resolve run_deferred to tool outputs.
         $.when(ss_deferred.go()).then(function(result) {
-            run_deferred.resolve(new DatasetCollection().reset(result));
+            run_deferred.resolve(new data.DatasetCollection().reset(result));
         });
         return run_deferred;
     }
 });
 
 /**
- * A tool input.
- */
-var ToolInput = Backbone.RelationalModel.extend({
-    defaults: {
-        name: null,
-        label: null,
-        type: null,
-        value: null,
-        num_samples: 5
-    },
-    
-    initialize: function() {
-        this.attributes.html = unescape(this.attributes.html);
-    },
-
-    copy: function() {
-        return new ToolInput(this.toJSON());
-    },
-    
-    /**
-     * Returns samples from a tool input.
-     */
-    get_samples: function() {
-        var type = this.get('type'),
-            samples = null;
-        if (type === 'number') {
-            samples = d3.scale.linear()
-                        .domain([this.get('min'), this.get('max')])
-                        .ticks(this.get('num_samples'));
-        }
-        else if (type === 'select') {
-            samples = _.map(this.get('options'), function(option) {
-                return option[0];
-            });
-        }
-        
-        return samples;
-    }   
-});
-
-/**
  * Wrap collection of tools for fast access/manipulation.
  */
 var ToolCollection = Backbone.Collection.extend({
             $('#left').width("650px");
         });
     }
-});
+});
+
+// Exports
+return {
+    Tool: Tool,
+    ToolSearch: ToolSearch,
+    ToolPanel: ToolPanel,
+    ToolPanelView: ToolPanelView,
+    ToolFormView: ToolFormView
+};
+
+});

File static/scripts/viz/sweepster.js

  * genomic visualization.
  */
 
-define( ["libs/d3", "viz/trackster/util", "viz/visualization", "viz/trackster/tracks"], function( d3, util, visualization, tracks ) {
+define(["libs/d3", "viz/trackster/util", "viz/visualization", "viz/trackster/tracks", "mvc/tools", "mvc/data"], 
+       function(d3, util, visualization, tracks, tools, data) {
 
 /**
  * A collection of tool input settings. Object is useful for keeping a list of settings 
         {
             type: Backbone.HasOne,
             key: 'dataset',
-            relatedModel: Dataset
+            relatedModel: data.Dataset
         },
         {
             type: Backbone.HasOne,
             key: 'tool',
-            relatedModel: Tool
+            relatedModel: tools.Tool
         },
         {
             type: Backbone.HasMany,
 
     render: function() {
         // Start with tool form view.
-        var tool_form_view = new ToolFormView({
+        var tool_form_view = new tools.ToolFormView({
             model: this.model.get('tool')
         });
         tool_form_view.render();

File static/scripts/viz/trackster/tracks.js

-define( ["libs/underscore", "viz/visualization", "viz/trackster/util", "viz/trackster/slotting", "viz/trackster/painters" ], function( _, visualization, util, slotting, painters ) {
+define( ["libs/underscore", "viz/visualization", "viz/trackster/util", 
+         "viz/trackster/slotting", "viz/trackster/painters", "mvc/data" ], 
+         function( _, visualization, util, slotting, painters, data ) {
 
 var extend = _.extend;
 var get_random_color = util.get_random_color;
     // Deferred object that indicates when view's chrom data has been loaded.
     this.load_chroms_deferred = null;
     this.init();
-    this.canvas_manager = new CanvasManager( this.container.get(0).ownerDocument );
+    this.canvas_manager = new visualization.CanvasManager( this.container.get(0).ownerDocument );
     this.reset();
 };
 _.extend( View.prototype, Backbone.Events);
         this.run(url_params, new_track,
                  // Success callback.
                  function(track_data) {
-                     new_track.set_dataset(new Dataset(track_data));
+                     new_track.set_dataset(new data.Dataset(track_data));
                      new_track.tiles_div.text("Running job.");
                      new_track.init();
                  }
     run: function(url_params, new_track, success_callback) {
         // Run tool.
         url_params.inputs = this.get_param_values_dict();
-        var ss_deferred = new ServerStateDeferred({
+        var ss_deferred = new util.ServerStateDeferred({
             ajax_settings: {
                 url: galaxy_paths.get('tool_url'),
                 data: JSON.stringify(url_params),
                             .css({'height': ERROR_PADDING-1, 'width': canvas.width}).prependTo(this.html_elt);
                                                         
         // Handle message; only message currently is that only the first N elements are displayed.
-        var tile_region = new GenomeRegion({
+        var tile_region = new visualization.GenomeRegion({
                 chrom: track.view.chrom,
                 start: this.low,
                 end: this.high
     //
     // Attribute init.
     //
-    this.dataset = new Dataset({
+    this.dataset = new data.Dataset({
         id: obj_dict.dataset_id,
         hda_ldda: obj_dict.hda_ldda
     }); 
                     ok_fn = function() {
                         var regions_to_use = $('select[name="regions"] option:selected').val(),
                             regions,
-                            view_region = new GenomeRegion({
+                            view_region = new visualization.GenomeRegion({
                                 chrom: view.chrom,
                                 start: view.low,
                                 end: view.high
                             }),
                             bookmarked_regions = _.map($(".bookmark"), function(elt) { 
-                                return new GenomeRegion({from_str: $(elt).children(".position").text()});
+                                return new visualization.GenomeRegion({from_str: $(elt).children(".position").text()});
                             });
 
                         // Get regions for visualization.
             tile_length = Math.ceil( TILE_SIZE * resolution ),
             // Tile high cannot be larger than view.max_high, which the chromosome length.
             tile_high = (tile_low + tile_length <= this.view.max_high ? tile_low + tile_length : this.view.max_high);
-        return new GenomeRegion({
+        return new visualization.GenomeRegion({
             chrom: this.view.chrom,
             start: tile_low,
             end: tile_high
             self.data_query_wait = DEFAULT_DATA_QUERY_WAIT;
 
             // Reset data URL when dataset indexing has completed/when not pending.
-            var ss_deferred = new ServerStateDeferred({
+            var ss_deferred = new util.ServerStateDeferred({
                 url: self.dataset_state_url,
                 url_params: {dataset_id : self.dataset_id, hda_ldda: self.hda_ldda},
                 interval: self.data_query_wait,

File static/scripts/viz/trackster/util.js

 exports = {};
 
 /**
+ * Implementation of a server-state based deferred. Server is repeatedly polled, and when
+ * condition is met, deferred is resolved.
+ */
+exports.ServerStateDeferred = Backbone.Model.extend({
+    defaults: {
+        ajax_settings: {},
+        interval: 1000,
+        success_fn: function(result) { return true; }
+    },
+    
+    /**
+     * Returns a deferred that resolves when success function returns true.
+     */
+    go: function() {
+        var deferred = $.Deferred(),
+            self = this,
+            ajax_settings = self.get('ajax_settings'),
+            success_fn = self.get('success_fn'),
+            interval = self.get('interval'),
+             _go = function() {
+                 $.ajax(ajax_settings).success(function(result) {
+                     if (success_fn(result)) {
+                         // Result is good, so resolve.
+                         deferred.resolve(result);
+                     }
+                     else {
+                         // Result not good, try again.
+                         setTimeout(_go, interval);
+                     }
+                 });
+             };
+         _go();
+         return deferred;
+    }
+});
+
+/**
  * Returns a random color in hexadecimal format that is sufficiently different from a single color
  * or set of colors.
  * @param colors a color or list of colors in the format '#RRGGBB'

File static/scripts/viz/visualization.js

-(function(){
+define( ["mvc/data", "viz/trackster/util" ], function(data, util) {
 
 /**
  * Model, view, and controller objects for Galaxy visualization framework.
 // --------- Models ---------
 
 /**
- * Implementation of a server-state based deferred. Server is repeatedly polled, and when
- * condition is met, deferred is resolved.
- */
-var ServerStateDeferred = Backbone.Model.extend({
-    defaults: {
-        ajax_settings: {},
-        interval: 1000,
-        success_fn: function(result) { return true; }
-    },
-    
-    /**
-     * Returns a deferred that resolves when success function returns true.
-     */
-    go: function() {
-        var deferred = $.Deferred(),
-            self = this,
-            ajax_settings = self.get('ajax_settings'),
-            success_fn = self.get('success_fn'),
-            interval = self.get('interval'),
-             _go = function() {
-                 $.ajax(ajax_settings).success(function(result) {
-                     if (success_fn(result)) {
-                         // Result is good, so resolve.
-                         deferred.resolve(result);
-                     }
-                     else {
-                         // Result not good, try again.
-                         setTimeout(_go, interval);
-                     }
-                 });
-             };
-         _go();
-         return deferred;
-    }
-});
-
-// TODO: move to Backbone
-
-/**
  * Canvas manager is used to create canvases, for browsers, this deals with
  * backward comparibility using excanvas, as well as providing a pattern cache
  */
     data_is_ready: function() {
         var dataset = this.get('dataset'),
             ready_deferred = $.Deferred(),
-            ss_deferred = new ServerStateDeferred({
+            ss_deferred = new util.ServerStateDeferred({
                 ajax_settings: {
                     url: this.get('dataset').url(),
                     data: {
  * A track of data in a genome visualization.
  */
 // TODO: rename to Track and merge with Trackster's Track object.
-var BackboneTrack = Dataset.extend({
+var BackboneTrack = data.Dataset.extend({
 
     initialize: function(options) {
         // Dataset id is unique ID for now.
     });
 };
 
-// ---- Exports ----
+return {
+    BrowserBookmark: BrowserBookmark,
+    BrowserBookmarkCollection: BrowserBookmarkCollection,
+    Cache: Cache,
+    CanvasManager: CanvasManager,
+    Genome: Genome,
+    GenomeDataManager: GenomeDataManager,
+    GenomeRegion: GenomeRegion,
+    GenomeRegionCollection: GenomeRegionCollection,
+    GenomeVisualization: GenomeVisualization,
+    GenomeWideBigWigData: GenomeWideBigWigData,
+    GenomeWideSummaryTreeData: GenomeWideSummaryTreeData,
+    ReferenceTrackDataManager: ReferenceTrackDataManager,
+    TrackBrowserRouter: TrackBrowserRouter,
+    TrackConfig: TrackConfig,
+    Visualization: Visualization,
+    add_datasets: add_datasets
+};
 
-var exports = (function() {
-    if ( typeof module !== 'undefined' && module.exports ) {
-        // CommonJS
-        return module.exports;
-    } else if ( typeof define === 'function' && define.amd ) {
-        // AMD
-        exports = {};
-        define( function() { return exports; } );
-        return exports;
-    } else {
-        // Browser global
-        return window;
-    }
-})();
-
-exports.BrowserBookmark = BrowserBookmark;        
-exports.BrowserBookmarkCollection = BrowserBookmarkCollection;
-exports.Cache = Cache;
-exports.CanvasManager = CanvasManager;
-exports.Genome = Genome;
-exports.GenomeDataManager = GenomeDataManager;
-exports.GenomeRegion = GenomeRegion;
-exports.GenomeRegionCollection = GenomeRegionCollection;
-exports.GenomeVisualization = GenomeVisualization;
-exports.GenomeWideBigWigData = GenomeWideBigWigData;
-exports.GenomeWideSummaryTreeData = GenomeWideSummaryTreeData;
-exports.ReferenceTrackDataManager = ReferenceTrackDataManager;
-exports.ServerStateDeferred = ServerStateDeferred;
-exports.TrackBrowserRouter = TrackBrowserRouter;
-exports.TrackConfig = TrackConfig;
-exports.Visualization = Visualization;
-exports.add_datasets = add_datasets;
-
-}).call(this);
+});

File templates/root/tool_menu.mako

 <%def name="javascripts()">
     ${parent.javascripts()}
     ${h.templates( "tool_link", "panel_section", "tool_search" )}
-    ${h.js( "galaxy.autocom_tagging", "mvc/tools" )}
+    ${h.js( "libs/require", "galaxy.autocom_tagging" )}
     
     <%
         # Set up for creating tool panel.
     %>
     
     <script type="text/javascript">
-        // Init. on document load.
-        var tool_panel, tool_panel_view, tool_search;
-        $(function() {
-            // Set up search.
-            tool_search = new ToolSearch( {spinner_url: "${h.url_for('/static/images/loading_small_white_bg.gif')}",
-										   search_url: "${h.url_for( controller='root', action='tool_search' )}",
-                                           hidden: ${tool_search_hidden} } );
-										   
-            // Set up tool panel.
-            tool_panel = new ToolPanel( { tool_search: tool_search } );
-            tool_panel.reset( tool_panel.parse( ${h.to_json_string( dictified_panel )} ) );
-            
-            // Set up tool panel view and initialize.
-            tool_panel_view = new ToolPanelView( {collection: tool_panel} );
-            tool_panel_view.render();
-            $('body').prepend(tool_panel_view.$el);
-                        
-            // Minsize init hint.
-            $( "a[minsizehint]" ).click( function() {
-                if ( parent.handle_minwidth_hint ) {
-                    parent.handle_minwidth_hint( $(this).attr( "minsizehint" ) );
+
+        require.config({ 
+                baseUrl: "${h.url_for('/static/scripts')}",
+                shim: {
+                    "libs/underscore": { exports: "_" }
                 }
+        });
+
+        require(["mvc/tools"], function(tools) {
+
+            // Init. on document load.
+            var tool_panel, tool_panel_view, tool_search;
+            $(function() {
+                // Set up search.
+                tool_search = new tools.ToolSearch( 
+                    { spinner_url: "${h.url_for('/static/images/loading_small_white_bg.gif')}",
+                      search_url: "${h.url_for( controller='root', action='tool_search' )}",
+                      hidden: ${tool_search_hidden} } );
+    										   
+                // Set up tool panel.
+                tool_panel = new tools.ToolPanel( { tool_search: tool_search } );
+                tool_panel.reset( tool_panel.parse( ${h.to_json_string( dictified_panel )} ) );
+                
+                // Set up tool panel view and initialize.
+                tool_panel_view = new tools.ToolPanelView( {collection: tool_panel} );
+                tool_panel_view.render();
+                $('body').prepend(tool_panel_view.$el);
+                            
+                // Minsize init hint.
+                $( "a[minsizehint]" ).click( function() {
+                    if ( parent.handle_minwidth_hint ) {
+                        parent.handle_minwidth_hint( $(this).attr( "minsizehint" ) );
+                    }
+                });
+                
+                // Log clicks on tools.
+                /*
+                $("div.toolTitle > a").click( function() {
+                    var tool_title = $(this).attr('id').split("-")[1];
+                    var section_title = $.trim( $(this).parents("div.toolSectionWrapper").find("div.toolSectionTitle").text() );
+                    var search_active = $(this).parents("div.toolTitle").hasClass("search_match");
+                    
+                    // Log action.
+                    galaxy_async.log_user_action("tool_menu_click." + tool_title, section_title, 
+                                                    JSON.stringify({"search_active" : search_active}));
+                });
+                */
+    			
+    			$( '.tooltip' ).tooltip();
+                
+                // TODO: is this necessary?
+                $( "a[minsizehint]" ).click( function() {
+                    if ( parent.handle_minwidth_hint ) {
+                        parent.handle_minwidth_hint( $(this).attr( "minsizehint" ) );
+                    }
+                });
             });
-            
-            // Log clicks on tools.
-            /*
-            $("div.toolTitle > a").click( function() {
-                var tool_title = $(this).attr('id').split("-")[1];
-                var section_title = $.trim( $(this).parents("div.toolSectionWrapper").find("div.toolSectionTitle").text() );
-                var search_active = $(this).parents("div.toolTitle").hasClass("search_match");
-                
-                // Log action.
-                galaxy_async.log_user_action("tool_menu_click." + tool_title, section_title, 
-                                                JSON.stringify({"search_active" : search_active}));
-            });
-            */
-			
-			$( '.tooltip' ).tooltip();
-            
-            // TODO: is this necessary?
-            $( "a[minsizehint]" ).click( function() {
-                if ( parent.handle_minwidth_hint ) {
-                    parent.handle_minwidth_hint( $(this).attr( "minsizehint" ) );
-                }
-            });
+
         });
     </script>
 </%def>

File templates/tracks/browser.mako

         baseUrl: "${h.url_for('/static/scripts') }",
         shim: {
             "libs/underscore": { exports: "_" },
-            "libs/backbone/backbone": { exports: "Backbone" }
+            "libs/backbone/backbone": { exports: "Backbone" },
+            "libs/backbone/backbone-relational": ["libs/backbone/backbone"]
         }
     });
-    require( ["base", "viz/trackster_ui","viz/trackster/util","viz/trackster/tracks"], function( base, trackster_ui, util, tracks ) {
+    require( ["base", "viz/visualization", "viz/trackster_ui", "viz/trackster/tracks"], 
+             function( base, visualization, trackster_ui, tracks ) {
 
     //
     // Place URLs here so that url_for can be used to generate them.
      * Set up router.
      */
     var set_up_router = function(options) {
-        browser_router = new TrackBrowserRouter(options);
+        browser_router = new visualization.TrackBrowserRouter(options);
         Backbone.history.start();   
     };
     

File templates/visualization/circster.mako

 <%def name="javascripts()">
     ${parent.javascripts()}
 
-    ${h.js( "libs/require", "mvc/data" )}
+    ${h.js( "libs/require" )}
 
     <script type="text/javascript">
 

File templates/visualization/sweepster.mako

 
     ${h.templates( "tool_link", "panel_section", "tool_search", "tool_form" )}
     ${h.js( "libs/require", "libs/jquery/jquery-ui-1.8.23.custom.min" )}
-    ${h.js( "mvc/data", "mvc/tools" )}
-
+    
     <script type="text/javascript">
         require.config({ 
                 baseUrl: "${h.url_for('/static/scripts')}",
                 shim: {
                     "libs/underscore": { exports: "_" },
                     "libs/d3": { exports: "d3" },
-                    "libs/backbone/backbone": { exports: "Backbone" }
+                    "libs/backbone/backbone": { exports: "Backbone" },
+                    "libs/backbone/backbone-relational": ["libs/backbone/backbone"]
                 }
         });
 
-        require(["libs/d3", "viz/visualization", "viz/sweepster"], function(d3, visualization, sweepster) {
+        require(["libs/d3", "viz/sweepster"], function(d3, sweepster) {
 
             var viz;
             $(function() {            

File templates/visualization/trackster_common.mako

 
 ## Render needed JavaScript files.
 <%def name="render_trackster_js_files()">
-	${h.js( "galaxy.panels", "libs/jquery/jstorage", "libs/jquery/jquery.event.drag", "libs/jquery/jquery.event.hover","libs/jquery/jquery.mousewheel", "libs/jquery/jquery-ui-1.8.23.custom.min", "mvc/data", "viz/visualization", "libs/require", "libs/farbtastic" )}
+	${h.js( "galaxy.panels", "libs/jquery/jstorage", "libs/jquery/jquery.event.drag", "libs/jquery/jquery.event.hover","libs/jquery/jquery.mousewheel", "libs/jquery/jquery-ui-1.8.23.custom.min", "libs/require", "libs/farbtastic" )}
 </%def>
 
 ## Render a block of JavaScript that contains all necessary variables for Trackster.